| 1 |
|
| 2 |
""" |
| 3 |
d-MMOT solvers for optimal transport |
| 4 |
""" |
| 5 |
|
| 6 |
|
| 7 |
|
| 8 |
|
| 9 |
|
| 10 |
|
| 11 |
import numpy as np |
| 12 |
from ..backend import get_backend |
| 13 |
|
| 14 |
|
| 15 |
def dist_monge_max_min(i): |
| 16 |
r""" |
| 17 |
A tensor :math:c is Monge if for all valid :math:i_1, \ldots i_d and |
| 18 |
:math:j_1, \ldots, j_d, |
| 19 |
|
| 20 |
.. math:: |
| 21 |
c(s_1, \ldots, s_d) + c(t_1, \ldots t_d) \leq c(i_1, \ldots i_d) + |
| 22 |
c(j_1, \ldots, j_d) |
| 23 |
|
| 24 |
where :math:s_k = \min(i_k, j_k) and :math:t_k = \max(i_k, j_k). |
| 25 |
|
| 26 |
Our focus is on a specific cost, which is known to be Monge: |
| 27 |
|
| 28 |
.. math:: |
| 29 |
c(i_1,i_2,\ldots,i_d) = \max{i_k:k\in[d]} - \min{i_k:k\in[d]}. |
| 30 |
|
| 31 |
When :math:d=2, this cost reduces to :math:c(i_1,i_2)=|i_1-i_2|, |
| 32 |
which agrees with the classical EMD cost. This choice of :math:c is called |
| 33 |
the generalized EMD cost. |
| 34 |
|
| 35 |
Parameters |
| 36 |
---------- |
| 37 |
i : list |
| 38 |
The list of integer indexes. |
| 39 |
|
| 40 |
Returns |
| 41 |
------- |
| 42 |
cost : numeric value |
| 43 |
The ground cost (generalized EMD cost) of the tensor. |
| 44 |
|
| 45 |
References |
| 46 |
---------- |
| 47 |
.. [56] Jeffery Kline. Properties of the d-dimensional earth mover's |
| 48 |
problem. Discrete Applied Mathematics, 265: 128-141, 2019. |
| 49 |
.. [57] Wolfgang W. Bein, Peter Brucker, James K. Park, and Pramod K. |
| 50 |
Pathak. A monge property for the d-dimensional transportation problem. |
| 51 |
Discrete Applied Mathematics, 58(2):97-109, 1995. ISSN 0166-218X. doi: |
| 52 |
https://doi.org/10.1016/0166-218X(93)E0121-E. URL |
| 53 |
https://www.sciencedirect.com/ science/article/pii/0166218X93E0121E. |
| 54 |
Workshop on Discrete Algorithms. |
| 55 |
""" |
| 56 |
|
| 57 |
return max(i) - min(i) |
| 58 |
|
| 59 |
|
| 60 |
def dmmot_monge_1dgrid_loss(A, verbose=False, log=False): |
| 61 |
r""" |
| 62 |
Compute the discrete multi-marginal optimal transport of distributions A. |
| 63 |
|
| 64 |
This function operates on distributions whose supports are real numbers on |
| 65 |
the real line. |
| 66 |
|
| 67 |
The algorithm solves both primal and dual d-MMOT programs concurrently to |
| 68 |
produce the optimal transport plan as well as the total (minimal) cost. |
| 69 |
The cost is a ground cost, and the solution is independent of |
| 70 |
which Monge cost is desired. |
| 71 |
|
| 72 |
The algorithm accepts :math:`d` distributions (i.e., histograms) |
| 73 |
:math:`a_{1}, \ldots, a_{d} \in \mathbb{R}_{+}^{n}` with :math:`e^{\prime} |
| 74 |
a_{j}=1` for all :math:`j \in[d]`. Although the algorithm states that all |
| 75 |
histograms have the same number of bins, the algorithm can be easily |
| 76 |
adapted to accept as inputs :math:`a_{i} \in \mathbb{R}_{+}^{n_{i}}` |
| 77 |
with :math:`n_{i} \neq n_{j}` [50]. |
| 78 |
|
| 79 |
The function solves the following optimization problem[51]: |
| 80 |
|
| 81 |
.. math:: |
| 82 |
\begin{align}\begin{aligned} |
| 83 |
\underset{\gamma\in\mathbb{R}^{n^{d}}_{+}} {\textrm{min}} |
| 84 |
\sum_{i_1,\ldots,i_d} c(i_1,\ldots, i_d)\, \gamma(i_1,\ldots,i_d) |
| 85 |
\quad \textrm{s.t.} |
| 86 |
\sum_{i_2,\ldots,i_d} \gamma(i_1,\ldots,i_d) &= a_1(i_i), |
| 87 |
(\forall i_1\in[n])\\ |
| 88 |
\qquad\vdots\\ |
| 89 |
\sum_{i_1,\ldots,i_{d-1}} \gamma(i_1,\ldots,i_d) &= a_{d}(i_{d}), |
| 90 |
(\forall i_d\in[n]). |
| 91 |
\end{aligned} |
| 92 |
\end{align} |
| 93 |
|
| 94 |
|
| 95 |
Parameters |
| 96 |
---------- |
| 97 |
A : nx.ndarray, shape (dim, n_hists) |
| 98 |
The input ndarray containing distributions of n bins in d dimensions. |
| 99 |
verbose : bool, optional |
| 100 |
If True, print debugging information during execution. Default=False. |
| 101 |
log : bool, optional |
| 102 |
If True, record log. Default is False. |
| 103 |
|
| 104 |
Returns |
| 105 |
------- |
| 106 |
obj : float |
| 107 |
the value of the primal objective function evaluated at the solution. |
| 108 |
log : dict |
| 109 |
A dictionary containing the log of the discrete mmot problem: |
| 110 |
- 'A': a dictionary that maps tuples of indices to the corresponding |
| 111 |
primal variables. The tuples are the indices of the entries that are |
| 112 |
set to their minimum value during the algorithm. |
| 113 |
- 'primal objective': a float, the value of the objective function |
| 114 |
evaluated at the solution. |
| 115 |
- 'dual': a list of arrays, the dual variables corresponding to |
| 116 |
the input arrays. The i-th element of the list is the dual variable |
| 117 |
corresponding to the i-th dimension of the input arrays. |
| 118 |
- 'dual objective': a float, the value of the dual objective function |
| 119 |
evaluated at the solution. |
| 120 |
|
| 121 |
|
| 122 |
References |
| 123 |
---------- |
| 124 |
.. [55] Ronak Mehta, Jeffery Kline, Vishnu Suresh Lokhande, Glenn Fung, & |
| 125 |
Vikas Singh (2023). Efficient Discrete Multi Marginal Optimal |
| 126 |
Transport Regularization. In The Eleventh International |
| 127 |
Conference on Learning Representations. |
| 128 |
.. [56] Jeffery Kline. Properties of the d-dimensional earth mover's |
| 129 |
problem. Discrete Applied Mathematics, 265: 128-141, 2019. |
| 130 |
.. [58] Leonid V Kantorovich. On the translocation of masses. Dokl. Akad. |
| 131 |
Nauk SSSR, 37:227-229, 1942. |
| 132 |
|
| 133 |
See Also |
| 134 |
-------- |
| 135 |
ot.lp.dmmot_monge_1dgrid_optimize : Optimize the d-Dimensional Earth |
| 136 |
Mover's Distance (d-MMOT) |
| 137 |
""" |
| 138 |
|
| 139 |
nx = get_backend(A) |
| 140 |
A_copy = A |
| 141 |
A = nx.to_numpy(A) |
| 142 |
|
| 143 |
AA = [np.copy(A[:, j]) for j in range(A.shape[1])] |
| 144 |
|
| 145 |
dims = tuple([len(_) for _ in AA]) |
| 146 |
xx = {} |
| 147 |
dual = [np.zeros(d) for d in dims] |
| 148 |
|
| 149 |
idx = [ |
| 150 |
0, |
| 151 |
] * len(AA) |
| 152 |
obj = 0 |
| 153 |
|
| 154 |
if verbose: |
| 155 |
print("i minval oldidx\t\tobj\t\tvals") |
| 156 |
|
| 157 |
while all([i < _ for _, i in zip(dims, idx)]): |
| 158 |
vals = [v[i] for v, i in zip(AA, idx)] |
| 159 |
minval = min(vals) |
| 160 |
i = vals.index(minval) |
| 161 |
xx[tuple(idx)] = minval |
| 162 |
obj += (dist_monge_max_min(idx)) * minval |
| 163 |
for v, j in zip(AA, idx): |
| 164 |
v[j] -= minval |
| 165 |
|
| 166 |
oldidx = idx.copy() |
| 167 |
idx[i] += 1 |
| 168 |
if idx[i] < dims[i]: |
| 169 |
temp = ( |
| 170 |
dist_monge_max_min(idx) |
| 171 |
- dist_monge_max_min(oldidx) |
| 172 |
+ dual[i][idx[i] - 1] |
| 173 |
) |
| 174 |
dual[i][idx[i]] += temp |
| 175 |
if verbose: |
| 176 |
print(i, minval, oldidx, obj, "\t", vals) |
| 177 |
|
| 178 |
|
| 179 |
|
| 180 |
|
| 181 |
for _, i in enumerate(idx): |
| 182 |
try: |
| 183 |
dual[_][i:] = dual[_][i] |
| 184 |
except Exception: |
| 185 |
pass |
| 186 |
|
| 187 |
dualobj = sum([np.dot(A[:, i], arr) for i, arr in enumerate(dual)]) |
| 188 |
obj = nx.from_numpy(obj) |
| 189 |
|
| 190 |
log_dict = { |
| 191 |
"A": xx, |
| 192 |
"primal objective": obj, |
| 193 |
"dual": dual, |
| 194 |
"dual objective": dualobj, |
| 195 |
} |
| 196 |
|
| 197 |
|
| 198 |
obj = nx.set_gradients(obj, (A_copy), (dual)) |
| 199 |
|
| 200 |
if log: |
| 201 |
return obj, log_dict |
| 202 |
else: |
| 203 |
return obj |
| 204 |
|
| 205 |
|
| 206 |
def dmmot_monge_1dgrid_optimize( |
| 207 |
A, |
| 208 |
niters=100, |
| 209 |
lr_init=1e-5, |
| 210 |
lr_decay=0.995, |
| 211 |
print_rate=100, |
| 212 |
verbose=False, |
| 213 |
log=False, |
| 214 |
): |
| 215 |
r"""Minimize the d-dimensional EMD using gradient descent. |
| 216 |
|
| 217 |
Discrete Multi-Marginal Optimal Transport (d-MMOT): Let :math:`a_1, \ldots, |
| 218 |
a_d\in\mathbb{R}^n_{+}` be discrete probability distributions. Here, |
| 219 |
the d-MMOT is the LP, |
| 220 |
|
| 221 |
.. math:: |
| 222 |
\begin{align}\begin{aligned} |
| 223 |
\underset{x\in\mathbb{R}^{n^{d}}_{+}} {\textrm{min}} |
| 224 |
\sum_{i_1,\ldots,i_d} c(i_1,\ldots, i_d)\, x(i_1,\ldots,i_d) \quad |
| 225 |
\textrm{s.t.} |
| 226 |
\sum_{i_2,\ldots,i_d} x(i_1,\ldots,i_d) &= a_1(i_i), |
| 227 |
(\forall i_1\in[n])\\ |
| 228 |
\qquad\vdots\\ |
| 229 |
\sum_{i_1,\ldots,i_{d-1}} x(i_1,\ldots,i_d) &= a_{d}(i_{d}), |
| 230 |
(\forall i_d\in[n]). |
| 231 |
\end{aligned} |
| 232 |
\end{align} |
| 233 |
|
| 234 |
The dual linear program of the d-MMOT problem is: |
| 235 |
|
| 236 |
.. math:: |
| 237 |
\underset{z_j\in\mathbb{R}^n, j\in[d]}{\textrm{maximize}}\qquad\sum_{j} |
| 238 |
a_j'z_j\qquad \textrm{subject to}\qquad z_{1}(i_1)+\cdots+z_{d}(i_{d}) |
| 239 |
\leq c(i_1,\ldots,i_{d}), |
| 240 |
|
| 241 |
|
| 242 |
where the indices in the constraints include all :math:`i_j\in[n]`, :math: |
| 243 |
`j\in[d]`. Denote by :math:`\phi(a_1,\ldots,a_d)`, the optimal objective |
| 244 |
value of the LP in d-MMOT problem. Let :math:`z^*` be an optimal solution |
| 245 |
to the dual program. Then, |
| 246 |
|
| 247 |
.. math:: |
| 248 |
\begin{align} |
| 249 |
\nabla \phi(a_1,\ldots,a_{d}) &= z^*, |
| 250 |
~~\text{and for any $t\in \mathbb{R}$,}~~ |
| 251 |
\phi(a_1,a_2,\ldots,a_{d}) = \sum_{j}a_j' |
| 252 |
(z_j^* + t\, \eta), \nonumber \\ |
| 253 |
\text{where } \eta &:= (z_1^{*}(n)\,e, z^*_1(n)\,e, \cdots, |
| 254 |
z^*_{d}(n)\,e) |
| 255 |
\end{align} |
| 256 |
|
| 257 |
Using these dual variables naturally provided by the algorithm in |
| 258 |
ot.lp.dmmot_monge_1dgrid_loss, gradient steps move each input distribution |
| 259 |
to minimize their d-mmot distance. |
| 260 |
|
| 261 |
Parameters |
| 262 |
---------- |
| 263 |
A : nx.ndarray, shape (dim, n_hists) |
| 264 |
The input ndarray containing distributions of n bins in d dimensions. |
| 265 |
niters : int, optional (default=100) |
| 266 |
The maximum number of iterations for the optimization algorithm. |
| 267 |
lr_init : float, optional (default=1e-5) |
| 268 |
The initial learning rate (step size) for the optimization algorithm. |
| 269 |
lr_decay : float, optional (default=0.995) |
| 270 |
The learning rate decay rate in each iteration. |
| 271 |
print_rate : int, optional (default=100) |
| 272 |
The rate at which to print the objective value and gradient norm |
| 273 |
during the optimization algorithm. |
| 274 |
verbose : bool, optional |
| 275 |
If True, print debugging information during execution. Default=False. |
| 276 |
log : bool, optional |
| 277 |
If True, record log. Default is False. |
| 278 |
|
| 279 |
Returns |
| 280 |
------- |
| 281 |
a : list of ndarrays, each of shape (n,) |
| 282 |
The optimal solution as a list of n approximate barycenters, each of |
| 283 |
length vecsize. |
| 284 |
log : dict |
| 285 |
log dictionary return only if log==True in parameters |
| 286 |
|
| 287 |
References |
| 288 |
---------- |
| 289 |
.. [55] Ronak Mehta, Jeffery Kline, Vishnu Suresh Lokhande, Glenn Fung, & |
| 290 |
Vikas Singh (2023). Efficient Discrete Multi Marginal Optimal |
| 291 |
Transport Regularization. In The Eleventh International |
| 292 |
Conference on Learning Representations. |
| 293 |
.. [60] Olvi L Mangasarian and RR Meyer. Nonlinear perturbation of linear |
| 294 |
programs. SIAM Journal on Control and Optimization, 17(6):745-752, 1979 |
| 295 |
.. [59] Michael C Ferris and Olvi L Mangasarian. Finite perturbation of |
| 296 |
convex programs. Applied Mathematics and Optimization, 23(1):263-273, |
| 297 |
1991. |
| 298 |
|
| 299 |
See Also |
| 300 |
-------- |
| 301 |
ot.lp.dmmot_monge_1dgrid_loss: d-Dimensional Earth Mover's Solver |
| 302 |
""" |
| 303 |
|
| 304 |
|
| 305 |
nx = get_backend(A) |
| 306 |
A = nx.to_numpy(A) |
| 307 |
n, d = A.shape |
| 308 |
|
| 309 |
def dualIter(A, lr): |
| 310 |
funcval, log_dict = dmmot_monge_1dgrid_loss(A, verbose=verbose, log=True) |
| 311 |
grad = np.column_stack(log_dict["dual"]) |
| 312 |
A_new = np.reshape(A, (n, d)) - grad * lr |
| 313 |
return funcval, A_new, grad, log_dict |
| 314 |
|
| 315 |
def renormalize(A): |
| 316 |
A = np.reshape(A, (n, d)) |
| 317 |
for i in range(A.shape[1]): |
| 318 |
if min(A[:, i]) < 0: |
| 319 |
A[:, i] -= min(A[:, i]) |
| 320 |
A[:, i] /= np.sum(A[:, i]) |
| 321 |
return A |
| 322 |
|
| 323 |
def listify(A): |
| 324 |
return [A[:, i] for i in range(A.shape[1])] |
| 325 |
|
| 326 |
lr = lr_init |
| 327 |
|
| 328 |
funcval, _, grad, log_dict = dualIter(A, lr) |
| 329 |
gn = np.linalg.norm(grad) |
| 330 |
|
| 331 |
print(f"Initial:\t\tObj:\t{funcval:.4f}\tGradNorm:\t{gn:.4f}") |
| 332 |
|
| 333 |
for i in range(niters): |
| 334 |
A = renormalize(A) |
| 335 |
funcval, A, grad, log_dict = dualIter(A, lr) |
| 336 |
gn = np.linalg.norm(grad) |
| 337 |
|
| 338 |
if i % print_rate == 0: |
| 339 |
print(f"Iter {i:2.0f}:\tObj:\t{funcval:.4f}\tGradNorm:\t{gn:.4f}") |
| 340 |
|
| 341 |
lr *= lr_decay |
| 342 |
|
| 343 |
A = renormalize(A) |
| 344 |
a = listify(A) |
| 345 |
|
| 346 |
if log: |
| 347 |
return a, log_dict |
| 348 |
else: |
| 349 |
return a |