def Plot(M, Mu, Mv, number): br.plot(211) #pudb.set_trace() br.plot(Mu.times / br.ms, Mu[0] / br.mvolt, label='u') br.plot((Mv.times) / br.ms, 2000 * (Mv[0] / br.mvolt) - 58000, label='v') br.plot((M.times) / br.ms, 2000 * (M[0] / br.mvolt) - 58000, label='ge') #br.plot(Mv.times/br.ms,Mv[ br.legend() br.show()
def save_and_plot_results(): global fig_num print '...saving results' if not test_mode: save_theta() if not test_mode: save_connections() else: np.save(top_level_path + 'activity/conv_patch_connectivity_activity/results_' + str(num_examples) + '_' + ending, result_monitor) np.save(top_level_path + 'activity/conv_patch_connectivity_activity/input_numbers_' + str(num_examples) + '_' + ending, input_numbers) if do_plot: if rate_monitors: b.figure(fig_num) fig_num += 1 for i, name in enumerate(rate_monitors): b.subplot(len(rate_monitors), 1, i + 1) b.plot(rate_monitors[name].times / b.second, rate_monitors[name].rate, '.') b.title('Rates of population ' + name) if spike_monitors: b.figure(fig_num) fig_num += 1 for i, name in enumerate(spike_monitors): b.subplot(len(spike_monitors), 1, i + 1) b.raster_plot(spike_monitors[name]) b.title('Spikes of population ' + name) if spike_counters: b.figure(fig_num) fig_num += 1 for i, name in enumerate(spike_counters): b.subplot(len(spike_counters), 1, i + 1) b.plot(np.asarray(spike_counters['Ae'].count[:])) b.title('Spike count of population ' + name) plot_2d_input_weights() plot_patch_weights() b.ioff() b.show()
def main(): fs = 100e3 cf = 1e3 tmax = 50e-3 sound = wv.ramped_tone( fs=fs, freq=cf, duration=tmax, pad=30e-3, dbspl=50, ) anf_trains = cochlea.run_zilany2014( sound=sound, fs=fs, cf=cf, anf_num=(300, 0, 0), seed=0, species='cat', ) anfs = cochlea.make_brian_group(anf_trains) print(anfs) brainstem = make_brainstem_group(100) print(brainstem) monitor = brian.SpikeMonitor(brainstem) net = brian.Network([brainstem, monitor]) net.run(tmax*second) brian.raster_plot(monitor) brian.show()
def main(): fs = 100e3 cf = 1e3 tmax = 50e-3 sound = wv.ramped_tone( fs=fs, freq=cf, duration=tmax, pad=30e-3, dbspl=50, ) anf_trains = cochlea.run_zilany2014( sound=sound, fs=fs, cf=cf, anf_num=(300, 0, 0), seed=0, species='cat', ) anfs = cochlea.make_brian_group(anf_trains) print(anfs) brainstem = make_brainstem_group(100) print(brainstem) monitor = brian.SpikeMonitor(brainstem) net = brian.Network([brainstem, monitor]) net.run(tmax * second) brian.raster_plot(monitor) brian.show()
correct3 = len(np.where(difference3 == 0)[0]) correct4 = len(np.where(difference4 == 0)[0]) correct5 = len(np.where(difference5 == 0)[0]) incorrect1 = np.where(difference1 != 0)[0] incorrect2 = np.where(difference2 != 0)[0] incorrect3 = np.where(difference3 != 0)[0] incorrect4 = np.where(difference4 != 0)[0] incorrect5 = np.where(difference5 != 0)[0] sum_accuracy[0] = correct1 / float(end_time - start_time) * 100 sum_accuracy[1] = correct2 / float(end_time - start_time) * 100 sum_accuracy[2] = correct3 / float(end_time - start_time) * 100 sum_accuracy[3] = correct4 / float(end_time - start_time) * 100 sum_accuracy[4] = correct5 / float(end_time - start_time) * 100 print 'All neurons response - accuracy:', sum_accuracy[ 0], 'num incorrect:', len(incorrect1) print 'Most-spiked (per patch) neurons vote - accuracy:', sum_accuracy[ 1], 'num incorrect:', len(incorrect2) print 'Most-spiked (overall) neurons vote - accuracy:', sum_accuracy[ 2], 'num incorrect:', len(incorrect3) print 'Simple clusters vote - accuracy:', sum_accuracy[ 3], 'num incorrect:', len(incorrect4) print 'Spatial correlation clusters vote - accuracy:', sum_accuracy[ 4], 'num incorrect:', len(incorrect5) b.show() print '\n'
print 'get assignments' test_results = np.zeros((10, end_time_testing-start_time_testing)) test_results_max = np.zeros((10, end_time_testing-start_time_testing)) test_results_top = np.zeros((10, end_time_testing-start_time_testing)) test_results_fixed = np.zeros((10, end_time_testing-start_time_testing)) assignments = get_new_assignments(training_result_monitor[start_time_training:end_time_training], training_input_numbers[start_time_training:end_time_training]) print assignments counter = 0 num_tests = end_time_testing / 10000 sum_accurracy = [0] * num_tests while (counter < num_tests): end_time = min(end_time_testing, 10000*(counter+1)) start_time = 10000*counter test_results = np.zeros((10, end_time-start_time)) print 'calculate accuracy for sum' for i in xrange(end_time - start_time): test_results[:,i] = get_recognized_number_ranking(assignments, testing_result_monitor[i+start_time,:]) difference = test_results[0,:] - testing_input_numbers[start_time:end_time] correct = len(np.where(difference == 0)[0]) incorrect = np.where(difference != 0)[0] sum_accurracy[counter] = correct/float(end_time-start_time) * 100 print 'Sum response - accuracy: ', sum_accurracy[counter], ' num incorrect: ', len(incorrect) counter += 1 print 'Sum response - accuracy --> mean: ', np.mean(sum_accurracy), '--> standard deviation: ', np.std(sum_accurracy) b.show()
def hodgkin_huxley(duration=100, num=10, percent_excited=0.7, sample=1): """ The hodgkin_huxley function takes the following parameters: duration - is the timeperiod to model for measured in milliseconds. num - an integer value represeting the number of neurons you want to model. percent_excited - a float between 0 and 1 representing the percentage of excited neurons. sample - gives the number of random neurons you would like plotted (default is 1) """ # Assert that we are getting valid input assert(percent_excited >= 0 and percent_excited <= 1.0) assert(duration > 0) assert(num > 0) assert(sample > 0) assert(num >= sample) # Constants used in the modeling equation area = 20000*umetre**2 Cm = (1*ufarad*cm**-2)*area gl = (5e-5*siemens*cm**-2)*area El = -60*mV EK = -90*mV ENa = 50*mV g_na = (100*msiemens*cm**-2)*area g_kd = (30*msiemens*cm**-2)*area VT = -63*mV # Time constants taue = 5*ms # excitatory taui = 10*ms # inhibitory # Reversal potentials Ee = 0*mV # excitatory Ei = -80*mV # inhibitory # Synaptic weights we = 6*nS # excitatory wi = 67*nS # inhibitory # The model equations eqs = Equations( ''' dv/dt = (gl*(El-v)+ge*(Ee-v)+gi*(Ei-v)-g_na*(m*m*m)*h*(v-ENa)-g_kd*(n*n*n*n)*(v-EK))/Cm : volt dm/dt = alpham*(1-m)-betam*m : 1 dn/dt = alphan*(1-n)-betan*n : 1 dh/dt = alphah*(1-h)-betah*h : 1 dge/dt = -ge*(1./taue) : siemens dgi/dt = -gi*(1./taui) : siemens alpham = 0.32*(mV**-1)*(13*mV-v+VT)/(exp((13*mV-v+VT)/(4*mV))-1.)/ms : Hz betam = 0.28*(mV**-1)*(v-VT-40*mV)/(exp((v-VT-40*mV)/(5*mV))-1)/ms : Hz alphah = 0.128*exp((17*mV-v+VT)/(18*mV))/ms : Hz betah = 4./(1+exp((40*mV-v+VT)/(5*mV)))/ms : Hz alphan = 0.032*(mV**-1)*(15*mV-v+VT)/(exp((15*mV-v+VT)/(5*mV))-1.)/ms : Hz betan = .5*exp((10*mV-v+VT)/(40*mV))/ms : Hz ''' ) # Build the neuron group neurons = NeuronGroup( num, model=eqs, threshold=EmpiricalThreshold(threshold=-20*mV,refractory=3*ms), implicit=True, freeze=True ) num_excited = int(num * percent_excited) num_inhibited = num - num_excited excited = neurons.subgroup(num_excited) inhibited = neurons.subgroup(num_inhibited) excited_conn = Connection(excited, neurons, 'ge', weight=we, sparseness=0.02) inhibited_conn = Connection(inhibited, neurons, 'gi', weight=wi, sparseness=0.02) # Initialization neurons.v = El+(randn(num)*5-5)*mV neurons.ge = (randn(num)*1.5+4)*10.*nS neurons.gi = (randn(num)*12+20)*10.*nS # Record a few trace and run recorded = choice(num, sample) trace = StateMonitor(neurons, 'v', record=recorded) run(duration * msecond) for i in recorded: plot(trace.times/ms, trace[i]/mV) show()
def plotResults(self): #------------------------------------------------------------------------------ # plot results #------------------------------------------------------------------------------ if self.rateMonitors: b.figure() for i, name in enumerate(self.rateMonitors): b.subplot(len(self.rateMonitors), 1, i) b.plot(self.rateMonitors[name].times/b.second, self.rateMonitors[name].rate, '.') b.title('rates of population ' + name) if self.spikeMonitors: b.figure() for i, name in enumerate(self.spikeMonitors): b.subplot(len(self.spikeMonitors), 1, i) b.raster_plot(self.spikeMonitors[name]) b.title('spikes of population ' + name) if name=='Ce': timePoints = np.linspace(0+(self.singleExampleTime+self.restingTime)/(2*b.second)*1000, self.runtime/b.second*1000-(self.singleExampleTime+self.restingTime)/(2*b.second)*1000, self.numExamples) b.plot(timePoints, self.resultMonitor[:,0]*self.nE, 'g') b.plot(timePoints, self.resultMonitor[:,1]*self.nE, 'r') if self.stateMonitors: b.figure() for i, name in enumerate(self.stateMonitors): b.plot(self.stateMonitors[name].times/b.second, self.stateMonitors[name]['v'][0], label = name + ' v 0') b.legend() b.title('membrane voltages of population ' + name) b.figure() for i, name in enumerate(self.stateMonitors): b.plot(self.stateMonitors[name].times/b.second, self.stateMonitors[name]['ge'][0], label = name + ' v 0') b.legend() b.title('conductances of population ' + name) plotWeights = [ # 'XeAe', # 'XeAi', # 'AeAe', # 'AeAi', # 'AiAe', # 'AiAi', # 'BeBe', # 'BeBi', # 'BiBe', # 'BiBi', # 'CeCe', # 'CeCi', 'CiCe', # 'CiCi', # 'HeHe', # 'HeHi', # 'HiHe', # 'HiHi', 'AeHe', # 'BeHe', # 'CeHe', 'HeAe', # 'HeBe', # 'HeCe', ] for name in plotWeights: b.figure() # my_cmap = matplotlib.colors.LinearSegmentedColormap.from_list('own2',['#f4f4f4', '#000000']) # my_cmap2 = matplotlib.colors.LinearSegmentedColormap.from_list('own2',['#000000', '#f4f4f4']) if name[1]=='e': nSrc = self.nE else: nSrc = self.nI if name[3]=='e': nTgt = self.nE else: nTgt = self.nI w_post = np.zeros((nSrc, nTgt)) connMatrix = self.connections[name][:] for i in xrange(nSrc): w_post[i, connMatrix.rowj[i]] = connMatrix.rowdata[i] im2 = b.imshow(w_post, interpolation="nearest", vmin = 0, cmap=cm.get_cmap('gist_ncar')) #my_cmap b.colorbar(im2) b.title('weights of connection' + name) if self.plotError: error = np.abs(self.resultMonitor[:,1] - self.resultMonitor[:,0]) correctionIdxs = np.where(error > 0.5)[0] correctedError = [1 - error[i] if (i in correctionIdxs) else error[i] for i in xrange(len(error))] correctedErrorSum = np.average(correctedError) b.figure() b.scatter(self.resultMonitor[:,1], self.resultMonitor[:,0], c=range(len(error)), cmap=cm.get_cmap('gray')) b.title('Error: ' + str(correctedErrorSum)) b.xlabel('Desired activity') b.ylabel('Population activity') b.figure() error = np.abs(self.resultMonitor[:,1] - self.resultMonitor[:,0]) correctionIdxs = np.where(error > 0.5)[0] correctedError = [1 - error[i] if (i in correctionIdxs) else error[i] for i in xrange(len(error))] correctedErrorSum = np.average(correctedError) b.scatter(self.resultMonitor[:,1], self.resultMonitor[:,0], c=self.resultMonitor[:,2], cmap=cm.get_cmap('gray')) b.title('Error: ' + str(correctedErrorSum)) b.xlabel('Desired activity') b.ylabel('Population activity') b.ioff() b.show()
def lif_measures(synchrony, jitter, num_inp, freq, weight): # initializing (could go in a separate initializer) brian.reinit_default_clock(0*second) if brian.defaultclock.t > 0: warnings.warn("Clock start value > 0 : %f" % ( brian.defaultclock.t)) seed = int(time()+(synchrony+jitter+num_inp+freq+weight)*1e3) jitter = jitter*second freq = freq*hertz weight = weight*volt # neuron neuron = brian.NeuronGroup(1, "dV/dt = -V/tau : volt", threshold="V>Vth", reset="V=0*mvolt", refractory=1*msecond) neuron.V = 0*mvolt netw = brian.Network(neuron) config = {"id": seed, "S_in": synchrony, "sigma": jitter, "f_in": freq, "N_in": num_inp, "weight": weight} # inputs sync_inp, rand_inp = st.tools.gen_input_groups(num_inp, freq, synchrony, jitter, duration, dt) netw.add(sync_inp, rand_inp) # connections if len(sync_inp): sync_con = brian.Connection(sync_inp, neuron, "V", weight=weight) netw.add(sync_con) if len(rand_inp): rand_con = brian.Connection(rand_inp, neuron, "V", weight=weight) netw.add(rand_con) # monitors sync_mon = brian.SpikeMonitor(sync_inp) rand_mon = brian.SpikeMonitor(rand_inp) netw.add(sync_mon, rand_mon) v_mon = brian.StateMonitor(neuron, "V", record=True) out_mon = brian.SpikeMonitor(neuron) netw.add(v_mon, out_mon) # network operator for calculating measures every time spike is fired @brian.network_operation(when="end") def calc_measures(): if len(out_mon[0]) > 1 and out_mon[0][-1]*second == brian.defaultclock.t: isi_edges = (out_mon[0][-2], out_mon[0][-1]) isi_dura = isi_edges[1]-isi_edges[0] isi_dt = (int(isi_edges[0]/dt), int(isi_edges[1]/dt)) interval_trace = v_mon[0][isi_dt[0]:isi_dt[1]+2] slope = (float(Vth)-interval_trace[-int(slope_w/dt)])/float(slope_w) # grab interval inputs interval_inputs = [] for inp in sync_mon.spiketimes.itervalues(): _idx = (isi_edges[0] < inp) & (inp < isi_edges[1]) interval_inputs.append(inp[_idx]-isi_edges[0]) for inp in rand_mon.spiketimes.itervalues(): _idx = (isi_edges[0] < inp) & (inp < isi_edges[1]) interval_inputs.append(inp[_idx]-isi_edges[0]) kreuz = st.metrics.kreuz.pairwise(interval_inputs, isi_edges[0], isi_edges[1], 2) kreuz = kreuz[1][0] #if len(kreuz[1]) == 1: # kreuz = kreuz[1][0] #else: # warnings.warn("Kreuz metric returned multiple values.") # print(kreuz[1]) # kreuz = brian.mean(kreuz[1]) vp = st.metrics.victor_purpura.pairwise(interval_inputs, dcost) mod = st.metrics.modulus_metric.pairwise(interval_inputs, isi_edges[0], isi_edges[1]).item() #corr = st.metrics.corrcoef.corrcoef_spiketrains(interval_inputs, # duration=isi_dura) measures.append({"slope": slope, #"npss": npss, "kreuz": kreuz, "vp": vp, "mod": mod}) netw.add(calc_measures) # run netw.run(duration, report=None) brian.plot(v_mon.times, v_mon[0]) brian.show() return {"id": seed, "config": config, "measures": measures}