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 ...
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', la...
[ "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,) ...
[ "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) Sourc...
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], ...
[ "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) Targe...
[ "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 ...
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 ...
[ "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:...
[ "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 = ar...
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 = ar...
[ "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 ...
[ "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_\gamm...
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_\gamm...
[ "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 :...
[ "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_...
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...
[ "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 ...
[ "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: .....
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...
[ "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)...
[ "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_\m...
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 ...
[ "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 : - :m...
[ "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 pr...
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 pr...
[ "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 ...
[ "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 pr...
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 pr...
[ "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 \gamm...
[ "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 diverg...
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 diverg...
[ "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_...
[ "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 an...
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 l...
[ "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 prop...
[ "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...
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: ...
[ "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 i...
[ "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 follo...
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: ...
[ "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 \gam...
[ "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 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....
[ "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 [1...
[ "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...
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:...
[ "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 mat...
[ "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) m...
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...
[ "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', R...
[ "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 los...
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 derph...
[ "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.n...
[ "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)...
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: ...
[ "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 (n...
[ "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 ...
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 ...
[ "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 ...
[ "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: p...
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_non...
[ "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:...
[ "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) ...
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) ...
[ "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). ...
[ "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,...
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...
[ "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 delt...
[ "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 (sho...
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...
[ "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 = le...
[ "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)...
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 = min...
[ "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...
[ "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....
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 ...
[ "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 a...
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) G...
[ "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:: ...
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:: ...
[ "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 j...
[ "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]_ : ...
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]_ : ...
[ "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:`\m...
[ "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 ...
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 ...
[ "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 ...
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) T...
[ "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 = Tru...
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,...
[ "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 N...
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(...
[ "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, **kwa...
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....
[ "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 Regul...
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...
[ "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) ...
[ "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\...
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\...
[ "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 ...
[ "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 + ...
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 + ...
[ "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 ...
[ "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 m...
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 m...
[ "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 - re...
[ "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: .. ma...
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: .. ma...
[ "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 ...
[ "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} -...
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} -...
[ "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 \i...
[ "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 + re...
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 + re...
[ "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 ...
[ "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:: ...
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:: ...
[ "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 ...
[ "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) ...
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.pus...
[ "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 ...
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: ...
[ "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: ...
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. ...
[ "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...
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.fi...
[ "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): ...
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.m...
[ "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 locall...
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 ...
[ "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() ...
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 ...
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_e...
[ "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' " ...
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." ...
[ "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 """ i...
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 spaw...
[ "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 invo...
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' ...
[ "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 us...
[ "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 ...
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.write...
[ "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 na...
[ "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 sp...
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 Environm...
[ "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...
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' ...
[ "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 ""...
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() r...
[ "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 = extrac...
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_...
[ "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 fi...
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)) ...
[ "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 fil...
[ "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='...
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. Def...
[ "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_ma...
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_map...
[ "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 ...
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.Su...
[ "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 na...
[ "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 ------...
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), ...
[ "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` ...
[ "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 ...
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 pd...
[ "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 neare...
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 = ResultDi...
[ "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. ...
[ "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. ''' na...
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. ''' na...
[ "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 a...
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 = (na...
[ "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,...
[ "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_packa...
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_packa...
[ "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...
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...
[ "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 sa...
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]...
[ "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 fo...
[ "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: ...
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...
[ "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 - bou...
[ "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...
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_nam...
[ "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 ...
[ "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 brut...
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 brut...
[ "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(...
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(...
[ "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, ...
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, ...
[ "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. ...
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. ...
[ "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, ...
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, ...
[ "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 n...
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_...
[ "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 optim...
[ "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 : num...
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") ...
[ "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 paramete...
[ "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 ...
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 ...
[ "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):...
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) ...
[ "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 ...
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