| 1 |
# -*- coding: utf-8 -*- |
| 2 |
""" |
| 3 |
Cython linker with C solver |
| 4 |
""" |
| 5 |
|
| 6 |
# Author: Remi Flamary <[email protected]> |
| 7 |
# |
| 8 |
# License: MIT License |
| 9 |
|
| 10 |
import numpy as np |
| 11 |
cimport numpy as np |
| 12 |
|
| 13 |
from ..utils import dist |
| 14 |
|
| 15 |
cimport cython |
| 16 |
cimport libc.math as math |
| 17 |
from libc.stdint cimport uint64_t |
| 18 |
|
| 19 |
import warnings |
| 20 |
|
| 21 |
|
| 22 |
cdef extern from "EMD.h": |
| 23 |
int EMD_wrap(int n1,int n2, double *X, double *Y,double *D, double *G, double* alpha, double* beta, double *cost, uint64_t maxIter) nogil |
| 24 |
int EMD_wrap_omp(int n1,int n2, double *X, double *Y,double *D, double *G, double* alpha, double* beta, double *cost, uint64_t maxIter, int numThreads) nogil |
| 25 |
cdef enum ProblemType: INFEASIBLE, OPTIMAL, UNBOUNDED, MAX_ITER_REACHED |
| 26 |
|
| 27 |
|
| 28 |
def check_result(result_code): |
| 29 |
if result_code == OPTIMAL: |
| 30 |
return None |
| 31 |
|
| 32 |
if result_code == INFEASIBLE: |
| 33 |
message = "Problem infeasible. Check that a and b are in the simplex" |
| 34 |
elif result_code == UNBOUNDED: |
| 35 |
message = "Problem unbounded" |
| 36 |
elif result_code == MAX_ITER_REACHED: |
| 37 |
message = "numItermax reached before optimality. Try to increase numItermax." |
| 38 |
warnings.warn(message) |
| 39 |
return message |
| 40 |
|
| 41 |
@cython.boundscheck(False) |
| 42 |
@cython.wraparound(False) |
| 43 |
def emd_c(np.ndarray[double, ndim=1, mode="c"] a, np.ndarray[double, ndim=1, mode="c"] b, np.ndarray[double, ndim=2, mode="c"] M, uint64_t max_iter, int numThreads): |
| 44 |
""" |
| 45 |
Solves the Earth Movers distance problem and returns the optimal transport matrix |
| 46 |
|
| 47 |
gamm=emd(a,b,M) |
| 48 |
|
| 49 |
.. math:: |
| 50 |
\gamma = arg\min_\gamma <\gamma,M>_F |
| 51 |
|
| 52 |
s.t. \gamma 1 = a |
| 53 |
|
| 54 |
\gamma^T 1= b |
| 55 |
|
| 56 |
\gamma\geq 0 |
| 57 |
where : |
| 58 |
|
| 59 |
- M is the metric cost matrix |
| 60 |
- a and b are the sample weights |
| 61 |
|
| 62 |
.. warning:: |
| 63 |
Note that the M matrix needs to be a C-order :py.cls:`numpy.array` |
| 64 |
|
| 65 |
.. warning:: |
| 66 |
The C++ solver discards all samples in the distributions with |
| 67 |
zeros weights. This means that while the primal variable (transport |
| 68 |
matrix) is exact, the solver only returns feasible dual potentials |
| 69 |
on the samples with weights different from zero. |
| 70 |
|
| 71 |
Parameters |
| 72 |
---------- |
| 73 |
a : (ns,) numpy.ndarray, float64 |
| 74 |
source histogram |
| 75 |
b : (nt,) numpy.ndarray, float64 |
| 76 |
target histogram |
| 77 |
M : (ns,nt) numpy.ndarray, float64 |
| 78 |
loss matrix |
| 79 |
max_iter : uint64_t |
| 80 |
The maximum number of iterations before stopping the optimization |
| 81 |
algorithm if it has not converged. |
| 82 |
|
| 83 |
Returns |
| 84 |
------- |
| 85 |
gamma: (ns x nt) numpy.ndarray |
| 86 |
Optimal transportation matrix for the given parameters |
| 87 |
|
| 88 |
""" |
| 89 |
cdef int n1= M.shape[0] |
| 90 |
cdef int n2= M.shape[1] |
| 91 |
cdef int nmax=n1+n2-1 |
| 92 |
cdef int result_code = 0 |
| 93 |
cdef int nG=0 |
| 94 |
|
| 95 |
cdef double cost=0 |
| 96 |
cdef np.ndarray[double, ndim=1, mode="c"] alpha=np.zeros(n1) |
| 97 |
cdef np.ndarray[double, ndim=1, mode="c"] beta=np.zeros(n2) |
| 98 |
|
| 99 |
cdef np.ndarray[double, ndim=2, mode="c"] G=np.zeros([0, 0]) |
| 100 |
|
| 101 |
cdef np.ndarray[double, ndim=1, mode="c"] Gv=np.zeros(0) |
| 102 |
|
| 103 |
if not len(a): |
| 104 |
a=np.ones((n1,))/n1 |
| 105 |
|
| 106 |
if not len(b): |
| 107 |
b=np.ones((n2,))/n2 |
| 108 |
|
| 109 |
# init OT matrix |
| 110 |
G=np.zeros([n1, n2]) |
| 111 |
|
| 112 |
# calling the function |
| 113 |
with nogil: |
| 114 |
if numThreads == 1: |
| 115 |
result_code = EMD_wrap(n1, n2, <double*> a.data, <double*> b.data, <double*> M.data, <double*> G.data, <double*> alpha.data, <double*> beta.data, <double*> &cost, max_iter) |
| 116 |
else: |
| 117 |
result_code = EMD_wrap_omp(n1, n2, <double*> a.data, <double*> b.data, <double*> M.data, <double*> G.data, <double*> alpha.data, <double*> beta.data, <double*> &cost, max_iter, numThreads) |
| 118 |
return G, cost, alpha, beta, result_code |
| 119 |
|
| 120 |
|
| 121 |
@cython.boundscheck(False) |
| 122 |
@cython.wraparound(False) |
| 123 |
def emd_1d_sorted(np.ndarray[double, ndim=1, mode="c"] u_weights, |
| 124 |
np.ndarray[double, ndim=1, mode="c"] v_weights, |
| 125 |
np.ndarray[double, ndim=1, mode="c"] u, |
| 126 |
np.ndarray[double, ndim=1, mode="c"] v, |
| 127 |
str metric='sqeuclidean', |
| 128 |
double p=1.): |
| 129 |
r""" |
| 130 |
Solves the Earth Movers distance problem between sorted 1d measures and |
| 131 |
returns the OT matrix and the associated cost |
| 132 |
|
| 133 |
Parameters |
| 134 |
---------- |
| 135 |
u_weights : (ns,) ndarray, float64 |
| 136 |
Source histogram |
| 137 |
v_weights : (nt,) ndarray, float64 |
| 138 |
Target histogram |
| 139 |
u : (ns,) ndarray, float64 |
| 140 |
Source dirac locations (on the real line) |
| 141 |
v : (nt,) ndarray, float64 |
| 142 |
Target dirac locations (on the real line) |
| 143 |
metric: str, optional (default='sqeuclidean') |
| 144 |
Metric to be used. Only works with either of the strings |
| 145 |
`'sqeuclidean'`, `'minkowski'`, `'cityblock'`, or `'euclidean'`. |
| 146 |
p: float, optional (default=1.0) |
| 147 |
The p-norm to apply for if metric='minkowski' |
| 148 |
|
| 149 |
Returns |
| 150 |
------- |
| 151 |
gamma: (n, ) ndarray, float64 |
| 152 |
Values in the Optimal transportation matrix |
| 153 |
indices: (n, 2) ndarray, int64 |
| 154 |
Indices of the values stored in gamma for the Optimal transportation |
| 155 |
matrix |
| 156 |
cost |
| 157 |
cost associated to the optimal transportation |
| 158 |
""" |
| 159 |
cdef double cost = 0. |
| 160 |
cdef Py_ssize_t n = u_weights.shape[0] |
| 161 |
cdef Py_ssize_t m = v_weights.shape[0] |
| 162 |
|
| 163 |
cdef Py_ssize_t i = 0 |
| 164 |
cdef double w_i = u_weights[0] |
| 165 |
cdef Py_ssize_t j = 0 |
| 166 |
cdef double w_j = v_weights[0] |
| 167 |
|
| 168 |
cdef double m_ij = 0. |
| 169 |
|
| 170 |
cdef np.ndarray[double, ndim=1, mode="c"] G = np.zeros((n + m - 1, ), |
| 171 |
dtype=np.float64) |
| 172 |
cdef np.ndarray[long long, ndim=2, mode="c"] indices = np.zeros((n + m - 1, 2), |
| 173 |
dtype=np.int64) |
| 174 |
cdef Py_ssize_t cur_idx = 0 |
| 175 |
while True: |
| 176 |
if metric == 'sqeuclidean': |
| 177 |
m_ij = (u[i] - v[j]) * (u[i] - v[j]) |
| 178 |
elif metric == 'cityblock' or metric == 'euclidean': |
| 179 |
m_ij = math.fabs(u[i] - v[j]) |
| 180 |
elif metric == 'minkowski': |
| 181 |
m_ij = math.pow(math.fabs(u[i] - v[j]), p) |
| 182 |
else: |
| 183 |
raise ValueError("Solver for EMD in 1d only supports metrics " + |
| 184 |
"from the following list: " + |
| 185 |
"`['sqeuclidean', 'minkowski', 'cityblock', 'euclidean']`") |
| 186 |
if w_i < w_j or j == m - 1: |
| 187 |
cost += m_ij * w_i |
| 188 |
G[cur_idx] = w_i |
| 189 |
indices[cur_idx, 0] = i |
| 190 |
indices[cur_idx, 1] = j |
| 191 |
i += 1 |
| 192 |
if i == n: |
| 193 |
break |
| 194 |
w_j -= w_i |
| 195 |
w_i = u_weights[i] |
| 196 |
else: |
| 197 |
cost += m_ij * w_j |
| 198 |
G[cur_idx] = w_j |
| 199 |
indices[cur_idx, 0] = i |
| 200 |
indices[cur_idx, 1] = j |
| 201 |
j += 1 |
| 202 |
if j == m: |
| 203 |
break |
| 204 |
w_i -= w_j |
| 205 |
w_j = v_weights[j] |
| 206 |
cur_idx += 1 |
| 207 |
cur_idx += 1 |
| 208 |
return G[:cur_idx], indices[:cur_idx], cost |