Samples

chain

class desilike.samples.chain.Chain(data=None, params=None, logposterior=None, loglikelihood=None, logprior=None, aweight=None, fweight=None, weight=None, attrs=None)[source]

Bases: Samples

Class that holds samples drawn from posterior (in practice, Samples with a log-posterior and optional weights).

Parameter arrays can be accessed (and updated) as for a dictionary:

chain = Chain([np.ones(100), np.zeros(100)], params=['a', 'b'])
chain['a'] += 1.
print(chain['a'].mean())

chain['c'] = chain['b'] + 1
chain['c'].param.update(latex='c')

Initialize Chain.

Parameters:
  • data (list, dict, Samples) – Can be:

    • list of ParameterArray, or np.ndarray if list of parameters (or ParameterCollection) is provided in params

    • dictionary mapping parameter to array

  • params (list, ParameterCollection) – Optionally, list of parameters.

  • logposterior (str, default=’logposterior’) – Name of log-posterior in data.

  • loglikelihood (str, default=’loglikelihood’) – Name of log-likelihood in data.

  • logprior (str, default=’logprior’) – Name of log-prior in data.

  • aweight (str, default=’aweight’) – Name of sample weights (which default to 1. if not provided in data).

  • fweight (str, default=’fweight’) – Name of sample frequency weights (which default to 1 if not provided in data).

  • weight (str, default=’weight’) – Name of sample total weight. It is defined as the product of aweight and fweight, hence should not provided in data.

  • attrs (dict, default=None) – Optionally, other attributes, stored in attrs.

argmax(params=None)[source]

Return parameter values for maximum of log-posterior (optionally restricted to input parameters). If a single parameter is given as input and this parameter is a scalar, return a scalar.

property aweight

Sample weights (floats).

basenames(**kwargs)

Return base parameter names in collection.

classmethod bcast(value, mpicomm=None, mpiroot=0)

Broadcast input samples value from rank mpiroot to other processes.

choice(index='mean', params=None, return_type='dict', **kwargs)[source]

Return parameter mean(s) or best fit(s).

Parameters:
  • index (str, default=’mean’) – ‘argmax’ to return “best fit” (as defined by the point with maximum log-posterior in the chain). ‘mean’ to return mean of parameters (weighted by weight).

  • params (list, ParameterCollection, default=None) – Parameters to compute mean / best fit for. Defaults to all parameters.

  • return_type (default=’dict’) – ‘dict’ to return a dictionary mapping parameter names to mean / best fit; ‘nparray’ to return an array of parameter mean / best fit; None to return a Chain instance with a single value.

  • **kwargs (dict) – Optional arguments passed to params() to select params to return, e.g. varied=True, derived=False.

Returns:

toret

Return type:

dict, array, Chain

clear()

Empty collection.

clone(*args, **kwargs)

Clone collection, i.e. (shallow) copy and update.

classmethod concatenate(*others, intersection=False)

Concatenate input samples, which requires all samples to hold same parameters, except if intersection == True, in which case common parameters are selected.

corrcoef(params=None)[source]

Return correlation matrix array computed from (weighted) samples (optionally restricted to input parameters).

covariance(params=None, return_type='nparray', ddof=1)[source]

Return parameter covariance computed from (weighted) samples.

Parameters:
  • params (list, ParameterCollection, default=None) – Parameters to compute covariance for. Defaults to all parameters. If a single parameter is provided, this parameter is a scalar, and return_type is ‘nparray’, return a scalar.

  • return_type (str, default=’nparray’) – ‘nparray’ to return matrix array; None to return ParameterCovariance instance.

  • ddof (int, default=1) – Number of degrees of freedom.

Returns:

covariance

Return type:

array, float, ParameterCovariance

deepcopy()

Deep copy.

extend(other)

Extend collection with other. Unique items only are kept.

classmethod from_getdist(samples, concatenate=None)[source]

Turn getdist.MCSamples into a Chain instance.

Note

GetDist package is required.

property fweight

Sample frequency weights (integers).

get(name, *args, **kwargs)

Return item of parameter name name in collection.

Parameters:

name (Parameter, str) – Parameter name. If Parameter instance, search for parameter with same name.

index(name)

Return index of parameter name.

Parameters:

name (Parameter, str, int) – Parameter name. If Parameter instance, search for parameter with same name. If integer, index in collection.

Returns:

index

Return type:

int

interval(params=None, nsigmas=1.0)[source]

Return n-sigma confidence interval(s).

Parameters:
  • params (list, ParameterCollection, default=None) – Parameters to compute confidence interval for. Defaults to all parameters.

  • nsigmas (int) – Return interval for this number of sigmas.

Returns:

interval

Return type:

tuple, list

items(**kwargs)

Return list of tuples (parameter name, item).

keys(**kwargs)

Return parameter names.

classmethod load(filename)

Load samples from disk.

property logposterior

Log-posterior.

match(other, eps=1e-07, params=None)

Match other Samples against self, for parameters params.

Parameters:
  • other (Samples) – Samples to match.

  • eps (float, default=1e-7) – Distance upper bound above which samples are not considered equal. 1e-7 to handle float32/float64 conversions.

  • params (ParameterCollection, list, default=None) – Parameters to use. Defaults to all parameters that are not derived.

Return type:

index_in_other, index_in_self

mean(params=None)[source]

Return mean computed from (weighted) samples (optionally restricted to input parameters). If a single parameter is given as input and this parameter is a scalar, return a scalar.

median(params=None, method='linear')[source]

Return parameter median of weighted parameter samples (optionally restricted to input parameters). If a single parameter is given as input and this parameter is a scalar, return a scalar.

names(**kwargs)

Return parameter names in collection.

property ndim

Number of dimensions.

params(**kwargs)

Return ParameterCollection, collection of parameters corresponding to items stored in this collection.

pop(name, *args, **kwargs)

Remove and return item indexed by name.

precision(params=None, return_type='nparray', ddof=1)[source]

Return inverse parameter covariance computed from (weighted) samples.

Parameters:
  • params (list, ParameterCollection, default=None) – Parameters to compute covariance for. Defaults to all parameters. If a single parameter is provided, this parameter is a scalar, and return_type is ‘nparray’, return a scalar.

  • return_type (str, default=’nparray’) – ‘nparray’ to return matrix array. None to return a ParameterPrecision instance.

  • ddof (int, default=1) – Number of degrees of freedom.

Returns:

precision

Return type:

array, float, ParameterPrecision

quantile(params=None, q=(0.1587, 0.8413), method='linear')[source]

Compute the q-th quantile of the weighted parameter samples. If a single parameter is given as input this parameter is a scalar, and a q is a scalar, return a scalar.

Parameters:
  • params (list, ParameterCollection, default=None) – Parameters to compute quantiles for. Defaults to all parameters.

  • q (tuple, list, array) – Quantile or sequence of quantiles to compute, which must be between 0 and 1 inclusive.

  • method ({‘linear’, ‘lower’, ‘higher’, ‘midpoint’, ‘nearest’}, default=’linear’) – This optional parameter specifies the method method to use when the desired quantile lies between two data points i < j:

    • linear: i + (j - i) * fraction, where fraction is the fractional part of the index surrounded by i and j.

    • lower: i.

    • higher: j.

    • nearest: i or j, whichever is nearest.

    • midpoint: (i + j) / 2.

Returns:

quantiles

Return type:

list, scalar, array

ravel()

Flatten samples.

classmethod read_getdist(base_fn, ichains=None, concatenate=False)[source]

Load samples in CosmoMC format, i.e.:

  • ‘_{ichain}.txt’ files for sample values

  • ‘.paramnames’ files for parameter names / latex

  • ‘.ranges’ for parameter ranges

Note

GetDist package is not required.

Parameters:
  • base_fn (str, Path) – Base CosmoMC file name. Will be appended by ‘_{ichain}.txt’ for sample values, ‘.paramnames’ for parameter names and ‘.ranges’ for parameter ranges.

  • ichains (int, tuple, list, default=None) – Chain numbers to load. Defaults to all chains matching pattern ‘{base_fn}*.txt’. If a single number is provided, return a unique chain. If multiple numbers are provided, or is None, return a list of chains (see concatenate).

  • concatenate (bool, default=False) – If True, concatenate all chains in one.

Returns:

samples – Chain or list of chains.

Return type:

list, Chain

classmethod recv(source=mpi4py.MPI.ANY_SOURCE, tag=mpi4py.MPI.ANY_TAG, mpicomm=None)

Receive samples from rank source.

remove_burnin(burnin=0)[source]

Return new samples with burn-in removed.

Parameters:

burnin (float, int) – If burnin between 0 and 1, remove that fraction of samples. Else, remove burnin (integer) first points.

Returns:

samples

Return type:

Chain

reshape(*args)

Reshape samples (with shallow copy).

sample_solved(size=1, seed=42)[source]

Sample parameters that have been analytic marginalized over (solved).

save(filename)

Save samples to disk.

select(**kwargs)[source]

Return new collection, after selection of parameters whose attribute match input values:

collection.select(fixed=True)

returns collection of fixed parameters. If ‘name’ is provided, consider all matching parameters, e.g.:

collection.select(varied=True, name='a_[0:2]')

returns a collection of varied parameters, with name in ['a_0', 'a_1'].

send(dest, tag=0, mpicomm=None)

Send self to rank dest.

classmethod sendrecv(value, source=0, dest=0, tag=0, mpicomm=None)

Send samples from rank source to rank dest and receive them here.

set(item)

Add new ParameterArray to samples.

set_derived(basename, array, **kwargs)[source]

Set derived parameter.

Parameters:
  • array (np.array) – Numpy array.

  • kwargs (dict) – Arguments for Parameter.

setdefault(item)

Set item in collection if not already in it.

property shape

Shape of samples.

property size

Total number of samples.

sort(key=None)

Sort (in-place) collection, such that if follows the list of parameter names key. If None, no sorting is performed.

std(params=None, ddof=1)[source]

Return standard deviation computed from (weighted) samples (optionally restricted to input parameters). If a single parameter is given as input and this parameter is a scalar, return a scalar. ddof is the number of degrees of freedom.

to_anesthetic(params=None, label=None, **kwargs)[source]

Return anesthetic hook to samples.

Note

anesthetic package is required.

Parameters:
  • params (list, ParameterCollection, default=None) – Parameters to save samples of (weight and log-posterior are added anyway). Defaults to all parameters.

  • label (str, default=None) – Name for anesthetic to use for these samples.

  • **kwargs (dict) – Optional arguments for anesthetic.MCMCSamples.

Returns:

samples

Return type:

anesthetic.MCMCSamples

to_array(params=None, struct=True, derivs=None)

Return samples as numpy array.

Parameters:
  • params (ParameterCollection, list, default=None) – Parameters to use. Defaults to all parameters.

  • struct (bool, default=True) – Whether to return structured array, with columns accessible through e.g. array['x']. If False, numpy will attempt to cast types of different columns.

Returns:

array

Return type:

array

to_dict(params=None)

Return samples as a dictionary.

Parameters:

params (ParameterCollection, list, default=None) – Parameters to use. Defaults to all parameters.

Returns:

dict – Dictionary mapping parameter name to array.

Return type:

dict

to_fisher(params=None, ddof=1, **kwargs)[source]

Return Fisher from (weighted) samples.

Parameters:
  • params (list, ParameterCollection, default=None) – Parameters to return Fisher for. Defaults to all parameters.

  • ddof (int, default=1) – Number of degrees of freedom.

  • **kwargs (dict) – Arguments for choice(), giving the mean of the output Fisher likelihood.

Returns:

fisher

Return type:

LikelihoodFisher

to_getdist(chain, params=None, label=None, **kwargs)[source]

Return GetDist hook to samples.

Note

GetDist package is required.

Parameters:
  • params (list, ParameterCollection, default=None) – Parameters to save samples of (weight and log-posterior are added anyway). Defaults to all parameters.

  • label (str, default=None) – Name for GetDist to use for these samples.

  • **kwargs (dict) – Optional arguments for getdist.MCSamples.

Returns:

samples

Return type:

getdist.MCSamples

to_stats(params=None, quantities=None, sigfigs=2, tablefmt='latex_raw', fn=None)[source]

Export summary sampling quantities.

Parameters:
  • params (list, ParameterCollection, default=None) – Parameters to export quantities for. Defaults to all parameters.

  • quantities (list, default=None) – Quantities to export. Defaults to ['argmax', 'mean', 'median', 'std', 'quantile:1sigma', 'interval:1sigma'].

  • sigfigs (int, default=2) – Number of significant digits. See utils.round_measurement().

  • tablefmt (str, default=’latex_raw’) – Format for summary table. See tabulate.tabulate(). If ‘list’, return table as list of list of strings, and headers. If ‘list_latex’, return table as list of list of latex strings, and headers.

  • fn (str, default=None) – If not None, file name where to save summary table.

Returns:

tab – Summary table.

Return type:

str

update(*args, **kwargs)

Update samples with new one; arguments can be a Samples or arguments to instantiate such a class (see __init__()).

values(**kwargs)

Return items.

var(params=None, ddof=1)[source]

Return variance computed from (weighted) samples (optionally restricted to input parameters). If a single parameter is given as input and this parameter is a scalar, return a scalar. ddof is the number of degrees of freedom.

property weight

Return total weight, as the product of aweight and fweight.

write_getdist(chain, base_fn, params=None, ichain=None, fmt='%.18e', delimiter=' ', **kwargs)[source]

Save samples to disk in CosmoMC format.

Note

GetDist package is not required.

Parameters:
  • base_fn (str, Path) – Base CosmoMC file name. Will be prepended by ‘_{ichain}.txt’ for sample values, ‘.paramnames’ for parameter names and ‘.ranges’ for parameter ranges.

  • params (list, ParameterCollection, default=None) – Parameters to save samples of (weight and log-posterior are added anyway). Defaults to all parameters.

  • ichain (int, default=None) – Chain number to append to file name, i.e. sample values will be saved as ‘{base_fn}_{ichain}.txt’. If None, does not append any number, sample values will be saved as ‘{base_fn}.txt’.

  • fmt (str, default=’%.18e’) – How to format floats.

  • delimiter (str, default=’ ‘) – String or character separating columns.

  • kwargs (dict) – Optional arguments for numpy.savetxt().

desilike.samples.chain.vectorize(func)[source]

Vectorize input function func for input parameters.

profiles

Definition of Profiles, to hold products of likelihood profiling.

class desilike.samples.profiles.MetaClass(name, bases, class_dict)[source]

Bases: BaseMetaClass, ABCMeta

mro()

Return a type’s method resolution order.

register(subclass)

Register a virtual subclass of an ABC.

Returns the subclass, to allow usage as a class decorator.

set_logger()

Add attributes for logging:

  • logger

  • methods log_debug, log_info, log_warning, log_error, log_critical

class desilike.samples.profiles.ParameterBestFit(*args, logposterior=None, loglikelihood=None, logprior=None, **kwargs)[source]

Bases: Samples

Class holding parameter best fits (in practice, Samples with a log-posterior).

Parameter arrays can be accessed (and updated) as for a dictionary:

bestfit = ParameterBestFit([np.ones(10), np.zeros(10), np.linspace(0., 1., 10)], params=['a', 'b', 'logposterior'])
di = bestfit.choice(index='argmax')  # dictionary of parameter values for best fit with larger log-posterior.
index = bestfit.logposterior.argmax()
assert {param.name: bestfit[param][index] for param in bestfit.params()} == di

Initialize ParameterBestFit.

Parameters:
  • data (list, dict, Samples) – Can be:

    • list of ParameterArray, or np.ndarray if list of parameters (or ParameterCollection) is provided in params

    • dictionary mapping parameter to array

  • params (list, ParameterCollection) – Optionally, list of parameters.

  • logposterior (str, default=’logposterior’) – Name of log-posterior in data.

  • loglikelihood (str, default=’loglikelihood’) – Name of log-likelihood in data.

  • logprior (str, default=’logprior’) – Name of log-prior in data.

  • attrs (dict, default=None) – Optionally, other attributes, stored in attrs.

basenames(**kwargs)

Return base parameter names in collection.

classmethod bcast(value, mpicomm=None, mpiroot=0)

Broadcast input samples value from rank mpiroot to other processes.

property chi2min

Minimum \(\chi^{2}\) (= -2 * logposterior.max())

choice(index='argmax', params=None, return_type='dict', **kwargs)[source]

Return parameter best fit(s).

Parameters:
  • index (str, default=’argmax’) – ‘argmax’ to return best fit (as defined by the point with maximum log-posterior in the samples).

  • params (list, ParameterCollection, default=None) – Parameters to compute best fit for. Defaults to all parameters.

  • return_dict (default=’dict’) – ‘dict’ to return a dictionary mapping parameter names to best fit; ‘nparray’ to return an array of parameter best fits; None to return a ParameterBestFit instance with a single value.

  • **kwargs (dict) – Optional arguments passed to params() to select params to return, e.g. varied=True, derived=False.

Returns:

toret

Return type:

dict, array, ParameterBestFit

clear()

Empty collection.

clone(*args, **kwargs)

Clone collection, i.e. (shallow) copy and update.

classmethod concatenate(*others, intersection=False)

Concatenate input samples, which requires all samples to hold same parameters, except if intersection == True, in which case common parameters are selected.

deepcopy()

Deep copy.

extend(other)

Extend collection with other. Unique items only are kept.

get(name, *args, **kwargs)

Return item of parameter name name in collection.

Parameters:

name (Parameter, str) – Parameter name. If Parameter instance, search for parameter with same name.

index(name)

Return index of parameter name.

Parameters:

name (Parameter, str, int) – Parameter name. If Parameter instance, search for parameter with same name. If integer, index in collection.

Returns:

index

Return type:

int

items(**kwargs)

Return list of tuples (parameter name, item).

keys(**kwargs)

Return parameter names.

classmethod load(filename)

Load samples from disk.

property logposterior

Log-posterior.

match(other, eps=1e-07, params=None)

Match other Samples against self, for parameters params.

Parameters:
  • other (Samples) – Samples to match.

  • eps (float, default=1e-7) – Distance upper bound above which samples are not considered equal. 1e-7 to handle float32/float64 conversions.

  • params (ParameterCollection, list, default=None) – Parameters to use. Defaults to all parameters that are not derived.

Return type:

index_in_other, index_in_self

names(**kwargs)

Return parameter names in collection.

property ndim

Number of dimensions.

params(**kwargs)

Return ParameterCollection, collection of parameters corresponding to items stored in this collection.

pop(name, *args, **kwargs)

Remove and return item indexed by name.

ravel()

Flatten samples.

classmethod recv(source=mpi4py.MPI.ANY_SOURCE, tag=mpi4py.MPI.ANY_TAG, mpicomm=None)

Receive samples from rank source.

reshape(*args)

Reshape samples (with shallow copy).

save(filename)

Save samples to disk.

select(**kwargs)

Return new collection, after selection of parameters whose attribute match input values:

collection.select(fixed=True)

returns collection of fixed parameters. If ‘name’ is provided, consider all matching parameters, e.g.:

collection.select(varied=True, name='a_[0:2]')

returns a collection of varied parameters, with name in ['a_0', 'a_1'].

send(dest, tag=0, mpicomm=None)

Send self to rank dest.

classmethod sendrecv(value, source=0, dest=0, tag=0, mpicomm=None)

Send samples from rank source to rank dest and receive them here.

set(item)

Add new ParameterArray to samples.

setdefault(item)

Set item in collection if not already in it.

property shape

Shape of samples.

property size

Total number of samples.

sort(key=None)

Sort (in-place) collection, such that if follows the list of parameter names key. If None, no sorting is performed.

to_array(params=None, struct=True, derivs=None)

Return samples as numpy array.

Parameters:
  • params (ParameterCollection, list, default=None) – Parameters to use. Defaults to all parameters.

  • struct (bool, default=True) – Whether to return structured array, with columns accessible through e.g. array['x']. If False, numpy will attempt to cast types of different columns.

Returns:

array

Return type:

array

to_dict(params=None)

Return samples as a dictionary.

Parameters:

params (ParameterCollection, list, default=None) – Parameters to use. Defaults to all parameters.

Returns:

dict – Dictionary mapping parameter name to array.

Return type:

dict

update(*args, **kwargs)

Update samples with new one; arguments can be a Samples or arguments to instantiate such a class (see __init__()).

values(**kwargs)

Return items.

class desilike.samples.profiles.ParameterContour(data=None, params=None, attrs=None)[source]

Bases: BaseParameterCollection

Class holding parameter 2D contours (in practice, BaseParameterCollection indexed by two parameters).

Initialize ParameterContours.

Parameters:
  • data (list, dict, ParameterContours) – Can be:

    • list of tuples of arrays if list of parameters (or ParameterCollection) is provided in params

    • dictionary mapping tuple of parameters to tuple of arrays

  • params (list, ParameterCollection) – Optionally, list of tuple of parameters.

  • attrs (dict, default=None) – Optionally, other attributes, stored in attrs.

basenames(**kwargs)[source]

Return tuple of base parameter names in collection.

classmethod bcast(value, mpicomm=None, mpiroot=0)[source]

Broadcast input contours value from rank mpiroot to other processes.

clear()

Empty collection.

clone(*args, **kwargs)

Clone collection, i.e. (shallow) copy and update.

classmethod concatenate(*others)

Concatenate input collections. Unique items only are kept.

deepcopy()

Deep copy.

extend(other)

Extend collection with other. Unique items only are kept.

get(name, *args, **kwargs)

Return item of parameter name name in collection.

Parameters:

name (Parameter, str) – Parameter name. If Parameter instance, search for parameter with same name.

index(name)

Return index of parameter name.

Parameters:

name (Parameter, str, int) – Parameter name. If Parameter instance, search for parameter with same name. If integer, index in collection.

Returns:

index

Return type:

int

interpolate(size=100)[source]

Cubic spline interpolation.

Parameters:

size (int, default=100) – Number of points.

items(**kwargs)

Return list of tuples (parameter name, item).

keys(**kwargs)

Return parameter names.

names(**kwargs)[source]

Return tuple of parameter names in collection.

params(**kwargs)[source]

Return tuple of parameters.

pop(name, *args, **kwargs)

Remove and return item indexed by name.

classmethod recv(source=mpi4py.MPI.ANY_SOURCE, tag=mpi4py.MPI.ANY_TAG, mpicomm=None)[source]

Receive contours from rank source.

select(**kwargs)

Return new collection, after selection of parameters whose attribute match input values:

collection.select(fixed=True)

returns collection of fixed parameters. If ‘name’ is provided, consider all matching parameters, e.g.:

collection.select(varied=True, name='a_[0:2]')

returns a collection of varied parameters, with name in ['a_0', 'a_1'].

send(dest, tag=0, mpicomm=None)[source]

Send self to rank dest.

classmethod sendrecv(value, source=0, dest=0, tag=0, mpicomm=None)[source]

Send samples from rank source to rank dest and receive them here.

set(item)

Set item in collection. If there is already a parameter with same name in collection, replace this stored item by the input one. Else, append item to collection.

setdefault(item)[source]

Set parameter contour in collection if not already in it.

sort(key=None)

Sort (in-place) collection, such that if follows the list of parameter names key. If None, no sorting is performed.

update(*args, **kwargs)

Update collection with new one; arguments can be a BaseParameterCollection or arguments to instantiate such a class (see __init__()).

values(**kwargs)

Return items.

class desilike.samples.profiles.ParameterContours(data=None, **kwargs)[source]

Bases: BaseClass, UserDict

classmethod bcast(value, mpicomm=None, mpiroot=0)[source]

Broadcast input contours value from rank mpiroot to other processes.

clear() None.  Remove all items from D.
clone(*args, **kwargs)[source]

Clone, i.e. copy and optionally update.

deepcopy()[source]

Return a deep copy.

get(k[, d]) D[k] if k in D, else d.  d defaults to None.
interpolate(size=100)[source]

Cubic spline interpolation.

Parameters:

size (int, default=100) – Number of points.

items() a set-like object providing a view on D's items
keys() a set-like object providing a view on D's keys
pop(k[, d]) v, remove specified key and return the corresponding value.

If key is not found, d is returned if given, otherwise KeyError is raised.

popitem() (k, v), remove and return some (key, value) pair

as a 2-tuple; but raise KeyError if D is empty.

setdefault(k[, d]) D.get(k,d), also set D[k]=d if k not in D
update(other)[source]

Update contours.

values() an object providing a view on D's values
class desilike.samples.profiles.ParameterGrid(*args, logposterior=None, loglikelihood=None, logprior=None, **kwargs)[source]

Bases: ParameterBestFit

Initialize ParameterBestFit.

Parameters:
  • data (list, dict, Samples) – Can be:

    • list of ParameterArray, or np.ndarray if list of parameters (or ParameterCollection) is provided in params

    • dictionary mapping parameter to array

  • params (list, ParameterCollection) – Optionally, list of parameters.

  • logposterior (str, default=’logposterior’) – Name of log-posterior in data.

  • loglikelihood (str, default=’loglikelihood’) – Name of log-likelihood in data.

  • logprior (str, default=’logprior’) – Name of log-prior in data.

  • attrs (dict, default=None) – Optionally, other attributes, stored in attrs.

basenames(**kwargs)

Return base parameter names in collection.

classmethod bcast(value, mpicomm=None, mpiroot=0)

Broadcast input samples value from rank mpiroot to other processes.

property chi2min

Minimum \(\chi^{2}\) (= -2 * logposterior.max())

choice(index='argmax', params=None, return_type='dict', **kwargs)

Return parameter best fit(s).

Parameters:
  • index (str, default=’argmax’) – ‘argmax’ to return best fit (as defined by the point with maximum log-posterior in the samples).

  • params (list, ParameterCollection, default=None) – Parameters to compute best fit for. Defaults to all parameters.

  • return_dict (default=’dict’) – ‘dict’ to return a dictionary mapping parameter names to best fit; ‘nparray’ to return an array of parameter best fits; None to return a ParameterBestFit instance with a single value.

  • **kwargs (dict) – Optional arguments passed to params() to select params to return, e.g. varied=True, derived=False.

Returns:

toret

Return type:

dict, array, ParameterBestFit

clear()

Empty collection.

clone(*args, **kwargs)

Clone collection, i.e. (shallow) copy and update.

classmethod concatenate(*others, intersection=False)

Concatenate input samples, which requires all samples to hold same parameters, except if intersection == True, in which case common parameters are selected.

deepcopy()

Deep copy.

extend(other)

Extend collection with other. Unique items only are kept.

get(name, *args, **kwargs)

Return item of parameter name name in collection.

Parameters:

name (Parameter, str) – Parameter name. If Parameter instance, search for parameter with same name.

index(name)

Return index of parameter name.

Parameters:

name (Parameter, str, int) – Parameter name. If Parameter instance, search for parameter with same name. If integer, index in collection.

Returns:

index

Return type:

int

items(**kwargs)

Return list of tuples (parameter name, item).

keys(**kwargs)

Return parameter names.

classmethod load(filename)

Load samples from disk.

property logposterior

Log-posterior.

match(other, eps=1e-07, params=None)

Match other Samples against self, for parameters params.

Parameters:
  • other (Samples) – Samples to match.

  • eps (float, default=1e-7) – Distance upper bound above which samples are not considered equal. 1e-7 to handle float32/float64 conversions.

  • params (ParameterCollection, list, default=None) – Parameters to use. Defaults to all parameters that are not derived.

Return type:

index_in_other, index_in_self

names(**kwargs)

Return parameter names in collection.

property ndim

Number of dimensions.

params(**kwargs)

Return ParameterCollection, collection of parameters corresponding to items stored in this collection.

pop(name, *args, **kwargs)

Remove and return item indexed by name.

ravel()

Flatten samples.

classmethod recv(source=mpi4py.MPI.ANY_SOURCE, tag=mpi4py.MPI.ANY_TAG, mpicomm=None)

Receive samples from rank source.

reshape(*args)

Reshape samples (with shallow copy).

save(filename)

Save samples to disk.

select(**kwargs)

Return new collection, after selection of parameters whose attribute match input values:

collection.select(fixed=True)

returns collection of fixed parameters. If ‘name’ is provided, consider all matching parameters, e.g.:

collection.select(varied=True, name='a_[0:2]')

returns a collection of varied parameters, with name in ['a_0', 'a_1'].

send(dest, tag=0, mpicomm=None)

Send self to rank dest.

classmethod sendrecv(value, source=0, dest=0, tag=0, mpicomm=None)

Send samples from rank source to rank dest and receive them here.

set(item)

Add new ParameterArray to samples.

setdefault(item)

Set item in collection if not already in it.

property shape

Shape of samples.

property size

Total number of samples.

sort(key=None)

Sort (in-place) collection, such that if follows the list of parameter names key. If None, no sorting is performed.

to_array(params=None, struct=True, derivs=None)

Return samples as numpy array.

Parameters:
  • params (ParameterCollection, list, default=None) – Parameters to use. Defaults to all parameters.

  • struct (bool, default=True) – Whether to return structured array, with columns accessible through e.g. array['x']. If False, numpy will attempt to cast types of different columns.

Returns:

array

Return type:

array

to_dict(params=None)

Return samples as a dictionary.

Parameters:

params (ParameterCollection, list, default=None) – Parameters to use. Defaults to all parameters.

Returns:

dict – Dictionary mapping parameter name to array.

Return type:

dict

update(*args, **kwargs)

Update samples with new one; arguments can be a Samples or arguments to instantiate such a class (see __init__()).

values(**kwargs)

Return items.

class desilike.samples.profiles.ParameterProfiles(data=None, params=None, attrs=None)[source]

Bases: Samples

Class holding parameter 1D profiles.

Parameter arrays can be accessed (and updated) as for a dictionary:

profile = ParameterProfiles([np.array([np.ones(10), np.linspace(0., 1., 10)]).T], params=['a'])
profile['a']  # 2D array, profile['a'][:, 0] is 'a'-values, profile['a'][: 1] is the corresponding log-posterior

Initialize Samples.

Parameters:
  • data (list, dict, Samples) – Can be:

    • list of ParameterArray, or np.ndarray if list of parameters (or ParameterCollection) is provided in params

    • dictionary mapping parameter to array

  • params (list, ParameterCollection) – Optionally, list of parameters.

  • attrs (dict, default=None) – Optionally, other attributes, stored in attrs.

basenames(**kwargs)

Return base parameter names in collection.

classmethod bcast(value, mpicomm=None, mpiroot=0)

Broadcast input samples value from rank mpiroot to other processes.

choice(index='argmax', params=None, return_type='dict', **kwargs)[source]

Return parameter best fit(s).

Parameters:
  • index (str, default=’argmax’) – ‘argmax’ to return best fit (as defined by the point with maximum log-posterior in the samples).

  • params (list, ParameterCollection, default=None) – Parameters to compute best fit for. Defaults to all parameters.

  • return_dict (default=’dict’) – ‘dict’ to return a dictionary mapping parameter names to best fit; ‘nparray’ to return an array of parameter best fits; None to return a ParameterProfiles instance with a single value.

  • **kwargs (dict) – Optional arguments passed to params() to select params to return, e.g. varied=True, derived=False.

Returns:

toret

Return type:

dict, array, ParameterProfiles

clear()

Empty collection.

clone(*args, **kwargs)

Clone collection, i.e. (shallow) copy and update.

classmethod concatenate(*others, intersection=False)

Concatenate input samples, which requires all samples to hold same parameters, except if intersection == True, in which case common parameters are selected.

deepcopy()

Deep copy.

extend(other)

Extend collection with other. Unique items only are kept.

get(name, *args, **kwargs)

Return item of parameter name name in collection.

Parameters:

name (Parameter, str) – Parameter name. If Parameter instance, search for parameter with same name.

index(name)

Return index of parameter name.

Parameters:

name (Parameter, str, int) – Parameter name. If Parameter instance, search for parameter with same name. If integer, index in collection.

Returns:

index

Return type:

int

items(**kwargs)

Return list of tuples (parameter name, item).

keys(**kwargs)

Return parameter names.

classmethod load(filename)

Load samples from disk.

match(other, eps=1e-07, params=None)

Match other Samples against self, for parameters params.

Parameters:
  • other (Samples) – Samples to match.

  • eps (float, default=1e-7) – Distance upper bound above which samples are not considered equal. 1e-7 to handle float32/float64 conversions.

  • params (ParameterCollection, list, default=None) – Parameters to use. Defaults to all parameters that are not derived.

Return type:

index_in_other, index_in_self

names(**kwargs)

Return parameter names in collection.

property ndim

Number of dimensions.

params(**kwargs)

Return ParameterCollection, collection of parameters corresponding to items stored in this collection.

pop(name, *args, **kwargs)

Remove and return item indexed by name.

ravel()

Flatten samples.

classmethod recv(source=mpi4py.MPI.ANY_SOURCE, tag=mpi4py.MPI.ANY_TAG, mpicomm=None)

Receive samples from rank source.

reshape(*args)

Reshape samples (with shallow copy).

save(filename)

Save samples to disk.

select(**kwargs)

Return new collection, after selection of parameters whose attribute match input values:

collection.select(fixed=True)

returns collection of fixed parameters. If ‘name’ is provided, consider all matching parameters, e.g.:

collection.select(varied=True, name='a_[0:2]')

returns a collection of varied parameters, with name in ['a_0', 'a_1'].

send(dest, tag=0, mpicomm=None)

Send self to rank dest.

classmethod sendrecv(value, source=0, dest=0, tag=0, mpicomm=None)

Send samples from rank source to rank dest and receive them here.

set(item)

Add new ParameterArray to samples.

setdefault(item)

Set item in collection if not already in it.

property shape

Shape of samples.

property size

Total number of samples.

sort(key=None)

Sort (in-place) collection, such that if follows the list of parameter names key. If None, no sorting is performed.

to_array(params=None, struct=True, derivs=None)

Return samples as numpy array.

Parameters:
  • params (ParameterCollection, list, default=None) – Parameters to use. Defaults to all parameters.

  • struct (bool, default=True) – Whether to return structured array, with columns accessible through e.g. array['x']. If False, numpy will attempt to cast types of different columns.

Returns:

array

Return type:

array

to_dict(params=None)

Return samples as a dictionary.

Parameters:

params (ParameterCollection, list, default=None) – Parameters to use. Defaults to all parameters.

Returns:

dict – Dictionary mapping parameter name to array.

Return type:

dict

update(*args, **kwargs)

Update samples with new one; arguments can be a Samples or arguments to instantiate such a class (see __init__()).

values(**kwargs)

Return items.

class desilike.samples.profiles.Profiles(attrs=None, **kwargs)[source]

Bases: BaseClass

Class holding results of posterior profiling.

start

Initial parameter values.

Type:

Samples

bestfit

Best fit parameters.

Type:

ParameterBestFit

error

Parameter parabolic errors.

Type:

Samples

covariance

Parameter covariance at best fit.

Type:

ParameterCovariance

interval

Lower and upper errors corresponding to \(\Delta \chi^{2} = 1\).

Type:

Samples

profile

Parameter 1D profiles.

Type:

Samples

contour

Parameter 2D contours.

Type:

ParameterContours

Initialize Profiles.

Parameters:
  • attrs (dict, default=None) – Optionally, other attributes, stored in attrs.

  • **kwargs (dict) – Name and attributes; pass e.g. bestfit=....

classmethod bcast(value, mpicomm=None, mpiroot=0)[source]

Broadcast input profiles value from rank mpiroot to other processes.

choice(index='argmax')[source]

Return profiles restricted to best fit(s).

Parameters:

index (str, default=’argmax’) – ‘argmax’ to return profiles for best fit (as defined by the point with maximum log-posterior in the samples).

Returns:

toret

Return type:

dict, array, ParameterBestFit

clone(*args, **kwargs)[source]

Clone, i.e. copy and update.

classmethod concatenate(*others, **kwargs)[source]

Concatenate profiles together.

Parameters:

others (list) – List of Profiles instances.

Returns:

new

Return type:

Profiles

Warning

attrs of returned profiles contains, for each key, the last value found in others attrs dictionaries.

deepcopy()[source]

Deep copy.

extend(other)[source]

Extend profiles with other.

get(*args, **kwargs)[source]

Access attribute by name.

items()[source]

Return list of tuples (name, attribute).

set(**kwargs)[source]

Set attributes; pass e.g. bestfit=...

to_fisher(params=None, **kwargs)[source]

Return a Fisher, centered on bestfit.choice, with covariance matrix covariance.

Parameters:
  • params (list, ParameterCollection, default=None) – Parameters to return Fisher for. Defaults to all parameters.

  • ddof (int, default=1) – Number of degrees of freedom.

  • **kwargs (dict) – Arguments for bestfit.choice(), giving the mean of the output Fisher likelihood.

Returns:

fisher

Return type:

LikelihoodFisher

to_getdist(params=None, label=None, ignore_limits=True)[source]

Return a GetDist Gaussian distribution, centered on bestfit.choice, with covariance matrix covariance.

Parameters:
  • params (list, ParameterCollection, default=None) – Parameters to share to GetDist. Defaults to all parameters.

  • label (str, default=None) – Name for GetDist to use for this distribution.

  • ignore_limits (bool, default=True) – GetDist does not seem to be able to integrate over distribution if bounded; so drop parameter limits.

Returns:

samples

Return type:

getdist.gaussian_mixtures.MixtureND

to_stats(params=None, quantities=None, sigfigs=2, tablefmt='latex_raw', fn=None)[source]

Export summary profiling quantities.

Parameters:
  • params (list, ParameterCollection, default=None) – Parameters to export quantities for. Defaults to all parameters.

  • quantities (list, default=None) – Quantities to export. Defaults to ['bestfit', 'error', 'interval'].

  • sigfigs (int, default=2) – Number of significant digits. See utils.round_measurement().

  • tablefmt (str, default=’latex_raw’) – Format for summary table. See tabulate.tabulate(). If ‘list’, return table as list of list of strings, and headers. If ‘list_latex’, return table as list of list of latex strings, and headers.

  • fn (str, default=None) – If not None, file name where to save summary table.

Returns:

tab – Summary table.

Return type:

str

update(other)[source]

Update self attributes with other Profiles attributes (including attrs).

diagnostics

desilike.samples.diagnostics.autocorrelation(chains, params=None)[source]

Estimate weighted autocorrelation. Adapted from https://github.com/dfm/emcee/blob/main/src/emcee/autocorr.py

Parameters:
  • chains (list, Chain) – List of or single Chain instance(s).

  • params (list, ParameterCollection) – Parameters to compute autocorrelation statistics for. Defaults to all parameters.

Returns:

autocorr – Autocorrelation (array of size the number of samples if single parameter provided, else of shape (number of parameters, samples)).

Return type:

1D or 2D array

desilike.samples.diagnostics.gelman_rubin(chains, params=None, nsplits=None, statistic='mean', method='eigen', return_matrices=False, check_valid='raise')[source]

Estimate Gelman-Rubin statistics, which compares covariance of chain means to (mean of) intra-chain covariances.

Parameters:
  • chains (list, Chain) – List of or single Chain instance(s).

  • params (list, ParameterCollection) – Parameters to compute Gelman-Rubin statistics for. Defaults to all parameters.

  • nsplits (int, default=None) – The Gelman-Rubin criterion requires at least 2 chains. If provided, split input chains into nsplits parts.

  • statistic (str, callable, default=’mean’) – If ‘mean’, compares covariance of chain means to (mean of) intra-chain covariances. Else, must be a callable taking Chain instance and parameter list as input and returning array of values (one for each parameter).

  • method (str, default=’eigen’) – If ‘eigen’, return eigenvalues of covariance ratios, else diagonal.

  • return_matrices (bool, default=False) – If True, also return pair of covariance matrices (of chain means and (mean of) intra-chain covariances).

  • check_valid (str, default=’raise’) – If inversion of intra-chain covariances is inaccurate, and check_valid is:

    • ‘raise’: raise a LinAlgError

    • ‘warn’: issue a warning

    • ‘ignore’: ignore

Returns:

  • gr (scalar, array, tuple) – Gelman-Rubin statistics (scalar if single parameter provided, else array of size params). If return_matrices, also return pair covariance matrices.

  • Reference

  • ———

  • http (//www.stat.columbia.edu/~gelman/research/published/brooksgelman2.pdf)

desilike.samples.diagnostics.geweke(chains, params=None, first=0.1, last=0.5)[source]

Estimate Geweke statistics, i.e. the difference of chain averages in the first and last samples, w.r.t. the sum of covariances in the first and last samples.

Parameters:
  • chains (list, Chain) – List of or single Chain instance(s).

  • params (list, ParameterCollection) – Parameters to compute Geweke statistics for. Defaults to all parameters.

  • first (float, default=0.1) – Fraction of samples in the first part of the chain.

  • last (float, default=0.5) – Fraction of samples in the last part of the chain.

Returns:

geweke – Geweke statistics (array of size number of chains if single parameter provided, else array of shape (number of parameters, number of chains)).

Return type:

2D or 1D array

desilike.samples.diagnostics.integrated_autocorrelation_time(chains, params=None, criterion='sokal', min_corr=None, reliable=50, check_valid='warn', **kwargs)[source]

Estimate integrated autocorrelation time (averaged over all chains). Adapted from https://github.com/dfm/emcee/blob/main/src/emcee/autocorr.py and https://github.com/blackjax-devs/blackjax/blob/main/blackjax/diagnostics.py Effective sample size (ESS) can be computed as (number of samples) / (integrated autocorrelation time).

Parameters:
  • chains (list, Chain) – List of or single Chain instance(s).

  • params (list, ParameterCollection) – Parameters to compute integrated autocorrelation time for. Defaults to all parameters.

  • criterion (str, default=’sokal’) – Criterion to stop (\(N\)) the integration of autocorrelation time:

    \[\hat{\tau} = -1 + 2 \sum_{t=0}^{N} \hat{\rho}_{t}\]

    If ‘min_corr’, maximum index \(N\) for which \(\hat{\rho}_{N} > \mathrm{min_corr}\). min_corr can be provided in kwargs. If ‘sokal’, minimum index \(N\) for which \(N > C \hat{\rho}_{N}\). . c can be provided in kwargs, defaults to 5. If ‘geyer’, maximum index \(N\) for which \(\hat{\rho}_{2N} + \hat{\rho}_{2N + 1} > 0\).

  • min_corr (float, default=None) – Integrate starting from this lower autocorrelation threshold. If None, use c.

  • c (float, int, default=5) – Step size for the window search.

  • reliable (float, int, default=50) – Minimum ratio between the chain length and estimated autocorrelation time for it to be considered reliable.

  • check_valid (bool, default=False) – If estimate of autocorrelation time (based on reliable) is not reliable, and check_valid is:

    • ‘raise’: raise a LinAlgError

    • ‘warn’: issue a warning

    • ‘ignore’: ignore

Returns:

iat – Integrated autocorrelation time (scalar if single parameter provided, else array of size params).

Return type:

scalar, array

plotting

desilike.samples.plotting.add_1d_profile(profile, param, ax=None, **kwargs)[source]

Add 1D profile to axes. Requires Profiles.profile (or Profiles.bestfit and Profiles.error or Profiles.covariance for Gaussian approximation).

Parameters:
  • profile (Profile) – Profile instance.

  • param (Parameter, str) – Parameter to plot profile for.

  • ax (matplotlib.axes.Axes, default=None) – Axes where to add profile. Defaults to plt.gca().

  • **kwargs (dict) – Other arguments for plt.plot().

desilike.samples.plotting.add_2d_contour(profile, param1, param2, ax=None, cl=(1, 2), color='C0', filled=False, pale_factor=0.6, alpha=1.0, **kwargs)[source]

Add 2D contour to axes. Requires Profiles.contour (or Profiles.bestfit and Profiles.covariance for Gaussian approximation).

Parameters:
  • profile (Profile) – Profile instance.

  • param1 (Parameter, str) – First parameter to plot contour for.

  • param2 (Parameter, str) – Second parameter to plot contour for.

  • ax (matplotlib.axes.Axes, default=None) – Axes where to add profile. Defaults to plt.gca().

  • cl (int, default=2) – Plot contours up to cl \(\sigma\).

  • color (str, default=’C0’) – Color.

  • filled (bool, default=False) – If True, draw filled contours.

  • pale_factor (float, default=0.6) – When filled, lightens contour colors of increasing confidence levels by this amount.

  • alpha (float, default=1.) – Opacity.

  • **kwargs (dict) – Other arguments for plt.plot().

desilike.samples.plotting.add_legend(labels, colors=None, linestyles=None, fig=None, kw_handle=None, **kwargs)[source]

Add legend to figure.

Parameters:
  • labels (list, str) – Label(s) for profiles within each Profiles instance.

  • colors (list, str, default=None) – Color(s) for profiles within each Profiles instance.

  • linestyles (list, str, default=None) – Linestyle(s) for profiles within each Profiles instance.

  • fig (matplotlib.figure.Figure, default=None) – Optionally, figure to add legend to. Else, take plt.gcf().

  • **kwargs (dict) – Other arguments for fig.legend().

desilike.samples.plotting.plot_aligned(profiles, param, ids=None, labels=None, colors=None, truth=None, error='error', labelsize=None, ticksize=None, kw_scatter=None, yband=None, kw_mean=None, kw_truth=None, kw_yband=None, kw_legend=None, fig=None)[source]

Plot best fit estimates for single parameter.

Parameters:
  • profiles (list) – List of (or single) Profiles instance(s).

  • param (Parameter, str) – Parameter name.

  • ids (list, str, default=None) – Label(s) for input profiles.

  • labels (list, str, default=None) – Label(s) for best fits within each Profiles instance.

  • colors (list, str, default=None) – Color(s) for best fits within each Profiles instance.

  • truth (float, bool, default=None) – Plot this truth / reference value for parameter. If True, take Parameter.value.

  • error (str, default=’error’) – What to take as error: - ‘error’ for parabolic error - ‘interval’ for lower and upper errors corresponding to \(\Delta \chi^{2} = 1\).

  • labelsize (int, default=None) – Label sizes.

  • ticksize (int, default=None) – Tick sizes.

  • kw_scatter (dict, default=None) – Optional arguments for matplotlib.axes.Axes.scatter(). Defaults to {'marker': 'o'}.

  • yband (float, tuple, default=None) – If not None, plot horizontal band. If tuple and last element set to 'abs', absolute lower and upper y-coordinates of band; lower and upper fraction around truth. If float, fraction around truth.

  • kw_mean (dict, default=None) – If None, no mean is plotted. Else, optional arguments for matplotlib.axes.Axes.errorbar(). Defaults to {'marker': 'o'}.

  • kw_truth (dict, default=None) – If None, and truth not provided, no truth is plotted. Else, optional arguments for matplotlib.axes.Axes.axhline(). Defaults to {'color': 'k', 'linestyle': ':', 'linewidth': 2}.

  • kw_yband (dict, default=None) – Optional arguments for matplotlib.axes.Axes.axhspan().

  • kw_legend (dict, default=None) – Optional arguments for matplotlib.axes.Axes.legend().

  • fig (matplotlib.figure.Figure, default=None) – Optionally, a figure with at least 1 axis.

  • fn (str, Path, default=None) – Optionally, path where to save figure. If not provided, figure is not saved.

  • kw_save (dict, default=None) – Optionally, arguments for matplotlib.figure.Figure.savefig().

  • show (bool, default=False) – If True, show figure.

Returns:

fig

Return type:

matplotlib.figure.Figure

desilike.samples.plotting.plot_aligned_stacked(profiles, params=None, ids=None, labels=None, truths=None, ybands=None, ylimits=None, figsize=None, fig=None, **kwargs)[source]

Plot best fits, with a panel for each parameter.

Parameters:
  • profiles (list) – List of (or single) Profiles instance(s).

  • params (list, ParameterCollection, default=None) – Parameters to plot best fits for. Defaults to varied and not derived parameters.

  • ids (list, str) – Label(s) for input profiles.

  • labels (list, str) – Label(s) for best fits within each Profiles instance.

  • truths (list, dict, default=None) – Plot these truth / reference value for each parameter.

  • ybands (list, default=None) – If not None, plot horizontal bands. See plot_aligned().

  • ylimits (list, default=None) – If not None, limits for y-axis.

  • figsize (float, tuple, default=None) – Figure size.

  • fig (matplotlib.figure.Figure, default=None) – Optionally, a figure with at least as many axes as params.

  • fn (str, Path, default=None) – Optionally, path where to save figure. If not provided, figure is not saved.

  • kw_save (dict, default=None) – Optionally, arguments for matplotlib.figure.Figure.savefig().

  • show (bool, default=False) – If True, show figure.

Returns:

fig

Return type:

matplotlib.figure.Figure

desilike.samples.plotting.plot_autocorrelation_time(chains, params=None, threshold=50, slices=None, labelsize=None, fig=None)[source]

Plot integrated autocorrelation time.

Parameters:
  • chains (list, default=None) – List of (or single) Chain instance(s).

  • params (list, ParameterCollection, default=None) – Parameters to plot autocorrelation time for. Defaults to varied and not derived parameters.

  • threshold (float, default=50) – If not None, plot \(y = x/\mathrm{threshold}\) line. Integrated autocorrelation time estimation can be considered reliable when falling under this line.

  • slices (list, array) – List of increasing number of steps to include in calculation of autocorrelation time. Defaults to np.arange(100, nsteps, 500), where nsteps is the minimum size of input chains: Autocorrelation time is then plotted for chain slices (0, 100), (0, 600), …

  • labelsize (int, default=None) – Label sizes.

  • fig (matplotlib.figure.Figure, default=None) – Optionally, a figure with at least 1 axis.

  • fn (str, Path, default=None) – Optionally, path where to save figure. If not provided, figure is not saved.

  • kw_save (dict, default=None) – Optionally, arguments for matplotlib.figure.Figure.savefig().

  • show (bool, default=False) – If True, show figure.

Returns:

fig

Return type:

matplotlib.figure.Figure

desilike.samples.plotting.plot_gelman_rubin(chains, params=None, multivariate=False, threshold=None, slices=None, offset=0, labelsize=None, fig=None, **kwargs)[source]

Plot Gelman-Rubin statistics as a function of steps.

Parameters:
  • chains (list, default=None) – List of (or single) Chain instance(s).

  • params (list, ParameterCollection, default=None) – Parameters to plot Gelman-Rubin statistics for. Defaults to varied and not derived parameters.

  • multivariate (bool, default=False) – If True, add line for maximum of eigen value of Gelman-Rubin matrix. See diagnostics.gelman_rubin().

  • threshold (float, default=None) – If not None, plot horizontal line at this value.

  • slices (list, array) – List of increasing number of steps to include in calculation of Gelman-Rubin statistics. Defaults to np.arange(100, nsteps, 500), where nsteps is the minimum size of input chains: Gelman-Rubin statistics is then plotted for chain slices (0, 100), (0, 600), …

  • offset (float, default=0) – Offset to apply to the Gelman-Rubin statistics, typically 0 or -1.

  • labelsize (int, default=None) – Label sizes.

  • fig (matplotlib.figure.Figure, default=None) – Optionally, a figure with at least 1 axis.

  • **kwargs (dict) – Optional arguments for diagnostics.gelman_rubin() (‘nsplits’, ‘check_valid’).

  • fn (str, Path, default=None) – Optionally, path where to save figure. If not provided, figure is not saved.

  • kw_save (dict, default=None) – Optionally, arguments for matplotlib.figure.Figure.savefig().

  • show (bool, default=False) – If True, show figure.

Returns:

fig

Return type:

matplotlib.figure.Figure

desilike.samples.plotting.plot_geweke(chains, params=None, threshold=None, slices=None, labelsize=None, fig=None, **kwargs)[source]

Plot Geweke statistics.

Parameters:
  • chains (list, default=None) – List of (or single) Chain instance(s).

  • params (list, ParameterCollection, default=None) – Parameters to plot Geweke statistics for. Defaults to varied and not derived parameters.

  • threshold (float, default=None) – If not None, plot horizontal line at this value.

  • slices (list, array) – List of increasing number of steps to include in calculation of Geweke statistics. Defaults to np.arange(100, nsteps, 500), where nsteps is the minimum size of input chains: Geweke statistics is then plotted for chain slices (0, 100), (0, 600), …

  • labelsize (int, default=None) – Label sizes.

  • fig (matplotlib.figure.Figure, default=None) – Optionally, a figure with at least 1 axis.

  • **kwargs (dict) – Optional arguments for diagnostics.geweke() (‘first’, ‘last’).

  • fn (str, Path, default=None) – Optionally, path where to save figure. If not provided, figure is not saved.

  • kw_save (dict, default=None) – Optionally, arguments for matplotlib.figure.Figure.savefig().

  • show (bool, default=False) – If True, show figure.

Returns:

fig

Return type:

matplotlib.figure.Figure

desilike.samples.plotting.plot_profile(profiles, params=None, offsets=0.0, nrows=1, labels=None, colors=None, linestyles=None, cl=(1, 2, 3), labelsize=None, ticksize=None, kw_profile=None, kw_cl=None, kw_legend=None, figsize=None, fig=None)[source]

Plot profiles, with a panel for each parameter.

Parameters:
  • profiles (list) – List of (or single) Profiles instance(s).

  • params (list, ParameterCollection, default=None) – Parameters to plot profiles for. Defaults to varied and not derived parameters.

  • offsets (list, float, default=0) – Vertical offset for each profile.

  • nrows (int, default=1) – Number of rows in figure.

  • labels (list, str) – Label(s) for profiles within each Profiles instance.

  • colors (list, str, default=None) – Color(s) for profiles within each Profiles instance.

  • linestyles (list, str, default=None) – Linestyle(s) for profiles within each Profiles instance.

  • cl (int, tuple, default=(1, 2, 3)) – Confidence levels to plot.

  • labelsize (int, default=None) – Label sizes.

  • ticksize (int, default=None) – Tick sizes.

  • kw_profile (dict, default=None) – Optional arguments for matplotlib.axes.Axes.plot(). Defaults to {'marker': 'o'}.

  • kw_cl (dict, default=None) – Optional arguments for matplotlib.axes.Axes.axhline(). Defaults to {'color': 'k', 'linestyle': ':', 'linewidth': 2}.

  • kw_legend (dict, default=None) – Optional arguments for matplotlib.axes.Axes.legend().

  • figsize (float, tuple, default=None) – Figure size.

  • fig (matplotlib.figure.Figure, default=None) – Optionally, a figure with at least as many axes as params.

  • fn (str, Path, default=None) – Optionally, path where to save figure. If not provided, figure is not saved.

  • kw_save (dict, default=None) – Optionally, arguments for matplotlib.figure.Figure.savefig().

  • show (bool, default=False) – If True, show figure.

Returns:

fig

Return type:

matplotlib.figure.Figure

desilike.samples.plotting.plot_profile_comparison(profiles, profiles_ref, params=None, labels=None, colors=None, **kwargs)[source]

Plot profile comparison, wrapping plot_profile(). Profiles profiles and profiles_ref are both offset by profiles minimum \(\chi^{2}\).

Parameters:
  • profiles (list) – List of (or single) Profiles instance(s).

  • profiles_ref (list) – List of (or single) Profiles instance(s) to compare to.

  • params (list, ParameterCollection, default=None) – Parameters to plot profiles for. Defaults to varied and not derived parameters.

  • labels (list, str) – Label(s) for profiles within each Profiles instance.

  • colors (list, str, default=None) – Color(s) for profiles within each Profiles instance.

  • **kwargs (dict) – Optional arguments for plot_profile() (‘nrows’, ‘cl’, ‘labelsize’, ‘ticksize’, ‘kw_profile’, ‘kw_cl’, ‘kw_legend’, ‘figsize’).

  • fig (matplotlib.figure.Figure, default=None) – Optionally, a figure with at least as many axes as params.

  • fn (str, Path, default=None) – Optionally, path where to save figure. If not provided, figure is not saved.

  • kw_save (dict, default=None) – Optionally, arguments for matplotlib.figure.Figure.savefig().

  • show (bool, default=False) – If True, show figure.

Returns:

fig

Return type:

matplotlib.figure.Figure

desilike.samples.plotting.plot_trace(chains, params=None, figsize=None, colors=None, labelsize=None, kw_plot=None, fig=None)[source]

Make trace plot as a function of steps, with a panel for each parameter.

Parameters:
  • chains (list, default=None) – List of (or single) Chain instance(s).

  • params (list, ParameterCollection, default=None) – Parameters to plot trace for. Defaults to varied and not derived parameters.

  • figsize (float, tuple, default=None) – Figure size.

  • colors (str, list) – List of (or single) color(s) for chains.

  • labelsize (int, default=None) – Label sizes.

  • kw_plot (dict, default=None) – Optional arguments for matplotlib.axes.Axes.plot(). Defaults to {'alpha': 0.2}.

  • fn (str, Path, default=None) – Optionally, path where to save figure. If not provided, figure is not saved.

  • kw_save (dict, default=None) – Optionally, arguments for matplotlib.figure.Figure.savefig().

  • show (bool, default=False) – If True, show figure.

  • fig (matplotlib.figure.Figure, default=None) – Optionally, a figure with at least as many axes as params.

Returns:

fig

Return type:

matplotlib.figure.Figure

desilike.samples.plotting.plot_triangle(samples, params=None, labels=None, g=None, contour_colors=None, contour_ls=None, filled=False, legend_ncol=None, legend_loc=None, markers=None, **kwargs)[source]

Triangle plot. GetDist package is used to plot chains. If Profiles are provided, requires Profiles.profile (or Profiles.bestfit and Profiles.error or Profiles.covariance for Gaussian approximation) and Profiles.contour (or Profiles.bestfit and Profiles.covariance for Gaussian approximation).

Parameters:
  • samples (list, default=None) – List of (or single) Chain, Profiles or LikelihoodFisher instance(s).

  • params (list, ParameterCollection, default=None) – Parameters to plot distribution for. Defaults to varied and not derived parameters.

  • labels (str, list, default=None) – Name for GetDist to use for input samples.

  • fn (str, Path, default=None) – Optionally, path where to save figure. If not provided, figure is not saved.

  • kw_save (dict, default=None) – Optionally, arguments for matplotlib.figure.Figure.savefig().

  • g (getdist subplot_plotter) – can be created with g = getdist.plots.get_subplot_plotter() and can be modified with g.settings

  • show (bool, default=False) – If True, show figure.

  • **kwargs (dict) – Optional parameters for GetDistPlotter.triangle_plot().

Returns:

g

Return type:

getdist.plots.GetDistPlotter

desilike.samples.plotting.plot_triangle_contours(profiles, params=None, labels=None, colors=None, linestyles=None, filled=False, pale_factor=0.6, cl=2, alpha=1.0, truths=None, kw_contour=None, kw_truth=None, labelsize=None, kw_legend=None, figsize=None, fig=None)[source]

Triangle plot for likelihood profiling. Requires Profiles.profile (or Profiles.bestfit and Profiles.error or Profiles.covariance for Gaussian approximation) and Profiles.contour (or Profiles.bestfit and Profiles.covariance for Gaussian approximation).

Parameters:
  • profiles (list, default=None) – List of (or single) Profiles instance(s).

  • params (list, ParameterCollection, default=None) – Parameters to plot distribution for. Defaults to varied and not derived parameters.

  • labels (list, str) – Label(s) for profiles within each Profiles instance.

  • colors (list, str, default=None) – Color(s) for profiles within each Profiles instance.

  • linestyles (list, str, default=None) – Linestyle(s) for profiles within each Profiles instance.

  • filled (list, bool, default=None) – If True, draw filled contours. Can be provided for each Profiles instance.

  • pale_factor (float, default=0.6) – When filled, lightens contour colors of increasing confidence levels by this amount.

  • cl (int, default=2) – Plot contours up to cl \(\sigma\).

  • alpha (list, float, default=1.) – Opacity(ies). Can be provided for each Profiles instance.

  • truths (list, dict, default=None) – Plot these truth / reference value for each parameter.

  • kw_contour (dict, default=None) – Other options for plots.

  • kw_truth (dict, default=None) – If None, and truth not provided, no truth is plotted. Else, optional arguments for matplotlib.axes.Axes.axhline(). Defaults to {'color': 'k', 'linestyle': ':', 'linewidth': 2}.

  • labelsize (int, default=None) – Label sizes.

  • fig (matplotlib.figure.Figure, list, array, default=None) – Optionally, figure or array / list of axes.

  • fn (str, Path, default=None) – Optionally, path where to save figure. If not provided, figure is not saved.

  • kw_save (dict, default=None) – Optionally, arguments for matplotlib.figure.Figure.savefig().

  • show (bool, default=False) – If True, show figure.

Returns:

fig

Return type:

matplotlib.figure.Figure