Search is not available for this dataset
text
stringlengths
75
104k
def full_data(self): """ Returns all the info available for the user in the following format: name [username] <id> (locale) bot_or_user If any data is not available, it is not added. """ data = [ self.full_name, self._username(), se...
def full_data(self): """ Returns all the info available for the chat in the following format: title [username] (type) <id> If any data is not available, it is not added. """ data = [ self.chat.title, self._username(), self._type(), ...
def use_defaults(func): """ Decorator for functions that should automatically fall back to the Cohort-default filter_fn and normalized_per_mb if not specified. """ @wraps(func) def wrapper(row, cohort, filter_fn=None, normalized_per_mb=None, **kwargs): filter_fn = first_not_none_param([f...
def count_function(func): """ Decorator for functions that return a collection (technically a dict of collections) that should be counted up. Also automatically falls back to the Cohort-default filter_fn and normalized_per_mb if not specified. """ # Fall back to Cohort-level defaults. @use_d...
def count_variants_function_builder(function_name, filterable_variant_function=None): """ Creates a function that counts variants that are filtered by the provided filterable_variant_function. The filterable_variant_function is a function that takes a filterable_variant and returns True or False. Users...
def count_effects_function_builder(function_name, only_nonsynonymous, filterable_effect_function=None): """ Create a function that counts effects that are filtered by the provided filterable_effect_function. The filterable_effect_function is a function that takes a filterable_effect and returns True or Fals...
def median_vaf_purity(row, cohort, **kwargs): """ Estimate purity based on 2 * median VAF. Even if the Cohort has a default filter_fn, ignore it: we want to use all variants for this estimate. """ patient_id = row["patient_id"] patient = cohort.patient_from_id(patient_id) variants = coh...
def bootstrap_auc(df, col, pred_col, n_bootstrap=1000): """ Calculate the boostrapped AUC for a given col trying to predict a pred_col. Parameters ---------- df : pandas.DataFrame col : str column to retrieve the values from pred_col : str the column we're trying to predict ...
def set_callbacks(self, worker_start_callback: callable, worker_end_callback: callable, are_async: bool = False): """ :param are_async: True if the callbacks execute asynchronously, posting any heavy work to another thread. """ # We are setting self.worker_start_callback and self.worker_...
def _start_worker(self, worker: Worker): """ Can be safely called multiple times on the same worker (for workers that support it) to start a new thread for it. """ # This function is called from main thread and from worker pools threads to start their children threads wit...
def new_worker(self, name: str): """Creates a new Worker and start a new Thread with it. Returns the Worker.""" if not self.running: return self.immediate_worker worker = self._new_worker(name) self._start_worker(worker) return worker
def new_worker_pool(self, name: str, min_workers: int = 0, max_workers: int = 1, max_seconds_idle: int = DEFAULT_WORKER_POOL_MAX_SECONDS_IDLE): """ Creates a new worker pool and starts it. Returns the Worker that schedules works to the pool. """ if not sel...
def as_dataframe(self, on=None, join_with=None, join_how=None, return_cols=False, rename_cols=False, keep_paren_contents=True, **kwargs): """ Return this Cohort as a DataFrame, and optionally include additional columns using `on`. on : str or fu...
def load_dataframe(self, df_loader_name): """ Instead of joining a DataFrameJoiner with the Cohort in `as_dataframe`, sometimes we may want to just directly load a particular DataFrame. """ logger.debug("loading dataframe: {}".format(df_loader_name)) # Get the DataFrameLo...
def _get_function_name(self, fn, default="None"): """ Return name of function, using default value if function not defined """ if fn is None: fn_name = default else: fn_name = fn.__name__ return fn_name
def load_variants(self, patients=None, filter_fn=None, **kwargs): """Load a dictionary of patient_id to varcode.VariantCollection Parameters ---------- patients : str, optional Filter to a subset of patients filter_fn : function Takes a FilterableVariant ...
def _hash_filter_fn(self, filter_fn, **kwargs): """ Construct string representing state of filter_fn Used to cache filtered variants or effects uniquely depending on filter fn values """ filter_fn_name = self._get_function_name(filter_fn, default="filter-none") logger.debug("...
def _load_single_patient_variants(self, patient, filter_fn, use_cache=True, **kwargs): """ Load filtered, merged variants for a single patient, optionally using cache Note that filtered variants are first merged before filtering, and each step is cached independently. Turn on debug ...
def _load_single_patient_merged_variants(self, patient, use_cache=True): """ Load merged variants for a single patient, optionally using cache Note that merged variants are not filtered. Use `_load_single_patient_variants` to get filtered variants """ logger.debug("loadi...
def load_polyphen_annotations(self, as_dataframe=False, filter_fn=None): """Load a dataframe containing polyphen2 annotations for all variants Parameters ---------- database_file : string, sqlite Path to the WHESS/Polyphen2 SQLite database. ...
def load_effects(self, patients=None, only_nonsynonymous=False, all_effects=False, filter_fn=None, **kwargs): """Load a dictionary of patient_id to varcode.EffectCollection Note that this only loads one effect per variant. Parameters ---------- patients : s...
def load_kallisto(self): """ Load Kallisto transcript quantification data for a cohort Parameters ---------- Returns ------- kallisto_data : Pandas dataframe Pandas dataframe with Kallisto data for all patients columns include patient_id,...
def _load_single_patient_kallisto(self, patient): """ Load Kallisto gene quantification given a patient Parameters ---------- patient : Patient Returns ------- data: Pandas dataframe Pandas dataframe of sample's Kallisto data colu...
def load_cufflinks(self, filter_ok=True): """ Load a Cufflinks gene expression data for a cohort Parameters ---------- filter_ok : bool, optional If true, filter Cufflinks data to row with FPKM_status == "OK" Returns ------- cufflinks_data : ...
def _load_single_patient_cufflinks(self, patient, filter_ok): """ Load Cufflinks gene quantification given a patient Parameters ---------- patient : Patient filter_ok : bool, optional If true, filter Cufflinks data to row with FPKM_status == "OK" Ret...
def get_filtered_isovar_epitopes(self, epitopes, ic50_cutoff): """ Mostly replicates topiary.build_epitope_collection_from_binding_predictions Note: topiary needs to do fancy stuff like subsequence_protein_offset + binding_prediction.offset in order to figure out whether a variant is in...
def plot_roc_curve(self, on, bootstrap_samples=100, ax=None, **kwargs): """Plot an ROC curve for benefit and a given variable Parameters ---------- on : str or function or list or dict See `cohort.load.as_dataframe` bootstrap_samples : int, optional Numbe...
def plot_benefit(self, on, benefit_col="benefit", label="Response", ax=None, alternative="two-sided", boolean_value_map={}, order=None, **kwargs): """Plot a comparison of benefit/response in the cohort on a given variable """ no_benefit_plot_name = "No %...
def plot_boolean(self, on, boolean_col, plot_col=None, boolean_label=None, boolean_value_map={}, order=None, ax=None, alternative="two-sided", ...
def plot_survival(self, on, how="os", survival_units="Days", strata=None, ax=None, ci_show=False, with_condition_color="#B38600", no_condition_c...
def plot_correlation(self, on, x_col=None, plot_type="jointplot", stat_func=pearsonr, show_stat_func=True, plot_kwargs={}, **kwargs): """Plot the correlation between two variables. Parameters ---------- on : list or dict of functions or strings See `cohort.load.as_dataframe`...
def _list_patient_ids(self): """ Utility function to return a list of patient ids in the Cohort """ results = [] for patient in self: results.append(patient.id) return(results)
def summarize_provenance_per_cache(self): """Utility function to summarize provenance files for cached items used by a Cohort, for each cache_dir that exists. Only existing cache_dirs are summarized. This is a summary of provenance files because the function checks to see whether all pa...
def summarize_dataframe(self): """Summarize default dataframe for this cohort using a hash function. Useful for confirming the version of data used in various reports, e.g. ipynbs """ if self.dataframe_hash: return(self.dataframe_hash) else: df = self._as_...
def summarize_provenance(self): """Utility function to summarize provenance files for cached items used by a Cohort. At the moment, most PROVENANCE files contain details about packages used to generate files. However, this function is generic & so it summarizes the contents of those fil...
def summarize_data_sources(self): """Utility function to summarize data source status for this Cohort, useful for confirming the state of data used for an analysis Returns ---------- Dictionary with summary of data sources Currently contains - dataframe_hash: ha...
def strelka_somatic_variant_stats(variant, variant_metadata): """Parse out the variant calling statistics for a given variant from a Strelka VCF Parameters ---------- variant : varcode.Variant sample_info : dict Dictionary of sample to variant calling statistics, corresponds to the sample c...
def _strelka_variant_stats(variant, sample_info): """Parse a single sample"s variant calling statistics based on Strelka VCF output Parameters ---------- variant : varcode.Variant sample_info : dict Dictionary of Strelka-specific variant calling fields Returns ------- VariantSt...
def mutect_somatic_variant_stats(variant, variant_metadata): """Parse out the variant calling statistics for a given variant from a Mutect VCF Parameters ---------- variant : varcode.Variant sample_info : dict Dictionary of sample to variant calling statistics, corresponds to the sample col...
def _mutect_variant_stats(variant, sample_info): """Parse a single sample"s variant calling statistics based on Mutect"s (v1) VCF output Parameters ---------- variant : varcode.Variant sample_info : dict Dictionary of Mutect-specific variant calling fields Returns ------- Varia...
def maf_somatic_variant_stats(variant, variant_metadata): """ Parse out the variant calling statistics for a given variant from a MAF file Assumes the MAF format described here: https://www.biostars.org/p/161298/#161777 Parameters ---------- variant : varcode.Variant variant_metadata : dic...
def _vcf_is_strelka(variant_file, variant_metadata): """Return True if variant_file given is in strelka format """ if "strelka" in variant_file.lower(): return True elif "NORMAL" in variant_metadata["sample_info"].keys(): return True else: vcf_reader = vcf.Reader(open(variant...
def variant_stats_from_variant(variant, metadata, merge_fn=(lambda all_stats: \ max(all_stats, key=(lambda stats: stats.tumor_stats.depth)))): """Parse the variant calling stats from a variant called from multiple variant ...
def _get_and_execute(self): """ :return: True if it should continue running, False if it should end its execution. """ try: work = self.queue.get(timeout=self.max_seconds_idle) except queue.Empty: # max_seconds_idle has been exhausted, exiting ...
def format(self, full_info: bool = False): """ :param full_info: If True, adds more info about the chat. Please, note that this additional info requires to make up to THREE synchronous api calls. """ chat = self.api_object if full_info: self.__format_full(...
def list(self): """ :rtype: list(setting_name, value, default_value, is_set, is_supported) """ settings = [] for setting in _SETTINGS: value = self.get(setting) is_set = self.is_set(setting) default_value = self.get_default_value(setting) ...
def load_ensembl_coverage(cohort, coverage_path, min_tumor_depth, min_normal_depth=0, pageant_dir_fn=None): """ Load in Pageant CoverageDepth results with Ensembl loci. coverage_path is a path to Pageant CoverageDepth output directory, with one subdirectory per patient and a `...
def vertical_percent(plot, percent=0.1): """ Using the size of the y axis, return a fraction of that size. """ plot_bottom, plot_top = plot.get_ylim() return percent * (plot_top - plot_bottom)
def hide_ticks(plot, min_tick_value=None, max_tick_value=None): """Hide tick values that are outside of [min_tick_value, max_tick_value]""" for tick, tick_value in zip(plot.get_yticklabels(), plot.get_yticks()): tick_label = as_numeric(tick_value) if tick_label: if (min_tick_value is...
def add_significance_indicator(plot, col_a=0, col_b=1, significant=False): """ Add a p-value significance indicator. """ plot_bottom, plot_top = plot.get_ylim() # Give the plot a little room for the significance indicator line_height = vertical_percent(plot, 0.1) # Add some extra spacing bel...
def stripboxplot(x, y, data, ax=None, significant=None, **kwargs): """ Overlay a stripplot on top of a boxplot. """ ax = sb.boxplot( x=x, y=y, data=data, ax=ax, fliersize=0, **kwargs ) plot = sb.stripplot( x=x, y=y, data=da...
def fishers_exact_plot(data, condition1, condition2, ax=None, condition1_value=None, alternative="two-sided", **kwargs): """ Perform a Fisher's exact test to compare to binary columns Parameters ---------- data: Pandas dataframe Dataframe to ret...
def mann_whitney_plot(data, condition, distribution, ax=None, condition_value=None, alternative="two-sided", skip_plot=False, **kwargs): """ Create a box plot...
def roc_curve_plot(data, value_column, outcome_column, bootstrap_samples=100, ax=None): """Create a ROC curve and compute the bootstrap AUC for the given variable and outcome Parameters ---------- data : Pandas dataframe Dataframe to retrieve information from value_column : str Colu...
def get_cache_dir(cache_dir, cache_root_dir=None, *args, **kwargs): """ Return full cache_dir, according to following logic: - if cache_dir is a full path (per path.isabs), return that value - if not and if cache_root_dir is not None, join two paths - otherwise, log warnings and return N...
def _strip_column_name(col_name, keep_paren_contents=True): """ Utility script applying several regexs to a string. Intended to be used by `strip_column_names`. This function will: 1. replace informative punctuation components with text 2. (optionally) remove text within parentheses ...
def strip_column_names(cols, keep_paren_contents=True): """ Utility script for renaming pandas columns to patsy-friendly names. Revised names have been: - stripped of all punctuation and whitespace (converted to text or `_`) - converted to lower case Takes a list of column names, retur...
def set_attributes(obj, additional_data): """ Given an object and a dictionary, give the object new attributes from that dictionary. Uses _strip_column_name to git rid of whitespace/uppercase/special characters. """ for key, value in additional_data.items(): if hasattr(obj, key): ...
def return_obj(cols, df, return_cols=False): """Construct a DataFrameHolder and then return either that or the DataFrame.""" df_holder = DataFrameHolder(cols=cols, df=df) return df_holder.return_self(return_cols=return_cols)
def compare_provenance( this_provenance, other_provenance, left_outer_diff = "In current but not comparison", right_outer_diff = "In comparison but not current"): """Utility function to compare two abritrary provenance dicts returns number of discrepancies. Parameters ----------...
def _plot_kmf_single(df, condition_col, survival_col, censor_col, threshold, title, xlabel, ylabel, ax, with_condition_color, ...
def plot_kmf(df, condition_col, censor_col, survival_col, strata_col=None, threshold=None, title=None, xlabel=None, ylabel=None, ax=None, with_condition_color="#B38600", no_cond...
def concat(self, formatted_text): """:type formatted_text: FormattedText""" assert self._is_compatible(formatted_text), "Cannot concat text with different modes" self.text += formatted_text.text return self
def join(self, formatted_texts): """:type formatted_texts: list[FormattedText]""" formatted_texts = list(formatted_texts) # so that after the first iteration elements are not lost if generator for formatted_text in formatted_texts: assert self._is_compatible(formatted_text), "Cannot...
def concat(self, *args, **kwargs): """ :type args: FormattedText :type kwargs: FormattedText """ for arg in args: assert self.formatted_text._is_compatible(arg), "Cannot concat text with different modes" self.format_args.append(arg.text) for kwarg ...
def random_cohort(size, cache_dir, data_dir=None, min_random_variants=None, max_random_variants=None, seed_val=1234): """ Parameters ---------- min_random_variants: optional, int Minimum number of random variants to be generated per patient. ...
def generate_random_missense_variants(num_variants=10, max_search=100000, reference="GRCh37"): """ Generate a random collection of missense variants by trying random variants repeatedly. """ variants = [] for i in range(max_search): bases = ["A", "C", "T", "G"] random_ref = choice(ba...
def generate_simple_vcf(filename, variant_collection): """ Output a very simple metadata-free VCF for each variant in a variant_collection. """ contigs = [] positions = [] refs = [] alts = [] for variant in variant_collection: contigs.append("chr" + variant.contig) positi...
def list_folder(self, path): """Looks up folder contents of `path.`""" # Inspired by https://github.com/rspivak/sftpserver/blob/0.3/src/sftpserver/stub_sftp.py#L70 try: folder_contents = [] for f in os.listdir(path): attr = paramiko.SFTPAttributes.from_sta...
def filter_variants(variant_collection, patient, filter_fn, **kwargs): """Filter variants from the Variant Collection Parameters ---------- variant_collection : varcode.VariantCollection patient : cohorts.Patient filter_fn: function Takes a FilterableVariant and returns a boolean. Only ...
def filter_effects(effect_collection, variant_collection, patient, filter_fn, all_effects, **kwargs): """Filter variants from the Effect Collection Parameters ---------- effect_collection : varcode.EffectCollection variant_collection : varcode.VariantCollection patient : cohorts.Patient fil...
def count_lines_in(filename): "Count lines in a file" f = open(filename) lines = 0 buf_size = 1024 * 1024 read_f = f.read # loop optimization buf = read_f(buf_size) while buf: lines += buf.count('\n') buf = read_f(buf_size) return lines
def view_name_from(path): "Resolve a path to the full python module name of the related view function" try: return CACHED_VIEWS[path] except KeyError: view = resolve(path) module = path name = '' if hasattr(view.func, '__module__'): module = resol...
def generate_table_from(data): "Output a nicely formatted ascii table" table = Texttable(max_width=120) table.add_row(["view", "method", "status", "count", "minimum", "maximum", "mean", "stdev", "queries", "querytime"]) table.set_cols_align(["l", "l", "l", "r", "r", "r", "r", "r", "r", "r"]) for i...
def analyze_log_file(logfile, pattern, reverse_paths=True, progress=True): "Given a log file and regex group and extract the performance data" if progress: lines = count_lines_in(logfile) pbar = ProgressBar(widgets=[Percentage(), Bar()], maxval=lines+1).start() counter = 0 data ...
def to_string(self, limit=None): """ Create a string representation of this collection, showing up to `limit` items. """ header = self.short_string() if len(self) == 0: return header contents = "" element_lines = [ " -- %s" % (elem...
def get_instance(cls, state): """:rtype: UserStorageHandler""" if cls.instance is None: cls.instance = UserStorageHandler(state) return cls.instance
def _get_active_threads_names(): """May contain sensitive info (like user ids). Use with care.""" active_threads = threading.enumerate() return FormattedText().join( [ FormattedText().newline().normal(" - {name}").start_format().bold(name=thread.name).end_format() ...
def _get_running_workers_names(running_workers: list): """May contain sensitive info (like user ids). Use with care.""" return FormattedText().join( [ FormattedText().newline().normal(" - {name}").start_format().bold(name=worker.name).end_format() for worker i...
def _get_worker_pools_names(worker_pools: list): """May contain sensitive info (like user ids). Use with care.""" return FormattedText().join( [ FormattedText().newline().normal(" - {name}").start_format().bold(name=worker.name).end_format() for worker in work...
def format(self, member_info: bool = False): """ :param member_info: If True, adds also chat member info. Please, note that this additional info requires to make ONE api call. """ user = self.api_object self.__format_user(user) if member_info and self.chat.typ...
def safe_log_error(self, error: Exception, *info: str): """Log error failing silently on error""" self.__do_safe(lambda: self.logger.error(error, *info))
def safe_log_info(self, *info: str): """Log info failing silently on error""" self.__do_safe(lambda: self.logger.info(*info))
def wald_wolfowitz(sequence): """ implements the wald-wolfowitz runs test: http://en.wikipedia.org/wiki/Wald-Wolfowitz_runs_test http://support.sas.com/kb/33/092.html :param sequence: any iterable with at most 2 values. e.g. '1001001' [1, 0, 1, 0, 1] ...
def auto_correlation(sequence): """ test for the autocorrelation of a sequence between t and t - 1 as the 'auto_correlation' it is less likely that the sequence is generated randomly. :param sequence: any iterable with at most 2 values that can be turned into a float via np.floa...
def _parse_header_links(response): """ Parse the links from a Link: header field. .. todo:: Links with the same relation collide at the moment. :param bytes value: The header value. :rtype: `dict` :return: A dictionary of parsed links, keyed by ``rel`` or ``url``. """ values = respon...
def _default_client(jws_client, reactor, key, alg): """ Make a client if we didn't get one. """ if jws_client is None: pool = HTTPConnectionPool(reactor) agent = Agent(reactor, pool=pool) jws_client = JWSClient(HTTPClient(agent=agent), key, alg) return jws_client
def _find_supported_challenge(authzr, responders): """ Find a challenge combination that consists of a single challenge that the responder can satisfy. :param ~acme.messages.AuthorizationResource auth: The authorization to examine. :type responder: List[`~txacme.interfaces.IResponder`] ...
def answer_challenge(authzr, client, responders): """ Complete an authorization using a responder. :param ~acme.messages.AuthorizationResource auth: The authorization to complete. :param .Client client: The ACME client. :type responders: List[`~txacme.interfaces.IResponder`] :param res...
def poll_until_valid(authzr, clock, client, timeout=300.0): """ Poll an authorization until it is in a state other than pending or processing. :param ~acme.messages.AuthorizationResource auth: The authorization to complete. :param clock: The ``IReactorTime`` implementation to use; usually t...
def from_url(cls, reactor, url, key, alg=RS256, jws_client=None): """ Construct a client from an ACME directory at a given URL. :param url: The ``twisted.python.url.URL`` to fetch the directory from. See `txacme.urls` for constants for various well-known public directori...
def register(self, new_reg=None): """ Create a new registration with the ACME server. :param ~acme.messages.NewRegistration new_reg: The registration message to use, or ``None`` to construct one. :return: The registration resource. :rtype: Deferred[`~acme.messages.R...
def _maybe_location(cls, response, uri=None): """ Get the Location: if there is one. """ location = response.headers.getRawHeaders(b'location', [None])[0] if location is not None: return location.decode('ascii') return uri
def _maybe_registered(self, failure, new_reg): """ If the registration already exists, we should just load it. """ failure.trap(ServerError) response = failure.value.response if response.code == http.CONFLICT: reg = new_reg.update( resource=mes...
def agree_to_tos(self, regr): """ Accept the terms-of-service for a registration. :param ~acme.messages.RegistrationResource regr: The registration to update. :return: The updated registration resource. :rtype: Deferred[`~acme.messages.RegistrationResource`] ...
def update_registration(self, regr, uri=None): """ Submit a registration to the server to update it. :param ~acme.messages.RegistrationResource regr: The registration to update. Can be a :class:`~acme.messages.NewRegistration` instead, in order to create a new registrat...
def _parse_regr_response(self, response, uri=None, new_authzr_uri=None, terms_of_service=None): """ Parse a registration response from the server. """ links = _parse_header_links(response) if u'terms-of-service' in links: terms_of_service ...
def _check_regr(self, regr, new_reg): """ Check that a registration response contains the registration we were expecting. """ body = getattr(new_reg, 'body', new_reg) for k, v in body.items(): if k == 'resource' or not v: continue i...
def request_challenges(self, identifier): """ Create a new authorization. :param ~acme.messages.Identifier identifier: The identifier to authorize. :return: The new authorization resource. :rtype: Deferred[`~acme.messages.AuthorizationResource`] """ ...
def _expect_response(cls, response, code): """ Ensure we got the expected response code. """ if response.code != code: raise errors.ClientError( 'Expected {!r} response but got {!r}'.format( code, response.code)) return response