Debian Codegraph @

ot/lp/cvx.py

raw symbols SCIP
1 # -*- coding: utf-8 -*-
2 """
3 LP solvers for optimal transport using cvxopt
4 """
5
6 # Author: Remi Flamary <[email protected]>
7 #
8 # License: MIT License
9
10 import numpy as np
11 import scipy as sp
12 import scipy.sparse as sps
13
14 try:
15 import cvxopt
16 from cvxopt import solvers, matrix, spmatrix
17 except ImportError:
18 cvxopt = False
19
20
21 def scipy_sparse_to_spmatrix(A):
22 """Efficient conversion from scipy sparse matrix to cvxopt sparse matrix"""
23 coo = A.tocoo()
24 SP = spmatrix(coo.data.tolist(), coo.row.tolist(), coo.col.tolist(), size=A.shape)
25 return SP
26
27
28 def barycenter(A, M, weights=None, verbose=False, log=False, solver="highs-ipm"):
29 r"""Compute the Wasserstein barycenter of distributions A
30
31 The function solves the following optimization problem [16]:
32
33 .. math::
34 \mathbf{a} = arg\min_\mathbf{a} \sum_i W_{1}(\mathbf{a},\mathbf{a}_i)
35
36 where :
37
38 - :math:`W_1(\cdot,\cdot)` is the Wasserstein distance (see ot.emd.sinkhorn)
39 - :math:`\mathbf{a}_i` are training distributions in the columns of matrix :math:`\mathbf{A}`
40
41 The linear program is solved using the interior point solver from scipy.optimize.
42 If cvxopt solver if installed it can use cvxopt
43
44 Note that this problem do not scale well (both in memory and computational time).
45
46 Parameters
47 ----------
48 A : np.ndarray (d,n)
49 n training distributions a_i of size d
50 M : np.ndarray (d,d)
51 loss matrix for OT
52 reg : float
53 Regularization term >0
54 weights : np.ndarray (n,)
55 Weights of each histogram a_i on the simplex (barycentric coordinates)
56 verbose : bool, optional
57 Print information along iterations
58 log : bool, optional
59 record log if True
60 solver : string, optional
61 the solver used, default 'interior-point' use the lp solver from
62 scipy.optimize. None, or 'glpk' or 'mosek' use the solver from cvxopt.
63
64 Returns
65 -------
66 a : (d,) ndarray
67 Wasserstein barycenter
68 log : dict
69 log dictionary return only if log==True in parameters
70
71
72 References
73 ----------
74
75 .. [16] Agueh, M., & Carlier, G. (2011). Barycenters in the Wasserstein space. SIAM Journal on Mathematical Analysis, 43(2), 904-924.
76
77
78 """
79
80 if weights is None:
81 weights = np.ones(A.shape[1]) / A.shape[1]
82 else:
83 assert len(weights) == A.shape[1]
84
85 n_distributions = A.shape[1]
86 n = A.shape[0]
87
88 n2 = n * n
89 c = np.zeros((0))
90 b_eq1 = np.zeros((0))
91 for i in range(n_distributions):
92 c = np.concatenate((c, M.ravel() * weights[i]))
93 b_eq1 = np.concatenate((b_eq1, A[:, i]))
94 c = np.concatenate((c, np.zeros(n)))
95
96 lst_idiag1 = [sps.kron(sps.eye(n), np.ones((1, n))) for i in range(n_distributions)]
97 # row constraints
98 A_eq1 = sps.hstack(
99 (sps.block_diag(lst_idiag1), sps.coo_matrix((n_distributions * n, n)))
100 )
101
102 # columns constraints
103 lst_idiag2 = []
104 lst_eye = []
105 for i in range(n_distributions):
106 if i == 0:
107 lst_idiag2.append(sps.kron(np.ones((1, n)), sps.eye(n)))
108 lst_eye.append(-sps.eye(n))
109 else:
110 lst_idiag2.append(sps.kron(np.ones((1, n)), sps.eye(n - 1, n)))
111 lst_eye.append(-sps.eye(n - 1, n))
112
113 A_eq2 = sps.hstack((sps.block_diag(lst_idiag2), sps.vstack(lst_eye)))
114 b_eq2 = np.zeros((A_eq2.shape[0]))
115
116 # full problem
117 A_eq = sps.vstack((A_eq1, A_eq2))
118 b_eq = np.concatenate((b_eq1, b_eq2))
119
120 if not cvxopt or solver in ["interior-point", "highs", "highs-ipm", "highs-ds"]:
121 # cvxopt not installed or interior point
122
123 if solver is None:
124 solver = "interior-point"
125
126 options = {"disp": verbose}
127 sol = sp.optimize.linprog(
128 c, A_eq=A_eq, b_eq=b_eq, method=solver, options=options
129 )
130 x = sol.x
131 b = x[-n:]
132
133 else:
134 h = np.zeros((n_distributions * n2 + n))
135 G = -sps.eye(n_distributions * n2 + n)
136
137 sol = solvers.lp(
138 matrix(c),
139 scipy_sparse_to_spmatrix(G),
140 matrix(h),
141 A=scipy_sparse_to_spmatrix(A_eq),
142 b=matrix(b_eq),
143 solver=solver,
144 )
145
146 x = np.array(sol["x"])
147 b = x[-n:].ravel()
148
149 if log:
150 return b, sol
151 else:
152 return b