Coverage for lpsolvers / cvxpy_.py: 94%

18 statements  

« prev     ^ index     » next       coverage.py v7.13.5, created at 2026-04-20 15:19 +0000

1#!/usr/bin/env python 

2# -*- coding: utf-8 -*- 

3# 

4# SPDX-License-Identifier: LGPL-3.0-or-later 

5# Copyright (C) 2016-2022 Stéphane Caron 

6 

7"""Solver interface for CVXPY.""" 

8 

9from typing import Optional 

10 

11import numpy as np 

12from cvxpy import Minimize, Problem, Variable 

13from numpy import array 

14 

15 

16def cvxpy_solve_lp( 

17 c: np.ndarray, 

18 G: np.ndarray, 

19 h: np.ndarray, 

20 A: Optional[np.ndarray] = None, 

21 b: Optional[np.ndarray] = None, 

22 solver: Optional[str] = None, 

23 verbose: bool = False, 

24 **kwargs, 

25) -> np.ndarray: 

26 r"""Solve a linear program using CVXPY. 

27 

28 The linear program is defined by: 

29 

30 .. math:: 

31 

32 \begin{split}\begin{array}{ll} 

33 \mbox{minimize} 

34 & c^T x \\ 

35 \mbox{subject to} 

36 & G x \leq h \\ 

37 & A x = b 

38 \end{array}\end{split} 

39 

40 It is solved using a solver wrapped by `CVXPY <http://www.cvxpy.org/>`_. 

41 The underlying solver is selected via the corresponding keyword argument. 

42 

43 Parameters 

44 ---------- 

45 c : 

46 Linear cost vector. 

47 G : 

48 Linear inequality constraint matrix. 

49 h : 

50 Linear inequality constraint vector. 

51 A : 

52 Linear equality constraint matrix. 

53 b : 

54 Linear equality constraint vector. 

55 solver : 

56 Solver name in ``cvxpy.installed_solvers()``. 

57 verbose : 

58 Set to `True` to print out extra information. 

59 

60 Returns 

61 ------- 

62 x : array, shape=(n,) 

63 Optimal (primal) solution of the linear program, if it exists. 

64 

65 Raises 

66 ------ 

67 ValueError 

68 If the LP is not feasible. 

69 """ 

70 n = c.shape[0] 

71 x = Variable(n) 

72 objective = Minimize(c @ x) 

73 constraints = [] 

74 if G is not None: 

75 constraints.append(G @ x <= h) 

76 if A is not None: 

77 constraints.append(A @ x == b) 

78 prob = Problem(objective, constraints) 

79 prob.solve(solver=solver, verbose=verbose, **kwargs) 

80 if x.value is None: 

81 raise ValueError("Linear program is not feasible") 

82 return array(x.value).reshape((n,))