def structured_connectivity(N_excitatory, Jpos, sigma): """ J– = (360 - math.sqrt(2*pi) * sigma * J+)/ (360 - math.sqrt(2*pi) * sigma) W(θi – θj) = J– + (J+ – J–)exp[–(θi – θj)^2/2σ^2] Parameters ---------- N_excitatory(int): Size of the excitatory population Jpos(float): Strength of the recurrent input within the excitatory population. sigma(float): standard deviation of the gaussian input profile in the excitatory population. Returns ------- presyn_weight : array weight profile for the structured excitatory-to-excitatory connectivity in recurrent population """ tmp = np.sqrt(2 * np.pi) * sigma Jneg = (360 - tmp * Jpos) / (360 - tmp) neurons = np.arange(N_excitatory) delta_theta = 360 * np.minimum(neurons, N_excitatory - neurons) / N_excitatory presyn_weight = ( Jneg + (Jpos - Jneg) * np.exp(-1 / 2 * delta_theta**2 / sigma**2)) return presyn_weight
def gaussian_input(num_neurons, features, width): neurons = np.arange(0, 360, 360 / num_neurons) stim = np.zeros(num_neurons) for feature in features: tuning = stats.norm.pdf(neurons, loc=feature, scale=width) tuning = np.sqrt(2 * np.pi) * width * tuning stim += tuning return stim
def structured_connectivity(N_excitatory, Jpos, sigma): tmp = np.sqrt(2 * np.pi) * sigma Jneg = (360 - tmp * Jpos) / (360 - tmp) neuron = np.arange(N_excitatory) delta_theta = 360 * np.minimum(neuron, N_excitatory - neuron) / N_excitatory presyn_weight = ( Jneg + (Jpos - Jneg) * np.exp(-1 / 2 * delta_theta**2 / sigma**2)) return presyn_weight / sum(presyn_weight) * 360
def plot_raster(): ax.plot(spike_monitor.t / ms, spike_monitor.i, c="k", marker=".", markersize=2, linewidth=0) ax.set_xlabel('Time (ms)') ax.set_xticks(np.arange(0, 2001, 100)) ax.set_ylabel('Neuron index') ax.set_ylim(0, num_neuron) ax.set_title("Raster Plot", fontsize=10) plt.savefig(num_trial + 'raster_1d.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
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) ax.vlines(np.arange(n_repetitions * 10) * repeat_every / second + pattern_length / second, 0, 100, color='gray', alpha=0.5) ax.plot(spike_mon.t / second, spike_mon.i, '|') ax.set(xlim=(0, 10), xlabel='time (s)') plt.show()
def plot_synapses(S, n, elev_azim_list, fig_dir, nspl=50): """ Visualize Sudoku connectivity S as 3D matrix from different angles. TODO: make it weighted! """ # Init params. nv = np.arange(n) xspl, yspl = calc_base_spline(nspl) # Init figure. fig = plt.figure(figsize=(10, 10)) ax = plt.axes(projection='3d') ax.set_aspect(1) node_cols = get_node_colors(n) # Plot table at the bottom. kws = {'color': 'k'} lims = [-0.5, n - 0.5] zlvl = [-0.5, -0.5] for iv in range(n + 1): lvl = iv - 0.5 lw = 4 if not iv % np.sqrt(n) else 2 ax.plot(lims, [lvl, lvl], zlvl, lw=lw, **kws) ax.plot([lvl, lvl], lims, zlvl, lw=lw, **kws) # Plot nodes. x, y, z = zip(*sudoku_util.all_ijk_triples(n)) all_node_cols = [node_cols[zi] for zi in z] ax.scatter(x, y, z, marker='o', c=all_node_cols, s=200) # Plot each connection. for idx1, idx2 in zip(S.i, S.j): i1, j1, k1 = sudoku_util.mat_idx(idx1, n) i2, j2, k2 = sudoku_util.mat_idx(idx2, n) # Get 3D curve of connection. v1, v2 = [i1, j1, k1], [i2, j2, k2] x, y, z = calc_3D_spline_coords(v1, v2, xspl, yspl) # Plot connection curve. ax.plot(x, y, z, ls='-', color=node_cols[k1], alpha=0.5, lw=0.5) # TODO: add arrow head to show direction? # Format plot. ax.set_xlabel('Row') ax.set_ylabel('Column') ax.set_zlabel('Neuron') for f_tp, f_tl in [(ax.set_xticks, ax.set_xticklabels), (ax.set_yticks, ax.set_yticklabels), (ax.set_zticks, ax.set_zticklabels)]: f_tp(nv) f_tl(nv + 1) # Set limits. lim = [-0.5, n - 0.5] ax.set_xlim(lim) ax.set_ylim(lim) ax.set_zlim(lim) # Set background color. ax.set_facecolor((1.0, 1.0, 1.0)) # Save it from different viewpoints. for elev, azim in elev_azim_list: ax.view_init(elev=elev, azim=azim) ffig = fig_dir + 'elev_{}_azim_{}.png'.format(elev, azim) fig.savefig(ffig, dpi=300, bbox_inches='tight') return ax
set_device("genn") N = 10000 # 10000 "neurons" bin_size = 2 * ms p = 1 * Hz * bin_size # Firing rate per neuron: 1Hz total = 10 * second # Total length of our stimulus spikes = np.random.rand(N, int(total / bin_size)) < p pattern_length = 250 * ms pattern = spikes[:, 0:int(pattern_length / bin_size)] repeat_every = pattern_length * 4 n_repetitions = int(total / repeat_every) for rep in np.arange(n_repetitions): spikes[:, rep * int(repeat_every / bin_size):rep * int(repeat_every / bin_size) + int(pattern_length / bin_size)] = pattern indices, time_bins = spikes.nonzero() times = time_bins * bin_size fig, ax = plt.subplots() ax.plot(times / second, indices, '.') # Add lines to show the repeated stimulation windows ax.vlines(np.arange(n_repetitions) * repeat_every / second, 0, 500, color='gray') ax.vlines(np.arange(n_repetitions) * repeat_every / second +
def all_ijk_triples(n): """Return all (i, j, k) triplets for table size n.""" nv = np.arange(n) ijk_triples = list(product(nv, nv, nv)) return ijk_triples
def all_ij_pairs(n): """Return all (i, j) pairs for table size n.""" nv = np.arange(n) ij_pairs = list(product(nv, nv)) return ij_pairs
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) run(250 * ms, report="text") indices, times = spikeMonitor.it for j in range(np.array(indices).shape[0]): pattern[indices[j]][int(times[j] / bin_size)] = True for rep in np.arange(n_repetitions): spikes[:, rep * int(repeat_every / bin_size):rep * int(repeat_every / bin_size) + int(pattern_length / bin_size)] = pattern indices, time_bins = spikes.nonzero() # add a const shift to move the spikes time later, # every img produces spikes for (total) seconds time_bins += np.repeat(i * int(total / bin_size), time_bins.shape[0]) # print("Shift Value: %d " % (i * int(total / bin_size))) times = time_bins * bin_size # plt.plot(times / second, indices, '.') # # Add lines to show the repeated stimulation windows # plt.vlines(np.arange(n_repetitions) * repeat_every / second, 0, 500, color='gray') # plt.vlines(np.arange(n_repetitions) * repeat_every / second + pattern_length / second, 0, 500, color='gray') # plt.xlim(i * 10, i*10+5)
def gaussian_input(num_neurons, center_deg, width_deg): neuron = np.arange(0, 360, 360 / num_neurons) tuning = stats.norm.pdf(neuron, loc=center_deg, scale=width_deg) return tuning * width_deg