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
75
19.8k
code_tokens
list
docstring
stringlengths
3
17.3k
docstring_tokens
list
sha
stringlengths
40
40
url
stringlengths
87
242
227,100
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
227,101
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): """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...
[ "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
227,102
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): """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...
[ "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
227,103
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): """ Solve the entropic regularization optimal transport problem with group lasso regularization The function solves the follo...
[ "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
227,104
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): """ 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...
[ "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
227,105
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): """ 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...
[ "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
227,106
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): """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...
[ "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
227,107
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): """ 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])
[ "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
227,108
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): """ 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])
[ "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
227,109
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): """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
[ "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
227,110
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): """ 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...
[ "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
227,111
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): """ 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)...
[ "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
227,112
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): """ Solve the general regularized OT problem with the generalized conditional gradient The function solves the following optimization problem: .. math:: \gamma ...
[ "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
227,113
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): """ 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...
[ "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
227,114
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): """ 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) ...
[ "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
227,115
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): """ 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,...
[ "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
227,116
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): """ 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...
[ "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
227,117
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): """ 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)...
[ "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
227,118
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): """ 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....
[ "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
227,119
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): """ 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...
[ "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
227,120
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
227,121
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
227,122
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): """Compute kernel matrix""" 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
227,123
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): """ 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
[ "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
227,124
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'): """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 ...
[ "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
227,125
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): """ 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 ...
[ "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
227,126
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()): """ 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...
[ "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
227,127
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): """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...
[ "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
227,128
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): """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...
[ "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
227,129
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): """split samples in X by classes in 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
227,130
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): """ 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...
[ "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
227,131
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
227,132
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
227,133
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
227,134
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
227,135
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
227,136
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
227,137
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
227,138
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): """ pyflakes found something wrong with the code. @param: A L{pyflakes.messages.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
227,139
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): """ 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
[ "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
227,140
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): """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
[ "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
227,141
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): """ 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) ...
[ "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
227,142
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): """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 ...
[ "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
227,143
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): """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: ...
[ "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
227,144
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): """ 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...
[ "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
227,145
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): """ 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): ...
[ "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
227,146
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): """ 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)
[ "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
227,147
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): """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...
[ "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
227,148
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): """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() ...
[ "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
227,149
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): """ 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 ...
[ "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
227,150
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): """ 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' " ...
[ "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
227,151
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'): """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...
[ "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
227,152
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'): """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...
[ "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
227,153
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): """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 ...
[ "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
227,154
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): """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...
[ "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
227,155
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): """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...
[ "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
227,156
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): """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 ""...
[ "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
227,157
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): """ 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...
[ "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
227,158
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): """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
[ "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
227,159
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): """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
[ "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
227,160
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): """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...
[ "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
227,161
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(): """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='...
[ "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
227,162
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): """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...
[ "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
227,163
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): """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 ...
[ "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
227,164
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): """ 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 ------...
[ "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
227,165
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): """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 ...
[ "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
227,166
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): """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...
[ "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
227,167
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
227,168
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): """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...
[ "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
227,169
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
227,170
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
227,171
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): """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...
[ "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
227,172
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): """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: ...
[ "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
227,173
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): """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...
[ "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
227,174
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
227,175
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
227,176
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
227,177
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
227,178
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): """ 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, ...
[ "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
227,179
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): """Use brute force method to find most distant trajectories Arguments --------- input_sample : numpy.ndarray n...
[ "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
227,180
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): """ Finds the 'k_choices' most distant choices from the 'num_samples' trajectories contained in 'input_sample' Arguments --------- input_sample : num...
[ "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
227,181
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
227,182
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): """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):...
[ "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
227,183
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): """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 ...
[ "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
227,184
SALib/SALib
src/SALib/sample/morris/__init__.py
sample
def sample(problem, N, num_levels=4, optimal_trajectories=None, local_optimization=True): """Generate model inputs using the Method of Morris Returns a NumPy matrix containing the model inputs required for Method of Morris. The resulting matrix has :math:`(G+1)*T` rows and :math:`D` columns...
python
def sample(problem, N, num_levels=4, optimal_trajectories=None, local_optimization=True): """Generate model inputs using the Method of Morris Returns a NumPy matrix containing the model inputs required for Method of Morris. The resulting matrix has :math:`(G+1)*T` rows and :math:`D` columns...
[ "def", "sample", "(", "problem", ",", "N", ",", "num_levels", "=", "4", ",", "optimal_trajectories", "=", "None", ",", "local_optimization", "=", "True", ")", ":", "if", "problem", ".", "get", "(", "'groups'", ")", ":", "sample", "=", "_sample_groups", "...
Generate model inputs using the Method of Morris Returns a NumPy matrix containing the model inputs required for Method of Morris. The resulting matrix has :math:`(G+1)*T` rows and :math:`D` columns, where :math:`D` is the number of parameters, :math:`G` is the number of groups (if no groups are selec...
[ "Generate", "model", "inputs", "using", "the", "Method", "of", "Morris" ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/sample/morris/__init__.py#L53-L103
227,185
SALib/SALib
src/SALib/sample/morris/__init__.py
_sample_oat
def _sample_oat(problem, N, num_levels=4): """Generate trajectories without groups Arguments --------- problem : dict The problem definition N : int The number of samples to generate num_levels : int, default=4 The number of grid levels """ group_membership = np....
python
def _sample_oat(problem, N, num_levels=4): """Generate trajectories without groups Arguments --------- problem : dict The problem definition N : int The number of samples to generate num_levels : int, default=4 The number of grid levels """ group_membership = np....
[ "def", "_sample_oat", "(", "problem", ",", "N", ",", "num_levels", "=", "4", ")", ":", "group_membership", "=", "np", ".", "asmatrix", "(", "np", ".", "identity", "(", "problem", "[", "'num_vars'", "]", ",", "dtype", "=", "int", ")", ")", "num_params",...
Generate trajectories without groups Arguments --------- problem : dict The problem definition N : int The number of samples to generate num_levels : int, default=4 The number of grid levels
[ "Generate", "trajectories", "without", "groups" ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/sample/morris/__init__.py#L106-L126
227,186
SALib/SALib
src/SALib/sample/morris/__init__.py
_sample_groups
def _sample_groups(problem, N, num_levels=4): """Generate trajectories for groups Returns an :math:`N(g+1)`-by-:math:`k` array of `N` trajectories, where :math:`g` is the number of groups and :math:`k` is the number of factors Arguments --------- problem : dict The problem definiti...
python
def _sample_groups(problem, N, num_levels=4): """Generate trajectories for groups Returns an :math:`N(g+1)`-by-:math:`k` array of `N` trajectories, where :math:`g` is the number of groups and :math:`k` is the number of factors Arguments --------- problem : dict The problem definiti...
[ "def", "_sample_groups", "(", "problem", ",", "N", ",", "num_levels", "=", "4", ")", ":", "if", "len", "(", "problem", "[", "'groups'", "]", ")", "!=", "problem", "[", "'num_vars'", "]", ":", "raise", "ValueError", "(", "\"Groups do not match to number of va...
Generate trajectories for groups Returns an :math:`N(g+1)`-by-:math:`k` array of `N` trajectories, where :math:`g` is the number of groups and :math:`k` is the number of factors Arguments --------- problem : dict The problem definition N : int The number of trajectories to ...
[ "Generate", "trajectories", "for", "groups" ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/sample/morris/__init__.py#L129-L166
227,187
SALib/SALib
src/SALib/sample/morris/__init__.py
generate_trajectory
def generate_trajectory(group_membership, num_levels=4): """Return a single trajectory Return a single trajectory of size :math:`(g+1)`-by-:math:`k` where :math:`g` is the number of groups, and :math:`k` is the number of factors, both implied by the dimensions of `group_membership` Arguments ...
python
def generate_trajectory(group_membership, num_levels=4): """Return a single trajectory Return a single trajectory of size :math:`(g+1)`-by-:math:`k` where :math:`g` is the number of groups, and :math:`k` is the number of factors, both implied by the dimensions of `group_membership` Arguments ...
[ "def", "generate_trajectory", "(", "group_membership", ",", "num_levels", "=", "4", ")", ":", "delta", "=", "compute_delta", "(", "num_levels", ")", "# Infer number of groups `g` and number of params `k` from", "# `group_membership` matrix", "num_params", "=", "group_membersh...
Return a single trajectory Return a single trajectory of size :math:`(g+1)`-by-:math:`k` where :math:`g` is the number of groups, and :math:`k` is the number of factors, both implied by the dimensions of `group_membership` Arguments --------- group_membership : np.ndarray a k-by-g ...
[ "Return", "a", "single", "trajectory" ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/sample/morris/__init__.py#L169-L215
227,188
SALib/SALib
src/SALib/sample/morris/__init__.py
generate_p_star
def generate_p_star(num_groups): """Describe the order in which groups move Arguments --------- num_groups : int Returns ------- np.ndarray Matrix P* - size (g-by-g) """ p_star = np.eye(num_groups, num_groups) rd.shuffle(p_star) return p_star
python
def generate_p_star(num_groups): """Describe the order in which groups move Arguments --------- num_groups : int Returns ------- np.ndarray Matrix P* - size (g-by-g) """ p_star = np.eye(num_groups, num_groups) rd.shuffle(p_star) return p_star
[ "def", "generate_p_star", "(", "num_groups", ")", ":", "p_star", "=", "np", ".", "eye", "(", "num_groups", ",", "num_groups", ")", "rd", ".", "shuffle", "(", "p_star", ")", "return", "p_star" ]
Describe the order in which groups move Arguments --------- num_groups : int Returns ------- np.ndarray Matrix P* - size (g-by-g)
[ "Describe", "the", "order", "in", "which", "groups", "move" ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/sample/morris/__init__.py#L230-L244
227,189
SALib/SALib
src/SALib/scripts/salib.py
parse_subargs
def parse_subargs(module, parser, method, opts): '''Attach argument parser for action specific options. Arguments --------- module : module name of module to extract action from parser : argparser argparser object to attach additional arguments to method : str name of me...
python
def parse_subargs(module, parser, method, opts): '''Attach argument parser for action specific options. Arguments --------- module : module name of module to extract action from parser : argparser argparser object to attach additional arguments to method : str name of me...
[ "def", "parse_subargs", "(", "module", ",", "parser", ",", "method", ",", "opts", ")", ":", "module", ".", "cli_args", "(", "parser", ")", "subargs", "=", "parser", ".", "parse_args", "(", "opts", ")", "return", "subargs" ]
Attach argument parser for action specific options. Arguments --------- module : module name of module to extract action from parser : argparser argparser object to attach additional arguments to method : str name of method (morris, sobol, etc). Must match one of the...
[ "Attach", "argument", "parser", "for", "action", "specific", "options", "." ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/scripts/salib.py#L8-L29
227,190
SALib/SALib
src/SALib/sample/morris/local.py
LocalOptimisation.find_local_maximum
def find_local_maximum(self, input_sample, N, num_params, k_choices, num_groups=None): """Find the most different trajectories in the input sample using a local approach An alternative by Ruano et al. (2012) for the brute force approach as originally proposed ...
python
def find_local_maximum(self, input_sample, N, num_params, k_choices, num_groups=None): """Find the most different trajectories in the input sample using a local approach An alternative by Ruano et al. (2012) for the brute force approach as originally proposed ...
[ "def", "find_local_maximum", "(", "self", ",", "input_sample", ",", "N", ",", "num_params", ",", "k_choices", ",", "num_groups", "=", "None", ")", ":", "distance_matrix", "=", "self", ".", "compute_distance_matrix", "(", "input_sample", ",", "N", ",", "num_par...
Find the most different trajectories in the input sample using a local approach An alternative by Ruano et al. (2012) for the brute force approach as originally proposed by Campolongo et al. (2007). The method should improve the speed with which an optimal set of trajectories is ...
[ "Find", "the", "most", "different", "trajectories", "in", "the", "input", "sample", "using", "a", "local", "approach" ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/sample/morris/local.py#L18-L89
227,191
SALib/SALib
src/SALib/sample/morris/local.py
LocalOptimisation.sum_distances
def sum_distances(self, indices, distance_matrix): """Calculate combinatorial distance between a select group of trajectories, indicated by indices Arguments --------- indices : tuple distance_matrix : numpy.ndarray (M,M) Returns ------- numpy.nd...
python
def sum_distances(self, indices, distance_matrix): """Calculate combinatorial distance between a select group of trajectories, indicated by indices Arguments --------- indices : tuple distance_matrix : numpy.ndarray (M,M) Returns ------- numpy.nd...
[ "def", "sum_distances", "(", "self", ",", "indices", ",", "distance_matrix", ")", ":", "combs_tup", "=", "np", ".", "array", "(", "tuple", "(", "combinations", "(", "indices", ",", "2", ")", ")", ")", "# Put indices from tuples into two-dimensional array.", "com...
Calculate combinatorial distance between a select group of trajectories, indicated by indices Arguments --------- indices : tuple distance_matrix : numpy.ndarray (M,M) Returns ------- numpy.ndarray Notes ----- This function can p...
[ "Calculate", "combinatorial", "distance", "between", "a", "select", "group", "of", "trajectories", "indicated", "by", "indices" ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/sample/morris/local.py#L91-L121
227,192
SALib/SALib
src/SALib/sample/morris/local.py
LocalOptimisation.get_max_sum_ind
def get_max_sum_ind(self, indices_list, distances, i, m): '''Get the indices that belong to the maximum distance in `distances` Arguments --------- indices_list : list list of tuples distances : numpy.ndarray size M i : int m : int ...
python
def get_max_sum_ind(self, indices_list, distances, i, m): '''Get the indices that belong to the maximum distance in `distances` Arguments --------- indices_list : list list of tuples distances : numpy.ndarray size M i : int m : int ...
[ "def", "get_max_sum_ind", "(", "self", ",", "indices_list", ",", "distances", ",", "i", ",", "m", ")", ":", "if", "len", "(", "indices_list", ")", "!=", "len", "(", "distances", ")", ":", "msg", "=", "\"Indices and distances are lists of different length.\"", ...
Get the indices that belong to the maximum distance in `distances` Arguments --------- indices_list : list list of tuples distances : numpy.ndarray size M i : int m : int Returns ------- list
[ "Get", "the", "indices", "that", "belong", "to", "the", "maximum", "distance", "in", "distances" ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/sample/morris/local.py#L123-L147
227,193
SALib/SALib
src/SALib/sample/morris/local.py
LocalOptimisation.add_indices
def add_indices(self, indices, distance_matrix): '''Adds extra indices for the combinatorial problem. Arguments --------- indices : tuple distance_matrix : numpy.ndarray (M,M) Example ------- >>> add_indices((1,2), numpy.array((5,5))) [(1, 2, 3),...
python
def add_indices(self, indices, distance_matrix): '''Adds extra indices for the combinatorial problem. Arguments --------- indices : tuple distance_matrix : numpy.ndarray (M,M) Example ------- >>> add_indices((1,2), numpy.array((5,5))) [(1, 2, 3),...
[ "def", "add_indices", "(", "self", ",", "indices", ",", "distance_matrix", ")", ":", "list_new_indices", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "distance_matrix", ")", ")", ":", "if", "i", "not", "in", "indices", ":", "l...
Adds extra indices for the combinatorial problem. Arguments --------- indices : tuple distance_matrix : numpy.ndarray (M,M) Example ------- >>> add_indices((1,2), numpy.array((5,5))) [(1, 2, 3), (1, 2, 4), (1, 2, 5)]
[ "Adds", "extra", "indices", "for", "the", "combinatorial", "problem", "." ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/sample/morris/local.py#L149-L167
227,194
SALib/SALib
src/SALib/util/results.py
ResultDict.to_df
def to_df(self): '''Convert dict structure into Pandas DataFrame.''' return pd.DataFrame({k: v for k, v in self.items() if k is not 'names'}, index=self['names'])
python
def to_df(self): '''Convert dict structure into Pandas DataFrame.''' return pd.DataFrame({k: v for k, v in self.items() if k is not 'names'}, index=self['names'])
[ "def", "to_df", "(", "self", ")", ":", "return", "pd", ".", "DataFrame", "(", "{", "k", ":", "v", "for", "k", ",", "v", "in", "self", ".", "items", "(", ")", "if", "k", "is", "not", "'names'", "}", ",", "index", "=", "self", "[", "'names'", "...
Convert dict structure into Pandas DataFrame.
[ "Convert", "dict", "structure", "into", "Pandas", "DataFrame", "." ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/util/results.py#L13-L16
227,195
SALib/SALib
src/SALib/plotting/morris.py
horizontal_bar_plot
def horizontal_bar_plot(ax, Si, param_dict, sortby='mu_star', unit=''): '''Updates a matplotlib axes instance with a horizontal bar plot of mu_star, with error bars representing mu_star_conf ''' assert sortby in ['mu_star', 'mu_star_conf', 'sigma', 'mu'] # Sort all the plotted elements by mu_star...
python
def horizontal_bar_plot(ax, Si, param_dict, sortby='mu_star', unit=''): '''Updates a matplotlib axes instance with a horizontal bar plot of mu_star, with error bars representing mu_star_conf ''' assert sortby in ['mu_star', 'mu_star_conf', 'sigma', 'mu'] # Sort all the plotted elements by mu_star...
[ "def", "horizontal_bar_plot", "(", "ax", ",", "Si", ",", "param_dict", ",", "sortby", "=", "'mu_star'", ",", "unit", "=", "''", ")", ":", "assert", "sortby", "in", "[", "'mu_star'", ",", "'mu_star_conf'", ",", "'sigma'", ",", "'mu'", "]", "# Sort all the p...
Updates a matplotlib axes instance with a horizontal bar plot of mu_star, with error bars representing mu_star_conf
[ "Updates", "a", "matplotlib", "axes", "instance", "with", "a", "horizontal", "bar", "plot" ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/plotting/morris.py#L33-L64
227,196
SALib/SALib
src/SALib/plotting/morris.py
sample_histograms
def sample_histograms(fig, input_sample, problem, param_dict): '''Plots a set of subplots of histograms of the input sample ''' num_vars = problem['num_vars'] names = problem['names'] framing = 101 + (num_vars * 10) # Find number of levels num_levels = len(set(input_sample[:, 1])) ou...
python
def sample_histograms(fig, input_sample, problem, param_dict): '''Plots a set of subplots of histograms of the input sample ''' num_vars = problem['num_vars'] names = problem['names'] framing = 101 + (num_vars * 10) # Find number of levels num_levels = len(set(input_sample[:, 1])) ou...
[ "def", "sample_histograms", "(", "fig", ",", "input_sample", ",", "problem", ",", "param_dict", ")", ":", "num_vars", "=", "problem", "[", "'num_vars'", "]", "names", "=", "problem", "[", "'names'", "]", "framing", "=", "101", "+", "(", "num_vars", "*", ...
Plots a set of subplots of histograms of the input sample
[ "Plots", "a", "set", "of", "subplots", "of", "histograms", "of", "the", "input", "sample" ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/plotting/morris.py#L105-L138
227,197
SALib/SALib
src/SALib/sample/ff.py
extend_bounds
def extend_bounds(problem): """Extends the problem bounds to the nearest power of two Arguments ========= problem : dict The problem definition """ num_vars = problem['num_vars'] num_ff_vars = 2 ** find_smallest(num_vars) num_dummy_variables = num_ff_vars - num_vars bounds...
python
def extend_bounds(problem): """Extends the problem bounds to the nearest power of two Arguments ========= problem : dict The problem definition """ num_vars = problem['num_vars'] num_ff_vars = 2 ** find_smallest(num_vars) num_dummy_variables = num_ff_vars - num_vars bounds...
[ "def", "extend_bounds", "(", "problem", ")", ":", "num_vars", "=", "problem", "[", "'num_vars'", "]", "num_ff_vars", "=", "2", "**", "find_smallest", "(", "num_vars", ")", "num_dummy_variables", "=", "num_ff_vars", "-", "num_vars", "bounds", "=", "list", "(", ...
Extends the problem bounds to the nearest power of two Arguments ========= problem : dict The problem definition
[ "Extends", "the", "problem", "bounds", "to", "the", "nearest", "power", "of", "two" ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/sample/ff.py#L33-L56
227,198
SALib/SALib
src/SALib/sample/ff.py
generate_contrast
def generate_contrast(problem): """Generates the raw sample from the problem file Arguments ========= problem : dict The problem definition """ num_vars = problem['num_vars'] # Find the smallest n, such that num_vars < k k = [2 ** n for n in range(16)] k_chosen = 2 ** find...
python
def generate_contrast(problem): """Generates the raw sample from the problem file Arguments ========= problem : dict The problem definition """ num_vars = problem['num_vars'] # Find the smallest n, such that num_vars < k k = [2 ** n for n in range(16)] k_chosen = 2 ** find...
[ "def", "generate_contrast", "(", "problem", ")", ":", "num_vars", "=", "problem", "[", "'num_vars'", "]", "# Find the smallest n, such that num_vars < k", "k", "=", "[", "2", "**", "n", "for", "n", "in", "range", "(", "16", ")", "]", "k_chosen", "=", "2", ...
Generates the raw sample from the problem file Arguments ========= problem : dict The problem definition
[ "Generates", "the", "raw", "sample", "from", "the", "problem", "file" ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/sample/ff.py#L59-L77
227,199
SALib/SALib
src/SALib/sample/ff.py
sample
def sample(problem, seed=None): """Generates model inputs using a fractional factorial sample Returns a NumPy matrix containing the model inputs required for a fractional factorial analysis. The resulting matrix has D columns, where D is smallest power of 2 that is greater than the number of parame...
python
def sample(problem, seed=None): """Generates model inputs using a fractional factorial sample Returns a NumPy matrix containing the model inputs required for a fractional factorial analysis. The resulting matrix has D columns, where D is smallest power of 2 that is greater than the number of parame...
[ "def", "sample", "(", "problem", ",", "seed", "=", "None", ")", ":", "if", "seed", ":", "np", ".", "random", ".", "seed", "(", "seed", ")", "contrast", "=", "generate_contrast", "(", "problem", ")", "sample", "=", "np", ".", "array", "(", "(", "con...
Generates model inputs using a fractional factorial sample Returns a NumPy matrix containing the model inputs required for a fractional factorial analysis. The resulting matrix has D columns, where D is smallest power of 2 that is greater than the number of parameters. These model inputs are intend...
[ "Generates", "model", "inputs", "using", "a", "fractional", "factorial", "sample" ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/sample/ff.py#L80-L113