API for Users

This page details the methods and classes provided by the cosmoHammer module which are of interest for users of cosmoHammer.

Samplers

CosmoHammerSampler Module

Standard usage of CosmoHammer involves instantiating an CosmoHammerSampler.

class cosmoHammer.CosmoHammerSampler(params, likelihoodComputationChain, filePrefix, walkersRatio, burninIterations, sampleIterations, stopCriteriaStrategy=None, initPositionGenerator=None, storageUtil=None, threadCount=1, reuseBurnin=False, logLevel=20, pool=None)[source]

A complete sampler implementation taking care of correct setup, chain burn in and sampling.

Parameters:
  • params – the parameter of the priors
  • likelihoodComputationChain – the callable computation chain
  • filePrefix – the prefix for the log and output files
  • walkersRatio – the ratio of walkers and the count of sampled parameters
  • burninIterations – number of iteration for burn in
  • sampleIterations – number of iteration to sample
  • stopCriteriaStrategy – the strategy to stop the sampling. Default is None an then IterationStopCriteriaStrategy is used
  • initPositionGenerator – the generator for the init walker position. Default is None an then SampleBallPositionGenerator is used
  • storageUtil – util used to store the results
  • threadCount – The count of threads to be used for the computation. Default is 1
  • reuseBurnin – Flag if the burn in should be reused. If true the values will be read from the file System. Default is False
createEmceeSampler(callable, **kwargs)[source]

Factory method to create the emcee sampler

createInitPos()[source]

Factory method to create initial positions

createInitPositionGenerator()[source]

Returns a new instance of a Init Position Generator

createSampleFileUtil()[source]

Returns a new instance of a File Util

createStopCriteriaStrategy()[source]

Returns a new instance of a stop criteria stategy

getChain()[source]

Returns the sample chain

isMaster()[source]

Returns True. Can be overridden for multitasking i.e. with MPI

loadBurnin()[source]

loads the burn in form the file system

log(message, level=20)[source]

Logs a message to the logfile

resetSampler()[source]

Resets the emcee sampler in the master node

sample(burninPos, burninProb=None, burninRstate=None, datas=None)[source]

Starts the sampling process

sampleBurnin(p0)[source]

Run the emcee sampler for the burnin to create walker which are independent form their starting position

startSampleBurnin()[source]

Runs the sampler for the burn in

startSampling()[source]

Launches the sampling

MpiCosmoHammerSampler Module

To distribute CosmoHammer in a cluster involves instantiating an MpiCosmoHammerSampler.

class cosmoHammer.MpiCosmoHammerSampler(**kwargs)[source]

Bases: cosmoHammer.CosmoHammerSampler.CosmoHammerSampler

A sampler implementation extending the regular sampler in order to allow for distributing the computation with MPI.

Parameters:kwargs – key word arguments passed to the CosmoHammerSampler

ConcurrentMpiCosmoHammerSampler Module

To distribute CosmoHammer in a cluster and to spawn multiple processes involves instantiating an ConcurrentMpiCosmoHammerSampler.

class cosmoHammer.ConcurrentMpiCosmoHammerSampler(threads=1, **kwargs)[source]

Bases: cosmoHammer.MpiCosmoHammerSampler.MpiCosmoHammerSampler

A sampler implementation extending the mpi sampler in order to allow to distribute the computation with MPI and using multiprocessing on a single node.

Parameters:
  • threads – (optional) The number of threads to use for parallelization. If threads == 1, then the multiprocessing module is not used but if threads > 1, then a Pool object is created
  • kwargs – key word arguments passed to the CosmoHammerSampler

CosmoHammer Chains

CosmoHammer comes with a plain vanillia chain implementation LikelihoodComputationChain.

class cosmoHammer.LikelihoodComputationChain(min=None, max=None)[source]

Implementation of a likelihood computation chain.

addCoreModule(module)[source]

adds a module to the likelihood module list

Parameters:module – callable the callable module to add for the computation of the data
addLikelihoodModule(module)[source]

adds a module to the likelihood module list

Parameters:module – callable the callable module to add for the likelihood computation
computeLikelihoods(ctx)[source]

Computes the likelihoods by iterating thru all the modules. Sums up the log likelihoods.

createChainContext(p)[source]

Returns a new instance of a chain context

getCoreModules()[source]

pointer to the likelihood module list

getLikelihoodModules()[source]

pointer to the core module list

invokeCoreModule(coreModule, ctx)[source]

Invokes the given module with the given ChainContext

invokeCoreModules(ctx)[source]

Iterates thru the core modules and invokes them

invokeLikelihoodModule(likelihoodModule, ctx)[source]

Invokes the given module with the given ChainContext

isValid(p)[source]

checks if the given parameters are valid

setup()[source]

sets up the chain and its modules

class cosmoHammer.ChainContext(parent, params)[source]

Context holding a dict to store data and information durring the computation of the likelihood

add(key, value)[source]

Adds the value to the context using the key

Parameters:
  • key – string key to use
  • value – object the value to store
contains(key)[source]

Checks if the key is in the context

Parameters:key – string key to check
Returns:True if the key is in the context
get(key, default=None)[source]

Returns the value stored in the context at the key or the default value in the context doesn’t contain the key

Parameters:
  • key – string key to use
  • default – string the default value to use if the key is not available
getData()[source]

Returns the data

Returns:The data of this context
getParams()[source]

Returns the currently processed parameters

Returns:The param of this context
getParent()[source]

Returns the parent

Returns:The parent chain of this context
remove(key)[source]

Removes the value from the context

Parameters:key – string key to remove from the context

CosmoHammer Exceptions

CosmoHammer may raise the following exceptions while execution

exception cosmoHammer.exceptions.InvalidLikelihoodException(params=None)[source]

Bases: cosmoHammer.exceptions.LikelihoodComputationException

Exception for invalid likelihoods e.g. -loglike >= 0.0

exception cosmoHammer.exceptions.LikelihoodComputationException[source]

Bases: exceptions.Exception

Exception for likelihood computation

CosmoHammer Utils

class cosmoHammer.util.Params(*args)[source]

A key-value parameter store preserving the order of the params passed to the intializer.

Examples:

$ params = Params(("key1", [1,2,3]),
                  ("key2", [1,2,3]))

$ print(params.keys)
> ['key1', 'key2']

$ print(params.key1)
> [1, 2, 3]

$ params[:,0] = 0

$ print(params.values)
> [[0 2 3]
   [0 2 3]]
   
$ print(params[:,1])
> [2 2]
class cosmoHammer.util.SampleBallPositionGenerator[source]

Generates samples in a very thight n-dimensional ball

generate()[source]

generates the positions

setup(sampler)[source]

setup the generator

class cosmoHammer.util.FlatPositionGenerator[source]

Generates samples in a flat random space using center + (random values * 2 -1) * width

generate()[source]

generates the positions

setup(sampler)[source]

setup the generator

class cosmoHammer.util.SampleFileUtil(filePrefix, master=True, reuseBurnin=False)[source]

Util for handling sample files

Parameters:
  • filePrefix – the prefix to use
  • master – True if the sampler instance is the master
  • reuseBurnin – True if the burn in data from a previous run should be used
persistValues(posFile, probFile, pos, prob, data)[source]

Writes the walker positions and the likelihood to the disk

class cosmoHammer.util.InMemoryStorageUtil(master=True)[source]
Stores the data in memory
Variables:
  • samplesBurin – samples from the burn in
  • probBurnin – likelihoods from the burn in
  • samples – samples from the burn in
  • prob

    likelihoods from the burn in

    param master:True if the sampler instance is the master

ParticleSwarmOptimizer Package

ParticleSwarmOptimizer Module

class cosmoHammer.ParticleSwarmOptimizer(func, low, high, particleCount=25, threads=1, pool=None)[source]

Optimizer using a swarm of particles

Parameters:
  • func – A function that takes a vector in the parameter space as input and returns the natural logarithm of the posterior probability for that position.
  • low – array of the lower bound of the parameter space
  • high – array of the upper bound of the parameter space
  • particleCount – the number of particles to use.
  • threads – (optional) The number of threads to use for parallelization. If threads == 1, then the multiprocessing module is not used but if threads > 1, then a Pool object is created and calls to lnpostfn are run in parallel.
  • pool – (optional) An alternative method of using the parallelized algorithm. If provided, the value of threads is ignored and the object provided by pool is used for all parallelization. It can be any object with a map method that follows the same calling sequence as the built-in map function.
optimize(maxIter=1000, c1=1.193, c2=1.193, p=0.7, m=0.001, n=0.01)[source]

Runs the complete optimiziation.

Parameters:
  • maxIter – maximum iterations
  • c1 – cognitive weight
  • c2 – social weight
  • p – stop criterion, percentage of particles to use
  • m – stop criterion, difference between mean fitness and global best
  • n – stop criterion, difference between norm of the particle vector and norm of the global best
Return swarms, gBests:
 

the swarms and the global bests of all iterations

sample(maxIter=1000, c1=1.193, c2=1.193, p=0.7, m=0.001, n=0.01)[source]

Launches the PSO. Yields the complete swarm per iteration

Parameters:
  • maxIter – maximum iterations
  • c1 – cognitive weight
  • c2 – social weight
  • p – stop criterion, percentage of particles to use
  • m – stop criterion, difference between mean fitness and global best
  • n – stop criterion, difference between norm of the particle vector and norm of the global best

MpiParticleSwarmOptimizer Module

class cosmoHammer.MpiParticleSwarmOptimizer(func, low, high, particleCount=25, threads=1)[source]

PSO with support for MPI to distribute the workload over multiple nodes