INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Show PyPI releases for the last number of hours
def show_pypi_releases(self): """ Show PyPI releases for the last number of `hours` @returns: 0 = success or 1 if failed to retrieve from XML-RPC server """ try: hours = int(self.options.show_pypi_releases) except ValueError: self.logger.error("E...
Query PyPI for pkg download URI for a packge
def show_download_links(self): """ Query PyPI for pkg download URI for a packge @returns: 0 """ #In case they specify version as 'dev' instead of using -T svn, #don't show three svn URI's if self.options.file_type == "all" and self.version == "dev": ...
@param version: version number or dev for svn @type version: string
def print_download_uri(self, version, source): """ @param version: version number or 'dev' for svn @type version: string @param source: download source or egg @type source: boolean @returns: None """ if version == "dev": pkg_type = "subvers...
Download a package
def fetch(self): """ Download a package @returns: 0 = success or 1 if failed download """ #Default type to download source = True directory = "." if self.options.file_type == "svn": version = "dev" svn_uri = get_download_uri(self...
Use urllib. urlretrieve to download package to file in sandbox dir.
def fetch_uri(self, directory, uri): """ Use ``urllib.urlretrieve`` to download package to file in sandbox dir. @param directory: directory to download to @type directory: string @param uri: uri to download @type uri: string @returns: 0 = success or 1 for faile...
Fetch subversion repository
def fetch_svn(self, svn_uri, directory): """ Fetch subversion repository @param svn_uri: subversion repository uri to check out @type svn_uri: string @param directory: directory to download to @type directory: string @returns: 0 = success or 1 for failed downlo...
Launch web browser at project s homepage
def browse_website(self, browser=None): """ Launch web browser at project's homepage @param browser: name of web browser to use @type browser: string @returns: 0 if homepage found, 1 if no homepage found """ if len(self.all_versions): metadata = self...
Show pkg metadata queried from PyPI
def query_metadata_pypi(self): """ Show pkg metadata queried from PyPI @returns: 0 """ if self.version and self.version in self.all_versions: metadata = self.pypi.release_data(self.project_name, self.version) else: #Give highest version ...
Query PyPI for a particular version or all versions of a package
def versions_available(self): """ Query PyPI for a particular version or all versions of a package @returns: 0 if version(s) found or 1 if none found """ if self.version: spec = "%s==%s" % (self.project_name, self.version) else: spec = self.proje...
Parse search args and return spec dict for PyPI * Owwww my eyes!. Re - write this.
def parse_search_spec(self, spec): """ Parse search args and return spec dict for PyPI * Owwww, my eyes!. Re-write this. @param spec: Cheese Shop package search spec e.g. name=Cheetah license=ZPL license...
Search PyPI by metadata keyword e. g. yolk - S name = yolk AND license = GPL
def pypi_search(self): """ Search PyPI by metadata keyword e.g. yolk -S name=yolk AND license=GPL @param spec: Cheese Shop search spec @type spec: list of strings spec examples: ["name=yolk"] ["license=GPL"] ["name=yolk", "AND", "license=GP...
Show entry map for a package
def show_entry_map(self): """ Show entry map for a package @param dist: package @param type: srting @returns: 0 for success or 1 if error """ pprinter = pprint.PrettyPrinter() try: entry_map = pkg_resources.get_entry_map(self.options.show_ent...
Show entry points for a module
def show_entry_points(self): """ Show entry points for a module @returns: 0 for success or 1 if error """ found = False for entry_point in \ pkg_resources.iter_entry_points(self.options.show_entry_points): found = True try: ...
Return tuple with project_name and version from CLI args If the user gave the wrong case for the project name this corrects it
def parse_pkg_ver(self, want_installed): """ Return tuple with project_name and version from CLI args If the user gave the wrong case for the project name, this corrects it @param want_installed: whether package we want is installed or not @type want_installed: boolean ...
Install a backport import hook for Qt4 api
def install_backport_hook(api): """ Install a backport import hook for Qt4 api Parameters ---------- api : str The Qt4 api whose structure should be intercepted ('pyqt4' or 'pyside'). Example ------- >>> install_backport_hook("pyqt4") >>> import PyQt4 Loaded mod...
Install a deny import hook for Qt api.
def install_deny_hook(api): """ Install a deny import hook for Qt api. Parameters ---------- api : str The Qt api whose import should be prevented Example ------- >>> install_deny_import("pyqt4") >>> import PyQt4 Traceback (most recent call last):... ImportError: Im...
Run command and return its return status code and its output
def run_command(cmd, env=None, max_timeout=None): """ Run command and return its return status code and its output """ arglist = cmd.split() output = os.tmpfile() try: pipe = Popen(arglist, stdout=output, stderr=STDOUT, env=env) except Exception as errmsg: return 1, errmsg ...
Iterate over a slack API method supporting pagination
async def iter( self, url: Union[str, methods], data: Optional[MutableMapping] = None, headers: Optional[MutableMapping] = None, *, limit: int = 200, iterkey: Optional[str] = None, itermode: Optional[str] = None, minimum_time: Optional[int] = None,...
Connect and discard incoming RTM event if necessary.
async def _incoming_from_rtm( self, url: str, bot_id: str ) -> AsyncIterator[events.Event]: """ Connect and discard incoming RTM event if necessary. :param url: Websocket url :param bot_id: Bot ID :return: Incoming events """ async for data in self._r...
Displays the login form and handles the login action.
def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME, authentication_form=AuthenticationForm, current_app=None, extra_context=None): """ Displays the login form and handles the login action. """ redirect_to = request.POST.get(r...
Returns True if package manager owns file Returns False if package manager does not own file
def package_manager_owns(self, dist): """ Returns True if package manager 'owns' file Returns False if package manager does not 'own' file There is currently no way to determine if distutils or setuptools installed a package. A future feature of setuptools will make a pa...
If the environmental variable HTTP_PROXY is set it will most likely be in one of these forms:
def check_proxy_setting(): """ If the environmental variable 'HTTP_PROXY' is set, it will most likely be in one of these forms: proxyhost:8080 http://proxyhost:8080 urlllib2 requires the proxy URL to start with 'http://' This routine does that, and returns the transport for xml...
Returns URL of specified file type source egg or all
def filter_url(pkg_type, url): """ Returns URL of specified file type 'source', 'egg', or 'all' """ bad_stuff = ["?modtime", "#md5="] for junk in bad_stuff: if junk in url: url = url.split(junk)[0] break #pkg_spec==dev (svn) if url.endswith("-dev"): ...
Send xml - rpc request using proxy
def request(self, host, handler, request_body, verbose): '''Send xml-rpc request using proxy''' #We get a traceback if we don't have this attribute: self.verbose = verbose url = 'http://' + host + handler request = urllib2.Request(url) request.add_data(request_body) ...
Get a package name list from disk cache or PyPI
def get_cache(self): """ Get a package name list from disk cache or PyPI """ #This is used by external programs that import `CheeseShop` and don't #want a cache file written to ~/.pypi and query PyPI every time. if self.no_cache: self.pkg_list = self.list_pack...
Returns PyPI s XML - RPC server instance
def get_xmlrpc_server(self): """ Returns PyPI's XML-RPC server instance """ check_proxy_setting() if os.environ.has_key('XMLRPC_DEBUG'): debug = 1 else: debug = 0 try: return xmlrpclib.Server(XML_RPC_SERVER, transport=ProxyTrans...
Fetch list of available versions for a package from The CheeseShop
def query_versions_pypi(self, package_name): """Fetch list of available versions for a package from The CheeseShop""" if not package_name in self.pkg_list: self.logger.debug("Package %s not in cache, querying PyPI..." \ % package_name) self.fetch_pkg_list() ...
Return list of pickled package names from PYPI
def query_cached_package_list(self): """Return list of pickled package names from PYPI""" if self.debug: self.logger.debug("DEBUG: reading pickled cache file") return cPickle.load(open(self.pkg_cache_file, "r"))
Fetch and cache master list of package names from PYPI
def fetch_pkg_list(self): """Fetch and cache master list of package names from PYPI""" self.logger.debug("DEBUG: Fetching package name list from PyPI") package_list = self.list_packages() cPickle.dump(package_list, open(self.pkg_cache_file, "w")) self.pkg_list = package_list
Query PYPI via XMLRPC interface using search spec
def search(self, spec, operator): '''Query PYPI via XMLRPC interface using search spec''' return self.xmlrpc.search(spec, operator.lower())
Query PYPI via XMLRPC interface for a pkg s metadata
def release_data(self, package_name, version): """Query PYPI via XMLRPC interface for a pkg's metadata""" try: return self.xmlrpc.release_data(package_name, version) except xmlrpclib.Fault: #XXX Raises xmlrpclib.Fault if you give non-existant version #Could th...
Query PYPI via XMLRPC interface for a pkg s available versions
def package_releases(self, package_name): """Query PYPI via XMLRPC interface for a pkg's available versions""" if self.debug: self.logger.debug("DEBUG: querying PyPI for versions of " \ + package_name) return self.xmlrpc.package_releases(package_name)
Query PyPI for pkg download URI for a packge
def get_download_urls(self, package_name, version="", pkg_type="all"): """Query PyPI for pkg download URI for a packge""" if version: versions = [version] else: #If they don't specify version, show em all. (package_name, versions) = self.query_versions_pypi...
Clone the event
def clone(self) -> "Event": """ Clone the event Returns: :class:`slack.events.Event` """ return self.__class__(copy.deepcopy(self.event), copy.deepcopy(self.metadata))
Create an event with data coming from the RTM API.
def from_rtm(cls, raw_event: MutableMapping) -> "Event": """ Create an event with data coming from the RTM API. If the event type is a message a :class:`slack.events.Message` is returned. Args: raw_event: JSON decoded data from the RTM API Returns: :cla...
Create an event with data coming from the HTTP Event API.
def from_http( cls, raw_body: MutableMapping, verification_token: Optional[str] = None, team_id: Optional[str] = None, ) -> "Event": """ Create an event with data coming from the HTTP Event API. If the event type is a message a :class:`slack.events.Message` i...
Create a response message.
def response(self, in_thread: Optional[bool] = None) -> "Message": """ Create a response message. Depending on the incoming message the response can be in a thread. By default the response follow where the incoming message was posted. Args: in_thread (boolean): Over...
Serialize the message for sending to slack API
def serialize(self) -> dict: """ Serialize the message for sending to slack API Returns: serialized message """ data = {**self} if "attachments" in self: data["attachments"] = json.dumps(self["attachments"]) return data
Register a new handler for a specific: class: slack. events. Event type ( See slack event types documentation <https:// api. slack. com/ events > _ for a list of event types ).
def register(self, event_type: str, handler: Any, **detail: Any) -> None: """ Register a new handler for a specific :class:`slack.events.Event` `type` (See `slack event types documentation <https://api.slack.com/events>`_ for a list of event types). The arbitrary keyword argument is use...
Yields handlers matching the routing of the incoming: class: slack. events. Event.
def dispatch(self, event: Event) -> Iterator[Any]: """ Yields handlers matching the routing of the incoming :class:`slack.events.Event`. Args: event: :class:`slack.events.Event` Yields: handler """ LOG.debug('Dispatching event "%s"', event.get("t...
Register a new handler for a specific: class: slack. events. Message.
def register( self, pattern: str, handler: Any, flags: int = 0, channel: str = "*", subtype: Optional[str] = None, ) -> None: """ Register a new handler for a specific :class:`slack.events.Message`. The routing is based on regex pattern matchi...
Yields handlers matching the routing of the incoming: class: slack. events. Message
def dispatch(self, message: Message) -> Iterator[Any]: """ Yields handlers matching the routing of the incoming :class:`slack.events.Message` Args: message: :class:`slack.events.Message` Yields: handler """ if "text" in message: text ...
Query the slack API
def query( # type: ignore self, url: Union[str, methods], data: Optional[MutableMapping] = None, headers: Optional[MutableMapping] = None, as_json: Optional[bool] = None, ) -> dict: """ Query the slack API When using :class:`slack.methods` the reques...
Iterate over event from the RTM API
def rtm( # type: ignore self, url: Optional[str] = None, bot_id: Optional[str] = None ) -> Iterator[events.Event]: """ Iterate over event from the RTM API Args: url: Websocket connection url bot_id: Connecting bot ID Returns: :class:`sla...
Displays the login form for the given HttpRequest.
def login(self, request, extra_context=None): """ Displays the login form for the given HttpRequest. """ context = { 'title': _('Log in'), 'app_path': request.get_full_path(), } if (REDIRECT_FIELD_NAME not in request.GET and REDIREC...
Get configuration from a file.
def get_config(config_file): """Get configuration from a file.""" def load(fp): try: return yaml.safe_load(fp) except yaml.YAMLError as e: sys.stderr.write(text_type(e)) sys.exit(1) # TODO document exit codes if config_file == '-': return load(sy...
Figure out what options to use based on the four places it can come from.
def get_options(config_options, local_options, cli_options): """ Figure out what options to use based on the four places it can come from. Order of precedence: * cli_options specified by the user at the command line * local_options specified in the config file for the metric * config_op...
Output the results to stdout.
def output_results(results, metric, options): """ Output the results to stdout. TODO: add AMPQ support for efficiency """ formatter = options['Formatter'] context = metric.copy() # XXX might need to sanitize this try: context['dimension'] = list(metric['Dimensions'].values())[0] ...
This method is analogous to gsutil cp gsuri localpath but in a programatically accesible way. The only difference is that we have to make a guess about the encoding of the file to not upset downstream file operations. If you are downloading a VCF then False is great. If this is a BAM file you are asking for you should ...
def download_to_path(self, gsuri, localpath, binary_mode=False, tmpdir=None): """ This method is analogous to "gsutil cp gsuri localpath", but in a programatically accesible way. The only difference is that we have to make a guess about the encoding of the file to not upset downs...
Accurate float rounding from http:// stackoverflow. com/ a/ 15398691.
def round_float(f, digits, rounding=ROUND_HALF_UP): """ Accurate float rounding from http://stackoverflow.com/a/15398691. """ return Decimal(str(f)).quantize(Decimal(10) ** (-1 * digits), rounding=rounding)
Returns a string representing a float where the number of significant digits is min_digits unless it takes more digits to hit a non - zero digit ( and the number is 0 < x < 1 ). We stop looking for a non - zero digit after max_digits.
def float_str(f, min_digits=2, max_digits=6): """ Returns a string representing a float, where the number of significant digits is min_digits unless it takes more digits to hit a non-zero digit (and the number is 0 < x < 1). We stop looking for a non-zero digit after max_digits. """ if f >= ...
Returns full name ( first and last ) if name is available. If not returns username if available. If not available too returns the user id as a string.
def default_format(self): """ Returns full name (first and last) if name is available. If not, returns username if available. If not available too, returns the user id as a string. """ user = self.user if user.first_name is not None: return self.full_n...
Returns the first and last name of the user separated by a space.
def full_name(self): """ Returns the first and last name of the user separated by a space. """ formatted_user = [] if self.user.first_name is not None: formatted_user.append(self.user.first_name) if self.user.last_name is not None: formatted_user.a...
Returns the full name ( first and last parts ) and the username between brackets if the user has it. If there is no info about the user returns the user id between < and >.
def full_format(self): """ Returns the full name (first and last parts), and the username between brackets if the user has it. If there is no info about the user, returns the user id between < and >. """ formatted_user = self.full_name if self.user.username is not None: ...
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.
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...
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.
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(), ...
Decorator for functions that should automatically fall back to the Cohort - default filter_fn and normalized_per_mb if not specified.
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...
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.
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...
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.
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...
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 False.
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...
Estimate purity based on 2 * median VAF.
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...
Calculate the boostrapped AUC for a given col trying to predict a pred_col.
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 ...
: param are_async: True if the callbacks execute asynchronously posting any heavy work to another thread.
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_...
Can be safely called multiple times on the same worker ( for workers that support it ) to start a new thread for it.
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...
Creates a new Worker and start a new Thread with it. Returns the Worker.
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
Creates a new worker pool and starts it. Returns the Worker that schedules works to the pool.
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...
Return this Cohort as a DataFrame and optionally include additional columns using on.
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...
Instead of joining a DataFrameJoiner with the Cohort in as_dataframe sometimes we may want to just directly load a particular DataFrame.
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...
Return name of function using default value if function not defined
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
Load a dictionary of patient_id to varcode. VariantCollection
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 ...
Construct string representing state of filter_fn Used to cache filtered variants or effects uniquely depending on filter fn values
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("...
Load filtered merged variants for a single patient optionally using cache
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 ...
Load merged variants for a single patient optionally using cache
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...
Load a dataframe containing polyphen2 annotations for all variants
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. ...
Load a dictionary of patient_id to varcode. EffectCollection
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...
Load Kallisto transcript quantification data for a cohort
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,...
Load Kallisto gene quantification given a patient
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...
Load a Cufflinks gene expression data for a cohort
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 : ...
Load Cufflinks gene quantification given a patient
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...
Mostly replicates topiary. build_epitope_collection_from_binding_predictions
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...
Plot an ROC curve for benefit and a given variable
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...
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 cohort on a given variable """ no_benefit_plot_name = "No %...
Plot a comparison of boolean_col in the cohort on a given variable via on or col.
def plot_boolean(self, on, boolean_col, plot_col=None, boolean_label=None, boolean_value_map={}, order=None, ax=None, alternative="two-sided", ...
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 survival ) survival_units: str Unit of time for the survival meas...
def plot_survival(self, on, how="os", survival_units="Days", strata=None, ax=None, ci_show=False, with_condition_color="#B38600", no_condition_c...
Plot the correlation between two variables.
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`...
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.
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...
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 in various reports, e.g. ipynbs """ if self.dataframe_hash: return(self.dataframe_hash) else: df = self._as_...
Utility function to summarize provenance files for cached items used by a Cohort.
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...
Utility function to summarize data source status for this Cohort useful for confirming the state of data used for an analysis
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...
Parse out the variant calling statistics for a given variant from a Strelka VCF
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...
Parse a single sample s variant calling statistics based on Strelka VCF output
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...
Parse out the variant calling statistics for a given variant from a Mutect VCF
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...
Parse a single sample s variant calling statistics based on Mutect s ( v1 ) VCF output
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...
Parse out the variant calling statistics for a given variant from a MAF file
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...
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 True else: vcf_reader = vcf.Reader(open(variant...
Parse the variant calling stats from a variant called from multiple variant files. The stats are merged based on merge_fn
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 ...
: 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 queue.Empty: # max_seconds_idle has been exhausted, exiting ...
: 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 info requires to make up to THREE synchronous api calls. """ chat = self.api_object if full_info: self.__format_full(...
: 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(setting) default_value = self.get_default_value(setting) ...