def plot_raster3d(): ax = Axes3D(fig) y = np.array(spike_monitor.i) % num_neuron z = np.array(spike_monitor.i) // num_neuron x = spike_monitor.t / ms ax.plot(x, y, z, c="k", marker=".", markersize=2, linewidth=0, alpha=0.7) ax.set_xlabel('Time') ax.set_xlim(0, 500) ax.set_ylabel('1st dimension') ax.set_ylim(0, num_neuron) ax.set_zlabel('2nd dimension') ax.set_zlim(0, num_neuron) ax.view_init(30, -70) plt.savefig(num_trial + 'raster_2d.png', quality=95)
def test_correct_solution_2D(M): """ Function to test if solution is correct, returning detailed results. M is a 2D matrix, i.e. cell-wise competition is assumed to have a winner. """ # Check if matrix is valid size. M = np.array(M) nrow, ncol = M.shape if nrow != ncol: raise ValueError('Matrix is not square size!') if not np.sqrt(nrow).is_integer(): raise ValueError('Matrix length is not a square number!') unique_vals = np.arange(nrow) + 1 # Test each row. row_correct = np.array( [np.array_equal(np.unique(M[i, :]), unique_vals) for i in range(nrow)]) # Test each column. col_correct = np.array( [np.array_equal(np.unique(M[:, j]), unique_vals) for j in range(ncol)]) # Test each sub-rectangle. nsrow, nscol = int(np.sqrt(nrow)), int(np.sqrt(ncol)) sub_correct = [[ np.array_equal( np.unique(M[(nsrow * i):(nsrow * (i + 1)), (nscol * j):(nscol * (j + 1))]), unique_vals) for j in range(nscol) ] for i in range(nsrow)] sub_correct = np.array(sub_correct) # Collest test results. test_res = {'rows': row_correct, 'cols': col_correct, 'subs': sub_correct} return test_res
def _extract_state_monitor(self, monitor): self.f_set(record_variables=monitor.record_variables) self.f_set(record=monitor.record) self.f_set(when=monitor.when) self.f_set(source=str(monitor.source)) self.f_set(name=monitor.name) times = np.array(monitor.t[:]) if len(times) > 0: self.f_set(t=times) for varname in monitor.record_variables: val = getattr(monitor, varname) self.f_set(**{varname: val})
def _extract_state_monitor(self, monitor): self.f_set(record_variables=monitor.record_variables) self.f_set(record=monitor.record) self.f_set(when=monitor.when) self.f_set(source=str(monitor.source)) self.f_set(name=monitor.name) times=np.array(monitor.t[:]) if len(times) > 0: self.f_set(t=times) for varname in monitor.record_variables: val = getattr(monitor, varname) self.f_set(**{varname: val})
def experimenter_bias(self): """ Shows the statistics of the average recording across all experimenters """ # extracting rat id list id_list = [rat_id for rat_id in self.data.data_vars] # extracting experimenters name list - conversion for set and back to list for uniqueness exp_name_list = [self.data[id].experimenter_name for id in id_list] # extracting mean, average and std descriptors = [(self.data[id].mean(), self.data[id].std(), self.data[id].median()) for id in id_list] # creating dataFrame variables avrg = np.array(descriptors)[:, 0] std = np.array(descriptors)[:, 1] med = np.array(descriptors)[:, 2] # dataframe instance plt.figure() df = pd.DataFrame({ 'average': avrg, 'std': std, 'median': med }, index=exp_name_list) # barplot df.plot.bar(rot=0) plt.show()
f = h5py.File(STDP_WEIGHTS_FILE) weights = f["weights"][:] f.close() e_synapses.w = weights * mV else: print("Initating new weights") # adjust initiated weights to force output spike e_synapses.w = 'rand()**4 * 2*mV' # mon = StateMonitor(neurons, 'V', record=0) spike_mon = SpikeMonitor(neurons) run(sim_time, report='stdout') weights = np.array(e_synapses.w / mV) f = h5py.File(STDP_WEIGHTS_FILE, 'w') f["weights"] = weights f.close() fig, ax = plt.subplots() ax.hist(e_synapses.w / mV, bins=50) ax.set(xlabel='$w_e$ (mV)') fig, ax = plt.subplots() ax.vlines(np.arange(n_repetitions * 10) * repeat_every / second, 0, 100, color='gray', alpha=0.5)
def plot_sudoku(M, pM=None, cM=None, add_errors=None, remove_lbls=True, title=None, fname=None): """ Plot Sudoku matrix, optionally adding errors. M: a complete or partial solution. pM: a partial solution, if provided, numbers are colored by differently. cM: confidence matrix to scale size of numbers with. """ # Init. M = np.array(M) if pM is not None: pM = np.array(pM) if cM is not None: cM = np.array(cM) nrow, ncol = M.shape nsrow, nscol = int(np.sqrt(nrow)), int(np.sqrt(ncol)) if add_errors is None: # Add errors if matrix is complete. add_errors = not np.any(np.isnan(M)) # Init figure. base_cell_size = 1 ndigits_fac = 1 if nrow < 10 else 1.1 size = ndigits_fac * nrow * base_cell_size fig = plt.figure(figsize=(size, size)) ax = plt.axes() # Plot matrix. sns.heatmap(M, vmin=0, vmax=0, cmap='OrRd', cbar=False, square=True, linecolor='k', linewidth=1, annot=False, ax=ax) # Add cell numbers. for i, j in sudoku_util.all_ij_pairs(nrow): lbl = int(M[i, j]) if not np.isnan(M[i, j]) else '' # Color: is cell present in partial solution? c = 'k' if pM is None else 'g' if not np.isnan(pM[i, j]) else 'b' # Size: confidence level of cell. s = 30 if cM is None else 10 + 20 * cM[i, j] # Plot cell label. ax.text(j + 0.5, nrow - i - 0.5, lbl, va='center', ha='center', weight='bold', fontsize=s, color=c) # Remove tick labels. if remove_lbls: ax.tick_params(labelbottom='off') ax.tick_params(labelleft='off') # Embolden border lines. kws = {'linewidth': 6, 'color': 'k'} for i in range(nsrow + 1): ax.plot([0, ncol], [i * nsrow, i * nsrow], **kws) for j in range(nscol + 1): ax.plot([j * nscol, j * nscol], [0, ncol], **kws) # Highlight errors. if add_errors: col, alpha = 'r', 1. / 3 test_res = sudoku_util.test_correct_solution_2D(M) # Rows. for i in np.where(np.logical_not(test_res['rows']))[0]: irow = nrow - i - 1 rect = mpl.patches.Rectangle((0, irow), ncol, 1, alpha=alpha, fc=col) ax.add_patch(rect) # Columns. for j in np.where(np.logical_not(test_res['cols']))[0]: rect = mpl.patches.Rectangle((j, 0), 1, nrow, alpha=alpha, fc=col) ax.add_patch(rect) # Sub-squares. for i, j in np.argwhere(np.logical_not(test_res['subs'])): isrow = nsrow - i - 1 rect = mpl.patches.Rectangle((j * nscol, isrow * nsrow), nscol, nsrow, alpha=alpha, fc=col) ax.add_patch(rect) # Add title. if title is not None: ax.set_title(title, fontsize='xx-large') # Save figure. if fname is not None: fig.savefig(fname, dpi=300, bbox_inches='tight') return ax
def __init__( self, weights: np.ndarray, weights_in: np.ndarray, dt: float = 0.1 * ms, noise_std: float = 0 * mV, refractory=0 * ms, neuron_params=None, syn_params=None, integrator_name: str = "rk4", name: str = "unnamed", ): """ Construct a spiking recurrent layer with IAF neurons, with a Brian2 back-end :param weights: np.array NxN weight matrix :param weights_in: np.array 1xN input weight matrix. :param refractory: float Refractory period after each spike. Default: 0ms :param neuron_params: dict Parameters to over overwriting neuron defaulst :param syn_params: dict Parameters to over overwriting synapse defaulst :param integrator_name: str Integrator to use for simulation. Default: 'exact' :param name: str Name for the layer. Default: 'unnamed' """ warn("RecDynapseBrian: This layer is deprecated.") # - Call super constructor super().__init__( weights=weights, dt=np.asarray(dt), noise_std=np.asarray(noise_std), name=name, ) # - Input weights must be provided assert weights_in is not None, "weights_in must be provided." # - Warn that nosie is not implemented if noise_std != 0: print("WARNING: Noise is currently not implemented in this layer.") # - Set up spike source to receive spiking input self._input_generator = b2.SpikeGeneratorGroup( self.size, [0], [0 * second], dt=np.asarray(dt) * second) # - Handle unit of dt: if no unit provided, assume it is in seconds dt = np.asscalar(np.array(dt)) * second ### --- Neurons # - Set up reservoir neurons self._neuron_group = teiliNG( N=self.size, equation_builder=teiliDPIEqts(num_inputs=2), name="reservoir_neurons", refractory=refractory, method=integrator_name, dt=dt, ) # - Overwrite default neuron parameters if neuron_params is not None: self._neuron_group.set_params( dict(dTeiliNeuronParam, **neuron_params)) else: self._neuron_group.set_params(dTeiliNeuronParam) ### --- Synapses # - Add recurrent synapses (all-to-all) self._rec_synapses = teiliSyn( self._neuron_group, self._neuron_group, equation_builder=teiliDPISynEqts, method=integrator_name, dt=dt, name="reservoir_recurrent_synapses", ) self._rec_synapses.connect() # - Add source -> reservoir synapses (one-to-one) self._inp_synapses = teiliSyn( self._input_generator, self._neuron_group, equation_builder=teiliDPISynEqts, method=integrator_name, dt=np.asarray(dt) * second, name="receiver_synapses", ) # Each spike generator neuron corresponds to one reservoir neuron self._inp_synapses.connect("i==j") # - Overwrite default synapse parameters if syn_params is not None: self._rec_synapses.set_params(neuron_params) self._inp_synapses.set_params(neuron_params) # - Add spike monitor to record layer outputs self._spike_monitor = b2.SpikeMonitor(self._neuron_group, record=True, name="layer_spikes") # - Call Network constructor self._net = b2.Network( self._neuron_group, self._rec_synapses, self._input_generator, self._inp_synapses, self._spike_monitor, name="recurrent_spiking_layer", ) # - Record neuron / synapse parameters # automatically sets weights via setters self.weights = weights self.weights_in = weights_in # - Store "reset" state self._net.store("reset")
IMG_SIZE = 784 bin_size = 2 * ms p = 1 * Hz * bin_size # Firing rate per neuron: 1Hz total = 50 * second # Total length of our stimulus of one img pattern_length = 250 * ms repeat_every = pattern_length * 4 n_repetitions = int(total / repeat_every) f = h5py.File(MNIST_TRAIN_HDF5_FILE, 'r') train_img = f["img"][:] train_label = f["label"][:] f.close() N = 100 global_indices = np.array([]) global_times = np.array([]) start_time = time.time() for i in range(N): spikes = np.random.rand(IMG_SIZE, int(total / bin_size)) < p # create zero pattern first for we only fill nonzero position after pattern = np.zeros([IMG_SIZE, int(pattern_length / bin_size)]) img_flatten = np.array(train_img[i]).flatten() # This parameter is gotten using several experiments rates = img_flatten / 255 * 125 * Hz inp = PoissonGroup(IMG_SIZE, rates) spikeMonitor = SpikeMonitor(inp)