code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
''' Build a list of sink proxies. sink proxies are a two-level ordered dictionary. The first level contains the lst of drivers, and the second level contains the list of sink proxies for each driver: drv1-->sink1 | |->sink2 | drv2-->sink1 |->sink2 ''' sink_proxies = Orde...
def make_sink_proxies(drivers)
Build a list of sink proxies. sink proxies are a two-level ordered dictionary. The first level contains the lst of drivers, and the second level contains the list of sink proxies for each driver: drv1-->sink1 | |->sink2 | drv2-->sink1 |->sink2
4.493845
2.297368
1.956084
chrom = variant.CHROM if chrom.startswith(('chr', 'CHR', 'Chr')): chrom = chrom[3:] pos = int(variant.POS) variant_id = get_variant_id(variant) ref = variant.REF alt = variant.ALT[0] maf = get_maf(variant) profile_variant = ProfileVariant( variant_id=variant_id...
def build_profile_variant(variant)
Returns a ProfileVariant object Args: variant (cyvcf2.Variant) Returns: variant (models.ProfileVariant)
2.469413
2.338
1.056208
vcf_obj.add_info_to_header( { 'ID':"Obs", 'Number': '1', 'Type': 'Integer', 'Description': "The number of observations for the variant"} ) if not sv: vcf_obj.add_info_to_header( { 'ID':"Hom", 'N...
def add_headers(vcf_obj, nr_cases=None, sv=False)
Add loqus specific information to a VCF header Args: vcf_obj(cyvcf2.VCF)
2.506294
2.544857
0.984847
LOG.debug("Check if file end is correct") if not os.path.exists(file_path): raise IOError("No such file:{0}".format(file_path)) if not os.path.splitext(file_path)[-1] in VALID_ENDINGS: raise IOError("Not a valid vcf file name: {}".format(file_path)) vcf_obj = VCF(file_path) ...
def get_file_handle(file_path)
Return cyvcf2 VCF object Args: file_path(str) Returns: vcf_obj(cyvcf2.VCF)
3.964235
3.599606
1.101297
LOG.info("Check if vcf is on correct format...") vcf = VCF(vcf_path) individuals = vcf.samples variant_type = None previous_pos = None previous_chrom = None posititon_variants = set() nr_variants = 0 for nr_variants,variant in enumerate(vcf,1): # Check the type of v...
def check_vcf(vcf_path, expected_type='snv')
Check if there are any problems with the vcf file Args: vcf_path(str) expected_type(str): 'sv' or 'snv' Returns: vcf_info(dict): dict like { 'nr_variants':<INT>, 'variant_type': <STR> in ['snv', 'sv'], 'individuals': <LIST> individual positio...
3.094148
2.934842
1.054281
if s == '': return True rm = DN_REGEX.match(s) return rm is not None and rm.group(0) == s
def is_dn(s)
Return True if s is a LDAP DN.
5.075338
5.137645
0.987872
if len(line) <= self._cols: self._output_file.write(line) self._output_file.write(self._line_sep) else: pos = self._cols self._output_file.write(line[0:self._cols]) self._output_file.write(self._line_sep) while pos < len(li...
def _fold_line(self, line)
Write string line as one or more folded lines.
2.023917
1.932225
1.047454
return attr_type.lower() in self._base64_attrs or \ isinstance(attr_value, bytes) or \ UNSAFE_STRING_RE.search(attr_value) is not None
def _needs_base64_encoding(self, attr_type, attr_value)
Return True if attr_value has to be base-64 encoded. This is the case because of special chars or because attr_type is in self._base64_attrs
4.614937
3.806466
1.212394
if self._needs_base64_encoding(attr_type, attr_value): if not isinstance(attr_value, bytes): attr_value = attr_value.encode(self._encoding) encoded = base64.encodestring(attr_value)\ .replace(b'\n', b'')\ .decode('ascii') ...
def _unparse_attr(self, attr_type, attr_value)
Write a single attribute type/value pair.
3.002253
2.840899
1.056797
for attr_type in sorted(entry.keys()): for attr_value in entry[attr_type]: self._unparse_attr(attr_type, attr_value)
def _unparse_entry_record(self, entry)
:type entry: Dict[string, List[string]] :param entry: Dictionary holding an entry
3.508586
3.736234
0.93907
if mod_len == 2: changetype = 'add' elif mod_len == 3: changetype = 'modify' else: raise ValueError("modlist item of wrong length") self._unparse_attr('changetype', changetype)
def _unparse_changetype(self, mod_len)
Detect and write the changetype.
3.899757
3.78967
1.029049
mod_len = len(modlist[0]) self._unparse_changetype(mod_len) for mod in modlist: if len(mod) != mod_len: raise ValueError("Subsequent modlist item of wrong length") if mod_len == 2: mod_type, mod_vals = mod elif mod_le...
def _unparse_change_record(self, modlist)
:type modlist: List[Tuple] :param modlist: List of additions (2-tuple) or modifications (3-tuple)
3.458162
3.328884
1.038835
self._unparse_attr('dn', dn) if isinstance(record, dict): self._unparse_entry_record(record) elif isinstance(record, list): self._unparse_change_record(record) else: raise ValueError("Argument record must be dictionary or list") self._...
def unparse(self, dn, record)
Write an entry or change record to the output file. :type dn: string :param dn: distinguished name :type record: Union[Dict[string, List[string]], List[Tuple]] :param record: Either a dictionary holding an entry or a list of additions (2-tuple) or modifications (3-tuple).
3.926381
3.365209
1.166757
if s[-2:] == b'\r\n': return s[:-2] elif s[-1:] == b'\n': return s[:-1] else: return s
def _strip_line_sep(self, s)
Strip trailing line separators from s, but no other whitespaces.
2.294411
2.111041
1.086862
line = self._input_file.readline() while line: self.line_counter += 1 self.byte_counter += len(line) line = self._strip_line_sep(line) nextline = self._input_file.readline() while nextline and nextline[:1] == b' ': li...
def _iter_unfolded_lines(self)
Iter input unfoled lines. Skip comments.
2.933665
2.695311
1.088433
lines = [] for line in self._iter_unfolded_lines(): if line: lines.append(line) elif lines: self.records_read += 1 yield lines lines = [] if lines: self.records_read += 1 yiel...
def _iter_blocks(self)
Iter input lines in blocks separated by blank lines.
3.409747
2.791054
1.22167
colon_pos = line.index(b':') attr_type = line[0:colon_pos].decode('ascii') if line[colon_pos:].startswith(b'::'): attr_value = base64.decodestring(line[colon_pos + 2:]) elif line[colon_pos:].startswith(b':<'): url = line[colon_pos + 2:].strip() ...
def _parse_attr(self, line)
Parse a single attribute type/value pair.
2.697091
2.605634
1.0351
if dn is not None: self._error('Two lines starting with dn: in one record.') if not is_dn(attr_value): self._error('No valid string-representation of ' 'distinguished name %s.' % attr_value)
def _check_dn(self, dn, attr_value)
Check dn attribute for issues.
8.957505
8.751017
1.023596
if dn is None: self._error('Read changetype: before getting valid dn: line.') if changetype is not None: self._error('Two lines starting with changetype: in one record.') if attr_value not in CHANGE_TYPES: self._error('changetype value %s is invalid.'...
def _check_changetype(self, dn, changetype, attr_value)
Check changetype attribute for issues.
8.22219
7.804609
1.053504
dn = None entry = OrderedDict() for line in lines: attr_type, attr_value = self._parse_attr(line) if attr_type == 'dn': self._check_dn(dn, attr_value) dn = attr_value elif attr_type == 'version' and dn is None: ...
def _parse_entry_record(self, lines)
Parse a single entry record from a list of lines.
3.096076
3.044065
1.017086
genes, clusters = m.shape cells = X.shape[1] nonzeros = (X!=0) def objective(w): # convert w into a matrix first... because it's a vector for # optimization purposes w = w.reshape((m.shape[1], X.shape[1])) d = m.dot(w)+eps # derivative of objective wrt all el...
def _create_w_objective(m, X, Z=None)
Creates an objective function and its derivative for W, given M and X (data) Args: m (array): genes x clusters X (array): genes x cells Z (array): zero-inflation parameters - genes x 1
8.972672
8.342655
1.075518
genes, cells = data.shape # TODO: estimate ZIP parameter? if init_means is None: means, assignments = kmeans_pp(data, clusters) else: means = init_means.copy() clusters = means.shape[1] w_init = np.random.random(cells*clusters) if init_weights is not None: if len...
def zip_estimate_state(data, clusters, init_means=None, init_weights=None, max_iters=10, tol=1e-4, disp=True, inner_max_iters=400, normalize=True)
Uses a Zero-inflated Poisson Mixture model to estimate cell states and cell state mixing weights. Args: data (array): genes x cells clusters (int): number of mixture components init_means (array, optional): initial centers - genes x clusters. Default: kmeans++ initializations in...
2.734342
2.606453
1.049066
# TODO: what if there is missing data for a given gene? # missing data could be if all the entires are -1. genes, cells = data.shape if sparse.issparse(data) and not sparse.isspmatrix_csc(data): data = sparse.csc_matrix(data) num_known_centers = 0 if centers is None: centers...
def kmeans_pp(data, k, centers=None)
Generates kmeans++ initial centers. Args: data (array): A 2d array- genes x cells k (int): Number of clusters centers (array, optional): if provided, these are one or more known cluster centers. 2d array of genes x number of centers (<=k). Returns: centers - a genes x k array o...
3.113436
3.055977
1.018802
# TODO: be able to use a combination of fixed and unknown starting points # e.g., have init values only for certain genes, have a row of all # zeros indicating that kmeans++ should be used for that row. genes, cells = data.shape #print 'starting: ', centers if sparse.issparse(data) and not ...
def poisson_cluster(data, k, init=None, max_iters=100)
Performs Poisson hard EM on the given data. Args: data (array): A 2d array- genes x cells. Can be dense or sparse; for best performance, sparse matrices should be in CSC format. k (int): Number of clusters init (array, optional): Initial centers - genes x k array. Default: None, use kmeans+...
3.538291
3.333218
1.061524
adapter = ctx.obj['adapter'] cases = [] if case_id: case_obj = adapter.case({'case_id':case_id}) if not case_obj: LOG.info("Case {0} does not exist in database".format(case_id)) return case_obj['_id'] = str(case_obj['_id']) cases.append(case_obj...
def cases(ctx, case_id, to_json)
Display cases in the database.
2.336718
2.260662
1.033643
if sv_type: variant_type = 'sv' adapter = ctx.obj['adapter'] if (start or end): if not (chromosome and start and end): LOG.warning("Regions must be specified with chromosome, start and end") return if variant_id: variant = adapter.get_variant({'_id...
def variants(ctx, variant_id, chromosome, end_chromosome, start, end, variant_type, sv_type)
Display variants in the database.
2.823407
2.801732
1.007736
adapter = ctx.obj['adapter'] if view: click.echo(adapter.indexes()) return adapter.ensure_indexes()
def index(ctx, view)
Index the database.
8.644665
6.998699
1.235182
r A = asarray(A, float) B = asarray(B, float) if A.ndim == 1 and B.ndim == 1: if out is None: return dot(A, B) return dot(A, B, out) if out is None: out = empty((A.shape[0],), float) return einsum("ij,ji->i", A, B, out=out)
def dotd(A, B, out=None)
r"""Diagonal of :math:`\mathrm A\mathrm B^\intercal`. If ``A`` is :math:`n\times p` and ``B`` is :math:`p\times n`, it is done in :math:`O(pn)`. Args: A (array_like): Left matrix. B (array_like): Right matrix. out (:class:`numpy.ndarray`, optional): copy result to. Returns: ...
2.474536
2.719702
0.909855
r L = asarray(L, float) R = asarray(R, float) if left is None: ok = min(L.ndim, R.ndim) == 1 and max(L.ndim, R.ndim) == 2 if not ok: msg = "Wrong array layout. One array should have" msg += " ndim=1 and the other one ndim=2." raise ValueError(msg) ...
def ddot(L, R, left=None, out=None)
r"""Dot product of a matrix and a diagonal one. Args: L (array_like): Left matrix. R (array_like): Right matrix. out (:class:`numpy.ndarray`, optional): copy result to. Returns: :class:`numpy.ndarray`: Resulting matrix.
2.664276
2.935945
0.907468
r L = asarray(L, float) layout_error = "Wrong matrix layout." if L.ndim != 2: raise ValueError(layout_error) if L.shape[0] != L.shape[1]: raise ValueError(layout_error) if out is None: out = empty((L.shape[0], L.shape[1]), float) return einsum("ij,kj->ik", L, L, ...
def cdot(L, out=None)
r"""Product of a Cholesky matrix with itself transposed. Args: L (array_like): Cholesky matrix. out (:class:`numpy.ndarray`, optional): copy result to. Returns: :class:`numpy.ndarray`: :math:`\mathrm L\mathrm L^\intercal`.
3.252251
3.933065
0.8269
from scipy.stats import rankdata if hasattr(a, "dtype") and issubdtype(a.dtype, integer): raise ValueError("Integer type is not supported.") if isinstance(a, (tuple, list)): if inplace: raise ValueError("Can't use `inplace=True` for {}.".format(type(a))) a = asarra...
def nanrankdata(a, axis=-1, inplace=False)
Rank data for arrays contaning NaN values. Parameters ---------- X : array_like Array of values. axis : int, optional Axis value. Defaults to `1`. inplace : bool, optional Defaults to `False`. Returns ------- array_like Ranked array. Examples -...
2.621747
2.871679
0.912967
r egvals = eigvalsh(K) return npsum(log(egvals[egvals > epsilon]))
def plogdet(K)
r"""Log of the pseudo-determinant. It assumes that ``K`` is a positive semi-definite matrix. Args: K (array_like): matrix. Returns: float: log of the pseudo-determinant.
17.546186
26.927982
0.651597
r (S, Q) = eigh(K) nok = abs(max(Q[0].min(), Q[0].max(), key=abs)) < epsilon nok = nok and abs(max(K.min(), K.max(), key=abs)) >= epsilon if nok: from scipy.linalg import eigh as sp_eigh (S, Q) = sp_eigh(K) ok = S >= epsilon nok = logical_not(ok) S0 = S[ok] Q0 = Q...
def economic_qs(K, epsilon=sqrt(finfo(float).eps))
r"""Economic eigen decomposition for symmetric matrices. A symmetric matrix ``K`` can be decomposed in :math:`\mathrm Q_0 \mathrm S_0 \mathrm Q_0^\intercal + \mathrm Q_1\ \mathrm S_1 \mathrm Q_1^ \intercal`, where :math:`\mathrm S_1` is a zero matrix with size determined by ``K``'s rank deficiency. ...
4.541814
3.87721
1.171413
r import dask.array as da if not isinstance(G, da.Array): G = asarray(G, float) if G.shape[0] > G.shape[1]: (Q, Ssq, _) = svd(G, full_matrices=True) S0 = Ssq ** 2 rank = len(S0) Q0, Q1 = Q[:, :rank], Q[:, rank:] return ((Q0, Q1), S0) return economic...
def economic_qs_linear(G)
r"""Economic eigen decomposition for symmetric matrices ``dot(G, G.T)``. It is theoretically equivalent to ``economic_qs(dot(G, G.T))``. Refer to :func:`numpy_sugar.economic_qs` for further information. Args: G (array_like): Matrix. Returns: tuple: ``((Q0, Q1), S0)``.
4.729614
3.617104
1.307569
r n = len(shape) idx = [slice(0, s) for s in shape] g = rollaxis(mgrid[idx], 0, n + 1) return g.reshape((prod(shape), n))
def cartesian(shape)
r"""Cartesian indexing. Returns a sequence of n-tuples indexing each element of a hypothetical matrix of the given shape. Args: shape (tuple): tuple of dimensions. Returns: array_like: indices. Example ------- .. doctest:: >>> from numpy_sugar import cartesian ...
5.640339
7.206603
0.782663
r import dask.array as da if isinstance(ar, da.core.Array): return da.unique(ar) return _unique(ar)
def unique(ar)
r"""Find the unique elements of an array. It uses ``dask.array.unique`` if necessary. Args: ar (array_like): Input array. Returns: array_like: the sorted unique elements.
5.723234
5.090927
1.124203
r LU = (asarray(LU[0], float), asarray(LU[1], float)) adet = _sum(log(_abs(LU[0].diagonal()))) s = prod(sign(LU[0].diagonal())) nrows_exchange = LU[1].size - _sum(LU[1] == arange(LU[1].size, dtype="int32")) odd = nrows_exchange % 2 == 1 if odd: s *= -1.0 return (s, adet)
def lu_slogdet(LU)
r"""Natural logarithm of a LU decomposition. Args: LU (tuple): LU decomposition. Returns: tuple: sign and log-determinant.
6.404179
6.370309
1.005317
r from scipy.linalg import lu_solve as sp_lu_solve LU = (asarray(LU[0], float), asarray(LU[1], float)) b = asarray(b, float) return sp_lu_solve(LU, b, check_finite=False)
def lu_solve(LU, b)
r"""Solve for LU decomposition. Solve the linear equations :math:`\mathrm A \mathbf x = \mathbf b`, given the LU factorization of :math:`\mathrm A`. Args: LU (array_like): LU decomposition. b (array_like): Right-hand side. Returns: :class:`numpy.ndarray`: The solution to the s...
3.292393
4.764063
0.691089
r A = asarray(A, float) b = asarray(b, float) if A.ndim == 1: A = A[:, newaxis] if A.shape[1] == 1: return dot(A.T, b) / squeeze(dot(A.T, A)) rcond = finfo(double).eps * max(*A.shape) return npy_lstsq(A, b, rcond=rcond)[0]
def lstsq(A, b)
r"""Return the least-squares solution to a linear matrix equation. Args: A (array_like): Coefficient matrix. b (array_like): Ordinate values. Returns: :class:`numpy.ndarray`: Least-squares solution.
2.930496
3.359191
0.872381
r A = asarray(A, float) B = asarray(B, float) if A.ndim == 1 and B.ndim == 1: return dot(A, B) out = empty((A.shape[0],), float) out[:] = sum(A * B.T, axis=1) return out
def dotd(A, B)
r"""Diagonal of :math:`\mathrm A\mathrm B^\intercal`. If ``A`` is :math:`n\times p` and ``B`` is :math:`p\times n`, it is done in :math:`O(pn)`. Args: A (array_like): Left matrix. B (array_like): Right matrix. Returns: :class:`numpy.ndarray`: Resulting diagonal.
2.922698
3.460728
0.844533
r from scipy.linalg import svd G = asarray(G, float) (U, S, V) = svd(G, full_matrices=False, check_finite=False) ok = S >= epsilon S = S[ok] U = U[:, ok] V = V[ok, :] return (U, S, V)
def economic_svd(G, epsilon=sqrt(finfo(float).eps))
r"""Economic Singular Value Decomposition. Args: G (array_like): Matrix to be factorized. epsilon (float): Threshold on the square root of the eigen values. Default is ``sqrt(finfo(float).eps)``. Returns: :class:`numpy.ndarray`: Unitary matrix. :class:`...
2.750277
3.063977
0.897617
r n = _norm(A[0, 0], A[1, 0]) u0 = A[0, 0] - n u1 = A[1, 0] nu = _norm(u0, u1) with errstate(invalid="ignore", divide="ignore"): v0 = nan_to_num(u0 / nu) v1 = nan_to_num(u1 / nu) B00 = 1 - 2 * v0 * v0 B01 = 0 - 2 * v0 * v1 B11 = 1 - 2 * v1 * v1 D00 = B00 * A[0...
def hsolve(A, y)
r"""Solver for the linear equations of two variables and equations only. It uses Householder reductions to solve ``Ax = y`` in a robust manner. Parameters ---------- A : array_like Coefficient matrix. y : array_like Ordinate values. Returns ------- :class:`numpy.ndarra...
1.808403
1.821883
0.992601
r A = asarray(A, float) b = asarray(b, float) if A.shape[0] == 1: with errstate(divide="ignore"): A_ = array([[1.0 / A[0, 0]]]) if not isfinite(A_[0, 0]): raise LinAlgError("Division error.") return dot(A_, b) elif A.shape[0] == 2: a = A[0, ...
def solve(A, b)
r"""Solve for the linear equations :math:`\mathrm A \mathbf x = \mathbf b`. Args: A (array_like): Coefficient matrix. b (array_like): Ordinate values. Returns: :class:`numpy.ndarray`: Solution ``x``.
2.612144
2.782736
0.938696
r A = asarray(A, float) b = asarray(b, float) if A.shape[0] == 0: return zeros((A.shape[1],)) if A.shape[1] == 0: return zeros((0,)) try: x = lstsq(A, b, rcond=epsilon) r = sum(x[3] > epsilon) if r == 0: return zeros(A.shape[1]) return ...
def rsolve(A, b, epsilon=_epsilon)
r"""Robust solve for the linear equations. Args: A (array_like): Coefficient matrix. b (array_like): Ordinate values. Returns: :class:`numpy.ndarray`: Solution ``x``.
2.806751
2.935681
0.956082
r from numpy import dot, zeros, asarray A = asarray(A) B = asarray(B) C = asarray(C) if out is None: out = zeros((B.shape[0], A.shape[0])) dot(B, dot(C, A.T), out=out) return out
def kron_dot(A, B, C, out=None)
r""" Kronecker product followed by dot product. Let :math:`\mathrm A`, :math:`\mathrm B`, and :math:`\mathrm C` be matrices of dimensions :math:`p\times p`, :math:`n\times d`, and :math:`d\times p`. It computes .. math:: \text{unvec}((\mathrm A\otimes\mathrm B)\text{vec}(\mathrm C)) ...
2.836184
3.591315
0.789734
B = empty_like(A) B[:] = A B[diag_indices_from(B)] += sqrt(finfo(float).eps) try: cholesky(B) except LinAlgError: return False return True
def check_semidefinite_positiveness(A)
Check if ``A`` is a semi-definite positive matrix. Args: A (array_like): Matrix. Returns: bool: ``True`` if ``A`` is definite positive; ``False`` otherwise.
3.865128
4.676658
0.826472
A = asanyarray(A) if A.ndim != 2: raise ValueError("Checks symmetry only for bi-dimensional arrays.") if A.shape[0] != A.shape[1]: return False return abs(A - A.T).max() < sqrt(finfo(float).eps)
def check_symmetry(A)
Check if ``A`` is a symmetric matrix. Args: A (array_like): Matrix. Returns: bool: ``True`` if ``A`` is symmetric; ``False`` otherwise.
3.837139
3.890953
0.986169
r from scipy.linalg import cho_solve as sp_cho_solve L = asarray(L, float) b = asarray(b, float) if L.size == 0: if b.size != 0: raise ValueError("Dimension mismatch between L and b.") return empty(b.shape) return sp_cho_solve((L, True), b, check_finite=False)
def cho_solve(L, b)
r"""Solve for Cholesky decomposition. Solve the linear equations :math:`\mathrm A \mathbf x = \mathbf b`, given the Cholesky factorization of :math:`\mathrm A`. Args: L (array_like): Lower triangular matrix. b (array_like): Right-hand side. Returns: :class:`numpy.ndarray`: The...
2.851417
3.687916
0.773178
'''get filename and check if in getcwd then get from the package resources folder ''' if fname is not None: filename = os.path.expanduser(fname) resource_package = opentargets_validator.__name__ resource_path = os.path.sep.join(('resources', filename)) abs_filename ...
def file_or_resource(fname=None)
get filename and check if in getcwd then get from the package resources folder
4.527247
2.986102
1.516106
r from scipy.linalg import solve_triangular A = asarray(A, float) b = asarray(b, float) return solve_triangular(A, b, lower=True, check_finite=False)
def stl(A, b)
r"""Shortcut to ``solve_triangular(A, b, lower=True, check_finite=False)``. Solve linear systems :math:`\mathrm A \mathbf x = \mathbf b` when :math:`\mathrm A` is a lower-triangular matrix. Args: A (array_like): A lower-triangular matrix. b (array_like): Ordinate values. Returns: ...
2.780928
3.369268
0.82538
try: import win32api except ImportError: if (2, 8) < sys.version_info < (3, 5): logger.info( "Resolving executable names only supported on Python 2.7 and 3.5+" ) else: logger.warning( "Could not resolve executable n...
def _windows_resolve(command)
Try and find the full path and file extension of the executable to run. This is so that e.g. calls to 'somescript' will point at 'somescript.cmd' without the need to set shell=True in the subprocess. If the executable contains periods it is a special case. Here the win32api call will fail to resolve the...
3.04215
2.841189
1.070731
warnings.warn( "procrunner.run_process_dummy() is deprecated", DeprecationWarning, stacklevel=2 ) time_start = time.strftime("%Y-%m-%d %H:%M:%S GMT", time.gmtime()) logger.info("run_process is disabled. Requested command: %s", command) result = ReturnObject( { "exi...
def run_process_dummy(command, **kwargs)
A stand-in function that returns a valid result dictionary indicating a successful execution. The external process is not run.
3.226353
3.216085
1.003193
warnings.warn( "procrunner.run_process() is deprecated and has been renamed to run()", DeprecationWarning, stacklevel=2, ) return run(*args, **kwargs)
def run_process(*args, **kwargs)
API used up to version 0.2.0.
3.761628
3.35486
1.121247
data = self._decoder.decode(data) if not data: return self._buffer += data if "\n" in data: to_print, remainder = self._buffer.rsplit("\n") if self._print: try: print(to_print) except Unicode...
def add(self, data)
Add a single character to buffer. If one or more full lines are found, print them (if desired) and pass to callback function.
3.599373
3.132623
1.148996
self._buffer += self._decoder.decode(b"", final=True) if self._buffer: if self._print: print(self._buffer) if self._callback: self._callback(self._buffer) self._buffer = ""
def flush(self)
Print/send any remaining data to callback function.
3.815506
3.188738
1.196557
self._closing = True if not self.has_finished(): if self._debug: # Main thread overtook stream reading thread. underrun_debug_timer = timeit.default_timer() logger.warning("NBSR underrun") self._thread.join() if...
def get_output(self)
Retrieve the stored data in full. This call may block if the reading thread has not yet terminated.
4.434824
4.190509
1.058302
r A = asarray(A, float) B = asarray(B, float) layout_error = "Wrong matrix layout." if not (len(A.shape) == 2 and len(B.shape) == 2): raise ValueError(layout_error) if not (A.shape[1] == B.shape[0] and A.shape[0] == B.shape[1]): raise ValueError(layout_error) return _sum(...
def trace2(A, B)
r"""Trace of :math:`\mathrm A \mathrm B^\intercal`. Args: A (array_like): Left-hand side. B (array_like): Right-hand side. Returns: float: Trace of :math:`\mathrm A \mathrm B^\intercal`.
2.856702
3.290759
0.868098
r A = asarray(A, float) D = asarray(D, float) if out is None: out = copy(A) else: copyto(out, A) einsum("ii->i", out)[:] += D return out
def sum2diag(A, D, out=None)
r"""Add values ``D`` to the diagonal of matrix ``A``. Args: A (array_like): Left-hand side. D (array_like or float): Values to add. out (:class:`numpy.ndarray`, optional): copy result to. Returns: :class:`numpy.ndarray`: Resulting matrix.
3.908916
4.773285
0.818915
if ignore: h2k_map = _exclude_ignorechar(ignore, H2K_TABLE.copy()) return _convert(text, h2k_map) return _convert(text, H2K_TABLE)
def hira2kata(text, ignore='')
Convert Hiragana to Full-width (Zenkaku) Katakana. Parameters ---------- text : str Hiragana string. ignore : str Characters to be ignored in converting. Return ------ str Katakana string. Examples -------- >>> print(jaconv.hira2kata('ともえまみ')) トモエマミ...
6.010128
9.081553
0.661795
if ignore: h2hk_map = _exclude_ignorechar(ignore, H2HK_TABLE.copy()) return _convert(text, h2hk_map) return _convert(text, H2HK_TABLE)
def hira2hkata(text, ignore='')
Convert Hiragana to Half-width (Hankaku) Katakana Parameters ---------- text : str Hiragana string. ignore : str Characters to be ignored in converting. Return ------ str Half-width Katakana string. Examples -------- >>> print(jaconv.hira2hkata('ともえまみ')...
5.892234
8.034301
0.733385
if ignore: k2h_map = _exclude_ignorechar(ignore, K2H_TABLE.copy()) return _convert(text, k2h_map) return _convert(text, K2H_TABLE)
def kata2hira(text, ignore='')
Convert Full-width Katakana to Hiragana Parameters ---------- text : str Full-width Katakana string. ignore : str Characters to be ignored in converting. Return ------ str Hiragana string. Examples -------- >>> print(jaconv.kata2hira('巴マミ')) 巴まみ ...
6.433354
8.943551
0.719329
def _conv_dakuten(text): text = text.replace("ガ", "ガ").replace("ギ", "ギ") text = text.replace("グ", "グ").replace("ゲ", "ゲ") text = text.replace("ゴ", "ゴ").replace("ザ", "ザ") text = text.replace("ジ", "ジ").replace("ズ", "ズ") text = text.replace("ゼ", "ゼ").replac...
def h2z(text, ignore='', kana=True, ascii=False, digit=False)
Convert Half-width (Hankaku) Katakana to Full-width (Zenkaku) Katakana Parameters ---------- text : str Half-width Katakana string. ignore : str Characters to be ignored in converting. kana : bool Either converting Kana or not. ascii : bool Either converting asci...
1.48537
1.535725
0.967211
if ascii: if digit: if kana: z2h_map = Z2H_ALL else: z2h_map = Z2H_AD elif kana: z2h_map = Z2H_AK else: z2h_map = Z2H_A elif digit: if kana: z2h_map = Z2H_DK else: ...
def z2h(text, ignore='', kana=True, ascii=False, digit=False)
Convert Full-width (Zenkaku) Katakana to Half-width (Hankaku) Katakana Parameters ---------- text : str Full-width Katakana string. ignore : str Characters to be ignored in converting. kana : bool Either converting Kana or not. ascii : bool Either converting asci...
2.172539
2.554079
0.850615
text = text.replace('〜', 'ー').replace('~', 'ー') text = text.replace("’", "'").replace('”', '"').replace('“', '``') text = text.replace('―', '-').replace('‐', '-').replace('˗', '-').replace('֊', '-') text = text.replace('‐', '-').replace('‑', '-').replace('‒', '-').replace('–', '-') text = text....
def normalize(text, mode='NFKC', ignore='')
Convert Half-width (Hankaku) Katakana to Full-width (Zenkaku) Katakana, Full-width (Zenkaku) ASCII and DIGIT to Half-width (Hankaku) ASCII and DIGIT. Additionally, Full-width wave dash (〜) etc. are normalized Parameters ---------- text : str Source string. mode : str Unicode...
2.395296
2.674
0.895773
import matplotlib.pyplot as plt if bins is None: bins = calc_nbins(x) h, bins = np.histogram(x, bins=bins) width = bins[1] - bins[0] center = (bins[:-1] + bins[1:]) / 2 area = sum(h * width) if isinstance(yerr, str): yerr = poisson_limits(h, yerr) if xerr == 'bin...
def histpoints(x, bins=None, xerr=None, yerr='gamma', normed=False, **kwargs)
Plot a histogram as a series of data points. Compute and draw the histogram of *x* using individual (x,y) points for the bin contents. By default, vertical poisson error bars are calculated using the gamma distribution. Horizontal error bars are omitted by default. These can be enabled using ...
2.445781
2.574567
0.949978
self._pool = self._pool or eventlet.GreenPool(size=self.pool_size) return self._pool
def pool(self)
Get an eventlet pool used to dispatch requests.
4.356588
2.654443
1.641244
if self.pid is not None: LOG.error( "The process is already running with pid {0}.".format(self.pid) ) sys.exit(exit.ALREADY_RUNNING) self.daemonize() LOG.info("Beginning run loop for process.") try: self.run() ...
def start(self)
Start the process with daemonization. If the process is already started this call should exit with code ALREADY_RUNNING. Otherwise it must call the 'daemonize' method and then call 'run'.
4.8359
3.817957
1.26662
if self.pid is None: return None try: while True: self.send(signal.SIGTERM) time.sleep(0.1) except RuntimeError as err: if "No such process" in str(err): LOG.info("Succesfully stopped the process....
def stop(self)
Stop the daemonized process. If the process is already stopped this call should exit successfully. If the process cannot be stopped this call should exit with code STOP_FAILED.
3.055189
2.758534
1.107541
if not isinstance(signum, int): raise TypeError( "Signals must be given as integers. Got {0}.".format( type(signum), ), ) if not callable(handler): raise TypeError( "Signal handlers must b...
def handle(self, signum, handler)
Set a function to run when the given signal is recieved. Multiple handlers may be assigned to a single signal. The order of handlers does not need to be preserved. 'signum' must be an integer representing a signal. 'handler' must be a callable.
3.170313
3.250712
0.975267
if not isinstance(signum, int): raise TypeError( "Signals must be given as integers. Got {0}.".format( type(signum), ), ) try: os.kill(self.pid, signum) except OSError as err: if "No...
def send(self, signum)
Send the given signal to the running process. If the process is not running a RuntimeError with a message of "No such process" should be emitted.
2.969628
2.606531
1.139303
if signum in self.kill_signals: return self.shutdown(signum) for handler in self._handlers[signum]: handler()
def _handle_signals(self, signum, frame)
Handler for all signals. This method must be used to handle all signals for the process. It is responsible for runnin the appropriate signal handlers registered with the 'handle' method unless they are shutdown signals. Shutdown signals must trigger the 'shutdown' method.
7.040445
6.102699
1.153661
dirty = False for handler in self._handlers[signum]: try: handler() except: LOG.exception("A shutdown handler failed to execute:") dirty = True del self.pid if dirty: sys.exit(exit.SHUTDOW...
def shutdown(self, signum)
Handle all signals which trigger a process stop. This method should run all appropriate signal handlers registered through the 'handle' method. At the end it should cause the process to exit with a status code. If any of the handlers raise an exception the exit code should be SHUTDOWN_F...
7.190215
6.183275
1.162849
if path.startswith("gs://"): fs = gcsfs.GCSFileSystem(token=get_gcloud_token()) for sub_f in fs.ls(path): if sub_f.endswith("/") and sub_f.split("/")[-2] == FILES_FOLDER: return "gs://" + sub_f return path if path.startswith("hdfs://"): return pat...
def preprocess_path(path)
Given a dataset path, the following structure is to be expected: - path/ - files/ - S_00000.gdm - S_00000.gdm.meta - S_00001.gdm - S_00001.gdm.meta - ... - schema.xml - [profile.xml] ...
3.003207
3.079218
0.975315
all_files = os.listdir(files) meta_files = set(map(lambda y: y[: -9], filter(lambda x: x.endswith(".gdm.meta"), all_files))) regs_files = set(map(lambda y: y[: -4], filter(lambda x: x.endswith(".gdm"), all_files))) return meta_files == regs_files
def check_for_dataset(files)
A GDM dataset has the form: - S_00000.gdm - S_00000.gdm.meta - S_00001.gdm - S_00001.gdm.meta - ... - schema.xml - [profile.xml] - [web_profile.xml] :param files: path of the dataset :return: True if the path contains a gdm dataset
3.576409
2.947576
1.213339
from .. import GDataframe from .. import GMQLDataset pmg = get_python_manager() local_path = preprocess_path(local_path) if all_load: # load directly the metadata for exploration meta = MetaLoaderFile.load_meta_from_path(local_path) if isinstance(parser, RegionParser)...
def load_from_path(local_path=None, parser=None, all_load=False)
Loads the data from a local path into a GMQLDataset. The loading of the files is "lazy", which means that the files are loaded only when the user does a materialization (see :func:`~gmql.dataset.GMQLDataset.GMQLDataset.materialize` ). The user can force the materialization of the data (maybe for an initial ...
4.416142
3.999329
1.104221
from .. import GMQLDataset pmg = get_python_manager() remote_manager = get_remote_manager() parser = remote_manager.get_dataset_schema(remote_name, owner) source_table = get_source_table() id = source_table.search_source(remote=remote_name) if id is None: id = source_table.add_...
def load_from_remote(remote_name, owner=None)
Loads the data from a remote repository. :param remote_name: The name of the dataset in the remote repository :param owner: (optional) The owner of the dataset. If nothing is provided, the current user is used. For public datasets use 'public'. :return: A new GMQLDataset or a GDataframe
5.913596
6.154395
0.960874
interface = _get_bytes(interface) head = ffi.new('wireless_scan_head *') with iwlib_socket() as sock: range = _get_range_info(interface, sock=sock) if iwlib.iw_scan(sock, interface, range.we_version_compiled, head) != 0: errno = ffi.errno strerror = "Error whi...
def scan(interface)
Perform a scan for access points in the area. Arguments: interface - device to use for scanning (e.g. eth1, wlan0).
4.257174
4.411459
0.965026
if (username is None) and (password is None): auth_token = self.__login_guest() elif (username is not None) and (password is not None): auth_token, fullName = self.__login_credentials(username, password) self.logger.info("You are logged as {}".format(fullName...
def login(self, username=None, password=None)
Before doing any remote operation, the user has to login to the GMQL serivice. This can be done in the two following ways: * Guest mode: the user has no credentials and uses the system only as a temporary guest * Authenticated mode: the users has credentials and a stable remote account ...
3.307164
3.181869
1.039378
url = self.address + "/logout" header = self.__check_authentication() response = requests.get(url, headers=header) if response.status_code != 200: raise ValueError("Code {}. {}".format(response.status_code, response.json().get("error")))
def logout(self)
Logout from the remote account :return: None
3.581748
3.749941
0.955148
url = self.address + "/datasets" header = self.__check_authentication() response = requests.get(url, headers=header) response = response.json() datasets = response.get("datasets") res = pd.DataFrame.from_dict(datasets) return self.process_info_list(res, "...
def get_dataset_list(self)
Returns the list of available datasets for the current user. :return: a pandas Dataframe
4.739371
4.754578
0.996802
if isinstance(owner, str): owner = owner.lower() dataset_name = owner + "." + dataset_name header = self.__check_authentication() url = self.address + "/datasets/" + dataset_name response = requests.get(url, headers=header) if response.status_co...
def get_dataset_samples(self, dataset_name, owner=None)
Get the list of samples of a specific remote dataset. :param dataset_name: the dataset name :param owner: (optional) who owns the dataset. If it is not specified, the current user is used. For public dataset use 'public'. :return: a pandas Dataframe
3.105674
3.117282
0.996276
if isinstance(owner, str): owner = owner.lower() dataset_name = owner + "." + dataset_name url = self.address + "/datasets/" + dataset_name+"/schema" header = self.__check_authentication() response = requests.get(url, headers=header) if response...
def get_dataset_schema(self, dataset_name, owner=None)
Given a dataset name, it returns a BedParser coherent with the schema of it :param dataset_name: a dataset name on the repository :param owner: (optional) who owns the dataset. If it is not specified, the current user is used. For public dataset use 'public'. :return: a BedParser
2.3382
2.301992
1.015729
url = self.address + "/datasets/" + dataset_name + "/uploadSample" header = self.__check_authentication() fields = dict() remove = False if isinstance(dataset, GDataframe): tmp_path = TempFileManager.get_new_dataset_tmp_folder() dataset.to_datas...
def upload_dataset(self, dataset, dataset_name, schema_path=None)
Upload to the repository an entire dataset from a local path :param dataset: the local path of the dataset :param dataset_name: the name you want to assign to the dataset remotely :return: None
3.369078
3.332464
1.010987
url = self.address + "/datasets/" + dataset_name header = self.__check_authentication() response = requests.delete(url, headers=header) if response.status_code != 200: raise ValueError("Code {}: {}".format(response.status_code, response.json().get("error"))) ...
def delete_dataset(self, dataset_name)
Deletes the dataset having the specified name :param dataset_name: the name that the dataset has on the repository :return: None
3.01256
2.99102
1.007202
if not os.path.isdir(local_path): os.makedirs(local_path) else: raise ValueError("Path {} already exists!".format(local_path)) local_path = os.path.join(local_path, FILES_FOLDER) os.makedirs(local_path) if how == 'zip': return self.d...
def download_dataset(self, dataset_name, local_path, how="stream")
It downloads from the repository the specified dataset and puts it in the specified local folder :param dataset_name: the name the dataset has in the repository :param local_path: where you want to save the dataset :param how: 'zip' downloads the whole dataset as a zip file and decompre...
2.116043
2.164993
0.97739
header = self.__check_authentication() header['Content-Type'] = "text/plain" output = output.lower() if output not in ['tab', 'gtf']: raise ValueError("output must be 'tab' or 'gtf'") url = self.address + "/queries/run/" + file_name + '/' + output res...
def query(self, query, output_path=None, file_name="query", output="tab")
Execute a GMQL textual query on the remote server. :param query: the string containing the query :param output_path (optional): where to store the results locally. If specified the results are downloaded locally :param file_name (optional): the name of the query :param ou...
3.535859
3.24297
1.090315
header = self.__check_authentication() status_url = self.address + "/jobs/" + jobId + "/trace" status_resp = requests.get(status_url, headers=header) if status_resp.status_code != 200: raise ValueError("Code {}. {}".format(status_resp.status_code, status_resp.json()....
def trace_job(self, jobId)
Get information about the specified remote job :param jobId: the job identifier :return: a dictionary with the information
2.973636
3.183897
0.933961
global __mode if how == "local": __mode = how elif how == "remote": __mode = how else: raise ValueError("how must be 'local' or 'remote'")
def set_mode(how)
Sets the behavior of the API :param how: if 'remote' all the execution is performed on the remote server; if 'local' all it is executed locally. Default = 'local' :return: None
3.10676
3.40699
0.911878
global __progress_bar if isinstance(how, bool): __progress_bar = how else: raise ValueError( "how must be a boolean. {} was found".format(type(how)))
def set_progress(how)
Enables or disables the progress bars for the loading, writing and downloading of datasets :param how: True if you want the progress bar, False otherwise :return: None Example:: import gmql as gl gl.set_progress(True) # abilitates progress bars # ....do something... ...
4.450314
5.510646
0.807585
global __metadata_profiling if isinstance(how, bool): __metadata_profiling = how else: raise TypeError("how must be boolean. {} was provided".format(type(how)))
def set_meta_profiling(how)
Enables or disables the profiling of metadata at the loading of a GMQLDataset :param how: True if you want to analyze the metadata when a GMQLDataset is created by a load_from_*. False otherwise. (Default=True) :return: None
3.828968
4.242117
0.902608
if self.schema_format.lower() == GTF.lower(): res = self._parse_gtf_regions(path) else: res = self._parse_tab_regions(path) return res
def parse_regions(self, path)
Given a file path, it loads it into memory as a Pandas dataframe :param path: file path :return: a Pandas Dataframe
5.286192
6.197848
0.852908
attr = ['chr', 'start', 'stop'] if self.strandPos is not None: attr.append('strand') if self.otherPos: for i, o in enumerate(self.otherPos): attr.append(o[1]) return attr
def get_attributes(self)
Returns the unordered list of attributes :return: list of strings
5.17538
5.799489
0.892386
attrs = self.get_attributes() attr_arr = np.array(attrs) poss = [self.chrPos, self.startPos, self.stopPos] if self.strandPos is not None: poss.append(self.strandPos) if self.otherPos: for o in self.otherPos: poss.append(o[0]) ...
def get_ordered_attributes(self)
Returns the ordered list of attributes :return: list of strings
4.015326
4.143114
0.969157
types = [str, int, int] if self.strandPos is not None: types.append(str) if self.otherPos: for o in self.otherPos: types.append(o[2]) return types
def get_types(self)
Returns the unordered list of data types :return: list of data types
6.049244
6.367394
0.950035
attrs = self.get_attributes() types = self.get_types() d = dict() for i,a in enumerate(attrs): d[a] = types[i] return d
def get_name_type_dict(self)
Returns a dictionary of the type {'column_name': data_type, ...} :return: dict
3.277645
3.322977
0.986358
types = self.get_types() types_arr = np.array(types) poss = [self.chrPos, self.startPos, self.stopPos] if self.strandPos is not None: poss.append(self.strandPos) if self.otherPos: for o in self.otherPos: poss.append(o[0]) i...
def get_ordered_types(self)
Returns the ordered list of data types :return: list of data types
3.802286
3.985781
0.953962
model = xmeans(None, initial_centers, kmax, tolerance, criterion, ccore) return cls(model)
def xmeans(cls, initial_centers=None, kmax=20, tolerance=0.025, criterion=splitting_type.BAYESIAN_INFORMATION_CRITERION, ccore=False)
Constructor of the x-means clustering.rst algorithm :param initial_centers: Initial coordinates of centers of clusters that are represented by list: [center1, center2, ...] Note: The dimensions of the initial centers should be same as of the dataset. :param kmax: Maximum number of clusters that...
3.651443
5.845309
0.624679
model = clarans(None, number_clusters, num_local, max_neighbour) return cls(model)
def clarans(cls, number_clusters, num_local, max_neighbour)
Constructor of the CLARANS clustering.rst algorithm :param number_clusters: the number of clusters to be allocated :param num_local: the number of local minima obtained (amount of iterations for solving the problem). :param max_neighbour: the number of local minima obtained (amount of iteration...
4.758785
7.547492
0.630512
data = cls.input_preprocess(data) model = rock(data, eps, number_clusters, threshold, ccore) return cls(model)
def rock(cls, data, eps, number_clusters, threshold=0.5, ccore=False)
Constructor of the ROCK cluster analysis algorithm :param eps: Connectivity radius (similarity threshold), points are neighbors if distance between them is less than connectivity radius :param number_clusters: Defines number of clusters that should be allocated from the input data set :param th...
4.554541
6.507534
0.699887
data = cls.input_preprocess(data) model = optics(data, eps, minpts) return cls(model)
def optics(cls, data, eps, minpts, ccore=False)
Constructor of OPTICS clustering.rst algorithm :param data: Input data that is presented as a list of points (objects), where each point is represented by list or tuple :param eps: Connectivity radius between points, points may be connected if distance between them less than the radius :param m...
6.07014
8.662183
0.700763