output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
def total(self): """Return the total number of records""" if self._result_cache: return self._result_cache.total return self.all().total
Implement a Python 3 function for returning the total number of records in the database
As a python code expert, you are capable of creating scripts from specifications.
def first(self): """Return the first result""" if self._result_cache: return self._result_cache.first return self.all().first
How would you code a function in Python 3 to return the first result
As a Python code composer, you craft elegant and concise scripts.
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
Write a Python 3 function for returning True if there are more values present
As a Python code composer, you craft elegant and concise scripts.
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
How would you code a function in Python 3 to return True if there are previous values present
You are a Python code analyst, evaluating scripts for potential improvements.
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(...
Implement a function in Python 3 to load an email backend and return an instance of it.
As a python code expert, you are capable of creating scripts from specifications.
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...
Write a Python 3 function for sending an email to a list of recipients.
As a Python code composer, you craft elegant and concise scripts.
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...
Create a Python 3 function to send a mass mail to a node.
As a Python code analyst, you investigate and solve complex coding mysteries
Utility method to build a Resource Error object.
Given the following Python 3 function, write the documentation def build_response(cls, code=Status.SYSTEM_ERROR, errors=None): errors = [errors] if not isinstance(errors, list) else errors return cls(code, errors)
You are a Python code architect, reviewing and designing scalable and efficient code
Utility method to build a HTTP 404 Resource Error response
Can you tell what is the following Python 3 function doing def build_not_found(cls, errors=None): errors = [errors] if not isinstance(errors, list) else errors return cls(Status.NOT_FOUND, errors)
As a Python code composer, you craft elegant and concise scripts.
Utility method to build a HTTP 500 System Error response
Can you generate a brief explanation for the following Python 3 code def build_system_error(cls, errors=None): errors = [errors] if not isinstance(errors, list) else errors return cls(Status.SYSTEM_ERROR, errors)
You are a Python code analyst, evaluating scripts for potential improvements.
Utility method to build a HTTP 400 Parameter Error response
Make a summary of the following Python 3 code def build_parameters_error(cls, errors=None): errors = [errors] if not isinstance(errors, list) else errors return cls(Status.PARAMETERS_ERROR, errors)
As a Python code composer, you craft elegant and concise scripts.
Utility method to build a 422 Parameter Error object
Can you generate a brief explanation for the following Python 3 code def build_unprocessable_error(cls, errors=None): errors = [errors] if not isinstance(errors, list) else errors return cls(Status.UNPROCESSABLE_ENTITY, errors)
You are a Python code architect, reviewing and designing scalable and efficient code
Returns a linearly - up to end value of the sequence of signal created by this function
Explain what the following Python 3 code does 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 ...
You are a Python code generator, capable of creating scripts from specifications.
This function is used to create a new object that is a linearly up to max value during the attack time.
Can you generate the documentation for the following Python 3 function 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, control...
As a Python code translator, you convert algorithms and pseudocode into Python.
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 ...
Create a Python 3 function to set the current value and optionally maintain it for a period
As a Python code translator, you convert algorithms and pseudocode into Python.
Create a linear section of the current value to new value over acertain number of samples.
How would you explain what the following Python 3 function does 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 :retu...
You are a Python code generator, capable of creating scripts from specifications.
This function is used to flow the user into the Salesforce website.
Can you generate the documentation for the following Python 3 function def oauth_flow(s, oauth_url, username=None, password=None, sandbox=False): 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":use...
As a Python code analyst, you investigate and solve complex coding mysteries
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...
Can you write a function in Python 3 where it updates a single case in the database.
As a Python code composer, you craft elegant and concise scripts.
Creates an error router that routes errors to the input observable.
Can you tell what is the following Python 3 function doing def make_error_router(): sink_observer = None def on_subscribe(observer): nonlocal sink_observer sink_observer = observer def dispose(): nonlocal sink_observer sink_observer = None return dispos...
You are a Python code generator, capable of creating scripts from specifications.
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...
How would you code a function in Python 3 to load the variants of a single case into the database.
As a Python code analyst, you investigate and solve complex coding mysteries
Wipe the whole database
Here you have a function in Python 3, explain what it does def wipe_db(self): logger.warning("Wiping the whole database") self.client.drop_database(self.db_name) logger.debug("Database wiped")
You are a Python code architect, reviewing and designing scalable and efficient code
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') ...
Create a Python 3 function for checking if the indexes exists
As a Python code analyst, you investigate and solve complex coding mysteries
Update the indexes for the current user
Can you tell what is the following Python 3 function doing def ensure_indexes(self): 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...
You are a Python code generator, capable of creating scripts from specifications.
Format the info field for the SNV variants
Make a summary of the following Python 3 code def format_info(variant, variant_type='snv'): observations = variant.get('observations',0) homozygotes = variant.get('homozygote') hemizygotes = variant.get('hemizygote') vcf_info = f"Obs={observations}" if homozygotes: vcf_info += f"...
As a python code expert, you are capable of creating scripts from specifications.
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')...
Write a Python 3 function that can convert a variant dictionary to a VCF formated string
As a Python code analyst, you investigate and solve complex coding mysteries
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((...
How would you code a function in Python 3 to create an objective function and its derivative for M given W and X.
You are a Python code generator, capable of creating scripts from specifications.
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...
Can you implement a function in Python 3 that creates a weight initialization matrix from Poisson clustering assignments.
You are a Python code generator, capable of creating scripts from specifications.
Initializes the M matrix given the data and a set of cluster labels.
Make a summary of the following Python 3 code def initialize_means(data, clusters, k): 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...
You are a Python code generator, capable of creating scripts from specifications.
Initializes the weights with a nearest - neighbor approach using the means.
Can you tell what is the following Python 3 function doing def initialize_weights_nn(data, means, lognorm=True): # 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
As a python code expert, you are capable of creating scripts from specifications.
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(...
Can you create a Python 3 function that generates initial means and weights for state estimation.
As a Python code analyst, you investigate and solve complex coding mysteries
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...
Write a Python 3 script to use a Poisson Covex Mixture model to estimate cell states and cell mixing weights.
As a Python code analyst, you investigate and solve complex coding mysteries
This function updates the M matrix with the given data and a subset of genes.
How would you explain what the following Python 3 function does 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): genes, cells = data.shape k = old_M.shape[1] non_selected_genes = [x f...
As a Python code composer, you craft elegant and concise scripts.
Setup the VeSync component.
Can you tell what is the following Python 3 function doing def setup(hass, config): 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(): _LOG...
You are a Python code generator, capable of creating scripts from specifications.
Runs an ensemble method on the list of M arrays from state estimation M_list is a list of M arrays from state estimation se_params is a dictionary of parameters to be used in the state estimation algorithm.
Here you have a function in Python 3, explain what it does def state_estimation_ensemble(data, k, n_runs=10, M_list=[], **se_params): 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 ...
You are a Python code architect, reviewing and designing scalable and efficient code
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 ...
Create a Python 3 function to run an ensemble method on the list of NMF W matrices...
You are a Python code analyst, evaluating scripts for potential improvements.
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):...
Create a Python 3 function to run K - fold ensemble topic modeling
As a python code expert, you are capable of creating scripts from specifications.
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...
Write a Python 3 function that can initialize the NMF model from the given data.
As a python code expert, you are capable of creating scripts from specifications.
runs tsne - NMF and tsne + k on all WH matrices and returns the W and H of the NMF run
Here you have a function in Python 3, explain what it does def nmf_tsne(data, k, n_runs=10, init='enhanced', **params): 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_transfor...
As a Python code translator, you convert algorithms and pseudocode into Python.
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. """ ...
How would you implement a function in Python 3 that initializes state estimation using a consensus of several SVD - k - means rounds and fast clustering algorithm.
As a Python code composer, you craft elegant and concise scripts.
Initializes Poisson State Estimation using a consensus Poisson clustering.
Make a summary of the following Python 3 code def poisson_consensus_se(data, k, n_runs=10, **se_params): clusters = [] for i in range(n_runs): assignments, means = poisson_cluster(data, k) clusters.append(assignments) clusterings = np.vstack(clusters) consensus = CE.cluster_ensembles(cl...
As a Python code analyst, you investigate and solve complex coding mysteries
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...
Create a Python 3 function to run L - EnsNMF on the data.
As a Python code analyst, you investigate and solve complex coding mysteries
Return ped_parser case from a family file
Here you have a function in Python 3, explain what it does def get_case(family_lines, family_type='ped', vcf_path=None): family = None LOG.info("Parsing family information") family_parser = FamilyParser(family_lines, family_type) families = list(family_parser.families.keys()) LOG.info...
As a Python code composer, you craft elegant and concise scripts.
Update an existing case with the contents of the VCF files.
Make a summary of the following Python 3 code def update_case(case_obj, existing_case): 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...
As a python code expert, you are capable of creating scripts from specifications.
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...
Create a Python 3 function to print the sequence of states in the SEDML file.
As a Python code analyst, you investigate and solve complex coding mysteries
Login to the profile.
Can you tell what is the following Python 3 function doing async def login(self, email: str, password: str) -> bool: login_resp = await self._request( 'post', API_URL_USER, json={ 'version': '1.0', 'method': 'Signin', 'param': {...
You are a Python code analyst, evaluating scripts for potential improvements.
Get the list of packages associated with the account.
Can you tell what is the following Python 3 function doing 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', ...
You are a Python code generator, capable of creating scripts from specifications.
Get a quick summary of how many packages are in an account.
Can you generate a brief explanation for the following Python 3 code async def summary(self, show_archived: bool = False) -> dict: summary_resp = await self._request( 'post', API_URL_BUYER, json={ 'version': '1.0', 'method': 'GetIndexData', ...
You are a Python code generator, capable of creating scripts from specifications.
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: ...
Create a Python 3 function for setting up the VeSync switch platform.
As a Python code analyst, you investigate and solve complex coding mysteries
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...
Write a Python 3 function for returning the state attributes of the device.
You are a Python code generator, capable of creating scripts from specifications.
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), ...
Can you write a function in Python 3 where it converts a variant to a proper update
As a Python code analyst, you investigate and solve complex coding mysteries
Adds a variant to the variant collection
How would you explain what the following Python 3 function does def add_variant(self, variant): LOG.debug("Upserting variant: {0}".format(variant.get('_id'))) update = self._get_update(variant) message = self.db.variant.update_one( {'_id': variant['_id']}, ...
As a Python code analyst, you investigate and solve complex coding mysteries
Adds a bulk of variants to the database
Given the following Python 3 function, write the documentation def add_variants(self, variants): 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 base...
You are a Python code architect, reviewing and designing scalable and efficient code
Make a batch search for variants in the database
Can you generate a brief explanation for the following Python 3 code def search_variants(self, variant_ids): query = {'_id': {'$in': variant_ids}} return self.db.variant.find(query)
As a python code expert, you are capable of creating scripts from specifications.
Return all variants in the database.
Given the following Python 3 function, write the documentation def get_variants(self, chromosome=None, start=None, end=None): query = {} if chromosome: query['chrom'] = chromosome if start: query['start'] = {'$lte': end} query['end'] = {'$gte': start} ...
You are a Python code generator, capable of creating scripts from specifications.
Delete a single variant in database
Can you tell what is the following Python 3 function doing def delete_variant(self, variant): mongo_variant = self.get_variant(variant) if mongo_variant: if mongo_variant['observations'] == 1: LOG.debug("Removing variant {0}".format( ...
As a Python code translator, you convert algorithms and pseudocode into Python.
Return a list of all chromosomes found in the database.
Can you generate a brief explanation for the following Python 3 code def get_chromosomes(self, sv=False): if sv: res = self.db.structural_variant.distinct('chrom') else: res = self.db.variant.distinct('chrom') return res
You are a Python code generator, capable of creating scripts from specifications.
Get the last position observed on a chromosome in the database
Can you generate a brief explanation for the following Python 3 code def get_max_position(self, chrom): 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
As a Python code analyst, you investigate and solve complex coding mysteries
Restore the database from a zipped file.
Can you tell what is the following Python 3 function doing def restore(ctx, filename): 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...
You are a Python code analyst, evaluating scripts for potential improvements.
Creates an objective function and its derivative for W given M and X and R.
Make a summary of the following Python 3 code def _create_w_objective(m, X, R): 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 ...
You are a Python code architect, reviewing and designing scalable and efficient code
Use a Negative Binomial Mixture model to estimate cell states and cell mixing weights for each cell.
Here you have a function in Python 3, explain what it does 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): # TODO: deal with non-NB data... just ignore it? or do something else? data_subset = data.copy() ...
You are a Python code analyst, evaluating scripts for potential improvements.
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[...
How would you implement a function in Python 3 that returns an objective function and its derivative for M given W and X.
You are a Python code architect, reviewing and designing scalable and efficient code
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...
Write a Python 3 function for running LightLDA on the given data and returns the state of the cluster.
As a Python code composer, you craft elegant and concise scripts.
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}...
Can you write a function in Python 3 where it loads all files in a directory.
As a python code expert, you are capable of creating scripts from specifications.
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...
Create a Python 3 function for generating initial M and W given a data set and an array of cluster labels.
You are a Python code architect, reviewing and designing scalable and efficient code
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...
Write a Python 3 function for logging Normalization of a NMF file.
As a python code expert, you are capable of creating scripts from specifications.
Check if a coordinate is in the PAR region AttributeNames.
Make a summary of the following Python 3 code def check_par(chrom, pos): par = False for interval in PAR.get(chrom,[]): if (pos >= interval[0] and pos <= interval[1]): par = True return par
As a Python code translator, you convert algorithms and pseudocode into Python.
Get a variant id on the format chrom_pos_ref_alt
Here you have a function in Python 3, explain what it does def get_variant_id(variant): variant_id = '_'.join([ str(variant.CHROM), str(variant.POS), str(variant.REF), str(variant.ALT[0]) ] ) return variant_id
As a Python code analyst, you investigate and solve complex coding mysteries
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...
Write a Python 3 function that can check if a position is greater than b.
You are a Python code analyst, evaluating scripts for potential improvements.
Returns a dictionary with position information for the current VCF record.
Can you generate the documentation for the following Python 3 function def get_coords(variant): coordinates = { 'chrom': None, 'end_chrom': None, 'sv_length': None, 'sv_type': None, 'pos': None, 'end': None, } chrom = variant.CHROM if chrom.startswith(('ch...
As a Python code composer, you craft elegant and concise scripts.
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...
How would you code a function in Python 3 to build a Variant object from a Cyvcf2 formated variant line and return a dictionary of Variant objects.
As a Python code analyst, you investigate and solve complex coding mysteries
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...
How would you code a function in Python 3 to migrate an old loqusdb instance to 1. 0
You are a Python code generator, capable of creating scripts from specifications.
Load the variants of a single case and store them in the database.
Given the following Python 3 function, write the documentation 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 ...
As a Python code translator, you convert algorithms and pseudocode into Python.
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...
Implement a Python 3 function for exporting the variants of a loqus db Shipment to a vcf file
As a Python code analyst, you investigate and solve complex coding mysteries
Load the database with a case and its variants
Given the following Python 3 function, write the documentation 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...
You are a Python code architect, reviewing and designing scalable and efficient code
Load a case to the database
Given the following Python 3 function, write the documentation def load_case(adapter, case_obj, update=False): # 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".for...
As a Python code composer, you craft elegant and concise scripts.
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 ...
Write a Python 3 script for loading variants for a family into the database.
As a Python code translator, you convert algorithms and pseudocode into Python.
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, ...
Write a Python 3 script for calculating the mean and variance of a sparse matrix.
As a Python code translator, you convert algorithms and pseudocode into Python.
Normalizes the data where the expression is equal to the total count per cell.
Can you generate a brief explanation for the following Python 3 code def cell_normalize(data): if sparse.issparse(data): data = sparse.csc_matrix(data.astype(float)) # normalize in-place sparse_cell_normalize(data.data, data.indices, data.indptr, ...
As a Python code composer, you craft elegant and concise scripts.
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)
Write a Python 3 function that can return the log1p of the data.
You are a Python code architect, reviewing and designing scalable and efficient code
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...
Create a Python 3 function to return a dictionary with individual positions
You are a Python code generator, capable of creating scripts from specifications.
Build a Case object from the given information.
Can you generate the documentation for the following Python 3 function 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 ...
You are a Python code architect, reviewing and designing scalable and efficient code
Generates poisson - distributed data given a set of means for each cluster.
Given the following Python 3 function, write the documentation def generate_poisson_data(centers, n_cells, cluster_probs=None): 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(...
As a Python code analyst, you investigate and solve complex coding mysteries
Generates zero - inflated poisson - distributed data given a set of means and zero probs for each cluster.
Can you generate the documentation for the following Python 3 function def generate_zip_data(M, L, n_cells, cluster_probs=None): 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_c...
You are a Python code generator, capable of creating scripts from specifications.
Generates data according to the Poisson Convex Mixture Model.
Given the following Python 3 function, write the documentation def generate_state_data(means, weights): x_true = np.dot(means, weights) sample = np.random.poisson(x_true) return sample.astype(float)
As a Python code composer, you craft elegant and concise scripts.
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...
Create a Python 3 function to generate data according to Zero - inflated Poisson Convex Mixture Model.
As a python code expert, you are capable of creating scripts from specifications.
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...
Can you create a Python 3 function that generates data according to the Negative Binomial Convex Mixture Model.
You are a Python code architect, reviewing and designing scalable and efficient code
Generates the means and weights for the Negative Binomial Mixture Model.
Explain what the following Python 3 code does def generate_nb_states(n_states, n_cells, n_genes): 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
You are a Python code analyst, evaluating scripts for potential improvements.
Generates the Poisson states for a given set of genes and number of cells.
How would you explain what the following Python 3 function does def generate_poisson_states(n_states, n_cells, n_genes): 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
You are a Python code analyst, evaluating scripts for potential improvements.
Generates a lineage for each state.
Here you have a function in Python 3, explain what it does def generate_poisson_lineage(n_states, n_cells_per_cluster, n_genes, means=300): # 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 cen...
You are a Python code analyst, evaluating scripts for potential improvements.
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 ...
Implement a Python 3 function for generating negative binomial data for a set of cells in a cluster.
As a Python code translator, you convert algorithms and pseudocode into Python.
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': ...
Create a Python 3 function for visualizing a Poisson W.
You are a Python code analyst, evaluating scripts for potential improvements.
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,) ...
Create a Python 3 function to visualize the dimred matrix r.
As a Python code translator, you convert algorithms and pseudocode into Python.
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. ...
How would you code a function in Python 3 to run a pre - processing + clustering experiment on a list of methods.
You are a Python code analyst, evaluating scripts for potential improvements.
Generates visualizations for all the methods in the cluster.
Can you generate the documentation for the following Python 3 function 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 ru...
As a Python code translator, you convert algorithms and pseudocode into Python.
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) ...
Implement a Python 3 function for running the Poisson EstimateState method.
As a Python code analyst, you investigate and solve complex coding mysteries
Credit for conversion to itsnotlupus / vesync_wsproxy
Can you generate the documentation for the following Python 3 function def calculate_hex(hex_string): hex_conv = hex_string.split(':') converted_hex = (int(hex_conv[0], 16) + int(hex_conv[1], 16))/8192 return converted_hex
As a Python code analyst, you investigate and solve complex coding mysteries
Merges changes from one list of devices against another
Can you generate the documentation for the following Python 3 function def resolve_updates(orig_list, updated_list): 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...
As a Python code analyst, you investigate and solve complex coding mysteries
create_sedml output - filename
How would you explain what the following Python 3 function does def main (args): if (len(args) != 2): print(main.__doc__) sys.exit(1); # create the document doc = libsedml.SedDocument(); doc.setLevel(1); doc.setVersion(1); # create a first model referencing an sbml file model = doc.createModel()...
You are a Python code analyst, evaluating scripts for potential improvements.
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...
Can you implement a function in Python 3 that gives a vcf file return a dictionary of profile strings for each sample in the vcf
As a python code expert, you are capable of creating scripts from specifications.
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: ...
Write a Python 3 script for returning a list of similar samples for each sample in the DB.
You are a Python code architect, reviewing and designing scalable and efficient code