output
stringlengths
1
928k
instruction
stringlengths
7
928k
system
stringlengths
0
104k
This function verifies the token using the secret key and returns its contents.
Explain what the following Python 3 code does def read_session_token(secret_key, token): return jwt.decode(token.encode('utf-8'), secret_key, algorithms=[token_encryption_algorithm()] )
You are a Python code generator, capable of creating scripts from specifications.
This method is used to announce the existence of the service.
Given the following Python 3 function, write the documentation async def announce(self): # send a serialized event await self.event_broker.send( action_type=intialize_service_action(), payload=json.dumps(self.summarize()) )
You are a Python code generator, capable of creating scripts from specifications.
This method adds an http endpoint to the router.
Make a summary of the following Python 3 code def add_http_endpoint(self, url, request_handler): self.app.router.add_route('*', url, request_handler)
You are a Python code analyst, evaluating scripts for potential improvements.
This method provides a decorator for adding endpoints to the specified route.
Can you tell what is the following Python 3 function doing def route(cls, route, config=None): def decorator(wrapped_class, **kwds): # add the endpoint at the given route cls._routes.append( dict(url=route, request_handler=wrapped_class) ) # retur...
You are a Python code architect, reviewing and designing scalable and efficient code
This function generates a session token signed by the secret key which can be used to extract the user credentials in a verifiable way.
Explain what the following Python 3 code does def generate_session_token(secret_key, **payload): return jwt.encode(payload, secret_key, algorithm=token_encryption_algorithm()).decode('utf-8')
As a python code expert, you are capable of creating scripts from specifications.
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))
Implement a Python 3 function for creating a PasswordHash from the given password.
You are a Python code generator, capable of creating scripts from specifications.
Ensure that loaded values are PasswordHashes.
Can you tell what is the following Python 3 function doing def coerce(cls, key, value): if isinstance(value, PasswordHash): return value return super(PasswordHash, cls).coerce(key, value)
As a python code expert, you are capable of creating scripts from specifications.
def rehash(self, password): """Recreates the internal hash.""" self.hash = self._new(password, self.desired_rounds) self.rounds = self.desired_rounds
Implement a function in Python 3 to recreate the internal hash.
As a Python code analyst, you investigate and solve complex coding mysteries
This function handles the registration of the given user credentials in the database and returns a dictionary with the user and sessionToken.
Explain what the following Python 3 code does async def login_user(self, password, **kwds): # find the matching user with the given email user_data = (await self._get_matching_user(fields=list(kwds.keys()), **kwds))['data'] try: # look for a matching entry in the local database ...
As a Python code composer, you craft elegant and concise scripts.
This function creates a user and stores it in the database and returns a dictionary with the user created and a sessionToken for later requests.
Explain what the following Python 3 code does async def register_user(self, password, **kwds): # so make one user = await self._create_remote_user(password=password, **kwds) # if there is no pk field if not 'pk' in user: # make sure the user has a pk field user['p...
As a Python code composer, you craft elegant and concise scripts.
This function resolves a given object in the remote backend services.
Here you have a function in Python 3, explain what it does async def object_resolver(self, object_name, fields, obey_auth=False, current_user=None, **filters): try: # check if an object with that name has been registered registered = [model for model in self._external_service_data['mode...
You are a Python code architect, reviewing and designing scalable and efficient code
This method is used to resolve the event type of a specific mutation and return the fields contained in the result.
Can you tell what is the following Python 3 function doing async def mutation_resolver(self, mutation_name, args, fields): try: # make sure we can identify the mutation mutation_summary = [mutation for mutation in \ self._external_service_data...
As a Python code translator, you convert algorithms and pseudocode into Python.
Calculates the WER with Levenshtein distance.
Can you generate a brief explanation for the following Python 3 code def calculate_wer(reference, hypothesis): # initialisation import numpy d = numpy.zeros((len(reference)+1)*(len(hypothesis)+1), dtype=numpy.uint8) d = d.reshape((len(reference)+1, len(hypothesis)+1)) for i in range(len(reference)+1...
You are a Python code generator, capable of creating scripts from specifications.
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...
Write a Python 3 script to get a parser object
As a Python code translator, you convert algorithms and pseudocode into Python.
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() ...
How would you code a function in Python 3 to perform a GET web request and return a bs4 parser
As a Python code translator, you convert algorithms and pseudocode into Python.
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...
Can you implement a function in Python 3 that determines the current channel using fuzzywuzzy.
You are a Python code generator, capable of creating scripts from specifications.
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...
Implement a function in Python 3 to get the list of channels and corresponding urls.
As a Python code translator, you convert algorithms and pseudocode into Python.
Resize a program s thumbnail to the desired dimension.
Can you generate a brief explanation for the following Python 3 code 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 r...
You are a Python code generator, capable of creating scripts from specifications.
Get the current progress of the program in %
How would you explain what the following Python 3 function does 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 = no...
As a Python code translator, you convert algorithms and pseudocode into Python.
Get a program s duration in seconds.
Can you tell what is the following Python 3 function doing 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 dete...
As a python code expert, you are capable of creating scripts from specifications.
Get the remaining time in seconds of a program.
Explain what the following Python 3 code does 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 no...
You are a Python code analyst, evaluating scripts for potential improvements.
Extract the summary data from a program s detail page
Can you generate a brief explanation for the following Python 3 code 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'...
You are a Python code analyst, evaluating scripts for potential improvements.
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...
Write a Python 3 script to set a program s summary
As a python code expert, you are capable of creating scripts from specifications.
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...
Can you implement a function in Python 3 that gets the program data for a channel.
You are a Python code architect, reviewing and designing scalable and efficient code
Get the current TV program info for a channel.
Can you generate a brief explanation for the following Python 3 code 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: _LOGGE...
As a Python code analyst, you investigate and solve complex coding mysteries
Get or create publish
How would you explain what the following Python 3 function does def publish(self, distribution, storage=""): try: return self._publishes[distribution] except KeyError: self._publishes[distribution] = Publish(self.client, distribution, timestamp=self.timestamp, storage=(storage or...
You are a Python code analyst, evaluating scripts for potential improvements.
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)
How would you implement a function in Python 3 that adds a new snapshot to the publish list
As a Python code translator, you convert algorithms and pseudocode into Python.
Check if publish name matches list of names or regex patterns
Here you have a function in Python 3, explain what it does def _publish_match(self, publish, names=False, name_only=False): if names: for name in names: if not name_only and isinstance(name, re._pattern_type): if re.match(name, publish.name): ...
As a Python code composer, you craft elegant and concise scripts.
Get the information about the repository and publish.
Can you tell what is the following Python 3 function doing def get_repo_information(config, client, fill_repo=False, components=[]): repo_dict = {} publish_dict = {} for origin in ['repo', 'mirror']: for name, repo in config.get(origin, {}).items(): if components and...
As a Python code composer, you craft elegant and concise scripts.
Compare two publish sets and return a tuple of dictionaries containing the difference of the publish sets and the other publish sets.
Make a summary of the following Python 3 code def compare(self, other, components=[]): lg.debug("Comparing publish %s (%s) and %s (%s)" % (self.name, self.storage or "local", other.name, other.storage or "local")) diff, equal = ({}, {}) for component, snapshots in self.components.items(): ...
You are a Python code architect, reviewing and designing scalable and efficient code
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...
Can you create a Python 3 function that finds this publish on remote node
You are a Python code architect, reviewing and designing scalable and efficient code
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...
Create a Python 3 function for serializing publish in YAML
You are a Python code architect, reviewing and designing scalable and efficient code
Restore publish from config file
Here you have a function in Python 3, explain what it does def restore_publish(self, config, components, recreate=False): if "all" in components: components = [] try: self.load() publish = True except NoSuchPublish: publish = False new_pu...
You are a Python code generator, capable of creating scripts from specifications.
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...
Can you write a function in Python 3 where it loads publish info from remote
As a Python code translator, you convert algorithms and pseudocode into Python.
Get packages for given components and packages.
Here you have a function in Python 3, explain what it does def get_packages(self, component=None, components=[], packages=None): if component: components = [component] package_refs = [] for snapshot in self.publish_snapshots: if component and snapshot['Component'] not in...
You are a Python code generator, capable of creating scripts from specifications.
Parse a package reference string into a tuple of architecture package_name version and id.
Can you generate a brief explanation for the following Python 3 code def parse_package_ref(self, ref): if not ref: return None parsed = re.match('(.*)\ (.*)\ (.*)\ (.*)', ref) return parsed.groups()
As a Python code analyst, you investigate and solve complex coding mysteries
def add(self, snapshot, component='main'): """ Add snapshot of component to publish """ try: self.components[component].append(snapshot) except KeyError: self.components[component] = [snapshot]
Create a Python 3 function for adding a snapshot of a component to publish
You are a Python code architect, reviewing and designing scalable and efficient code
Find a snapshot on remote by name or regular expression
How would you explain what the following Python 3 function does def _find_snapshot(self, name): remote_snapshots = self._get_snapshots(self.client) for remote in reversed(remote_snapshots): if remote["Name"] == name or \ re.match(name, remote["Name"]): ret...
As a Python code translator, you convert algorithms and pseudocode into Python.
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...
Create a Python 3 function for getting list of source snapshot names of given snapshot
You are a Python code generator, capable of creating scripts from specifications.
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 ...
How would you code a function in Python 3 to create component snapshots by merging other snapshots of same component
You are a Python code analyst, evaluating scripts for potential improvements.
A decorator that prints the time func takes to execute.
Given the following Python 3 function, write the documentation def timing_decorator(func): @functools.wraps(func) def wrapper(*args, **kwargs): """ Wrapper for printing execution time. Parameters ---------- print_time: bool, optional whether or not to print t...
As a Python code composer, you craft elegant and concise scripts.
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,...
How would you code a function in Python 3 to save and/or loads func output (must be picklable).
You are a Python code generator, capable of creating scripts from specifications.
Saves object with pickle.
How would you explain what the following Python 3 function does def pickle_save(data, name, **kwargs): extension = kwargs.pop('extension', '.pkl') overwrite_existing = kwargs.pop('overwrite_existing', True) if kwargs: raise TypeError('Unexpected **kwargs: {0}'.format(kwargs)) filename = name + e...
You are a Python code generator, capable of creating scripts from specifications.
Load data with pickle.
Make a summary of the following Python 3 code def pickle_load(name, extension='.pkl'): filename = name + extension infile = open(filename, 'rb') data = pickle.load(infile) infile.close() return data
You are a Python code analyst, evaluating scripts for potential improvements.
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...
Can you implement a function in Python 3 that bootstraps resamples threads of nested sampling run returning a new nested sampling run.
You are a Python code architect, reviewing and designing scalable and efficient code
Uses bootstrap resampling to calculate an estimate of the the standard deviation of the distribution of sampling errors on the calculation result for each estimator in estimator_list.
Make a summary of the following Python 3 code def run_std_bootstrap(ns_run, estimator_list, **kwargs): bs_values = run_bootstrap_values(ns_run, estimator_list, **kwargs) stds = np.zeros(bs_values.shape[0]) for j, _ in enumerate(stds): stds[j] = np.std(bs_values[j, :], ddof=1) return stds
You are a Python code architect, reviewing and designing scalable and efficient code
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...
Create a Python 3 function to use bootstrap resampling to calculate an estimate of the standard deviation of the distribution of sampling errors on the calculation result for each estimator in estimator_list.
As a python code expert, you are capable of creating scripts from specifications.
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...
Write a Python 3 function that can use bootstrap resampling to calculate credible intervals on the sampling errors on the calculation result for each nested sampling run.
As a Python code analyst, you investigate and solve complex coding mysteries
Uses the simulated weights method to calculate an estimate of the standard deviation of the distribution of sampling errors the uncertainty on the calculation.
Can you generate a brief explanation for the following Python 3 code def run_std_simulate(ns_run, estimator_list, n_simulate=None): assert n_simulate is not None, 'run_std_simulate: must specify n_simulate' all_values = np.zeros((len(estimator_list), n_simulate)) for i in range(n_simulate): all_valu...
You are a Python code architect, reviewing and designing scalable and efficient code
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. ...
Create a Python 3 function to apply statistical_distances to each unique pair of distribution samples in dist_list.
As a python code expert, you are capable of creating scripts from specifications.
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 ...
Write a Python 3 script for computing the statistical distances between two samples.
As a Python code composer, you craft elegant and concise scripts.
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...
Write a Python 3 script for generating dummy data for a single nested sampling thread.
As a Python code composer, you craft elegant and concise scripts.
Generate dummy data for a nested sampling run.
How would you explain what the following Python 3 function does def get_dummy_run(nthread, nsamples, **kwargs): seed = kwargs.pop('seed', False) ndim = kwargs.pop('ndim', 2) logl_start = kwargs.pop('logl_start', -np.inf) logl_range = kwargs.pop('logl_range', 1) if kwargs: raise TypeError('Un...
As a Python code analyst, you investigate and solve complex coding mysteries
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...
Implement a Python 3 function for generating dummy data for a dynamic nested sampling run.
As a Python code analyst, you investigate and solve complex coding mysteries
Get PyPI long description from the. rst file.
Make a summary of the following Python 3 code def get_long_description(): 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
As a Python code translator, you convert algorithms and pseudocode into Python.
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('\'', '')
Write a Python 3 function for getting single - source __version__.
You are a Python code analyst, evaluating scripts for potential improvements.
Plot the allocations of live points as a function of logX for the nested sampling sets of the given method.
Can you generate the documentation for the following Python 3 function def plot_run_nlive(method_names, run_dict, **kwargs): logx_given_logl = kwargs.pop('logx_given_logl', None) logl_given_logx = kwargs.pop('logl_given_logx', None) logx_min = kwargs.pop('logx_min', None) ymax = kwargs.pop('ymax', None)...
You are a Python code generator, capable of creating scripts from specifications.
Plots kde estimates of distributions of samples in each cell of the dataframe df.
Can you tell what is the following Python 3 function doing def kde_plot_df(df, xlims=None, **kwargs): assert xlims is None or isinstance(xlims, dict) figsize = kwargs.pop('figsize', (6.4, 1.5)) num_xticks = kwargs.pop('num_xticks', None) nrows = kwargs.pop('nrows', 1) ncols = kwargs.pop('ncols', int...
You are a Python code generator, capable of creating scripts from specifications.
Creates posterior distributions and their bootstrap error functions for nested sampling run lists and estimators.
Can you generate the documentation for the following Python 3 function def bs_param_dists(run_list, **kwargs): fthetas = kwargs.pop('fthetas', [lambda theta: theta[:, 0], lambda theta: theta[:, 1]]) labels = kwargs.pop('labels', [r'$\theta_' + str(i + 1) + '$' for i in ...
You are a Python code analyst, evaluating scripts for potential improvements.
Creates a diagram of nested sampling run s evolution towards higher likelihoods.
Explain what the following Python 3 code does def param_logx_diagram(run_list, **kwargs): fthetas = kwargs.pop('fthetas', [lambda theta: theta[:, 0], lambda theta: theta[:, 1]]) labels = kwargs.pop('labels', [r'$\theta_' + str(i + 1) + '$' for i in ...
As a python code expert, you are capable of creating scripts from specifications.
Helper function for plotting bootstrap resamples and fgivenx distributions on posterior distributions using bootstrap resamples and fgivenx module.
Explain what the following Python 3 code does def plot_bs_dists(run, fthetas, axes, **kwargs): ftheta_lims = kwargs.pop('ftheta_lims', [[-1, 1]] * len(fthetas)) n_simulate = kwargs.pop('n_simulate', 100) colormap = kwargs.pop('colormap', plt.get_cmap('Reds_r')) mean_color = kwargs.pop('mean_color', None...
As a Python code translator, you convert algorithms and pseudocode into Python.
Helper function for making fgivenx plots of functions with 2 array arguments of variable lengths.
Can you tell what is the following Python 3 function doing def alternate_helper(x, alt_samps, func=None): alt_samps = alt_samps[~np.isnan(alt_samps)] arg1 = alt_samps[::2] arg2 = alt_samps[1::2] return func(x, arg1, arg2)
You are a Python code architect, reviewing and designing scalable and efficient code
Gaussian kde with weighted samples
Make a summary of the following Python 3 code def weighted_1d_gaussian_kde(x, samples, weights): assert x.ndim == 1 assert samples.ndim == 1 assert samples.shape == weights.shape # normalise weights and find effective number of samples weights /= np.sum(weights) nz_weights = weights[np.nonzero(w...
You are a Python code generator, capable of creating scripts from specifications.
Calculate the relative posterior mass at each array of logx values at each logl value.
How would you explain what the following Python 3 function does def rel_posterior_mass(logx, logl): logw = logx + logl w_rel = np.exp(logw - logw.max()) w_rel /= np.abs(np.trapz(w_rel, x=logx)) return w_rel
As a Python code translator, you convert algorithms and pseudocode into Python.
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...
Implement a Python 3 function for processing output from many nested sampling runs in parallel with optional error handling and caching.
As a Python code analyst, you investigate and solve complex coding mysteries
Wrapper which applies process_func and handles common errors and returns a nested sampling run dict.
Here you have a function in Python 3, explain what it does 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 t...
As a Python code analyst, you investigate and solve complex coding mysteries
Loads data from a MultiNest run into the nestcheck dictionary format for the nested sampling run.
Can you generate the documentation for the following Python 3 function def process_multinest_run(file_root, base_dir, **kwargs): # Load dead and live points dead = np.loadtxt(os.path.join(base_dir, file_root) + '-dead-birth.txt') live = np.loadtxt(os.path.join(base_dir, file_root) + '-...
You are a Python code analyst, evaluating scripts for potential improvements.
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...
Can you create a Python 3 function that transforms results from a dynesty run into a nestcheck dictionary.
As a python code expert, you are capable of creating scripts from specifications.
Reads a PolyChord <root. stats output file and returns the information contained in a dictionary.
Here you have a function in Python 3, explain what it does def process_polychord_stats(file_root, base_dir): filename = os.path.join(base_dir, file_root) + '.stats' output = {'base_dir': base_dir, 'file_root': file_root} with open(filename, 'r') as stats_file: lines = stats_file.readli...
You are a Python code analyst, evaluating scripts for potential improvements.
Convert an array of nested sampling dead points and any remaining live points at termination into a nestcheck nested sampling run dictionary.
Given the following Python 3 function, write the documentation def process_samples_array(samples, **kwargs): samples = samples[np.argsort(samples[:, -2])] ns_run = {} ns_run['logl'] = samples[:, -2] ns_run['theta'] = samples[:, :-2] birth_contours = samples[:, -1] # birth_contours, ns_run['theta...
As a Python code translator, you convert algorithms and pseudocode into Python.
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...
Write a Python 3 function for mapping iso - likelihood contours on which points were born to the index of the first occurrence of the dead point on the contour.
As a Python code translator, you convert algorithms and pseudocode into Python.
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....
How would you implement a function in Python 3 that 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.
As a python code expert, you are capable of creating scripts from specifications.
Divides a nested sampling run into threads given a list of birth indices.
Explain what the following Python 3 code does def threads_given_birth_inds(birth_inds): unique, counts = np.unique(birth_inds, return_counts=True) # First get a list of all the indexes on which threads start and their # counts. This is every point initially sampled from the prior, plus any # indexes whe...
You are a Python code analyst, evaluating scripts for potential improvements.
Apply function to iterable with parallel map and return list of function outputs.
Explain what the following Python 3 code does def parallel_map(func, *arg_iterable, **kwargs): chunksize = kwargs.pop('chunksize', 1) func_pre_args = kwargs.pop('func_pre_args', ()) func_kwargs = kwargs.pop('func_kwargs', {}) max_workers = kwargs.pop('max_workers', None) parallel = kwargs.pop('paral...
As a Python code translator, you convert algorithms and pseudocode into Python.
Apply function to iterable with parallelisation and a tqdm progress bar.
Given the following Python 3 function, write the documentation def parallel_apply(func, arg_iterable, **kwargs): max_workers = kwargs.pop('max_workers', None) parallel = kwargs.pop('parallel', True) parallel_warning = kwargs.pop('parallel_warning', True) func_args = kwargs.pop('func_args', ()) func_...
As a Python code composer, you craft elegant and concise scripts.
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...
Write a Python 3 script to return a tqdm progress bar.
You are a Python code analyst, evaluating scripts for potential improvements.
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...
How would you code a function in Python 3 to 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 th...
You are a Python code architect, reviewing and designing scalable and efficient code
This function converts a list of 1d numpy arrays to a DataFrame and calls summary_df on it.
Explain what the following Python 3 code does def summary_df_from_list(results_list, names, **kwargs): for arr in results_list: assert arr.shape == (len(names),) df = pd.DataFrame(np.stack(results_list, axis=0)) df.columns = names return summary_df(df, **kwargs)
As a Python code composer, you craft elegant and concise scripts.
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 ...
Write a Python 3 script for applying summary_df to a multiindex while preserving some levels.
As a python code expert, you are capable of creating scripts from specifications.
Make a multiindex DataFrame that contains the mean and standard deviations of each column.
How would you explain what the following Python 3 function does def summary_df(df_in, **kwargs): true_values = kwargs.pop('true_values', None) include_true_values = kwargs.pop('include_true_values', False) include_rmse = kwargs.pop('include_rmse', False) if kwargs: raise TypeError('Unexpected **...
You are a Python code analyst, evaluating scripts for potential improvements.
r Calculates the efficiency gain of a given set of methods.
Can you generate the documentation for the following Python 3 function def efficiency_gain_df(method_names, method_values, est_names, **kwargs): true_values = kwargs.pop('true_values', None) include_true_values = kwargs.pop('include_true_values', False) include_rmse = kwargs.pop('include_rmse', False) a...
As a Python code composer, you craft elegant and concise scripts.
Transform the efficiency gain data frames output by nestcheck into the order they appear in the order they appear.
Here you have a function in Python 3, explain what it does def paper_format_efficiency_gain_df(eff_gain_df): idxs = pd.IndexSlice[['std', 'std efficiency gain'], :, :] paper_df = copy.deepcopy(eff_gain_df.loc[idxs, :]) # Show mean number of samples and likelihood calls instead of st dev means = (eff_gai...
As a python code expert, you are capable of creating scripts from specifications.
r Calculates the effective gain for a new method compared to a base method.
Here you have a function in Python 3, explain what it does def get_eff_gain(base_std, base_std_unc, meth_std, meth_std_unc, adjust=1): ratio = base_std / meth_std ratio_unc = array_ratio_std( base_std, base_std_unc, meth_std, meth_std_unc) gain = ratio ** 2 gain_unc = 2 * ratio * ratio_unc g...
As a Python code analyst, you investigate and solve complex coding mysteries
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...
Write a Python 3 function that can calculate the values of list of quantities for each estimator in estimator_list.
As a python code expert, you are capable of creating scripts from specifications.
Converts information on samples in a nested sampling run dictionary into a numpy array representation. This allows fast addition of more samples and nlive recalculation of nlive at sample.
Can you tell what is the following Python 3 function doing def array_given_run(ns_run): samples = np.zeros((ns_run['logl'].shape[0], 3 + ns_run['theta'].shape[1])) samples[:, 0] = ns_run['logl'] samples[:, 1] = ns_run['thread_labels'] # Calculate 'change in nlive' after each step samples[:-1, 2] = n...
You are a Python code architect, reviewing and designing scalable and efficient code
Converts an array of information about samples back into a nested sampling run dictionary.
How would you explain what the following Python 3 function does def dict_given_run_array(samples, thread_min_max): ns_run = {'logl': samples[:, 0], 'thread_labels': samples[:, 1], 'thread_min_max': thread_min_max, 'theta': samples[:, 3:]} if np.all(~np.isnan(ns_run['thr...
As a Python code composer, you craft elegant and concise scripts.
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 ...
Can you write a function in Python 3 where it gets the individual threads from a nested sampling run.
You are a Python code analyst, evaluating scripts for potential improvements.
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...
How would you code a function in Python 3 to combine a list of complete nested sampling run dictionaries into a single nested sampling run.
You are a Python code analyst, evaluating scripts for potential improvements.
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...
Write a Python 3 script to combine a list of threads into a single ns run.
You are a Python code architect, reviewing and designing scalable and efficient code
r Calculates the log posterior weights of the samples in the nested sampling run dictionary.
Can you tell what is the following Python 3 function doing def get_logw(ns_run, simulate=False): try: # find logX value for each point logx = get_logx(ns_run['nlive_array'], simulate=simulate) logw = np.zeros(ns_run['logl'].shape[0]) # Vectorized trapezium rule: w_i prop to (X_{i-1} ...
You are a Python code analyst, evaluating scripts for potential improvements.
def get_w_rel(ns_run, simulate=False): """Get the relative posterior weights of the samples, normalised so the maximum sample weight is 1. This is calculated from get_logw with protection against numerical overflows. Parameters ---------- ns_run: dict Nested sampling run dict (see data_...
How would you code a function in Python 3 to get the relative posterior weights of the samples normalised so the maximum sample weight is 1. This is calculated from get_logw with the simulate parameter.
As a Python code analyst, you investigate and solve complex coding mysteries
def check_ns_run(run, dup_assert=False, dup_warn=False): """Checks a nestcheck format nested sampling run dictionary has the expected properties (see the data_processing module docstring for more details). Parameters ---------- run: dict nested sampling run to check. dup_assert: boo...
Write a Python 3 function for checking that nested sampling run dictionary has the expected properties.
As a Python code analyst, you investigate and solve complex coding mysteries
Checks that nested sampling run member keys and values are consistent with the expected properties.
Can you generate the documentation for the following Python 3 function def check_ns_run_members(run): run_keys = list(run.keys()) # Mandatory keys for key in ['logl', 'nlive_array', 'theta', 'thread_labels', 'thread_min_max']: assert key in run_keys run_keys.remove(key) #...
As a python code expert, you are capable of creating scripts from specifications.
Checks that the logls in the nested sampling run are unique and in the correct order.
How would you explain what the following Python 3 function does def check_ns_run_logls(run, dup_assert=False, dup_warn=False): assert np.array_equal(run['logl'], run['logl'][np.argsort(run['logl'])]) if dup_assert or dup_warn: unique_logls, counts = np.unique(run['logl'], return_counts=True) rep...
As a Python code analyst, you investigate and solve complex coding mysteries
Checks that the nested sampling run has expected properties.
Can you generate the documentation for the following Python 3 function def check_ns_run_threads(run): assert run['thread_labels'].dtype == int uniq_th = np.unique(run['thread_labels']) assert np.array_equal( np.asarray(range(run['thread_min_max'].shape[0])), uniq_th), \ str(uniq_th) # Ch...
As a Python code analyst, you investigate and solve complex coding mysteries
def count_samples(ns_run, **kwargs): r"""Number of samples in run. Unlike most estimators this does not require log weights, but for convenience will not throw an error if they are specified. Parameters ---------- ns_run: dict Nested sampling run dict (see the data_processing module ...
Write a Python 3 script to count the number of samples in a nested sampling run.
You are a Python code analyst, evaluating scripts for potential improvements.
Natural log of Bayesian evidence.
How would you explain what the following Python 3 function does def logz(ns_run, logw=None, simulate=False): if logw is None: logw = nestcheck.ns_run_utils.get_logw(ns_run, simulate=simulate) return scipy.special.logsumexp(logw)
You are a Python code architect, reviewing and designing scalable and efficient code
def param_mean(ns_run, logw=None, simulate=False, param_ind=0, handle_indexerror=False): """Mean of a single parameter (single component of theta). Parameters ---------- ns_run: dict Nested sampling run dict (see the data_processing module docstring for more details). ...
Write a Python 3 function that can calculate the mean of a single parameter for a nested sampling run.
As a Python code composer, you craft elegant and concise scripts.
def param_squared_mean(ns_run, logw=None, simulate=False, param_ind=0): """Mean of the square of single parameter (second moment of its posterior distribution). Parameters ---------- ns_run: dict Nested sampling run dict (see the data_processing module docstring for more details). ...
Can you write a function in Python 3 where it means of the square of single parameter of its posterior distribution.
As a python code expert, you are capable of creating scripts from specifications.
Mean of the radial coordinate.
Here you have a function in Python 3, explain what it does def r_mean(ns_run, logw=None, simulate=False): if logw is None: logw = nestcheck.ns_run_utils.get_logw(ns_run, simulate=simulate) w_relative = np.exp(logw - logw.max()) r = np.sqrt(np.sum(ns_run['theta'] ** 2, axis=1)) return np.sum(w_re...
As a Python code translator, you convert algorithms and pseudocode into Python.