def initialize(self,tau_metric): self.delay_range =max(self.delays)- min(self.delays)#delay range self.min_delay = abs(min(self.delays))#minimum of possible delay self.corr_vector=zeros(self.N) self.norm_pop = zeros(self.N) self.norm_target = zeros(self.N) self.nbr_neurons_group = self.N/self.K eqs=""" tau:second dv/dt=(-v)/tau: volt """ # network to convolve target spikes with the kernel self.input_target=SpikeGeneratorGroup(self.K,self.spikes,clock=self.group.clock) self.kernel_target=NeuronGroup(self.N,model=eqs,clock=self.group.clock) self.C_target = DelayConnection(self.input_target, self.kernel_target, 'v', structure='sparse', max_delay=self.min_delay) self.kernel_target.tau=tau_metric for igroup in xrange(self.K): self.C_target.W[igroup,igroup*self.nbr_neurons_group:(1+igroup)*self.nbr_neurons_group] = ones(self.nbr_neurons_group) self.C_target.delay[igroup,igroup*self.nbr_neurons_group:(1+igroup)*self.nbr_neurons_group] = self.min_delay * ones(self.nbr_neurons_group) # network to convolve population spikes with the kernel self.kernel_population=NeuronGroup(self.N,model=eqs,clock=self.group.clock) self.C_population = DelayConnection(self.group, self.kernel_population, 'v', structure='sparse', max_delay=self.delay_range) for iN in xrange(self.N): self.C_population.delay[iN,iN] = diagflat(self.min_delay + self.delays[iN]) self.C_population.connect_one_to_one(self.group,self.kernel_population) self.kernel_population.tau=tau_metric self.spikecount = SpikeCounter(self.group) self.contained_objects = [self.kernel_population,self.C_population,self.spikecount,self.input_target,self.C_target,self.kernel_target]
def __init__( self, model, reset, threshold, inputs, input_var="I", dt=defaultclock.dt, refractory=0 * ms, max_refractory=None, spikes=None, traces=None, groups=1, slices=1, overlap=0 * second, onset=0 * second, neurons=1000, # = nodesize = number of neurons on this node = total number of neurons/slices initial_values=None, unit_type="CPU", stepsize=100 * ms, precision="double", criterion=None, statemonitor_var=None, method="Euler", ): self.model = model self.reset = reset self.threshold = threshold self.inputs = inputs self.input_var = input_var self.dt = dt self.refractory = refractory self.max_refractory = max_refractory self.spikes = spikes self.traces = traces self.initial_values = initial_values self.groups = groups self.slices = slices self.overlap = overlap self.onset = onset self.neurons = neurons self.unit_type = unit_type self.statemonitor_var = statemonitor_var self.stepsize = stepsize self.precision = precision self.criterion = criterion self.method = method self.use_gpu = self.unit_type == "GPU" if self.statemonitor_var is not None: self.statemonitor_values = zeros(self.neurons) self.initialize_neurongroup() self.transform_data() self.inject_input() self.initialize_criterion(delays=zeros(self.neurons)) if self.use_gpu: self.initialize_gpu()
def __init__( self, model, reset, threshold, inputs, input_var='I', dt=defaultclock.dt, refractory=0 * ms, max_refractory=None, spikes=None, traces=None, groups=1, slices=1, overlap=0 * second, onset=0 * second, neurons=1000, # = nodesize = number of neurons on this node = total number of neurons/slices initial_values=None, unit_type='CPU', stepsize=100 * ms, precision='double', criterion=None, statemonitor_var=None, method='Euler'): self.model = model self.reset = reset self.threshold = threshold self.inputs = inputs self.input_var = input_var self.dt = dt self.refractory = refractory self.max_refractory = max_refractory self.spikes = spikes self.traces = traces self.initial_values = initial_values self.groups = groups self.slices = slices self.overlap = overlap self.onset = onset self.neurons = neurons self.unit_type = unit_type self.statemonitor_var = statemonitor_var self.stepsize = stepsize self.precision = precision self.criterion = criterion self.method = method self.use_gpu = self.unit_type == 'GPU' if self.statemonitor_var is not None: self.statemonitor_values = zeros(self.neurons) self.initialize_neurongroup() self.transform_data() self.inject_input() self.initialize_criterion(delays=zeros(self.neurons)) if self.use_gpu: self.initialize_gpu()
def run(self, **param_values): delays = param_values.pop('delays', zeros(self.neurons)) # print self.refractory,self.max_refractory if self.max_refractory is not None: refractory = param_values.pop('refractory', zeros(self.neurons)) else: refractory = self.refractory*ones(self.neurons) tau_metric = param_values.pop('tau_metric', zeros(self.neurons)) self.update_neurongroup(**param_values) # repeat spike delays and refractory to take slices into account delays = kron(delays, ones(self.slices)) refractory = kron(refractory, ones(self.slices)) tau_metric = kron(tau_metric, ones(self.slices)) # TODO: add here parameters to criterion_params if a criterion must use some parameters criterion_params = dict(delays=delays) if self.criterion.__class__.__name__ == 'Brette': criterion_params['tau_metric'] = tau_metric self.update_neurongroup(**param_values) self.initialize_criterion(**criterion_params) if self.use_gpu: # Reinitializes the simulation object self.mf.reinit_vars(self.criterion_object, self.inputs_inline, self.inputs_offset, self.spikes_inline, self.spikes_offset, self.traces_inline, self.traces_offset, delays, refractory ) # LAUNCHES the simulation on the GPU self.mf.launch(self.sliced_duration, self.stepsize) # Synchronize the GPU values with a call to gpuarray.get() self.criterion_object.update_gpu_values() else: # set the refractory period if self.max_refractory is not None: self.group.refractory = refractory # Launch the simulation on the CPU self.group.clock.reinit() net = Network(self.group, self.criterion_object) if self.statemonitor_var is not None: self.statemonitors = [] for state in self.statemonitor_var: monitor = StateMonitor(self.group, state, record=True) self.statemonitors.append(monitor) net.add(monitor) net.run(self.sliced_duration) sliced_values = self.criterion_object.get_values() combined_values = self.combine_sliced_values(sliced_values) values = self.criterion_object.normalize(combined_values) return values
def initialize_cuda_variables(self): """ Initialize GPU variables to pass to the kernel """ self.spike_count_gpu = gpuarray.to_gpu(zeros(self.N, dtype=int32)) self.coincidences_gpu = gpuarray.to_gpu(zeros(self.N, dtype=int32)) if self.algorithm == 'exclusive': self.last_spike_allowed_arr = gpuarray.to_gpu(zeros(self.N, dtype=bool)) self.next_spike_allowed_arr = gpuarray.to_gpu(ones(self.N, dtype=bool))
def initialize_cuda_variables(self): """ Initialize GPU variables to pass to the kernel """ self.spike_count_gpu = gpuarray.to_gpu(zeros(self.N, dtype=int32)) self.coincidences_gpu = gpuarray.to_gpu(zeros(self.N, dtype=int32)) if self.algorithm == 'exclusive': self.last_spike_allowed_arr = gpuarray.to_gpu( zeros(self.N, dtype=bool)) self.next_spike_allowed_arr = gpuarray.to_gpu( ones(self.N, dtype=bool))
def initialize_statemonitor(self): self.statemonitor_values = [gpuarray.to_gpu(zeros(self.N*self.duration, dtype=self.precision)) for state in self.statemonitor_var] self.statemonitor_offsets = gpuarray.to_gpu(arange(0, self.duration*self.N+1, self.duration, dtype=int32))
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, neurons, input, spikes = None, traces = None, dt = defaultclock.dt, slices = 1, overlap = 0*ms, groups = 1,ntrials=1): self.neurons = neurons # number of particles on the node self.input = input # a IxT array self.spikes = spikes # a list of spikes [(i,t)...] self.traces = traces # a KxT array self.slices = slices self.overlap = overlap self.groups = groups self.ntrials=ntrials self.dt = dt # ensure 2 dimensions if self.input.ndim == 1: self.input = self.input.reshape((1,-1)) if self.traces is not None: if self.traces.ndim == 1: self.traces = self.traces.reshape((1,-1)) self.inputs_count = self.input.shape[0] self.T = self.input.shape[1] # number of steps self.duration = self.T*self.dt self.subpopsize = self.neurons/self.groups # number of neurons per group: nodesize/groups self.input = self.input[:,0:self.slices * (self.T / self.slices)] # makes sure that len(input) is a multiple of slices self.sliced_steps = self.T / self.slices # timesteps per slice self.overlap_steps = int(self.overlap / self.dt) # timesteps during the overlap self.total_steps = self.sliced_steps + self.overlap_steps # total number of timesteps self.sliced_duration = self.overlap + self.duration / self.slices # duration of the vectorized simulation self.N = self.neurons * self.slices # TOTAL number of neurons on this node self.input = hstack((zeros((self.inputs_count, self.overlap_steps)), self.input)) # add zeros at the beginning because there is no overlap from the previous slice
def initialize_spikemonitor(self): self.spikemonitor_values = gpuarray.to_gpu( zeros(self.N * self.nbr_spikes, dtype=self.precision)) self.spikemonitor_offsets = gpuarray.to_gpu( arange(0, self.nbr_spikes * self.N + 1, self.nbr_spikes, dtype=int32))
def initialize_statemonitor(self): self.statemonitor_values = [ gpuarray.to_gpu(zeros(self.N * self.duration, dtype=self.precision)) for state in self.statemonitor_var ] self.statemonitor_offsets = gpuarray.to_gpu( arange(0, self.duration * self.N + 1, self.duration, dtype=int32))
def initialize(self, p=2, varname='v'): """ Called at the beginning of every iteration. The keyword arguments here are specified in modelfitting.initialize_criterion(). """ self.p = double(p) self.varname = varname self._error = zeros((self.K, self.N))
def evaluate(self, **param_values): """ Use fitparams['delays'] to take delays into account Use fitparams['refractory'] to take refractory into account """ delays = param_values.pop('delays', zeros(self.neurons)) refractory = param_values.pop('refractory', zeros(self.neurons)) tau_metric = param_values.pop('tau_metric', zeros(self.neurons)) # repeat spike delays and refractory to take slices into account delays = kron(delays, ones(self.slices)) refractory = kron(refractory, ones(self.slices)) tau_metric = kron(tau_metric, ones(self.slices)) self.update_neurongroup(**param_values) if self.criterion.__class__.__name__ == 'Brette': self.initialize_criterion(delays,tau_metric) else: self.initialize_criterion(delays) if self.use_gpu: pass ######### # TODO ######### # # Reinitializes the simulation object # self.mf.reinit_vars(self.input, self.I_offset, self.spiketimes, self.spiketimes_offset, delays, refractory) # # LAUNCHES the simulation on the GPU # self.mf.launch(self.duration, self.stepsize) # coincidence_count = self.mf.coincidence_count # spike_count = self.mf.spike_count else: # set the refractory period if self.max_refractory is not None: self.group.refractory = refractory # Launch the simulation on the CPU self.group.clock.reinit() net = Network(self.group, self.criterion_object) net.run(self.duration) sliced_values = self.criterion_object.get_values() combined_values = self.combine_sliced_values(sliced_values) values = self.criterion_object.normalize(combined_values) return values
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 slice_traces(self, traces): # from standard structure to standard structure k = traces.shape[0] sliced_traces = zeros((k*self.slices, self.total_steps)) for slice in xrange(self.slices): i0 = slice*k i1 = (slice+1)*k j0 = slice*self.sliced_steps j1 = (slice+1)*self.sliced_steps sliced_traces[i0:i1,self.overlap_steps:] = traces[:,j0:j1] if slice>0: sliced_traces[i0:i1,:self.overlap_steps] = traces[:,j0-self.overlap_steps:j0] return sliced_traces
def transform_data(self): self.transformer = DataTransformer(self.neurons, self.inputs, spikes = self.spikes, traces = self.traces, dt = self.dt, slices = self.slices, overlap = self.overlap, groups = self.groups,ntrials=self.ntrials) self.total_steps = self.transformer.total_steps self.sliced_duration = self.transformer.sliced_duration if self.ntrials>1: self.inputs_inline = self.inputs.flatten() self.sliced_inputs = self.inputs self.inputs_offset = zeros(self.neurons) else: self.sliced_inputs = self.transformer.slice_traces(self.inputs) self.inputs_inline, self.inputs_offset = self.transformer.transform_traces(self.sliced_inputs) if self.traces is not None: self.sliced_traces = self.transformer.slice_traces(self.traces) self.traces_inline, self.traces_offset = self.transformer.transform_traces(self.sliced_traces) else: self.sliced_traces, self.traces_inline, self.traces_offset = None, None, None if self.spikes is not None: if self.ntrials>1: self.sliced_spikes = self.transformer.slice_spikes(self.spikes) self.spikes_inline, self.trials_offset = self.transformer.transform_trials(self.spikes) self.spikes_offset = zeros((self.neurons),dtype=int) else: self.sliced_spikes = self.transformer.slice_spikes(self.spikes) self.spikes_inline, self.spikes_offset = self.transformer.transform_spikes(self.sliced_spikes) self.trials_offset=[0] else: self.sliced_spikes, self.spikes_inline, self.spikes_offset,self.trials_offset = None, None, None, None
def predict(model=None, reset=None, threshold=None, data=None, delta=4 * ms, input=None, input_var='I', dt=None, **params): """ Predicts the gamma factor of a fitted model with respect to the data with a different input current. **Arguments** ``model``, ``reset``, ``threshold``, ``input_var``, ``dt`` Same parameters as for the ``modelfitting`` function. ``input`` The input current, that can be different from the current used for the fitting procedure. ``data`` The experimental spike times to compute the gamma factor against. They have been obtained with the current ``input``. ``**params`` The best parameters returned by the ``modelfitting`` function. **Returns** ``gamma`` The gamma factor of the model spike trains against the data. If there were several groups in the fitting procedure, it is a vector containing the gamma factor for each group. """ spikes = get_spikes(model=model, reset=reset, threshold=threshold, input=input, input_var=input_var, dt=dt, **params) ngroups = len(params[params.keys()[0]]) gamma = zeros(ngroups) for i in xrange(ngroups): spk = [t for j, t in spikes if j == i] gamma[i] = gamma_factor(spk, data, delta, normalize=True, dt=dt) if len(gamma) == 1: return gamma[0] else: return gamma
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 initialize_spikemonitor(self): self.spikemonitor_values = gpuarray.to_gpu(zeros(self.N*self.nbr_spikes, dtype=self.precision)) self.spikemonitor_offsets = gpuarray.to_gpu(arange(0, self.nbr_spikes*self.N+1, self.nbr_spikes, 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_cuda_variables(self): """ Initialize GPU variables to pass to the kernel """ self.error_gpu = gpuarray.to_gpu(zeros(self.N, dtype=double))
def initialize(self, p=2, varname='v'): self.p = p self.varname = varname self._error = zeros((self.K, self.N))
def get_spikes_count(self, spikes): count = zeros(self.K) for (i,t) in spikes: count[i] += 1 return count
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
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, 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
""" 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
`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 log_warn("Not implemented yet") pass inputs = input if inputs.ndim==1:
def get_spikes_count(self, spikes): count = zeros(self.K) for (i, t) in spikes: count[i] += 1 return count
def __init__(self, model, reset, threshold, inputs, input_var = 'I', dt = defaultclock.dt, refractory = 0*ms, max_refractory = None, spikes = None, traces = None, groups = 1, slices = 1, overlap = 0*second, onset = 0*second, neurons = 1000, # = nodesize = number of neurons on this node = (total number of neurons on this node)/(number of slices) initial_values = None, unit_type = 'CPU', stepsize = 128*ms, precision = 'double', criterion = None, statemonitor_var=None, spikemonitor = False, nbr_spikes = 200, ntrials=1, method = 'Euler', # stand_alone=False, # neuron_group=None, # given_neuron_group=False ): # print refractory, max_refractory # self.neuron_group = neuron_group # self.given_neuron_group = False # self.stand_alone = given_neuron_group self.model = model self.reset = reset self.threshold = threshold self.inputs = inputs self.input_var = input_var self.dt = dt self.refractory = refractory self.max_refractory = max_refractory self.spikes = spikes self.traces = traces self.initial_values = initial_values self.groups = groups self.slices = slices self.overlap = overlap self.ntrials=ntrials self.onset = onset self.neurons = neurons self.unit_type = unit_type if type(statemonitor_var) is not list and statemonitor_var is not None: statemonitor_var = [statemonitor_var] self.statemonitor_var = statemonitor_var self.spikemonitor=spikemonitor self.nbr_spikes = nbr_spikes self.stepsize = stepsize self.precision = precision self.criterion = criterion self.method = method self.use_gpu = self.unit_type=='GPU' if self.statemonitor_var is not None: self.statemonitor_values = [zeros(self.neurons)]*len(statemonitor_var) self.initialize_neurongroup() self.transform_data() self.inject_input() if self.criterion.__class__.__name__ == 'Brette': self.initialize_criterion(delays=zeros(self.neurons),tau_metric=zeros(self.neurons)) else: self.initialize_criterion(delays=zeros(self.neurons)) if self.use_gpu: self.initialize_gpu()