def plotPSTHs(ax, sts, t=None, bs=100, c='b', show_single=False, show_ticks=False, ylim=None, show_sd=True, lw=2): single_neurons = [] if len(sts.shape) > 1: for st in sts: xs, ys = spk.psth(st, bs).get_plottable_data() single_neurons.append(ys) if show_single: ax.plot(xs, ys, c='grey', lw=0.3) else: show_sd = False xy, ys = spk.psth(sts.flatten(), bs).get_plottable_data() ys = ys / sts.shape[0] if show_sd: ax.fill_between(xy, ys - np.std(single_neurons, 0), ys + np.std(single_neurons, 0), color=c) ax.plot(xy, ys, c='k', lw=2) else: ax.plot(xy, ys, c=c, lw=lw) if t is not None: ax.set_title(t) if ylim is not None: ax.set_ylim(ylim) if show_ticks == False: ax.set_xticks(()) ax.set_yticks(())
f = spk.spike_profile(spike_trains[0], spike_trains[1]) x, y = f.get_plottable_data() plt.plot(x, y, '-b', label="SPIKE-profile") plt.axis([0, 4000, -0.1, 1.1]) plt.legend(loc="center right") plt.figure() plt.subplot(211) f = spk.spike_sync_profile_multi(spike_trains) x, y = f.get_plottable_data() plt.plot(x, y, '-b', alpha=0.7, label="SPIKE-Sync profile") x1, y1 = f.get_plottable_data(averaging_window_size=50) plt.plot(x1, y1, '-k', lw=2.5, label="averaged SPIKE-Sync profile") plt.subplot(212) f_psth = spk.psth(spike_trains, bin_size=50.0) x, y = f_psth.get_plottable_data() plt.plot(x, y, '-k', alpha=1.0, label="PSTH") print("Average:", f.avrg()) plt.show()
f = spk.spike_sync_profile(spike_trains) x, y = f.get_plottable_data() with open('../export/spike_sync_profile.csv', 'w') as fw: writer = csv.writer(fw) writer.writerows(t([x, y])) plt.plot(x, y, '-b', alpha=0.7, label="SPIKE-Sync profile") x1, y1 = f.get_plottable_data(averaging_window_size=50) plt.plot(x1, y1, '-k', lw=2.5, label="averaged SPIKE-Sync profile") with open('../export/spike_sync_averaged.csv', 'w') as fw: writer = csv.writer(fw) writer.writerows(t([x1, y1])) plt.subplot(212) f_psth = spk.psth(spike_trains, bin_size=50.0) x, y = f_psth.get_plottable_data() plt.plot(x, y, '-k', alpha=1.0, label="PSTH") with open('../export/spike_sync_averaged_last.csv', 'w') as fw: writer = csv.writer(fw) writer.writerows(t([x, y])) print("Average:", f.avrg()) plt.show()
def iter_plot0(md): import seaborn as sns import pickle with open('cell_indexs.p', 'rb') as f: returned_list = pickle.load(f) index_exc = returned_list[0] index_inh = returned_list[1] index, mdf1 = md #wgf = {0.025:None,0.05:None,0.125:None,0.25:None,0.3:None,0.4:None,0.5:None,1.0:None,1.5:None,2.0:None,2.5:None,3.0:None} wgf = { 0.0025: None, 0.0125: None, 0.025: None, 0.05: None, 0.125: None, 0.25: None, 0.3: None, 0.4: None, 0.5: None, 1.0: None, 1.5: None, 2.0: None, 2.5: None, 3.0: None } weight_gain_factors = {k: v for k, v in enumerate(wgf.keys())} print(len(weight_gain_factors)) print(weight_gain_factors.keys()) #weight_gain_factors = {0:0.5,1:1.0,2:1.5,3:2.0,4:2.5,5:3} #weight_gain_factors = {:None,1.0:None,1.5:None,2.0:None,2.5:None} k = weight_gain_factors[index] #print(len(mdf1.segments),'length of block') ass = mdf1.analogsignals[0] time_points = ass.times avg = np.mean(ass, axis=0) # Average over signals of Segment #maxx = np.max(ass, axis=0) # Average over signals of Segment std = np.std(ass, axis=0) # Average over signals of Segment #avg_minus = plt.figure() plt.plot([i for i in range(0, len(avg))], avg) plt.plot([i for i in range(0, len(std))], std) plt.title("Mean and Standard Dev of $V_{m}$ amplitude per neuron ") plt.xlabel('time $(ms)$') plt.xlabel('Voltage $(mV)$') plt.savefig(str(index) + 'prs.png') vm_spiking = [] vm_not_spiking = [] spike_trains = [] binary_trains = [] max_spikes = 0 vms = np.array(mdf1.analogsignals[0].as_array().T) #print(data) #for i,vm in enumerate(data): cnt = 0 for spiketrain in mdf1.spiketrains: #spiketrain = mdf1.spiketrains[index] y = np.ones_like(spiketrain) * spiketrain.annotations['source_id'] #import sklearn #sklearn.decomposition.NMF(y) # argument edges is the time interval you want to be considered. pspikes = pyspike.SpikeTrain(spiketrain, edges=(0, len(ass))) spike_trains.append(pspikes) if len(spiketrain) > max_spikes: max_spikes = len(spiketrain) if np.max(ass[spiketrain.annotations['source_id']]) > 0.0: vm_spiking.append(vms[spiketrain.annotations['source_id']]) else: vm_not_spiking.append(vms[spiketrain.annotations['source_id']]) cnt += 1 for spiketrain in mdf1.spiketrains: x = conv.BinnedSpikeTrain(spiketrain, binsize=1 * pq.ms, t_start=0 * pq.s) binary_trains.append(x) end_floor = np.floor(float(mdf1.t_stop)) dt = float(mdf1.t_stop) % end_floor mdf1.t_start #v = mdf1.take_slice_of_analogsignalarray_by_unit() t_axis = np.arange(float(mdf1.t_start), float(mdf1.t_stop), dt) plt.figure() plt.clf() plt.figure() plt.clf() cleaned = [] data = np.array(mdf1.analogsignals[0].as_array().T) #print(data) for i, vm in enumerate(data): if np.max(vm) > 900.0 or np.min(vm) < -900.0: pass else: plt.plot(ass.times, vm) #,label='neuron identifier '+str(i))) cleaned.append(vm) #vm = s#.as_array()[:,i] assert len(cleaned) < len(ass) print(len(cleaned)) plt.title('neuron $V_{m}$') #plt.legend(loc="upper left") plt.savefig(str('weight_') + str(k) + 'analogsignals' + '.png') plt.xlabel('Time $(ms)$') plt.ylabel('Voltage $(mV)$') plt.close() #pass plt.figure() plt.clf() plt.title('Single Neuron $V_{m}$ trace') plt.plot(ass.times[0:int(len(ass.times) / 10)], vm_not_spiking[index_exc[0]][0:int(len(ass.times) / 10)]) plt.xlabel('$ms$') plt.ylabel('$mV$') plt.xlabel('Time $(ms)$') plt.ylabel('Voltage $(mV)$') plt.savefig(str('weight_') + str(k) + 'eespecific_analogsignals' + '.png') plt.close() plt.figure() plt.clf() plt.title('Single Neuron $V_{m}$ trace') plt.plot(ass.times[0:int(len(ass.times) / 10)], vm_not_spiking[index_inh[0]][0:int(len(ass.times) / 10)]) plt.xlabel('$ms$') plt.ylabel('$mV$') plt.savefig(str('weight_') + str(k) + 'inhibitory_analogsignals' + '.png') plt.close() cvs = [0 for i in range(0, len(spike_trains))] cvsd = {} cvs = [] cvsi = [] rates = [] # firing rates per cell. in spikes a second. for i, j in enumerate(spike_trains): rates.append(float(len(j) / 2.0)) cva = cv(j) if np.isnan(cva) or cva == 0: pass #cvs[i] = 0 #cvsd[i] = 0 else: pass #cvs[i] = cva #cvsd[i] = cva cvs.append(cva) #import pickle #with open(str('weight_')+str(k)+'coefficients_of_variation.p','wb') as f: # pickle.dump([cvs,cvsd],f) import numpy a = numpy.asarray(cvs) numpy.savetxt('pickles/' + str('weight_') + str(k) + 'coefficients_of_variation.csv', a, delimiter=",") import numpy a = numpy.asarray(rates) numpy.savetxt('pickles/' + str('weight_') + str(k) + 'firing_of_rate.csv', a, delimiter=",") cvs = [i for i in cvs if i != 0] cells = [i for i in range(0, len(cvs))] plt.clf() fig, axes = plt.subplots() axes.set_title('Coefficient of Variation Versus Neuron') axes.set_xlabel('Neuron number') axes.set_ylabel('CV estimate') mcv = np.mean(cvs) #plt.scatter(cells,cvs) cvs = np.array(cvs) plt.scatter(index_inh, cvs[index_inh], label="inhibitory cells") plt.scatter(index_exc, cvs[index_exc], label="excitatory cells") plt.legend(loc="upper left") fig.tight_layout() plt.savefig(str('weight_') + str(k) + 'cvs_mean_' + str(mcv) + '.png') plt.close() plt.clf() #frequencies, power = elephant.spectral.welch_psd(ass) #mfreq = frequencies[np.where(power==np.max(power))[0][0]] #fig, axes = plt.subplots() axes.set_title('Firing Rate Versus Neuron Number at mean f=' + str(np.mean(rates)) + str('(Spike Per Second)')) axes.set_xlabel('Neuron number') axes.set_ylabel('Spikes per second') rates = np.array(rates) plt.scatter(index_inh, rates[index_inh], label="inhibitory cells") plt.scatter(index_exc, rates[index_exc], label="excitatory cells") plt.legend(loc="upper left") fig.tight_layout() plt.savefig(str('firing_rates_per_cell_') + str(k) + str(mcv) + '.png') plt.close() ''' import pandas as pd d = {'coefficent_of_variation': cvs, 'cells': cells} df = pd.DataFrame(data=d) ax = sns.regplot(x='cells', y='coefficent_of_variation', data=df)#, fit_reg=False) plt.savefig(str('weight_')+str(k)+'cvs_regexp_'+str(mcv)+'.png'); plt.close() ''' spike_trains = [] ass = mdf1.analogsignals[0] tstop = mdf1.t_stop np.max(ass.times) == mdf1.t_stop #assert tstop == 2000 tstop = 2000 vm_spiking = [] for spiketrain in mdf1.spiketrains: vm_spiking.append( mdf1.analogsignals[0][spiketrain.annotations['source_id']]) y = np.ones_like(spiketrain) * spiketrain.annotations['source_id'] # argument edges is the time interval you want to be considered. pspikes = pyspike.SpikeTrain(spiketrain, edges=(0, tstop)) spike_trains.append(pspikes) # plot the spike times plt.clf() for (i, spike_train) in enumerate(spike_trains): plt.scatter(spike_train, i * np.ones_like(spike_train), marker='.') plt.xlabel('Time (ms)') plt.ylabel('Cell identifier') plt.title('Raster Plot for weight strength:' + str(k)) plt.savefig(str('weight_') + str(k) + 'raster_plot' + '.png') plt.close() f = spk.isi_profile(spike_trains, indices=[0, 1]) x, y = f.get_plottable_data() #text_file.close() text_file = open(str('weight_') + str(index) + 'net_out.txt', 'w') plt.figure() plt.plot(x, np.abs(y), '--k', label="ISI-profile") print("ISI-distance: %.8f" % f.avrg()) f = spk.spike_profile(spike_trains, indices=[0, 1]) x, y = f.get_plottable_data() plt.plot(x, y, '-b', label="SPIKE-profile") #print("SPIKE-distance: %.8f" % f.avrg()) string_to_write = str("ISI-distance:") + str(f.avrg()) + str("\n\n") plt.title(string_to_write) plt.xlabel('Time $(ms)$') plt.ylabel('ISI distance') plt.legend(loc="upper left") plt.savefig(str('weight_') + str(k) + 'ISI_distance_bivariate' + '.png') plt.close() text_file.write(string_to_write) #text_file.write("SPIKE-distance: %.8f" % f.avrg()) #text_file.write("\n\n") plt.figure() f = spk.spike_sync_profile(spike_trains[0], spike_trains[1]) x, y = f.get_plottable_data() plt.plot(x, y, '--ok', label="SPIKE-SYNC profile") print(f, f.avrg()) print("Average:" + str(f.avrg())) #print(len(f.avrg()),f.avrg()) string_to_write = str("instantaneous synchrony:") + str( f.avrg()) + 'weight: ' + str(index) plt.title(string_to_write) plt.xlabel('Time $(ms)$') plt.ylabel('instantaneous synchrony') text_file.write(string_to_write) #text_file.write(list()) f = spk.spike_profile(spike_trains[0], spike_trains[1]) x, y = f.get_plottable_data() plt.plot(x, y, '-b', label="SPIKE-profile") plt.axis([0, 4000, -0.1, 1.1]) plt.legend(loc="center right") plt.clf() plt.figure() plt.subplot(211) f = spk.spike_sync_profile(spike_trains) x, y = f.get_plottable_data() plt.plot(x, y, '-b', alpha=0.7, label="SPIKE-Sync profile") x1, y1 = f.get_plottable_data(averaging_window_size=50) plt.plot(x1, y1, '-k', lw=2.5, label="averaged SPIKE-Sync profile") plt.subplot(212) f_psth = spk.psth(spike_trains, bin_size=50.0) x, y = f_psth.get_plottable_data() plt.plot(x, y, '-k', alpha=1.0, label="PSTH") plt.savefig(str('weight_') + str(k) + 'multivariate_PSTH' + '.png') plt.close() plt.xlabel('Time $(ms)$') plt.ylabel('Spikes per bin') plt.clf() plt.figure() f_psth = spk.psth(spike_trains, bin_size=50.0) x, y = f_psth.get_plottable_data() plt.plot(x, y, '-k', alpha=1.0, label="PSTH") plt.savefig(str('weight_') + str(k) + 'exclusively_PSTH' + '.png') plt.close() plt.figure() isi_distance = spk.isi_distance_matrix(spike_trains) plt.imshow(isi_distance, interpolation='none') plt.title('Pairwise ISI distance, T=0-2000') plt.xlabel('post-synaptic neuron number') plt.ylabel('pre-synaptic neuron number') plt.title("ISI-distance") plt.savefig(str('weight_') + str(k) + 'ISI_distance' + '.png') plt.close() #plt.show() plt.figure() plt.clf() import seaborn as sns sns.set() sns.clustermap(isi_distance) #,vmin=-,vmax=1); plt.savefig(str('weight_') + str(k) + 'cluster_isi_distance' + '.png') plt.close() plt.figure() spike_distance = spk.spike_distance_matrix(spike_trains, interval=(0, float(tstop))) import pickle with open('spike_distance_matrix.p', 'wb') as f: pickle.dump(spike_distance, f) plt.imshow(spike_distance, interpolation='none') plt.title("Pairwise SPIKE-distance, T=0-2000") plt.xlabel('post-synaptic neuron number') plt.ylabel('pre-synaptic neuron number') plt.savefig(str('weight_') + str(k) + 'spike_distance_matrix' + '.png') plt.close() plt.figure() plt.clf() sns.set() sns.clustermap(spike_distance) plt.savefig(str('weight_') + str(k) + 'cluster_spike_distance' + '.png') plt.close() plt.figure() spike_sync = spk.spike_sync_matrix(spike_trains, interval=(0, float(tstop))) plt.imshow(spike_sync, interpolation='none') plt.title('Pairwise Spike Synchony, T=0-2000') plt.xlabel('post-synaptic neuron number') plt.ylabel('pre-synaptic neuron number') import numpy a = numpy.asarray(spike_sync) numpy.savetxt("spike_sync_matrix.csv", a, delimiter=",") plt.figure() plt.clf() sns.clustermap(spike_sync) plt.savefig( str('weight_') + str(k) + 'cluster_spike_sync_distance' + '.png') plt.close()
def medmaxSpikeRate(st_s, ms=200): mxs = [] for st in st_s: n = spk.psth(st, ms).y mxs.append((np.max(n) - np.median(n)) / (ms / 1000)) return np.asarray(mxs)
def getPSTHs(sts, bs=100): single_neurons = [] for st in sts: xs, ys = spk.psth(st, bs).get_plottable_data() single_neurons.append(ys) return xs, single_neurons