def test_time_histogram_output(self): # Normalization mean histogram = es.time_histogram(self.spiketrains, binsize=pq.s, output="mean") targ = np.array([4, 2, 1, 1, 2, 2, 1, 0, 1, 0], dtype=float) / 2 assert_array_equal(targ.reshape(targ.size, 1), histogram.magnitude) # Normalization rate histogram = es.time_histogram(self.spiketrains, binsize=pq.s, output="rate") assert_array_equal(histogram.view(pq.Quantity), targ.reshape(targ.size, 1) * 1 / pq.s) # Normalization unspecified, raises error self.assertRaises(ValueError, es.time_histogram, self.spiketrains, binsize=pq.s, output=" ")
def test_time_histogram_tstart_tstop(self): # Start, stop short range targ = np.array([2, 1]) histogram = es.time_histogram(self.spiketrains, binsize=pq.s, t_start=5 * pq.s, t_stop=7 * pq.s) assert_array_equal(targ, histogram[:, 0].magnitude) # Test without t_stop targ = np.array([4, 2, 1, 1, 2, 2, 1, 0, 1, 0]) histogram = es.time_histogram(self.spiketrains, binsize=1 * pq.s, t_start=0 * pq.s) assert_array_equal(targ, histogram[:, 0].magnitude) # Test without t_start histogram = es.time_histogram(self.spiketrains, binsize=1 * pq.s, t_stop=10 * pq.s) assert_array_equal(targ, histogram[:, 0].magnitude)
con_number = '040' if ls_condition == 4: con_number = '100' os.chdir('/Users/jiemei/Desktop/TC_model') tc_results = './run_lgn_pgn/largernet/'+conn_weight+'/tc_csr_results' if not os.path.exists(tc_results): os.makedirs(tc_results) os.chdir(tc_results_dat) r = io.AsciiSpikeTrainIO(filename = 'tc_cell'+str(i)+'_csr'+con_number+'.dat') seg = r.read_segment(unit=ms) #print seg.spiketrains for st in seg.spiketrains: st.t_stop = 2400*ms tc_plot = es.time_histogram(seg.spiketrains, 10*ms, output='counts') plt.plot(tc_plot) plt.ylim(0, 100) os.chdir('/Users/jiemei/Desktop/TC_model/run_lgn_pgn/largernet/'+conn_weight+'/tc_csr_results') plt.savefig('tc_cell'+str(i)+'_csr'+con_number+'.png') plt.close() re_plot = [] for i in range(0, num_re_cell): os.chdir('/Users/jiemei/Desktop/TC_model') re_results = './run_lgn_pgn/largernet/'+conn_weight+'/re_csr_results' if not os.path.exists(re_results): os.makedirs(re_results) os.chdir(re_results_dat) r = io.AsciiSpikeTrainIO(filename = 're_cell'+str(i)+'_csr'+con_number+'.dat')
def test_time_histogram_binary(self): targ = np.array([2, 2, 1, 1, 2, 2, 1, 0, 1, 0]) histogram = es.time_histogram(self.spiketrains, binsize=pq.s, binary=True) assert_array_equal(targ, histogram[:, 0].magnitude)
def test_time_histogram(self): targ = np.array([4, 2, 1, 1, 2, 2, 1, 0, 1, 0]) histogram = es.time_histogram(self.spiketrains, binsize=pq.s) assert_array_equal(targ, histogram.magnitude[:, 0])
def cch(block, unit1=0, unit2=1): # Load the data sts1 = [segment.spiketrains[unit1] for segment in block.segments] sts2 = [segment.spiketrains[unit2] for segment in block.segments] # Compute the CCH w = 2 * pq.ms # binsize for CCH maxlag = 200 * pq.ms # maximum correlation lag Nlags = int((maxlag / w).simplified) CCH = neo.AnalogSignal(np.zeros(2 * Nlags + 1) * pq.dimensionless, sampling_period=w, t_start=-maxlag) for st1, st2 in zip(sts1, sts2): CCH += corr.cross_correlation_histogram(conv.BinnedSpikeTrain(st1, w), conv.BinnedSpikeTrain(st2, w), window=[-Nlags, Nlags], border_correction=False, binary=True)[0] CCH = CCH / float(len(sts1)) # Compute PSTH psth1 = stats.time_histogram(sts1, binsize=w, output='rate').rescale('Hz') psth2 = stats.time_histogram(sts2, binsize=w, output='rate').rescale('Hz') # Compute ISI dist ISIpdf1 = misc.isi_pdf(sts1, bins=w, rng=[0 * pq.s, None], density=True) ISIpdf2 = misc.isi_pdf(sts2, bins=w, rng=[0 * pq.s, None], density=True) # plot plt.figure(figsize=(12, 8)) plt.subplots_adjust(top=.85, right=.85, left=.2, bottom=.1, hspace=.7, wspace=.3) num_row, num_col = 4, 3 ax = plt.subplot2grid((num_row, num_col), (0, 0), rowspan=1, colspan=2) misc.raster(sts1, ms=2, xlabel='time', ylabel='trial id', color='r') plt.subplot2grid((num_row, num_col), (1, 0), rowspan=1, colspan=2, sharex=ax) misc.raster(sts2, ms=2, xlabel='time', ylabel='trial id', color='b') plt.subplot2grid((num_row, num_col), (2, 0), rowspan=2, colspan=2, sharex=ax) plt.title('PSTH') plt.plot(psth1.times, psth1, color='r') plt.plot(psth2.times, psth2, color='b') ax.set_xlim(0, 4010) #max(psth1.times.magnitude)) plt.subplot2grid((num_row, num_col), (0, 2), rowspan=1, colspan=1) plt.plot([len(st) for st in sts1], range(1, len(sts1) + 1), '.-', ms=5, color='r') plt.title('Spike Count') plt.ylabel('trial id') plt.subplot2grid((num_row, num_col), (1, 2), rowspan=1, colspan=1) plt.plot([len(st) for st in sts2], range(1, len(sts2) + 1), '.-', ms=5, color='b') plt.ylabel('trial id') plt.subplot2grid((num_row, num_col), (2, 2), rowspan=2, colspan=1) plt.plot(ISIpdf1.times, ISIpdf1, color='r') plt.plot(ISIpdf2.times, ISIpdf2, color='b') plt.title('ISI distribution') # Plot the CCH plt.figure(figsize=(12, 8)) plt.subplot2grid((2, 2), (1, 1), rowspan=2, colspan=2) plt.plot(CCH.times.rescale(pq.ms), CCH, 'k-', label='raw CCH') plt.title('CCH') plt.xlabel('time lag (%s)' % (CCH.times.units.__str__().split(' ')[-1])) plt.ylabel('counts') plt.xlim(-maxlag, maxlag) plt.legend() plt.show()
from elephant.spike_train_generation import homogeneous_poisson_process from quantities import Hz, s, ms from elephant.statistics import time_histogram spiketrain = homogeneous_poisson_process(rate=10.0*Hz, t_start=0.0*s, t_stop=100.0*s) binsize=5.0*ms time_histogram( spiketrain, binsize, t_start=0.0, t_stop=100.0*s)
def complexity(all_data, color, trial, bin_size, save_figures=True): """ Give all_data, color as a string, trial as a scalar, bins as a scalar, default is save_figures = True. Plots: raster plot, spike counts per bin (in ms), the complexity distribution for that bin size, complexity distribution for data vs. surrogates, then substracts the two from each other. Finally, three plots are created of complexity distributions for data, surrogates, and their difference, scanning across bin sizes from 0 to 30 ms. """ # if color=='blue': # color_map = 'Blues' # if color=='green': # color_map = 'Greens' # if color=='grey': # color_map = 'Greys' # if color=='orange': # color_map = 'Oranges' # if color=='purple': # color_map = 'Purples' # if color=='red': # color_map = 'Reds' # block = ut.load_dataset(color) block = all_data[color]['neo_block'] train = block.segments[trial].spiketrains # segments is trials binsize = bin_size * pq.ms pophist = stats.time_histogram(train, binsize, binary=True) complexity_cpp = stats.complexity_pdf(train, binsize) # Plot the results # plt.xkcd() fig = plt.figure(figsize=(12, 5)) fig.subplots_adjust(top=.92, bottom=.05, hspace=.5, wspace=.2) misc.add_raster(fig, 2, 2, 1, train, ms=1, xlabel='time', ylabel='neuron id') misc.add_hist(fig, 2, 2, 3, pophist.times, pophist, pophist.sampling_period, xlabel='time', ylabel='counts') ylim = plt.gca().get_ylim() plt.subplot(1, 2, 2) # plt.bar(complexity_cpp.times, list(A) + [0]*(n-assembly_size), color='r', label='amplitude distrib.') #plt.bar(range(len(A)), A, color='r', label='amplitude distrib.') plt.plot(complexity_cpp.times, complexity_cpp, label='complexity distrib.', color=color) plt.ylim([0, 0.25]) plt.xlim([0, 30]) plt.xlabel('complexity', size=12) plt.ylabel('probability', size=12) plt.suptitle('train', size=14) plt.legend() if save_figures: complexity_png = 'ATplots/complexity_bin' + str( bin_size) + '_color_' + str(color) + '.png' complexity_pdf = 'ATplots/complexity_bin' + str( bin_size) + '_color_' + str(color) + '.pdf' plt.savefig(complexity_png) plt.savefig(complexity_pdf) # generation of surrogates surr_sts = [] for st in train: surr_sts.append(surr.randomise_spikes(st)[0]) # Computation of the Complexity Distributions complexity_surr = stats.complexity_pdf(surr_sts, binsize) diff_complexity = complexity_cpp - complexity_surr # Plot the difference of the complexity distributions of the correlated and independent CPP plt.figure(figsize=(12, 4)) plt.subplot(1, 2, 1) plt.plot(complexity_cpp.times, complexity_cpp, color=color, label="corr'd") plt.plot(complexity_surr.times, complexity_surr, color=color, label="surrogate", ls=':') plt.xlabel('complexity') plt.xlim([0, 30]) plt.ylabel('probability') plt.legend() plt.subplot(1, 2, 2) plt.plot(complexity_cpp.times, diff_complexity, color=color) plt.xlabel('complexity') plt.xlim([0, 30]) plt.ylabel('probability diff.') if save_figures: complexity_surr_png = 'ATplots/complexity_surr' + str( bin_size) + '_color_' + str(color) + '.png' complexity_surr_pdf = 'ATplots/complexity_surr' + str( bin_size) + '_color_' + str(color) + '.pdf' plt.savefig(complexity_surr_png) plt.savefig(complexity_surr_pdf) plt.show() # computation of the complexity distributions of CPP and surrogates for different binsizes # and storing the result in matrices binsizes = range(1, 31) * pq.ms max2 = [] complexity_cpp_matrix = stats.complexity_pdf(train, binsizes[0]).magnitude complexity_surr_matrix = stats.complexity_pdf(surr_sts, binsizes[0]).magnitude diff_complexity_matrix = complexity_cpp_matrix - complexity_surr_matrix max2.append( numpy.argmax(diff_complexity.magnitude[numpy.argmin(diff_complexity. magnitude):]) + numpy.argmin(diff_complexity.magnitude)) for i, h in enumerate(binsizes[1:]): complexity_cpp = stats.complexity_pdf(train, h) complexity_surr = stats.complexity_pdf(surr_sts, h) diff_complexity = complexity_cpp - complexity_surr max2.append( numpy.argmax(diff_complexity. magnitude[numpy.argmin(diff_complexity.magnitude):]) + numpy.argmin(diff_complexity.magnitude)) complexity_cpp_matrix = numpy.hstack( (complexity_cpp_matrix, complexity_cpp.magnitude)) complexity_surr_matrix = numpy.hstack( (complexity_surr_matrix, complexity_surr.magnitude)) diff_complexity_matrix = numpy.hstack( (diff_complexity_matrix, diff_complexity.magnitude)) # Plot the complexity matrices inch2cm = 0.3937 scale = 2 # figure scale; '1' creates a 8x10 cm figure (half a page width) label_size = 6 + 1 * scale text_size = 8 + 1 * scale tick_size = 4 + 1 * scale plt.figure(figsize=(8 * scale * inch2cm, 12 * scale * inch2cm), dpi=100 * scale) plt.subplots_adjust(right=.97, top=.95, bottom=.2 - .08 * scale, hspace=.55) plt.subplot(3, 1, 1) plt.title('CPP complexity') plt.pcolor(complexity_cpp_matrix.T) plt.colorbar() plt.tick_params(length=2, direction='out', pad=0) plt.yticks(binsizes[0:-1:3].magnitude) plt.ylabel('Binsize') plt.xlabel('Complexity') #plt.xlim([0,complexity_cpp_matrix.T.shape[1]]) plt.xlim([0, 30]) plt.ylim([0, complexity_cpp_matrix.T.shape[0]]) plt.ylim([binsizes[0], binsizes[-1]]) plt.subplot(3, 1, 2) plt.title('Surrogate complexity') plt.pcolor(complexity_surr_matrix.T) plt.colorbar() plt.ylabel('Binsize') plt.xlabel('Complexity') plt.tick_params(length=2, direction='out', pad=0) plt.yticks(binsizes[0:-1:3].magnitude) #plt.xlim([0,complexity_cpp_matrix.T.shape[1]]) plt.xlim([0, 30]) plt.ylim([0, complexity_cpp_matrix.T.shape[0]]) plt.ylim([binsizes[0], binsizes[-1]]) plt.subplot(3, 1, 3) plt.title('Difference of complexities') plt.pcolor(diff_complexity_matrix.T) plt.colorbar() plt.plot(max2, binsizes, 'm') plt.ylabel('Binsize') plt.xlabel('Complexity') #plt.yticks(binsizes[0:-1:3].magnitude) plt.tick_params(length=2, direction='out', pad=0) #plt.xlim([0,complexity_cpp_matrix.T.shape[1]]) plt.xlim([0, 30]) plt.ylim([0, complexity_cpp_matrix.T.shape[0]]) plt.ylim([binsizes[0], binsizes[-1]]) if save_figures: sliding_bin_png = 'ATplots/complexity_sliding_bin_' + str( color) + '.png' sliding_bin_pdf = 'ATplots/complexity_sliding_bin_' + str( color) + '.pdf' plt.savefig(sliding_bin_png) plt.savefig(sliding_bin_pdf) plt.show()
def test_time_histogram_binary(self): targ = np.array([2, 2, 1, 1, 2, 2, 1, 0, 1, 0]) histogram = statistics.time_histogram(self.spiketrains, bin_size=pq.s, binary=True) assert_array_equal(targ, histogram.magnitude[:, 0])