예제 #1
0
 def plot(self, slice=None):
     if slice == None:
         slice = len(self.cutoffs)
     plt.hlines(1,0,1)
     plt.eventplot(self.cutoffs[:slice], orientation='horizontal', colors='b')
     plt.show()
     plt.pause(0.0001)
예제 #2
0
 def display(self,
             filename='../../results/fig3-learning-rule/protocol.pdf'):
     """
     Plot pairing protocol
     """
     try:
         assert (len(self.spiketimes_pre) > 0
                 and len(self.spiketimes_post) > 0
                 )  # check if spiketimes list are non-empty
         plt.figure(figsize=(5, 2))
         plt.eventplot(self.spiketimes_pre[:5],
                       colors=[custom_colors['bluish_green']],
                       lineoffsets=1,
                       linelengths=1,
                       lw=0.5,
                       label='pre')
         plt.eventplot(self.spiketimes_post[:5],
                       colors=[custom_colors['sky_blue']],
                       lineoffsets=2,
                       linelengths=1,
                       lw=0.5,
                       label='post')
         #plt.plot([0.5, 0.510], [3.5, 3.5], lw=0.5)
         #plt.xlim([0,min(5, max(self.spiketimes_post[-1], self.spiketimes_pre[-1]))])
         #plt.xticks([])
         #plt.yticks([])
         #sns.despine(left=True, bottom=True)
         plt.savefig(filename)
         plt.close()
     except:
         print('Empty spiketimes list. Nothing to plot.')
예제 #3
0
def raster_plot(event_mask):
    for i,trace in enumerate(event_mask.T):
        indices=np.where(trace==1)
        plt.eventplot(indices,lineoffsets=i)

        
#mask=mask_spikes(data[600000:800000,65:130])
예제 #4
0
def inhExcCircuitRasterPLot(excSD,inhSD,nExc,nInh,timerange = (0.0,0.0)):
    excSD = nest.GetStatus(excSD,keys = "events")
    inhSD = nest.GetStatus(inhSD,keys = "events")
    ets = excSD[0]['times']
    esenders = excSD[0]['senders']
    its = inhSD[0]['times']
    isenders = inhSD[0]['senders']

    allts = list(ets) + list(its)
    senders = list(esenders) + list(isenders)

    ts = [[] for n in range(nExc + nInh)]
    for t, source in zip(allts,senders):
        ts[source-1].append(t)

    ts = list(filter(None, ts)) # take out non spiking neurons
    eUniq = np.unique(esenders)
    iUniq = np.unique(isenders)
    print('Active neurons',len(eUniq) + len(iUniq))

    colors = ['r' for n in range(len(eUniq))] + ['b' for n in range(len(iUniq))]
    plt.figure()
    plt.title('Raster plot of circuit activity')
    plt.eventplot(ts,colors = colors)
    plt.xlim(timerange[0],timerange[1])
    plt.xlabel('Time (ms)')
    plt.ylabel('Neuron')
예제 #5
0
def plotRasters(goal_starts, goal_stops, gs, col):
    #the following finds trajectories starting from goal
    #global spikes, cum_t, xsmooth
    for trajectory, goal in enumerate(goal_starts):
        ax = plt.subplot(gs[trajectory, col])
        goal_stop = np.where(goal_stops > goal)[0]
        if len(goal_stop) > 0:
            rest_one = rests[goal]
            rest_two = rests[goal_stops[goal_stop[0]]]
            ##traj_start and traj_stop are times of arrival at goals
            traj_start = cum_t[rest_one[-1]]
            traj_stop = cum_t[rest_two[0]]
            #print("start {}; stop {}".format(traj_start, traj_stop))
            lapspikes = [
                spike for spike in spikes if traj_start < spike < traj_stop
            ]
            moving, stopped = returnSpikeLocations(lapspikes, imoving)
            #print("Trajectory duration: {}".format(traj_stop-traj_start))

        raster = np.zeros(len(moving))

        for i, spike in enumerate(moving):
            raster[i] = x[spike]

        plt.eventplot(raster, linewidths=5, color='k')
        plt.xlim([0, 65])

        plt.axis('off')
예제 #6
0
 def raster(self,threshold,distance=50,plot=True):
     #EXECUTE THE TRACE METHOD FIRST
     #Function to get spike time index  and raster plot
     #Threshold is the minimum spike size to be recognized
     #distance in points = minimum horizontal space between spikes 
    
     spike_times = []
     
     time = self.trace[0][0]  #report all sweeps on the first one for the time
     
     if plot == True:
         plt.figure()
         plt.suptitle('Raster Plot')
         plt.xlabel('Time (s)')
         plt.ylabel('Sweep #')
         plt.xlim(time[0],time[-1])
     
     for i in range(len(self.block.segments)):
         seg = self.trace[i][1] #the analogsignal
 
         spikes, _ = signal.find_peaks(seg,height=threshold,distance=distance) #Spike Indexes
         spike_idx = np.squeeze(spikes/self.sampling_rate) #Spikes times
         spike_times.append(spike_idx)
         
         if plot==True:
             plt.eventplot(spike_idx,orientation='horizontal',lineoffsets=-i,linelengths=0.8)
         
     return spike_times
예제 #7
0
def display_raster_with_eventplot(rasterfile, outfile, discard=0, binsize=50e-3, burst_detection_thr=16.e-3):
    eventtimes, bursttimes, otherspiketimes, isolatedspiketimes = get_eventtimes(rasterfile, discard, burst_detection_thr)

    N_neurons = 25
    lineoffs = np.arange(1, N_neurons+1)
    times, ER, BR = BRER_from_raster(rasterfile, binsize=binsize, tau=burst_detection_thr)

    plt.figure(figsize=(3, 2.))
    #plt.eventplot(otherspiketimes[:N_neurons], colors=['black'], lineoffsets=lineoffs, linelengths=1, lw=0.3)
    plt.eventplot(eventtimes[:N_neurons], colors=[(0, 0.45, 0.8)], lineoffsets=lineoffs, linelengths=1, lw=0.5)
    plt.eventplot(bursttimes[:N_neurons], colors=[(0.78, 0, 0)], lineoffsets=lineoffs, linelengths=1, lw=0.5)
    #plt.eventplot(isolatedspiketimes[:N_neurons], colors=['black'], lineoffsets=lineoffs, linelengths=1, lw=0.3)
    plt.xlim([1, 3])
    plt.xticks(list(np.arange(1., 3.1, 1)))
    #plt.ylim(ymin=0)
    plt.yticks([1, N_neurons])
    # plt.yticks([])
    plt.gca().spines['top'].set_visible(False)
    plt.gca().spines['right'].set_visible(False)
    plt.ylabel('Neuron')
    plt.xlabel('Time [s]')

    ax1_tw = plt.gca().twinx()
    ax1_tw.plot(times, 100 * BR / ER, color=custom_colors['red'], lw=2, alpha=0.5)
    ax1_tw.plot(times, ER, color=custom_colors['blue'], lw=2, alpha=0.5)
    ax1_tw.set_yticks([0, 25, 50])
    ax1_tw.set_ylim([0, 60])
    ax1_tw.set_xlim([1, 3])
    #ax1_tw.legend(loc='upper right', bbox_to_anchor=(1, 1.1))
    ax1_tw.set_ylabel('BP [\%], ER [Hz]')
    #ax1_tw.spines['top'].set_visible(False)

    plt.tight_layout()
    plt.savefig(outfile)
    plt.close()
예제 #8
0
 def draw_event_plot(PCs_df, sample_1_size, description):
     plt.eventplot(PCs_df.iloc[:sample_1_size, 0], colors='r')
     plt.eventplot(PCs_df.iloc[sample_1_size:, 0], colors='b')
     plt.title(f'PC1 event plot of two given samples \n ({description})')
     fname = '.'.join(['event ' + description, Plotter.DEFAULT_IMAGE_EXT])
     plt.savefig(os.path.join(PLOTS_DIR, fname))
     plt.show()
    def plot_graph(self, title, x_spike, y_spike):

        post_spike = self.spikes
        totalTime = self.time
        timeStepSize = self.timestep

        temp = np.arange(0, totalTime + timeStepSize, timeStepSize)

        # Create 3 x numTimeSteps size 2d array filled with zeros
        neuralData = []
        neuralData.append(x_spike * temp)
        neuralData.append(y_spike * temp)
        neuralData.append(post_spike * temp)

        # Draw a spike raster plot
        colorCodes = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0]])

        lineSize = [0.75, 0.75, 0.75]
        plot.eventplot(neuralData, color=colorCodes, linelengths=lineSize)
        plot.title(title)

        # Give x axis label for the spike raster plot
        plot.xlabel('Timesteps')

        # Give y axis label for the spike raster plot
        plot.ylabel('Neuron')
        plot.yticks(np.arange(3), ['Post', 'Y', 'X'])

        # Display the spike raster plot
        plot.show()
예제 #10
0
def rasterPlot(neurons,
               window=None,
               col='black',
               width=0.5,
               height=1,
               offsets=1):
    if window is None:
        last_spike = np.empty(len(neurons))
        for i, n in enumerate(neurons):
            last_spike[i] = n.as_units('s').index.values[-1]

        window = np.array([[0, np.max(last_spike)]])

    if type(window) is list: window = np.array([window])
    window = nts.IntervalSet(window[:, 0], window[:, 1], time_units='s')
    neurons_np = []

    if isinstance(neurons, nts.time_series.Tsd):
        neurons = [neurons]
    for neuron in neurons:
        neurons_np.append(neuron.restrict(window).as_units('s').index)

    neurons_np = np.array(neurons_np, dtype='object')

    plt.eventplot(neurons_np,
                  color=col,
                  linewidth=width,
                  linelengths=height,
                  lineoffsets=offsets)
    plt.ylabel('Neurons')
    plt.xlabel('Time(s)')
예제 #11
0
def plot_raster(neuralData,
                linecolor=[0, 0, 0],
                linesize=0.5,
                x='trial#',
                title_name='Spike raster plot'):
    plt.eventplot(neuralData, color=linecolor, linelengths=linesize)
    plt.title(title_name)
    plt.ylabel(x)
예제 #12
0
def plot_events(firings, n, tot):
    plt.title('Neuronal Firings')
    plt.xlabel('Time')
    plt.ylabel('Sample Number')
    n_samples = firings[np.random.choice(
        range(tot - 1), n)]  # chooses n neurons to sample for plotting
    plt.eventplot(n_samples)
    plt.show()
def plot_spikes(net):
    spikes = net.spikemon.spike_times
    colors = ['r', 'g', 'b', 'm', 'k']
    fig = plt.figure()
    for i in range(net.N):
        plt.eventplot(spikes[i], lineoffsets=i, colors=colors[i % len(colors)])
    plt.ylim([-1, net.N])
    return fig
예제 #14
0
파일: memory.py 프로젝트: yult0821/norse
def _plot_run(xs,
              ys,
              readouts,
              spikes,
              epoch,
              total_epochs,
              accuracy,
              file_prefix=None):
    """
    Only plots the first batch event
    """
    def spikes_to_events(spike_list):
        return [[x for x, spike in enumerate(ts) if spike > 0]
                for ts in spike_list.T]

    try:
        import matplotlib.pyplot as plt
        import matplotlib.gridspec as gridspec

        # Setup grid
        plt.title(f"Accuracy: {accuracy} (epoch {epoch}/{total_epochs}")
        gridspec.GridSpec(4, 1)
        plt.subplot2grid((4, 1), (0, 0), rowspan=3)
        input_events = spikes_to_events(xs[0])
        network_events = spikes_to_events(spikes[:, 0])
        plt.eventplot(
            network_events + input_events[::-1],
            linewidth=1,
            linelengths=0.8,
            color="black",
        )
        yticks = [x for x in range(len(network_events))
                  ] + [22.5, 27.5, 32.5, 37.5]
        y_labels = [""] * len(network_events)
        y_labels.append("Recall")
        y_labels.append("Store")
        y_labels.append("1")
        y_labels.append("0")
        plt.gca().set_yticks(yticks)
        plt.gca().set_yticklabels(y_labels)

        readout_events = readouts[:, :, 0].detach().reshape(-1, 2).softmax(1)
        readout_sum = (readout_events[:, 0] -
                       readout_events[:, 1]).cpu().numpy()

        plt.subplot2grid((4, 1), (3, 0), rowspan=1)
        plt.gca().set_ylim(-1.1, 1.1)
        plt.gca().set_yticks([-1, 0, 1])
        plt.plot(readout_sum, color="black")

        plt.tight_layout()
        if file_prefix:
            plt.savefig(f"{file_prefix}_{epoch}.png")
        else:
            plt.show()
        plt.close()
    except ImportError as e:
        logging.warning("Plotting failed: Cannot import matplotlib: " + str(e))
예제 #15
0
    def plotRasters(self, *args):
        if args:
            if 'sine' in args:
                print('plotting spikes aligned to TTL (sine) phase:')
                try:
                    self.unitsXspikeStimAligned
                except:
                    self.unitsXspikeStimAligned = self.alignSpikesToSine()
                spikes = self.unitsXspikeStimAligned
            elif 'mod' in args:
                print(
                    'plotting modulated spikes aligned to modulation-sine phase'
                )
                try:
                    self.unitsXspikesModAligned
                except:
                    self.unitsXspikesModAligned = self.alignSpikesToSine('mod')
                spikes = self.unitsXspikesModAligned
            plt.figure()
            LINE_LENGTHS = 0.8
            plt.eventplot(
                spikes,
                linelengths=LINE_LENGTHS)  #, linelengths = lineLengths)
            plt.show()
            print('done')
        elif not args:
            print('no argument provided --> plotting generic rasters')

        ### plot spikes over recording length (with TTL stimuli if present)
        plt.figure()
        numUnits = len(self.unitsXspikesLst)

        ####################### TO DO: auto generate appropriate line lengths and colorCodes for the given num of neurons
        lineLengths = np.ones(numUnits)
        colorCodes = np.array([[0, 0, 0], [1, 0, 0], [0, 1, 0], [0, 0, 1],
                               [1, 1, 0], [1, 0, 1], [0, 1, 1], [1, 0, 1]])
        #        plt.eventplot(self.unitsXspikesLst[0:8][:], color=colorCodes) #, linelengths = lineLengths)
        plt.eventplot(
            self.unitsXspikesLst[:][:])  #, linelengths = lineLengths)

        try:
            Y_OFFSET_FOR_TTLs = 2
            sine_vals_offset = self.sine_vals - Y_OFFSET_FOR_TTLs
            TTL_squ_vals_offset = self.TTL_squ_vals - Y_OFFSET_FOR_TTLs
            TTL_vals_offset = TTL_values - Y_OFFSET_FOR_TTLs
            plt.plot(self.TTL_squ_timesInSecs,
                     TTL_squ_vals_offset,
                     'o',
                     color='b')
            plt.plot(self.sine_timesInSecs, sine_vals_offset, 'o', color='g')
            plt.plot(TTL_times, TTL_vals_offset, 'o', color='r')
            print('stimuli plotted as negative y values')
        except:
            print(
                'WARNING: plotting TTL stimuli failed either because TTL were not present or due to an error'
            )
        plt.show()
예제 #16
0
def plot(base, filtered, rate_damaged_pkts, rate_lost_pkts):
    plt.eventplot([base, filtered],
                  colors=[[0, 1, 0], [1, 0, 0]],
                  lineoffsets=[0, 0])
    plt.text(
        0, 1,
        r'$rate\_of\_lost\_packets={},\ rate\_of\_damaged\_packets={}$'.format(
            round(rate_lost_pkts, 2), round(rate_damaged_pkts, 2)))
    plt.show()
 def showRaster(net):
     fig = plt.figure()
     neuralData = []
     for n in net.neurons:
         neuralData.append(n.spikes)
     plt.eventplot(neuralData)
     plt.ylabel('Neuron')
     plt.xlabel('Spiketime in ms')
     plt.show()
예제 #18
0
파일: raster.py 프로젝트: lneisenman/meanet
def draw_raster(mea):
    """ Draw a raster plot from MEA data """
    fig = plt.figure()
    for i in range(60):
        plt.eventplot(mea[i], lineoffsets=i+0.5, colors=[(0, 0, 0)])

    plt.xlim(0, mea.dur)
    plt.ylim(0, 60)
    return fig
예제 #19
0
def createPlot(dataset):

    #dataset = np.swapaxes(dataset,0,1)
    plot.eventplot(dataset, linestyles='solid')
    #print(dataset)
    plot.title("Spike raster plot")
    plot.xlabel('Time')
    plot.ylabel('Neuron')
    plot.show()
예제 #20
0
def generate_plot_product_changes_over_time():
    MAX_PROD_COUNT = 30
    MAX_TIME = 400
    events = []
    events_fraud = []

    for index, product in products.iterrows():
        if index >= MAX_PROD_COUNT:
            break

        print(f'generating plot for {product["name"]}')

        changes_product = changes[
            (changes['record_id'] == index) &
            (changes['table_column_ref'].str.contains('MST_PRODUCTS'))
        ]

        x_times = []
        event_times = []
        event_times_fraud = []

        for time in range(0, MAX_TIME):
            changes_at_time = changes_product[changes_product['timestamp'] == time]
            x_times.append(time)
            count_changes = 0
            count_changes_fraud = 0

            if len(changes_at_time) > 0:
                for _, change in changes_at_time.iterrows():
                    if change['is_fraud']:
                        count_changes_fraud += 1
                        event_times_fraud.append(time)
                    else:
                        count_changes += 1
                        event_times.append(time)

        events.append(event_times)
        events_fraud.append(event_times_fraud)

    plt.figure(figsize=(24, 12))
    plt.margins(0, 0)
    plt.xlabel('Time [in days]')
    plt.ylabel('Product ID')
    plt.title(f'Price Changes on Products over Time')
    plt.yticks(np.arange(0, MAX_PROD_COUNT))
    plt.xticks(np.arange(0, MAX_TIME + 1, 30))
    plt.hlines(range(0, MAX_PROD_COUNT, 10), 0, MAX_TIME, colors='#c7c7c7',
               linestyles='dashed')
    plt.vlines(cfg.SIMULATION_SPECIAL_EVENT_TIMES[0], -0.5, MAX_PROD_COUNT - 0.5, colors='r',
               linestyles='dotted')

    plt.eventplot(events, orientation='horizontal', linelengths=0.8, linewidths=2.0)
    plt.eventplot(events_fraud, orientation='horizontal', linelengths=0.8, linewidths=2.0, colors='orange')
    plt.draw()
    plt.savefig(f'{cfg.STORAGE_BASE_PATH_PLOTS}\\misc\\activity_per_product.pdf', format='pdf', bbox_inches='tight')
    plt.close()
예제 #21
0
def plotSpikeOutputs(populationID, neuronID):
    x = [
        float(x[0]) for x in eventContent
        if populationID == x[1] and neuronID == x[2] and x[3] == '0'
    ]
    y = [
        int(neuronID) for x in eventContent
        if populationID == x[1] and neuronID == x[2] and x[3] == '0'
    ]
    plt.eventplot(x, lineoffsets=int(neuronID), linelengths=0.7)
예제 #22
0
def event_plot(df, title, **kwargs):
    # Load in the values to a vertical event plot
    plt.eventplot(df, orientation=kwargs.get('orientation'))

    # Set the graph values and display
    plt.title(title)
    if kwargs.get('orientation') == 'vertical':
        plt.gca().axes.get_xaxis().set_visible(False)
    else:
        plt.gca().axes.get_yaxis().set_visible(False)
    plt.show()
예제 #23
0
def visualize_events(events, color, title, label):
    plt.title(title)
    maxi, mini, μ, med, σ, med_σ = get_desc_stats(events)
    text = f'Max: {maxi:.3f}\nMin: {mini:.3f}\nMean: {μ:.3f}\nMed: {med:.3f}\nStDev: {σ:.3f}\nMAD: {med_σ:.3f}'
    plt.gcf().text(0.02, 0.35, text, fontsize=14)
    plt.hlines(1,0,1)
    plt.gca().yaxis.set_major_locator(plt.NullLocator())
    plt.eventplot(events, orientation='horizontal', colors=color, alpha = 0.5, label=label)
    plt.subplots_adjust(left=0.25)
    plt.legend()
    plt.show()
예제 #24
0
def TimeSeq(labelList_5_1, Kopt_1):
    listlabels = []
    for i in range(Kopt_1):
        listlabels.append(np.where(labelList_5_1 == i)[0])
    plt.figure(1, figsize=(28, Kopt_1 + 3))
    plt.eventplot(listlabels,
                  lineoffsets=1.01,
                  colors=colorsSeq[:Kopt_1],
                  linelengths=1,
                  linewidths=0.7)
    plt.show()
예제 #25
0
def event(x, title, xlabel, ylabel, save_path):
    plt.close()
    plt.figure(figsize=(10, 8))
    fig, ax = plt.subplots(1)

    plt.eventplot(x)

    plt.title(title)
    ax.set_yticklabels([])
    plt.xlabel(xlabel)
    plt.ylabel(ylabel)
    plt.savefig(save_path)
예제 #26
0
def PlotTrials(process=HomogeneousPoissonEfficient,
               rate=40,
               duration=1,
               trials=20):
    plt.figure(figsize=(8, 5), dpi=100)
    NeuralResponses = []
    for i in range(trials):
        NeuralResponses.append(process(10, 1))

    plt.eventplot(NeuralResponses, linelengths=0.5)
    plt.xlabel('time [ms]')
    plt.ylabel('trial number')
예제 #27
0
    def _cluster_spike_waveforms_by_freq(self,
                                         feature_mode='integral',
                                         plot_hist=False):
        """
        Clusters the found spikes into simple and complex, using a gmm_nc component GMM
        It uses the maximum power in the lower region of the frequency spectrum of the 
        spike waveforms
        """
        if feature_mode is 'integral':
            power_feature = self._find_integral_powers()[0]
        elif feature_mode is 'max':
            power_feature = self._find_max_powers()[0]
        else:
            raise ValueError('feature_mode should be either integral or max')
        gmm = GaussianMixture(self.cs_num_gmm_components,
                              covariance_type=self.cs_cov_type,
                              random_state=0).fit(power_feature.reshape(-1, 1))
        cluster_labels = gmm.predict(power_feature.reshape(-1, 1))
        cluster_labels = cluster_labels.reshape(power_feature.shape)

        cs_indices = self.get_spike_indices()[cluster_labels == np.argmax(
            gmm.means_)]
        if plot_hist:
            plt.figure()
            # uniq = np.unique(ss.d_voltage[prang] , return_counts=True)
            x = np.arange(np.min(power_feature), np.max(power_feature), 1)
            if self.cs_cov_type == 'tied':
                gauss_mixt = np.array([
                    p * norm.pdf(x, mu, np.sqrt(gmm.covariances_.flatten()))
                    for mu, p in zip(gmm.means_.flatten(), gmm.weights_)
                ])
            else:
                gauss_mixt = np.array([
                    p * norm.pdf(x, mu, sd)
                    for mu, sd, p in zip(gmm.means_.flatten(
                    ), np.sqrt(gmm.covariances_.flatten()), gmm.weights_)
                ])

            colors = plt.cm.jet(np.linspace(0, 1, len(gauss_mixt)))

            # plot histogram overlaid by gmm gaussians
            for i, gmixt in enumerate(gauss_mixt):
                plt.plot(x, gmixt, label='Gaussian ' + str(i), color=colors[i])

                plt.hist(power_feature.reshape(-1, 1),
                         bins=256,
                         density=True,
                         color='gray')
                plt.eventplot(gmm.means_,
                              linelength=np.max(np.max(power_feature)))
                plt.show()
        self.cs_indices = cs_indices
 def plot_raster(self):
     self.raw_data = np.transpose(self.raw_data)
     manipulated_data = []
     for n in self.raw_data:
         manipulated_data.append([d for d in n if d != 0])
     plt.eventplot(manipulated_data,
                   color=self.colors,
                   linewidths=2,
                   linelengths=2,
                   lineoffsets=2)
     plt.ylabel("neurons")
     plt.xlabel("time")
     plt.show()
예제 #29
0
def rasterPlot(spikesDict, Nuclei, Directory):
    rasterList = []
    
    if not os.path.exists(Directory + '/rasterPlot'):
        os.makedirs(Directory + '/rasterPlot')

    for neuron in spikesDict:
        rasterList.append(spikesDict[neuron])  
    plt.figure(figsize=(40,15))
    plt.eventplot(rasterList, linelengths = 0.8, linewidths = 0.6)
    plt.title('Spike raster plot ' + Nuclei)
    plt.grid()
    plt.savefig(Directory + '/rasterPlot/' + 'RasterPlot_' + Nuclei + '.png')
예제 #30
0
def circuitRasterPlot(spikedetector,timerange = (0.0,0.0),colors = []):
    plt.figure()
    dSD = nest.GetStatus(spikedetector,keys = "events")
    allts = dSD[0]['times']
    senders = dSD[0]['senders']
    ts = [[] for n in range(np.max(dSD[0]['senders']))]
    for t, source in zip(allts,senders):
        ts[source-1].append(t)

    plt.title('Raster plot of circuit activity')
    plt.eventplot(ts,colors = colors)
    plt.xlim(timerange[0],timerange[1])
    plt.xlabel('Time')
    plt.ylabel('Neuron')
예제 #31
0
 def raster(self, height_light_range=(1000, 2000), xlim=(0, 2500)):
     colors1 = np.array([[1, 0, 0], [0, 1, 1], [0, 0, 1], [0, 1, 0],
                         [1, 0, 1]])
     trials = sorted(self._trials, key=lambda trial: trial.category)
     color_mapping = [colors1[trial.category - 1] for trial in trials]
     trials_timestamps = [trial.trial_timestamps for trial in trials]
     plt.eventplot(np.asarray(trials_timestamps) / 1000,
                   colors=color_mapping)
     plt.axvspan(height_light_range[0],
                 height_light_range[1],
                 color='grey',
                 alpha=0.1)
     plt.xlim(xlim[0], xlim[1])
     plt.show()
예제 #32
0
    def showRasterPlot(self, patternIdx, sampleIdx):
        """ displays the MC output spike raster during the test phase for a
        particular test sample (sampleIdx) belonging to a particular pattern(
        patternIdx)"""
        probes = self.allMCSomaProbes
        numGammaPattern = self.numGammaCyclesTest + self.numGammaCyclesIdle
        testDuration = self.gammaCycleDuration * numGammaPattern

        beginLabel = self.trainDuration + (patternIdx * testDuration)
        endLabel = beginLabel + testDuration
        dataLabel = [
            np.nonzero(probe.data[beginLabel:endLabel])[0] for probe in probes
        ]

        beginSample = self.trainDuration + (self.numPatterns * testDuration)
        beginSample += (patternIdx * self.numTestSamples + sampleIdx) * \
                       testDuration
        endSample = beginSample + testDuration
        dataSample = [
            np.nonzero(probe.data[beginSample:endSample])[0]
            for probe in probes
        ]

        size = self.numMCs
        fig, _ = plt.subplots()
        plt.eventplot(positions=dataLabel,
                      colors='blue',
                      lineoffsets=np.arange(size),
                      linelengths=0.8)
        plt.eventplot(positions=dataSample,
                      colors='red',
                      lineoffsets=np.arange(size),
                      linelengths=0.5)
        plt.title("""MC Output Spike Raster (patternIdx={}, sampleIdx={})
                    """.format(patternIdx, sampleIdx))
        plt.ylabel("#MC Neurons")
        plt.xlabel("""Time ({} gamma cycles; gamma cycle={} timesteps)
                """.format(self.numGammaCyclesTest, self.gammaCycleDuration))
        xticks = [
            self.gammaCycleDuration * i for i in range(self.numGammaCyclesTest)
        ]
        plt.xticks(xticks)
        legend_elements = [
            Line2D([0], [0], color='blue', lw=1, label='Trained Pattern'),
            Line2D([1], [0], color='red', lw=1, label='Test Pattern')
        ]
        fig.legend(handles=legend_elements, loc='center right')
        fig.tight_layout()
        fig.subplots_adjust(right=0.9)
        plt.show()
import nengo
import nengo_spinnaker
import numpy as np

model = nengo.Network()
with model:
    source = nengo.Node(np.sin)
    target = nengo.Ensemble(25, 1)

    c1 = nengo.Connection(source, target)

    p = nengo.Probe(target, 'spikes')

sim = nengo_spinnaker.Simulator(model)
sim.run(10.)

# Plot the results
from matplotlib import pyplot as plt

plt.eventplot(sim.data[p], colors=[[0, 0, 1]])
plt.xlabel("Time / s")
plt.ylabel("Neurons")
plt.show(block=True)
plt.subplot(3,1,2)
plt.plot(sim.data(model.t_probe)[1:], sim.data(in_p)[1:], lw=2)
plt.gca().spines['top'].set_visible(False)
plt.gca().spines['bottom'].set_visible(False)
plt.gca().spines['right'].set_visible(False)
plt.gca().yaxis.set_ticks_position('left')
plt.xlim(0, 1)
plt.xticks(())
plt.ylabel("Input signal")

plt.subplot(3,1,3)
color_cycle = plt.gca()._get_lines.color_cycle
colors = [next(color_cycle) for _ in xrange(a.n_neurons)]
plt.axis([0, 1, a.n_neurons-0.5, -0.5])
plt.eventplot(spikes, colors=colors)
plt.gca().spines['top'].set_visible(False)
plt.gca().spines['right'].set_visible(False)
plt.gca().xaxis.set_ticks_position('none')
plt.gca().yaxis.set_ticks_position('none')
plt.xlabel("Time (s)")
plt.ylabel("Neuron")

plt.tight_layout(pad=0.1, h_pad=0.1)
plt.savefig("../figures/nef_summary_enc.svg")

## Decoding
model = nengo.Model("Encoding")
in_ = nengo.Node(output=lambda t: t * 2 - 1)
in_p = nengo.Probe(in_, 'output')
예제 #35
0
plt.ylim(-1.2, 1.2)
plt.subplot(1, 3, 3)
plt.title("B ({} compartmental)".format(num_neurons))
plt.plot(sim.trange(), sim.data[B_probe])
plt.xlabel("t")
plt.gca().set_yticklabels([])
plt.xlim(0, 2 * np.pi)
plt.ylim(-1.2, 1.2)
plt.savefig(prefix + 'decoded.pdf')


dt = 1000.0
sns.set_style('white')
plt.figure(figsize=(18, 4))
plt.eventplot(
    [np.where(x)[0] / dt for x in sim.data[A_spikes].T[:50, :] if np.any(x)],
    colors=[(0, 0, 0, 1)], linewidth=1)
plt.title("Spike raster of A population (first 50 neurons)")
plt.xlabel("t")
plt.ylabel("Neuron index")
plt.xlim(0, 2 * np.pi)
plt.ylim(-0.5, 49.5)
plt.savefig(prefix + 'spikes_A.pdf')

dt = 1000.0
sns.set_style('white')
plt.figure(figsize=(18, 4))
spikes = [np.where(x)[0] / dt for x in sim.data[B_spikes].T if np.any(x)]
plt.eventplot(spikes, colors=[(0, 0, 0, 1)], linewidth=1)
plt.title("Spike raster of B population")
plt.xlabel("t")
ERP = np.mean(data_neuro['data'], axis=0).transpose()
sk_std = 0.01 if signal_type == 'spk' else 0.002
ERP = pna.SmoothTrace(ERP, sk_std=sk_std, ts=ts)

""" plot ERP in GM32 layout """
h_fig, h_axes = pnp.ErpPlot(ERP, ts=ts, array_layout=layout_GM32)

""" add laser onset tick """
[ylim_min, ylim_max] = plt.gca().get_ylim()
evt_tick_offset = (ylim_max+ylim_min)*0.5
evt_tick_length = (ylim_max-ylim_min)*0.9
for ch, ax_loc in layout_GM32.items():
    plt.axes(h_axes[ax_loc])
    evt_tick_color = ['limegreen'] if ch==laser_name_ch[name_evt] else ['peru']
    evt_tick_alpha = 0.9 if ch==laser_name_ch[name_evt] else 0.7
    plt.eventplot(ts_evt_ticks, lineoffsets=evt_tick_offset, linelengths=evt_tick_length, linewidths=0.5,
                  colors=evt_tick_color, alpha=evt_tick_alpha)
plt.ylim(ylim_min, ylim_max)

""" save fig """
plt.savefig('./temp_figs/laser_response_{}_{}_{}.png'.format(keyword_tank, signal_type, name_evt))




""" psth to stim onset """

def GetPSTH(tankname, signal_type='spk'):

    [blk, data_df, name_tdt_blocks] = data_load_DLSH.load_data('x_.*{}.*'.format('grating'), tankname, tf_interactive=False,
                                                               dir_tdt_tank=dir_tdt_tank, dir_dg=dir_dg, sortname='')
예제 #37
0
def ctree_test(clust_str, var_str, space_str, rng, num_samples):
    from data import UniformMixture as um

    def gen_data(clust_str, var_str, space_str, rng, num_samples):
        size_map = {'s': 1, 'm': 3, 'l': 5}
        var_map = {'s': 1, 'm': 3, 'l': 5}
        space_map = {'s': 1, 'm': 3, 'l': 5}
        
        sizes = [[size_map[c] for c in clust] for clust in clust_str.split('-')]
        sizes = [sum(csizes) for csizes in sizes]
        spaces = [[space_map[c] for c in clust] for clust in space_str.split('-')]
        spaces = [sum(cspaces) for cspaces in spaces]
        variances = [[var_map[c] for c in clust] for clust in var_str.split('-')] 
        variances = [sum(cvars) for cvars in variances]

        total_space = sum(spaces) + sum(variances)
        total_size = sum(sizes)
        ranges, probs = [], []
        tspace = 0
        for i in range(len(variances)):
            space, var, size = spaces[i], variances[i], sizes[i]
            tspace += space
            start = (tspace * 1.0 / total_space) * rng
            end = start + var * 1.0 / total_space * rng
            slot = (start, end)
            tspace += var
            prob = size * 1.0 / total_size
            ranges.append(slot); probs.append(prob)

        dist = um(ranges, probs)
        data = dist.sample(num_samples) 
        return data
    
    def draw_ellipse(axes, cluster):
        x = 0.5 * (cluster.data[0] + cluster.data[1])
        rng = cluster.data[1] - cluster.data[0]
        y = .25 + (cluster.level - 1) * 1.5 / (max_level - 1) 
        height = 1.5 / (max_level - 1)
        ell = Ellipse(xy=[x,y], width=rng, height=height, angle=0)
        axes.add_artist(ell)
        ell.set_clip_box(axes.bbox)
        ell.set_alpha(0.5)
        ell.set_facecolor([0, 0, 1.0])

    data = gen_data(clust_str, var_str, space_str, rng, num_samples)
    ct = ClusterTree(data)
    max_level, clusters = ct.max_level, ct.clusters

    fig, ax = plt.subplots()
    offset, length = [1], [2.0]
    plt.hlines(0.1, 0, rng) 
    plt.xlim([0, rng])
    plt.ylim([0, 2.0])

    ev = plt.eventplot(data, lineoffsets=offset, linelengths=length, orientation='horizontal', colors='b')
    ax.get_yaxis().set_visible(False)

    for cluster in clusters:
        draw_ellipse(ax, clusters[cluster])

    plt.show()
예제 #38
0
two_arrays_to_be_plotted = np.array([EigenfrequenzenLuft_final, mitte])
# Plot
plt.clf()
# Titel
ax1 = plt.axes(frameon=False)
ax1.set_title ('Position des Mikrofons: Mitte')
# Kein Rahmen
ax1.set_frame_on(False)
ax1.get_xaxis().tick_bottom()
# keine y-Achse
ax1.axes.get_yaxis().set_visible(False)
# hinzugecheatete x-Achse
ax1.add_artist(mpl.lines.Line2D((150, 1250), (0, 0), color='black', linewidth=2))
plt.xlabel(r'$f \:/\: \si{\hertz}$')
# fancy eventplot für 1D-Darstellung mit Balken
plt.eventplot(two_arrays_to_be_plotted, colors=colors1, lineoffsets = lineoffsets, linelengths = linelengths, linewidth = linewidth)
plt.tight_layout(pad=0, h_pad=1.08, w_pad=1.08)
plt.savefig('build/mitte.pdf')

# Data
two_arrays_to_be_plotted = np.array([EigenfrequenzenLuft_final, rechts])
# Plot
plt.clf()
# Titel
ax1 = plt.axes(frameon=False)
ax1.set_title ('Position des Mikrofons: Rechts')
# Kein Rahmen
ax1.set_frame_on(False)
ax1.get_xaxis().tick_bottom()
# keine y-Achse
ax1.axes.get_yaxis().set_visible(False)
예제 #39
0
# Get OSN and PN label indices:
osn_ind_labels = [int(re.search('osn_.*_(\d+)', name).group(1)) \
                  for name in df_node.ix[osn_ind].name]
pn_ind_labels = [int(re.search('.*_pn_(\d+)', name).group(1)) \
                 for name in df_node.ix[pn_ind].name]

fmt = lambda x, pos: '%2.2f' % (float(x)/1e4)
with h5py.File('./data/olfactory_input.h5', 'r') as fi, \
    h5py.File('olfactory_output_spike.h5', 'r') as fo:
    data_i = fi['array'].value
    data_o = fo['array'].value
mpl.rcParams['figure.dpi'] = 120
mpl.rcParams['figure.figsize'] = (12,9)

raster = lambda data: plt.eventplot([np.nonzero(data[i, :])[0] for i in xrange(data.shape[0])],
                                    colors = [(0, 0, 0)],
                                    lineoffsets = np.arange(data.shape[0]),
                                    linelengths = np.ones(data.shape[0])/2.0)
f = plt.figure()
plt.subplot(311)
ax = plt.gca()
ax.xaxis.set_major_formatter(ticker.FuncFormatter(fmt))
plt.plot(data_i[:10000,0])
ax.set_ylim(np.min(data_i)-1, np.max(data_i)+1)
ax.set_xlim(0, 10000)
plt.title('Input Stimulus'); plt.ylabel('Concentration') 

plt.subplot(312)
raster(data_o.T[osn_ind, :])
plt.title('Spikes Generated by OSNs'); plt.ylabel('OSN #');
ax = plt.gca()
ax.set_ylim(np.min(osn_ind_labels), np.max(osn_ind_labels))