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 divergence :math:`S`: .. math:: W &= \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) W_a &= \min_{\gamma_a} <\gamma_a,M_a>_F + reg\cdot\Omega(\gamma_a) W_b &= \min_{\gamma_b} <\gamma_b,M_b>_F + reg\cdot\Omega(\gamma_b) S &= W - 1/2 * (W_a + W_b) .. math:: s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 \gamma_a 1 = a \gamma_a^T 1= a \gamma_a\geq 0 \gamma_b 1 = b \gamma_b^T 1= b \gamma_b\geq 0 where : - :math:`M` (resp. :math:`M_a, M_b`) is the (ns,nt) metric cost matrix (resp (ns, ns) and (nt, nt)) - :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - :math:`a` and :math:`b` are source and target weights (sum to 1) Parameters ---------- X_s : np.ndarray (ns, d) samples in the source domain X_t : np.ndarray (nt, d) samples in the target domain reg : float Regularization term >0 a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) samples weights in the target domain numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Regularized optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters Examples -------- >>> n_s = 2 >>> n_t = 4 >>> reg = 0.1 >>> X_s = np.reshape(np.arange(n_s), (n_s, 1)) >>> X_t = np.reshape(np.arange(0, n_t), (n_t, 1)) >>> emp_sinkhorn_div = empirical_sinkhorn_divergence(X_s, X_t, reg) >>> print(emp_sinkhorn_div) >>> [2.99977435] References ---------- .. [23] Aude Genevay, Gabriel Peyré, Marco Cuturi, Learning Generative Models with Sinkhorn Divergences, Proceedings of the Twenty-First International Conference on Artficial Intelligence and Statistics, (AISTATS) 21, 2018 ''' if log: sinkhorn_loss_ab, log_ab = empirical_sinkhorn2(X_s, X_t, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwargs) sinkhorn_loss_a, log_a = empirical_sinkhorn2(X_s, X_s, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwargs) sinkhorn_loss_b, log_b = empirical_sinkhorn2(X_t, X_t, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwargs) sinkhorn_div = sinkhorn_loss_ab - 1 / 2 * (sinkhorn_loss_a + sinkhorn_loss_b) log = {} log['sinkhorn_loss_ab'] = sinkhorn_loss_ab log['sinkhorn_loss_a'] = sinkhorn_loss_a log['sinkhorn_loss_b'] = sinkhorn_loss_b log['log_sinkhorn_ab'] = log_ab log['log_sinkhorn_a'] = log_a log['log_sinkhorn_b'] = log_b return max(0, sinkhorn_div), log else: sinkhorn_loss_ab = empirical_sinkhorn2(X_s, X_t, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwargs) sinkhorn_loss_a = empirical_sinkhorn2(X_s, X_s, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwargs) sinkhorn_loss_b = empirical_sinkhorn2(X_t, X_t, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwargs) sinkhorn_div = sinkhorn_loss_ab - 1 / 2 * (sinkhorn_loss_a + sinkhorn_loss_b) return max(0, sinkhorn_div)
python
def empirical_sinkhorn_divergence(X_s, X_t, reg, a=None, b=None, metric='sqeuclidean', numIterMax=10000, stopThr=1e-9, verbose=False, log=False, **kwargs): ''' Compute the sinkhorn divergence loss from empirical data The function solves the following optimization problems and return the sinkhorn divergence :math:`S`: .. math:: W &= \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) W_a &= \min_{\gamma_a} <\gamma_a,M_a>_F + reg\cdot\Omega(\gamma_a) W_b &= \min_{\gamma_b} <\gamma_b,M_b>_F + reg\cdot\Omega(\gamma_b) S &= W - 1/2 * (W_a + W_b) .. math:: s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 \gamma_a 1 = a \gamma_a^T 1= a \gamma_a\geq 0 \gamma_b 1 = b \gamma_b^T 1= b \gamma_b\geq 0 where : - :math:`M` (resp. :math:`M_a, M_b`) is the (ns,nt) metric cost matrix (resp (ns, ns) and (nt, nt)) - :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - :math:`a` and :math:`b` are source and target weights (sum to 1) Parameters ---------- X_s : np.ndarray (ns, d) samples in the source domain X_t : np.ndarray (nt, d) samples in the target domain reg : float Regularization term >0 a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) samples weights in the target domain numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Regularized optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters Examples -------- >>> n_s = 2 >>> n_t = 4 >>> reg = 0.1 >>> X_s = np.reshape(np.arange(n_s), (n_s, 1)) >>> X_t = np.reshape(np.arange(0, n_t), (n_t, 1)) >>> emp_sinkhorn_div = empirical_sinkhorn_divergence(X_s, X_t, reg) >>> print(emp_sinkhorn_div) >>> [2.99977435] References ---------- .. [23] Aude Genevay, Gabriel Peyré, Marco Cuturi, Learning Generative Models with Sinkhorn Divergences, Proceedings of the Twenty-First International Conference on Artficial Intelligence and Statistics, (AISTATS) 21, 2018 ''' if log: sinkhorn_loss_ab, log_ab = empirical_sinkhorn2(X_s, X_t, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwargs) sinkhorn_loss_a, log_a = empirical_sinkhorn2(X_s, X_s, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwargs) sinkhorn_loss_b, log_b = empirical_sinkhorn2(X_t, X_t, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwargs) sinkhorn_div = sinkhorn_loss_ab - 1 / 2 * (sinkhorn_loss_a + sinkhorn_loss_b) log = {} log['sinkhorn_loss_ab'] = sinkhorn_loss_ab log['sinkhorn_loss_a'] = sinkhorn_loss_a log['sinkhorn_loss_b'] = sinkhorn_loss_b log['log_sinkhorn_ab'] = log_ab log['log_sinkhorn_a'] = log_a log['log_sinkhorn_b'] = log_b return max(0, sinkhorn_div), log else: sinkhorn_loss_ab = empirical_sinkhorn2(X_s, X_t, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwargs) sinkhorn_loss_a = empirical_sinkhorn2(X_s, X_s, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwargs) sinkhorn_loss_b = empirical_sinkhorn2(X_t, X_t, reg, a, b, metric=metric, numIterMax=numIterMax, stopThr=1e-9, verbose=verbose, log=log, **kwargs) sinkhorn_div = sinkhorn_loss_ab - 1 / 2 * (sinkhorn_loss_a + sinkhorn_loss_b) return max(0, sinkhorn_div)
[ "def", "empirical_sinkhorn_divergence", "(", "X_s", ",", "X_t", ",", "reg", ",", "a", "=", "None", ",", "b", "=", "None", ",", "metric", "=", "'sqeuclidean'", ",", "numIterMax", "=", "10000", ",", "stopThr", "=", "1e-9", ",", "verbose", "=", "False", ",", "log", "=", "False", ",", "*", "*", "kwargs", ")", ":", "if", "log", ":", "sinkhorn_loss_ab", ",", "log_ab", "=", "empirical_sinkhorn2", "(", "X_s", ",", "X_t", ",", "reg", ",", "a", ",", "b", ",", "metric", "=", "metric", ",", "numIterMax", "=", "numIterMax", ",", "stopThr", "=", "1e-9", ",", "verbose", "=", "verbose", ",", "log", "=", "log", ",", "*", "*", "kwargs", ")", "sinkhorn_loss_a", ",", "log_a", "=", "empirical_sinkhorn2", "(", "X_s", ",", "X_s", ",", "reg", ",", "a", ",", "b", ",", "metric", "=", "metric", ",", "numIterMax", "=", "numIterMax", ",", "stopThr", "=", "1e-9", ",", "verbose", "=", "verbose", ",", "log", "=", "log", ",", "*", "*", "kwargs", ")", "sinkhorn_loss_b", ",", "log_b", "=", "empirical_sinkhorn2", "(", "X_t", ",", "X_t", ",", "reg", ",", "a", ",", "b", ",", "metric", "=", "metric", ",", "numIterMax", "=", "numIterMax", ",", "stopThr", "=", "1e-9", ",", "verbose", "=", "verbose", ",", "log", "=", "log", ",", "*", "*", "kwargs", ")", "sinkhorn_div", "=", "sinkhorn_loss_ab", "-", "1", "/", "2", "*", "(", "sinkhorn_loss_a", "+", "sinkhorn_loss_b", ")", "log", "=", "{", "}", "log", "[", "'sinkhorn_loss_ab'", "]", "=", "sinkhorn_loss_ab", "log", "[", "'sinkhorn_loss_a'", "]", "=", "sinkhorn_loss_a", "log", "[", "'sinkhorn_loss_b'", "]", "=", "sinkhorn_loss_b", "log", "[", "'log_sinkhorn_ab'", "]", "=", "log_ab", "log", "[", "'log_sinkhorn_a'", "]", "=", "log_a", "log", "[", "'log_sinkhorn_b'", "]", "=", "log_b", "return", "max", "(", "0", ",", "sinkhorn_div", ")", ",", "log", "else", ":", "sinkhorn_loss_ab", "=", "empirical_sinkhorn2", "(", "X_s", ",", "X_t", ",", "reg", ",", "a", ",", "b", ",", "metric", "=", "metric", ",", "numIterMax", "=", "numIterMax", ",", "stopThr", "=", "1e-9", ",", "verbose", "=", "verbose", ",", "log", "=", "log", ",", "*", "*", "kwargs", ")", "sinkhorn_loss_a", "=", "empirical_sinkhorn2", "(", "X_s", ",", "X_s", ",", "reg", ",", "a", ",", "b", ",", "metric", "=", "metric", ",", "numIterMax", "=", "numIterMax", ",", "stopThr", "=", "1e-9", ",", "verbose", "=", "verbose", ",", "log", "=", "log", ",", "*", "*", "kwargs", ")", "sinkhorn_loss_b", "=", "empirical_sinkhorn2", "(", "X_t", ",", "X_t", ",", "reg", ",", "a", ",", "b", ",", "metric", "=", "metric", ",", "numIterMax", "=", "numIterMax", ",", "stopThr", "=", "1e-9", ",", "verbose", "=", "verbose", ",", "log", "=", "log", ",", "*", "*", "kwargs", ")", "sinkhorn_div", "=", "sinkhorn_loss_ab", "-", "1", "/", "2", "*", "(", "sinkhorn_loss_a", "+", "sinkhorn_loss_b", ")", "return", "max", "(", "0", ",", "sinkhorn_div", ")" ]
Compute the sinkhorn divergence loss from empirical data The function solves the following optimization problems and return the sinkhorn divergence :math:`S`: .. math:: W &= \min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) W_a &= \min_{\gamma_a} <\gamma_a,M_a>_F + reg\cdot\Omega(\gamma_a) W_b &= \min_{\gamma_b} <\gamma_b,M_b>_F + reg\cdot\Omega(\gamma_b) S &= W - 1/2 * (W_a + W_b) .. math:: s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 \gamma_a 1 = a \gamma_a^T 1= a \gamma_a\geq 0 \gamma_b 1 = b \gamma_b^T 1= b \gamma_b\geq 0 where : - :math:`M` (resp. :math:`M_a, M_b`) is the (ns,nt) metric cost matrix (resp (ns, ns) and (nt, nt)) - :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - :math:`a` and :math:`b` are source and target weights (sum to 1) Parameters ---------- X_s : np.ndarray (ns, d) samples in the source domain X_t : np.ndarray (nt, d) samples in the target domain reg : float Regularization term >0 a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) samples weights in the target domain numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Regularized optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters Examples -------- >>> n_s = 2 >>> n_t = 4 >>> reg = 0.1 >>> X_s = np.reshape(np.arange(n_s), (n_s, 1)) >>> X_t = np.reshape(np.arange(0, n_t), (n_t, 1)) >>> emp_sinkhorn_div = empirical_sinkhorn_divergence(X_s, X_t, reg) >>> print(emp_sinkhorn_div) >>> [2.99977435] References ---------- .. [23] Aude Genevay, Gabriel Peyré, Marco Cuturi, Learning Generative Models with Sinkhorn Divergences, Proceedings of the Twenty-First International Conference on Artficial Intelligence and Statistics, (AISTATS) 21, 2018
[ "Compute", "the", "sinkhorn", "divergence", "loss", "from", "empirical", "data" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/bregman.py#L1483-L1599
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 and b are the sample weights Uses the algorithm proposed in [1]_ Parameters ---------- a : (ns,) ndarray, float64 Source histogram (uniform weigth if empty list) b : (nt,) ndarray, float64 Target histogram (uniform weigth if empty list) M : (ns,nt) ndarray, float64 loss matrix numItermax : int, optional (default=100000) The maximum number of iterations before stopping the optimization algorithm if it has not converged. log: boolean, optional (default=False) If True, returns a dictionary containing the cost and dual variables. Otherwise returns only the optimal transportation matrix. Returns ------- gamma: (ns x nt) ndarray Optimal transportation matrix for the given parameters log: dict If input log is true, a dictionary containing the cost and dual variables and exit status Examples -------- Simple example with obvious solution. The function emd accepts lists and perform automatic conversion to numpy arrays >>> import ot >>> a=[.5,.5] >>> b=[.5,.5] >>> M=[[0.,1.],[1.,0.]] >>> ot.emd(a,b,M) array([[ 0.5, 0. ], [ 0. , 0.5]]) References ---------- .. [1] Bonneel, N., Van De Panne, M., Paris, S., & Heidrich, W. (2011, December). Displacement interpolation using Lagrangian mass transport. In ACM Transactions on Graphics (TOG) (Vol. 30, No. 6, p. 158). ACM. See Also -------- ot.bregman.sinkhorn : Entropic regularized OT ot.optim.cg : General regularized OT""" a = np.asarray(a, dtype=np.float64) b = np.asarray(b, dtype=np.float64) M = np.asarray(M, dtype=np.float64) # if empty array given then use unifor distributions if len(a) == 0: a = np.ones((M.shape[0],), dtype=np.float64) / M.shape[0] if len(b) == 0: b = np.ones((M.shape[1],), dtype=np.float64) / M.shape[1] G, cost, u, v, result_code = emd_c(a, b, M, numItermax) result_code_string = check_result(result_code) if log: log = {} log['cost'] = cost log['u'] = u log['v'] = v log['warning'] = result_code_string log['result_code'] = result_code return G, log return G
python
def emd(a, b, M, numItermax=100000, log=False): """Solves the Earth Movers distance problem and returns the OT matrix .. math:: \gamma = arg\min_\gamma <\gamma,M>_F s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - M is the metric cost matrix - a and b are the sample weights Uses the algorithm proposed in [1]_ Parameters ---------- a : (ns,) ndarray, float64 Source histogram (uniform weigth if empty list) b : (nt,) ndarray, float64 Target histogram (uniform weigth if empty list) M : (ns,nt) ndarray, float64 loss matrix numItermax : int, optional (default=100000) The maximum number of iterations before stopping the optimization algorithm if it has not converged. log: boolean, optional (default=False) If True, returns a dictionary containing the cost and dual variables. Otherwise returns only the optimal transportation matrix. Returns ------- gamma: (ns x nt) ndarray Optimal transportation matrix for the given parameters log: dict If input log is true, a dictionary containing the cost and dual variables and exit status Examples -------- Simple example with obvious solution. The function emd accepts lists and perform automatic conversion to numpy arrays >>> import ot >>> a=[.5,.5] >>> b=[.5,.5] >>> M=[[0.,1.],[1.,0.]] >>> ot.emd(a,b,M) array([[ 0.5, 0. ], [ 0. , 0.5]]) References ---------- .. [1] Bonneel, N., Van De Panne, M., Paris, S., & Heidrich, W. (2011, December). Displacement interpolation using Lagrangian mass transport. In ACM Transactions on Graphics (TOG) (Vol. 30, No. 6, p. 158). ACM. See Also -------- ot.bregman.sinkhorn : Entropic regularized OT ot.optim.cg : General regularized OT""" a = np.asarray(a, dtype=np.float64) b = np.asarray(b, dtype=np.float64) M = np.asarray(M, dtype=np.float64) # if empty array given then use unifor distributions if len(a) == 0: a = np.ones((M.shape[0],), dtype=np.float64) / M.shape[0] if len(b) == 0: b = np.ones((M.shape[1],), dtype=np.float64) / M.shape[1] G, cost, u, v, result_code = emd_c(a, b, M, numItermax) result_code_string = check_result(result_code) if log: log = {} log['cost'] = cost log['u'] = u log['v'] = v log['warning'] = result_code_string log['result_code'] = result_code return G, log return G
[ "def", "emd", "(", "a", ",", "b", ",", "M", ",", "numItermax", "=", "100000", ",", "log", "=", "False", ")", ":", "a", "=", "np", ".", "asarray", "(", "a", ",", "dtype", "=", "np", ".", "float64", ")", "b", "=", "np", ".", "asarray", "(", "b", ",", "dtype", "=", "np", ".", "float64", ")", "M", "=", "np", ".", "asarray", "(", "M", ",", "dtype", "=", "np", ".", "float64", ")", "# if empty array given then use unifor distributions", "if", "len", "(", "a", ")", "==", "0", ":", "a", "=", "np", ".", "ones", "(", "(", "M", ".", "shape", "[", "0", "]", ",", ")", ",", "dtype", "=", "np", ".", "float64", ")", "/", "M", ".", "shape", "[", "0", "]", "if", "len", "(", "b", ")", "==", "0", ":", "b", "=", "np", ".", "ones", "(", "(", "M", ".", "shape", "[", "1", "]", ",", ")", ",", "dtype", "=", "np", ".", "float64", ")", "/", "M", ".", "shape", "[", "1", "]", "G", ",", "cost", ",", "u", ",", "v", ",", "result_code", "=", "emd_c", "(", "a", ",", "b", ",", "M", ",", "numItermax", ")", "result_code_string", "=", "check_result", "(", "result_code", ")", "if", "log", ":", "log", "=", "{", "}", "log", "[", "'cost'", "]", "=", "cost", "log", "[", "'u'", "]", "=", "u", "log", "[", "'v'", "]", "=", "v", "log", "[", "'warning'", "]", "=", "result_code_string", "log", "[", "'result_code'", "]", "=", "result_code", "return", "G", ",", "log", "return", "G" ]
Solves the Earth Movers distance problem and returns the OT matrix .. math:: \gamma = arg\min_\gamma <\gamma,M>_F s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - M is the metric cost matrix - a and b are the sample weights Uses the algorithm proposed in [1]_ Parameters ---------- a : (ns,) ndarray, float64 Source histogram (uniform weigth if empty list) b : (nt,) ndarray, float64 Target histogram (uniform weigth if empty list) M : (ns,nt) ndarray, float64 loss matrix numItermax : int, optional (default=100000) The maximum number of iterations before stopping the optimization algorithm if it has not converged. log: boolean, optional (default=False) If True, returns a dictionary containing the cost and dual variables. Otherwise returns only the optimal transportation matrix. Returns ------- gamma: (ns x nt) ndarray Optimal transportation matrix for the given parameters log: dict If input log is true, a dictionary containing the cost and dual variables and exit status Examples -------- Simple example with obvious solution. The function emd accepts lists and perform automatic conversion to numpy arrays >>> import ot >>> a=[.5,.5] >>> b=[.5,.5] >>> M=[[0.,1.],[1.,0.]] >>> ot.emd(a,b,M) array([[ 0.5, 0. ], [ 0. , 0.5]]) References ---------- .. [1] Bonneel, N., Van De Panne, M., Paris, S., & Heidrich, W. (2011, December). Displacement interpolation using Lagrangian mass transport. In ACM Transactions on Graphics (TOG) (Vol. 30, No. 6, p. 158). ACM. See Also -------- ot.bregman.sinkhorn : Entropic regularized OT ot.optim.cg : General regularized OT
[ "Solves", "the", "Earth", "Movers", "distance", "problem", "and", "returns", "the", "OT", "matrix" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/lp/__init__.py#L25-L113
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\geq 0 where : - M is the metric cost matrix - a and b are the sample weights Uses the algorithm proposed in [1]_ Parameters ---------- a : (ns,) ndarray, float64 Source histogram (uniform weigth if empty list) b : (nt,) ndarray, float64 Target histogram (uniform weigth if empty list) M : (ns,nt) ndarray, float64 loss matrix numItermax : int, optional (default=100000) The maximum number of iterations before stopping the optimization algorithm if it has not converged. log: boolean, optional (default=False) If True, returns a dictionary containing the cost and dual variables. Otherwise returns only the optimal transportation cost. return_matrix: boolean, optional (default=False) If True, returns the optimal transportation matrix in the log. Returns ------- gamma: (ns x nt) ndarray Optimal transportation matrix for the given parameters log: dict If input log is true, a dictionary containing the cost and dual variables and exit status Examples -------- Simple example with obvious solution. The function emd accepts lists and perform automatic conversion to numpy arrays >>> import ot >>> a=[.5,.5] >>> b=[.5,.5] >>> M=[[0.,1.],[1.,0.]] >>> ot.emd2(a,b,M) 0.0 References ---------- .. [1] Bonneel, N., Van De Panne, M., Paris, S., & Heidrich, W. (2011, December). Displacement interpolation using Lagrangian mass transport. In ACM Transactions on Graphics (TOG) (Vol. 30, No. 6, p. 158). ACM. See Also -------- ot.bregman.sinkhorn : Entropic regularized OT ot.optim.cg : General regularized OT""" a = np.asarray(a, dtype=np.float64) b = np.asarray(b, dtype=np.float64) M = np.asarray(M, dtype=np.float64) # if empty array given then use unifor distributions if len(a) == 0: a = np.ones((M.shape[0],), dtype=np.float64) / M.shape[0] if len(b) == 0: b = np.ones((M.shape[1],), dtype=np.float64) / M.shape[1] if log or return_matrix: def f(b): G, cost, u, v, resultCode = emd_c(a, b, M, numItermax) result_code_string = check_result(resultCode) log = {} if return_matrix: log['G'] = G log['u'] = u log['v'] = v log['warning'] = result_code_string log['result_code'] = resultCode return [cost, log] else: def f(b): G, cost, u, v, result_code = emd_c(a, b, M, numItermax) check_result(result_code) return cost if len(b.shape) == 1: return f(b) nb = b.shape[1] res = parmap(f, [b[:, i] for i in range(nb)], processes) return res
python
def emd2(a, b, M, processes=multiprocessing.cpu_count(), numItermax=100000, log=False, return_matrix=False): """Solves the Earth Movers distance problem and returns the loss .. math:: \gamma = arg\min_\gamma <\gamma,M>_F s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - M is the metric cost matrix - a and b are the sample weights Uses the algorithm proposed in [1]_ Parameters ---------- a : (ns,) ndarray, float64 Source histogram (uniform weigth if empty list) b : (nt,) ndarray, float64 Target histogram (uniform weigth if empty list) M : (ns,nt) ndarray, float64 loss matrix numItermax : int, optional (default=100000) The maximum number of iterations before stopping the optimization algorithm if it has not converged. log: boolean, optional (default=False) If True, returns a dictionary containing the cost and dual variables. Otherwise returns only the optimal transportation cost. return_matrix: boolean, optional (default=False) If True, returns the optimal transportation matrix in the log. Returns ------- gamma: (ns x nt) ndarray Optimal transportation matrix for the given parameters log: dict If input log is true, a dictionary containing the cost and dual variables and exit status Examples -------- Simple example with obvious solution. The function emd accepts lists and perform automatic conversion to numpy arrays >>> import ot >>> a=[.5,.5] >>> b=[.5,.5] >>> M=[[0.,1.],[1.,0.]] >>> ot.emd2(a,b,M) 0.0 References ---------- .. [1] Bonneel, N., Van De Panne, M., Paris, S., & Heidrich, W. (2011, December). Displacement interpolation using Lagrangian mass transport. In ACM Transactions on Graphics (TOG) (Vol. 30, No. 6, p. 158). ACM. See Also -------- ot.bregman.sinkhorn : Entropic regularized OT ot.optim.cg : General regularized OT""" a = np.asarray(a, dtype=np.float64) b = np.asarray(b, dtype=np.float64) M = np.asarray(M, dtype=np.float64) # if empty array given then use unifor distributions if len(a) == 0: a = np.ones((M.shape[0],), dtype=np.float64) / M.shape[0] if len(b) == 0: b = np.ones((M.shape[1],), dtype=np.float64) / M.shape[1] if log or return_matrix: def f(b): G, cost, u, v, resultCode = emd_c(a, b, M, numItermax) result_code_string = check_result(resultCode) log = {} if return_matrix: log['G'] = G log['u'] = u log['v'] = v log['warning'] = result_code_string log['result_code'] = resultCode return [cost, log] else: def f(b): G, cost, u, v, result_code = emd_c(a, b, M, numItermax) check_result(result_code) return cost if len(b.shape) == 1: return f(b) nb = b.shape[1] res = parmap(f, [b[:, i] for i in range(nb)], processes) return res
[ "def", "emd2", "(", "a", ",", "b", ",", "M", ",", "processes", "=", "multiprocessing", ".", "cpu_count", "(", ")", ",", "numItermax", "=", "100000", ",", "log", "=", "False", ",", "return_matrix", "=", "False", ")", ":", "a", "=", "np", ".", "asarray", "(", "a", ",", "dtype", "=", "np", ".", "float64", ")", "b", "=", "np", ".", "asarray", "(", "b", ",", "dtype", "=", "np", ".", "float64", ")", "M", "=", "np", ".", "asarray", "(", "M", ",", "dtype", "=", "np", ".", "float64", ")", "# if empty array given then use unifor distributions", "if", "len", "(", "a", ")", "==", "0", ":", "a", "=", "np", ".", "ones", "(", "(", "M", ".", "shape", "[", "0", "]", ",", ")", ",", "dtype", "=", "np", ".", "float64", ")", "/", "M", ".", "shape", "[", "0", "]", "if", "len", "(", "b", ")", "==", "0", ":", "b", "=", "np", ".", "ones", "(", "(", "M", ".", "shape", "[", "1", "]", ",", ")", ",", "dtype", "=", "np", ".", "float64", ")", "/", "M", ".", "shape", "[", "1", "]", "if", "log", "or", "return_matrix", ":", "def", "f", "(", "b", ")", ":", "G", ",", "cost", ",", "u", ",", "v", ",", "resultCode", "=", "emd_c", "(", "a", ",", "b", ",", "M", ",", "numItermax", ")", "result_code_string", "=", "check_result", "(", "resultCode", ")", "log", "=", "{", "}", "if", "return_matrix", ":", "log", "[", "'G'", "]", "=", "G", "log", "[", "'u'", "]", "=", "u", "log", "[", "'v'", "]", "=", "v", "log", "[", "'warning'", "]", "=", "result_code_string", "log", "[", "'result_code'", "]", "=", "resultCode", "return", "[", "cost", ",", "log", "]", "else", ":", "def", "f", "(", "b", ")", ":", "G", ",", "cost", ",", "u", ",", "v", ",", "result_code", "=", "emd_c", "(", "a", ",", "b", ",", "M", ",", "numItermax", ")", "check_result", "(", "result_code", ")", "return", "cost", "if", "len", "(", "b", ".", "shape", ")", "==", "1", ":", "return", "f", "(", "b", ")", "nb", "=", "b", ".", "shape", "[", "1", "]", "res", "=", "parmap", "(", "f", ",", "[", "b", "[", ":", ",", "i", "]", "for", "i", "in", "range", "(", "nb", ")", "]", ",", "processes", ")", "return", "res" ]
Solves the Earth Movers distance problem and returns the loss .. math:: \gamma = arg\min_\gamma <\gamma,M>_F s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - M is the metric cost matrix - a and b are the sample weights Uses the algorithm proposed in [1]_ Parameters ---------- a : (ns,) ndarray, float64 Source histogram (uniform weigth if empty list) b : (nt,) ndarray, float64 Target histogram (uniform weigth if empty list) M : (ns,nt) ndarray, float64 loss matrix numItermax : int, optional (default=100000) The maximum number of iterations before stopping the optimization algorithm if it has not converged. log: boolean, optional (default=False) If True, returns a dictionary containing the cost and dual variables. Otherwise returns only the optimal transportation cost. return_matrix: boolean, optional (default=False) If True, returns the optimal transportation matrix in the log. Returns ------- gamma: (ns x nt) ndarray Optimal transportation matrix for the given parameters log: dict If input log is true, a dictionary containing the cost and dual variables and exit status Examples -------- Simple example with obvious solution. The function emd accepts lists and perform automatic conversion to numpy arrays >>> import ot >>> a=[.5,.5] >>> b=[.5,.5] >>> M=[[0.,1.],[1.,0.]] >>> ot.emd2(a,b,M) 0.0 References ---------- .. [1] Bonneel, N., Van De Panne, M., Paris, S., & Heidrich, W. (2011, December). Displacement interpolation using Lagrangian mass transport. In ACM Transactions on Graphics (TOG) (Vol. 30, No. 6, p. 158). ACM. See Also -------- ot.bregman.sinkhorn : Entropic regularized OT ot.optim.cg : General regularized OT
[ "Solves", "the", "Earth", "Movers", "distance", "problem", "and", "returns", "the", "loss" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/lp/__init__.py#L116-L219
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 following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega_e(\gamma)+ \eta \Omega_g(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - M is the (ns,nt) metric cost matrix - :math:`\Omega_e` is the entropic regularization term :math:`\Omega_e(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - :math:`\Omega_g` is the group lasso regulaization term :math:`\Omega_g(\gamma)=\sum_{i,c} \|\gamma_{i,\mathcal{I}_c}\|^2` where :math:`\mathcal{I}_c` are the index of samples from class c in the source domain. - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is the generalised conditional gradient as proposed in [5]_ [7]_ Parameters ---------- a : np.ndarray (ns,) samples weights in the source domain labels_a : np.ndarray (ns,) labels of samples in the source domain b : np.ndarray (nt,) samples in the target domain M : np.ndarray (ns,nt) loss matrix reg : float Regularization term for entropic regularization >0 eta : float, optional Regularization term for group lasso regularization >0 numItermax : int, optional Max number of iterations numInnerItermax : int, optional Max number of iterations (inner sinkhorn solver) stopInnerThr : float, optional Stop threshold on error (inner sinkhorn solver) (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters References ---------- .. [5] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy, "Optimal Transport for Domain Adaptation," in IEEE Transactions on Pattern Analysis and Machine Intelligence , vol.PP, no.99, pp.1-1 .. [7] Rakotomamonjy, A., Flamary, R., & Courty, N. (2015). Generalized conditional gradient: analysis of convergence and applications. arXiv preprint arXiv:1510.06567. See Also -------- ot.optim.gcg : Generalized conditional gradient for OT problems """ lstlab = np.unique(labels_a) def f(G): res = 0 for i in range(G.shape[1]): for lab in lstlab: temp = G[labels_a == lab, i] res += np.linalg.norm(temp) return res def df(G): W = np.zeros(G.shape) for i in range(G.shape[1]): for lab in lstlab: temp = G[labels_a == lab, i] n = np.linalg.norm(temp) if n: W[labels_a == lab, i] = temp / n return W return gcg(a, b, M, reg, eta, f, df, G0=None, numItermax=numItermax, numInnerItermax=numInnerItermax, stopThr=stopInnerThr, verbose=verbose, log=log)
python
def sinkhorn_l1l2_gl(a, labels_a, b, M, reg, eta=0.1, numItermax=10, numInnerItermax=200, stopInnerThr=1e-9, verbose=False, log=False): """ Solve the entropic regularization optimal transport problem with group lasso regularization The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega_e(\gamma)+ \eta \Omega_g(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - M is the (ns,nt) metric cost matrix - :math:`\Omega_e` is the entropic regularization term :math:`\Omega_e(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - :math:`\Omega_g` is the group lasso regulaization term :math:`\Omega_g(\gamma)=\sum_{i,c} \|\gamma_{i,\mathcal{I}_c}\|^2` where :math:`\mathcal{I}_c` are the index of samples from class c in the source domain. - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is the generalised conditional gradient as proposed in [5]_ [7]_ Parameters ---------- a : np.ndarray (ns,) samples weights in the source domain labels_a : np.ndarray (ns,) labels of samples in the source domain b : np.ndarray (nt,) samples in the target domain M : np.ndarray (ns,nt) loss matrix reg : float Regularization term for entropic regularization >0 eta : float, optional Regularization term for group lasso regularization >0 numItermax : int, optional Max number of iterations numInnerItermax : int, optional Max number of iterations (inner sinkhorn solver) stopInnerThr : float, optional Stop threshold on error (inner sinkhorn solver) (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters References ---------- .. [5] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy, "Optimal Transport for Domain Adaptation," in IEEE Transactions on Pattern Analysis and Machine Intelligence , vol.PP, no.99, pp.1-1 .. [7] Rakotomamonjy, A., Flamary, R., & Courty, N. (2015). Generalized conditional gradient: analysis of convergence and applications. arXiv preprint arXiv:1510.06567. See Also -------- ot.optim.gcg : Generalized conditional gradient for OT problems """ lstlab = np.unique(labels_a) def f(G): res = 0 for i in range(G.shape[1]): for lab in lstlab: temp = G[labels_a == lab, i] res += np.linalg.norm(temp) return res def df(G): W = np.zeros(G.shape) for i in range(G.shape[1]): for lab in lstlab: temp = G[labels_a == lab, i] n = np.linalg.norm(temp) if n: W[labels_a == lab, i] = temp / n return W return gcg(a, b, M, reg, eta, f, df, G0=None, numItermax=numItermax, numInnerItermax=numInnerItermax, stopThr=stopInnerThr, verbose=verbose, log=log)
[ "def", "sinkhorn_l1l2_gl", "(", "a", ",", "labels_a", ",", "b", ",", "M", ",", "reg", ",", "eta", "=", "0.1", ",", "numItermax", "=", "10", ",", "numInnerItermax", "=", "200", ",", "stopInnerThr", "=", "1e-9", ",", "verbose", "=", "False", ",", "log", "=", "False", ")", ":", "lstlab", "=", "np", ".", "unique", "(", "labels_a", ")", "def", "f", "(", "G", ")", ":", "res", "=", "0", "for", "i", "in", "range", "(", "G", ".", "shape", "[", "1", "]", ")", ":", "for", "lab", "in", "lstlab", ":", "temp", "=", "G", "[", "labels_a", "==", "lab", ",", "i", "]", "res", "+=", "np", ".", "linalg", ".", "norm", "(", "temp", ")", "return", "res", "def", "df", "(", "G", ")", ":", "W", "=", "np", ".", "zeros", "(", "G", ".", "shape", ")", "for", "i", "in", "range", "(", "G", ".", "shape", "[", "1", "]", ")", ":", "for", "lab", "in", "lstlab", ":", "temp", "=", "G", "[", "labels_a", "==", "lab", ",", "i", "]", "n", "=", "np", ".", "linalg", ".", "norm", "(", "temp", ")", "if", "n", ":", "W", "[", "labels_a", "==", "lab", ",", "i", "]", "=", "temp", "/", "n", "return", "W", "return", "gcg", "(", "a", ",", "b", ",", "M", ",", "reg", ",", "eta", ",", "f", ",", "df", ",", "G0", "=", "None", ",", "numItermax", "=", "numItermax", ",", "numInnerItermax", "=", "numInnerItermax", ",", "stopThr", "=", "stopInnerThr", ",", "verbose", "=", "verbose", ",", "log", "=", "log", ")" ]
Solve the entropic regularization optimal transport problem with group lasso regularization The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega_e(\gamma)+ \eta \Omega_g(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - M is the (ns,nt) metric cost matrix - :math:`\Omega_e` is the entropic regularization term :math:`\Omega_e(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - :math:`\Omega_g` is the group lasso regulaization term :math:`\Omega_g(\gamma)=\sum_{i,c} \|\gamma_{i,\mathcal{I}_c}\|^2` where :math:`\mathcal{I}_c` are the index of samples from class c in the source domain. - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is the generalised conditional gradient as proposed in [5]_ [7]_ Parameters ---------- a : np.ndarray (ns,) samples weights in the source domain labels_a : np.ndarray (ns,) labels of samples in the source domain b : np.ndarray (nt,) samples in the target domain M : np.ndarray (ns,nt) loss matrix reg : float Regularization term for entropic regularization >0 eta : float, optional Regularization term for group lasso regularization >0 numItermax : int, optional Max number of iterations numInnerItermax : int, optional Max number of iterations (inner sinkhorn solver) stopInnerThr : float, optional Stop threshold on error (inner sinkhorn solver) (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters References ---------- .. [5] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy, "Optimal Transport for Domain Adaptation," in IEEE Transactions on Pattern Analysis and Machine Intelligence , vol.PP, no.99, pp.1-1 .. [7] Rakotomamonjy, A., Flamary, R., & Courty, N. (2015). Generalized conditional gradient: analysis of convergence and applications. arXiv preprint arXiv:1510.06567. See Also -------- ot.optim.gcg : Generalized conditional gradient for OT problems
[ "Solve", "the", "entropic", "regularization", "optimal", "transport", "problem", "with", "group", "lasso", "regularization" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/da.py#L134-L238
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 between two Gaussian distributions :math:`N(\mu_s,\Sigma_s)` and :math:`N(\mu_t,\Sigma_t)` as proposed in [14] and discussed in remark 2.29 in [15]. The linear operator from source to target :math:`M` .. math:: M(x)=Ax+b where : .. math:: A=\Sigma_s^{-1/2}(\Sigma_s^{1/2}\Sigma_t\Sigma_s^{1/2})^{1/2} \Sigma_s^{-1/2} .. math:: b=\mu_t-A\mu_s Parameters ---------- xs : np.ndarray (ns,d) samples in the source domain xt : np.ndarray (nt,d) samples in the target domain reg : float,optional regularization added to the diagonals of convariances (>0) ws : np.ndarray (ns,1), optional weights for the source samples wt : np.ndarray (ns,1), optional weights for the target samples bias: boolean, optional estimate bias b else b=0 (default:True) log : bool, optional record log if True Returns ------- A : (d x d) ndarray Linear operator b : (1 x d) ndarray bias log : dict log dictionary return only if log==True in parameters References ---------- .. [14] Knott, M. and Smith, C. S. "On the optimal mapping of distributions", Journal of Optimization Theory and Applications Vol 43, 1984 .. [15] Peyré, G., & Cuturi, M. (2017). "Computational Optimal Transport", 2018. """ d = xs.shape[1] if bias: mxs = xs.mean(0, keepdims=True) mxt = xt.mean(0, keepdims=True) xs = xs - mxs xt = xt - mxt else: mxs = np.zeros((1, d)) mxt = np.zeros((1, d)) if ws is None: ws = np.ones((xs.shape[0], 1)) / xs.shape[0] if wt is None: wt = np.ones((xt.shape[0], 1)) / xt.shape[0] Cs = (xs * ws).T.dot(xs) / ws.sum() + reg * np.eye(d) Ct = (xt * wt).T.dot(xt) / wt.sum() + reg * np.eye(d) Cs12 = linalg.sqrtm(Cs) Cs_12 = linalg.inv(Cs12) M0 = linalg.sqrtm(Cs12.dot(Ct.dot(Cs12))) A = Cs_12.dot(M0.dot(Cs_12)) b = mxt - mxs.dot(A) if log: log = {} log['Cs'] = Cs log['Ct'] = Ct log['Cs12'] = Cs12 log['Cs_12'] = Cs_12 return A, b, log else: return A, b
python
def OT_mapping_linear(xs, xt, reg=1e-6, ws=None, wt=None, bias=True, log=False): """ return OT linear operator between samples The function estimates the optimal linear operator that aligns the two empirical distributions. This is equivalent to estimating the closed form mapping between two Gaussian distributions :math:`N(\mu_s,\Sigma_s)` and :math:`N(\mu_t,\Sigma_t)` as proposed in [14] and discussed in remark 2.29 in [15]. The linear operator from source to target :math:`M` .. math:: M(x)=Ax+b where : .. math:: A=\Sigma_s^{-1/2}(\Sigma_s^{1/2}\Sigma_t\Sigma_s^{1/2})^{1/2} \Sigma_s^{-1/2} .. math:: b=\mu_t-A\mu_s Parameters ---------- xs : np.ndarray (ns,d) samples in the source domain xt : np.ndarray (nt,d) samples in the target domain reg : float,optional regularization added to the diagonals of convariances (>0) ws : np.ndarray (ns,1), optional weights for the source samples wt : np.ndarray (ns,1), optional weights for the target samples bias: boolean, optional estimate bias b else b=0 (default:True) log : bool, optional record log if True Returns ------- A : (d x d) ndarray Linear operator b : (1 x d) ndarray bias log : dict log dictionary return only if log==True in parameters References ---------- .. [14] Knott, M. and Smith, C. S. "On the optimal mapping of distributions", Journal of Optimization Theory and Applications Vol 43, 1984 .. [15] Peyré, G., & Cuturi, M. (2017). "Computational Optimal Transport", 2018. """ d = xs.shape[1] if bias: mxs = xs.mean(0, keepdims=True) mxt = xt.mean(0, keepdims=True) xs = xs - mxs xt = xt - mxt else: mxs = np.zeros((1, d)) mxt = np.zeros((1, d)) if ws is None: ws = np.ones((xs.shape[0], 1)) / xs.shape[0] if wt is None: wt = np.ones((xt.shape[0], 1)) / xt.shape[0] Cs = (xs * ws).T.dot(xs) / ws.sum() + reg * np.eye(d) Ct = (xt * wt).T.dot(xt) / wt.sum() + reg * np.eye(d) Cs12 = linalg.sqrtm(Cs) Cs_12 = linalg.inv(Cs12) M0 = linalg.sqrtm(Cs12.dot(Ct.dot(Cs12))) A = Cs_12.dot(M0.dot(Cs_12)) b = mxt - mxs.dot(A) if log: log = {} log['Cs'] = Cs log['Ct'] = Ct log['Cs12'] = Cs12 log['Cs_12'] = Cs_12 return A, b, log else: return A, b
[ "def", "OT_mapping_linear", "(", "xs", ",", "xt", ",", "reg", "=", "1e-6", ",", "ws", "=", "None", ",", "wt", "=", "None", ",", "bias", "=", "True", ",", "log", "=", "False", ")", ":", "d", "=", "xs", ".", "shape", "[", "1", "]", "if", "bias", ":", "mxs", "=", "xs", ".", "mean", "(", "0", ",", "keepdims", "=", "True", ")", "mxt", "=", "xt", ".", "mean", "(", "0", ",", "keepdims", "=", "True", ")", "xs", "=", "xs", "-", "mxs", "xt", "=", "xt", "-", "mxt", "else", ":", "mxs", "=", "np", ".", "zeros", "(", "(", "1", ",", "d", ")", ")", "mxt", "=", "np", ".", "zeros", "(", "(", "1", ",", "d", ")", ")", "if", "ws", "is", "None", ":", "ws", "=", "np", ".", "ones", "(", "(", "xs", ".", "shape", "[", "0", "]", ",", "1", ")", ")", "/", "xs", ".", "shape", "[", "0", "]", "if", "wt", "is", "None", ":", "wt", "=", "np", ".", "ones", "(", "(", "xt", ".", "shape", "[", "0", "]", ",", "1", ")", ")", "/", "xt", ".", "shape", "[", "0", "]", "Cs", "=", "(", "xs", "*", "ws", ")", ".", "T", ".", "dot", "(", "xs", ")", "/", "ws", ".", "sum", "(", ")", "+", "reg", "*", "np", ".", "eye", "(", "d", ")", "Ct", "=", "(", "xt", "*", "wt", ")", ".", "T", ".", "dot", "(", "xt", ")", "/", "wt", ".", "sum", "(", ")", "+", "reg", "*", "np", ".", "eye", "(", "d", ")", "Cs12", "=", "linalg", ".", "sqrtm", "(", "Cs", ")", "Cs_12", "=", "linalg", ".", "inv", "(", "Cs12", ")", "M0", "=", "linalg", ".", "sqrtm", "(", "Cs12", ".", "dot", "(", "Ct", ".", "dot", "(", "Cs12", ")", ")", ")", "A", "=", "Cs_12", ".", "dot", "(", "M0", ".", "dot", "(", "Cs_12", ")", ")", "b", "=", "mxt", "-", "mxs", ".", "dot", "(", "A", ")", "if", "log", ":", "log", "=", "{", "}", "log", "[", "'Cs'", "]", "=", "Cs", "log", "[", "'Ct'", "]", "=", "Ct", "log", "[", "'Cs12'", "]", "=", "Cs12", "log", "[", "'Cs_12'", "]", "=", "Cs_12", "return", "A", ",", "b", ",", "log", "else", ":", "return", "A", ",", "b" ]
return OT linear operator between samples The function estimates the optimal linear operator that aligns the two empirical distributions. This is equivalent to estimating the closed form mapping between two Gaussian distributions :math:`N(\mu_s,\Sigma_s)` and :math:`N(\mu_t,\Sigma_t)` as proposed in [14] and discussed in remark 2.29 in [15]. The linear operator from source to target :math:`M` .. math:: M(x)=Ax+b where : .. math:: A=\Sigma_s^{-1/2}(\Sigma_s^{1/2}\Sigma_t\Sigma_s^{1/2})^{1/2} \Sigma_s^{-1/2} .. math:: b=\mu_t-A\mu_s Parameters ---------- xs : np.ndarray (ns,d) samples in the source domain xt : np.ndarray (nt,d) samples in the target domain reg : float,optional regularization added to the diagonals of convariances (>0) ws : np.ndarray (ns,1), optional weights for the source samples wt : np.ndarray (ns,1), optional weights for the target samples bias: boolean, optional estimate bias b else b=0 (default:True) log : bool, optional record log if True Returns ------- A : (d x d) ndarray Linear operator b : (1 x d) ndarray bias log : dict log dictionary return only if log==True in parameters References ---------- .. [14] Knott, M. and Smith, C. S. "On the optimal mapping of distributions", Journal of Optimization Theory and Applications Vol 43, 1984 .. [15] Peyré, G., & Cuturi, M. (2017). "Computational Optimal Transport", 2018.
[ "return", "OT", "linear", "operator", "between", "samples" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/da.py#L639-L740
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 (n, f) first matrix b : np.ndarray (m, f) second matrix to_numpy : boolean, optional (default True) If true convert back the GPU array result to numpy format. squared : boolean, optional (default False) if True, return squared euclidean distance matrix Returns ------- c : (n x m) np.ndarray or cupy.ndarray pairwise euclidean distance distance matrix """ a, b = to_gpu(a, b) a2 = np.sum(np.square(a), 1) b2 = np.sum(np.square(b), 1) c = -2 * np.dot(a, b.T) c += a2[:, None] c += b2[None, :] if not squared: np.sqrt(c, out=c) if to_numpy: return to_np(c) else: return c
python
def euclidean_distances(a, b, squared=False, to_numpy=True): """ Compute the pairwise euclidean distance between matrices a and b. If the input matrix are in numpy format, they will be uploaded to the GPU first which can incur significant time overhead. Parameters ---------- a : np.ndarray (n, f) first matrix b : np.ndarray (m, f) second matrix to_numpy : boolean, optional (default True) If true convert back the GPU array result to numpy format. squared : boolean, optional (default False) if True, return squared euclidean distance matrix Returns ------- c : (n x m) np.ndarray or cupy.ndarray pairwise euclidean distance distance matrix """ a, b = to_gpu(a, b) a2 = np.sum(np.square(a), 1) b2 = np.sum(np.square(b), 1) c = -2 * np.dot(a, b.T) c += a2[:, None] c += b2[None, :] if not squared: np.sqrt(c, out=c) if to_numpy: return to_np(c) else: return c
[ "def", "euclidean_distances", "(", "a", ",", "b", ",", "squared", "=", "False", ",", "to_numpy", "=", "True", ")", ":", "a", ",", "b", "=", "to_gpu", "(", "a", ",", "b", ")", "a2", "=", "np", ".", "sum", "(", "np", ".", "square", "(", "a", ")", ",", "1", ")", "b2", "=", "np", ".", "sum", "(", "np", ".", "square", "(", "b", ")", ",", "1", ")", "c", "=", "-", "2", "*", "np", ".", "dot", "(", "a", ",", "b", ".", "T", ")", "c", "+=", "a2", "[", ":", ",", "None", "]", "c", "+=", "b2", "[", "None", ",", ":", "]", "if", "not", "squared", ":", "np", ".", "sqrt", "(", "c", ",", "out", "=", "c", ")", "if", "to_numpy", ":", "return", "to_np", "(", "c", ")", "else", ":", "return", "c" ]
Compute the pairwise euclidean distance between matrices a and b. If the input matrix are in numpy format, they will be uploaded to the GPU first which can incur significant time overhead. Parameters ---------- a : np.ndarray (n, f) first matrix b : np.ndarray (m, f) second matrix to_numpy : boolean, optional (default True) If true convert back the GPU array result to numpy format. squared : boolean, optional (default False) if True, return squared euclidean distance matrix Returns ------- c : (n x m) np.ndarray or cupy.ndarray pairwise euclidean distance distance matrix
[ "Compute", "the", "pairwise", "euclidean", "distance", "between", "matrices", "a", "and", "b", "." ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/gpu/utils.py#L16-L54
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) metric : str Metric from 'sqeuclidean', 'euclidean', Returns ------- M : np.array (n1,n2) distance matrix computed with given metric """ if x2 is None: x2 = x1 if metric == "sqeuclidean": return euclidean_distances(x1, x2, squared=True, to_numpy=to_numpy) elif metric == "euclidean": return euclidean_distances(x1, x2, squared=False, to_numpy=to_numpy) else: raise NotImplementedError
python
def dist(x1, x2=None, metric='sqeuclidean', to_numpy=True): """Compute distance between samples in x1 and x2 on gpu Parameters ---------- x1 : np.array (n1,d) matrix with n1 samples of size d x2 : np.array (n2,d), optional matrix with n2 samples of size d (if None then x2=x1) metric : str Metric from 'sqeuclidean', 'euclidean', Returns ------- M : np.array (n1,n2) distance matrix computed with given metric """ if x2 is None: x2 = x1 if metric == "sqeuclidean": return euclidean_distances(x1, x2, squared=True, to_numpy=to_numpy) elif metric == "euclidean": return euclidean_distances(x1, x2, squared=False, to_numpy=to_numpy) else: raise NotImplementedError
[ "def", "dist", "(", "x1", ",", "x2", "=", "None", ",", "metric", "=", "'sqeuclidean'", ",", "to_numpy", "=", "True", ")", ":", "if", "x2", "is", "None", ":", "x2", "=", "x1", "if", "metric", "==", "\"sqeuclidean\"", ":", "return", "euclidean_distances", "(", "x1", ",", "x2", ",", "squared", "=", "True", ",", "to_numpy", "=", "to_numpy", ")", "elif", "metric", "==", "\"euclidean\"", ":", "return", "euclidean_distances", "(", "x1", ",", "x2", ",", "squared", "=", "False", ",", "to_numpy", "=", "to_numpy", ")", "else", ":", "raise", "NotImplementedError" ]
Compute distance between samples in x1 and x2 on gpu Parameters ---------- x1 : np.array (n1,d) matrix with n1 samples of size d x2 : np.array (n2,d), optional matrix with n2 samples of size d (if None then x2=x1) metric : str Metric from 'sqeuclidean', 'euclidean', Returns ------- M : np.array (n1,n2) distance matrix computed with given metric
[ "Compute", "distance", "between", "samples", "in", "x1", "and", "x2", "on", "gpu" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/gpu/utils.py#L57-L85
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", ".", "tolist", "(", ")", ",", "size", "=", "A", ".", "shape", ")", "return", "SP" ]
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 loss function xk : np.ndarray initial position pk : np.ndarray descent direction gfk : np.ndarray gradient of f at xk old_fval : float loss value at xk args : tuple, optional arguments given to f c1 : float, optional c1 const in armijo rule (>0) alpha0 : float, optional initial step (>0) Returns ------- alpha : float step that satisfy armijo conditions fc : int nb of function call fa : float loss value at step alpha """ xk = np.atleast_1d(xk) fc = [0] def phi(alpha1): fc[0] += 1 return f(xk + alpha1 * pk, *args) if old_fval is None: phi0 = phi(0.) else: phi0 = old_fval derphi0 = np.sum(pk * gfk) # Quickfix for matrices alpha, phi1 = scalar_search_armijo( phi, phi0, derphi0, c1=c1, alpha0=alpha0) return alpha, fc[0], phi1
python
def line_search_armijo(f, xk, pk, gfk, old_fval, args=(), c1=1e-4, alpha0=0.99): """ Armijo linesearch function that works with matrices find an approximate minimum of f(xk+alpha*pk) that satifies the armijo conditions. Parameters ---------- f : function loss function xk : np.ndarray initial position pk : np.ndarray descent direction gfk : np.ndarray gradient of f at xk old_fval : float loss value at xk args : tuple, optional arguments given to f c1 : float, optional c1 const in armijo rule (>0) alpha0 : float, optional initial step (>0) Returns ------- alpha : float step that satisfy armijo conditions fc : int nb of function call fa : float loss value at step alpha """ xk = np.atleast_1d(xk) fc = [0] def phi(alpha1): fc[0] += 1 return f(xk + alpha1 * pk, *args) if old_fval is None: phi0 = phi(0.) else: phi0 = old_fval derphi0 = np.sum(pk * gfk) # Quickfix for matrices alpha, phi1 = scalar_search_armijo( phi, phi0, derphi0, c1=c1, alpha0=alpha0) return alpha, fc[0], phi1
[ "def", "line_search_armijo", "(", "f", ",", "xk", ",", "pk", ",", "gfk", ",", "old_fval", ",", "args", "=", "(", ")", ",", "c1", "=", "1e-4", ",", "alpha0", "=", "0.99", ")", ":", "xk", "=", "np", ".", "atleast_1d", "(", "xk", ")", "fc", "=", "[", "0", "]", "def", "phi", "(", "alpha1", ")", ":", "fc", "[", "0", "]", "+=", "1", "return", "f", "(", "xk", "+", "alpha1", "*", "pk", ",", "*", "args", ")", "if", "old_fval", "is", "None", ":", "phi0", "=", "phi", "(", "0.", ")", "else", ":", "phi0", "=", "old_fval", "derphi0", "=", "np", ".", "sum", "(", "pk", "*", "gfk", ")", "# Quickfix for matrices", "alpha", ",", "phi1", "=", "scalar_search_armijo", "(", "phi", ",", "phi0", ",", "derphi0", ",", "c1", "=", "c1", ",", "alpha0", "=", "alpha0", ")", "return", "alpha", ",", "fc", "[", "0", "]", ",", "phi1" ]
Armijo linesearch function that works with matrices find an approximate minimum of f(xk+alpha*pk) that satifies the armijo conditions. Parameters ---------- f : function loss function xk : np.ndarray initial position pk : np.ndarray descent direction gfk : np.ndarray gradient of f at xk old_fval : float loss value at xk args : tuple, optional arguments given to f c1 : float, optional c1 const in armijo rule (>0) alpha0 : float, optional initial step (>0) Returns ------- alpha : float step that satisfy armijo conditions fc : int nb of function call fa : float loss value at step alpha
[ "Armijo", "linesearch", "function", "that", "works", "with", "matrices" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/optim.py#L18-L72
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) s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - M is the (ns,nt) metric cost matrix - :math:`f` is the regularization term ( and df is its gradient) - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is conditional gradient as discussed in [1]_ Parameters ---------- a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) samples in the target domain M : np.ndarray (ns,nt) loss matrix reg : float Regularization term >0 G0 : np.ndarray (ns,nt), optional initial guess (default is indep joint density) numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters References ---------- .. [1] Ferradans, S., Papadakis, N., Peyré, G., & Aujol, J. F. (2014). Regularized discrete optimal transport. SIAM Journal on Imaging Sciences, 7(3), 1853-1882. See Also -------- ot.lp.emd : Unregularized optimal ransport ot.bregman.sinkhorn : Entropic regularized optimal transport """ loop = 1 if log: log = {'loss': []} if G0 is None: G = np.outer(a, b) else: G = G0 def cost(G): return np.sum(M * G) + reg * f(G) f_val = cost(G) if log: log['loss'].append(f_val) it = 0 if verbose: print('{:5s}|{:12s}|{:8s}'.format( 'It.', 'Loss', 'Delta loss') + '\n' + '-' * 32) print('{:5d}|{:8e}|{:8e}'.format(it, f_val, 0)) while loop: it += 1 old_fval = f_val # problem linearization Mi = M + reg * df(G) # set M positive Mi += Mi.min() # solve linear program Gc = emd(a, b, Mi) deltaG = Gc - G # line search alpha, fc, f_val = line_search_armijo(cost, G, deltaG, Mi, f_val) G = G + alpha * deltaG # test convergence if it >= numItermax: loop = 0 delta_fval = (f_val - old_fval) / abs(f_val) if abs(delta_fval) < stopThr: loop = 0 if log: log['loss'].append(f_val) if verbose: if it % 20 == 0: print('{:5s}|{:12s}|{:8s}'.format( 'It.', 'Loss', 'Delta loss') + '\n' + '-' * 32) print('{:5d}|{:8e}|{:8e}'.format(it, f_val, delta_fval)) if log: return G, log else: return G
python
def cg(a, b, M, reg, f, df, G0=None, numItermax=200, stopThr=1e-9, verbose=False, log=False): """ Solve the general regularized OT problem with conditional gradient The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg*f(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - M is the (ns,nt) metric cost matrix - :math:`f` is the regularization term ( and df is its gradient) - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is conditional gradient as discussed in [1]_ Parameters ---------- a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) samples in the target domain M : np.ndarray (ns,nt) loss matrix reg : float Regularization term >0 G0 : np.ndarray (ns,nt), optional initial guess (default is indep joint density) numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters References ---------- .. [1] Ferradans, S., Papadakis, N., Peyré, G., & Aujol, J. F. (2014). Regularized discrete optimal transport. SIAM Journal on Imaging Sciences, 7(3), 1853-1882. See Also -------- ot.lp.emd : Unregularized optimal ransport ot.bregman.sinkhorn : Entropic regularized optimal transport """ loop = 1 if log: log = {'loss': []} if G0 is None: G = np.outer(a, b) else: G = G0 def cost(G): return np.sum(M * G) + reg * f(G) f_val = cost(G) if log: log['loss'].append(f_val) it = 0 if verbose: print('{:5s}|{:12s}|{:8s}'.format( 'It.', 'Loss', 'Delta loss') + '\n' + '-' * 32) print('{:5d}|{:8e}|{:8e}'.format(it, f_val, 0)) while loop: it += 1 old_fval = f_val # problem linearization Mi = M + reg * df(G) # set M positive Mi += Mi.min() # solve linear program Gc = emd(a, b, Mi) deltaG = Gc - G # line search alpha, fc, f_val = line_search_armijo(cost, G, deltaG, Mi, f_val) G = G + alpha * deltaG # test convergence if it >= numItermax: loop = 0 delta_fval = (f_val - old_fval) / abs(f_val) if abs(delta_fval) < stopThr: loop = 0 if log: log['loss'].append(f_val) if verbose: if it % 20 == 0: print('{:5s}|{:12s}|{:8s}'.format( 'It.', 'Loss', 'Delta loss') + '\n' + '-' * 32) print('{:5d}|{:8e}|{:8e}'.format(it, f_val, delta_fval)) if log: return G, log else: return G
[ "def", "cg", "(", "a", ",", "b", ",", "M", ",", "reg", ",", "f", ",", "df", ",", "G0", "=", "None", ",", "numItermax", "=", "200", ",", "stopThr", "=", "1e-9", ",", "verbose", "=", "False", ",", "log", "=", "False", ")", ":", "loop", "=", "1", "if", "log", ":", "log", "=", "{", "'loss'", ":", "[", "]", "}", "if", "G0", "is", "None", ":", "G", "=", "np", ".", "outer", "(", "a", ",", "b", ")", "else", ":", "G", "=", "G0", "def", "cost", "(", "G", ")", ":", "return", "np", ".", "sum", "(", "M", "*", "G", ")", "+", "reg", "*", "f", "(", "G", ")", "f_val", "=", "cost", "(", "G", ")", "if", "log", ":", "log", "[", "'loss'", "]", ".", "append", "(", "f_val", ")", "it", "=", "0", "if", "verbose", ":", "print", "(", "'{:5s}|{:12s}|{:8s}'", ".", "format", "(", "'It.'", ",", "'Loss'", ",", "'Delta loss'", ")", "+", "'\\n'", "+", "'-'", "*", "32", ")", "print", "(", "'{:5d}|{:8e}|{:8e}'", ".", "format", "(", "it", ",", "f_val", ",", "0", ")", ")", "while", "loop", ":", "it", "+=", "1", "old_fval", "=", "f_val", "# problem linearization", "Mi", "=", "M", "+", "reg", "*", "df", "(", "G", ")", "# set M positive", "Mi", "+=", "Mi", ".", "min", "(", ")", "# solve linear program", "Gc", "=", "emd", "(", "a", ",", "b", ",", "Mi", ")", "deltaG", "=", "Gc", "-", "G", "# line search", "alpha", ",", "fc", ",", "f_val", "=", "line_search_armijo", "(", "cost", ",", "G", ",", "deltaG", ",", "Mi", ",", "f_val", ")", "G", "=", "G", "+", "alpha", "*", "deltaG", "# test convergence", "if", "it", ">=", "numItermax", ":", "loop", "=", "0", "delta_fval", "=", "(", "f_val", "-", "old_fval", ")", "/", "abs", "(", "f_val", ")", "if", "abs", "(", "delta_fval", ")", "<", "stopThr", ":", "loop", "=", "0", "if", "log", ":", "log", "[", "'loss'", "]", ".", "append", "(", "f_val", ")", "if", "verbose", ":", "if", "it", "%", "20", "==", "0", ":", "print", "(", "'{:5s}|{:12s}|{:8s}'", ".", "format", "(", "'It.'", ",", "'Loss'", ",", "'Delta loss'", ")", "+", "'\\n'", "+", "'-'", "*", "32", ")", "print", "(", "'{:5d}|{:8e}|{:8e}'", ".", "format", "(", "it", ",", "f_val", ",", "delta_fval", ")", ")", "if", "log", ":", "return", "G", ",", "log", "else", ":", "return", "G" ]
Solve the general regularized OT problem with conditional gradient The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg*f(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - M is the (ns,nt) metric cost matrix - :math:`f` is the regularization term ( and df is its gradient) - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is conditional gradient as discussed in [1]_ Parameters ---------- a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) samples in the target domain M : np.ndarray (ns,nt) loss matrix reg : float Regularization term >0 G0 : np.ndarray (ns,nt), optional initial guess (default is indep joint density) numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters References ---------- .. [1] Ferradans, S., Papadakis, N., Peyré, G., & Aujol, J. F. (2014). Regularized discrete optimal transport. SIAM Journal on Imaging Sciences, 7(3), 1853-1882. See Also -------- ot.lp.emd : Unregularized optimal ransport ot.bregman.sinkhorn : Entropic regularized optimal transport
[ "Solve", "the", "general", "regularized", "OT", "problem", "with", "conditional", "gradient" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/optim.py#L75-L204
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 = arg\min_\gamma <\gamma,M>_F + reg1\cdot\Omega(\gamma) + reg2\cdot f(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - :math:`f` is the regularization term ( and df is its gradient) - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is the generalized conditional gradient as discussed in [5,7]_ Parameters ---------- a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) samples in the target domain M : np.ndarray (ns,nt) loss matrix reg1 : float Entropic Regularization term >0 reg2 : float Second Regularization term >0 G0 : np.ndarray (ns,nt), optional initial guess (default is indep joint density) numItermax : int, optional Max number of iterations numInnerItermax : int, optional Max number of iterations of Sinkhorn stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters References ---------- .. [5] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy, "Optimal Transport for Domain Adaptation," in IEEE Transactions on Pattern Analysis and Machine Intelligence , vol.PP, no.99, pp.1-1 .. [7] Rakotomamonjy, A., Flamary, R., & Courty, N. (2015). Generalized conditional gradient: analysis of convergence and applications. arXiv preprint arXiv:1510.06567. See Also -------- ot.optim.cg : conditional gradient """ loop = 1 if log: log = {'loss': []} if G0 is None: G = np.outer(a, b) else: G = G0 def cost(G): return np.sum(M * G) + reg1 * np.sum(G * np.log(G)) + reg2 * f(G) f_val = cost(G) if log: log['loss'].append(f_val) it = 0 if verbose: print('{:5s}|{:12s}|{:8s}'.format( 'It.', 'Loss', 'Delta loss') + '\n' + '-' * 32) print('{:5d}|{:8e}|{:8e}'.format(it, f_val, 0)) while loop: it += 1 old_fval = f_val # problem linearization Mi = M + reg2 * df(G) # solve linear program with Sinkhorn # Gc = sinkhorn_stabilized(a,b, Mi, reg1, numItermax = numInnerItermax) Gc = sinkhorn(a, b, Mi, reg1, numItermax=numInnerItermax) deltaG = Gc - G # line search dcost = Mi + reg1 * (1 + np.log(G)) # ?? alpha, fc, f_val = line_search_armijo(cost, G, deltaG, dcost, f_val) G = G + alpha * deltaG # test convergence if it >= numItermax: loop = 0 delta_fval = (f_val - old_fval) / abs(f_val) if abs(delta_fval) < stopThr: loop = 0 if log: log['loss'].append(f_val) if verbose: if it % 20 == 0: print('{:5s}|{:12s}|{:8s}'.format( 'It.', 'Loss', 'Delta loss') + '\n' + '-' * 32) print('{:5d}|{:8e}|{:8e}'.format(it, f_val, delta_fval)) if log: return G, log else: return G
python
def gcg(a, b, M, reg1, reg2, f, df, G0=None, numItermax=10, numInnerItermax=200, stopThr=1e-9, verbose=False, log=False): """ Solve the general regularized OT problem with the generalized conditional gradient The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg1\cdot\Omega(\gamma) + reg2\cdot f(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - :math:`f` is the regularization term ( and df is its gradient) - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is the generalized conditional gradient as discussed in [5,7]_ Parameters ---------- a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) samples in the target domain M : np.ndarray (ns,nt) loss matrix reg1 : float Entropic Regularization term >0 reg2 : float Second Regularization term >0 G0 : np.ndarray (ns,nt), optional initial guess (default is indep joint density) numItermax : int, optional Max number of iterations numInnerItermax : int, optional Max number of iterations of Sinkhorn stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters References ---------- .. [5] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy, "Optimal Transport for Domain Adaptation," in IEEE Transactions on Pattern Analysis and Machine Intelligence , vol.PP, no.99, pp.1-1 .. [7] Rakotomamonjy, A., Flamary, R., & Courty, N. (2015). Generalized conditional gradient: analysis of convergence and applications. arXiv preprint arXiv:1510.06567. See Also -------- ot.optim.cg : conditional gradient """ loop = 1 if log: log = {'loss': []} if G0 is None: G = np.outer(a, b) else: G = G0 def cost(G): return np.sum(M * G) + reg1 * np.sum(G * np.log(G)) + reg2 * f(G) f_val = cost(G) if log: log['loss'].append(f_val) it = 0 if verbose: print('{:5s}|{:12s}|{:8s}'.format( 'It.', 'Loss', 'Delta loss') + '\n' + '-' * 32) print('{:5d}|{:8e}|{:8e}'.format(it, f_val, 0)) while loop: it += 1 old_fval = f_val # problem linearization Mi = M + reg2 * df(G) # solve linear program with Sinkhorn # Gc = sinkhorn_stabilized(a,b, Mi, reg1, numItermax = numInnerItermax) Gc = sinkhorn(a, b, Mi, reg1, numItermax=numInnerItermax) deltaG = Gc - G # line search dcost = Mi + reg1 * (1 + np.log(G)) # ?? alpha, fc, f_val = line_search_armijo(cost, G, deltaG, dcost, f_val) G = G + alpha * deltaG # test convergence if it >= numItermax: loop = 0 delta_fval = (f_val - old_fval) / abs(f_val) if abs(delta_fval) < stopThr: loop = 0 if log: log['loss'].append(f_val) if verbose: if it % 20 == 0: print('{:5s}|{:12s}|{:8s}'.format( 'It.', 'Loss', 'Delta loss') + '\n' + '-' * 32) print('{:5d}|{:8e}|{:8e}'.format(it, f_val, delta_fval)) if log: return G, log else: return G
[ "def", "gcg", "(", "a", ",", "b", ",", "M", ",", "reg1", ",", "reg2", ",", "f", ",", "df", ",", "G0", "=", "None", ",", "numItermax", "=", "10", ",", "numInnerItermax", "=", "200", ",", "stopThr", "=", "1e-9", ",", "verbose", "=", "False", ",", "log", "=", "False", ")", ":", "loop", "=", "1", "if", "log", ":", "log", "=", "{", "'loss'", ":", "[", "]", "}", "if", "G0", "is", "None", ":", "G", "=", "np", ".", "outer", "(", "a", ",", "b", ")", "else", ":", "G", "=", "G0", "def", "cost", "(", "G", ")", ":", "return", "np", ".", "sum", "(", "M", "*", "G", ")", "+", "reg1", "*", "np", ".", "sum", "(", "G", "*", "np", ".", "log", "(", "G", ")", ")", "+", "reg2", "*", "f", "(", "G", ")", "f_val", "=", "cost", "(", "G", ")", "if", "log", ":", "log", "[", "'loss'", "]", ".", "append", "(", "f_val", ")", "it", "=", "0", "if", "verbose", ":", "print", "(", "'{:5s}|{:12s}|{:8s}'", ".", "format", "(", "'It.'", ",", "'Loss'", ",", "'Delta loss'", ")", "+", "'\\n'", "+", "'-'", "*", "32", ")", "print", "(", "'{:5d}|{:8e}|{:8e}'", ".", "format", "(", "it", ",", "f_val", ",", "0", ")", ")", "while", "loop", ":", "it", "+=", "1", "old_fval", "=", "f_val", "# problem linearization", "Mi", "=", "M", "+", "reg2", "*", "df", "(", "G", ")", "# solve linear program with Sinkhorn", "# Gc = sinkhorn_stabilized(a,b, Mi, reg1, numItermax = numInnerItermax)", "Gc", "=", "sinkhorn", "(", "a", ",", "b", ",", "Mi", ",", "reg1", ",", "numItermax", "=", "numInnerItermax", ")", "deltaG", "=", "Gc", "-", "G", "# line search", "dcost", "=", "Mi", "+", "reg1", "*", "(", "1", "+", "np", ".", "log", "(", "G", ")", ")", "# ??", "alpha", ",", "fc", ",", "f_val", "=", "line_search_armijo", "(", "cost", ",", "G", ",", "deltaG", ",", "dcost", ",", "f_val", ")", "G", "=", "G", "+", "alpha", "*", "deltaG", "# test convergence", "if", "it", ">=", "numItermax", ":", "loop", "=", "0", "delta_fval", "=", "(", "f_val", "-", "old_fval", ")", "/", "abs", "(", "f_val", ")", "if", "abs", "(", "delta_fval", ")", "<", "stopThr", ":", "loop", "=", "0", "if", "log", ":", "log", "[", "'loss'", "]", ".", "append", "(", "f_val", ")", "if", "verbose", ":", "if", "it", "%", "20", "==", "0", ":", "print", "(", "'{:5s}|{:12s}|{:8s}'", ".", "format", "(", "'It.'", ",", "'Loss'", ",", "'Delta loss'", ")", "+", "'\\n'", "+", "'-'", "*", "32", ")", "print", "(", "'{:5d}|{:8e}|{:8e}'", ".", "format", "(", "it", ",", "f_val", ",", "delta_fval", ")", ")", "if", "log", ":", "return", "G", ",", "log", "else", ":", "return", "G" ]
Solve the general regularized OT problem with the generalized conditional gradient The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg1\cdot\Omega(\gamma) + reg2\cdot f(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma\geq 0 where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - :math:`f` is the regularization term ( and df is its gradient) - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is the generalized conditional gradient as discussed in [5,7]_ Parameters ---------- a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) samples in the target domain M : np.ndarray (ns,nt) loss matrix reg1 : float Entropic Regularization term >0 reg2 : float Second Regularization term >0 G0 : np.ndarray (ns,nt), optional initial guess (default is indep joint density) numItermax : int, optional Max number of iterations numInnerItermax : int, optional Max number of iterations of Sinkhorn stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters References ---------- .. [5] N. Courty; R. Flamary; D. Tuia; A. Rakotomamonjy, "Optimal Transport for Domain Adaptation," in IEEE Transactions on Pattern Analysis and Machine Intelligence , vol.PP, no.99, pp.1-1 .. [7] Rakotomamonjy, A., Flamary, R., & Courty, N. (2015). Generalized conditional gradient: analysis of convergence and applications. arXiv preprint arXiv:1510.06567. See Also -------- ot.optim.cg : conditional gradient
[ "Solve", "the", "general", "regularized", "OT", "problem", "with", "the", "generalized", "conditional", "gradient" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/optim.py#L207-L341
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: project each V[i] by P(V[i]; z[i]) - axis=0: project each V[:, j] by P(V[:, j]; z[j]) """ if axis == 1: n_features = V.shape[1] U = np.sort(V, axis=1)[:, ::-1] z = np.ones(len(V)) * z cssv = np.cumsum(U, axis=1) - z[:, np.newaxis] ind = np.arange(n_features) + 1 cond = U - cssv / ind > 0 rho = np.count_nonzero(cond, axis=1) theta = cssv[np.arange(len(V)), rho - 1] / rho return np.maximum(V - theta[:, np.newaxis], 0) elif axis == 0: return projection_simplex(V.T, z, axis=1).T else: V = V.ravel().reshape(1, -1) return projection_simplex(V, z, axis=1).ravel()
python
def projection_simplex(V, z=1, axis=None): """ Projection of x onto the simplex, scaled by z P(x; z) = argmin_{y >= 0, sum(y) = z} ||y - x||^2 z: float or array If array, len(z) must be compatible with V axis: None or int - axis=None: project V by P(V.ravel(); z) - axis=1: project each V[i] by P(V[i]; z[i]) - axis=0: project each V[:, j] by P(V[:, j]; z[j]) """ if axis == 1: n_features = V.shape[1] U = np.sort(V, axis=1)[:, ::-1] z = np.ones(len(V)) * z cssv = np.cumsum(U, axis=1) - z[:, np.newaxis] ind = np.arange(n_features) + 1 cond = U - cssv / ind > 0 rho = np.count_nonzero(cond, axis=1) theta = cssv[np.arange(len(V)), rho - 1] / rho return np.maximum(V - theta[:, np.newaxis], 0) elif axis == 0: return projection_simplex(V.T, z, axis=1).T else: V = V.ravel().reshape(1, -1) return projection_simplex(V, z, axis=1).ravel()
[ "def", "projection_simplex", "(", "V", ",", "z", "=", "1", ",", "axis", "=", "None", ")", ":", "if", "axis", "==", "1", ":", "n_features", "=", "V", ".", "shape", "[", "1", "]", "U", "=", "np", ".", "sort", "(", "V", ",", "axis", "=", "1", ")", "[", ":", ",", ":", ":", "-", "1", "]", "z", "=", "np", ".", "ones", "(", "len", "(", "V", ")", ")", "*", "z", "cssv", "=", "np", ".", "cumsum", "(", "U", ",", "axis", "=", "1", ")", "-", "z", "[", ":", ",", "np", ".", "newaxis", "]", "ind", "=", "np", ".", "arange", "(", "n_features", ")", "+", "1", "cond", "=", "U", "-", "cssv", "/", "ind", ">", "0", "rho", "=", "np", ".", "count_nonzero", "(", "cond", ",", "axis", "=", "1", ")", "theta", "=", "cssv", "[", "np", ".", "arange", "(", "len", "(", "V", ")", ")", ",", "rho", "-", "1", "]", "/", "rho", "return", "np", ".", "maximum", "(", "V", "-", "theta", "[", ":", ",", "np", ".", "newaxis", "]", ",", "0", ")", "elif", "axis", "==", "0", ":", "return", "projection_simplex", "(", "V", ".", "T", ",", "z", ",", "axis", "=", "1", ")", ".", "T", "else", ":", "V", "=", "V", ".", "ravel", "(", ")", ".", "reshape", "(", "1", ",", "-", "1", ")", "return", "projection_simplex", "(", "V", ",", "z", ",", "axis", "=", "1", ")", ".", "ravel", "(", ")" ]
Projection of x onto the simplex, scaled by z P(x; z) = argmin_{y >= 0, sum(y) = z} ||y - x||^2 z: float or array If array, len(z) must be compatible with V axis: None or int - axis=None: project V by P(V.ravel(); z) - axis=1: project each V[i] by P(V[i]; z[i]) - axis=0: project each V[:, j] by P(V[:, j]; z[j])
[ "Projection", "of", "x", "onto", "the", "simplex", "scaled", "by", "z" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/smooth.py#L47-L74
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) Input histograms (should be non-negative and sum to 1). C: array, shape = len(a) x len(b) Ground cost matrix. regul: Regularization object Should implement a delta_Omega(X) method. Returns ------- obj: float Objective value (higher is better). grad_alpha: array, shape = len(a) Gradient w.r.t. alpha. grad_beta: array, shape = len(b) Gradient w.r.t. beta. """ obj = np.dot(alpha, a) + np.dot(beta, b) grad_alpha = a.copy() grad_beta = b.copy() # X[:, j] = alpha + beta[j] - C[:, j] X = alpha[:, np.newaxis] + beta - C # val.shape = len(b) # G.shape = len(a) x len(b) val, G = regul.delta_Omega(X) obj -= np.sum(val) grad_alpha -= G.sum(axis=1) grad_beta -= G.sum(axis=0) return obj, grad_alpha, grad_beta
python
def dual_obj_grad(alpha, beta, a, b, C, regul): """ Compute objective value and gradients of dual objective. Parameters ---------- alpha: array, shape = len(a) beta: array, shape = len(b) Current iterate of dual potentials. a: array, shape = len(a) b: array, shape = len(b) Input histograms (should be non-negative and sum to 1). C: array, shape = len(a) x len(b) Ground cost matrix. regul: Regularization object Should implement a delta_Omega(X) method. Returns ------- obj: float Objective value (higher is better). grad_alpha: array, shape = len(a) Gradient w.r.t. alpha. grad_beta: array, shape = len(b) Gradient w.r.t. beta. """ obj = np.dot(alpha, a) + np.dot(beta, b) grad_alpha = a.copy() grad_beta = b.copy() # X[:, j] = alpha + beta[j] - C[:, j] X = alpha[:, np.newaxis] + beta - C # val.shape = len(b) # G.shape = len(a) x len(b) val, G = regul.delta_Omega(X) obj -= np.sum(val) grad_alpha -= G.sum(axis=1) grad_beta -= G.sum(axis=0) return obj, grad_alpha, grad_beta
[ "def", "dual_obj_grad", "(", "alpha", ",", "beta", ",", "a", ",", "b", ",", "C", ",", "regul", ")", ":", "obj", "=", "np", ".", "dot", "(", "alpha", ",", "a", ")", "+", "np", ".", "dot", "(", "beta", ",", "b", ")", "grad_alpha", "=", "a", ".", "copy", "(", ")", "grad_beta", "=", "b", ".", "copy", "(", ")", "# X[:, j] = alpha + beta[j] - C[:, j]", "X", "=", "alpha", "[", ":", ",", "np", ".", "newaxis", "]", "+", "beta", "-", "C", "# val.shape = len(b)", "# G.shape = len(a) x len(b)", "val", ",", "G", "=", "regul", ".", "delta_Omega", "(", "X", ")", "obj", "-=", "np", ".", "sum", "(", "val", ")", "grad_alpha", "-=", "G", ".", "sum", "(", "axis", "=", "1", ")", "grad_beta", "-=", "G", ".", "sum", "(", "axis", "=", "0", ")", "return", "obj", ",", "grad_alpha", ",", "grad_beta" ]
Compute objective value and gradients of dual objective. Parameters ---------- alpha: array, shape = len(a) beta: array, shape = len(b) Current iterate of dual potentials. a: array, shape = len(a) b: array, shape = len(b) Input histograms (should be non-negative and sum to 1). C: array, shape = len(a) x len(b) Ground cost matrix. regul: Regularization object Should implement a delta_Omega(X) method. Returns ------- obj: float Objective value (higher is better). grad_alpha: array, shape = len(a) Gradient w.r.t. alpha. grad_beta: array, shape = len(b) Gradient w.r.t. beta.
[ "Compute", "objective", "value", "and", "gradients", "of", "dual", "objective", "." ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/smooth.py#L192-L233
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, shape = len(a) x len(b) Ground cost matrix. regul: Regularization object Should implement a delta_Omega(X) method. method: str Solver to be used (passed to `scipy.optimize.minimize`). tol: float Tolerance parameter. max_iter: int Maximum number of iterations. Returns ------- alpha: array, shape = len(a) beta: array, shape = len(b) Dual potentials. """ def _func(params): # Unpack alpha and beta. alpha = params[:len(a)] beta = params[len(a):] obj, grad_alpha, grad_beta = dual_obj_grad(alpha, beta, a, b, C, regul) # Pack grad_alpha and grad_beta. grad = np.concatenate((grad_alpha, grad_beta)) # We need to maximize the dual. return -obj, -grad # Unfortunately, `minimize` only supports functions whose argument is a # vector. So, we need to concatenate alpha and beta. alpha_init = np.zeros(len(a)) beta_init = np.zeros(len(b)) params_init = np.concatenate((alpha_init, beta_init)) res = minimize(_func, params_init, method=method, jac=True, tol=tol, options=dict(maxiter=max_iter, disp=verbose)) alpha = res.x[:len(a)] beta = res.x[len(a):] return alpha, beta, res
python
def solve_dual(a, b, C, regul, method="L-BFGS-B", tol=1e-3, max_iter=500, verbose=False): """ Solve the "smoothed" dual objective. Parameters ---------- a: array, shape = len(a) b: array, shape = len(b) Input histograms (should be non-negative and sum to 1). C: array, shape = len(a) x len(b) Ground cost matrix. regul: Regularization object Should implement a delta_Omega(X) method. method: str Solver to be used (passed to `scipy.optimize.minimize`). tol: float Tolerance parameter. max_iter: int Maximum number of iterations. Returns ------- alpha: array, shape = len(a) beta: array, shape = len(b) Dual potentials. """ def _func(params): # Unpack alpha and beta. alpha = params[:len(a)] beta = params[len(a):] obj, grad_alpha, grad_beta = dual_obj_grad(alpha, beta, a, b, C, regul) # Pack grad_alpha and grad_beta. grad = np.concatenate((grad_alpha, grad_beta)) # We need to maximize the dual. return -obj, -grad # Unfortunately, `minimize` only supports functions whose argument is a # vector. So, we need to concatenate alpha and beta. alpha_init = np.zeros(len(a)) beta_init = np.zeros(len(b)) params_init = np.concatenate((alpha_init, beta_init)) res = minimize(_func, params_init, method=method, jac=True, tol=tol, options=dict(maxiter=max_iter, disp=verbose)) alpha = res.x[:len(a)] beta = res.x[len(a):] return alpha, beta, res
[ "def", "solve_dual", "(", "a", ",", "b", ",", "C", ",", "regul", ",", "method", "=", "\"L-BFGS-B\"", ",", "tol", "=", "1e-3", ",", "max_iter", "=", "500", ",", "verbose", "=", "False", ")", ":", "def", "_func", "(", "params", ")", ":", "# Unpack alpha and beta.", "alpha", "=", "params", "[", ":", "len", "(", "a", ")", "]", "beta", "=", "params", "[", "len", "(", "a", ")", ":", "]", "obj", ",", "grad_alpha", ",", "grad_beta", "=", "dual_obj_grad", "(", "alpha", ",", "beta", ",", "a", ",", "b", ",", "C", ",", "regul", ")", "# Pack grad_alpha and grad_beta.", "grad", "=", "np", ".", "concatenate", "(", "(", "grad_alpha", ",", "grad_beta", ")", ")", "# We need to maximize the dual.", "return", "-", "obj", ",", "-", "grad", "# Unfortunately, `minimize` only supports functions whose argument is a", "# vector. So, we need to concatenate alpha and beta.", "alpha_init", "=", "np", ".", "zeros", "(", "len", "(", "a", ")", ")", "beta_init", "=", "np", ".", "zeros", "(", "len", "(", "b", ")", ")", "params_init", "=", "np", ".", "concatenate", "(", "(", "alpha_init", ",", "beta_init", ")", ")", "res", "=", "minimize", "(", "_func", ",", "params_init", ",", "method", "=", "method", ",", "jac", "=", "True", ",", "tol", "=", "tol", ",", "options", "=", "dict", "(", "maxiter", "=", "max_iter", ",", "disp", "=", "verbose", ")", ")", "alpha", "=", "res", ".", "x", "[", ":", "len", "(", "a", ")", "]", "beta", "=", "res", ".", "x", "[", "len", "(", "a", ")", ":", "]", "return", "alpha", ",", "beta", ",", "res" ]
Solve the "smoothed" dual objective. Parameters ---------- a: array, shape = len(a) b: array, shape = len(b) Input histograms (should be non-negative and sum to 1). C: array, shape = len(a) x len(b) Ground cost matrix. regul: Regularization object Should implement a delta_Omega(X) method. method: str Solver to be used (passed to `scipy.optimize.minimize`). tol: float Tolerance parameter. max_iter: int Maximum number of iterations. Returns ------- alpha: array, shape = len(a) beta: array, shape = len(b) Dual potentials.
[ "Solve", "the", "smoothed", "dual", "objective", "." ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/smooth.py#L236-L289
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 (should be non-negative and sum to 1). C: array, shape = len(a) x len(b) Ground cost matrix. regul: Regularization object Should implement a max_Omega(X) method. Returns ------- obj: float Objective value (higher is better). grad: array, shape = len(a) Gradient w.r.t. alpha. """ obj = np.dot(alpha, a) grad = a.copy() # X[:, j] = alpha - C[:, j] X = alpha[:, np.newaxis] - C # val.shape = len(b) # G.shape = len(a) x len(b) val, G = regul.max_Omega(X, b) obj -= np.dot(b, val) grad -= np.dot(G, b) return obj, grad
python
def semi_dual_obj_grad(alpha, a, b, C, regul): """ Compute objective value and gradient of semi-dual objective. Parameters ---------- alpha: array, shape = len(a) Current iterate of semi-dual potentials. a: array, shape = len(a) b: array, shape = len(b) Input histograms (should be non-negative and sum to 1). C: array, shape = len(a) x len(b) Ground cost matrix. regul: Regularization object Should implement a max_Omega(X) method. Returns ------- obj: float Objective value (higher is better). grad: array, shape = len(a) Gradient w.r.t. alpha. """ obj = np.dot(alpha, a) grad = a.copy() # X[:, j] = alpha - C[:, j] X = alpha[:, np.newaxis] - C # val.shape = len(b) # G.shape = len(a) x len(b) val, G = regul.max_Omega(X, b) obj -= np.dot(b, val) grad -= np.dot(G, b) return obj, grad
[ "def", "semi_dual_obj_grad", "(", "alpha", ",", "a", ",", "b", ",", "C", ",", "regul", ")", ":", "obj", "=", "np", ".", "dot", "(", "alpha", ",", "a", ")", "grad", "=", "a", ".", "copy", "(", ")", "# X[:, j] = alpha - C[:, j]", "X", "=", "alpha", "[", ":", ",", "np", ".", "newaxis", "]", "-", "C", "# val.shape = len(b)", "# G.shape = len(a) x len(b)", "val", ",", "G", "=", "regul", ".", "max_Omega", "(", "X", ",", "b", ")", "obj", "-=", "np", ".", "dot", "(", "b", ",", "val", ")", "grad", "-=", "np", ".", "dot", "(", "G", ",", "b", ")", "return", "obj", ",", "grad" ]
Compute objective value and gradient of semi-dual objective. Parameters ---------- alpha: array, shape = len(a) Current iterate of semi-dual potentials. a: array, shape = len(a) b: array, shape = len(b) Input histograms (should be non-negative and sum to 1). C: array, shape = len(a) x len(b) Ground cost matrix. regul: Regularization object Should implement a max_Omega(X) method. Returns ------- obj: float Objective value (higher is better). grad: array, shape = len(a) Gradient w.r.t. alpha.
[ "Compute", "objective", "value", "and", "gradient", "of", "semi", "-", "dual", "objective", "." ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/smooth.py#L292-L328
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). C: array, shape = len(a) x len(b) Ground cost matrix. regul: Regularization object Should implement a max_Omega(X) method. method: str Solver to be used (passed to `scipy.optimize.minimize`). tol: float Tolerance parameter. max_iter: int Maximum number of iterations. Returns ------- alpha: array, shape = len(a) Semi-dual potentials. """ def _func(alpha): obj, grad = semi_dual_obj_grad(alpha, a, b, C, regul) # We need to maximize the semi-dual. return -obj, -grad alpha_init = np.zeros(len(a)) res = minimize(_func, alpha_init, method=method, jac=True, tol=tol, options=dict(maxiter=max_iter, disp=verbose)) return res.x, res
python
def solve_semi_dual(a, b, C, regul, method="L-BFGS-B", tol=1e-3, max_iter=500, verbose=False): """ Solve the "smoothed" semi-dual objective. Parameters ---------- a: array, shape = len(a) b: array, shape = len(b) Input histograms (should be non-negative and sum to 1). C: array, shape = len(a) x len(b) Ground cost matrix. regul: Regularization object Should implement a max_Omega(X) method. method: str Solver to be used (passed to `scipy.optimize.minimize`). tol: float Tolerance parameter. max_iter: int Maximum number of iterations. Returns ------- alpha: array, shape = len(a) Semi-dual potentials. """ def _func(alpha): obj, grad = semi_dual_obj_grad(alpha, a, b, C, regul) # We need to maximize the semi-dual. return -obj, -grad alpha_init = np.zeros(len(a)) res = minimize(_func, alpha_init, method=method, jac=True, tol=tol, options=dict(maxiter=max_iter, disp=verbose)) return res.x, res
[ "def", "solve_semi_dual", "(", "a", ",", "b", ",", "C", ",", "regul", ",", "method", "=", "\"L-BFGS-B\"", ",", "tol", "=", "1e-3", ",", "max_iter", "=", "500", ",", "verbose", "=", "False", ")", ":", "def", "_func", "(", "alpha", ")", ":", "obj", ",", "grad", "=", "semi_dual_obj_grad", "(", "alpha", ",", "a", ",", "b", ",", "C", ",", "regul", ")", "# We need to maximize the semi-dual.", "return", "-", "obj", ",", "-", "grad", "alpha_init", "=", "np", ".", "zeros", "(", "len", "(", "a", ")", ")", "res", "=", "minimize", "(", "_func", ",", "alpha_init", ",", "method", "=", "method", ",", "jac", "=", "True", ",", "tol", "=", "tol", ",", "options", "=", "dict", "(", "maxiter", "=", "max_iter", ",", "disp", "=", "verbose", ")", ")", "return", "res", ".", "x", ",", "res" ]
Solve the "smoothed" semi-dual objective. Parameters ---------- a: array, shape = len(a) b: array, shape = len(b) Input histograms (should be non-negative and sum to 1). C: array, shape = len(a) x len(b) Ground cost matrix. regul: Regularization object Should implement a max_Omega(X) method. method: str Solver to be used (passed to `scipy.optimize.minimize`). tol: float Tolerance parameter. max_iter: int Maximum number of iterations. Returns ------- alpha: array, shape = len(a) Semi-dual potentials.
[ "Solve", "the", "smoothed", "semi", "-", "dual", "objective", "." ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/smooth.py#L331-L368
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. regul: Regularization object Should implement a delta_Omega(X) method. Returns ------- T: array, shape = len(a) x len(b) Optimal transportation plan. """ X = alpha[:, np.newaxis] + beta - C return regul.delta_Omega(X)[1]
python
def get_plan_from_dual(alpha, beta, C, regul): """ Retrieve optimal transportation plan from optimal dual potentials. Parameters ---------- alpha: array, shape = len(a) beta: array, shape = len(b) Optimal dual potentials. C: array, shape = len(a) x len(b) Ground cost matrix. regul: Regularization object Should implement a delta_Omega(X) method. Returns ------- T: array, shape = len(a) x len(b) Optimal transportation plan. """ X = alpha[:, np.newaxis] + beta - C return regul.delta_Omega(X)[1]
[ "def", "get_plan_from_dual", "(", "alpha", ",", "beta", ",", "C", ",", "regul", ")", ":", "X", "=", "alpha", "[", ":", ",", "np", ".", "newaxis", "]", "+", "beta", "-", "C", "return", "regul", ".", "delta_Omega", "(", "X", ")", "[", "1", "]" ]
Retrieve optimal transportation plan from optimal dual potentials. Parameters ---------- alpha: array, shape = len(a) beta: array, shape = len(b) Optimal dual potentials. C: array, shape = len(a) x len(b) Ground cost matrix. regul: Regularization object Should implement a delta_Omega(X) method. Returns ------- T: array, shape = len(a) x len(b) Optimal transportation plan.
[ "Retrieve", "optimal", "transportation", "plan", "from", "optimal", "dual", "potentials", "." ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/smooth.py#L371-L391
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 and sum to 1). C: array, shape = len(a) x len(b) Ground cost matrix. regul: Regularization object Should implement a delta_Omega(X) method. Returns ------- T: array, shape = len(a) x len(b) Optimal transportation plan. """ X = alpha[:, np.newaxis] - C return regul.max_Omega(X, b)[1] * b
python
def get_plan_from_semi_dual(alpha, b, C, regul): """ Retrieve optimal transportation plan from optimal semi-dual potentials. Parameters ---------- alpha: array, shape = len(a) Optimal semi-dual potentials. b: array, shape = len(b) Second input histogram (should be non-negative and sum to 1). C: array, shape = len(a) x len(b) Ground cost matrix. regul: Regularization object Should implement a delta_Omega(X) method. Returns ------- T: array, shape = len(a) x len(b) Optimal transportation plan. """ X = alpha[:, np.newaxis] - C return regul.max_Omega(X, b)[1] * b
[ "def", "get_plan_from_semi_dual", "(", "alpha", ",", "b", ",", "C", ",", "regul", ")", ":", "X", "=", "alpha", "[", ":", ",", "np", ".", "newaxis", "]", "-", "C", "return", "regul", ".", "max_Omega", "(", "X", ",", "b", ")", "[", "1", "]", "*", "b" ]
Retrieve optimal transportation plan from optimal semi-dual potentials. Parameters ---------- alpha: array, shape = len(a) Optimal semi-dual potentials. b: array, shape = len(b) Second input histogram (should be non-negative and sum to 1). C: array, shape = len(a) x len(b) Ground cost matrix. regul: Regularization object Should implement a delta_Omega(X) method. Returns ------- T: array, shape = len(a) x len(b) Optimal transportation plan.
[ "Retrieve", "optimal", "transportation", "plan", "from", "optimal", "semi", "-", "dual", "potentials", "." ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/smooth.py#L394-L415
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:: \max_{\alpha,\beta}\quad a^T\alpha+b^T\beta-\sum_j\delta_\Omega(\alpha+\beta_j-\mathbf{m}_j) where : - :math:`\mathbf{m}_j` is the jth column of the cost matrix - :math:`\delta_\Omega` is the convex conjugate of the regularization term :math:`\Omega` - a and b are source and target weights (sum to 1) The OT matrix can is reconstructed from the gradient of :math:`\delta_\Omega` (See [17]_ Proposition 1). The optimization algorithm is using gradient decent (L-BFGS by default). Parameters ---------- a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) or np.ndarray (nt,nbb) samples in the target domain, compute sinkhorn with multiple targets and fixed M if b is a matrix (return OT loss + dual variables in log) M : np.ndarray (ns,nt) loss matrix reg : float Regularization term >0 reg_type : str Regularization type, can be the following (default ='l2'): - 'kl' : Kullback Leibler (~ Neg-entropy used in sinkhorn [2]_) - 'l2' : Squared Euclidean regularization method : str Solver to use for scipy.optimize.minimize numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters References ---------- .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013 .. [17] Blondel, M., Seguy, V., & Rolet, A. (2018). Smooth and Sparse Optimal Transport. Proceedings of the Twenty-First International Conference on Artificial Intelligence and Statistics (AISTATS). See Also -------- ot.lp.emd : Unregularized OT ot.sinhorn : Entropic regularized OT ot.optim.cg : General regularized OT """ if reg_type.lower() in ['l2', 'squaredl2']: regul = SquaredL2(gamma=reg) elif reg_type.lower() in ['entropic', 'negentropy', 'kl']: regul = NegEntropy(gamma=reg) else: raise NotImplementedError('Unknown regularization') # solve dual alpha, beta, res = solve_dual(a, b, M, regul, max_iter=numItermax, tol=stopThr, verbose=verbose) # reconstruct transport matrix G = get_plan_from_dual(alpha, beta, M, regul) if log: log = {'alpha': alpha, 'beta': beta, 'res': res} return G, log else: return G
python
def smooth_ot_dual(a, b, M, reg, reg_type='l2', method="L-BFGS-B", stopThr=1e-9, numItermax=500, verbose=False, log=False): r""" Solve the regularized OT problem in the dual and return the OT matrix The function solves the smooth relaxed dual formulation (7) in [17]_ : .. math:: \max_{\alpha,\beta}\quad a^T\alpha+b^T\beta-\sum_j\delta_\Omega(\alpha+\beta_j-\mathbf{m}_j) where : - :math:`\mathbf{m}_j` is the jth column of the cost matrix - :math:`\delta_\Omega` is the convex conjugate of the regularization term :math:`\Omega` - a and b are source and target weights (sum to 1) The OT matrix can is reconstructed from the gradient of :math:`\delta_\Omega` (See [17]_ Proposition 1). The optimization algorithm is using gradient decent (L-BFGS by default). Parameters ---------- a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) or np.ndarray (nt,nbb) samples in the target domain, compute sinkhorn with multiple targets and fixed M if b is a matrix (return OT loss + dual variables in log) M : np.ndarray (ns,nt) loss matrix reg : float Regularization term >0 reg_type : str Regularization type, can be the following (default ='l2'): - 'kl' : Kullback Leibler (~ Neg-entropy used in sinkhorn [2]_) - 'l2' : Squared Euclidean regularization method : str Solver to use for scipy.optimize.minimize numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters References ---------- .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013 .. [17] Blondel, M., Seguy, V., & Rolet, A. (2018). Smooth and Sparse Optimal Transport. Proceedings of the Twenty-First International Conference on Artificial Intelligence and Statistics (AISTATS). See Also -------- ot.lp.emd : Unregularized OT ot.sinhorn : Entropic regularized OT ot.optim.cg : General regularized OT """ if reg_type.lower() in ['l2', 'squaredl2']: regul = SquaredL2(gamma=reg) elif reg_type.lower() in ['entropic', 'negentropy', 'kl']: regul = NegEntropy(gamma=reg) else: raise NotImplementedError('Unknown regularization') # solve dual alpha, beta, res = solve_dual(a, b, M, regul, max_iter=numItermax, tol=stopThr, verbose=verbose) # reconstruct transport matrix G = get_plan_from_dual(alpha, beta, M, regul) if log: log = {'alpha': alpha, 'beta': beta, 'res': res} return G, log else: return G
[ "def", "smooth_ot_dual", "(", "a", ",", "b", ",", "M", ",", "reg", ",", "reg_type", "=", "'l2'", ",", "method", "=", "\"L-BFGS-B\"", ",", "stopThr", "=", "1e-9", ",", "numItermax", "=", "500", ",", "verbose", "=", "False", ",", "log", "=", "False", ")", ":", "if", "reg_type", ".", "lower", "(", ")", "in", "[", "'l2'", ",", "'squaredl2'", "]", ":", "regul", "=", "SquaredL2", "(", "gamma", "=", "reg", ")", "elif", "reg_type", ".", "lower", "(", ")", "in", "[", "'entropic'", ",", "'negentropy'", ",", "'kl'", "]", ":", "regul", "=", "NegEntropy", "(", "gamma", "=", "reg", ")", "else", ":", "raise", "NotImplementedError", "(", "'Unknown regularization'", ")", "# solve dual", "alpha", ",", "beta", ",", "res", "=", "solve_dual", "(", "a", ",", "b", ",", "M", ",", "regul", ",", "max_iter", "=", "numItermax", ",", "tol", "=", "stopThr", ",", "verbose", "=", "verbose", ")", "# reconstruct transport matrix", "G", "=", "get_plan_from_dual", "(", "alpha", ",", "beta", ",", "M", ",", "regul", ")", "if", "log", ":", "log", "=", "{", "'alpha'", ":", "alpha", ",", "'beta'", ":", "beta", ",", "'res'", ":", "res", "}", "return", "G", ",", "log", "else", ":", "return", "G" ]
r""" Solve the regularized OT problem in the dual and return the OT matrix The function solves the smooth relaxed dual formulation (7) in [17]_ : .. math:: \max_{\alpha,\beta}\quad a^T\alpha+b^T\beta-\sum_j\delta_\Omega(\alpha+\beta_j-\mathbf{m}_j) where : - :math:`\mathbf{m}_j` is the jth column of the cost matrix - :math:`\delta_\Omega` is the convex conjugate of the regularization term :math:`\Omega` - a and b are source and target weights (sum to 1) The OT matrix can is reconstructed from the gradient of :math:`\delta_\Omega` (See [17]_ Proposition 1). The optimization algorithm is using gradient decent (L-BFGS by default). Parameters ---------- a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) or np.ndarray (nt,nbb) samples in the target domain, compute sinkhorn with multiple targets and fixed M if b is a matrix (return OT loss + dual variables in log) M : np.ndarray (ns,nt) loss matrix reg : float Regularization term >0 reg_type : str Regularization type, can be the following (default ='l2'): - 'kl' : Kullback Leibler (~ Neg-entropy used in sinkhorn [2]_) - 'l2' : Squared Euclidean regularization method : str Solver to use for scipy.optimize.minimize numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters References ---------- .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013 .. [17] Blondel, M., Seguy, V., & Rolet, A. (2018). Smooth and Sparse Optimal Transport. Proceedings of the Twenty-First International Conference on Artificial Intelligence and Statistics (AISTATS). See Also -------- ot.lp.emd : Unregularized OT ot.sinhorn : Entropic regularized OT ot.optim.cg : General regularized OT
[ "r", "Solve", "the", "regularized", "OT", "problem", "in", "the", "dual", "and", "return", "the", "OT", "matrix" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/smooth.py#L418-L507
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]_ : .. math:: \max_{\alpha}\quad a^T\alpha-OT_\Omega^*(\alpha,b) where : .. math:: OT_\Omega^*(\alpha,b)=\sum_j b_j - :math:`\mathbf{m}_j` is the jth column of the cost matrix - :math:`OT_\Omega^*(\alpha,b)` is defined in Eq. (9) in [17] - a and b are source and target weights (sum to 1) The OT matrix can is reconstructed using [17]_ Proposition 2. The optimization algorithm is using gradient decent (L-BFGS by default). Parameters ---------- a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) or np.ndarray (nt,nbb) samples in the target domain, compute sinkhorn with multiple targets and fixed M if b is a matrix (return OT loss + dual variables in log) M : np.ndarray (ns,nt) loss matrix reg : float Regularization term >0 reg_type : str Regularization type, can be the following (default ='l2'): - 'kl' : Kullback Leibler (~ Neg-entropy used in sinkhorn [2]_) - 'l2' : Squared Euclidean regularization method : str Solver to use for scipy.optimize.minimize numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters References ---------- .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013 .. [17] Blondel, M., Seguy, V., & Rolet, A. (2018). Smooth and Sparse Optimal Transport. Proceedings of the Twenty-First International Conference on Artificial Intelligence and Statistics (AISTATS). See Also -------- ot.lp.emd : Unregularized OT ot.sinhorn : Entropic regularized OT ot.optim.cg : General regularized OT """ if reg_type.lower() in ['l2', 'squaredl2']: regul = SquaredL2(gamma=reg) elif reg_type.lower() in ['entropic', 'negentropy', 'kl']: regul = NegEntropy(gamma=reg) else: raise NotImplementedError('Unknown regularization') # solve dual alpha, res = solve_semi_dual(a, b, M, regul, max_iter=numItermax, tol=stopThr, verbose=verbose) # reconstruct transport matrix G = get_plan_from_semi_dual(alpha, b, M, regul) if log: log = {'alpha': alpha, 'res': res} return G, log else: return G
python
def smooth_ot_semi_dual(a, b, M, reg, reg_type='l2', method="L-BFGS-B", stopThr=1e-9, numItermax=500, verbose=False, log=False): r""" Solve the regularized OT problem in the semi-dual and return the OT matrix The function solves the smooth relaxed dual formulation (10) in [17]_ : .. math:: \max_{\alpha}\quad a^T\alpha-OT_\Omega^*(\alpha,b) where : .. math:: OT_\Omega^*(\alpha,b)=\sum_j b_j - :math:`\mathbf{m}_j` is the jth column of the cost matrix - :math:`OT_\Omega^*(\alpha,b)` is defined in Eq. (9) in [17] - a and b are source and target weights (sum to 1) The OT matrix can is reconstructed using [17]_ Proposition 2. The optimization algorithm is using gradient decent (L-BFGS by default). Parameters ---------- a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) or np.ndarray (nt,nbb) samples in the target domain, compute sinkhorn with multiple targets and fixed M if b is a matrix (return OT loss + dual variables in log) M : np.ndarray (ns,nt) loss matrix reg : float Regularization term >0 reg_type : str Regularization type, can be the following (default ='l2'): - 'kl' : Kullback Leibler (~ Neg-entropy used in sinkhorn [2]_) - 'l2' : Squared Euclidean regularization method : str Solver to use for scipy.optimize.minimize numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters References ---------- .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013 .. [17] Blondel, M., Seguy, V., & Rolet, A. (2018). Smooth and Sparse Optimal Transport. Proceedings of the Twenty-First International Conference on Artificial Intelligence and Statistics (AISTATS). See Also -------- ot.lp.emd : Unregularized OT ot.sinhorn : Entropic regularized OT ot.optim.cg : General regularized OT """ if reg_type.lower() in ['l2', 'squaredl2']: regul = SquaredL2(gamma=reg) elif reg_type.lower() in ['entropic', 'negentropy', 'kl']: regul = NegEntropy(gamma=reg) else: raise NotImplementedError('Unknown regularization') # solve dual alpha, res = solve_semi_dual(a, b, M, regul, max_iter=numItermax, tol=stopThr, verbose=verbose) # reconstruct transport matrix G = get_plan_from_semi_dual(alpha, b, M, regul) if log: log = {'alpha': alpha, 'res': res} return G, log else: return G
[ "def", "smooth_ot_semi_dual", "(", "a", ",", "b", ",", "M", ",", "reg", ",", "reg_type", "=", "'l2'", ",", "method", "=", "\"L-BFGS-B\"", ",", "stopThr", "=", "1e-9", ",", "numItermax", "=", "500", ",", "verbose", "=", "False", ",", "log", "=", "False", ")", ":", "if", "reg_type", ".", "lower", "(", ")", "in", "[", "'l2'", ",", "'squaredl2'", "]", ":", "regul", "=", "SquaredL2", "(", "gamma", "=", "reg", ")", "elif", "reg_type", ".", "lower", "(", ")", "in", "[", "'entropic'", ",", "'negentropy'", ",", "'kl'", "]", ":", "regul", "=", "NegEntropy", "(", "gamma", "=", "reg", ")", "else", ":", "raise", "NotImplementedError", "(", "'Unknown regularization'", ")", "# solve dual", "alpha", ",", "res", "=", "solve_semi_dual", "(", "a", ",", "b", ",", "M", ",", "regul", ",", "max_iter", "=", "numItermax", ",", "tol", "=", "stopThr", ",", "verbose", "=", "verbose", ")", "# reconstruct transport matrix", "G", "=", "get_plan_from_semi_dual", "(", "alpha", ",", "b", ",", "M", ",", "regul", ")", "if", "log", ":", "log", "=", "{", "'alpha'", ":", "alpha", ",", "'res'", ":", "res", "}", "return", "G", ",", "log", "else", ":", "return", "G" ]
r""" Solve the regularized OT problem in the semi-dual and return the OT matrix The function solves the smooth relaxed dual formulation (10) in [17]_ : .. math:: \max_{\alpha}\quad a^T\alpha-OT_\Omega^*(\alpha,b) where : .. math:: OT_\Omega^*(\alpha,b)=\sum_j b_j - :math:`\mathbf{m}_j` is the jth column of the cost matrix - :math:`OT_\Omega^*(\alpha,b)` is defined in Eq. (9) in [17] - a and b are source and target weights (sum to 1) The OT matrix can is reconstructed using [17]_ Proposition 2. The optimization algorithm is using gradient decent (L-BFGS by default). Parameters ---------- a : np.ndarray (ns,) samples weights in the source domain b : np.ndarray (nt,) or np.ndarray (nt,nbb) samples in the target domain, compute sinkhorn with multiple targets and fixed M if b is a matrix (return OT loss + dual variables in log) M : np.ndarray (ns,nt) loss matrix reg : float Regularization term >0 reg_type : str Regularization type, can be the following (default ='l2'): - 'kl' : Kullback Leibler (~ Neg-entropy used in sinkhorn [2]_) - 'l2' : Squared Euclidean regularization method : str Solver to use for scipy.optimize.minimize numItermax : int, optional Max number of iterations stopThr : float, optional Stop threshol on error (>0) verbose : bool, optional Print information along iterations log : bool, optional record log if True Returns ------- gamma : (ns x nt) ndarray Optimal transportation matrix for the given parameters log : dict log dictionary return only if log==True in parameters References ---------- .. [2] M. Cuturi, Sinkhorn Distances : Lightspeed Computation of Optimal Transport, Advances in Neural Information Processing Systems (NIPS) 26, 2013 .. [17] Blondel, M., Seguy, V., & Rolet, A. (2018). Smooth and Sparse Optimal Transport. Proceedings of the Twenty-First International Conference on Artificial Intelligence and Statistics (AISTATS). See Also -------- ot.lp.emd : Unregularized OT ot.sinhorn : Entropic regularized OT ot.optim.cg : General regularized OT
[ "r", "Solve", "the", "regularized", "OT", "problem", "in", "the", "semi", "-", "dual", "and", "return", "the", "OT", "matrix" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/smooth.py#L510-L600
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", "=", "np", ".", "exp", "(", "-", "dist", "(", "x1", ",", "x2", ")", "/", "(", "2", "*", "sigma", "**", "2", ")", ")", "return", "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", ">", "0", "]", "b2", "=", "b", "[", "b", ">", "0", "]", "return", "a2", ",", "b2", ",", "M2" ]
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 None then x2=x1) metric : str, fun, optional name of the metric to be computed (full list in the doc of scipy), If a string, the distance function can be 'braycurtis', 'canberra', 'chebyshev', 'cityblock', 'correlation', 'cosine', 'dice', 'euclidean', 'hamming', 'jaccard', 'kulsinski', 'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'wminkowski', 'yule'. Returns ------- M : np.array (n1,n2) distance matrix computed with given metric """ if x2 is None: x2 = x1 if metric == "sqeuclidean": return euclidean_distances(x1, x2, squared=True) return cdist(x1, x2, metric=metric)
python
def dist(x1, x2=None, metric='sqeuclidean'): """Compute distance between samples in x1 and x2 using function scipy.spatial.distance.cdist Parameters ---------- x1 : np.array (n1,d) matrix with n1 samples of size d x2 : np.array (n2,d), optional matrix with n2 samples of size d (if None then x2=x1) metric : str, fun, optional name of the metric to be computed (full list in the doc of scipy), If a string, the distance function can be 'braycurtis', 'canberra', 'chebyshev', 'cityblock', 'correlation', 'cosine', 'dice', 'euclidean', 'hamming', 'jaccard', 'kulsinski', 'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'wminkowski', 'yule'. Returns ------- M : np.array (n1,n2) distance matrix computed with given metric """ if x2 is None: x2 = x1 if metric == "sqeuclidean": return euclidean_distances(x1, x2, squared=True) return cdist(x1, x2, metric=metric)
[ "def", "dist", "(", "x1", ",", "x2", "=", "None", ",", "metric", "=", "'sqeuclidean'", ")", ":", "if", "x2", "is", "None", ":", "x2", "=", "x1", "if", "metric", "==", "\"sqeuclidean\"", ":", "return", "euclidean_distances", "(", "x1", ",", "x2", ",", "squared", "=", "True", ")", "return", "cdist", "(", "x1", ",", "x2", ",", "metric", "=", "metric", ")" ]
Compute distance between samples in x1 and x2 using function scipy.spatial.distance.cdist Parameters ---------- x1 : np.array (n1,d) matrix with n1 samples of size d x2 : np.array (n2,d), optional matrix with n2 samples of size d (if None then x2=x1) metric : str, fun, optional name of the metric to be computed (full list in the doc of scipy), If a string, the distance function can be 'braycurtis', 'canberra', 'chebyshev', 'cityblock', 'correlation', 'cosine', 'dice', 'euclidean', 'hamming', 'jaccard', 'kulsinski', 'mahalanobis', 'matching', 'minkowski', 'rogerstanimoto', 'russellrao', 'seuclidean', 'sokalmichener', 'sokalsneath', 'sqeuclidean', 'wminkowski', 'yule'. Returns ------- M : np.array (n1,n2) distance matrix computed with given metric
[ "Compute", "distance", "between", "samples", "in", "x1", "and", "x2", "using", "function", "scipy", ".", "spatial", ".", "distance", ".", "cdist" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/utils.py#L108-L137
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 ------- C : np.array (n1, n2) The input cost matrix normalized according to given norm. """ if norm == "median": C /= float(np.median(C)) elif norm == "max": C /= float(np.max(C)) elif norm == "log": C = np.log(1 + C) elif norm == "loglog": C = np.log(1 + np.log(1 + C)) return C
python
def cost_normalization(C, norm=None): """ Apply normalization to the loss matrix Parameters ---------- C : np.array (n1, n2) The cost matrix to normalize. norm : str type of normalization from 'median','max','log','loglog'. Any other value do not normalize. Returns ------- C : np.array (n1, n2) The input cost matrix normalized according to given norm. """ if norm == "median": C /= float(np.median(C)) elif norm == "max": C /= float(np.max(C)) elif norm == "log": C = np.log(1 + C) elif norm == "loglog": C = np.log(1 + np.log(1 + C)) return C
[ "def", "cost_normalization", "(", "C", ",", "norm", "=", "None", ")", ":", "if", "norm", "==", "\"median\"", ":", "C", "/=", "float", "(", "np", ".", "median", "(", "C", ")", ")", "elif", "norm", "==", "\"max\"", ":", "C", "/=", "float", "(", "np", ".", "max", "(", "C", ")", ")", "elif", "norm", "==", "\"log\"", ":", "C", "=", "np", ".", "log", "(", "1", "+", "C", ")", "elif", "norm", "==", "\"loglog\"", ":", "C", "=", "np", ".", "log", "(", "1", "+", "np", ".", "log", "(", "1", "+", "C", ")", ")", "return", "C" ]
Apply normalization to the loss matrix Parameters ---------- C : np.array (n1, n2) The cost matrix to normalize. norm : str type of normalization from 'median','max','log','loglog'. Any other value do not normalize. Returns ------- C : np.array (n1, n2) The input cost matrix normalized according to given norm.
[ "Apply", "normalization", "to", "the", "loss", "matrix" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/utils.py#L169-L199
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 = True p.start() sent = [q_in.put((i, x)) for i, x in enumerate(X)] [q_in.put((None, None)) for _ in range(nprocs)] res = [q_out.get() for _ in range(len(sent))] [p.join() for p in proc] return [x for i, x in sorted(res)]
python
def parmap(f, X, nprocs=multiprocessing.cpu_count()): """ paralell map for multiprocessing """ q_in = multiprocessing.Queue(1) q_out = multiprocessing.Queue() proc = [multiprocessing.Process(target=fun, args=(f, q_in, q_out)) for _ in range(nprocs)] for p in proc: p.daemon = True p.start() sent = [q_in.put((i, x)) for i, x in enumerate(X)] [q_in.put((None, None)) for _ in range(nprocs)] res = [q_out.get() for _ in range(len(sent))] [p.join() for p in proc] return [x for i, x in sorted(res)]
[ "def", "parmap", "(", "f", ",", "X", ",", "nprocs", "=", "multiprocessing", ".", "cpu_count", "(", ")", ")", ":", "q_in", "=", "multiprocessing", ".", "Queue", "(", "1", ")", "q_out", "=", "multiprocessing", ".", "Queue", "(", ")", "proc", "=", "[", "multiprocessing", ".", "Process", "(", "target", "=", "fun", ",", "args", "=", "(", "f", ",", "q_in", ",", "q_out", ")", ")", "for", "_", "in", "range", "(", "nprocs", ")", "]", "for", "p", "in", "proc", ":", "p", ".", "daemon", "=", "True", "p", ".", "start", "(", ")", "sent", "=", "[", "q_in", ".", "put", "(", "(", "i", ",", "x", ")", ")", "for", "i", ",", "x", "in", "enumerate", "(", "X", ")", "]", "[", "q_in", ".", "put", "(", "(", "None", ",", "None", ")", ")", "for", "_", "in", "range", "(", "nprocs", ")", "]", "res", "=", "[", "q_out", ".", "get", "(", ")", "for", "_", "in", "range", "(", "len", "(", "sent", ")", ")", "]", "[", "p", ".", "join", "(", ")", "for", "p", "in", "proc", "]", "return", "[", "x", "for", "i", ",", "x", "in", "sorted", "(", "res", ")", "]" ]
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 None: closures = [] is_deprecated = ('deprecated' in ''.join([c.cell_contents for c in closures if isinstance(c.cell_contents, str)])) return is_deprecated
python
def _is_deprecated(func): """Helper to check if func is wraped by our deprecated decorator""" if sys.version_info < (3, 5): raise NotImplementedError("This is only available for python3.5 " "or above") closures = getattr(func, '__closure__', []) if closures is None: closures = [] is_deprecated = ('deprecated' in ''.join([c.cell_contents for c in closures if isinstance(c.cell_contents, str)])) return is_deprecated
[ "def", "_is_deprecated", "(", "func", ")", ":", "if", "sys", ".", "version_info", "<", "(", "3", ",", "5", ")", ":", "raise", "NotImplementedError", "(", "\"This is only available for python3.5 \"", "\"or above\"", ")", "closures", "=", "getattr", "(", "func", ",", "'__closure__'", ",", "[", "]", ")", "if", "closures", "is", "None", ":", "closures", "=", "[", "]", "is_deprecated", "=", "(", "'deprecated'", "in", "''", ".", "join", "(", "[", "c", ".", "cell_contents", "for", "c", "in", "closures", "if", "isinstance", "(", "c", ".", "cell_contents", ",", "str", ")", "]", ")", ")", "return", "is_deprecated" ]
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, **kwargs) wrapped.__name__ = fun.__name__ wrapped.__dict__ = fun.__dict__ wrapped.__doc__ = self._update_doc(fun.__doc__) return wrapped
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, **kwargs) wrapped.__name__ = fun.__name__ wrapped.__dict__ = fun.__dict__ wrapped.__doc__ = self._update_doc(fun.__doc__) return wrapped
[ "def", "_decorate_fun", "(", "self", ",", "fun", ")", ":", "msg", "=", "\"Function %s is deprecated\"", "%", "fun", ".", "__name__", "if", "self", ".", "extra", ":", "msg", "+=", "\"; %s\"", "%", "self", ".", "extra", "def", "wrapped", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "warnings", ".", "warn", "(", "msg", ",", "category", "=", "DeprecationWarning", ")", "return", "fun", "(", "*", "args", ",", "*", "*", "kwargs", ")", "wrapped", ".", "__name__", "=", "fun", ".", "__name__", "wrapped", ".", "__dict__", "=", "fun", ".", "__dict__", "wrapped", ".", "__doc__", "=", "self", ".", "_update_doc", "(", "fun", ".", "__doc__", ")", "return", "wrapped" ]
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 Regularization term >0 (ridge regularization) Returns ------- P : (d x p) ndarray Optimal transportation matrix for the given parameters proj : fun projection function including mean centering """ mx = np.mean(X) X -= mx.reshape((1, -1)) # data split between classes d = X.shape[1] xc = split_classes(X, y) nc = len(xc) p = min(nc - 1, p) Cw = 0 for x in xc: Cw += np.cov(x, rowvar=False) Cw /= nc mxc = np.zeros((d, nc)) for i in range(nc): mxc[:, i] = np.mean(xc[i]) mx0 = np.mean(mxc, 1) Cb = 0 for i in range(nc): Cb += (mxc[:, i] - mx0).reshape((-1, 1)) * \ (mxc[:, i] - mx0).reshape((1, -1)) w, V = linalg.eig(Cb, Cw + reg * np.eye(d)) idx = np.argsort(w.real) Popt = V[:, idx[-p:]] def proj(X): return (X - mx.reshape((1, -1))).dot(Popt) return Popt, proj
python
def fda(X, y, p=2, reg=1e-16): """ Fisher Discriminant Analysis Parameters ---------- X : numpy.ndarray (n,d) Training samples y : np.ndarray (n,) labels for training samples p : int, optional size of dimensionnality reduction reg : float, optional Regularization term >0 (ridge regularization) Returns ------- P : (d x p) ndarray Optimal transportation matrix for the given parameters proj : fun projection function including mean centering """ mx = np.mean(X) X -= mx.reshape((1, -1)) # data split between classes d = X.shape[1] xc = split_classes(X, y) nc = len(xc) p = min(nc - 1, p) Cw = 0 for x in xc: Cw += np.cov(x, rowvar=False) Cw /= nc mxc = np.zeros((d, nc)) for i in range(nc): mxc[:, i] = np.mean(xc[i]) mx0 = np.mean(mxc, 1) Cb = 0 for i in range(nc): Cb += (mxc[:, i] - mx0).reshape((-1, 1)) * \ (mxc[:, i] - mx0).reshape((1, -1)) w, V = linalg.eig(Cb, Cw + reg * np.eye(d)) idx = np.argsort(w.real) Popt = V[:, idx[-p:]] def proj(X): return (X - mx.reshape((1, -1))).dot(Popt) return Popt, proj
[ "def", "fda", "(", "X", ",", "y", ",", "p", "=", "2", ",", "reg", "=", "1e-16", ")", ":", "mx", "=", "np", ".", "mean", "(", "X", ")", "X", "-=", "mx", ".", "reshape", "(", "(", "1", ",", "-", "1", ")", ")", "# data split between classes", "d", "=", "X", ".", "shape", "[", "1", "]", "xc", "=", "split_classes", "(", "X", ",", "y", ")", "nc", "=", "len", "(", "xc", ")", "p", "=", "min", "(", "nc", "-", "1", ",", "p", ")", "Cw", "=", "0", "for", "x", "in", "xc", ":", "Cw", "+=", "np", ".", "cov", "(", "x", ",", "rowvar", "=", "False", ")", "Cw", "/=", "nc", "mxc", "=", "np", ".", "zeros", "(", "(", "d", ",", "nc", ")", ")", "for", "i", "in", "range", "(", "nc", ")", ":", "mxc", "[", ":", ",", "i", "]", "=", "np", ".", "mean", "(", "xc", "[", "i", "]", ")", "mx0", "=", "np", ".", "mean", "(", "mxc", ",", "1", ")", "Cb", "=", "0", "for", "i", "in", "range", "(", "nc", ")", ":", "Cb", "+=", "(", "mxc", "[", ":", ",", "i", "]", "-", "mx0", ")", ".", "reshape", "(", "(", "-", "1", ",", "1", ")", ")", "*", "(", "mxc", "[", ":", ",", "i", "]", "-", "mx0", ")", ".", "reshape", "(", "(", "1", ",", "-", "1", ")", ")", "w", ",", "V", "=", "linalg", ".", "eig", "(", "Cb", ",", "Cw", "+", "reg", "*", "np", ".", "eye", "(", "d", ")", ")", "idx", "=", "np", ".", "argsort", "(", "w", ".", "real", ")", "Popt", "=", "V", "[", ":", ",", "idx", "[", "-", "p", ":", "]", "]", "def", "proj", "(", "X", ")", ":", "return", "(", "X", "-", "mx", ".", "reshape", "(", "(", "1", ",", "-", "1", ")", ")", ")", ".", "dot", "(", "Popt", ")", "return", "Popt", ",", "proj" ]
Fisher Discriminant Analysis Parameters ---------- X : numpy.ndarray (n,d) Training samples y : np.ndarray (n,) labels for training samples p : int, optional size of dimensionnality reduction reg : float, optional Regularization term >0 (ridge regularization) Returns ------- P : (d x p) ndarray Optimal transportation matrix for the given parameters proj : fun projection function including mean centering
[ "Fisher", "Discriminant", "Analysis" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/dr.py#L45-L107
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\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1 = b \gamma \geq 0 Where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is the SAG algorithm as proposed in [18]_ [alg.1] Parameters ---------- a : np.ndarray(ns,), source measure b : np.ndarray(nt,), target measure M : np.ndarray(ns, nt), cost matrix reg : float number, Regularization term > 0 numItermax : int number number of iteration lr : float number learning rate Returns ------- v : np.ndarray(nt,) dual variable Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 300000 >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> method = "ASGD" >>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg, method, numItermax) >>> print(asgd_pi) References ---------- [Genevay et al., 2016] : Stochastic Optimization for Large-scale Optimal Transport, Advances in Neural Information Processing Systems (2016), arXiv preprint arxiv:1605.08527. ''' if lr is None: lr = 1. / max(a / reg) n_source = np.shape(M)[0] n_target = np.shape(M)[1] cur_beta = np.zeros(n_target) stored_gradient = np.zeros((n_source, n_target)) sum_stored_gradient = np.zeros(n_target) for _ in range(numItermax): i = np.random.randint(n_source) cur_coord_grad = a[i] * coordinate_grad_semi_dual(b, M, reg, cur_beta, i) sum_stored_gradient += (cur_coord_grad - stored_gradient[i]) stored_gradient[i] = cur_coord_grad cur_beta += lr * (1. / n_source) * sum_stored_gradient return cur_beta
python
def sag_entropic_transport(a, b, M, reg, numItermax=10000, lr=None): ''' Compute the SAG algorithm to solve the regularized discrete measures optimal transport max problem The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1 = b \gamma \geq 0 Where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is the SAG algorithm as proposed in [18]_ [alg.1] Parameters ---------- a : np.ndarray(ns,), source measure b : np.ndarray(nt,), target measure M : np.ndarray(ns, nt), cost matrix reg : float number, Regularization term > 0 numItermax : int number number of iteration lr : float number learning rate Returns ------- v : np.ndarray(nt,) dual variable Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 300000 >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> method = "ASGD" >>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg, method, numItermax) >>> print(asgd_pi) References ---------- [Genevay et al., 2016] : Stochastic Optimization for Large-scale Optimal Transport, Advances in Neural Information Processing Systems (2016), arXiv preprint arxiv:1605.08527. ''' if lr is None: lr = 1. / max(a / reg) n_source = np.shape(M)[0] n_target = np.shape(M)[1] cur_beta = np.zeros(n_target) stored_gradient = np.zeros((n_source, n_target)) sum_stored_gradient = np.zeros(n_target) for _ in range(numItermax): i = np.random.randint(n_source) cur_coord_grad = a[i] * coordinate_grad_semi_dual(b, M, reg, cur_beta, i) sum_stored_gradient += (cur_coord_grad - stored_gradient[i]) stored_gradient[i] = cur_coord_grad cur_beta += lr * (1. / n_source) * sum_stored_gradient return cur_beta
[ "def", "sag_entropic_transport", "(", "a", ",", "b", ",", "M", ",", "reg", ",", "numItermax", "=", "10000", ",", "lr", "=", "None", ")", ":", "if", "lr", "is", "None", ":", "lr", "=", "1.", "/", "max", "(", "a", "/", "reg", ")", "n_source", "=", "np", ".", "shape", "(", "M", ")", "[", "0", "]", "n_target", "=", "np", ".", "shape", "(", "M", ")", "[", "1", "]", "cur_beta", "=", "np", ".", "zeros", "(", "n_target", ")", "stored_gradient", "=", "np", ".", "zeros", "(", "(", "n_source", ",", "n_target", ")", ")", "sum_stored_gradient", "=", "np", ".", "zeros", "(", "n_target", ")", "for", "_", "in", "range", "(", "numItermax", ")", ":", "i", "=", "np", ".", "random", ".", "randint", "(", "n_source", ")", "cur_coord_grad", "=", "a", "[", "i", "]", "*", "coordinate_grad_semi_dual", "(", "b", ",", "M", ",", "reg", ",", "cur_beta", ",", "i", ")", "sum_stored_gradient", "+=", "(", "cur_coord_grad", "-", "stored_gradient", "[", "i", "]", ")", "stored_gradient", "[", "i", "]", "=", "cur_coord_grad", "cur_beta", "+=", "lr", "*", "(", "1.", "/", "n_source", ")", "*", "sum_stored_gradient", "return", "cur_beta" ]
Compute the SAG algorithm to solve the regularized discrete measures optimal transport max problem The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1 = b \gamma \geq 0 Where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is the SAG algorithm as proposed in [18]_ [alg.1] Parameters ---------- a : np.ndarray(ns,), source measure b : np.ndarray(nt,), target measure M : np.ndarray(ns, nt), cost matrix reg : float number, Regularization term > 0 numItermax : int number number of iteration lr : float number learning rate Returns ------- v : np.ndarray(nt,) dual variable Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 300000 >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> method = "ASGD" >>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg, method, numItermax) >>> print(asgd_pi) References ---------- [Genevay et al., 2016] : Stochastic Optimization for Large-scale Optimal Transport, Advances in Neural Information Processing Systems (2016), arXiv preprint arxiv:1605.08527.
[ "Compute", "the", "SAG", "algorithm", "to", "solve", "the", "regularized", "discrete", "measures", "optimal", "transport", "max", "problem" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/stochastic.py#L86-L175
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 + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma \geq 0 Where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is the ASGD algorithm as proposed in [18]_ [alg.2] Parameters ---------- b : np.ndarray(nt,) target measure M : np.ndarray(ns, nt) cost matrix reg : float number Regularization term > 0 numItermax : int number number of iteration lr : float number learning rate Returns ------- ave_v : np.ndarray(nt,) dual variable Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 300000 >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> method = "ASGD" >>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg, method, numItermax) >>> print(asgd_pi) References ---------- [Genevay et al., 2016] : Stochastic Optimization for Large-scale Optimal Transport, Advances in Neural Information Processing Systems (2016), arXiv preprint arxiv:1605.08527. ''' if lr is None: lr = 1. / max(a / reg) n_source = np.shape(M)[0] n_target = np.shape(M)[1] cur_beta = np.zeros(n_target) ave_beta = np.zeros(n_target) for cur_iter in range(numItermax): k = cur_iter + 1 i = np.random.randint(n_source) cur_coord_grad = coordinate_grad_semi_dual(b, M, reg, cur_beta, i) cur_beta += (lr / np.sqrt(k)) * cur_coord_grad ave_beta = (1. / k) * cur_beta + (1 - 1. / k) * ave_beta return ave_beta
python
def averaged_sgd_entropic_transport(a, b, M, reg, numItermax=300000, lr=None): ''' Compute the ASGD algorithm to solve the regularized semi continous measures optimal transport max problem The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma \geq 0 Where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is the ASGD algorithm as proposed in [18]_ [alg.2] Parameters ---------- b : np.ndarray(nt,) target measure M : np.ndarray(ns, nt) cost matrix reg : float number Regularization term > 0 numItermax : int number number of iteration lr : float number learning rate Returns ------- ave_v : np.ndarray(nt,) dual variable Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 300000 >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> method = "ASGD" >>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg, method, numItermax) >>> print(asgd_pi) References ---------- [Genevay et al., 2016] : Stochastic Optimization for Large-scale Optimal Transport, Advances in Neural Information Processing Systems (2016), arXiv preprint arxiv:1605.08527. ''' if lr is None: lr = 1. / max(a / reg) n_source = np.shape(M)[0] n_target = np.shape(M)[1] cur_beta = np.zeros(n_target) ave_beta = np.zeros(n_target) for cur_iter in range(numItermax): k = cur_iter + 1 i = np.random.randint(n_source) cur_coord_grad = coordinate_grad_semi_dual(b, M, reg, cur_beta, i) cur_beta += (lr / np.sqrt(k)) * cur_coord_grad ave_beta = (1. / k) * cur_beta + (1 - 1. / k) * ave_beta return ave_beta
[ "def", "averaged_sgd_entropic_transport", "(", "a", ",", "b", ",", "M", ",", "reg", ",", "numItermax", "=", "300000", ",", "lr", "=", "None", ")", ":", "if", "lr", "is", "None", ":", "lr", "=", "1.", "/", "max", "(", "a", "/", "reg", ")", "n_source", "=", "np", ".", "shape", "(", "M", ")", "[", "0", "]", "n_target", "=", "np", ".", "shape", "(", "M", ")", "[", "1", "]", "cur_beta", "=", "np", ".", "zeros", "(", "n_target", ")", "ave_beta", "=", "np", ".", "zeros", "(", "n_target", ")", "for", "cur_iter", "in", "range", "(", "numItermax", ")", ":", "k", "=", "cur_iter", "+", "1", "i", "=", "np", ".", "random", ".", "randint", "(", "n_source", ")", "cur_coord_grad", "=", "coordinate_grad_semi_dual", "(", "b", ",", "M", ",", "reg", ",", "cur_beta", ",", "i", ")", "cur_beta", "+=", "(", "lr", "/", "np", ".", "sqrt", "(", "k", ")", ")", "*", "cur_coord_grad", "ave_beta", "=", "(", "1.", "/", "k", ")", "*", "cur_beta", "+", "(", "1", "-", "1.", "/", "k", ")", "*", "ave_beta", "return", "ave_beta" ]
Compute the ASGD algorithm to solve the regularized semi continous measures optimal transport max problem The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma \geq 0 Where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is the ASGD algorithm as proposed in [18]_ [alg.2] Parameters ---------- b : np.ndarray(nt,) target measure M : np.ndarray(ns, nt) cost matrix reg : float number Regularization term > 0 numItermax : int number number of iteration lr : float number learning rate Returns ------- ave_v : np.ndarray(nt,) dual variable Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 300000 >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> method = "ASGD" >>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg, method, numItermax) >>> print(asgd_pi) References ---------- [Genevay et al., 2016] : Stochastic Optimization for Large-scale Optimal Transport, Advances in Neural Information Processing Systems (2016), arXiv preprint arxiv:1605.08527.
[ "Compute", "the", "ASGD", "algorithm", "to", "solve", "the", "regularized", "semi", "continous", "measures", "optimal", "transport", "max", "problem" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/stochastic.py#L178-L263
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 matrix - u, v are dual variables in R^IxR^J - reg is the regularization term It is used to recover an optimal u from optimal v solving the semi dual problem, see Proposition 2.1 of [18]_ Parameters ---------- b : np.ndarray(nt,) target measure M : np.ndarray(ns, nt) cost matrix reg : float regularization term > 0 v : np.ndarray(nt,) dual variable Returns ------- u : np.ndarray(ns,) dual variable Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 300000 >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> method = "ASGD" >>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg, method, numItermax) >>> print(asgd_pi) References ---------- [Genevay et al., 2016] : Stochastic Optimization for Large-scale Optimal Transport, Advances in Neural Information Processing Systems (2016), arXiv preprint arxiv:1605.08527. ''' n_source = np.shape(M)[0] alpha = np.zeros(n_source) for i in range(n_source): r = M[i, :] - beta min_r = np.min(r) exp_beta = np.exp(-(r - min_r) / reg) * b alpha[i] = min_r - reg * np.log(np.sum(exp_beta)) return alpha
python
def c_transform_entropic(b, M, reg, beta): ''' The goal is to recover u from the c-transform. The function computes the c_transform of a dual variable from the other dual variable: .. math:: u = v^{c,reg} = -reg \sum_j exp((v - M)/reg) b_j Where : - M is the (ns,nt) metric cost matrix - u, v are dual variables in R^IxR^J - reg is the regularization term It is used to recover an optimal u from optimal v solving the semi dual problem, see Proposition 2.1 of [18]_ Parameters ---------- b : np.ndarray(nt,) target measure M : np.ndarray(ns, nt) cost matrix reg : float regularization term > 0 v : np.ndarray(nt,) dual variable Returns ------- u : np.ndarray(ns,) dual variable Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 300000 >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> method = "ASGD" >>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg, method, numItermax) >>> print(asgd_pi) References ---------- [Genevay et al., 2016] : Stochastic Optimization for Large-scale Optimal Transport, Advances in Neural Information Processing Systems (2016), arXiv preprint arxiv:1605.08527. ''' n_source = np.shape(M)[0] alpha = np.zeros(n_source) for i in range(n_source): r = M[i, :] - beta min_r = np.min(r) exp_beta = np.exp(-(r - min_r) / reg) * b alpha[i] = min_r - reg * np.log(np.sum(exp_beta)) return alpha
[ "def", "c_transform_entropic", "(", "b", ",", "M", ",", "reg", ",", "beta", ")", ":", "n_source", "=", "np", ".", "shape", "(", "M", ")", "[", "0", "]", "alpha", "=", "np", ".", "zeros", "(", "n_source", ")", "for", "i", "in", "range", "(", "n_source", ")", ":", "r", "=", "M", "[", "i", ",", ":", "]", "-", "beta", "min_r", "=", "np", ".", "min", "(", "r", ")", "exp_beta", "=", "np", ".", "exp", "(", "-", "(", "r", "-", "min_r", ")", "/", "reg", ")", "*", "b", "alpha", "[", "i", "]", "=", "min_r", "-", "reg", "*", "np", ".", "log", "(", "np", ".", "sum", "(", "exp_beta", ")", ")", "return", "alpha" ]
The goal is to recover u from the c-transform. The function computes the c_transform of a dual variable from the other dual variable: .. math:: u = v^{c,reg} = -reg \sum_j exp((v - M)/reg) b_j Where : - M is the (ns,nt) metric cost matrix - u, v are dual variables in R^IxR^J - reg is the regularization term It is used to recover an optimal u from optimal v solving the semi dual problem, see Proposition 2.1 of [18]_ Parameters ---------- b : np.ndarray(nt,) target measure M : np.ndarray(ns, nt) cost matrix reg : float regularization term > 0 v : np.ndarray(nt,) dual variable Returns ------- u : np.ndarray(ns,) dual variable Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 300000 >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> method = "ASGD" >>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg, method, numItermax) >>> print(asgd_pi) References ---------- [Genevay et al., 2016] : Stochastic Optimization for Large-scale Optimal Transport, Advances in Neural Information Processing Systems (2016), arXiv preprint arxiv:1605.08527.
[ "The", "goal", "is", "to", "recover", "u", "from", "the", "c", "-", "transform", "." ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/stochastic.py#L266-L338
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: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma \geq 0 Where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is the SAG or ASGD algorithms as proposed in [18]_ Parameters ---------- a : np.ndarray(ns,) source measure b : np.ndarray(nt,) target measure M : np.ndarray(ns, nt) cost matrix reg : float number Regularization term > 0 methode : str used method (SAG or ASGD) numItermax : int number number of iteration lr : float number learning rate n_source : int number size of the source measure n_target : int number size of the target measure log : bool, optional record log if True Returns ------- pi : np.ndarray(ns, nt) transportation matrix log : dict log dictionary return only if log==True in parameters Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 300000 >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> method = "ASGD" >>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg, method, numItermax) >>> print(asgd_pi) References ---------- [Genevay et al., 2016] : Stochastic Optimization for Large-scale Optimal Transport, Advances in Neural Information Processing Systems (2016), arXiv preprint arxiv:1605.08527. ''' if method.lower() == "sag": opt_beta = sag_entropic_transport(a, b, M, reg, numItermax, lr) elif method.lower() == "asgd": opt_beta = averaged_sgd_entropic_transport(a, b, M, reg, numItermax, lr) else: print("Please, select your method between SAG and ASGD") return None opt_alpha = c_transform_entropic(b, M, reg, opt_beta) pi = (np.exp((opt_alpha[:, None] + opt_beta[None, :] - M[:, :]) / reg) * a[:, None] * b[None, :]) if log: log = {} log['alpha'] = opt_alpha log['beta'] = opt_beta return pi, log else: return pi
python
def solve_semi_dual_entropic(a, b, M, reg, method, numItermax=10000, lr=None, log=False): ''' Compute the transportation matrix to solve the regularized discrete measures optimal transport max problem The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma \geq 0 Where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is the SAG or ASGD algorithms as proposed in [18]_ Parameters ---------- a : np.ndarray(ns,) source measure b : np.ndarray(nt,) target measure M : np.ndarray(ns, nt) cost matrix reg : float number Regularization term > 0 methode : str used method (SAG or ASGD) numItermax : int number number of iteration lr : float number learning rate n_source : int number size of the source measure n_target : int number size of the target measure log : bool, optional record log if True Returns ------- pi : np.ndarray(ns, nt) transportation matrix log : dict log dictionary return only if log==True in parameters Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 300000 >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> method = "ASGD" >>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg, method, numItermax) >>> print(asgd_pi) References ---------- [Genevay et al., 2016] : Stochastic Optimization for Large-scale Optimal Transport, Advances in Neural Information Processing Systems (2016), arXiv preprint arxiv:1605.08527. ''' if method.lower() == "sag": opt_beta = sag_entropic_transport(a, b, M, reg, numItermax, lr) elif method.lower() == "asgd": opt_beta = averaged_sgd_entropic_transport(a, b, M, reg, numItermax, lr) else: print("Please, select your method between SAG and ASGD") return None opt_alpha = c_transform_entropic(b, M, reg, opt_beta) pi = (np.exp((opt_alpha[:, None] + opt_beta[None, :] - M[:, :]) / reg) * a[:, None] * b[None, :]) if log: log = {} log['alpha'] = opt_alpha log['beta'] = opt_beta return pi, log else: return pi
[ "def", "solve_semi_dual_entropic", "(", "a", ",", "b", ",", "M", ",", "reg", ",", "method", ",", "numItermax", "=", "10000", ",", "lr", "=", "None", ",", "log", "=", "False", ")", ":", "if", "method", ".", "lower", "(", ")", "==", "\"sag\"", ":", "opt_beta", "=", "sag_entropic_transport", "(", "a", ",", "b", ",", "M", ",", "reg", ",", "numItermax", ",", "lr", ")", "elif", "method", ".", "lower", "(", ")", "==", "\"asgd\"", ":", "opt_beta", "=", "averaged_sgd_entropic_transport", "(", "a", ",", "b", ",", "M", ",", "reg", ",", "numItermax", ",", "lr", ")", "else", ":", "print", "(", "\"Please, select your method between SAG and ASGD\"", ")", "return", "None", "opt_alpha", "=", "c_transform_entropic", "(", "b", ",", "M", ",", "reg", ",", "opt_beta", ")", "pi", "=", "(", "np", ".", "exp", "(", "(", "opt_alpha", "[", ":", ",", "None", "]", "+", "opt_beta", "[", "None", ",", ":", "]", "-", "M", "[", ":", ",", ":", "]", ")", "/", "reg", ")", "*", "a", "[", ":", ",", "None", "]", "*", "b", "[", "None", ",", ":", "]", ")", "if", "log", ":", "log", "=", "{", "}", "log", "[", "'alpha'", "]", "=", "opt_alpha", "log", "[", "'beta'", "]", "=", "opt_beta", "return", "pi", ",", "log", "else", ":", "return", "pi" ]
Compute the transportation matrix to solve the regularized discrete measures optimal transport max problem The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma \geq 0 Where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - a and b are source and target weights (sum to 1) The algorithm used for solving the problem is the SAG or ASGD algorithms as proposed in [18]_ Parameters ---------- a : np.ndarray(ns,) source measure b : np.ndarray(nt,) target measure M : np.ndarray(ns, nt) cost matrix reg : float number Regularization term > 0 methode : str used method (SAG or ASGD) numItermax : int number number of iteration lr : float number learning rate n_source : int number size of the source measure n_target : int number size of the target measure log : bool, optional record log if True Returns ------- pi : np.ndarray(ns, nt) transportation matrix log : dict log dictionary return only if log==True in parameters Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 300000 >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> method = "ASGD" >>> asgd_pi = stochastic.solve_semi_dual_entropic(a, b, M, reg, method, numItermax) >>> print(asgd_pi) References ---------- [Genevay et al., 2016] : Stochastic Optimization for Large-scale Optimal Transport, Advances in Neural Information Processing Systems (2016), arXiv preprint arxiv:1605.08527.
[ "Compute", "the", "transportation", "matrix", "to", "solve", "the", "regularized", "discrete", "measures", "optimal", "transport", "max", "problem" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/stochastic.py#L341-L444
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} - \sum_{j \in B_v} exp((u_i + v_j - M_{i,j})/reg) * a_i * b_j \partial_{v_j} F = v_j * b_s/l_{u} - \sum_{i \in B_u} exp((u_i + v_j - M_{i,j})/reg) * a_i * b_j Where : - M is the (ns,nt) metric cost matrix - u, v are dual variables in R^ixR^J - reg is the regularization term - :math:`B_u` and :math:`B_v` are lists of index - :math:`b_s` is the size of the batchs :math:`B_u` and :math:`B_v` - :math:`l_u` and :math:`l_v` are the lenghts of :math:`B_u` and :math:`B_v` - a and b are source and target weights (sum to 1) The algorithm used for solving the dual problem is the SGD algorithm as proposed in [19]_ [alg.1] Parameters ---------- a : np.ndarray(ns,) source measure b : np.ndarray(nt,) target measure M : np.ndarray(ns, nt) cost matrix reg : float number Regularization term > 0 alpha : np.ndarray(ns,) dual variable beta : np.ndarray(nt,) dual variable batch_size : int number size of the batch batch_alpha : np.ndarray(bs,) batch of index of alpha batch_beta : np.ndarray(bs,) batch of index of beta Returns ------- grad : np.ndarray(ns,) partial grad F Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 20000 >>> lr = 0.1 >>> batch_size = 3 >>> log = True >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> sgd_dual_pi, log = stochastic.solve_dual_entropic(a, b, M, reg, batch_size, numItermax, lr, log) >>> print(log['alpha'], log['beta']) >>> print(sgd_dual_pi) References ---------- [Seguy et al., 2018] : International Conference on Learning Representation (2018), arXiv preprint arxiv:1711.02283. ''' G = - (np.exp((alpha[batch_alpha, None] + beta[None, batch_beta] - M[batch_alpha, :][:, batch_beta]) / reg) * a[batch_alpha, None] * b[None, batch_beta]) grad_beta = np.zeros(np.shape(M)[1]) grad_alpha = np.zeros(np.shape(M)[0]) grad_beta[batch_beta] = (b[batch_beta] * len(batch_alpha) / np.shape(M)[0] + G.sum(0)) grad_alpha[batch_alpha] = (a[batch_alpha] * len(batch_beta) / np.shape(M)[1] + G.sum(1)) return grad_alpha, grad_beta
python
def batch_grad_dual(a, b, M, reg, alpha, beta, batch_size, batch_alpha, batch_beta): ''' Computes the partial gradient of the dual optimal transport problem. For each (i,j) in a batch of coordinates, the partial gradients are : .. math:: \partial_{u_i} F = u_i * b_s/l_{v} - \sum_{j \in B_v} exp((u_i + v_j - M_{i,j})/reg) * a_i * b_j \partial_{v_j} F = v_j * b_s/l_{u} - \sum_{i \in B_u} exp((u_i + v_j - M_{i,j})/reg) * a_i * b_j Where : - M is the (ns,nt) metric cost matrix - u, v are dual variables in R^ixR^J - reg is the regularization term - :math:`B_u` and :math:`B_v` are lists of index - :math:`b_s` is the size of the batchs :math:`B_u` and :math:`B_v` - :math:`l_u` and :math:`l_v` are the lenghts of :math:`B_u` and :math:`B_v` - a and b are source and target weights (sum to 1) The algorithm used for solving the dual problem is the SGD algorithm as proposed in [19]_ [alg.1] Parameters ---------- a : np.ndarray(ns,) source measure b : np.ndarray(nt,) target measure M : np.ndarray(ns, nt) cost matrix reg : float number Regularization term > 0 alpha : np.ndarray(ns,) dual variable beta : np.ndarray(nt,) dual variable batch_size : int number size of the batch batch_alpha : np.ndarray(bs,) batch of index of alpha batch_beta : np.ndarray(bs,) batch of index of beta Returns ------- grad : np.ndarray(ns,) partial grad F Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 20000 >>> lr = 0.1 >>> batch_size = 3 >>> log = True >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> sgd_dual_pi, log = stochastic.solve_dual_entropic(a, b, M, reg, batch_size, numItermax, lr, log) >>> print(log['alpha'], log['beta']) >>> print(sgd_dual_pi) References ---------- [Seguy et al., 2018] : International Conference on Learning Representation (2018), arXiv preprint arxiv:1711.02283. ''' G = - (np.exp((alpha[batch_alpha, None] + beta[None, batch_beta] - M[batch_alpha, :][:, batch_beta]) / reg) * a[batch_alpha, None] * b[None, batch_beta]) grad_beta = np.zeros(np.shape(M)[1]) grad_alpha = np.zeros(np.shape(M)[0]) grad_beta[batch_beta] = (b[batch_beta] * len(batch_alpha) / np.shape(M)[0] + G.sum(0)) grad_alpha[batch_alpha] = (a[batch_alpha] * len(batch_beta) / np.shape(M)[1] + G.sum(1)) return grad_alpha, grad_beta
[ "def", "batch_grad_dual", "(", "a", ",", "b", ",", "M", ",", "reg", ",", "alpha", ",", "beta", ",", "batch_size", ",", "batch_alpha", ",", "batch_beta", ")", ":", "G", "=", "-", "(", "np", ".", "exp", "(", "(", "alpha", "[", "batch_alpha", ",", "None", "]", "+", "beta", "[", "None", ",", "batch_beta", "]", "-", "M", "[", "batch_alpha", ",", ":", "]", "[", ":", ",", "batch_beta", "]", ")", "/", "reg", ")", "*", "a", "[", "batch_alpha", ",", "None", "]", "*", "b", "[", "None", ",", "batch_beta", "]", ")", "grad_beta", "=", "np", ".", "zeros", "(", "np", ".", "shape", "(", "M", ")", "[", "1", "]", ")", "grad_alpha", "=", "np", ".", "zeros", "(", "np", ".", "shape", "(", "M", ")", "[", "0", "]", ")", "grad_beta", "[", "batch_beta", "]", "=", "(", "b", "[", "batch_beta", "]", "*", "len", "(", "batch_alpha", ")", "/", "np", ".", "shape", "(", "M", ")", "[", "0", "]", "+", "G", ".", "sum", "(", "0", ")", ")", "grad_alpha", "[", "batch_alpha", "]", "=", "(", "a", "[", "batch_alpha", "]", "*", "len", "(", "batch_beta", ")", "/", "np", ".", "shape", "(", "M", ")", "[", "1", "]", "+", "G", ".", "sum", "(", "1", ")", ")", "return", "grad_alpha", ",", "grad_beta" ]
Computes the partial gradient of the dual optimal transport problem. For each (i,j) in a batch of coordinates, the partial gradients are : .. math:: \partial_{u_i} F = u_i * b_s/l_{v} - \sum_{j \in B_v} exp((u_i + v_j - M_{i,j})/reg) * a_i * b_j \partial_{v_j} F = v_j * b_s/l_{u} - \sum_{i \in B_u} exp((u_i + v_j - M_{i,j})/reg) * a_i * b_j Where : - M is the (ns,nt) metric cost matrix - u, v are dual variables in R^ixR^J - reg is the regularization term - :math:`B_u` and :math:`B_v` are lists of index - :math:`b_s` is the size of the batchs :math:`B_u` and :math:`B_v` - :math:`l_u` and :math:`l_v` are the lenghts of :math:`B_u` and :math:`B_v` - a and b are source and target weights (sum to 1) The algorithm used for solving the dual problem is the SGD algorithm as proposed in [19]_ [alg.1] Parameters ---------- a : np.ndarray(ns,) source measure b : np.ndarray(nt,) target measure M : np.ndarray(ns, nt) cost matrix reg : float number Regularization term > 0 alpha : np.ndarray(ns,) dual variable beta : np.ndarray(nt,) dual variable batch_size : int number size of the batch batch_alpha : np.ndarray(bs,) batch of index of alpha batch_beta : np.ndarray(bs,) batch of index of beta Returns ------- grad : np.ndarray(ns,) partial grad F Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 20000 >>> lr = 0.1 >>> batch_size = 3 >>> log = True >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> sgd_dual_pi, log = stochastic.solve_dual_entropic(a, b, M, reg, batch_size, numItermax, lr, log) >>> print(log['alpha'], log['beta']) >>> print(sgd_dual_pi) References ---------- [Seguy et al., 2018] : International Conference on Learning Representation (2018), arXiv preprint arxiv:1711.02283.
[ "Computes", "the", "partial", "gradient", "of", "the", "dual", "optimal", "transport", "problem", "." ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/stochastic.py#L452-L547
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 + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma \geq 0 Where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - a and b are source and target weights (sum to 1) Parameters ---------- a : np.ndarray(ns,) source measure b : np.ndarray(nt,) target measure M : np.ndarray(ns, nt) cost matrix reg : float number Regularization term > 0 batch_size : int number size of the batch numItermax : int number number of iteration lr : float number learning rate Returns ------- alpha : np.ndarray(ns,) dual variable beta : np.ndarray(nt,) dual variable Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 20000 >>> lr = 0.1 >>> batch_size = 3 >>> log = True >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> sgd_dual_pi, log = stochastic.solve_dual_entropic(a, b, M, reg, batch_size, numItermax, lr, log) >>> print(log['alpha'], log['beta']) >>> print(sgd_dual_pi) References ---------- [Seguy et al., 2018] : International Conference on Learning Representation (2018), arXiv preprint arxiv:1711.02283. ''' n_source = np.shape(M)[0] n_target = np.shape(M)[1] cur_alpha = np.zeros(n_source) cur_beta = np.zeros(n_target) for cur_iter in range(numItermax): k = np.sqrt(cur_iter + 1) batch_alpha = np.random.choice(n_source, batch_size, replace=False) batch_beta = np.random.choice(n_target, batch_size, replace=False) update_alpha, update_beta = batch_grad_dual(a, b, M, reg, cur_alpha, cur_beta, batch_size, batch_alpha, batch_beta) cur_alpha[batch_alpha] += (lr / k) * update_alpha[batch_alpha] cur_beta[batch_beta] += (lr / k) * update_beta[batch_beta] return cur_alpha, cur_beta
python
def sgd_entropic_regularization(a, b, M, reg, batch_size, numItermax, lr): ''' Compute the sgd algorithm to solve the regularized discrete measures optimal transport dual problem The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma \geq 0 Where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - a and b are source and target weights (sum to 1) Parameters ---------- a : np.ndarray(ns,) source measure b : np.ndarray(nt,) target measure M : np.ndarray(ns, nt) cost matrix reg : float number Regularization term > 0 batch_size : int number size of the batch numItermax : int number number of iteration lr : float number learning rate Returns ------- alpha : np.ndarray(ns,) dual variable beta : np.ndarray(nt,) dual variable Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 20000 >>> lr = 0.1 >>> batch_size = 3 >>> log = True >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> sgd_dual_pi, log = stochastic.solve_dual_entropic(a, b, M, reg, batch_size, numItermax, lr, log) >>> print(log['alpha'], log['beta']) >>> print(sgd_dual_pi) References ---------- [Seguy et al., 2018] : International Conference on Learning Representation (2018), arXiv preprint arxiv:1711.02283. ''' n_source = np.shape(M)[0] n_target = np.shape(M)[1] cur_alpha = np.zeros(n_source) cur_beta = np.zeros(n_target) for cur_iter in range(numItermax): k = np.sqrt(cur_iter + 1) batch_alpha = np.random.choice(n_source, batch_size, replace=False) batch_beta = np.random.choice(n_target, batch_size, replace=False) update_alpha, update_beta = batch_grad_dual(a, b, M, reg, cur_alpha, cur_beta, batch_size, batch_alpha, batch_beta) cur_alpha[batch_alpha] += (lr / k) * update_alpha[batch_alpha] cur_beta[batch_beta] += (lr / k) * update_beta[batch_beta] return cur_alpha, cur_beta
[ "def", "sgd_entropic_regularization", "(", "a", ",", "b", ",", "M", ",", "reg", ",", "batch_size", ",", "numItermax", ",", "lr", ")", ":", "n_source", "=", "np", ".", "shape", "(", "M", ")", "[", "0", "]", "n_target", "=", "np", ".", "shape", "(", "M", ")", "[", "1", "]", "cur_alpha", "=", "np", ".", "zeros", "(", "n_source", ")", "cur_beta", "=", "np", ".", "zeros", "(", "n_target", ")", "for", "cur_iter", "in", "range", "(", "numItermax", ")", ":", "k", "=", "np", ".", "sqrt", "(", "cur_iter", "+", "1", ")", "batch_alpha", "=", "np", ".", "random", ".", "choice", "(", "n_source", ",", "batch_size", ",", "replace", "=", "False", ")", "batch_beta", "=", "np", ".", "random", ".", "choice", "(", "n_target", ",", "batch_size", ",", "replace", "=", "False", ")", "update_alpha", ",", "update_beta", "=", "batch_grad_dual", "(", "a", ",", "b", ",", "M", ",", "reg", ",", "cur_alpha", ",", "cur_beta", ",", "batch_size", ",", "batch_alpha", ",", "batch_beta", ")", "cur_alpha", "[", "batch_alpha", "]", "+=", "(", "lr", "/", "k", ")", "*", "update_alpha", "[", "batch_alpha", "]", "cur_beta", "[", "batch_beta", "]", "+=", "(", "lr", "/", "k", ")", "*", "update_beta", "[", "batch_beta", "]", "return", "cur_alpha", ",", "cur_beta" ]
Compute the sgd algorithm to solve the regularized discrete measures optimal transport dual problem The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma \geq 0 Where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term with :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - a and b are source and target weights (sum to 1) Parameters ---------- a : np.ndarray(ns,) source measure b : np.ndarray(nt,) target measure M : np.ndarray(ns, nt) cost matrix reg : float number Regularization term > 0 batch_size : int number size of the batch numItermax : int number number of iteration lr : float number learning rate Returns ------- alpha : np.ndarray(ns,) dual variable beta : np.ndarray(nt,) dual variable Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 20000 >>> lr = 0.1 >>> batch_size = 3 >>> log = True >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> sgd_dual_pi, log = stochastic.solve_dual_entropic(a, b, M, reg, batch_size, numItermax, lr, log) >>> print(log['alpha'], log['beta']) >>> print(sgd_dual_pi) References ---------- [Seguy et al., 2018] : International Conference on Learning Representation (2018), arXiv preprint arxiv:1711.02283.
[ "Compute", "the", "sgd", "algorithm", "to", "solve", "the", "regularized", "discrete", "measures", "optimal", "transport", "dual", "problem" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/stochastic.py#L550-L642
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:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma \geq 0 Where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - a and b are source and target weights (sum to 1) Parameters ---------- a : np.ndarray(ns,) source measure b : np.ndarray(nt,) target measure M : np.ndarray(ns, nt) cost matrix reg : float number Regularization term > 0 batch_size : int number size of the batch numItermax : int number number of iteration lr : float number learning rate log : bool, optional record log if True Returns ------- pi : np.ndarray(ns, nt) transportation matrix log : dict log dictionary return only if log==True in parameters Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 20000 >>> lr = 0.1 >>> batch_size = 3 >>> log = True >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> sgd_dual_pi, log = stochastic.solve_dual_entropic(a, b, M, reg, batch_size, numItermax, lr, log) >>> print(log['alpha'], log['beta']) >>> print(sgd_dual_pi) References ---------- [Seguy et al., 2018] : International Conference on Learning Representation (2018), arXiv preprint arxiv:1711.02283. ''' opt_alpha, opt_beta = sgd_entropic_regularization(a, b, M, reg, batch_size, numItermax, lr) pi = (np.exp((opt_alpha[:, None] + opt_beta[None, :] - M[:, :]) / reg) * a[:, None] * b[None, :]) if log: log = {} log['alpha'] = opt_alpha log['beta'] = opt_beta return pi, log else: return pi
python
def solve_dual_entropic(a, b, M, reg, batch_size, numItermax=10000, lr=1, log=False): ''' Compute the transportation matrix to solve the regularized discrete measures optimal transport dual problem The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma \geq 0 Where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - a and b are source and target weights (sum to 1) Parameters ---------- a : np.ndarray(ns,) source measure b : np.ndarray(nt,) target measure M : np.ndarray(ns, nt) cost matrix reg : float number Regularization term > 0 batch_size : int number size of the batch numItermax : int number number of iteration lr : float number learning rate log : bool, optional record log if True Returns ------- pi : np.ndarray(ns, nt) transportation matrix log : dict log dictionary return only if log==True in parameters Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 20000 >>> lr = 0.1 >>> batch_size = 3 >>> log = True >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> sgd_dual_pi, log = stochastic.solve_dual_entropic(a, b, M, reg, batch_size, numItermax, lr, log) >>> print(log['alpha'], log['beta']) >>> print(sgd_dual_pi) References ---------- [Seguy et al., 2018] : International Conference on Learning Representation (2018), arXiv preprint arxiv:1711.02283. ''' opt_alpha, opt_beta = sgd_entropic_regularization(a, b, M, reg, batch_size, numItermax, lr) pi = (np.exp((opt_alpha[:, None] + opt_beta[None, :] - M[:, :]) / reg) * a[:, None] * b[None, :]) if log: log = {} log['alpha'] = opt_alpha log['beta'] = opt_beta return pi, log else: return pi
[ "def", "solve_dual_entropic", "(", "a", ",", "b", ",", "M", ",", "reg", ",", "batch_size", ",", "numItermax", "=", "10000", ",", "lr", "=", "1", ",", "log", "=", "False", ")", ":", "opt_alpha", ",", "opt_beta", "=", "sgd_entropic_regularization", "(", "a", ",", "b", ",", "M", ",", "reg", ",", "batch_size", ",", "numItermax", ",", "lr", ")", "pi", "=", "(", "np", ".", "exp", "(", "(", "opt_alpha", "[", ":", ",", "None", "]", "+", "opt_beta", "[", "None", ",", ":", "]", "-", "M", "[", ":", ",", ":", "]", ")", "/", "reg", ")", "*", "a", "[", ":", ",", "None", "]", "*", "b", "[", "None", ",", ":", "]", ")", "if", "log", ":", "log", "=", "{", "}", "log", "[", "'alpha'", "]", "=", "opt_alpha", "log", "[", "'beta'", "]", "=", "opt_beta", "return", "pi", ",", "log", "else", ":", "return", "pi" ]
Compute the transportation matrix to solve the regularized discrete measures optimal transport dual problem The function solves the following optimization problem: .. math:: \gamma = arg\min_\gamma <\gamma,M>_F + reg\cdot\Omega(\gamma) s.t. \gamma 1 = a \gamma^T 1= b \gamma \geq 0 Where : - M is the (ns,nt) metric cost matrix - :math:`\Omega` is the entropic regularization term :math:`\Omega(\gamma)=\sum_{i,j} \gamma_{i,j}\log(\gamma_{i,j})` - a and b are source and target weights (sum to 1) Parameters ---------- a : np.ndarray(ns,) source measure b : np.ndarray(nt,) target measure M : np.ndarray(ns, nt) cost matrix reg : float number Regularization term > 0 batch_size : int number size of the batch numItermax : int number number of iteration lr : float number learning rate log : bool, optional record log if True Returns ------- pi : np.ndarray(ns, nt) transportation matrix log : dict log dictionary return only if log==True in parameters Examples -------- >>> n_source = 7 >>> n_target = 4 >>> reg = 1 >>> numItermax = 20000 >>> lr = 0.1 >>> batch_size = 3 >>> log = True >>> a = ot.utils.unif(n_source) >>> b = ot.utils.unif(n_target) >>> rng = np.random.RandomState(0) >>> X_source = rng.randn(n_source, 2) >>> Y_target = rng.randn(n_target, 2) >>> M = ot.dist(X_source, Y_target) >>> sgd_dual_pi, log = stochastic.solve_dual_entropic(a, b, M, reg, batch_size, numItermax, lr, log) >>> print(log['alpha'], log['beta']) >>> print(sgd_dual_pi) References ---------- [Seguy et al., 2018] : International Conference on Learning Representation (2018), arXiv preprint arxiv:1711.02283.
[ "Compute", "the", "transportation", "matrix", "to", "solve", "the", "regularized", "discrete", "measures", "optimal", "transport", "dual", "problem" ]
c5108efc7b6702e1af3928bef1032e6b37734d1c
https://github.com/rflamary/POT/blob/c5108efc7b6702e1af3928bef1032e6b37734d1c/ot/stochastic.py#L645-L736
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", ".", "fullName" ]
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) for baseNode in node.bases: self.handleNode(baseNode, node) if not PY2: for keywordNode in node.keywords: self.handleNode(keywordNode, node) self.pushScope(ClassScope) # doctest does not process doctest within a doctest # classes within classes are processed. if (self.withDoctest and not self._in_doctest() and not isinstance(self.scope, FunctionScope)): self.deferFunction(lambda: self.handleDoctests(node)) for stmt in node.body: self.handleNode(stmt, node) self.popScope() self.addBinding(node, ClassDefinition(node.name, node))
python
def CLASSDEF(self, node): """ Check names used in a class definition, including its decorators, base classes, and the body of its definition. Additionally, add its name to the current scope. """ for deco in node.decorator_list: self.handleNode(deco, node) for baseNode in node.bases: self.handleNode(baseNode, node) if not PY2: for keywordNode in node.keywords: self.handleNode(keywordNode, node) self.pushScope(ClassScope) # doctest does not process doctest within a doctest # classes within classes are processed. if (self.withDoctest and not self._in_doctest() and not isinstance(self.scope, FunctionScope)): self.deferFunction(lambda: self.handleDoctests(node)) for stmt in node.body: self.handleNode(stmt, node) self.popScope() self.addBinding(node, ClassDefinition(node.name, node))
[ "def", "CLASSDEF", "(", "self", ",", "node", ")", ":", "for", "deco", "in", "node", ".", "decorator_list", ":", "self", ".", "handleNode", "(", "deco", ",", "node", ")", "for", "baseNode", "in", "node", ".", "bases", ":", "self", ".", "handleNode", "(", "baseNode", ",", "node", ")", "if", "not", "PY2", ":", "for", "keywordNode", "in", "node", ".", "keywords", ":", "self", ".", "handleNode", "(", "keywordNode", ",", "node", ")", "self", ".", "pushScope", "(", "ClassScope", ")", "# doctest does not process doctest within a doctest", "# classes within classes are processed.", "if", "(", "self", ".", "withDoctest", "and", "not", "self", ".", "_in_doctest", "(", ")", "and", "not", "isinstance", "(", "self", ".", "scope", ",", "FunctionScope", ")", ")", ":", "self", ".", "deferFunction", "(", "lambda", ":", "self", ".", "handleDoctests", "(", "node", ")", ")", "for", "stmt", "in", "node", ".", "body", ":", "self", ".", "handleNode", "(", "stmt", ",", "node", ")", "self", ".", "popScope", "(", ")", "self", ".", "addBinding", "(", "node", ",", "ClassDefinition", "(", "node", ".", "name", ",", "node", ")", ")" ]
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 = f.read(max_bytes) if not text: return False except IOError: return False first_line = text.splitlines()[0] return PYTHON_SHEBANG_REGEX.match(first_line)
python
def isPythonFile(filename): """Return True if filename points to a Python file.""" if filename.endswith('.py'): return True # Avoid obvious Emacs backup files if filename.endswith("~"): return False max_bytes = 128 try: with open(filename, 'rb') as f: text = f.read(max_bytes) if not text: return False except IOError: return False first_line = text.splitlines()[0] return PYTHON_SHEBANG_REGEX.match(first_line)
[ "def", "isPythonFile", "(", "filename", ")", ":", "if", "filename", ".", "endswith", "(", "'.py'", ")", ":", "return", "True", "# Avoid obvious Emacs backup files", "if", "filename", ".", "endswith", "(", "\"~\"", ")", ":", "return", "False", "max_bytes", "=", "128", "try", ":", "with", "open", "(", "filename", ",", "'rb'", ")", "as", "f", ":", "text", "=", "f", ".", "read", "(", "max_bytes", ")", "if", "not", "text", ":", "return", "False", "except", "IOError", ":", "return", "False", "first_line", "=", "text", ".", "splitlines", "(", ")", "[", "0", "]", "return", "PYTHON_SHEBANG_REGEX", ".", "match", "(", "first_line", ")" ]
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: # the signal constants defined in the signal module are defined by # whether the C library supports them or not. So, SIGPIPE might not # even be defined. return def handler(sig, f): sys.exit(message) try: signal.signal(sigNumber, handler) except ValueError: # It's also possible the signal is defined, but then it's invalid. In # this case, signal.signal raises ValueError. pass
python
def _exitOnSignal(sigName, message): """Handles a signal with sys.exit. Some of these signals (SIGPIPE, for example) don't exist or are invalid on Windows. So, ignore errors that might arise. """ import signal try: sigNumber = getattr(signal, sigName) except AttributeError: # the signal constants defined in the signal module are defined by # whether the C library supports them or not. So, SIGPIPE might not # even be defined. return def handler(sig, f): sys.exit(message) try: signal.signal(sigNumber, handler) except ValueError: # It's also possible the signal is defined, but then it's invalid. In # this case, signal.signal raises ValueError. pass
[ "def", "_exitOnSignal", "(", "sigName", ",", "message", ")", ":", "import", "signal", "try", ":", "sigNumber", "=", "getattr", "(", "signal", ",", "sigName", ")", "except", "AttributeError", ":", "# the signal constants defined in the signal module are defined by", "# whether the C library supports them or not. So, SIGPIPE might not", "# even be defined.", "return", "def", "handler", "(", "sig", ",", "f", ")", ":", "sys", ".", "exit", "(", "message", ")", "try", ":", "signal", ".", "signal", "(", "sigNumber", ",", "handler", ")", "except", "ValueError", ":", "# It's also possible the signal is defined, but then it's invalid. In", "# this case, signal.signal raises ValueError.", "pass" ]
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.get_fields() if isinstance(f, OneToOneRel)] rels = [ rel for rel in related_objects if isinstance(rel.field, OneToOneField) and issubclass(rel.field.model, model) and model is not rel.field.model and rel.parent_link ] subclasses = [] if levels: levels -= 1 for rel in rels: if levels or levels is None: for subclass in self._get_subclasses_recurse( rel.field.model, levels=levels): subclasses.append( rel.get_accessor_name() + LOOKUP_SEP + subclass) subclasses.append(rel.get_accessor_name()) return subclasses
python
def _get_subclasses_recurse(self, model, levels=None): """ Given a Model class, find all related objects, exploring children recursively, returning a `list` of strings representing the relations for select_related """ related_objects = [ f for f in model._meta.get_fields() if isinstance(f, OneToOneRel)] rels = [ rel for rel in related_objects if isinstance(rel.field, OneToOneField) and issubclass(rel.field.model, model) and model is not rel.field.model and rel.parent_link ] subclasses = [] if levels: levels -= 1 for rel in rels: if levels or levels is None: for subclass in self._get_subclasses_recurse( rel.field.model, levels=levels): subclasses.append( rel.get_accessor_name() + LOOKUP_SEP + subclass) subclasses.append(rel.get_accessor_name()) return subclasses
[ "def", "_get_subclasses_recurse", "(", "self", ",", "model", ",", "levels", "=", "None", ")", ":", "related_objects", "=", "[", "f", "for", "f", "in", "model", ".", "_meta", ".", "get_fields", "(", ")", "if", "isinstance", "(", "f", ",", "OneToOneRel", ")", "]", "rels", "=", "[", "rel", "for", "rel", "in", "related_objects", "if", "isinstance", "(", "rel", ".", "field", ",", "OneToOneField", ")", "and", "issubclass", "(", "rel", ".", "field", ".", "model", ",", "model", ")", "and", "model", "is", "not", "rel", ".", "field", ".", "model", "and", "rel", ".", "parent_link", "]", "subclasses", "=", "[", "]", "if", "levels", ":", "levels", "-=", "1", "for", "rel", "in", "rels", ":", "if", "levels", "or", "levels", "is", "None", ":", "for", "subclass", "in", "self", ".", "_get_subclasses_recurse", "(", "rel", ".", "field", ".", "model", ",", "levels", "=", "levels", ")", ":", "subclasses", ".", "append", "(", "rel", ".", "get_accessor_name", "(", ")", "+", "LOOKUP_SEP", "+", "subclass", ")", "subclasses", ".", "append", "(", "rel", ".", "get_accessor_name", "(", ")", ")", "return", "subclasses" ]
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): raise ValueError( "%r is not a subclass of %r" % (model, self.model)) ancestry = [] # should be a OneToOneField or None parent_link = model._meta.get_ancestor_link(self.model) if levels: levels -= 1 while parent_link is not None: related = parent_link.remote_field ancestry.insert(0, related.get_accessor_name()) if levels or levels is None: parent_model = related.model parent_link = parent_model._meta.get_ancestor_link( self.model) else: parent_link = None return LOOKUP_SEP.join(ancestry)
python
def _get_ancestors_path(self, model, levels=None): """ Serves as an opposite to _get_subclasses_recurse, instead walking from the Model class up the Model's ancestry and constructing the desired select_related string backwards. """ if not issubclass(model, self.model): raise ValueError( "%r is not a subclass of %r" % (model, self.model)) ancestry = [] # should be a OneToOneField or None parent_link = model._meta.get_ancestor_link(self.model) if levels: levels -= 1 while parent_link is not None: related = parent_link.remote_field ancestry.insert(0, related.get_accessor_name()) if levels or levels is None: parent_model = related.model parent_link = parent_model._meta.get_ancestor_link( self.model) else: parent_link = None return LOOKUP_SEP.join(ancestry)
[ "def", "_get_ancestors_path", "(", "self", ",", "model", ",", "levels", "=", "None", ")", ":", "if", "not", "issubclass", "(", "model", ",", "self", ".", "model", ")", ":", "raise", "ValueError", "(", "\"%r is not a subclass of %r\"", "%", "(", "model", ",", "self", ".", "model", ")", ")", "ancestry", "=", "[", "]", "# should be a OneToOneField or None", "parent_link", "=", "model", ".", "_meta", ".", "get_ancestor_link", "(", "self", ".", "model", ")", "if", "levels", ":", "levels", "-=", "1", "while", "parent_link", "is", "not", "None", ":", "related", "=", "parent_link", ".", "remote_field", "ancestry", ".", "insert", "(", "0", ",", "related", ".", "get_accessor_name", "(", ")", ")", "if", "levels", "or", "levels", "is", "None", ":", "parent_model", "=", "related", ".", "model", "parent_link", "=", "parent_model", ".", "_meta", ".", "get_ancestor_link", "(", "self", ".", "model", ")", "else", ":", "parent_link", "=", "None", "return", "LOOKUP_SEP", ".", "join", "(", "ancestry", ")" ]
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", ".", "_hints", "return", "self", ".", "_queryset_class", "(", "*", "*", "kwargs", ")", ".", "filter", "(", "is_removed", "=", "False", ")" ]
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 locally, simply fetch and un-defer the value if field not in self.instance.__dict__: self.get_field_value(field) # if the field has been assigned locally, store the local value, fetch the database value, # store database value to saved_data, and restore the local value else: current_value = self.get_field_value(field) self.instance.refresh_from_db(fields=[field]) self.saved_data[field] = deepcopy(self.get_field_value(field)) setattr(self.instance, self.field_map[field], current_value) return self.saved_data.get(field)
python
def previous(self, field): """Returns currently saved value of given field""" # handle deferred fields that have not yet been loaded from the database if self.instance.pk and field in self.deferred_fields and field not in self.saved_data: # if the field has not been assigned locally, simply fetch and un-defer the value if field not in self.instance.__dict__: self.get_field_value(field) # if the field has been assigned locally, store the local value, fetch the database value, # store database value to saved_data, and restore the local value else: current_value = self.get_field_value(field) self.instance.refresh_from_db(fields=[field]) self.saved_data[field] = deepcopy(self.get_field_value(field)) setattr(self.instance, self.field_map[field], current_value) return self.saved_data.get(field)
[ "def", "previous", "(", "self", ",", "field", ")", ":", "# handle deferred fields that have not yet been loaded from the database", "if", "self", ".", "instance", ".", "pk", "and", "field", "in", "self", ".", "deferred_fields", "and", "field", "not", "in", "self", ".", "saved_data", ":", "# if the field has not been assigned locally, simply fetch and un-defer the value", "if", "field", "not", "in", "self", ".", "instance", ".", "__dict__", ":", "self", ".", "get_field_value", "(", "field", ")", "# if the field has been assigned locally, store the local value, fetch the database value,", "# store database value to saved_data, and restore the local value", "else", ":", "current_value", "=", "self", ".", "get_field_value", "(", "field", ")", "self", ".", "instance", ".", "refresh_from_db", "(", "fields", "=", "[", "field", "]", ")", "self", ".", "saved_data", "[", "field", "]", "=", "deepcopy", "(", "self", ".", "get_field_value", "(", "field", ")", ")", "setattr", "(", "self", ".", "instance", ",", "self", ".", "field_map", "[", "field", "]", ",", "current_value", ")", "return", "self", ".", "saved_data", ".", "get", "(", "field", ")" ]
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() if k in field_map)) return field_map
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() if k in field_map)) return field_map
[ "def", "get_field_map", "(", "self", ",", "cls", ")", ":", "field_map", "=", "dict", "(", "(", "field", ",", "field", ")", "for", "field", "in", "self", ".", "fields", ")", "all_fields", "=", "dict", "(", "(", "f", ".", "name", ",", "f", ".", "attname", ")", "for", "f", "in", "cls", ".", "_meta", ".", "fields", ")", "field_map", ".", "update", "(", "*", "*", "dict", "(", "(", "k", ",", "v", ")", "for", "(", "k", ",", "v", ")", "in", "all_fields", ".", "items", "(", ")", "if", "k", "in", "field_map", ")", ")", "return", "field_map" ]
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 for value, display in getattr(sender, 'STATUS', ()): if _field_exists(sender, value): raise ImproperlyConfigured( "StatusModel: Model '%s' has a field named '%s' which " "conflicts with a status of the same name." % (sender.__name__, value) ) sender.add_to_class(value, QueryManager(status=value)) if django.VERSION >= (1, 10): # ...then, put it back, as add_to_class is modifying the default manager! sender._meta.default_manager_name = default_manager.name
python
def add_status_query_managers(sender, **kwargs): """ Add a Querymanager for each status item dynamically. """ if not issubclass(sender, StatusModel): return if django.VERSION >= (1, 10): # First, get current manager name... default_manager = sender._meta.default_manager for value, display in getattr(sender, 'STATUS', ()): if _field_exists(sender, value): raise ImproperlyConfigured( "StatusModel: Model '%s' has a field named '%s' which " "conflicts with a status of the same name." % (sender.__name__, value) ) sender.add_to_class(value, QueryManager(status=value)) if django.VERSION >= (1, 10): # ...then, put it back, as add_to_class is modifying the default manager! sender._meta.default_manager_name = default_manager.name
[ "def", "add_status_query_managers", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "if", "not", "issubclass", "(", "sender", ",", "StatusModel", ")", ":", "return", "if", "django", ".", "VERSION", ">=", "(", "1", ",", "10", ")", ":", "# First, get current manager name...", "default_manager", "=", "sender", ".", "_meta", ".", "default_manager", "for", "value", ",", "display", "in", "getattr", "(", "sender", ",", "'STATUS'", ",", "(", ")", ")", ":", "if", "_field_exists", "(", "sender", ",", "value", ")", ":", "raise", "ImproperlyConfigured", "(", "\"StatusModel: Model '%s' has a field named '%s' which \"", "\"conflicts with a status of the same name.\"", "%", "(", "sender", ".", "__name__", ",", "value", ")", ")", "sender", ".", "add_to_class", "(", "value", ",", "QueryManager", "(", "status", "=", "value", ")", ")", "if", "django", ".", "VERSION", ">=", "(", "1", ",", "10", ")", ":", "# ...then, put it back, as add_to_class is modifying the default manager!", "sender", ".", "_meta", ".", "default_manager_name", "=", "default_manager", ".", "name" ]
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' " "which conflicts with the TimeFramedModel manager." % sender.__name__ ) sender.add_to_class('timeframed', QueryManager( (models.Q(start__lte=now) | models.Q(start__isnull=True)) & (models.Q(end__gte=now) | models.Q(end__isnull=True)) ))
python
def add_timeframed_query_manager(sender, **kwargs): """ Add a QueryManager for a specific timeframe. """ if not issubclass(sender, TimeFramedModel): return if _field_exists(sender, 'timeframed'): raise ImproperlyConfigured( "Model '%s' has a field named 'timeframed' " "which conflicts with the TimeFramedModel manager." % sender.__name__ ) sender.add_to_class('timeframed', QueryManager( (models.Q(start__lte=now) | models.Q(start__isnull=True)) & (models.Q(end__gte=now) | models.Q(end__isnull=True)) ))
[ "def", "add_timeframed_query_manager", "(", "sender", ",", "*", "*", "kwargs", ")", ":", "if", "not", "issubclass", "(", "sender", ",", "TimeFramedModel", ")", ":", "return", "if", "_field_exists", "(", "sender", ",", "'timeframed'", ")", ":", "raise", "ImproperlyConfigured", "(", "\"Model '%s' has a field named 'timeframed' \"", "\"which conflicts with the TimeFramedModel manager.\"", "%", "sender", ".", "__name__", ")", "sender", ".", "add_to_class", "(", "'timeframed'", ",", "QueryManager", "(", "(", "models", ".", "Q", "(", "start__lte", "=", "now", ")", "|", "models", ".", "Q", "(", "start__isnull", "=", "True", ")", ")", "&", "(", "models", ".", "Q", "(", "end__gte", "=", "now", ")", "|", "models", ".", "Q", "(", "end__isnull", "=", "True", ")", ")", ")", ")" ]
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 """ import subprocess from distutils import spawn import tempfile import time # Check for dependencies. Needs Tesseract and Imagemagick installed. if not spawn.find_executable('tesseract'): raise EnvironmentError('tesseract not installed.') if not spawn.find_executable('convert'): raise EnvironmentError('imagemagick not installed.') if not spawn.find_executable('gs'): raise EnvironmentError('ghostscript not installed.') with tempfile.NamedTemporaryFile(suffix='.tiff') as tf: # Step 1: Convert to TIFF gs_cmd = [ 'gs', '-q', '-dNOPAUSE', '-r600x600', '-sDEVICE=tiff24nc', '-sOutputFile=' + tf.name, path, '-c', 'quit', ] subprocess.Popen(gs_cmd) time.sleep(3) # Step 2: Enhance TIFF magick_cmd = [ 'convert', tf.name, '-colorspace', 'gray', '-type', 'grayscale', '-contrast-stretch', '0', '-sharpen', '0x1', 'tiff:-', ] p1 = subprocess.Popen(magick_cmd, stdout=subprocess.PIPE) tess_cmd = ['tesseract', '-l', language, '--oem', '1', '--psm', '3', 'stdin', 'stdout'] p2 = subprocess.Popen(tess_cmd, stdin=p1.stdout, stdout=subprocess.PIPE) out, err = p2.communicate() extracted_str = out return extracted_str
python
def to_text(path, language='fra'): """Wraps Tesseract 4 OCR with custom language model. Parameters ---------- path : str path of electronic invoice in JPG or PNG format Returns ------- extracted_str : str returns extracted text from image in JPG or PNG format """ import subprocess from distutils import spawn import tempfile import time # Check for dependencies. Needs Tesseract and Imagemagick installed. if not spawn.find_executable('tesseract'): raise EnvironmentError('tesseract not installed.') if not spawn.find_executable('convert'): raise EnvironmentError('imagemagick not installed.') if not spawn.find_executable('gs'): raise EnvironmentError('ghostscript not installed.') with tempfile.NamedTemporaryFile(suffix='.tiff') as tf: # Step 1: Convert to TIFF gs_cmd = [ 'gs', '-q', '-dNOPAUSE', '-r600x600', '-sDEVICE=tiff24nc', '-sOutputFile=' + tf.name, path, '-c', 'quit', ] subprocess.Popen(gs_cmd) time.sleep(3) # Step 2: Enhance TIFF magick_cmd = [ 'convert', tf.name, '-colorspace', 'gray', '-type', 'grayscale', '-contrast-stretch', '0', '-sharpen', '0x1', 'tiff:-', ] p1 = subprocess.Popen(magick_cmd, stdout=subprocess.PIPE) tess_cmd = ['tesseract', '-l', language, '--oem', '1', '--psm', '3', 'stdin', 'stdout'] p2 = subprocess.Popen(tess_cmd, stdin=p1.stdout, stdout=subprocess.PIPE) out, err = p2.communicate() extracted_str = out return extracted_str
[ "def", "to_text", "(", "path", ",", "language", "=", "'fra'", ")", ":", "import", "subprocess", "from", "distutils", "import", "spawn", "import", "tempfile", "import", "time", "# Check for dependencies. Needs Tesseract and Imagemagick installed.", "if", "not", "spawn", ".", "find_executable", "(", "'tesseract'", ")", ":", "raise", "EnvironmentError", "(", "'tesseract not installed.'", ")", "if", "not", "spawn", ".", "find_executable", "(", "'convert'", ")", ":", "raise", "EnvironmentError", "(", "'imagemagick not installed.'", ")", "if", "not", "spawn", ".", "find_executable", "(", "'gs'", ")", ":", "raise", "EnvironmentError", "(", "'ghostscript not installed.'", ")", "with", "tempfile", ".", "NamedTemporaryFile", "(", "suffix", "=", "'.tiff'", ")", "as", "tf", ":", "# Step 1: Convert to TIFF", "gs_cmd", "=", "[", "'gs'", ",", "'-q'", ",", "'-dNOPAUSE'", ",", "'-r600x600'", ",", "'-sDEVICE=tiff24nc'", ",", "'-sOutputFile='", "+", "tf", ".", "name", ",", "path", ",", "'-c'", ",", "'quit'", ",", "]", "subprocess", ".", "Popen", "(", "gs_cmd", ")", "time", ".", "sleep", "(", "3", ")", "# Step 2: Enhance TIFF", "magick_cmd", "=", "[", "'convert'", ",", "tf", ".", "name", ",", "'-colorspace'", ",", "'gray'", ",", "'-type'", ",", "'grayscale'", ",", "'-contrast-stretch'", ",", "'0'", ",", "'-sharpen'", ",", "'0x1'", ",", "'tiff:-'", ",", "]", "p1", "=", "subprocess", ".", "Popen", "(", "magick_cmd", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "tess_cmd", "=", "[", "'tesseract'", ",", "'-l'", ",", "language", ",", "'--oem'", ",", "'1'", ",", "'--psm'", ",", "'3'", ",", "'stdin'", ",", "'stdout'", "]", "p2", "=", "subprocess", ".", "Popen", "(", "tess_cmd", ",", "stdin", "=", "p1", ".", "stdout", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "out", ",", "err", "=", "p2", ".", "communicate", "(", ")", "extracted_str", "=", "out", "return", "extracted_str" ]
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 invoice in JPG or PNG format bucket_name : str name of bucket to use for file storage and results cache. Returns ------- extracted_str : str returns extracted text from image in JPG or PNG format """ """OCR with PDF/TIFF as source files on GCS""" import os from google.cloud import vision from google.cloud import storage from google.protobuf import json_format # Supported mime_types are: 'application/pdf' and 'image/tiff' mime_type = 'application/pdf' path_dir, filename = os.path.split(path) result_blob_basename = filename.replace('.pdf', '').replace('.PDF', '') result_blob_name = result_blob_basename + '/output-1-to-1.json' result_blob_uri = 'gs://{}/{}/'.format(bucket_name, result_blob_basename) input_blob_uri = 'gs://{}/{}'.format(bucket_name, filename) # Upload file to gcloud if it doesn't exist yet storage_client = storage.Client() bucket = storage_client.get_bucket(bucket_name) if bucket.get_blob(filename) is None: blob = bucket.blob(filename) blob.upload_from_filename(path) # See if result already exists # TODO: upload as hash, not filename result_blob = bucket.get_blob(result_blob_name) if result_blob is None: # How many pages should be grouped into each json output file. batch_size = 10 client = vision.ImageAnnotatorClient() feature = vision.types.Feature(type=vision.enums.Feature.Type.DOCUMENT_TEXT_DETECTION) gcs_source = vision.types.GcsSource(uri=input_blob_uri) input_config = vision.types.InputConfig(gcs_source=gcs_source, mime_type=mime_type) gcs_destination = vision.types.GcsDestination(uri=result_blob_uri) output_config = vision.types.OutputConfig( gcs_destination=gcs_destination, batch_size=batch_size ) async_request = vision.types.AsyncAnnotateFileRequest( features=[feature], input_config=input_config, output_config=output_config ) operation = client.async_batch_annotate_files(requests=[async_request]) print('Waiting for the operation to finish.') operation.result(timeout=180) # Get result after OCR is completed result_blob = bucket.get_blob(result_blob_name) json_string = result_blob.download_as_string() response = json_format.Parse(json_string, vision.types.AnnotateFileResponse()) # The actual response for the first page of the input file. first_page_response = response.responses[0] annotation = first_page_response.full_text_annotation return annotation.text.encode('utf-8')
python
def to_text(path, bucket_name='cloud-vision-84893', language='fr'): """Sends PDF files to Google Cloud Vision for OCR. Before using invoice2data, make sure you have the auth json path set as env var GOOGLE_APPLICATION_CREDENTIALS Parameters ---------- path : str path of electronic invoice in JPG or PNG format bucket_name : str name of bucket to use for file storage and results cache. Returns ------- extracted_str : str returns extracted text from image in JPG or PNG format """ """OCR with PDF/TIFF as source files on GCS""" import os from google.cloud import vision from google.cloud import storage from google.protobuf import json_format # Supported mime_types are: 'application/pdf' and 'image/tiff' mime_type = 'application/pdf' path_dir, filename = os.path.split(path) result_blob_basename = filename.replace('.pdf', '').replace('.PDF', '') result_blob_name = result_blob_basename + '/output-1-to-1.json' result_blob_uri = 'gs://{}/{}/'.format(bucket_name, result_blob_basename) input_blob_uri = 'gs://{}/{}'.format(bucket_name, filename) # Upload file to gcloud if it doesn't exist yet storage_client = storage.Client() bucket = storage_client.get_bucket(bucket_name) if bucket.get_blob(filename) is None: blob = bucket.blob(filename) blob.upload_from_filename(path) # See if result already exists # TODO: upload as hash, not filename result_blob = bucket.get_blob(result_blob_name) if result_blob is None: # How many pages should be grouped into each json output file. batch_size = 10 client = vision.ImageAnnotatorClient() feature = vision.types.Feature(type=vision.enums.Feature.Type.DOCUMENT_TEXT_DETECTION) gcs_source = vision.types.GcsSource(uri=input_blob_uri) input_config = vision.types.InputConfig(gcs_source=gcs_source, mime_type=mime_type) gcs_destination = vision.types.GcsDestination(uri=result_blob_uri) output_config = vision.types.OutputConfig( gcs_destination=gcs_destination, batch_size=batch_size ) async_request = vision.types.AsyncAnnotateFileRequest( features=[feature], input_config=input_config, output_config=output_config ) operation = client.async_batch_annotate_files(requests=[async_request]) print('Waiting for the operation to finish.') operation.result(timeout=180) # Get result after OCR is completed result_blob = bucket.get_blob(result_blob_name) json_string = result_blob.download_as_string() response = json_format.Parse(json_string, vision.types.AnnotateFileResponse()) # The actual response for the first page of the input file. first_page_response = response.responses[0] annotation = first_page_response.full_text_annotation return annotation.text.encode('utf-8')
[ "def", "to_text", "(", "path", ",", "bucket_name", "=", "'cloud-vision-84893'", ",", "language", "=", "'fr'", ")", ":", "\"\"\"OCR with PDF/TIFF as source files on GCS\"\"\"", "import", "os", "from", "google", ".", "cloud", "import", "vision", "from", "google", ".", "cloud", "import", "storage", "from", "google", ".", "protobuf", "import", "json_format", "# Supported mime_types are: 'application/pdf' and 'image/tiff'", "mime_type", "=", "'application/pdf'", "path_dir", ",", "filename", "=", "os", ".", "path", ".", "split", "(", "path", ")", "result_blob_basename", "=", "filename", ".", "replace", "(", "'.pdf'", ",", "''", ")", ".", "replace", "(", "'.PDF'", ",", "''", ")", "result_blob_name", "=", "result_blob_basename", "+", "'/output-1-to-1.json'", "result_blob_uri", "=", "'gs://{}/{}/'", ".", "format", "(", "bucket_name", ",", "result_blob_basename", ")", "input_blob_uri", "=", "'gs://{}/{}'", ".", "format", "(", "bucket_name", ",", "filename", ")", "# Upload file to gcloud if it doesn't exist yet", "storage_client", "=", "storage", ".", "Client", "(", ")", "bucket", "=", "storage_client", ".", "get_bucket", "(", "bucket_name", ")", "if", "bucket", ".", "get_blob", "(", "filename", ")", "is", "None", ":", "blob", "=", "bucket", ".", "blob", "(", "filename", ")", "blob", ".", "upload_from_filename", "(", "path", ")", "# See if result already exists", "# TODO: upload as hash, not filename", "result_blob", "=", "bucket", ".", "get_blob", "(", "result_blob_name", ")", "if", "result_blob", "is", "None", ":", "# How many pages should be grouped into each json output file.", "batch_size", "=", "10", "client", "=", "vision", ".", "ImageAnnotatorClient", "(", ")", "feature", "=", "vision", ".", "types", ".", "Feature", "(", "type", "=", "vision", ".", "enums", ".", "Feature", ".", "Type", ".", "DOCUMENT_TEXT_DETECTION", ")", "gcs_source", "=", "vision", ".", "types", ".", "GcsSource", "(", "uri", "=", "input_blob_uri", ")", "input_config", "=", "vision", ".", "types", ".", "InputConfig", "(", "gcs_source", "=", "gcs_source", ",", "mime_type", "=", "mime_type", ")", "gcs_destination", "=", "vision", ".", "types", ".", "GcsDestination", "(", "uri", "=", "result_blob_uri", ")", "output_config", "=", "vision", ".", "types", ".", "OutputConfig", "(", "gcs_destination", "=", "gcs_destination", ",", "batch_size", "=", "batch_size", ")", "async_request", "=", "vision", ".", "types", ".", "AsyncAnnotateFileRequest", "(", "features", "=", "[", "feature", "]", ",", "input_config", "=", "input_config", ",", "output_config", "=", "output_config", ")", "operation", "=", "client", ".", "async_batch_annotate_files", "(", "requests", "=", "[", "async_request", "]", ")", "print", "(", "'Waiting for the operation to finish.'", ")", "operation", ".", "result", "(", "timeout", "=", "180", ")", "# Get result after OCR is completed", "result_blob", "=", "bucket", ".", "get_blob", "(", "result_blob_name", ")", "json_string", "=", "result_blob", ".", "download_as_string", "(", ")", "response", "=", "json_format", ".", "Parse", "(", "json_string", ",", "vision", ".", "types", ".", "AnnotateFileResponse", "(", ")", ")", "# The actual response for the first page of the input file.", "first_page_response", "=", "response", ".", "responses", "[", "0", "]", "annotation", "=", "first_page_response", ".", "full_text_annotation", "return", "annotation", ".", "text", ".", "encode", "(", "'utf-8'", ")" ]
Sends PDF files to Google Cloud Vision for OCR. Before using invoice2data, make sure you have the auth json path set as env var GOOGLE_APPLICATION_CREDENTIALS Parameters ---------- path : str path of electronic invoice in JPG or PNG format bucket_name : str name of bucket to use for file storage and results cache. Returns ------- extracted_str : str returns extracted text from image in JPG or PNG format
[ "Sends", "PDF", "files", "to", "Google", "Cloud", "Vision", "for", "OCR", "." ]
d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20
https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/input/gvision.py#L2-L83
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 Notes ---- Do give file name to the function parameter path. Examples -------- >>> from invoice2data.output import to_csv >>> to_csv.write_to_file(data, "/exported_csv/invoice.csv") >>> to_csv.write_to_file(data, "invoice.csv") """ if path.endswith('.csv'): filename = path else: filename = path + '.csv' if sys.version_info[0] < 3: openfile = open(filename, "wb") else: openfile = open(filename, "w", newline='') with openfile as csv_file: writer = csv.writer(csv_file, delimiter=',') for line in data: first_row = [] for k, v in line.items(): first_row.append(k) writer.writerow(first_row) for line in data: csv_items = [] for k, v in line.items(): # first_row.append(k) if k == 'date': v = v.strftime('%d/%m/%Y') csv_items.append(v) writer.writerow(csv_items)
python
def write_to_file(data, path): """Export extracted fields to csv Appends .csv to path if missing and generates csv file in specified directory, if not then in root Parameters ---------- data : dict Dictionary of extracted fields path : str directory to save generated csv file Notes ---- Do give file name to the function parameter path. Examples -------- >>> from invoice2data.output import to_csv >>> to_csv.write_to_file(data, "/exported_csv/invoice.csv") >>> to_csv.write_to_file(data, "invoice.csv") """ if path.endswith('.csv'): filename = path else: filename = path + '.csv' if sys.version_info[0] < 3: openfile = open(filename, "wb") else: openfile = open(filename, "w", newline='') with openfile as csv_file: writer = csv.writer(csv_file, delimiter=',') for line in data: first_row = [] for k, v in line.items(): first_row.append(k) writer.writerow(first_row) for line in data: csv_items = [] for k, v in line.items(): # first_row.append(k) if k == 'date': v = v.strftime('%d/%m/%Y') csv_items.append(v) writer.writerow(csv_items)
[ "def", "write_to_file", "(", "data", ",", "path", ")", ":", "if", "path", ".", "endswith", "(", "'.csv'", ")", ":", "filename", "=", "path", "else", ":", "filename", "=", "path", "+", "'.csv'", "if", "sys", ".", "version_info", "[", "0", "]", "<", "3", ":", "openfile", "=", "open", "(", "filename", ",", "\"wb\"", ")", "else", ":", "openfile", "=", "open", "(", "filename", ",", "\"w\"", ",", "newline", "=", "''", ")", "with", "openfile", "as", "csv_file", ":", "writer", "=", "csv", ".", "writer", "(", "csv_file", ",", "delimiter", "=", "','", ")", "for", "line", "in", "data", ":", "first_row", "=", "[", "]", "for", "k", ",", "v", "in", "line", ".", "items", "(", ")", ":", "first_row", ".", "append", "(", "k", ")", "writer", ".", "writerow", "(", "first_row", ")", "for", "line", "in", "data", ":", "csv_items", "=", "[", "]", "for", "k", ",", "v", "in", "line", ".", "items", "(", ")", ":", "# first_row.append(k)", "if", "k", "==", "'date'", ":", "v", "=", "v", ".", "strftime", "(", "'%d/%m/%Y'", ")", "csv_items", ".", "append", "(", "v", ")", "writer", ".", "writerow", "(", "csv_items", ")" ]
Export extracted fields to csv Appends .csv to path if missing and generates csv file in specified directory, if not then in root Parameters ---------- data : dict Dictionary of extracted fields path : str directory to save generated csv file Notes ---- Do give file name to the function parameter path. Examples -------- >>> from invoice2data.output import to_csv >>> to_csv.write_to_file(data, "/exported_csv/invoice.csv") >>> to_csv.write_to_file(data, "invoice.csv")
[ "Export", "extracted", "fields", "to", "csv" ]
d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20
https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/output/to_csv.py#L5-L54
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 spawn # Check for dependencies. Needs Tesseract and Imagemagick installed. if not spawn.find_executable('tesseract'): raise EnvironmentError('tesseract not installed.') if not spawn.find_executable('convert'): raise EnvironmentError('imagemagick not installed.') # convert = "convert -density 350 %s -depth 8 tiff:-" % (path) convert = ['convert', '-density', '350', path, '-depth', '8', 'png:-'] p1 = subprocess.Popen(convert, stdout=subprocess.PIPE) tess = ['tesseract', 'stdin', 'stdout'] p2 = subprocess.Popen(tess, stdin=p1.stdout, stdout=subprocess.PIPE) out, err = p2.communicate() extracted_str = out return extracted_str
python
def to_text(path): """Wraps Tesseract OCR. Parameters ---------- path : str path of electronic invoice in JPG or PNG format Returns ------- extracted_str : str returns extracted text from image in JPG or PNG format """ import subprocess from distutils import spawn # Check for dependencies. Needs Tesseract and Imagemagick installed. if not spawn.find_executable('tesseract'): raise EnvironmentError('tesseract not installed.') if not spawn.find_executable('convert'): raise EnvironmentError('imagemagick not installed.') # convert = "convert -density 350 %s -depth 8 tiff:-" % (path) convert = ['convert', '-density', '350', path, '-depth', '8', 'png:-'] p1 = subprocess.Popen(convert, stdout=subprocess.PIPE) tess = ['tesseract', 'stdin', 'stdout'] p2 = subprocess.Popen(tess, stdin=p1.stdout, stdout=subprocess.PIPE) out, err = p2.communicate() extracted_str = out return extracted_str
[ "def", "to_text", "(", "path", ")", ":", "import", "subprocess", "from", "distutils", "import", "spawn", "# Check for dependencies. Needs Tesseract and Imagemagick installed.", "if", "not", "spawn", ".", "find_executable", "(", "'tesseract'", ")", ":", "raise", "EnvironmentError", "(", "'tesseract not installed.'", ")", "if", "not", "spawn", ".", "find_executable", "(", "'convert'", ")", ":", "raise", "EnvironmentError", "(", "'imagemagick not installed.'", ")", "# convert = \"convert -density 350 %s -depth 8 tiff:-\" % (path)", "convert", "=", "[", "'convert'", ",", "'-density'", ",", "'350'", ",", "path", ",", "'-depth'", ",", "'8'", ",", "'png:-'", "]", "p1", "=", "subprocess", ".", "Popen", "(", "convert", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "tess", "=", "[", "'tesseract'", ",", "'stdin'", ",", "'stdout'", "]", "p2", "=", "subprocess", ".", "Popen", "(", "tess", ",", "stdin", "=", "p1", ".", "stdout", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", "out", ",", "err", "=", "p2", ".", "communicate", "(", ")", "extracted_str", "=", "out", "return", "extracted_str" ]
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 'start' in table, 'Table start regex missing' assert 'end' in table, 'Table end regex missing' assert 'body' in table, 'Table body regex missing' start = re.search(table['start'], content) end = re.search(table['end'], content) if not start or not end: logger.warning('no table body found - start %s, end %s', start, end) continue table_body = content[start.end(): end.start()] for line in re.split(table['line_separator'], table_body): # if the line has empty lines in it , skip them if not line.strip('').strip('\n') or not line: continue match = re.search(table['body'], line) if match: for field, value in match.groupdict().items(): # If a field name already exists, do not overwrite it if field in output: continue if field.startswith('date') or field.endswith('date'): output[field] = self.parse_date(value) if not output[field]: logger.error("Date parsing failed on date '%s'", value) return None elif field.startswith('amount'): output[field] = self.parse_number(value) else: output[field] = value logger.debug('ignoring *%s* because it doesn\'t match anything', line)
python
def extract(self, content, output): """Try to extract tables from an invoice""" for table in self['tables']: # First apply default options. plugin_settings = DEFAULT_OPTIONS.copy() plugin_settings.update(table) table = plugin_settings # Validate settings assert 'start' in table, 'Table start regex missing' assert 'end' in table, 'Table end regex missing' assert 'body' in table, 'Table body regex missing' start = re.search(table['start'], content) end = re.search(table['end'], content) if not start or not end: logger.warning('no table body found - start %s, end %s', start, end) continue table_body = content[start.end(): end.start()] for line in re.split(table['line_separator'], table_body): # if the line has empty lines in it , skip them if not line.strip('').strip('\n') or not line: continue match = re.search(table['body'], line) if match: for field, value in match.groupdict().items(): # If a field name already exists, do not overwrite it if field in output: continue if field.startswith('date') or field.endswith('date'): output[field] = self.parse_date(value) if not output[field]: logger.error("Date parsing failed on date '%s'", value) return None elif field.startswith('amount'): output[field] = self.parse_number(value) else: output[field] = value logger.debug('ignoring *%s* because it doesn\'t match anything', line)
[ "def", "extract", "(", "self", ",", "content", ",", "output", ")", ":", "for", "table", "in", "self", "[", "'tables'", "]", ":", "# First apply default options.", "plugin_settings", "=", "DEFAULT_OPTIONS", ".", "copy", "(", ")", "plugin_settings", ".", "update", "(", "table", ")", "table", "=", "plugin_settings", "# Validate settings", "assert", "'start'", "in", "table", ",", "'Table start regex missing'", "assert", "'end'", "in", "table", ",", "'Table end regex missing'", "assert", "'body'", "in", "table", ",", "'Table body regex missing'", "start", "=", "re", ".", "search", "(", "table", "[", "'start'", "]", ",", "content", ")", "end", "=", "re", ".", "search", "(", "table", "[", "'end'", "]", ",", "content", ")", "if", "not", "start", "or", "not", "end", ":", "logger", ".", "warning", "(", "'no table body found - start %s, end %s'", ",", "start", ",", "end", ")", "continue", "table_body", "=", "content", "[", "start", ".", "end", "(", ")", ":", "end", ".", "start", "(", ")", "]", "for", "line", "in", "re", ".", "split", "(", "table", "[", "'line_separator'", "]", ",", "table_body", ")", ":", "# if the line has empty lines in it , skip them", "if", "not", "line", ".", "strip", "(", "''", ")", ".", "strip", "(", "'\\n'", ")", "or", "not", "line", ":", "continue", "match", "=", "re", ".", "search", "(", "table", "[", "'body'", "]", ",", "line", ")", "if", "match", ":", "for", "field", ",", "value", "in", "match", ".", "groupdict", "(", ")", ".", "items", "(", ")", ":", "# If a field name already exists, do not overwrite it", "if", "field", "in", "output", ":", "continue", "if", "field", ".", "startswith", "(", "'date'", ")", "or", "field", ".", "endswith", "(", "'date'", ")", ":", "output", "[", "field", "]", "=", "self", ".", "parse_date", "(", "value", ")", "if", "not", "output", "[", "field", "]", ":", "logger", ".", "error", "(", "\"Date parsing failed on date '%s'\"", ",", "value", ")", "return", "None", "elif", "field", ".", "startswith", "(", "'amount'", ")", ":", "output", "[", "field", "]", "=", "self", ".", "parse_number", "(", "value", ")", "else", ":", "output", "[", "field", "]", "=", "value", "logger", ".", "debug", "(", "'ignoring *%s* because it doesn\\'t match anything'", ",", "line", ")" ]
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 """ import subprocess from distutils import spawn # py2 compat if spawn.find_executable("pdftotext"): # shutil.which('pdftotext'): out, err = subprocess.Popen( ["pdftotext", '-layout', '-enc', 'UTF-8', path, '-'], stdout=subprocess.PIPE ).communicate() return out else: raise EnvironmentError( 'pdftotext not installed. Can be downloaded from https://poppler.freedesktop.org/' )
python
def to_text(path): """Wrapper around Poppler pdftotext. Parameters ---------- path : str path of electronic invoice in PDF Returns ------- out : str returns extracted text from pdf Raises ------ EnvironmentError: If pdftotext library is not found """ import subprocess from distutils import spawn # py2 compat if spawn.find_executable("pdftotext"): # shutil.which('pdftotext'): out, err = subprocess.Popen( ["pdftotext", '-layout', '-enc', 'UTF-8', path, '-'], stdout=subprocess.PIPE ).communicate() return out else: raise EnvironmentError( 'pdftotext not installed. Can be downloaded from https://poppler.freedesktop.org/' )
[ "def", "to_text", "(", "path", ")", ":", "import", "subprocess", "from", "distutils", "import", "spawn", "# py2 compat", "if", "spawn", ".", "find_executable", "(", "\"pdftotext\"", ")", ":", "# shutil.which('pdftotext'):", "out", ",", "err", "=", "subprocess", ".", "Popen", "(", "[", "\"pdftotext\"", ",", "'-layout'", ",", "'-enc'", ",", "'UTF-8'", ",", "path", ",", "'-'", "]", ",", "stdout", "=", "subprocess", ".", "PIPE", ")", ".", "communicate", "(", ")", "return", "out", "else", ":", "raise", "EnvironmentError", "(", "'pdftotext not installed. Can be downloaded from https://poppler.freedesktop.org/'", ")" ]
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 = extracted_str # Remove accents if self.options['remove_accents']: optimized_str = unidecode(optimized_str) # convert to lower case if self.options['lowercase']: optimized_str = optimized_str.lower() # specific replace for replace in self.options['replace']: assert len(replace) == 2, 'A replace should be a list of 2 items' optimized_str = optimized_str.replace(replace[0], replace[1]) return optimized_str
python
def prepare_input(self, extracted_str): """ Input raw string and do transformations, as set in template file. """ # Remove withspace if self.options['remove_whitespace']: optimized_str = re.sub(' +', '', extracted_str) else: optimized_str = extracted_str # Remove accents if self.options['remove_accents']: optimized_str = unidecode(optimized_str) # convert to lower case if self.options['lowercase']: optimized_str = optimized_str.lower() # specific replace for replace in self.options['replace']: assert len(replace) == 2, 'A replace should be a list of 2 items' optimized_str = optimized_str.replace(replace[0], replace[1]) return optimized_str
[ "def", "prepare_input", "(", "self", ",", "extracted_str", ")", ":", "# Remove withspace", "if", "self", ".", "options", "[", "'remove_whitespace'", "]", ":", "optimized_str", "=", "re", ".", "sub", "(", "' +'", ",", "''", ",", "extracted_str", ")", "else", ":", "optimized_str", "=", "extracted_str", "# Remove accents", "if", "self", ".", "options", "[", "'remove_accents'", "]", ":", "optimized_str", "=", "unidecode", "(", "optimized_str", ")", "# convert to lower case", "if", "self", ".", "options", "[", "'lowercase'", "]", ":", "optimized_str", "=", "optimized_str", ".", "lower", "(", ")", "# specific replace", "for", "replace", "in", "self", ".", "options", "[", "'replace'", "]", ":", "assert", "len", "(", "replace", ")", "==", "2", ",", "'A replace should be a list of 2 items'", "optimized_str", "=", "optimized_str", ".", "replace", "(", "replace", "[", "0", "]", ",", "replace", "[", "1", "]", ")", "return", "optimized_str" ]
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'", ",", "self", "[", "'template_name'", "]", ")", "return", "True" ]
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'", "]", ")", "logger", ".", "debug", "(", "\"result of date parsing=%s\"", ",", "res", ")", "return", "res" ]
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 file Notes ---- Do give file name to the function parameter path. Examples -------- >>> from invoice2data.output import to_json >>> to_json.write_to_file(data, "/exported_json/invoice.json") >>> to_json.write_to_file(data, "invoice.json") """ if path.endswith('.json'): filename = path else: filename = path + '.json' with codecs.open(filename, "w", encoding='utf-8') as json_file: for line in data: line['date'] = line['date'].strftime('%d/%m/%Y') print(type(json)) print(json) json.dump( data, json_file, indent=4, sort_keys=True, default=myconverter, ensure_ascii=False )
python
def write_to_file(data, path): """Export extracted fields to json Appends .json to path if missing and generates json file in specified directory, if not then in root Parameters ---------- data : dict Dictionary of extracted fields path : str directory to save generated json file Notes ---- Do give file name to the function parameter path. Examples -------- >>> from invoice2data.output import to_json >>> to_json.write_to_file(data, "/exported_json/invoice.json") >>> to_json.write_to_file(data, "invoice.json") """ if path.endswith('.json'): filename = path else: filename = path + '.json' with codecs.open(filename, "w", encoding='utf-8') as json_file: for line in data: line['date'] = line['date'].strftime('%d/%m/%Y') print(type(json)) print(json) json.dump( data, json_file, indent=4, sort_keys=True, default=myconverter, ensure_ascii=False )
[ "def", "write_to_file", "(", "data", ",", "path", ")", ":", "if", "path", ".", "endswith", "(", "'.json'", ")", ":", "filename", "=", "path", "else", ":", "filename", "=", "path", "+", "'.json'", "with", "codecs", ".", "open", "(", "filename", ",", "\"w\"", ",", "encoding", "=", "'utf-8'", ")", "as", "json_file", ":", "for", "line", "in", "data", ":", "line", "[", "'date'", "]", "=", "line", "[", "'date'", "]", ".", "strftime", "(", "'%d/%m/%Y'", ")", "print", "(", "type", "(", "json", ")", ")", "print", "(", "json", ")", "json", ".", "dump", "(", "data", ",", "json_file", ",", "indent", "=", "4", ",", "sort_keys", "=", "True", ",", "default", "=", "myconverter", ",", "ensure_ascii", "=", "False", ")" ]
Export extracted fields to json Appends .json to path if missing and generates json file in specified directory, if not then in root Parameters ---------- data : dict Dictionary of extracted fields path : str directory to save generated json file Notes ---- Do give file name to the function parameter path. Examples -------- >>> from invoice2data.output import to_json >>> to_json.write_to_file(data, "/exported_json/invoice.json") >>> to_json.write_to_file(data, "invoice.json")
[ "Export", "extracted", "fields", "to", "json" ]
d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20
https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/output/to_json.py#L12-L47
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='Choose text extraction function. Default: pdftotext', ) parser.add_argument( '--output-format', choices=output_mapping.keys(), default='none', help='Choose output format. Default: none', ) parser.add_argument( '--output-name', '-o', dest='output_name', default='invoices-output', help='Custom name for output file. Extension is added based on chosen format.', ) parser.add_argument( '--debug', dest='debug', action='store_true', help='Enable debug information.' ) parser.add_argument( '--copy', '-c', dest='copy', help='Copy and rename processed PDFs to specified folder.' ) parser.add_argument( '--move', '-m', dest='move', help='Move and rename processed PDFs to specified folder.' ) parser.add_argument( '--filename-format', dest='filename', default="{date} {invoice_number} {desc}.pdf", help='Filename format to use when moving or copying processed PDFs.' 'Default: "{date} {invoice_number} {desc}.pdf"', ) parser.add_argument( '--template-folder', '-t', dest='template_folder', help='Folder containing invoice templates in yml file. Always adds built-in templates.', ) parser.add_argument( '--exclude-built-in-templates', dest='exclude_built_in_templates', default=False, help='Ignore built-in templates.', action="store_true", ) parser.add_argument( 'input_files', type=argparse.FileType('r'), nargs='+', help='File or directory to analyze.' ) return parser
python
def create_parser(): """Returns argument parser """ parser = argparse.ArgumentParser( description='Extract structured data from PDF files and save to CSV or JSON.' ) parser.add_argument( '--input-reader', choices=input_mapping.keys(), default='pdftotext', help='Choose text extraction function. Default: pdftotext', ) parser.add_argument( '--output-format', choices=output_mapping.keys(), default='none', help='Choose output format. Default: none', ) parser.add_argument( '--output-name', '-o', dest='output_name', default='invoices-output', help='Custom name for output file. Extension is added based on chosen format.', ) parser.add_argument( '--debug', dest='debug', action='store_true', help='Enable debug information.' ) parser.add_argument( '--copy', '-c', dest='copy', help='Copy and rename processed PDFs to specified folder.' ) parser.add_argument( '--move', '-m', dest='move', help='Move and rename processed PDFs to specified folder.' ) parser.add_argument( '--filename-format', dest='filename', default="{date} {invoice_number} {desc}.pdf", help='Filename format to use when moving or copying processed PDFs.' 'Default: "{date} {invoice_number} {desc}.pdf"', ) parser.add_argument( '--template-folder', '-t', dest='template_folder', help='Folder containing invoice templates in yml file. Always adds built-in templates.', ) parser.add_argument( '--exclude-built-in-templates', dest='exclude_built_in_templates', default=False, help='Ignore built-in templates.', action="store_true", ) parser.add_argument( 'input_files', type=argparse.FileType('r'), nargs='+', help='File or directory to analyze.' ) return parser
[ "def", "create_parser", "(", ")", ":", "parser", "=", "argparse", ".", "ArgumentParser", "(", "description", "=", "'Extract structured data from PDF files and save to CSV or JSON.'", ")", "parser", ".", "add_argument", "(", "'--input-reader'", ",", "choices", "=", "input_mapping", ".", "keys", "(", ")", ",", "default", "=", "'pdftotext'", ",", "help", "=", "'Choose text extraction function. Default: pdftotext'", ",", ")", "parser", ".", "add_argument", "(", "'--output-format'", ",", "choices", "=", "output_mapping", ".", "keys", "(", ")", ",", "default", "=", "'none'", ",", "help", "=", "'Choose output format. Default: none'", ",", ")", "parser", ".", "add_argument", "(", "'--output-name'", ",", "'-o'", ",", "dest", "=", "'output_name'", ",", "default", "=", "'invoices-output'", ",", "help", "=", "'Custom name for output file. Extension is added based on chosen format.'", ",", ")", "parser", ".", "add_argument", "(", "'--debug'", ",", "dest", "=", "'debug'", ",", "action", "=", "'store_true'", ",", "help", "=", "'Enable debug information.'", ")", "parser", ".", "add_argument", "(", "'--copy'", ",", "'-c'", ",", "dest", "=", "'copy'", ",", "help", "=", "'Copy and rename processed PDFs to specified folder.'", ")", "parser", ".", "add_argument", "(", "'--move'", ",", "'-m'", ",", "dest", "=", "'move'", ",", "help", "=", "'Move and rename processed PDFs to specified folder.'", ")", "parser", ".", "add_argument", "(", "'--filename-format'", ",", "dest", "=", "'filename'", ",", "default", "=", "\"{date} {invoice_number} {desc}.pdf\"", ",", "help", "=", "'Filename format to use when moving or copying processed PDFs.'", "'Default: \"{date} {invoice_number} {desc}.pdf\"'", ",", ")", "parser", ".", "add_argument", "(", "'--template-folder'", ",", "'-t'", ",", "dest", "=", "'template_folder'", ",", "help", "=", "'Folder containing invoice templates in yml file. Always adds built-in templates.'", ",", ")", "parser", ".", "add_argument", "(", "'--exclude-built-in-templates'", ",", "dest", "=", "'exclude_built_in_templates'", ",", "default", "=", "False", ",", "help", "=", "'Ignore built-in templates.'", ",", "action", "=", "\"store_true\"", ",", ")", "parser", ".", "add_argument", "(", "'input_files'", ",", "type", "=", "argparse", ".", "FileType", "(", "'r'", ")", ",", "nargs", "=", "'+'", ",", "help", "=", "'File or directory to analyze.'", ")", "return", "parser" ]
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_mapping[args.input_reader] output_module = output_mapping[args.output_format] templates = [] # Load templates from external folder if set. if args.template_folder: templates += read_templates(os.path.abspath(args.template_folder)) # Load internal templates, if not disabled. if not args.exclude_built_in_templates: templates += read_templates() output = [] for f in args.input_files: res = extract_data(f.name, templates=templates, input_module=input_module) if res: logger.info(res) output.append(res) if args.copy: filename = args.filename.format( date=res['date'].strftime('%Y-%m-%d'), invoice_number=res['invoice_number'], desc=res['desc'], ) shutil.copyfile(f.name, join(args.copy, filename)) if args.move: filename = args.filename.format( date=res['date'].strftime('%Y-%m-%d'), invoice_number=res['invoice_number'], desc=res['desc'], ) shutil.move(f.name, join(args.move, filename)) f.close() if output_module is not None: output_module.write_to_file(output, args.output_name)
python
def main(args=None): """Take folder or single file and analyze each.""" if args is None: parser = create_parser() args = parser.parse_args() if args.debug: logging.basicConfig(level=logging.DEBUG) else: logging.basicConfig(level=logging.INFO) input_module = input_mapping[args.input_reader] output_module = output_mapping[args.output_format] templates = [] # Load templates from external folder if set. if args.template_folder: templates += read_templates(os.path.abspath(args.template_folder)) # Load internal templates, if not disabled. if not args.exclude_built_in_templates: templates += read_templates() output = [] for f in args.input_files: res = extract_data(f.name, templates=templates, input_module=input_module) if res: logger.info(res) output.append(res) if args.copy: filename = args.filename.format( date=res['date'].strftime('%Y-%m-%d'), invoice_number=res['invoice_number'], desc=res['desc'], ) shutil.copyfile(f.name, join(args.copy, filename)) if args.move: filename = args.filename.format( date=res['date'].strftime('%Y-%m-%d'), invoice_number=res['invoice_number'], desc=res['desc'], ) shutil.move(f.name, join(args.move, filename)) f.close() if output_module is not None: output_module.write_to_file(output, args.output_name)
[ "def", "main", "(", "args", "=", "None", ")", ":", "if", "args", "is", "None", ":", "parser", "=", "create_parser", "(", ")", "args", "=", "parser", ".", "parse_args", "(", ")", "if", "args", ".", "debug", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "DEBUG", ")", "else", ":", "logging", ".", "basicConfig", "(", "level", "=", "logging", ".", "INFO", ")", "input_module", "=", "input_mapping", "[", "args", ".", "input_reader", "]", "output_module", "=", "output_mapping", "[", "args", ".", "output_format", "]", "templates", "=", "[", "]", "# Load templates from external folder if set.", "if", "args", ".", "template_folder", ":", "templates", "+=", "read_templates", "(", "os", ".", "path", ".", "abspath", "(", "args", ".", "template_folder", ")", ")", "# Load internal templates, if not disabled.", "if", "not", "args", ".", "exclude_built_in_templates", ":", "templates", "+=", "read_templates", "(", ")", "output", "=", "[", "]", "for", "f", "in", "args", ".", "input_files", ":", "res", "=", "extract_data", "(", "f", ".", "name", ",", "templates", "=", "templates", ",", "input_module", "=", "input_module", ")", "if", "res", ":", "logger", ".", "info", "(", "res", ")", "output", ".", "append", "(", "res", ")", "if", "args", ".", "copy", ":", "filename", "=", "args", ".", "filename", ".", "format", "(", "date", "=", "res", "[", "'date'", "]", ".", "strftime", "(", "'%Y-%m-%d'", ")", ",", "invoice_number", "=", "res", "[", "'invoice_number'", "]", ",", "desc", "=", "res", "[", "'desc'", "]", ",", ")", "shutil", ".", "copyfile", "(", "f", ".", "name", ",", "join", "(", "args", ".", "copy", ",", "filename", ")", ")", "if", "args", ".", "move", ":", "filename", "=", "args", ".", "filename", ".", "format", "(", "date", "=", "res", "[", "'date'", "]", ".", "strftime", "(", "'%Y-%m-%d'", ")", ",", "invoice_number", "=", "res", "[", "'invoice_number'", "]", ",", "desc", "=", "res", "[", "'desc'", "]", ",", ")", "shutil", ".", "move", "(", "f", ".", "name", ",", "join", "(", "args", ".", "move", ",", "filename", ")", ")", "f", ".", "close", "(", ")", "if", "output_module", "is", "not", "None", ":", "output_module", ".", "write_to_file", "(", "output", ",", "args", ".", "output_name", ")" ]
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 Notes ---- Do give file name to the function parameter path. Only `date`, `desc`, `amount` and `currency` are exported Examples -------- >>> from invoice2data.output import to_xml >>> to_xml.write_to_file(data, "/exported_xml/invoice.xml") >>> to_xml.write_to_file(data, "invoice.xml") """ if path.endswith('.xml'): filename = path else: filename = path + '.xml' tag_data = ET.Element('data') xml_file = open(filename, "w") i = 0 for line in data: i += 1 tag_item = ET.SubElement(tag_data, 'item') tag_date = ET.SubElement(tag_item, 'date') tag_desc = ET.SubElement(tag_item, 'desc') tag_currency = ET.SubElement(tag_item, 'currency') tag_amount = ET.SubElement(tag_item, 'amount') tag_item.set('id', str(i)) tag_date.text = line['date'].strftime('%d/%m/%Y') tag_desc.text = line['desc'] tag_currency.text = line['currency'] tag_amount.text = str(line['amount']) xml_file.write(prettify(tag_data)) xml_file.close()
python
def write_to_file(data, path): """Export extracted fields to xml Appends .xml to path if missing and generates xml file in specified directory, if not then in root Parameters ---------- data : dict Dictionary of extracted fields path : str directory to save generated xml file Notes ---- Do give file name to the function parameter path. Only `date`, `desc`, `amount` and `currency` are exported Examples -------- >>> from invoice2data.output import to_xml >>> to_xml.write_to_file(data, "/exported_xml/invoice.xml") >>> to_xml.write_to_file(data, "invoice.xml") """ if path.endswith('.xml'): filename = path else: filename = path + '.xml' tag_data = ET.Element('data') xml_file = open(filename, "w") i = 0 for line in data: i += 1 tag_item = ET.SubElement(tag_data, 'item') tag_date = ET.SubElement(tag_item, 'date') tag_desc = ET.SubElement(tag_item, 'desc') tag_currency = ET.SubElement(tag_item, 'currency') tag_amount = ET.SubElement(tag_item, 'amount') tag_item.set('id', str(i)) tag_date.text = line['date'].strftime('%d/%m/%Y') tag_desc.text = line['desc'] tag_currency.text = line['currency'] tag_amount.text = str(line['amount']) xml_file.write(prettify(tag_data)) xml_file.close()
[ "def", "write_to_file", "(", "data", ",", "path", ")", ":", "if", "path", ".", "endswith", "(", "'.xml'", ")", ":", "filename", "=", "path", "else", ":", "filename", "=", "path", "+", "'.xml'", "tag_data", "=", "ET", ".", "Element", "(", "'data'", ")", "xml_file", "=", "open", "(", "filename", ",", "\"w\"", ")", "i", "=", "0", "for", "line", "in", "data", ":", "i", "+=", "1", "tag_item", "=", "ET", ".", "SubElement", "(", "tag_data", ",", "'item'", ")", "tag_date", "=", "ET", ".", "SubElement", "(", "tag_item", ",", "'date'", ")", "tag_desc", "=", "ET", ".", "SubElement", "(", "tag_item", ",", "'desc'", ")", "tag_currency", "=", "ET", ".", "SubElement", "(", "tag_item", ",", "'currency'", ")", "tag_amount", "=", "ET", ".", "SubElement", "(", "tag_item", ",", "'amount'", ")", "tag_item", ".", "set", "(", "'id'", ",", "str", "(", "i", ")", ")", "tag_date", ".", "text", "=", "line", "[", "'date'", "]", ".", "strftime", "(", "'%d/%m/%Y'", ")", "tag_desc", ".", "text", "=", "line", "[", "'desc'", "]", "tag_currency", ".", "text", "=", "line", "[", "'currency'", "]", "tag_amount", ".", "text", "=", "str", "(", "line", "[", "'amount'", "]", ")", "xml_file", ".", "write", "(", "prettify", "(", "tag_data", ")", ")", "xml_file", ".", "close", "(", ")" ]
Export extracted fields to xml Appends .xml to path if missing and generates xml file in specified directory, if not then in root Parameters ---------- data : dict Dictionary of extracted fields path : str directory to save generated xml file Notes ---- Do give file name to the function parameter path. Only `date`, `desc`, `amount` and `currency` are exported Examples -------- >>> from invoice2data.output import to_xml >>> to_xml.write_to_file(data, "/exported_xml/invoice.xml") >>> to_xml.write_to_file(data, "invoice.xml")
[ "Export", "extracted", "fields", "to", "xml" ]
d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20
https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/output/to_xml.py#L12-L59
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 ------- output : Instance of `InvoiceTemplate` template which match based on keywords Examples -------- >>> read_template("home/duskybomb/invoice-templates/") InvoiceTemplate([('issuer', 'OYO'), ('fields', OrderedDict([('amount', 'GrandTotalRs(\\d+)'), ('date', 'Date:(\\d{1,2}\\/\\d{1,2}\\/\\d{1,4})'), ('invoice_number', '([A-Z0-9]+)CashatHotel')])), ('keywords', ['OYO', 'Oravel', 'Stays']), ('options', OrderedDict([('currency', 'INR'), ('decimal_separator', '.'), ('remove_whitespace', True)])), ('template_name', 'com.oyo.invoice.yml')]) After reading the template you can use the result as an instance of `InvoiceTemplate` to extract fields from `extract_data()` >>> my_template = InvoiceTemplate([('issuer', 'OYO'), ('fields', OrderedDict([('amount', 'GrandTotalRs(\\d+)'), ('date', 'Date:(\\d{1,2}\\/\\d{1,2}\\/\\d{1,4})'), ('invoice_number', '([A-Z0-9]+)CashatHotel')])), ('keywords', ['OYO', 'Oravel', 'Stays']), ('options', OrderedDict([('currency', 'INR'), ('decimal_separator', '.'), ('remove_whitespace', True)])), ('template_name', 'com.oyo.invoice.yml')]) >>> extract_data("invoice2data/test/pdfs/oyo.pdf", my_template, pdftotext) {'issuer': 'OYO', 'amount': 1939.0, 'date': datetime.datetime(2017, 12, 31, 0, 0), 'invoice_number': 'IBZY2087', 'currency': 'INR', 'desc': 'Invoice IBZY2087 from OYO'} """ output = [] if folder is None: folder = pkg_resources.resource_filename(__name__, 'templates') for path, subdirs, files in os.walk(folder): for name in sorted(files): if name.endswith('.yml'): with open(os.path.join(path, name), 'rb') as f: encoding = chardet.detect(f.read())['encoding'] with codecs.open(os.path.join(path, name), encoding=encoding) as template_file: tpl = ordered_load(template_file.read()) tpl['template_name'] = name # Test if all required fields are in template: assert 'keywords' in tpl.keys(), 'Missing keywords field.' # Keywords as list, if only one. if type(tpl['keywords']) is not list: tpl['keywords'] = [tpl['keywords']] output.append(InvoiceTemplate(tpl)) return output
python
def read_templates(folder=None): """ Load yaml templates from template folder. Return list of dicts. Use built-in templates if no folder is set. Parameters ---------- folder : str user defined folder where they stores their files, if None uses built-in templates Returns ------- output : Instance of `InvoiceTemplate` template which match based on keywords Examples -------- >>> read_template("home/duskybomb/invoice-templates/") InvoiceTemplate([('issuer', 'OYO'), ('fields', OrderedDict([('amount', 'GrandTotalRs(\\d+)'), ('date', 'Date:(\\d{1,2}\\/\\d{1,2}\\/\\d{1,4})'), ('invoice_number', '([A-Z0-9]+)CashatHotel')])), ('keywords', ['OYO', 'Oravel', 'Stays']), ('options', OrderedDict([('currency', 'INR'), ('decimal_separator', '.'), ('remove_whitespace', True)])), ('template_name', 'com.oyo.invoice.yml')]) After reading the template you can use the result as an instance of `InvoiceTemplate` to extract fields from `extract_data()` >>> my_template = InvoiceTemplate([('issuer', 'OYO'), ('fields', OrderedDict([('amount', 'GrandTotalRs(\\d+)'), ('date', 'Date:(\\d{1,2}\\/\\d{1,2}\\/\\d{1,4})'), ('invoice_number', '([A-Z0-9]+)CashatHotel')])), ('keywords', ['OYO', 'Oravel', 'Stays']), ('options', OrderedDict([('currency', 'INR'), ('decimal_separator', '.'), ('remove_whitespace', True)])), ('template_name', 'com.oyo.invoice.yml')]) >>> extract_data("invoice2data/test/pdfs/oyo.pdf", my_template, pdftotext) {'issuer': 'OYO', 'amount': 1939.0, 'date': datetime.datetime(2017, 12, 31, 0, 0), 'invoice_number': 'IBZY2087', 'currency': 'INR', 'desc': 'Invoice IBZY2087 from OYO'} """ output = [] if folder is None: folder = pkg_resources.resource_filename(__name__, 'templates') for path, subdirs, files in os.walk(folder): for name in sorted(files): if name.endswith('.yml'): with open(os.path.join(path, name), 'rb') as f: encoding = chardet.detect(f.read())['encoding'] with codecs.open(os.path.join(path, name), encoding=encoding) as template_file: tpl = ordered_load(template_file.read()) tpl['template_name'] = name # Test if all required fields are in template: assert 'keywords' in tpl.keys(), 'Missing keywords field.' # Keywords as list, if only one. if type(tpl['keywords']) is not list: tpl['keywords'] = [tpl['keywords']] output.append(InvoiceTemplate(tpl)) return output
[ "def", "read_templates", "(", "folder", "=", "None", ")", ":", "output", "=", "[", "]", "if", "folder", "is", "None", ":", "folder", "=", "pkg_resources", ".", "resource_filename", "(", "__name__", ",", "'templates'", ")", "for", "path", ",", "subdirs", ",", "files", "in", "os", ".", "walk", "(", "folder", ")", ":", "for", "name", "in", "sorted", "(", "files", ")", ":", "if", "name", ".", "endswith", "(", "'.yml'", ")", ":", "with", "open", "(", "os", ".", "path", ".", "join", "(", "path", ",", "name", ")", ",", "'rb'", ")", "as", "f", ":", "encoding", "=", "chardet", ".", "detect", "(", "f", ".", "read", "(", ")", ")", "[", "'encoding'", "]", "with", "codecs", ".", "open", "(", "os", ".", "path", ".", "join", "(", "path", ",", "name", ")", ",", "encoding", "=", "encoding", ")", "as", "template_file", ":", "tpl", "=", "ordered_load", "(", "template_file", ".", "read", "(", ")", ")", "tpl", "[", "'template_name'", "]", "=", "name", "# Test if all required fields are in template:", "assert", "'keywords'", "in", "tpl", ".", "keys", "(", ")", ",", "'Missing keywords field.'", "# Keywords as list, if only one.", "if", "type", "(", "tpl", "[", "'keywords'", "]", ")", "is", "not", "list", ":", "tpl", "[", "'keywords'", "]", "=", "[", "tpl", "[", "'keywords'", "]", "]", "output", ".", "append", "(", "InvoiceTemplate", "(", "tpl", ")", ")", "return", "output" ]
Load yaml templates from template folder. Return list of dicts. Use built-in templates if no folder is set. Parameters ---------- folder : str user defined folder where they stores their files, if None uses built-in templates Returns ------- output : Instance of `InvoiceTemplate` template which match based on keywords Examples -------- >>> read_template("home/duskybomb/invoice-templates/") InvoiceTemplate([('issuer', 'OYO'), ('fields', OrderedDict([('amount', 'GrandTotalRs(\\d+)'), ('date', 'Date:(\\d{1,2}\\/\\d{1,2}\\/\\d{1,4})'), ('invoice_number', '([A-Z0-9]+)CashatHotel')])), ('keywords', ['OYO', 'Oravel', 'Stays']), ('options', OrderedDict([('currency', 'INR'), ('decimal_separator', '.'), ('remove_whitespace', True)])), ('template_name', 'com.oyo.invoice.yml')]) After reading the template you can use the result as an instance of `InvoiceTemplate` to extract fields from `extract_data()` >>> my_template = InvoiceTemplate([('issuer', 'OYO'), ('fields', OrderedDict([('amount', 'GrandTotalRs(\\d+)'), ('date', 'Date:(\\d{1,2}\\/\\d{1,2}\\/\\d{1,4})'), ('invoice_number', '([A-Z0-9]+)CashatHotel')])), ('keywords', ['OYO', 'Oravel', 'Stays']), ('options', OrderedDict([('currency', 'INR'), ('decimal_separator', '.'), ('remove_whitespace', True)])), ('template_name', 'com.oyo.invoice.yml')]) >>> extract_data("invoice2data/test/pdfs/oyo.pdf", my_template, pdftotext) {'issuer': 'OYO', 'amount': 1939.0, 'date': datetime.datetime(2017, 12, 31, 0, 0), 'invoice_number': 'IBZY2087', 'currency': 'INR', 'desc': 'Invoice IBZY2087 from OYO'}
[ "Load", "yaml", "templates", "from", "template", "folder", ".", "Return", "list", "of", "dicts", "." ]
d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20
https://github.com/invoice-x/invoice2data/blob/d97fdc5db9c1844fd77fa64f8ea7c42fefd0ba20/src/invoice2data/extract/loader.py#L39-L99
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 reload(sys) # noqa: F821 sys.setdefaultencoding('utf8') except ImportError: from io import StringIO from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.converter import TextConverter from pdfminer.layout import LAParams from pdfminer.pdfpage import PDFPage rsrcmgr = PDFResourceManager() retstr = StringIO() codec = 'utf-8' laparams = LAParams() laparams.all_texts = True device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams) with open(path, 'rb') as fp: interpreter = PDFPageInterpreter(rsrcmgr, device) password = "" maxpages = 0 caching = True pagenos = set() pages = PDFPage.get_pages( fp, pagenos, maxpages=maxpages, password=password, caching=caching, check_extractable=True, ) for page in pages: interpreter.process_page(page) device.close() str = retstr.getvalue() retstr.close() return str.encode('utf-8')
python
def to_text(path): """Wrapper around `pdfminer`. Parameters ---------- path : str path of electronic invoice in PDF Returns ------- str : str returns extracted text from pdf """ try: # python 2 from StringIO import StringIO import sys reload(sys) # noqa: F821 sys.setdefaultencoding('utf8') except ImportError: from io import StringIO from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter from pdfminer.converter import TextConverter from pdfminer.layout import LAParams from pdfminer.pdfpage import PDFPage rsrcmgr = PDFResourceManager() retstr = StringIO() codec = 'utf-8' laparams = LAParams() laparams.all_texts = True device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams) with open(path, 'rb') as fp: interpreter = PDFPageInterpreter(rsrcmgr, device) password = "" maxpages = 0 caching = True pagenos = set() pages = PDFPage.get_pages( fp, pagenos, maxpages=maxpages, password=password, caching=caching, check_extractable=True, ) for page in pages: interpreter.process_page(page) device.close() str = retstr.getvalue() retstr.close() return str.encode('utf-8')
[ "def", "to_text", "(", "path", ")", ":", "try", ":", "# python 2", "from", "StringIO", "import", "StringIO", "import", "sys", "reload", "(", "sys", ")", "# noqa: F821", "sys", ".", "setdefaultencoding", "(", "'utf8'", ")", "except", "ImportError", ":", "from", "io", "import", "StringIO", "from", "pdfminer", ".", "pdfinterp", "import", "PDFResourceManager", ",", "PDFPageInterpreter", "from", "pdfminer", ".", "converter", "import", "TextConverter", "from", "pdfminer", ".", "layout", "import", "LAParams", "from", "pdfminer", ".", "pdfpage", "import", "PDFPage", "rsrcmgr", "=", "PDFResourceManager", "(", ")", "retstr", "=", "StringIO", "(", ")", "codec", "=", "'utf-8'", "laparams", "=", "LAParams", "(", ")", "laparams", ".", "all_texts", "=", "True", "device", "=", "TextConverter", "(", "rsrcmgr", ",", "retstr", ",", "codec", "=", "codec", ",", "laparams", "=", "laparams", ")", "with", "open", "(", "path", ",", "'rb'", ")", "as", "fp", ":", "interpreter", "=", "PDFPageInterpreter", "(", "rsrcmgr", ",", "device", ")", "password", "=", "\"\"", "maxpages", "=", "0", "caching", "=", "True", "pagenos", "=", "set", "(", ")", "pages", "=", "PDFPage", ".", "get_pages", "(", "fp", ",", "pagenos", ",", "maxpages", "=", "maxpages", ",", "password", "=", "password", ",", "caching", "=", "caching", ",", "check_extractable", "=", "True", ",", ")", "for", "page", "in", "pages", ":", "interpreter", ".", "process_page", "(", "page", ")", "device", ".", "close", "(", ")", "str", "=", "retstr", ".", "getvalue", "(", ")", "retstr", ".", "close", "(", ")", "return", "str", ".", "encode", "(", "'utf-8'", ")" ]
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 nearest 2**n. Any results involving dummy parameters could indicate a problem with the model runs. Arguments --------- problem: dict The problem definition X: numpy.matrix The NumPy matrix containing the model inputs Y: numpy.array The NumPy array containing the model outputs second_order: bool, default=False Include interaction effects print_to_console: bool, default=False Print results directly to console Returns ------- Si: dict A dictionary of sensitivity indices, including main effects ``ME``, and interaction effects ``IE`` (if ``second_order`` is True) Examples -------- >>> X = sample(problem) >>> Y = X[:, 0] + (0.1 * X[:, 1]) + ((1.2 * X[:, 2]) * (0.2 + X[:, 0])) >>> analyze(problem, X, Y, second_order=True, print_to_console=True) """ if seed: np.random.seed(seed) problem = extend_bounds(problem) num_vars = problem['num_vars'] X = generate_contrast(problem) main_effect = (1. / (2 * num_vars)) * np.dot(Y, X) Si = ResultDict((k, [None] * num_vars) for k in ['names', 'ME']) Si['ME'] = main_effect Si['names'] = problem['names'] if print_to_console: print("Parameter ME") for j in range(num_vars): print("%s %f" % (problem['names'][j], Si['ME'][j])) if second_order: interaction_names, interaction_effects = interactions(problem, Y, print_to_console) Si['interaction_names'] = interaction_names Si['IE'] = interaction_effects Si.to_df = MethodType(to_df, Si) return Si
python
def analyze(problem, X, Y, second_order=False, print_to_console=False, seed=None): """Perform a fractional factorial analysis Returns a dictionary with keys 'ME' (main effect) and 'IE' (interaction effect). The techniques bulks out the number of parameters with dummy parameters to the nearest 2**n. Any results involving dummy parameters could indicate a problem with the model runs. Arguments --------- problem: dict The problem definition X: numpy.matrix The NumPy matrix containing the model inputs Y: numpy.array The NumPy array containing the model outputs second_order: bool, default=False Include interaction effects print_to_console: bool, default=False Print results directly to console Returns ------- Si: dict A dictionary of sensitivity indices, including main effects ``ME``, and interaction effects ``IE`` (if ``second_order`` is True) Examples -------- >>> X = sample(problem) >>> Y = X[:, 0] + (0.1 * X[:, 1]) + ((1.2 * X[:, 2]) * (0.2 + X[:, 0])) >>> analyze(problem, X, Y, second_order=True, print_to_console=True) """ if seed: np.random.seed(seed) problem = extend_bounds(problem) num_vars = problem['num_vars'] X = generate_contrast(problem) main_effect = (1. / (2 * num_vars)) * np.dot(Y, X) Si = ResultDict((k, [None] * num_vars) for k in ['names', 'ME']) Si['ME'] = main_effect Si['names'] = problem['names'] if print_to_console: print("Parameter ME") for j in range(num_vars): print("%s %f" % (problem['names'][j], Si['ME'][j])) if second_order: interaction_names, interaction_effects = interactions(problem, Y, print_to_console) Si['interaction_names'] = interaction_names Si['IE'] = interaction_effects Si.to_df = MethodType(to_df, Si) return Si
[ "def", "analyze", "(", "problem", ",", "X", ",", "Y", ",", "second_order", "=", "False", ",", "print_to_console", "=", "False", ",", "seed", "=", "None", ")", ":", "if", "seed", ":", "np", ".", "random", ".", "seed", "(", "seed", ")", "problem", "=", "extend_bounds", "(", "problem", ")", "num_vars", "=", "problem", "[", "'num_vars'", "]", "X", "=", "generate_contrast", "(", "problem", ")", "main_effect", "=", "(", "1.", "/", "(", "2", "*", "num_vars", ")", ")", "*", "np", ".", "dot", "(", "Y", ",", "X", ")", "Si", "=", "ResultDict", "(", "(", "k", ",", "[", "None", "]", "*", "num_vars", ")", "for", "k", "in", "[", "'names'", ",", "'ME'", "]", ")", "Si", "[", "'ME'", "]", "=", "main_effect", "Si", "[", "'names'", "]", "=", "problem", "[", "'names'", "]", "if", "print_to_console", ":", "print", "(", "\"Parameter ME\"", ")", "for", "j", "in", "range", "(", "num_vars", ")", ":", "print", "(", "\"%s %f\"", "%", "(", "problem", "[", "'names'", "]", "[", "j", "]", ",", "Si", "[", "'ME'", "]", "[", "j", "]", ")", ")", "if", "second_order", ":", "interaction_names", ",", "interaction_effects", "=", "interactions", "(", "problem", ",", "Y", ",", "print_to_console", ")", "Si", "[", "'interaction_names'", "]", "=", "interaction_names", "Si", "[", "'IE'", "]", "=", "interaction_effects", "Si", ".", "to_df", "=", "MethodType", "(", "to_df", ",", "Si", ")", "return", "Si" ]
Perform a fractional factorial analysis Returns a dictionary with keys 'ME' (main effect) and 'IE' (interaction effect). The techniques bulks out the number of parameters with dummy parameters to the nearest 2**n. Any results involving dummy parameters could indicate a problem with the model runs. Arguments --------- problem: dict The problem definition X: numpy.matrix The NumPy matrix containing the model inputs Y: numpy.array The NumPy array containing the model outputs second_order: bool, default=False Include interaction effects print_to_console: bool, default=False Print results directly to console Returns ------- Si: dict A dictionary of sensitivity indices, including main effects ``ME``, and interaction effects ``IE`` (if ``second_order`` is True) Examples -------- >>> X = sample(problem) >>> Y = X[:, 0] + (0.1 * X[:, 1]) + ((1.2 * X[:, 2]) * (0.2 + X[:, 0])) >>> analyze(problem, X, Y, second_order=True, print_to_console=True)
[ "Perform", "a", "fractional", "factorial", "analysis" ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/analyze/ff.py#L18-L81
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. ''' names = self['names'] main_effect = self['ME'] interactions = self.get('IE', None) inter_effect = None if interactions: interaction_names = self.get('interaction_names') names = [name for name in names if not isinstance(name, list)] inter_effect = pd.DataFrame({'IE': interactions}, index=interaction_names) main_effect = pd.DataFrame({'ME': main_effect}, index=names) return main_effect, inter_effect
python
def to_df(self): '''Conversion method to Pandas DataFrame. To be attached to ResultDict. Returns ------- main_effect, inter_effect: tuple A tuple of DataFrames for main effects and interaction effects. The second element (for interactions) will be `None` if not available. ''' names = self['names'] main_effect = self['ME'] interactions = self.get('IE', None) inter_effect = None if interactions: interaction_names = self.get('interaction_names') names = [name for name in names if not isinstance(name, list)] inter_effect = pd.DataFrame({'IE': interactions}, index=interaction_names) main_effect = pd.DataFrame({'ME': main_effect}, index=names) return main_effect, inter_effect
[ "def", "to_df", "(", "self", ")", ":", "names", "=", "self", "[", "'names'", "]", "main_effect", "=", "self", "[", "'ME'", "]", "interactions", "=", "self", ".", "get", "(", "'IE'", ",", "None", ")", "inter_effect", "=", "None", "if", "interactions", ":", "interaction_names", "=", "self", ".", "get", "(", "'interaction_names'", ")", "names", "=", "[", "name", "for", "name", "in", "names", "if", "not", "isinstance", "(", "name", ",", "list", ")", "]", "inter_effect", "=", "pd", ".", "DataFrame", "(", "{", "'IE'", ":", "interactions", "}", ",", "index", "=", "interaction_names", ")", "main_effect", "=", "pd", ".", "DataFrame", "(", "{", "'ME'", ":", "main_effect", "}", ",", "index", "=", "names", ")", "return", "main_effect", ",", "inter_effect" ]
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 array containing the model outputs print_to_console: bool, default=False Print results directly to console Returns ------- ie_names: list The names of the interaction pairs IE: list The sensitivity indices for the pairwise interactions """ names = problem['names'] num_vars = problem['num_vars'] X = generate_contrast(problem) ie_names = [] IE = [] for col in range(X.shape[1]): for col_2 in range(col): x = X[:, col] * X[:, col_2] var_names = (names[col_2], names[col]) ie_names.append(var_names) IE.append((1. / (2 * num_vars)) * np.dot(Y, x)) if print_to_console: [print('%s %f' % (n, i)) for (n, i) in zip(ie_names, IE)] return ie_names, IE
python
def interactions(problem, Y, print_to_console=False): """Computes the second order effects Computes the second order effects (interactions) between all combinations of pairs of input factors Arguments --------- problem: dict The problem definition Y: numpy.array The NumPy array containing the model outputs print_to_console: bool, default=False Print results directly to console Returns ------- ie_names: list The names of the interaction pairs IE: list The sensitivity indices for the pairwise interactions """ names = problem['names'] num_vars = problem['num_vars'] X = generate_contrast(problem) ie_names = [] IE = [] for col in range(X.shape[1]): for col_2 in range(col): x = X[:, col] * X[:, col_2] var_names = (names[col_2], names[col]) ie_names.append(var_names) IE.append((1. / (2 * num_vars)) * np.dot(Y, x)) if print_to_console: [print('%s %f' % (n, i)) for (n, i) in zip(ie_names, IE)] return ie_names, IE
[ "def", "interactions", "(", "problem", ",", "Y", ",", "print_to_console", "=", "False", ")", ":", "names", "=", "problem", "[", "'names'", "]", "num_vars", "=", "problem", "[", "'num_vars'", "]", "X", "=", "generate_contrast", "(", "problem", ")", "ie_names", "=", "[", "]", "IE", "=", "[", "]", "for", "col", "in", "range", "(", "X", ".", "shape", "[", "1", "]", ")", ":", "for", "col_2", "in", "range", "(", "col", ")", ":", "x", "=", "X", "[", ":", ",", "col", "]", "*", "X", "[", ":", ",", "col_2", "]", "var_names", "=", "(", "names", "[", "col_2", "]", ",", "names", "[", "col", "]", ")", "ie_names", ".", "append", "(", "var_names", ")", "IE", ".", "append", "(", "(", "1.", "/", "(", "2", "*", "num_vars", ")", ")", "*", "np", ".", "dot", "(", "Y", ",", "x", ")", ")", "if", "print_to_console", ":", "[", "print", "(", "'%s %f'", "%", "(", "n", ",", "i", ")", ")", "for", "(", "n", ",", "i", ")", "in", "zip", "(", "ie_names", ",", "IE", ")", "]", "return", "ie_names", ",", "IE" ]
Computes the second order effects Computes the second order effects (interactions) between all combinations of pairs of input factors Arguments --------- problem: dict The problem definition Y: numpy.array The NumPy array containing the model outputs print_to_console: bool, default=False Print results directly to console Returns ------- ie_names: list The names of the interaction pairs IE: list The sensitivity indices for the pairwise interactions
[ "Computes", "the", "second", "order", "effects" ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/analyze/ff.py#L109-L150
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_packages(path=pkg.__path__) if modname not in ['common_args', 'directions', 'sobol_sequence']] return methods
python
def avail_approaches(pkg): '''Create list of available modules. Arguments --------- pkg : module module to inspect Returns --------- method : list A list of available submodules ''' methods = [modname for importer, modname, ispkg in pkgutil.walk_packages(path=pkg.__path__) if modname not in ['common_args', 'directions', 'sobol_sequence']] return methods
[ "def", "avail_approaches", "(", "pkg", ")", ":", "methods", "=", "[", "modname", "for", "importer", ",", "modname", ",", "ispkg", "in", "pkgutil", ".", "walk_packages", "(", "path", "=", "pkg", ".", "__path__", ")", "if", "modname", "not", "in", "[", "'common_args'", ",", "'directions'", ",", "'sobol_sequence'", "]", "]", "return", "methods" ]
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 of samples ''' # Check bounds are legal (upper bound is greater than lower bound) b = np.array(bounds) lower_bounds = b[:, 0] upper_bounds = b[:, 1] if np.any(lower_bounds >= upper_bounds): raise ValueError("Bounds are not legal") # This scales the samples in-place, by using the optional output # argument for the numpy ufunctions # The calculation is equivalent to: # sample * (upper_bound - lower_bound) + lower_bound np.add(np.multiply(params, (upper_bounds - lower_bounds), out=params), lower_bounds, out=params)
python
def scale_samples(params, bounds): '''Rescale samples in 0-to-1 range to arbitrary bounds Arguments --------- bounds : list list of lists of dimensions `num_params`-by-2 params : numpy.ndarray numpy array of dimensions `num_params`-by-:math:`N`, where :math:`N` is the number of samples ''' # Check bounds are legal (upper bound is greater than lower bound) b = np.array(bounds) lower_bounds = b[:, 0] upper_bounds = b[:, 1] if np.any(lower_bounds >= upper_bounds): raise ValueError("Bounds are not legal") # This scales the samples in-place, by using the optional output # argument for the numpy ufunctions # The calculation is equivalent to: # sample * (upper_bound - lower_bound) + lower_bound np.add(np.multiply(params, (upper_bounds - lower_bounds), out=params), lower_bounds, out=params)
[ "def", "scale_samples", "(", "params", ",", "bounds", ")", ":", "# Check bounds are legal (upper bound is greater than lower bound)", "b", "=", "np", ".", "array", "(", "bounds", ")", "lower_bounds", "=", "b", "[", ":", ",", "0", "]", "upper_bounds", "=", "b", "[", ":", ",", "1", "]", "if", "np", ".", "any", "(", "lower_bounds", ">=", "upper_bounds", ")", ":", "raise", "ValueError", "(", "\"Bounds are not legal\"", ")", "# This scales the samples in-place, by using the optional output", "# argument for the numpy ufunctions", "# The calculation is equivalent to:", "# sample * (upper_bound - lower_bound) + lower_bound", "np", ".", "add", "(", "np", ".", "multiply", "(", "params", ",", "(", "upper_bounds", "-", "lower_bounds", ")", ",", "out", "=", "params", ")", ",", "lower_bounds", ",", "out", "=", "params", ")" ]
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 samples dists : list list of distributions, one for each parameter unif: uniform with lower and upper bounds triang: triangular with width (scale) and location of peak location of peak is in percentage of width lower bound assumed to be zero norm: normal distribution with mean and standard deviation lognorm: lognormal with ln-space mean and standard deviation """ b = np.array(bounds) # initializing matrix for converted values conv_params = np.zeros_like(params) # loop over the parameters for i in range(conv_params.shape[1]): # setting first and second arguments for distributions b1 = b[i][0] b2 = b[i][1] if dists[i] == 'triang': # checking for correct parameters if b1 <= 0 or b2 <= 0 or b2 >= 1: raise ValueError('''Triangular distribution: Scale must be greater than zero; peak on interval [0,1]''') else: conv_params[:, i] = sp.stats.triang.ppf( params[:, i], c=b2, scale=b1, loc=0) elif dists[i] == 'unif': if b1 >= b2: raise ValueError('''Uniform distribution: lower bound must be less than upper bound''') else: conv_params[:, i] = params[:, i] * (b2 - b1) + b1 elif dists[i] == 'norm': if b2 <= 0: raise ValueError('''Normal distribution: stdev must be > 0''') else: conv_params[:, i] = sp.stats.norm.ppf( params[:, i], loc=b1, scale=b2) # lognormal distribution (ln-space, not base-10) # paramters are ln-space mean and standard deviation elif dists[i] == 'lognorm': # checking for valid parameters if b2 <= 0: raise ValueError( '''Lognormal distribution: stdev must be > 0''') else: conv_params[:, i] = np.exp( sp.stats.norm.ppf(params[:, i], loc=b1, scale=b2)) else: valid_dists = ['unif', 'triang', 'norm', 'lognorm'] raise ValueError('Distributions: choose one of %s' % ", ".join(valid_dists)) return conv_params
python
def nonuniform_scale_samples(params, bounds, dists): """Rescale samples in 0-to-1 range to other distributions Arguments --------- problem : dict problem definition including bounds params : numpy.ndarray numpy array of dimensions num_params-by-N, where N is the number of samples dists : list list of distributions, one for each parameter unif: uniform with lower and upper bounds triang: triangular with width (scale) and location of peak location of peak is in percentage of width lower bound assumed to be zero norm: normal distribution with mean and standard deviation lognorm: lognormal with ln-space mean and standard deviation """ b = np.array(bounds) # initializing matrix for converted values conv_params = np.zeros_like(params) # loop over the parameters for i in range(conv_params.shape[1]): # setting first and second arguments for distributions b1 = b[i][0] b2 = b[i][1] if dists[i] == 'triang': # checking for correct parameters if b1 <= 0 or b2 <= 0 or b2 >= 1: raise ValueError('''Triangular distribution: Scale must be greater than zero; peak on interval [0,1]''') else: conv_params[:, i] = sp.stats.triang.ppf( params[:, i], c=b2, scale=b1, loc=0) elif dists[i] == 'unif': if b1 >= b2: raise ValueError('''Uniform distribution: lower bound must be less than upper bound''') else: conv_params[:, i] = params[:, i] * (b2 - b1) + b1 elif dists[i] == 'norm': if b2 <= 0: raise ValueError('''Normal distribution: stdev must be > 0''') else: conv_params[:, i] = sp.stats.norm.ppf( params[:, i], loc=b1, scale=b2) # lognormal distribution (ln-space, not base-10) # paramters are ln-space mean and standard deviation elif dists[i] == 'lognorm': # checking for valid parameters if b2 <= 0: raise ValueError( '''Lognormal distribution: stdev must be > 0''') else: conv_params[:, i] = np.exp( sp.stats.norm.ppf(params[:, i], loc=b1, scale=b2)) else: valid_dists = ['unif', 'triang', 'norm', 'lognorm'] raise ValueError('Distributions: choose one of %s' % ", ".join(valid_dists)) return conv_params
[ "def", "nonuniform_scale_samples", "(", "params", ",", "bounds", ",", "dists", ")", ":", "b", "=", "np", ".", "array", "(", "bounds", ")", "# initializing matrix for converted values", "conv_params", "=", "np", ".", "zeros_like", "(", "params", ")", "# loop over the parameters", "for", "i", "in", "range", "(", "conv_params", ".", "shape", "[", "1", "]", ")", ":", "# setting first and second arguments for distributions", "b1", "=", "b", "[", "i", "]", "[", "0", "]", "b2", "=", "b", "[", "i", "]", "[", "1", "]", "if", "dists", "[", "i", "]", "==", "'triang'", ":", "# checking for correct parameters", "if", "b1", "<=", "0", "or", "b2", "<=", "0", "or", "b2", ">=", "1", ":", "raise", "ValueError", "(", "'''Triangular distribution: Scale must be\n greater than zero; peak on interval [0,1]'''", ")", "else", ":", "conv_params", "[", ":", ",", "i", "]", "=", "sp", ".", "stats", ".", "triang", ".", "ppf", "(", "params", "[", ":", ",", "i", "]", ",", "c", "=", "b2", ",", "scale", "=", "b1", ",", "loc", "=", "0", ")", "elif", "dists", "[", "i", "]", "==", "'unif'", ":", "if", "b1", ">=", "b2", ":", "raise", "ValueError", "(", "'''Uniform distribution: lower bound\n must be less than upper bound'''", ")", "else", ":", "conv_params", "[", ":", ",", "i", "]", "=", "params", "[", ":", ",", "i", "]", "*", "(", "b2", "-", "b1", ")", "+", "b1", "elif", "dists", "[", "i", "]", "==", "'norm'", ":", "if", "b2", "<=", "0", ":", "raise", "ValueError", "(", "'''Normal distribution: stdev must be > 0'''", ")", "else", ":", "conv_params", "[", ":", ",", "i", "]", "=", "sp", ".", "stats", ".", "norm", ".", "ppf", "(", "params", "[", ":", ",", "i", "]", ",", "loc", "=", "b1", ",", "scale", "=", "b2", ")", "# lognormal distribution (ln-space, not base-10)", "# paramters are ln-space mean and standard deviation", "elif", "dists", "[", "i", "]", "==", "'lognorm'", ":", "# checking for valid parameters", "if", "b2", "<=", "0", ":", "raise", "ValueError", "(", "'''Lognormal distribution: stdev must be > 0'''", ")", "else", ":", "conv_params", "[", ":", ",", "i", "]", "=", "np", ".", "exp", "(", "sp", ".", "stats", ".", "norm", ".", "ppf", "(", "params", "[", ":", ",", "i", "]", ",", "loc", "=", "b1", ",", "scale", "=", "b2", ")", ")", "else", ":", "valid_dists", "=", "[", "'unif'", ",", "'triang'", ",", "'norm'", ",", "'lognorm'", "]", "raise", "ValueError", "(", "'Distributions: choose one of %s'", "%", "\", \"", ".", "join", "(", "valid_dists", ")", ")", "return", "conv_params" ]
Rescale samples in 0-to-1 range to other distributions Arguments --------- problem : dict problem definition including bounds params : numpy.ndarray numpy array of dimensions num_params-by-N, where N is the number of samples dists : list list of distributions, one for each parameter unif: uniform with lower and upper bounds triang: triangular with width (scale) and location of peak location of peak is in percentage of width lower bound assumed to be zero norm: normal distribution with mean and standard deviation lognorm: lognormal with ln-space mean and standard deviation
[ "Rescale", "samples", "in", "0", "-", "to", "-", "1", "range", "to", "other", "distributions" ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/util/__init__.py#L96-L165
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: - names - the names of the parameters - bounds - a list of lists of lower and upper bounds - num_vars - a scalar indicating the number of variables (the length of names) - groups - a list of group names (strings) for each variable - dists - a list of distributions for the problem, None if not specified or all uniform Arguments --------- filename : str The path to the parameter file delimiter : str, default=None The delimiter used in the file to distinguish between columns """ names = [] bounds = [] groups = [] dists = [] num_vars = 0 fieldnames = ['name', 'lower_bound', 'upper_bound', 'group', 'dist'] with open(filename, 'rU') as csvfile: dialect = csv.Sniffer().sniff(csvfile.read(1024), delimiters=delimiter) csvfile.seek(0) reader = csv.DictReader( csvfile, fieldnames=fieldnames, dialect=dialect) for row in reader: if row['name'].strip().startswith('#'): pass else: num_vars += 1 names.append(row['name']) bounds.append( [float(row['lower_bound']), float(row['upper_bound'])]) # If the fourth column does not contain a group name, use # the parameter name if row['group'] is None: groups.append(row['name']) elif row['group'] is 'NA': groups.append(row['name']) else: groups.append(row['group']) # If the fifth column does not contain a distribution # use uniform if row['dist'] is None: dists.append('unif') else: dists.append(row['dist']) if groups == names: groups = None elif len(set(groups)) == 1: raise ValueError('''Only one group defined, results will not be meaningful''') # setting dists to none if all are uniform # because non-uniform scaling is not needed if all([d == 'unif' for d in dists]): dists = None return {'names': names, 'bounds': bounds, 'num_vars': num_vars, 'groups': groups, 'dists': dists}
python
def read_param_file(filename, delimiter=None): """Unpacks a parameter file into a dictionary Reads a parameter file of format:: Param1,0,1,Group1,dist1 Param2,0,1,Group2,dist2 Param3,0,1,Group3,dist3 (Group and Dist columns are optional) Returns a dictionary containing: - names - the names of the parameters - bounds - a list of lists of lower and upper bounds - num_vars - a scalar indicating the number of variables (the length of names) - groups - a list of group names (strings) for each variable - dists - a list of distributions for the problem, None if not specified or all uniform Arguments --------- filename : str The path to the parameter file delimiter : str, default=None The delimiter used in the file to distinguish between columns """ names = [] bounds = [] groups = [] dists = [] num_vars = 0 fieldnames = ['name', 'lower_bound', 'upper_bound', 'group', 'dist'] with open(filename, 'rU') as csvfile: dialect = csv.Sniffer().sniff(csvfile.read(1024), delimiters=delimiter) csvfile.seek(0) reader = csv.DictReader( csvfile, fieldnames=fieldnames, dialect=dialect) for row in reader: if row['name'].strip().startswith('#'): pass else: num_vars += 1 names.append(row['name']) bounds.append( [float(row['lower_bound']), float(row['upper_bound'])]) # If the fourth column does not contain a group name, use # the parameter name if row['group'] is None: groups.append(row['name']) elif row['group'] is 'NA': groups.append(row['name']) else: groups.append(row['group']) # If the fifth column does not contain a distribution # use uniform if row['dist'] is None: dists.append('unif') else: dists.append(row['dist']) if groups == names: groups = None elif len(set(groups)) == 1: raise ValueError('''Only one group defined, results will not be meaningful''') # setting dists to none if all are uniform # because non-uniform scaling is not needed if all([d == 'unif' for d in dists]): dists = None return {'names': names, 'bounds': bounds, 'num_vars': num_vars, 'groups': groups, 'dists': dists}
[ "def", "read_param_file", "(", "filename", ",", "delimiter", "=", "None", ")", ":", "names", "=", "[", "]", "bounds", "=", "[", "]", "groups", "=", "[", "]", "dists", "=", "[", "]", "num_vars", "=", "0", "fieldnames", "=", "[", "'name'", ",", "'lower_bound'", ",", "'upper_bound'", ",", "'group'", ",", "'dist'", "]", "with", "open", "(", "filename", ",", "'rU'", ")", "as", "csvfile", ":", "dialect", "=", "csv", ".", "Sniffer", "(", ")", ".", "sniff", "(", "csvfile", ".", "read", "(", "1024", ")", ",", "delimiters", "=", "delimiter", ")", "csvfile", ".", "seek", "(", "0", ")", "reader", "=", "csv", ".", "DictReader", "(", "csvfile", ",", "fieldnames", "=", "fieldnames", ",", "dialect", "=", "dialect", ")", "for", "row", "in", "reader", ":", "if", "row", "[", "'name'", "]", ".", "strip", "(", ")", ".", "startswith", "(", "'#'", ")", ":", "pass", "else", ":", "num_vars", "+=", "1", "names", ".", "append", "(", "row", "[", "'name'", "]", ")", "bounds", ".", "append", "(", "[", "float", "(", "row", "[", "'lower_bound'", "]", ")", ",", "float", "(", "row", "[", "'upper_bound'", "]", ")", "]", ")", "# If the fourth column does not contain a group name, use", "# the parameter name", "if", "row", "[", "'group'", "]", "is", "None", ":", "groups", ".", "append", "(", "row", "[", "'name'", "]", ")", "elif", "row", "[", "'group'", "]", "is", "'NA'", ":", "groups", ".", "append", "(", "row", "[", "'name'", "]", ")", "else", ":", "groups", ".", "append", "(", "row", "[", "'group'", "]", ")", "# If the fifth column does not contain a distribution", "# use uniform", "if", "row", "[", "'dist'", "]", "is", "None", ":", "dists", ".", "append", "(", "'unif'", ")", "else", ":", "dists", ".", "append", "(", "row", "[", "'dist'", "]", ")", "if", "groups", "==", "names", ":", "groups", "=", "None", "elif", "len", "(", "set", "(", "groups", ")", ")", "==", "1", ":", "raise", "ValueError", "(", "'''Only one group defined, results will not be\n meaningful'''", ")", "# setting dists to none if all are uniform", "# because non-uniform scaling is not needed", "if", "all", "(", "[", "d", "==", "'unif'", "for", "d", "in", "dists", "]", ")", ":", "dists", "=", "None", "return", "{", "'names'", ":", "names", ",", "'bounds'", ":", "bounds", ",", "'num_vars'", ":", "num_vars", ",", "'groups'", ":", "groups", ",", "'dists'", ":", "dists", "}" ]
Unpacks a parameter file into a dictionary Reads a parameter file of format:: Param1,0,1,Group1,dist1 Param2,0,1,Group2,dist2 Param3,0,1,Group3,dist3 (Group and Dist columns are optional) Returns a dictionary containing: - names - the names of the parameters - bounds - a list of lists of lower and upper bounds - num_vars - a scalar indicating the number of variables (the length of names) - groups - a list of group names (strings) for each variable - dists - a list of distributions for the problem, None if not specified or all uniform Arguments --------- filename : str The path to the parameter file delimiter : str, default=None The delimiter used in the file to distinguish between columns
[ "Unpacks", "a", "parameter", "file", "into", "a", "dictionary" ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/util/__init__.py#L168-L245
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 positions correspond to the order of groups in the k-by-g matrix Arguments --------- groups : list Group names corresponding to each variable Returns ------- tuple containing group matrix assigning parameters to groups and a list of unique group names """ if not groups: return None num_vars = len(groups) # Get a unique set of the group names unique_group_names = list(OrderedDict.fromkeys(groups)) number_of_groups = len(unique_group_names) indices = dict([(x, i) for (i, x) in enumerate(unique_group_names)]) output = np.zeros((num_vars, number_of_groups), dtype=np.int) for parameter_row, group_membership in enumerate(groups): group_index = indices[group_membership] output[parameter_row, group_index] = 1 return output, unique_group_names
python
def compute_groups_matrix(groups): """Generate matrix which notes factor membership of groups Computes a k-by-g matrix which notes factor membership of groups where: k is the number of variables (factors) g is the number of groups Also returns a g-length list of unique group_names whose positions correspond to the order of groups in the k-by-g matrix Arguments --------- groups : list Group names corresponding to each variable Returns ------- tuple containing group matrix assigning parameters to groups and a list of unique group names """ if not groups: return None num_vars = len(groups) # Get a unique set of the group names unique_group_names = list(OrderedDict.fromkeys(groups)) number_of_groups = len(unique_group_names) indices = dict([(x, i) for (i, x) in enumerate(unique_group_names)]) output = np.zeros((num_vars, number_of_groups), dtype=np.int) for parameter_row, group_membership in enumerate(groups): group_index = indices[group_membership] output[parameter_row, group_index] = 1 return output, unique_group_names
[ "def", "compute_groups_matrix", "(", "groups", ")", ":", "if", "not", "groups", ":", "return", "None", "num_vars", "=", "len", "(", "groups", ")", "# Get a unique set of the group names", "unique_group_names", "=", "list", "(", "OrderedDict", ".", "fromkeys", "(", "groups", ")", ")", "number_of_groups", "=", "len", "(", "unique_group_names", ")", "indices", "=", "dict", "(", "[", "(", "x", ",", "i", ")", "for", "(", "i", ",", "x", ")", "in", "enumerate", "(", "unique_group_names", ")", "]", ")", "output", "=", "np", ".", "zeros", "(", "(", "num_vars", ",", "number_of_groups", ")", ",", "dtype", "=", "np", ".", "int", ")", "for", "parameter_row", ",", "group_membership", "in", "enumerate", "(", "groups", ")", ":", "group_index", "=", "indices", "[", "group_membership", "]", "output", "[", "parameter_row", ",", "group_index", "]", "=", "1", "return", "output", ",", "unique_group_names" ]
Generate matrix which notes factor membership of groups Computes a k-by-g matrix which notes factor membership of groups where: k is the number of variables (factors) g is the number of groups Also returns a g-length list of unique group_names whose positions correspond to the order of groups in the k-by-g matrix Arguments --------- groups : list Group names corresponding to each variable Returns ------- tuple containing group matrix assigning parameters to groups and a list of unique group names
[ "Generate", "matrix", "which", "notes", "factor", "membership", "of", "groups" ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/util/__init__.py#L248-L286
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 brute force options as preference. ''' def _outer_wrapper(wrapped_function): def _wrapper(*args, **kwargs): if _has_gurobi: result = wrapped_function(*args, **kwargs) else: warn("Gurobi not available", ImportWarning) result = None return result return _wrapper return _outer_wrapper
python
def requires_gurobipy(_has_gurobi): ''' Decorator function which takes a boolean _has_gurobi as an argument. Use decorate any functions which require gurobi. Raises an import error at runtime if gurobi is not present. Note that all runtime errors should be avoided in the working code, using brute force options as preference. ''' def _outer_wrapper(wrapped_function): def _wrapper(*args, **kwargs): if _has_gurobi: result = wrapped_function(*args, **kwargs) else: warn("Gurobi not available", ImportWarning) result = None return result return _wrapper return _outer_wrapper
[ "def", "requires_gurobipy", "(", "_has_gurobi", ")", ":", "def", "_outer_wrapper", "(", "wrapped_function", ")", ":", "def", "_wrapper", "(", "*", "args", ",", "*", "*", "kwargs", ")", ":", "if", "_has_gurobi", ":", "result", "=", "wrapped_function", "(", "*", "args", ",", "*", "*", "kwargs", ")", "else", ":", "warn", "(", "\"Gurobi not available\"", ",", "ImportWarning", ")", "result", "=", "None", "return", "result", "return", "_wrapper", "return", "_outer_wrapper" ]
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", "present", ".", "Note", "that", "all", "runtime", "errors", "should", "be", "avoided", "in", "the", "working", "code", "using", "brute", "force", "options", "as", "preference", "." ]
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(ungrouped_sigma * group_matrix.T, mask=(group_matrix ^ 1).T) sigma_agg = np.ma.mean(sigma_masked, axis=1) sigma = np.zeros(group_matrix.shape[1], dtype=np.float) np.copyto(sigma, sigma_agg, where=group_matrix.sum(axis=0) == 1) np.copyto(sigma, np.NAN, where=group_matrix.sum(axis=0) != 1) return sigma
python
def compute_grouped_sigma(ungrouped_sigma, group_matrix): ''' Returns sigma for the groups of parameter values in the argument ungrouped_metric where the group consists of no more than one parameter ''' group_matrix = np.array(group_matrix, dtype=np.bool) sigma_masked = np.ma.masked_array(ungrouped_sigma * group_matrix.T, mask=(group_matrix ^ 1).T) sigma_agg = np.ma.mean(sigma_masked, axis=1) sigma = np.zeros(group_matrix.shape[1], dtype=np.float) np.copyto(sigma, sigma_agg, where=group_matrix.sum(axis=0) == 1) np.copyto(sigma, np.NAN, where=group_matrix.sum(axis=0) != 1) return sigma
[ "def", "compute_grouped_sigma", "(", "ungrouped_sigma", ",", "group_matrix", ")", ":", "group_matrix", "=", "np", ".", "array", "(", "group_matrix", ",", "dtype", "=", "np", ".", "bool", ")", "sigma_masked", "=", "np", ".", "ma", ".", "masked_array", "(", "ungrouped_sigma", "*", "group_matrix", ".", "T", ",", "mask", "=", "(", "group_matrix", "^", "1", ")", ".", "T", ")", "sigma_agg", "=", "np", ".", "ma", ".", "mean", "(", "sigma_masked", ",", "axis", "=", "1", ")", "sigma", "=", "np", ".", "zeros", "(", "group_matrix", ".", "shape", "[", "1", "]", ",", "dtype", "=", "np", ".", "float", ")", "np", ".", "copyto", "(", "sigma", ",", "sigma_agg", ",", "where", "=", "group_matrix", ".", "sum", "(", "axis", "=", "0", ")", "==", "1", ")", "np", ".", "copyto", "(", "sigma", ",", "np", ".", "NAN", ",", "where", "=", "group_matrix", ".", "sum", "(", "axis", "=", "0", ")", "!=", "1", ")", "return", "sigma" ]
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, mask=(group_matrix ^ 1).T) mean_of_mu_star = np.ma.mean(mu_star_masked, axis=1) return mean_of_mu_star
python
def compute_grouped_metric(ungrouped_metric, group_matrix): ''' Computes the mean value for the groups of parameter values in the argument ungrouped_metric ''' group_matrix = np.array(group_matrix, dtype=np.bool) mu_star_masked = np.ma.masked_array(ungrouped_metric * group_matrix.T, mask=(group_matrix ^ 1).T) mean_of_mu_star = np.ma.mean(mu_star_masked, axis=1) return mean_of_mu_star
[ "def", "compute_grouped_metric", "(", "ungrouped_metric", ",", "group_matrix", ")", ":", "group_matrix", "=", "np", ".", "array", "(", "group_matrix", ",", "dtype", "=", "np", ".", "bool", ")", "mu_star_masked", "=", "np", ".", "ma", ".", "masked_array", "(", "ungrouped_metric", "*", "group_matrix", ".", "T", ",", "mask", "=", "(", "group_matrix", "^", "1", ")", ".", "T", ")", "mean_of_mu_star", "=", "np", ".", "ma", ".", "mean", "(", "mu_star_masked", ",", "axis", "=", "1", ")", "return", "mean_of_mu_star" ]
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. ''' ee_resampled = np.zeros([num_trajectories]) mu_star_resampled = np.zeros([num_resamples]) if not 0 < conf_level < 1: raise ValueError("Confidence level must be between 0-1.") resample_index = np.random.randint( len(ee), size=(num_resamples, num_trajectories)) ee_resampled = ee[resample_index] # Compute average of the absolute values over each of the resamples mu_star_resampled = np.average(np.abs(ee_resampled), axis=1) return norm.ppf(0.5 + conf_level / 2) * mu_star_resampled.std(ddof=1)
python
def compute_mu_star_confidence(ee, num_trajectories, num_resamples, conf_level): ''' Uses bootstrapping where the elementary effects are resampled with replacement to produce a histogram of resampled mu_star metrics. This resample is used to produce a confidence interval. ''' ee_resampled = np.zeros([num_trajectories]) mu_star_resampled = np.zeros([num_resamples]) if not 0 < conf_level < 1: raise ValueError("Confidence level must be between 0-1.") resample_index = np.random.randint( len(ee), size=(num_resamples, num_trajectories)) ee_resampled = ee[resample_index] # Compute average of the absolute values over each of the resamples mu_star_resampled = np.average(np.abs(ee_resampled), axis=1) return norm.ppf(0.5 + conf_level / 2) * mu_star_resampled.std(ddof=1)
[ "def", "compute_mu_star_confidence", "(", "ee", ",", "num_trajectories", ",", "num_resamples", ",", "conf_level", ")", ":", "ee_resampled", "=", "np", ".", "zeros", "(", "[", "num_trajectories", "]", ")", "mu_star_resampled", "=", "np", ".", "zeros", "(", "[", "num_resamples", "]", ")", "if", "not", "0", "<", "conf_level", "<", "1", ":", "raise", "ValueError", "(", "\"Confidence level must be between 0-1.\"", ")", "resample_index", "=", "np", ".", "random", ".", "randint", "(", "len", "(", "ee", ")", ",", "size", "=", "(", "num_resamples", ",", "num_trajectories", ")", ")", "ee_resampled", "=", "ee", "[", "resample_index", "]", "# Compute average of the absolute values over each of the resamples", "mu_star_resampled", "=", "np", ".", "average", "(", "np", ".", "abs", "(", "ee_resampled", ")", ",", "axis", "=", "1", ")", "return", "norm", ".", "ppf", "(", "0.5", "+", "conf_level", "/", "2", ")", "*", "mu_star_resampled", ".", "std", "(", "ddof", "=", "1", ")" ]
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", "interval", "." ]
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, N, dt.strftime(dt.now(), "%d%m%y%H%M%S")) return string
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, N, dt.strftime(dt.now(), "%d%m%y%H%M%S")) return string
[ "def", "timestamp", "(", "num_params", ",", "p_levels", ",", "k_choices", ",", "N", ")", ":", "string", "=", "\"_v%s_l%s_gs%s_k%s_N%s_%s.txt\"", "%", "(", "num_params", ",", "p_levels", ",", "k_choices", ",", "N", ",", "dt", ".", "strftime", "(", "dt", ".", "now", "(", ")", ",", "\"%d%m%y%H%M%S\"", ")", ")", "return", "string" ]
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 num_samples : int The number of samples to generate num_params : int The number of parameters k_choices : int The number of optimal trajectories num_groups : int, default=None The number of groups Returns ------- list """ scores = self.find_most_distant(input_sample, num_samples, num_params, k_choices, num_groups) maximum_combo = self.find_maximum(scores, num_samples, k_choices) return maximum_combo
python
def brute_force_most_distant(self, input_sample, num_samples, num_params, k_choices, num_groups=None): """Use brute force method to find most distant trajectories Arguments --------- input_sample : numpy.ndarray num_samples : int The number of samples to generate num_params : int The number of parameters k_choices : int The number of optimal trajectories num_groups : int, default=None The number of groups Returns ------- list """ scores = self.find_most_distant(input_sample, num_samples, num_params, k_choices, num_groups) maximum_combo = self.find_maximum(scores, num_samples, k_choices) return maximum_combo
[ "def", "brute_force_most_distant", "(", "self", ",", "input_sample", ",", "num_samples", ",", "num_params", ",", "k_choices", ",", "num_groups", "=", "None", ")", ":", "scores", "=", "self", ".", "find_most_distant", "(", "input_sample", ",", "num_samples", ",", "num_params", ",", "k_choices", ",", "num_groups", ")", "maximum_combo", "=", "self", ".", "find_maximum", "(", "scores", ",", "num_samples", ",", "k_choices", ")", "return", "maximum_combo" ]
Use brute force method to find most distant trajectories Arguments --------- input_sample : numpy.ndarray num_samples : int The number of samples to generate num_params : int The number of parameters k_choices : int The number of optimal trajectories num_groups : int, default=None The number of groups Returns ------- list
[ "Use", "brute", "force", "method", "to", "find", "most", "distant", "trajectories" ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/sample/morris/brute.py#L19-L48
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 : numpy.ndarray num_samples : int The number of samples to generate num_params : int The number of parameters k_choices : int The number of optimal trajectories num_groups : int, default=None The number of groups Returns ------- numpy.ndarray """ # Now evaluate the (N choose k_choices) possible combinations if nchoosek(num_samples, k_choices) >= sys.maxsize: raise ValueError("Number of combinations is too large") number_of_combinations = int(nchoosek(num_samples, k_choices)) # First compute the distance matrix for each possible pairing # of trajectories and store in a shared-memory array distance_matrix = self.compute_distance_matrix(input_sample, num_samples, num_params, num_groups) # Initialise the output array chunk = int(1e6) if chunk > number_of_combinations: chunk = number_of_combinations counter = 0 # Generate a list of all the possible combinations combo_gen = combinations(list(range(num_samples)), k_choices) scores = np.zeros(number_of_combinations, dtype=np.float32) # Generate the pairwise indices once pairwise = np.array( [y for y in combinations(list(range(k_choices)), 2)]) for combos in self.grouper(chunk, combo_gen): scores[(counter * chunk):((counter + 1) * chunk)] \ = self.mappable(combos, pairwise, distance_matrix) counter += 1 return scores
python
def find_most_distant(self, input_sample, num_samples, num_params, k_choices, num_groups=None): """ Finds the 'k_choices' most distant choices from the 'num_samples' trajectories contained in 'input_sample' Arguments --------- input_sample : numpy.ndarray num_samples : int The number of samples to generate num_params : int The number of parameters k_choices : int The number of optimal trajectories num_groups : int, default=None The number of groups Returns ------- numpy.ndarray """ # Now evaluate the (N choose k_choices) possible combinations if nchoosek(num_samples, k_choices) >= sys.maxsize: raise ValueError("Number of combinations is too large") number_of_combinations = int(nchoosek(num_samples, k_choices)) # First compute the distance matrix for each possible pairing # of trajectories and store in a shared-memory array distance_matrix = self.compute_distance_matrix(input_sample, num_samples, num_params, num_groups) # Initialise the output array chunk = int(1e6) if chunk > number_of_combinations: chunk = number_of_combinations counter = 0 # Generate a list of all the possible combinations combo_gen = combinations(list(range(num_samples)), k_choices) scores = np.zeros(number_of_combinations, dtype=np.float32) # Generate the pairwise indices once pairwise = np.array( [y for y in combinations(list(range(k_choices)), 2)]) for combos in self.grouper(chunk, combo_gen): scores[(counter * chunk):((counter + 1) * chunk)] \ = self.mappable(combos, pairwise, distance_matrix) counter += 1 return scores
[ "def", "find_most_distant", "(", "self", ",", "input_sample", ",", "num_samples", ",", "num_params", ",", "k_choices", ",", "num_groups", "=", "None", ")", ":", "# Now evaluate the (N choose k_choices) possible combinations", "if", "nchoosek", "(", "num_samples", ",", "k_choices", ")", ">=", "sys", ".", "maxsize", ":", "raise", "ValueError", "(", "\"Number of combinations is too large\"", ")", "number_of_combinations", "=", "int", "(", "nchoosek", "(", "num_samples", ",", "k_choices", ")", ")", "# First compute the distance matrix for each possible pairing", "# of trajectories and store in a shared-memory array", "distance_matrix", "=", "self", ".", "compute_distance_matrix", "(", "input_sample", ",", "num_samples", ",", "num_params", ",", "num_groups", ")", "# Initialise the output array", "chunk", "=", "int", "(", "1e6", ")", "if", "chunk", ">", "number_of_combinations", ":", "chunk", "=", "number_of_combinations", "counter", "=", "0", "# Generate a list of all the possible combinations", "combo_gen", "=", "combinations", "(", "list", "(", "range", "(", "num_samples", ")", ")", ",", "k_choices", ")", "scores", "=", "np", ".", "zeros", "(", "number_of_combinations", ",", "dtype", "=", "np", ".", "float32", ")", "# Generate the pairwise indices once", "pairwise", "=", "np", ".", "array", "(", "[", "y", "for", "y", "in", "combinations", "(", "list", "(", "range", "(", "k_choices", ")", ")", ",", "2", ")", "]", ")", "for", "combos", "in", "self", ".", "grouper", "(", "chunk", ",", "combo_gen", ")", ":", "scores", "[", "(", "counter", "*", "chunk", ")", ":", "(", "(", "counter", "+", "1", ")", "*", "chunk", ")", "]", "=", "self", ".", "mappable", "(", "combos", ",", "pairwise", ",", "distance_matrix", ")", "counter", "+=", "1", "return", "scores" ]
Finds the 'k_choices' most distant choices from the 'num_samples' trajectories contained in 'input_sample' Arguments --------- input_sample : numpy.ndarray num_samples : int The number of samples to generate num_params : int The number of parameters k_choices : int The number of optimal trajectories num_groups : int, default=None The number of groups Returns ------- numpy.ndarray
[ "Finds", "the", "k_choices", "most", "distant", "choices", "from", "the", "num_samples", "trajectories", "contained", "in", "input_sample" ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/sample/morris/brute.py#L50-L101
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 ''' combos = np.array(combos) # Create a list of all pairwise combination for each combo in combos combo_list = combos[:, pairwise[:, ]] addresses = tuple([combo_list[:, :, 1], combo_list[:, :, 0]]) all_distances = distance_matrix[addresses] new_scores = np.sqrt( np.einsum('ij,ij->i', all_distances, all_distances)) return new_scores
python
def mappable(combos, pairwise, distance_matrix): ''' Obtains scores from the distance_matrix for each pairwise combination held in the combos array Arguments ---------- combos : numpy.ndarray pairwise : numpy.ndarray distance_matrix : numpy.ndarray ''' combos = np.array(combos) # Create a list of all pairwise combination for each combo in combos combo_list = combos[:, pairwise[:, ]] addresses = tuple([combo_list[:, :, 1], combo_list[:, :, 0]]) all_distances = distance_matrix[addresses] new_scores = np.sqrt( np.einsum('ij,ij->i', all_distances, all_distances)) return new_scores
[ "def", "mappable", "(", "combos", ",", "pairwise", ",", "distance_matrix", ")", ":", "combos", "=", "np", ".", "array", "(", "combos", ")", "# Create a list of all pairwise combination for each combo in combos", "combo_list", "=", "combos", "[", ":", ",", "pairwise", "[", ":", ",", "]", "]", "addresses", "=", "tuple", "(", "[", "combo_list", "[", ":", ",", ":", ",", "1", "]", ",", "combo_list", "[", ":", ",", ":", ",", "0", "]", "]", ")", "all_distances", "=", "distance_matrix", "[", "addresses", "]", "new_scores", "=", "np", ".", "sqrt", "(", "np", ".", "einsum", "(", "'ij,ij->i'", ",", "all_distances", ",", "all_distances", ")", ")", "return", "new_scores" ]
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): raise TypeError("Scores input is not a numpy array") index_of_maximum = int(scores.argmax()) maximum_combo = self.nth(combinations( list(range(N)), k_choices), index_of_maximum, None) return sorted(maximum_combo)
python
def find_maximum(self, scores, N, k_choices): """Finds the `k_choices` maximum scores from `scores` Arguments --------- scores : numpy.ndarray N : int k_choices : int Returns ------- list """ if not isinstance(scores, np.ndarray): raise TypeError("Scores input is not a numpy array") index_of_maximum = int(scores.argmax()) maximum_combo = self.nth(combinations( list(range(N)), k_choices), index_of_maximum, None) return sorted(maximum_combo)
[ "def", "find_maximum", "(", "self", ",", "scores", ",", "N", ",", "k_choices", ")", ":", "if", "not", "isinstance", "(", "scores", ",", "np", ".", "ndarray", ")", ":", "raise", "TypeError", "(", "\"Scores input is not a numpy array\"", ")", "index_of_maximum", "=", "int", "(", "scores", ".", "argmax", "(", ")", ")", "maximum_combo", "=", "self", ".", "nth", "(", "combinations", "(", "list", "(", "range", "(", "N", ")", ")", ",", "k_choices", ")", ",", "index_of_maximum", ",", "None", ")", "return", "sorted", "(", "maximum_combo", ")" ]
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 integer") return next(islice(iterable, n, None), default)
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 integer") return next(islice(iterable, n, None), default)
[ "def", "nth", "(", "iterable", ",", "n", ",", "default", "=", "None", ")", ":", "if", "type", "(", "n", ")", "!=", "int", ":", "raise", "TypeError", "(", "\"n is not an integer\"", ")", "return", "next", "(", "islice", "(", "iterable", ",", "n", ",", "None", ")", ",", "default", ")" ]
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, where :math:`D` is the number of parameters, :math:`G` is the number of groups (if no groups are selected, the number of parameters). :math:`T` is the number of trajectories :math:`N`, or `optimal_trajectories` if selected. These model inputs are intended to be used with :func:`SALib.analyze.morris.analyze`. Parameters ---------- problem : dict The problem definition N : int The number of trajectories to generate num_levels : int, default=4 The number of grid levels optimal_trajectories : int The number of optimal trajectories to sample (between 2 and N) local_optimization : bool, default=True Flag whether to use local optimization according to Ruano et al. (2012) Speeds up the process tremendously for bigger N and num_levels. If set to ``False`` brute force method is used, unless ``gurobipy`` is available Returns ------- sample : numpy.ndarray Returns a numpy.ndarray containing the model inputs required for Method of Morris. The resulting matrix has :math:`(G/D+1)*N/T` rows and :math:`D` columns, where :math:`D` is the number of parameters. """ if problem.get('groups'): sample = _sample_groups(problem, N, num_levels) else: sample = _sample_oat(problem, N, num_levels) if optimal_trajectories: sample = _compute_optimised_trajectories(problem, sample, N, optimal_trajectories, local_optimization) scale_samples(sample, problem['bounds']) return sample
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, where :math:`D` is the number of parameters, :math:`G` is the number of groups (if no groups are selected, the number of parameters). :math:`T` is the number of trajectories :math:`N`, or `optimal_trajectories` if selected. These model inputs are intended to be used with :func:`SALib.analyze.morris.analyze`. Parameters ---------- problem : dict The problem definition N : int The number of trajectories to generate num_levels : int, default=4 The number of grid levels optimal_trajectories : int The number of optimal trajectories to sample (between 2 and N) local_optimization : bool, default=True Flag whether to use local optimization according to Ruano et al. (2012) Speeds up the process tremendously for bigger N and num_levels. If set to ``False`` brute force method is used, unless ``gurobipy`` is available Returns ------- sample : numpy.ndarray Returns a numpy.ndarray containing the model inputs required for Method of Morris. The resulting matrix has :math:`(G/D+1)*N/T` rows and :math:`D` columns, where :math:`D` is the number of parameters. """ if problem.get('groups'): sample = _sample_groups(problem, N, num_levels) else: sample = _sample_oat(problem, N, num_levels) if optimal_trajectories: sample = _compute_optimised_trajectories(problem, sample, N, optimal_trajectories, local_optimization) scale_samples(sample, problem['bounds']) return sample
[ "def", "sample", "(", "problem", ",", "N", ",", "num_levels", "=", "4", ",", "optimal_trajectories", "=", "None", ",", "local_optimization", "=", "True", ")", ":", "if", "problem", ".", "get", "(", "'groups'", ")", ":", "sample", "=", "_sample_groups", "(", "problem", ",", "N", ",", "num_levels", ")", "else", ":", "sample", "=", "_sample_oat", "(", "problem", ",", "N", ",", "num_levels", ")", "if", "optimal_trajectories", ":", "sample", "=", "_compute_optimised_trajectories", "(", "problem", ",", "sample", ",", "N", ",", "optimal_trajectories", ",", "local_optimization", ")", "scale_samples", "(", "sample", ",", "problem", "[", "'bounds'", "]", ")", "return", "sample" ]
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 selected, the number of parameters). :math:`T` is the number of trajectories :math:`N`, or `optimal_trajectories` if selected. These model inputs are intended to be used with :func:`SALib.analyze.morris.analyze`. Parameters ---------- problem : dict The problem definition N : int The number of trajectories to generate num_levels : int, default=4 The number of grid levels optimal_trajectories : int The number of optimal trajectories to sample (between 2 and N) local_optimization : bool, default=True Flag whether to use local optimization according to Ruano et al. (2012) Speeds up the process tremendously for bigger N and num_levels. If set to ``False`` brute force method is used, unless ``gurobipy`` is available Returns ------- sample : numpy.ndarray Returns a numpy.ndarray containing the model inputs required for Method of Morris. The resulting matrix has :math:`(G/D+1)*N/T` rows and :math:`D` columns, where :math:`D` is the number of parameters.
[ "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.asmatrix(np.identity(problem['num_vars'], dtype=int)) num_params = group_membership.shape[0] sample = np.zeros((N * (num_params + 1), num_params)) sample = np.array([generate_trajectory(group_membership, num_levels) for n in range(N)]) return sample.reshape((N * (num_params + 1), num_params))
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.asmatrix(np.identity(problem['num_vars'], dtype=int)) num_params = group_membership.shape[0] sample = np.zeros((N * (num_params + 1), num_params)) sample = np.array([generate_trajectory(group_membership, num_levels) for n in range(N)]) return sample.reshape((N * (num_params + 1), num_params))
[ "def", "_sample_oat", "(", "problem", ",", "N", ",", "num_levels", "=", "4", ")", ":", "group_membership", "=", "np", ".", "asmatrix", "(", "np", ".", "identity", "(", "problem", "[", "'num_vars'", "]", ",", "dtype", "=", "int", ")", ")", "num_params", "=", "group_membership", ".", "shape", "[", "0", "]", "sample", "=", "np", ".", "zeros", "(", "(", "N", "*", "(", "num_params", "+", "1", ")", ",", "num_params", ")", ")", "sample", "=", "np", ".", "array", "(", "[", "generate_trajectory", "(", "group_membership", ",", "num_levels", ")", "for", "n", "in", "range", "(", "N", ")", "]", ")", "return", "sample", ".", "reshape", "(", "(", "N", "*", "(", "num_params", "+", "1", ")", ",", "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 definition N : int The number of trajectories to generate num_levels : int, default=4 The number of grid levels Returns ------- numpy.ndarray """ if len(problem['groups']) != problem['num_vars']: raise ValueError("Groups do not match to number of variables") group_membership, _ = compute_groups_matrix(problem['groups']) if group_membership is None: raise ValueError("Please define the 'group_membership' matrix") if not isinstance(group_membership, np.ndarray): raise TypeError("Argument 'group_membership' should be formatted \ as a numpy ndarray") num_params = group_membership.shape[0] num_groups = group_membership.shape[1] sample = np.zeros((N * (num_groups + 1), num_params)) sample = np.array([generate_trajectory(group_membership, num_levels) for n in range(N)]) return sample.reshape((N * (num_groups + 1), num_params))
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 definition N : int The number of trajectories to generate num_levels : int, default=4 The number of grid levels Returns ------- numpy.ndarray """ if len(problem['groups']) != problem['num_vars']: raise ValueError("Groups do not match to number of variables") group_membership, _ = compute_groups_matrix(problem['groups']) if group_membership is None: raise ValueError("Please define the 'group_membership' matrix") if not isinstance(group_membership, np.ndarray): raise TypeError("Argument 'group_membership' should be formatted \ as a numpy ndarray") num_params = group_membership.shape[0] num_groups = group_membership.shape[1] sample = np.zeros((N * (num_groups + 1), num_params)) sample = np.array([generate_trajectory(group_membership, num_levels) for n in range(N)]) return sample.reshape((N * (num_groups + 1), num_params))
[ "def", "_sample_groups", "(", "problem", ",", "N", ",", "num_levels", "=", "4", ")", ":", "if", "len", "(", "problem", "[", "'groups'", "]", ")", "!=", "problem", "[", "'num_vars'", "]", ":", "raise", "ValueError", "(", "\"Groups do not match to number of variables\"", ")", "group_membership", ",", "_", "=", "compute_groups_matrix", "(", "problem", "[", "'groups'", "]", ")", "if", "group_membership", "is", "None", ":", "raise", "ValueError", "(", "\"Please define the 'group_membership' matrix\"", ")", "if", "not", "isinstance", "(", "group_membership", ",", "np", ".", "ndarray", ")", ":", "raise", "TypeError", "(", "\"Argument 'group_membership' should be formatted \\\n as a numpy ndarray\"", ")", "num_params", "=", "group_membership", ".", "shape", "[", "0", "]", "num_groups", "=", "group_membership", ".", "shape", "[", "1", "]", "sample", "=", "np", ".", "zeros", "(", "(", "N", "*", "(", "num_groups", "+", "1", ")", ",", "num_params", ")", ")", "sample", "=", "np", ".", "array", "(", "[", "generate_trajectory", "(", "group_membership", ",", "num_levels", ")", "for", "n", "in", "range", "(", "N", ")", "]", ")", "return", "sample", ".", "reshape", "(", "(", "N", "*", "(", "num_groups", "+", "1", ")", ",", "num_params", ")", ")" ]
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 num_levels : int, default=4 The number of grid levels Returns ------- numpy.ndarray
[ "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 --------- group_membership : np.ndarray a k-by-g matrix which notes factor membership of groups num_levels : int, default=4 The number of levels in the grid Returns ------- np.ndarray """ delta = compute_delta(num_levels) # Infer number of groups `g` and number of params `k` from # `group_membership` matrix num_params = group_membership.shape[0] num_groups = group_membership.shape[1] # Matrix B - size (g + 1) * g - lower triangular matrix B = np.tril(np.ones([num_groups + 1, num_groups], dtype=int), -1) P_star = generate_p_star(num_groups) # Matrix J - a (g+1)-by-num_params matrix of ones J = np.ones((num_groups + 1, num_params)) # Matrix D* - num_params-by-num_params matrix which decribes whether # factors move up or down D_star = np.diag([rd.choice([-1, 1]) for _ in range(num_params)]) x_star = generate_x_star(num_params, num_levels) # Matrix B* - size (num_groups + 1) * num_params B_star = compute_b_star(J, x_star, delta, B, group_membership, P_star, D_star) return B_star
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 --------- group_membership : np.ndarray a k-by-g matrix which notes factor membership of groups num_levels : int, default=4 The number of levels in the grid Returns ------- np.ndarray """ delta = compute_delta(num_levels) # Infer number of groups `g` and number of params `k` from # `group_membership` matrix num_params = group_membership.shape[0] num_groups = group_membership.shape[1] # Matrix B - size (g + 1) * g - lower triangular matrix B = np.tril(np.ones([num_groups + 1, num_groups], dtype=int), -1) P_star = generate_p_star(num_groups) # Matrix J - a (g+1)-by-num_params matrix of ones J = np.ones((num_groups + 1, num_params)) # Matrix D* - num_params-by-num_params matrix which decribes whether # factors move up or down D_star = np.diag([rd.choice([-1, 1]) for _ in range(num_params)]) x_star = generate_x_star(num_params, num_levels) # Matrix B* - size (num_groups + 1) * num_params B_star = compute_b_star(J, x_star, delta, B, group_membership, P_star, D_star) return B_star
[ "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_membership", ".", "shape", "[", "0", "]", "num_groups", "=", "group_membership", ".", "shape", "[", "1", "]", "# Matrix B - size (g + 1) * g - lower triangular matrix", "B", "=", "np", ".", "tril", "(", "np", ".", "ones", "(", "[", "num_groups", "+", "1", ",", "num_groups", "]", ",", "dtype", "=", "int", ")", ",", "-", "1", ")", "P_star", "=", "generate_p_star", "(", "num_groups", ")", "# Matrix J - a (g+1)-by-num_params matrix of ones", "J", "=", "np", ".", "ones", "(", "(", "num_groups", "+", "1", ",", "num_params", ")", ")", "# Matrix D* - num_params-by-num_params matrix which decribes whether", "# factors move up or down", "D_star", "=", "np", ".", "diag", "(", "[", "rd", ".", "choice", "(", "[", "-", "1", ",", "1", "]", ")", "for", "_", "in", "range", "(", "num_params", ")", "]", ")", "x_star", "=", "generate_x_star", "(", "num_params", ",", "num_levels", ")", "# Matrix B* - size (num_groups + 1) * num_params", "B_star", "=", "compute_b_star", "(", "J", ",", "x_star", ",", "delta", ",", "B", ",", "group_membership", ",", "P_star", ",", "D_star", ")", "return", "B_star" ]
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 matrix which notes factor membership of groups num_levels : int, default=4 The number of levels in the grid Returns ------- np.ndarray
[ "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 method (morris, sobol, etc). Must match one of the available submodules opts : list A list of argument options to parse Returns --------- subargs : argparser namespace object ''' module.cli_args(parser) subargs = parser.parse_args(opts) return subargs
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 method (morris, sobol, etc). Must match one of the available submodules opts : list A list of argument options to parse Returns --------- subargs : argparser namespace object ''' module.cli_args(parser) subargs = parser.parse_args(opts) return subargs
[ "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 available submodules opts : list A list of argument options to parse Returns --------- subargs : argparser namespace object
[ "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 by Campolongo et al. (2007). The method should improve the speed with which an optimal set of trajectories is found tremendously for larger sample sizes. Arguments --------- input_sample : np.ndarray N : int The number of trajectories num_params : int The number of factors k_choices : int The number of optimal trajectories to return num_groups : int, default=None The number of groups Returns ------- list """ distance_matrix = self.compute_distance_matrix(input_sample, N, num_params, num_groups, local_optimization=True) tot_indices_list = [] tot_max_array = np.zeros(k_choices - 1) # Loop over `k_choices`, i starts at 1 for i in range(1, k_choices): indices_list = [] row_maxima_i = np.zeros(len(distance_matrix)) row_nr = 0 for row in distance_matrix: indices = tuple(row.argsort()[-i:][::-1]) + (row_nr,) row_maxima_i[row_nr] = self.sum_distances( indices, distance_matrix) indices_list.append(indices) row_nr += 1 # Find the indices belonging to the maximum distance i_max_ind = self.get_max_sum_ind(indices_list, row_maxima_i, i, 0) # Loop 'm' (called loop 'k' in Ruano) m_max_ind = i_max_ind # m starts at 1 m = 1 while m <= k_choices - i - 1: m_ind = self.add_indices(m_max_ind, distance_matrix) m_maxima = np.zeros(len(m_ind)) for n in range(0, len(m_ind)): m_maxima[n] = self.sum_distances(m_ind[n], distance_matrix) m_max_ind = self.get_max_sum_ind(m_ind, m_maxima, i, m) m += 1 tot_indices_list.append(m_max_ind) tot_max_array[i - 1] = self.sum_distances(m_max_ind, distance_matrix) tot_max = self.get_max_sum_ind( tot_indices_list, tot_max_array, "tot", "tot") return sorted(list(tot_max))
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 by Campolongo et al. (2007). The method should improve the speed with which an optimal set of trajectories is found tremendously for larger sample sizes. Arguments --------- input_sample : np.ndarray N : int The number of trajectories num_params : int The number of factors k_choices : int The number of optimal trajectories to return num_groups : int, default=None The number of groups Returns ------- list """ distance_matrix = self.compute_distance_matrix(input_sample, N, num_params, num_groups, local_optimization=True) tot_indices_list = [] tot_max_array = np.zeros(k_choices - 1) # Loop over `k_choices`, i starts at 1 for i in range(1, k_choices): indices_list = [] row_maxima_i = np.zeros(len(distance_matrix)) row_nr = 0 for row in distance_matrix: indices = tuple(row.argsort()[-i:][::-1]) + (row_nr,) row_maxima_i[row_nr] = self.sum_distances( indices, distance_matrix) indices_list.append(indices) row_nr += 1 # Find the indices belonging to the maximum distance i_max_ind = self.get_max_sum_ind(indices_list, row_maxima_i, i, 0) # Loop 'm' (called loop 'k' in Ruano) m_max_ind = i_max_ind # m starts at 1 m = 1 while m <= k_choices - i - 1: m_ind = self.add_indices(m_max_ind, distance_matrix) m_maxima = np.zeros(len(m_ind)) for n in range(0, len(m_ind)): m_maxima[n] = self.sum_distances(m_ind[n], distance_matrix) m_max_ind = self.get_max_sum_ind(m_ind, m_maxima, i, m) m += 1 tot_indices_list.append(m_max_ind) tot_max_array[i - 1] = self.sum_distances(m_max_ind, distance_matrix) tot_max = self.get_max_sum_ind( tot_indices_list, tot_max_array, "tot", "tot") return sorted(list(tot_max))
[ "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_params", ",", "num_groups", ",", "local_optimization", "=", "True", ")", "tot_indices_list", "=", "[", "]", "tot_max_array", "=", "np", ".", "zeros", "(", "k_choices", "-", "1", ")", "# Loop over `k_choices`, i starts at 1", "for", "i", "in", "range", "(", "1", ",", "k_choices", ")", ":", "indices_list", "=", "[", "]", "row_maxima_i", "=", "np", ".", "zeros", "(", "len", "(", "distance_matrix", ")", ")", "row_nr", "=", "0", "for", "row", "in", "distance_matrix", ":", "indices", "=", "tuple", "(", "row", ".", "argsort", "(", ")", "[", "-", "i", ":", "]", "[", ":", ":", "-", "1", "]", ")", "+", "(", "row_nr", ",", ")", "row_maxima_i", "[", "row_nr", "]", "=", "self", ".", "sum_distances", "(", "indices", ",", "distance_matrix", ")", "indices_list", ".", "append", "(", "indices", ")", "row_nr", "+=", "1", "# Find the indices belonging to the maximum distance", "i_max_ind", "=", "self", ".", "get_max_sum_ind", "(", "indices_list", ",", "row_maxima_i", ",", "i", ",", "0", ")", "# Loop 'm' (called loop 'k' in Ruano)", "m_max_ind", "=", "i_max_ind", "# m starts at 1", "m", "=", "1", "while", "m", "<=", "k_choices", "-", "i", "-", "1", ":", "m_ind", "=", "self", ".", "add_indices", "(", "m_max_ind", ",", "distance_matrix", ")", "m_maxima", "=", "np", ".", "zeros", "(", "len", "(", "m_ind", ")", ")", "for", "n", "in", "range", "(", "0", ",", "len", "(", "m_ind", ")", ")", ":", "m_maxima", "[", "n", "]", "=", "self", ".", "sum_distances", "(", "m_ind", "[", "n", "]", ",", "distance_matrix", ")", "m_max_ind", "=", "self", ".", "get_max_sum_ind", "(", "m_ind", ",", "m_maxima", ",", "i", ",", "m", ")", "m", "+=", "1", "tot_indices_list", ".", "append", "(", "m_max_ind", ")", "tot_max_array", "[", "i", "-", "1", "]", "=", "self", ".", "sum_distances", "(", "m_max_ind", ",", "distance_matrix", ")", "tot_max", "=", "self", ".", "get_max_sum_ind", "(", "tot_indices_list", ",", "tot_max_array", ",", "\"tot\"", ",", "\"tot\"", ")", "return", "sorted", "(", "list", "(", "tot_max", ")", ")" ]
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 found tremendously for larger sample sizes. Arguments --------- input_sample : np.ndarray N : int The number of trajectories num_params : int The number of factors k_choices : int The number of optimal trajectories to return num_groups : int, default=None The number of groups Returns ------- list
[ "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.ndarray Notes ----- This function can perhaps be quickened by calculating the sum of the distances. The calculated distances, as they are right now, are only used in a relative way. Purely summing distances would lead to the same result, at a perhaps quicker rate. """ combs_tup = np.array(tuple(combinations(indices, 2))) # Put indices from tuples into two-dimensional array. combs = np.array([[i[0] for i in combs_tup], [i[1] for i in combs_tup]]) # Calculate distance (vectorized) dist = np.sqrt( np.sum(np.square(distance_matrix[combs[0], combs[1]]), axis=0)) return dist
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.ndarray Notes ----- This function can perhaps be quickened by calculating the sum of the distances. The calculated distances, as they are right now, are only used in a relative way. Purely summing distances would lead to the same result, at a perhaps quicker rate. """ combs_tup = np.array(tuple(combinations(indices, 2))) # Put indices from tuples into two-dimensional array. combs = np.array([[i[0] for i in combs_tup], [i[1] for i in combs_tup]]) # Calculate distance (vectorized) dist = np.sqrt( np.sum(np.square(distance_matrix[combs[0], combs[1]]), axis=0)) return dist
[ "def", "sum_distances", "(", "self", ",", "indices", ",", "distance_matrix", ")", ":", "combs_tup", "=", "np", ".", "array", "(", "tuple", "(", "combinations", "(", "indices", ",", "2", ")", ")", ")", "# Put indices from tuples into two-dimensional array.", "combs", "=", "np", ".", "array", "(", "[", "[", "i", "[", "0", "]", "for", "i", "in", "combs_tup", "]", ",", "[", "i", "[", "1", "]", "for", "i", "in", "combs_tup", "]", "]", ")", "# Calculate distance (vectorized)", "dist", "=", "np", ".", "sqrt", "(", "np", ".", "sum", "(", "np", ".", "square", "(", "distance_matrix", "[", "combs", "[", "0", "]", ",", "combs", "[", "1", "]", "]", ")", ",", "axis", "=", "0", ")", ")", "return", "dist" ]
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 perhaps be quickened by calculating the sum of the distances. The calculated distances, as they are right now, are only used in a relative way. Purely summing distances would lead to the same result, at a perhaps quicker rate.
[ "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 Returns ------- list ''' if len(indices_list) != len(distances): msg = "Indices and distances are lists of different length." + \ "Length indices_list = {} and length distances = {}." + \ "In loop i = {} and m = {}" raise ValueError(msg.format( len(indices_list), len(distances), i, m)) max_index = tuple(distances.argsort()[-1:][::-1]) return indices_list[max_index[0]]
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 Returns ------- list ''' if len(indices_list) != len(distances): msg = "Indices and distances are lists of different length." + \ "Length indices_list = {} and length distances = {}." + \ "In loop i = {} and m = {}" raise ValueError(msg.format( len(indices_list), len(distances), i, m)) max_index = tuple(distances.argsort()[-1:][::-1]) return indices_list[max_index[0]]
[ "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.\"", "+", "\"Length indices_list = {} and length distances = {}.\"", "+", "\"In loop i = {} and m = {}\"", "raise", "ValueError", "(", "msg", ".", "format", "(", "len", "(", "indices_list", ")", ",", "len", "(", "distances", ")", ",", "i", ",", "m", ")", ")", "max_index", "=", "tuple", "(", "distances", ".", "argsort", "(", ")", "[", "-", "1", ":", "]", "[", ":", ":", "-", "1", "]", ")", "return", "indices_list", "[", "max_index", "[", "0", "]", "]" ]
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), (1, 2, 4), (1, 2, 5)] ''' list_new_indices = [] for i in range(0, len(distance_matrix)): if i not in indices: list_new_indices.append(indices + (i,)) return list_new_indices
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), (1, 2, 4), (1, 2, 5)] ''' list_new_indices = [] for i in range(0, len(distance_matrix)): if i not in indices: list_new_indices.append(indices + (i,)) return list_new_indices
[ "def", "add_indices", "(", "self", ",", "indices", ",", "distance_matrix", ")", ":", "list_new_indices", "=", "[", "]", "for", "i", "in", "range", "(", "0", ",", "len", "(", "distance_matrix", ")", ")", ":", "if", "i", "not", "in", "indices", ":", "list_new_indices", ".", "append", "(", "indices", "+", "(", "i", ",", ")", ")", "return", "list_new_indices" ]
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 (or optionally another # metric) names_sorted = _sort_Si(Si, 'names', sortby) mu_star_sorted = _sort_Si(Si, 'mu_star', sortby) mu_star_conf_sorted = _sort_Si(Si, 'mu_star_conf', sortby) # Plot horizontal barchart y_pos = np.arange(len(mu_star_sorted)) plot_names = names_sorted out = ax.barh(y_pos, mu_star_sorted, xerr=mu_star_conf_sorted, align='center', ecolor='black', **param_dict) ax.set_yticks(y_pos) ax.set_yticklabels(plot_names) ax.set_xlabel(r'$\mu^\star$' + unit) ax.set_ylim(min(y_pos)-1, max(y_pos)+1) return out
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 (or optionally another # metric) names_sorted = _sort_Si(Si, 'names', sortby) mu_star_sorted = _sort_Si(Si, 'mu_star', sortby) mu_star_conf_sorted = _sort_Si(Si, 'mu_star_conf', sortby) # Plot horizontal barchart y_pos = np.arange(len(mu_star_sorted)) plot_names = names_sorted out = ax.barh(y_pos, mu_star_sorted, xerr=mu_star_conf_sorted, align='center', ecolor='black', **param_dict) ax.set_yticks(y_pos) ax.set_yticklabels(plot_names) ax.set_xlabel(r'$\mu^\star$' + unit) ax.set_ylim(min(y_pos)-1, max(y_pos)+1) return out
[ "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 plotted elements by mu_star (or optionally another", "# metric)", "names_sorted", "=", "_sort_Si", "(", "Si", ",", "'names'", ",", "sortby", ")", "mu_star_sorted", "=", "_sort_Si", "(", "Si", ",", "'mu_star'", ",", "sortby", ")", "mu_star_conf_sorted", "=", "_sort_Si", "(", "Si", ",", "'mu_star_conf'", ",", "sortby", ")", "# Plot horizontal barchart", "y_pos", "=", "np", ".", "arange", "(", "len", "(", "mu_star_sorted", ")", ")", "plot_names", "=", "names_sorted", "out", "=", "ax", ".", "barh", "(", "y_pos", ",", "mu_star_sorted", ",", "xerr", "=", "mu_star_conf_sorted", ",", "align", "=", "'center'", ",", "ecolor", "=", "'black'", ",", "*", "*", "param_dict", ")", "ax", ".", "set_yticks", "(", "y_pos", ")", "ax", ".", "set_yticklabels", "(", "plot_names", ")", "ax", ".", "set_xlabel", "(", "r'$\\mu^\\star$'", "+", "unit", ")", "ax", ".", "set_ylim", "(", "min", "(", "y_pos", ")", "-", "1", ",", "max", "(", "y_pos", ")", "+", "1", ")", "return", "out" ]
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])) out = [] for variable in range(num_vars): ax = fig.add_subplot(framing + variable) out.append(ax.hist(input_sample[:, variable], bins=num_levels, normed=False, label=None, **param_dict)) ax.set_title('%s' % (names[variable])) ax.tick_params(axis='x', # changes apply to the x-axis which='both', # both major and minor ticks are affected bottom='off', # ticks along the bottom edge are off top='off', # ticks along the top edge are off labelbottom='off') # labels along the bottom edge off) if variable > 0: ax.tick_params(axis='y', # changes apply to the y-axis which='both', # both major and minor ticks affected labelleft='off') # labels along the left edge off) return out
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])) out = [] for variable in range(num_vars): ax = fig.add_subplot(framing + variable) out.append(ax.hist(input_sample[:, variable], bins=num_levels, normed=False, label=None, **param_dict)) ax.set_title('%s' % (names[variable])) ax.tick_params(axis='x', # changes apply to the x-axis which='both', # both major and minor ticks are affected bottom='off', # ticks along the bottom edge are off top='off', # ticks along the top edge are off labelbottom='off') # labels along the bottom edge off) if variable > 0: ax.tick_params(axis='y', # changes apply to the y-axis which='both', # both major and minor ticks affected labelleft='off') # labels along the left edge off) return out
[ "def", "sample_histograms", "(", "fig", ",", "input_sample", ",", "problem", ",", "param_dict", ")", ":", "num_vars", "=", "problem", "[", "'num_vars'", "]", "names", "=", "problem", "[", "'names'", "]", "framing", "=", "101", "+", "(", "num_vars", "*", "10", ")", "# Find number of levels", "num_levels", "=", "len", "(", "set", "(", "input_sample", "[", ":", ",", "1", "]", ")", ")", "out", "=", "[", "]", "for", "variable", "in", "range", "(", "num_vars", ")", ":", "ax", "=", "fig", ".", "add_subplot", "(", "framing", "+", "variable", ")", "out", ".", "append", "(", "ax", ".", "hist", "(", "input_sample", "[", ":", ",", "variable", "]", ",", "bins", "=", "num_levels", ",", "normed", "=", "False", ",", "label", "=", "None", ",", "*", "*", "param_dict", ")", ")", "ax", ".", "set_title", "(", "'%s'", "%", "(", "names", "[", "variable", "]", ")", ")", "ax", ".", "tick_params", "(", "axis", "=", "'x'", ",", "# changes apply to the x-axis", "which", "=", "'both'", ",", "# both major and minor ticks are affected", "bottom", "=", "'off'", ",", "# ticks along the bottom edge are off", "top", "=", "'off'", ",", "# ticks along the top edge are off", "labelbottom", "=", "'off'", ")", "# labels along the bottom edge off)", "if", "variable", ">", "0", ":", "ax", ".", "tick_params", "(", "axis", "=", "'y'", ",", "# changes apply to the y-axis", "which", "=", "'both'", ",", "# both major and minor ticks affected", "labelleft", "=", "'off'", ")", "# labels along the left edge off)", "return", "out" ]
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 = list(problem['bounds']) names = problem['names'] if num_dummy_variables > 0: bounds.extend([[0, 1] for x in range(num_dummy_variables)]) names.extend(["dummy_" + str(var) for var in range(num_dummy_variables)]) problem['bounds'] = bounds problem['names'] = names problem['num_vars'] = num_ff_vars return problem
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 = list(problem['bounds']) names = problem['names'] if num_dummy_variables > 0: bounds.extend([[0, 1] for x in range(num_dummy_variables)]) names.extend(["dummy_" + str(var) for var in range(num_dummy_variables)]) problem['bounds'] = bounds problem['names'] = names problem['num_vars'] = num_ff_vars return problem
[ "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", "(", "problem", "[", "'bounds'", "]", ")", "names", "=", "problem", "[", "'names'", "]", "if", "num_dummy_variables", ">", "0", ":", "bounds", ".", "extend", "(", "[", "[", "0", ",", "1", "]", "for", "x", "in", "range", "(", "num_dummy_variables", ")", "]", ")", "names", ".", "extend", "(", "[", "\"dummy_\"", "+", "str", "(", "var", ")", "for", "var", "in", "range", "(", "num_dummy_variables", ")", "]", ")", "problem", "[", "'bounds'", "]", "=", "bounds", "problem", "[", "'names'", "]", "=", "names", "problem", "[", "'num_vars'", "]", "=", "num_ff_vars", "return", "problem" ]
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_smallest(num_vars) # Generate the fractional factorial contrast contrast = np.vstack([hadamard(k_chosen), -hadamard(k_chosen)]) return contrast
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_smallest(num_vars) # Generate the fractional factorial contrast contrast = np.vstack([hadamard(k_chosen), -hadamard(k_chosen)]) return contrast
[ "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", "**", "find_smallest", "(", "num_vars", ")", "# Generate the fractional factorial contrast", "contrast", "=", "np", ".", "vstack", "(", "[", "hadamard", "(", "k_chosen", ")", ",", "-", "hadamard", "(", "k_chosen", ")", "]", ")", "return", "contrast" ]
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 parameters. These model inputs are intended to be used with :func:`SALib.analyze.ff.analyze`. The problem file is padded with a number of dummy variables called ``dummy_0`` required for this procedure. These dummy variables can be used as a check for errors in the analyze procedure. This algorithm is an implementation of that contained in [`Saltelli et al. 2008 <http://www.wiley.com/WileyCDA/WileyTitle/productCd-0470059974.html>`_] Arguments ========= problem : dict The problem definition Returns ======= sample : :class:`numpy.array` """ if seed: np.random.seed(seed) contrast = generate_contrast(problem) sample = np.array((contrast + 1.) / 2, dtype=np.float) problem = extend_bounds(problem) scale_samples(sample, problem['bounds']) return sample
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 parameters. These model inputs are intended to be used with :func:`SALib.analyze.ff.analyze`. The problem file is padded with a number of dummy variables called ``dummy_0`` required for this procedure. These dummy variables can be used as a check for errors in the analyze procedure. This algorithm is an implementation of that contained in [`Saltelli et al. 2008 <http://www.wiley.com/WileyCDA/WileyTitle/productCd-0470059974.html>`_] Arguments ========= problem : dict The problem definition Returns ======= sample : :class:`numpy.array` """ if seed: np.random.seed(seed) contrast = generate_contrast(problem) sample = np.array((contrast + 1.) / 2, dtype=np.float) problem = extend_bounds(problem) scale_samples(sample, problem['bounds']) return sample
[ "def", "sample", "(", "problem", ",", "seed", "=", "None", ")", ":", "if", "seed", ":", "np", ".", "random", ".", "seed", "(", "seed", ")", "contrast", "=", "generate_contrast", "(", "problem", ")", "sample", "=", "np", ".", "array", "(", "(", "contrast", "+", "1.", ")", "/", "2", ",", "dtype", "=", "np", ".", "float", ")", "problem", "=", "extend_bounds", "(", "problem", ")", "scale_samples", "(", "sample", ",", "problem", "[", "'bounds'", "]", ")", "return", "sample" ]
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 intended to be used with :func:`SALib.analyze.ff.analyze`. The problem file is padded with a number of dummy variables called ``dummy_0`` required for this procedure. These dummy variables can be used as a check for errors in the analyze procedure. This algorithm is an implementation of that contained in [`Saltelli et al. 2008 <http://www.wiley.com/WileyCDA/WileyTitle/productCd-0470059974.html>`_] Arguments ========= problem : dict The problem definition Returns ======= sample : :class:`numpy.array`
[ "Generates", "model", "inputs", "using", "a", "fractional", "factorial", "sample" ]
9744d73bb17cfcffc8282c7dc4a727efdc4bea3f
https://github.com/SALib/SALib/blob/9744d73bb17cfcffc8282c7dc4a727efdc4bea3f/src/SALib/sample/ff.py#L80-L113