id
int32
0
252k
repo
stringlengths
7
55
path
stringlengths
4
127
func_name
stringlengths
1
88
original_string
stringlengths
75
19.8k
language
stringclasses
1 value
code
stringlengths
51
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
240,900
rflamary/POT
ot/plot.py
plot1D_mat
def plot1D_mat(a, b, M, title=''): """ Plot matrix M with the source and target 1D distribution Creates a subplot with the source distribution a on the left and target distribution b on the tot. The matrix M is shown in between. Parameters ---------- a : np.array, shape (na,) Source distribution b : np.array, shape (nb,) Target distribution M : np.array, shape (na,nb) Matrix to plot """ na, nb = M.shape gs = gridspec.GridSpec(3, 3) xa = np.arange(na) xb = np.arange(nb) ax1 = pl.subplot(gs[0, 1:]) pl.plot(xb, b, 'r', label='Target distribution') pl.yticks(()) pl.title(title) ax2 = pl.subplot(gs[1:, 0]) pl.plot(a, xa, 'b', label='Source distribution') pl.gca().invert_xaxis() pl.gca().invert_yaxis() pl.xticks(()) pl.subplot(gs[1:, 1:], sharex=ax1, sharey=ax2) pl.imshow(M, interpolation='nearest') pl.axis('off') pl.xlim((0, nb)) pl.tight_layout() pl.subplots_adjust(wspace=0., hspace=0.2)
python
def plot1D_mat(a, b, M, title=''): na, nb = M.shape gs = gridspec.GridSpec(3, 3) xa = np.arange(na) xb = np.arange(nb) ax1 = pl.subplot(gs[0, 1:]) pl.plot(xb, b, 'r', label='Target distribution') pl.yticks(()) pl.title(title) ax2 = pl.subplot(gs[1:, 0]) pl.plot(a, xa, 'b', label='Source distribution') pl.gca().invert_xaxis() pl.gca().invert_yaxis() pl.xticks(()) pl.subplot(gs[1:, 1:], sharex=ax1, sharey=ax2) pl.imshow(M, interpolation='nearest') pl.axis('off') pl.xlim((0, nb)) pl.tight_layout() pl.subplots_adjust(wspace=0., hspace=0.2)
[ "def", "plot1D_mat", "(", "a", ",", "b", ",", "M", ",", "title", "=", "''", ")", ":", "na", ",", "nb", "=", "M", ".", "shape", "gs", "=", "gridspec", ".", "GridSpec", "(", "3", ",", "3", ")", "xa", "=", "np", ".", "arange", "(", "na", ")", ...
Plot matrix M with the source and target 1D distribution Creates a subplot with the source distribution a on the left and target distribution b on the tot. The matrix M is shown in between. Parameters ---------- a : np.array, shape (na,) Source distribution b : np.array, shape (nb,) Target distribution M : np.array, shape (na,nb) Matrix to plot
[ "Plot", "matrix", "M", "with", "the", "source", "and", "target", "1D", "distribution" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/plot.py#L14-L54
240,901
rflamary/POT
ot/plot.py
plot2D_samples_mat
def plot2D_samples_mat(xs, xt, G, thr=1e-8, **kwargs): """ Plot matrix M in 2D with lines using alpha values Plot lines between source and target 2D samples with a color proportional to the value of the matrix G between samples. Parameters ---------- xs : ndarray, shape (ns,2) Source samples positions b : ndarray, shape (nt,2) Target samples positions G : ndarray, shape (na,nb) OT matrix thr : float, optional threshold above which the line is drawn **kwargs : dict paameters given to the plot functions (default color is black if nothing given) """ if ('color' not in kwargs) and ('c' not in kwargs): kwargs['color'] = 'k' mx = G.max() for i in range(xs.shape[0]): for j in range(xt.shape[0]): if G[i, j] / mx > thr: pl.plot([xs[i, 0], xt[j, 0]], [xs[i, 1], xt[j, 1]], alpha=G[i, j] / mx, **kwargs)
python
def plot2D_samples_mat(xs, xt, G, thr=1e-8, **kwargs): if ('color' not in kwargs) and ('c' not in kwargs): kwargs['color'] = 'k' mx = G.max() for i in range(xs.shape[0]): for j in range(xt.shape[0]): if G[i, j] / mx > thr: pl.plot([xs[i, 0], xt[j, 0]], [xs[i, 1], xt[j, 1]], alpha=G[i, j] / mx, **kwargs)
[ "def", "plot2D_samples_mat", "(", "xs", ",", "xt", ",", "G", ",", "thr", "=", "1e-8", ",", "*", "*", "kwargs", ")", ":", "if", "(", "'color'", "not", "in", "kwargs", ")", "and", "(", "'c'", "not", "in", "kwargs", ")", ":", "kwargs", "[", "'color'...
Plot matrix M in 2D with lines using alpha values Plot lines between source and target 2D samples with a color proportional to the value of the matrix G between samples. Parameters ---------- xs : ndarray, shape (ns,2) Source samples positions b : ndarray, shape (nt,2) Target samples positions G : ndarray, shape (na,nb) OT matrix thr : float, optional threshold above which the line is drawn **kwargs : dict paameters given to the plot functions (default color is black if nothing given)
[ "Plot", "matrix", "M", "in", "2D", "with", "lines", "using", "alpha", "values" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/plot.py#L57-L85
240,902
rflamary/POT
ot/gpu/da.py
sinkhorn_lpl1_mm
def sinkhorn_lpl1_mm(a, labels_a, b, M, reg, eta=0.1, numItermax=10, numInnerItermax=200, stopInnerThr=1e-9, verbose=False, log=False, to_numpy=True): """ Solve the entropic regularization optimal transport problem with nonconvex group lasso regularization on GPU If the input matrix are in numpy format, they will be uploaded to the GPU first which can incur significant time overhead. The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega_e(\gamma) + \eta \Omega_g(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - M is the (ns,nt) metric cost matrix - :math:`\Omega_e` is the entropic regularization term :math:`\Omega_e(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - :math:`\Omega_g` is the group lasso regulaization term :math:`\Omega_g(\gamma)=\sum_{i,c} \|\gamma_{i,\mathcal{I}_c}\|^{1/2}_1` where :math:`\mathcal{I}_c` are the index of samples from class c in the source domain. - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is the generalised conditional gradient as proposed in [5]_ [7]_ Parameters ---------- a : np.ndarray (ns,) samples weights in the source domain labels_a : np.ndarray (ns,) labels of samples in the source domain b : np.ndarray (nt,) samples weights in the target domain M : np.ndarray (ns,nt) loss matrix reg : float Regularization term for entropic regularization >0 eta : float, optional Regularization term for group lasso regularization >0 numItermax : int, optional Max number of iterations numInnerItermax : int, optional Max number of iterations (inner sinkhorn solver) stopInnerThr : float, optional Stop threshold on error (inner sinkhorn solver) (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True to_numpy : boolean, optional (default True) If true convert back the GPU array result to numpy format. Returns ------- gamma : (ns x nt) ndarray Optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters References ---------- .. [5] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy, "Optimal Transport for Domain Adaptation," in IEEE Transactions on Pattern Analysis and Machine Intelligence , vol.PP, no.99, pp.1-1 .. [7] Rakotomamonjy, A., Flamary, R., & Courty, N. (2015). Generalized conditional gradient: analysis of convergence and applications. arXiv preprint arXiv:1510.06567. See Also -------- ot.lp.emd : Unregularized OT ot.bregman.sinkhorn : Entropic regularized OT ot.optim.cg : General regularized OT """ a, labels_a, b, M = utils.to_gpu(a, labels_a, b, M) p = 0.5 epsilon = 1e-3 indices_labels = [] labels_a2 = cp.asnumpy(labels_a) classes = npp.unique(labels_a2) for c in classes: idxc, = utils.to_gpu(npp.where(labels_a2 == c)) indices_labels.append(idxc) W = np.zeros(M.shape) for cpt in range(numItermax): Mreg = M + eta * W transp = sinkhorn(a, b, Mreg, reg, numItermax=numInnerItermax, stopThr=stopInnerThr, to_numpy=False) # the transport has been computed. Check if classes are really # separated W = np.ones(M.shape) for (i, c) in enumerate(classes): majs = np.sum(transp[indices_labels[i]], axis=0) majs = p * ((majs + epsilon)**(p - 1)) W[indices_labels[i]] = majs if to_numpy: return utils.to_np(transp) else: return transp
python
def sinkhorn_lpl1_mm(a, labels_a, b, M, reg, eta=0.1, numItermax=10, numInnerItermax=200, stopInnerThr=1e-9, verbose=False, log=False, to_numpy=True): a, labels_a, b, M = utils.to_gpu(a, labels_a, b, M) p = 0.5 epsilon = 1e-3 indices_labels = [] labels_a2 = cp.asnumpy(labels_a) classes = npp.unique(labels_a2) for c in classes: idxc, = utils.to_gpu(npp.where(labels_a2 == c)) indices_labels.append(idxc) W = np.zeros(M.shape) for cpt in range(numItermax): Mreg = M + eta * W transp = sinkhorn(a, b, Mreg, reg, numItermax=numInnerItermax, stopThr=stopInnerThr, to_numpy=False) # the transport has been computed. Check if classes are really # separated W = np.ones(M.shape) for (i, c) in enumerate(classes): majs = np.sum(transp[indices_labels[i]], axis=0) majs = p * ((majs + epsilon)**(p - 1)) W[indices_labels[i]] = majs if to_numpy: return utils.to_np(transp) else: return transp
[ "def", "sinkhorn_lpl1_mm", "(", "a", ",", "labels_a", ",", "b", ",", "M", ",", "reg", ",", "eta", "=", "0.1", ",", "numItermax", "=", "10", ",", "numInnerItermax", "=", "200", ",", "stopInnerThr", "=", "1e-9", ",", "verbose", "=", "False", ",", "log"...
Solve the entropic regularization optimal transport problem with nonconvex group lasso regularization on GPU If the input matrix are in numpy format, they will be uploaded to the GPU first which can incur significant time overhead. The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega_e(\gamma) + \eta \Omega_g(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - M is the (ns,nt) metric cost matrix - :math:`\Omega_e` is the entropic regularization term :math:`\Omega_e(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - :math:`\Omega_g` is the group lasso regulaization term :math:`\Omega_g(\gamma)=\sum_{i,c} \|\gamma_{i,\mathcal{I}_c}\|^{1/2}_1` where :math:`\mathcal{I}_c` are the index of samples from class c in the source domain. - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is the generalised conditional gradient as proposed in [5]_ [7]_ Parameters ---------- a : np.ndarray (ns,) samples weights in the source domain labels_a : np.ndarray (ns,) labels of samples in the source domain b : np.ndarray (nt,) samples weights in the target domain M : np.ndarray (ns,nt) loss matrix reg : float Regularization term for entropic regularization >0 eta : float, optional Regularization term for group lasso regularization >0 numItermax : int, optional Max number of iterations numInnerItermax : int, optional Max number of iterations (inner sinkhorn solver) stopInnerThr : float, optional Stop threshold on error (inner sinkhorn solver) (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True to_numpy : boolean, optional (default True) If true convert back the GPU array result to numpy format. Returns ------- gamma : (ns x nt) ndarray Optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters References ---------- .. [5] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy, "Optimal Transport for Domain Adaptation," in IEEE Transactions on Pattern Analysis and Machine Intelligence , vol.PP, no.99, pp.1-1 .. [7] Rakotomamonjy, A., Flamary, R., & Courty, N. (2015). Generalized conditional gradient: analysis of convergence and applications. arXiv preprint arXiv:1510.06567. See Also -------- ot.lp.emd : Unregularized OT ot.bregman.sinkhorn : Entropic regularized OT ot.optim.cg : General regularized OT
[ "Solve", "the", "entropic", "regularization", "optimal", "transport", "problem", "with", "nonconvex", "group", "lasso", "regularization", "on", "GPU" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/gpu/da.py#L22-L144
240,903
rflamary/POT
ot/datasets.py
get_2D_samples_gauss
def get_2D_samples_gauss(n, m, sigma, random_state=None): """ Deprecated see make_2D_samples_gauss """ return make_2D_samples_gauss(n, m, sigma, random_state=None)
python
def get_2D_samples_gauss(n, m, sigma, random_state=None): return make_2D_samples_gauss(n, m, sigma, random_state=None)
[ "def", "get_2D_samples_gauss", "(", "n", ",", "m", ",", "sigma", ",", "random_state", "=", "None", ")", ":", "return", "make_2D_samples_gauss", "(", "n", ",", "m", ",", "sigma", ",", "random_state", "=", "None", ")" ]
Deprecated see make_2D_samples_gauss
[ "Deprecated", "see", "make_2D_samples_gauss" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/datasets.py#L83-L85
240,904
rflamary/POT
ot/datasets.py
get_data_classif
def get_data_classif(dataset, n, nz=.5, theta=0, random_state=None, **kwargs): """ Deprecated see make_data_classif """ return make_data_classif(dataset, n, nz=.5, theta=0, random_state=None, **kwargs)
python
def get_data_classif(dataset, n, nz=.5, theta=0, random_state=None, **kwargs): return make_data_classif(dataset, n, nz=.5, theta=0, random_state=None, **kwargs)
[ "def", "get_data_classif", "(", "dataset", ",", "n", ",", "nz", "=", ".5", ",", "theta", "=", "0", ",", "random_state", "=", "None", ",", "*", "*", "kwargs", ")", ":", "return", "make_data_classif", "(", "dataset", ",", "n", ",", "nz", "=", ".5", "...
Deprecated see make_data_classif
[ "Deprecated", "see", "make_data_classif" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/datasets.py#L170-L172
240,905
rflamary/POT
ot/bregman.py
sinkhorn
def sinkhorn(a, b, M, reg, method='sinkhorn', numItermax=1000, stopThr=1e-9, verbose=False, log=False, **kwargs): u""" Solve the entropic regularization optimal transport problem and return the OT matrix The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [2]_ Parameters ---------- a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) or np.ndarray (nt,nbb) samples in the target domain, compute sinkhorn with multiple targets and fixed M if b is a matrix (return OT loss + dual variables in log) M : np.ndarray (ns,nt) loss matrix reg : float Regularization term >0 method : str method used for the solver either 'sinkhorn', 'greenkhorn', 'sinkhorn_stabilized' or 'sinkhorn_epsilon_scaling', see those function for specific parameters numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters Examples -------- >>> import ot >>> a=[.5,.5] >>> b=[.5,.5] >>> M=[[0.,1.],[1.,0.]] >>> ot.sinkhorn(a,b,M,1) array([[ 0.36552929, 0.13447071], [ 0.13447071, 0.36552929]]) References ---------- .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013 .. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519. .. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816. See Also -------- ot.lp.emd : Unregularized OT ot.optim.cg : General regularized OT ot.bregman.sinkhorn_knopp : Classic Sinkhorn [2] ot.bregman.sinkhorn_stabilized: Stabilized sinkhorn [9][10] ot.bregman.sinkhorn_epsilon_scaling: Sinkhorn with epslilon scaling [9][10] """ if method.lower() == 'sinkhorn': def sink(): return sinkhorn_knopp(a, b, M, reg, numItermax=numItermax, stopThr=stopThr, verbose=verbose, log=log, **kwargs) elif method.lower() == 'greenkhorn': def sink(): return greenkhorn(a, b, M, reg, numItermax=numItermax, stopThr=stopThr, verbose=verbose, log=log) elif method.lower() == 'sinkhorn_stabilized': def sink(): return sinkhorn_stabilized(a, b, M, reg, numItermax=numItermax, stopThr=stopThr, verbose=verbose, log=log, **kwargs) elif method.lower() == 'sinkhorn_epsilon_scaling': def sink(): return sinkhorn_epsilon_scaling( a, b, M, reg, numItermax=numItermax, stopThr=stopThr, verbose=verbose, log=log, **kwargs) else: print('Warning : unknown method using classic Sinkhorn Knopp') def sink(): return sinkhorn_knopp(a, b, M, reg, numItermax=numItermax, stopThr=stopThr, verbose=verbose, log=log, **kwargs) return sink()
python
def sinkhorn(a, b, M, reg, method='sinkhorn', numItermax=1000, stopThr=1e-9, verbose=False, log=False, **kwargs): u""" Solve the entropic regularization optimal transport problem and return the OT matrix The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [2]_ Parameters ---------- a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) or np.ndarray (nt,nbb) samples in the target domain, compute sinkhorn with multiple targets and fixed M if b is a matrix (return OT loss + dual variables in log) M : np.ndarray (ns,nt) loss matrix reg : float Regularization term >0 method : str method used for the solver either 'sinkhorn', 'greenkhorn', 'sinkhorn_stabilized' or 'sinkhorn_epsilon_scaling', see those function for specific parameters numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters Examples -------- >>> import ot >>> a=[.5,.5] >>> b=[.5,.5] >>> M=[[0.,1.],[1.,0.]] >>> ot.sinkhorn(a,b,M,1) array([[ 0.36552929, 0.13447071], [ 0.13447071, 0.36552929]]) References ---------- .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013 .. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519. .. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816. See Also -------- ot.lp.emd : Unregularized OT ot.optim.cg : General regularized OT ot.bregman.sinkhorn_knopp : Classic Sinkhorn [2] ot.bregman.sinkhorn_stabilized: Stabilized sinkhorn [9][10] ot.bregman.sinkhorn_epsilon_scaling: Sinkhorn with epslilon scaling [9][10] """ if method.lower() == 'sinkhorn': def sink(): return sinkhorn_knopp(a, b, M, reg, numItermax=numItermax, stopThr=stopThr, verbose=verbose, log=log, **kwargs) elif method.lower() == 'greenkhorn': def sink(): return greenkhorn(a, b, M, reg, numItermax=numItermax, stopThr=stopThr, verbose=verbose, log=log) elif method.lower() == 'sinkhorn_stabilized': def sink(): return sinkhorn_stabilized(a, b, M, reg, numItermax=numItermax, stopThr=stopThr, verbose=verbose, log=log, **kwargs) elif method.lower() == 'sinkhorn_epsilon_scaling': def sink(): return sinkhorn_epsilon_scaling( a, b, M, reg, numItermax=numItermax, stopThr=stopThr, verbose=verbose, log=log, **kwargs) else: print('Warning : unknown method using classic Sinkhorn Knopp') def sink(): return sinkhorn_knopp(a, b, M, reg, numItermax=numItermax, stopThr=stopThr, verbose=verbose, log=log, **kwargs) return sink()
[ "def", "sinkhorn", "(", "a", ",", "b", ",", "M", ",", "reg", ",", "method", "=", "'sinkhorn'", ",", "numItermax", "=", "1000", ",", "stopThr", "=", "1e-9", ",", "verbose", "=", "False", ",", "log", "=", "False", ",", "*", "*", "kwargs", ")", ":",...
u""" Solve the entropic regularization optimal transport problem and return the OT matrix The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [2]_ Parameters ---------- a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) or np.ndarray (nt,nbb) samples in the target domain, compute sinkhorn with multiple targets and fixed M if b is a matrix (return OT loss + dual variables in log) M : np.ndarray (ns,nt) loss matrix reg : float Regularization term >0 method : str method used for the solver either 'sinkhorn', 'greenkhorn', 'sinkhorn_stabilized' or 'sinkhorn_epsilon_scaling', see those function for specific parameters numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters Examples -------- >>> import ot >>> a=[.5,.5] >>> b=[.5,.5] >>> M=[[0.,1.],[1.,0.]] >>> ot.sinkhorn(a,b,M,1) array([[ 0.36552929, 0.13447071], [ 0.13447071, 0.36552929]]) References ---------- .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013 .. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519. .. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816. See Also -------- ot.lp.emd : Unregularized OT ot.optim.cg : General regularized OT ot.bregman.sinkhorn_knopp : Classic Sinkhorn [2] ot.bregman.sinkhorn_stabilized: Stabilized sinkhorn [9][10] ot.bregman.sinkhorn_epsilon_scaling: Sinkhorn with epslilon scaling [9][10]
[ "u", "Solve", "the", "entropic", "regularization", "optimal", "transport", "problem", "and", "return", "the", "OT", "matrix" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L16-L128
240,906
rflamary/POT
ot/bregman.py
sinkhorn2
def sinkhorn2(a, b, M, reg, method='sinkhorn', numItermax=1000, stopThr=1e-9, verbose=False, log=False, **kwargs): u""" Solve the entropic regularization optimal transport problem and return the loss The function solves the following optimization problem: .. math:: W = \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [2]_ Parameters ---------- a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) or np.ndarray (nt,nbb) samples in the target domain, compute sinkhorn with multiple targets and fixed M if b is a matrix (return OT loss + dual variables in log) M : np.ndarray (ns,nt) loss matrix reg : float Regularization term >0 method : str method used for the solver either 'sinkhorn', 'sinkhorn_stabilized' or 'sinkhorn_epsilon_scaling', see those function for specific parameters numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- W : (nt) ndarray or float Optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters Examples -------- >>> import ot >>> a=[.5,.5] >>> b=[.5,.5] >>> M=[[0.,1.],[1.,0.]] >>> ot.sinkhorn2(a,b,M,1) array([ 0.26894142]) References ---------- .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013 .. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519. .. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816. [21] Altschuler J., Weed J., Rigollet P. : Near-linear time approximation algorithms for optimal transport via Sinkhorn iteration, Advances in Neural Information Processing Systems (NIPS) 31, 2017 See Also -------- ot.lp.emd : Unregularized OT ot.optim.cg : General regularized OT ot.bregman.sinkhorn_knopp : Classic Sinkhorn [2] ot.bregman.greenkhorn : Greenkhorn [21] ot.bregman.sinkhorn_stabilized: Stabilized sinkhorn [9][10] ot.bregman.sinkhorn_epsilon_scaling: Sinkhorn with epslilon scaling [9][10] """ if method.lower() == 'sinkhorn': def sink(): return sinkhorn_knopp(a, b, M, reg, numItermax=numItermax, stopThr=stopThr, verbose=verbose, log=log, **kwargs) elif method.lower() == 'sinkhorn_stabilized': def sink(): return sinkhorn_stabilized(a, b, M, reg, numItermax=numItermax, stopThr=stopThr, verbose=verbose, log=log, **kwargs) elif method.lower() == 'sinkhorn_epsilon_scaling': def sink(): return sinkhorn_epsilon_scaling( a, b, M, reg, numItermax=numItermax, stopThr=stopThr, verbose=verbose, log=log, **kwargs) else: print('Warning : unknown method using classic Sinkhorn Knopp') def sink(): return sinkhorn_knopp(a, b, M, reg, **kwargs) b = np.asarray(b, dtype=np.float64) if len(b.shape) < 2: b = b.reshape((-1, 1)) return sink()
python
def sinkhorn2(a, b, M, reg, method='sinkhorn', numItermax=1000, stopThr=1e-9, verbose=False, log=False, **kwargs): u""" Solve the entropic regularization optimal transport problem and return the loss The function solves the following optimization problem: .. math:: W = \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [2]_ Parameters ---------- a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) or np.ndarray (nt,nbb) samples in the target domain, compute sinkhorn with multiple targets and fixed M if b is a matrix (return OT loss + dual variables in log) M : np.ndarray (ns,nt) loss matrix reg : float Regularization term >0 method : str method used for the solver either 'sinkhorn', 'sinkhorn_stabilized' or 'sinkhorn_epsilon_scaling', see those function for specific parameters numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- W : (nt) ndarray or float Optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters Examples -------- >>> import ot >>> a=[.5,.5] >>> b=[.5,.5] >>> M=[[0.,1.],[1.,0.]] >>> ot.sinkhorn2(a,b,M,1) array([ 0.26894142]) References ---------- .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013 .. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519. .. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816. [21] Altschuler J., Weed J., Rigollet P. : Near-linear time approximation algorithms for optimal transport via Sinkhorn iteration, Advances in Neural Information Processing Systems (NIPS) 31, 2017 See Also -------- ot.lp.emd : Unregularized OT ot.optim.cg : General regularized OT ot.bregman.sinkhorn_knopp : Classic Sinkhorn [2] ot.bregman.greenkhorn : Greenkhorn [21] ot.bregman.sinkhorn_stabilized: Stabilized sinkhorn [9][10] ot.bregman.sinkhorn_epsilon_scaling: Sinkhorn with epslilon scaling [9][10] """ if method.lower() == 'sinkhorn': def sink(): return sinkhorn_knopp(a, b, M, reg, numItermax=numItermax, stopThr=stopThr, verbose=verbose, log=log, **kwargs) elif method.lower() == 'sinkhorn_stabilized': def sink(): return sinkhorn_stabilized(a, b, M, reg, numItermax=numItermax, stopThr=stopThr, verbose=verbose, log=log, **kwargs) elif method.lower() == 'sinkhorn_epsilon_scaling': def sink(): return sinkhorn_epsilon_scaling( a, b, M, reg, numItermax=numItermax, stopThr=stopThr, verbose=verbose, log=log, **kwargs) else: print('Warning : unknown method using classic Sinkhorn Knopp') def sink(): return sinkhorn_knopp(a, b, M, reg, **kwargs) b = np.asarray(b, dtype=np.float64) if len(b.shape) < 2: b = b.reshape((-1, 1)) return sink()
[ "def", "sinkhorn2", "(", "a", ",", "b", ",", "M", ",", "reg", ",", "method", "=", "'sinkhorn'", ",", "numItermax", "=", "1000", ",", "stopThr", "=", "1e-9", ",", "verbose", "=", "False", ",", "log", "=", "False", ",", "*", "*", "kwargs", ")", ":"...
u""" Solve the entropic regularization optimal transport problem and return the loss The function solves the following optimization problem: .. math:: W = \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [2]_ Parameters ---------- a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) or np.ndarray (nt,nbb) samples in the target domain, compute sinkhorn with multiple targets and fixed M if b is a matrix (return OT loss + dual variables in log) M : np.ndarray (ns,nt) loss matrix reg : float Regularization term >0 method : str method used for the solver either 'sinkhorn', 'sinkhorn_stabilized' or 'sinkhorn_epsilon_scaling', see those function for specific parameters numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- W : (nt) ndarray or float Optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters Examples -------- >>> import ot >>> a=[.5,.5] >>> b=[.5,.5] >>> M=[[0.,1.],[1.,0.]] >>> ot.sinkhorn2(a,b,M,1) array([ 0.26894142]) References ---------- .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013 .. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519. .. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816. [21] Altschuler J., Weed J., Rigollet P. : Near-linear time approximation algorithms for optimal transport via Sinkhorn iteration, Advances in Neural Information Processing Systems (NIPS) 31, 2017 See Also -------- ot.lp.emd : Unregularized OT ot.optim.cg : General regularized OT ot.bregman.sinkhorn_knopp : Classic Sinkhorn [2] ot.bregman.greenkhorn : Greenkhorn [21] ot.bregman.sinkhorn_stabilized: Stabilized sinkhorn [9][10] ot.bregman.sinkhorn_epsilon_scaling: Sinkhorn with epslilon scaling [9][10]
[ "u", "Solve", "the", "entropic", "regularization", "optimal", "transport", "problem", "and", "return", "the", "loss" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L131-L245
240,907
rflamary/POT
ot/bregman.py
geometricBar
def geometricBar(weights, alldistribT): """return the weighted geometric mean of distributions""" assert(len(weights) == alldistribT.shape[1]) return np.exp(np.dot(np.log(alldistribT), weights.T))
python
def geometricBar(weights, alldistribT): assert(len(weights) == alldistribT.shape[1]) return np.exp(np.dot(np.log(alldistribT), weights.T))
[ "def", "geometricBar", "(", "weights", ",", "alldistribT", ")", ":", "assert", "(", "len", "(", "weights", ")", "==", "alldistribT", ".", "shape", "[", "1", "]", ")", "return", "np", ".", "exp", "(", "np", ".", "dot", "(", "np", ".", "log", "(", ...
return the weighted geometric mean of distributions
[ "return", "the", "weighted", "geometric", "mean", "of", "distributions" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L968-L971
240,908
rflamary/POT
ot/bregman.py
geometricMean
def geometricMean(alldistribT): """return the geometric mean of distributions""" return np.exp(np.mean(np.log(alldistribT), axis=1))
python
def geometricMean(alldistribT): return np.exp(np.mean(np.log(alldistribT), axis=1))
[ "def", "geometricMean", "(", "alldistribT", ")", ":", "return", "np", ".", "exp", "(", "np", ".", "mean", "(", "np", ".", "log", "(", "alldistribT", ")", ",", "axis", "=", "1", ")", ")" ]
return the geometric mean of distributions
[ "return", "the", "geometric", "mean", "of", "distributions" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L974-L976
240,909
rflamary/POT
ot/bregman.py
projR
def projR(gamma, p): """return the KL projection on the row constrints """ return np.multiply(gamma.T, p / np.maximum(np.sum(gamma, axis=1), 1e-10)).T
python
def projR(gamma, p): return np.multiply(gamma.T, p / np.maximum(np.sum(gamma, axis=1), 1e-10)).T
[ "def", "projR", "(", "gamma", ",", "p", ")", ":", "return", "np", ".", "multiply", "(", "gamma", ".", "T", ",", "p", "/", "np", ".", "maximum", "(", "np", ".", "sum", "(", "gamma", ",", "axis", "=", "1", ")", ",", "1e-10", ")", ")", ".", "T...
return the KL projection on the row constrints
[ "return", "the", "KL", "projection", "on", "the", "row", "constrints" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L979-L981
240,910
rflamary/POT
ot/bregman.py
projC
def projC(gamma, q): """return the KL projection on the column constrints """ return np.multiply(gamma, q / np.maximum(np.sum(gamma, axis=0), 1e-10))
python
def projC(gamma, q): return np.multiply(gamma, q / np.maximum(np.sum(gamma, axis=0), 1e-10))
[ "def", "projC", "(", "gamma", ",", "q", ")", ":", "return", "np", ".", "multiply", "(", "gamma", ",", "q", "/", "np", ".", "maximum", "(", "np", ".", "sum", "(", "gamma", ",", "axis", "=", "0", ")", ",", "1e-10", ")", ")" ]
return the KL projection on the column constrints
[ "return", "the", "KL", "projection", "on", "the", "column", "constrints" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L984-L986
240,911
rflamary/POT
ot/bregman.py
barycenter
def barycenter(A, M, reg, weights=None, numItermax=1000, stopThr=1e-4, verbose=False, log=False): """Compute the entropic regularized wasserstein barycenter of distributions A The function solves the following optimization problem: .. math:: \mathbf{a} = arg\min_\mathbf{a} \sum_i W_{reg}(\mathbf{a},\mathbf{a}_i) where : - :math:`W_{reg}(\cdot,\cdot)` is the entropic regularized Wasserstein distance (see ot.bregman.sinkhorn) - :math:`\mathbf{a}_i` are training distributions in the columns of matrix :math:`\mathbf{A}` - reg and :math:`\mathbf{M}` are respectively the regularization term and the cost matrix for OT The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [3]_ Parameters ---------- A : np.ndarray (d,n) n training distributions a_i of size d M : np.ndarray (d,d) loss matrix for OT reg : float Regularization term >0 weights : np.ndarray (n,) Weights of each histogram a_i on the simplex (barycentric coodinates) numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- a : (d,) ndarray Wasserstein barycenter log : dict log dictionary return only if log==True in parameters References ---------- .. [3] Benamou, J. D., Carlier, G., Cuturi, M., Nenna, L., & Peyré, G. (2015). Iterative Bregman projections for regularized transportation problems. SIAM Journal on Scientific Computing, 37(2), A1111-A1138. """ if weights is None: weights = np.ones(A.shape[1]) / A.shape[1] else: assert(len(weights) == A.shape[1]) if log: log = {'err': []} # M = M/np.median(M) # suggested by G. Peyre K = np.exp(-M / reg) cpt = 0 err = 1 UKv = np.dot(K, np.divide(A.T, np.sum(K, axis=0)).T) u = (geometricMean(UKv) / UKv.T).T while (err > stopThr and cpt < numItermax): cpt = cpt + 1 UKv = u * np.dot(K, np.divide(A, np.dot(K, u))) u = (u.T * geometricBar(weights, UKv)).T / UKv if cpt % 10 == 1: err = np.sum(np.std(UKv, axis=1)) # log and verbose print if log: log['err'].append(err) if verbose: if cpt % 200 == 0: print( '{:5s}|{:12s}'.format('It.', 'Err') + '\n' + '-' * 19) print('{:5d}|{:8e}|'.format(cpt, err)) if log: log['niter'] = cpt return geometricBar(weights, UKv), log else: return geometricBar(weights, UKv)
python
def barycenter(A, M, reg, weights=None, numItermax=1000, stopThr=1e-4, verbose=False, log=False): if weights is None: weights = np.ones(A.shape[1]) / A.shape[1] else: assert(len(weights) == A.shape[1]) if log: log = {'err': []} # M = M/np.median(M) # suggested by G. Peyre K = np.exp(-M / reg) cpt = 0 err = 1 UKv = np.dot(K, np.divide(A.T, np.sum(K, axis=0)).T) u = (geometricMean(UKv) / UKv.T).T while (err > stopThr and cpt < numItermax): cpt = cpt + 1 UKv = u * np.dot(K, np.divide(A, np.dot(K, u))) u = (u.T * geometricBar(weights, UKv)).T / UKv if cpt % 10 == 1: err = np.sum(np.std(UKv, axis=1)) # log and verbose print if log: log['err'].append(err) if verbose: if cpt % 200 == 0: print( '{:5s}|{:12s}'.format('It.', 'Err') + '\n' + '-' * 19) print('{:5d}|{:8e}|'.format(cpt, err)) if log: log['niter'] = cpt return geometricBar(weights, UKv), log else: return geometricBar(weights, UKv)
[ "def", "barycenter", "(", "A", ",", "M", ",", "reg", ",", "weights", "=", "None", ",", "numItermax", "=", "1000", ",", "stopThr", "=", "1e-4", ",", "verbose", "=", "False", ",", "log", "=", "False", ")", ":", "if", "weights", "is", "None", ":", "...
Compute the entropic regularized wasserstein barycenter of distributions A The function solves the following optimization problem: .. math:: \mathbf{a} = arg\min_\mathbf{a} \sum_i W_{reg}(\mathbf{a},\mathbf{a}_i) where : - :math:`W_{reg}(\cdot,\cdot)` is the entropic regularized Wasserstein distance (see ot.bregman.sinkhorn) - :math:`\mathbf{a}_i` are training distributions in the columns of matrix :math:`\mathbf{A}` - reg and :math:`\mathbf{M}` are respectively the regularization term and the cost matrix for OT The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [3]_ Parameters ---------- A : np.ndarray (d,n) n training distributions a_i of size d M : np.ndarray (d,d) loss matrix for OT reg : float Regularization term >0 weights : np.ndarray (n,) Weights of each histogram a_i on the simplex (barycentric coodinates) numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- a : (d,) ndarray Wasserstein barycenter log : dict log dictionary return only if log==True in parameters References ---------- .. [3] Benamou, J. D., Carlier, G., Cuturi, M., Nenna, L., & Peyré, G. (2015). Iterative Bregman projections for regularized transportation problems. SIAM Journal on Scientific Computing, 37(2), A1111-A1138.
[ "Compute", "the", "entropic", "regularized", "wasserstein", "barycenter", "of", "distributions", "A" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L989-L1082
240,912
rflamary/POT
ot/bregman.py
convolutional_barycenter2d
def convolutional_barycenter2d(A, reg, weights=None, numItermax=10000, stopThr=1e-9, stabThr=1e-30, verbose=False, log=False): """Compute the entropic regularized wasserstein barycenter of distributions A where A is a collection of 2D images. The function solves the following optimization problem: .. math:: \mathbf{a} = arg\min_\mathbf{a} \sum_i W_{reg}(\mathbf{a},\mathbf{a}_i) where : - :math:`W_{reg}(\cdot,\cdot)` is the entropic regularized Wasserstein distance (see ot.bregman.sinkhorn) - :math:`\mathbf{a}_i` are training distributions (2D images) in the mast two dimensions of matrix :math:`\mathbf{A}` - reg is the regularization strength scalar value The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [21]_ Parameters ---------- A : np.ndarray (n,w,h) n distributions (2D images) of size w x h reg : float Regularization term >0 weights : np.ndarray (n,) Weights of each image on the simplex (barycentric coodinates) numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) stabThr : float, optional Stabilization threshold to avoid numerical precision issue verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- a : (w,h) ndarray 2D Wasserstein barycenter log : dict log dictionary return only if log==True in parameters References ---------- .. [21] Solomon, J., De Goes, F., Peyré, G., Cuturi, M., Butscher, A., Nguyen, A. & Guibas, L. (2015). Convolutional wasserstein distances: Efficient optimal transportation on geometric domains ACM Transactions on Graphics (TOG), 34(4), 66 """ if weights is None: weights = np.ones(A.shape[0]) / A.shape[0] else: assert(len(weights) == A.shape[0]) if log: log = {'err': []} b = np.zeros_like(A[0, :, :]) U = np.ones_like(A) KV = np.ones_like(A) cpt = 0 err = 1 # build the convolution operator t = np.linspace(0, 1, A.shape[1]) [Y, X] = np.meshgrid(t, t) xi1 = np.exp(-(X - Y)**2 / reg) def K(x): return np.dot(np.dot(xi1, x), xi1) while (err > stopThr and cpt < numItermax): bold = b cpt = cpt + 1 b = np.zeros_like(A[0, :, :]) for r in range(A.shape[0]): KV[r, :, :] = K(A[r, :, :] / np.maximum(stabThr, K(U[r, :, :]))) b += weights[r] * np.log(np.maximum(stabThr, U[r, :, :] * KV[r, :, :])) b = np.exp(b) for r in range(A.shape[0]): U[r, :, :] = b / np.maximum(stabThr, KV[r, :, :]) if cpt % 10 == 1: err = np.sum(np.abs(bold - b)) # log and verbose print if log: log['err'].append(err) if verbose: if cpt % 200 == 0: print('{:5s}|{:12s}'.format('It.', 'Err') + '\n' + '-' * 19) print('{:5d}|{:8e}|'.format(cpt, err)) if log: log['niter'] = cpt log['U'] = U return b, log else: return b
python
def convolutional_barycenter2d(A, reg, weights=None, numItermax=10000, stopThr=1e-9, stabThr=1e-30, verbose=False, log=False): if weights is None: weights = np.ones(A.shape[0]) / A.shape[0] else: assert(len(weights) == A.shape[0]) if log: log = {'err': []} b = np.zeros_like(A[0, :, :]) U = np.ones_like(A) KV = np.ones_like(A) cpt = 0 err = 1 # build the convolution operator t = np.linspace(0, 1, A.shape[1]) [Y, X] = np.meshgrid(t, t) xi1 = np.exp(-(X - Y)**2 / reg) def K(x): return np.dot(np.dot(xi1, x), xi1) while (err > stopThr and cpt < numItermax): bold = b cpt = cpt + 1 b = np.zeros_like(A[0, :, :]) for r in range(A.shape[0]): KV[r, :, :] = K(A[r, :, :] / np.maximum(stabThr, K(U[r, :, :]))) b += weights[r] * np.log(np.maximum(stabThr, U[r, :, :] * KV[r, :, :])) b = np.exp(b) for r in range(A.shape[0]): U[r, :, :] = b / np.maximum(stabThr, KV[r, :, :]) if cpt % 10 == 1: err = np.sum(np.abs(bold - b)) # log and verbose print if log: log['err'].append(err) if verbose: if cpt % 200 == 0: print('{:5s}|{:12s}'.format('It.', 'Err') + '\n' + '-' * 19) print('{:5d}|{:8e}|'.format(cpt, err)) if log: log['niter'] = cpt log['U'] = U return b, log else: return b
[ "def", "convolutional_barycenter2d", "(", "A", ",", "reg", ",", "weights", "=", "None", ",", "numItermax", "=", "10000", ",", "stopThr", "=", "1e-9", ",", "stabThr", "=", "1e-30", ",", "verbose", "=", "False", ",", "log", "=", "False", ")", ":", "if", ...
Compute the entropic regularized wasserstein barycenter of distributions A where A is a collection of 2D images. The function solves the following optimization problem: .. math:: \mathbf{a} = arg\min_\mathbf{a} \sum_i W_{reg}(\mathbf{a},\mathbf{a}_i) where : - :math:`W_{reg}(\cdot,\cdot)` is the entropic regularized Wasserstein distance (see ot.bregman.sinkhorn) - :math:`\mathbf{a}_i` are training distributions (2D images) in the mast two dimensions of matrix :math:`\mathbf{A}` - reg is the regularization strength scalar value The algorithm used for solving the problem is the Sinkhorn-Knopp matrix scaling algorithm as proposed in [21]_ Parameters ---------- A : np.ndarray (n,w,h) n distributions (2D images) of size w x h reg : float Regularization term >0 weights : np.ndarray (n,) Weights of each image on the simplex (barycentric coodinates) numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) stabThr : float, optional Stabilization threshold to avoid numerical precision issue verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- a : (w,h) ndarray 2D Wasserstein barycenter log : dict log dictionary return only if log==True in parameters References ---------- .. [21] Solomon, J., De Goes, F., Peyré, G., Cuturi, M., Butscher, A., Nguyen, A. & Guibas, L. (2015). Convolutional wasserstein distances: Efficient optimal transportation on geometric domains ACM Transactions on Graphics (TOG), 34(4), 66
[ "Compute", "the", "entropic", "regularized", "wasserstein", "barycenter", "of", "distributions", "A", "where", "A", "is", "a", "collection", "of", "2D", "images", "." ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L1085-L1192
240,913
rflamary/POT
ot/bregman.py
unmix
def unmix(a, D, M, M0, h0, reg, reg0, alpha, numItermax=1000, stopThr=1e-3, verbose=False, log=False): """ Compute the unmixing of an observation with a given dictionary using Wasserstein distance The function solve the following optimization problem: .. math:: \mathbf{h} = arg\min_\mathbf{h} (1- \\alpha) W_{M,reg}(\mathbf{a},\mathbf{Dh})+\\alpha W_{M0,reg0}(\mathbf{h}_0,\mathbf{h}) where : - :math:`W_{M,reg}(\cdot,\cdot)` is the entropic regularized Wasserstein distance with M loss matrix (see ot.bregman.sinkhorn) - :math:`\mathbf{a}` is an observed distribution, :math:`\mathbf{h}_0` is aprior on unmixing - reg and :math:`\mathbf{M}` are respectively the regularization term and the cost matrix for OT data fitting - reg0 and :math:`\mathbf{M0}` are respectively the regularization term and the cost matrix for regularization - :math:`\\alpha`weight data fitting and regularization The optimization problem is solved suing the algorithm described in [4] Parameters ---------- a : np.ndarray (d) observed distribution D : np.ndarray (d,n) dictionary matrix M : np.ndarray (d,d) loss matrix M0 : np.ndarray (n,n) loss matrix h0 : np.ndarray (n,) prior on h reg : float Regularization term >0 (Wasserstein data fitting) reg0 : float Regularization term >0 (Wasserstein reg with h0) alpha : float How much should we trust the prior ([0,1]) numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- a : (d,) ndarray Wasserstein barycenter log : dict log dictionary return only if log==True in parameters References ---------- .. [4] S. Nakhostin, N. Courty, R. Flamary, D. Tuia, T. Corpetti, Supervised planetary unmixing with optimal transport, Whorkshop on Hyperspectral Image and Signal Processing : Evolution in Remote Sensing (WHISPERS), 2016. """ # M = M/np.median(M) K = np.exp(-M / reg) # M0 = M0/np.median(M0) K0 = np.exp(-M0 / reg0) old = h0 err = 1 cpt = 0 # log = {'niter':0, 'all_err':[]} if log: log = {'err': []} while (err > stopThr and cpt < numItermax): K = projC(K, a) K0 = projC(K0, h0) new = np.sum(K0, axis=1) # we recombine the current selection from dictionnary inv_new = np.dot(D, new) other = np.sum(K, axis=1) # geometric interpolation delta = np.exp(alpha * np.log(other) + (1 - alpha) * np.log(inv_new)) K = projR(K, delta) K0 = np.dot(np.diag(np.dot(D.T, delta / inv_new)), K0) err = np.linalg.norm(np.sum(K0, axis=1) - old) old = new if log: log['err'].append(err) if verbose: if cpt % 200 == 0: print('{:5s}|{:12s}'.format('It.', 'Err') + '\n' + '-' * 19) print('{:5d}|{:8e}|'.format(cpt, err)) cpt = cpt + 1 if log: log['niter'] = cpt return np.sum(K0, axis=1), log else: return np.sum(K0, axis=1)
python
def unmix(a, D, M, M0, h0, reg, reg0, alpha, numItermax=1000, stopThr=1e-3, verbose=False, log=False): # M = M/np.median(M) K = np.exp(-M / reg) # M0 = M0/np.median(M0) K0 = np.exp(-M0 / reg0) old = h0 err = 1 cpt = 0 # log = {'niter':0, 'all_err':[]} if log: log = {'err': []} while (err > stopThr and cpt < numItermax): K = projC(K, a) K0 = projC(K0, h0) new = np.sum(K0, axis=1) # we recombine the current selection from dictionnary inv_new = np.dot(D, new) other = np.sum(K, axis=1) # geometric interpolation delta = np.exp(alpha * np.log(other) + (1 - alpha) * np.log(inv_new)) K = projR(K, delta) K0 = np.dot(np.diag(np.dot(D.T, delta / inv_new)), K0) err = np.linalg.norm(np.sum(K0, axis=1) - old) old = new if log: log['err'].append(err) if verbose: if cpt % 200 == 0: print('{:5s}|{:12s}'.format('It.', 'Err') + '\n' + '-' * 19) print('{:5d}|{:8e}|'.format(cpt, err)) cpt = cpt + 1 if log: log['niter'] = cpt return np.sum(K0, axis=1), log else: return np.sum(K0, axis=1)
[ "def", "unmix", "(", "a", ",", "D", ",", "M", ",", "M0", ",", "h0", ",", "reg", ",", "reg0", ",", "alpha", ",", "numItermax", "=", "1000", ",", "stopThr", "=", "1e-3", ",", "verbose", "=", "False", ",", "log", "=", "False", ")", ":", "# M = M/n...
Compute the unmixing of an observation with a given dictionary using Wasserstein distance The function solve the following optimization problem: .. math:: \mathbf{h} = arg\min_\mathbf{h} (1- \\alpha) W_{M,reg}(\mathbf{a},\mathbf{Dh})+\\alpha W_{M0,reg0}(\mathbf{h}_0,\mathbf{h}) where : - :math:`W_{M,reg}(\cdot,\cdot)` is the entropic regularized Wasserstein distance with M loss matrix (see ot.bregman.sinkhorn) - :math:`\mathbf{a}` is an observed distribution, :math:`\mathbf{h}_0` is aprior on unmixing - reg and :math:`\mathbf{M}` are respectively the regularization term and the cost matrix for OT data fitting - reg0 and :math:`\mathbf{M0}` are respectively the regularization term and the cost matrix for regularization - :math:`\\alpha`weight data fitting and regularization The optimization problem is solved suing the algorithm described in [4] Parameters ---------- a : np.ndarray (d) observed distribution D : np.ndarray (d,n) dictionary matrix M : np.ndarray (d,d) loss matrix M0 : np.ndarray (n,n) loss matrix h0 : np.ndarray (n,) prior on h reg : float Regularization term >0 (Wasserstein data fitting) reg0 : float Regularization term >0 (Wasserstein reg with h0) alpha : float How much should we trust the prior ([0,1]) numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- a : (d,) ndarray Wasserstein barycenter log : dict log dictionary return only if log==True in parameters References ---------- .. [4] S. Nakhostin, N. Courty, R. Flamary, D. Tuia, T. Corpetti, Supervised planetary unmixing with optimal transport, Whorkshop on Hyperspectral Image and Signal Processing : Evolution in Remote Sensing (WHISPERS), 2016.
[ "Compute", "the", "unmixing", "of", "an", "observation", "with", "a", "given", "dictionary", "using", "Wasserstein", "distance" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L1195-L1300
240,914
rflamary/POT
ot/bregman.py
empirical_sinkhorn
def empirical_sinkhorn(X_s, X_t, reg, a=None, b=None, metric='sqeuclidean', numIterMax=10000, stopThr=1e-9, verbose=False, log=False, **kwargs): ''' Solve the entropic regularization optimal transport problem and return the OT matrix from empirical data The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - :math:`M` is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - :math:`a` and :math:`b` are source and target weights (sum to 1) Parameters ---------- X_s : np.ndarray (ns, d) samples in the source domain X_t : np.ndarray (nt, d) samples in the target domain reg : float Regularization term >0 a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) samples weights in the target domain numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Regularized optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters Examples -------- >>> n_s = 2 >>> n_t = 2 >>> reg = 0.1 >>> X_s = np.reshape(np.arange(n_s), (n_s, 1)) >>> X_t = np.reshape(np.arange(0, n_t), (n_t, 1)) >>> emp_sinkhorn = empirical_sinkhorn(X_s, X_t, reg, verbose=False) >>> print(emp_sinkhorn) >>> [[4.99977301e-01 2.26989344e-05] [2.26989344e-05 4.99977301e-01]] References ---------- .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013 .. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519. .. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816. ''' if a is None: a = unif(np.shape(X_s)[0]) if b is None: b = unif(np.shape(X_t)[0]) M = dist(X_s, X_t, metric=metric) if log: pi, log = sinkhorn(a, b, M, reg, numItermax=numIterMax, stopThr=stopThr, verbose=verbose, log=True, **kwargs) return pi, log else: pi = sinkhorn(a, b, M, reg, numItermax=numIterMax, stopThr=stopThr, verbose=verbose, log=False, **kwargs) return pi
python
def empirical_sinkhorn(X_s, X_t, reg, a=None, b=None, metric='sqeuclidean', numIterMax=10000, stopThr=1e-9, verbose=False, log=False, **kwargs): ''' Solve the entropic regularization optimal transport problem and return the OT matrix from empirical data The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - :math:`M` is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - :math:`a` and :math:`b` are source and target weights (sum to 1) Parameters ---------- X_s : np.ndarray (ns, d) samples in the source domain X_t : np.ndarray (nt, d) samples in the target domain reg : float Regularization term >0 a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) samples weights in the target domain numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Regularized optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters Examples -------- >>> n_s = 2 >>> n_t = 2 >>> reg = 0.1 >>> X_s = np.reshape(np.arange(n_s), (n_s, 1)) >>> X_t = np.reshape(np.arange(0, n_t), (n_t, 1)) >>> emp_sinkhorn = empirical_sinkhorn(X_s, X_t, reg, verbose=False) >>> print(emp_sinkhorn) >>> [[4.99977301e-01 2.26989344e-05] [2.26989344e-05 4.99977301e-01]] References ---------- .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013 .. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519. .. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816. ''' if a is None: a = unif(np.shape(X_s)[0]) if b is None: b = unif(np.shape(X_t)[0]) M = dist(X_s, X_t, metric=metric) if log: pi, log = sinkhorn(a, b, M, reg, numItermax=numIterMax, stopThr=stopThr, verbose=verbose, log=True, **kwargs) return pi, log else: pi = sinkhorn(a, b, M, reg, numItermax=numIterMax, stopThr=stopThr, verbose=verbose, log=False, **kwargs) return pi
[ "def", "empirical_sinkhorn", "(", "X_s", ",", "X_t", ",", "reg", ",", "a", "=", "None", ",", "b", "=", "None", ",", "metric", "=", "'sqeuclidean'", ",", "numIterMax", "=", "10000", ",", "stopThr", "=", "1e-9", ",", "verbose", "=", "False", ",", "log"...
Solve the entropic regularization optimal transport problem and return the OT matrix from empirical data The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - :math:`M` is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - :math:`a` and :math:`b` are source and target weights (sum to 1) Parameters ---------- X_s : np.ndarray (ns, d) samples in the source domain X_t : np.ndarray (nt, d) samples in the target domain reg : float Regularization term >0 a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) samples weights in the target domain numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Regularized optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters Examples -------- >>> n_s = 2 >>> n_t = 2 >>> reg = 0.1 >>> X_s = np.reshape(np.arange(n_s), (n_s, 1)) >>> X_t = np.reshape(np.arange(0, n_t), (n_t, 1)) >>> emp_sinkhorn = empirical_sinkhorn(X_s, X_t, reg, verbose=False) >>> print(emp_sinkhorn) >>> [[4.99977301e-01 2.26989344e-05] [2.26989344e-05 4.99977301e-01]] References ---------- .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013 .. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519. .. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.
[ "Solve", "the", "entropic", "regularization", "optimal", "transport", "problem", "and", "return", "the", "OT", "matrix", "from", "empirical", "data" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L1303-L1390
240,915
rflamary/POT
ot/bregman.py
empirical_sinkhorn2
def empirical_sinkhorn2(X_s, X_t, reg, a=None, b=None, metric='sqeuclidean', numIterMax=10000, stopThr=1e-9, verbose=False, log=False, **kwargs): ''' Solve the entropic regularization optimal transport problem from empirical data and return the OT loss The function solves the following optimization problem: .. math:: W = \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - :math:`M` is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - :math:`a` and :math:`b` are source and target weights (sum to 1) Parameters ---------- X_s : np.ndarray (ns, d) samples in the source domain X_t : np.ndarray (nt, d) samples in the target domain reg : float Regularization term >0 a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) samples weights in the target domain numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Regularized optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters Examples -------- >>> n_s = 2 >>> n_t = 2 >>> reg = 0.1 >>> X_s = np.reshape(np.arange(n_s), (n_s, 1)) >>> X_t = np.reshape(np.arange(0, n_t), (n_t, 1)) >>> loss_sinkhorn = empirical_sinkhorn2(X_s, X_t, reg, verbose=False) >>> print(loss_sinkhorn) >>> [4.53978687e-05] References ---------- .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013 .. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519. .. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816. ''' if a is None: a = unif(np.shape(X_s)[0]) if b is None: b = unif(np.shape(X_t)[0]) M = dist(X_s, X_t, metric=metric) if log: sinkhorn_loss, log = sinkhorn2(a, b, M, reg, numItermax=numIterMax, stopThr=stopThr, verbose=verbose, log=log, **kwargs) return sinkhorn_loss, log else: sinkhorn_loss = sinkhorn2(a, b, M, reg, numItermax=numIterMax, stopThr=stopThr, verbose=verbose, log=log, **kwargs) return sinkhorn_loss
python
def empirical_sinkhorn2(X_s, X_t, reg, a=None, b=None, metric='sqeuclidean', numIterMax=10000, stopThr=1e-9, verbose=False, log=False, **kwargs): ''' Solve the entropic regularization optimal transport problem from empirical data and return the OT loss The function solves the following optimization problem: .. math:: W = \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - :math:`M` is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - :math:`a` and :math:`b` are source and target weights (sum to 1) Parameters ---------- X_s : np.ndarray (ns, d) samples in the source domain X_t : np.ndarray (nt, d) samples in the target domain reg : float Regularization term >0 a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) samples weights in the target domain numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Regularized optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters Examples -------- >>> n_s = 2 >>> n_t = 2 >>> reg = 0.1 >>> X_s = np.reshape(np.arange(n_s), (n_s, 1)) >>> X_t = np.reshape(np.arange(0, n_t), (n_t, 1)) >>> loss_sinkhorn = empirical_sinkhorn2(X_s, X_t, reg, verbose=False) >>> print(loss_sinkhorn) >>> [4.53978687e-05] References ---------- .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013 .. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519. .. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816. ''' if a is None: a = unif(np.shape(X_s)[0]) if b is None: b = unif(np.shape(X_t)[0]) M = dist(X_s, X_t, metric=metric) if log: sinkhorn_loss, log = sinkhorn2(a, b, M, reg, numItermax=numIterMax, stopThr=stopThr, verbose=verbose, log=log, **kwargs) return sinkhorn_loss, log else: sinkhorn_loss = sinkhorn2(a, b, M, reg, numItermax=numIterMax, stopThr=stopThr, verbose=verbose, log=log, **kwargs) return sinkhorn_loss
[ "def", "empirical_sinkhorn2", "(", "X_s", ",", "X_t", ",", "reg", ",", "a", "=", "None", ",", "b", "=", "None", ",", "metric", "=", "'sqeuclidean'", ",", "numIterMax", "=", "10000", ",", "stopThr", "=", "1e-9", ",", "verbose", "=", "False", ",", "log...
Solve the entropic regularization optimal transport problem from empirical data and return the OT loss The function solves the following optimization problem: .. math:: W = \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - :math:`M` is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - :math:`a` and :math:`b` are source and target weights (sum to 1) Parameters ---------- X_s : np.ndarray (ns, d) samples in the source domain X_t : np.ndarray (nt, d) samples in the target domain reg : float Regularization term >0 a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) samples weights in the target domain numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Regularized optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters Examples -------- >>> n_s = 2 >>> n_t = 2 >>> reg = 0.1 >>> X_s = np.reshape(np.arange(n_s), (n_s, 1)) >>> X_t = np.reshape(np.arange(0, n_t), (n_t, 1)) >>> loss_sinkhorn = empirical_sinkhorn2(X_s, X_t, reg, verbose=False) >>> print(loss_sinkhorn) >>> [4.53978687e-05] References ---------- .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013 .. [9] Schmitzer, B. (2016). Stabilized Sparse Scaling Algorithms for Entropy Regularized Transport Problems. arXiv preprint arXiv:1610.06519. .. [10] Chizat, L., Peyré, G., Schmitzer, B., & Vialard, F. X. (2016). Scaling algorithms for unbalanced transport problems. arXiv preprint arXiv:1607.05816.
[ "Solve", "the", "entropic", "regularization", "optimal", "transport", "problem", "from", "empirical", "data", "and", "return", "the", "OT", "loss" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L1393-L1480
240,916
rflamary/POT
ot/bregman.py
empirical_sinkhorn_divergence
def empirical_sinkhorn_divergence(X_s, X_t, reg, a=None, b=None, metric='sqeuclidean', numIterMax=10000, stopThr=1e-9, verbose=False, log=False, **kwargs): ''' Compute the sinkhorn divergence loss from empirical data The function solves the following optimization problems and return the sinkhorn divergence :math:`S`: .. math:: W &= \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) W_a &= \min_{\gamma_a} <\gamma_a,M_a>_F + reg\cdot\Omega(\gamma_a) W_b &= \min_{\gamma_b} <\gamma_b,M_b>_F + reg\cdot\Omega(\gamma_b) S &= W - 1/2 * (W_a + W_b) .. math:: s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 \gamma_a 1 = a \gamma_a^T 1= a \gamma_a\geq 0 \gamma_b 1 = b \gamma_b^T 1= b \gamma_b\geq 0 where : - :math:`M` (resp. :math:`M_a, M_b`) is the (ns,nt) metric cost matrix (resp (ns, ns) and (nt, nt)) - :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - :math:`a` and :math:`b` are source and target weights (sum to 1) Parameters ---------- X_s : np.ndarray (ns, d) samples in the source domain X_t : np.ndarray (nt, d) samples in the target domain reg : float Regularization term >0 a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) samples weights in the target domain numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Regularized optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters Examples -------- >>> n_s = 2 >>> n_t = 4 >>> reg = 0.1 >>> X_s = np.reshape(np.arange(n_s), (n_s, 1)) >>> X_t = np.reshape(np.arange(0, n_t), (n_t, 1)) >>> emp_sinkhorn_div = empirical_sinkhorn_divergence(X_s, X_t, reg) >>> print(emp_sinkhorn_div) >>> [2.99977435] References ---------- .. [23] Aude Genevay, Gabriel Peyré, Marco Cuturi, Learning Generative Models with Sinkhorn Divergences, Proceedings of the Twenty-First International Conference on Artficial Intelligence and Statistics, (AISTATS) 21, 2018 ''' if log: sinkhorn_loss_ab, log_ab = empirical_sinkhorn2(X_s, X_t, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwargs) sinkhorn_loss_a, log_a = empirical_sinkhorn2(X_s, X_s, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwargs) sinkhorn_loss_b, log_b = empirical_sinkhorn2(X_t, X_t, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwargs) sinkhorn_div = sinkhorn_loss_ab - 1 / 2 * (sinkhorn_loss_a + sinkhorn_loss_b) log = {} log['sinkhorn_loss_ab'] = sinkhorn_loss_ab log['sinkhorn_loss_a'] = sinkhorn_loss_a log['sinkhorn_loss_b'] = sinkhorn_loss_b log['log_sinkhorn_ab'] = log_ab log['log_sinkhorn_a'] = log_a log['log_sinkhorn_b'] = log_b return max(0, sinkhorn_div), log else: sinkhorn_loss_ab = empirical_sinkhorn2(X_s, X_t, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwargs) sinkhorn_loss_a = empirical_sinkhorn2(X_s, X_s, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwargs) sinkhorn_loss_b = empirical_sinkhorn2(X_t, X_t, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwargs) sinkhorn_div = sinkhorn_loss_ab - 1 / 2 * (sinkhorn_loss_a + sinkhorn_loss_b) return max(0, sinkhorn_div)
python
def empirical_sinkhorn_divergence(X_s, X_t, reg, a=None, b=None, metric='sqeuclidean', numIterMax=10000, stopThr=1e-9, verbose=False, log=False, **kwargs): ''' Compute the sinkhorn divergence loss from empirical data The function solves the following optimization problems and return the sinkhorn divergence :math:`S`: .. math:: W &= \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) W_a &= \min_{\gamma_a} <\gamma_a,M_a>_F + reg\cdot\Omega(\gamma_a) W_b &= \min_{\gamma_b} <\gamma_b,M_b>_F + reg\cdot\Omega(\gamma_b) S &= W - 1/2 * (W_a + W_b) .. math:: s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 \gamma_a 1 = a \gamma_a^T 1= a \gamma_a\geq 0 \gamma_b 1 = b \gamma_b^T 1= b \gamma_b\geq 0 where : - :math:`M` (resp. :math:`M_a, M_b`) is the (ns,nt) metric cost matrix (resp (ns, ns) and (nt, nt)) - :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - :math:`a` and :math:`b` are source and target weights (sum to 1) Parameters ---------- X_s : np.ndarray (ns, d) samples in the source domain X_t : np.ndarray (nt, d) samples in the target domain reg : float Regularization term >0 a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) samples weights in the target domain numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Regularized optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters Examples -------- >>> n_s = 2 >>> n_t = 4 >>> reg = 0.1 >>> X_s = np.reshape(np.arange(n_s), (n_s, 1)) >>> X_t = np.reshape(np.arange(0, n_t), (n_t, 1)) >>> emp_sinkhorn_div = empirical_sinkhorn_divergence(X_s, X_t, reg) >>> print(emp_sinkhorn_div) >>> [2.99977435] References ---------- .. [23] Aude Genevay, Gabriel Peyré, Marco Cuturi, Learning Generative Models with Sinkhorn Divergences, Proceedings of the Twenty-First International Conference on Artficial Intelligence and Statistics, (AISTATS) 21, 2018 ''' if log: sinkhorn_loss_ab, log_ab = empirical_sinkhorn2(X_s, X_t, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwargs) sinkhorn_loss_a, log_a = empirical_sinkhorn2(X_s, X_s, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwargs) sinkhorn_loss_b, log_b = empirical_sinkhorn2(X_t, X_t, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwargs) sinkhorn_div = sinkhorn_loss_ab - 1 / 2 * (sinkhorn_loss_a + sinkhorn_loss_b) log = {} log['sinkhorn_loss_ab'] = sinkhorn_loss_ab log['sinkhorn_loss_a'] = sinkhorn_loss_a log['sinkhorn_loss_b'] = sinkhorn_loss_b log['log_sinkhorn_ab'] = log_ab log['log_sinkhorn_a'] = log_a log['log_sinkhorn_b'] = log_b return max(0, sinkhorn_div), log else: sinkhorn_loss_ab = empirical_sinkhorn2(X_s, X_t, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwargs) sinkhorn_loss_a = empirical_sinkhorn2(X_s, X_s, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwargs) sinkhorn_loss_b = empirical_sinkhorn2(X_t, X_t, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwargs) sinkhorn_div = sinkhorn_loss_ab - 1 / 2 * (sinkhorn_loss_a + sinkhorn_loss_b) return max(0, sinkhorn_div)
[ "def", "empirical_sinkhorn_divergence", "(", "X_s", ",", "X_t", ",", "reg", ",", "a", "=", "None", ",", "b", "=", "None", ",", "metric", "=", "'sqeuclidean'", ",", "numIterMax", "=", "10000", ",", "stopThr", "=", "1e-9", ",", "verbose", "=", "False", "...
Compute the sinkhorn divergence loss from empirical data The function solves the following optimization problems and return the sinkhorn divergence :math:`S`: .. math:: W &= \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) W_a &= \min_{\gamma_a} <\gamma_a,M_a>_F + reg\cdot\Omega(\gamma_a) W_b &= \min_{\gamma_b} <\gamma_b,M_b>_F + reg\cdot\Omega(\gamma_b) S &= W - 1/2 * (W_a + W_b) .. math:: s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 \gamma_a 1 = a \gamma_a^T 1= a \gamma_a\geq 0 \gamma_b 1 = b \gamma_b^T 1= b \gamma_b\geq 0 where : - :math:`M` (resp. :math:`M_a, M_b`) is the (ns,nt) metric cost matrix (resp (ns, ns) and (nt, nt)) - :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - :math:`a` and :math:`b` are source and target weights (sum to 1) Parameters ---------- X_s : np.ndarray (ns, d) samples in the source domain X_t : np.ndarray (nt, d) samples in the target domain reg : float Regularization term >0 a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) samples weights in the target domain numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Regularized optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters Examples -------- >>> n_s = 2 >>> n_t = 4 >>> reg = 0.1 >>> X_s = np.reshape(np.arange(n_s), (n_s, 1)) >>> X_t = np.reshape(np.arange(0, n_t), (n_t, 1)) >>> emp_sinkhorn_div = empirical_sinkhorn_divergence(X_s, X_t, reg) >>> print(emp_sinkhorn_div) >>> [2.99977435] References ---------- .. [23] Aude Genevay, Gabriel Peyré, Marco Cuturi, Learning Generative Models with Sinkhorn Divergences, Proceedings of the Twenty-First International Conference on Artficial Intelligence and Statistics, (AISTATS) 21, 2018
[ "Compute", "the", "sinkhorn", "divergence", "loss", "from", "empirical", "data" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L1483-L1599
240,917
rflamary/POT
ot/lp/__init__.py
emd
def emd(a, b, M, numItermax=100000, log=False): """Solves the Earth Movers distance problem and returns the OT matrix .. math:: \gamma = arg\min_\gamma <\gamma,M>_F s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - M is the metric cost matrix - a and b are the sample weights Uses the algorithm proposed in [1]_ Parameters ---------- a : (ns,) ndarray, float64 Source histogram (uniform weigth if empty list) b : (nt,) ndarray, float64 Target histogram (uniform weigth if empty list) M : (ns,nt) ndarray, float64 loss matrix numItermax : int, optional (default=100000) The maximum number of iterations before stopping the optimization algorithm if it has not converged. log: boolean, optional (default=False) If True, returns a dictionary containing the cost and dual variables. Otherwise returns only the optimal transportation matrix. Returns ------- gamma: (ns x nt) ndarray Optimal transportation matrix for the given parameters log: dict If input log is true, a dictionary containing the cost and dual variables and exit status Examples -------- Simple example with obvious solution. The function emd accepts lists and perform automatic conversion to numpy arrays >>> import ot >>> a=[.5,.5] >>> b=[.5,.5] >>> M=[[0.,1.],[1.,0.]] >>> ot.emd(a,b,M) array([[ 0.5, 0. ], [ 0. , 0.5]]) References ---------- .. [1] Bonneel, N., Van De Panne, M., Paris, S., & Heidrich, W. (2011, December). Displacement interpolation using Lagrangian mass transport. In ACM Transactions on Graphics (TOG) (Vol. 30, No. 6, p. 158). ACM. See Also -------- ot.bregman.sinkhorn : Entropic regularized OT ot.optim.cg : General regularized OT""" a = np.asarray(a, dtype=np.float64) b = np.asarray(b, dtype=np.float64) M = np.asarray(M, dtype=np.float64) # if empty array given then use unifor distributions if len(a) == 0: a = np.ones((M.shape[0],), dtype=np.float64) / M.shape[0] if len(b) == 0: b = np.ones((M.shape[1],), dtype=np.float64) / M.shape[1] G, cost, u, v, result_code = emd_c(a, b, M, numItermax) result_code_string = check_result(result_code) if log: log = {} log['cost'] = cost log['u'] = u log['v'] = v log['warning'] = result_code_string log['result_code'] = result_code return G, log return G
python
def emd(a, b, M, numItermax=100000, log=False): a = np.asarray(a, dtype=np.float64) b = np.asarray(b, dtype=np.float64) M = np.asarray(M, dtype=np.float64) # if empty array given then use unifor distributions if len(a) == 0: a = np.ones((M.shape[0],), dtype=np.float64) / M.shape[0] if len(b) == 0: b = np.ones((M.shape[1],), dtype=np.float64) / M.shape[1] G, cost, u, v, result_code = emd_c(a, b, M, numItermax) result_code_string = check_result(result_code) if log: log = {} log['cost'] = cost log['u'] = u log['v'] = v log['warning'] = result_code_string log['result_code'] = result_code return G, log return G
[ "def", "emd", "(", "a", ",", "b", ",", "M", ",", "numItermax", "=", "100000", ",", "log", "=", "False", ")", ":", "a", "=", "np", ".", "asarray", "(", "a", ",", "dtype", "=", "np", ".", "float64", ")", "b", "=", "np", ".", "asarray", "(", "...
Solves the Earth Movers distance problem and returns the OT matrix .. math:: \gamma = arg\min_\gamma <\gamma,M>_F s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - M is the metric cost matrix - a and b are the sample weights Uses the algorithm proposed in [1]_ Parameters ---------- a : (ns,) ndarray, float64 Source histogram (uniform weigth if empty list) b : (nt,) ndarray, float64 Target histogram (uniform weigth if empty list) M : (ns,nt) ndarray, float64 loss matrix numItermax : int, optional (default=100000) The maximum number of iterations before stopping the optimization algorithm if it has not converged. log: boolean, optional (default=False) If True, returns a dictionary containing the cost and dual variables. Otherwise returns only the optimal transportation matrix. Returns ------- gamma: (ns x nt) ndarray Optimal transportation matrix for the given parameters log: dict If input log is true, a dictionary containing the cost and dual variables and exit status Examples -------- Simple example with obvious solution. The function emd accepts lists and perform automatic conversion to numpy arrays >>> import ot >>> a=[.5,.5] >>> b=[.5,.5] >>> M=[[0.,1.],[1.,0.]] >>> ot.emd(a,b,M) array([[ 0.5, 0. ], [ 0. , 0.5]]) References ---------- .. [1] Bonneel, N., Van De Panne, M., Paris, S., & Heidrich, W. (2011, December). Displacement interpolation using Lagrangian mass transport. In ACM Transactions on Graphics (TOG) (Vol. 30, No. 6, p. 158). ACM. See Also -------- ot.bregman.sinkhorn : Entropic regularized OT ot.optim.cg : General regularized OT
[ "Solves", "the", "Earth", "Movers", "distance", "problem", "and", "returns", "the", "OT", "matrix" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/lp/__init__.py#L25-L113
240,918
rflamary/POT
ot/lp/__init__.py
emd2
def emd2(a, b, M, processes=multiprocessing.cpu_count(), numItermax=100000, log=False, return_matrix=False): """Solves the Earth Movers distance problem and returns the loss .. math:: \gamma = arg\min_\gamma <\gamma,M>_F s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - M is the metric cost matrix - a and b are the sample weights Uses the algorithm proposed in [1]_ Parameters ---------- a : (ns,) ndarray, float64 Source histogram (uniform weigth if empty list) b : (nt,) ndarray, float64 Target histogram (uniform weigth if empty list) M : (ns,nt) ndarray, float64 loss matrix numItermax : int, optional (default=100000) The maximum number of iterations before stopping the optimization algorithm if it has not converged. log: boolean, optional (default=False) If True, returns a dictionary containing the cost and dual variables. Otherwise returns only the optimal transportation cost. return_matrix: boolean, optional (default=False) If True, returns the optimal transportation matrix in the log. Returns ------- gamma: (ns x nt) ndarray Optimal transportation matrix for the given parameters log: dict If input log is true, a dictionary containing the cost and dual variables and exit status Examples -------- Simple example with obvious solution. The function emd accepts lists and perform automatic conversion to numpy arrays >>> import ot >>> a=[.5,.5] >>> b=[.5,.5] >>> M=[[0.,1.],[1.,0.]] >>> ot.emd2(a,b,M) 0.0 References ---------- .. [1] Bonneel, N., Van De Panne, M., Paris, S., & Heidrich, W. (2011, December). Displacement interpolation using Lagrangian mass transport. In ACM Transactions on Graphics (TOG) (Vol. 30, No. 6, p. 158). ACM. See Also -------- ot.bregman.sinkhorn : Entropic regularized OT ot.optim.cg : General regularized OT""" a = np.asarray(a, dtype=np.float64) b = np.asarray(b, dtype=np.float64) M = np.asarray(M, dtype=np.float64) # if empty array given then use unifor distributions if len(a) == 0: a = np.ones((M.shape[0],), dtype=np.float64) / M.shape[0] if len(b) == 0: b = np.ones((M.shape[1],), dtype=np.float64) / M.shape[1] if log or return_matrix: def f(b): G, cost, u, v, resultCode = emd_c(a, b, M, numItermax) result_code_string = check_result(resultCode) log = {} if return_matrix: log['G'] = G log['u'] = u log['v'] = v log['warning'] = result_code_string log['result_code'] = resultCode return [cost, log] else: def f(b): G, cost, u, v, result_code = emd_c(a, b, M, numItermax) check_result(result_code) return cost if len(b.shape) == 1: return f(b) nb = b.shape[1] res = parmap(f, [b[:, i] for i in range(nb)], processes) return res
python
def emd2(a, b, M, processes=multiprocessing.cpu_count(), numItermax=100000, log=False, return_matrix=False): a = np.asarray(a, dtype=np.float64) b = np.asarray(b, dtype=np.float64) M = np.asarray(M, dtype=np.float64) # if empty array given then use unifor distributions if len(a) == 0: a = np.ones((M.shape[0],), dtype=np.float64) / M.shape[0] if len(b) == 0: b = np.ones((M.shape[1],), dtype=np.float64) / M.shape[1] if log or return_matrix: def f(b): G, cost, u, v, resultCode = emd_c(a, b, M, numItermax) result_code_string = check_result(resultCode) log = {} if return_matrix: log['G'] = G log['u'] = u log['v'] = v log['warning'] = result_code_string log['result_code'] = resultCode return [cost, log] else: def f(b): G, cost, u, v, result_code = emd_c(a, b, M, numItermax) check_result(result_code) return cost if len(b.shape) == 1: return f(b) nb = b.shape[1] res = parmap(f, [b[:, i] for i in range(nb)], processes) return res
[ "def", "emd2", "(", "a", ",", "b", ",", "M", ",", "processes", "=", "multiprocessing", ".", "cpu_count", "(", ")", ",", "numItermax", "=", "100000", ",", "log", "=", "False", ",", "return_matrix", "=", "False", ")", ":", "a", "=", "np", ".", "asarr...
Solves the Earth Movers distance problem and returns the loss .. math:: \gamma = arg\min_\gamma <\gamma,M>_F s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - M is the metric cost matrix - a and b are the sample weights Uses the algorithm proposed in [1]_ Parameters ---------- a : (ns,) ndarray, float64 Source histogram (uniform weigth if empty list) b : (nt,) ndarray, float64 Target histogram (uniform weigth if empty list) M : (ns,nt) ndarray, float64 loss matrix numItermax : int, optional (default=100000) The maximum number of iterations before stopping the optimization algorithm if it has not converged. log: boolean, optional (default=False) If True, returns a dictionary containing the cost and dual variables. Otherwise returns only the optimal transportation cost. return_matrix: boolean, optional (default=False) If True, returns the optimal transportation matrix in the log. Returns ------- gamma: (ns x nt) ndarray Optimal transportation matrix for the given parameters log: dict If input log is true, a dictionary containing the cost and dual variables and exit status Examples -------- Simple example with obvious solution. The function emd accepts lists and perform automatic conversion to numpy arrays >>> import ot >>> a=[.5,.5] >>> b=[.5,.5] >>> M=[[0.,1.],[1.,0.]] >>> ot.emd2(a,b,M) 0.0 References ---------- .. [1] Bonneel, N., Van De Panne, M., Paris, S., & Heidrich, W. (2011, December). Displacement interpolation using Lagrangian mass transport. In ACM Transactions on Graphics (TOG) (Vol. 30, No. 6, p. 158). ACM. See Also -------- ot.bregman.sinkhorn : Entropic regularized OT ot.optim.cg : General regularized OT
[ "Solves", "the", "Earth", "Movers", "distance", "problem", "and", "returns", "the", "loss" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/lp/__init__.py#L116-L219
240,919
rflamary/POT
ot/da.py
sinkhorn_l1l2_gl
def sinkhorn_l1l2_gl(a, labels_a, b, M, reg, eta=0.1, numItermax=10, numInnerItermax=200, stopInnerThr=1e-9, verbose=False, log=False): """ Solve the entropic regularization optimal transport problem with group lasso regularization The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega_e(\gamma)+ \eta \Omega_g(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - M is the (ns,nt) metric cost matrix - :math:`\Omega_e` is the entropic regularization term :math:`\Omega_e(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - :math:`\Omega_g` is the group lasso regulaization term :math:`\Omega_g(\gamma)=\sum_{i,c} \|\gamma_{i,\mathcal{I}_c}\|^2` where :math:`\mathcal{I}_c` are the index of samples from class c in the source domain. - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is the generalised conditional gradient as proposed in [5]_ [7]_ Parameters ---------- a : np.ndarray (ns,) samples weights in the source domain labels_a : np.ndarray (ns,) labels of samples in the source domain b : np.ndarray (nt,) samples in the target domain M : np.ndarray (ns,nt) loss matrix reg : float Regularization term for entropic regularization >0 eta : float, optional Regularization term for group lasso regularization >0 numItermax : int, optional Max number of iterations numInnerItermax : int, optional Max number of iterations (inner sinkhorn solver) stopInnerThr : float, optional Stop threshold on error (inner sinkhorn solver) (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters References ---------- .. [5] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy, "Optimal Transport for Domain Adaptation," in IEEE Transactions on Pattern Analysis and Machine Intelligence , vol.PP, no.99, pp.1-1 .. [7] Rakotomamonjy, A., Flamary, R., & Courty, N. (2015). Generalized conditional gradient: analysis of convergence and applications. arXiv preprint arXiv:1510.06567. See Also -------- ot.optim.gcg : Generalized conditional gradient for OT problems """ lstlab = np.unique(labels_a) def f(G): res = 0 for i in range(G.shape[1]): for lab in lstlab: temp = G[labels_a == lab, i] res += np.linalg.norm(temp) return res def df(G): W = np.zeros(G.shape) for i in range(G.shape[1]): for lab in lstlab: temp = G[labels_a == lab, i] n = np.linalg.norm(temp) if n: W[labels_a == lab, i] = temp / n return W return gcg(a, b, M, reg, eta, f, df, G0=None, numItermax=numItermax, numInnerItermax=numInnerItermax, stopThr=stopInnerThr, verbose=verbose, log=log)
python
def sinkhorn_l1l2_gl(a, labels_a, b, M, reg, eta=0.1, numItermax=10, numInnerItermax=200, stopInnerThr=1e-9, verbose=False, log=False): lstlab = np.unique(labels_a) def f(G): res = 0 for i in range(G.shape[1]): for lab in lstlab: temp = G[labels_a == lab, i] res += np.linalg.norm(temp) return res def df(G): W = np.zeros(G.shape) for i in range(G.shape[1]): for lab in lstlab: temp = G[labels_a == lab, i] n = np.linalg.norm(temp) if n: W[labels_a == lab, i] = temp / n return W return gcg(a, b, M, reg, eta, f, df, G0=None, numItermax=numItermax, numInnerItermax=numInnerItermax, stopThr=stopInnerThr, verbose=verbose, log=log)
[ "def", "sinkhorn_l1l2_gl", "(", "a", ",", "labels_a", ",", "b", ",", "M", ",", "reg", ",", "eta", "=", "0.1", ",", "numItermax", "=", "10", ",", "numInnerItermax", "=", "200", ",", "stopInnerThr", "=", "1e-9", ",", "verbose", "=", "False", ",", "log"...
Solve the entropic regularization optimal transport problem with group lasso regularization The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega_e(\gamma)+ \eta \Omega_g(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - M is the (ns,nt) metric cost matrix - :math:`\Omega_e` is the entropic regularization term :math:`\Omega_e(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - :math:`\Omega_g` is the group lasso regulaization term :math:`\Omega_g(\gamma)=\sum_{i,c} \|\gamma_{i,\mathcal{I}_c}\|^2` where :math:`\mathcal{I}_c` are the index of samples from class c in the source domain. - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is the generalised conditional gradient as proposed in [5]_ [7]_ Parameters ---------- a : np.ndarray (ns,) samples weights in the source domain labels_a : np.ndarray (ns,) labels of samples in the source domain b : np.ndarray (nt,) samples in the target domain M : np.ndarray (ns,nt) loss matrix reg : float Regularization term for entropic regularization >0 eta : float, optional Regularization term for group lasso regularization >0 numItermax : int, optional Max number of iterations numInnerItermax : int, optional Max number of iterations (inner sinkhorn solver) stopInnerThr : float, optional Stop threshold on error (inner sinkhorn solver) (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters References ---------- .. [5] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy, "Optimal Transport for Domain Adaptation," in IEEE Transactions on Pattern Analysis and Machine Intelligence , vol.PP, no.99, pp.1-1 .. [7] Rakotomamonjy, A., Flamary, R., & Courty, N. (2015). Generalized conditional gradient: analysis of convergence and applications. arXiv preprint arXiv:1510.06567. See Also -------- ot.optim.gcg : Generalized conditional gradient for OT problems
[ "Solve", "the", "entropic", "regularization", "optimal", "transport", "problem", "with", "group", "lasso", "regularization" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/da.py#L134-L238
240,920
rflamary/POT
ot/da.py
OT_mapping_linear
def OT_mapping_linear(xs, xt, reg=1e-6, ws=None, wt=None, bias=True, log=False): """ return OT linear operator between samples The function estimates the optimal linear operator that aligns the two empirical distributions. This is equivalent to estimating the closed form mapping between two Gaussian distributions :math:`N(\mu_s,\Sigma_s)` and :math:`N(\mu_t,\Sigma_t)` as proposed in [14] and discussed in remark 2.29 in [15]. The linear operator from source to target :math:`M` .. math:: M(x)=Ax+b where : .. math:: A=\Sigma_s^{-1/2}(\Sigma_s^{1/2}\Sigma_t\Sigma_s^{1/2})^{1/2} \Sigma_s^{-1/2} .. math:: b=\mu_t-A\mu_s Parameters ---------- xs : np.ndarray (ns,d) samples in the source domain xt : np.ndarray (nt,d) samples in the target domain reg : float,optional regularization added to the diagonals of convariances (>0) ws : np.ndarray (ns,1), optional weights for the source samples wt : np.ndarray (ns,1), optional weights for the target samples bias: boolean, optional estimate bias b else b=0 (default:True) log : bool, optional record log if True Returns ------- A : (d x d) ndarray Linear operator b : (1 x d) ndarray bias log : dict log dictionary return only if log==True in parameters References ---------- .. [14] Knott, M. and Smith, C. S. "On the optimal mapping of distributions", Journal of Optimization Theory and Applications Vol 43, 1984 .. [15] Peyré, G., & Cuturi, M. (2017). "Computational Optimal Transport", 2018. """ d = xs.shape[1] if bias: mxs = xs.mean(0, keepdims=True) mxt = xt.mean(0, keepdims=True) xs = xs - mxs xt = xt - mxt else: mxs = np.zeros((1, d)) mxt = np.zeros((1, d)) if ws is None: ws = np.ones((xs.shape[0], 1)) / xs.shape[0] if wt is None: wt = np.ones((xt.shape[0], 1)) / xt.shape[0] Cs = (xs * ws).T.dot(xs) / ws.sum() + reg * np.eye(d) Ct = (xt * wt).T.dot(xt) / wt.sum() + reg * np.eye(d) Cs12 = linalg.sqrtm(Cs) Cs_12 = linalg.inv(Cs12) M0 = linalg.sqrtm(Cs12.dot(Ct.dot(Cs12))) A = Cs_12.dot(M0.dot(Cs_12)) b = mxt - mxs.dot(A) if log: log = {} log['Cs'] = Cs log['Ct'] = Ct log['Cs12'] = Cs12 log['Cs_12'] = Cs_12 return A, b, log else: return A, b
python
def OT_mapping_linear(xs, xt, reg=1e-6, ws=None, wt=None, bias=True, log=False): d = xs.shape[1] if bias: mxs = xs.mean(0, keepdims=True) mxt = xt.mean(0, keepdims=True) xs = xs - mxs xt = xt - mxt else: mxs = np.zeros((1, d)) mxt = np.zeros((1, d)) if ws is None: ws = np.ones((xs.shape[0], 1)) / xs.shape[0] if wt is None: wt = np.ones((xt.shape[0], 1)) / xt.shape[0] Cs = (xs * ws).T.dot(xs) / ws.sum() + reg * np.eye(d) Ct = (xt * wt).T.dot(xt) / wt.sum() + reg * np.eye(d) Cs12 = linalg.sqrtm(Cs) Cs_12 = linalg.inv(Cs12) M0 = linalg.sqrtm(Cs12.dot(Ct.dot(Cs12))) A = Cs_12.dot(M0.dot(Cs_12)) b = mxt - mxs.dot(A) if log: log = {} log['Cs'] = Cs log['Ct'] = Ct log['Cs12'] = Cs12 log['Cs_12'] = Cs_12 return A, b, log else: return A, b
[ "def", "OT_mapping_linear", "(", "xs", ",", "xt", ",", "reg", "=", "1e-6", ",", "ws", "=", "None", ",", "wt", "=", "None", ",", "bias", "=", "True", ",", "log", "=", "False", ")", ":", "d", "=", "xs", ".", "shape", "[", "1", "]", "if", "bias"...
return OT linear operator between samples The function estimates the optimal linear operator that aligns the two empirical distributions. This is equivalent to estimating the closed form mapping between two Gaussian distributions :math:`N(\mu_s,\Sigma_s)` and :math:`N(\mu_t,\Sigma_t)` as proposed in [14] and discussed in remark 2.29 in [15]. The linear operator from source to target :math:`M` .. math:: M(x)=Ax+b where : .. math:: A=\Sigma_s^{-1/2}(\Sigma_s^{1/2}\Sigma_t\Sigma_s^{1/2})^{1/2} \Sigma_s^{-1/2} .. math:: b=\mu_t-A\mu_s Parameters ---------- xs : np.ndarray (ns,d) samples in the source domain xt : np.ndarray (nt,d) samples in the target domain reg : float,optional regularization added to the diagonals of convariances (>0) ws : np.ndarray (ns,1), optional weights for the source samples wt : np.ndarray (ns,1), optional weights for the target samples bias: boolean, optional estimate bias b else b=0 (default:True) log : bool, optional record log if True Returns ------- A : (d x d) ndarray Linear operator b : (1 x d) ndarray bias log : dict log dictionary return only if log==True in parameters References ---------- .. [14] Knott, M. and Smith, C. S. "On the optimal mapping of distributions", Journal of Optimization Theory and Applications Vol 43, 1984 .. [15] Peyré, G., & Cuturi, M. (2017). "Computational Optimal Transport", 2018.
[ "return", "OT", "linear", "operator", "between", "samples" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/da.py#L639-L740
240,921
rflamary/POT
ot/gpu/utils.py
euclidean_distances
def euclidean_distances(a, b, squared=False, to_numpy=True): """ Compute the pairwise euclidean distance between matrices a and b. If the input matrix are in numpy format, they will be uploaded to the GPU first which can incur significant time overhead. Parameters ---------- a : np.ndarray (n, f) first matrix b : np.ndarray (m, f) second matrix to_numpy : boolean, optional (default True) If true convert back the GPU array result to numpy format. squared : boolean, optional (default False) if True, return squared euclidean distance matrix Returns ------- c : (n x m) np.ndarray or cupy.ndarray pairwise euclidean distance distance matrix """ a, b = to_gpu(a, b) a2 = np.sum(np.square(a), 1) b2 = np.sum(np.square(b), 1) c = -2 * np.dot(a, b.T) c += a2[:, None] c += b2[None, :] if not squared: np.sqrt(c, out=c) if to_numpy: return to_np(c) else: return c
python
def euclidean_distances(a, b, squared=False, to_numpy=True): a, b = to_gpu(a, b) a2 = np.sum(np.square(a), 1) b2 = np.sum(np.square(b), 1) c = -2 * np.dot(a, b.T) c += a2[:, None] c += b2[None, :] if not squared: np.sqrt(c, out=c) if to_numpy: return to_np(c) else: return c
[ "def", "euclidean_distances", "(", "a", ",", "b", ",", "squared", "=", "False", ",", "to_numpy", "=", "True", ")", ":", "a", ",", "b", "=", "to_gpu", "(", "a", ",", "b", ")", "a2", "=", "np", ".", "sum", "(", "np", ".", "square", "(", "a", ")...
Compute the pairwise euclidean distance between matrices a and b. If the input matrix are in numpy format, they will be uploaded to the GPU first which can incur significant time overhead. Parameters ---------- a : np.ndarray (n, f) first matrix b : np.ndarray (m, f) second matrix to_numpy : boolean, optional (default True) If true convert back the GPU array result to numpy format. squared : boolean, optional (default False) if True, return squared euclidean distance matrix Returns ------- c : (n x m) np.ndarray or cupy.ndarray pairwise euclidean distance distance matrix
[ "Compute", "the", "pairwise", "euclidean", "distance", "between", "matrices", "a", "and", "b", "." ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/gpu/utils.py#L16-L54
240,922
rflamary/POT
ot/gpu/utils.py
dist
def dist(x1, x2=None, metric='sqeuclidean', to_numpy=True): """Compute distance between samples in x1 and x2 on gpu Parameters ---------- x1 : np.array (n1,d) matrix with n1 samples of size d x2 : np.array (n2,d), optional matrix with n2 samples of size d (if None then x2=x1) metric : str Metric from 'sqeuclidean', 'euclidean', Returns ------- M : np.array (n1,n2) distance matrix computed with given metric """ if x2 is None: x2 = x1 if metric == "sqeuclidean": return euclidean_distances(x1, x2, squared=True, to_numpy=to_numpy) elif metric == "euclidean": return euclidean_distances(x1, x2, squared=False, to_numpy=to_numpy) else: raise NotImplementedError
python
def dist(x1, x2=None, metric='sqeuclidean', to_numpy=True): if x2 is None: x2 = x1 if metric == "sqeuclidean": return euclidean_distances(x1, x2, squared=True, to_numpy=to_numpy) elif metric == "euclidean": return euclidean_distances(x1, x2, squared=False, to_numpy=to_numpy) else: raise NotImplementedError
[ "def", "dist", "(", "x1", ",", "x2", "=", "None", ",", "metric", "=", "'sqeuclidean'", ",", "to_numpy", "=", "True", ")", ":", "if", "x2", "is", "None", ":", "x2", "=", "x1", "if", "metric", "==", "\"sqeuclidean\"", ":", "return", "euclidean_distances"...
Compute distance between samples in x1 and x2 on gpu Parameters ---------- x1 : np.array (n1,d) matrix with n1 samples of size d x2 : np.array (n2,d), optional matrix with n2 samples of size d (if None then x2=x1) metric : str Metric from 'sqeuclidean', 'euclidean', Returns ------- M : np.array (n1,n2) distance matrix computed with given metric
[ "Compute", "distance", "between", "samples", "in", "x1", "and", "x2", "on", "gpu" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/gpu/utils.py#L57-L85
240,923
rflamary/POT
ot/gpu/utils.py
to_gpu
def to_gpu(*args): """ Upload numpy arrays to GPU and return them""" if len(args) > 1: return (cp.asarray(x) for x in args) else: return cp.asarray(args[0])
python
def to_gpu(*args): if len(args) > 1: return (cp.asarray(x) for x in args) else: return cp.asarray(args[0])
[ "def", "to_gpu", "(", "*", "args", ")", ":", "if", "len", "(", "args", ")", ">", "1", ":", "return", "(", "cp", ".", "asarray", "(", "x", ")", "for", "x", "in", "args", ")", "else", ":", "return", "cp", ".", "asarray", "(", "args", "[", "0", ...
Upload numpy arrays to GPU and return them
[ "Upload", "numpy", "arrays", "to", "GPU", "and", "return", "them" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/gpu/utils.py#L88-L93
240,924
rflamary/POT
ot/gpu/utils.py
to_np
def to_np(*args): """ convert GPU arras to numpy and return them""" if len(args) > 1: return (cp.asnumpy(x) for x in args) else: return cp.asnumpy(args[0])
python
def to_np(*args): if len(args) > 1: return (cp.asnumpy(x) for x in args) else: return cp.asnumpy(args[0])
[ "def", "to_np", "(", "*", "args", ")", ":", "if", "len", "(", "args", ")", ">", "1", ":", "return", "(", "cp", ".", "asnumpy", "(", "x", ")", "for", "x", "in", "args", ")", "else", ":", "return", "cp", ".", "asnumpy", "(", "args", "[", "0", ...
convert GPU arras to numpy and return them
[ "convert", "GPU", "arras", "to", "numpy", "and", "return", "them" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/gpu/utils.py#L96-L101
240,925
rflamary/POT
ot/lp/cvx.py
scipy_sparse_to_spmatrix
def scipy_sparse_to_spmatrix(A): """Efficient conversion from scipy sparse matrix to cvxopt sparse matrix""" coo = A.tocoo() SP = spmatrix(coo.data.tolist(), coo.row.tolist(), coo.col.tolist(), size=A.shape) return SP
python
def scipy_sparse_to_spmatrix(A): coo = A.tocoo() SP = spmatrix(coo.data.tolist(), coo.row.tolist(), coo.col.tolist(), size=A.shape) return SP
[ "def", "scipy_sparse_to_spmatrix", "(", "A", ")", ":", "coo", "=", "A", ".", "tocoo", "(", ")", "SP", "=", "spmatrix", "(", "coo", ".", "data", ".", "tolist", "(", ")", ",", "coo", ".", "row", ".", "tolist", "(", ")", ",", "coo", ".", "col", "....
Efficient conversion from scipy sparse matrix to cvxopt sparse matrix
[ "Efficient", "conversion", "from", "scipy", "sparse", "matrix", "to", "cvxopt", "sparse", "matrix" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/lp/cvx.py#L22-L26
240,926
rflamary/POT
ot/optim.py
line_search_armijo
def line_search_armijo(f, xk, pk, gfk, old_fval, args=(), c1=1e-4, alpha0=0.99): """ Armijo linesearch function that works with matrices find an approximate minimum of f(xk+alpha*pk) that satifies the armijo conditions. Parameters ---------- f : function loss function xk : np.ndarray initial position pk : np.ndarray descent direction gfk : np.ndarray gradient of f at xk old_fval : float loss value at xk args : tuple, optional arguments given to f c1 : float, optional c1 const in armijo rule (>0) alpha0 : float, optional initial step (>0) Returns ------- alpha : float step that satisfy armijo conditions fc : int nb of function call fa : float loss value at step alpha """ xk = np.atleast_1d(xk) fc = [0] def phi(alpha1): fc[0] += 1 return f(xk + alpha1 * pk, *args) if old_fval is None: phi0 = phi(0.) else: phi0 = old_fval derphi0 = np.sum(pk * gfk) # Quickfix for matrices alpha, phi1 = scalar_search_armijo( phi, phi0, derphi0, c1=c1, alpha0=alpha0) return alpha, fc[0], phi1
python
def line_search_armijo(f, xk, pk, gfk, old_fval, args=(), c1=1e-4, alpha0=0.99): xk = np.atleast_1d(xk) fc = [0] def phi(alpha1): fc[0] += 1 return f(xk + alpha1 * pk, *args) if old_fval is None: phi0 = phi(0.) else: phi0 = old_fval derphi0 = np.sum(pk * gfk) # Quickfix for matrices alpha, phi1 = scalar_search_armijo( phi, phi0, derphi0, c1=c1, alpha0=alpha0) return alpha, fc[0], phi1
[ "def", "line_search_armijo", "(", "f", ",", "xk", ",", "pk", ",", "gfk", ",", "old_fval", ",", "args", "=", "(", ")", ",", "c1", "=", "1e-4", ",", "alpha0", "=", "0.99", ")", ":", "xk", "=", "np", ".", "atleast_1d", "(", "xk", ")", "fc", "=", ...
Armijo linesearch function that works with matrices find an approximate minimum of f(xk+alpha*pk) that satifies the armijo conditions. Parameters ---------- f : function loss function xk : np.ndarray initial position pk : np.ndarray descent direction gfk : np.ndarray gradient of f at xk old_fval : float loss value at xk args : tuple, optional arguments given to f c1 : float, optional c1 const in armijo rule (>0) alpha0 : float, optional initial step (>0) Returns ------- alpha : float step that satisfy armijo conditions fc : int nb of function call fa : float loss value at step alpha
[ "Armijo", "linesearch", "function", "that", "works", "with", "matrices" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/optim.py#L18-L72
240,927
rflamary/POT
ot/optim.py
cg
def cg(a, b, M, reg, f, df, G0=None, numItermax=200, stopThr=1e-9, verbose=False, log=False): """ Solve the general regularized OT problem with conditional gradient The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg*f(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - M is the (ns,nt) metric cost matrix - :math:`f` is the regularization term ( and df is its gradient) - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is conditional gradient as discussed in [1]_ Parameters ---------- a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) samples in the target domain M : np.ndarray (ns,nt) loss matrix reg : float Regularization term >0 G0 : np.ndarray (ns,nt), optional initial guess (default is indep joint density) numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters References ---------- .. [1] Ferradans, S., Papadakis, N., Peyré, G., & Aujol, J. F. (2014). Regularized discrete optimal transport. SIAM Journal on Imaging Sciences, 7(3), 1853-1882. See Also -------- ot.lp.emd : Unregularized optimal ransport ot.bregman.sinkhorn : Entropic regularized optimal transport """ loop = 1 if log: log = {'loss': []} if G0 is None: G = np.outer(a, b) else: G = G0 def cost(G): return np.sum(M * G) + reg * f(G) f_val = cost(G) if log: log['loss'].append(f_val) it = 0 if verbose: print('{:5s}|{:12s}|{:8s}'.format( 'It.', 'Loss', 'Delta loss') + '\n' + '-' * 32) print('{:5d}|{:8e}|{:8e}'.format(it, f_val, 0)) while loop: it += 1 old_fval = f_val # problem linearization Mi = M + reg * df(G) # set M positive Mi += Mi.min() # solve linear program Gc = emd(a, b, Mi) deltaG = Gc - G # line search alpha, fc, f_val = line_search_armijo(cost, G, deltaG, Mi, f_val) G = G + alpha * deltaG # test convergence if it >= numItermax: loop = 0 delta_fval = (f_val - old_fval) / abs(f_val) if abs(delta_fval) < stopThr: loop = 0 if log: log['loss'].append(f_val) if verbose: if it % 20 == 0: print('{:5s}|{:12s}|{:8s}'.format( 'It.', 'Loss', 'Delta loss') + '\n' + '-' * 32) print('{:5d}|{:8e}|{:8e}'.format(it, f_val, delta_fval)) if log: return G, log else: return G
python
def cg(a, b, M, reg, f, df, G0=None, numItermax=200, stopThr=1e-9, verbose=False, log=False): loop = 1 if log: log = {'loss': []} if G0 is None: G = np.outer(a, b) else: G = G0 def cost(G): return np.sum(M * G) + reg * f(G) f_val = cost(G) if log: log['loss'].append(f_val) it = 0 if verbose: print('{:5s}|{:12s}|{:8s}'.format( 'It.', 'Loss', 'Delta loss') + '\n' + '-' * 32) print('{:5d}|{:8e}|{:8e}'.format(it, f_val, 0)) while loop: it += 1 old_fval = f_val # problem linearization Mi = M + reg * df(G) # set M positive Mi += Mi.min() # solve linear program Gc = emd(a, b, Mi) deltaG = Gc - G # line search alpha, fc, f_val = line_search_armijo(cost, G, deltaG, Mi, f_val) G = G + alpha * deltaG # test convergence if it >= numItermax: loop = 0 delta_fval = (f_val - old_fval) / abs(f_val) if abs(delta_fval) < stopThr: loop = 0 if log: log['loss'].append(f_val) if verbose: if it % 20 == 0: print('{:5s}|{:12s}|{:8s}'.format( 'It.', 'Loss', 'Delta loss') + '\n' + '-' * 32) print('{:5d}|{:8e}|{:8e}'.format(it, f_val, delta_fval)) if log: return G, log else: return G
[ "def", "cg", "(", "a", ",", "b", ",", "M", ",", "reg", ",", "f", ",", "df", ",", "G0", "=", "None", ",", "numItermax", "=", "200", ",", "stopThr", "=", "1e-9", ",", "verbose", "=", "False", ",", "log", "=", "False", ")", ":", "loop", "=", "...
Solve the general regularized OT problem with conditional gradient The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg*f(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - M is the (ns,nt) metric cost matrix - :math:`f` is the regularization term ( and df is its gradient) - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is conditional gradient as discussed in [1]_ Parameters ---------- a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) samples in the target domain M : np.ndarray (ns,nt) loss matrix reg : float Regularization term >0 G0 : np.ndarray (ns,nt), optional initial guess (default is indep joint density) numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters References ---------- .. [1] Ferradans, S., Papadakis, N., Peyré, G., & Aujol, J. F. (2014). Regularized discrete optimal transport. SIAM Journal on Imaging Sciences, 7(3), 1853-1882. See Also -------- ot.lp.emd : Unregularized optimal ransport ot.bregman.sinkhorn : Entropic regularized optimal transport
[ "Solve", "the", "general", "regularized", "OT", "problem", "with", "conditional", "gradient" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/optim.py#L75-L204
240,928
rflamary/POT
ot/optim.py
gcg
def gcg(a, b, M, reg1, reg2, f, df, G0=None, numItermax=10, numInnerItermax=200, stopThr=1e-9, verbose=False, log=False): """ Solve the general regularized OT problem with the generalized conditional gradient The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg1\cdot\Omega(\gamma) + reg2\cdot f(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - :math:`f` is the regularization term ( and df is its gradient) - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is the generalized conditional gradient as discussed in [5,7]_ Parameters ---------- a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) samples in the target domain M : np.ndarray (ns,nt) loss matrix reg1 : float Entropic Regularization term >0 reg2 : float Second Regularization term >0 G0 : np.ndarray (ns,nt), optional initial guess (default is indep joint density) numItermax : int, optional Max number of iterations numInnerItermax : int, optional Max number of iterations of Sinkhorn stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters References ---------- .. [5] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy, "Optimal Transport for Domain Adaptation," in IEEE Transactions on Pattern Analysis and Machine Intelligence , vol.PP, no.99, pp.1-1 .. [7] Rakotomamonjy, A., Flamary, R., & Courty, N. (2015). Generalized conditional gradient: analysis of convergence and applications. arXiv preprint arXiv:1510.06567. See Also -------- ot.optim.cg : conditional gradient """ loop = 1 if log: log = {'loss': []} if G0 is None: G = np.outer(a, b) else: G = G0 def cost(G): return np.sum(M * G) + reg1 * np.sum(G * np.log(G)) + reg2 * f(G) f_val = cost(G) if log: log['loss'].append(f_val) it = 0 if verbose: print('{:5s}|{:12s}|{:8s}'.format( 'It.', 'Loss', 'Delta loss') + '\n' + '-' * 32) print('{:5d}|{:8e}|{:8e}'.format(it, f_val, 0)) while loop: it += 1 old_fval = f_val # problem linearization Mi = M + reg2 * df(G) # solve linear program with Sinkhorn # Gc = sinkhorn_stabilized(a,b, Mi, reg1, numItermax = numInnerItermax) Gc = sinkhorn(a, b, Mi, reg1, numItermax=numInnerItermax) deltaG = Gc - G # line search dcost = Mi + reg1 * (1 + np.log(G)) # ?? alpha, fc, f_val = line_search_armijo(cost, G, deltaG, dcost, f_val) G = G + alpha * deltaG # test convergence if it >= numItermax: loop = 0 delta_fval = (f_val - old_fval) / abs(f_val) if abs(delta_fval) < stopThr: loop = 0 if log: log['loss'].append(f_val) if verbose: if it % 20 == 0: print('{:5s}|{:12s}|{:8s}'.format( 'It.', 'Loss', 'Delta loss') + '\n' + '-' * 32) print('{:5d}|{:8e}|{:8e}'.format(it, f_val, delta_fval)) if log: return G, log else: return G
python
def gcg(a, b, M, reg1, reg2, f, df, G0=None, numItermax=10, numInnerItermax=200, stopThr=1e-9, verbose=False, log=False): loop = 1 if log: log = {'loss': []} if G0 is None: G = np.outer(a, b) else: G = G0 def cost(G): return np.sum(M * G) + reg1 * np.sum(G * np.log(G)) + reg2 * f(G) f_val = cost(G) if log: log['loss'].append(f_val) it = 0 if verbose: print('{:5s}|{:12s}|{:8s}'.format( 'It.', 'Loss', 'Delta loss') + '\n' + '-' * 32) print('{:5d}|{:8e}|{:8e}'.format(it, f_val, 0)) while loop: it += 1 old_fval = f_val # problem linearization Mi = M + reg2 * df(G) # solve linear program with Sinkhorn # Gc = sinkhorn_stabilized(a,b, Mi, reg1, numItermax = numInnerItermax) Gc = sinkhorn(a, b, Mi, reg1, numItermax=numInnerItermax) deltaG = Gc - G # line search dcost = Mi + reg1 * (1 + np.log(G)) # ?? alpha, fc, f_val = line_search_armijo(cost, G, deltaG, dcost, f_val) G = G + alpha * deltaG # test convergence if it >= numItermax: loop = 0 delta_fval = (f_val - old_fval) / abs(f_val) if abs(delta_fval) < stopThr: loop = 0 if log: log['loss'].append(f_val) if verbose: if it % 20 == 0: print('{:5s}|{:12s}|{:8s}'.format( 'It.', 'Loss', 'Delta loss') + '\n' + '-' * 32) print('{:5d}|{:8e}|{:8e}'.format(it, f_val, delta_fval)) if log: return G, log else: return G
[ "def", "gcg", "(", "a", ",", "b", ",", "M", ",", "reg1", ",", "reg2", ",", "f", ",", "df", ",", "G0", "=", "None", ",", "numItermax", "=", "10", ",", "numInnerItermax", "=", "200", ",", "stopThr", "=", "1e-9", ",", "verbose", "=", "False", ",",...
Solve the general regularized OT problem with the generalized conditional gradient The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg1\cdot\Omega(\gamma) + reg2\cdot f(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - :math:`f` is the regularization term ( and df is its gradient) - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is the generalized conditional gradient as discussed in [5,7]_ Parameters ---------- a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) samples in the target domain M : np.ndarray (ns,nt) loss matrix reg1 : float Entropic Regularization term >0 reg2 : float Second Regularization term >0 G0 : np.ndarray (ns,nt), optional initial guess (default is indep joint density) numItermax : int, optional Max number of iterations numInnerItermax : int, optional Max number of iterations of Sinkhorn stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters References ---------- .. [5] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy, "Optimal Transport for Domain Adaptation," in IEEE Transactions on Pattern Analysis and Machine Intelligence , vol.PP, no.99, pp.1-1 .. [7] Rakotomamonjy, A., Flamary, R., & Courty, N. (2015). Generalized conditional gradient: analysis of convergence and applications. arXiv preprint arXiv:1510.06567. See Also -------- ot.optim.cg : conditional gradient
[ "Solve", "the", "general", "regularized", "OT", "problem", "with", "the", "generalized", "conditional", "gradient" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/optim.py#L207-L341
240,929
rflamary/POT
ot/smooth.py
projection_simplex
def projection_simplex(V, z=1, axis=None): """ Projection of x onto the simplex, scaled by z P(x; z) = argmin_{y >= 0, sum(y) = z} ||y - x||^2 z: float or array If array, len(z) must be compatible with V axis: None or int - axis=None: project V by P(V.ravel(); z) - axis=1: project each V[i] by P(V[i]; z[i]) - axis=0: project each V[:, j] by P(V[:, j]; z[j]) """ if axis == 1: n_features = V.shape[1] U = np.sort(V, axis=1)[:, ::-1] z = np.ones(len(V)) * z cssv = np.cumsum(U, axis=1) - z[:, np.newaxis] ind = np.arange(n_features) + 1 cond = U - cssv / ind > 0 rho = np.count_nonzero(cond, axis=1) theta = cssv[np.arange(len(V)), rho - 1] / rho return np.maximum(V - theta[:, np.newaxis], 0) elif axis == 0: return projection_simplex(V.T, z, axis=1).T else: V = V.ravel().reshape(1, -1) return projection_simplex(V, z, axis=1).ravel()
python
def projection_simplex(V, z=1, axis=None): if axis == 1: n_features = V.shape[1] U = np.sort(V, axis=1)[:, ::-1] z = np.ones(len(V)) * z cssv = np.cumsum(U, axis=1) - z[:, np.newaxis] ind = np.arange(n_features) + 1 cond = U - cssv / ind > 0 rho = np.count_nonzero(cond, axis=1) theta = cssv[np.arange(len(V)), rho - 1] / rho return np.maximum(V - theta[:, np.newaxis], 0) elif axis == 0: return projection_simplex(V.T, z, axis=1).T else: V = V.ravel().reshape(1, -1) return projection_simplex(V, z, axis=1).ravel()
[ "def", "projection_simplex", "(", "V", ",", "z", "=", "1", ",", "axis", "=", "None", ")", ":", "if", "axis", "==", "1", ":", "n_features", "=", "V", ".", "shape", "[", "1", "]", "U", "=", "np", ".", "sort", "(", "V", ",", "axis", "=", "1", ...
Projection of x onto the simplex, scaled by z P(x; z) = argmin_{y >= 0, sum(y) = z} ||y - x||^2 z: float or array If array, len(z) must be compatible with V axis: None or int - axis=None: project V by P(V.ravel(); z) - axis=1: project each V[i] by P(V[i]; z[i]) - axis=0: project each V[:, j] by P(V[:, j]; z[j])
[ "Projection", "of", "x", "onto", "the", "simplex", "scaled", "by", "z" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/smooth.py#L47-L74
240,930
rflamary/POT
ot/smooth.py
dual_obj_grad
def dual_obj_grad(alpha, beta, a, b, C, regul): """ Compute objective value and gradients of dual objective. Parameters ---------- alpha: array, shape = len(a) beta: array, shape = len(b) Current iterate of dual potentials. a: array, shape = len(a) b: array, shape = len(b) Input histograms (should be non-negative and sum to 1). C: array, shape = len(a) x len(b) Ground cost matrix. regul: Regularization object Should implement a delta_Omega(X) method. Returns ------- obj: float Objective value (higher is better). grad_alpha: array, shape = len(a) Gradient w.r.t. alpha. grad_beta: array, shape = len(b) Gradient w.r.t. beta. """ obj = np.dot(alpha, a) + np.dot(beta, b) grad_alpha = a.copy() grad_beta = b.copy() # X[:, j] = alpha + beta[j] - C[:, j] X = alpha[:, np.newaxis] + beta - C # val.shape = len(b) # G.shape = len(a) x len(b) val, G = regul.delta_Omega(X) obj -= np.sum(val) grad_alpha -= G.sum(axis=1) grad_beta -= G.sum(axis=0) return obj, grad_alpha, grad_beta
python
def dual_obj_grad(alpha, beta, a, b, C, regul): obj = np.dot(alpha, a) + np.dot(beta, b) grad_alpha = a.copy() grad_beta = b.copy() # X[:, j] = alpha + beta[j] - C[:, j] X = alpha[:, np.newaxis] + beta - C # val.shape = len(b) # G.shape = len(a) x len(b) val, G = regul.delta_Omega(X) obj -= np.sum(val) grad_alpha -= G.sum(axis=1) grad_beta -= G.sum(axis=0) return obj, grad_alpha, grad_beta
[ "def", "dual_obj_grad", "(", "alpha", ",", "beta", ",", "a", ",", "b", ",", "C", ",", "regul", ")", ":", "obj", "=", "np", ".", "dot", "(", "alpha", ",", "a", ")", "+", "np", ".", "dot", "(", "beta", ",", "b", ")", "grad_alpha", "=", "a", "...
Compute objective value and gradients of dual objective. Parameters ---------- alpha: array, shape = len(a) beta: array, shape = len(b) Current iterate of dual potentials. a: array, shape = len(a) b: array, shape = len(b) Input histograms (should be non-negative and sum to 1). C: array, shape = len(a) x len(b) Ground cost matrix. regul: Regularization object Should implement a delta_Omega(X) method. Returns ------- obj: float Objective value (higher is better). grad_alpha: array, shape = len(a) Gradient w.r.t. alpha. grad_beta: array, shape = len(b) Gradient w.r.t. beta.
[ "Compute", "objective", "value", "and", "gradients", "of", "dual", "objective", "." ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/smooth.py#L192-L233
240,931
rflamary/POT
ot/smooth.py
solve_dual
def solve_dual(a, b, C, regul, method="L-BFGS-B", tol=1e-3, max_iter=500, verbose=False): """ Solve the "smoothed" dual objective. Parameters ---------- a: array, shape = len(a) b: array, shape = len(b) Input histograms (should be non-negative and sum to 1). C: array, shape = len(a) x len(b) Ground cost matrix. regul: Regularization object Should implement a delta_Omega(X) method. method: str Solver to be used (passed to `scipy.optimize.minimize`). tol: float Tolerance parameter. max_iter: int Maximum number of iterations. Returns ------- alpha: array, shape = len(a) beta: array, shape = len(b) Dual potentials. """ def _func(params): # Unpack alpha and beta. alpha = params[:len(a)] beta = params[len(a):] obj, grad_alpha, grad_beta = dual_obj_grad(alpha, beta, a, b, C, regul) # Pack grad_alpha and grad_beta. grad = np.concatenate((grad_alpha, grad_beta)) # We need to maximize the dual. return -obj, -grad # Unfortunately, `minimize` only supports functions whose argument is a # vector. So, we need to concatenate alpha and beta. alpha_init = np.zeros(len(a)) beta_init = np.zeros(len(b)) params_init = np.concatenate((alpha_init, beta_init)) res = minimize(_func, params_init, method=method, jac=True, tol=tol, options=dict(maxiter=max_iter, disp=verbose)) alpha = res.x[:len(a)] beta = res.x[len(a):] return alpha, beta, res
python
def solve_dual(a, b, C, regul, method="L-BFGS-B", tol=1e-3, max_iter=500, verbose=False): def _func(params): # Unpack alpha and beta. alpha = params[:len(a)] beta = params[len(a):] obj, grad_alpha, grad_beta = dual_obj_grad(alpha, beta, a, b, C, regul) # Pack grad_alpha and grad_beta. grad = np.concatenate((grad_alpha, grad_beta)) # We need to maximize the dual. return -obj, -grad # Unfortunately, `minimize` only supports functions whose argument is a # vector. So, we need to concatenate alpha and beta. alpha_init = np.zeros(len(a)) beta_init = np.zeros(len(b)) params_init = np.concatenate((alpha_init, beta_init)) res = minimize(_func, params_init, method=method, jac=True, tol=tol, options=dict(maxiter=max_iter, disp=verbose)) alpha = res.x[:len(a)] beta = res.x[len(a):] return alpha, beta, res
[ "def", "solve_dual", "(", "a", ",", "b", ",", "C", ",", "regul", ",", "method", "=", "\"L-BFGS-B\"", ",", "tol", "=", "1e-3", ",", "max_iter", "=", "500", ",", "verbose", "=", "False", ")", ":", "def", "_func", "(", "params", ")", ":", "# Unpack al...
Solve the "smoothed" dual objective. Parameters ---------- a: array, shape = len(a) b: array, shape = len(b) Input histograms (should be non-negative and sum to 1). C: array, shape = len(a) x len(b) Ground cost matrix. regul: Regularization object Should implement a delta_Omega(X) method. method: str Solver to be used (passed to `scipy.optimize.minimize`). tol: float Tolerance parameter. max_iter: int Maximum number of iterations. Returns ------- alpha: array, shape = len(a) beta: array, shape = len(b) Dual potentials.
[ "Solve", "the", "smoothed", "dual", "objective", "." ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/smooth.py#L236-L289
240,932
rflamary/POT
ot/smooth.py
semi_dual_obj_grad
def semi_dual_obj_grad(alpha, a, b, C, regul): """ Compute objective value and gradient of semi-dual objective. Parameters ---------- alpha: array, shape = len(a) Current iterate of semi-dual potentials. a: array, shape = len(a) b: array, shape = len(b) Input histograms (should be non-negative and sum to 1). C: array, shape = len(a) x len(b) Ground cost matrix. regul: Regularization object Should implement a max_Omega(X) method. Returns ------- obj: float Objective value (higher is better). grad: array, shape = len(a) Gradient w.r.t. alpha. """ obj = np.dot(alpha, a) grad = a.copy() # X[:, j] = alpha - C[:, j] X = alpha[:, np.newaxis] - C # val.shape = len(b) # G.shape = len(a) x len(b) val, G = regul.max_Omega(X, b) obj -= np.dot(b, val) grad -= np.dot(G, b) return obj, grad
python
def semi_dual_obj_grad(alpha, a, b, C, regul): obj = np.dot(alpha, a) grad = a.copy() # X[:, j] = alpha - C[:, j] X = alpha[:, np.newaxis] - C # val.shape = len(b) # G.shape = len(a) x len(b) val, G = regul.max_Omega(X, b) obj -= np.dot(b, val) grad -= np.dot(G, b) return obj, grad
[ "def", "semi_dual_obj_grad", "(", "alpha", ",", "a", ",", "b", ",", "C", ",", "regul", ")", ":", "obj", "=", "np", ".", "dot", "(", "alpha", ",", "a", ")", "grad", "=", "a", ".", "copy", "(", ")", "# X[:, j] = alpha - C[:, j]", "X", "=", "alpha", ...
Compute objective value and gradient of semi-dual objective. Parameters ---------- alpha: array, shape = len(a) Current iterate of semi-dual potentials. a: array, shape = len(a) b: array, shape = len(b) Input histograms (should be non-negative and sum to 1). C: array, shape = len(a) x len(b) Ground cost matrix. regul: Regularization object Should implement a max_Omega(X) method. Returns ------- obj: float Objective value (higher is better). grad: array, shape = len(a) Gradient w.r.t. alpha.
[ "Compute", "objective", "value", "and", "gradient", "of", "semi", "-", "dual", "objective", "." ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/smooth.py#L292-L328
240,933
rflamary/POT
ot/smooth.py
solve_semi_dual
def solve_semi_dual(a, b, C, regul, method="L-BFGS-B", tol=1e-3, max_iter=500, verbose=False): """ Solve the "smoothed" semi-dual objective. Parameters ---------- a: array, shape = len(a) b: array, shape = len(b) Input histograms (should be non-negative and sum to 1). C: array, shape = len(a) x len(b) Ground cost matrix. regul: Regularization object Should implement a max_Omega(X) method. method: str Solver to be used (passed to `scipy.optimize.minimize`). tol: float Tolerance parameter. max_iter: int Maximum number of iterations. Returns ------- alpha: array, shape = len(a) Semi-dual potentials. """ def _func(alpha): obj, grad = semi_dual_obj_grad(alpha, a, b, C, regul) # We need to maximize the semi-dual. return -obj, -grad alpha_init = np.zeros(len(a)) res = minimize(_func, alpha_init, method=method, jac=True, tol=tol, options=dict(maxiter=max_iter, disp=verbose)) return res.x, res
python
def solve_semi_dual(a, b, C, regul, method="L-BFGS-B", tol=1e-3, max_iter=500, verbose=False): def _func(alpha): obj, grad = semi_dual_obj_grad(alpha, a, b, C, regul) # We need to maximize the semi-dual. return -obj, -grad alpha_init = np.zeros(len(a)) res = minimize(_func, alpha_init, method=method, jac=True, tol=tol, options=dict(maxiter=max_iter, disp=verbose)) return res.x, res
[ "def", "solve_semi_dual", "(", "a", ",", "b", ",", "C", ",", "regul", ",", "method", "=", "\"L-BFGS-B\"", ",", "tol", "=", "1e-3", ",", "max_iter", "=", "500", ",", "verbose", "=", "False", ")", ":", "def", "_func", "(", "alpha", ")", ":", "obj", ...
Solve the "smoothed" semi-dual objective. Parameters ---------- a: array, shape = len(a) b: array, shape = len(b) Input histograms (should be non-negative and sum to 1). C: array, shape = len(a) x len(b) Ground cost matrix. regul: Regularization object Should implement a max_Omega(X) method. method: str Solver to be used (passed to `scipy.optimize.minimize`). tol: float Tolerance parameter. max_iter: int Maximum number of iterations. Returns ------- alpha: array, shape = len(a) Semi-dual potentials.
[ "Solve", "the", "smoothed", "semi", "-", "dual", "objective", "." ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/smooth.py#L331-L368
240,934
rflamary/POT
ot/smooth.py
get_plan_from_dual
def get_plan_from_dual(alpha, beta, C, regul): """ Retrieve optimal transportation plan from optimal dual potentials. Parameters ---------- alpha: array, shape = len(a) beta: array, shape = len(b) Optimal dual potentials. C: array, shape = len(a) x len(b) Ground cost matrix. regul: Regularization object Should implement a delta_Omega(X) method. Returns ------- T: array, shape = len(a) x len(b) Optimal transportation plan. """ X = alpha[:, np.newaxis] + beta - C return regul.delta_Omega(X)[1]
python
def get_plan_from_dual(alpha, beta, C, regul): X = alpha[:, np.newaxis] + beta - C return regul.delta_Omega(X)[1]
[ "def", "get_plan_from_dual", "(", "alpha", ",", "beta", ",", "C", ",", "regul", ")", ":", "X", "=", "alpha", "[", ":", ",", "np", ".", "newaxis", "]", "+", "beta", "-", "C", "return", "regul", ".", "delta_Omega", "(", "X", ")", "[", "1", "]" ]
Retrieve optimal transportation plan from optimal dual potentials. Parameters ---------- alpha: array, shape = len(a) beta: array, shape = len(b) Optimal dual potentials. C: array, shape = len(a) x len(b) Ground cost matrix. regul: Regularization object Should implement a delta_Omega(X) method. Returns ------- T: array, shape = len(a) x len(b) Optimal transportation plan.
[ "Retrieve", "optimal", "transportation", "plan", "from", "optimal", "dual", "potentials", "." ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/smooth.py#L371-L391
240,935
rflamary/POT
ot/smooth.py
get_plan_from_semi_dual
def get_plan_from_semi_dual(alpha, b, C, regul): """ Retrieve optimal transportation plan from optimal semi-dual potentials. Parameters ---------- alpha: array, shape = len(a) Optimal semi-dual potentials. b: array, shape = len(b) Second input histogram (should be non-negative and sum to 1). C: array, shape = len(a) x len(b) Ground cost matrix. regul: Regularization object Should implement a delta_Omega(X) method. Returns ------- T: array, shape = len(a) x len(b) Optimal transportation plan. """ X = alpha[:, np.newaxis] - C return regul.max_Omega(X, b)[1] * b
python
def get_plan_from_semi_dual(alpha, b, C, regul): X = alpha[:, np.newaxis] - C return regul.max_Omega(X, b)[1] * b
[ "def", "get_plan_from_semi_dual", "(", "alpha", ",", "b", ",", "C", ",", "regul", ")", ":", "X", "=", "alpha", "[", ":", ",", "np", ".", "newaxis", "]", "-", "C", "return", "regul", ".", "max_Omega", "(", "X", ",", "b", ")", "[", "1", "]", "*",...
Retrieve optimal transportation plan from optimal semi-dual potentials. Parameters ---------- alpha: array, shape = len(a) Optimal semi-dual potentials. b: array, shape = len(b) Second input histogram (should be non-negative and sum to 1). C: array, shape = len(a) x len(b) Ground cost matrix. regul: Regularization object Should implement a delta_Omega(X) method. Returns ------- T: array, shape = len(a) x len(b) Optimal transportation plan.
[ "Retrieve", "optimal", "transportation", "plan", "from", "optimal", "semi", "-", "dual", "potentials", "." ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/smooth.py#L394-L415
240,936
rflamary/POT
ot/smooth.py
smooth_ot_dual
def smooth_ot_dual(a, b, M, reg, reg_type='l2', method="L-BFGS-B", stopThr=1e-9, numItermax=500, verbose=False, log=False): r""" Solve the regularized OT problem in the dual and return the OT matrix The function solves the smooth relaxed dual formulation (7) in [17]_ : .. math:: \max_{\alpha,\beta}\quad a^T\alpha+b^T\beta-\sum_j\delta_\Omega(\alpha+\beta_j-\mathbf{m}_j) where : - :math:`\mathbf{m}_j` is the jth column of the cost matrix - :math:`\delta_\Omega` is the convex conjugate of the regularization term :math:`\Omega` - a and b are source and target weights (sum to 1) The OT matrix can is reconstructed from the gradient of :math:`\delta_\Omega` (See [17]_ Proposition 1). The optimization algorithm is using gradient decent (L-BFGS by default). Parameters ---------- a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) or np.ndarray (nt,nbb) samples in the target domain, compute sinkhorn with multiple targets and fixed M if b is a matrix (return OT loss + dual variables in log) M : np.ndarray (ns,nt) loss matrix reg : float Regularization term >0 reg_type : str Regularization type, can be the following (default ='l2'): - 'kl' : Kullback Leibler (~ Neg-entropy used in sinkhorn [2]_) - 'l2' : Squared Euclidean regularization method : str Solver to use for scipy.optimize.minimize numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters References ---------- .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013 .. [17] Blondel, M., Seguy, V., & Rolet, A. (2018). Smooth and Sparse Optimal Transport. Proceedings of the Twenty-First International Conference on Artificial Intelligence and Statistics (AISTATS). See Also -------- ot.lp.emd : Unregularized OT ot.sinhorn : Entropic regularized OT ot.optim.cg : General regularized OT """ if reg_type.lower() in ['l2', 'squaredl2']: regul = SquaredL2(gamma=reg) elif reg_type.lower() in ['entropic', 'negentropy', 'kl']: regul = NegEntropy(gamma=reg) else: raise NotImplementedError('Unknown regularization') # solve dual alpha, beta, res = solve_dual(a, b, M, regul, max_iter=numItermax, tol=stopThr, verbose=verbose) # reconstruct transport matrix G = get_plan_from_dual(alpha, beta, M, regul) if log: log = {'alpha': alpha, 'beta': beta, 'res': res} return G, log else: return G
python
def smooth_ot_dual(a, b, M, reg, reg_type='l2', method="L-BFGS-B", stopThr=1e-9, numItermax=500, verbose=False, log=False): r""" Solve the regularized OT problem in the dual and return the OT matrix The function solves the smooth relaxed dual formulation (7) in [17]_ : .. math:: \max_{\alpha,\beta}\quad a^T\alpha+b^T\beta-\sum_j\delta_\Omega(\alpha+\beta_j-\mathbf{m}_j) where : - :math:`\mathbf{m}_j` is the jth column of the cost matrix - :math:`\delta_\Omega` is the convex conjugate of the regularization term :math:`\Omega` - a and b are source and target weights (sum to 1) The OT matrix can is reconstructed from the gradient of :math:`\delta_\Omega` (See [17]_ Proposition 1). The optimization algorithm is using gradient decent (L-BFGS by default). Parameters ---------- a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) or np.ndarray (nt,nbb) samples in the target domain, compute sinkhorn with multiple targets and fixed M if b is a matrix (return OT loss + dual variables in log) M : np.ndarray (ns,nt) loss matrix reg : float Regularization term >0 reg_type : str Regularization type, can be the following (default ='l2'): - 'kl' : Kullback Leibler (~ Neg-entropy used in sinkhorn [2]_) - 'l2' : Squared Euclidean regularization method : str Solver to use for scipy.optimize.minimize numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters References ---------- .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013 .. [17] Blondel, M., Seguy, V., & Rolet, A. (2018). Smooth and Sparse Optimal Transport. Proceedings of the Twenty-First International Conference on Artificial Intelligence and Statistics (AISTATS). See Also -------- ot.lp.emd : Unregularized OT ot.sinhorn : Entropic regularized OT ot.optim.cg : General regularized OT """ if reg_type.lower() in ['l2', 'squaredl2']: regul = SquaredL2(gamma=reg) elif reg_type.lower() in ['entropic', 'negentropy', 'kl']: regul = NegEntropy(gamma=reg) else: raise NotImplementedError('Unknown regularization') # solve dual alpha, beta, res = solve_dual(a, b, M, regul, max_iter=numItermax, tol=stopThr, verbose=verbose) # reconstruct transport matrix G = get_plan_from_dual(alpha, beta, M, regul) if log: log = {'alpha': alpha, 'beta': beta, 'res': res} return G, log else: return G
[ "def", "smooth_ot_dual", "(", "a", ",", "b", ",", "M", ",", "reg", ",", "reg_type", "=", "'l2'", ",", "method", "=", "\"L-BFGS-B\"", ",", "stopThr", "=", "1e-9", ",", "numItermax", "=", "500", ",", "verbose", "=", "False", ",", "log", "=", "False", ...
r""" Solve the regularized OT problem in the dual and return the OT matrix The function solves the smooth relaxed dual formulation (7) in [17]_ : .. math:: \max_{\alpha,\beta}\quad a^T\alpha+b^T\beta-\sum_j\delta_\Omega(\alpha+\beta_j-\mathbf{m}_j) where : - :math:`\mathbf{m}_j` is the jth column of the cost matrix - :math:`\delta_\Omega` is the convex conjugate of the regularization term :math:`\Omega` - a and b are source and target weights (sum to 1) The OT matrix can is reconstructed from the gradient of :math:`\delta_\Omega` (See [17]_ Proposition 1). The optimization algorithm is using gradient decent (L-BFGS by default). Parameters ---------- a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) or np.ndarray (nt,nbb) samples in the target domain, compute sinkhorn with multiple targets and fixed M if b is a matrix (return OT loss + dual variables in log) M : np.ndarray (ns,nt) loss matrix reg : float Regularization term >0 reg_type : str Regularization type, can be the following (default ='l2'): - 'kl' : Kullback Leibler (~ Neg-entropy used in sinkhorn [2]_) - 'l2' : Squared Euclidean regularization method : str Solver to use for scipy.optimize.minimize numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters References ---------- .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013 .. [17] Blondel, M., Seguy, V., & Rolet, A. (2018). Smooth and Sparse Optimal Transport. Proceedings of the Twenty-First International Conference on Artificial Intelligence and Statistics (AISTATS). See Also -------- ot.lp.emd : Unregularized OT ot.sinhorn : Entropic regularized OT ot.optim.cg : General regularized OT
[ "r", "Solve", "the", "regularized", "OT", "problem", "in", "the", "dual", "and", "return", "the", "OT", "matrix" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/smooth.py#L418-L507
240,937
rflamary/POT
ot/smooth.py
smooth_ot_semi_dual
def smooth_ot_semi_dual(a, b, M, reg, reg_type='l2', method="L-BFGS-B", stopThr=1e-9, numItermax=500, verbose=False, log=False): r""" Solve the regularized OT problem in the semi-dual and return the OT matrix The function solves the smooth relaxed dual formulation (10) in [17]_ : .. math:: \max_{\alpha}\quad a^T\alpha-OT_\Omega^*(\alpha,b) where : .. math:: OT_\Omega^*(\alpha,b)=\sum_j b_j - :math:`\mathbf{m}_j` is the jth column of the cost matrix - :math:`OT_\Omega^*(\alpha,b)` is defined in Eq. (9) in [17] - a and b are source and target weights (sum to 1) The OT matrix can is reconstructed using [17]_ Proposition 2. The optimization algorithm is using gradient decent (L-BFGS by default). Parameters ---------- a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) or np.ndarray (nt,nbb) samples in the target domain, compute sinkhorn with multiple targets and fixed M if b is a matrix (return OT loss + dual variables in log) M : np.ndarray (ns,nt) loss matrix reg : float Regularization term >0 reg_type : str Regularization type, can be the following (default ='l2'): - 'kl' : Kullback Leibler (~ Neg-entropy used in sinkhorn [2]_) - 'l2' : Squared Euclidean regularization method : str Solver to use for scipy.optimize.minimize numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters References ---------- .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013 .. [17] Blondel, M., Seguy, V., & Rolet, A. (2018). Smooth and Sparse Optimal Transport. Proceedings of the Twenty-First International Conference on Artificial Intelligence and Statistics (AISTATS). See Also -------- ot.lp.emd : Unregularized OT ot.sinhorn : Entropic regularized OT ot.optim.cg : General regularized OT """ if reg_type.lower() in ['l2', 'squaredl2']: regul = SquaredL2(gamma=reg) elif reg_type.lower() in ['entropic', 'negentropy', 'kl']: regul = NegEntropy(gamma=reg) else: raise NotImplementedError('Unknown regularization') # solve dual alpha, res = solve_semi_dual(a, b, M, regul, max_iter=numItermax, tol=stopThr, verbose=verbose) # reconstruct transport matrix G = get_plan_from_semi_dual(alpha, b, M, regul) if log: log = {'alpha': alpha, 'res': res} return G, log else: return G
python
def smooth_ot_semi_dual(a, b, M, reg, reg_type='l2', method="L-BFGS-B", stopThr=1e-9, numItermax=500, verbose=False, log=False): r""" Solve the regularized OT problem in the semi-dual and return the OT matrix The function solves the smooth relaxed dual formulation (10) in [17]_ : .. math:: \max_{\alpha}\quad a^T\alpha-OT_\Omega^*(\alpha,b) where : .. math:: OT_\Omega^*(\alpha,b)=\sum_j b_j - :math:`\mathbf{m}_j` is the jth column of the cost matrix - :math:`OT_\Omega^*(\alpha,b)` is defined in Eq. (9) in [17] - a and b are source and target weights (sum to 1) The OT matrix can is reconstructed using [17]_ Proposition 2. The optimization algorithm is using gradient decent (L-BFGS by default). Parameters ---------- a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) or np.ndarray (nt,nbb) samples in the target domain, compute sinkhorn with multiple targets and fixed M if b is a matrix (return OT loss + dual variables in log) M : np.ndarray (ns,nt) loss matrix reg : float Regularization term >0 reg_type : str Regularization type, can be the following (default ='l2'): - 'kl' : Kullback Leibler (~ Neg-entropy used in sinkhorn [2]_) - 'l2' : Squared Euclidean regularization method : str Solver to use for scipy.optimize.minimize numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters References ---------- .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013 .. [17] Blondel, M., Seguy, V., & Rolet, A. (2018). Smooth and Sparse Optimal Transport. Proceedings of the Twenty-First International Conference on Artificial Intelligence and Statistics (AISTATS). See Also -------- ot.lp.emd : Unregularized OT ot.sinhorn : Entropic regularized OT ot.optim.cg : General regularized OT """ if reg_type.lower() in ['l2', 'squaredl2']: regul = SquaredL2(gamma=reg) elif reg_type.lower() in ['entropic', 'negentropy', 'kl']: regul = NegEntropy(gamma=reg) else: raise NotImplementedError('Unknown regularization') # solve dual alpha, res = solve_semi_dual(a, b, M, regul, max_iter=numItermax, tol=stopThr, verbose=verbose) # reconstruct transport matrix G = get_plan_from_semi_dual(alpha, b, M, regul) if log: log = {'alpha': alpha, 'res': res} return G, log else: return G
[ "def", "smooth_ot_semi_dual", "(", "a", ",", "b", ",", "M", ",", "reg", ",", "reg_type", "=", "'l2'", ",", "method", "=", "\"L-BFGS-B\"", ",", "stopThr", "=", "1e-9", ",", "numItermax", "=", "500", ",", "verbose", "=", "False", ",", "log", "=", "Fals...
r""" Solve the regularized OT problem in the semi-dual and return the OT matrix The function solves the smooth relaxed dual formulation (10) in [17]_ : .. math:: \max_{\alpha}\quad a^T\alpha-OT_\Omega^*(\alpha,b) where : .. math:: OT_\Omega^*(\alpha,b)=\sum_j b_j - :math:`\mathbf{m}_j` is the jth column of the cost matrix - :math:`OT_\Omega^*(\alpha,b)` is defined in Eq. (9) in [17] - a and b are source and target weights (sum to 1) The OT matrix can is reconstructed using [17]_ Proposition 2. The optimization algorithm is using gradient decent (L-BFGS by default). Parameters ---------- a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) or np.ndarray (nt,nbb) samples in the target domain, compute sinkhorn with multiple targets and fixed M if b is a matrix (return OT loss + dual variables in log) M : np.ndarray (ns,nt) loss matrix reg : float Regularization term >0 reg_type : str Regularization type, can be the following (default ='l2'): - 'kl' : Kullback Leibler (~ Neg-entropy used in sinkhorn [2]_) - 'l2' : Squared Euclidean regularization method : str Solver to use for scipy.optimize.minimize numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters References ---------- .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013 .. [17] Blondel, M., Seguy, V., & Rolet, A. (2018). Smooth and Sparse Optimal Transport. Proceedings of the Twenty-First International Conference on Artificial Intelligence and Statistics (AISTATS). See Also -------- ot.lp.emd : Unregularized OT ot.sinhorn : Entropic regularized OT ot.optim.cg : General regularized OT
[ "r", "Solve", "the", "regularized", "OT", "problem", "in", "the", "semi", "-", "dual", "and", "return", "the", "OT", "matrix" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/smooth.py#L510-L600
240,938
rflamary/POT
ot/utils.py
kernel
def kernel(x1, x2, method='gaussian', sigma=1, **kwargs): """Compute kernel matrix""" if method.lower() in ['gaussian', 'gauss', 'rbf']: K = np.exp(-dist(x1, x2) / (2 * sigma**2)) return K
python
def kernel(x1, x2, method='gaussian', sigma=1, **kwargs): if method.lower() in ['gaussian', 'gauss', 'rbf']: K = np.exp(-dist(x1, x2) / (2 * sigma**2)) return K
[ "def", "kernel", "(", "x1", ",", "x2", ",", "method", "=", "'gaussian'", ",", "sigma", "=", "1", ",", "*", "*", "kwargs", ")", ":", "if", "method", ".", "lower", "(", ")", "in", "[", "'gaussian'", ",", "'gauss'", ",", "'rbf'", "]", ":", "K", "=...
Compute kernel matrix
[ "Compute", "kernel", "matrix" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/utils.py#L45-L49
240,939
rflamary/POT
ot/utils.py
clean_zeros
def clean_zeros(a, b, M): """ Remove all components with zeros weights in a and b """ M2 = M[a > 0, :][:, b > 0].copy() # copy force c style matrix (froemd) a2 = a[a > 0] b2 = b[b > 0] return a2, b2, M2
python
def clean_zeros(a, b, M): M2 = M[a > 0, :][:, b > 0].copy() # copy force c style matrix (froemd) a2 = a[a > 0] b2 = b[b > 0] return a2, b2, M2
[ "def", "clean_zeros", "(", "a", ",", "b", ",", "M", ")", ":", "M2", "=", "M", "[", "a", ">", "0", ",", ":", "]", "[", ":", ",", "b", ">", "0", "]", ".", "copy", "(", ")", "# copy force c style matrix (froemd)", "a2", "=", "a", "[", "a", ">", ...
Remove all components with zeros weights in a and b
[ "Remove", "all", "components", "with", "zeros", "weights", "in", "a", "and", "b" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/utils.py#L71-L77
240,940
rflamary/POT
ot/utils.py
dist
def dist(x1, x2=None, metric='sqeuclidean'): """Compute distance between samples in x1 and x2 using function scipy.spatial.distance.cdist Parameters ---------- x1 : np.array (n1,d) matrix with n1 samples of size d x2 : np.array (n2,d), optional matrix with n2 samples of size d (if None then x2=x1) metric : str, fun, optional name of the metric to be computed (full list in the doc of scipy), If a string, the distance function can be 'braycurtis', 'canberra', 'chebyshev', 'cityblock', 'correlation', 'cosine', 'dice', 'euclidean', 'hamming', 'jaccard', 'kulsinski', 'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'wminkowski', 'yule'. Returns ------- M : np.array (n1,n2) distance matrix computed with given metric """ if x2 is None: x2 = x1 if metric == "sqeuclidean": return euclidean_distances(x1, x2, squared=True) return cdist(x1, x2, metric=metric)
python
def dist(x1, x2=None, metric='sqeuclidean'): if x2 is None: x2 = x1 if metric == "sqeuclidean": return euclidean_distances(x1, x2, squared=True) return cdist(x1, x2, metric=metric)
[ "def", "dist", "(", "x1", ",", "x2", "=", "None", ",", "metric", "=", "'sqeuclidean'", ")", ":", "if", "x2", "is", "None", ":", "x2", "=", "x1", "if", "metric", "==", "\"sqeuclidean\"", ":", "return", "euclidean_distances", "(", "x1", ",", "x2", ",",...
Compute distance between samples in x1 and x2 using function scipy.spatial.distance.cdist Parameters ---------- x1 : np.array (n1,d) matrix with n1 samples of size d x2 : np.array (n2,d), optional matrix with n2 samples of size d (if None then x2=x1) metric : str, fun, optional name of the metric to be computed (full list in the doc of scipy), If a string, the distance function can be 'braycurtis', 'canberra', 'chebyshev', 'cityblock', 'correlation', 'cosine', 'dice', 'euclidean', 'hamming', 'jaccard', 'kulsinski', 'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'wminkowski', 'yule'. Returns ------- M : np.array (n1,n2) distance matrix computed with given metric
[ "Compute", "distance", "between", "samples", "in", "x1", "and", "x2", "using", "function", "scipy", ".", "spatial", ".", "distance", ".", "cdist" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/utils.py#L108-L137
240,941
rflamary/POT
ot/utils.py
cost_normalization
def cost_normalization(C, norm=None): """ Apply normalization to the loss matrix Parameters ---------- C : np.array (n1, n2) The cost matrix to normalize. norm : str type of normalization from 'median','max','log','loglog'. Any other value do not normalize. Returns ------- C : np.array (n1, n2) The input cost matrix normalized according to given norm. """ if norm == "median": C /= float(np.median(C)) elif norm == "max": C /= float(np.max(C)) elif norm == "log": C = np.log(1 + C) elif norm == "loglog": C = np.log(1 + np.log(1 + C)) return C
python
def cost_normalization(C, norm=None): if norm == "median": C /= float(np.median(C)) elif norm == "max": C /= float(np.max(C)) elif norm == "log": C = np.log(1 + C) elif norm == "loglog": C = np.log(1 + np.log(1 + C)) return C
[ "def", "cost_normalization", "(", "C", ",", "norm", "=", "None", ")", ":", "if", "norm", "==", "\"median\"", ":", "C", "/=", "float", "(", "np", ".", "median", "(", "C", ")", ")", "elif", "norm", "==", "\"max\"", ":", "C", "/=", "float", "(", "np...
Apply normalization to the loss matrix Parameters ---------- C : np.array (n1, n2) The cost matrix to normalize. norm : str type of normalization from 'median','max','log','loglog'. Any other value do not normalize. Returns ------- C : np.array (n1, n2) The input cost matrix normalized according to given norm.
[ "Apply", "normalization", "to", "the", "loss", "matrix" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/utils.py#L169-L199
240,942
rflamary/POT
ot/utils.py
parmap
def parmap(f, X, nprocs=multiprocessing.cpu_count()): """ paralell map for multiprocessing """ q_in = multiprocessing.Queue(1) q_out = multiprocessing.Queue() proc = [multiprocessing.Process(target=fun, args=(f, q_in, q_out)) for _ in range(nprocs)] for p in proc: p.daemon = True p.start() sent = [q_in.put((i, x)) for i, x in enumerate(X)] [q_in.put((None, None)) for _ in range(nprocs)] res = [q_out.get() for _ in range(len(sent))] [p.join() for p in proc] return [x for i, x in sorted(res)]
python
def parmap(f, X, nprocs=multiprocessing.cpu_count()): q_in = multiprocessing.Queue(1) q_out = multiprocessing.Queue() proc = [multiprocessing.Process(target=fun, args=(f, q_in, q_out)) for _ in range(nprocs)] for p in proc: p.daemon = True p.start() sent = [q_in.put((i, x)) for i, x in enumerate(X)] [q_in.put((None, None)) for _ in range(nprocs)] res = [q_out.get() for _ in range(len(sent))] [p.join() for p in proc] return [x for i, x in sorted(res)]
[ "def", "parmap", "(", "f", ",", "X", ",", "nprocs", "=", "multiprocessing", ".", "cpu_count", "(", ")", ")", ":", "q_in", "=", "multiprocessing", ".", "Queue", "(", "1", ")", "q_out", "=", "multiprocessing", ".", "Queue", "(", ")", "proc", "=", "[", ...
paralell map for multiprocessing
[ "paralell", "map", "for", "multiprocessing" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/utils.py#L216-L233
240,943
rflamary/POT
ot/utils.py
_is_deprecated
def _is_deprecated(func): """Helper to check if func is wraped by our deprecated decorator""" if sys.version_info < (3, 5): raise NotImplementedError("This is only available for python3.5 " "or above") closures = getattr(func, '__closure__', []) if closures is None: closures = [] is_deprecated = ('deprecated' in ''.join([c.cell_contents for c in closures if isinstance(c.cell_contents, str)])) return is_deprecated
python
def _is_deprecated(func): if sys.version_info < (3, 5): raise NotImplementedError("This is only available for python3.5 " "or above") closures = getattr(func, '__closure__', []) if closures is None: closures = [] is_deprecated = ('deprecated' in ''.join([c.cell_contents for c in closures if isinstance(c.cell_contents, str)])) return is_deprecated
[ "def", "_is_deprecated", "(", "func", ")", ":", "if", "sys", ".", "version_info", "<", "(", "3", ",", "5", ")", ":", "raise", "NotImplementedError", "(", "\"This is only available for python3.5 \"", "\"or above\"", ")", "closures", "=", "getattr", "(", "func", ...
Helper to check if func is wraped by our deprecated decorator
[ "Helper", "to", "check", "if", "func", "is", "wraped", "by", "our", "deprecated", "decorator" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/utils.py#L361-L372
240,944
rflamary/POT
ot/utils.py
deprecated._decorate_fun
def _decorate_fun(self, fun): """Decorate function fun""" msg = "Function %s is deprecated" % fun.__name__ if self.extra: msg += "; %s" % self.extra def wrapped(*args, **kwargs): warnings.warn(msg, category=DeprecationWarning) return fun(*args, **kwargs) wrapped.__name__ = fun.__name__ wrapped.__dict__ = fun.__dict__ wrapped.__doc__ = self._update_doc(fun.__doc__) return wrapped
python
def _decorate_fun(self, fun): msg = "Function %s is deprecated" % fun.__name__ if self.extra: msg += "; %s" % self.extra def wrapped(*args, **kwargs): warnings.warn(msg, category=DeprecationWarning) return fun(*args, **kwargs) wrapped.__name__ = fun.__name__ wrapped.__dict__ = fun.__dict__ wrapped.__doc__ = self._update_doc(fun.__doc__) return wrapped
[ "def", "_decorate_fun", "(", "self", ",", "fun", ")", ":", "msg", "=", "\"Function %s is deprecated\"", "%", "fun", ".", "__name__", "if", "self", ".", "extra", ":", "msg", "+=", "\"; %s\"", "%", "self", ".", "extra", "def", "wrapped", "(", "*", "args", ...
Decorate function fun
[ "Decorate", "function", "fun" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/utils.py#L335-L350
240,945
rflamary/POT
ot/dr.py
split_classes
def split_classes(X, y): """split samples in X by classes in y """ lstsclass = np.unique(y) return [X[y == i, :].astype(np.float32) for i in lstsclass]
python
def split_classes(X, y): lstsclass = np.unique(y) return [X[y == i, :].astype(np.float32) for i in lstsclass]
[ "def", "split_classes", "(", "X", ",", "y", ")", ":", "lstsclass", "=", "np", ".", "unique", "(", "y", ")", "return", "[", "X", "[", "y", "==", "i", ",", ":", "]", ".", "astype", "(", "np", ".", "float32", ")", "for", "i", "in", "lstsclass", ...
split samples in X by classes in y
[ "split", "samples", "in", "X", "by", "classes", "in", "y" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/dr.py#L38-L42
240,946
rflamary/POT
ot/dr.py
fda
def fda(X, y, p=2, reg=1e-16): """ Fisher Discriminant Analysis Parameters ---------- X : numpy.ndarray (n,d) Training samples y : np.ndarray (n,) labels for training samples p : int, optional size of dimensionnality reduction reg : float, optional Regularization term >0 (ridge regularization) Returns ------- P : (d x p) ndarray Optimal transportation matrix for the given parameters proj : fun projection function including mean centering """ mx = np.mean(X) X -= mx.reshape((1, -1)) # data split between classes d = X.shape[1] xc = split_classes(X, y) nc = len(xc) p = min(nc - 1, p) Cw = 0 for x in xc: Cw += np.cov(x, rowvar=False) Cw /= nc mxc = np.zeros((d, nc)) for i in range(nc): mxc[:, i] = np.mean(xc[i]) mx0 = np.mean(mxc, 1) Cb = 0 for i in range(nc): Cb += (mxc[:, i] - mx0).reshape((-1, 1)) * \ (mxc[:, i] - mx0).reshape((1, -1)) w, V = linalg.eig(Cb, Cw + reg * np.eye(d)) idx = np.argsort(w.real) Popt = V[:, idx[-p:]] def proj(X): return (X - mx.reshape((1, -1))).dot(Popt) return Popt, proj
python
def fda(X, y, p=2, reg=1e-16): mx = np.mean(X) X -= mx.reshape((1, -1)) # data split between classes d = X.shape[1] xc = split_classes(X, y) nc = len(xc) p = min(nc - 1, p) Cw = 0 for x in xc: Cw += np.cov(x, rowvar=False) Cw /= nc mxc = np.zeros((d, nc)) for i in range(nc): mxc[:, i] = np.mean(xc[i]) mx0 = np.mean(mxc, 1) Cb = 0 for i in range(nc): Cb += (mxc[:, i] - mx0).reshape((-1, 1)) * \ (mxc[:, i] - mx0).reshape((1, -1)) w, V = linalg.eig(Cb, Cw + reg * np.eye(d)) idx = np.argsort(w.real) Popt = V[:, idx[-p:]] def proj(X): return (X - mx.reshape((1, -1))).dot(Popt) return Popt, proj
[ "def", "fda", "(", "X", ",", "y", ",", "p", "=", "2", ",", "reg", "=", "1e-16", ")", ":", "mx", "=", "np", ".", "mean", "(", "X", ")", "X", "-=", "mx", ".", "reshape", "(", "(", "1", ",", "-", "1", ")", ")", "# data split between classes", ...
Fisher Discriminant Analysis Parameters ---------- X : numpy.ndarray (n,d) Training samples y : np.ndarray (n,) labels for training samples p : int, optional size of dimensionnality reduction reg : float, optional Regularization term >0 (ridge regularization) Returns ------- P : (d x p) ndarray Optimal transportation matrix for the given parameters proj : fun projection function including mean centering
[ "Fisher", "Discriminant", "Analysis" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/dr.py#L45-L107
240,947
rflamary/POT
ot/stochastic.py
sag_entropic_transport
def sag_entropic_transport(a, b, M, reg, numItermax=10000, lr=None): ''' Compute the SAG algorithm to solve the regularized discrete measures optimal transport max problem The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1 = b \gamma \geq 0 Where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is the SAG algorithm as proposed in [18]_ [alg.1] Parameters ---------- a : np.ndarray(ns,), source measure b : np.ndarray(nt,), target measure M : np.ndarray(ns, nt), cost matrix reg : float number, Regularization term > 0 numItermax : int number number of iteration lr : float number learning rate Returns ------- v : np.ndarray(nt,) dual variable Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 300000 >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> method = "ASGD" >>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg, method, numItermax) >>> print(asgd_pi) References ---------- [Genevay et al., 2016] : Stochastic Optimization for Large-scale Optimal Transport, Advances in Neural Information Processing Systems (2016), arXiv preprint arxiv:1605.08527. ''' if lr is None: lr = 1. / max(a / reg) n_source = np.shape(M)[0] n_target = np.shape(M)[1] cur_beta = np.zeros(n_target) stored_gradient = np.zeros((n_source, n_target)) sum_stored_gradient = np.zeros(n_target) for _ in range(numItermax): i = np.random.randint(n_source) cur_coord_grad = a[i] * coordinate_grad_semi_dual(b, M, reg, cur_beta, i) sum_stored_gradient += (cur_coord_grad - stored_gradient[i]) stored_gradient[i] = cur_coord_grad cur_beta += lr * (1. / n_source) * sum_stored_gradient return cur_beta
python
def sag_entropic_transport(a, b, M, reg, numItermax=10000, lr=None): ''' Compute the SAG algorithm to solve the regularized discrete measures optimal transport max problem The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1 = b \gamma \geq 0 Where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is the SAG algorithm as proposed in [18]_ [alg.1] Parameters ---------- a : np.ndarray(ns,), source measure b : np.ndarray(nt,), target measure M : np.ndarray(ns, nt), cost matrix reg : float number, Regularization term > 0 numItermax : int number number of iteration lr : float number learning rate Returns ------- v : np.ndarray(nt,) dual variable Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 300000 >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> method = "ASGD" >>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg, method, numItermax) >>> print(asgd_pi) References ---------- [Genevay et al., 2016] : Stochastic Optimization for Large-scale Optimal Transport, Advances in Neural Information Processing Systems (2016), arXiv preprint arxiv:1605.08527. ''' if lr is None: lr = 1. / max(a / reg) n_source = np.shape(M)[0] n_target = np.shape(M)[1] cur_beta = np.zeros(n_target) stored_gradient = np.zeros((n_source, n_target)) sum_stored_gradient = np.zeros(n_target) for _ in range(numItermax): i = np.random.randint(n_source) cur_coord_grad = a[i] * coordinate_grad_semi_dual(b, M, reg, cur_beta, i) sum_stored_gradient += (cur_coord_grad - stored_gradient[i]) stored_gradient[i] = cur_coord_grad cur_beta += lr * (1. / n_source) * sum_stored_gradient return cur_beta
[ "def", "sag_entropic_transport", "(", "a", ",", "b", ",", "M", ",", "reg", ",", "numItermax", "=", "10000", ",", "lr", "=", "None", ")", ":", "if", "lr", "is", "None", ":", "lr", "=", "1.", "/", "max", "(", "a", "/", "reg", ")", "n_source", "="...
Compute the SAG algorithm to solve the regularized discrete measures optimal transport max problem The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1 = b \gamma \geq 0 Where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is the SAG algorithm as proposed in [18]_ [alg.1] Parameters ---------- a : np.ndarray(ns,), source measure b : np.ndarray(nt,), target measure M : np.ndarray(ns, nt), cost matrix reg : float number, Regularization term > 0 numItermax : int number number of iteration lr : float number learning rate Returns ------- v : np.ndarray(nt,) dual variable Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 300000 >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> method = "ASGD" >>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg, method, numItermax) >>> print(asgd_pi) References ---------- [Genevay et al., 2016] : Stochastic Optimization for Large-scale Optimal Transport, Advances in Neural Information Processing Systems (2016), arXiv preprint arxiv:1605.08527.
[ "Compute", "the", "SAG", "algorithm", "to", "solve", "the", "regularized", "discrete", "measures", "optimal", "transport", "max", "problem" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/stochastic.py#L86-L175
240,948
rflamary/POT
ot/stochastic.py
averaged_sgd_entropic_transport
def averaged_sgd_entropic_transport(a, b, M, reg, numItermax=300000, lr=None): ''' Compute the ASGD algorithm to solve the regularized semi continous measures optimal transport max problem The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma \geq 0 Where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is the ASGD algorithm as proposed in [18]_ [alg.2] Parameters ---------- b : np.ndarray(nt,) target measure M : np.ndarray(ns, nt) cost matrix reg : float number Regularization term > 0 numItermax : int number number of iteration lr : float number learning rate Returns ------- ave_v : np.ndarray(nt,) dual variable Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 300000 >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> method = "ASGD" >>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg, method, numItermax) >>> print(asgd_pi) References ---------- [Genevay et al., 2016] : Stochastic Optimization for Large-scale Optimal Transport, Advances in Neural Information Processing Systems (2016), arXiv preprint arxiv:1605.08527. ''' if lr is None: lr = 1. / max(a / reg) n_source = np.shape(M)[0] n_target = np.shape(M)[1] cur_beta = np.zeros(n_target) ave_beta = np.zeros(n_target) for cur_iter in range(numItermax): k = cur_iter + 1 i = np.random.randint(n_source) cur_coord_grad = coordinate_grad_semi_dual(b, M, reg, cur_beta, i) cur_beta += (lr / np.sqrt(k)) * cur_coord_grad ave_beta = (1. / k) * cur_beta + (1 - 1. / k) * ave_beta return ave_beta
python
def averaged_sgd_entropic_transport(a, b, M, reg, numItermax=300000, lr=None): ''' Compute the ASGD algorithm to solve the regularized semi continous measures optimal transport max problem The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma \geq 0 Where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is the ASGD algorithm as proposed in [18]_ [alg.2] Parameters ---------- b : np.ndarray(nt,) target measure M : np.ndarray(ns, nt) cost matrix reg : float number Regularization term > 0 numItermax : int number number of iteration lr : float number learning rate Returns ------- ave_v : np.ndarray(nt,) dual variable Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 300000 >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> method = "ASGD" >>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg, method, numItermax) >>> print(asgd_pi) References ---------- [Genevay et al., 2016] : Stochastic Optimization for Large-scale Optimal Transport, Advances in Neural Information Processing Systems (2016), arXiv preprint arxiv:1605.08527. ''' if lr is None: lr = 1. / max(a / reg) n_source = np.shape(M)[0] n_target = np.shape(M)[1] cur_beta = np.zeros(n_target) ave_beta = np.zeros(n_target) for cur_iter in range(numItermax): k = cur_iter + 1 i = np.random.randint(n_source) cur_coord_grad = coordinate_grad_semi_dual(b, M, reg, cur_beta, i) cur_beta += (lr / np.sqrt(k)) * cur_coord_grad ave_beta = (1. / k) * cur_beta + (1 - 1. / k) * ave_beta return ave_beta
[ "def", "averaged_sgd_entropic_transport", "(", "a", ",", "b", ",", "M", ",", "reg", ",", "numItermax", "=", "300000", ",", "lr", "=", "None", ")", ":", "if", "lr", "is", "None", ":", "lr", "=", "1.", "/", "max", "(", "a", "/", "reg", ")", "n_sour...
Compute the ASGD algorithm to solve the regularized semi continous measures optimal transport max problem The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma \geq 0 Where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is the ASGD algorithm as proposed in [18]_ [alg.2] Parameters ---------- b : np.ndarray(nt,) target measure M : np.ndarray(ns, nt) cost matrix reg : float number Regularization term > 0 numItermax : int number number of iteration lr : float number learning rate Returns ------- ave_v : np.ndarray(nt,) dual variable Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 300000 >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> method = "ASGD" >>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg, method, numItermax) >>> print(asgd_pi) References ---------- [Genevay et al., 2016] : Stochastic Optimization for Large-scale Optimal Transport, Advances in Neural Information Processing Systems (2016), arXiv preprint arxiv:1605.08527.
[ "Compute", "the", "ASGD", "algorithm", "to", "solve", "the", "regularized", "semi", "continous", "measures", "optimal", "transport", "max", "problem" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/stochastic.py#L178-L263
240,949
rflamary/POT
ot/stochastic.py
c_transform_entropic
def c_transform_entropic(b, M, reg, beta): ''' The goal is to recover u from the c-transform. The function computes the c_transform of a dual variable from the other dual variable: .. math:: u = v^{c,reg} = -reg \sum_j exp((v - M)/reg) b_j Where : - M is the (ns,nt) metric cost matrix - u, v are dual variables in R^IxR^J - reg is the regularization term It is used to recover an optimal u from optimal v solving the semi dual problem, see Proposition 2.1 of [18]_ Parameters ---------- b : np.ndarray(nt,) target measure M : np.ndarray(ns, nt) cost matrix reg : float regularization term > 0 v : np.ndarray(nt,) dual variable Returns ------- u : np.ndarray(ns,) dual variable Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 300000 >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> method = "ASGD" >>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg, method, numItermax) >>> print(asgd_pi) References ---------- [Genevay et al., 2016] : Stochastic Optimization for Large-scale Optimal Transport, Advances in Neural Information Processing Systems (2016), arXiv preprint arxiv:1605.08527. ''' n_source = np.shape(M)[0] alpha = np.zeros(n_source) for i in range(n_source): r = M[i, :] - beta min_r = np.min(r) exp_beta = np.exp(-(r - min_r) / reg) * b alpha[i] = min_r - reg * np.log(np.sum(exp_beta)) return alpha
python
def c_transform_entropic(b, M, reg, beta): ''' The goal is to recover u from the c-transform. The function computes the c_transform of a dual variable from the other dual variable: .. math:: u = v^{c,reg} = -reg \sum_j exp((v - M)/reg) b_j Where : - M is the (ns,nt) metric cost matrix - u, v are dual variables in R^IxR^J - reg is the regularization term It is used to recover an optimal u from optimal v solving the semi dual problem, see Proposition 2.1 of [18]_ Parameters ---------- b : np.ndarray(nt,) target measure M : np.ndarray(ns, nt) cost matrix reg : float regularization term > 0 v : np.ndarray(nt,) dual variable Returns ------- u : np.ndarray(ns,) dual variable Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 300000 >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> method = "ASGD" >>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg, method, numItermax) >>> print(asgd_pi) References ---------- [Genevay et al., 2016] : Stochastic Optimization for Large-scale Optimal Transport, Advances in Neural Information Processing Systems (2016), arXiv preprint arxiv:1605.08527. ''' n_source = np.shape(M)[0] alpha = np.zeros(n_source) for i in range(n_source): r = M[i, :] - beta min_r = np.min(r) exp_beta = np.exp(-(r - min_r) / reg) * b alpha[i] = min_r - reg * np.log(np.sum(exp_beta)) return alpha
[ "def", "c_transform_entropic", "(", "b", ",", "M", ",", "reg", ",", "beta", ")", ":", "n_source", "=", "np", ".", "shape", "(", "M", ")", "[", "0", "]", "alpha", "=", "np", ".", "zeros", "(", "n_source", ")", "for", "i", "in", "range", "(", "n_...
The goal is to recover u from the c-transform. The function computes the c_transform of a dual variable from the other dual variable: .. math:: u = v^{c,reg} = -reg \sum_j exp((v - M)/reg) b_j Where : - M is the (ns,nt) metric cost matrix - u, v are dual variables in R^IxR^J - reg is the regularization term It is used to recover an optimal u from optimal v solving the semi dual problem, see Proposition 2.1 of [18]_ Parameters ---------- b : np.ndarray(nt,) target measure M : np.ndarray(ns, nt) cost matrix reg : float regularization term > 0 v : np.ndarray(nt,) dual variable Returns ------- u : np.ndarray(ns,) dual variable Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 300000 >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> method = "ASGD" >>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg, method, numItermax) >>> print(asgd_pi) References ---------- [Genevay et al., 2016] : Stochastic Optimization for Large-scale Optimal Transport, Advances in Neural Information Processing Systems (2016), arXiv preprint arxiv:1605.08527.
[ "The", "goal", "is", "to", "recover", "u", "from", "the", "c", "-", "transform", "." ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/stochastic.py#L266-L338
240,950
rflamary/POT
ot/stochastic.py
solve_semi_dual_entropic
def solve_semi_dual_entropic(a, b, M, reg, method, numItermax=10000, lr=None, log=False): ''' Compute the transportation matrix to solve the regularized discrete measures optimal transport max problem The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma \geq 0 Where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is the SAG or ASGD algorithms as proposed in [18]_ Parameters ---------- a : np.ndarray(ns,) source measure b : np.ndarray(nt,) target measure M : np.ndarray(ns, nt) cost matrix reg : float number Regularization term > 0 methode : str used method (SAG or ASGD) numItermax : int number number of iteration lr : float number learning rate n_source : int number size of the source measure n_target : int number size of the target measure log : bool, optional record log if True Returns ------- pi : np.ndarray(ns, nt) transportation matrix log : dict log dictionary return only if log==True in parameters Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 300000 >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> method = "ASGD" >>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg, method, numItermax) >>> print(asgd_pi) References ---------- [Genevay et al., 2016] : Stochastic Optimization for Large-scale Optimal Transport, Advances in Neural Information Processing Systems (2016), arXiv preprint arxiv:1605.08527. ''' if method.lower() == "sag": opt_beta = sag_entropic_transport(a, b, M, reg, numItermax, lr) elif method.lower() == "asgd": opt_beta = averaged_sgd_entropic_transport(a, b, M, reg, numItermax, lr) else: print("Please, select your method between SAG and ASGD") return None opt_alpha = c_transform_entropic(b, M, reg, opt_beta) pi = (np.exp((opt_alpha[:, None] + opt_beta[None, :] - M[:, :]) / reg) * a[:, None] * b[None, :]) if log: log = {} log['alpha'] = opt_alpha log['beta'] = opt_beta return pi, log else: return pi
python
def solve_semi_dual_entropic(a, b, M, reg, method, numItermax=10000, lr=None, log=False): ''' Compute the transportation matrix to solve the regularized discrete measures optimal transport max problem The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma \geq 0 Where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is the SAG or ASGD algorithms as proposed in [18]_ Parameters ---------- a : np.ndarray(ns,) source measure b : np.ndarray(nt,) target measure M : np.ndarray(ns, nt) cost matrix reg : float number Regularization term > 0 methode : str used method (SAG or ASGD) numItermax : int number number of iteration lr : float number learning rate n_source : int number size of the source measure n_target : int number size of the target measure log : bool, optional record log if True Returns ------- pi : np.ndarray(ns, nt) transportation matrix log : dict log dictionary return only if log==True in parameters Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 300000 >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> method = "ASGD" >>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg, method, numItermax) >>> print(asgd_pi) References ---------- [Genevay et al., 2016] : Stochastic Optimization for Large-scale Optimal Transport, Advances in Neural Information Processing Systems (2016), arXiv preprint arxiv:1605.08527. ''' if method.lower() == "sag": opt_beta = sag_entropic_transport(a, b, M, reg, numItermax, lr) elif method.lower() == "asgd": opt_beta = averaged_sgd_entropic_transport(a, b, M, reg, numItermax, lr) else: print("Please, select your method between SAG and ASGD") return None opt_alpha = c_transform_entropic(b, M, reg, opt_beta) pi = (np.exp((opt_alpha[:, None] + opt_beta[None, :] - M[:, :]) / reg) * a[:, None] * b[None, :]) if log: log = {} log['alpha'] = opt_alpha log['beta'] = opt_beta return pi, log else: return pi
[ "def", "solve_semi_dual_entropic", "(", "a", ",", "b", ",", "M", ",", "reg", ",", "method", ",", "numItermax", "=", "10000", ",", "lr", "=", "None", ",", "log", "=", "False", ")", ":", "if", "method", ".", "lower", "(", ")", "==", "\"sag\"", ":", ...
Compute the transportation matrix to solve the regularized discrete measures optimal transport max problem The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma \geq 0 Where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is the SAG or ASGD algorithms as proposed in [18]_ Parameters ---------- a : np.ndarray(ns,) source measure b : np.ndarray(nt,) target measure M : np.ndarray(ns, nt) cost matrix reg : float number Regularization term > 0 methode : str used method (SAG or ASGD) numItermax : int number number of iteration lr : float number learning rate n_source : int number size of the source measure n_target : int number size of the target measure log : bool, optional record log if True Returns ------- pi : np.ndarray(ns, nt) transportation matrix log : dict log dictionary return only if log==True in parameters Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 300000 >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> method = "ASGD" >>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg, method, numItermax) >>> print(asgd_pi) References ---------- [Genevay et al., 2016] : Stochastic Optimization for Large-scale Optimal Transport, Advances in Neural Information Processing Systems (2016), arXiv preprint arxiv:1605.08527.
[ "Compute", "the", "transportation", "matrix", "to", "solve", "the", "regularized", "discrete", "measures", "optimal", "transport", "max", "problem" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/stochastic.py#L341-L444
240,951
rflamary/POT
ot/stochastic.py
batch_grad_dual
def batch_grad_dual(a, b, M, reg, alpha, beta, batch_size, batch_alpha, batch_beta): ''' Computes the partial gradient of the dual optimal transport problem. For each (i,j) in a batch of coordinates, the partial gradients are : .. math:: \partial_{u_i} F = u_i * b_s/l_{v} - \sum_{j \in B_v} exp((u_i + v_j - M_{i,j})/reg) * a_i * b_j \partial_{v_j} F = v_j * b_s/l_{u} - \sum_{i \in B_u} exp((u_i + v_j - M_{i,j})/reg) * a_i * b_j Where : - M is the (ns,nt) metric cost matrix - u, v are dual variables in R^ixR^J - reg is the regularization term - :math:`B_u` and :math:`B_v` are lists of index - :math:`b_s` is the size of the batchs :math:`B_u` and :math:`B_v` - :math:`l_u` and :math:`l_v` are the lenghts of :math:`B_u` and :math:`B_v` - a and b are source and target weights (sum to 1) The algorithm used for solving the dual problem is the SGD algorithm as proposed in [19]_ [alg.1] Parameters ---------- a : np.ndarray(ns,) source measure b : np.ndarray(nt,) target measure M : np.ndarray(ns, nt) cost matrix reg : float number Regularization term > 0 alpha : np.ndarray(ns,) dual variable beta : np.ndarray(nt,) dual variable batch_size : int number size of the batch batch_alpha : np.ndarray(bs,) batch of index of alpha batch_beta : np.ndarray(bs,) batch of index of beta Returns ------- grad : np.ndarray(ns,) partial grad F Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 20000 >>> lr = 0.1 >>> batch_size = 3 >>> log = True >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> sgd_dual_pi, log = stochastic.solve_dual_entropic(a, b, M, reg, batch_size, numItermax, lr, log) >>> print(log['alpha'], log['beta']) >>> print(sgd_dual_pi) References ---------- [Seguy et al., 2018] : International Conference on Learning Representation (2018), arXiv preprint arxiv:1711.02283. ''' G = - (np.exp((alpha[batch_alpha, None] + beta[None, batch_beta] - M[batch_alpha, :][:, batch_beta]) / reg) * a[batch_alpha, None] * b[None, batch_beta]) grad_beta = np.zeros(np.shape(M)[1]) grad_alpha = np.zeros(np.shape(M)[0]) grad_beta[batch_beta] = (b[batch_beta] * len(batch_alpha) / np.shape(M)[0] + G.sum(0)) grad_alpha[batch_alpha] = (a[batch_alpha] * len(batch_beta) / np.shape(M)[1] + G.sum(1)) return grad_alpha, grad_beta
python
def batch_grad_dual(a, b, M, reg, alpha, beta, batch_size, batch_alpha, batch_beta): ''' Computes the partial gradient of the dual optimal transport problem. For each (i,j) in a batch of coordinates, the partial gradients are : .. math:: \partial_{u_i} F = u_i * b_s/l_{v} - \sum_{j \in B_v} exp((u_i + v_j - M_{i,j})/reg) * a_i * b_j \partial_{v_j} F = v_j * b_s/l_{u} - \sum_{i \in B_u} exp((u_i + v_j - M_{i,j})/reg) * a_i * b_j Where : - M is the (ns,nt) metric cost matrix - u, v are dual variables in R^ixR^J - reg is the regularization term - :math:`B_u` and :math:`B_v` are lists of index - :math:`b_s` is the size of the batchs :math:`B_u` and :math:`B_v` - :math:`l_u` and :math:`l_v` are the lenghts of :math:`B_u` and :math:`B_v` - a and b are source and target weights (sum to 1) The algorithm used for solving the dual problem is the SGD algorithm as proposed in [19]_ [alg.1] Parameters ---------- a : np.ndarray(ns,) source measure b : np.ndarray(nt,) target measure M : np.ndarray(ns, nt) cost matrix reg : float number Regularization term > 0 alpha : np.ndarray(ns,) dual variable beta : np.ndarray(nt,) dual variable batch_size : int number size of the batch batch_alpha : np.ndarray(bs,) batch of index of alpha batch_beta : np.ndarray(bs,) batch of index of beta Returns ------- grad : np.ndarray(ns,) partial grad F Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 20000 >>> lr = 0.1 >>> batch_size = 3 >>> log = True >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> sgd_dual_pi, log = stochastic.solve_dual_entropic(a, b, M, reg, batch_size, numItermax, lr, log) >>> print(log['alpha'], log['beta']) >>> print(sgd_dual_pi) References ---------- [Seguy et al., 2018] : International Conference on Learning Representation (2018), arXiv preprint arxiv:1711.02283. ''' G = - (np.exp((alpha[batch_alpha, None] + beta[None, batch_beta] - M[batch_alpha, :][:, batch_beta]) / reg) * a[batch_alpha, None] * b[None, batch_beta]) grad_beta = np.zeros(np.shape(M)[1]) grad_alpha = np.zeros(np.shape(M)[0]) grad_beta[batch_beta] = (b[batch_beta] * len(batch_alpha) / np.shape(M)[0] + G.sum(0)) grad_alpha[batch_alpha] = (a[batch_alpha] * len(batch_beta) / np.shape(M)[1] + G.sum(1)) return grad_alpha, grad_beta
[ "def", "batch_grad_dual", "(", "a", ",", "b", ",", "M", ",", "reg", ",", "alpha", ",", "beta", ",", "batch_size", ",", "batch_alpha", ",", "batch_beta", ")", ":", "G", "=", "-", "(", "np", ".", "exp", "(", "(", "alpha", "[", "batch_alpha", ",", "...
Computes the partial gradient of the dual optimal transport problem. For each (i,j) in a batch of coordinates, the partial gradients are : .. math:: \partial_{u_i} F = u_i * b_s/l_{v} - \sum_{j \in B_v} exp((u_i + v_j - M_{i,j})/reg) * a_i * b_j \partial_{v_j} F = v_j * b_s/l_{u} - \sum_{i \in B_u} exp((u_i + v_j - M_{i,j})/reg) * a_i * b_j Where : - M is the (ns,nt) metric cost matrix - u, v are dual variables in R^ixR^J - reg is the regularization term - :math:`B_u` and :math:`B_v` are lists of index - :math:`b_s` is the size of the batchs :math:`B_u` and :math:`B_v` - :math:`l_u` and :math:`l_v` are the lenghts of :math:`B_u` and :math:`B_v` - a and b are source and target weights (sum to 1) The algorithm used for solving the dual problem is the SGD algorithm as proposed in [19]_ [alg.1] Parameters ---------- a : np.ndarray(ns,) source measure b : np.ndarray(nt,) target measure M : np.ndarray(ns, nt) cost matrix reg : float number Regularization term > 0 alpha : np.ndarray(ns,) dual variable beta : np.ndarray(nt,) dual variable batch_size : int number size of the batch batch_alpha : np.ndarray(bs,) batch of index of alpha batch_beta : np.ndarray(bs,) batch of index of beta Returns ------- grad : np.ndarray(ns,) partial grad F Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 20000 >>> lr = 0.1 >>> batch_size = 3 >>> log = True >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> sgd_dual_pi, log = stochastic.solve_dual_entropic(a, b, M, reg, batch_size, numItermax, lr, log) >>> print(log['alpha'], log['beta']) >>> print(sgd_dual_pi) References ---------- [Seguy et al., 2018] : International Conference on Learning Representation (2018), arXiv preprint arxiv:1711.02283.
[ "Computes", "the", "partial", "gradient", "of", "the", "dual", "optimal", "transport", "problem", "." ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/stochastic.py#L452-L547
240,952
rflamary/POT
ot/stochastic.py
sgd_entropic_regularization
def sgd_entropic_regularization(a, b, M, reg, batch_size, numItermax, lr): ''' Compute the sgd algorithm to solve the regularized discrete measures optimal transport dual problem The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma \geq 0 Where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - a and b are source and target weights (sum to 1) Parameters ---------- a : np.ndarray(ns,) source measure b : np.ndarray(nt,) target measure M : np.ndarray(ns, nt) cost matrix reg : float number Regularization term > 0 batch_size : int number size of the batch numItermax : int number number of iteration lr : float number learning rate Returns ------- alpha : np.ndarray(ns,) dual variable beta : np.ndarray(nt,) dual variable Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 20000 >>> lr = 0.1 >>> batch_size = 3 >>> log = True >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> sgd_dual_pi, log = stochastic.solve_dual_entropic(a, b, M, reg, batch_size, numItermax, lr, log) >>> print(log['alpha'], log['beta']) >>> print(sgd_dual_pi) References ---------- [Seguy et al., 2018] : International Conference on Learning Representation (2018), arXiv preprint arxiv:1711.02283. ''' n_source = np.shape(M)[0] n_target = np.shape(M)[1] cur_alpha = np.zeros(n_source) cur_beta = np.zeros(n_target) for cur_iter in range(numItermax): k = np.sqrt(cur_iter + 1) batch_alpha = np.random.choice(n_source, batch_size, replace=False) batch_beta = np.random.choice(n_target, batch_size, replace=False) update_alpha, update_beta = batch_grad_dual(a, b, M, reg, cur_alpha, cur_beta, batch_size, batch_alpha, batch_beta) cur_alpha[batch_alpha] += (lr / k) * update_alpha[batch_alpha] cur_beta[batch_beta] += (lr / k) * update_beta[batch_beta] return cur_alpha, cur_beta
python
def sgd_entropic_regularization(a, b, M, reg, batch_size, numItermax, lr): ''' Compute the sgd algorithm to solve the regularized discrete measures optimal transport dual problem The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma \geq 0 Where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - a and b are source and target weights (sum to 1) Parameters ---------- a : np.ndarray(ns,) source measure b : np.ndarray(nt,) target measure M : np.ndarray(ns, nt) cost matrix reg : float number Regularization term > 0 batch_size : int number size of the batch numItermax : int number number of iteration lr : float number learning rate Returns ------- alpha : np.ndarray(ns,) dual variable beta : np.ndarray(nt,) dual variable Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 20000 >>> lr = 0.1 >>> batch_size = 3 >>> log = True >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> sgd_dual_pi, log = stochastic.solve_dual_entropic(a, b, M, reg, batch_size, numItermax, lr, log) >>> print(log['alpha'], log['beta']) >>> print(sgd_dual_pi) References ---------- [Seguy et al., 2018] : International Conference on Learning Representation (2018), arXiv preprint arxiv:1711.02283. ''' n_source = np.shape(M)[0] n_target = np.shape(M)[1] cur_alpha = np.zeros(n_source) cur_beta = np.zeros(n_target) for cur_iter in range(numItermax): k = np.sqrt(cur_iter + 1) batch_alpha = np.random.choice(n_source, batch_size, replace=False) batch_beta = np.random.choice(n_target, batch_size, replace=False) update_alpha, update_beta = batch_grad_dual(a, b, M, reg, cur_alpha, cur_beta, batch_size, batch_alpha, batch_beta) cur_alpha[batch_alpha] += (lr / k) * update_alpha[batch_alpha] cur_beta[batch_beta] += (lr / k) * update_beta[batch_beta] return cur_alpha, cur_beta
[ "def", "sgd_entropic_regularization", "(", "a", ",", "b", ",", "M", ",", "reg", ",", "batch_size", ",", "numItermax", ",", "lr", ")", ":", "n_source", "=", "np", ".", "shape", "(", "M", ")", "[", "0", "]", "n_target", "=", "np", ".", "shape", "(", ...
Compute the sgd algorithm to solve the regularized discrete measures optimal transport dual problem The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma \geq 0 Where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - a and b are source and target weights (sum to 1) Parameters ---------- a : np.ndarray(ns,) source measure b : np.ndarray(nt,) target measure M : np.ndarray(ns, nt) cost matrix reg : float number Regularization term > 0 batch_size : int number size of the batch numItermax : int number number of iteration lr : float number learning rate Returns ------- alpha : np.ndarray(ns,) dual variable beta : np.ndarray(nt,) dual variable Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 20000 >>> lr = 0.1 >>> batch_size = 3 >>> log = True >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> sgd_dual_pi, log = stochastic.solve_dual_entropic(a, b, M, reg, batch_size, numItermax, lr, log) >>> print(log['alpha'], log['beta']) >>> print(sgd_dual_pi) References ---------- [Seguy et al., 2018] : International Conference on Learning Representation (2018), arXiv preprint arxiv:1711.02283.
[ "Compute", "the", "sgd", "algorithm", "to", "solve", "the", "regularized", "discrete", "measures", "optimal", "transport", "dual", "problem" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/stochastic.py#L550-L642
240,953
rflamary/POT
ot/stochastic.py
solve_dual_entropic
def solve_dual_entropic(a, b, M, reg, batch_size, numItermax=10000, lr=1, log=False): ''' Compute the transportation matrix to solve the regularized discrete measures optimal transport dual problem The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma \geq 0 Where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - a and b are source and target weights (sum to 1) Parameters ---------- a : np.ndarray(ns,) source measure b : np.ndarray(nt,) target measure M : np.ndarray(ns, nt) cost matrix reg : float number Regularization term > 0 batch_size : int number size of the batch numItermax : int number number of iteration lr : float number learning rate log : bool, optional record log if True Returns ------- pi : np.ndarray(ns, nt) transportation matrix log : dict log dictionary return only if log==True in parameters Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 20000 >>> lr = 0.1 >>> batch_size = 3 >>> log = True >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> sgd_dual_pi, log = stochastic.solve_dual_entropic(a, b, M, reg, batch_size, numItermax, lr, log) >>> print(log['alpha'], log['beta']) >>> print(sgd_dual_pi) References ---------- [Seguy et al., 2018] : International Conference on Learning Representation (2018), arXiv preprint arxiv:1711.02283. ''' opt_alpha, opt_beta = sgd_entropic_regularization(a, b, M, reg, batch_size, numItermax, lr) pi = (np.exp((opt_alpha[:, None] + opt_beta[None, :] - M[:, :]) / reg) * a[:, None] * b[None, :]) if log: log = {} log['alpha'] = opt_alpha log['beta'] = opt_beta return pi, log else: return pi
python
def solve_dual_entropic(a, b, M, reg, batch_size, numItermax=10000, lr=1, log=False): ''' Compute the transportation matrix to solve the regularized discrete measures optimal transport dual problem The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma \geq 0 Where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - a and b are source and target weights (sum to 1) Parameters ---------- a : np.ndarray(ns,) source measure b : np.ndarray(nt,) target measure M : np.ndarray(ns, nt) cost matrix reg : float number Regularization term > 0 batch_size : int number size of the batch numItermax : int number number of iteration lr : float number learning rate log : bool, optional record log if True Returns ------- pi : np.ndarray(ns, nt) transportation matrix log : dict log dictionary return only if log==True in parameters Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 20000 >>> lr = 0.1 >>> batch_size = 3 >>> log = True >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> sgd_dual_pi, log = stochastic.solve_dual_entropic(a, b, M, reg, batch_size, numItermax, lr, log) >>> print(log['alpha'], log['beta']) >>> print(sgd_dual_pi) References ---------- [Seguy et al., 2018] : International Conference on Learning Representation (2018), arXiv preprint arxiv:1711.02283. ''' opt_alpha, opt_beta = sgd_entropic_regularization(a, b, M, reg, batch_size, numItermax, lr) pi = (np.exp((opt_alpha[:, None] + opt_beta[None, :] - M[:, :]) / reg) * a[:, None] * b[None, :]) if log: log = {} log['alpha'] = opt_alpha log['beta'] = opt_beta return pi, log else: return pi
[ "def", "solve_dual_entropic", "(", "a", ",", "b", ",", "M", ",", "reg", ",", "batch_size", ",", "numItermax", "=", "10000", ",", "lr", "=", "1", ",", "log", "=", "False", ")", ":", "opt_alpha", ",", "opt_beta", "=", "sgd_entropic_regularization", "(", ...
Compute the transportation matrix to solve the regularized discrete measures optimal transport dual problem The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma \geq 0 Where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - a and b are source and target weights (sum to 1) Parameters ---------- a : np.ndarray(ns,) source measure b : np.ndarray(nt,) target measure M : np.ndarray(ns, nt) cost matrix reg : float number Regularization term > 0 batch_size : int number size of the batch numItermax : int number number of iteration lr : float number learning rate log : bool, optional record log if True Returns ------- pi : np.ndarray(ns, nt) transportation matrix log : dict log dictionary return only if log==True in parameters Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 20000 >>> lr = 0.1 >>> batch_size = 3 >>> log = True >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> sgd_dual_pi, log = stochastic.solve_dual_entropic(a, b, M, reg, batch_size, numItermax, lr, log) >>> print(log['alpha'], log['beta']) >>> print(sgd_dual_pi) References ---------- [Seguy et al., 2018] : International Conference on Learning Representation (2018), arXiv preprint arxiv:1711.02283.
[ "Compute", "the", "transportation", "matrix", "to", "solve", "the", "regularized", "discrete", "measures", "optimal", "transport", "dual", "problem" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/stochastic.py#L645-L736
240,954
PyCQA/pyflakes
pyflakes/reporter.py
Reporter.flake
def flake(self, message): """ pyflakes found something wrong with the code. @param: A L{pyflakes.messages.Message}. """ self._stdout.write(str(message)) self._stdout.write('\n')
python
def flake(self, message): self._stdout.write(str(message)) self._stdout.write('\n')
[ "def", "flake", "(", "self", ",", "message", ")", ":", "self", ".", "_stdout", ".", "write", "(", "str", "(", "message", ")", ")", "self", ".", "_stdout", ".", "write", "(", "'\\n'", ")" ]
pyflakes found something wrong with the code. @param: A L{pyflakes.messages.Message}.
[ "pyflakes", "found", "something", "wrong", "with", "the", "code", "." ]
232cb1d27ee134bf96adc8f37e53589dc259b159
https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/reporter.py#L68-L75
240,955
PyCQA/pyflakes
pyflakes/checker.py
counter
def counter(items): """ Simplest required implementation of collections.Counter. Required as 2.6 does not have Counter in collections. """ results = {} for item in items: results[item] = results.get(item, 0) + 1 return results
python
def counter(items): results = {} for item in items: results[item] = results.get(item, 0) + 1 return results
[ "def", "counter", "(", "items", ")", ":", "results", "=", "{", "}", "for", "item", "in", "items", ":", "results", "[", "item", "]", "=", "results", ".", "get", "(", "item", ",", "0", ")", "+", "1", "return", "results" ]
Simplest required implementation of collections.Counter. Required as 2.6 does not have Counter in collections.
[ "Simplest", "required", "implementation", "of", "collections", ".", "Counter", ".", "Required", "as", "2", ".", "6", "does", "not", "have", "Counter", "in", "collections", "." ]
232cb1d27ee134bf96adc8f37e53589dc259b159
https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/checker.py#L103-L111
240,956
PyCQA/pyflakes
pyflakes/checker.py
Importation.source_statement
def source_statement(self): """Generate a source statement equivalent to the import.""" if self._has_alias(): return 'import %s as %s' % (self.fullName, self.name) else: return 'import %s' % self.fullName
python
def source_statement(self): if self._has_alias(): return 'import %s as %s' % (self.fullName, self.name) else: return 'import %s' % self.fullName
[ "def", "source_statement", "(", "self", ")", ":", "if", "self", ".", "_has_alias", "(", ")", ":", "return", "'import %s as %s'", "%", "(", "self", ".", "fullName", ",", "self", ".", "name", ")", "else", ":", "return", "'import %s'", "%", "self", ".", "...
Generate a source statement equivalent to the import.
[ "Generate", "a", "source", "statement", "equivalent", "to", "the", "import", "." ]
232cb1d27ee134bf96adc8f37e53589dc259b159
https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/checker.py#L265-L270
240,957
PyCQA/pyflakes
pyflakes/checker.py
Checker.CLASSDEF
def CLASSDEF(self, node): """ Check names used in a class definition, including its decorators, base classes, and the body of its definition. Additionally, add its name to the current scope. """ for deco in node.decorator_list: self.handleNode(deco, node) for baseNode in node.bases: self.handleNode(baseNode, node) if not PY2: for keywordNode in node.keywords: self.handleNode(keywordNode, node) self.pushScope(ClassScope) # doctest does not process doctest within a doctest # classes within classes are processed. if (self.withDoctest and not self._in_doctest() and not isinstance(self.scope, FunctionScope)): self.deferFunction(lambda: self.handleDoctests(node)) for stmt in node.body: self.handleNode(stmt, node) self.popScope() self.addBinding(node, ClassDefinition(node.name, node))
python
def CLASSDEF(self, node): for deco in node.decorator_list: self.handleNode(deco, node) for baseNode in node.bases: self.handleNode(baseNode, node) if not PY2: for keywordNode in node.keywords: self.handleNode(keywordNode, node) self.pushScope(ClassScope) # doctest does not process doctest within a doctest # classes within classes are processed. if (self.withDoctest and not self._in_doctest() and not isinstance(self.scope, FunctionScope)): self.deferFunction(lambda: self.handleDoctests(node)) for stmt in node.body: self.handleNode(stmt, node) self.popScope() self.addBinding(node, ClassDefinition(node.name, node))
[ "def", "CLASSDEF", "(", "self", ",", "node", ")", ":", "for", "deco", "in", "node", ".", "decorator_list", ":", "self", ".", "handleNode", "(", "deco", ",", "node", ")", "for", "baseNode", "in", "node", ".", "bases", ":", "self", ".", "handleNode", "...
Check names used in a class definition, including its decorators, base classes, and the body of its definition. Additionally, add its name to the current scope.
[ "Check", "names", "used", "in", "a", "class", "definition", "including", "its", "decorators", "base", "classes", "and", "the", "body", "of", "its", "definition", ".", "Additionally", "add", "its", "name", "to", "the", "current", "scope", "." ]
232cb1d27ee134bf96adc8f37e53589dc259b159
https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/checker.py#L1519-L1542
240,958
PyCQA/pyflakes
pyflakes/api.py
isPythonFile
def isPythonFile(filename): """Return True if filename points to a Python file.""" if filename.endswith('.py'): return True # Avoid obvious Emacs backup files if filename.endswith("~"): return False max_bytes = 128 try: with open(filename, 'rb') as f: text = f.read(max_bytes) if not text: return False except IOError: return False first_line = text.splitlines()[0] return PYTHON_SHEBANG_REGEX.match(first_line)
python
def isPythonFile(filename): if filename.endswith('.py'): return True # Avoid obvious Emacs backup files if filename.endswith("~"): return False max_bytes = 128 try: with open(filename, 'rb') as f: text = f.read(max_bytes) if not text: return False except IOError: return False first_line = text.splitlines()[0] return PYTHON_SHEBANG_REGEX.match(first_line)
[ "def", "isPythonFile", "(", "filename", ")", ":", "if", "filename", ".", "endswith", "(", "'.py'", ")", ":", "return", "True", "# Avoid obvious Emacs backup files", "if", "filename", ".", "endswith", "(", "\"~\"", ")", ":", "return", "False", "max_bytes", "=",...
Return True if filename points to a Python file.
[ "Return", "True", "if", "filename", "points", "to", "a", "Python", "file", "." ]
232cb1d27ee134bf96adc8f37e53589dc259b159
https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/api.py#L102-L122
240,959
PyCQA/pyflakes
pyflakes/api.py
_exitOnSignal
def _exitOnSignal(sigName, message): """Handles a signal with sys.exit. Some of these signals (SIGPIPE, for example) don't exist or are invalid on Windows. So, ignore errors that might arise. """ import signal try: sigNumber = getattr(signal, sigName) except AttributeError: # the signal constants defined in the signal module are defined by # whether the C library supports them or not. So, SIGPIPE might not # even be defined. return def handler(sig, f): sys.exit(message) try: signal.signal(sigNumber, handler) except ValueError: # It's also possible the signal is defined, but then it's invalid. In # this case, signal.signal raises ValueError. pass
python
def _exitOnSignal(sigName, message): import signal try: sigNumber = getattr(signal, sigName) except AttributeError: # the signal constants defined in the signal module are defined by # whether the C library supports them or not. So, SIGPIPE might not # even be defined. return def handler(sig, f): sys.exit(message) try: signal.signal(sigNumber, handler) except ValueError: # It's also possible the signal is defined, but then it's invalid. In # this case, signal.signal raises ValueError. pass
[ "def", "_exitOnSignal", "(", "sigName", ",", "message", ")", ":", "import", "signal", "try", ":", "sigNumber", "=", "getattr", "(", "signal", ",", "sigName", ")", "except", "AttributeError", ":", "# the signal constants defined in the signal module are defined by", "#...
Handles a signal with sys.exit. Some of these signals (SIGPIPE, for example) don't exist or are invalid on Windows. So, ignore errors that might arise.
[ "Handles", "a", "signal", "with", "sys", ".", "exit", "." ]
232cb1d27ee134bf96adc8f37e53589dc259b159
https://github.com/PyCQA/pyflakes/blob/232cb1d27ee134bf96adc8f37e53589dc259b159/pyflakes/api.py#L160-L184
240,960
jazzband/django-model-utils
model_utils/managers.py
InheritanceQuerySetMixin._get_subclasses_recurse
def _get_subclasses_recurse(self, model, levels=None): """ Given a Model class, find all related objects, exploring children recursively, returning a `list` of strings representing the relations for select_related """ related_objects = [ f for f in model._meta.get_fields() if isinstance(f, OneToOneRel)] rels = [ rel for rel in related_objects if isinstance(rel.field, OneToOneField) and issubclass(rel.field.model, model) and model is not rel.field.model and rel.parent_link ] subclasses = [] if levels: levels -= 1 for rel in rels: if levels or levels is None: for subclass in self._get_subclasses_recurse( rel.field.model, levels=levels): subclasses.append( rel.get_accessor_name() + LOOKUP_SEP + subclass) subclasses.append(rel.get_accessor_name()) return subclasses
python
def _get_subclasses_recurse(self, model, levels=None): related_objects = [ f for f in model._meta.get_fields() if isinstance(f, OneToOneRel)] rels = [ rel for rel in related_objects if isinstance(rel.field, OneToOneField) and issubclass(rel.field.model, model) and model is not rel.field.model and rel.parent_link ] subclasses = [] if levels: levels -= 1 for rel in rels: if levels or levels is None: for subclass in self._get_subclasses_recurse( rel.field.model, levels=levels): subclasses.append( rel.get_accessor_name() + LOOKUP_SEP + subclass) subclasses.append(rel.get_accessor_name()) return subclasses
[ "def", "_get_subclasses_recurse", "(", "self", ",", "model", ",", "levels", "=", "None", ")", ":", "related_objects", "=", "[", "f", "for", "f", "in", "model", ".", "_meta", ".", "get_fields", "(", ")", "if", "isinstance", "(", "f", ",", "OneToOneRel", ...
Given a Model class, find all related objects, exploring children recursively, returning a `list` of strings representing the relations for select_related
[ "Given", "a", "Model", "class", "find", "all", "related", "objects", "exploring", "children", "recursively", "returning", "a", "list", "of", "strings", "representing", "the", "relations", "for", "select_related" ]
d557c4253312774a7c2f14bcd02675e9ac2ea05f
https://github.com/jazzband/django-model-utils/blob/d557c4253312774a7c2f14bcd02675e9ac2ea05f/model_utils/managers.py#L146-L174
240,961
jazzband/django-model-utils
model_utils/managers.py
InheritanceQuerySetMixin._get_ancestors_path
def _get_ancestors_path(self, model, levels=None): """ Serves as an opposite to _get_subclasses_recurse, instead walking from the Model class up the Model's ancestry and constructing the desired select_related string backwards. """ if not issubclass(model, self.model): raise ValueError( "%r is not a subclass of %r" % (model, self.model)) ancestry = [] # should be a OneToOneField or None parent_link = model._meta.get_ancestor_link(self.model) if levels: levels -= 1 while parent_link is not None: related = parent_link.remote_field ancestry.insert(0, related.get_accessor_name()) if levels or levels is None: parent_model = related.model parent_link = parent_model._meta.get_ancestor_link( self.model) else: parent_link = None return LOOKUP_SEP.join(ancestry)
python
def _get_ancestors_path(self, model, levels=None): if not issubclass(model, self.model): raise ValueError( "%r is not a subclass of %r" % (model, self.model)) ancestry = [] # should be a OneToOneField or None parent_link = model._meta.get_ancestor_link(self.model) if levels: levels -= 1 while parent_link is not None: related = parent_link.remote_field ancestry.insert(0, related.get_accessor_name()) if levels or levels is None: parent_model = related.model parent_link = parent_model._meta.get_ancestor_link( self.model) else: parent_link = None return LOOKUP_SEP.join(ancestry)
[ "def", "_get_ancestors_path", "(", "self", ",", "model", ",", "levels", "=", "None", ")", ":", "if", "not", "issubclass", "(", "model", ",", "self", ".", "model", ")", ":", "raise", "ValueError", "(", "\"%r is not a subclass of %r\"", "%", "(", "model", ",...
Serves as an opposite to _get_subclasses_recurse, instead walking from the Model class up the Model's ancestry and constructing the desired select_related string backwards.
[ "Serves", "as", "an", "opposite", "to", "_get_subclasses_recurse", "instead", "walking", "from", "the", "Model", "class", "up", "the", "Model", "s", "ancestry", "and", "constructing", "the", "desired", "select_related", "string", "backwards", "." ]
d557c4253312774a7c2f14bcd02675e9ac2ea05f
https://github.com/jazzband/django-model-utils/blob/d557c4253312774a7c2f14bcd02675e9ac2ea05f/model_utils/managers.py#L176-L200
240,962
jazzband/django-model-utils
model_utils/managers.py
SoftDeletableManagerMixin.get_queryset
def get_queryset(self): """ Return queryset limited to not removed entries. """ kwargs = {'model': self.model, 'using': self._db} if hasattr(self, '_hints'): kwargs['hints'] = self._hints return self._queryset_class(**kwargs).filter(is_removed=False)
python
def get_queryset(self): kwargs = {'model': self.model, 'using': self._db} if hasattr(self, '_hints'): kwargs['hints'] = self._hints return self._queryset_class(**kwargs).filter(is_removed=False)
[ "def", "get_queryset", "(", "self", ")", ":", "kwargs", "=", "{", "'model'", ":", "self", ".", "model", ",", "'using'", ":", "self", ".", "_db", "}", "if", "hasattr", "(", "self", ",", "'_hints'", ")", ":", "kwargs", "[", "'hints'", "]", "=", "self...
Return queryset limited to not removed entries.
[ "Return", "queryset", "limited", "to", "not", "removed", "entries", "." ]
d557c4253312774a7c2f14bcd02675e9ac2ea05f
https://github.com/jazzband/django-model-utils/blob/d557c4253312774a7c2f14bcd02675e9ac2ea05f/model_utils/managers.py#L295-L303
240,963
jazzband/django-model-utils
model_utils/tracker.py
FieldInstanceTracker.previous
def previous(self, field): """Returns currently saved value of given field""" # handle deferred fields that have not yet been loaded from the database if self.instance.pk and field in self.deferred_fields and field not in self.saved_data: # if the field has not been assigned locally, simply fetch and un-defer the value if field not in self.instance.__dict__: self.get_field_value(field) # if the field has been assigned locally, store the local value, fetch the database value, # store database value to saved_data, and restore the local value else: current_value = self.get_field_value(field) self.instance.refresh_from_db(fields=[field]) self.saved_data[field] = deepcopy(self.get_field_value(field)) setattr(self.instance, self.field_map[field], current_value) return self.saved_data.get(field)
python
def previous(self, field): # handle deferred fields that have not yet been loaded from the database if self.instance.pk and field in self.deferred_fields and field not in self.saved_data: # if the field has not been assigned locally, simply fetch and un-defer the value if field not in self.instance.__dict__: self.get_field_value(field) # if the field has been assigned locally, store the local value, fetch the database value, # store database value to saved_data, and restore the local value else: current_value = self.get_field_value(field) self.instance.refresh_from_db(fields=[field]) self.saved_data[field] = deepcopy(self.get_field_value(field)) setattr(self.instance, self.field_map[field], current_value) return self.saved_data.get(field)
[ "def", "previous", "(", "self", ",", "field", ")", ":", "# handle deferred fields that have not yet been loaded from the database", "if", "self", ".", "instance", ".", "pk", "and", "field", "in", "self", ".", "deferred_fields", "and", "field", "not", "in", "self", ...
Returns currently saved value of given field
[ "Returns", "currently", "saved", "value", "of", "given", "field" ]
d557c4253312774a7c2f14bcd02675e9ac2ea05f
https://github.com/jazzband/django-model-utils/blob/d557c4253312774a7c2f14bcd02675e9ac2ea05f/model_utils/tracker.py#L142-L160
240,964
jazzband/django-model-utils
model_utils/tracker.py
FieldTracker.get_field_map
def get_field_map(self, cls): """Returns dict mapping fields names to model attribute names""" field_map = dict((field, field) for field in self.fields) all_fields = dict((f.name, f.attname) for f in cls._meta.fields) field_map.update(**dict((k, v) for (k, v) in all_fields.items() if k in field_map)) return field_map
python
def get_field_map(self, cls): field_map = dict((field, field) for field in self.fields) all_fields = dict((f.name, f.attname) for f in cls._meta.fields) field_map.update(**dict((k, v) for (k, v) in all_fields.items() if k in field_map)) return field_map
[ "def", "get_field_map", "(", "self", ",", "cls", ")", ":", "field_map", "=", "dict", "(", "(", "field", ",", "field", ")", "for", "field", "in", "self", ".", "fields", ")", "all_fields", "=", "dict", "(", "(", "f", ".", "name", ",", "f", ".", "at...
Returns dict mapping fields names to model attribute names
[ "Returns", "dict", "mapping", "fields", "names", "to", "model", "attribute", "names" ]
d557c4253312774a7c2f14bcd02675e9ac2ea05f
https://github.com/jazzband/django-model-utils/blob/d557c4253312774a7c2f14bcd02675e9ac2ea05f/model_utils/tracker.py#L202-L208
240,965
jazzband/django-model-utils
model_utils/models.py
add_status_query_managers
def add_status_query_managers(sender, **kwargs): """ Add a Querymanager for each status item dynamically. """ if not issubclass(sender, StatusModel): return if django.VERSION >= (1, 10): # First, get current manager name... default_manager = sender._meta.default_manager for value, display in getattr(sender, 'STATUS', ()): if _field_exists(sender, value): raise ImproperlyConfigured( "StatusModel: Model '%s' has a field named '%s' which " "conflicts with a status of the same name." % (sender.__name__, value) ) sender.add_to_class(value, QueryManager(status=value)) if django.VERSION >= (1, 10): # ...then, put it back, as add_to_class is modifying the default manager! sender._meta.default_manager_name = default_manager.name
python
def add_status_query_managers(sender, **kwargs): if not issubclass(sender, StatusModel): return if django.VERSION >= (1, 10): # First, get current manager name... default_manager = sender._meta.default_manager for value, display in getattr(sender, 'STATUS', ()): if _field_exists(sender, value): raise ImproperlyConfigured( "StatusModel: Model '%s' has a field named '%s' which " "conflicts with a status of the same name." % (sender.__name__, value) ) sender.add_to_class(value, QueryManager(status=value)) if django.VERSION >= (1, 10): # ...then, put it back, as add_to_class is modifying the default manager! sender._meta.default_manager_name = default_manager.name
[ "def", "add_status_query_managers", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "if", "not", "issubclass", "(", "sender", ",", "StatusModel", ")", ":", "return", "if", "django", ".", "VERSION", ">=", "(", "1", ",", "10", ")", ":", "# First, get cur...
Add a Querymanager for each status item dynamically.
[ "Add", "a", "Querymanager", "for", "each", "status", "item", "dynamically", "." ]
d557c4253312774a7c2f14bcd02675e9ac2ea05f
https://github.com/jazzband/django-model-utils/blob/d557c4253312774a7c2f14bcd02675e9ac2ea05f/model_utils/models.py#L60-L83
240,966
jazzband/django-model-utils
model_utils/models.py
add_timeframed_query_manager
def add_timeframed_query_manager(sender, **kwargs): """ Add a QueryManager for a specific timeframe. """ if not issubclass(sender, TimeFramedModel): return if _field_exists(sender, 'timeframed'): raise ImproperlyConfigured( "Model '%s' has a field named 'timeframed' " "which conflicts with the TimeFramedModel manager." % sender.__name__ ) sender.add_to_class('timeframed', QueryManager( (models.Q(start__lte=now) | models.Q(start__isnull=True)) & (models.Q(end__gte=now) | models.Q(end__isnull=True)) ))
python
def add_timeframed_query_manager(sender, **kwargs): if not issubclass(sender, TimeFramedModel): return if _field_exists(sender, 'timeframed'): raise ImproperlyConfigured( "Model '%s' has a field named 'timeframed' " "which conflicts with the TimeFramedModel manager." % sender.__name__ ) sender.add_to_class('timeframed', QueryManager( (models.Q(start__lte=now) | models.Q(start__isnull=True)) & (models.Q(end__gte=now) | models.Q(end__isnull=True)) ))
[ "def", "add_timeframed_query_manager", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "if", "not", "issubclass", "(", "sender", ",", "TimeFramedModel", ")", ":", "return", "if", "_field_exists", "(", "sender", ",", "'timeframed'", ")", ":", "raise", "Impr...
Add a QueryManager for a specific timeframe.
[ "Add", "a", "QueryManager", "for", "a", "specific", "timeframe", "." ]
d557c4253312774a7c2f14bcd02675e9ac2ea05f
https://github.com/jazzband/django-model-utils/blob/d557c4253312774a7c2f14bcd02675e9ac2ea05f/model_utils/models.py#L86-L102
240,967
invoice-x/invoice2data
src/invoice2data/input/tesseract4.py
to_text
def to_text(path, language='fra'): """Wraps Tesseract 4 OCR with custom language model. Parameters ---------- path : str path of electronic invoice in JPG or PNG format Returns ------- extracted_str : str returns extracted text from image in JPG or PNG format """ import subprocess from distutils import spawn import tempfile import time # Check for dependencies. Needs Tesseract and Imagemagick installed. if not spawn.find_executable('tesseract'): raise EnvironmentError('tesseract not installed.') if not spawn.find_executable('convert'): raise EnvironmentError('imagemagick not installed.') if not spawn.find_executable('gs'): raise EnvironmentError('ghostscript not installed.') with tempfile.NamedTemporaryFile(suffix='.tiff') as tf: # Step 1: Convert to TIFF gs_cmd = [ 'gs', '-q', '-dNOPAUSE', '-r600x600', '-sDEVICE=tiff24nc', '-sOutputFile=' + tf.name, path, '-c', 'quit', ] subprocess.Popen(gs_cmd) time.sleep(3) # Step 2: Enhance TIFF magick_cmd = [ 'convert', tf.name, '-colorspace', 'gray', '-type', 'grayscale', '-contrast-stretch', '0', '-sharpen', '0x1', 'tiff:-', ] p1 = subprocess.Popen(magick_cmd, stdout=subprocess.PIPE) tess_cmd = ['tesseract', '-l', language, '--oem', '1', '--psm', '3', 'stdin', 'stdout'] p2 = subprocess.Popen(tess_cmd, stdin=p1.stdout, stdout=subprocess.PIPE) out, err = p2.communicate() extracted_str = out return extracted_str
python
def to_text(path, language='fra'): import subprocess from distutils import spawn import tempfile import time # Check for dependencies. Needs Tesseract and Imagemagick installed. if not spawn.find_executable('tesseract'): raise EnvironmentError('tesseract not installed.') if not spawn.find_executable('convert'): raise EnvironmentError('imagemagick not installed.') if not spawn.find_executable('gs'): raise EnvironmentError('ghostscript not installed.') with tempfile.NamedTemporaryFile(suffix='.tiff') as tf: # Step 1: Convert to TIFF gs_cmd = [ 'gs', '-q', '-dNOPAUSE', '-r600x600', '-sDEVICE=tiff24nc', '-sOutputFile=' + tf.name, path, '-c', 'quit', ] subprocess.Popen(gs_cmd) time.sleep(3) # Step 2: Enhance TIFF magick_cmd = [ 'convert', tf.name, '-colorspace', 'gray', '-type', 'grayscale', '-contrast-stretch', '0', '-sharpen', '0x1', 'tiff:-', ] p1 = subprocess.Popen(magick_cmd, stdout=subprocess.PIPE) tess_cmd = ['tesseract', '-l', language, '--oem', '1', '--psm', '3', 'stdin', 'stdout'] p2 = subprocess.Popen(tess_cmd, stdin=p1.stdout, stdout=subprocess.PIPE) out, err = p2.communicate() extracted_str = out return extracted_str
[ "def", "to_text", "(", "path", ",", "language", "=", "'fra'", ")", ":", "import", "subprocess", "from", "distutils", "import", "spawn", "import", "tempfile", "import", "time", "# Check for dependencies. Needs Tesseract and Imagemagick installed.", "if", "not", "spawn", ...
Wraps Tesseract 4 OCR with custom language model. Parameters ---------- path : str path of electronic invoice in JPG or PNG format Returns ------- extracted_str : str returns extracted text from image in JPG or PNG format
[ "Wraps", "Tesseract", "4", "OCR", "with", "custom", "language", "model", "." ]
d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20
https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/input/tesseract4.py#L2-L69
240,968
invoice-x/invoice2data
src/invoice2data/input/gvision.py
to_text
def to_text(path, bucket_name='cloud-vision-84893', language='fr'): """Sends PDF files to Google Cloud Vision for OCR. Before using invoice2data, make sure you have the auth json path set as env var GOOGLE_APPLICATION_CREDENTIALS Parameters ---------- path : str path of electronic invoice in JPG or PNG format bucket_name : str name of bucket to use for file storage and results cache. Returns ------- extracted_str : str returns extracted text from image in JPG or PNG format """ """OCR with PDF/TIFF as source files on GCS""" import os from google.cloud import vision from google.cloud import storage from google.protobuf import json_format # Supported mime_types are: 'application/pdf' and 'image/tiff' mime_type = 'application/pdf' path_dir, filename = os.path.split(path) result_blob_basename = filename.replace('.pdf', '').replace('.PDF', '') result_blob_name = result_blob_basename + '/output-1-to-1.json' result_blob_uri = 'gs://{}/{}/'.format(bucket_name, result_blob_basename) input_blob_uri = 'gs://{}/{}'.format(bucket_name, filename) # Upload file to gcloud if it doesn't exist yet storage_client = storage.Client() bucket = storage_client.get_bucket(bucket_name) if bucket.get_blob(filename) is None: blob = bucket.blob(filename) blob.upload_from_filename(path) # See if result already exists # TODO: upload as hash, not filename result_blob = bucket.get_blob(result_blob_name) if result_blob is None: # How many pages should be grouped into each json output file. batch_size = 10 client = vision.ImageAnnotatorClient() feature = vision.types.Feature(type=vision.enums.Feature.Type.DOCUMENT_TEXT_DETECTION) gcs_source = vision.types.GcsSource(uri=input_blob_uri) input_config = vision.types.InputConfig(gcs_source=gcs_source, mime_type=mime_type) gcs_destination = vision.types.GcsDestination(uri=result_blob_uri) output_config = vision.types.OutputConfig( gcs_destination=gcs_destination, batch_size=batch_size ) async_request = vision.types.AsyncAnnotateFileRequest( features=[feature], input_config=input_config, output_config=output_config ) operation = client.async_batch_annotate_files(requests=[async_request]) print('Waiting for the operation to finish.') operation.result(timeout=180) # Get result after OCR is completed result_blob = bucket.get_blob(result_blob_name) json_string = result_blob.download_as_string() response = json_format.Parse(json_string, vision.types.AnnotateFileResponse()) # The actual response for the first page of the input file. first_page_response = response.responses[0] annotation = first_page_response.full_text_annotation return annotation.text.encode('utf-8')
python
def to_text(path, bucket_name='cloud-vision-84893', language='fr'): """OCR with PDF/TIFF as source files on GCS""" import os from google.cloud import vision from google.cloud import storage from google.protobuf import json_format # Supported mime_types are: 'application/pdf' and 'image/tiff' mime_type = 'application/pdf' path_dir, filename = os.path.split(path) result_blob_basename = filename.replace('.pdf', '').replace('.PDF', '') result_blob_name = result_blob_basename + '/output-1-to-1.json' result_blob_uri = 'gs://{}/{}/'.format(bucket_name, result_blob_basename) input_blob_uri = 'gs://{}/{}'.format(bucket_name, filename) # Upload file to gcloud if it doesn't exist yet storage_client = storage.Client() bucket = storage_client.get_bucket(bucket_name) if bucket.get_blob(filename) is None: blob = bucket.blob(filename) blob.upload_from_filename(path) # See if result already exists # TODO: upload as hash, not filename result_blob = bucket.get_blob(result_blob_name) if result_blob is None: # How many pages should be grouped into each json output file. batch_size = 10 client = vision.ImageAnnotatorClient() feature = vision.types.Feature(type=vision.enums.Feature.Type.DOCUMENT_TEXT_DETECTION) gcs_source = vision.types.GcsSource(uri=input_blob_uri) input_config = vision.types.InputConfig(gcs_source=gcs_source, mime_type=mime_type) gcs_destination = vision.types.GcsDestination(uri=result_blob_uri) output_config = vision.types.OutputConfig( gcs_destination=gcs_destination, batch_size=batch_size ) async_request = vision.types.AsyncAnnotateFileRequest( features=[feature], input_config=input_config, output_config=output_config ) operation = client.async_batch_annotate_files(requests=[async_request]) print('Waiting for the operation to finish.') operation.result(timeout=180) # Get result after OCR is completed result_blob = bucket.get_blob(result_blob_name) json_string = result_blob.download_as_string() response = json_format.Parse(json_string, vision.types.AnnotateFileResponse()) # The actual response for the first page of the input file. first_page_response = response.responses[0] annotation = first_page_response.full_text_annotation return annotation.text.encode('utf-8')
[ "def", "to_text", "(", "path", ",", "bucket_name", "=", "'cloud-vision-84893'", ",", "language", "=", "'fr'", ")", ":", "\"\"\"OCR with PDF/TIFF as source files on GCS\"\"\"", "import", "os", "from", "google", ".", "cloud", "import", "vision", "from", "google", ".",...
Sends PDF files to Google Cloud Vision for OCR. Before using invoice2data, make sure you have the auth json path set as env var GOOGLE_APPLICATION_CREDENTIALS Parameters ---------- path : str path of electronic invoice in JPG or PNG format bucket_name : str name of bucket to use for file storage and results cache. Returns ------- extracted_str : str returns extracted text from image in JPG or PNG format
[ "Sends", "PDF", "files", "to", "Google", "Cloud", "Vision", "for", "OCR", "." ]
d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20
https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/input/gvision.py#L2-L83
240,969
invoice-x/invoice2data
src/invoice2data/output/to_csv.py
write_to_file
def write_to_file(data, path): """Export extracted fields to csv Appends .csv to path if missing and generates csv file in specified directory, if not then in root Parameters ---------- data : dict Dictionary of extracted fields path : str directory to save generated csv file Notes ---- Do give file name to the function parameter path. Examples -------- >>> from invoice2data.output import to_csv >>> to_csv.write_to_file(data, "/exported_csv/invoice.csv") >>> to_csv.write_to_file(data, "invoice.csv") """ if path.endswith('.csv'): filename = path else: filename = path + '.csv' if sys.version_info[0] < 3: openfile = open(filename, "wb") else: openfile = open(filename, "w", newline='') with openfile as csv_file: writer = csv.writer(csv_file, delimiter=',') for line in data: first_row = [] for k, v in line.items(): first_row.append(k) writer.writerow(first_row) for line in data: csv_items = [] for k, v in line.items(): # first_row.append(k) if k == 'date': v = v.strftime('%d/%m/%Y') csv_items.append(v) writer.writerow(csv_items)
python
def write_to_file(data, path): if path.endswith('.csv'): filename = path else: filename = path + '.csv' if sys.version_info[0] < 3: openfile = open(filename, "wb") else: openfile = open(filename, "w", newline='') with openfile as csv_file: writer = csv.writer(csv_file, delimiter=',') for line in data: first_row = [] for k, v in line.items(): first_row.append(k) writer.writerow(first_row) for line in data: csv_items = [] for k, v in line.items(): # first_row.append(k) if k == 'date': v = v.strftime('%d/%m/%Y') csv_items.append(v) writer.writerow(csv_items)
[ "def", "write_to_file", "(", "data", ",", "path", ")", ":", "if", "path", ".", "endswith", "(", "'.csv'", ")", ":", "filename", "=", "path", "else", ":", "filename", "=", "path", "+", "'.csv'", "if", "sys", ".", "version_info", "[", "0", "]", "<", ...
Export extracted fields to csv Appends .csv to path if missing and generates csv file in specified directory, if not then in root Parameters ---------- data : dict Dictionary of extracted fields path : str directory to save generated csv file Notes ---- Do give file name to the function parameter path. Examples -------- >>> from invoice2data.output import to_csv >>> to_csv.write_to_file(data, "/exported_csv/invoice.csv") >>> to_csv.write_to_file(data, "invoice.csv")
[ "Export", "extracted", "fields", "to", "csv" ]
d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20
https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/output/to_csv.py#L5-L54
240,970
invoice-x/invoice2data
src/invoice2data/input/tesseract.py
to_text
def to_text(path): """Wraps Tesseract OCR. Parameters ---------- path : str path of electronic invoice in JPG or PNG format Returns ------- extracted_str : str returns extracted text from image in JPG or PNG format """ import subprocess from distutils import spawn # Check for dependencies. Needs Tesseract and Imagemagick installed. if not spawn.find_executable('tesseract'): raise EnvironmentError('tesseract not installed.') if not spawn.find_executable('convert'): raise EnvironmentError('imagemagick not installed.') # convert = "convert -density 350 %s -depth 8 tiff:-" % (path) convert = ['convert', '-density', '350', path, '-depth', '8', 'png:-'] p1 = subprocess.Popen(convert, stdout=subprocess.PIPE) tess = ['tesseract', 'stdin', 'stdout'] p2 = subprocess.Popen(tess, stdin=p1.stdout, stdout=subprocess.PIPE) out, err = p2.communicate() extracted_str = out return extracted_str
python
def to_text(path): import subprocess from distutils import spawn # Check for dependencies. Needs Tesseract and Imagemagick installed. if not spawn.find_executable('tesseract'): raise EnvironmentError('tesseract not installed.') if not spawn.find_executable('convert'): raise EnvironmentError('imagemagick not installed.') # convert = "convert -density 350 %s -depth 8 tiff:-" % (path) convert = ['convert', '-density', '350', path, '-depth', '8', 'png:-'] p1 = subprocess.Popen(convert, stdout=subprocess.PIPE) tess = ['tesseract', 'stdin', 'stdout'] p2 = subprocess.Popen(tess, stdin=p1.stdout, stdout=subprocess.PIPE) out, err = p2.communicate() extracted_str = out return extracted_str
[ "def", "to_text", "(", "path", ")", ":", "import", "subprocess", "from", "distutils", "import", "spawn", "# Check for dependencies. Needs Tesseract and Imagemagick installed.", "if", "not", "spawn", ".", "find_executable", "(", "'tesseract'", ")", ":", "raise", "Environ...
Wraps Tesseract OCR. Parameters ---------- path : str path of electronic invoice in JPG or PNG format Returns ------- extracted_str : str returns extracted text from image in JPG or PNG format
[ "Wraps", "Tesseract", "OCR", "." ]
d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20
https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/input/tesseract.py#L4-L38
240,971
invoice-x/invoice2data
src/invoice2data/extract/plugins/tables.py
extract
def extract(self, content, output): """Try to extract tables from an invoice""" for table in self['tables']: # First apply default options. plugin_settings = DEFAULT_OPTIONS.copy() plugin_settings.update(table) table = plugin_settings # Validate settings assert 'start' in table, 'Table start regex missing' assert 'end' in table, 'Table end regex missing' assert 'body' in table, 'Table body regex missing' start = re.search(table['start'], content) end = re.search(table['end'], content) if not start or not end: logger.warning('no table body found - start %s, end %s', start, end) continue table_body = content[start.end(): end.start()] for line in re.split(table['line_separator'], table_body): # if the line has empty lines in it , skip them if not line.strip('').strip('\n') or not line: continue match = re.search(table['body'], line) if match: for field, value in match.groupdict().items(): # If a field name already exists, do not overwrite it if field in output: continue if field.startswith('date') or field.endswith('date'): output[field] = self.parse_date(value) if not output[field]: logger.error("Date parsing failed on date '%s'", value) return None elif field.startswith('amount'): output[field] = self.parse_number(value) else: output[field] = value logger.debug('ignoring *%s* because it doesn\'t match anything', line)
python
def extract(self, content, output): for table in self['tables']: # First apply default options. plugin_settings = DEFAULT_OPTIONS.copy() plugin_settings.update(table) table = plugin_settings # Validate settings assert 'start' in table, 'Table start regex missing' assert 'end' in table, 'Table end regex missing' assert 'body' in table, 'Table body regex missing' start = re.search(table['start'], content) end = re.search(table['end'], content) if not start or not end: logger.warning('no table body found - start %s, end %s', start, end) continue table_body = content[start.end(): end.start()] for line in re.split(table['line_separator'], table_body): # if the line has empty lines in it , skip them if not line.strip('').strip('\n') or not line: continue match = re.search(table['body'], line) if match: for field, value in match.groupdict().items(): # If a field name already exists, do not overwrite it if field in output: continue if field.startswith('date') or field.endswith('date'): output[field] = self.parse_date(value) if not output[field]: logger.error("Date parsing failed on date '%s'", value) return None elif field.startswith('amount'): output[field] = self.parse_number(value) else: output[field] = value logger.debug('ignoring *%s* because it doesn\'t match anything', line)
[ "def", "extract", "(", "self", ",", "content", ",", "output", ")", ":", "for", "table", "in", "self", "[", "'tables'", "]", ":", "# First apply default options.", "plugin_settings", "=", "DEFAULT_OPTIONS", ".", "copy", "(", ")", "plugin_settings", ".", "update...
Try to extract tables from an invoice
[ "Try", "to", "extract", "tables", "from", "an", "invoice" ]
d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20
https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/extract/plugins/tables.py#L11-L56
240,972
invoice-x/invoice2data
src/invoice2data/input/pdftotext.py
to_text
def to_text(path): """Wrapper around Poppler pdftotext. Parameters ---------- path : str path of electronic invoice in PDF Returns ------- out : str returns extracted text from pdf Raises ------ EnvironmentError: If pdftotext library is not found """ import subprocess from distutils import spawn # py2 compat if spawn.find_executable("pdftotext"): # shutil.which('pdftotext'): out, err = subprocess.Popen( ["pdftotext", '-layout', '-enc', 'UTF-8', path, '-'], stdout=subprocess.PIPE ).communicate() return out else: raise EnvironmentError( 'pdftotext not installed. Can be downloaded from https://poppler.freedesktop.org/' )
python
def to_text(path): import subprocess from distutils import spawn # py2 compat if spawn.find_executable("pdftotext"): # shutil.which('pdftotext'): out, err = subprocess.Popen( ["pdftotext", '-layout', '-enc', 'UTF-8', path, '-'], stdout=subprocess.PIPE ).communicate() return out else: raise EnvironmentError( 'pdftotext not installed. Can be downloaded from https://poppler.freedesktop.org/' )
[ "def", "to_text", "(", "path", ")", ":", "import", "subprocess", "from", "distutils", "import", "spawn", "# py2 compat", "if", "spawn", ".", "find_executable", "(", "\"pdftotext\"", ")", ":", "# shutil.which('pdftotext'):", "out", ",", "err", "=", "subprocess", ...
Wrapper around Poppler pdftotext. Parameters ---------- path : str path of electronic invoice in PDF Returns ------- out : str returns extracted text from pdf Raises ------ EnvironmentError: If pdftotext library is not found
[ "Wrapper", "around", "Poppler", "pdftotext", "." ]
d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20
https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/input/pdftotext.py#L2-L31
240,973
invoice-x/invoice2data
src/invoice2data/extract/invoice_template.py
InvoiceTemplate.prepare_input
def prepare_input(self, extracted_str): """ Input raw string and do transformations, as set in template file. """ # Remove withspace if self.options['remove_whitespace']: optimized_str = re.sub(' +', '', extracted_str) else: optimized_str = extracted_str # Remove accents if self.options['remove_accents']: optimized_str = unidecode(optimized_str) # convert to lower case if self.options['lowercase']: optimized_str = optimized_str.lower() # specific replace for replace in self.options['replace']: assert len(replace) == 2, 'A replace should be a list of 2 items' optimized_str = optimized_str.replace(replace[0], replace[1]) return optimized_str
python
def prepare_input(self, extracted_str): # Remove withspace if self.options['remove_whitespace']: optimized_str = re.sub(' +', '', extracted_str) else: optimized_str = extracted_str # Remove accents if self.options['remove_accents']: optimized_str = unidecode(optimized_str) # convert to lower case if self.options['lowercase']: optimized_str = optimized_str.lower() # specific replace for replace in self.options['replace']: assert len(replace) == 2, 'A replace should be a list of 2 items' optimized_str = optimized_str.replace(replace[0], replace[1]) return optimized_str
[ "def", "prepare_input", "(", "self", ",", "extracted_str", ")", ":", "# Remove withspace", "if", "self", ".", "options", "[", "'remove_whitespace'", "]", ":", "optimized_str", "=", "re", ".", "sub", "(", "' +'", ",", "''", ",", "extracted_str", ")", "else", ...
Input raw string and do transformations, as set in template file.
[ "Input", "raw", "string", "and", "do", "transformations", "as", "set", "in", "template", "file", "." ]
d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20
https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/extract/invoice_template.py#L64-L88
240,974
invoice-x/invoice2data
src/invoice2data/extract/invoice_template.py
InvoiceTemplate.matches_input
def matches_input(self, optimized_str): """See if string matches keywords set in template file""" if all([keyword in optimized_str for keyword in self['keywords']]): logger.debug('Matched template %s', self['template_name']) return True
python
def matches_input(self, optimized_str): if all([keyword in optimized_str for keyword in self['keywords']]): logger.debug('Matched template %s', self['template_name']) return True
[ "def", "matches_input", "(", "self", ",", "optimized_str", ")", ":", "if", "all", "(", "[", "keyword", "in", "optimized_str", "for", "keyword", "in", "self", "[", "'keywords'", "]", "]", ")", ":", "logger", ".", "debug", "(", "'Matched template %s'", ",", ...
See if string matches keywords set in template file
[ "See", "if", "string", "matches", "keywords", "set", "in", "template", "file" ]
d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20
https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/extract/invoice_template.py#L90-L95
240,975
invoice-x/invoice2data
src/invoice2data/extract/invoice_template.py
InvoiceTemplate.parse_date
def parse_date(self, value): """Parses date and returns date after parsing""" res = dateparser.parse( value, date_formats=self.options['date_formats'], languages=self.options['languages'] ) logger.debug("result of date parsing=%s", res) return res
python
def parse_date(self, value): res = dateparser.parse( value, date_formats=self.options['date_formats'], languages=self.options['languages'] ) logger.debug("result of date parsing=%s", res) return res
[ "def", "parse_date", "(", "self", ",", "value", ")", ":", "res", "=", "dateparser", ".", "parse", "(", "value", ",", "date_formats", "=", "self", ".", "options", "[", "'date_formats'", "]", ",", "languages", "=", "self", ".", "options", "[", "'languages'...
Parses date and returns date after parsing
[ "Parses", "date", "and", "returns", "date", "after", "parsing" ]
d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20
https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/extract/invoice_template.py#L108-L114
240,976
invoice-x/invoice2data
src/invoice2data/output/to_json.py
write_to_file
def write_to_file(data, path): """Export extracted fields to json Appends .json to path if missing and generates json file in specified directory, if not then in root Parameters ---------- data : dict Dictionary of extracted fields path : str directory to save generated json file Notes ---- Do give file name to the function parameter path. Examples -------- >>> from invoice2data.output import to_json >>> to_json.write_to_file(data, "/exported_json/invoice.json") >>> to_json.write_to_file(data, "invoice.json") """ if path.endswith('.json'): filename = path else: filename = path + '.json' with codecs.open(filename, "w", encoding='utf-8') as json_file: for line in data: line['date'] = line['date'].strftime('%d/%m/%Y') print(type(json)) print(json) json.dump( data, json_file, indent=4, sort_keys=True, default=myconverter, ensure_ascii=False )
python
def write_to_file(data, path): if path.endswith('.json'): filename = path else: filename = path + '.json' with codecs.open(filename, "w", encoding='utf-8') as json_file: for line in data: line['date'] = line['date'].strftime('%d/%m/%Y') print(type(json)) print(json) json.dump( data, json_file, indent=4, sort_keys=True, default=myconverter, ensure_ascii=False )
[ "def", "write_to_file", "(", "data", ",", "path", ")", ":", "if", "path", ".", "endswith", "(", "'.json'", ")", ":", "filename", "=", "path", "else", ":", "filename", "=", "path", "+", "'.json'", "with", "codecs", ".", "open", "(", "filename", ",", "...
Export extracted fields to json Appends .json to path if missing and generates json file in specified directory, if not then in root Parameters ---------- data : dict Dictionary of extracted fields path : str directory to save generated json file Notes ---- Do give file name to the function parameter path. Examples -------- >>> from invoice2data.output import to_json >>> to_json.write_to_file(data, "/exported_json/invoice.json") >>> to_json.write_to_file(data, "invoice.json")
[ "Export", "extracted", "fields", "to", "json" ]
d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20
https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/output/to_json.py#L12-L47
240,977
invoice-x/invoice2data
src/invoice2data/main.py
create_parser
def create_parser(): """Returns argument parser """ parser = argparse.ArgumentParser( description='Extract structured data from PDF files and save to CSV or JSON.' ) parser.add_argument( '--input-reader', choices=input_mapping.keys(), default='pdftotext', help='Choose text extraction function. Default: pdftotext', ) parser.add_argument( '--output-format', choices=output_mapping.keys(), default='none', help='Choose output format. Default: none', ) parser.add_argument( '--output-name', '-o', dest='output_name', default='invoices-output', help='Custom name for output file. Extension is added based on chosen format.', ) parser.add_argument( '--debug', dest='debug', action='store_true', help='Enable debug information.' ) parser.add_argument( '--copy', '-c', dest='copy', help='Copy and rename processed PDFs to specified folder.' ) parser.add_argument( '--move', '-m', dest='move', help='Move and rename processed PDFs to specified folder.' ) parser.add_argument( '--filename-format', dest='filename', default="{date} {invoice_number} {desc}.pdf", help='Filename format to use when moving or copying processed PDFs.' 'Default: "{date} {invoice_number} {desc}.pdf"', ) parser.add_argument( '--template-folder', '-t', dest='template_folder', help='Folder containing invoice templates in yml file. Always adds built-in templates.', ) parser.add_argument( '--exclude-built-in-templates', dest='exclude_built_in_templates', default=False, help='Ignore built-in templates.', action="store_true", ) parser.add_argument( 'input_files', type=argparse.FileType('r'), nargs='+', help='File or directory to analyze.' ) return parser
python
def create_parser(): parser = argparse.ArgumentParser( description='Extract structured data from PDF files and save to CSV or JSON.' ) parser.add_argument( '--input-reader', choices=input_mapping.keys(), default='pdftotext', help='Choose text extraction function. Default: pdftotext', ) parser.add_argument( '--output-format', choices=output_mapping.keys(), default='none', help='Choose output format. Default: none', ) parser.add_argument( '--output-name', '-o', dest='output_name', default='invoices-output', help='Custom name for output file. Extension is added based on chosen format.', ) parser.add_argument( '--debug', dest='debug', action='store_true', help='Enable debug information.' ) parser.add_argument( '--copy', '-c', dest='copy', help='Copy and rename processed PDFs to specified folder.' ) parser.add_argument( '--move', '-m', dest='move', help='Move and rename processed PDFs to specified folder.' ) parser.add_argument( '--filename-format', dest='filename', default="{date} {invoice_number} {desc}.pdf", help='Filename format to use when moving or copying processed PDFs.' 'Default: "{date} {invoice_number} {desc}.pdf"', ) parser.add_argument( '--template-folder', '-t', dest='template_folder', help='Folder containing invoice templates in yml file. Always adds built-in templates.', ) parser.add_argument( '--exclude-built-in-templates', dest='exclude_built_in_templates', default=False, help='Ignore built-in templates.', action="store_true", ) parser.add_argument( 'input_files', type=argparse.FileType('r'), nargs='+', help='File or directory to analyze.' ) return parser
[ "def", "create_parser", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Extract structured data from PDF files and save to CSV or JSON.'", ")", "parser", ".", "add_argument", "(", "'--input-reader'", ",", "choices", "=", "inpu...
Returns argument parser
[ "Returns", "argument", "parser" ]
d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20
https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/main.py#L99-L167
240,978
invoice-x/invoice2data
src/invoice2data/main.py
main
def main(args=None): """Take folder or single file and analyze each.""" if args is None: parser = create_parser() args = parser.parse_args() if args.debug: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) input_module = input_mapping[args.input_reader] output_module = output_mapping[args.output_format] templates = [] # Load templates from external folder if set. if args.template_folder: templates += read_templates(os.path.abspath(args.template_folder)) # Load internal templates, if not disabled. if not args.exclude_built_in_templates: templates += read_templates() output = [] for f in args.input_files: res = extract_data(f.name, templates=templates, input_module=input_module) if res: logger.info(res) output.append(res) if args.copy: filename = args.filename.format( date=res['date'].strftime('%Y-%m-%d'), invoice_number=res['invoice_number'], desc=res['desc'], ) shutil.copyfile(f.name, join(args.copy, filename)) if args.move: filename = args.filename.format( date=res['date'].strftime('%Y-%m-%d'), invoice_number=res['invoice_number'], desc=res['desc'], ) shutil.move(f.name, join(args.move, filename)) f.close() if output_module is not None: output_module.write_to_file(output, args.output_name)
python
def main(args=None): if args is None: parser = create_parser() args = parser.parse_args() if args.debug: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) input_module = input_mapping[args.input_reader] output_module = output_mapping[args.output_format] templates = [] # Load templates from external folder if set. if args.template_folder: templates += read_templates(os.path.abspath(args.template_folder)) # Load internal templates, if not disabled. if not args.exclude_built_in_templates: templates += read_templates() output = [] for f in args.input_files: res = extract_data(f.name, templates=templates, input_module=input_module) if res: logger.info(res) output.append(res) if args.copy: filename = args.filename.format( date=res['date'].strftime('%Y-%m-%d'), invoice_number=res['invoice_number'], desc=res['desc'], ) shutil.copyfile(f.name, join(args.copy, filename)) if args.move: filename = args.filename.format( date=res['date'].strftime('%Y-%m-%d'), invoice_number=res['invoice_number'], desc=res['desc'], ) shutil.move(f.name, join(args.move, filename)) f.close() if output_module is not None: output_module.write_to_file(output, args.output_name)
[ "def", "main", "(", "args", "=", "None", ")", ":", "if", "args", "is", "None", ":", "parser", "=", "create_parser", "(", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "if", "args", ".", "debug", ":", "logging", ".", "basicConfig", "(", "...
Take folder or single file and analyze each.
[ "Take", "folder", "or", "single", "file", "and", "analyze", "each", "." ]
d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20
https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/main.py#L170-L215
240,979
invoice-x/invoice2data
src/invoice2data/output/to_xml.py
write_to_file
def write_to_file(data, path): """Export extracted fields to xml Appends .xml to path if missing and generates xml file in specified directory, if not then in root Parameters ---------- data : dict Dictionary of extracted fields path : str directory to save generated xml file Notes ---- Do give file name to the function parameter path. Only `date`, `desc`, `amount` and `currency` are exported Examples -------- >>> from invoice2data.output import to_xml >>> to_xml.write_to_file(data, "/exported_xml/invoice.xml") >>> to_xml.write_to_file(data, "invoice.xml") """ if path.endswith('.xml'): filename = path else: filename = path + '.xml' tag_data = ET.Element('data') xml_file = open(filename, "w") i = 0 for line in data: i += 1 tag_item = ET.SubElement(tag_data, 'item') tag_date = ET.SubElement(tag_item, 'date') tag_desc = ET.SubElement(tag_item, 'desc') tag_currency = ET.SubElement(tag_item, 'currency') tag_amount = ET.SubElement(tag_item, 'amount') tag_item.set('id', str(i)) tag_date.text = line['date'].strftime('%d/%m/%Y') tag_desc.text = line['desc'] tag_currency.text = line['currency'] tag_amount.text = str(line['amount']) xml_file.write(prettify(tag_data)) xml_file.close()
python
def write_to_file(data, path): if path.endswith('.xml'): filename = path else: filename = path + '.xml' tag_data = ET.Element('data') xml_file = open(filename, "w") i = 0 for line in data: i += 1 tag_item = ET.SubElement(tag_data, 'item') tag_date = ET.SubElement(tag_item, 'date') tag_desc = ET.SubElement(tag_item, 'desc') tag_currency = ET.SubElement(tag_item, 'currency') tag_amount = ET.SubElement(tag_item, 'amount') tag_item.set('id', str(i)) tag_date.text = line['date'].strftime('%d/%m/%Y') tag_desc.text = line['desc'] tag_currency.text = line['currency'] tag_amount.text = str(line['amount']) xml_file.write(prettify(tag_data)) xml_file.close()
[ "def", "write_to_file", "(", "data", ",", "path", ")", ":", "if", "path", ".", "endswith", "(", "'.xml'", ")", ":", "filename", "=", "path", "else", ":", "filename", "=", "path", "+", "'.xml'", "tag_data", "=", "ET", ".", "Element", "(", "'data'", ")...
Export extracted fields to xml Appends .xml to path if missing and generates xml file in specified directory, if not then in root Parameters ---------- data : dict Dictionary of extracted fields path : str directory to save generated xml file Notes ---- Do give file name to the function parameter path. Only `date`, `desc`, `amount` and `currency` are exported Examples -------- >>> from invoice2data.output import to_xml >>> to_xml.write_to_file(data, "/exported_xml/invoice.xml") >>> to_xml.write_to_file(data, "invoice.xml")
[ "Export", "extracted", "fields", "to", "xml" ]
d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20
https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/output/to_xml.py#L12-L59
240,980
invoice-x/invoice2data
src/invoice2data/extract/loader.py
read_templates
def read_templates(folder=None): """ Load yaml templates from template folder. Return list of dicts. Use built-in templates if no folder is set. Parameters ---------- folder : str user defined folder where they stores their files, if None uses built-in templates Returns ------- output : Instance of `InvoiceTemplate` template which match based on keywords Examples -------- >>> read_template("home/duskybomb/invoice-templates/") InvoiceTemplate([('issuer', 'OYO'), ('fields', OrderedDict([('amount', 'GrandTotalRs(\\d+)'), ('date', 'Date:(\\d{1,2}\\/\\d{1,2}\\/\\d{1,4})'), ('invoice_number', '([A-Z0-9]+)CashatHotel')])), ('keywords', ['OYO', 'Oravel', 'Stays']), ('options', OrderedDict([('currency', 'INR'), ('decimal_separator', '.'), ('remove_whitespace', True)])), ('template_name', 'com.oyo.invoice.yml')]) After reading the template you can use the result as an instance of `InvoiceTemplate` to extract fields from `extract_data()` >>> my_template = InvoiceTemplate([('issuer', 'OYO'), ('fields', OrderedDict([('amount', 'GrandTotalRs(\\d+)'), ('date', 'Date:(\\d{1,2}\\/\\d{1,2}\\/\\d{1,4})'), ('invoice_number', '([A-Z0-9]+)CashatHotel')])), ('keywords', ['OYO', 'Oravel', 'Stays']), ('options', OrderedDict([('currency', 'INR'), ('decimal_separator', '.'), ('remove_whitespace', True)])), ('template_name', 'com.oyo.invoice.yml')]) >>> extract_data("invoice2data/test/pdfs/oyo.pdf", my_template, pdftotext) {'issuer': 'OYO', 'amount': 1939.0, 'date': datetime.datetime(2017, 12, 31, 0, 0), 'invoice_number': 'IBZY2087', 'currency': 'INR', 'desc': 'Invoice IBZY2087 from OYO'} """ output = [] if folder is None: folder = pkg_resources.resource_filename(__name__, 'templates') for path, subdirs, files in os.walk(folder): for name in sorted(files): if name.endswith('.yml'): with open(os.path.join(path, name), 'rb') as f: encoding = chardet.detect(f.read())['encoding'] with codecs.open(os.path.join(path, name), encoding=encoding) as template_file: tpl = ordered_load(template_file.read()) tpl['template_name'] = name # Test if all required fields are in template: assert 'keywords' in tpl.keys(), 'Missing keywords field.' # Keywords as list, if only one. if type(tpl['keywords']) is not list: tpl['keywords'] = [tpl['keywords']] output.append(InvoiceTemplate(tpl)) return output
python
def read_templates(folder=None): output = [] if folder is None: folder = pkg_resources.resource_filename(__name__, 'templates') for path, subdirs, files in os.walk(folder): for name in sorted(files): if name.endswith('.yml'): with open(os.path.join(path, name), 'rb') as f: encoding = chardet.detect(f.read())['encoding'] with codecs.open(os.path.join(path, name), encoding=encoding) as template_file: tpl = ordered_load(template_file.read()) tpl['template_name'] = name # Test if all required fields are in template: assert 'keywords' in tpl.keys(), 'Missing keywords field.' # Keywords as list, if only one. if type(tpl['keywords']) is not list: tpl['keywords'] = [tpl['keywords']] output.append(InvoiceTemplate(tpl)) return output
[ "def", "read_templates", "(", "folder", "=", "None", ")", ":", "output", "=", "[", "]", "if", "folder", "is", "None", ":", "folder", "=", "pkg_resources", ".", "resource_filename", "(", "__name__", ",", "'templates'", ")", "for", "path", ",", "subdirs", ...
Load yaml templates from template folder. Return list of dicts. Use built-in templates if no folder is set. Parameters ---------- folder : str user defined folder where they stores their files, if None uses built-in templates Returns ------- output : Instance of `InvoiceTemplate` template which match based on keywords Examples -------- >>> read_template("home/duskybomb/invoice-templates/") InvoiceTemplate([('issuer', 'OYO'), ('fields', OrderedDict([('amount', 'GrandTotalRs(\\d+)'), ('date', 'Date:(\\d{1,2}\\/\\d{1,2}\\/\\d{1,4})'), ('invoice_number', '([A-Z0-9]+)CashatHotel')])), ('keywords', ['OYO', 'Oravel', 'Stays']), ('options', OrderedDict([('currency', 'INR'), ('decimal_separator', '.'), ('remove_whitespace', True)])), ('template_name', 'com.oyo.invoice.yml')]) After reading the template you can use the result as an instance of `InvoiceTemplate` to extract fields from `extract_data()` >>> my_template = InvoiceTemplate([('issuer', 'OYO'), ('fields', OrderedDict([('amount', 'GrandTotalRs(\\d+)'), ('date', 'Date:(\\d{1,2}\\/\\d{1,2}\\/\\d{1,4})'), ('invoice_number', '([A-Z0-9]+)CashatHotel')])), ('keywords', ['OYO', 'Oravel', 'Stays']), ('options', OrderedDict([('currency', 'INR'), ('decimal_separator', '.'), ('remove_whitespace', True)])), ('template_name', 'com.oyo.invoice.yml')]) >>> extract_data("invoice2data/test/pdfs/oyo.pdf", my_template, pdftotext) {'issuer': 'OYO', 'amount': 1939.0, 'date': datetime.datetime(2017, 12, 31, 0, 0), 'invoice_number': 'IBZY2087', 'currency': 'INR', 'desc': 'Invoice IBZY2087 from OYO'}
[ "Load", "yaml", "templates", "from", "template", "folder", ".", "Return", "list", "of", "dicts", "." ]
d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20
https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/extract/loader.py#L39-L99
240,981
invoice-x/invoice2data
src/invoice2data/input/pdfminer_wrapper.py
to_text
def to_text(path): """Wrapper around `pdfminer`. Parameters ---------- path : str path of electronic invoice in PDF Returns ------- str : str returns extracted text from pdf """ try: # python 2 from StringIO import StringIO import sys reload(sys) # noqa: F821 sys.setdefaultencoding('utf8') except ImportError: from io import StringIO from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.converter import TextConverter from pdfminer.layout import LAParams from pdfminer.pdfpage import PDFPage rsrcmgr = PDFResourceManager() retstr = StringIO() codec = 'utf-8' laparams = LAParams() laparams.all_texts = True device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams) with open(path, 'rb') as fp: interpreter = PDFPageInterpreter(rsrcmgr, device) password = "" maxpages = 0 caching = True pagenos = set() pages = PDFPage.get_pages( fp, pagenos, maxpages=maxpages, password=password, caching=caching, check_extractable=True, ) for page in pages: interpreter.process_page(page) device.close() str = retstr.getvalue() retstr.close() return str.encode('utf-8')
python
def to_text(path): try: # python 2 from StringIO import StringIO import sys reload(sys) # noqa: F821 sys.setdefaultencoding('utf8') except ImportError: from io import StringIO from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.converter import TextConverter from pdfminer.layout import LAParams from pdfminer.pdfpage import PDFPage rsrcmgr = PDFResourceManager() retstr = StringIO() codec = 'utf-8' laparams = LAParams() laparams.all_texts = True device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams) with open(path, 'rb') as fp: interpreter = PDFPageInterpreter(rsrcmgr, device) password = "" maxpages = 0 caching = True pagenos = set() pages = PDFPage.get_pages( fp, pagenos, maxpages=maxpages, password=password, caching=caching, check_extractable=True, ) for page in pages: interpreter.process_page(page) device.close() str = retstr.getvalue() retstr.close() return str.encode('utf-8')
[ "def", "to_text", "(", "path", ")", ":", "try", ":", "# python 2", "from", "StringIO", "import", "StringIO", "import", "sys", "reload", "(", "sys", ")", "# noqa: F821", "sys", ".", "setdefaultencoding", "(", "'utf8'", ")", "except", "ImportError", ":", "from...
Wrapper around `pdfminer`. Parameters ---------- path : str path of electronic invoice in PDF Returns ------- str : str returns extracted text from pdf
[ "Wrapper", "around", "pdfminer", "." ]
d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20
https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/input/pdfminer_wrapper.py#L2-L57
240,982
SALib/SALib
src/SALib/analyze/ff.py
analyze
def analyze(problem, X, Y, second_order=False, print_to_console=False, seed=None): """Perform a fractional factorial analysis Returns a dictionary with keys 'ME' (main effect) and 'IE' (interaction effect). The techniques bulks out the number of parameters with dummy parameters to the nearest 2**n. Any results involving dummy parameters could indicate a problem with the model runs. Arguments --------- problem: dict The problem definition X: numpy.matrix The NumPy matrix containing the model inputs Y: numpy.array The NumPy array containing the model outputs second_order: bool, default=False Include interaction effects print_to_console: bool, default=False Print results directly to console Returns ------- Si: dict A dictionary of sensitivity indices, including main effects ``ME``, and interaction effects ``IE`` (if ``second_order`` is True) Examples -------- >>> X = sample(problem) >>> Y = X[:, 0] + (0.1 * X[:, 1]) + ((1.2 * X[:, 2]) * (0.2 + X[:, 0])) >>> analyze(problem, X, Y, second_order=True, print_to_console=True) """ if seed: np.random.seed(seed) problem = extend_bounds(problem) num_vars = problem['num_vars'] X = generate_contrast(problem) main_effect = (1. / (2 * num_vars)) * np.dot(Y, X) Si = ResultDict((k, [None] * num_vars) for k in ['names', 'ME']) Si['ME'] = main_effect Si['names'] = problem['names'] if print_to_console: print("Parameter ME") for j in range(num_vars): print("%s %f" % (problem['names'][j], Si['ME'][j])) if second_order: interaction_names, interaction_effects = interactions(problem, Y, print_to_console) Si['interaction_names'] = interaction_names Si['IE'] = interaction_effects Si.to_df = MethodType(to_df, Si) return Si
python
def analyze(problem, X, Y, second_order=False, print_to_console=False, seed=None): if seed: np.random.seed(seed) problem = extend_bounds(problem) num_vars = problem['num_vars'] X = generate_contrast(problem) main_effect = (1. / (2 * num_vars)) * np.dot(Y, X) Si = ResultDict((k, [None] * num_vars) for k in ['names', 'ME']) Si['ME'] = main_effect Si['names'] = problem['names'] if print_to_console: print("Parameter ME") for j in range(num_vars): print("%s %f" % (problem['names'][j], Si['ME'][j])) if second_order: interaction_names, interaction_effects = interactions(problem, Y, print_to_console) Si['interaction_names'] = interaction_names Si['IE'] = interaction_effects Si.to_df = MethodType(to_df, Si) return Si
[ "def", "analyze", "(", "problem", ",", "X", ",", "Y", ",", "second_order", "=", "False", ",", "print_to_console", "=", "False", ",", "seed", "=", "None", ")", ":", "if", "seed", ":", "np", ".", "random", ".", "seed", "(", "seed", ")", "problem", "=...
Perform a fractional factorial analysis Returns a dictionary with keys 'ME' (main effect) and 'IE' (interaction effect). The techniques bulks out the number of parameters with dummy parameters to the nearest 2**n. Any results involving dummy parameters could indicate a problem with the model runs. Arguments --------- problem: dict The problem definition X: numpy.matrix The NumPy matrix containing the model inputs Y: numpy.array The NumPy array containing the model outputs second_order: bool, default=False Include interaction effects print_to_console: bool, default=False Print results directly to console Returns ------- Si: dict A dictionary of sensitivity indices, including main effects ``ME``, and interaction effects ``IE`` (if ``second_order`` is True) Examples -------- >>> X = sample(problem) >>> Y = X[:, 0] + (0.1 * X[:, 1]) + ((1.2 * X[:, 2]) * (0.2 + X[:, 0])) >>> analyze(problem, X, Y, second_order=True, print_to_console=True)
[ "Perform", "a", "fractional", "factorial", "analysis" ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/analyze/ff.py#L18-L81
240,983
SALib/SALib
src/SALib/analyze/ff.py
to_df
def to_df(self): '''Conversion method to Pandas DataFrame. To be attached to ResultDict. Returns ------- main_effect, inter_effect: tuple A tuple of DataFrames for main effects and interaction effects. The second element (for interactions) will be `None` if not available. ''' names = self['names'] main_effect = self['ME'] interactions = self.get('IE', None) inter_effect = None if interactions: interaction_names = self.get('interaction_names') names = [name for name in names if not isinstance(name, list)] inter_effect = pd.DataFrame({'IE': interactions}, index=interaction_names) main_effect = pd.DataFrame({'ME': main_effect}, index=names) return main_effect, inter_effect
python
def to_df(self): '''Conversion method to Pandas DataFrame. To be attached to ResultDict. Returns ------- main_effect, inter_effect: tuple A tuple of DataFrames for main effects and interaction effects. The second element (for interactions) will be `None` if not available. ''' names = self['names'] main_effect = self['ME'] interactions = self.get('IE', None) inter_effect = None if interactions: interaction_names = self.get('interaction_names') names = [name for name in names if not isinstance(name, list)] inter_effect = pd.DataFrame({'IE': interactions}, index=interaction_names) main_effect = pd.DataFrame({'ME': main_effect}, index=names) return main_effect, inter_effect
[ "def", "to_df", "(", "self", ")", ":", "names", "=", "self", "[", "'names'", "]", "main_effect", "=", "self", "[", "'ME'", "]", "interactions", "=", "self", ".", "get", "(", "'IE'", ",", "None", ")", "inter_effect", "=", "None", "if", "interactions", ...
Conversion method to Pandas DataFrame. To be attached to ResultDict. Returns ------- main_effect, inter_effect: tuple A tuple of DataFrames for main effects and interaction effects. The second element (for interactions) will be `None` if not available.
[ "Conversion", "method", "to", "Pandas", "DataFrame", ".", "To", "be", "attached", "to", "ResultDict", "." ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/analyze/ff.py#L84-L106
240,984
SALib/SALib
src/SALib/analyze/ff.py
interactions
def interactions(problem, Y, print_to_console=False): """Computes the second order effects Computes the second order effects (interactions) between all combinations of pairs of input factors Arguments --------- problem: dict The problem definition Y: numpy.array The NumPy array containing the model outputs print_to_console: bool, default=False Print results directly to console Returns ------- ie_names: list The names of the interaction pairs IE: list The sensitivity indices for the pairwise interactions """ names = problem['names'] num_vars = problem['num_vars'] X = generate_contrast(problem) ie_names = [] IE = [] for col in range(X.shape[1]): for col_2 in range(col): x = X[:, col] * X[:, col_2] var_names = (names[col_2], names[col]) ie_names.append(var_names) IE.append((1. / (2 * num_vars)) * np.dot(Y, x)) if print_to_console: [print('%s %f' % (n, i)) for (n, i) in zip(ie_names, IE)] return ie_names, IE
python
def interactions(problem, Y, print_to_console=False): names = problem['names'] num_vars = problem['num_vars'] X = generate_contrast(problem) ie_names = [] IE = [] for col in range(X.shape[1]): for col_2 in range(col): x = X[:, col] * X[:, col_2] var_names = (names[col_2], names[col]) ie_names.append(var_names) IE.append((1. / (2 * num_vars)) * np.dot(Y, x)) if print_to_console: [print('%s %f' % (n, i)) for (n, i) in zip(ie_names, IE)] return ie_names, IE
[ "def", "interactions", "(", "problem", ",", "Y", ",", "print_to_console", "=", "False", ")", ":", "names", "=", "problem", "[", "'names'", "]", "num_vars", "=", "problem", "[", "'num_vars'", "]", "X", "=", "generate_contrast", "(", "problem", ")", "ie_name...
Computes the second order effects Computes the second order effects (interactions) between all combinations of pairs of input factors Arguments --------- problem: dict The problem definition Y: numpy.array The NumPy array containing the model outputs print_to_console: bool, default=False Print results directly to console Returns ------- ie_names: list The names of the interaction pairs IE: list The sensitivity indices for the pairwise interactions
[ "Computes", "the", "second", "order", "effects" ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/analyze/ff.py#L109-L150
240,985
SALib/SALib
src/SALib/util/__init__.py
avail_approaches
def avail_approaches(pkg): '''Create list of available modules. Arguments --------- pkg : module module to inspect Returns --------- method : list A list of available submodules ''' methods = [modname for importer, modname, ispkg in pkgutil.walk_packages(path=pkg.__path__) if modname not in ['common_args', 'directions', 'sobol_sequence']] return methods
python
def avail_approaches(pkg): '''Create list of available modules. Arguments --------- pkg : module module to inspect Returns --------- method : list A list of available submodules ''' methods = [modname for importer, modname, ispkg in pkgutil.walk_packages(path=pkg.__path__) if modname not in ['common_args', 'directions', 'sobol_sequence']] return methods
[ "def", "avail_approaches", "(", "pkg", ")", ":", "methods", "=", "[", "modname", "for", "importer", ",", "modname", ",", "ispkg", "in", "pkgutil", ".", "walk_packages", "(", "path", "=", "pkg", ".", "__path__", ")", "if", "modname", "not", "in", "[", "...
Create list of available modules. Arguments --------- pkg : module module to inspect Returns --------- method : list A list of available submodules
[ "Create", "list", "of", "available", "modules", "." ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/util/__init__.py#L18-L35
240,986
SALib/SALib
src/SALib/util/__init__.py
scale_samples
def scale_samples(params, bounds): '''Rescale samples in 0-to-1 range to arbitrary bounds Arguments --------- bounds : list list of lists of dimensions `num_params`-by-2 params : numpy.ndarray numpy array of dimensions `num_params`-by-:math:`N`, where :math:`N` is the number of samples ''' # Check bounds are legal (upper bound is greater than lower bound) b = np.array(bounds) lower_bounds = b[:, 0] upper_bounds = b[:, 1] if np.any(lower_bounds >= upper_bounds): raise ValueError("Bounds are not legal") # This scales the samples in-place, by using the optional output # argument for the numpy ufunctions # The calculation is equivalent to: # sample * (upper_bound - lower_bound) + lower_bound np.add(np.multiply(params, (upper_bounds - lower_bounds), out=params), lower_bounds, out=params)
python
def scale_samples(params, bounds): '''Rescale samples in 0-to-1 range to arbitrary bounds Arguments --------- bounds : list list of lists of dimensions `num_params`-by-2 params : numpy.ndarray numpy array of dimensions `num_params`-by-:math:`N`, where :math:`N` is the number of samples ''' # Check bounds are legal (upper bound is greater than lower bound) b = np.array(bounds) lower_bounds = b[:, 0] upper_bounds = b[:, 1] if np.any(lower_bounds >= upper_bounds): raise ValueError("Bounds are not legal") # This scales the samples in-place, by using the optional output # argument for the numpy ufunctions # The calculation is equivalent to: # sample * (upper_bound - lower_bound) + lower_bound np.add(np.multiply(params, (upper_bounds - lower_bounds), out=params), lower_bounds, out=params)
[ "def", "scale_samples", "(", "params", ",", "bounds", ")", ":", "# Check bounds are legal (upper bound is greater than lower bound)", "b", "=", "np", ".", "array", "(", "bounds", ")", "lower_bounds", "=", "b", "[", ":", ",", "0", "]", "upper_bounds", "=", "b", ...
Rescale samples in 0-to-1 range to arbitrary bounds Arguments --------- bounds : list list of lists of dimensions `num_params`-by-2 params : numpy.ndarray numpy array of dimensions `num_params`-by-:math:`N`, where :math:`N` is the number of samples
[ "Rescale", "samples", "in", "0", "-", "to", "-", "1", "range", "to", "arbitrary", "bounds" ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/util/__init__.py#L38-L65
240,987
SALib/SALib
src/SALib/util/__init__.py
nonuniform_scale_samples
def nonuniform_scale_samples(params, bounds, dists): """Rescale samples in 0-to-1 range to other distributions Arguments --------- problem : dict problem definition including bounds params : numpy.ndarray numpy array of dimensions num_params-by-N, where N is the number of samples dists : list list of distributions, one for each parameter unif: uniform with lower and upper bounds triang: triangular with width (scale) and location of peak location of peak is in percentage of width lower bound assumed to be zero norm: normal distribution with mean and standard deviation lognorm: lognormal with ln-space mean and standard deviation """ b = np.array(bounds) # initializing matrix for converted values conv_params = np.zeros_like(params) # loop over the parameters for i in range(conv_params.shape[1]): # setting first and second arguments for distributions b1 = b[i][0] b2 = b[i][1] if dists[i] == 'triang': # checking for correct parameters if b1 <= 0 or b2 <= 0 or b2 >= 1: raise ValueError('''Triangular distribution: Scale must be greater than zero; peak on interval [0,1]''') else: conv_params[:, i] = sp.stats.triang.ppf( params[:, i], c=b2, scale=b1, loc=0) elif dists[i] == 'unif': if b1 >= b2: raise ValueError('''Uniform distribution: lower bound must be less than upper bound''') else: conv_params[:, i] = params[:, i] * (b2 - b1) + b1 elif dists[i] == 'norm': if b2 <= 0: raise ValueError('''Normal distribution: stdev must be > 0''') else: conv_params[:, i] = sp.stats.norm.ppf( params[:, i], loc=b1, scale=b2) # lognormal distribution (ln-space, not base-10) # paramters are ln-space mean and standard deviation elif dists[i] == 'lognorm': # checking for valid parameters if b2 <= 0: raise ValueError( '''Lognormal distribution: stdev must be > 0''') else: conv_params[:, i] = np.exp( sp.stats.norm.ppf(params[:, i], loc=b1, scale=b2)) else: valid_dists = ['unif', 'triang', 'norm', 'lognorm'] raise ValueError('Distributions: choose one of %s' % ", ".join(valid_dists)) return conv_params
python
def nonuniform_scale_samples(params, bounds, dists): b = np.array(bounds) # initializing matrix for converted values conv_params = np.zeros_like(params) # loop over the parameters for i in range(conv_params.shape[1]): # setting first and second arguments for distributions b1 = b[i][0] b2 = b[i][1] if dists[i] == 'triang': # checking for correct parameters if b1 <= 0 or b2 <= 0 or b2 >= 1: raise ValueError('''Triangular distribution: Scale must be greater than zero; peak on interval [0,1]''') else: conv_params[:, i] = sp.stats.triang.ppf( params[:, i], c=b2, scale=b1, loc=0) elif dists[i] == 'unif': if b1 >= b2: raise ValueError('''Uniform distribution: lower bound must be less than upper bound''') else: conv_params[:, i] = params[:, i] * (b2 - b1) + b1 elif dists[i] == 'norm': if b2 <= 0: raise ValueError('''Normal distribution: stdev must be > 0''') else: conv_params[:, i] = sp.stats.norm.ppf( params[:, i], loc=b1, scale=b2) # lognormal distribution (ln-space, not base-10) # paramters are ln-space mean and standard deviation elif dists[i] == 'lognorm': # checking for valid parameters if b2 <= 0: raise ValueError( '''Lognormal distribution: stdev must be > 0''') else: conv_params[:, i] = np.exp( sp.stats.norm.ppf(params[:, i], loc=b1, scale=b2)) else: valid_dists = ['unif', 'triang', 'norm', 'lognorm'] raise ValueError('Distributions: choose one of %s' % ", ".join(valid_dists)) return conv_params
[ "def", "nonuniform_scale_samples", "(", "params", ",", "bounds", ",", "dists", ")", ":", "b", "=", "np", ".", "array", "(", "bounds", ")", "# initializing matrix for converted values", "conv_params", "=", "np", ".", "zeros_like", "(", "params", ")", "# loop over...
Rescale samples in 0-to-1 range to other distributions Arguments --------- problem : dict problem definition including bounds params : numpy.ndarray numpy array of dimensions num_params-by-N, where N is the number of samples dists : list list of distributions, one for each parameter unif: uniform with lower and upper bounds triang: triangular with width (scale) and location of peak location of peak is in percentage of width lower bound assumed to be zero norm: normal distribution with mean and standard deviation lognorm: lognormal with ln-space mean and standard deviation
[ "Rescale", "samples", "in", "0", "-", "to", "-", "1", "range", "to", "other", "distributions" ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/util/__init__.py#L96-L165
240,988
SALib/SALib
src/SALib/util/__init__.py
read_param_file
def read_param_file(filename, delimiter=None): """Unpacks a parameter file into a dictionary Reads a parameter file of format:: Param1,0,1,Group1,dist1 Param2,0,1,Group2,dist2 Param3,0,1,Group3,dist3 (Group and Dist columns are optional) Returns a dictionary containing: - names - the names of the parameters - bounds - a list of lists of lower and upper bounds - num_vars - a scalar indicating the number of variables (the length of names) - groups - a list of group names (strings) for each variable - dists - a list of distributions for the problem, None if not specified or all uniform Arguments --------- filename : str The path to the parameter file delimiter : str, default=None The delimiter used in the file to distinguish between columns """ names = [] bounds = [] groups = [] dists = [] num_vars = 0 fieldnames = ['name', 'lower_bound', 'upper_bound', 'group', 'dist'] with open(filename, 'rU') as csvfile: dialect = csv.Sniffer().sniff(csvfile.read(1024), delimiters=delimiter) csvfile.seek(0) reader = csv.DictReader( csvfile, fieldnames=fieldnames, dialect=dialect) for row in reader: if row['name'].strip().startswith('#'): pass else: num_vars += 1 names.append(row['name']) bounds.append( [float(row['lower_bound']), float(row['upper_bound'])]) # If the fourth column does not contain a group name, use # the parameter name if row['group'] is None: groups.append(row['name']) elif row['group'] is 'NA': groups.append(row['name']) else: groups.append(row['group']) # If the fifth column does not contain a distribution # use uniform if row['dist'] is None: dists.append('unif') else: dists.append(row['dist']) if groups == names: groups = None elif len(set(groups)) == 1: raise ValueError('''Only one group defined, results will not be meaningful''') # setting dists to none if all are uniform # because non-uniform scaling is not needed if all([d == 'unif' for d in dists]): dists = None return {'names': names, 'bounds': bounds, 'num_vars': num_vars, 'groups': groups, 'dists': dists}
python
def read_param_file(filename, delimiter=None): names = [] bounds = [] groups = [] dists = [] num_vars = 0 fieldnames = ['name', 'lower_bound', 'upper_bound', 'group', 'dist'] with open(filename, 'rU') as csvfile: dialect = csv.Sniffer().sniff(csvfile.read(1024), delimiters=delimiter) csvfile.seek(0) reader = csv.DictReader( csvfile, fieldnames=fieldnames, dialect=dialect) for row in reader: if row['name'].strip().startswith('#'): pass else: num_vars += 1 names.append(row['name']) bounds.append( [float(row['lower_bound']), float(row['upper_bound'])]) # If the fourth column does not contain a group name, use # the parameter name if row['group'] is None: groups.append(row['name']) elif row['group'] is 'NA': groups.append(row['name']) else: groups.append(row['group']) # If the fifth column does not contain a distribution # use uniform if row['dist'] is None: dists.append('unif') else: dists.append(row['dist']) if groups == names: groups = None elif len(set(groups)) == 1: raise ValueError('''Only one group defined, results will not be meaningful''') # setting dists to none if all are uniform # because non-uniform scaling is not needed if all([d == 'unif' for d in dists]): dists = None return {'names': names, 'bounds': bounds, 'num_vars': num_vars, 'groups': groups, 'dists': dists}
[ "def", "read_param_file", "(", "filename", ",", "delimiter", "=", "None", ")", ":", "names", "=", "[", "]", "bounds", "=", "[", "]", "groups", "=", "[", "]", "dists", "=", "[", "]", "num_vars", "=", "0", "fieldnames", "=", "[", "'name'", ",", "'low...
Unpacks a parameter file into a dictionary Reads a parameter file of format:: Param1,0,1,Group1,dist1 Param2,0,1,Group2,dist2 Param3,0,1,Group3,dist3 (Group and Dist columns are optional) Returns a dictionary containing: - names - the names of the parameters - bounds - a list of lists of lower and upper bounds - num_vars - a scalar indicating the number of variables (the length of names) - groups - a list of group names (strings) for each variable - dists - a list of distributions for the problem, None if not specified or all uniform Arguments --------- filename : str The path to the parameter file delimiter : str, default=None The delimiter used in the file to distinguish between columns
[ "Unpacks", "a", "parameter", "file", "into", "a", "dictionary" ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/util/__init__.py#L168-L245
240,989
SALib/SALib
src/SALib/util/__init__.py
compute_groups_matrix
def compute_groups_matrix(groups): """Generate matrix which notes factor membership of groups Computes a k-by-g matrix which notes factor membership of groups where: k is the number of variables (factors) g is the number of groups Also returns a g-length list of unique group_names whose positions correspond to the order of groups in the k-by-g matrix Arguments --------- groups : list Group names corresponding to each variable Returns ------- tuple containing group matrix assigning parameters to groups and a list of unique group names """ if not groups: return None num_vars = len(groups) # Get a unique set of the group names unique_group_names = list(OrderedDict.fromkeys(groups)) number_of_groups = len(unique_group_names) indices = dict([(x, i) for (i, x) in enumerate(unique_group_names)]) output = np.zeros((num_vars, number_of_groups), dtype=np.int) for parameter_row, group_membership in enumerate(groups): group_index = indices[group_membership] output[parameter_row, group_index] = 1 return output, unique_group_names
python
def compute_groups_matrix(groups): if not groups: return None num_vars = len(groups) # Get a unique set of the group names unique_group_names = list(OrderedDict.fromkeys(groups)) number_of_groups = len(unique_group_names) indices = dict([(x, i) for (i, x) in enumerate(unique_group_names)]) output = np.zeros((num_vars, number_of_groups), dtype=np.int) for parameter_row, group_membership in enumerate(groups): group_index = indices[group_membership] output[parameter_row, group_index] = 1 return output, unique_group_names
[ "def", "compute_groups_matrix", "(", "groups", ")", ":", "if", "not", "groups", ":", "return", "None", "num_vars", "=", "len", "(", "groups", ")", "# Get a unique set of the group names", "unique_group_names", "=", "list", "(", "OrderedDict", ".", "fromkeys", "(",...
Generate matrix which notes factor membership of groups Computes a k-by-g matrix which notes factor membership of groups where: k is the number of variables (factors) g is the number of groups Also returns a g-length list of unique group_names whose positions correspond to the order of groups in the k-by-g matrix Arguments --------- groups : list Group names corresponding to each variable Returns ------- tuple containing group matrix assigning parameters to groups and a list of unique group names
[ "Generate", "matrix", "which", "notes", "factor", "membership", "of", "groups" ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/util/__init__.py#L248-L286
240,990
SALib/SALib
src/SALib/util/__init__.py
requires_gurobipy
def requires_gurobipy(_has_gurobi): ''' Decorator function which takes a boolean _has_gurobi as an argument. Use decorate any functions which require gurobi. Raises an import error at runtime if gurobi is not present. Note that all runtime errors should be avoided in the working code, using brute force options as preference. ''' def _outer_wrapper(wrapped_function): def _wrapper(*args, **kwargs): if _has_gurobi: result = wrapped_function(*args, **kwargs) else: warn("Gurobi not available", ImportWarning) result = None return result return _wrapper return _outer_wrapper
python
def requires_gurobipy(_has_gurobi): ''' Decorator function which takes a boolean _has_gurobi as an argument. Use decorate any functions which require gurobi. Raises an import error at runtime if gurobi is not present. Note that all runtime errors should be avoided in the working code, using brute force options as preference. ''' def _outer_wrapper(wrapped_function): def _wrapper(*args, **kwargs): if _has_gurobi: result = wrapped_function(*args, **kwargs) else: warn("Gurobi not available", ImportWarning) result = None return result return _wrapper return _outer_wrapper
[ "def", "requires_gurobipy", "(", "_has_gurobi", ")", ":", "def", "_outer_wrapper", "(", "wrapped_function", ")", ":", "def", "_wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "_has_gurobi", ":", "result", "=", "wrapped_function", "(", ...
Decorator function which takes a boolean _has_gurobi as an argument. Use decorate any functions which require gurobi. Raises an import error at runtime if gurobi is not present. Note that all runtime errors should be avoided in the working code, using brute force options as preference.
[ "Decorator", "function", "which", "takes", "a", "boolean", "_has_gurobi", "as", "an", "argument", ".", "Use", "decorate", "any", "functions", "which", "require", "gurobi", ".", "Raises", "an", "import", "error", "at", "runtime", "if", "gurobi", "is", "not", ...
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/util/__init__.py#L289-L306
240,991
SALib/SALib
src/SALib/analyze/morris.py
compute_grouped_sigma
def compute_grouped_sigma(ungrouped_sigma, group_matrix): ''' Returns sigma for the groups of parameter values in the argument ungrouped_metric where the group consists of no more than one parameter ''' group_matrix = np.array(group_matrix, dtype=np.bool) sigma_masked = np.ma.masked_array(ungrouped_sigma * group_matrix.T, mask=(group_matrix ^ 1).T) sigma_agg = np.ma.mean(sigma_masked, axis=1) sigma = np.zeros(group_matrix.shape[1], dtype=np.float) np.copyto(sigma, sigma_agg, where=group_matrix.sum(axis=0) == 1) np.copyto(sigma, np.NAN, where=group_matrix.sum(axis=0) != 1) return sigma
python
def compute_grouped_sigma(ungrouped_sigma, group_matrix): ''' Returns sigma for the groups of parameter values in the argument ungrouped_metric where the group consists of no more than one parameter ''' group_matrix = np.array(group_matrix, dtype=np.bool) sigma_masked = np.ma.masked_array(ungrouped_sigma * group_matrix.T, mask=(group_matrix ^ 1).T) sigma_agg = np.ma.mean(sigma_masked, axis=1) sigma = np.zeros(group_matrix.shape[1], dtype=np.float) np.copyto(sigma, sigma_agg, where=group_matrix.sum(axis=0) == 1) np.copyto(sigma, np.NAN, where=group_matrix.sum(axis=0) != 1) return sigma
[ "def", "compute_grouped_sigma", "(", "ungrouped_sigma", ",", "group_matrix", ")", ":", "group_matrix", "=", "np", ".", "array", "(", "group_matrix", ",", "dtype", "=", "np", ".", "bool", ")", "sigma_masked", "=", "np", ".", "ma", ".", "masked_array", "(", ...
Returns sigma for the groups of parameter values in the argument ungrouped_metric where the group consists of no more than one parameter
[ "Returns", "sigma", "for", "the", "groups", "of", "parameter", "values", "in", "the", "argument", "ungrouped_metric", "where", "the", "group", "consists", "of", "no", "more", "than", "one", "parameter" ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/analyze/morris.py#L170-L186
240,992
SALib/SALib
src/SALib/analyze/morris.py
compute_grouped_metric
def compute_grouped_metric(ungrouped_metric, group_matrix): ''' Computes the mean value for the groups of parameter values in the argument ungrouped_metric ''' group_matrix = np.array(group_matrix, dtype=np.bool) mu_star_masked = np.ma.masked_array(ungrouped_metric * group_matrix.T, mask=(group_matrix ^ 1).T) mean_of_mu_star = np.ma.mean(mu_star_masked, axis=1) return mean_of_mu_star
python
def compute_grouped_metric(ungrouped_metric, group_matrix): ''' Computes the mean value for the groups of parameter values in the argument ungrouped_metric ''' group_matrix = np.array(group_matrix, dtype=np.bool) mu_star_masked = np.ma.masked_array(ungrouped_metric * group_matrix.T, mask=(group_matrix ^ 1).T) mean_of_mu_star = np.ma.mean(mu_star_masked, axis=1) return mean_of_mu_star
[ "def", "compute_grouped_metric", "(", "ungrouped_metric", ",", "group_matrix", ")", ":", "group_matrix", "=", "np", ".", "array", "(", "group_matrix", ",", "dtype", "=", "np", ".", "bool", ")", "mu_star_masked", "=", "np", ".", "ma", ".", "masked_array", "("...
Computes the mean value for the groups of parameter values in the argument ungrouped_metric
[ "Computes", "the", "mean", "value", "for", "the", "groups", "of", "parameter", "values", "in", "the", "argument", "ungrouped_metric" ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/analyze/morris.py#L189-L201
240,993
SALib/SALib
src/SALib/analyze/morris.py
compute_mu_star_confidence
def compute_mu_star_confidence(ee, num_trajectories, num_resamples, conf_level): ''' Uses bootstrapping where the elementary effects are resampled with replacement to produce a histogram of resampled mu_star metrics. This resample is used to produce a confidence interval. ''' ee_resampled = np.zeros([num_trajectories]) mu_star_resampled = np.zeros([num_resamples]) if not 0 < conf_level < 1: raise ValueError("Confidence level must be between 0-1.") resample_index = np.random.randint( len(ee), size=(num_resamples, num_trajectories)) ee_resampled = ee[resample_index] # Compute average of the absolute values over each of the resamples mu_star_resampled = np.average(np.abs(ee_resampled), axis=1) return norm.ppf(0.5 + conf_level / 2) * mu_star_resampled.std(ddof=1)
python
def compute_mu_star_confidence(ee, num_trajectories, num_resamples, conf_level): ''' Uses bootstrapping where the elementary effects are resampled with replacement to produce a histogram of resampled mu_star metrics. This resample is used to produce a confidence interval. ''' ee_resampled = np.zeros([num_trajectories]) mu_star_resampled = np.zeros([num_resamples]) if not 0 < conf_level < 1: raise ValueError("Confidence level must be between 0-1.") resample_index = np.random.randint( len(ee), size=(num_resamples, num_trajectories)) ee_resampled = ee[resample_index] # Compute average of the absolute values over each of the resamples mu_star_resampled = np.average(np.abs(ee_resampled), axis=1) return norm.ppf(0.5 + conf_level / 2) * mu_star_resampled.std(ddof=1)
[ "def", "compute_mu_star_confidence", "(", "ee", ",", "num_trajectories", ",", "num_resamples", ",", "conf_level", ")", ":", "ee_resampled", "=", "np", ".", "zeros", "(", "[", "num_trajectories", "]", ")", "mu_star_resampled", "=", "np", ".", "zeros", "(", "[",...
Uses bootstrapping where the elementary effects are resampled with replacement to produce a histogram of resampled mu_star metrics. This resample is used to produce a confidence interval.
[ "Uses", "bootstrapping", "where", "the", "elementary", "effects", "are", "resampled", "with", "replacement", "to", "produce", "a", "histogram", "of", "resampled", "mu_star", "metrics", ".", "This", "resample", "is", "used", "to", "produce", "a", "confidence", "i...
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/analyze/morris.py#L261-L280
240,994
SALib/SALib
src/SALib/sample/morris/gurobi.py
timestamp
def timestamp(num_params, p_levels, k_choices, N): """ Returns a uniform timestamp with parameter values for file identification """ string = "_v%s_l%s_gs%s_k%s_N%s_%s.txt" % (num_params, p_levels, k_choices, N, dt.strftime(dt.now(), "%d%m%y%H%M%S")) return string
python
def timestamp(num_params, p_levels, k_choices, N): string = "_v%s_l%s_gs%s_k%s_N%s_%s.txt" % (num_params, p_levels, k_choices, N, dt.strftime(dt.now(), "%d%m%y%H%M%S")) return string
[ "def", "timestamp", "(", "num_params", ",", "p_levels", ",", "k_choices", ",", "N", ")", ":", "string", "=", "\"_v%s_l%s_gs%s_k%s_N%s_%s.txt\"", "%", "(", "num_params", ",", "p_levels", ",", "k_choices", ",", "N", ",", "dt", ".", "strftime", "(", "dt", "."...
Returns a uniform timestamp with parameter values for file identification
[ "Returns", "a", "uniform", "timestamp", "with", "parameter", "values", "for", "file", "identification" ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/sample/morris/gurobi.py#L131-L141
240,995
SALib/SALib
src/SALib/sample/morris/brute.py
BruteForce.brute_force_most_distant
def brute_force_most_distant(self, input_sample, num_samples, num_params, k_choices, num_groups=None): """Use brute force method to find most distant trajectories Arguments --------- input_sample : numpy.ndarray num_samples : int The number of samples to generate num_params : int The number of parameters k_choices : int The number of optimal trajectories num_groups : int, default=None The number of groups Returns ------- list """ scores = self.find_most_distant(input_sample, num_samples, num_params, k_choices, num_groups) maximum_combo = self.find_maximum(scores, num_samples, k_choices) return maximum_combo
python
def brute_force_most_distant(self, input_sample, num_samples, num_params, k_choices, num_groups=None): scores = self.find_most_distant(input_sample, num_samples, num_params, k_choices, num_groups) maximum_combo = self.find_maximum(scores, num_samples, k_choices) return maximum_combo
[ "def", "brute_force_most_distant", "(", "self", ",", "input_sample", ",", "num_samples", ",", "num_params", ",", "k_choices", ",", "num_groups", "=", "None", ")", ":", "scores", "=", "self", ".", "find_most_distant", "(", "input_sample", ",", "num_samples", ",",...
Use brute force method to find most distant trajectories Arguments --------- input_sample : numpy.ndarray num_samples : int The number of samples to generate num_params : int The number of parameters k_choices : int The number of optimal trajectories num_groups : int, default=None The number of groups Returns ------- list
[ "Use", "brute", "force", "method", "to", "find", "most", "distant", "trajectories" ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/sample/morris/brute.py#L19-L48
240,996
SALib/SALib
src/SALib/sample/morris/brute.py
BruteForce.find_most_distant
def find_most_distant(self, input_sample, num_samples, num_params, k_choices, num_groups=None): """ Finds the 'k_choices' most distant choices from the 'num_samples' trajectories contained in 'input_sample' Arguments --------- input_sample : numpy.ndarray num_samples : int The number of samples to generate num_params : int The number of parameters k_choices : int The number of optimal trajectories num_groups : int, default=None The number of groups Returns ------- numpy.ndarray """ # Now evaluate the (N choose k_choices) possible combinations if nchoosek(num_samples, k_choices) >= sys.maxsize: raise ValueError("Number of combinations is too large") number_of_combinations = int(nchoosek(num_samples, k_choices)) # First compute the distance matrix for each possible pairing # of trajectories and store in a shared-memory array distance_matrix = self.compute_distance_matrix(input_sample, num_samples, num_params, num_groups) # Initialise the output array chunk = int(1e6) if chunk > number_of_combinations: chunk = number_of_combinations counter = 0 # Generate a list of all the possible combinations combo_gen = combinations(list(range(num_samples)), k_choices) scores = np.zeros(number_of_combinations, dtype=np.float32) # Generate the pairwise indices once pairwise = np.array( [y for y in combinations(list(range(k_choices)), 2)]) for combos in self.grouper(chunk, combo_gen): scores[(counter * chunk):((counter + 1) * chunk)] \ = self.mappable(combos, pairwise, distance_matrix) counter += 1 return scores
python
def find_most_distant(self, input_sample, num_samples, num_params, k_choices, num_groups=None): # Now evaluate the (N choose k_choices) possible combinations if nchoosek(num_samples, k_choices) >= sys.maxsize: raise ValueError("Number of combinations is too large") number_of_combinations = int(nchoosek(num_samples, k_choices)) # First compute the distance matrix for each possible pairing # of trajectories and store in a shared-memory array distance_matrix = self.compute_distance_matrix(input_sample, num_samples, num_params, num_groups) # Initialise the output array chunk = int(1e6) if chunk > number_of_combinations: chunk = number_of_combinations counter = 0 # Generate a list of all the possible combinations combo_gen = combinations(list(range(num_samples)), k_choices) scores = np.zeros(number_of_combinations, dtype=np.float32) # Generate the pairwise indices once pairwise = np.array( [y for y in combinations(list(range(k_choices)), 2)]) for combos in self.grouper(chunk, combo_gen): scores[(counter * chunk):((counter + 1) * chunk)] \ = self.mappable(combos, pairwise, distance_matrix) counter += 1 return scores
[ "def", "find_most_distant", "(", "self", ",", "input_sample", ",", "num_samples", ",", "num_params", ",", "k_choices", ",", "num_groups", "=", "None", ")", ":", "# Now evaluate the (N choose k_choices) possible combinations", "if", "nchoosek", "(", "num_samples", ",", ...
Finds the 'k_choices' most distant choices from the 'num_samples' trajectories contained in 'input_sample' Arguments --------- input_sample : numpy.ndarray num_samples : int The number of samples to generate num_params : int The number of parameters k_choices : int The number of optimal trajectories num_groups : int, default=None The number of groups Returns ------- numpy.ndarray
[ "Finds", "the", "k_choices", "most", "distant", "choices", "from", "the", "num_samples", "trajectories", "contained", "in", "input_sample" ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/sample/morris/brute.py#L50-L101
240,997
SALib/SALib
src/SALib/sample/morris/brute.py
BruteForce.mappable
def mappable(combos, pairwise, distance_matrix): ''' Obtains scores from the distance_matrix for each pairwise combination held in the combos array Arguments ---------- combos : numpy.ndarray pairwise : numpy.ndarray distance_matrix : numpy.ndarray ''' combos = np.array(combos) # Create a list of all pairwise combination for each combo in combos combo_list = combos[:, pairwise[:, ]] addresses = tuple([combo_list[:, :, 1], combo_list[:, :, 0]]) all_distances = distance_matrix[addresses] new_scores = np.sqrt( np.einsum('ij,ij->i', all_distances, all_distances)) return new_scores
python
def mappable(combos, pairwise, distance_matrix): ''' Obtains scores from the distance_matrix for each pairwise combination held in the combos array Arguments ---------- combos : numpy.ndarray pairwise : numpy.ndarray distance_matrix : numpy.ndarray ''' combos = np.array(combos) # Create a list of all pairwise combination for each combo in combos combo_list = combos[:, pairwise[:, ]] addresses = tuple([combo_list[:, :, 1], combo_list[:, :, 0]]) all_distances = distance_matrix[addresses] new_scores = np.sqrt( np.einsum('ij,ij->i', all_distances, all_distances)) return new_scores
[ "def", "mappable", "(", "combos", ",", "pairwise", ",", "distance_matrix", ")", ":", "combos", "=", "np", ".", "array", "(", "combos", ")", "# Create a list of all pairwise combination for each combo in combos", "combo_list", "=", "combos", "[", ":", ",", "pairwise"...
Obtains scores from the distance_matrix for each pairwise combination held in the combos array Arguments ---------- combos : numpy.ndarray pairwise : numpy.ndarray distance_matrix : numpy.ndarray
[ "Obtains", "scores", "from", "the", "distance_matrix", "for", "each", "pairwise", "combination", "held", "in", "the", "combos", "array" ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/sample/morris/brute.py#L113-L133
240,998
SALib/SALib
src/SALib/sample/morris/brute.py
BruteForce.find_maximum
def find_maximum(self, scores, N, k_choices): """Finds the `k_choices` maximum scores from `scores` Arguments --------- scores : numpy.ndarray N : int k_choices : int Returns ------- list """ if not isinstance(scores, np.ndarray): raise TypeError("Scores input is not a numpy array") index_of_maximum = int(scores.argmax()) maximum_combo = self.nth(combinations( list(range(N)), k_choices), index_of_maximum, None) return sorted(maximum_combo)
python
def find_maximum(self, scores, N, k_choices): if not isinstance(scores, np.ndarray): raise TypeError("Scores input is not a numpy array") index_of_maximum = int(scores.argmax()) maximum_combo = self.nth(combinations( list(range(N)), k_choices), index_of_maximum, None) return sorted(maximum_combo)
[ "def", "find_maximum", "(", "self", ",", "scores", ",", "N", ",", "k_choices", ")", ":", "if", "not", "isinstance", "(", "scores", ",", "np", ".", "ndarray", ")", ":", "raise", "TypeError", "(", "\"Scores input is not a numpy array\"", ")", "index_of_maximum",...
Finds the `k_choices` maximum scores from `scores` Arguments --------- scores : numpy.ndarray N : int k_choices : int Returns ------- list
[ "Finds", "the", "k_choices", "maximum", "scores", "from", "scores" ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/sample/morris/brute.py#L135-L154
240,999
SALib/SALib
src/SALib/sample/morris/brute.py
BruteForce.nth
def nth(iterable, n, default=None): """Returns the nth item or a default value Arguments --------- iterable : iterable n : int default : default=None The default value to return """ if type(n) != int: raise TypeError("n is not an integer") return next(islice(iterable, n, None), default)
python
def nth(iterable, n, default=None): if type(n) != int: raise TypeError("n is not an integer") return next(islice(iterable, n, None), default)
[ "def", "nth", "(", "iterable", ",", "n", ",", "default", "=", "None", ")", ":", "if", "type", "(", "n", ")", "!=", "int", ":", "raise", "TypeError", "(", "\"n is not an integer\"", ")", "return", "next", "(", "islice", "(", "iterable", ",", "n", ",",...
Returns the nth item or a default value Arguments --------- iterable : iterable n : int default : default=None The default value to return
[ "Returns", "the", "nth", "item", "or", "a", "default", "value" ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/sample/morris/brute.py#L157-L171