text
stringlengths
18
773k
def items(self): """Return result values""" if self._result_cache: return self._result_cache.items return self.all().items
def first(self): """Return the first result""" if self._result_cache: return self._result_cache.first return self.all().first
def has_next(self): """Return True if there are more values present""" if self._result_cache: return self._result_cache.has_next return self.all().has_next
def has_prev(self): """Return True if there are previous values present""" if self._result_cache: return self._result_cache.has_prev return self.all().has_prev
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. """ klass = perform_import(...
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...
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 th...
def value(self): """Utility method to retrieve Response Object information""" # 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 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. """ errors = [errors] if not isinstance(errors, list) else errors return cls(code, 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.""" errors = [{err['parameter']: err['message']} for err in invalid_request_object.errors] return cls.build_response...
def build_not_found(cls, errors=None): """Utility method to build a HTTP 404 Resource Error response""" errors = [errors] if not isinstance(errors, list) else errors return cls(Status.NOT_FOUND, errors)
def build_system_error(cls, errors=None): """Utility method to build a HTTP 500 System Error response""" errors = [errors] if not isinstance(errors, list) else errors return cls(Status.SYSTEM_ERROR, errors)
def build_parameters_error(cls, errors=None): """Utility method to build a HTTP 400 Parameter Error response""" errors = [errors] if not isinstance(errors, list) else errors return cls(Status.PARAMETERS_ERROR, errors)
def build_unprocessable_error(cls, errors=None): """Utility method to build a HTTP 422 Parameter Error object""" errors = [errors] if not isinstance(errors, list) else errors return cls(Status.UNPROCESSABLE_ENTITY, errors)
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 ''' return np.lins...
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 ...
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: ''' if self.params.length > self.pos and samples ...
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: ''' if self.params.length > self.pos and sam...
def oauth_flow(s, oauth_url, username=None, password=None, sandbox=False): """s should be a requests session""" 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":256...
def update_database(adapter, variant_file=None, sv_file=None, family_file=None, family_type='ped', skip_case_id=False, gq_treshold=None, case_id=None, max_window = 3000): """Update a case in the database Args: adapter: Connection to database variant_file(str): Path t...
def make_crossroad_router(source, drain=False): ''' 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 ...
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/err...
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 pro...
def wipe_db(self): """Wipe the whole database""" logger.warning("Wiping the whole database") self.client.drop_database(self.db_name) logger.debug("Database wiped")
def check_indexes(self): """Check if the indexes exists""" 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') ...
def ensure_indexes(self): """Update the indexes""" 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 inde...
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 """ observations = variant.get('observations',0) homozygotes = varian...
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) """ chrom = variant.get('chrom') pos = variant.get('start') ref = variant.get('ref')...
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 """ clusters, cells = w.shape genes = X.shape[0] w_sum = w.sum(1) def objective(m): m = m.reshape((...
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, opti...
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 "...
def initialize_weights_nn(data, means, lognorm=True): """ Initializes the weights with a nearest-neighbor approach using the means. """ # 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...
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. """ genes, cells = data.shape if init_means is None: if init_weights is not None: if len(...
def poisson_estimate_state(data, clusters, init_means=None, init_weights=None, method='NoLips', max_iters=30, tol=0, disp=False, inner_max_iters=100, normalize=True, initialization='tsvd', parallel=True, threads=4, max_assign_weight=0.75, run_w_first=True, constrain_w=False, regularization=0.0, write_progress_file=None...
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 ge...
def setup(hass, config): """Set up the VeSync component.""" 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...
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): ...
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 ...
def nmf_kfold(data, k, n_runs=10, **nmf_params): """ Runs K-fold ensemble topic modeling (Belford et al. 2017) """ # 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):...
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 o...
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 a...
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. """ ...
def poisson_consensus_se(data, k, n_runs=10, **se_params): """ Initializes Poisson State Estimation using a consensus Poisson clustering. """ clusters = [] for i in range(n_runs): assignments, means = poisson_cluster(data, k) clusters.append(assignments) clusterings = np.vstack(...
def lensNMF(data, k, ks=1): """ Runs L-EnsNMF on the data. (Suh et al. 2016) """ # 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.zero...
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 line...
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 """ variant_nrs = ['nr_va...
def main (args): """Usage: print_sedml input-filename """ 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...
async def login(self, email: str, password: str) -> bool: """Login to the profile.""" login_resp = await self._request( 'post', API_URL_USER, json={ 'version': '1.0', 'method': 'Signin', 'param': { 'E...
async def packages( self, package_state: Union[int, str] = '', show_archived: bool = False) -> list: """Get the list of packages associated with the account.""" packages_resp = await self._request( 'post', API_URL_BUYER, json={ ...
async def summary(self, show_archived: bool = False) -> dict: """Get a quick summary of how many packages are in an account.""" summary_resp = await self._request( 'post', API_URL_BUYER, json={ 'version': '1.0', 'method': 'GetIndexData'...
def setup_platform(hass, config, add_entities, discovery_info=None): """Set up the VeSync switch platform.""" 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: ...
def device_state_attributes(self): """Return the state attributes of the device.""" 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.smar...
def _get_update(self, variant): """Convert a variant to a proper update Args: variant(dict) Returns: update(dict) """ update = { '$inc': { 'homozygote': variant.get('homozygote', 0), ...
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 """ LOG.debug("Upserting variant...
def add_variants(self, variants): """Add a bulk of variants This could be used for faster inserts Args: variants(iterable(dict)) """ operations = [] nr_inserted = 0 for i,variant in enumerate(variants, 1): ...
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 """ query = {'_id': {'$in': variant_ids}} ...
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(Iterab...
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 'fam...
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 """ if sv: ...
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 """ res = self.db.variant.find({'chrom':chrom}, {'_id':0,...
def restore(ctx, filename): """Restore the database from a zipped file. Default is to restore from db dump in loqusdb/resources/ """ 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...
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 """ n_genes = data.shape[0] n_cells = data.shape[1] new_data = data.copy() total_count = fl...
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 """ genes, clusters = m.shape cells = X.shape[1] R1 = R.reshape((genes, ...
def nb_estimate_state(data, clusters, R=None, init_means=None, init_weights=None, max_iters=10, tol=1e-4, disp=True, inner_max_iters=400, normalize=True): """ Uses a Negative Binomial Mixture model to estimate cell states and cell state mixing weights. If some of the genes do not fit a negative binomia...
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 """ clusters, cells = w.shape genes = X.shape[...
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 ind...
def cli(ctx, directory, uri, verbose, count): """Load all files in a directory.""" # 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}...
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...
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 n...
def check_par(chrom, pos): """Check if a coordinate is in the PAR region Args: chrom(str) pos(int) Returns: par(bool) """ par = False for interval in PAR.get(chrom,[]): if (pos >= interval[0] and pos <= interval[1]): ...
def get_variant_id(variant): """Get a variant id on the format chrom_pos_ref_alt""" variant_id = '_'.join([ str(variant.CHROM), str(variant.POS), str(variant.REF), str(variant.ALT[0]) ] ) return variant_id
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...
def get_coords(variant): """Returns a dictionary with position information Args: variant(cyvcf2.Variant) Returns: coordinates(dict) """ coordinates = { 'chrom': None, 'end_chrom': None, 'sv_length': None, 'sv_type': None, 'pos': None,...
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(cy...
def migrate(ctx,): """Migrate an old loqusdb instance to 1.0 """ 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.in...
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 ...
def export(ctx, outfile, variant_type): """Export the variants of a loqus db The variants are exported to a vcf file """ adapter = ctx.obj['adapter'] version = ctx.obj['version'] LOG.info("Export the variants from {0}".format(adapter)) nr_cases = 0 is_sv = variant_type...
def load_database(adapter, variant_file=None, sv_file=None, family_file=None, family_type='ped', skip_case_id=False, gq_treshold=None, case_id=None, max_window = 3000, profile_file=None, hard_threshold=0.95, soft_threshold=0.9): """Load the database with a case ...
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) """ # Check if the case already exists in database. ...
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 ...
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. """ data = sparse.csc_matrix(data) return sparse_means_var_csc(data.data, data.indices, ...
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 (flo...
def cell_normalize(data): """ Returns the data where the expression is normalized so that the total count per cell is equal. """ if sparse.issparse(data): data = sparse.csc_matrix(data.astype(float)) # normalize in-place sparse_cell_normalize(data.data, data.i...
def log1p(data): """ Returns ln(data+1), whether the original data is dense or sparse. """ if sparse.issparse(data): return data.log1p() else: return np.log1p(data)
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 """ ind_pos = {} if individuals: for i, ind in enu...
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): ...
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 clus...
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)...
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 """ x_true = np....
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 Retu...
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 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 o...
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 stat...
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 """ # means... M = np.random.random((n_genes, n_states))...
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 ...
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. """ if method == 'pca': pca = PCA(2) r_dim_red = pca.fit_transform(w.T).T elif method == 'tsne': ...
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,) ...
def run_experiment(methods, data, n_classes, true_labels, n_runs=10, use_purity=True, use_nmi=False, use_ari=False, use_nne=False, consensus=False): """ runs a pre-processing + clustering experiment... exactly one of use_purity, use_nmi, or use_ari can be true Args: methods: list of 2-tuples. ...
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...
def run(self, data): """ Returns: list of W, M*W ll """ 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) ...