signature stringlengths 8 3.44k | body stringlengths 0 1.41M | docstring stringlengths 1 122k | id stringlengths 5 17 |
|---|---|---|---|
def summary_df(df_in, **kwargs): | true_values = kwargs.pop('<STR_LIT>', None)<EOL>include_true_values = kwargs.pop('<STR_LIT>', False)<EOL>include_rmse = kwargs.pop('<STR_LIT>', False)<EOL>if kwargs:<EOL><INDENT>raise TypeError('<STR_LIT>'.format(kwargs))<EOL><DEDENT>if true_values is not None:<EOL><INDENT>assert true_values.shape[<NUM_LIT:0>] == df_in... | 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... | f15346:m3 |
def efficiency_gain_df(method_names, method_values, est_names, **kwargs): | true_values = kwargs.pop('<STR_LIT>', None)<EOL>include_true_values = kwargs.pop('<STR_LIT>', False)<EOL>include_rmse = kwargs.pop('<STR_LIT>', False)<EOL>adjust_nsamp = kwargs.pop('<STR_LIT>', None)<EOL>if kwargs:<EOL><INDENT>raise TypeError('<STR_LIT>'.format(kwargs))<EOL><DEDENT>if adjust_nsamp is not None:<EOL><IND... | 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... | f15346:m4 |
def paper_format_efficiency_gain_df(eff_gain_df): | idxs = pd.IndexSlice[['<STR_LIT>', '<STR_LIT>'], :, :]<EOL>paper_df = copy.deepcopy(eff_gain_df.loc[idxs, :])<EOL>means = (eff_gain_df.xs('<STR_LIT>', level='<STR_LIT>')<EOL>.xs('<STR_LIT:value>', level='<STR_LIT>'))<EOL>for col in ['<STR_LIT>', '<STR_LIT>']:<EOL><INDENT>try:<EOL><INDENT>col_vals = []<EOL>for val in me... | 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... | f15346:m5 |
def get_eff_gain(base_std, base_std_unc, meth_std, meth_std_unc, adjust=<NUM_LIT:1>): | ratio = base_std / meth_std<EOL>ratio_unc = array_ratio_std(<EOL>base_std, base_std_unc, meth_std, meth_std_unc)<EOL>gain = ratio ** <NUM_LIT:2><EOL>gain_unc = <NUM_LIT:2> * ratio * ratio_unc<EOL>gain *= adjust<EOL>gain_unc *= adjust<EOL>return gain, gain_unc<EOL> | 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... | f15346:m6 |
def rmse_and_unc(values_array, true_values): | assert true_values.shape == (values_array.shape[<NUM_LIT:1>],)<EOL>errors = values_array - true_values[np.newaxis, :]<EOL>sq_errors = errors ** <NUM_LIT:2><EOL>sq_errors_mean = np.mean(sq_errors, axis=<NUM_LIT:0>)<EOL>sq_errors_mean_unc = (np.std(sq_errors, axis=<NUM_LIT:0>, ddof=<NUM_LIT:1>) /<EOL>np.sqrt(sq_errors.sh... | 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... | f15346:m7 |
def array_ratio_std(values_n, sigmas_n, values_d, sigmas_d): | std = np.sqrt((sigmas_n / values_n) ** <NUM_LIT:2> + (sigmas_d / values_d) ** <NUM_LIT:2>)<EOL>std *= (values_n / values_d)<EOL>return std<EOL> | 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
--... | f15346:m8 |
@nestcheck.io_utils.save_load_result<EOL>def run_list_error_values(run_list, estimator_list, estimator_names,<EOL>n_simulate=<NUM_LIT:100>, **kwargs): | thread_pvalue = kwargs.pop('<STR_LIT>', False)<EOL>bs_stat_dist = kwargs.pop('<STR_LIT>', False)<EOL>parallel = kwargs.pop('<STR_LIT>', True)<EOL>if kwargs:<EOL><INDENT>raise TypeError('<STR_LIT>'.format(kwargs))<EOL><DEDENT>assert len(estimator_list) == len(estimator_names), (<EOL>'<STR_LIT>'<EOL>.format(len(estimator... | Gets a data frame with calculation values and error diagnostics for each
run in the input run list.
NB when parallelised the results will not be produced in order (so results
from some run number will not nessesarily correspond to that number run in
run_list).
Parameters
----------
run_lis... | f15347:m0 |
@nestcheck.io_utils.save_load_result<EOL>def estimator_values_df(run_list, estimator_list, **kwargs): | estimator_names = kwargs.pop(<EOL>'<STR_LIT>',<EOL>['<STR_LIT>' + str(i) for i in range(len(estimator_list))])<EOL>parallel = kwargs.pop('<STR_LIT>', True)<EOL>if kwargs:<EOL><INDENT>raise TypeError('<STR_LIT>'.format(kwargs))<EOL><DEDENT>values_list = pu.parallel_apply(<EOL>nestcheck.ns_run_utils.run_estimators, run_l... | Get a dataframe of estimator values.
NB when parallelised the results will not be produced in order (so results
from some run number will not nessesarily correspond to that number run in
run_list).
Parameters
----------
run_list: list of dicts
List of nested sampling run dicts.
est... | f15347:m1 |
def error_values_summary(error_values, **summary_df_kwargs): | df = pf.summary_df_from_multi(error_values, **summary_df_kwargs)<EOL>imp_std, imp_std_unc, imp_frac, imp_frac_unc =nestcheck.error_analysis.implementation_std(<EOL>df.loc[('<STR_LIT>', '<STR_LIT:value>')],<EOL>df.loc[('<STR_LIT>', '<STR_LIT>')],<EOL>df.loc[('<STR_LIT>', '<STR_LIT:value>')],<EOL>df.loc[('<STR_LIT>', '<S... | Get summary statistics about calculation errors, including estimated
implementation errors.
Parameters
----------
error_values: pandas DataFrame
Of format output by run_list_error_values (look at it for more
details).
summary_df_kwargs: dict, optional
See pandas_functions.su... | f15347:m2 |
def run_list_error_summary(run_list, estimator_list, estimator_names,<EOL>n_simulate, **kwargs): | true_values = kwargs.pop('<STR_LIT>', None)<EOL>include_true_values = kwargs.pop('<STR_LIT>', False)<EOL>include_rmse = kwargs.pop('<STR_LIT>', False)<EOL>error_values = run_list_error_values(run_list, estimator_list,<EOL>estimator_names, n_simulate, **kwargs)<EOL>return error_values_summary(error_values, true_values=t... | Wrapper which runs run_list_error_values then applies error_values
summary to the resulting dataframe. See the docstrings for those two
funcions for more details and for descriptions of parameters and output. | f15347:m3 |
def bs_values_df(run_list, estimator_list, estimator_names, n_simulate,<EOL>**kwargs): | tqdm_kwargs = kwargs.pop('<STR_LIT>', {'<STR_LIT>': '<STR_LIT>'})<EOL>assert len(estimator_list) == len(estimator_names), (<EOL>'<STR_LIT>'<EOL>.format(len(estimator_list), len(estimator_names)))<EOL>bs_values_list = pu.parallel_apply(<EOL>nestcheck.error_analysis.run_bootstrap_values, run_list,<EOL>func_args=(estimato... | Computes a data frame of bootstrap resampled values.
Parameters
----------
run_list: list of dicts
List of nested sampling run dicts.
estimator_list: list of functions
Estimators to apply to runs.
estimator_names: list of strs
Name of each func in estimator_list.
n_simul... | f15347:m4 |
def thread_values_df(run_list, estimator_list, estimator_names, **kwargs): | tqdm_kwargs = kwargs.pop('<STR_LIT>', {'<STR_LIT>': '<STR_LIT>'})<EOL>assert len(estimator_list) == len(estimator_names), (<EOL>'<STR_LIT>'<EOL>.format(len(estimator_list), len(estimator_names)))<EOL>thread_vals_arrays = pu.parallel_apply(<EOL>nestcheck.error_analysis.run_thread_values, run_list,<EOL>func_args=(estimat... | Calculates estimator values for the constituent threads of the input
runs.
Parameters
----------
run_list: list of dicts
List of nested sampling run dicts.
estimator_list: list of functions
Estimators to apply to runs.
estimator_names: list of strs
Name of each func in e... | f15347:m5 |
def pairwise_dists_on_cols(df_in, earth_mover_dist=True, energy_dist=True): | df = pd.DataFrame()<EOL>for col in df_in.columns:<EOL><INDENT>df[col] = nestcheck.error_analysis.pairwise_distances(<EOL>df_in[col].values, earth_mover_dist=earth_mover_dist,<EOL>energy_dist=energy_dist)<EOL><DEDENT>return df<EOL> | Computes pairwise statistical distance measures.
parameters
----------
df_in: pandas data frame
Columns represent estimators and rows represent runs.
Each data frane element is an array of values which are used as samples
in the distance measures.
earth_mover_dist: bool, optiona... | f15347:m6 |
def write_run_output(run, **kwargs): | write_dead = kwargs.pop('<STR_LIT>', True)<EOL>write_stats = kwargs.pop('<STR_LIT>', True)<EOL>posteriors = kwargs.pop('<STR_LIT>', False)<EOL>equals = kwargs.pop('<STR_LIT>', False)<EOL>stats_means_errs = kwargs.pop('<STR_LIT>', True)<EOL>fmt = kwargs.pop('<STR_LIT>', '<STR_LIT>')<EOL>n_simulate = kwargs.pop('<STR_LIT... | Writes PolyChord output files corresponding to the input nested sampling
run. The file root is
.. code-block:: python
root = os.path.join(run['output']['base_dir'],
run['output']['file_root'])
Output files which can be made with this function (see the PolyChord
doc... | f15348:m0 |
def run_dead_birth_array(run, **kwargs): | nestcheck.ns_run_utils.check_ns_run(run, **kwargs)<EOL>threads = nestcheck.ns_run_utils.get_run_threads(run)<EOL>samp_arrays = []<EOL>ndim = run['<STR_LIT>'].shape[<NUM_LIT:1>]<EOL>for th in threads:<EOL><INDENT>samp_arr = np.zeros((th['<STR_LIT>'].shape[<NUM_LIT:0>], ndim + <NUM_LIT:2>))<EOL>samp_arr[:, :ndim] = th['<... | Converts input run into an array of the format of a PolyChord
<root>_dead-birth.txt file. Note that this in fact includes live points
remaining at termination as well as dead points.
Parameters
----------
ns_run: dict
Nested sampling run dict (see data_processing module docstring for more
... | f15348:m1 |
def write_stats_file(run_output_dict): | mandatory_keys = ['<STR_LIT>', '<STR_LIT>']<EOL>for key in mandatory_keys:<EOL><INDENT>assert key in run_output_dict, key + '<STR_LIT>'<EOL><DEDENT>default_output = {'<STR_LIT>': <NUM_LIT:0.0>,<EOL>'<STR_LIT>': <NUM_LIT:0.0>,<EOL>'<STR_LIT>': [<NUM_LIT:0.0>],<EOL>'<STR_LIT>': [<NUM_LIT:0.0>],<EOL>'<STR_LIT>': <NUM_LIT:... | Writes a dummy PolyChord format .stats file for tests functions for
processing stats files. This is written to:
base_dir/file_root.stats
Also returns the data in the file as a dict for comparison.
Parameters
----------
run_output_dict: dict
Output information to write to .stats file. ... | f15348:m2 |
def timing_decorator(func): | @functools.wraps(func)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>"""<STR_LIT>"""<EOL>print_time = kwargs.pop('<STR_LIT>', False)<EOL>if not print_time:<EOL><INDENT>return func(*args, **kwargs)<EOL><DEDENT>else:<EOL><INDENT>start_time = time.time()<EOL>result = func(*args, **kwargs)<EOL>end_time = time.time()<EOL>pr... | Prints the time func takes to execute. | f15349:m0 |
def save_load_result(func): | @functools.wraps(func)<EOL>def wrapper(*args, **kwargs):<EOL><INDENT>"""<STR_LIT>"""<EOL>save_name = kwargs.pop('<STR_LIT>', None)<EOL>save = kwargs.pop('<STR_LIT>', save_name is not None)<EOL>load = kwargs.pop('<STR_LIT>', save_name is not None)<EOL>overwrite_existing = kwargs.pop('<STR_LIT>', True)<EOL>warn_if_error ... | Saves and/or loads func output (must be picklable). | f15349:m1 |
@timing_decorator<EOL>def pickle_save(data, name, **kwargs): | extension = kwargs.pop('<STR_LIT>', '<STR_LIT>')<EOL>overwrite_existing = kwargs.pop('<STR_LIT>', True)<EOL>if kwargs:<EOL><INDENT>raise TypeError('<STR_LIT>'.format(kwargs))<EOL><DEDENT>filename = name + extension<EOL>dirname = os.path.dirname(filename)<EOL>if not os.path.exists(dirname) and dirname != '<STR_LIT>':<EO... | 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 ... | f15349:m2 |
@timing_decorator<EOL>def pickle_load(name, extension='<STR_LIT>'): | filename = name + extension<EOL>infile = open(filename, '<STR_LIT:rb>')<EOL>data = pickle.load(infile)<EOL>infile.close()<EOL>return data<EOL> | 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. | f15349:m3 |
def count_samples(ns_run, **kwargs): | kwargs.pop('<STR_LIT>', None)<EOL>kwargs.pop('<STR_LIT>', None)<EOL>if kwargs:<EOL><INDENT>raise TypeError('<STR_LIT>'.format(kwargs))<EOL><DEDENT>return ns_run['<STR_LIT>'].shape[<NUM_LIT:0>]<EOL> | 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
docstring for more details).
R... | f15350:m0 |
def logz(ns_run, logw=None, simulate=False): | if logw is None:<EOL><INDENT>logw = nestcheck.ns_run_utils.get_logw(ns_run, simulate=simulate)<EOL><DEDENT>return scipy.special.logsumexp(logw)<EOL> | r"""Natural log of Bayesian evidence :math:`\log \mathcal{Z}`.
Parameters
----------
ns_run: dict
Nested sampling run dict (see the data_processing module
docstring for more details).
logw: None or 1d numpy array, optional
Log weights of samples.
simulate: bool, optional
... | f15350:m1 |
def evidence(ns_run, logw=None, simulate=False): | if logw is None:<EOL><INDENT>logw = nestcheck.ns_run_utils.get_logw(ns_run, simulate=simulate)<EOL><DEDENT>return np.exp(scipy.special.logsumexp(logw))<EOL> | r"""Bayesian evidence :math:`\log \mathcal{Z}`.
Parameters
----------
ns_run: dict
Nested sampling run dict (see the data_processing module
docstring for more details).
logw: None or 1d numpy array, optional
Log weights of samples.
simulate: bool, optional
Passed to ... | f15350:m2 |
def param_mean(ns_run, logw=None, simulate=False, param_ind=<NUM_LIT:0>,<EOL>handle_indexerror=False): | if logw is None:<EOL><INDENT>logw = nestcheck.ns_run_utils.get_logw(ns_run, simulate=simulate)<EOL><DEDENT>w_relative = np.exp(logw - logw.max())<EOL>try:<EOL><INDENT>return (np.sum(w_relative * ns_run['<STR_LIT>'][:, param_ind])<EOL>/ np.sum(w_relative))<EOL><DEDENT>except IndexError:<EOL><INDENT>if handle_indexerror:... | 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).
logw: None or 1d numpy array, optional
Log weights of samples.
simulate: bool, optional
Pa... | f15350:m3 |
def param_cred(ns_run, logw=None, simulate=False, probability=<NUM_LIT:0.5>,<EOL>param_ind=<NUM_LIT:0>): | if logw is None:<EOL><INDENT>logw = nestcheck.ns_run_utils.get_logw(ns_run, simulate=simulate)<EOL><DEDENT>w_relative = np.exp(logw - logw.max()) <EOL>return weighted_quantile(probability, ns_run['<STR_LIT>'][:, param_ind],<EOL>w_relative)<EOL> | One-tailed credible interval on the value of a single parameter
(component of theta).
Parameters
----------
ns_run: dict
Nested sampling run dict (see the data_processing module
docstring for more details).
logw: None or 1d numpy array, optional
Log weights of samples.
s... | f15350:m4 |
def param_squared_mean(ns_run, logw=None, simulate=False, param_ind=<NUM_LIT:0>): | if logw is None:<EOL><INDENT>logw = nestcheck.ns_run_utils.get_logw(ns_run, simulate=simulate)<EOL><DEDENT>w_relative = np.exp(logw - logw.max()) <EOL>w_relative /= np.sum(w_relative)<EOL>return np.sum(w_relative * (ns_run['<STR_LIT>'][:, param_ind] ** <NUM_LIT:2>))<EOL> | 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).
logw: None or 1d numpy array, optional
Log weights of samples.
s... | f15350:m5 |
def r_mean(ns_run, logw=None, simulate=False): | if logw is None:<EOL><INDENT>logw = nestcheck.ns_run_utils.get_logw(ns_run, simulate=simulate)<EOL><DEDENT>w_relative = np.exp(logw - logw.max())<EOL>r = np.sqrt(np.sum(ns_run['<STR_LIT>'] ** <NUM_LIT:2>, axis=<NUM_LIT:1>))<EOL>return np.sum(w_relative * r) / np.sum(w_relative)<EOL> | Mean of the radial coordinate (magnitude of theta vector).
Parameters
----------
ns_run: dict
Nested sampling run dict (see the data_processing module
docstring for more details).
logw: None or 1d numpy array, optional
Log weights of samples.
simulate: bool, optional
... | f15350:m6 |
def r_cred(ns_run, logw=None, simulate=False, probability=<NUM_LIT:0.5>): | if logw is None:<EOL><INDENT>logw = nestcheck.ns_run_utils.get_logw(ns_run, simulate=simulate)<EOL><DEDENT>w_relative = np.exp(logw - logw.max()) <EOL>r = np.sqrt(np.sum(ns_run['<STR_LIT>'] ** <NUM_LIT:2>, axis=<NUM_LIT:1>))<EOL>return weighted_quantile(probability, r, w_relative)<EOL> | One-tailed credible interval on the value of the radial coordinate
(magnitude of theta vector).
Parameters
----------
ns_run: dict
Nested sampling run dict (see the data_processing module
docstring for more details).
logw: None or 1d numpy array, optional
Log weights of samp... | f15350:m7 |
def get_latex_name(func_in, **kwargs): | if isinstance(func_in, functools.partial):<EOL><INDENT>func = func_in.func<EOL>assert not set(func_in.keywords) & set(kwargs), (<EOL>'<STR_LIT>'<EOL>.format(kwargs, func_in.keywords))<EOL>kwargs.update(func_in.keywords)<EOL><DEDENT>else:<EOL><INDENT>func = func_in<EOL><DEDENT>param_ind = kwargs.pop('<STR_LIT>', <NUM_LI... | Produce a latex formatted name for each function for use in labelling
results.
Parameters
----------
func_in: function
kwargs: dict, optional
Kwargs for function.
Returns
-------
latex_name: str
Latex formatted name for the function. | f15350:m8 |
def weighted_quantile(probability, values, weights): | assert <NUM_LIT:1> > probability > <NUM_LIT:0>, (<EOL>'<STR_LIT>' + str(probability) + '<STR_LIT>')<EOL>assert values.shape == weights.shape<EOL>assert values.ndim == <NUM_LIT:1><EOL>assert weights.ndim == <NUM_LIT:1><EOL>sorted_inds = np.argsort(values)<EOL>quantiles = np.cumsum(weights[sorted_inds]) - (<NUM_LIT:0.5> ... | Get quantile estimate for input probability given weighted samples using
linear interpolation.
Parameters
----------
probability: float
Quantile to estimate - must be in open interval (0, 1).
For example, use 0.5 for the median and 0.84 for the upper
84% quantile.
values: 1d numpy array
Sample values.
... | f15350:m9 |
def parallel_map(func, *arg_iterable, **kwargs): | chunksize = kwargs.pop('<STR_LIT>', <NUM_LIT:1>)<EOL>func_pre_args = kwargs.pop('<STR_LIT>', ())<EOL>func_kwargs = kwargs.pop('<STR_LIT>', {})<EOL>max_workers = kwargs.pop('<STR_LIT>', None)<EOL>parallel = kwargs.pop('<STR_LIT>', True)<EOL>parallel_warning = kwargs.pop('<STR_LIT>', True)<EOL>if kwargs:<EOL><INDENT>rais... | 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... | f15351:m0 |
def parallel_apply(func, arg_iterable, **kwargs): | max_workers = kwargs.pop('<STR_LIT>', None)<EOL>parallel = kwargs.pop('<STR_LIT>', True)<EOL>parallel_warning = kwargs.pop('<STR_LIT>', True)<EOL>func_args = kwargs.pop('<STR_LIT>', ())<EOL>func_pre_args = kwargs.pop('<STR_LIT>', ())<EOL>func_kwargs = kwargs.pop('<STR_LIT>', {})<EOL>tqdm_kwargs = kwargs.pop('<STR_LIT>'... | 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... | f15351:m1 |
def select_tqdm(): | try:<EOL><INDENT>progress = tqdm.tqdm_notebook<EOL>assert get_ipython().has_trait('<STR_LIT>')<EOL><DEDENT>except (NameError, AssertionError):<EOL><INDENT>progress = tqdm.tqdm<EOL><DEDENT>return progress<EOL> | If running in a jupyter notebook, then returns tqdm_notebook.
Otherwise returns a regular tqdm progress bar.
Returns
-------
progress: function | f15351:m2 |
@nestcheck.io_utils.save_load_result<EOL>def batch_process_data(file_roots, **kwargs): | base_dir = kwargs.pop('<STR_LIT>', '<STR_LIT>')<EOL>process_func = kwargs.pop('<STR_LIT>', process_polychord_run)<EOL>func_kwargs = kwargs.pop('<STR_LIT>', {})<EOL>func_kwargs['<STR_LIT>'] = kwargs.pop('<STR_LIT>', ())<EOL>data = nestcheck.parallel_utils.parallel_apply(<EOL>process_error_helper, file_roots, func_args=(... | 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... | f15352:m0 |
def process_error_helper(root, base_dir, process_func, errors_to_handle=(),<EOL>**func_kwargs): | try:<EOL><INDENT>return process_func(root, base_dir, **func_kwargs)<EOL><DEDENT>except errors_to_handle as err:<EOL><INDENT>run = {'<STR_LIT:error>': type(err).__name__,<EOL>'<STR_LIT>': {'<STR_LIT>': root}}<EOL>return run<EOL><DEDENT> | 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... | f15352:m1 |
def process_polychord_run(file_root, base_dir, process_stats_file=True,<EOL>**kwargs): | <EOL>samples = np.loadtxt(os.path.join(base_dir, file_root) + '<STR_LIT>')<EOL>ns_run = process_samples_array(samples, **kwargs)<EOL>ns_run['<STR_LIT>'] = {'<STR_LIT>': base_dir, '<STR_LIT>': file_root}<EOL>if process_stats_file:<EOL><INDENT>try:<EOL><INDENT>ns_run['<STR_LIT>'] = process_polychord_stats(file_root, base... | 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... | f15352:m2 |
def process_multinest_run(file_root, base_dir, **kwargs): | <EOL>dead = np.loadtxt(os.path.join(base_dir, file_root) + '<STR_LIT>')<EOL>live = np.loadtxt(os.path.join(base_dir, file_root)<EOL>+ '<STR_LIT>')<EOL>dead = dead[:, :-<NUM_LIT:2>]<EOL>live = live[:, :-<NUM_LIT:1>]<EOL>assert dead[:, -<NUM_LIT:2>].max() < live[:, -<NUM_LIT:2>].min(), (<EOL>'<STR_LIT>',<EOL>dead, live)<... | 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
--------... | f15352:m3 |
def process_dynesty_run(results): | samples = np.zeros((results.samples.shape[<NUM_LIT:0>],<EOL>results.samples.shape[<NUM_LIT:1>] + <NUM_LIT:3>))<EOL>samples[:, <NUM_LIT:0>] = results.logl<EOL>samples[:, <NUM_LIT:1>] = results.samples_id<EOL>samples[:, <NUM_LIT:3>:] = results.samples<EOL>unique_th, first_inds = np.unique(results.samples_id, return_index... | 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 ... | f15352:m4 |
def process_polychord_stats(file_root, base_dir): | filename = os.path.join(base_dir, file_root) + '<STR_LIT>'<EOL>output = {'<STR_LIT>': base_dir,<EOL>'<STR_LIT>': file_root}<EOL>with open(filename, '<STR_LIT:r>') as stats_file:<EOL><INDENT>lines = stats_file.readlines()<EOL><DEDENT>output['<STR_LIT>'] = float(lines[<NUM_LIT:8>].split()[<NUM_LIT:2>])<EOL>output['<STR_L... | 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
... | f15352:m5 |
def process_samples_array(samples, **kwargs): | samples = samples[np.argsort(samples[:, -<NUM_LIT:2>])]<EOL>ns_run = {}<EOL>ns_run['<STR_LIT>'] = samples[:, -<NUM_LIT:2>]<EOL>ns_run['<STR_LIT>'] = samples[:, :-<NUM_LIT:2>]<EOL>birth_contours = samples[:, -<NUM_LIT:1>]<EOL>birth_inds = birth_inds_given_contours(<EOL>birth_contours, ns_run['<STR_LIT>'], **kwargs)<EOL>... | 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 ... | f15352:m6 |
def birth_inds_given_contours(birth_logl_arr, logl_arr, **kwargs): | dup_assert = kwargs.pop('<STR_LIT>', False)<EOL>dup_warn = kwargs.pop('<STR_LIT>', False)<EOL>if kwargs:<EOL><INDENT>raise TypeError('<STR_LIT>'.format(kwargs))<EOL><DEDENT>assert logl_arr.ndim == <NUM_LIT:1>, logl_arr.ndim<EOL>assert birth_logl_arr.ndim == <NUM_LIT:1>, birth_logl_arr.ndim<EOL>nestcheck.ns_run_utils.ch... | 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... | f15352:m7 |
def sample_less_than_condition(choices_in, condition): | output = np.zeros(min(condition.shape[<NUM_LIT:0>], choices_in.shape[<NUM_LIT:0>]))<EOL>choices = copy.deepcopy(choices_in)<EOL>for i, _ in enumerate(output):<EOL><INDENT>avail_inds = np.where(choices < condition[i])[<NUM_LIT:0>]<EOL>selected_ind = np.random.choice(avail_inds)<EOL>output[i] = choices[selected_ind]<EOL>... | 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. | f15352:m8 |
def threads_given_birth_inds(birth_inds): | unique, counts = np.unique(birth_inds, return_counts=True)<EOL>thread_start_inds = np.concatenate((<EOL>unique[:<NUM_LIT:1>], unique[<NUM_LIT:1>:][counts[<NUM_LIT:1>:] > <NUM_LIT:1>]))<EOL>thread_start_counts = np.concatenate((<EOL>counts[:<NUM_LIT:1>], counts[<NUM_LIT:1>:][counts[<NUM_LIT:1>:] > <NUM_LIT:1>] - <NUM_LI... | 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... | f15352:m9 |
def get_dummy_thread(nsamples, **kwargs): | seed = kwargs.pop('<STR_LIT>', False)<EOL>ndim = kwargs.pop('<STR_LIT>', <NUM_LIT:2>)<EOL>logl_start = kwargs.pop('<STR_LIT>', -np.inf)<EOL>logl_range = kwargs.pop('<STR_LIT>', <NUM_LIT:1>)<EOL>if kwargs:<EOL><INDENT>raise TypeError('<STR_LIT>'.format(kwargs))<EOL><DEDENT>if seed is not False:<EOL><INDENT>np.random.see... | 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... | f15354:m0 |
def get_dummy_run(nthread, nsamples, **kwargs): | seed = kwargs.pop('<STR_LIT>', False)<EOL>ndim = kwargs.pop('<STR_LIT>', <NUM_LIT:2>)<EOL>logl_start = kwargs.pop('<STR_LIT>', -np.inf)<EOL>logl_range = kwargs.pop('<STR_LIT>', <NUM_LIT:1>)<EOL>if kwargs:<EOL><INDENT>raise TypeError('<STR_LIT>'.format(kwargs))<EOL><DEDENT>threads = []<EOL>if seed is not False:<EOL><IND... | 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... | f15354:m1 |
def get_dummy_dynamic_run(nsamples, **kwargs): | seed = kwargs.pop('<STR_LIT>', False)<EOL>ndim = kwargs.pop('<STR_LIT>', <NUM_LIT:2>)<EOL>nthread_init = kwargs.pop('<STR_LIT>', <NUM_LIT:2>)<EOL>nthread_dyn = kwargs.pop('<STR_LIT>', <NUM_LIT:3>)<EOL>logl_range = kwargs.pop('<STR_LIT>', <NUM_LIT:1>)<EOL>if kwargs:<EOL><INDENT>raise TypeError('<STR_LIT>'.format(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 generated from a uniform
distribution in (0, 1).
... | f15354:m2 |
def plot_run_nlive(method_names, run_dict, **kwargs): | logx_given_logl = kwargs.pop('<STR_LIT>', None)<EOL>logl_given_logx = kwargs.pop('<STR_LIT>', None)<EOL>logx_min = kwargs.pop('<STR_LIT>', None)<EOL>ymax = kwargs.pop('<STR_LIT>', None)<EOL>npoints = kwargs.pop('<STR_LIT>', <NUM_LIT:100>)<EOL>figsize = kwargs.pop('<STR_LIT>', (<NUM_LIT>, <NUM_LIT:2>))<EOL>post_mass_nor... | 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.
... | f15355:m0 |
def kde_plot_df(df, xlims=None, **kwargs): | assert xlims is None or isinstance(xlims, dict)<EOL>figsize = kwargs.pop('<STR_LIT>', (<NUM_LIT>, <NUM_LIT>))<EOL>num_xticks = kwargs.pop('<STR_LIT>', None)<EOL>nrows = kwargs.pop('<STR_LIT>', <NUM_LIT:1>)<EOL>ncols = kwargs.pop('<STR_LIT>', int(np.ceil(len(df.columns) / nrows)))<EOL>normalize = kwargs.pop('<STR_LIT>',... | 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... | f15355:m1 |
def bs_param_dists(run_list, **kwargs): | fthetas = kwargs.pop('<STR_LIT>', [lambda theta: theta[:, <NUM_LIT:0>],<EOL>lambda theta: theta[:, <NUM_LIT:1>]])<EOL>labels = kwargs.pop('<STR_LIT>', [r'<STR_LIT>' + str(i + <NUM_LIT:1>) + '<STR_LIT:$>' for i in<EOL>range(len(fthetas))])<EOL>ftheta_lims = kwargs.pop('<STR_LIT>', [[-<NUM_LIT:1>, <NUM_LIT:1>]] * len(fth... | 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... | f15355:m2 |
def param_logx_diagram(run_list, **kwargs): | fthetas = kwargs.pop('<STR_LIT>', [lambda theta: theta[:, <NUM_LIT:0>],<EOL>lambda theta: theta[:, <NUM_LIT:1>]])<EOL>labels = kwargs.pop('<STR_LIT>', [r'<STR_LIT>' + str(i + <NUM_LIT:1>) + '<STR_LIT:$>' for i in<EOL>range(len(fthetas))])<EOL>ftheta_lims = kwargs.pop('<STR_LIT>', [[-<NUM_LIT:1>, <NUM_LIT:1>]] * len(fth... | 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... | f15355:m3 |
def plot_bs_dists(run, fthetas, axes, **kwargs): | ftheta_lims = kwargs.pop('<STR_LIT>', [[-<NUM_LIT:1>, <NUM_LIT:1>]] * len(fthetas))<EOL>n_simulate = kwargs.pop('<STR_LIT>', <NUM_LIT:100>)<EOL>colormap = kwargs.pop('<STR_LIT>', plt.get_cmap('<STR_LIT>'))<EOL>mean_color = kwargs.pop('<STR_LIT>', None)<EOL>nx = kwargs.pop('<STR_LIT>', <NUM_LIT:100>)<EOL>ny = kwargs.pop... | 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... | f15355:m4 |
def alternate_helper(x, alt_samps, func=None): | alt_samps = alt_samps[~np.isnan(alt_samps)]<EOL>arg1 = alt_samps[::<NUM_LIT:2>]<EOL>arg2 = alt_samps[<NUM_LIT:1>::<NUM_LIT:2>]<EOL>return func(x, arg1, arg2)<EOL> | Helper function for making fgivenx plots of functions with 2 array
arguments of variable lengths. | f15355:m5 |
def weighted_1d_gaussian_kde(x, samples, weights): | assert x.ndim == <NUM_LIT:1><EOL>assert samples.ndim == <NUM_LIT:1><EOL>assert samples.shape == weights.shape<EOL>weights /= np.sum(weights)<EOL>nz_weights = weights[np.nonzero(weights)]<EOL>nsamp_eff = np.exp(-<NUM_LIT:1.> * np.sum(nz_weights * np.log(nz_weights)))<EOL>mu = np.sum(weights * samples)<EOL>var = np.sum(w... | 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... | f15355:m6 |
def rel_posterior_mass(logx, logl): | logw = logx + logl<EOL>w_rel = np.exp(logw - logw.max())<EOL>w_rel /= np.abs(np.trapz(w_rel, x=logx))<EOL>return w_rel<EOL> | 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... | f15355:m7 |
def average_by_key(dict_in, key): | if key is None:<EOL><INDENT>return np.mean(np.concatenate(list(dict_in.values())))<EOL><DEDENT>else:<EOL><INDENT>try:<EOL><INDENT>return np.mean(dict_in[key])<EOL><DEDENT>except KeyError:<EOL><INDENT>print('<STR_LIT>' + key + '<STR_LIT>' +<EOL>'<STR_LIT>' +<EOL>'<STR_LIT>')<EOL>return np.mean(np.concatenate(list(dict_i... | 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 | f15355:m8 |
def run_estimators(ns_run, estimator_list, simulate=False): | logw = get_logw(ns_run, simulate=simulate)<EOL>output = np.zeros(len(estimator_list))<EOL>for i, est in enumerate(estimator_list):<EOL><INDENT>output[i] = est(ns_run, logw=logw)<EOL><DEDENT>return output<EOL> | 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 ... | f15356:m0 |
def array_given_run(ns_run): | samples = np.zeros((ns_run['<STR_LIT>'].shape[<NUM_LIT:0>], <NUM_LIT:3> + ns_run['<STR_LIT>'].shape[<NUM_LIT:1>]))<EOL>samples[:, <NUM_LIT:0>] = ns_run['<STR_LIT>']<EOL>samples[:, <NUM_LIT:1>] = ns_run['<STR_LIT>']<EOL>samples[:-<NUM_LIT:1>, <NUM_LIT:2>] = np.diff(ns_run['<STR_LIT>'])<EOL>samples[-<NUM_LIT:1>, <NUM_LIT... | 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... | f15356:m1 |
def dict_given_run_array(samples, thread_min_max): | ns_run = {'<STR_LIT>': samples[:, <NUM_LIT:0>],<EOL>'<STR_LIT>': samples[:, <NUM_LIT:1>],<EOL>'<STR_LIT>': thread_min_max,<EOL>'<STR_LIT>': samples[:, <NUM_LIT:3>:]}<EOL>if np.all(~np.isnan(ns_run['<STR_LIT>'])):<EOL><INDENT>ns_run['<STR_LIT>'] = ns_run['<STR_LIT>'].astype(int)<EOL>assert np.array_equal(samples[:, <NUM... | 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 the run output can... | f15356:m2 |
def get_run_threads(ns_run): | samples = array_given_run(ns_run)<EOL>unique_threads = np.unique(ns_run['<STR_LIT>'])<EOL>assert ns_run['<STR_LIT>'].shape[<NUM_LIT:0>] == unique_threads.shape[<NUM_LIT:0>], (<EOL>'<STR_LIT>'.format(<EOL>unique_threads.shape[<NUM_LIT:0>], ns_run['<STR_LIT>'].shape[<NUM_LIT:0>]))<EOL>threads = []<EOL>for i, th_lab in en... | 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 containing columns
[logl, thread label,... | f15356:m3 |
def combine_ns_runs(run_list_in, **kwargs): | run_list = copy.deepcopy(run_list_in)<EOL>if len(run_list) == <NUM_LIT:1>:<EOL><INDENT>run = run_list[<NUM_LIT:0>]<EOL><DEDENT>else:<EOL><INDENT>nthread_tot = <NUM_LIT:0><EOL>for i, _ in enumerate(run_list):<EOL><INDENT>check_ns_run(run_list[i], **kwargs)<EOL>run_list[i]['<STR_LIT>'] += nthread_tot<EOL>nthread_tot += r... | 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).
kwargs: dict, optional
Optio... | f15356:m4 |
def combine_threads(threads, assert_birth_point=False): | thread_min_max = np.vstack([td['<STR_LIT>'] for td in threads])<EOL>assert len(threads) == thread_min_max.shape[<NUM_LIT:0>]<EOL>samples_temp = np.vstack([array_given_run(thread) for thread in threads])<EOL>samples_temp = samples_temp[np.argsort(samples_temp[:, <NUM_LIT:0>])]<EOL>logl_starts = thread_min_max[:, <NUM_LI... | 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 output will fail chec... | f15356:m5 |
def get_logw(ns_run, simulate=False): | try:<EOL><INDENT>logx = get_logx(ns_run['<STR_LIT>'], simulate=simulate)<EOL>logw = np.zeros(ns_run['<STR_LIT>'].shape[<NUM_LIT:0>])<EOL>logw[<NUM_LIT:1>:-<NUM_LIT:1>] = log_subtract(logx[:-<NUM_LIT:2>], logx[<NUM_LIT:2>:]) - np.log(<NUM_LIT:2>)<EOL>logw[<NUM_LIT:0>] = log_subtract(<NUM_LIT:0>, scipy.special.logsumexp(... | r"""Calculates the log posterior weights of the samples (using logarithms
to avoid overflow errors with very large or small values).
Uses the trapezium rule such that the weight of point i is
.. math:: w_i = \mathcal{L}_i (X_{i-1} - X_{i+1}) / 2
Parameters
----------
ns_run: dict
Nest... | f15356:m6 |
def get_w_rel(ns_run, simulate=False): | logw = get_logw(ns_run, simulate=simulate)<EOL>return np.exp(logw - logw.max())<EOL> | 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_processing module docstring for more
d... | f15356:m7 |
def get_logx(nlive, simulate=False): | assert nlive.min() > <NUM_LIT:0>, (<EOL>'<STR_LIT>' + str(nlive))<EOL>if simulate:<EOL><INDENT>logx_steps = np.log(np.random.random(nlive.shape)) / nlive<EOL><DEDENT>else:<EOL><INDENT>logx_steps = -<NUM_LIT:1> * (nlive.astype(float) ** -<NUM_LIT:1>)<EOL><DEDENT>return np.cumsum(logx_steps)<EOL> | r"""Returns a logx vector showing the expected or simulated logx positions
of points.
The shrinkage factor between two points
.. math:: t_i = X_{i-1} / X_{i}
is distributed as the largest of :math:`n_i` uniform random variables
between 1 and 0, where :math:`n_i` is the local number of live points... | f15356:m8 |
def log_subtract(loga, logb): | return loga + np.log(<NUM_LIT:1> - np.exp(logb - loga))<EOL> | r"""Numerically stable method for avoiding overflow errors when calculating
:math:`\log (a-b)`, given :math:`\log (a)`, :math:`\log (a)` and that
:math:`a > b`.
See https://hips.seas.harvard.edu/blog/2013/01/09/computing-log-sum-exp/
for more details.
Parameters
----------
loga: float
... | f15356:m9 |
def check_ns_run(run, dup_assert=False, dup_warn=False): | assert isinstance(run, dict)<EOL>check_ns_run_members(run)<EOL>check_ns_run_logls(run, dup_assert=dup_assert, dup_warn=dup_warn)<EOL>check_ns_run_threads(run)<EOL> | 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: bool, optional
See check_ns_run_logls docstring.
dup_wa... | f15356:m10 |
def check_ns_run_members(run): | run_keys = list(run.keys())<EOL>for key in ['<STR_LIT>', '<STR_LIT>', '<STR_LIT>', '<STR_LIT>',<EOL>'<STR_LIT>']:<EOL><INDENT>assert key in run_keys<EOL>run_keys.remove(key)<EOL><DEDENT>for key in ['<STR_LIT>']:<EOL><INDENT>try:<EOL><INDENT>run_keys.remove(key)<EOL><DEDENT>except ValueError:<EOL><INDENT>pass<EOL><DEDEN... | Check nested sampling run member keys and values.
Parameters
----------
run: dict
nested sampling run to check.
Raises
------
AssertionError
if run does not have expected properties. | f15356:m11 |
def check_ns_run_logls(run, dup_assert=False, dup_warn=False): | assert np.array_equal(run['<STR_LIT>'], run['<STR_LIT>'][np.argsort(run['<STR_LIT>'])])<EOL>if dup_assert or dup_warn:<EOL><INDENT>unique_logls, counts = np.unique(run['<STR_LIT>'], return_counts=True)<EOL>repeat_logls = run['<STR_LIT>'].shape[<NUM_LIT:0>] - unique_logls.shape[<NUM_LIT:0>]<EOL>msg = ('<STR_LIT>'<EOL>'<... | Check run logls are unique and in the correct order.
Parameters
----------
run: dict
nested sampling run to check.
dup_assert: bool, optional
Whether to raise and AssertionError if there are duplicate logl values.
dup_warn: bool, optional
Whether to give a UserWarning if the... | f15356:m12 |
def check_ns_run_threads(run): | assert run['<STR_LIT>'].dtype == int<EOL>uniq_th = np.unique(run['<STR_LIT>'])<EOL>assert np.array_equal(<EOL>np.asarray(range(run['<STR_LIT>'].shape[<NUM_LIT:0>])), uniq_th),str(uniq_th)<EOL>assert np.any(run['<STR_LIT>'][:, <NUM_LIT:0>] == -np.inf), (<EOL>'<STR_LIT>' +<EOL>'<STR_LIT>')<EOL>for th_lab in uniq_th:<EOL>... | Check thread labels and thread_min_max have expected properties.
Parameters
----------
run: dict
Nested sampling run to check.
Raises
------
AssertionError
If run does not have expected properties. | f15356:m13 |
def bootstrap_resample_run(ns_run, threads=None, ninit_sep=False,<EOL>random_seed=False): | if random_seed is not False:<EOL><INDENT>state = np.random.get_state()<EOL>np.random.seed(random_seed)<EOL><DEDENT>if threads is None:<EOL><INDENT>threads = nestcheck.ns_run_utils.get_run_threads(ns_run)<EOL><DEDENT>n_threads = len(threads)<EOL>if ninit_sep:<EOL><INDENT>try:<EOL><INDENT>ninit = ns_run['<STR_LIT>']['<ST... | 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... | f15357:m0 |
def run_std_bootstrap(ns_run, estimator_list, **kwargs): | bs_values = run_bootstrap_values(ns_run, estimator_list, **kwargs)<EOL>stds = np.zeros(bs_values.shape[<NUM_LIT:0>])<EOL>for j, _ in enumerate(stds):<EOL><INDENT>stds[j] = np.std(bs_values[j, :], ddof=<NUM_LIT:1>)<EOL><DEDENT>return stds<EOL> | 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 parameter estimat... | f15357:m1 |
def run_bootstrap_values(ns_run, estimator_list, **kwargs): | ninit_sep = kwargs.pop('<STR_LIT>', False)<EOL>flip_skew = kwargs.pop('<STR_LIT>', True)<EOL>n_simulate = kwargs.pop('<STR_LIT>') <EOL>random_seeds = kwargs.pop('<STR_LIT>', range(n_simulate))<EOL>assert len(random_seeds) == n_simulate<EOL>if kwargs:<EOL><INDENT>raise TypeError('<STR_LIT>'.format(kwargs))<EOL><DEDENT>... | 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... | f15357:m2 |
def run_ci_bootstrap(ns_run, estimator_list, **kwargs): | cred_int = kwargs.pop('<STR_LIT>') <EOL>bs_values = run_bootstrap_values(ns_run, estimator_list, **kwargs)<EOL>expected_estimators = nestcheck.ns_run_utils.run_estimators(<EOL>ns_run, estimator_list)<EOL>cdf = ((np.asarray(range(bs_values.shape[<NUM_LIT:1>])) + <NUM_LIT:0.5>) /<EOL>bs_values.shape[<NUM_LIT:1>])<EOL>c... | 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... | f15357:m3 |
def run_std_simulate(ns_run, estimator_list, n_simulate=None): | assert n_simulate is not None, '<STR_LIT>'<EOL>all_values = np.zeros((len(estimator_list), n_simulate))<EOL>for i in range(n_simulate):<EOL><INDENT>all_values[:, i] = nestcheck.ns_run_utils.run_estimators(<EOL>ns_run, estimator_list, simulate=True)<EOL><DEDENT>stds = np.zeros(all_values.shape[<NUM_LIT:0>])<EOL>for 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... | f15357:m4 |
def implementation_std(vals_std, vals_std_u, bs_std, bs_std_u, **kwargs): | nsim = kwargs.pop('<STR_LIT>', <NUM_LIT>)<EOL>random_seed = kwargs.pop('<STR_LIT>', <NUM_LIT:0>)<EOL>if kwargs:<EOL><INDENT>raise TypeError('<STR_LIT>'.format(kwargs))<EOL><DEDENT>imp_var = (vals_std ** <NUM_LIT:2>) - (bs_std ** <NUM_LIT:2>)<EOL>imp_std = np.sqrt(np.abs(imp_var)) * np.sign(imp_var)<EOL>ind = np.where(i... | 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 ... | f15357:m5 |
def run_thread_values(run, estimator_list): | threads = nestcheck.ns_run_utils.get_run_threads(run)<EOL>vals_list = [nestcheck.ns_run_utils.run_estimators(th, estimator_list)<EOL>for th in threads]<EOL>vals_array = np.stack(vals_list, axis=<NUM_LIT:1>)<EOL>assert vals_array.shape == (len(estimator_list), len(threads))<EOL>return vals_array<EOL> | 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)... | f15357:m6 |
def pairwise_distances(dist_list, earth_mover_dist=True, energy_dist=True): | out = []<EOL>index = []<EOL>for i, samp_i in enumerate(dist_list):<EOL><INDENT>for j, samp_j in enumerate(dist_list):<EOL><INDENT>if j < i:<EOL><INDENT>index.append(str((i, j)))<EOL>out.append(statistical_distances(<EOL>samp_i, samp_j, earth_mover_dist=earth_mover_dist,<EOL>energy_dist=energy_dist))<EOL><DEDENT><DEDENT... | 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
... | f15357:m7 |
def statistical_distances(samples1, samples2, earth_mover_dist=True,<EOL>energy_dist=True): | out = []<EOL>temp = scipy.stats.ks_2samp(samples1, samples2)<EOL>out.append(temp.pvalue)<EOL>out.append(temp.statistic)<EOL>if earth_mover_dist:<EOL><INDENT>out.append(scipy.stats.wasserstein_distance(samples1, samples2))<EOL><DEDENT>if energy_dist:<EOL><INDENT>out.append(scipy.stats.energy_distance(samples1, samples2)... | 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... | f15357:m8 |
def update_results(self, results): | if not results:<EOL><INDENT>raise PickerResultException('<STR_LIT>')<EOL><DEDENT>if results['<STR_LIT>'] != self.sequence or results['<STR_LIT>'] != self.season:<EOL><INDENT>raise PickerResultException('<STR_LIT>')<EOL><DEDENT>completed = {g['<STR_LIT>']: g for g in results['<STR_LIT>'] if g['<STR_LIT:status>'].startsw... | results schema: {'sequence': 1, 'season': 2018, 'games': [{
"home": "HOME",
"away": "AWAY",
"home_score": 15,
"away_score": 10,
"status": "Final",
"winner": "HOME",
}]} | f15389:c9:m13 |
def update_picks(self, games=None, points=None): | if games:<EOL><INDENT>game_dict = {g.id: g for g in self.gameset.games.filter(id__in=games)}<EOL>game_picks = {pick.game.id: pick for pick in self.gamepicks.filter(game__id__in=games)}<EOL>for key, winner in games.items():<EOL><INDENT>game = game_dict[key]<EOL>if not game.has_started:<EOL><INDENT>pick = game_picks[key]... | games can be dict of {game.id: winner_id} for all picked games to update | f15389:c11:m7 |
@task<EOL>def clean(ctx): | rmdb(ctx)<EOL>ctx.run('<STR_LIT>')<EOL> | Remove build artifacts | f15406:m1 |
@task<EOL>def install(ctx): | ctx.run('<STR_LIT>', pty=True)<EOL> | Install base requirements | f15406:m2 |
@task<EOL>def demo(ctx, reset=False): | if reset:<EOL><INDENT>rmdb(ctx)<EOL><DEDENT>ctx.run('<STR_LIT>', pty=True)<EOL>ctx.run('<STR_LIT>', pty=True)<EOL>ctx.run('<STR_LIT>', pty=True)<EOL> | Set up the demo environment and run the server | f15406:m4 |
@task<EOL>def check(ctx): | ctx.run('<STR_LIT>')<EOL> | Run PEP8 checks | f15406:m5 |
def __init__(<EOL>self, name=None, bases=None, _dict=None, update=True,<EOL>*args, **kwargs<EOL>): | super(Transform, self).__init__(*args, **kwargs)<EOL>self.name = name<EOL>self.bases = (Annotation,) if bases is None else bases<EOL>self.dict = {} if _dict is None else _dict<EOL>self.update = update<EOL> | According to type constructor parameters, you can specifiy name,
bases and dict.
:param str name: new class name.
:param tuple bases: new class bases.
:param dict dict: class __dict__.
:param bool update: if True, update new properties on the new class.
Otherwise rep... | f15409:c0:m0 |
@staticmethod<EOL><INDENT>def mixin_class(target, cls):<DEDENT> | for name, field in getmembers(cls):<EOL><INDENT>Mixin.mixin(target, field, name)<EOL><DEDENT> | Mix cls content in target. | f15409:c1:m2 |
@staticmethod<EOL><INDENT>def mixin_function_or_method(target, routine, name=None, isbound=False):<DEDENT> | function = None<EOL>if isfunction(routine):<EOL><INDENT>function = routine<EOL><DEDENT>elif ismethod(routine):<EOL><INDENT>function = get_method_function(routine)<EOL><DEDENT>else:<EOL><INDENT>raise Mixin.MixInError(<EOL>"<STR_LIT>".format(routine))<EOL><DEDENT>if name is None:<EOL><INDENT>name = routine.__name__<EOL><... | Mixin a routine into the target.
:param routine: routine to mix in target.
:param str name: mixin name. Routine name by default.
:param bool isbound: If True (False by default), the mixin result is a
bound method to target. | f15409:c1:m3 |
@staticmethod<EOL><INDENT>def mixin(target, resource, name=None):<DEDENT> | result = None<EOL>if ismethod(resource) or isfunction(resource):<EOL><INDENT>result = Mixin.mixin_function_or_method(target, resource, name)<EOL><DEDENT>elif isclass(resource):<EOL><INDENT>result = list()<EOL>for name, content in getmembers(resource):<EOL><INDENT>if isclass(content):<EOL><INDENT>mixin = Mixin.set_mixin... | Do the correct mixin depending on the type of input resource.
- Method or Function: mixin_function_or_method.
- class: mixin_class.
- other: set_mixin.
And returns the result of the choosen method (one or a list of mixins). | f15409:c1:m4 |
@staticmethod<EOL><INDENT>def get_mixedins_by_name(target):<DEDENT> | result = getattr(target, Mixin.__MIXEDIN_KEY__, None)<EOL>if result is None:<EOL><INDENT>result = dict()<EOL>setattr(target, Mixin.__MIXEDIN_KEY__, result)<EOL><DEDENT>return result<EOL> | Get a set of couple (name, field) of target mixedin. | f15409:c1:m5 |
@staticmethod<EOL><INDENT>def set_mixin(target, resource, name=None, override=True):<DEDENT> | if name is None and not hasattr(resource, '<STR_LIT>'):<EOL><INDENT>raise Mixin.MixInError(<EOL>"<STR_LIT>"<EOL>.format(resource))<EOL><DEDENT>result = None<EOL>name = resource.__name__ if name is None else name<EOL>mixedins_by_name = Mixin.get_mixedins_by_name(target)<EOL>result = getattr(target, name, Mixin.__NEW_CON... | Set a resource and returns the mixed one in target content or
Mixin.__NEW_CONTENT_KEY__ if resource name didn't exist in target.
:param str name: target content item to mix with the resource.
:param bool override: If True (default) permits to replace an old
resource by the new one. | f15409:c1:m6 |
@staticmethod<EOL><INDENT>def remove_mixin(target, name, mixedin=None, replace=True):<DEDENT> | try:<EOL><INDENT>result = getattr(target, name)<EOL><DEDENT>except AttributeError:<EOL><INDENT>raise Mixin.MixInError(<EOL>"<STR_LIT>".format(name, target)<EOL>)<EOL><DEDENT>mixedins_by_name = Mixin.get_mixedins_by_name(target)<EOL>mixedins = mixedins_by_name.get(name)<EOL>if mixedins:<EOL><INDENT>if mixedin is None:<E... | Remove a mixin with name (and reference) from targetand returns the
replaced one or None.
:param mixedin: a mixedin value or the last defined mixedin if is None
(by default).
:param bool replace: If True (default), the removed mixedin replaces
the current mixin. | f15409:c1:m7 |
@staticmethod<EOL><INDENT>def remove_mixins(target):<DEDENT> | mixedins_by_name = Mixin.get_mixedins_by_name(target).copy()<EOL>for _name in mixedins_by_name: <EOL><INDENT>while True: <EOL><INDENT>try:<EOL><INDENT>Mixin.remove_mixin(target, _name)<EOL><DEDENT>except Mixin.MixInError:<EOL><INDENT>break<EOL><DEDENT><DEDENT><DEDENT> | Tries to get back target in a no mixin consistent state. | f15409:c1:m8 |
def setUp(self): | self.annotation = Annotation()<EOL> | Create a new annotation. | f15412:c1:m0 |
def tearDown(self): | self.annotation.__del__()<EOL>del self.annotation<EOL> | Delete self.annotation. | f15412:c1:m1 |
def tearDown(self): | self.interceptor.__del__()<EOL>del self.interceptor<EOL> | Delete self.interceptor | f15413:c0:m4 |
def call_target(self): | self.target()<EOL> | Call target. | f15413:c1:m2 |
def _threaded(self, *args, **kwargs): | for target in self.targets:<EOL><INDENT>result = target(*args, **kwargs)<EOL>self.queue.put(result)<EOL><DEDENT> | Call the target and put the result in the Queue. | f15415:c2:m1 |
def start(self, *args, **kwargs): | self.queue = Queue()<EOL>thread = Thread(target=self._threaded, args=args, kwargs=kwargs)<EOL>thread.start()<EOL>return Asynchronous.Result(self.queue, thread)<EOL> | Start execution of the function. | f15415:c2:m3 |
def _handle_timeout(self, frame=None, **_): | raise TimeOut.TimeOutError(self, frame)<EOL> | Sig ALARM timeout function. | f15415:c3:m1 |
def register_observer(self, observer): | self.observers.add(observer)<EOL> | Register an observer. | f15415:c5:m1 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.