code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
if self._result_cache:
return self._result_cache.has_next
return self.all().has_next | def has_next(self) | Return True if there are more values present | 8.440028 | 7.569524 | 1.115001 |
if self._result_cache:
return self._result_cache.has_prev
return self.all().has_prev | def has_prev(self) | Return True if there are previous values present | 7.326245 | 6.523602 | 1.123037 |
klass = perform_import(backend or active_config.EMAIL_BACKEND)
return klass(fail_silently=fail_silently, **kwargs) | def get_connection(backend=None, fail_silently=False, **kwargs) | Load an email backend and return an instance of it.
If backend is None (default), use settings.EMAIL_BACKEND.
Both fail_silently and other keyword arguments are used in the
constructor of the backend. | 6.276484 | 6.126516 | 1.024479 |
connection = connection or get_connection(
username=auth_user,
password=auth_password,
fail_silently=fail_silently,
)
mail_message = EmailMessage(subject, message, from_email, recipient_list,
**kwargs)
return connection.send_messages([mail_me... | def send_mail(subject, message, recipient_list, from_email=None,
fail_silently=False, auth_user=None, auth_password=None,
connection=None, **kwargs) | Easy wrapper for sending a single message to a recipient list. All members
of the recipient list will see the other recipients in the 'To' field. | 2.006464 | 2.298163 | 0.873073 |
connection = connection or get_connection(
username=auth_user,
password=auth_password,
fail_silently=fail_silently,
)
messages = [
EmailMessage(subject, message, sender, recipient)
for subject, message, sender, recipient in data_tuple
]
return connection.... | def send_mass_mail(data_tuple, fail_silently=False, auth_user=None,
auth_password=None, connection=None) | Given a data_tuple of (subject, message, from_email, recipient_list), send
each message to each recipient list. Return the number of emails sent.
If from_email is None, use the DEFAULT_FROM_EMAIL setting. | 2.050467 | 2.229774 | 0.919585 |
# Set the code to the status value
if isinstance(self.code, Status):
code = self.code.value
else:
code = self.code
return {'code': code, 'errors': self.errors} | def value(self) | Utility method to retrieve Response Object information | 5.290071 | 4.516818 | 1.171194 |
errors = [errors] if not isinstance(errors, list) else errors
return cls(code, errors) | def build_response(cls, code=Status.SYSTEM_ERROR, errors=None) | Utility method to build a new Resource Error object.
Can be used to build all kinds of error messages. | 4.034011 | 4.119946 | 0.979142 |
errors = [{err['parameter']: err['message']} for err in invalid_request_object.errors]
return cls.build_response(Status.UNPROCESSABLE_ENTITY, errors) | def build_from_invalid_request(cls, invalid_request_object) | Utility method to build a new Error object from parameters.
Typically used to build HTTP 422 error response. | 4.906639 | 4.560516 | 1.075896 |
errors = [errors] if not isinstance(errors, list) else errors
return cls(Status.NOT_FOUND, errors) | def build_not_found(cls, errors=None) | Utility method to build a HTTP 404 Resource Error response | 4.209488 | 4.150457 | 1.014223 |
errors = [errors] if not isinstance(errors, list) else errors
return cls(Status.SYSTEM_ERROR, errors) | def build_system_error(cls, errors=None) | Utility method to build a HTTP 500 System Error response | 4.308498 | 4.690114 | 0.918634 |
errors = [errors] if not isinstance(errors, list) else errors
return cls(Status.PARAMETERS_ERROR, errors) | def build_parameters_error(cls, errors=None) | Utility method to build a HTTP 400 Parameter Error response | 4.909399 | 5.202725 | 0.943621 |
errors = [errors] if not isinstance(errors, list) else errors
return cls(Status.UNPROCESSABLE_ENTITY, errors) | def build_unprocessable_error(cls, errors=None) | Utility method to build a HTTP 422 Parameter Error object | 3.834975 | 3.888682 | 0.986189 |
'''
Signal starts at start value, ramps linearly up to end value
:param params: buffer parameters, controls length of signal created
:param start: start value (number)
:param end: end value (number)
:return: array of resulting signal
'''
return np.linspace(start, end, num=params.length, ... | def linseg(params, start=0, end=1) | Signal starts at start value, ramps linearly up to end value
:param params: buffer parameters, controls length of signal created
:param start: start value (number)
:param end: end value (number)
:return: array of resulting signal | 5.97157 | 1.878528 | 3.178856 |
'''
Signal starts at min value, ramps linearly up to max value during the
attack time, than ramps back down to min value over remaining time
:param params: buffer parameters, controls length of signal created
:param attack: attack time, in samples
:param start: start value (number)
:param pe... | def attack_decay(params, attack, start=0, peak=1) | Signal starts at min value, ramps linearly up to max value during the
attack time, than ramps back down to min value over remaining time
:param params: buffer parameters, controls length of signal created
:param attack: attack time, in samples
:param start: start value (number)
:param peak: peak val... | 6.773817 | 2.479941 | 2.731442 |
'''
Set the current value and optionally maintain it for a period
:param value: New current value
:param samples: Add current value for this number of samples (if not zero)
:return:
'''
if self.params.length > self.pos and samples > 0:
l = min(samples,... | def set(self, value, samples=0) | Set the current value and optionally maintain it for a period
:param value: New current value
:param samples: Add current value for this number of samples (if not zero)
:return: | 4.30624 | 2.52213 | 1.707382 |
'''
Create a linear section moving from current value to new value over acertain number of
samples.
:param value: New value
:param samples: Length of segment in samples
:return:
'''
if self.params.length > self.pos and samples > 0:
len = min(sa... | def linseg(self, value, samples) | Create a linear section moving from current value to new value over acertain number of
samples.
:param value: New value
:param samples: Length of segment in samples
:return: | 4.369563 | 2.702832 | 1.616661 |
r = s.get(oauth_url)
if r.status_code >= 300:
raise RuntimeError(r.text)
params = urlparse.parse_qs(urlparse.urlparse(r.url).query)
data = {"un":username,
"width":2560,
"height":1440,
"hasRememberUn":True,
"startURL":params['startURL'],
... | def oauth_flow(s, oauth_url, username=None, password=None, sandbox=False) | s should be a requests session | 3.556775 | 3.576663 | 0.994439 |
''' legacy crossroad implementation. deprecated
'''
sink_observer = None
def on_sink_subscribe(observer):
nonlocal sink_observer
sink_observer = observer
def dispose():
nonlocal sink_observer
sink_observer = None
return dispose
def route_cr... | def make_crossroad_router(source, drain=False) | legacy crossroad implementation. deprecated | 2.31864 | 2.207318 | 1.050433 |
sink_observer = None
def on_subscribe(observer):
nonlocal sink_observer
sink_observer = observer
def dispose():
nonlocal sink_observer
sink_observer = None
return dispose
def route_error(obs, convert):
def catch_error(e):
... | def make_error_router() | Creates an error router
An error router takes a higher order observable a input and returns two
observables: One containing the flattened items of the input observable
and another one containing the flattened errors of the input observable.
.. image:: ../docs/asset/error_router.png
:scale: 60%... | 3.727159 | 3.259033 | 1.14364 |
if not (family_file or case_id):
LOG.warning("Please provide a family file or a case id")
ctx.abort()
if not (variant_file or sv_variants):
LOG.warning("Please provide a VCF file")
ctx.abort()
variant_path = None
if variant_file:
variant_path = os.path.absp... | def load(ctx, variant_file, sv_variants, family_file, family_type, skip_case_id, gq_treshold,
case_id, ensure_index, max_window, check_profile, hard_threshold, soft_threshold) | Load the variants of a case
A variant is loaded if it is observed in any individual of a case
If no family file is provided all individuals in vcf file will be considered. | 2.192536 | 2.221014 | 0.987178 |
logger.warning("Wiping the whole database")
self.client.drop_database(self.db_name)
logger.debug("Database wiped") | def wipe_db(self) | Wipe the whole database | 4.460496 | 4.153864 | 1.073818 |
for collection_name in INDEXES:
existing_indexes = self.indexes(collection_name)
indexes = INDEXES[collection_name]
for index in indexes:
index_name = index.document.get('name')
if not index_name in existing_indexes:
... | def check_indexes(self) | Check if the indexes exists | 4.66996 | 4.452281 | 1.048892 |
for collection_name in INDEXES:
existing_indexes = self.indexes(collection_name)
indexes = INDEXES[collection_name]
for index in indexes:
index_name = index.document.get('name')
if index_name in existing_indexes:
lo... | def ensure_indexes(self) | Update the indexes | 2.549125 | 2.517421 | 1.012594 |
observations = variant.get('observations',0)
homozygotes = variant.get('homozygote')
hemizygotes = variant.get('hemizygote')
vcf_info = f"Obs={observations}"
if homozygotes:
vcf_info += f";Hom={homozygotes}"
if hemizygotes:
vcf_info += f";Hem={hemizygotes}"
... | def format_info(variant, variant_type='snv') | Format the info field for SNV variants
Args:
variant(dict)
variant_type(str): snv or sv
Returns:
vcf_info(str): A VCF formated info field | 2.922122 | 2.768465 | 1.055502 |
chrom = variant.get('chrom')
pos = variant.get('start')
ref = variant.get('ref')
alt = variant.get('alt')
if variant_type == 'sv':
pos = int((variant['pos_left'] + variant['pos_right'])/2)
ref = 'N'
alt = f"<{variant['sv_type']}>"
info = None
info... | def format_variant(variant, variant_type='snv') | Convert variant information to a VCF formated string
Args:
variant(dict)
variant_type(str)
Returns:
vcf_variant(str) | 2.834962 | 3.013359 | 0.940798 |
clusters, cells = w.shape
genes = X.shape[0]
w_sum = w.sum(1)
def objective(m):
m = m.reshape((X.shape[0], w.shape[0]))
d = m.dot(w)+eps
temp = X/d
w2 = w.dot(temp.T)
deriv = w_sum - w2.T
return np.sum(d - X*np.log(d))/genes, deriv.flatten()/genes
... | def _create_m_objective(w, X) | Creates an objective function and its derivative for M, given W and X
Args:
w (array): clusters x cells
X (array): genes x cells | 6.431287 | 5.114053 | 1.257571 |
cells = len(assignments)
init_W = np.zeros((k, cells))
for i, a in enumerate(assignments):
# entirely arbitrary... maybe it would be better to scale
# the weights based on k?
init_W[a, i] = max_assign_weight
for a2 in range(k):
if a2!=a:
init_... | def initialize_from_assignments(assignments, k, max_assign_weight=0.75) | Creates a weight initialization matrix from Poisson clustering assignments.
Args:
assignments (array): 1D array of integers, of length cells
k (int): number of states/clusters
max_assign_weight (float, optional): between 0 and 1 - how much weight to assign to the highest cluster. Default: 0... | 3.908104 | 3.958015 | 0.98739 |
init_w = np.zeros((data.shape[0], k))
if sparse.issparse(data):
for i in range(k):
if data[:,clusters==i].shape[1]==0:
point = np.random.randint(0, data.shape[1])
init_w[:,i] = data[:,point].toarray().flatten()
else:
# memory u... | def initialize_means(data, clusters, k) | Initializes the M matrix given the data and a set of cluster labels.
Cluster centers are set to the mean of each cluster.
Args:
data (array): genes x cells
clusters (array): 1d array of ints (0...k-1)
k (int): number of clusters | 2.288464 | 2.342299 | 0.977016 |
# TODO
genes, cells = data.shape
k = means.shape[1]
if lognorm:
data = log1p(cell_normalize(data))
for i in range(cells):
for j in range(k):
pass | def initialize_weights_nn(data, means, lognorm=True) | Initializes the weights with a nearest-neighbor approach using the means. | 5.975041 | 5.83676 | 1.023691 |
genes, cells = data.shape
if init_means is None:
if init_weights is not None:
if len(init_weights.shape)==1:
means = initialize_means(data, init_weights, clusters)
else:
means = initialize_means(data, init_weights.argmax(0),
... | def initialize_means_weights(data, clusters, init_means=None, init_weights=None, initialization='tsvd', max_assign_weight=0.75) | Generates initial means and weights for state estimation. | 2.461793 | 2.45628 | 1.002244 |
genes, cells = data.shape
k = old_M.shape[1]
non_selected_genes = [x for x in range(genes) if x not in set(selected_genes)]
# 1. initialize new M
new_M = np.zeros((genes, k))
new_M[selected_genes, :] = old_M
# TODO: how to initialize rest of genes?
# data*w?
if disp:
pri... | def update_m(data, old_M, old_W, selected_genes, disp=False, inner_max_iters=100, parallel=True, threads=4, write_progress_file=None, tol=0.0, regularization=0.0, **kwargs) | This returns a new M matrix that contains all genes, given an M that was
created from running state estimation with a subset of genes.
Args:
data (sparse matrix or dense array): data matrix of shape (genes, cells), containing all genes
old_M (array): shape is (selected_genes, k)
old_W (... | 3.580869 | 3.586643 | 0.99839 |
from pyvesync.vesync import VeSync
conf = config[DOMAIN]
manager = VeSync(conf.get(CONF_USERNAME), conf.get(CONF_PASSWORD),
time_zone=conf.get(CONF_TIME_ZONE))
if not manager.login():
_LOGGER.error("Unable to login to VeSync")
return
manager.update()
... | def setup(hass, config) | Set up the VeSync component. | 2.619491 | 2.285327 | 1.146221 |
if len(M_list)==0:
M_list = []
for i in range(n_runs):
M, W, ll = poisson_estimate_state(data, k, **se_params)
M_list.append(M)
M_stacked = np.hstack(M_list)
M_new, W_new, ll = poisson_estimate_state(M_stacked, k, **se_params)
W_new = np.dot(data.T, M_new)
... | def state_estimation_ensemble(data, k, n_runs=10, M_list=[], **se_params) | Runs an ensemble method on the list of M results...
Args:
data: genes x cells array
k: number of classes
n_runs (optional): number of random initializations of state estimation
M_list (optional): list of M arrays from state estimation
se_params (optional): optional poisson_e... | 2.483251 | 1.949432 | 1.273833 |
nmf = NMF(k)
if len(W_list)==0:
W_list = []
for i in range(n_runs):
W = nmf.fit_transform(data)
W_list.append(W)
W_stacked = np.hstack(W_list)
nmf_w = nmf.fit_transform(W_stacked)
nmf_h = nmf.components_
H_new = data.T.dot(nmf_w).T
nmf2 = NMF(k, i... | def nmf_ensemble(data, k, n_runs=10, W_list=[], **nmf_params) | Runs an ensemble method on the list of NMF W matrices...
Args:
data: genes x cells array (should be log + cell-normalized)
k: number of classes
n_runs (optional): number of random initializations of state estimation
M_list (optional): list of M arrays from state estimation
s... | 2.893488 | 3.070446 | 0.942367 |
# TODO
nmf = NMF(k)
W_list = []
kf = KFold(n_splits=n_runs, shuffle=True)
# TODO: randomly divide data into n_runs folds
for train_index, test_index in kf.split(data.T):
W = nmf.fit_transform(data[:,train_index])
W_list.append(W)
W_stacked = np.hstack(W_list)
nmf_w =... | def nmf_kfold(data, k, n_runs=10, **nmf_params) | Runs K-fold ensemble topic modeling (Belford et al. 2017) | 2.686304 | 2.696347 | 0.996275 |
init_w = np.zeros((data.shape[0], k))
if sparse.issparse(data):
for i in range(k):
if data[:,clusters==i].shape[1]==0:
point = np.random.randint(0, data.shape[1])
init_w[:,i] = data[:,point].toarray().flatten()
else:
init_w[:,i... | def nmf_init(data, clusters, k, init='enhanced') | runs enhanced NMF initialization from clusterings (Gong 2013)
There are 3 options for init:
enhanced - uses EIn-NMF from Gong 2013
basic - uses means for W, assigns H such that the chosen cluster for a given cell has value 0.75 and all others have 0.25/(k-1).
nmf - uses means for W, and ass... | 2.092698 | 2.054508 | 1.018589 |
clusters = []
nmf = NMF(k)
tsne = TSNE(2)
km = KMeans(k)
for i in range(n_runs):
w = nmf.fit_transform(data)
h = nmf.components_
tsne_wh = tsne.fit_transform(w.dot(h).T)
clust = km.fit_predict(tsne_wh)
clusters.append(clust)
clusterings = np.vstack(cl... | def nmf_tsne(data, k, n_runs=10, init='enhanced', **params) | runs tsne-consensus-NMF
1. run a bunch of NMFs, get W and H
2. run tsne + km on all WH matrices
3. run consensus clustering on all km results
4. use consensus clustering as initialization for a new run of NMF
5. return the W and H from the resulting NMF run | 3.500878 | 3.12659 | 1.119711 |
clusters = []
norm_data = cell_normalize(data)
if sparse.issparse(data):
log_data = data.log1p()
log_norm = norm_data.log1p()
else:
log_data = np.log1p(data)
log_norm = np.log1p(norm_data)
tsvd_50 = TruncatedSVD(50)
tsvd_k = TruncatedSVD(k)
km = KMeans(k)... | def poisson_se_multiclust(data, k, n_runs=10, **se_params) | Initializes state estimation using a consensus of several
fast clustering/dimensionality reduction algorithms.
It does a consensus of 8 truncated SVD - k-means rounds, and uses the
basic nmf_init to create starting points. | 2.435839 | 2.269926 | 1.073092 |
clusters = []
for i in range(n_runs):
assignments, means = poisson_cluster(data, k)
clusters.append(assignments)
clusterings = np.vstack(clusters)
consensus = CE.cluster_ensembles(clusterings, verbose=False, N_clusters_max=k)
init_m, init_w = nmf_init(data, consensus, k, 'basic... | def poisson_consensus_se(data, k, n_runs=10, **se_params) | Initializes Poisson State Estimation using a consensus Poisson clustering. | 5.331558 | 4.95674 | 1.075618 |
# TODO: why is this not working
n_rounds = k/ks
R_i = data.copy()
nmf = NMF(ks)
nmf2 = NMF(ks, init='custom')
w_is = []
h_is = []
rs = []
w_i = np.zeros((data.shape[0], ks))
h_i = np.zeros((ks, data.shape[1]))
for i in range(n_rounds):
R_i = R_i - w_i.dot(h_i)
... | def lensNMF(data, k, ks=1) | Runs L-EnsNMF on the data. (Suh et al. 2016) | 2.443264 | 2.433693 | 1.003933 |
family = None
LOG.info("Parsing family information")
family_parser = FamilyParser(family_lines, family_type)
families = list(family_parser.families.keys())
LOG.info("Found families {0}".format(', '.join(families)))
if len(families) > 1:
raise CaseError("Only one ... | def get_case(family_lines, family_type='ped', vcf_path=None) | Return ped_parser case from a family file
Create a dictionary with case data. If no family file is given create from VCF
Args:
family_lines (iterator): The family lines
family_type (str): The format of the family lines
vcf_path(str): Path to VCF
Returns:
family... | 3.536084 | 3.768878 | 0.938232 |
variant_nrs = ['nr_variants', 'nr_sv_variants']
individuals = [('individuals','_inds'), ('sv_individuals','_sv_inds')]
updated_case = deepcopy(existing_case)
for i,file_name in enumerate(['vcf_path','vcf_sv_path']):
variant_type = 'snv'
if file_name == 'vcf_sv_path':
... | def update_case(case_obj, existing_case) | Update an existing case
This will add paths to VCF files, individuals etc
Args:
case_obj(models.Case)
existing_case(models.Case)
Returns:
updated_case(models.Case): Updated existing case | 3.016073 | 2.96285 | 1.017963 |
if len(args) != 2:
print(main.__doc__)
sys.exit(1)
doc = libsedml.readSedML(args[1]);
if ( doc.getErrorLog().getNumFailsWithSeverity(libsedml.LIBSEDML_SEV_ERROR) > 0):
print doc.getErrorLog().toString();
sys.exit(2);
print 'The document has {0}" simulation(s).'.format(doc.getNumSimulat... | def main (args) | Usage: print_sedml input-filename | 2.283485 | 2.222831 | 1.027287 |
login_resp = await self._request(
'post',
API_URL_USER,
json={
'version': '1.0',
'method': 'Signin',
'param': {
'Email': email,
'Password': password,
'CaptchaC... | async def login(self, email: str, password: str) -> bool | Login to the profile. | 4.00355 | 3.762889 | 1.063957 |
packages_resp = await self._request(
'post',
API_URL_BUYER,
json={
'version': '1.0',
'method': 'GetTrackInfoList',
'param': {
'IsArchived': show_archived,
'Item': '',
... | async def packages(
self, package_state: Union[int, str] = '',
show_archived: bool = False) -> list | Get the list of packages associated with the account. | 4.017373 | 3.954465 | 1.015908 |
summary_resp = await self._request(
'post',
API_URL_BUYER,
json={
'version': '1.0',
'method': 'GetIndexData',
'param': {
'IsArchived': show_archived
},
'sourcetype': 0... | async def summary(self, show_archived: bool = False) -> dict | Get a quick summary of how many packages are in an account. | 6.428539 | 5.722672 | 1.123346 |
if discovery_info is None:
return
switches = []
manager = hass.data[DOMAIN]['manager']
if manager.outlets is not None and manager.outlets:
if len(manager.outlets) == 1:
count_string = 'switch'
else:
count_string = 'switches'
_LOGGER.info("... | def setup_platform(hass, config, add_entities, discovery_info=None) | Set up the VeSync switch platform. | 3.108091 | 2.808246 | 1.106773 |
attr = {}
attr['active_time'] = self.smartplug.active_time
attr['voltage'] = self.smartplug.voltage
attr['active_time'] = self.smartplug.active_time
attr['weekly_energy_total'] = self.smartplug.weekly_energy_total
attr['monthly_energy_total'] = self.smartplug.mon... | def device_state_attributes(self) | Return the state attributes of the device. | 2.079138 | 1.986077 | 1.046857 |
update = {
'$inc': {
'homozygote': variant.get('homozygote', 0),
'hemizygote': variant.get('hemizygote', 0),
'observations': 1
},
'$set': {
'chrom': variant.get('chrom'),
... | def _get_update(self, variant) | Convert a variant to a proper update
Args:
variant(dict)
Returns:
update(dict) | 2.486461 | 2.586727 | 0.961238 |
LOG.debug("Upserting variant: {0}".format(variant.get('_id')))
update = self._get_update(variant)
message = self.db.variant.update_one(
{'_id': variant['_id']},
update,
upsert=True
)
if message.modified_count == 1:
... | def add_variant(self, variant) | Add a variant to the variant collection
If the variant exists we update the count else we insert a new variant object.
Args:
variant (dict): A variant dictionary | 3.625354 | 3.748569 | 0.96713 |
operations = []
nr_inserted = 0
for i,variant in enumerate(variants, 1):
# We need to check if there was any information returned
# The variant could be excluded based on low gq or if no individiual was called
# in the particular case
... | def add_variants(self, variants) | Add a bulk of variants
This could be used for faster inserts
Args:
variants(iterable(dict)) | 4.25406 | 4.112267 | 1.034481 |
query = {'_id': {'$in': variant_ids}}
return self.db.variant.find(query) | def search_variants(self, variant_ids) | Make a batch search for variants in the database
Args:
variant_ids(list(str)): List of variant ids
Returns:
res(pymngo.Cursor(variant_obj)): The result | 4.180952 | 6.743824 | 0.619968 |
query = {}
if chromosome:
query['chrom'] = chromosome
if start:
query['start'] = {'$lte': end}
query['end'] = {'$gte': start}
LOG.info("Find all variants {}".format(query))
return self.db.variant.find(query).sort([('start', ASCENDING)]... | def get_variants(self, chromosome=None, start=None, end=None) | Return all variants in the database
If no region is specified all variants will be returned.
Args:
chromosome(str)
start(int)
end(int)
Returns:
variants(Iterable(Variant)) | 3.186376 | 3.510522 | 0.907664 |
mongo_variant = self.get_variant(variant)
if mongo_variant:
if mongo_variant['observations'] == 1:
LOG.debug("Removing variant {0}".format(
mongo_variant.get('_id')
))
message = self.db.variant... | def delete_variant(self, variant) | Delete observation in database
This means that we take down the observations variable with one.
If 'observations' == 1 we remove the variant. If variant was homozygote
we decrease 'homozygote' with one.
Also remove the family from array 'families'.
Args:
variant (di... | 2.807918 | 2.580089 | 1.088303 |
if sv:
res = self.db.structural_variant.distinct('chrom')
else:
res = self.db.variant.distinct('chrom')
return res | def get_chromosomes(self, sv=False) | Return a list of all chromosomes found in database
Args:
sv(bool): if sv variants should be choosen
Returns:
res(iterable(str)): An iterable with all chromosomes in the database | 4.510236 | 4.936923 | 0.913572 |
res = self.db.variant.find({'chrom':chrom}, {'_id':0, 'end':1}).sort([('end', DESCENDING)]).limit(1)
end = 0
for variant in res:
end = variant['end']
return end | def get_max_position(self, chrom) | Get the last position observed on a chromosome in the database
Args:
chrom(str)
Returns:
end(int): The largest end position found | 3.051115 | 3.24654 | 0.939805 |
filename = filename or background_path
if not os.path.isfile(filename):
LOG.warning("File {} does not exist. Please point to a valid file".format(filename))
ctx.abort()
call = ['mongorestore', '--gzip', '--db', 'loqusdb', '--archive={}'.format(filename)]
LOG.info('Restorin... | def restore(ctx, filename) | Restore the database from a zipped file.
Default is to restore from db dump in loqusdb/resources/ | 3.35873 | 3.28252 | 1.023217 |
n_genes = data.shape[0]
n_cells = data.shape[1]
new_data = data.copy()
total_count = float(data.sum())
to_remove = total_count*percent
# sum of read counts per cell
cell_sums = data.sum(0).astype(float)
# probability of selecting genes per cell
cell_gene_probs = data/cell_sums
... | def downsample(data, percent) | downsample the data by removing a given percentage of the reads.
Args:
data: genes x cells array or sparse matrix
percent: float between 0 and 1 | 3.057307 | 2.942007 | 1.039191 |
genes, clusters = m.shape
cells = X.shape[1]
R1 = R.reshape((genes, 1)).dot(np.ones((1, cells)))
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
re... | def _create_w_objective(m, X, R) | 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
R (array): 1 x genes | 5.170357 | 4.694198 | 1.101436 |
clusters, cells = w.shape
genes = X.shape[0]
#m = m.reshape((X.shape[0], w.shape[0]))
d = m.dot(w)+eps
#temp = X/d
#w_sum = w.sum(1)
#w2 = w.dot(temp.T)
#deriv = w_sum - w2.T
return np.sum(d - X*np.log(d))/genes | def poisson_objective(X, m, w) | Creates an objective function and its derivative for M, given W and X
Args:
w (array): clusters x cells
X (array): genes x cells
selected_genes (array): array of ints - genes to be selected | 6.721255 | 5.404526 | 1.243634 |
if lightlda_folder is None:
lightlda_folder = LIGHTLDA_FOLDER
if prepare_data:
prepare_lightlda_data(data, input_folder, lightlda_folder)
# Check if initializations for M/W were provided.
if ((init_means is not None) and (init_weights is None)) or ((init_means is None) and (init_we... | def lightlda_estimate_state(data, k, input_folder="data1/LightLDA_input", threads=8, max_iters=250, prepare_data=True, init_means=None, init_weights=None, lightlda_folder=None, data_capacity=1000) | Runs LDA on the given dataset (can be an 2-D array of any form - sparse
or dense, as long as it can be indexed). If the data has not already been
prepared into LDA format, set "prepare_data" to TRUE. If "prepare_data" is
FALSE, the method assumes that the data has already been preprocessed into
LightLDA... | 3.493577 | 3.519988 | 0.992497 |
# configure root logger to print to STDERR
loglevel = "INFO"
if verbose:
loglevel = "DEBUG"
coloredlogs.install(level=loglevel)
p = Path(directory)
if not p.is_dir():
LOG.warning("{0} is not a valid directory".format(directory))
ctx.abort()
start_t... | def cli(ctx, directory, uri, verbose, count) | Load all files in a directory. | 3.021696 | 3.039865 | 0.994023 |
init_m = np.zeros((data.shape[0], k))
if sparse.issparse(data):
for i in range(k):
if data[:,clusters==i].shape[1]==0:
point = np.random.randint(0, data.shape[1])
init_m[:,i] = data[:,point].toarray().flatten()
else:
init_m[:,i... | def nmf_init(data, clusters, k, init='enhanced') | Generates initial M and W given a data set and an array of cluster labels.
There are 3 options for init:
enhanced - uses EIn-NMF from Gong 2013
basic - uses means for M, assigns W such that the chosen cluster for a given cell has value 0.75 and all others have 0.25/(k-1).
nmf - uses means f... | 2.093305 | 2.034661 | 1.028823 |
init = None
data = log1p(cell_normalize(data))
if init_weights is not None or init_means is not None:
init = 'custom'
if init_weights is None:
init_weights_, _, n_iter = non_negative_factorization(data.T, n_components=k, init='custom', update_W=False, W=init_means.T)
... | def log_norm_nmf(data, k, normalize_w=True, return_cost=True, init_weights=None, init_means=None, write_progress_file=None, **kwargs) | Args:
data (array): dense or sparse array with shape (genes, cells)
k (int): number of cell types
normalize_w (bool, optional): True if W should be normalized (so that each column sums to 1). Default: True
return_cost (bool, optional): True if the NMF objective value (squared error) shou... | 2.352998 | 2.387049 | 0.985735 |
par = False
for interval in PAR.get(chrom,[]):
if (pos >= interval[0] and pos <= interval[1]):
par = True
return par | def check_par(chrom, pos) | Check if a coordinate is in the PAR region
Args:
chrom(str)
pos(int)
Returns:
par(bool) | 4.557381 | 5.838753 | 0.78054 |
variant_id = '_'.join([
str(variant.CHROM),
str(variant.POS),
str(variant.REF),
str(variant.ALT[0])
]
)
return variant_id | def get_variant_id(variant) | Get a variant id on the format chrom_pos_ref_alt | 2.508372 | 2.212008 | 1.13398 |
a_chrom = CHROM_TO_INT.get(a.chrom,0)
b_chrom = CHROM_TO_INT.get(b.chrom,0)
if (a_chrom == 0 or b_chrom == 0):
return False
if a_chrom > b_chrom:
return True
if a_chrom == b_chrom:
if a.pos > b.pos:
return True
return False | def is_greater(a,b) | Check if position a is greater than position b
This will look at chromosome and position.
For example a position where chrom = 2 and pos = 300 is greater than a position where
chrom = 1 and pos = 1000
If any of the chromosomes is outside [1-22,X,Y,MT] we can not say which is biggest.
... | 2.317573 | 2.055384 | 1.127562 |
coordinates = {
'chrom': None,
'end_chrom': None,
'sv_length': None,
'sv_type': None,
'pos': None,
'end': None,
}
chrom = variant.CHROM
if chrom.startswith(('chr', 'CHR', 'Chr')):
chrom = chrom[3:]
coordinates['chrom'] = chrom
end_chro... | def get_coords(variant) | Returns a dictionary with position information
Args:
variant(cyvcf2.Variant)
Returns:
coordinates(dict) | 2.824418 | 2.884473 | 0.97918 |
variant_obj = None
sv = False
# Let cyvcf2 tell if it is a Structural Variant or not
if variant.var_type == 'sv':
sv = True
# chrom_pos_ref_alt
variant_id = get_variant_id(variant)
ref = variant.REF
# ALT is an array in cyvcf2
# We allways assume splitted and normaliz... | def build_variant(variant, case_obj, case_id=None, gq_treshold=None) | Return a Variant object
Take a cyvcf2 formated variant line and return a models.Variant.
If criterias are not fullfilled, eg. variant have no gt call or quality
is below gq treshold then return None.
Args:
variant(cyvcf2.Variant)
case_obj(Case): We need the case object to check indivi... | 3.773109 | 3.72938 | 1.011725 |
adapter = ctx.obj['adapter']
start_time = datetime.now()
nr_updated = migrate_database(adapter)
LOG.info("All variants updated, time to complete migration: {}".format(
datetime.now() - start_time))
LOG.info("Nr variants that where updated: %s", nr_updated) | def migrate(ctx,) | Migrate an old loqusdb instance to 1.0 | 6.180267 | 5.583749 | 1.106831 |
if not (family_file or case_id):
LOG.warning("Please provide a family file or a case id")
ctx.abort()
if not (variant_file or sv_variants):
LOG.warning("Please provide a VCF file")
ctx.abort()
variant_path = None
if variant_file:
variant_path = os.... | def update(ctx, variant_file, sv_variants, family_file, family_type, skip_case_id, gq_treshold,
case_id, ensure_index, max_window) | Load the variants of a case
A variant is loaded if it is observed in any individual of a case
If no family file is provided all individuals in vcf file will be considered. | 2.518767 | 2.535267 | 0.993492 |
adapter = ctx.obj['adapter']
version = ctx.obj['version']
LOG.info("Export the variants from {0}".format(adapter))
nr_cases = 0
is_sv = variant_type == 'sv'
existing_chromosomes = set(adapter.get_chromosomes(sv=is_sv))
ordered_chromosomes = []
for chrom in CHROMOSOME_ORDE... | def export(ctx, outfile, variant_type) | Export the variants of a loqus db
The variants are exported to a vcf file | 2.349464 | 2.344264 | 1.002219 |
# Check if the case already exists in database.
existing_case = adapter.case(case_obj)
if existing_case:
if not update:
raise CaseError("Case {0} already exists in database".format(case_obj['case_id']))
case_obj = update_case(case_obj, existing_case)
# Add the case to d... | def load_case(adapter, case_obj, update=False) | Load a case to the database
Args:
adapter: Connection to database
case_obj: dict
update(bool): If existing case should be updated
Returns:
case_obj(models.Case) | 2.641353 | 2.892793 | 0.91308 |
if variant_type == 'snv':
nr_variants = case_obj['nr_variants']
else:
nr_variants = case_obj['nr_sv_variants']
nr_inserted = 0
case_id = case_obj['case_id']
if skip_case_id:
case_id = None
# Loop over the variants in the vcf
with click.progressbar(vcf_obj, label... | def load_variants(adapter, vcf_obj, case_obj, skip_case_id=False, gq_treshold=None,
max_window=3000, variant_type='snv') | Load variants for a family into the database.
Args:
adapter (loqusdb.plugins.Adapter): initialized plugin
case_obj(Case): dict with case information
nr_variants(int)
skip_case_id (bool): whether to include the case id on variant level
or not
gq_t... | 2.789839 | 2.517982 | 1.107966 |
data = sparse.csc_matrix(data)
return sparse_means_var_csc(data.data,
data.indices,
data.indptr,
data.shape[1],
data.shape[0]) | def sparse_mean_var(data) | Calculates the variance for each row of a sparse matrix,
using the relationship Var = E[x^2] - E[x]^2.
Returns:
pair of matrices mean, variance. | 3.744913 | 4.802609 | 0.779766 |
# TODO: profile, make more efficient for large matrices
# 8000 cells: 0.325 seconds
# top time: sparse.csc_tocsr, csc_matvec, astype, copy, mul_scalar
# 73233 cells: 5.347 seconds, 4.762 s in sparse_var
# csc_tocsr: 1.736 s
# copy: 1.028 s
# astype: 0.999 s
# there is almost certain... | def max_variance_genes(data, nbins=5, frac=0.2) | This function identifies the genes that have the max variance
across a number of bins sorted by mean.
Args:
data (array): genes x cells
nbins (int): number of bins to sort genes by mean expression level. Default: 10.
frac (float): fraction of genes to return per bin - between 0 and 1. D... | 4.703223 | 4.635822 | 1.014539 |
if sparse.issparse(data):
data = sparse.csc_matrix(data.astype(float))
# normalize in-place
sparse_cell_normalize(data.data,
data.indices,
data.indptr,
data.shape[1],
data.shape[0])
return data
data_norm = data.... | def cell_normalize(data) | Returns the data where the expression is normalized so that the total
count per cell is equal. | 3.229387 | 3.156985 | 1.022934 |
if sparse.issparse(data):
return data.log1p()
else:
return np.log1p(data) | def log1p(data) | Returns ln(data+1), whether the original data is dense or sparse. | 2.607397 | 2.13434 | 1.221641 |
ind_pos = {}
if individuals:
for i, ind in enumerate(individuals):
ind_pos[ind] = i
return ind_pos | def get_individual_positions(individuals) | Return a dictionary with individual positions
Args:
individuals(list): A list with vcf individuals in correct order
Returns:
ind_pos(dict): Map from ind_id -> index position | 3.239869 | 3.826111 | 0.846779 |
# Create a dict that maps the ind ids to the position they have in vcf
individual_positions = get_individual_positions(vcf_individuals)
sv_individual_positions = get_individual_positions(sv_individuals)
family_id = None
if case:
if not case.affected_individuals:
LOG.warning... | def build_case(case, vcf_individuals=None, case_id=None, vcf_path=None, sv_individuals=None,
vcf_sv_path=None, nr_variants=None, nr_sv_variants=None, profiles=None,
matches=None, profile_path=None) | Build a Case from the given information
Args:
case(ped_parser.Family): A family object
vcf_individuals(list): Show the order of inds in vcf file
case_id(str): If another name than the one in family file should be used
vcf_path(str)
sv_individuals(list): Show the order of ind... | 2.450714 | 2.390055 | 1.02538 |
genes, clusters = centers.shape
output = np.zeros((genes, n_cells))
if cluster_probs is None:
cluster_probs = np.ones(clusters)/clusters
labels = []
for i in range(n_cells):
c = np.random.choice(range(clusters), p=cluster_probs)
labels.append(c)
output[:,i] = np.... | def generate_poisson_data(centers, n_cells, cluster_probs=None) | Generates poisson-distributed data, given a set of means for each cluster.
Args:
centers (array): genes x clusters matrix
n_cells (int): number of output cells
cluster_probs (array): prior probability for each cluster.
Default: uniform.
Returns:
output - array with ... | 2.30574 | 1.969075 | 1.170976 |
genes, clusters = M.shape
output = np.zeros((genes, n_cells))
if cluster_probs is None:
cluster_probs = np.ones(clusters)/clusters
zip_p = np.random.random((genes, n_cells))
labels = []
for i in range(n_cells):
c = np.random.choice(range(clusters), p=cluster_probs)
l... | def generate_zip_data(M, L, n_cells, cluster_probs=None) | Generates zero-inflated poisson-distributed data, given a set of means and zero probs for each cluster.
Args:
M (array): genes x clusters matrix
L (array): genes x clusters matrix - zero-inflation parameters
n_cells (int): number of output cells
cluster_probs (array): prior probabil... | 2.686925 | 2.208682 | 1.216529 |
x_true = np.dot(means, weights)
sample = np.random.poisson(x_true)
return sample.astype(float) | def generate_state_data(means, weights) | Generates data according to the Poisson Convex Mixture Model.
Args:
means (array): Cell types- genes x clusters
weights (array): Cell cluster assignments- clusters x cells
Returns:
data matrix - genes x cells | 4.767686 | 5.637574 | 0.845698 |
x_true = np.dot(means, weights)
sample = np.random.poisson(x_true)
random = np.random.random(x_true.shape)
x_true[random < z] = 0
return sample.astype(float) | def generate_zip_state_data(means, weights, z) | Generates data according to the Zero-inflated Poisson Convex Mixture Model.
Args:
means (array): Cell types- genes x clusters
weights (array): Cell cluster assignments- clusters x cells
z (float): zero-inflation parameter
Returns:
data matrix - genes x cells | 4.19032 | 4.472194 | 0.936972 |
cells = weights.shape[1]
# x_true = true means
x_true = np.dot(means, weights)
# convert means into P
R_ = np.tile(R, (cells, 1)).T
P_true = x_true/(R_ + x_true)
sample = np.random.negative_binomial(np.tile(R, (cells, 1)).T, P_true)
return sample.astype(float) | def generate_nb_state_data(means, weights, R) | Generates data according to the Negative Binomial Convex Mixture Model.
Args:
means (array): Cell types- genes x clusters
weights (array): Cell cluster assignments- clusters x cells
R (array): dispersion parameter - 1 x genes
Returns:
data matrix - genes x cells | 4.743895 | 4.61207 | 1.028583 |
W = np.random.dirichlet([1]*n_states, size=(n_cells,))
W = W.T
M = np.random.random((n_genes, n_states))*100
R = np.random.randint(1, 100, n_genes)
return M, W, R | def generate_nb_states(n_states, n_cells, n_genes) | Generates means and weights for the Negative Binomial Mixture Model.
Weights are distributed Dirichlet(1,1,...), means are rand(0, 1).
Returned values can be passed to generate_state_data(M, W).
Args:
n_states (int): number of states or clusters
n_cells (int): number of cells
n_gene... | 3.1717 | 2.466738 | 1.285787 |
W = np.random.dirichlet([1]*n_states, size=(n_cells,))
W = W.T
M = np.random.random((n_genes, n_states))*100
return M, W | def generate_poisson_states(n_states, n_cells, n_genes) | Generates means and weights for the Poisson Convex Mixture Model.
Weights are distributed Dirichlet(1,1,...), means are rand(0, 100).
Returned values can be passed to generate_state_data(M, W).
Args:
n_states (int): number of states or clusters
n_cells (int): number of cells
n_genes... | 3.560213 | 3.001374 | 1.186194 |
# means...
M = np.random.random((n_genes, n_states))*means
center = M.mean(1)
W = np.zeros((n_states, n_cells_per_cluster*n_states))
# TODO
# start at a center where all the clusters have equal probability, and for
# each cluster, interpolate linearly towards the cluster.
index = 0
... | def generate_poisson_lineage(n_states, n_cells_per_cluster, n_genes, means=300) | Generates a lineage for each state- assumes that each state has a common
ancestor.
Returns:
M - genes x clusters
W - clusters x cells | 4.162392 | 4.034391 | 1.031727 |
genes, clusters = P.shape
output = np.zeros((genes, n_cells))
if assignments is None:
cluster_probs = np.ones(clusters)/clusters
labels = []
for i in range(n_cells):
if assignments is None:
c = np.random.choice(range(clusters), p=cluster_probs)
else:
... | def generate_nb_data(P, R, n_cells, assignments=None) | Generates negative binomial data
Args:
P (array): genes x clusters
R (array): genes x clusters
n_cells (int): number of cells
assignments (list): cluster assignment of each cell. Default:
random uniform
Returns:
data array with shape genes x cells
la... | 3.452068 | 3.242971 | 1.064477 |
if method == 'pca':
pca = PCA(2)
r_dim_red = pca.fit_transform(w.T).T
elif method == 'tsne':
pass
else:
print("Method is not available. use 'pca' (default) or 'tsne'.")
return
visualize_dim_red(r_dim_red, labels, filename, figsize, title, **scatter_options) | def visualize_poisson_w(w, labels, filename, method='pca', figsize=(18,10), title='', **scatter_options) | Saves a scatter plot of a visualization of W, the result from Poisson SE. | 2.877582 | 2.94264 | 0.977891 |
fig = plt.figure(figsize=figsize)
plt.cla()
if not label_scale:
for i in set(labels):
label = i
if label_map is not None:
label = label_map[i]
if label_color_map is not None:
c = label_color_map[i]
plt.scatter(r... | def visualize_dim_red(r, labels, filename=None, figsize=(18,10), title='', legend=True, label_map=None, label_scale=False, label_color_map=None, **scatter_options) | Saves a scatter plot of a (2,n) matrix r, where each column is a cell.
Args:
r (array): (2,n) matrix
labels (array): (n,) array of ints/strings or floats. Can be None.
filename (string): string to save the output graph. If None, then this just displays the plot.
figsize (tuple): Def... | 1.619269 | 1.675549 | 0.966411 |
plt.figure(figsize=figsize)
for method in methods:
preproc= method[0]
if isinstance(preproc, Preprocess):
preprocessed, ll = preproc.run(data)
output_names = preproc.output_names
else:
# if the input is a list, only use the first preproc result
... | def generate_visualizations(methods, data, true_labels, base_dir = 'visualizations',
figsize=(18,10), **scatter_options) | Generates visualization scatters for all the methods.
Args:
methods: follows same format as run_experiments. List of tuples.
data: genes x cells
true_labels: array of integers
base_dir: base directory to save all the plots
figsize: tuple of ints representing size of figure
... | 2.524056 | 2.566988 | 0.983275 |
if self.normalize_data:
data = cell_normalize(data)
M, W, ll = poisson_estimate_state(data, **self.params)
outputs = []
if self.return_w:
outputs.append(W)
if self.return_m:
outputs.append(M)
if self.return_mw:
outp... | def run(self, data) | Returns:
list of W, M*W
ll | 5.049992 | 4.610341 | 1.095362 |
hex_conv = hex_string.split(':')
converted_hex = (int(hex_conv[0], 16) + int(hex_conv[1], 16))/8192
return converted_hex | def calculate_hex(hex_string) | Credit for conversion to itsnotlupus/vesync_wsproxy | 3.7644 | 3.784879 | 0.994589 |
if updated_list is not None and updated_list:
if orig_list is None:
orig_list = updated_list
else:
# Add new devices not in list but found in the update
for new_device in updated_list:
was_found = False
... | def resolve_updates(orig_list, updated_list) | Merges changes from one list of devices against another | 2.336087 | 2.273185 | 1.027671 |
vcf = get_file_handle(vcf_file)
individuals = vcf.samples
profiles = {individual: [] for individual in individuals}
for profile_variant in adapter.profile_variants():
ref = profile_variant['ref']
alt = profile_variant['alt']
pos = profile_variant['pos']
end = pos... | def get_profiles(adapter, vcf_file) | Given a vcf, get a profile string for each sample in the vcf
based on the profile variants in the database
Args:
adapter(MongoAdapter): Adapter to mongodb
vcf_file(str): Path to vcf file
Returns:
profiles (dict(str)): The profiles (given as strings) for each sample
... | 3.370412 | 3.370486 | 0.999978 |
matches = {sample: [] for sample in profiles.keys()}
for case in adapter.cases():
for individual in case['individuals']:
for sample in profiles.keys():
if individual.get('profile'):
similarity = compare_profiles(
profiles[... | def profile_match(adapter, profiles, hard_threshold=0.95, soft_threshold=0.9) | given a dict of profiles, searches through all the samples in the DB
for a match. If a matching sample is found an exception is raised,
and the variants will not be loaded into the database.
Args:
adapter (MongoAdapter): Adapter to mongodb
profiles (dict(str)): The profi... | 3.989263 | 3.705021 | 1.076718 |
length = len(profile1)
profile1 = np.array(list(profile1))
profile2 = np.array(list(profile2))
similarity_array = profile1 == profile2
matches = np.sum(similarity_array)
similarity_ratio = matches/length
return similarity_ratio | def compare_profiles(profile1, profile2) | Given two profiles, determine the ratio of similarity, i.e.
the hamming distance between the strings.
Args:
profile1/2 (str): profile string
Returns:
similarity_ratio (float): the ratio of similiarity (0-1) | 3.331177 | 2.980345 | 1.117715 |
for case in adapter.cases():
#If the case has a vcf_path, get the profiles and update the
#case with new profiled individuals.
if case.get('profile_path'):
profiles = get_profiles(adapter, case['profile_path'])
profiled_individuals = deepcopy(case['individual... | def update_profiles(adapter) | For all cases having vcf_path, update the profile string for the samples
Args:
adapter (MongoAdapter): Adapter to mongodb | 3.790688 | 3.461861 | 1.094986 |
profiles = []
samples = []
#Instatiate the distance dictionary with a count 0 for all the ranges
distance_dict = {key: 0 for key in HAMMING_RANGES.keys()}
for case in adapter.cases():
for individual in case['individuals']:
if individual.get('profile'):
#... | def profile_stats(adapter, threshold = 0.9) | Compares the pairwise hamming distances for all the sample profiles in
the database. Returns a table of the number of distances within given
ranges.
Args:
adapter (MongoAdapter): Adapter to mongodb
threshold (float): If any distance is found above this threshold
... | 4.155294 | 3.704873 | 1.121575 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.