code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
purity = 0.0
for i in set(labels):
indices = (labels==i)
true_clusters = true_labels[indices]
if len(true_clusters)==0:
continue
counts = Counter(true_clusters)
lab, count = counts.most_common()[0]
purity += count
return float(purity)/len(labe... | def purity(labels, true_labels) | Calculates the purity score for the given labels.
Args:
labels (array): 1D array of integers
true_labels (array): 1D array of integers - true labels
Returns:
purity score - a float bewteen 0 and 1. Closer to 1 is better. | 2.876311 | 3.50679 | 0.820212 |
# use sklearn's BallTree
bt = BallTree(dim_red.T)
correct = 0
for i, l in enumerate(true_labels):
dist, ind = bt.query([dim_red[:,i]], k=2)
closest_cell = ind[0, 1]
if true_labels[closest_cell] == l:
correct += 1
return float(correct)/len(true_labels) | def nne(dim_red, true_labels) | Calculates the nearest neighbor accuracy (basically leave-one-out cross
validation with a 1NN classifier).
Args:
dim_red (array): dimensions (k, cells)
true_labels (array): 1d array of integers
Returns:
Nearest neighbor accuracy - fraction of points for which the 1NN
1NN cl... | 3.162005 | 3.2082 | 0.985601 |
N, m = data.shape
cost = ll + (N*m + m*k)*(np.log(data.sum()/(N*k)))
return cost | def mdl(ll, k, data) | Returns the minimum description length score of the model given its
log-likelihood and k, the number of cell types.
a lower cost is better... | 8.571629 | 8.686492 | 0.986777 |
data_means = data.mean(1)
data_vars = data.var(1)
nb_indices = data_means < 0.9*data_vars
return nb_indices | def find_nb_genes(data) | Finds the indices of all genes in the dataset that have
a mean < 0.9 variance. Returns an array of booleans. | 4.141282 | 2.880196 | 1.437847 |
val = gammaln(a+1) - gammaln(a-b+1) - gammaln(b+1)
return val | def log_ncr(a, b) | Returns log(nCr(a,b)), given that b<a. Does not assume that a and b
are integers (uses log-gamma). | 3.045072 | 3.213505 | 0.947586 |
# TODO: include factorial...
#data = data + eps
genes, cells = data.shape
clusters = P.shape[1]
lls = np.zeros((cells, clusters))
for c in range(clusters):
P_c = P[:,c].reshape((genes, 1))
R_c = R[:,c].reshape((genes, 1))
# don't need constant factors...
ll =... | def nb_ll(data, P, R) | Returns the negative binomial log-likelihood of the data.
Args:
data (array): genes x cells
P (array): NB success probability param - genes x clusters
R (array): NB stopping param - genes x clusters
Returns:
cells x clusters array of log-likelihoods | 3.619464 | 3.38688 | 1.068672 |
lls = nb_ll(data, P, R)
clusters = P.shape[1]
for c in range(clusters):
pass
return lls | def zinb_ll(data, P, R, Z) | Returns the zero-inflated negative binomial log-likelihood of the data. | 6.42619 | 6.921459 | 0.928444 |
p = params[0]
r = params[1]
n = len(data_row)
ll = np.sum(gammaln(data_row + r)) - np.sum(gammaln(data_row + 1))
ll -= n*gammaln(r)
ll += np.sum(data_row)*np.log(p)
ll += n*r*np.log(1-p)
return -ll | def nb_ll_row(params, data_row) | returns the negative LL of a single row.
Args:
params (array) - [p, r]
data_row (array) - 1d array of data
Returns:
LL of row | 2.494383 | 2.608417 | 0.956283 |
n = len(data_row)
d = sum(digamma(data_row + r)) - n*digamma(r) + n*np.log(r/(r+np.mean(data_row)))
return d | def nb_r_deriv(r, data_row) | Derivative of log-likelihood wrt r (formula from wikipedia)
Args:
r (float): the R paramemter in the NB distribution
data_row (array): 1d array of length cells | 4.710279 | 5.552826 | 0.848267 |
means = data.mean(1)
variances = data.var(1)
if (means > variances).any():
raise ValueError("For NB fit, means must be less than variances")
genes, cells = data.shape
# method of moments
P = 1.0 - means/variances
R = means*(1-P)/P
for i in range(genes):
result = mini... | def nb_fit(data, P_init=None, R_init=None, epsilon=1e-8, max_iters=100) | Fits the NB distribution to data using method of moments.
Args:
data (array): genes x cells
P_init (array, optional): NB success prob param - genes x 1
R_init (array, optional): NB stopping param - genes x 1
Returns:
P, R - fit to data | 4.417427 | 3.869544 | 1.141588 |
genes, cells = data.shape
if P_init is None:
P_init = np.random.random((genes, k))
if R_init is None:
R_init = np.random.randint(1, data.max(), (genes, k))
R_init = R_init.astype(float)
if assignments is None:
_, assignments = kmeans_pp(data, k, means)
means = np... | def nb_cluster(data, k, P_init=None, R_init=None, assignments=None, means=None, max_iters=10) | Performs negative binomial clustering on the given data. If some genes have mean > variance, then these genes are fitted to a Poisson distribution.
Args:
data (array): genes x cells
k (int): number of clusters
P_init (array): NB success prob param - genes x k. Default: random
R_init... | 3.36985 | 3.033293 | 1.110954 |
for c in range(k):
if data[:,assignments==c].shape[1] == 0:
_, assignments = kmeans_pp(data, k)
genes, cells = data.shape
nb_gene_indices = np.array([True for i in range(genes)])
for c in range(k):
c_data = data[:,assignments==c]
nb_gene_indices = nb_gene_indices... | def fit_cluster(data, assignments, k, P_init, R_init, means) | Fits NB/poisson params to a cluster. | 3.151053 | 2.905842 | 1.084386 |
genes, cells = data.shape
clusters = means.shape[1]
ll = np.zeros((cells, clusters))
d0 = (data==0)
d1 = (data>0)
for i in range(clusters):
means_i = np.tile(means[:,i], (cells, 1))
means_i = means_i.transpose()
L_i = np.tile(M[:,i], (cells, 1))
L_i = L_i.tra... | def zip_ll(data, means, M) | Calculates the zero-inflated Poisson log-likelihood.
Args:
data (array): genes x cells
means (array): genes x k
M (array): genes x k - this is the zero-inflation parameter.
Returns:
cells x k array of log-likelihood for each cell/cluster pair. | 2.716157 | 2.619722 | 1.036811 |
l = params[0]
pi = params[1]
d0 = (data_row==0)
likelihood = d0*pi + (1-pi)*poisson.pmf(data_row, l)
return -np.log(likelihood+eps).sum() | def zip_ll_row(params, data_row) | Returns the negative log-likelihood of a row given ZIP data.
Args:
params (list): [lambda zero-inf]
data_row (array): 1d array
Returns:
negative log-likelihood | 6.112897 | 6.47886 | 0.943514 |
all_variants = adapter.get_variants()
nr_variants = all_variants.count()
nr_updated = 0
with progressbar(all_variants, label="Updating variants", length=nr_variants) as bar:
for variant in bar:
# Do not update if the variants have the correct format
if 'chrom' i... | def migrate_database(adapter) | Migrate an old loqusdb instance to 1.0
Args:
adapter
Returns:
nr_updated(int): Number of variants that where updated | 2.831855 | 2.665284 | 1.062496 |
if (len(args) != 2):
print(main.__doc__)
sys.exit(1);
# create the document
doc = libsedml.SedDocument();
doc.setLevel(1);
doc.setVersion(3);
# create a data description
ddesc = doc.createDataDescription()
ddesc.setId('data1')
ddesc.setName('Oscli Timecourse data')
ddesc.setSource('f... | def main (args) | Usage: create_sedml2 output-filename | 4.450266 | 4.249621 | 1.047215 |
import uncurl
from uncurl.preprocessing import log1p, cell_normalize
from sklearn.decomposition import TruncatedSVD
data_subset = data
if gene_subset:
gene_subset = uncurl.max_variance_genes(data)
data_subset = data[gene_subset, :]
tsvd = TruncatedSVD(min(8, data_subset.shap... | def preproc_data(data, gene_subset=False, **kwargs) | basic data preprocessing before running gap score
Assumes that data is a matrix of shape (genes, cells).
Returns a matrix of shape (cells, 8), using the first 8 SVD
components. Why 8? It's an arbitrary selection... | 3.596516 | 3.402858 | 1.05691 |
mins = data.min(0)
maxes = data.max(0)
return mins, maxes | def calculate_bounding_box(data) | Returns a 2 x m array indicating the min and max along each
dimension. | 3.755452 | 3.266191 | 1.149796 |
k = len(set(clustering))
Wk = km.inertia_
mins, maxes = calculate_bounding_box(data)
Wk_est = []
for i in range(B):
data_sample = (maxes-mins)*np.random.random(data.shape) + mins
km_b = KMeans(k)
km_b.fit_predict(data_sample)
Wk_est.append(km_b.inertia_)
Wk_e... | def calculate_gap(data, clustering, km, B=50, **kwargs) | See: https://datasciencelab.wordpress.com/2013/12/27/finding-the-k-in-k-means-clustering/
https://web.stanford.edu/~hastie/Papers/gap.pdf
Returns two results: the gap score, and s_k. | 3.11227 | 3.117175 | 0.998426 |
if k_min == k_max:
return k_min
gap_vals = []
sk_vals = []
k_range = list(range(k_min, k_max, skip))
min_k = 0
min_i = 0
for i, k in enumerate(k_range):
km = KMeans(k)
clusters = km.fit_predict(data)
gap, sk = calculate_gap(data, clusters, km, B=B)
... | def run_gap_k_selection(data, k_min=1, k_max=50, B=5,
skip=5, **kwargs) | Runs gap score for all k from k_min to k_max. | 2.067046 | 2.078572 | 0.994455 |
if not headers:
headers = {}
try:
async with self._websession.request(method, url, headers=headers,
params=params,
json=json) as resp:
resp.raise_for_status()... | async def _request(
self,
method: str,
url: str,
*,
headers: dict = None,
params: dict = None,
json: dict = None) -> dict | Make a request against the RainMachine device. | 2.602619 | 2.427476 | 1.072151 |
if not self.enabled:
return None
self.in_process = True
response, _ = helpers.call_api(
'/cloud/v1/deviceManaged/devices',
'post',
headers=helpers.req_headers(self),
json=helpers.req_body(self, 'devicelist')
)
... | def get_devices(self) -> list | Return list of VeSync devices | 4.104977 | 3.978687 | 1.031742 |
user_check = isinstance(self.username, str) and len(self.username) > 0
pass_check = isinstance(self.password, str) and len(self.password) > 0
if user_check and pass_check:
response, _ = helpers.call_api(
'/cloud/v1/user/login',
'post',
... | def login(self) -> bool | Return True if log in request succeeds | 2.74903 | 2.692477 | 1.021004 |
if self.device_time_check():
if not self.in_process:
outlets, switches, fans = self.get_devices()
self.outlets = helpers.resolve_updates(self.outlets, outlets)
self.switches = helpers.resolve_updates(
self.switches, swit... | def update(self) | Fetch updated information about devices | 4.023722 | 3.687966 | 1.091041 |
for outlet in self.outlets:
outlet.update_energy(bypass_check) | def update_energy(self, bypass_check=False) | Fetch updated energy information about devices | 4.609966 | 4.024941 | 1.14535 |
#Assumes data to be in the form of a numpy matrix
(r,c) = Dat.shape
Poiss = np.zeros(r)
Norm = np.zeros(r)
LogNorm = np.zeros(r)
for i in range(r):
temp = GetDistFitError(Dat[i])
Poiss[i] = temp['poiss']
Norm[i] = temp['norm']
LogNorm[i] = temp['lognorm']
... | def DistFitDataset(Dat) | Given a data matrix, this returns the per-gene fit error for the
Poisson, Normal, and Log-Normal distributions.
Args:
Dat (array): numpy array with shape (genes, cells)
Returns:
d (dict): 'poiss', 'norm', 'lognorm' give the fit error for each distribution. | 2.838618 | 2.221885 | 1.277572 |
# This will overwrite the updated case with the previous one
if update:
adapter.add_case(existing_case)
else:
adapter.delete_case(case_obj)
for file_type in ['vcf_path','vcf_sv_path']:
if not case_obj.get(file_type):
continue
variant_file = case_obj[file... | def delete(adapter, case_obj, update=False, existing_case=False) | Delete a case and all of it's variants from the database.
Args:
adapter: Connection to database
case_obj(models.Case)
update(bool): If we are in the middle of an update
existing_case(models.Case): If something failed during an update we need to revert
... | 4.118991 | 4.151464 | 0.992178 |
case_id = case_id or case_obj['case_id']
nr_deleted = 0
start_deleting = datetime.now()
chrom_time = datetime.now()
current_chrom = None
new_chrom = None
for variant in vcf_obj:
formated_variant = build_variant(
variant=variant,
case_obj=case_obj,
... | def delete_variants(adapter, vcf_obj, case_obj, case_id=None) | Delete variants for a case in the database
Args:
adapter(loqusdb.plugins.Adapter)
vcf_obj(iterable(dict))
ind_positions(dict)
case_id(str)
Returns:
nr_deleted (int): Number of deleted variants | 2.512088 | 2.647985 | 0.948679 |
adapter = ctx.obj['adapter']
variant_path = os.path.abspath(variant_file)
expected_type = 'snv'
if sv:
expected_type = 'sv'
if 'sv':
nr_cases = adapter.nr_cases(sv_cases=True)
else:
nr_cases = adapter.nr_cases(snv_cases=True)
LOG.info("Found {0} {1} cases in d... | def annotate(ctx, variant_file, sv) | Annotate the variants in a VCF | 3.280104 | 3.301897 | 0.9934 |
data = {'data': [{'num': num} for num in tracking_numbers]}
tracking_resp = await self._request('post', API_URL_TRACK, json=data)
print(tracking_resp)
if not tracking_resp.get('dat'):
raise InvalidTrackingNumberError('Invalid data')
packages = []
f... | async def find(self, *tracking_numbers: str) -> list | Get tracking info for one or more tracking numbers. | 3.801713 | 3.64643 | 1.042585 |
loglevel = "INFO"
if verbose:
loglevel = "DEBUG"
coloredlogs.install(level=loglevel)
LOG.info("Running loqusdb version %s", __version__)
configs = {}
if config:
try:
configs = yaml.safe_load(config)
except yaml.YAMLError as err:
LOG.warning(e... | def cli(ctx, database, username, password, authdb, port, host, uri, verbose, config, test) | loqusdb: manage a local variant count database. | 2.429136 | 2.428949 | 1.000077 |
thresholds = qualitative.min(1) + (qualitative.max(1) - qualitative.min(1))/2.0
binarized = qualitative > thresholds.reshape((len(thresholds), 1)).repeat(8,1)
return binarized.astype(int) | def binarize(qualitative) | binarizes an expression dataset. | 3.427151 | 3.572388 | 0.959344 |
genes, cells = data.shape
clusters = qualitative.shape[1]
output = np.zeros((genes, clusters))
missing_indices = []
genes_included = []
qual_indices = []
thresholds = qualitative.min(1) + (qualitative.max(1) - qualitative.min(1))/2.0
pvals = np.zeros(genes)
for i in range(genes)... | def qualNorm_filter_genes(data, qualitative, pval_threshold=0.05, smoothing=1e-5, eps=1e-5) | Does qualNorm but returns a filtered gene set, based on a p-value threshold. | 2.568218 | 2.604979 | 0.985888 |
genes, cells = data.shape
clusters = qualitative.shape[1]
output = np.zeros((genes, clusters))
missing_indices = []
qual_indices = []
thresholds = qualitative.min(1) + (qualitative.max(1) - qualitative.min(1))/2.0
for i in range(genes):
if qualitative[i,:].max() == -1 and qualit... | def qualNorm(data, qualitative) | Generates starting points using binarized data. If qualitative data is missing for a given gene, all of its entries should be -1 in the qualitative matrix.
Args:
data (array): 2d array of genes x cells
qualitative (array): 2d array of numerical data - genes x clusters
Returns:
Array of... | 2.573672 | 2.521497 | 1.020692 |
genes, cells = data.shape
clusters = qualitative.shape[1]
output = np.zeros((genes, clusters))
missing_indices = []
qual_indices = []
for i in range(genes):
if qualitative[i,:].max() == -1 and qualitative[i,:].min() == -1:
missing_indices.append(i)
continue
... | def qualNormGaussian(data, qualitative) | Generates starting points using binarized data. If qualitative data is missing for a given gene, all of its entries should be -1 in the qualitative matrix.
Args:
data (array): 2d array of genes x cells
qualitative (array): 2d array of numerical data - genes x clusters
Returns:
Array of... | 2.955772 | 2.819847 | 1.048203 |
if getattr(sys, 'frozen', False): # py2exe, PyInstaller, cx_Freeze
path = abspath(sys.executable)
else:
path = inspect.getabsfile(pyobject)
if follow_symlinks:
path = realpath(path)
return dirname(path) | def script_dir(pyobject, follow_symlinks=True) | Get current script's directory
Args:
pyobject (Any): Any Python object in the script
follow_symlinks (Optional[bool]): Follow symlinks or not. Defaults to True.
Returns:
str: Current script's directory | 2.291096 | 2.716756 | 0.84332 |
return join(script_dir(pyobject, follow_symlinks), filename) | def script_dir_plus_file(filename, pyobject, follow_symlinks=True) | Get current script's directory and then append a filename
Args:
filename (str): Filename to append to directory path
pyobject (Any): Any Python object in the script
follow_symlinks (Optional[bool]): Follow symlinks or not. Defaults to True.
Returns:
str: Current script's direct... | 3.729874 | 8.901066 | 0.419037 |
if not variant_id:
LOG.warning("Please provide a variant id")
ctx.abort()
adapter = ctx.obj['adapter']
version = ctx.obj['version']
LOG.info("Search variants {0}".format(adapter))
result = adapter.get_clusters(variant_id)
if result.count() == 0:
LOG.info("... | def identity(ctx, variant_id) | Check how well SVs are working in the database | 4.349268 | 4.110441 | 1.058103 |
if ATTR_ENTITY_REGISTRATION_AUTHORITY in self.raw:
try:
return self.raw[
ATTR_ENTITY_REGISTRATION_AUTHORITY][
ATTR_ENTITY_REGISTRATION_AUTHORITY_ENTITY_ID][
ATTR_DOLLAR_SIGN]
except KeyError:
... | def registration_authority_entity_id(self) | Some entities return the register entity id,
but other do not. Unsure if this is a bug or
inconsistently registered data. | 4.781669 | 4.176991 | 1.144764 |
if ATTR_ENTITY_LEGAL_FORM in self.raw:
try:
return LEGAL_FORMS[self.legal_jurisdiction][
self.raw[ATTR_ENTITY_LEGAL_FORM][
ATTR_ENTITY_LEGAL_FORM_CODE][ATTR_DOLLAR_SIGN]
]
except KeyError:
... | def legal_form(self) | In some cases, the legal form is stored in the JSON-data.
In other cases, an ELF-code, consisting of mix of exactly
four letters and numbers are stored. This ELF-code
can be looked up in a registry where a code maps to
a organizational type. ELF-codes are not unique,
it can reocc... | 4.682568 | 4.245721 | 1.102891 |
child_lei = list()
for d in self.raw['data']:
# We're not very greedy here, but it seems some records have
# lapsed even through the issuer is active
if d['attributes']['relationship']['status'] in ['ACTIVE']:
child_lei.append(
... | def valid_child_records(self) | Loop through data to find a valid record. Return list of LEI. | 18.779324 | 14.127703 | 1.329255 |
if var_obj:
variant.INFO['Obs'] = var_obj['observations']
if var_obj.get('homozygote'):
variant.INFO['Hom'] = var_obj['homozygote']
if var_obj.get('hemizygote'):
variant.INFO['Hem'] = var_obj['hemizygote']
return variant | def annotate_variant(variant, var_obj=None) | Annotate a cyvcf variant with observations
Args:
variant(cyvcf2.variant)
var_obj(dict)
Returns:
variant(cyvcf2.variant): Annotated variant | 2.761031 | 2.445091 | 1.129214 |
variant_id = get_variant_id(variant)
variant_obj = adapter.get_variant(variant={'_id':variant_id})
annotated_variant = annotated_variant(variant, variant_obj)
return annotated_variant | def annotate_snv(adpter, variant) | Annotate an SNV/INDEL variant
Args:
adapter(loqusdb.plugin.adapter)
variant(cyvcf2.Variant) | 4.571053 | 4.938569 | 0.925582 |
for nr_variants, variant in enumerate(vcf_obj, 1):
variant_info = get_coords(variant)
match = adapter.get_structural_variant(variant_info)
if match:
annotate_variant(variant, match)
yield variant | def annotate_svs(adapter, vcf_obj) | Annotate all SV variants in a VCF
Args:
adapter(loqusdb.plugin.adapter)
vcf_obj(cyvcf2.VCF)
Yields:
variant(cyvcf2.Variant) | 5.41155 | 5.661133 | 0.955913 |
variants = {}
for nr_variants, variant in enumerate(vcf_obj, 1):
# Add the variant to current batch
variants[get_variant_id(variant)] = variant
# If batch len == 1000 we annotate the batch
if (nr_variants % 1000) == 0:
for var_obj in adapter.sea... | def annotate_snvs(adapter, vcf_obj) | Annotate all variants in a VCF
Args:
adapter(loqusdb.plugin.adapter)
vcf_obj(cyvcf2.VCF)
Yields:
variant(cyvcf2.Variant): Annotated variant | 2.689992 | 2.68411 | 1.002192 |
type_ = geojson["type"].lower()
if type_ == "geometrycollection":
geometries = []
for geometry in geojson["geometries"]:
geometries.append(Geometry.from_geojson(geometry, srid=None))
return GeometryCollection(geometries, srid)
elif typ... | def from_geojson(geojson, srid=4326) | Create a Geometry from a GeoJSON. The SRID can be overridden from the
expected 4326. | 1.49586 | 1.47017 | 1.017475 |
if SHAPELY:
WKBWriter.defaults["include_srid"] = True
if srid:
lgeos.GEOSSetSRID(sgeom._geom, srid)
return Geometry(sgeom.wkb_hex)
else:
raise DependencyError("Shapely") | def from_shapely(sgeom, srid=None) | Create a Geometry from a Shapely geometry and the specified SRID.
The Shapely geometry will not be modified. | 6.483699 | 6.920607 | 0.936869 |
return self._to_wkb(use_srid=True, dimz=self.dimz, dimm=self.dimm) | def wkb(self) | Get the geometry as an (E)WKB. | 8.079901 | 6.348659 | 1.272694 |
dimz = "Z" if self.dimz else ""
dimm = "M" if self.dimm else ""
if self.srid:
return "geometry({}{}{},{})".format(self.type, dimz, dimm, self.srid)
else:
return "geometry({}{}{})".format(self.type, dimz, dimm) | def postgis_type(self) | Get the type of the geometry in PostGIS format, including additional
dimensions and SRID if they exist. | 3.165906 | 2.746805 | 1.152578 |
if sparse.issparse(data):
return sparse_poisson_ll(data, means)
genes, cells = data.shape
clusters = means.shape[1]
ll = np.zeros((cells, clusters))
for i in range(clusters):
means_i = np.tile(means[:,i], (cells, 1))
means_i = means_i.transpose() + eps
#ll[:,i] =... | def poisson_ll(data, means) | Calculates the Poisson log-likelihood.
Args:
data (array): 2d numpy array of genes x cells
means (array): 2d numpy array of genes x k
Returns:
cells x k array of log-likelihood for each cell/cluster pair | 2.594993 | 2.592047 | 1.001137 |
p1_1 = p1 + eps
p2_1 = p2 + eps
return np.sum(-p2_1 + p1_1*np.log(p2_1)) | def poisson_ll_2(p1, p2) | Calculates Poisson LL(p1|p2). | 3.488231 | 3.611866 | 0.96577 |
# ugh...
p1_ = p1 + eps
p2_ = p2 + eps
return np.dot(p1_-p2_, np.log(p1_/p2_)) | def poisson_dist(p1, p2) | Calculates the Poisson distance between two vectors.
p1 can be a sparse matrix, while p2 has to be a dense matrix. | 5.279904 | 5.57146 | 0.94767 |
if not (family_file or case_id):
LOG.error("Please provide a family file")
ctx.abort()
adapter = ctx.obj['adapter']
# Get a ped_parser.Family object from family file
family = None
family_id = None
if family_file:
with open(family_file, 'r') as family_lines:
... | def delete(ctx, family_file, family_type, case_id) | Delete the variants of a case. | 3.460598 | 3.43081 | 1.008682 |
if bypass_check or (not bypass_check and self.update_time_check):
self.get_weekly_energy()
if 'week' in self.energy:
self.get_monthly_energy()
self.get_yearly_energy()
if not bypass_check:
self.update_energy_ts = time.t... | def update_energy(self, bypass_check: bool = False) | Builds weekly, monthly and yearly dictionaries | 4.429904 | 3.338512 | 1.326909 |
body = helpers.req_body(self.manager, 'devicestatus')
body['uuid'] = self.uuid
body['mode'] = 'auto'
response, _ = helpers.call_api(
'/15a/v1/device/nightlightstatus',
'put',
headers=helpers.req_headers(self.manager),
json=body
... | def turn_on_nightlight(self) | Turn on nightlight | 6.828323 | 6.723629 | 1.015571 |
if len(args) != 3:
print(main.__doc__)
sys.exit(1)
d = libsedml.readSedML(args[1]);
if ( d.getErrorLog().getNumFailsWithSeverity(libsedml.LIBSEDML_SEV_ERROR) > 0):
print (d.getErrorLog().toString());
else:
libsedml.writeSedML(d, args[2]);
return 0; | def main (args) | Usage: echo_sedml input-filename output-filename | 3.063941 | 2.510591 | 1.220406 |
logging.basicConfig(level=logging.INFO)
async with ClientSession() as websession:
try:
client = Client(websession)
await client.profile.login('<EMAIL>', '<PASSWORD>')
_LOGGER.info('Account ID: %s', client.profile.account_id)
summary = await client.... | async def main() -> None | Create the aiohttp session and run the example. | 3.54476 | 3.201483 | 1.107224 |
module, attr = name.rsplit('.', 1)
mod = __import__(module, fromlist=[attr])
klass = getattr(mod, attr)
return klass() | def my_import(name) | dynamic importing | 2.350056 | 2.257431 | 1.041031 |
if FACEBOOK_APP_ID is None:
log.warning("FACEBOOK_APP_ID isn't setup correctly in your settings")
# make sure FACEBOOK_APP_ID is setup correct and user is authenticated
if FACEBOOK_APP_ID:
request = context.get('request', None)
if request:
return {"LIKE_BUTTON_IS_V... | def like_button_js_tag(context) | This tag will check to see if they have the FACEBOOK_LIKE_APP_ID setup
correctly in the django settings, if so then it will pass the data
along to the intercom_tag template to be displayed.
If something isn't perfect we will return False, which will then not
install the javascript since... | 5.246632 | 4.569251 | 1.148248 |
if FACEBOOK_APP_ID is None:
log.warning("FACEBOOK_APP_ID isn't setup correctly in your settings")
# make sure INTERCOM_APPID is setup correct and user is authenticated
if FACEBOOK_APP_ID:
request = context.get('request', None)
if request:
path_to_like = (
... | def like_button_tag(context) | This tag will check to see if they have the FACEBOOK_APP_ID setup
correctly in the django settings, if so then it will pass the data
along to the intercom_tag template to be displayed.
If something isn't perfect we will return False, which will then not
install the javascript since it i... | 3.932068 | 3.458951 | 1.13678 |
# Create a query for the database
# This will include more variants than we want
# The rest of the calculations will be done in python
query = {
'chrom': variant['chrom'],
'end_chrom': variant['end_chrom'],
'sv_type': variant['sv_t... | def get_structural_variant(self, variant) | Check if there are any overlapping sv clusters
Search the sv variants with chrom start end_chrom end and sv_type
Args:
variant (dict): A variant dictionary
Returns:
variant (dict): A variant dictionary | 4.400237 | 4.220089 | 1.042688 |
query = {}
if chromosome:
query['chrom'] = chromosome
if end_chromosome:
query['end_chrom'] = end_chromosome
if sv_type:
query['sv_type'] = sv_type
if pos:
if not '$and' in query:
query['$and'] = []... | def get_sv_variants(self, chromosome=None, end_chromosome=None, sv_type=None,
pos=None, end=None) | Return all structural variants in the database
Args:
chromosome (str)
end_chromosome (str)
sv_type (str)
pos (int): Left position of SV
end (int): Right position of SV
Returns:
variants (Iterable(Variant)) | 1.858143 | 1.972482 | 0.942033 |
query = {'variant_id':variant_id}
identities = self.db.identity.find(query)
return identities | def get_clusters(self, variant_id) | Search what clusters a variant belongs to
Args:
variant_id(str): From ID column in vcf
Returns:
clusters() | 5.607437 | 7.250075 | 0.773432 |
clusters = int(clusters)
func = poisson_estimate_state
dist = dist.lower()
if dist=='poiss' or dist=='poisson':
pass
elif dist=='nb':
func = nb_estimate_state
elif dist=='zip':
func = zip_estimate_state
elif dist=='lognorm' or dist=='log-normal' or dist=='lognorm... | def run_state_estimation(data, clusters, dist='Poiss', reps=1, **kwargs) | Runs state estimation for multiple initializations, returning the result with the highest log-likelihood. All the arguments are passed to the underlying state estimation functions (poisson_estimate_state, nb_estimate_state, zip_estimate_state).
Args:
data (array): genes x cells
clusters (int): numb... | 3.414848 | 2.894461 | 1.179787 |
body = helpers.req_body(self.manager, 'devicedetail')
head = helpers.req_headers(self.manager)
r, _ = helpers.call_api('/131airpurifier/v1/device/deviceDetail',
method='post', headers=head, json=body)
if r is not None and helpers.check_response(... | def get_details(self) | Build details dictionary | 4.126155 | 4.052018 | 1.018296 |
if self.device_status != 'on':
body = helpers.req_body(self.manager, 'devicestatus')
body['uuid'] = self.uuid
body['status'] = 'on'
head = helpers.req_headers(self.manager)
r, _ = helpers.call_api('/131airPurifier/v1/device/deviceStatus',
... | def turn_on(self) | Turn Air Purifier on | 5.24261 | 5.05794 | 1.036511 |
body = helpers.req_body(self.manager, 'devicestatus')
body['uuid'] = self.uuid
head = helpers.req_headers(self.manager)
if self.details.get('mode') != 'manual':
self.mode_toggle('manual')
else:
if speed is not None:
level = int(sel... | def fan_speed(self, speed: int = None) -> bool | Adjust Fan Speed by Specifying 1,2,3 as argument or cycle
through speeds increasing by one | 4.609313 | 4.474881 | 1.030042 |
head = helpers.req_headers(self.manager)
body = helpers.req_body(self.manager, 'devicestatus')
body['uuid'] = self.uuid
if mode != body['mode'] and mode in ['sleep', 'auto', 'manual']:
body['mode'] = mode
if mode == 'manual':
body['level']... | def mode_toggle(self, mode: str) -> bool | Set mode to manual, auto or sleep | 6.192688 | 5.789187 | 1.069699 |
output = 0
output += a[0]/2
w = a[1]
for n in range(2, len(a), 2):
n_ = n/2
val1 = a[n]
val2 = a[n+1]
output += val1*np.sin(n_*x*w)
output += val2*np.cos(n_*x*w)
return output | def fourier_series(x, *a) | Arbitrary dimensionality fourier series.
The first parameter is a_0, and the second parameter is the interval/scale
parameter.
The parameters are altering sin and cos paramters.
n = (len(a)-2)/2 | 2.853001 | 2.883653 | 0.98937 |
# convert adjacency list to adjacency dict
adj = {x: [] for x in range(len(distances))}
for n1, n2 in edges:
adj[n1].append(n2)
adj[n2].append(n1)
# run dijkstra's algorithm
to_visit = []
new_dist = {}
for n in adj[start]:
heapq.heappush(to_visit, (distances[star... | def graph_distances(start, edges, distances) | Given an undirected adjacency list and a pairwise distance matrix between
all nodes: calculates distances along graph from start node.
Args:
start (int): start node
edges (list): adjacency list of tuples
distances (array): 2d array of distances between nodes
Returns:
dict o... | 1.972831 | 2.028188 | 0.972706 |
output = 0.0
for n in range(0, len(a)):
output += a[n]*x**n
return output | def poly_curve(x, *a) | Arbitrary dimension polynomial. | 2.911718 | 2.669548 | 1.090716 |
# TODO
# 1. calculate a distance matrix...
distances = np.array([[sum((x - y)**2) for x in fitted_vals.T] for y in fitted_vals.T])
# 2. start from the root node/cell, calculate distance along graph
distance_dict = graph_distances(starting_node, edges, distances)
output = []
for i in ran... | def pseudotime(starting_node, edges, fitted_vals) | Args:
starting_node (int): index of the starting node
edges (list): list of tuples (node1, node2)
fitted_vals (array): output of lineage (2 x cells)
Returns:
A 1d array containing the pseudotime value of each cell. | 4.114966 | 4.052603 | 1.015388 |
# type: (str, hxl.Row) -> None
countryname = country.get('#country+name+preferred')
cls._countriesdata['countrynames2iso3'][countryname.upper()] = iso3
iso2 = country.get('#country+code+v_iso2')
if iso2:
cls._countriesdata['iso2iso3'][iso2] = iso3
... | def _add_countriesdata(cls, iso3, country) | Set up countries data from data in form provided by UNStats and World Bank
Args:
iso3 (str): ISO3 code for country
country (hxl.Row): Country information
Returns:
None | 2.152602 | 2.180553 | 0.987182 |
# type: (str) -> None
cls._countriesdata = dict()
cls._countriesdata['countries'] = dict()
cls._countriesdata['iso2iso3'] = dict()
cls._countriesdata['m49iso3'] = dict()
cls._countriesdata['countrynames2iso3'] = dict()
cls._countriesdata['regioncodes2coun... | def set_countriesdata(cls, countries) | Set up countries data from data in form provided by UNStats and World Bank
Args:
countries (str): Countries data in HTML format provided by UNStats
Returns:
None | 3.060672 | 3.323649 | 0.920877 |
# type: (bool) -> List[Dict[Dict]]
if cls._countriesdata is None:
countries = None
if use_live:
try:
countries = hxl.data(cls._ochaurl)
except IOError:
logger.exception('Download from OCHA feed faile... | def countriesdata(cls, use_live=True) | Read countries data from OCHA countries feed (falling back to file)
Args:
use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True.
Returns:
List[Dict[Dict]]: Countries dictionaries | 8.825243 | 7.768636 | 1.136009 |
# type: (str) -> None
if url is None:
url = cls._ochaurl_int
cls._ochaurl = url | def set_ocha_url(cls, url=None) | Set World Bank url from which to retrieve countries data
Args:
url (str): World Bank url from which to retrieve countries data. Defaults to internal value.
Returns:
None | 5.442855 | 9.200959 | 0.591553 |
# type: (str, bool, Optional[ExceptionUpperBound]) -> Optional[Dict[str]]
countriesdata = cls.countriesdata(use_live=use_live)
country = countriesdata['countries'].get(iso3.upper())
if country is not None:
return country
if exception is not None:
... | def get_country_info_from_iso3(cls, iso3, use_live=True, exception=None) | Get country information from ISO3 code
Args:
iso3 (str): ISO3 code for which to get country information
use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True.
exception (Optional[ExceptionUpperBound]): An exception to raise if cou... | 3.785014 | 4.076024 | 0.928605 |
# type: (str, bool, Optional[ExceptionUpperBound]) -> Optional[str]
countryinfo = cls.get_country_info_from_iso3(iso3, use_live=use_live, exception=exception)
if countryinfo is not None:
return countryinfo.get('#country+name+preferred')
return None | def get_country_name_from_iso3(cls, iso3, use_live=True, exception=None) | Get country name from ISO3 code
Args:
iso3 (str): ISO3 code for which to get country name
use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True.
exception (Optional[ExceptionUpperBound]): An exception to raise if country not found... | 3.621631 | 4.714428 | 0.768201 |
# type: (str, bool, Optional[ExceptionUpperBound]) -> Optional[str]
countriesdata = cls.countriesdata(use_live=use_live)
iso2 = countriesdata['iso2iso3'].get(iso3.upper())
if iso2 is not None:
return iso2
if exception is not None:
raise exception... | def get_iso2_from_iso3(cls, iso3, use_live=True, exception=None) | Get ISO2 from ISO3 code
Args:
iso3 (str): ISO3 code for which to get ISO2 code
use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True.
exception (Optional[ExceptionUpperBound]): An exception to raise if country not found. Defaults ... | 3.473556 | 4.09437 | 0.848374 |
# type: (str, bool, Optional[ExceptionUpperBound]) -> Optional[Dict[str]]
iso3 = cls.get_iso3_from_iso2(iso2, use_live=use_live, exception=exception)
if iso3 is not None:
return cls.get_country_info_from_iso3(iso3, use_live=use_live, exception=exception)
return None | def get_country_info_from_iso2(cls, iso2, use_live=True, exception=None) | Get country name from ISO2 code
Args:
iso2 (str): ISO2 code for which to get country information
use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True.
exception (Optional[ExceptionUpperBound]): An exception to raise if country no... | 2.258758 | 2.715734 | 0.83173 |
# type: (str, bool, Optional[ExceptionUpperBound]) -> Optional[str]
iso3 = cls.get_iso3_from_iso2(iso2, use_live=use_live, exception=exception)
if iso3 is not None:
return cls.get_country_name_from_iso3(iso3, exception=exception)
return None | def get_country_name_from_iso2(cls, iso2, use_live=True, exception=None) | Get country name from ISO2 code
Args:
iso2 (str): ISO2 code for which to get country name
use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True.
exception (Optional[ExceptionUpperBound]): An exception to raise if country not found... | 2.251667 | 2.948529 | 0.763658 |
# type: (str, bool, Optional[ExceptionUpperBound]) -> Optional[int]
countriesdata = cls.countriesdata(use_live=use_live)
m49 = countriesdata['m49iso3'].get(iso3)
if m49 is not None:
return m49
if exception is not None:
raise exception
ret... | def get_m49_from_iso3(cls, iso3, use_live=True, exception=None) | Get M49 from ISO3 code
Args:
iso3 (str): ISO3 code for which to get M49 code
use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True.
exception (Optional[ExceptionUpperBound]): An exception to raise if country not found. Defaults to... | 3.493333 | 3.83688 | 0.910462 |
# type: (int, bool, Optional[ExceptionUpperBound]) -> Optional[Dict[str]]
iso3 = cls.get_iso3_from_m49(m49, use_live=use_live, exception=exception)
if iso3 is not None:
return cls.get_country_info_from_iso3(iso3, exception=exception)
return None | def get_country_info_from_m49(cls, m49, use_live=True, exception=None) | Get country name from M49 code
Args:
m49 (int): M49 numeric code for which to get country information
use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True.
exception (Optional[ExceptionUpperBound]): An exception to raise if count... | 2.830684 | 3.000676 | 0.943349 |
# type: (int, bool, Optional[ExceptionUpperBound]) -> Optional[str]
iso3 = cls.get_iso3_from_m49(m49, use_live=use_live, exception=exception)
if iso3 is not None:
return cls.get_country_name_from_iso3(iso3, exception=exception)
return None | def get_country_name_from_m49(cls, m49, use_live=True, exception=None) | Get country name from M49 code
Args:
m49 (int): M49 numeric code for which to get country name
use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True.
exception (Optional[ExceptionUpperBound]): An exception to raise if country not ... | 2.463577 | 2.780351 | 0.886067 |
# type: (str) -> List[str]
def replace_ensure_space(word, replace, replacement):
return word.replace(replace, '%s ' % replacement).replace(' ', ' ').strip()
countryupper = country.upper()
for abbreviation in cls.abbreviations:
countryupper = replace_ensu... | def expand_countryname_abbrevs(cls, country) | Expands abbreviation(s) in country name in various ways (eg. FED -> FEDERATED, FEDERAL etc.)
Args:
country (str): Country with abbreviation(s)to expand
Returns:
List[str]: Uppercase country name with abbreviation(s) expanded in various ways | 3.143395 | 3.487326 | 0.901377 |
# type: (str) -> (str, List[str])
countryupper = country.upper()
words = get_words_in_sentence(countryupper)
index = countryupper.find(',')
if index != -1:
countryupper = countryupper[:index]
index = countryupper.find(':')
if index != -1:
... | def simplify_countryname(cls, country) | Simplifies country name by removing descriptive text eg. DEMOCRATIC, REPUBLIC OF etc.
Args:
country (str): Country name to simplify
Returns:
Tuple[str, List[str]]: Uppercase simplified country name and list of removed words | 2.351262 | 2.335167 | 1.006892 |
# type: (str, bool, Optional[ExceptionUpperBound]) -> Optional[str]
countriesdata = cls.countriesdata(use_live=use_live)
countryupper = country.upper()
len_countryupper = len(countryupper)
if len_countryupper == 3:
if countryupper in countriesdata['countries'... | def get_iso3_country_code(cls, country, use_live=True, exception=None) | Get ISO3 code for cls. Only exact matches or None are returned.
Args:
country (str): Country for which to get ISO3 code
use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True.
exception (Optional[ExceptionUpperBound]): An exception... | 2.647947 | 2.893491 | 0.915139 |
# type: (str, bool, Optional[ExceptionUpperBound]) -> Tuple[[Optional[str], bool]]
countriesdata = cls.countriesdata(use_live=use_live)
iso3 = cls.get_iso3_country_code(country,
use_live=use_live) # don't put exception param here as we don't wan... | def get_iso3_country_code_fuzzy(cls, country, use_live=True, exception=None) | Get ISO3 code for cls. A tuple is returned with the first value being the ISO3 code and the second
showing if the match is exact or not.
Args:
country (str): Country for which to get ISO3 code
use_live (bool): Try to get use latest data from web rather than file in package. Defa... | 2.967509 | 2.908247 | 1.020377 |
# type: (Union[int,str], bool, Optional[ExceptionUpperBound]) -> List[str]
countriesdata = cls.countriesdata(use_live=use_live)
if isinstance(region, int):
regioncode = region
else:
regionupper = region.upper()
regioncode = countriesdata['regi... | def get_countries_in_region(cls, region, use_live=True, exception=None) | Get countries (ISO3 codes) in region
Args:
region (Union[int,str]): Three digit UNStats M49 region code or region name
use_live (bool): Try to get use latest data from web rather than file in package. Defaults to True.
exception (Optional[ExceptionUpperBound]): An exception ... | 3.667618 | 4.218836 | 0.869344 |
adapter = ctx.obj['adapter']
if variant_file:
load_profile_variants(adapter, variant_file)
if update:
update_profiles(adapter)
if stats:
distance_dict = profile_stats(adapter, threshold=profile_threshold)
click.echo(table_from_dict(distance_dict)) | def load_profile(ctx, variant_file, update, stats, profile_threshold) | Command for profiling of samples. User may upload variants used in profiling
from a vcf, update the profiles for all samples, and get some stats
from the profiles in the database.
Profiling is used to monitor duplicates in the database. The profile is
based on the variants in the 'profi... | 4.010554 | 4.379299 | 0.915798 |
results = self.db.profile_variant.insert_many(profile_variants)
return results | def add_profile_variants(self, profile_variants) | Add several variants to the profile_variant collection in the
database
Args:
profile_variants(list(models.ProfileVariant)) | 6.140555 | 4.918679 | 1.248416 |
genes, cells = data.shape
m = data.mean(1)
v = data.var(1)
M = (v-m)/(m**2+v-m)
#M = v/(v+m**2)
#M[np.isnan(M)] = 0.0
M = np.array([min(1.0, max(0.0, x)) for x in M])
L = m + v/m - 1.0
#L = (v + m**2)/m
L[np.isnan(L)] = 0.0
L = np.array([max(0.0, x) for x in L])
retu... | def zip_fit_params(data) | Returns the ZIP parameters that best fit a given data set.
Args:
data (array): 2d array of genes x cells belonging to a given cluster
Returns:
L (array): 1d array of means
M (array): 1d array of zero-inflation parameter | 3.28105 | 3.079157 | 1.065568 |
genes, cells = data.shape
init, new_assignments = kmeans_pp(data+eps, k, centers=init)
centers = np.copy(init)
M = np.zeros(centers.shape)
assignments = new_assignments
for c in range(k):
centers[:,c], M[:,c] = zip_fit_params_mle(data[:, assignments==c])
for it in range(max_iter... | def zip_cluster(data, k, init=None, max_iters=100) | Performs hard EM clustering using the zero-inflated Poisson distribution.
Args:
data (array): A 2d array- genes x cells
k (int): Number of clusters
init (array, optional): Initial centers - genes x k array. Default: None, use kmeans++
max_iters (int, optional): Maximum number of ite... | 3.412921 | 3.07518 | 1.109828 |
for i in range(diffusion_rounds):
weights = weights*weights
weights = weights/weights.sum(0)
X = dim_reduce(means, weights, d)
if X.shape[0]==2:
return X.dot(weights)
else:
return X.T.dot(weights) | def diffusion_mds(means, weights, d, diffusion_rounds=10) | Dimensionality reduction using MDS, while running diffusion on W.
Args:
means (array): genes x clusters
weights (array): clusters x cells
d (int): desired dimensionality
Returns:
W_reduced (array): array of shape (d, cells) | 3.471823 | 4.84051 | 0.717243 |
X = dim_reduce(means, weights, d)
if X.shape[0]==2:
return X.dot(weights)
else:
return X.T.dot(weights) | def mds(means, weights, d) | Dimensionality reduction using MDS.
Args:
means (array): genes x clusters
weights (array): clusters x cells
d (int): desired dimensionality
Returns:
W_reduced (array): array of shape (d, cells) | 3.812249 | 5.604121 | 0.680258 |
genes, cells = data.shape
distances = np.zeros((cells, cells))
for i in range(cells):
for j in range(cells):
distances[i,j] = poisson_dist(data[:,i], data[:,j])
# do MDS on the distance matrix (procedure from Wikipedia)
proximity = distances**2
J = np.eye(cells) - 1./cel... | def dim_reduce_data(data, d) | Does a MDS on the data directly, not on the means.
Args:
data (array): genes x cells
d (int): desired dimensionality
Returns:
X, a cells x d matrix | 4.610687 | 4.580267 | 1.006642 |
LOG.debug("Getting case {0} from database".format(case.get('case_id')))
case_id = case['case_id']
return self.db.case.find_one({'case_id': case_id}) | def case(self, case) | Get a case from the database
Search the cases with the case id
Args:
case (dict): A case dictionary
Returns:
mongo_case (dict): A mongo case dictionary | 3.550494 | 3.585213 | 0.990316 |
query = {}
if snv_cases:
query = {'vcf_path': {'$exists':True}}
if sv_cases:
query = {'vcf_sv_path': {'$exists':True}}
if snv_cases and sv_cases:
query = None
return self.db.case.count_documents(query) | def nr_cases(self, snv_cases=None, sv_cases=None) | Return the number of cases in the database
Args:
snv_cases(bool): If only snv cases should be searched
sv_cases(bool): If only snv cases should be searched
Returns:
cases (Iterable(Case)): A iterable with mongo cases | 3.270613 | 3.252355 | 1.005614 |
existing_case = self.case(case)
if existing_case and not update:
raise CaseError("Case {} already exists".format(case['case_id']))
if existing_case:
self.db.case.find_one_and_replace(
{'case_id': case['case_id']},
case,
... | def add_case(self, case, update=False) | Add a case to the case collection
If the case exists and update is False raise error.
Args:
db (MongoClient): A connection to the mongodb
case (dict): A case dictionary
update(bool): If existing case should be updated
Returns:
mongo_case_id(Obje... | 2.454438 | 2.579558 | 0.951496 |
mongo_case = self.case(case)
if not mongo_case:
raise CaseError("Tried to delete case {0} but could not find case".format(
case.get('case_id')
))
LOG.info("Removing case {0} from database".format(
mongo_case.get('case_id')
))
... | def delete_case(self, case) | Delete case from the database
Delete a case from the database
Args:
case (dict): A case dictionary | 3.253045 | 3.476259 | 0.935789 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.