# brian2modelfitting.fitter module¶

class brian2modelfitting.fitter.Fitter(dt, model, input, output, input_var, output_var, n_samples, threshold, reset, refractory, method, param_init, penalty, use_units=True)[source]

Bases: object

Base Fitter class for model fitting applications.

Creates an interface for model fitting of traces with parameters draw by gradient-free algorithms (through ask/tell interfaces).

Initiates n_neurons = num input traces * num samples, to which drawn parameters get assigned and evaluates them in parallel.

Parameters: dt (Quantity) – The size of the time step. model (Equations or str) – The equations describing the model. input (ndarray or Quantity) – A 2D array of shape (n_traces, time steps) given the input that will be fed into the model. output (Quantity or list) – Recorded output of the model that the model should reproduce. Should be a 2D array of the same shape as the input when fitting traces with TraceFitter, a list of spike times when fitting spike trains with SpikeFitter. input_var (str) – The name of the input variable in the model. Note that this variable should be used in the model (e.g. a variable I that is added as a current in the membrane potential equation), but not defined. output_var (str) – The name of the output variable in the model. Only needed when fitting traces with TraceFitter. n_samples (int) – Number of parameter samples to be optimized over in a single iteration. threshold (str, optional) – The condition which produces spikes. Should be a boolean expression as a string. reset (str, optional) – The (possibly multi-line) string with the code to execute on reset. refractory (str or Quantity, optional) – Either the length of the refractory period (e.g. 2*ms), a string expression that evaluates to the length of the refractory period after each spike (e.g. ‘(1 + rand())*ms’), or a string expression evaluating to a boolean value, given the condition under which the neuron stays refractory after a spike (e.g. ‘v > -20*mV’) method (str, optional) – Integration method penalty (str, optional) – The name of a variable or subexpression in the model that will be added to the error at the end of each iteration. Note that only the term at the end of the simulation is taken into account, so this term should not be varying in time. param_init (dict, optional) – Dictionary of variables to be initialized with respective values
best_error
best_params
calc_errors(metric)[source]

Abstract method required in all Fitter classes, used for calculating errors

Parameters: metric (Metric children) – Child of Metric class, specifies optimization metric
fit(optimizer, metric=None, n_rounds=1, callback='text', restart=False, online_error=False, start_iteration=None, penalty=None, level=0, **params)[source]

Run the optimization algorithm for given amount of rounds with given number of samples drawn. Return best set of parameters and corresponding error.

Parameters: optimizer (Optimizer children) – Child of Optimizer class, specific for each library. metric (Metric children) – Child of Metric class, specifies optimization metric n_rounds (int) – Number of rounds to optimize over (feedback provided over each round). callback (str or Callable) – Either the name of a provided callback function (text or progressbar), or a custom feedback function func(parameters, errors, best_parameters, best_error, index). If this function returns True the fitting execution is interrupted. restart (bool) – Flag that reinitializes the Fitter to reset the optimization. With restart True user is allowed to change optimizer/metric. online_error (bool, optional) – Whether to calculate the squared error between target trace and simulated trace online. Defaults to False. start_iteration (int, optional) – A value for the iteration variable at the first iteration. If not given, will use 0 for the first call of fit (and for later calls when restart is specified). Later calls will continue to increase the value from the previous calls. penalty (str, optional) – The name of a variable or subexpression in the model that will be added to the error at the end of each iteration. Note that only the term at the end of the simulation is taken into account, so this term should not be varying in time. If not given, will reuse the value specified during Fitter initialization. level (int, optional) – How much farther to go down in the stack to find the namespace. **params – bounds for each parameter best_results (dict) – dictionary with best parameter set error (float) – error value for best parameter set
generate(output_var=None, params=None, param_init=None, iteration=1000000000.0, level=0)[source]

Generates traces for best fit of parameters and all inputs. If provided with other parameters provides those.

Parameters: output_var (str or sequence of str) – Name of the output variable to be monitored, or the special name spikes to record spikes. Can also be a sequence of names to record multiple variables. params (dict) – Dictionary of parameters to generate fits for. param_init (dict) – Dictionary of initial values for the model. iteration (int, optional) – Value for the iteration variable provided to the simulation. Defaults to a high value (1e9). This is based on the assumption that the model implements some coupling of the fitted variable to the target variable, and that this coupling inversely depends on the iteration number. In this case, one would usually want to switch off the coupling when generating traces/spikes for given parameters. level (int, optional) – How much farther to go down in the stack to find the namespace. Either a 2D Quantity with the recorded output variable over time, with shape × , or a list of spike times for each input trace. If several names were given as output_var, then the result is a dictionary with the names of the variable as the key. fit
optimization_iter(optimizer, metric, penalty)[source]

Function performs all operations required for one iteration of optimization. Drawing parameters, setting them to simulator and calulating the error.

Parameters: optimizer (Optimizer) – metric (Metric) – penalty (str, optional) – The name of a variable or subexpression in the model that will be added to the error at the end of each iteration. Note that only the term at the end of the simulation is taken into account, so this term should not be varying in time. results (list) – recommended parameters parameters (list of list) – drawn parameters errors (list) – calculated errors
results(format='list', use_units=None)[source]

Returns all of the gathered results (parameters and errors). In one of the 3 formats: ‘dataframe’, ‘list’, ‘dict’.

Parameters: format (str) – The desired output format. Currently supported: dataframe, list, or dict. use_units (bool, optional) – Whether to use units in the results. If not specified, defaults to Tracefitter.use_units, i.e. the value that was specified when the Tracefitter object was created (True by default). ‘dataframe’: returns pandas DataFrame without units ‘list’: list of dictionaries ‘dict’: dictionary of lists object
setup_neuron_group(n_neurons, namespace, calc_gradient=False, optimize=True, online_error=False, name='neurons')[source]

Setup neuron group, initialize required number of neurons, create namespace and initialize the parameters.

Parameters: n_neurons (int) – number of required neurons **namespace – arguments to be added to NeuronGroup namespace neurons – group of neurons NeuronGroup
setup_simulator(network_name, n_neurons, output_var, param_init, calc_gradient=False, optimize=True, online_error=False, level=1)[source]
class brian2modelfitting.fitter.OnlineTraceFitter(model, input_var, input, output_var, output, dt, n_samples=30, method=None, reset=None, refractory=False, threshold=None, param_init=None, t_start=0. * second, penalty=None)[source]
best_error
best_params
calc_errors(metric=None)[source]

Calculates error in online fashion.To be used inside optim_iter.

fit(optimizer, n_rounds=1, callback='text', restart=False, start_iteration=None, penalty=None, level=0, **params)[source]

Run the optimization algorithm for given amount of rounds with given number of samples drawn. Return best set of parameters and corresponding error.

Parameters: optimizer (Optimizer children) – Child of Optimizer class, specific for each library. metric (Metric children) – Child of Metric class, specifies optimization metric n_rounds (int) – Number of rounds to optimize over (feedback provided over each round). callback (str or Callable) – Either the name of a provided callback function (text or progressbar), or a custom feedback function func(parameters, errors, best_parameters, best_error, index). If this function returns True the fitting execution is interrupted. restart (bool) – Flag that reinitializes the Fitter to reset the optimization. With restart True user is allowed to change optimizer/metric. online_error (bool, optional) – Whether to calculate the squared error between target trace and simulated trace online. Defaults to False. start_iteration (int, optional) – A value for the iteration variable at the first iteration. If not given, will use 0 for the first call of fit (and for later calls when restart is specified). Later calls will continue to increase the value from the previous calls. penalty (str, optional) – The name of a variable or subexpression in the model that will be added to the error at the end of each iteration. Note that only the term at the end of the simulation is taken into account, so this term should not be varying in time. If not given, will reuse the value specified during Fitter initialization. level (int, optional) – How much farther to go down in the stack to find the namespace. **params – bounds for each parameter best_results (dict) – dictionary with best parameter set error (float) – error value for best parameter set
generate(output_var=None, params=None, param_init=None, iteration=1000000000.0, level=0)

Generates traces for best fit of parameters and all inputs. If provided with other parameters provides those.

Parameters: output_var (str or sequence of str) – Name of the output variable to be monitored, or the special name spikes to record spikes. Can also be a sequence of names to record multiple variables. params (dict) – Dictionary of parameters to generate fits for. param_init (dict) – Dictionary of initial values for the model. iteration (int, optional) – Value for the iteration variable provided to the simulation. Defaults to a high value (1e9). This is based on the assumption that the model implements some coupling of the fitted variable to the target variable, and that this coupling inversely depends on the iteration number. In this case, one would usually want to switch off the coupling when generating traces/spikes for given parameters. level (int, optional) – How much farther to go down in the stack to find the namespace. Either a 2D Quantity with the recorded output variable over time, with shape × , or a list of spike times for each input trace. If several names were given as output_var, then the result is a dictionary with the names of the variable as the key. fit
generate_traces(params=None, param_init=None, level=0)[source]

Generates traces for best fit of parameters and all inputs

optimization_iter(optimizer, metric, penalty)

Function performs all operations required for one iteration of optimization. Drawing parameters, setting them to simulator and calulating the error.

Parameters: optimizer (Optimizer) – metric (Metric) – penalty (str, optional) – The name of a variable or subexpression in the model that will be added to the error at the end of each iteration. Note that only the term at the end of the simulation is taken into account, so this term should not be varying in time. results (list) – recommended parameters parameters (list of list) – drawn parameters errors (list) – calculated errors
results(format='list', use_units=None)

Returns all of the gathered results (parameters and errors). In one of the 3 formats: ‘dataframe’, ‘list’, ‘dict’.

Parameters: format (str) – The desired output format. Currently supported: dataframe, list, or dict. use_units (bool, optional) – Whether to use units in the results. If not specified, defaults to Tracefitter.use_units, i.e. the value that was specified when the Tracefitter object was created (True by default). ‘dataframe’: returns pandas DataFrame without units ‘list’: list of dictionaries ‘dict’: dictionary of lists object
setup_neuron_group(n_neurons, namespace, calc_gradient=False, optimize=True, online_error=False, name='neurons')

Setup neuron group, initialize required number of neurons, create namespace and initialize the parameters.

Parameters: n_neurons (int) – number of required neurons **namespace – arguments to be added to NeuronGroup namespace neurons – group of neurons NeuronGroup
setup_simulator(network_name, n_neurons, output_var, param_init, calc_gradient=False, optimize=True, online_error=False, level=1)
class brian2modelfitting.fitter.SpikeFitter(model, input, output, dt, reset, threshold, input_var='I', refractory=False, n_samples=30, method=None, param_init=None, penalty=None, use_units=True)[source]
best_error
best_params
calc_errors(metric)[source]

Returns errors after simulation with SpikeMonitor. To be used inside optim_iter.

fit(optimizer, metric=None, n_rounds=1, callback='text', restart=False, start_iteration=None, penalty=None, level=0, **params)[source]

Run the optimization algorithm for given amount of rounds with given number of samples drawn. Return best set of parameters and corresponding error.

Parameters: optimizer (Optimizer children) – Child of Optimizer class, specific for each library. metric (Metric children) – Child of Metric class, specifies optimization metric n_rounds (int) – Number of rounds to optimize over (feedback provided over each round). callback (str or Callable) – Either the name of a provided callback function (text or progressbar), or a custom feedback function func(parameters, errors, best_parameters, best_error, index). If this function returns True the fitting execution is interrupted. restart (bool) – Flag that reinitializes the Fitter to reset the optimization. With restart True user is allowed to change optimizer/metric. online_error (bool, optional) – Whether to calculate the squared error between target trace and simulated trace online. Defaults to False. start_iteration (int, optional) – A value for the iteration variable at the first iteration. If not given, will use 0 for the first call of fit (and for later calls when restart is specified). Later calls will continue to increase the value from the previous calls. penalty (str, optional) – The name of a variable or subexpression in the model that will be added to the error at the end of each iteration. Note that only the term at the end of the simulation is taken into account, so this term should not be varying in time. If not given, will reuse the value specified during Fitter initialization. level (int, optional) – How much farther to go down in the stack to find the namespace. **params – bounds for each parameter best_results (dict) – dictionary with best parameter set error (float) – error value for best parameter set
generate(output_var=None, params=None, param_init=None, iteration=1000000000.0, level=0)

Generates traces for best fit of parameters and all inputs. If provided with other parameters provides those.

Parameters: output_var (str or sequence of str) – Name of the output variable to be monitored, or the special name spikes to record spikes. Can also be a sequence of names to record multiple variables. params (dict) – Dictionary of parameters to generate fits for. param_init (dict) – Dictionary of initial values for the model. iteration (int, optional) – Value for the iteration variable provided to the simulation. Defaults to a high value (1e9). This is based on the assumption that the model implements some coupling of the fitted variable to the target variable, and that this coupling inversely depends on the iteration number. In this case, one would usually want to switch off the coupling when generating traces/spikes for given parameters. level (int, optional) – How much farther to go down in the stack to find the namespace. Either a 2D Quantity with the recorded output variable over time, with shape × , or a list of spike times for each input trace. If several names were given as output_var, then the result is a dictionary with the names of the variable as the key. fit
generate_spikes(params=None, param_init=None, iteration=1000000000.0, level=0)[source]

Generates traces for best fit of parameters and all inputs

optimization_iter(optimizer, metric, penalty)

Function performs all operations required for one iteration of optimization. Drawing parameters, setting them to simulator and calulating the error.

Parameters: optimizer (Optimizer) – metric (Metric) – penalty (str, optional) – The name of a variable or subexpression in the model that will be added to the error at the end of each iteration. Note that only the term at the end of the simulation is taken into account, so this term should not be varying in time. results (list) – recommended parameters parameters (list of list) – drawn parameters errors (list) – calculated errors
results(format='list', use_units=None)

Returns all of the gathered results (parameters and errors). In one of the 3 formats: ‘dataframe’, ‘list’, ‘dict’.

Parameters: format (str) – The desired output format. Currently supported: dataframe, list, or dict. use_units (bool, optional) – Whether to use units in the results. If not specified, defaults to Tracefitter.use_units, i.e. the value that was specified when the Tracefitter object was created (True by default). ‘dataframe’: returns pandas DataFrame without units ‘list’: list of dictionaries ‘dict’: dictionary of lists object
setup_neuron_group(n_neurons, namespace, calc_gradient=False, optimize=True, online_error=False, name='neurons')

Setup neuron group, initialize required number of neurons, create namespace and initialize the parameters.

Parameters: n_neurons (int) – number of required neurons **namespace – arguments to be added to NeuronGroup namespace neurons – group of neurons NeuronGroup
setup_simulator(network_name, n_neurons, output_var, param_init, calc_gradient=False, optimize=True, online_error=False, level=1)
class brian2modelfitting.fitter.TraceFitter(model, input_var, input, output_var, output, dt, n_samples=30, method=None, reset=None, refractory=False, threshold=None, param_init=None, penalty=None, use_units=True)[source]

A Fitter for fitting recorded traces (e.g. of the membrane potential).

Parameters: model – input_var – input – output_var – output – dt – n_samples – method – reset – refractory – threshold – param_init – use_units (bool, optional) – Whether to use units in all user-facing interfaces, e.g. in the callback arguments or in the returned parameter dictionary and errors. Defaults to True.
best_error
best_params
calc_errors(metric)[source]

Returns errors after simulation with StateMonitor. To be used inside optim_iter.

fit(optimizer, metric=None, n_rounds=1, callback='text', restart=False, start_iteration=None, penalty=None, level=0, **params)[source]

Run the optimization algorithm for given amount of rounds with given number of samples drawn. Return best set of parameters and corresponding error.

Parameters: optimizer (Optimizer children) – Child of Optimizer class, specific for each library. metric (Metric children) – Child of Metric class, specifies optimization metric n_rounds (int) – Number of rounds to optimize over (feedback provided over each round). callback (str or Callable) – Either the name of a provided callback function (text or progressbar), or a custom feedback function func(parameters, errors, best_parameters, best_error, index). If this function returns True the fitting execution is interrupted. restart (bool) – Flag that reinitializes the Fitter to reset the optimization. With restart True user is allowed to change optimizer/metric. online_error (bool, optional) – Whether to calculate the squared error between target trace and simulated trace online. Defaults to False. start_iteration (int, optional) – A value for the iteration variable at the first iteration. If not given, will use 0 for the first call of fit (and for later calls when restart is specified). Later calls will continue to increase the value from the previous calls. penalty (str, optional) – The name of a variable or subexpression in the model that will be added to the error at the end of each iteration. Note that only the term at the end of the simulation is taken into account, so this term should not be varying in time. If not given, will reuse the value specified during Fitter initialization. level (int, optional) – How much farther to go down in the stack to find the namespace. **params – bounds for each parameter best_results (dict) – dictionary with best parameter set error (float) – error value for best parameter set
generate(output_var=None, params=None, param_init=None, iteration=1000000000.0, level=0)

Generates traces for best fit of parameters and all inputs. If provided with other parameters provides those.

Parameters: output_var (str or sequence of str) – Name of the output variable to be monitored, or the special name spikes to record spikes. Can also be a sequence of names to record multiple variables. params (dict) – Dictionary of parameters to generate fits for. param_init (dict) – Dictionary of initial values for the model. iteration (int, optional) – Value for the iteration variable provided to the simulation. Defaults to a high value (1e9). This is based on the assumption that the model implements some coupling of the fitted variable to the target variable, and that this coupling inversely depends on the iteration number. In this case, one would usually want to switch off the coupling when generating traces/spikes for given parameters. level (int, optional) – How much farther to go down in the stack to find the namespace. Either a 2D Quantity with the recorded output variable over time, with shape × , or a list of spike times for each input trace. If several names were given as output_var, then the result is a dictionary with the names of the variable as the key. fit
generate_traces(params=None, param_init=None, iteration=1000000000.0, level=0)[source]

Generates traces for best fit of parameters and all inputs

optimization_iter(optimizer, metric, penalty)

Function performs all operations required for one iteration of optimization. Drawing parameters, setting them to simulator and calulating the error.

Parameters: optimizer (Optimizer) – metric (Metric) – penalty (str, optional) – The name of a variable or subexpression in the model that will be added to the error at the end of each iteration. Note that only the term at the end of the simulation is taken into account, so this term should not be varying in time. results (list) – recommended parameters parameters (list of list) – drawn parameters errors (list) – calculated errors
refine(params=None, t_start=None, t_weights=None, normalization=None, callback='text', calc_gradient=False, optimize=True, iteration=1000000000.0, level=0, **kwds)[source]

Refine the fitting results with a sequentially operating minimization algorithm. Uses the lmfit package which itself makes use of scipy.optimize. Has to be called after fit, but a call with n_rounds=0 is enough.

Parameters: params (dict, optional) – A dictionary with the parameters to use as a starting point for the refinement. If not given, the best parameters found so far by fit will be used. t_start (Quantity, optional) – Start of time window considered for calculating the fit error. If not set, will reuse the t_start value from the previously used metric. t_weights (ndarray, optional) – A 1-dimensional array of weights for each time point. This array has to have the same size as the input/output traces that are used for fitting. A value of 0 means that data points are ignored. The weight values will be normalized so only the relative values matter. For example, an array containing 1s, and 2s, will weigh the regions with 2s twice as high (with respect to the squared error) as the regions with 1s. Using instead values of 0.5 and 1 would have the same effect. Cannot be combined with t_start. If not set, will reuse the t_weights value from the previously used metric. normalization (float, optional) – A normalization term that will be used rescale results before handing them to the optimization algorithm. Can be useful if the algorithm makes assumptions about the scale of errors, e.g. if the size of steps in the parameter space depends on the absolute value of the error. The difference between simulated and target traces will be divided by this value. If not set, will reuse the normalization value from the previously used metric. callback (str or Callable) – Either the name of a provided callback function (text or progressbar), or a custom feedback function func(parameters, errors, best_parameters, best_error, index). If this function returns True the fitting execution is interrupted. calc_gradient (bool, optional) – Whether to add “sensitivity variables” to the equation that track the sensitivity of the equation variables to the parameters. This information will be used to pass the local gradient of the error with respect to the parameters to the optimization function. This can lead to much faster convergence than with an estimated gradient but comes at the expense of additional computation. Defaults to False. optimize (bool, optional) – Whether to remove sensitivity variables from the equations that do not evolve if initialized to zero (e.g. dS_x_y/dt = -S_x_y/tau would be removed). This avoids unnecessary computation but will fail in the rare case that such a sensitivity variable needs to be initialized to a non-zero value. Only taken into account if calc_gradient is True. Defaults to True. iteration (int, optional) – Value for the iteration variable provided to the simulation. Defaults to a high value (1e9). This is based on the assumption that the model implements some coupling of the fitted variable to the target variable, and that this coupling inversely depends on the iteration number. In this case, one would usually want to switch off the coupling when refining the solution. level (int, optional) – How much farther to go down in the stack to find the namespace. kwds – Additional arguments can overwrite the bounds for individual parameters (if not given, the bounds previously specified in the call to fit will be used). All other arguments will be passed on to lmfit.minimize and can be used to e.g. change the method, or to specify method-specific arguments. parameters (dict) – The parameters at the end of the optimization process as a dictionary. result (lmfit.MinimizerResult) – The result of the optimization process.

Notes

The default method used by lmfit is least-squares minimization using a Levenberg-Marquardt method. Note that there is no support for specifying a Metric, the given output trace(s) will be subtracted from the simulated trace(s) and passed on to the minimization algorithm.

This method always uses the runtime mode, independent of the selection of the current device.

results(format='list', use_units=None)

Returns all of the gathered results (parameters and errors). In one of the 3 formats: ‘dataframe’, ‘list’, ‘dict’.

Parameters: format (str) – The desired output format. Currently supported: dataframe, list, or dict. use_units (bool, optional) – Whether to use units in the results. If not specified, defaults to Tracefitter.use_units, i.e. the value that was specified when the Tracefitter object was created (True by default). ‘dataframe’: returns pandas DataFrame without units ‘list’: list of dictionaries ‘dict’: dictionary of lists object
setup_neuron_group(n_neurons, namespace, calc_gradient=False, optimize=True, online_error=False, name='neurons')

Setup neuron group, initialize required number of neurons, create namespace and initialize the parameters.

Parameters: n_neurons (int) – number of required neurons **namespace – arguments to be added to NeuronGroup namespace neurons – group of neurons NeuronGroup
setup_simulator(network_name, n_neurons, output_var, param_init, calc_gradient=False, optimize=True, online_error=False, level=1)
brian2modelfitting.fitter.get_full_namespace(additional_namespace, level=0)[source]
brian2modelfitting.fitter.get_param_dic(params, param_names, n_traces, n_samples)[source]

Transform parameters into a dictionary of appropiate size

brian2modelfitting.fitter.get_sensitivity_equations(group, parameters, namespace=None, level=1, optimize=True)[source]

Get equations for sensitivity variables.

Parameters: group (NeuronGroup) – The group of neurons that will be simulated. parameters (list of str) – Names of the parameters that are fit. namespace (dict, optional) – The namespace to use. level (int, optional) – How much farther to go down in the stack to find the namespace. optimize (bool, optional) – Whether to remove sensitivity variables from the equations that do not evolve if initialized to zero (e.g. dS_x_y/dt = -S_x_y/tau would be removed). This avoids unnecessary computation but will fail in the rare case that such a sensitivity variable needs to be initialized to a non-zero value. Defaults to True. sensitivity_eqs – The equations for the sensitivity variables. Equations
brian2modelfitting.fitter.get_sensitivity_init(group, parameters, param_init)[source]

Calculate the initial values for the sensitivity parameters (necessary if initial values are functions of parameters).

Parameters: group (NeuronGroup) – The group of neurons that will be simulated. parameters (list of str) – Names of the parameters that are fit. param_init (dict) – The dictionary with expressions to initialize the model variables. sensitivity_init – Dictionary of expressions to initialize the sensitivity parameters. dict
brian2modelfitting.fitter.get_spikes(monitor, n_samples, n_traces)[source]

Get spikes from spike monitor change format from dict to a list, remove units.

brian2modelfitting.fitter.setup_fit()[source]

Function sets up simulator in one of the two available modes: runtime or standalone. The Simulator that will be used depends on the currently set Device. In the case of CPPStandaloneDevice, the device will also be reset if it has already run a simulation.

Returns: simulator Simulator