PyGLPK

0.4.8 · active · verified Thu Apr 16

PyGLPK (Python GLPK) is a Python module that provides a comprehensive interface to the GNU Linear Programming Kit (GLPK). It allows Python users to model and solve linear programming (LP), mixed integer programming (MIP), and other related optimization problems. The current version is 0.4.8. It has a moderate release cadence, largely tied to maintenance and updates related to the underlying GLPK C library.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart defines and solves a simple linear programming problem with two continuous variables and three constraints. It demonstrates variable definition, objective function setup, constraint creation, solving the problem, and interpreting the results.

from glpk import LP, Var, N, C, GLPK

# Create a new problem
lp = LP()

# Define variables
x1 = lp.add_var(name='x1', lb=0.0, ub=N, kind=C) # lb=0, ub=infinity, continuous
x2 = lp.add_var(name='x2', lb=0.0, ub=N, kind=C)

# Set objective function (maximize 10*x1 + 6*x2)
lp.obj.dir = LP.MAX
lp.obj += 10 * x1 + 6 * x2

# Add constraints
# Constraint 1: x1 + x2 <= 100
c1 = lp.add_row(name='c1')
c1.add_term(x1, 1.0)
c1.add_term(x2, 1.0)
c1.upper_bound = 100.0

# Constraint 2: 7*x1 + 3*x2 <= 350
c2 = lp.add_row(name='c2')
c2.add_term(x1, 7.0)
c2.add_term(x2, 3.0)
c2.upper_bound = 350.0

# Constraint 3: 3*x1 + 5*x2 <= 150
c3 = lp.add_row(name='c3')
c3.add_term(x1, 3.0)
c3.add_term(x2, 5.0)
c3.upper_bound = 150.0

# Solve the problem
lp.simplex()

# Print results
if lp.status == GLPK.LP_OPT:
    print(f"Status: Optimal")
    print(f"Objective value: {lp.obj.value:.2f}")
    print(f"x1 = {x1.value:.2f}")
    print(f"x2 = {x2.value:.2f}")
elif lp.status == GLPK.LP_FEAS:
    print(f"Status: Feasible, but not necessarily optimal")
    print(f"Objective value: {lp.obj.value:.2f}")
    print(f"x1 = {x1.value:.2f}")
    print(f"x2 = {x2.value:.2f}")
else:
    print(f"Status: Solver terminated with status code: {lp.status}")

# Clean up
lp.delete()

view raw JSON →