text
stringlengths
81
112k
Load Kallisto gene quantification given a patient Parameters ---------- patient : Patient Returns ------- data: Pandas dataframe Pandas dataframe of sample's Kallisto data columns include patient_id, target_id, length, eff_length, est_counts, tpm...
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 : Pandas dataframe Pandas dataframe with Cufflinks d...
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" Returns ------- data: Pandas dataframe Pandas dataframe o...
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 the peptide because it only has the variant's offset into the full protein...
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 Number of boostrap samples to use to compute the AUC ax : Axes, default None ...
Plot a comparison of benefit/response in the cohort on a given variable 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 co...
Plot a comparison of `boolean_col` in the cohort on a given variable via `on` or `col`. If the variable (through `on` or `col`) is binary this will compare odds-ratios and perform a Fisher's exact test. If the variable is numeric, this will compare the distributions through a M...
Plot a Kaplan Meier survival curve by splitting the cohort into two groups Parameters ---------- on : str or function or list or dict See `cohort.load.as_dataframe` how : {"os", "pfs"}, optional Whether to plot OS (overall survival) or PFS (progression free surviv...
Plot the correlation between two variables. Parameters ---------- on : list or dict of functions or strings See `cohort.load.as_dataframe` x_col : str, optional If `on` is a dict, this guarantees we have the expected ordering. plot_type : str, optional ...
Utility function to return a list of patient ids in the Cohort 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)
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 patients data have the same provenance within the cache...
Summarize default dataframe for this cohort using a hash function. Useful for confirming the version of data used in various reports, e.g. ipynbs def summarize_dataframe(self): """Summarize default dataframe for this cohort using a hash function. Useful for confirming the version of data used i...
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 files irrespective of their contents. ...
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: hash of the dataframe (see `?cohorts.Cohort.sum...
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 columns in a Strelka VCF Returns ------- SomaticV...
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 ------- VariantStats def _strelka_variant_stats(variant, sample_info): ...
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 columns in a Mutect VCF Returns ------- SomaticVar...
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 ------- VariantStats def _mutect_variant_stats(variant, sample_info)...
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 : dict Dictionary of metadata for this variant Returns ---...
Return True if variant_file given is in strelka format 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 Tru...
Parse the variant calling stats from a variant called from multiple variant files. The stats are merged based on `merge_fn` Parameters ---------- variant : varcode.Variant metadata : dict Dictionary of variant file to variant calling metadata from that file merge_fn : function F...
:return: True if it should continue running, False if it should end its execution. 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 ...
: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. def format(self, full_info: bool = False): """ :param full_info: If True, adds more info about the chat. Please, note that this additional inf...
:rtype: list(setting_name, value, default_value, is_set, is_supported) 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(se...
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 `cdf.csv` file inside each patient subdir. If min_normal_depth is 0, calculate tumor coverage. Otherwise, calculate join tumor/normal cove...
Using the size of the y axis, return a fraction of that size. 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)
Hide tick values that are outside of [min_tick_value, max_tick_value] 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_numer...
Add a p-value significance indicator. 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...
Overlay a stripplot on top of a boxplot. 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(...
Perform a Fisher's exact test to compare to binary columns Parameters ---------- data: Pandas dataframe Dataframe to retrieve information from condition1: str First binary column to compare (and used for test sidedness) condition2: str Second binary column to compare ...
Create a box plot comparing a condition and perform a Mann Whitney test to compare the distribution in condition A v B Parameters ---------- data: Pandas dataframe Dataframe to retrieve information from condition: str Column to use as the splitting criteria distribution: str ...
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 Column to retrieve the values from outcome_column : str Column to use as the outcome va...
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 None Separately, if args or kwargs are given, format cache_dir using kwargs ...
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 3. replace remaining punctuation/whitespace with _ 4. strip...
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, returns a dict mapping names to revised names. If there are any ...
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. def set_attributes(obj, additional_data): """ Given an object and a dictionary, give the object new attributes from that dictionary. Us...
Construct a DataFrameHolder and then return either that or the DataFrame. 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_co...
Utility function to compare two abritrary provenance dicts returns number of discrepancies. Parameters ---------- this_provenance: provenance dict (to be compared to "other_provenance") other_provenance: comparison provenance dict (optional) left_outer_diff: description/prefix used when pr...
Helper function to produce a single KM survival plot, among observations in df by groups defined by condition_col. All inputs are required - this function is intended to be called by `plot_kmf`. def _plot_kmf_single(df, condition_col, survival_col, ce...
Plot survival curves by splitting the dataset into two groups based on condition_col. Report results for a log-rank test (if two groups are plotted) or CoxPH survival analysis (if >2 groups) for association with survival. Regarding definition of groups: If condition_col is numeric, values are split...
:type formatted_text: FormattedText 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
:type formatted_texts: list[FormattedText] 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 ...
:type args: FormattedText :type kwargs: FormattedText 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" ...
Parameters ---------- min_random_variants: optional, int Minimum number of random variants to be generated per patient. max_random_variants: optional, int Maximum number of random variants to be generated per patient. def random_cohort(size, cache_dir, data_dir=None, min_r...
Generate a random collection of missense variants by trying random variants repeatedly. 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 ...
Output a very simple metadata-free VCF for each variant in a variant_collection. 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...
Looks up folder contents of `path.` 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): at...
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 variants returning True are preserved. Returns ------- varcode.Va...
Filter variants from the Effect Collection Parameters ---------- effect_collection : varcode.EffectCollection variant_collection : varcode.VariantCollection patient : cohorts.Patient filter_fn : function Takes a FilterableEffect and returns a boolean. Only effects returning True are pre...
Count lines in a file 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) ...
Resolve a path to the full python module name of the related view function 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 ...
Output a nicely formatted ascii table 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...
Given a log file and regex group and extract the performance data 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(),...
Create a string representation of this collection, showing up to `limit` items. 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: re...
:rtype: UserStorageHandler def get_instance(cls, state): """:rtype: UserStorageHandler""" if cls.instance is None: cls.instance = UserStorageHandler(state) return cls.instance
May contain sensitive info (like user ids). Use with care. 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(" - {na...
May contain sensitive info (like user ids). Use with care. 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...
May contain sensitive info (like user ids). Use with care. 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=...
:param member_info: If True, adds also chat member info. Please, note that this additional info requires to make ONE api call. def format(self, member_info: bool = False): """ :param member_info: If True, adds also chat member info. Please, note that this additional info requires ...
Log error failing silently on error def safe_log_error(self, error: Exception, *info: str): """Log error failing silently on error""" self.__do_safe(lambda: self.logger.error(error, *info))
Log info failing silently on error def safe_log_info(self, *info: str): """Log info failing silently on error""" self.__do_safe(lambda: self.logger.info(*info))
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] 'abaaabbba' :rtype: a ...
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.float . e.g. '1001001' ...
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``. def _parse_header_links(response): """ Parse the links from a Lin...
Make a client if we didn't get one. 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, al...
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`] :param responder: The possible responders to use. :raises...
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 responders: A list of responders that can be used to complete the...
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 the reactor, when not testing. :param .Client client: The ACM...
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 directories. :param reactor: The Twisted reactor to use. :param ~josepy.jwk.JWK...
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.RegistrationResource`] def register(self, new_reg=None...
Get the Location: if there is one. 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
If the registration already exists, we should just load it. 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: ...
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 agree_to_tos(self, regr): """ Accept...
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 registration. :param str uri: The url to submit to. Must be ...
Parse a registration response from the server. 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-...
Check that a registration response contains the registration we were expecting. 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...
Create a new authorization. :param ~acme.messages.Identifier identifier: The identifier to authorize. :return: The new authorization resource. :rtype: Deferred[`~acme.messages.AuthorizationResource`] def request_challenges(self, identifier): """ Create a new author...
Ensure we got the expected response code. 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, ...
Parse an authorization resource. def _parse_authorization(cls, response, uri=None): """ Parse an authorization resource. """ links = _parse_header_links(response) try: new_cert_uri = links[u'next'][u'url'] except KeyError: raise errors.ClientError...
Check that the authorization we got is the one we expected. def _check_authorization(cls, authzr, identifier): """ Check that the authorization we got is the one we expected. """ if authzr.body.identifier != identifier: raise errors.UnexpectedUpdate(authzr) return au...
Respond to an authorization challenge. :param ~acme.messages.ChallengeBody challenge_body: The challenge being responded to. :param ~acme.challenges.ChallengeResponse response: The response to the challenge. :return: The updated challenge resource. :rtype: Defer...
Parse a challenge resource. def _parse_challenge(cls, response): """ Parse a challenge resource. """ links = _parse_header_links(response) try: authzr_uri = links['up']['url'] except KeyError: raise errors.ClientError('"up" link missing') ...
Check that the challenge resource we got is the one we expected. def _check_challenge(cls, challenge, challenge_body): """ Check that the challenge resource we got is the one we expected. """ if challenge.uri != challenge_body.uri: raise errors.UnexpectedUpdate(challenge.uri...
Update an authorization from the server (usually to check its status). def poll(self, authzr): """ Update an authorization from the server (usually to check its status). """ action = LOG_ACME_POLL_AUTHORIZATION(authorization=authzr) with action.context(): return ( ...
Parse the Retry-After value from a response. def retry_after(cls, response, default=5, _now=time.time): """ Parse the Retry-After value from a response. """ val = response.headers.getRawHeaders(b'retry-after', [default])[0] try: return int(val) except ValueEr...
Request a certificate. Authorizations should have already been completed for all of the names requested in the CSR. Note that unlike `acme.client.Client.request_issuance`, the certificate resource will have the body data as raw bytes. .. seealso:: `txacme.util.csr_for_names` ...
Parse a response containing a certificate resource. def _parse_certificate(cls, response): """ Parse a response containing a certificate resource. """ links = _parse_header_links(response) try: cert_chain_uri = links[u'up'][u'url'] except KeyError: ...
Fetch the intermediary chain for a certificate. :param acme.messages.CertificateResource certr: The certificate to fetch the chain for. :param int max_length: The maximum length of the chain that will be fetched. :rtype: Deferred[List[`acme.messages.CertificateResource`...
Wrap ``JSONDeSerializable`` object in JWS. .. todo:: Implement ``acmePath``. :param ~josepy.interfaces.JSONDeSerializable obj: :param bytes nonce: :rtype: `bytes` :return: JSON-encoded data def _wrap_in_jws(self, nonce, obj): """ Wrap ``JSONDeSerializable`` o...
Check response content and its type. .. note:: Unlike :mod:`acme.client`, checking is strict. :param bytes content_type: Expected Content-Type response header. If the response Content-Type does not match, :exc:`ClientError` is raised. :raises .ServerErro...
Send HTTP request. :param str method: The HTTP method to use. :param str url: The URL to make the request to. :return: Deferred firing with the HTTP response. def _send_request(self, method, url, *args, **kwargs): """ Send HTTP request. :param str method: The HTTP met...
Send HEAD request without checking the response. Note that ``_check_response`` is not called, as there will be no response body to check. :param str url: The URL to make the request to. def head(self, url, *args, **kwargs): """ Send HEAD request without checking the response. ...
Send GET request and check response. :param str method: The HTTP method to use. :param str url: The URL to make the request to. :raises txacme.client.ServerError: If server response body carries HTTP Problem (draft-ietf-appsawg-http-problem-00). :raises acme.errors.ClientEr...
Store a nonce from a response we received. :param twisted.web.iweb.IResponse response: The HTTP response. :return: The response, unmodified. def _add_nonce(self, response): """ Store a nonce from a response we received. :param twisted.web.iweb.IResponse response: The HTTP res...
Get a nonce to use in a request, removing it from the nonces on hand. def _get_nonce(self, url): """ Get a nonce to use in a request, removing it from the nonces on hand. """ action = LOG_JWS_GET_NONCE() if len(self._nonces) > 0: with action: nonce = ...
POST an object and check the response. :param str url: The URL to request. :param ~josepy.interfaces.JSONDeSerializable obj: The serializable payload of the request. :param bytes content_type: The expected content type of the response. :raises txacme.client.ServerError: If ...
POST an object and check the response. Retry once if a badNonce error is received. :param str url: The URL to request. :param ~josepy.interfaces.JSONDeSerializable obj: The serializable payload of the request. :param bytes content_type: The expected content type of the respo...
Create a `threading.Thread`, but always set ``daemon``. def _daemon_thread(*a, **kw): """ Create a `threading.Thread`, but always set ``daemon``. """ thread = Thread(*a, **kw) thread.daemon = True return thread
Run a task in a worker, delivering the result as a ``Deferred`` in the reactor thread. def _defer_to_worker(deliver, worker, work, *args, **kwargs): """ Run a task in a worker, delivering the result as a ``Deferred`` in the reactor thread. """ deferred = Deferred() def wrapped_work(): ...
Split the zone portion off from a DNS label. :param str server_name: The full DNS label. :param str zone_name: The zone name suffix. def _split_zone(server_name, zone_name): """ Split the zone portion off from a DNS label. :param str server_name: The full DNS label. :param str zone_name: The ...