API

This page details the methods and classes provided by the SimpleMC.

Top level interface

class simplemc.DriverMC.DriverMC(iniFile=None, **kwargs)[source]

Bases: object

This class is the manager and wrapper between all the analyzers and the pertinent functions. It reads the input parameters or ini file.

Parameters:
  • iniFile (ini file) – Text file with ini extension that contains all the settings to SimpleMC. If use this option the following kwargs not are necessary.

  • chainsdir (str) – Directory for the outputs.

  • model (str) – Choose the model {LCDOM, LCDMasslessnu, nuLCDM, NeffLCDM, noradLCDM, nuoLCDM, nuwLCDM, oLCDM, wCDM, waCDM, owCDM,” owaCDM, JordiCDM, WeirdCDM, TLight, StepCDM, Spline, PolyCDM, fPolyCDM, Decay, Decay01, Decay05,” EarlyDE, EarlyDE_rd_DE, SlowRDE}

  • prefact (str) – {phy, pre}

  • vary8 (bool) – Default False

  • str (datasets) – Default HD (Hubble distance, i. e. Cosmic Chronometers). You can combine HD+SN+BBAO+Planck+UnionSN+…

  • analyzername (str) – The name of the analyzer. It can be a sampler: {mcmc, nested, emcee} or a optimizer: {maxlike, ga_deap}

  • compute_derived (bool) – True generates at the flight some derived parameters (such as Omega_Lambda or Universe Age, and save them in the output text file.

  • custom_parameters (list) – List of Parameter instances.

  • custom_function (method) – Custom method that reads a parameter list and a vector x, unzip the list, and return a f(x) in terms of the parameters.

  • path_to_data (str) – path of a dataset text file.

  • path_to_cov (str) – path of a covariance matrix text file.

  • fn (str) – Type of function to use in the likelihood due a custom data {“generic”, “hz”, …}.

emceeRunner(iniFile=None, **kwargs)[source]

This method calls the emcee library to use ensamble sampler.

Parameters:
  • walkers (int) – Number of walkers or ensambles.

  • nsamp (int) – Number of mcmc steps for each walker.

  • burnin (int) – skip steps.

  • nproc (int) – Number of processors in order to parallelise.

executer(**kwargs)[source]

This is a wrapper of the runners of the analyzer in order to make easier the execution, mainly if is through an ini file. **kwargs from mcmcRunner, nestedRunner, emceeRunner, genetic_deap and maxlikeRunner.

geneticdeap(iniFile=None, **kwargs)[source]

Genetic algorithms from Deap library.

iniReader(iniFile)[source]

It reads the ini file through configparser.

Parameters:

iniFile (file .ini) – Text file with settings

logLike(values)[source]

If the sampler used isn’t the MCMC of MCMCAnalyzer then, we need to set other types of likelihoods and priors objects. This method allows that. It is a likelihood defined for an external samplers and is used as parameter of the sampler run function.

Parameters:

values (n-dim vector) – implicit values, they are generated by the sampler.

logPosterior(theta)[source]

The natural logarithm of the joint posterior.

Parameters:
  • theta (tuple) – A sample containing individual parameter values

  • data (list) – The set of data/observations

  • sigma (float) – The standard deviation of the data points

  • x (list) – The abscissa values at which the data/model is defined

logPrior(theta)[source]

The natural logarithm of the prior probability.

Parameters:

theta (tuple) – A sample containing individual parameter values

maxLikeRunner(iniFile=None, **kwargs)[source]

It calls MaxLikeAnalyzer class.

Parameters:
  • withErrors (bool) – Plot errors.

  • plot_par1 (bool) – First parameter to plot.

  • plot_par2 (bool) – Second parameter to plot.

mcmcRunner(iniFile=None, **kwargs)[source]

This method calls MCMCAnalyzer.

Parameters:
  • nsamp (int) – Number of mcmc steps.

  • skip (int) – Burn-in.

  • temp (float) – Temperature for the weights.

  • GRstop (float) – Gelman Rubin criteria for stopping (0, 0.1].

  • evidence (bool) – True if after the mcmc chain was generated, estimates bayesian evidence throug MCEvidence (arXiv:1704.03472).

mppool(nproc)[source]

It creates a multiprocessing objet to parallelise nested and emcee samplers.

Parameters:

nproc (int) – number of processors to use.

Returns:

  • pool (multiprocessing.Pool) – object

  • nproc (int) – Number of processes

nestedRunner(iniFile=None, **kwargs)[source]

This method calls Dynesty nested samplers.

Parameters:
  • dynamic (bool) – Default False

  • nestedType (str) – {single, multi, balls, cubes}

  • nlivepoints (int) – Number of live points.

  • accuracy (float) – Stopping criteria in terms of logz.

  • nproc (int) – Number of processors to parallelize. Use 1 or 0 if you don’t want parallelise.

  • priortype (str) – Gaussian or uniform prior {‘g’, ‘u’}.

  • nsigma (float) – Sigma for gaussian priors.

neuralLike(iniFile=None, **kwargs)[source]

Under construction. This method trains a neural network in order to learn the likelihood function.

outputChecker()[source]

This method check if the name of the outputfile exists, if it already exists creates a new one with extension _new in its name.

paramFiles()[source]

This method writes the .paramnames file with theirs LaTeX names.

Parameters:
  • T (model) – T is result of ParseModel(model)

  • L (likelihood) – L is result of ParseDataset(datasets)

postprocess(addtxt=None)[source]

It calls the PostProcessing class.

Parameters:
  • summary (bool) – True for save summary.

  • addtxt (list) – A list with strings to save with the summary.

priorTransform(theta)[source]

Prior Transform for gaussian and flat priors

Parameters:

theta (array) – Vector of the parameter space

class simplemc.CosmoCalc.CosmoCalc(model, funct=None, param=None, minparam=None, maxparam=None, nsteps=3, savepdf=False, zmax=3, plot_data=False)[source]

Bases: object

Cosmological calculator to plot the basic functions

Parameters:
  • model (object) – Cosmological model.

  • funct (str) – Chosen function. It can be one of the following: ‘Hubble’, ‘DaOverrd’, ‘HIOverrd’, ‘DVOverrd’, ‘HubInvOverz’, ‘SNIa’, ‘fs8’, ‘Age’.

  • param (str) – Name of parameter.

  • minparam (float) – Min value of the chosen parameter.

  • maxparam (float) – Max value of the chosen parameter.

  • nsteps (int) – Number of steps to linspace for plot.

  • savepdf (bool) – Save a plot in pdf.

  • zmax (float) – Max value to redshift.

  • plot_data (bool) – Plot observational dataset?

class simplemc.PostProcessing.PostProcessing(dict_result, paramList, filename, skip=0.1, addDerived=True)[source]

Bases: object

This class makes postprocessing such as generate a summary with some statistics.

Parameters:
  • list_result (list) – List with results from sampling.

  • paramList (list) – List with Parameter objects.

  • filename (str.) – File name.

  • skip (float) – Burn-in.

  • addDerived (bool) – Derived parameters?

plot(chainsdir, show=False)[source]

Simple connection with the plotters.

Parameters:

show (bool) – Default False

Likelihood

class simplemc.likelihoods.BaseLikelihood.BaseLikelihood(name)[source]

Bases: object

This is the base likelihood object. Base for all other likelihoods.

freeParameters()[source]
Returns:

free parameters of the theory

name()[source]

Name of the dataset

Returns:

name

setTheory(theory)[source]

Define a theoretical model to use in the likelihood

Parameters:

theory (object) – Instance of BaseCosmology class. For example, theory = LCDMCosmology()

Returns:

theory

theory()[source]
Returns:

theory

updateParams(params)[source]

Update values of the model parameters

paramslist

List of instance of Parameter class.

Returns:

list of updated parameters

class simplemc.likelihoods.CompressedSNLikelihood.BetouleSN[source]

Bases: simplemc.likelihoods.CompressedSNLikelihood.CompressedSNLikelihood

Likelihood to binned JLA dataset.

class simplemc.likelihoods.CompressedSNLikelihood.CompressedSNLikelihood(name, values_filename, cov_filename)[source]

Bases: simplemc.likelihoods.BaseLikelihood.BaseLikelihood

This module calculates likelihood for the compressed SN.

Parameters:
  • name (str) – Name of the dataset

  • values_filename (str) – File text with the observational data.

  • cov_filename (str) – File text with the covariance matrix of the observational data.

class simplemc.likelihoods.CompressedSNLikelihood.UnionSN[source]

Bases: simplemc.likelihoods.CompressedSNLikelihood.CompressedSNLikelihood

Likelihood to binned Union 2.1 dataset

Cosmo

class simplemc.cosmo.Parameter.Parameter(name, value, err=0.0, bounds=None, Ltxname=None)[source]

Bases: object

A simple class for dealing with Parameter. Parameter has a name, a value, an error and some bounds Names have also latex names.

Parameters:
  • name (str) – Name to identify the parameter.

  • value (float) – Default value. In MCMC will be the starting value.

  • err (float) – Estimated error, in MCMC will be the step of the chain. Default is 0, but better to write any positive number.

  • bounds (list) – Priors. (minimum value, maximum value). List of pairs of bounds. Default is None, but computed as ‘(value-5*err, value+5*err)’.

  • Ltxname (str) – Latex name, use mainly for plotting. Default is None, and in this case uses the ‘name’ string.

Example

The hubble parameter h_par = Parameter(‘h’, 0.6821, 0.05, (0.4, 1.0), ‘h’)

class simplemc.cosmo.BaseCosmology.BaseCosmology(h=0.6821)[source]

Bases: object

Base Cosmology class doesn’t know about your parameterization of the equation of state or densities or anything. However, it does know about Hubble’s constant at z=0 OR the prefactor c/(H0*rd) which should be fit for in the case of “rd agnostic” fits. That is why you should let it declare those parameters based on its settings

However, to get the angular diameter distance you need to pass it its Curvature parameter (Omega_k basically), so you need to update it.

Also to use fs8 dataset you need to add s8 parameter.

We use speed of light in km s^-1.

Parameters:

h (float) – Value of the Hubble parameter h = H/100.

RHSquared_a(a)[source]

This is relative h-squared as a function of the factor scale a i.e. H(z)^2/H(z=0)^2.

Parameters:

a (float) – Factor scale.

updateParams(pars)[source]

Update parameters values.

Parameters:

pars (list) – List of instance of the Parameter class

class simplemc.cosmo.RadiationAndNeutrinos.RadiationAndNeutrinos(mnu=0.06, Nnu=3.046, varyMnu=False, varyNnu=False, degenerate=False, disable=False)[source]

Bases: object

Class for neutrinos, Mnu and Nnu

Parameters:
  • mnu (float) – Standard value for the mass of neutrinos.

  • Nnu (float) – Standard value for the number of families.

  • varyMnu (bool) – Whether varying mass for neutrinos.

  • varyNnu (bool) – Whether varying families for neutrinos.

  • degenerate (bool) – Degenerate neutrinos.

  • disable (bool) – Set radiation to zero.

class simplemc.cosmo.NuDensity.NuDensity(TCMB, Nnu=3.046, mnu=0.06, degenerate=False, fact=None)[source]

Bases: object

Compute Density parameter for neutrinos.

Parameters:
  • TCMB (float) – Temperature of the CMB.

  • Nnu (float, optional) – Families of neutrinos. Default value is ‘Neff=3.046’.

  • mnu (float, optional) – Sum of the neutrino masses. Default value is ‘mnu=0.06’.

  • degenerate (bool, optional) – Combinations of massive neutrinos.

  • fact (float, optional) – The ratio contribution: omrad_fac = 4.48130979e-7.

rho(a)[source]

Neutrinos density :param a:

Returns:

  • This returns the density at a normalized so that

  • we get nuh2 at a=0

  • (1 eV) / (Boltzmann constant * 1 kelvin) = 11 604.5193

class simplemc.cosmo.NuDensity.NuIntegral[source]

Bases: object

This module calculates the predictions for the evolution of neutrino energy densities. Here, we compute the integral I(r). Initialiazes the nu factor in rho_nu (self.interpolator).

SevenEights(mnuOT)[source]

Given the nu mass, returns the integral on the energy density of neutrinos.

Parameters:

mnuOT (float) – Sum of the neutrino masses.

Returns:

  • The integral given the sum of neutrino masses.

  • For massless neutrinos I(0)=78.

class simplemc.cosmo.NuDensity.ZeroNuDensity[source]

Bases: object

Fake class that returns zeros if want to disable neutrino contributions.

class simplemc.cosmo.Derivedparam.AllDerived[source]

Bases: object

Given base parameters, return a list of some Derived ones.

Omh2(z1, z2)[source]

Computes the Omh2 diagnostic at two redshifts to test deviations from the LCDM model. For LCDM the value is a constant for any combination of redshifts.

Parameters:
  • z1 (float) – Redshift z1 to compute the diagnostic.

  • z2 (float) – Redshift z2 to compute the diagnostic.

Returns:

Obh2 – Obh2 diagnostic: see [arXiv:1406.2209].

Return type:

float

computeDerived(parname)[source]

Initialize and compute Derived parameters in terms of the base ones.

listDerived(like)[source]

Given the base parameters compute derived ones.

Parameters:

like (object) – object defined in BaseLikelihood, that contains free-parameters and theory.

Returns:

list – List with values from derived parameters.

Return type:

list

class simplemc.cosmo.Derivedparam.Derivedparam(name, value, Ltxname=None)[source]

Bases: object

Auxiliary class, based on Parameter class.

Parameters:
  • name (string) – Parameter name.

  • value (float) – Initialize the value, and use a function to update it.

  • Ltxname (string, optional) – Provides the Latex name, useful for plotting. Default is None, and in this case uses the ‘name’ string.

Example

Hubble parameter self.H0 = Derivedparam(‘H0’, function, ‘H_0*’)

Models

class simplemc.models.LCDMCosmology.LCDMCosmology(Obh2=0.02234, Om=0.3038, h=0.6821, mnu=0.06, Nnu=3.046, degenerate_nu=False, disable_radiation=False, fixOm=False)[source]

Bases: simplemc.cosmo.BaseCosmology.BaseCosmology, simplemc.cosmo.RadiationAndNeutrinos.RadiationAndNeutrinos

This is LCDM cosmology, it is used as a base class for most other cosmologies, mostly because it treats Neutrinos and Radiation hassle.

Parameters:
  • Obh2 (float) – Barionic matter: Omega_bh^2

  • Om (float) – Matter density.

  • h (float) – Hubble parameter H/100.

  • mnu (float) – Standard value for the mass of neutrinos.

  • Nnu (float) – Standard value for the number of families.

  • degenerate_nu (bool) – Degenerate neutrinos.

  • disable_radiation (bool) – Without radiation.

  • fixOm (bool) – Om constant.

RHSquared_a(a)[source]

This is relative h-squared as a function of the factor scale a i.e. H(z)^2/H(z=0)^2.

Parameters:

a (float) – Factor scale.

updateParams(pars)[source]

Update parameters values.

Parameters:

pars (list) – List of instance of the Parameter class

class simplemc.models.owa0CDMCosmology.owa0CDMCosmology(varyw=True, varywa=True, varyOk=True)[source]

Bases: simplemc.models.LCDMCosmology.LCDMCosmology

This is CDM cosmology with w, wa and Ok. CPL parameterization with curvature. This class inherits LCDMCosmology class as the rest of the cosmological models already included in SimpleMC.

Parameters:
  • varyw (Boolean) – variable w0 parameter

  • varywa (Boolean) – variable wa parameter

  • varyOk (Boolean) – variable Ok parameter

RHSquared_a(a)[source]

This is relative h-squared as a function of the factor scale a i.e. H(z)^2/H(z=0)^2.

Parameters:

a (float) – Factor scale.

updateParams(pars)[source]

Update parameters values.

Parameters:

pars (list) – List of instance of the Parameter class

class simplemc.models.SimpleModel.SimpleCosmoModel(extra_params=None, RHSquared=None)[source]

Bases: simplemc.models.LCDMCosmology.LCDMCosmology

RHSquared_a(a)[source]

This is relative h-squared as a function of the factor scale a i.e. H(z)^2/H(z=0)^2.

Parameters:

a (float) – Factor scale.

updateParams(pars)[source]

Update parameters values.

Parameters:

pars (list) – List of instance of the Parameter class

class simplemc.models.SimpleModel.SimpleModel(parameters, function)[source]

Bases: object

This is a generic model

Parameters:
  • parameters (list) – List of Parameter objects

  • function (function) – model or function. It should be in terms of the parameters list.

Analyzers

class simplemc.analyzers.MCMCAnalyzer.MCMCAnalyzer(like, outfile, skip=5000, nsamp=100000, temp=1.0, cov=None, chain_num=None, addDerived=False, GRstop=0.01, checkGR=500)[source]

Bases: object

MCMC sampler (Metropolis-Hastings). This is the MCMC module. It spits out chains that are compatible with CosmoM it calculates cov matrix during burn-in. optional temperature makes it sample at a higher temperature but note that this guy, as opposed to cosmomc, reweights the weights on the fly.

Parameters:
  • like (Likelihood object) – Object of a Likelihood class.

  • outfile (str) – Output file.

  • skip (int) – Burn-in.

  • nsamp (int) – Number of mcmc samples.

  • temp (float) – Temperature

  • cov (numpy.array) – Covariance matrix. Default: None.

  • addDerived (bool) – In order to ad derived parameters such as age of the universe and Omega_{Lambda}.

  • GRstop (float) – Gelman-Rubin criteria.

GRDRun(chains)[source]

This is a implementation of the Gelman Rubin diagnostic. If the number of chains is 1, then this method divides it in two and does the diagnostic for convergence.

Parameters:

chains (list) – List with the chains to perform the GR-diagnostic.

Returns:

result – Gelman-Rubin diagnostic.

Return type:

float

GetProposal()[source]

Generation of proposal point in mcmc.

getLikes()[source]

Get loglikelihoods values from the used data.

openFiles()[source]

Open the files to save the samples and maxlike. Also add the Dervided Parameters if addDerived option is True.

class simplemc.analyzers.MaxLikeAnalyzer.MaxLikeAnalyzer(like, model, compute_errors=False, compute_derived=False, show_contours=False, plot_param1=None, plot_param2=None, outputname=None)[source]

Bases: object

This is an analyzer that takes a Likelihood function and then tries to maximize it with L-BFGS-B method and get the errors from the second derivative matrix. It kinda works, but not very well.

Parameters:
  • like – likelihood function.

  • model – theoretical model.

  • compute_errors (Boolean) – Compute errors.

  • compute_derived (Boolean) – Compute derivatives.

  • show_contours (Boolean) – Show contours in plots.

  • plot_param1 (str) – x-axis parameter to plot.

  • plot_param2 (str) – y-axis parameter to plot.

class simplemc.analyzers.GA_deap.GA_deap(like, model, outputname='deap_output', population=20, crossover=0.7, mutation=0.3, max_generation=20, hof_size=1, crowding_factor=1, plot_fitness=False, compute_errors=False, show_contours=False, plot_param1=None, plot_param2=None)[source]

Bases: object

Genetic algorithms from deap library

Parameters:
  • like – likelihood function

  • model – theoretical model model

  • plot_fitness – True if you want to generate a plot of the fitness.

  • compute_errors – True if you want to compute errors.

  • show_contours – True if you want to show the contours in a plot.

  • plot_param1 – a parameter to plot in x-axis.

  • plot_param2 – a parameter to plot in y-axis.

class simplemc.analyzers.neuralike.NeuralManager.NeuralManager(loglikelihood, pars_bounds, rootname, ndivsgrid=5, hidden_layers_neurons=None, epochs=100, plot=True, **kwargs)[source]

Bases: object

Manager for neural networks to learn likelihood function over a grid :param loglikelihood: :param pars_bounds: :param rootname: :param ndivsgrid: :param hidden_layers_neurons: :param epochs: :param plot:

modelChecker()[source]

This method checks if the name of the model.h5 exists, if it already exists use it, otherwise train a new neural net in order to generate a new model.

We use several nested sampling algorithms included in dynesty library. We slightly modify dynesty to save the strings in the text file and also to incorporate neural networks. However, its documentation is very complete, clear and didactic, so we recommend that you visit it.

Plots

class simplemc.plots.Simple_Plots.Simple_plots(dir_name, roots, label=None, **kwargs)[source]

Bases: simplemc.tools.cosmich.cosmochain

Collection of plotters.

Parameters:
  • dir_name (str) – Name of the directory with the mcmc chains text files.

  • roots – root name of the file.

  • label (list) – labels to each parameter.

  • kwargs**kwargs to plots. colors: list of colours, nchains: number of chains, skip: (int) burn-in

Plots1D(params, **kwargs)[source]

1D posterior plots. :param params: parameters to plot. :type params: list

Plots2D(params_pair, **kwargs)[source]

2D posterior plots between two parameters.

Parameters:
  • params_pair (list) – pair of parameters to 2D plots.

  • kwargs – pbest: boolean, solid: boolean.

cornerPlotter(params, color='g', show_titles=True, fill_contours=True)[source]

Triangle plot using corner library.

Parameters:
  • params – list of parameters

  • color – color, eg. ‘c’, ‘b’, etc.

  • show_titles – True if you want to show tittles.

  • fill_contours – True if you want to fill the contours.

fgivenx(params, z, func, labels=None)[source]

Plots with fgivenx library.

Parameters:
  • params – list of parameters.

  • z – independent variable.

  • func – funtion of the independent variable.

  • labels – labels for each parameter.

triangle(parlist, new_style=True, **kwargs)[source]

Triangle plots.

Parameters:

parlist – list of parameters