Skip to content

Commit

Permalink
Basic documentation (not complete)
Browse files Browse the repository at this point in the history
  • Loading branch information
metab0t committed Jan 27, 2024
1 parent c46816d commit 7a05cb5
Show file tree
Hide file tree
Showing 17 changed files with 582 additions and 34 deletions.
45 changes: 14 additions & 31 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,37 +1,12 @@
PyOptInterface
=======

# Overview

**PyOptInterface** is an open-source Python library to provide a unified API to construct and solve optimization models with various optimizers.

It is designed as a very thin wrapper of native C API of optimizers and attempts to provide common abstractions of an algebraic modelling environment including model, variable, constraint and expression with the least overhead of performance.

The key features of PyOptInterface include:
- Very fast speed to construct optimization model (10-20x faster than Pyomo, faster than JuMP.jl and some official Python bindings of optimizers)
- Low overhead to modify and re-solve the problem incrementally
- Unified API to cover common usages, write once and the code works for all optimizers
- You still have escape hatch to query or modify solver-specific parameter/attribute/information for different optimizers directly like the vendored Python binding of optimizer

It currently supports the following optimizers:
- [Gurobi](https://www.gurobi.com/)
- [COPT](https://shanshu.ai/copt)
- [MOSEK](https://www.mosek.com/)

It currently supports the following problem types:
- Linear Programming (LP)
- Mixed-Integer Linear Programming (MILP)
- Quadratic Programming (QP)
- Mixed-Integer Quadratic Programming (MIQP)
- Quadratically Constrained Quadratic Programming (QCQP)
- Mixed-Integer Quadratically Constrained Quadratic Programming (MIQCQP)

# Installation
```bash
## Installation
```console
pip install pyoptinterface
```

# Example
## Example
```python
import pyoptinterface as poi
from pyoptinterface import gurobi
Expand Down Expand Up @@ -59,7 +34,15 @@ y_val = model.get_variable_attribute(y, poi.VariableAttribute.Value)
# 1.0
```

# Documentation
## Documentation
Find the documentation [here](https://pyoptinterface.readthedocs.io/en/latest/).

## Acknowledgements
The design of PyOptInterface is inspired by [JuMP.jl](https://jump.dev).

## License
PyOptInterface is licensed under MPL-2.0 License.

It uses [nanobind](https://github.com/wjakob/nanobind), [fmtlib](https://github.com/fmtlib/fmt) and [martinus/unordered_dense](https://github.com/martinus/unordered_dense) as dependencies.

# License
PyOptInterface is licensed under MPL-2.0 License.
The design of PyOptInterface is inspired by [JuMP.jl](https://jump.dev).
20 changes: 20 additions & 0 deletions docs/Makefile
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# Minimal makefile for Sphinx documentation
#

# You can set these variables from the command line, and also
# from the environment for the first two.
SPHINXOPTS ?=
SPHINXBUILD ?= sphinx-build
SOURCEDIR = source
BUILDDIR = build

# Put it first so that "make" without argument is like "make help".
help:
@$(SPHINXBUILD) -M help "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)

.PHONY: help Makefile

# Catch-all target: route all unknown targets to Sphinx using the new
# "make mode" option. $(O) is meant as a shortcut for $(SPHINXOPTS).
%: Makefile
@$(SPHINXBUILD) -M $@ "$(SOURCEDIR)" "$(BUILDDIR)" $(SPHINXOPTS) $(O)
35 changes: 35 additions & 0 deletions docs/make.bat
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
@ECHO OFF

pushd %~dp0

REM Command file for Sphinx documentation

if "%SPHINXBUILD%" == "" (
set SPHINXBUILD=sphinx-build
)
set SOURCEDIR=source
set BUILDDIR=build

%SPHINXBUILD% >NUL 2>NUL
if errorlevel 9009 (
echo.
echo.The 'sphinx-build' command was not found. Make sure you have Sphinx
echo.installed, then set the SPHINXBUILD environment variable to point
echo.to the full path of the 'sphinx-build' executable. Alternatively you
echo.may add the Sphinx directory to PATH.
echo.
echo.If you don't have Sphinx installed, grab it from
echo.https://www.sphinx-doc.org/
exit /b 1
)

if "%1" == "" goto help

%SPHINXBUILD% -M %1 %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%
goto end

:help
%SPHINXBUILD% -M help %SOURCEDIR% %BUILDDIR% %SPHINXOPTS% %O%

:end
popd
8 changes: 8 additions & 0 deletions docs/source/api/pyoptinterface.gurobi.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
pyoptinterface.gurobi package
====================================

.. automodule:: pyoptinterface.gurobi
:members:
:inherited-members:
:undoc-members:
:show-inheritance:
15 changes: 15 additions & 0 deletions docs/source/api/pyoptinterface.rst
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
pyoptinterface package
===========================

.. automodule:: pyoptinterface
:members:
:undoc-members:
:show-inheritance:

Submodules
-----------

.. toctree::
:maxdepth: 2

pyoptinterface.gurobi.rst
32 changes: 32 additions & 0 deletions docs/source/conf.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
# Configuration file for the Sphinx documentation builder.
#
# For the full list of built-in configuration values, see the documentation:
# https://www.sphinx-doc.org/en/master/usage/configuration.html

# -- Project information -----------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#project-information

project = "PyOptInterface"
copyright = "2024, Yue Yang"
author = "Yue Yang"

# -- General configuration ---------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#general-configuration

extensions = [
"myst_parser",
"sphinx.ext.autodoc",
"sphinx_copybutton",
]

myst_enable_extensions = ["colon_fence", "dollarmath", "amsmath"]

templates_path = ["_templates"]
exclude_patterns = []


# -- Options for HTML output -------------------------------------------------
# https://www.sphinx-doc.org/en/master/usage/configuration.html#options-for-html-output

html_theme = "furo"
html_static_path = ["_static"]
2 changes: 2 additions & 0 deletions docs/source/constraint.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Constraint

75 changes: 75 additions & 0 deletions docs/source/expression.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,75 @@
# Expression

## Basic expression
PyOptInterface currently supports polynomial expressions with degree up to 2, including
- quadratic expression
- linear expression
- constant expression

The expression can be expressed by arithmetic operations of variables and constants. For example, we can create a quadratic expression by adding two quadratic expressions, multiplying a linear expression with a constant expression, etc.

```python
import pyoptinterface as poi
from pyoptinterface import gurobi

model = gurobi.Model()

x = model.add_variable()

# create a quadratic expression
expr1 = x * x + 2 * x + 1
# create a linear expression
expr2 = 2 * x + 1

# create a quadratic expression by adding two quadratic expressions
expr3 = x * expr2 + expr1
```

## Efficient expression construction
PyOptInterface provides a special class `ExprBuilder` to construct expressions efficiently. It is especially useful when we need to construct a large expression with many terms.

It supports the following operations:
- `add`: add a term to the expression
- `sub`: subtract a term from the expression
- `mul`: multiply the expression with a constant or another expression
- `div`: divide the expression with a constant

For example, we can use `ExprBuilder` to construct the following expression efficiently:

$$
\frac{1}{2} \sum_{i=1}^N x_i^2 - \sum_{i=1}^N x_i
$$

```python
expr = poi.ExprBuilder()

N = 1000
xs = [model.add_variable() for _ in range(N)]

for i in range(N):
expr.add(x[i] * x[i])
expr.sub(2 * x[i])

expr.mul(0.5)
```

## Pretty print expression
If the names of variables are specified, We can use the `pprint` method to print the expression in a human-readable format:

```python
x = model.add_variable(name="x")
y = model.add_variable(name="y")

expr = x * x + 2 * x * y + y * y

model.pprint(expr)
# output: 1*x*x + 2*x*y + 1*y*y
```

## Value of expression
We can use the `get_value` method to get the value of an expression after optimization:

```python
expr = x*y + x*x
expr_value = model.get_value(expr)
```
100 changes: 100 additions & 0 deletions docs/source/getting_started.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,100 @@
# Getting Started

## Installation
PyOptInterface has no dependencies other than Python itself. It can be installed via pip:
```console
pip install pyoptinterface
```

After installation, you can import the package via:
```python
import pyoptinterface as poi
```

## Let's build a simple model and solve it
As the first step, we will solve the following simple Quadratic Programming (QP) problem:

```{math}
\min \quad & x^{2}_{1} + 2x^{2}_{2} \\
\textrm{s.t.} \quad & x_{1} + x_{2} = 1 \\
\quad & x_{1}, x_{2} \geq 0
```

First, we need to create a model object:

:::{tip}
You need to acquire a valid license of [supported solvers](#supported-optimizers) to use them. If you want to use another optimizer, you can replace `gurobi` with `copt` or `mosek`)
:::

```python
import pyoptinterface as poi
from pyoptinterface import gurobi
# from pyoptinterface import copt (if you want to use COPT)

model = gurobi.Model()
```

Then, we need to add variables to the model:
```python
x1 = model.add_variable(lb=0, name="x1")
x2 = model.add_variable(lb=0, name="x2")
```
The `lb` argument specifies the lower bound of the variable. It is optional and defaults to $-\infty$.

The `name` argument is optional and can be used to specify the name of the variable.

Then, we need to add constraints to the model:
```python
con = model.add_linear_constraint(x1+x2, poi.ConstraintSense.Equal, 1, name="con")
```
`model.add_linear_constraint` adds a linear constraint to the model.
- The first argument `x1+x2` is the left-hand side of the constraint.
- The second argument is the sense of the constraint. It can be `poi.ConstraintSense.Equal`, `poi.ConstraintSense.LessEqual` or `poi.ConstraintSense.GreaterEqual`.
- The third argument is the right-hand side of the constraint. It must be a constant.
- The fourth argument is optional and can be used to specify the name of the constraint.

Finally, we need to set the objective function and solve the model:
```python
obj = x1*x1 + 2*x2*x2
model.set_objective(obj, poi.ObjectiveSense.Minimize)
```

The model can be solved via:
```python
model.optimize()
```
The Gurobi solver will be invoked to solve the model and writes the log to the console.

We can query the status of the model via:
```python
assert model.get_model_attribute(poi.ModelAttributes.TerminationStatus) == poi.TerminationStatusCode.OPTIMAL
```

The solution of the model can be queried via:
```python
print("x1 = ", model.get_value(x1))
print("x2 = ", model.get_value(x2))
print("obj = ", model.get_value(obj))
```

The whole code is as follows:
```python
import pyoptinterface as poi
from pyoptinterface import gurobi

model = gurobi.Model()
x1 = model.add_variable(lb=0, name="x1")
x2 = model.add_variable(lb=0, name="x2")

con = model.add_linear_constraint(x1+x2, poi.ConstraintSense.Equal, 1, name="con")

obj = x1*x1 + 2*x2*x2
model.set_objective(obj, poi.ObjectiveSense.Minimize)

model.optimize()
assert model.get_model_attribute(poi.ModelAttributes.TerminationStatus) == poi.TerminationStatusCode.OPTIMAL

print("x1 = ", model.get_value(x1))
print("x2 = ", model.get_value(x2))
print("obj = ", model.get_value(obj))
```
Loading

0 comments on commit 7a05cb5

Please sign in to comment.