def spike_call(self, spiking_neurons): dt = self.dt t = self.step() * dt spiking_neurons = array(spiking_neurons) if len(spiking_neurons) > 0: if t >= self.onset: self.spike_count[spiking_neurons] += 1 T_spiking = array(rint((t + self.delays[spiking_neurons]) / dt), dtype=int) remaining_neurons = spiking_neurons remaining_T_spiking = T_spiking while True: remaining_indices, = ( remaining_T_spiking > self.next_spike_time[remaining_neurons]).nonzero() if len(remaining_indices): indices = remaining_neurons[remaining_indices] self.spiketime_index[indices] += 1 self.last_spike_time[indices] = self.next_spike_time[ indices] self.next_spike_time[indices] = array(rint( self.spikes_inline[self.spiketime_index[indices] + 1] / dt), dtype=int) if self.algorithm == 'exclusive': self.last_spike_allowed[ indices] = self.next_spike_allowed[indices] self.next_spike_allowed[indices] = True remaining_neurons = remaining_neurons[remaining_indices] remaining_T_spiking = remaining_T_spiking[ remaining_indices] else: break # Updates coincidences count near_last_spike = self.last_spike_time[ spiking_neurons] + self.delta >= T_spiking near_next_spike = self.next_spike_time[ spiking_neurons] - self.delta <= T_spiking last_spike_allowed = self.last_spike_allowed[spiking_neurons] next_spike_allowed = self.next_spike_allowed[spiking_neurons] I = (near_last_spike & last_spike_allowed) | (near_next_spike & next_spike_allowed) if t >= self.onset: self.coincidences[spiking_neurons[I]] += 1 if self.algorithm == 'exclusive': near_both_allowed = (near_last_spike & last_spike_allowed) & ( near_next_spike & next_spike_allowed) self.last_spike_allowed[ spiking_neurons] = last_spike_allowed & -near_last_spike self.next_spike_allowed[spiking_neurons] = ( next_spike_allowed & -near_next_spike) | near_both_allowed
def __init__(self, group, traces=None, spikes=None, targets_count=1, duration=None, onset=0 * ms, spikes_inline=None, spikes_offset=None, traces_inline=None, traces_offset=None, delays=None, when='end', **params): NetworkOperation.__init__(self, None, clock=group.clock, when=when) self.group = group # needed by SpikeMonitor self.source = group self.source.set_max_delay(0) self.delay = 0 self.N = len(group) # number of neurons self.K = targets_count # number of targets self.dt = self.clock.dt if traces is not None: self.traces = array(traces) # KxT array if self.traces.ndim == 1: self.traces = self.traces.reshape((1, -1)) assert targets_count == self.traces.shape[0] self.spikes = spikes # get the duration from the traces if duration is not specified in the constructor if duration is None: duration = self.traces.shape[1] # total number of steps self.duration = duration self.total_steps = int(duration / self.dt) if delays is None: delays = zeros(self.n) self.delays = delays self.onset = int(onset / self.dt) self.intdelays = array(self.delays / self.clock.dt, dtype=int) self.mindelay = min(delays) self.maxdelay = max(delays) # the following data is sliced self.spikes_inline = spikes_inline self.spikes_offset = spikes_offset self.traces_inline = traces_inline self.traces_offset = traces_offset if self.spikes is not None: # target spike count and rates self.target_spikes_count = self.get_spikes_count(self.spikes) self.target_spikes_rate = self.get_spikes_rate(self.spikes) self.initialize(**params)
def reinit_vars(self, criterion, I, I_offset, spiketimes=None, spiketimes_offset=None, traces=None, traces_offset=None, spikedelays=None, refractory=None): self.criterion = criterion self.kernel_module = SourceModule(self.kernel_src) self.kernel_func = self.kernel_module.get_function('runsim') blocksize = BLOCKSIZE # try: # blocksize = self.kernel_func.get_attribute(pycuda.driver.function_attribute.MAX_THREADS_PER_BLOCK) # except: # above won't work unless CUDA>=2.2 # pass self.block = (blocksize, 1, 1) self.grid = (int(ceil(float(self.N) / blocksize)), 1) self.kernel_func_kwds = {'block': self.block, 'grid': self.grid} mydtype = self.mydtype N = self.N eqs = self.eqs statevars_arr = gpuarray.to_gpu( array(self.G._S.flatten(), dtype=mydtype)) self.I = gpuarray.to_gpu(array(I, dtype=mydtype)) self.statevars_arr = statevars_arr self.I_offset = gpuarray.to_gpu(array(I_offset, dtype=int32)) # SPIKES if self.criterion.type == 'spikes': self.initialize_spikes(spiketimes, spiketimes_offset) # TRACES if self.criterion.type == 'traces': self.initialize_traces(traces, traces_offset) self.criterion.initialize_cuda_variables() self.initialize_delays(spikedelays) self.initialize_refractory(refractory) if self.statemonitor_var is not None: self.initialize_statemonitor() if self.spikemonitor is True: self.initialize_spikemonitor() self.initialize_kernel_arguments()
def transform_traces(self, traces): # from standard structure to inline structure K, T = traces.shape traces_inline = traces.flatten() traces_offset = array(kron(arange(K), T * ones(self.subpopsize)), dtype=int) return traces_inline, traces_offset
def initialize(self, delta, coincidence_count_algorithm): self.algorithm = coincidence_count_algorithm self.delta = int(rint(delta / self.dt)) self.spike_count = zeros(self.N, dtype='int') self.coincidences = zeros(self.N, dtype='int') self.spiketime_index = self.spikes_offset self.last_spike_time = array(rint(self.spikes_inline[self.spiketime_index] / self.dt), dtype=int) self.next_spike_time = array(rint(self.spikes_inline[self.spiketime_index + 1] / self.dt), dtype=int) # First target spikes (needed for the computation of # the target train firing rates) # self.first_target_spike = zeros(self.N) self.last_spike_allowed = ones(self.N, dtype='bool') self.next_spike_allowed = ones(self.N, dtype='bool')
def initialize_refractory(self, refractory): if isinstance(refractory, float): refractory = refractory * ones(self.N) self.refractory_arr = gpuarray.to_gpu( array(rint(refractory / self.dt), dtype=int32)) self.next_allowed_spiketime_arr = gpuarray.to_gpu( -ones(self.N, dtype=int32))
def spike_call(self, spiking_neurons): dt = self.dt t = self.step()*dt spiking_neurons = array(spiking_neurons) if len(spiking_neurons)>0: if t >= self.onset: self.spike_count[spiking_neurons] += 1 T_spiking = array(rint((t + self.delays[spiking_neurons]) / dt), dtype=int) remaining_neurons = spiking_neurons remaining_T_spiking = T_spiking while True: remaining_indices, = (remaining_T_spiking > self.next_spike_time[remaining_neurons]).nonzero() if len(remaining_indices): indices = remaining_neurons[remaining_indices] self.spiketime_index[indices] += 1 self.last_spike_time[indices] = self.next_spike_time[indices] self.next_spike_time[indices] = array(rint(self.spikes_inline[self.spiketime_index[indices] + 1] / dt), dtype=int) if self.algorithm == 'exclusive': self.last_spike_allowed[indices] = self.next_spike_allowed[indices] self.next_spike_allowed[indices] = True remaining_neurons = remaining_neurons[remaining_indices] remaining_T_spiking = remaining_T_spiking[remaining_indices] else: break # Updates coincidences count near_last_spike = self.last_spike_time[spiking_neurons] + self.delta >= T_spiking near_next_spike = self.next_spike_time[spiking_neurons] - self.delta <= T_spiking last_spike_allowed = self.last_spike_allowed[spiking_neurons] next_spike_allowed = self.next_spike_allowed[spiking_neurons] I = (near_last_spike & last_spike_allowed) | (near_next_spike & next_spike_allowed) if t >= self.onset: self.coincidences[spiking_neurons[I]] += 1 if self.algorithm == 'exclusive': near_both_allowed = (near_last_spike & last_spike_allowed) & (near_next_spike & next_spike_allowed) self.last_spike_allowed[spiking_neurons] = last_spike_allowed & -near_last_spike self.next_spike_allowed[spiking_neurons] = (next_spike_allowed & -near_next_spike) | near_both_allowed
def reinit_vars(self, criterion, I, I_offset, spiketimes = None, spiketimes_offset = None, traces = None, traces_offset = None, spikedelays = None, refractory = None): self.criterion = criterion self.kernel_module = SourceModule(self.kernel_src) self.kernel_func = self.kernel_module.get_function('runsim') blocksize = BLOCKSIZE # try: # blocksize = self.kernel_func.get_attribute(pycuda.driver.function_attribute.MAX_THREADS_PER_BLOCK) # except: # above won't work unless CUDA>=2.2 # pass self.block = (blocksize, 1, 1) self.grid = (int(ceil(float(self.N) / blocksize)), 1) self.kernel_func_kwds = {'block':self.block, 'grid':self.grid} mydtype = self.mydtype N = self.N eqs = self.eqs statevars_arr = gpuarray.to_gpu(array(self.G._S.flatten(), dtype=mydtype)) self.I = gpuarray.to_gpu(array(I, dtype=mydtype)) self.statevars_arr = statevars_arr self.I_offset = gpuarray.to_gpu(array(I_offset, dtype=int32)) # SPIKES if self.criterion.type == 'spikes': self.initialize_spikes(spiketimes, spiketimes_offset) # TRACES if self.criterion.type == 'traces': self.initialize_traces(traces, traces_offset) self.criterion.initialize_cuda_variables() self.initialize_delays(spikedelays) self.initialize_refractory(refractory) if self.statemonitor_var is not None: self.initialize_statemonitor() if self.spikemonitor is True: self.initialize_spikemonitor() self.initialize_kernel_arguments()
def initialize(self, delta, coincidence_count_algorithm): self.algorithm = coincidence_count_algorithm self.delta = int(rint(delta / self.dt)) self.spike_count = zeros(self.N, dtype='int') self.coincidences = zeros(self.N, dtype='int') self.spiketime_index = self.spikes_offset self.last_spike_time = array(rint( self.spikes_inline[self.spiketime_index] / self.dt), dtype=int) self.next_spike_time = array(rint( self.spikes_inline[self.spiketime_index + 1] / self.dt), dtype=int) # First target spikes (needed for the computation of # the target train firing rates) # self.first_target_spike = zeros(self.N) self.last_spike_allowed = ones(self.N, dtype='bool') self.next_spike_allowed = ones(self.N, dtype='bool')
def __init__(self, group, traces=None, spikes=None, targets_count=1, duration=None, onset=0*ms, spikes_inline=None, spikes_offset=None, traces_inline=None, traces_offset=None, delays=None, when='end', **params): NetworkOperation.__init__(self, None, clock=group.clock, when=when) self.group = group # needed by SpikeMonitor self.source = group self.source.set_max_delay(0) self.delay = 0 self.N = len(group) # number of neurons self.K = targets_count # number of targets self.dt = self.clock.dt if traces is not None: self.traces = array(traces) # KxT array if self.traces.ndim == 1: self.traces = self.traces.reshape((1,-1)) assert targets_count==self.traces.shape[0] self.spikes = spikes # get the duration from the traces if duration is not specified in the constructor if duration is None: duration = self.traces.shape[1] # total number of steps self.duration = duration self.total_steps = int(duration/self.dt) if delays is None: delays = zeros(self.n) self.delays = delays self.onset = int(onset/self.dt) self.intdelays = array(self.delays/self.clock.dt, dtype=int) self.mindelay = min(delays) self.maxdelay = max(delays) # the following data is sliced self.spikes_inline = spikes_inline self.spikes_offset = spikes_offset self.traces_inline = traces_inline self.traces_offset = traces_offset if self.spikes is not None: # target spike count and rates self.target_spikes_count = self.get_spikes_count(self.spikes) self.target_spikes_rate = self.get_spikes_rate(self.spikes) self.initialize(**params)
def transform_spikes(self, spikes): # from standard structure to inline structure i, t = zip(*spikes) i = array(i) t = array(t) alls = [] n = 0 pointers = [] model_target = [] for j in xrange(self.groups): s = sort(t[i == j]) s = hstack((-1 * second, s, self.duration + 1 * second)) model_target.extend([j] * self.subpopsize) alls.append(s) pointers.append(n) n += len(s) pointers = array(pointers, dtype=int) model_target = array(hstack(model_target), dtype=int) spikes_inline = hstack(alls) spikes_offset = pointers[model_target] return spikes_inline, spikes_offset
def transform_trials(self, spikes): # from standard structure to inline structure i, t = zip(*spikes) i = array(i) t = array(t) alls = [] n = 0 pointers = [] model_target = [] pointers.append(0) for j in xrange(self.ntrials): s = sort(t[i == j]) s = hstack((-1 * second, s, self.duration + 1 * second)) alls.append(s) pointers.append(pointers[j]+len(s)) pointers.pop() spikes_inline = hstack(alls) # print pointers # print nonzero(spikes_inline==-1) # show() return spikes_inline, pointers
def initialize_spikes(self, spiketimes, spiketimes_indices): self.spiketimes = gpuarray.to_gpu(array(rint(spiketimes / self.dt), dtype=int32)) self.spiketime_indices = gpuarray.to_gpu(array(spiketimes_indices, dtype=int32))
def transform_traces(self, traces): # from standard structure to inline structure K, T = traces.shape traces_inline = traces.flatten() traces_offset = array(kron(arange(K), T*ones(self.subpopsize)), dtype=int) return traces_inline, traces_offset
def simulate(model, reset=None, threshold=None, input=None, input_var='I', dt=defaultclock.dt, refractory=0 * ms, max_refractory=None, data=None, groups=1, slices=1, overlap=0 * second, neurons=1, initial_values=None, use_gpu=False, stepsize=100 * ms, precision='double', criterion=None, record=None, method='Euler', **params): unit_type = 'CPU' if use_gpu: unit_type = 'GPU' for param in params.keys(): if (param not in model._diffeq_names) and (param != 'delays'): raise Exception( "Parameter %s must be defined as a parameter in the model" % param) if criterion is None: criterion = GammaFactor() data = array(data) if criterion.type == 'spikes': # Make sure that 'data' is a N*2-array if data.ndim == 1: data = concatenate((zeros((len(data), 1)), data.reshape((-1, 1))), axis=1) spikes = data traces = None groups = int(array(data)[:, 0].max() + 1) # number of target trains elif criterion.type == 'trace': if data.ndim == 1: data = data.reshape((1, -1)) spikes = None traces = data groups = data.shape[0] elif criterion.type == 'both': # TODO log_warn("Not implemented yet") pass inputs = input if inputs.ndim == 1: inputs = inputs.reshape((1, -1)) # dt must be set if dt is None: raise Exception('dt (sampling frequency of the input) must be set') # default overlap when no time slicing if slices == 1: overlap = 0 * ms # check numerical integration method if use_gpu and method not in ['Euler', 'RK', 'exponential_Euler']: raise Exception( "The method can only be 'Euler', 'RK', or 'exponential_Euler' when using the GPU" ) if method not in [ 'Euler', 'RK', 'exponential_Euler', 'linear', 'nonlinear' ]: raise Exception( "The method can only be 'Euler', 'RK', 'exponential_Euler', 'linear', or 'nonlinear'" ) # determines whether optimization over refractoriness or not if type(refractory) is tuple or type(refractory) is list: params['refractory'] = refractory max_refractory = refractory[-1] else: max_refractory = None # Initialize GPU if use_gpu: set_gpu_device(0) simulator = Simulator(model, reset, threshold, inputs, input_var=input_var, dt=dt, refractory=refractory, max_refractory=max_refractory, spikes=spikes, traces=traces, groups=groups, slices=slices, overlap=overlap, onset=overlap, neurons=neurons, initial_values=initial_values, unit_type=unit_type, stepsize=stepsize, precision=precision, criterion=criterion, statemonitor_var=record, method=method) criterion_values = simulator.run(**params) if record is not None: record_values = simulator.get_statemonitor_values() return criterion_values, record_values else: return criterion_values
def simulate( model, reset = None, threshold = None, input = None, input_var = 'I', dt = defaultclock.dt, refractory = 0*ms, max_refractory = None, data = None, groups = 1, slices = 1, overlap = 0*second, onset = None, neurons = 1, initial_values = None, use_gpu = False, stepsize = 128*ms, precision = 'double', criterion = None, ntrials=1, record = None, spikemonitor = False, nbr_spikes = 200, method = 'Euler', stand_alone=False, # neuron_group = none, **params): unit_type = 'CPU' if use_gpu: unit_type = 'GPU' for param in params.keys(): if (param not in model._diffeq_names) and (param != 'delays') and (param != 'tau_metric'): raise Exception("Parameter %s must be defined as a parameter in the model" % param) if criterion is None: criterion = GammaFactor() data = array(data) if criterion.type == 'spikes': # Make sure that 'data' is a N*2-array if data.ndim == 1: data = concatenate((zeros((len(data), 1)), data.reshape((-1, 1))), axis=1) spikes = data traces = None groups = int(array(data)[:, 0].max() + 1) # number of target trains elif criterion.type == 'trace': if data.ndim == 1: data = data.reshape((1,-1)) spikes = None traces = data groups = data.shape[0] elif criterion.type == 'both': # TODO log_warn("Not implemented yet") pass inputs = input if inputs.ndim==1: inputs = inputs.reshape((1,-1)) # dt must be set if dt is None: raise Exception('dt (sampling frequency of the input) must be set') # default overlap when no time slicing if slices == 1: overlap = 0*ms if onset is None: onset = overlap # check numerical integration method if use_gpu and method not in ['Euler', 'RK', 'exponential_Euler']: raise Exception("The method can only be 'Euler', 'RK', or 'exponential_Euler' when using the GPU") if method not in ['Euler', 'RK', 'exponential_Euler', 'linear', 'nonlinear']: raise Exception("The method can only be 'Euler', 'RK', 'exponential_Euler', 'linear', or 'nonlinear'") # determines whether optimization over refractoriness or not if type(refractory) is tuple or type(refractory) is list: params['refractory'] = refractory max_refractory = refractory[-1] else: max_refractory = None # Initialize GPU if use_gpu: set_gpu_device(0) # if neuron_group is not None: # self.neuron_group = neuron_group # self.given_neuron_group = True # else: # self.given_neuron_group = False simulator = Simulator(model, reset, threshold, inputs, input_var = input_var, dt = dt, refractory = refractory, max_refractory = max_refractory, spikes = spikes, traces = traces, groups = groups, slices = slices, overlap = overlap, onset = onset, neurons = neurons, initial_values = initial_values, unit_type = unit_type, stepsize = stepsize, precision = precision, ntrials=ntrials, criterion = criterion, statemonitor_var = record, spikemonitor = spikemonitor, nbr_spikes = nbr_spikes, method = method, # stand_alone=stand_alone, # self.neuron_group, # self.given_neuron_group ) criterion_values = simulator.run(**params) if record is not None and spikemonitor is False: record_values = simulator.get_statemonitor_values() return criterion_values, record_values elif record is not None and spikemonitor is True: record_values = simulator.get_statemonitor_values() spike_times = simulator.get_spikemonitor_values() return criterion_values, record_values,spike_times elif record is None and spikemonitor is True: spike_times = simulator.get_spikemonitor_values() return criterion_values,spike_times else: return criterion_values
For more details on the gamma factor, see `Jolivet et al. 2008, "A benchmark test for a quantitative assessment of simple neuron models", J. Neurosci. Methods <http://www.ncbi.nlm.nih.gov/pubmed/18160135>`__ (available in PDF `here <http://icwww.epfl.ch/~gerstner/PUBLICATIONS/Jolivet08.pdf>`__). """ for param in params.keys(): if (param not in model._diffeq_names) and (param != 'delays'): raise Exception( "Parameter %s must be defined as a parameter in the model" % param) if criterion is None: criterion = GammaFactor() data = array(data) if criterion.type == 'spikes': # Make sure that 'data' is a N*2-array if data.ndim == 1: data = concatenate((zeros((len(data), 1)), data.reshape((-1, 1))), axis=1) spikes = data traces = None groups = int(array(data)[:, 0].max() + 1) # number of target trains elif criterion.type == 'trace': if data.ndim == 1: data = data.reshape((1, -1)) spikes = None traces = data groups = data.shape[0] elif criterion.type == 'both':
``or[i][key]`` where ``i`` is a group index, is the same as ``or[i].best_pos[key]``. For more details on the gamma factor, see `Jolivet et al. 2008, "A benchmark test for a quantitative assessment of simple neuron models", J. Neurosci. Methods <http://www.ncbi.nlm.nih.gov/pubmed/18160135>`__ (available in PDF `here <http://icwww.epfl.ch/~gerstner/PUBLICATIONS/Jolivet08.pdf>`__). """ for param in params.keys(): if (param not in model._diffeq_names) and (param != 'delays'): raise Exception("Parameter %s must be defined as a parameter in the model" % param) if criterion is None: criterion = GammaFactor() data = array(data) if criterion.type == 'spikes': # Make sure that 'data' is a N*2-array if data.ndim == 1: data = concatenate((zeros((len(data), 1)), data.reshape((-1, 1))), axis=1) spikes = data traces = None groups = int(array(data)[:, 0].max() + 1) # number of target trains elif criterion.type == 'trace': if data.ndim == 1: data = data.reshape((1,-1)) spikes = None traces = data groups = data.shape[0] elif criterion.type == 'both': # TODO
def initialize_refractory(self, refractory): if isinstance(refractory, float): refractory = refractory*ones(self.N) self.refractory_arr = gpuarray.to_gpu(array(rint(refractory / self.dt), dtype=int32)) self.next_allowed_spiketime_arr = gpuarray.to_gpu(-ones(self.N, dtype=int32))
def modelfitting(model=None, reset=None, threshold=None, refractory=0*ms, data=None, input_var='I', input=None, dt=None, popsize=1000, maxiter=10, slices=1, overlap=0*second, initial_values=None, stepsize=100 * ms, unit_type='CPU', total_units=None, cpu=None, gpu=None, precision='double', # set to 'float' or 'double' to specify single or double precision on the GPU machines=[], allocation=None, returninfo=False, scaling=None, algorithm=CMAES, criterion=None, optparams={}, method='Euler', **params): """ Model fitting function. Fits a spiking neuron model to electrophysiological data (injected current and spikes). See also the section :ref:`model-fitting-library` in the user manual. **Arguments** ``model`` An :class:`~brian.Equations` object containing the equations defining the model. ``reset`` A reset value for the membrane potential, or a string containing the reset equations. ``threshold`` A threshold value for the membrane potential, or a string containing the threshold equations. ``refractory`` The refractory period in second. If it's a single value, the same refractory will be used in all the simulations. If it's a list or a tuple, the fitting will also optimize the refractory period (see ``**params`` below). Warning: when using a refractory period, you can't use a custom reset, only a fixed one. ``data`` A list of spike times, or a list of several spike trains as a list of pairs (index, spike time) if the fit must be performed in parallel over several target spike trains. In this case, the modelfitting function returns as many parameters sets as target spike trains. ``input_var='I'`` The variable name used in the equations for the input current. ``input`` A vector of values containing the time-varying signal the neuron responds to (generally an injected current). ``dt`` The time step of the input (the inverse of the sampling frequency). ``**params`` The list of parameters to fit the model with. Each parameter must be set as follows: ``param_name=[bound_min, min, max, bound_max]`` where ``bound_min`` and ``bound_max`` are the boundaries, and ``min`` and ``max`` specify the interval from which the parameter values are uniformly sampled at the beginning of the optimization algorithm. If not using boundaries, set ``param_name=[min, max]``. Also, you can add a fit parameter which is a spike delay for all spikes : add the special parameter ``delays`` in ``**params``, for example ``modelfitting(..., delays=[-10*ms, 10*ms])``. You can also add fit the refractory period by specifying ``modelfitting(..., refractory=[-10*ms, 10*ms])``. ``popsize`` Size of the population (number of particles) per target train used by the optimization algorithm. ``maxiter`` Number of iterations in the optimization algorithm. ``optparams`` Optimization algorithm parameters. It is a dictionary: keys are parameter names, values are parameter values or lists of parameters (one value per group). This argument is specific to the optimization algorithm used. See :class:`PSO`, :class:`GA`, :class:`CMAES`. ``delta=4*ms`` The precision factor delta (a scalar value in second). ``slices=1`` The number of time slices to use. ``overlap=0*ms`` When using several time slices, the overlap between consecutive slices, in seconds. ``initial_values`` A dictionary containing the initial values for the state variables. ``cpu`` The number of CPUs to use in parallel. It is set to the number of CPUs in the machine by default. ``gpu`` The number of GPUs to use in parallel. It is set to the number of GPUs in the machine by default. ``precision`` GPU only: a string set to either ``float`` or ``double`` to specify whether to use single or double precision on the GPU. If it is not specified, it will use the best precision available. ``returninfo=False`` Boolean indicating whether the modelfitting function should return technical information about the optimization. ``scaling=None`` Specify the scaling used for the parameters during the optimization. It can be ``None`` or ``'mapminmax'``. It is ``None`` by default (no scaling), and ``mapminmax`` by default for the CMAES algorithm. ``algorithm=CMAES`` ``optparams={}`` Optimization parameters. See ``method='Euler'`` Integration scheme used on the CPU and GPU: ``'Euler'`` (default), ``RK``, or ``exponential_Euler``. See also :ref:`numerical-integration`. ``machines=[]`` A list of machine names to use in parallel. See :ref:`modelfitting-clusters`. **Return values** Return an :class:`OptimizationResult` object with the following attributes: ``best_pos`` Minimizing position found by the algorithm. For array-like fitness functions, it is a single vector if there is one group, or a list of vectors. For keyword-like fitness functions, it is a dictionary where keys are parameter names and values are numeric values. If there are several groups, it is a list of dictionaries. ``best_fit`` The value of the fitness function for the best positions. It is a single value if there is one group, or it is a list if there are several groups. ``info`` A dictionary containing various information about the optimization. Also, the following syntax is possible with an ``OptimizationResult`` instance ``or``. The ``key`` is either an optimizing parameter name for keyword-like fitness functions, or a dimension index for array-like fitness functions. ``or[key]`` it is the best ``key`` parameter found (single value), or the list of the best parameters ``key`` found for all groups. ``or[i]`` where ``i`` is a group index. This object has attributes ``best_pos``, ``best_fit``, ``info`` but only for group ``i``. ``or[i][key]`` where ``i`` is a group index, is the same as ``or[i].best_pos[key]``. For more details on the gamma factor, see `Jolivet et al. 2008, "A benchmark test for a quantitative assessment of simple neuron models", J. Neurosci. Methods <http://www.ncbi.nlm.nih.gov/pubmed/18160135>`__ (available in PDF `here <http://icwww.epfl.ch/~gerstner/PUBLICATIONS/Jolivet08.pdf>`__). """ if criterion is None: criterion = GammaFactor() data = array(data) if criterion.type == 'spikes': # Make sure that 'data' is a N*2-array if data.ndim == 1: data = concatenate((zeros((len(data), 1)), data.reshape((-1, 1))), axis=1) spikes = data traces = None elif criterion.type == 'trace': if data.ndim == 1: data = data.reshape((1,-1)) spikes = None traces = data elif criterion.type == 'both': # TODO log_warn("Not implemented yet") pass inputs = input if inputs.ndim==1: inputs = inputs.reshape((1,-1)) # dt must be set if dt is None: raise Exception('dt (sampling frequency of the input) must be set') # default overlap when no time slicing if slices == 1: overlap = 0*ms # default allocation if cpu is None and gpu is None: if CANUSEGPU: gpu = 1 else: cpu = MAXCPU-1 # check numerical integration method if (gpu>0 or unit_type == 'GPU') and method not in ['Euler', 'RK', 'exponential_Euler']: raise Exception("The method can only be 'Euler', 'RK', or 'exponential_Euler' when using the GPU") if method not in ['Euler', 'RK', 'exponential_Euler', 'linear', 'nonlinear']: raise Exception("The method can only be 'Euler', 'RK', 'exponential_Euler', 'linear', or 'nonlinear'") if (algorithm == CMAES) & (scaling is None): scaling = 'mapminmax' # determines whether optimization over refractoriness or not if type(refractory) is tuple or type(refractory) is list: params['refractory'] = refractory max_refractory = refractory[-1] # refractory = 'refractory' else: max_refractory = None # common values # group_size = particles # Number of particles per target train groups = int(array(data)[:, 0].max() + 1) # number of target trains # N = group_size * group_count # number of neurons duration = len(input) * dt # duration of the input # keyword arguments for Modelfitting initialize kwds = dict( model=cPickle.dumps(model), threshold=threshold, reset=reset, refractory=refractory, max_refractory=max_refractory, input_var=input_var, dt=dt, duration=duration, criterion=criterion, slices=slices, overlap=overlap, returninfo=returninfo, precision=precision, stepsize=stepsize, method=method, onset=overlap) shared_data = dict(inputs=inputs, traces=traces, spikes=spikes, initial_values=initial_values) r = maximize( ModelFitting, shared_data=shared_data, kwds = kwds, groups=groups, popsize=popsize, maxiter=maxiter, optparams=optparams, unit_type = unit_type, machines=machines, allocation=allocation, cpu=cpu, gpu=gpu, returninfo=returninfo, codedependencies=[], algorithm=algorithm, scaling=scaling, **params) # r is (results, fitinfo) or (results) return r
def initialize_delays(self, spikedelays): self.spikedelay_arr = gpuarray.to_gpu( array(rint(spikedelays / self.dt), dtype=int32))
def initialize_spikes(self, spiketimes, spiketimes_indices): self.spiketimes = gpuarray.to_gpu( array(rint(spiketimes / self.dt), dtype=int32)) self.spiketime_indices = gpuarray.to_gpu( array(spiketimes_indices, dtype=int32))
For more details on the gamma factor, see `Jolivet et al. 2008, "A benchmark test for a quantitative assessment of simple neuron models", J. Neurosci. Methods <http://www.ncbi.nlm.nih.gov/pubmed/18160135>`__ (available in PDF `here <http://icwww.epfl.ch/~gerstner/PUBLICATIONS/Jolivet08.pdf>`__). """ for param in params.keys(): if (param not in model._diffeq_names) and (param != 'delays') and ( param != 'tau_metric'): raise Exception( "Parameter %s must be defined as a parameter in the model" % param) if criterion is None: criterion = GammaFactor() data = array(data) if criterion.type == 'spikes': # Make sure that 'data' is a N*2-array if data.ndim == 1: data = concatenate((zeros((len(data), 1)), data.reshape((-1, 1))), axis=1) spikes = data traces = None if ntrials > 1: groups = 1 else: groups = int(array(data)[:, 0].max() + 1) # number of target trains elif criterion.type == 'trace': if data.ndim == 1:
def initialize_traces(self, traces, traces_offset): self.traces = gpuarray.to_gpu(array(traces, dtype=double)) self.traces_offset = gpuarray.to_gpu(array(traces_offset, dtype=int32))
def initialize_delays(self, spikedelays): self.spikedelay_arr = gpuarray.to_gpu(array(rint(spikedelays / self.dt), dtype=int32))
def simulate( model, reset=None, threshold=None, input=None, input_var="I", dt=defaultclock.dt, refractory=0 * ms, max_refractory=None, data=None, groups=1, slices=1, overlap=0 * second, neurons=1, initial_values=None, use_gpu=False, stepsize=100 * ms, precision="double", criterion=None, record=None, method="Euler", **params ): unit_type = "CPU" if use_gpu: unit_type = "GPU" for param in params.keys(): if (param not in model._diffeq_names) and (param != "delays"): raise Exception("Parameter %s must be defined as a parameter in the model" % param) if criterion is None: criterion = GammaFactor() data = array(data) if criterion.type == "spikes": # Make sure that 'data' is a N*2-array if data.ndim == 1: data = concatenate((zeros((len(data), 1)), data.reshape((-1, 1))), axis=1) spikes = data traces = None groups = int(array(data)[:, 0].max() + 1) # number of target trains elif criterion.type == "trace": if data.ndim == 1: data = data.reshape((1, -1)) spikes = None traces = data groups = data.shape[0] elif criterion.type == "both": # TODO log_warn("Not implemented yet") pass inputs = input if inputs.ndim == 1: inputs = inputs.reshape((1, -1)) # dt must be set if dt is None: raise Exception("dt (sampling frequency of the input) must be set") # default overlap when no time slicing if slices == 1: overlap = 0 * ms # check numerical integration method if use_gpu and method not in ["Euler", "RK", "exponential_Euler"]: raise Exception("The method can only be 'Euler', 'RK', or 'exponential_Euler' when using the GPU") if method not in ["Euler", "RK", "exponential_Euler", "linear", "nonlinear"]: raise Exception("The method can only be 'Euler', 'RK', 'exponential_Euler', 'linear', or 'nonlinear'") # determines whether optimization over refractoriness or not if type(refractory) is tuple or type(refractory) is list: params["refractory"] = refractory max_refractory = refractory[-1] else: max_refractory = None # Initialize GPU if use_gpu: set_gpu_device(0) simulator = Simulator( model, reset, threshold, inputs, input_var=input_var, dt=dt, refractory=refractory, max_refractory=max_refractory, spikes=spikes, traces=traces, groups=groups, slices=slices, overlap=overlap, onset=overlap, neurons=neurons, initial_values=initial_values, unit_type=unit_type, stepsize=stepsize, precision=precision, criterion=criterion, statemonitor_var=record, method=method, ) criterion_values = simulator.run(**params) if record is not None: record_values = simulator.get_statemonitor_values() return criterion_values, record_values else: return criterion_values