Giter Site home page Giter Site logo

scipopt / pyscipopt Goto Github PK

View Code? Open in Web Editor NEW
750.0 26.0 257.0 6.03 MB

Python interface for the SCIP Optimization Suite

Home Page: https://scipopt.github.io/PySCIPOpt

License: MIT License

Python 13.55% Shell 0.20% Cython 39.01% JetBrains MPS 47.24%
integer-optimization nonlinear-optimization mathematical-programming scip python cython

pyscipopt's Introduction

PySCIPOpt

This project provides an interface from Python to the SCIP Optimization Suite. Starting from v8.0.3, SCIP uses the Apache2.0 license. If you plan to use an earlier version of SCIP, please review SCIP's license restrictions.

Gitter PySCIPOpt on PyPI Integration test coverage AppVeyor Status

Documentation

Please consult the online documentation or use the help() function directly in Python or ? in IPython/Jupyter.

See CHANGELOG.md for added, removed or fixed functionality.

Installation

Using Conda

Conda version Conda platforms

DO NOT USE THE CONDA BASE ENVIRONMENT TO INSTALL PYSCIPOPT.

Conda will install SCIP automatically, hence everything can be installed in a single command:

conda install --channel conda-forge pyscipopt

Using PyPI and from Source

See INSTALL.md for instructions. Please note that the latest PySCIPOpt version is usually only compatible with the latest major release of the SCIP Optimization Suite. The following table summarizes which version of PySCIPOpt is required for a given SCIP version:

SCIP PySCIPOpt
9.0 5.x
8.0 4.x
7.0 3.x
6.0 2.x
5.0 1.4, 1.3
4.0 1.2, 1.1
3.2 1.0

Information which version of PySCIPOpt is required for a given SCIP version can also be found in INSTALL.md.

Building and solving a model

There are several examples and tutorials. These display some functionality of the interface and can serve as an entry point for writing more complex code. Some of the common usecases are also available in the 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:

  1. It is necessary to import python-scip in your code. This is achieved by including the line
from pyscipopt import Model
  1. Create a solver instance.
model = Model("Example")  # model name is optional
  1. Access the methods in the scip.pxi file using the solver/model instance model, e.g.:
x = model.addVar("x")
y = model.addVar("y", vtype="INTEGER")
model.setObjective(x + y)
model.addCons(2*x - y*y >= 0)
model.optimize()
sol = model.getBestSol()
print("x: {}".format(sol[x]))
print("y: {}".format(sol[y]))

Writing new plugins

The Python interface can be used to define custom plugins to extend the functionality of SCIP. You may write a pricer, heuristic or even constraint handler using pure Python code and SCIP can call their methods using the callback system. Every available plugin has a base class that you need to extend, overwriting the predefined but empty callbacks. Please see test_pricer.py and test_heur.py for two simple examples.

Please notice that in most cases one needs to use a dictionary to specify the return values needed by SCIP.

Extending the interface

PySCIPOpt already covers many of the SCIP callable library methods. You may also extend it to increase the functionality of this interface. The following will provide some directions on how this can be achieved:

The two most important files in PySCIPOpt are the scip.pxd and scip.pxi. These two files specify the public functions of SCIP that can be accessed from your python code.

To make PySCIPOpt aware of the public functions you would like to access, you must add them to scip.pxd. There are two things that must be done in order to properly add the functions:

  1. Ensure any enums, structs or SCIP variable types are included in scip.pxd
  2. Add the prototype of the public function you wish to access to scip.pxd

After following the previous two steps, it is then possible to create functions in python that reference the SCIP public functions included in scip.pxd. This is achieved by modifying the scip.pxi file to add the functionality you require.

We are always happy to accept pull request containing patches or extensions!

Please have a look at our contribution guidelines.

Gotchas

Ranged constraints

While ranged constraints of the form

lhs <= expression <= rhs

are supported, the Python syntax for chained comparisons can't be hijacked with operator overloading. Instead, parenthesis must be used, e.g.,

lhs <= (expression <= rhs)

Alternatively, you may call model.chgRhs(cons, newrhs) or model.chgLhs(cons, newlhs) after the single-sided constraint has been created.

Variable objects

You can't use Variable objects as elements of sets or as keys of dicts. They are not hashable and comparable. The issue is that comparisons such as x == y will be interpreted as linear constraints, since Variables are also Expr objects.

Dual values

While PySCIPOpt supports access to the dual values of a solution, there are some limitations involved:

  • Can only be used when presolving and propagation is disabled to ensure that the LP solver - which is providing the dual information - actually solves the unmodified problem.
  • Heuristics should also be disabled to avoid that the problem is solved before the LP solver is called.
  • There should be no bound constraints, i.e., constraints with only one variable. This can cause incorrect values as explained in #136

Therefore, you should use the following settings when trying to work with dual information:

model.setPresolve(pyscipopt.SCIP_PARAMSETTING.OFF)
model.setHeuristics(pyscipopt.SCIP_PARAMSETTING.OFF)
model.disablePropagation()

Citing PySCIPOpt

Please cite this paper

@incollection{MaherMiltenbergerPedrosoRehfeldtSchwarzSerrano2016,
  author = {Stephen Maher and Matthias Miltenberger and Jo{\~{a}}o Pedro Pedroso and Daniel Rehfeldt and Robert Schwarz and Felipe Serrano},
  title = {{PySCIPOpt}: Mathematical Programming in Python with the {SCIP} Optimization Suite},
  booktitle = {Mathematical Software {\textendash} {ICMS} 2016},
  publisher = {Springer International Publishing},
  pages = {301--307},
  year = {2016},
  doi = {10.1007/978-3-319-42432-3_37},
}

as well as the corresponding SCIP Optimization Suite report when you use this tool for a publication or other scientific work.

pyscipopt's People

Contributors

ambros-gleixner avatar antoineprv avatar bzfmuelh avatar cgraczyk avatar charjon avatar ctdunc avatar drehfeldt avatar fschloesser avatar fserra avatar gasse avatar gregorch avatar jmtud avatar joao-dionisio avatar ju-manns avatar jurgen-lentz avatar lascavana avatar mattmilten avatar mkoeppe avatar mmghannam avatar mo271 avatar mueldgog avatar opt-mucca avatar penenkel avatar pfetsch avatar ramabile avatar roessig avatar rschwarz avatar steffanschlein avatar traviscibot avatar yozw avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

pyscipopt's Issues

Markowitz example not working

Hi,

The example markowitz_soco.py raises an exception:

/usr/local/lib/python2.7/dist-packages/pyscipopt/scip.so in pyscipopt.scip.Model.setObjective (pyscipopt/scip.c:38918)()

ValueError: Nonlinear objective functions are not supported!

Were nonlinear objectives working before and not any more? Or available in SCIP but not in PySCIPOpt?

Anyhow, the example should be updated I guess.

Best,

Installation problem

I have followed the instructions of PySCIPOpt and SCIP. However, when I run
import pysciopt

I get the following error
'''

import pyscipopt
Traceback (most recent call last):
File "", line 1, in
File "/usr/local/lib/python2.7/dist-packages/pyscipopt/init.py", line 3, in
from pyscipopt.scip import Model
ImportError: /home/hayato/PySCIPOpt/lib/libscipopt.so: undefined symbol: rl_library_version'''

Has anyone come across this problem before?

Installation problems on Ubuntu 16

Hello

I tried to install the Python Interface but when I want to import a Model I get the following error:
ImportError: /root/PySCIPOpt/lib/libscipopt.so: undefined symbol: rl_library_version

I build the scip installation in a Docker container:

# Install all packages
RUN apt-get update && apt-get upgrade -y && apt-get install -y build-essential libgmp3-dev zlib1g-dev  libreadline-dev python3 cython3 libncurses5-dev git

# Extract the tgz from the SCIP Page to the folder /root/scipoptsuite-3.2.1
ADD scipoptsuite-3.2.1.tgz /root  

WORKDIR /root/scipoptsuite-3.2.1

# Use INSTALLDIR ../../ to install it in the /usr/local and not in the /root/scipoptsuite-3.2.1/usr/local
RUN make -j6 && make -j6 SHARED=true scipoptlib && make -j6 install INSTALLDIR="../../usr/local"

WORKDIR /root/
RUN git clone https://github.com/SCIP-Interfaces/PySCIPOpt.git

WORKDIR /root/PySCIPOpt
RUN env SCIPOPTDIR=/root/scipoptsuite-3.2.1 python3 setup.py install

The make test runs through and I can start enter the scip to start the interactive shell.

Also in the folder /root/scipoptsuite-3.2.1 there is the lib-folder with the libscipopt.so and the src-folder under scip-3.2.1/src/.

What I missed?

gcc (Ubuntu 5.4.0-6ubuntu1~16.04.4) 5.4.0 20160609
Python 3.5.2 (default, Nov 17 2016, 17:05:23)
Cython version 0.23.4

Non Linear expressions

Hi,

First of all, thanks for the interface, coming from gurobipy, the transition was seamless.

However, I am looking to use non-linear expression, namely a log in the objective function. Looking inside the code and documentation, I couldn't find the correct way to do it.

Is it implemented yet?

Best,
Yoann

CONST part of Expression produces error in setObjective

the code in set objective says

assert isinstance(coeffs, Expr)
for term, coef in coeffs.terms.items():
    var = <Variable>term[0]
    PY_SCIP_CALL(SCIPchgVarObj(self._scip, var.var, coef))

which produces an error when term is (), ie, the CONST part of coeffs.

A solution is to put an if coef != 0.0: before. It this okay?

Slack variables?

Is there a way of accessing slack variables associated to a constraint in PySCIPOpt?

Handling of constraint releases not uniform across addCons methods

Not all addCons methods, namely addConsSOS1 and addConsSOS2, release the constraint pointer at the end of the method.

The method _addLinCons does the following:

        PY_SCIP_CALL(SCIPaddCons(self._scip, scip_cons))
        PyCons = Constraint.create(scip_cons)
        PY_SCIP_CALL(SCIPreleaseCons(self._scip, &scip_cons))

        return PyCons

However, I think none of the two approaches is really correct. When the PyCons is created, it has a pointer to the scip_cons internally. Only when this object is freed, a SCIPreleaseCons should be called, in my opinion.

This should currently not matter much, because none of the examples I have looked at so far ever use the returned PyCons object.

cutting planes

When I have a scip model that I have already solved,
if I add one additional constraint, such as e.g.
self.scip_model.addCons(expression <= 0)

(to make a cutting plane), I can't re-solve the problem:

/home/optimi/bzfsagno/python/lib/python2.7/site-packages/pyscipopt/scip.so in pyscipopt.scip.PY_SCIP_CALL (pyscipopt/scip.c:20408)()

Exception: SCIP: method cannot be called at this time in solution process!

I had a look at the example cutting_stock.py, but it seems that a function relax() is missing.
I'm not 100% sure of what relax() must do, but in any case with the approach in this file it is
a different copy of the scip model which is solved at each iteration. Would'nt it be possible to
just re-solve the same scip model without the need to create copies of it?

Different solutions by PySCIP and C++

I am trying SCIP on a mixed integer programming problem. While the python API gives the correct solution (figure 1), c++ version is not able to (figure 2). I found that both solution processes give exactly the same presolving result, which suggests I made no mistake in creating variables and constraints. Yet, I am not able to tell why this happens...

python

c

Cannot fix variables with chgVarLb() / chgVarUb()

Fixing variables with model.chgVarLb() / chgVarUb() does not seem to be working. Using the program attached (and miplib3's instance p0033.mps) leads to the error:

[src/scip/scip.c:19803] ERROR: invalid SCIP stage <10>
[...]
Exception: SCIP: method cannot be called at this time in solution process!

jpp

mipissue.py.txt

setup.sh should work when libscipopt and scip includes are installed in a standard location

I would suggest the following.

  1. As seems to be standard with Cython extensions, users are expected to simply set CPPFLAGS and LDFLAGS so that the compiler will find headers ands the library.
  2. Offer the SCIPOPTDIR variables as a convenience (which if provided would set include_dirs and library_dirs), but don't require it.
  3. Don't require symlinks.

(On a related note, SCIP's "make install" forgets to install several header files. https://trac.sagemath.org/ticket/21094 has patches for that and other things.)

make tests and example more SCIP conform

do not mix up original and transform data: look at test_tsp for an example

I guess the solution is to transform the original variables at some point (exitpre maybe)

setup travis

There are tests! We should run them. I personally like travis-ci.

Installation problems

This may be a trivial error but I use conda_setup.py to install scip and I get an ImportError.
File "pyscipopt/__init__.py", line 3,
from pyscipopt.scip import Model
Import Error: No module named scip

Installation problem using pip

Hi
I'm trying to install pyscipopt, but I'm running into some problems. I have installed the SCIP and completed the test succesfully. But when I run pip install pyscipopt I get det following output.
I'm using ubuntu 16 and anaconda. I have added 'export SCIPOPTDIR=~/programs/scipoptsuite-4.0.0' to my .barchrc file. Scipy is updated and python dev installed.
Do you have any ideas what I'm missing?


Collecting pyscipopt
Using cached PySCIPOpt-1.0.2.tar.gz
Building wheels for collected packages: pyscipopt
Running setup.py bdist_wheel for pyscipopt ... error
Complete output from command /home/peter/anaconda2/bin/python -u -c "import setuptools, tokenize;file='/tmp/pip-build-HbQXGx/pyscipopt/setup.py';exec(compile(getattr(tokenize, 'open', open)(file).read().replace('\r\n', '\n'), file, 'exec'))" bdist_wheel -d /tmp/tmpr5VaLEpip-wheel- --python-tag cp27:
running bdist_wheel
running build
running build_py
creating build
creating build/lib.linux-x86_64-2.7
creating build/lib.linux-x86_64-2.7/pyscipopt
copying pyscipopt/init.py -> build/lib.linux-x86_64-2.7/pyscipopt
copying pyscipopt/Multidict.py -> build/lib.linux-x86_64-2.7/pyscipopt
running build_ext
building 'pyscipopt.scip' extension
creating build/temp.linux-x86_64-2.7
creating build/temp.linux-x86_64-2.7/pyscipopt
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/peter/programs/scipoptsuite-4.0.0/include -I/home/peter/anaconda2/include/python2.7 -c pyscipopt/scip.c -o build/temp.linux-x86_64-2.7/pyscipopt/scip.o
pyscipopt/scip.c:306:23: fatal error: scip/scip.h: No such file or directory
compilation terminated.
error: command 'gcc' failed with exit status 1


Failed building wheel for pyscipopt
Running setup.py clean for pyscipopt
Failed to build pyscipopt
Installing collected packages: pyscipopt
Running setup.py install for pyscipopt ... error
Complete output from command /home/peter/anaconda2/bin/python -u -c "import setuptools, tokenize;file='/tmp/pip-build-HbQXGx/pyscipopt/setup.py';exec(compile(getattr(tokenize, 'open', open)(file).read().replace('\r\n', '\n'), file, 'exec'))" install --record /tmp/pip-NDmx1R-record/install-record.txt --single-version-externally-managed --compile:
running install
running build
running build_py
creating build
creating build/lib.linux-x86_64-2.7
creating build/lib.linux-x86_64-2.7/pyscipopt
copying pyscipopt/init.py -> build/lib.linux-x86_64-2.7/pyscipopt
copying pyscipopt/Multidict.py -> build/lib.linux-x86_64-2.7/pyscipopt
running build_ext
building 'pyscipopt.scip' extension
creating build/temp.linux-x86_64-2.7
creating build/temp.linux-x86_64-2.7/pyscipopt
gcc -pthread -fno-strict-aliasing -g -O2 -DNDEBUG -g -fwrapv -O3 -Wall -Wstrict-prototypes -fPIC -I/home/peter/programs/scipoptsuite-4.0.0/include -I/home/peter/anaconda2/include/python2.7 -c pyscipopt/scip.c -o build/temp.linux-x86_64-2.7/pyscipopt/scip.o
pyscipopt/scip.c:306:23: fatal error: scip/scip.h: No such file or directory
compilation terminated.
error: command 'gcc' failed with exit status 1

----------------------------------------

Command "/home/peter/anaconda2/bin/python -u -c "import setuptools, tokenize;file='/tmp/pip-build-HbQXGx/pyscipopt/setup.py';exec(compile(getattr(tokenize, 'open', open)(file).read().replace('\r\n', '\n'), file, 'exec'))" install --record /tmp/pip-NDmx1R-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-HbQXGx/pyscipopt/

How to get data from a problem when using `readProb()`?

  • implement getCoef(Constraint, Variable)
    Until now there is no way to get the coefficients of any constraints, when the problem was not created using PySCIPOpt. we should support this for linear, knapsack...
    This is how Gurobi does it.
  • store the constraint data within the Python Constraint
    unclear how to realize the identification of a constraint: names may not be unique
    The different ConsHdlrs could (should) be represented as different subclasses of Constraint... or we could store the type of the constraint and internally apply the corresponding method if it exists. For example, to have a linear constraint "handler" in python, which handles linear, knapsack, etc

How to use constraint handlers methods

How can I get the method CONSRESPROP triggered in a constraint handler for domain propagation?

I have implemented the three methods conscheck, consenfolp and conslock. I also added the method consresprop but the method never get called.

model = Model("Election")
conshdlr = ElectionHdlr(s, row=row, col=col, cons=constituency, logger=logger)
model.includeConshdlr(conshdlr, "election",  "Election", chckpriority=-10000,
                                       needscons=False, propfreq=10)
model.setBoolParam("misc/allowdualreds", False)

# Why is this necessary?
cons1 = model.createCons(conshdlr, "election")
conshdlr.createData(cons1, 10, "cons1_anothername")
model.addPyCons(cons1)

I would like to use the domain propagation for setting some constraints during the solve process. Are there any examples?

Thanks

PySCIPOpt test error

Dear Developers,

I installed the PySCIPOpt package on two Linux machines by following the instruction below
https://github.com/SCIP-Interfaces/PySCIPOpt/blob/master/INSTALL.md
But I encountered the following error
ImportError: No module named 'pyscipopt.scip'
when I tested the examples by py.test on one machine. The Linux version of this machine is
CentOS Linux release 7.2.1511
However, I can run the examples on the other Linux machine which is probably Ubuntu.

Could you give me some hints about how to solve this issue? Thank you very much!!

removing and adding constraints

I want to solve successive optimization problems, by removing and adding a set of constraints. I'm not sure how this may best be achieved. In the C-API there is a method to disable/enable a constraint, would this be the way to go? If it is, would it be possible to extend the python interface to include this functionality?

Problem with importing PySCIPOpt

I am trying to install PySCIPOpt on Ubuntu 16.04. The shared library is at /usr/local/lib and the binary at /usr/local/bin. After building PySCIPOpt from source, I got the following error when trying to import the package from python. I think libscipopt.so is already in position. Your input is much appreciated!!!

Python 2.7.12 (default, Nov 19 2016, 06:48:10)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.

import pyscipopt
Traceback (most recent call last):
File "", line 1, in
File "build/bdist.linux-x86_64/egg/pyscipopt/init.py", line 3, in
File "build/bdist.linux-x86_64/egg/pyscipopt/scip.py", line 7, in
File "build/bdist.linux-x86_64/egg/pyscipopt/scip.py", line 6, in bootstrap
ImportError: libscipopt.so: cannot open shared object file: No such file or directory

/usr/local/lib$ ls
libobjscip.so
libscip-4.0.0.linux.x86_64.gnu.opt.a
libscip-4.0.0.linux.x86_64.gnu.opt.so
libscip.a
libscip.linux.x86_64.gnu.opt.a
libscip.linux.x86_64.gnu.opt.so
libscipopt-4.0.0.linux.x86_64.gnu.opt.a
libscipopt-4.0.0.linux.x86_64.gnu.opt.so
libscipopt.a
libscipopt.so
libscip.so
libsoplex-3.0.0.linux.x86_64.gnu.opt.a
libsoplex-3.0.0.linux.x86_64.gnu.opt.so
libsoplex.a

Support for SOCP

Hi,
currently SOCP constraints such as
x^2 + y^2 <= t^2

are treated as a non-convex quadratic constraint when passed to PySCIPOpt.

Would it be possible to develop an interface to SCIP's c-code of cons_soc.h ? Then, I could implement SOCPs' correctly in PICOS!

Thanks, Guillaume.

Documentation inconsistency in setObjective()

From the docstring of setObjective() one might expect that the objective function is replaced by the given expression:

def setObjective(self, coeffs, sense = 'minimize'):
    """Establish the objective function, either as a variable dictionary or as a linear expression.

    Keyword arguments:
    coeffs -- the coefficients
    sense -- the objective sense (default 'minimize')
    """

This does not correspond to what is actually happening, though: Only the objective coefficents of the specified variables in the given expression are changed - all others will remain untouched.

OS X runtime library issues

The library of the SCIP Optimization Suite 4.0.0 is not built correctly on OS X. You need to modify the library slightly to make it work with PySCIPOpt:

install_name_tool -id '@rpath/libscipopt-4.0.0.darwin.x86_64.gnu.opt.so' lib/libscipopt-.0.0.darwin.x86_64.gnu.opt.so

You may need to adapt the call to match the correct name of the library on your system.

Execute this command after having generated the library with make scipoptlib SHARED=true. You may then call make install INSTALLDIR=<___> SHARED=true to copy the library and the necessary headers to some directory.

With this modification, PySCIPOpt can find the library at runtime.

SCIP Python Installation Windows with pip

Hello community / developers,

I am currently trying to install SCIP with python and found that there is Windows Support and a pip installer based on https://github.com/SCIP-Interfaces/PySCIPOpt/blob/master/INSTALL.md.

Nevertheless I run into a problem "Cannot open include file"

Below is a list of the things I performed to get to this step.

  1. Download Python Anaconda 2.7 64 bit from https://www.continuum.io/downloads
  2. Install with all checkboxes as they are
  3. Download PyCharm Community edition from https://www.jetbrains.com/pycharm/download/#section=windows
  4. Click 64 bit desktop link, and associate with .py checkboxes
  5. Open CMD > write: easy_install -U pip
  6. Download Visual C++ Compiler for Python 2.7 from https://www.microsoft.com/en-us/download/confirmation.aspx?id=44266
  7. Setup folder structure and downloaded header files
  8. CMD > pip install pyscipopt leads to error:

C:\Users\UserName\Downloads\SCIPOPTDIR\include\scip/def.h(32) : fatal error C1083: Cannot open include file: 'stdint.h': No such file or directory
error: command 'C:\Users\UserName\AppData\Local\Programs\Common\Microsoft\Visual C++ for Python\9.0\VC\Bin\cl.exe' failed with exit status 2

My environment variables and folder directory can be found here:
http://imgur.com/a/mJRva

Help is very much appreciated,
Kind regards

How to install it on Windows?

the INSTAll.md introduces the installing process on Linux, I wonder how to install it on Windows. looking forward to your reply, thank you very much.

clean up examples

Which of the examples actually work with PySCIPOpt? Should they be turned into automated tests?
Delete all the other files.

`SCIP_CALL` decorator

The scipErrorHandler decorator destroys our docstrings.

There are two ways around this:

  1. using functools.wraps to preserve the docstring
  2. use PY_SCIP_CALL explicitly instead of the decorator.

What do you think, @leethargo @fserra @xmunoz?

test suite failures (GIT version 2016/08/20)

I get the following test suite failures on my Gentoo system.
PySCIPOpt has been compiled from GIT (on 2016/08/20)
I have version 3.2.1 of the scipoptsuite installed here.

test_alldiff.py

Traceback (most recent call last):
File "test_alldiff.py", line 286, in
test_main()
File "test_alldiff.py", line 267, in test_main
scip, x = create_sudoku()
File "test_alldiff.py", line 225, in create_sudoku
domains[var] = vals
TypeError: unhashable type: 'pyscipopt.scip.Variable'


test_memory.py

Traceback (most recent call last):
File "test_memory.py", line 19, in
test_not_freed()
File "test_memory.py", line 7, in test_not_freed
pytest.skip()
File "/usr/lib64/python3.5/site-packages/_pytest/runner.py", line 468, in skip
raise Skipped(msg=msg)
Skipped:


test_short.py -- where are the files check/testset/short.{test,solu} ???

Traceback (most recent call last):
File "test_short.py", line 17, in
pytest.skip("Files for testset short not found (symlink missing?)")
File "/usr/lib64/python3.5/site-packages/_pytest/runner.py", line 468, in skip
raise Skipped(msg=msg)
Skipped: Files for testset short not found (symlink missing?)

Dual variables not accessible

The dual solution does not seem to be accessible; e.g., for a constraint c[i]
model.getDualsolLinear(c[i])
seems to always return 0.

Missing PATH description in INSTALL.rst

I find that one has to add %SCIPOPTDIR%\bin to path variable on Windows as well, not just the lib directory. Otherwise, I get an error complaining about cannot find dll.

segmentation fault running pyscipopt

Hi.

I have a problem at hand where I need to generate an instance and run the solver. Since I have a number of instances, I am trying to do this in a loop, i.e. in each loop {generate instance, build model, run model}. This is working for the first run over the loop. However, when the loop is executed second time, I am getting segfault error. If I comment "model.optimize()" there is no segfault. Wondering what could be the problem. I have removed readline library while compiling scipopt.

Example code is given below.

import os
import sys
from pyscipopt import Model, quicksum, multidict, Conshdlr, SCIP_RESULT, SCIP_PRESOLTIMING, SCIP_PROPTIMING

#create model now
class GMVconshdlr1(Conshdlr):

	def __init__(self, var1, var2,var3,var4):
    		self.I = var1
    		self.p = var2
    		self.alpha = var3
    		self.D = var4
    

  # checks whether solution is feasible
	def conscheck(self, constraints, solution, check_integrality, check_lp_rows, print_reason, completely, **results):
   	 	return {"result": SCIP_RESULT.FEASIBLE}

  # enforces LP solution
	def consenfolp(self, constraints, n_useful_conss, sol_infeasible): 
		self.model.addCons(quicksum((D[i]-alpha[i]*p[i]) for i in I if (i) in p) == t, name="Margin constraint") 
		return {"result": SCIP_RESULT.CONSADDED}

	def conslock(self, constraint, nlockspos, nlocksneg):
		pass



def max_gmv_st_totmargin(I,D,alpha):
    model1 = Model("price optimization")

    # Create variables
    p = {}
                       
    for i in I:
          p[i] = model1.addVar(vtype="C", name="p(%s)" % (i), lb = 200.0, ub = 500 )

    t={}
    t = model1.addVar(vtype="C", name="t",  ub = None )        

                              

    # Objective
    conshdlr = GMVconshdlr1(I,p,alpha,D)
    model1.includeConshdlr(conshdlr, "GVM", "GMV constraint", sepapriority = 0, enfopriority = -1, chckpriority = -1, sepafreq = -1, propfreq = -1, eagerfreq = -1, maxprerounds = 0, delaysepa = False, delayprop = False, needscons = True) 
    model1.setObjective(t, "maximize")

    model1.data = p,t

    return model1 





if __name__ == "__main__":
	os.chdir(".")
	for D in range(100, 300, 100): 
		d_arg={}
		alpha_arg={}
		d_arg[1]=15
		alpha_arg[1]= 0.033
		I={}
		I[1]=1
		D={}
		alpha={}
	
		D[1]= d_arg[1] 
		alpha[1]= alpha_arg[1] 
	
		model1 = max_gmv_st_totmargin(I,D,alpha)
		model1.optimize() 
		p, t =model1.data

Dual solution after recalculation

After I resolve a problem the dual values of a constraint is not updated, i.e. take a look at the following code:

import pyscipopt as scp
Mod=scp.Model()
Mod.setMaximize()
Mod.setPresolve(scp.SCIP_PARAMSETTING.OFF)
Mod.hideOutput()
x=Mod.addVar(ub=3,name="x",obj=0.1,vtype="C")
y=Mod.addVar(ub=3,name="y",obj=1)
c=Mod.addCons(x+y<=3,"C1")
  
Mod.optimize()
print("SCIP")
print("obj: ", Mod.getObjVal())
print(x.name,Mod.getVal(x))
print(y.name,Mod.getVal(y))
print("pi: ",Mod.getDualsolLinear(c))    
Mod.freeTransform() 
Mod.chgRhs(c,2)

Mod.optimize()
print("obj: ", Mod.getObjVal())
print(x.name,Mod.getVal(x))
print(y.name,Mod.getVal(y))
print("pi: ",Mod.getDualsolLinear(c))    

Output:

SCIP
obj:  3.0
x 0.0
y 3.0
pi:  0.1
obj:  2.0 
x 0.0
y 2.0
pi:  0.1

But clearly pi should be 1 after the constraint is tightened. If I also remove x from the objective function I receive the following: Warning: no dual solution available for constraint C1

Is this a bug or do I need to call some update function? I can just use another LP solver, just curious why I observe this behavior.

Thanks for all the help guys :)

Tests failing when libscipopt.so is compiled with OPT=dbg

After getting a fresh libscipopt.so with proper dependencies, I reran the tests which were still failing/crashing. In particular, there is SEGFAULT in test_conshdlr.py that seems to be related to the constraint names:

Program received signal SIGSEGV, Segmentation fault.
0x00007ffff6cea0ca in strlen () from /usr/lib/libc.so.6
(gdb) bt
#0  0x00007ffff6cea0ca in strlen () from /usr/lib/libc.so.6
#1  0x00007ffff79a075b in PyBytes_FromString (str=0x0)
    at Objects/bytesobject.c:106
#2  0x00007ffff67f8949 in __pyx_pf_9pyscipopt_4scip_10Constraint_4name___get__
    (__pyx_v_self=<optimized out>) at pyscipopt/scip.c:34518
#3  __pyx_pw_9pyscipopt_4scip_10Constraint_4name_1__get__ (
    __pyx_v_self=<optimized out>) at pyscipopt/scip.c:34496
#4  __pyx_getprop_9pyscipopt_4scip_10Constraint_name (o=<optimized out>, 
    x=<optimized out>) at pyscipopt/scip.c:55820
#5  0x00007ffff79e1593 in _PyObject_GenericGetAttrWithDict (
    obj=0x7ffff50f1d88, name=0x7ffff6c5b8b8, dict=0x0) at Objects/object.c:1043
...

For fun I recompiled libscipopt.so using OPT=opt and recompiled PySCIPOpt. Now all tests pass!

No access to variables' (global) bounds.

Sometimes it is necessary to know variables' global bounds (e.g., for models read in mps format).
This does not seem to be available in the current Python interface.

jpp

release variable, constraints, rows, etc

this is the follow up of issue 55 on gitlab.

In addVar we create a SCIP var and then release it. The same happens in addCons.
So the idea is then to have a __dealloc__, as in class Model, for variables, constraints, rows, etc, right?

get dual solution

The below code results in a segmentation fault error at the last line. If makes any difference I am running python 3.5 on Ubuntu. Any idea why this happens?

import pyscipopt as scp
Mod=scp.Model()
Mod.setPresolve(0)
Mod.hideOutput()
x=Mod.addVar(ub=3,name="x")
y=Mod.addVar(ub=4,name="y")
c1=Mod.addCons(x+y<=3,"C1")
Mod.setObjective(x+y, "maximize")
Mod.optimize()
print(Mod.getObjVal())
print(Mod.getDualsolLinear(c1)) # Error

Error message: Segmentation fault (core dumped)

AttributeError: 'tuple' object has no attribute 'ptrtuple'

python test_tsp.py # this is from the test suite
Traceback (most recent call last):
File "test_tsp.py", line 116, in
test_main()
File "test_tsp.py", line 110, in test_main
objective_value, edges = solve_tsp(vertices, distance)
File "test_tsp.py", line 88, in solve_tsp
model, x = create_tsp(vertices, distance)
File "test_tsp.py", line 83, in create_tsp
"minimize")
File "pyscipopt/scip.pyx", line 442, in pyscipopt.scip.Model.setObjective (pyscipopt/scip.c:38864)
File "pyscipopt/expr.pxi", line 55, in pyscipopt.scip.Term.eq (pyscipopt/scip.c:4904)
AttributeError: 'tuple' object has no attribute 'ptrtuple'

This occurs with the GIT version of PySCIPOpt used with Python 3.5.2

File "test_tsp.py", line 83, in create_tsp is this statement:

model.setObjective(
quicksum(distance[i,j] * x[i,j] for (i,j) in pairs(vertices)),
"minimize")

File "pyscipopt/expr.pxi", line 55 is this statement:

def __eq__(self, other):
    return self.ptrtuple == other.ptrtuple

where "other" is an (ordinary) tuple

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.