sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def run(self, host="localhost", port=8000, shutdown_timeout=60.0, **kwargs): """ This function starts the service's network intefaces. Args: port (int): The port for the http server. """ print("Running service on http://localhost:%i. " % port + \ ...
This function starts the service's network intefaces. Args: port (int): The port for the http server.
entailment
def cleanup(self): """ This function is called when the service has finished running regardless of intentionally or not. """ # if an event broker has been created for this service if self.event_broker: # stop the event broker self.event_br...
This function is called when the service has finished running regardless of intentionally or not.
entailment
def add_http_endpoint(self, url, request_handler): """ This method provides a programatic way of added invidual routes to the http server. Args: url (str): the url to be handled by the request_handler request_handler (nautilus.network.RequestH...
This method provides a programatic way of added invidual routes to the http server. Args: url (str): the url to be handled by the request_handler request_handler (nautilus.network.RequestHandler): The request handler
entailment
def route(cls, route, config=None): """ This method provides a decorator for adding endpoints to the http server. Args: route (str): The url to be handled by the RequestHandled config (dict): Configuration for the request handler ...
This method provides a decorator for adding endpoints to the http server. Args: route (str): The url to be handled by the RequestHandled config (dict): Configuration for the request handler Example: .. code-block:: python ...
entailment
def generate_session_token(secret_key, **payload): """ This function generates a session token signed by the secret key which can be used to extract the user credentials in a verifiable way. """ return jwt.encode(payload, secret_key, algorithm=token_encryption_algorithm()).decode('utf-8')
This function generates a session token signed by the secret key which can be used to extract the user credentials in a verifiable way.
entailment
def summarize_mutation(mutation_name, event, inputs, outputs, isAsync=False): """ This function provides a standard representation of mutations to be used when services announce themselves """ return dict( name=mutation_name, event=event, isAsync=isAsync, inpu...
This function provides a standard representation of mutations to be used when services announce themselves
entailment
def new(cls, password, rounds): """Creates a PasswordHash from the given password.""" if isinstance(password, str): password = password.encode('utf-8') return cls(cls._new(password, rounds))
Creates a PasswordHash from the given password.
entailment
def coerce(cls, key, value): """Ensure that loaded values are PasswordHashes.""" if isinstance(value, PasswordHash): return value return super(PasswordHash, cls).coerce(key, value)
Ensure that loaded values are PasswordHashes.
entailment
def rehash(self, password): """Recreates the internal hash.""" self.hash = self._new(password, self.desired_rounds) self.rounds = self.desired_rounds
Recreates the internal hash.
entailment
def init_db(self): """ This function configures the database used for models to make the configuration parameters. """ # get the database url from the configuration db_url = self.config.get('database_url', 'sqlite:///nautilus.db') # configure the nautilus ...
This function configures the database used for models to make the configuration parameters.
entailment
def auth_criteria(self): """ This attribute provides the mapping of services to their auth requirement Returns: (dict) : the mapping from services to their auth requirements. """ # the dictionary we will return auth = {} # go over each at...
This attribute provides the mapping of services to their auth requirement Returns: (dict) : the mapping from services to their auth requirements.
entailment
async def login_user(self, password, **kwds): """ This function handles the registration of the given user credentials in the database """ # find the matching user with the given email user_data = (await self._get_matching_user(fields=list(kwds.keys()), **kwds))['data'] ...
This function handles the registration of the given user credentials in the database
entailment
async def register_user(self, password, **kwds): """ This function is used to provide a sessionToken for later requests. Args: uid (str): The """ # so make one user = await self._create_remote_user(password=password, **kwds) # if there is ...
This function is used to provide a sessionToken for later requests. Args: uid (str): The
entailment
async def object_resolver(self, object_name, fields, obey_auth=False, current_user=None, **filters): """ This function resolves a given object in the remote backend services """ try: # check if an object with that name has been registered registered = [model ...
This function resolves a given object in the remote backend services
entailment
async def mutation_resolver(self, mutation_name, args, fields): """ the default behavior for mutations is to look up the event, publish the correct event type with the args as the body, and return the fields contained in the result """ try: # make...
the default behavior for mutations is to look up the event, publish the correct event type with the args as the body, and return the fields contained in the result
entailment
async def _check_for_matching_user(self, **user_filters): """ This function checks if there is a user with the same uid in the remote user service Args: **kwds : the filters of the user to check for Returns: (bool): wether or not th...
This function checks if there is a user with the same uid in the remote user service Args: **kwds : the filters of the user to check for Returns: (bool): wether or not there is a matching user
entailment
async def _create_remote_user(self, **payload): """ This method creates a service record in the remote user service with the given email. Args: uid (str): the user identifier to create Returns: (dict): a summary of the user that was...
This method creates a service record in the remote user service with the given email. Args: uid (str): the user identifier to create Returns: (dict): a summary of the user that was created
entailment
def calculate_wer(reference, hypothesis): """ Calculation of WER with Levenshtein distance. Works only for iterables up to 254 elements (uint8). O(nm) time and space complexity. >>> calculate_wer("who is there".split(), "is there".split()) 1 >>> calculate_wer("who is...
Calculation of WER with Levenshtein distance. Works only for iterables up to 254 elements (uint8). O(nm) time and space complexity. >>> calculate_wer("who is there".split(), "is there".split()) 1 >>> calculate_wer("who is there".split(), "".split()) 3 >>> calcula...
entailment
def get_parser(): """Get a parser object""" from argparse import ArgumentParser, ArgumentDefaultsHelpFormatter parser = ArgumentParser(description=__doc__, formatter_class=ArgumentDefaultsHelpFormatter) parser.add_argument("-s1", dest="s1", help="sequence 1") parser.add_a...
Get a parser object
entailment
async def _async_request_soup(url): ''' Perform a GET web request and return a bs4 parser ''' from bs4 import BeautifulSoup import aiohttp _LOGGER.debug('GET %s', url) async with aiohttp.ClientSession() as session: resp = await session.get(url) text = await resp.text() ...
Perform a GET web request and return a bs4 parser
entailment
async def async_determine_channel(channel): ''' Check whether the current channel is correct. If not try to determine it using fuzzywuzzy ''' from fuzzywuzzy import process channel_data = await async_get_channels() if not channel_data: _LOGGER.error('No channel data. Cannot determine...
Check whether the current channel is correct. If not try to determine it using fuzzywuzzy
entailment
async def async_get_channels(no_cache=False, refresh_interval=4): ''' Get channel list and corresponding urls ''' # Check cache now = datetime.datetime.now() max_cache_age = datetime.timedelta(hours=refresh_interval) if not no_cache and 'channels' in _CACHE: cache = _CACHE.get('chann...
Get channel list and corresponding urls
entailment
def resize_program_image(img_url, img_size=300): ''' Resize a program's thumbnail to the desired dimension ''' match = re.match(r'.+/(\d+)x(\d+)/.+', img_url) if not match: _LOGGER.warning('Could not compute current image resolution of %s', img_url) return img...
Resize a program's thumbnail to the desired dimension
entailment
def get_current_program_progress(program): ''' Get the current progress of the program in % ''' now = datetime.datetime.now() program_duration = get_program_duration(program) if not program_duration: return progress = now - program.get('start_time') return progress.seconds * 100 ...
Get the current progress of the program in %
entailment
def get_program_duration(program): ''' Get a program's duration in seconds ''' program_start = program.get('start_time') program_end = program.get('end_time') if not program_start or not program_end: _LOGGER.error('Could not determine program start and/or end times.') _LOGGER.deb...
Get a program's duration in seconds
entailment
def get_remaining_time(program): ''' Get the remaining time in seconds of a program that is currently on. ''' now = datetime.datetime.now() program_start = program.get('start_time') program_end = program.get('end_time') if not program_start or not program_end: _LOGGER.error('Could no...
Get the remaining time in seconds of a program that is currently on.
entailment
def extract_program_summary(data): ''' Extract the summary data from a program's detail page ''' from bs4 import BeautifulSoup soup = BeautifulSoup(data, 'html.parser') try: return soup.find( 'div', {'class': 'episode-synopsis'} ).find_all('div')[-1].text.strip() ...
Extract the summary data from a program's detail page
entailment
async def async_set_summary(program): ''' Set a program's summary ''' import aiohttp async with aiohttp.ClientSession() as session: resp = await session.get(program.get('url')) text = await resp.text() summary = extract_program_summary(text) program['summary'] = summa...
Set a program's summary
entailment
async def async_get_program_guide(channel, no_cache=False, refresh_interval=4): ''' Get the program data for a channel ''' chan = await async_determine_channel(channel) now = datetime.datetime.now() max_cache_age = datetime.timedelta(hours=refresh_interval) if not no_cache and 'guide' in _CA...
Get the program data for a channel
entailment
async def async_get_current_program(channel, no_cache=False): ''' Get the current program info ''' chan = await async_determine_channel(channel) guide = await async_get_program_guide(chan, no_cache) if not guide: _LOGGER.warning('Could not retrieve TV program for %s', channel) re...
Get the current program info
entailment
def publish(self, distribution, storage=""): """ Get or create publish """ try: return self._publishes[distribution] except KeyError: self._publishes[distribution] = Publish(self.client, distribution, timestamp=self.timestamp, storage=(storage or self.stor...
Get or create publish
entailment
def add(self, snapshot, distributions, component='main', storage=""): """ Add mirror or repo to publish """ for dist in distributions: self.publish(dist, storage=storage).add(snapshot, component)
Add mirror or repo to publish
entailment
def _publish_match(self, publish, names=False, name_only=False): """ Check if publish name matches list of names or regex patterns """ if names: for name in names: if not name_only and isinstance(name, re._pattern_type): if re.match(name, p...
Check if publish name matches list of names or regex patterns
entailment
def get_repo_information(config, client, fill_repo=False, components=[]): """ fill two dictionnaries : one containing all the packages for every repository and the second one associating to every component of every publish its repository""" repo_dict = {} publish_dict = {} f...
fill two dictionnaries : one containing all the packages for every repository and the second one associating to every component of every publish its repository
entailment
def compare(self, other, components=[]): """ Compare two publishes It expects that other publish is same or older than this one Return tuple (diff, equal) of dict {'component': ['snapshot']} """ lg.debug("Comparing publish %s (%s) and %s (%s)" % (self.name, self.storage ...
Compare two publishes It expects that other publish is same or older than this one Return tuple (diff, equal) of dict {'component': ['snapshot']}
entailment
def _get_publish(self): """ Find this publish on remote """ publishes = self._get_publishes(self.client) for publish in publishes: if publish['Distribution'] == self.distribution and \ publish['Prefix'].replace("/", "_") == (self.prefix or '.') and...
Find this publish on remote
entailment
def save_publish(self, save_path): """ Serialize publish in YAML """ timestamp = time.strftime("%Y%m%d%H%M%S") yaml_dict = {} yaml_dict["publish"] = self.name yaml_dict["name"] = timestamp yaml_dict["components"] = [] yaml_dict["storage"] = self.s...
Serialize publish in YAML
entailment
def restore_publish(self, config, components, recreate=False): """ Restore publish from config file """ if "all" in components: components = [] try: self.load() publish = True except NoSuchPublish: publish = False ...
Restore publish from config file
entailment
def load(self): """ Load publish info from remote """ publish = self._get_publish() self.architectures = publish['Architectures'] for source in publish['Sources']: component = source['Component'] snapshot = source['Name'] self.publish_s...
Load publish info from remote
entailment
def get_packages(self, component=None, components=[], packages=None): """ Return package refs for given components """ if component: components = [component] package_refs = [] for snapshot in self.publish_snapshots: if component and snapshot['Comp...
Return package refs for given components
entailment
def parse_package_ref(self, ref): """ Return tuple of architecture, package_name, version, id """ if not ref: return None parsed = re.match('(.*)\ (.*)\ (.*)\ (.*)', ref) return parsed.groups()
Return tuple of architecture, package_name, version, id
entailment
def add(self, snapshot, component='main'): """ Add snapshot of component to publish """ try: self.components[component].append(snapshot) except KeyError: self.components[component] = [snapshot]
Add snapshot of component to publish
entailment
def _find_snapshot(self, name): """ Find snapshot on remote by name or regular expression """ remote_snapshots = self._get_snapshots(self.client) for remote in reversed(remote_snapshots): if remote["Name"] == name or \ re.match(name, remote["Name"]...
Find snapshot on remote by name or regular expression
entailment
def _get_source_snapshots(self, snapshot, fallback_self=False): """ Get list of source snapshot names of given snapshot TODO: we have to decide by description at the moment """ if not snapshot: return [] source_snapshots = re.findall(r"'([\w\d\.-]+)'", snaps...
Get list of source snapshot names of given snapshot TODO: we have to decide by description at the moment
entailment
def merge_snapshots(self): """ Create component snapshots by merging other snapshots of same component """ self.publish_snapshots = [] for component, snapshots in self.components.items(): if len(snapshots) <= 1: # Only one snapshot, no need to merge ...
Create component snapshots by merging other snapshots of same component
entailment
def timing_decorator(func): """Prints the time func takes to execute.""" @functools.wraps(func) def wrapper(*args, **kwargs): """ Wrapper for printing execution time. Parameters ---------- print_time: bool, optional whether or not to print time function t...
Prints the time func takes to execute.
entailment
def save_load_result(func): """Saves and/or loads func output (must be picklable).""" @functools.wraps(func) def wrapper(*args, **kwargs): """ Default behavior is no saving and loading. Specify save_name to save and load. Parameters ---------- save_name: str,...
Saves and/or loads func output (must be picklable).
entailment
def pickle_save(data, name, **kwargs): """Saves object with pickle. Parameters ---------- data: anything picklable Object to save. name: str Path to save to (includes dir, excludes extension). extension: str, optional File extension. overwrite existing: bool, optiona...
Saves object with pickle. Parameters ---------- data: anything picklable Object to save. name: str Path to save to (includes dir, excludes extension). extension: str, optional File extension. overwrite existing: bool, optional When the save path already contains ...
entailment
def pickle_load(name, extension='.pkl'): """Load data with pickle. Parameters ---------- name: str Path to save to (includes dir, excludes extension). extension: str, optional File extension. Returns ------- Contents of file path. """ filename = name + extension...
Load data with pickle. Parameters ---------- name: str Path to save to (includes dir, excludes extension). extension: str, optional File extension. Returns ------- Contents of file path.
entailment
def bootstrap_resample_run(ns_run, threads=None, ninit_sep=False, random_seed=False): """Bootstrap resamples threads of nested sampling run, returning a new (resampled) nested sampling run. Get the individual threads for a nested sampling run. Parameters ---------- n...
Bootstrap resamples threads of nested sampling run, returning a new (resampled) nested sampling run. Get the individual threads for a nested sampling run. Parameters ---------- ns_run: dict Nested sampling run dictionary. threads: None or list of numpy arrays, optional ninit_sep: b...
entailment
def run_std_bootstrap(ns_run, estimator_list, **kwargs): """ Uses bootstrap resampling to calculate an estimate of the standard deviation of the distribution of sampling errors (the uncertainty on the calculation) for a single nested sampling run. For more details about bootstrap resampling for est...
Uses bootstrap resampling to calculate an estimate of the standard deviation of the distribution of sampling errors (the uncertainty on the calculation) for a single nested sampling run. For more details about bootstrap resampling for estimating sampling errors see 'Sampling errors in nested sampling p...
entailment
def run_bootstrap_values(ns_run, estimator_list, **kwargs): """Uses bootstrap resampling to calculate an estimate of the standard deviation of the distribution of sampling errors (the uncertainty on the calculation) for a single nested sampling run. For more details about bootstrap resampling for estim...
Uses bootstrap resampling to calculate an estimate of the standard deviation of the distribution of sampling errors (the uncertainty on the calculation) for a single nested sampling run. For more details about bootstrap resampling for estimating sampling errors see 'Sampling errors in nested sampling p...
entailment
def run_ci_bootstrap(ns_run, estimator_list, **kwargs): """Uses bootstrap resampling to calculate credible intervals on the distribution of sampling errors (the uncertainty on the calculation) for a single nested sampling run. For more details about bootstrap resampling for estimating sampling erro...
Uses bootstrap resampling to calculate credible intervals on the distribution of sampling errors (the uncertainty on the calculation) for a single nested sampling run. For more details about bootstrap resampling for estimating sampling errors see 'Sampling errors in nested sampling parameter estimation...
entailment
def run_std_simulate(ns_run, estimator_list, n_simulate=None): """Uses the 'simulated weights' method to calculate an estimate of the standard deviation of the distribution of sampling errors (the uncertainty on the calculation) for a single nested sampling run. Note that the simulated weights method i...
Uses the 'simulated weights' method to calculate an estimate of the standard deviation of the distribution of sampling errors (the uncertainty on the calculation) for a single nested sampling run. Note that the simulated weights method is not accurate for parameter estimation calculations. For mor...
entailment
def implementation_std(vals_std, vals_std_u, bs_std, bs_std_u, **kwargs): r"""Estimates varaition of results due to implementation-specific effects. See 'nestcheck: diagnostic tests for nested sampling calculations' (Higson et al. 2019) for more details. Uncertainties on the output are calculated numer...
r"""Estimates varaition of results due to implementation-specific effects. See 'nestcheck: diagnostic tests for nested sampling calculations' (Higson et al. 2019) for more details. Uncertainties on the output are calculated numerically using the fact that (from central limit theorem) our uncertainties ...
entailment
def run_thread_values(run, estimator_list): """Helper function for parallelising thread_values_df. Parameters ---------- ns_run: dict Nested sampling run dictionary. estimator_list: list of functions Returns ------- vals_array: numpy array Array of estimator values for ...
Helper function for parallelising thread_values_df. Parameters ---------- ns_run: dict Nested sampling run dictionary. estimator_list: list of functions Returns ------- vals_array: numpy array Array of estimator values for each thread. Has shape (len(estimator_list)...
entailment
def pairwise_distances(dist_list, earth_mover_dist=True, energy_dist=True): """Applies statistical_distances to each unique pair of distribution samples in dist_list. Parameters ---------- dist_list: list of 1d arrays earth_mover_dist: bool, optional Passed to statistical_distances. ...
Applies statistical_distances to each unique pair of distribution samples in dist_list. Parameters ---------- dist_list: list of 1d arrays earth_mover_dist: bool, optional Passed to statistical_distances. energy_dist: bool, optional Passed to statistical_distances. Returns ...
entailment
def statistical_distances(samples1, samples2, earth_mover_dist=True, energy_dist=True): """Compute measures of the statistical distance between samples. Parameters ---------- samples1: 1d array samples2: 1d array earth_mover_dist: bool, optional Whether or not ...
Compute measures of the statistical distance between samples. Parameters ---------- samples1: 1d array samples2: 1d array earth_mover_dist: bool, optional Whether or not to compute the Earth mover's distance between the samples. energy_dist: bool, optional Whether or not...
entailment
def get_dummy_thread(nsamples, **kwargs): """Generate dummy data for a single nested sampling thread. Log-likelihood values of points are generated from a uniform distribution in (0, 1), sorted, scaled by logl_range and shifted by logl_start (if it is not -np.inf). Theta values of each point are each g...
Generate dummy data for a single nested sampling thread. Log-likelihood values of points are generated from a uniform distribution in (0, 1), sorted, scaled by logl_range and shifted by logl_start (if it is not -np.inf). Theta values of each point are each generated from a uniform distribution in (0, 1...
entailment
def get_dummy_run(nthread, nsamples, **kwargs): """Generate dummy data for a nested sampling run. Log-likelihood values of points are generated from a uniform distribution in (0, 1), sorted, scaled by logl_range and shifted by logl_start (if it is not -np.inf). Theta values of each point are each gener...
Generate dummy data for a nested sampling run. Log-likelihood values of points are generated from a uniform distribution in (0, 1), sorted, scaled by logl_range and shifted by logl_start (if it is not -np.inf). Theta values of each point are each generated from a uniform distribution in (0, 1). Pa...
entailment
def get_dummy_dynamic_run(nsamples, **kwargs): """Generate dummy data for a dynamic nested sampling run. Loglikelihood values of points are generated from a uniform distribution in (0, 1), sorted, scaled by logl_range and shifted by logl_start (if it is not -np.inf). Theta values of each point are each...
Generate dummy data for a dynamic nested sampling run. Loglikelihood values of points are generated from a uniform distribution in (0, 1), sorted, scaled by logl_range and shifted by logl_start (if it is not -np.inf). Theta values of each point are each generated from a uniform distribution in (0, 1). ...
entailment
def get_long_description(): """Get PyPI long description from the .rst file.""" pkg_dir = get_package_dir() with open(os.path.join(pkg_dir, '.pypi_long_desc.rst')) as readme_file: long_description = readme_file.read() return long_description
Get PyPI long description from the .rst file.
entailment
def get_version(): """Get single-source __version__.""" pkg_dir = get_package_dir() with open(os.path.join(pkg_dir, 'nestcheck/_version.py')) as ver_file: string = ver_file.read() return string.strip().replace('__version__ = ', '').replace('\'', '')
Get single-source __version__.
entailment
def plot_run_nlive(method_names, run_dict, **kwargs): """Plot the allocations of live points as a function of logX for the input sets of nested sampling runs of the type used in the dynamic nested sampling paper (Higson et al. 2019). Plots also include analytically calculated distributions of relative ...
Plot the allocations of live points as a function of logX for the input sets of nested sampling runs of the type used in the dynamic nested sampling paper (Higson et al. 2019). Plots also include analytically calculated distributions of relative posterior mass and relative posterior mass remaining. ...
entailment
def kde_plot_df(df, xlims=None, **kwargs): """Plots kde estimates of distributions of samples in each cell of the input pandas DataFrame. There is one subplot for each dataframe column, and on each subplot there is one kde line. Parameters ---------- df: pandas data frame Each cell...
Plots kde estimates of distributions of samples in each cell of the input pandas DataFrame. There is one subplot for each dataframe column, and on each subplot there is one kde line. Parameters ---------- df: pandas data frame Each cell must contain a 1d numpy array of samples. xli...
entailment
def bs_param_dists(run_list, **kwargs): """Creates posterior distributions and their bootstrap error functions for input runs and estimators. For a more detailed description and some example use cases, see 'nestcheck: diagnostic tests for nested sampling calculations' (Higson et al. 2019). Paramet...
Creates posterior distributions and their bootstrap error functions for input runs and estimators. For a more detailed description and some example use cases, see 'nestcheck: diagnostic tests for nested sampling calculations' (Higson et al. 2019). Parameters ---------- run_list: dict or list o...
entailment
def param_logx_diagram(run_list, **kwargs): """Creates diagrams of a nested sampling run's evolution as it iterates towards higher likelihoods, expressed as a function of log X, where X(L) is the fraction of the prior volume with likelihood greater than some value L. For a more detailed description and...
Creates diagrams of a nested sampling run's evolution as it iterates towards higher likelihoods, expressed as a function of log X, where X(L) is the fraction of the prior volume with likelihood greater than some value L. For a more detailed description and some example use cases, see 'nestcheck: diagno...
entailment
def plot_bs_dists(run, fthetas, axes, **kwargs): """Helper function for plotting uncertainties on posterior distributions using bootstrap resamples and the fgivenx module. Used by bs_param_dists and param_logx_diagram. Parameters ---------- run: dict Nested sampling run to plot. fth...
Helper function for plotting uncertainties on posterior distributions using bootstrap resamples and the fgivenx module. Used by bs_param_dists and param_logx_diagram. Parameters ---------- run: dict Nested sampling run to plot. fthetas: list of functions Quantities to plot. Each...
entailment
def alternate_helper(x, alt_samps, func=None): """Helper function for making fgivenx plots of functions with 2 array arguments of variable lengths.""" alt_samps = alt_samps[~np.isnan(alt_samps)] arg1 = alt_samps[::2] arg2 = alt_samps[1::2] return func(x, arg1, arg2)
Helper function for making fgivenx plots of functions with 2 array arguments of variable lengths.
entailment
def weighted_1d_gaussian_kde(x, samples, weights): """Gaussian kde with weighted samples (1d only). Uses Scott bandwidth factor. When all the sample weights are equal, this is equivalent to kde = scipy.stats.gaussian_kde(theta) return kde(x) When the weights are not all equal, we compute the ...
Gaussian kde with weighted samples (1d only). Uses Scott bandwidth factor. When all the sample weights are equal, this is equivalent to kde = scipy.stats.gaussian_kde(theta) return kde(x) When the weights are not all equal, we compute the effective number of samples as the information content...
entailment
def rel_posterior_mass(logx, logl): """Calculate the relative posterior mass for some array of logx values given the likelihood, prior and number of dimensions. The posterior mass at each logX value is proportional to L(X)X, where L(X) is the likelihood. The weight is returned normalized so that the...
Calculate the relative posterior mass for some array of logx values given the likelihood, prior and number of dimensions. The posterior mass at each logX value is proportional to L(X)X, where L(X) is the likelihood. The weight is returned normalized so that the integral of the weight with respect to...
entailment
def average_by_key(dict_in, key): """Helper function for plot_run_nlive. Try returning the average of dict_in[key] and, if this does not work or if key is None, return average of whole dict. Parameters ---------- dict_in: dict Values should be arrays. key: str Returns ----...
Helper function for plot_run_nlive. Try returning the average of dict_in[key] and, if this does not work or if key is None, return average of whole dict. Parameters ---------- dict_in: dict Values should be arrays. key: str Returns ------- average: float
entailment
def batch_process_data(file_roots, **kwargs): """Process output from many nested sampling runs in parallel with optional error handling and caching. The result can be cached using the 'save_name', 'save' and 'load' kwargs (by default this is not done). See save_load_result docstring for more detail...
Process output from many nested sampling runs in parallel with optional error handling and caching. The result can be cached using the 'save_name', 'save' and 'load' kwargs (by default this is not done). See save_load_result docstring for more details. Remaining kwargs passed to parallel_utils.par...
entailment
def process_error_helper(root, base_dir, process_func, errors_to_handle=(), **func_kwargs): """Wrapper which applies process_func and handles some common errors so one bad run does not spoil the whole batch. Useful errors to handle include: OSError: if you are not sure if all ...
Wrapper which applies process_func and handles some common errors so one bad run does not spoil the whole batch. Useful errors to handle include: OSError: if you are not sure if all the files exist AssertionError: if some of the many assertions fail for known reasons; for example is there are occa...
entailment
def process_polychord_run(file_root, base_dir, process_stats_file=True, **kwargs): """Loads data from a PolyChord run into the nestcheck dictionary format for analysis. N.B. producing required output file containing information about the iso-likelihood contours within which po...
Loads data from a PolyChord run into the nestcheck dictionary format for analysis. N.B. producing required output file containing information about the iso-likelihood contours within which points were sampled (where they were "born") requies PolyChord version v1.13 or later and the setting write_de...
entailment
def process_multinest_run(file_root, base_dir, **kwargs): """Loads data from a MultiNest run into the nestcheck dictionary format for analysis. N.B. producing required output file containing information about the iso-likelihood contours within which points were sampled (where they were "born") requ...
Loads data from a MultiNest run into the nestcheck dictionary format for analysis. N.B. producing required output file containing information about the iso-likelihood contours within which points were sampled (where they were "born") requies MultiNest version 3.11 or later. Parameters --------...
entailment
def process_dynesty_run(results): """Transforms results from a dynesty run into the nestcheck dictionary format for analysis. This function has been tested with dynesty v9.2.0. Note that the nestcheck point weights and evidence will not be exactly the same as the dynesty ones as nestcheck calculates lo...
Transforms results from a dynesty run into the nestcheck dictionary format for analysis. This function has been tested with dynesty v9.2.0. Note that the nestcheck point weights and evidence will not be exactly the same as the dynesty ones as nestcheck calculates logX volumes more precisely (using the ...
entailment
def process_polychord_stats(file_root, base_dir): """Reads a PolyChord <root>.stats output file and returns the information contained in a dictionary. Parameters ---------- file_root: str Root for run output file names (PolyChord file_root setting). base_dir: str Directory conta...
Reads a PolyChord <root>.stats output file and returns the information contained in a dictionary. Parameters ---------- file_root: str Root for run output file names (PolyChord file_root setting). base_dir: str Directory containing data (PolyChord base_dir setting). Returns ...
entailment
def process_samples_array(samples, **kwargs): """Convert an array of nested sampling dead and live points of the type produced by PolyChord and MultiNest into a nestcheck nested sampling run dictionary. Parameters ---------- samples: 2d numpy array Array of dead points and any remaining...
Convert an array of nested sampling dead and live points of the type produced by PolyChord and MultiNest into a nestcheck nested sampling run dictionary. Parameters ---------- samples: 2d numpy array Array of dead points and any remaining live points at termination. Has #parameters ...
entailment
def birth_inds_given_contours(birth_logl_arr, logl_arr, **kwargs): """Maps the iso-likelihood contours on which points were born to the index of the dead point on this contour. MultiNest and PolyChord use different values to identify the inital live points which were sampled from the whole prior (PolyC...
Maps the iso-likelihood contours on which points were born to the index of the dead point on this contour. MultiNest and PolyChord use different values to identify the inital live points which were sampled from the whole prior (PolyChord uses -1e+30 and MultiNest -0.179769313486231571E+309). However in...
entailment
def sample_less_than_condition(choices_in, condition): """Creates a random sample from choices without replacement, subject to the condition that each element of the output is greater than the corresponding element of the condition array. condition should be in ascending order. """ output = np....
Creates a random sample from choices without replacement, subject to the condition that each element of the output is greater than the corresponding element of the condition array. condition should be in ascending order.
entailment
def threads_given_birth_inds(birth_inds): """Divides a nested sampling run into threads, using info on the indexes at which points were sampled. See "Sampling errors in nested sampling parameter estimation" (Higson et al. 2018) for more information. Parameters ---------- birth_inds: 1d numpy ar...
Divides a nested sampling run into threads, using info on the indexes at which points were sampled. See "Sampling errors in nested sampling parameter estimation" (Higson et al. 2018) for more information. Parameters ---------- birth_inds: 1d numpy array Indexes of the iso-likelihood contour...
entailment
def parallel_map(func, *arg_iterable, **kwargs): """Apply function to iterable with parallel map, and hence returns results in order. functools.partial is used to freeze func_pre_args and func_kwargs, meaning that the iterable argument must be the last positional argument. Roughly equivalent to ...
Apply function to iterable with parallel map, and hence returns results in order. functools.partial is used to freeze func_pre_args and func_kwargs, meaning that the iterable argument must be the last positional argument. Roughly equivalent to >>> [func(*func_pre_args, x, **func_kwargs) for x in a...
entailment
def parallel_apply(func, arg_iterable, **kwargs): """Apply function to iterable with parallelisation and a tqdm progress bar. Roughly equivalent to >>> [func(*func_pre_args, x, *func_args, **func_kwargs) for x in arg_iterable] but will **not** necessarily return results in input order. ...
Apply function to iterable with parallelisation and a tqdm progress bar. Roughly equivalent to >>> [func(*func_pre_args, x, *func_args, **func_kwargs) for x in arg_iterable] but will **not** necessarily return results in input order. Parameters ---------- func: function Func...
entailment
def select_tqdm(): """If running in a jupyter notebook, then returns tqdm_notebook. Otherwise returns a regular tqdm progress bar. Returns ------- progress: function """ try: progress = tqdm.tqdm_notebook assert get_ipython().has_trait('kernel') except (NameError, Assert...
If running in a jupyter notebook, then returns tqdm_notebook. Otherwise returns a regular tqdm progress bar. Returns ------- progress: function
entailment
def summary_df_from_array(results_array, names, axis=0, **kwargs): """Make a panda data frame of the mean and std devs of an array of results, including the uncertainties on the values. This function converts the array to a DataFrame and calls summary_df on it. Parameters ---------- results_ar...
Make a panda data frame of the mean and std devs of an array of results, including the uncertainties on the values. This function converts the array to a DataFrame and calls summary_df on it. Parameters ---------- results_array: 2d numpy array names: list of str Names for the output df...
entailment
def summary_df_from_list(results_list, names, **kwargs): """Make a panda data frame of the mean and std devs of each element of a list of 1d arrays, including the uncertainties on the values. This just converts the array to a DataFrame and calls summary_df on it. Parameters ---------- results_...
Make a panda data frame of the mean and std devs of each element of a list of 1d arrays, including the uncertainties on the values. This just converts the array to a DataFrame and calls summary_df on it. Parameters ---------- results_list: list of 1d numpy arrays Must have same length as n...
entailment
def summary_df_from_multi(multi_in, inds_to_keep=None, **kwargs): """Apply summary_df to a multiindex while preserving some levels. Parameters ---------- multi_in: multiindex pandas DataFrame inds_to_keep: None or list of strs, optional Index levels to preserve. kwargs: dict, optional ...
Apply summary_df to a multiindex while preserving some levels. Parameters ---------- multi_in: multiindex pandas DataFrame inds_to_keep: None or list of strs, optional Index levels to preserve. kwargs: dict, optional Keyword arguments to pass to summary_df. Returns ------- ...
entailment
def summary_df(df_in, **kwargs): """Make a panda data frame of the mean and std devs of an array of results, including the uncertainties on the values. This is similar to pandas.DataFrame.describe but also includes estimates of the numerical uncertainties. The output DataFrame has multiindex level...
Make a panda data frame of the mean and std devs of an array of results, including the uncertainties on the values. This is similar to pandas.DataFrame.describe but also includes estimates of the numerical uncertainties. The output DataFrame has multiindex levels: 'calculation type': mean and st...
entailment
def efficiency_gain_df(method_names, method_values, est_names, **kwargs): r"""Calculated data frame showing .. math:: \mathrm{efficiency\,gain} = \frac{\mathrm{Var[base\,method]}}{\mathrm{Var[new\,method]}} See the dynamic nested sampling paper (Higson et al. 2019) for more de...
r"""Calculated data frame showing .. math:: \mathrm{efficiency\,gain} = \frac{\mathrm{Var[base\,method]}}{\mathrm{Var[new\,method]}} See the dynamic nested sampling paper (Higson et al. 2019) for more details. The standard method on which to base the gain is assumed to be the...
entailment
def paper_format_efficiency_gain_df(eff_gain_df): """Transform efficiency gain data frames output by nestcheck into the format shown in the dynamic nested sampling paper (Higson et al. 2019). Parameters ---------- eff_gain_df: pandas DataFrame DataFrame of the from produced by efficiency_ga...
Transform efficiency gain data frames output by nestcheck into the format shown in the dynamic nested sampling paper (Higson et al. 2019). Parameters ---------- eff_gain_df: pandas DataFrame DataFrame of the from produced by efficiency_gain_df. Returns ------- paper_df: pandas Data...
entailment
def get_eff_gain(base_std, base_std_unc, meth_std, meth_std_unc, adjust=1): r"""Calculates efficiency gain for a new method compared to a base method. Given the variation in repeated calculations' results using the two methods, the efficiency gain is: .. math:: \mathrm{efficiency\,gain} ...
r"""Calculates efficiency gain for a new method compared to a base method. Given the variation in repeated calculations' results using the two methods, the efficiency gain is: .. math:: \mathrm{efficiency\,gain} = \frac{\mathrm{Var[base\,method]}}{\mathrm{Var[new\,method]}} Th...
entailment
def rmse_and_unc(values_array, true_values): r"""Calculate the root meet squared error and its numerical uncertainty. With a reasonably large number of values in values_list the uncertainty on sq_errors should be approximately normal (from the central limit theorem). Uncertainties are calculated vi...
r"""Calculate the root meet squared error and its numerical uncertainty. With a reasonably large number of values in values_list the uncertainty on sq_errors should be approximately normal (from the central limit theorem). Uncertainties are calculated via error propagation: if :math:`\sigma` is the...
entailment
def array_ratio_std(values_n, sigmas_n, values_d, sigmas_d): r"""Gives error on the ratio of 2 floats or 2 1-dimensional arrays given their values and uncertainties. This assumes the covariance = 0, and that the input uncertainties are small compared to the corresponding input values. _n and _d denote t...
r"""Gives error on the ratio of 2 floats or 2 1-dimensional arrays given their values and uncertainties. This assumes the covariance = 0, and that the input uncertainties are small compared to the corresponding input values. _n and _d denote the numerator and denominator respectively. Parameters --...
entailment
def run_estimators(ns_run, estimator_list, simulate=False): """Calculates values of list of quantities (such as the Bayesian evidence or mean of parameters) for a single nested sampling run. Parameters ---------- ns_run: dict Nested sampling run dict (see data_processing module docstring fo...
Calculates values of list of quantities (such as the Bayesian evidence or mean of parameters) for a single nested sampling run. Parameters ---------- ns_run: dict Nested sampling run dict (see data_processing module docstring for more details). estimator_list: list of functions for ...
entailment
def array_given_run(ns_run): """Converts information on samples in a nested sampling run dictionary into a numpy array representation. This allows fast addition of more samples and recalculation of nlive. Parameters ---------- ns_run: dict Nested sampling run dict (see data_processing m...
Converts information on samples in a nested sampling run dictionary into a numpy array representation. This allows fast addition of more samples and recalculation of nlive. Parameters ---------- ns_run: dict Nested sampling run dict (see data_processing module docstring for more det...
entailment
def dict_given_run_array(samples, thread_min_max): """ Converts an array of information about samples back into a nested sampling run dictionary (see data_processing module docstring for more details). N.B. the output dict only contains the following keys: 'logl', 'thread_label', 'nlive_array', 'th...
Converts an array of information about samples back into a nested sampling run dictionary (see data_processing module docstring for more details). N.B. the output dict only contains the following keys: 'logl', 'thread_label', 'nlive_array', 'theta'. Any other keys giving additional information about th...
entailment
def get_run_threads(ns_run): """ Get the individual threads from a nested sampling run. Parameters ---------- ns_run: dict Nested sampling run dict (see data_processing module docstring for more details). Returns ------- threads: list of numpy array Each thread ...
Get the individual threads from a nested sampling run. Parameters ---------- ns_run: dict Nested sampling run dict (see data_processing module docstring for more details). Returns ------- threads: list of numpy array Each thread (list element) is a samples array contain...
entailment
def combine_ns_runs(run_list_in, **kwargs): """ Combine a list of complete nested sampling run dictionaries into a single ns run. Input runs must contain any repeated threads. Parameters ---------- run_list_in: list of dicts List of nested sampling runs in dict format (see data_pro...
Combine a list of complete nested sampling run dictionaries into a single ns run. Input runs must contain any repeated threads. Parameters ---------- run_list_in: list of dicts List of nested sampling runs in dict format (see data_processing module docstring for more details). ...
entailment
def combine_threads(threads, assert_birth_point=False): """ Combine list of threads into a single ns run. This is different to combining runs as repeated threads are allowed, and as some threads can start from log-likelihood contours on which no dead point in the run is present. Note that if al...
Combine list of threads into a single ns run. This is different to combining runs as repeated threads are allowed, and as some threads can start from log-likelihood contours on which no dead point in the run is present. Note that if all the thread labels are not unique and in ascending order, the o...
entailment