cpm.generators

cpm.generators.Value(value=None, lower=0, upper=1, prior=None, args=None, **kwargs)

The Value class is a wrapper around a float value, with additional details such as the prior distribution, lower and upper bounds. It supports all basic mathematical operations and can be used as a regular float with the parameter value as operand.

Parameters:
  • value (float, default: None ) –

    The value of the parameter.

  • lower (float, default: 0 ) –

    The lower bound of the parameter.

  • upper (float, default: 1 ) –

    The upper bound of the parameter.

  • prior (string or object, default: None ) –

    If a string, it should be one of continuous distributions from scipy.stats. See the scipy documentation for more details. The default is None. If an object, it should be or contain a callable function representing the prior distribution of the parameter with methods similar to scipy.stats distributions. See Notes for more details.

  • args (dict, default: None ) –

    A dictionary of arguments for the prior distribution function.

Notes

We currently implement the following continuous distributions from scipy.stats corresponding to the prior argument:

  • 'uniform'
  • 'truncated_normal'
  • 'beta'
  • 'gamma'
  • 'truncated_exponential'
  • 'norm'

Because these distributions are inherited from scipy.stats, see the scipy documentation for more details on how to update variables of the distribution.

Returns:
  • Value

    A Value object, where each attribute is one of the arguments provided for the function. It support all basic mathematical operations and can be used as a regular float with the parameter value as operand.

PDF(log=False)

Return the prior distribution of the parameter.

Returns:
  • float

    The probability of the parameter value under the prior distribution. If log is True, the log probability is returned.

copy()

Return a copy of the parameter.

Returns:
  • Value

    A copy of the parameter.

fill(value)

Replace the value of the parameter with a new value.

Parameters:
  • value (float or array_like) –

    The new value of the parameter.

Notes

If the parameter is an array, it should be a list of values. If the parameter is an array, and the new value is a single value, it will be broadcasted to the shape of the array.

sample(size=1, jump=False)

Sample and update the parameter value from its prior distribution.

Returns:
  • sample( float ) –

    A sample from the prior distribution of the parameter.

update_prior(**kwargs)

Update the prior distribution of the parameter. Currently it is only implemented for truncated normal distributions.

Parameters:
  • **kwargs (dict, default: {} ) –

    Keyword arguments representing the parameters of the prior distribution. If you are unsure what the names are for the parameters of the prior distribution, you can check the scipy.stats documentation or the prior.kwds attribute.

cpm.generators.Parameters(**kwargs)

A class representing a set of parameters. It takes keyword arguments representing the parameters with their values and wraps them into a python object.

Parameters:
  • **kwargs (dict, default: {} ) –

    Keyword arguments representing the parameters.

Returns:
  • Parameters

    A Parameters object, where each attributes is one of the keyword arguments provided for the function wrapped by the Value class.

Examples:

>>> from cpm.generators import Parameters
>>> parameters = Parameters(a=0.5, b=0.5, c=0.5)
>>> parameters['a']
0.1
>>> parameters.a
0.1
>>> parameters()
{'a': 0.1, 'b': 0.2, 'c': 0.5}

The Parameters class can also provide a prior.

>>> x = Parameters(
>>>    a=Value(value=0.1, lower=0, upper=1, prior="normal", args={"mean": 0.5, "sd": 0.1}),
>>>    b=0.5,
>>>    weights=Value(value=[0.1, 0.2, 0.3], lower=0, upper=1, prior=None),
>>> )
>>> x.prior(log=True)
-6.5854290732499186

We can also sample new parameter values from the prior distributions.

>>> x.sample()
{'a': 0.4670755733417274, 'b': 0.30116207009111917}

PDF(log=False)

Return the prior probability density of the parameter values.

Returns:
  • float

    The summed probability density of the parameter set under the prior distribution for each parameter. If log is True, the log probability is returned. When the PDF is 0, it returns the smallest positive float value. If log is True and the log probability is negative infinity, it returns the most negative float value.

bounds()

Returns a tuple with lower (first element) and upper (second element) bounds for parameters with defined priors.

Returns:
  • lower, upper: tuples

    A tuple of lower and upper parameter bounds

export()

Return all freely-varying parameters and their accompanying lower and upper bounds, and prior distributions.

Returns:
  • DataFrame

    A table of all freely-varying parameters and their accompanying lower and upper bounds, and prior distributions. Each row is a parameter, and the columns are the lower bound, upper bound, prior distribution, and the parameters of the prior distribution.

free()

Return a dictionary of all parameters with a prior distribution.

Returns:
  • free( dict ) –

    A dictionary of all parameters with a prior distribution.

keys()

Return a list of all the keys in the parameters dictionary.

Returns:
  • keys( list ) –

    A list of all the keys in the parameters dictionary.

sample(size=1, jump=False)

Sample and update parameter values from their prior distribution.

Returns:
  • sample( dict ) –

    A dictionary of the sampled parameters.

update(**kwargs)

Update the parameters with new values.

Parameters:
  • **kwargs (dict, default: {} ) –

    Keyword arguments representing the parameters.

update_prior(**kwargs)

Update the prior distribution of all parameters.

Parameters:
  • **kwargs (dict, default: {} ) –

    Keyword arguments representing the parameters of the prior distribution. For each parameter, the keyword should be the name of the parameter and the value should be a dictionary of the parameters of the prior distribution. If you are unsure what the names are for the parameters of the prior distribution, you can check the scipy.stats documentation or the prior.kwds attribute.

cpm.generators.Wrapper(model=None, data=None, parameters=None)

A Wrapper class for a model function in the CPM toolbox. It is designed to run a model for a single experiment (participant) and store the output in a format that can be used for further analysis.

Parameters:
  • model (function, default: None ) –

    The model function that calculates the output(s) of the model for a single trial. See Notes for more information. See Notes for more information.

  • data (DataFrame or dict, default: None ) –

    If a pandas.DataFrame, it must contain information about each trial in the experiment that serves as an input to the model. Each trial is a complete row. If a dictionary, it must contains information about the each state in the environment or each trial in the experiment - all input to the model that are not parameters.

  • parameters (Parameters object, default: None ) –

    The parameters object for the model that contains all parameters (and initial states) for the model. See Notes on how it is updated internally.

Returns:
  • Wrapper( object ) –

    A Wrapper object.

Notes

The model function should take two arguments: parameters and trial. The parameters argument should be a Parameter object specifying the model parameters. The trial argument should be a dictionary or pd.Series containing all input to the model on a single trial. The model function should return a dictionary containing the model output for the trial. If the model is intended to be fitted to data, its output should contain the following keys:

  • 'dependent': Any dependent variables calculated by the model that will be used for the loss function.

If a model output contains any keys that are also present in parameters, it updates those in the parameters based on the model output.

export()

Export the trial-level simulation details.

Returns:
  • DataFrame

    A dataframe containing the model output for each participant and trial. If the output variable is organised as an array with more than one dimension, the output will be flattened.

reset(parameters=None, data=None)

Reset the model.

Parameters:
  • parameters ((dict, array_like, Series or Parameters), default: None ) –

    The parameters to reset the model with.

Notes

When resetting the model, and parameters is None, reset model to initial state. If parameter is array_like, it resets the only the parameters in the order they are provided, where the last parameter updated is the element in parameters corresponding to len(parameters).

Examples:

>>> x = Wrapper(model = mine, data = data, parameters = params)
>>> x.run()
>>> x.reset(parameters = [0.1, 1])
>>> x.run()
>>> x.reset(parameters = {'alpha': 0.1, 'temperature': 1})
>>> x.run()
>>> x.reset(parameters = np.array([0.1, 1, 0.5]))
>>> x.run()
Returns:
  • None

run()

Run the model.

Returns:
  • None

save(filename=None)

Save the model.

Parameters:
  • filename (str, default: None ) –

    The name of the file to save the results to.

Returns:
  • None

Examples:

>>> x = Wrapper(model = mine, data = data, parameters = params)
>>> x.run()
>>> x.save('simulation')

If you wish to save a file in a specific folder, provide the relative path.

>>> x.save('results/simulation')
>>> x.save('../archives/results/simulation')

cpm.generators.Simulator(wrapper=None, data=None, parameters=None)

A Simulator class for a model in the CPM toolbox. It is designed to run a model for multiple participants and store the output in a format that can be used for further analysis.

Parameters:
  • wrapper (Wrapper, default: None ) –

    An initialised Wrapper object for the model.

  • data (pandas.core.groupby.generic.DataFrameGroupBy or list of dictionaries, default: None ) –

    The data required for the simulation. If it is a pandas.core.groupby.generic.DataFrameGroupBy, as returned by pandas.DataFrame.groupby(), each group must contain the data (or environment) for a single participant. If it is a list of dictionaries, each dictionary must contain the data (or environment) for a single participant.

  • parameters ((Parameters, DataFrame, Series or list), default: None ) –

    The parameters required for the simulation. It can be a Parameters object or a list of dictionaries whose length is equal to data. If it is a Parameters object, Simulator will use the same parameters for all simulations. It is a list of dictionaries, it will use match the parameters with data, so that for example parameters[6] will be used for the simulation of data[6].

Returns:
  • simulator( Simulator ) –

    A Simulator object.

export(save=False, path=None)

Return the trial- and participant-level information about the simulation.

Parameters:
  • save (bool, default: False ) –

    If True, the output will be saved to a file.

  • path (str, default: None ) –

    The path to save the output to.

Returns:
  • DataFrame

    A dataframe containing the the model output for each participant and trial. If the output variable is organised as an array with more than one dimension, the output will be flattened.

generate(variable='dependent')

Generate data for parameter recovery, etc.

Parameters:
  • variable

    Name of the variable to pull out from model output.

reset()

Resets the simulation.

run()

Runs the simulation.

Note

Data is sorted according to the group IDs as ordered by pandas.

save(filename=None)

Saves the simulation results.

Parameters:
  • filename (str, default: None ) –

    The name of the file to save the results to.

update(parameters=None)

Updates the parameters of the simulation.