quadprog: Quadratic Programming Solver

0.1.13 · active · verified Tue Apr 14

quadprog is a Python wrapper for a C++ library that efficiently solves quadratic programming problems. It minimizes `0.5 * x^T G x + a^T x` subject to `C^T x >= b` and an optional number of equality constraints (`meq`). The library is currently at version 0.1.13 and receives active, though somewhat irregular, maintenance.

Warnings

Install

Imports

Quickstart

This example demonstrates how to set up and solve a simple quadratic programming problem with inequality constraints using `quadprog.solve_qp`. The problem minimizes `x^2 + y^2 - x - y` subject to `x >= 0`, `y >= 0`, and `x + y >= 1`.

import numpy as np
from quadprog import solve_qp

# Define the quadratic program:
# Minimize 0.5 * x^T G x + a^T x
# Subject to C^T x >= b

# Example: Minimize x^2 + y^2 - x - y
# This means G = [[2, 0], [0, 2]] and a = [-1, -1]
G = np.array([[2., 0.], [0., 2.]])
a = np.array([-1., -1.])

# Constraints: x >= 0, y >= 0, x + y >= 1
# In quadprog, C's columns are the normal vectors of the constraints.
# C^T x >= b  =>  [[1, 0, 1], [0, 1, 1]]^T x >= [0, 0, 1]^T
# Which means:
# 1*x + 0*y >= 0
# 0*x + 1*y >= 0
# 1*x + 1*y >= 1
C = np.array([[1., 0., 1.],
              [0., 1., 1.]])
b = np.array([0., 0., 1.])

# Number of equality constraints (first 'meq' rows of C and b)
meq = 0

# Solve the QP. It returns (x, fval, xu, l)
# x: solution vector
# fval: objective function value at x
# xu: unconstrained solution (unused in this example)
# l: Lagrange multipliers (unused in this example)
solution, _, _, _ = solve_qp(G, a, C, b, meq)

print(f"Optimal solution x: {solution}")
# Expected output for this problem: Optimal solution x: [0.5 0.5]

view raw JSON →