Example #1
0
def test_regression_spiky():
    # standard example
    st1 = SpikeTrain(np.arange(100, 1201, 100), 1300)
    st2 = SpikeTrain(np.arange(100, 1201, 110), 1300)

    isi_dist = spk.isi_distance(st1, st2)
    assert_almost_equal(isi_dist, 9.0909090909090939e-02, decimal=15)
    isi_profile = spk.isi_profile(st1, st2)
    assert_equal(isi_profile.y, 0.1/1.1 * np.ones_like(isi_profile.y))

    spike_dist = spk.spike_distance(st1, st2)
    assert_equal(spike_dist, 2.1105878248735391e-01)

    spike_sync = spk.spike_sync(st1, st2)
    assert_equal(spike_sync, 8.6956521739130432e-01)

    # multivariate check

    spike_trains = spk.load_spike_trains_from_txt("test/PySpike_testdata.txt",
                                                  (0.0, 4000.0))
    isi_dist = spk.isi_distance_multi(spike_trains)
    # get the full precision from SPIKY
    assert_almost_equal(isi_dist, 0.17051816816999129656, decimal=15)

    spike_profile = spk.spike_profile_multi(spike_trains)
    assert_equal(len(spike_profile.y1)+len(spike_profile.y2), 1252)

    spike_dist = spk.spike_distance_multi(spike_trains)
    # get the full precision from SPIKY
    assert_almost_equal(spike_dist, 2.4432433330596512e-01, decimal=15)

    spike_sync = spk.spike_sync_multi(spike_trains)
    # get the full precision from SPIKY
    assert_equal(spike_sync, 0.7183531505298066)
Example #2
0
def test_regression_spiky():
    # standard example
    st1 = SpikeTrain(np.arange(100, 1201, 100), 1300)
    st2 = SpikeTrain(np.arange(100, 1201, 110), 1300)

    isi_dist = spk.isi_distance(st1, st2)
    assert_almost_equal(isi_dist, 9.0909090909090939e-02, decimal=15)
    isi_profile = spk.isi_profile(st1, st2)
    assert_equal(isi_profile.y, 0.1 / 1.1 * np.ones_like(isi_profile.y))

    spike_dist = spk.spike_distance(st1, st2)
    assert_equal(spike_dist, 0.211058782487353908)

    spike_sync = spk.spike_sync(st1, st2)
    assert_equal(spike_sync, 8.6956521739130432e-01)

    # multivariate check

    spike_trains = spk.load_spike_trains_from_txt(
        os.path.join(TEST_PATH, "PySpike_testdata.txt"), (0.0, 4000.0))
    isi_dist = spk.isi_distance_multi(spike_trains)
    # get the full precision from SPIKY
    assert_almost_equal(isi_dist, 0.17051816816999129656, decimal=15)

    spike_profile = spk.spike_profile_multi(spike_trains)
    assert_equal(len(spike_profile.y1) + len(spike_profile.y2), 1252)

    spike_dist = spk.spike_distance_multi(spike_trains)
    # get the full precision from SPIKY
    assert_almost_equal(spike_dist, 0.25188056475463755, decimal=15)

    spike_sync = spk.spike_sync_multi(spike_trains)
    # get the full precision from SPIKY
    assert_equal(spike_sync, 0.7183531505298066)

    # Eero's edge correction example
    st1 = SpikeTrain([0.5, 1.5, 2.5], 6.0)
    st2 = SpikeTrain([3.5, 4.5, 5.5], 6.0)

    f = spk.spike_profile(st1, st2)

    expected_times = np.array([0.0, 0.5, 1.5, 2.5, 3.5, 4.5, 5.5, 6.0])
    y_all = np.array([
        0.271604938271605, 0.271604938271605, 0.271604938271605,
        0.617283950617284, 0.617283950617284, 0.444444444444444,
        0.285714285714286, 0.285714285714286, 0.444444444444444,
        0.617283950617284, 0.617283950617284, 0.271604938271605,
        0.271604938271605, 0.271604938271605
    ])
    expected_y1 = y_all[::2]
    expected_y2 = y_all[1::2]

    assert_equal(f.x, expected_times)
    assert_array_almost_equal(f.y1, expected_y1, decimal=14)
    assert_array_almost_equal(f.y2, expected_y2, decimal=14)
def test_regression_random():

    spike_file = "test/numeric/regression_random_spikes.mat"
    spikes_name = "spikes"
    result_name = "Distances"
    result_file = "test/numeric/regression_random_results_cSPIKY.mat"

    spike_train_sets = loadmat(spike_file)[spikes_name][0]
    results_cSPIKY = loadmat(result_file)[result_name]

    for i, spike_train_data in enumerate(spike_train_sets):
        spike_trains = []
        for spikes in spike_train_data[0]:
            spike_trains.append(spk.SpikeTrain(spikes.flatten(), 100.0))

        isi = spk.isi_distance_multi(spike_trains)
        isi_prof = spk.isi_profile_multi(spike_trains).avrg()

        spike = spk.spike_distance_multi(spike_trains)
        spike_prof = spk.spike_profile_multi(spike_trains).avrg()

        spike_sync = spk.spike_sync_multi(spike_trains)
        spike_sync_prof = spk.spike_sync_profile_multi(spike_trains).avrg()

        assert_almost_equal(isi,
                            results_cSPIKY[i][0],
                            decimal=14,
                            err_msg="Index: %d, ISI" % i)
        assert_almost_equal(isi_prof,
                            results_cSPIKY[i][0],
                            decimal=14,
                            err_msg="Index: %d, ISI" % i)

        assert_almost_equal(spike,
                            results_cSPIKY[i][1],
                            decimal=14,
                            err_msg="Index: %d, SPIKE" % i)
        assert_almost_equal(spike_prof,
                            results_cSPIKY[i][1],
                            decimal=14,
                            err_msg="Index: %d, SPIKE" % i)

        assert_almost_equal(spike_sync,
                            spike_sync_prof,
                            decimal=14,
                            err_msg="Index: %d, SPIKE-Sync" % i)
    spiketrains = []
    print("")
    print("Constructing {} spike trains ...".format(N))
    for n in range(N):
        spiketrains.append(sl.tools.poisson_spikes(end, 10))
    print("Running pairwise_mp ...")
    tstart = time.time()
    # _ = sl.metrics.kreuz.pairwise_mp(spiketrains, start, end, 2000)
    tend = time.time()
    sla.append(tend-tstart)
    print("Running multivariate ...")
    tstart = time.time()
    _ = sl.metrics.kreuz.multivariate(spiketrains, start, end, 2000)
    tend = time.time()
    slm.append(tend-tstart)
    for idx in range(len(spiketrains)):
        spiketrains[idx] = spk.add_auxiliary_spikes(spiketrains[idx], end)
    print("Running PySpike ...")
    tstart = time.time()
    _ = spk.spike_profile_multi(spiketrains)
    tend = time.time()
    spa.append(tend-tstart)
    print("Finished {}".format(N))

plt.figure()
plt.plot(Nlist, sla, label="PW-MP")
plt.plot(Nlist, slm, label="Multi")
plt.plot(Nlist, spa, label="PySpk")
plt.legend()
plt.show()
    sim_dir = '../simulations/' + sim_ref
    time = np.loadtxt(sim_dir + '/time.dat')
    spike_trains = []
    for cell in range(n_cells):
        spikes = np.loadtxt(
            '{}/Golgi_network_reduced_{}.SPIKES_min20.spike'.format(
                sim_dir, cell))
        spike_trains.append(pyspike.add_auxiliary_spikes(spikes, sim_duration))
        if trial == 0:
            ax[0].scatter(spikes,
                          np.zeros_like(spikes) + cell,
                          marker='|',
                          s=2,
                          c=color)
    distances.append(
        pyspike.spike_profile_multi(spike_trains[n_excluded_cells:]))

# average synchrony index across trials
average_distance = distances[0]
for distance in distances[1:]:
    average_distance.add(distance)
average_distance.mul_scalar(1. / n_trials)

xmin = 50
xmax = 1900
x, y = average_distance.get_plottable_data()
ximin = np.searchsorted(x, xmin)
ximax = np.searchsorted(x, xmax)
lines.append(ax[1].plot(x[ximin:ximax + 1],
                        1 - y[ximin:ximax + 1],
                        lw=2,
def Synchronization_analysis(sim_duration,specify_targets,no_of_groups,exp_specify,spike_plot_parameters,general_plot_parameters):
    
    cell_no_array=[]
    for exp_id in range(0,len(exp_specify[0]) ):
        if exp_specify[1][1]==True:
           for cell_group in range(0,no_of_groups):
               cell_group_positions=np.loadtxt('simulations/%s/Golgi_pop%d.txt'%(exp_specify[0][exp_id],cell_group))
               dim_array=np.shape(cell_group_positions)
               cell_no_array.append(dim_array[0])
           
        else:
           for cell_group in range(0,no_of_groups):
               cell_group_positions=np.loadtxt('simulations/%s/sim0/Golgi_pop%d.txt'%(exp_specify[0][exp_id],cell_group))
               dim_array=np.shape(cell_group_positions)
               cell_no_array.append(dim_array[0])



    n_trials=exp_specify[2]

   

    lines = []
    lines_sep=[]
    experiment_seed=random.sample(range(0,15000),1)[0]
    for exp_id in range(0,len(exp_specify[0])):
        #get target ids
        experiment_parameters=[]
        experiment_parameters.append(exp_specify[0][exp_id])
        experiment_parameters.append(exp_specify[1])
        experiment_parameters.append(exp_specify[2])
       
        target_cell_array=get_cell_ids_for_sync_analysis(specify_targets,no_of_groups,experiment_parameters,experiment_seed)
        test_array=target_cell_array
        
        if exp_id==0:
           
           if "save sync plot to a separate file" in spike_plot_parameters:
              fig_sync, ax_sync=plt.subplots(figsize=(2,1.5),ncols=1,nrows=1)
              
           if spike_plot_parameters[0]=="2D raster plots":
              trial_indicator_target=False
              if n_trials >1:
                 target_cell_array_target_trial=target_cell_array[spike_plot_parameters[1]]
                 no_of_rasters=0
                 if target_cell_array_target_trial != []:
                    test_non_empty_target_array=True
                    trial_indicator_target=True
                    no_of_rasters=len(target_cell_array_target_trial)
                    rows=1+no_of_rasters
                    columns=1
                    fig_stack, ax_stack = plt.subplots(figsize=(4,rows+1),ncols=columns,nrows=rows, sharex=True)
                    ax_stack=ax_stack.ravel()
                 
                    
              else:
                 no_of_rasters=0
                 if target_cell_array != []:
                    target_cell_array_target_trial=target_cell_array[0]
                    trial_indicator_target=True
                    no_of_rasters=len(target_cell_array)
                    rows=1+no_of_rasters
                    columns=1
                    fig_stack, ax_stack = plt.subplots(figsize=(4,rows),ncols=columns,nrows=rows, sharex=True)
                    ax_stack=ax_stack.ravel()
              
              if "save all trials to separate files" in spike_plot_parameters:
                 raster_fig_array=[]
                 raster_ax_array=[]
                 pop_no_array=[]
                 trial_indicator_target=False
                 if n_trials >1:
                    non_empty_trial_indices=[]
                    for trial in range(0,n_trials):
                        if target_cell_array[trial] !=[]:
                           non_empty_trial_indices.append(trial)
                    test_indices=non_empty_trial_indices
                    for trial in range(0,len(non_empty_trial_indices)):
                        target_trial=target_cell_array[non_empty_trial_indices[trial]]
                        columns=1
                        rows=len(target_trial)
                        pop_no_array.append(rows)
                        plot_rows=rows+1
                        fig, ax = plt.subplots(figsize=(4,plot_rows),ncols=columns,nrows=rows, sharex=True)
                        if len(target_trial) >1 :
                           ax=ax.ravel()
                        raster_fig_array.append(fig)
                        raster_ax_array.append(ax)
                 else:
                    no_of_rasters=0
                    if target_cell_array != []:
                       trial_indicator_target=True
                       no_of_rasters=len(target_cell_array)
                       rows=no_of_rasters
                       pop_no_array.append(rows)
                       columns=1
                       plot_rows=rows+1
                       fig_stack_one_trial, ax_stack_one_trial= plt.subplots(figsize=(4,plot_rows),ncols=columns,nrows=rows, sharex=True)
                       if no_of_rasters  >  1:
                          ax_stack_one_trial=ax_stack.ravel()
              if "save all trials to one separate file" in spike_plot_parameters:
                 pop_no_array=[]
                 if n_trials >1:
                    non_empty_trial_indices=[]
                    for trial in range(0,n_trials):
                        if target_cell_array[trial] !=[]:
                           non_empty_trial_indices.append(trial)
                    total_no_of_rows=0
                    for trial in range(0,len(non_empty_trial_indices)):
                        target_trial=target_cell_array[non_empty_trial_indices[trial]]
                        
                        rows=len(target_trial)
                        pop_no_array.append(rows)
                        total_no_of_rows=total_no_of_rows + rows
                    
                    fig_all_trials, ax_all_trials = plt.subplots(figsize=(4,total_no_of_rows),ncols=1,nrows=total_no_of_rows, sharex=True)
                    if total_no_of_rows >1 :
                        ax_all_trials=ax_all_trials.ravel()
                    
                        
                 

                 

                    
        non_empty_non_unitary_trial_counter=0
        distances = []
        
        color = sns.color_palette()[exp_id+1]
        
        row_counter=0
        target_pop_index_array=[]
        if spike_plot_parameters[0]=="2D raster plots":
           if "save all trials to one separate file" in spike_plot_parameters:
              row_array=range(0,total_no_of_rows)
        if spike_plot_parameters[0]=="2D raster plots":
           if "save all trials to separate files" in spike_plot_parameters:
              raster_ax_row_counter=0
            
        for trial in range(0,n_trials):
            sim_dir = 'simulations/' + exp_specify[0][exp_id]+'/sim%d'%trial+'/txt'
            ######   
            if n_trials > 1:
               target_cell_array_per_trial=target_cell_array[trial]
            else:
               target_cell_array_per_trial=target_cell_array[0]
            
            if target_cell_array_per_trial !=[]:
               spike_trains = []
               target_pop_index_array_per_trial=[]
               print(" Trial %d is not empty"%(trial))
               for target_pop in range(0,len(target_cell_array_per_trial)):
                   for pop in range(0,no_of_groups):
                       if ('pop%d'%(pop)) in target_cell_array_per_trial[target_pop]:
                          target_pop_index_array_per_trial.append(pop)
                          target_cells = [x for x in target_cell_array_per_trial[target_pop] if isinstance(x,int)]
                          print target_cells
                          for cell in range(0,len(target_cells)):
                              #create target txt file containing spike times
                              #if not os.path.isfile('%s/Golgi_pop%d_cell%d.txt'%(sim_dir,pop,target_cells[cell])):
                              get_spike_times('Golgi_pop%d_cell%d'%(pop,target_cells[cell]),exp_specify[0][exp_id],trial)
                              spikes = np.loadtxt('%s/Golgi_pop%d_cell%d.txt'%(sim_dir,pop,target_cells[cell]))
                              spike_train=pyspike.SpikeTrain(spikes,[0,sim_duration])
                              spike_trains.append(spike_train)
                              print spike_trains
                              if spike_plot_parameters[0]=="2D raster plots":
                                 if spike_plot_parameters[1]==trial:
                                    ax_stack[target_pop].scatter(spikes,np.zeros_like(spikes)+target_cells[cell]+exp_id*(cell_no_array[pop]+1) ,marker='|',s=2,c=color)
                                 if "save all trials to separate files" in spike_plot_parameters:
                                    if n_trials >1:
                                       if len(target_cell_array_per_trial) > 1:
                                          raster_ax_array[raster_ax_row_counter][target_pop].scatter(spikes,np.zeros_like(spikes)+target_cells[cell]+exp_id*(cell_no_array[pop]+1) ,marker='|',s=2,c=color)
                                          
                                       else:
                                          raster_ax_array[raster_ax_row_counter].scatter(spikes,np.zeros_like(spikes)+target_cells[cell]+exp_id*(cell_no_array[pop]+1) ,marker='|',s=2,c=color)
                                          
                                    else:
                                       if len(target_cell_array_per_trial) >1:
                                          ax_stack_one_trial[target_pop].scatter(spikes,np.zeros_like(spikes)+target_cells[cell]+exp_id*(cell_no_array[pop]+1) ,marker='|',s=2,c=color)
                                       else:
                                          ax_stack_one_trial.scatter(spikes,np.zeros_like(spikes)+target_cells[cell]+exp_id*(cell_no_array[pop]+1) ,marker='|',s=2,c=color)
                                 if "save all trials to one separate file" in spike_plot_parameters:
                                    if n_trials >1:
                                       if total_no_of_rows >1 :
                                          ax_all_trials[row_array[row_counter]].scatter(spikes,np.zeros_like(spikes)+target_cells[cell]+exp_id*(cell_no_array[pop]+1) ,marker='|',s=2,c=color)
                                          
                                       else:
                                          ax_all_trials.scatter(spikes,np.zeros_like(spikes)+target_cells[cell]+exp_id*(cell_no_array[pop]+1) ,marker='|',s=2,c=color)
                          if spike_plot_parameters[0]=="2D raster plots":
                             if "save all trials to one separate file" in spike_plot_parameters:
                                row_counter=row_counter+1

               if spike_plot_parameters[0]=="2D raster plots":
                  if "save all trials to separate files" in spike_plot_parameters:

                     raster_ax_row_counter+=1
                  
              
               target_pop_index_array.append(target_pop_index_array_per_trial)

               if spike_plot_parameters[1]==trial:
                  target_trial_index=target_pop_index_array.index(target_pop_index_array_per_trial) 
               

               


               #target_pop_index_array.append(target_pop_index_array_per_trial)
               ########   
               print("Length of spike_trains is %d"%len(spike_trains))
               if len(spike_trains) >1:
                  print("Trial %d contains more than one cell; Synchrony metric will be computed for this trial"%(trial))
                  non_empty_non_unitary_trial_counter+=1
                  print non_empty_non_unitary_trial_counter
                  distances.append(pyspike.spike_profile_multi(spike_trains))
               else:
                  print("Trial %d contains one cell; Synchrony metric will not be computed for this trial"%(trial))
               ######## 
               
        # average synchrony index across "non empty" trials
        average_distance = distances[0]
        for distance in distances[1:]:
            average_distance.add(distance)
        average_distance.mul_scalar(1./non_empty_non_unitary_trial_counter)

        # below blocks for saving synchrony and spike raster plots
        
        mark_steps=sim_duration/50
        marks=[]
        for mark in range(0,mark_steps+1):
            Mark=50*mark
            marks.append(Mark)

        xmin = 50
        right_shaded_region=50
        if sim_duration >=1000:
            right_shaded_region=100
        xmax = sim_duration-right_shaded_region
        x, y = average_distance.get_plottable_data()
        ximin = np.searchsorted(x, xmin)
        ximax = np.searchsorted(x, xmax)
        if spike_plot_parameters[0]=="2D raster plots":
           if target_cell_array_target_trial != []:
              target_cell_array_target_trial_indicator=True
              lines.append(ax_stack[no_of_rasters].plot(x[ximin:ximax+1], 1-y[ximin:ximax+1], lw=2, c=color)[0])
              ax_stack[no_of_rasters].plot(x[:ximin+1], 1-y[:ximin+1], lw=2, c=color, alpha=0.4)
              ax_stack[no_of_rasters].plot(x[ximax:], 1-y[ximax:], lw=2, c=color, alpha=0.4)
        if "save sync plot to a separate file" in spike_plot_parameters:
           lines_sep.append(ax_sync.plot(x[ximin:ximax+1], 1-y[ximin:ximax+1], lw=2, c=color)[0])
           ax_sync.plot(x[:ximin+1], 1-y[:ximin+1], lw=2, c=color, alpha=0.4)
           ax_sync.plot(x[ximax:], 1-y[ximax:], lw=2, c=color, alpha=0.4)
        
             
              
    
    if "save sync plot to a separate file" in spike_plot_parameters:
       print("save sync plot to a separate file is specified")
       for tick in ax_sync.xaxis.get_major_ticks():
           tick.label.set_fontsize(general_plot_parameters[4]) 
       for tick in ax_sync.yaxis.get_major_ticks():
           tick.label.set_fontsize(general_plot_parameters[5])
       ax_sync.locator_params(axis='y', tight=True, nbins=10)
       ax_sync.set_xlabel('Time (ms)',fontsize=4)
       ax_sync.set_ylabel('Synchrony index',size=4)
       ax_sync.set_ylim(0,1)
       ax_sync.set_xticks(marks)
       ax_sync.set_title('Synchronization between %s'%general_plot_parameters[1],size=4)
       fig_sync.tight_layout()

       fig_sync.subplots_adjust(top=0.90)
       fig_sync.subplots_adjust(bottom=0.55)
       l=fig_sync.legend(lines_sep,general_plot_parameters[3],title=general_plot_parameters[2],loc='center',ncol=len(general_plot_parameters[3]),bbox_to_anchor=(0.52, 0.25),prop={'size':4})
       plt.setp(l.get_title(),fontsize=4)
          
       fig_sync.savefig('simulations/sync_only_%s.%s'%(general_plot_parameters[0],spike_plot_parameters[-1]))
       print("saved %s in simulations"%'sync_only_%s.%s'%(general_plot_parameters[0],spike_plot_parameters[-1]))
       
    if spike_plot_parameters[0]=="2D raster plots":    
       print("Intend to plot a main figure with representative 2D raster plots")
       #create label array
       if trial_indicator_target:
          print("2D raster plot procedures started")
          for pop in range(0,no_of_rasters):
              label_array=[]
              ytick_array=[]
              for exp in range(0,len(general_plot_parameters[3])):
                  label_array.append("%d"%0)
                  label_array.append("%d"%(cell_no_array[target_pop_index_array[target_trial_index][pop]]-1))

                  if exp==0:
                     ytick_array.append(exp)
                     ytick_array.append(cell_no_array[target_pop_index_array[target_trial_index][pop]]-1)
                     left_value=cell_no_array[target_pop_index_array[target_trial_index][pop]]-1
                  else:
                     ytick_array.append(left_value+2)
                     ytick_array.append(left_value+1+cell_no_array[target_pop_index_array[target_trial_index][pop]])
                     left_value=left_value+2+cell_no_array[target_pop_index_array[target_trial_index][pop]]

              print label_array
              print ytick_array
            
              ax_stack[pop].set_yticks(ytick_array)
              fig_stack.canvas.draw()
              ax_stack[pop].set_ylim(0,(cell_no_array[target_pop_index_array[target_trial_index][pop]]+1)*len(general_plot_parameters[3]) )
              ax_stack[pop].set_ylabel('Cell ids, population %d'%pop,size=4)
              ax_stack[pop].set_yticks([cell_no_array[target_pop_index_array[target_trial_index][pop]]+(cell_no_array[target_pop_index_array[target_trial_index][pop]]+2)*k for k in range(0,len(general_plot_parameters[3]))],minor=True)
              ax_stack[pop].yaxis.grid(False, which='major')
              ax_stack[pop].yaxis.grid(True, which='minor')
           
              labels = [x.get_text() for x in ax_stack[pop].get_yticklabels()]
           
              for label in range(0,len(labels)):
                   labels[label] =label_array[label]

              ax_stack[pop].set_yticklabels(labels)
              if pop==0:
                 ax_stack[pop].set_title('Raster plots for target Golgi cell populations (trial id=%d)'%spike_plot_parameters[1],size=6)
              for pop in range(0,no_of_rasters+1):
                  for tick in ax_stack[pop].xaxis.get_major_ticks():
                      tick.label.set_fontsize(general_plot_parameters[4]) 
                  for tick in ax_stack[pop].yaxis.get_major_ticks():
                      tick.label.set_fontsize(general_plot_parameters[5])
          ax_stack[no_of_rasters].locator_params(axis='y', tight=True, nbins=10)
          ax_stack[no_of_rasters].set_xlabel('Time (ms)',fontsize=6)
          ax_stack[no_of_rasters].set_ylabel('Synchrony index',size=4)
          ax_stack[no_of_rasters].set_ylim(0,1)
          ax_stack[no_of_rasters].set_xticks(marks)
          ax_stack[no_of_rasters].set_title('Synchronization between %s'%general_plot_parameters[1],size=6)
          fig_stack.tight_layout()
       
          fig_stack.subplots_adjust(top=0.80)
          fig_stack.subplots_adjust(bottom=0.15)
          fig_stack.subplots_adjust(hspace=.4)
          l=fig_stack.legend(lines,general_plot_parameters[3],title=general_plot_parameters[2], loc='upper center',ncol=len(general_plot_parameters[3]),bbox_to_anchor=(0.55, 1.2))
          max_xticks = 10
          xloc = plt.MaxNLocator(max_xticks)
          ax_stack[no_of_rasters].xaxis.set_major_locator(xloc)
              
          plt.setp(l.get_title(),fontsize=6)
          plt.setp(l.get_texts(), fontsize=6)
          fig_stack.savefig('simulations/%s.%s'%(general_plot_parameters[0],spike_plot_parameters[-1]),bbox_extra_artists=(l,),bbox_inches='tight')
       else:
          print("Intended to plot raster plots for trial %d, but specified region-specific selection of cells produces an empty target array.\nThus a main figure with a representative raster will not be produced.\nHowever, synchrony plot can be saved in a separate file.\nAlternatively, plot a non-empty trial"%(spike_plot_parameters[1]))
       if "save all trials to one separate file" in spike_plot_parameters:
          print target_pop_index_array
          if total_no_of_rows >1:
             row_counter=0
             for trial in range(0,len(non_empty_trial_indices)):
                 if len(target_pop_index_array[trial]) >1:
                    for pop in range(0,len(target_pop_index_array[trial])):
                        label_array=[]
                        ytick_array=[]
                        for exp in range(0,len(general_plot_parameters[3])):
                            label_array.append("%d"%0)
                            label_array.append("%d"%(cell_no_array[target_pop_index_array[trial][pop] ]-1))
                            if exp==0:
                               ytick_array.append(exp)
                               ytick_array.append(cell_no_array[target_pop_index_array[trial][pop]]-1)
                               left_value=cell_no_array[target_pop_index_array[trial][pop]]-1
                            else:
                               ytick_array.append(left_value+2)
                               ytick_array.append(left_value+1+cell_no_array[target_pop_index_array[trial][pop]]   )
                               left_value=left_value+2+cell_no_array[target_pop_index_array[trial][pop]]
                        ax_all_trials[row_counter].set_yticks(ytick_array)
                        #ax_all_trials[row_counter].canvas.draw()
                        ax_all_trials[row_counter].set_ylim(0,(cell_no_array[target_pop_index_array[trial][pop]]+1)*len(general_plot_parameters[3]) )
                        ax_all_trials[row_counter].set_ylabel('Cell ids for Golgi pop %d\ntrial %d'%(target_pop_index_array[trial][pop],non_empty_trial_indices[trial]),size=4)
                        ax_all_trials[row_counter].set_yticks([cell_no_array[target_pop_index_array[trial][pop]]+( cell_no_array[target_pop_index_array[trial][pop]]+2)*k for k in range(0,len(general_plot_parameters[3]))],minor=True)
                        ax_all_trials[row_counter].yaxis.grid(False, which='major')
                        ax_all_trials[row_counter].yaxis.grid(True, which='minor')
                        if row_counter==total_no_of_rows-1:
                           ax_all_trials[row_counter].set_xlabel('Time (ms)',fontsize=4)
           
                        labels = [x.get_text() for x in  ax_all_trials[row_counter].get_yticklabels()]
           
                        for label in range(0,len(labels)):
                             labels[label] =label_array[label]

                        ax_all_trials[row_counter].set_yticklabels(labels)
                         
                        for tick in ax_all_trials[row_counter].xaxis.get_major_ticks():
                            tick.label.set_fontsize(general_plot_parameters[4]) 
                        for tick in ax_all_trials[row_counter].yaxis.get_major_ticks():
                            tick.label.set_fontsize(general_plot_parameters[5])
                        row_counter+=1
                 else:
                    label_array=[]
                    ytick_array=[]
                    for exp in range(0,len(general_plot_parameters[3])):
                        label_array.append("%d"%0)
                        label_array.append("%d"%(cell_no_array[target_pop_index_array[trial][0]]-1))
                        if exp==0:
                           ytick_array.append(exp)
                           ytick_array.append(cell_no_array[target_pop_index_array[trial][0]]-1)
                           left_value=cell_no_array[target_pop_index_array[trial][0]]-1
                        else:
                           ytick_array.append(left_value+2)
                           ytick_array.append(left_value+1+cell_no_array[target_pop_index_array[trial][0]]   )
                           left_value=left_value+2+cell_no_array[target_pop_index_array[trial][0]]
                    ax_all_trials[row_counter].set_yticks(ytick_array)
                    ax_all_trials[row_counter].set_ylim(0,(cell_no_array[target_pop_index_array[trial][0]]+1)*len(general_plot_parameters[3]) )
                    ax_all_trials[row_counter].set_ylabel('Cell ids for pop %d\ntrial %d'%(target_pop_index_array[trial][0],non_empty_trial_indices[trial]),size=4)
                    ax_all_trials[row_counter].set_yticks([cell_no_array[target_pop_index_array[trial][0]]+( cell_no_array[target_pop_index_array[trial][0]]+2)*k for k in range(0,len(general_plot_parameters[3]))],minor=True)
                    ax_all_trials[row_counter].yaxis.grid(False, which='major')
                    ax_all_trials[row_counter].yaxis.grid(True, which='minor')
                    if row_counter==total_no_of_rows-1:
                       ax_all_trials[row_counter].set_xlabel('Time (ms)',fontsize=4)
           
                    labels = [x.get_text() for x in  ax_all_trials[row_counter].get_yticklabels()]
           
                    for label in range(0,len(labels)):
                        labels[label] =label_array[label]

                    ax_all_trials[row_counter].set_yticklabels(labels)
                         
                    for tick in ax_all_trials[row_counter].xaxis.get_major_ticks():
                        tick.label.set_fontsize(general_plot_parameters[4]) 
                    for tick in ax_all_trials[row_counter].yaxis.get_major_ticks():
                        tick.label.set_fontsize(general_plot_parameters[5])
                    row_counter+=1

          else:
             label_array=[]
             ytick_array=[]
             for exp in range(0,len(general_plot_parameters[3])):
                 label_array.append("%d"%0)
                 label_array.append("%d"%(cell_no_array[target_pop_index_array[0][0]]-1))
                 if exp==0:
                    ytick_array.append(exp)
                    ytick_array.append(cell_no_array[target_pop_index_array[0][pop]]-1)
                    left_value=cell_no_array[target_pop_index_array[0][0]]-1
                 else:
                    ytick_array.append(left_value+2)
                    ytick_array.append(left_value+1+cell_no_array[target_pop_index_array[0][0]]   )
                    left_value=left_value+2+cell_no_array[target_pop_index_array[0][0]]
             ax_all_trials.set_yticks(ytick_array)
             ax_all_trials.canvas.draw()
             ax_all_trials.set_ylim(0,(cell_no_array[target_pop_index_array[0][0]]+1)*len(general_plot_parameters[3]) )
             ax_all_trials.set_ylabel('Cell ids for pop %d\ntrial %d'%(target_pop_index_array[trial][pop],non_empty_trial_indices[trial]),size=4)
             ax_all_trials.set_yticks([cell_no_array[target_pop_index_array[0][0]]+( cell_no_array[target_pop_index_array[0][0]]+2)*k for k in range(0,len(general_plot_parameters[3]))],minor=True)
             ax_all_trials.yaxis.grid(False, which='major')
             ax_all_trials.yaxis.grid(True, which='minor')
             ax_all_trials.set_xlabel('Time (ms)',fontsize=4)
           
             labels = [x.get_text() for x in  ax_all_trials.get_yticklabels()]
           
             for label in range(0,len(labels)):
                 labels[label] =label_array[label]

             ax_all_trials.set_yticklabels(labels)
                         
             for tick in ax_all_trials.xaxis.get_major_ticks():
                 tick.label.set_fontsize(general_plot_parameters[4]) 
             for tick in ax_all_trials.yaxis.get_major_ticks():
                 tick.label.set_fontsize(general_plot_parameters[5])
          
          fig_all_trials.subplots_adjust(hspace=0.1)
          fig_all_trials.subplots_adjust(top=0.95)
          fig_all_trials.subplots_adjust(bottom=0.1)
          l=fig_all_trials.legend(lines,general_plot_parameters[3],title=general_plot_parameters[2],loc='center',ncol=len(general_plot_parameters[3]),bbox_to_anchor=(0.52, 0.98),prop={'size':4})
          plt.setp(l.get_title(),fontsize=4)

          fig_all_trials.savefig('simulations/all_trials_%s.%s'%(general_plot_parameters[0],spike_plot_parameters[-1]))
          plt.clf() 
             
       if "save all trials to separate files" in spike_plot_parameters:
          if n_trials >1:
             for trial in range(0,len(non_empty_trial_indices)):
                 print("started ploting non-empty trials")
                 if pop_no_array[trial] >1:
                    for pop in range(0,pop_no_array[trial]):
                        label_array=[]
                        ytick_array=[]
                        for exp in range(0,len(general_plot_parameters[3])):
                            label_array.append("%d"%0)
                            label_array.append("%d"%(cell_no_array[target_pop_index_array[trial][pop]]-1))
                            if exp==0:
                               ytick_array.append(exp)
                               ytick_array.append(cell_no_array[target_pop_index_array[trial][pop]]-1)
                               left_value=cell_no_array[target_pop_index_array[trial][pop]]-1
                            else:
                               ytick_array.append(left_value+2)
                               ytick_array.append(left_value+1+cell_no_array[target_pop_index_array[trial][pop]]   )
                               left_value=left_value+2+cell_no_array[target_pop_index_array[trial][pop]]
                        raster_ax_array[trial][pop].set_yticks(ytick_array)
                        raster_fig_array[trial].canvas.draw()
                        raster_ax_array[trial][pop].set_ylim(0,(cell_no_array[target_pop_index_array[trial][pop]]+1)*len(general_plot_parameters[3]) )
                        raster_ax_array[trial][pop].set_ylabel('Cell ids, population %d'%target_pop_index_array[trial][pop],size=4)
                        raster_ax_array[trial][pop].set_yticks([cell_no_array[target_pop_index_array[trial][pop]]+( cell_no_array[target_pop_index_array[trial][pop]]+2)*k for k in range(0,len(general_plot_parameters[3]))],minor=True)
                        raster_ax_array[trial][pop].yaxis.grid(False, which='major')
                        raster_ax_array[trial][pop].yaxis.grid(True, which='minor')
           
                        labels = [x.get_text() for x in raster_ax_array[trial][pop].get_yticklabels()]
           
                        for label in range(0,len(labels)):
                            labels[label] =label_array[label]

                        raster_ax_array[trial][pop].set_yticklabels(labels)
                        if pop==0:
                           raster_ax_array[trial][pop].set_title('Raster plot for Golgi cell populations (trial id=%d)'%non_empty_trial_indices[trial],size=6)
                        if pop==pop_no_array[trial]-1:
                           raster_ax_array[trial][pop].set_xlabel('Time (ms)',fontsize=6)
                        for tick in raster_ax_array[trial][pop].xaxis.get_major_ticks():
                            tick.label.set_fontsize(general_plot_parameters[4]) 
                        for tick in raster_ax_array[trial][pop].yaxis.get_major_ticks():
                            tick.label.set_fontsize(general_plot_parameters[5])
                 else:
                    label_array=[]
                    ytick_array=[]
                    for exp in range(0,len(general_plot_parameters[3])):
                        label_array.append("%d"%0)
                        label_array.append("%d"%(cell_no_array[target_pop_index_array[trial][0]]-1))
                        if exp==0:
                           ytick_array.append(exp)
                           ytick_array.append(cell_no_array[target_pop_index_array[trial][0]]-1)
                           left_value=cell_no_array[target_pop_index_array[trial][0]]-1
                        else:
                           ytick_array.append(left_value+2)
                           ytick_array.append(left_value+1+cell_no_array[target_pop_index_array[trial][0]]   )
                           left_value=left_value+2+cell_no_array[target_pop_index_array[trial][0]]
                        raster_ax_array[trial].set_yticks(ytick_array)
                        raster_fig_array[trial].canvas.draw()
                        raster_ax_array[trial].set_ylim(0,(cell_no_array[target_pop_index_array[trial][0]]+1)*len(general_plot_parameters[3]) )
                        raster_ax_array[trial].set_ylabel('Cell ids, population %d'% target_pop_index_array[trial][0],size=4)
                        raster_ax_array[trial].set_yticks([cell_no_array[target_pop_index_array[trial][0]]+( cell_no_array[target_pop_index_array[trial][0]]+2)*k for k in range(0,len(general_plot_parameters[3]))],minor=True)
                        raster_ax_array[trial].yaxis.grid(False, which='major')
                        raster_ax_array[trial].yaxis.grid(True, which='minor')
           
                        labels = [x.get_text() for x in raster_ax_array[trial].get_yticklabels()]
           
                        for label in range(0,len(labels)):
                            labels[label] =label_array[label]

                        raster_ax_array[trial].set_yticklabels(labels)
                        raster_ax_array[trial].set_title('Raster plot for Golgi cell populations (trial id=%d)'%non_empty_trial_indices[trial],size=6)
                        raster_ax_array[trial].set_xlabel('Time (ms)',fontsize=6)
                        for tick in raster_ax_array[trial].xaxis.get_major_ticks():
                            tick.label.set_fontsize(general_plot_parameters[4]) 
                        for tick in raster_ax_array[trial].yaxis.get_major_ticks():
                            tick.label.set_fontsize(general_plot_parameters[5])
                            
                 raster_fig_array[trial].subplots_adjust(top=0.90)
                 raster_fig_array[trial].subplots_adjust(bottom=0.3)
                 l=raster_fig_array[trial].legend(lines,general_plot_parameters[3],title=general_plot_parameters[2],loc='center',ncol=len(general_plot_parameters[3]),bbox_to_anchor=(0.52, 0.1),prop={'size':4})
                 plt.setp(l.get_title(),fontsize=4)

                 raster_fig_array[trial].savefig('simulations/sim%d_rasters_%s.%s'%(non_empty_trial_indices[trial],general_plot_parameters[0],spike_plot_parameters[-1]))
                   
          else:
             if trial_indicator:
                if pop_no_array[0] >1:
                   for pop in range(0,pop_no_array[0]):
                       label_array=[]
                       ytick_array=[]
                       for exp in range(0,len(general_plot_parameters[3])):
                           label_array.append("%d"%0)
                           label_array.append("%d"%(cell_no_array[target_pop_index_array[0][pop]]-1))
                           if exp==0:
                              ytick_array.append(exp)
                              ytick_array.append(cell_no_array[target_pop_index_array[0][pop]]-1)
                              left_value=cell_no_array[target_pop_index_array[0][pop]]-1
                           else:
                              ytick_array.append(left_value+2)
                              ytick_array.append(left_value+1+cell_no_array[target_pop_index_array[0][pop]]   )
                              left_value=left_value+2+cell_no_array[target_pop_index_array[0][pop]]
                       ax_stack_one_trial[pop].set_yticks(ytick_array)
                       fig_stack_one_trial.canvas.draw()
                       ax_stack_one_trial[pop].set_ylim(0,(cell_no_array[target_pop_index_array[0][pop]]+1)*len(general_plot_parameters[3]) )
                       ax_stack_one_trial[pop].set_ylabel('Cell ids, population %d'%target_pop_index_array[0][pop],size=4)
                       ax_stack_one_trial[pop].set_yticks([cell_no_array[target_pop_index_array[0][pop]]+( cell_no_array[target_pop_index_array[0][pop]]+2)*k for k in range(0,len(general_plot_parameters[3]))],minor=True)
                       ax_stack_one_trial[pop].yaxis.grid(False, which='major')
                       ax_stack_one_trial[pop].yaxis.grid(True, which='minor')
           
                       labels = [x.get_text() for x in ax_stack_one_trial[pop].get_yticklabels()]
           
                       for label in range(0,len(labels)):
                           labels[label] =label_array[label]

                       ax_stack_one_trial[pop].set_yticklabels(labels)
                       if pop==0:
                          ax_stack_one_trial[pop].set_title('Raster plot for Golgi cell populations (trial id=%d)'%spike_plot_parameters[1],size=6)
                       if pop==pop_no_array[0]-1:
                          ax_stack_one_trial[pop].set_xlabel('Time (ms)',fontsize=6)
                       for tick in ax_stack_one_trial[pop].xaxis.get_major_ticks():
                           tick.label.set_fontsize(general_plot_parameters[4]) 
                       for tick in ax_stack_one_trial[pop].yaxis.get_major_ticks():
                           tick.label.set_fontsize(general_plot_parameters[5])
                else:
                   label_array=[]
                   ytick_array=[]
                   for exp in range(0,len(general_plot_parameters[3])):
                       label_array.append("%d"%0)
                       label_array.append("%d"%(cell_no_array[target_pop_index_array[0][0]]-1))
                       if exp==0:
                          ytick_array.append(exp)
                          ytick_array.append(cell_no_array[target_pop_index_array[0][0]]-1)
                          left_value=cell_no_array[target_pop_index_array[0][0]]-1
                       else:
                          ytick_array.append(left_value+2)
                          ytick_array.append(left_value+1+cell_no_array[target_pop_index_array[0][0]]   )
                          left_value=left_value+2+cell_no_array[target_pop_index_array[0][0]]
                   ax_stack_one_trial.set_yticks(ytick_array)
                   fig_stack_one_trial.canvas.draw()
                   ax_stack_one_trial.set_ylim(0,(cell_no_array[target_pop_index_array[0][0]]+1)*len(general_plot_parameters[3]) )
                   ax_stack_one_trial.set_ylabel('Cell ids, population %d'%target_pop_index_array[0][0],size=4)
                   ax_stack_one_trial.set_yticks([cell_no_array[target_pop_index_array[0][0]]+( cell_no_array[target_pop_index_array[0][0]]+2)*k for k in range(0,len(general_plot_parameters[3]))],minor=True)
                   ax_stack_one_trial.yaxis.grid(False, which='major')
                   ax_stack_one_trial.yaxis.grid(True, which='minor')
           
                   labels = [x.get_text() for x in ax_stack_one_trial.get_yticklabels()]
           
                   for label in range(0,len(labels)):
                       labels[label] =label_array[label]

                   ax_stack_one_trial.set_yticklabels(labels)
                   ax_stack_one_trial.set_title('Raster plot for Golgi cell populations (trial id=%d)'%spike_plot_parameters[1],size=6)
                   ax_stack_one_trial.set_xlabel('Time (ms)',fontsize=6)
                   for tick in ax_stack_one_trial.xaxis.get_major_ticks():
                       tick.label.set_fontsize(general_plot_parameters[4]) 
                   for tick in ax_stack_one_trial.yaxis.get_major_ticks():
                       tick.label.set_fontsize(general_plot_parameters[5])
                fig_stack_one_trial.subplots_adjust(top=0.90)
                fig_stack_one_trial.subplots_adjust(bottom=0.3)
                l=fig_stack_one_trial.legend(lines,general_plot_parameters[3],title=general_plot_parameters[2],loc='center',ncol=len(general_plot_parameters[3]),bbox_to_anchor=(0.52, 0.1),prop={'size':4})
                plt.setp(l.get_title(),fontsize=4)

                fig_stack_one_trial.savefig('simulations/sim%d_rasters_%s.%s'%(spike_plot_parameters[1],general_plot_parameters[0],spike_plot_parameters[-1]))
                plt.clf() 
for trial in range(n_trials):
    sim_ref = utils.desynchronisation_random_graph(timestamp,
                                                   trial)
    sim_dir = '../simulations/' + sim_ref
    time = np.loadtxt(sim_dir + '/time.dat')
    spike_trains = []
    for cell in range(n_cells):
        spikes = np.loadtxt('{}/Golgi_network_reduced_{}.SPIKES_min20.spike'.format(sim_dir, cell))
        spike_trains.append(pyspike.add_auxiliary_spikes(spikes, sim_duration))
        if trial==0:
            ax[0].scatter(spikes,
                          np.zeros_like(spikes)+cell,
                          marker='|',
                          s=2,
                          c=color)
    distances.append(pyspike.spike_profile_multi(spike_trains[n_excluded_cells:]))

# average synchrony index across trials
average_distance = distances[0]
for distance in distances[1:]:
    average_distance.add(distance)
average_distance.mul_scalar(1./n_trials)


xmin = 50
xmax = 1900
x, y = average_distance.get_plottable_data()
ximin = np.searchsorted(x, xmin)
ximax = np.searchsorted(x, xmax)
lines.append(ax[1].plot(x[ximin:ximax+1], 1-y[ximin:ximax+1], lw=2, c=color)[0])
#labels.append('{:g}'.format(variance_scaling))
Example #8
0
        for cell in range(n_cells):
            spikes = np.loadtxt(
                '{}/Golgi_network_reduced_large_{}.SPIKES_min20.spike'.format(
                    sim_dir, cell))
            spike_trains.append(
                pyspike.add_auxiliary_spikes(spikes, sim_duration))
            if trial == 0 and cell in cells_for_raster:
                ax[0].scatter(spikes,
                              np.zeros_like(spikes) +
                              (raster_index + i * n_cells_in_raster),
                              marker='|',
                              s=2,
                              c=color)
                raster_index += 1
        distances.append(
            pyspike.spike_profile_multi(
                [spike_trains[c] for c in cells_for_distance]))

    # average synchrony index across trials
    average_distance = distances[0]
    for distance in distances[1:]:
        average_distance.add(distance)
    average_distance.mul_scalar(1. / n_trials)
    synchrony_indices.append(1 - average_distance.avrg())
    xmin = 50
    xmax = 1900
    x, y = average_distance.get_plottable_data()
    ximin = np.searchsorted(x, xmin)
    ximax = np.searchsorted(x, xmax)
    lines.append(ax[1].plot(x[ximin:ximax + 1],
                            1 - y[ximin:ximax + 1],
                            lw=2,
def Synchronization_analysis(sim_duration,specify_targets,no_of_groups,exp_specify,spike_plot_parameters,general_plot_parameters):
    
    cell_no_array=[]
    for exp_id in range(0,len(exp_specify[0]) ):
        if exp_specify[1][1]==True:
           for cell_group in range(0,no_of_groups):
               cell_group_positions=np.loadtxt('simulations/%s/Golgi_pop%d.txt'%(exp_specify[0][exp_id],cell_group))
               dim_array=np.shape(cell_group_positions)
               cell_no_array.append(dim_array[0])
           
        else:
           for cell_group in range(0,no_of_groups):
               cell_group_positions=np.loadtxt('simulations/%s/sim0/Golgi_pop%d.txt'%(exp_specify[0][exp_id],cell_group))
               dim_array=np.shape(cell_group_positions)
               cell_no_array.append(dim_array[0])



    n_trials=exp_specify[2]

   

    lines = []
    lines_sep=[]
    experiment_seed=random.sample(range(0,15000),1)[0]
    for exp_id in range(0,len(exp_specify[0])):
        #get target ids
        experiment_parameters=[]
        experiment_parameters.append(exp_specify[0][exp_id])
        experiment_parameters.append(exp_specify[1])
        experiment_parameters.append(exp_specify[2])
       
        target_cell_array=get_cell_ids_for_sync_analysis(specify_targets,no_of_groups,experiment_parameters,experiment_seed)
        test_array=target_cell_array
        
        if exp_id==0:
           
           if "save sync plot to a separate file" in spike_plot_parameters:
              fig_sync, ax_sync=plt.subplots(figsize=(2,1.5),ncols=1,nrows=1)
              
           if spike_plot_parameters[0]=="2D raster plots":
              trial_indicator_target=False
              if n_trials >1:
                 target_cell_array_target_trial=target_cell_array[spike_plot_parameters[1]]
                 no_of_rasters=0
                 if target_cell_array_target_trial != []:
                    test_non_empty_target_array=True
                    trial_indicator_target=True
                    no_of_rasters=len(target_cell_array_target_trial)
                    rows=1+no_of_rasters
                    columns=1
                    fig_stack, ax_stack = plt.subplots(figsize=(4,rows+1),ncols=columns,nrows=rows, sharex=True)
                    ax_stack=ax_stack.ravel()
                 
                    
              else:
                 no_of_rasters=0
                 if target_cell_array != []:
                    trial_indicator=True
                    no_of_rasters=len(target_cell_array)
                    rows=1+no_of_rasters
                    columns=1
                    fig_stack, ax_stack = plt.subplots(figsize=(4,rows),ncols=columns,nrows=rows, sharex=True)
                    ax_stack=ax_stack.ravel()
              
              if "save all trials to separate files" in spike_plot_parameters:
                 raster_fig_array=[]
                 raster_ax_array=[]
                 pop_no_array=[]
                 trial_indicator=False
                 if n_trials >1:
                    non_empty_trial_indices=[]
                    for trial in range(0,n_trials):
                        if target_cell_array[trial] !=[]:
                           non_empty_trial_indices.append(trial)
                    test_indices=non_empty_trial_indices
                    for trial in range(0,len(non_empty_trial_indices)):
                        target_trial=target_cell_array[non_empty_trial_indices[trial]]
                        columns=1
                        rows=len(target_trial)
                        pop_no_array.append(rows)
                        plot_rows=rows+1
                        fig, ax = plt.subplots(figsize=(4,plot_rows),ncols=columns,nrows=rows, sharex=True)
                        if len(target_trial) >1 :
                           ax=ax.ravel()
                        raster_fig_array.append(fig)
                        raster_ax_array.append(ax)
                 else:
                    no_of_rasters=0
                    if target_cell_array != []:
                       trial_indicator=True
                       no_of_rasters=len(target_cell_array)
                       rows=no_of_rasters
                       pop_no_array.append(rows)
                       columns=1
                       plot_rows=rows+1
                       fig_stack_one_trial, ax_stack_one_trial= plt.subplots(figsize=(4,plot_rows),ncols=columns,nrows=rows, sharex=True)
                       if no_of_rasters  >  1:
                          ax_stack_one_trial=ax_stack.ravel()
              if "save all trials to one separate file" in spike_plot_parameters:
                 pop_no_array=[]
                 if n_trials >1:
                    non_empty_trial_indices=[]
                    for trial in range(0,n_trials):
                        if target_cell_array[trial] !=[]:
                           non_empty_trial_indices.append(trial)
                    total_no_of_rows=0
                    for trial in range(0,len(non_empty_trial_indices)):
                        target_trial=target_cell_array[non_empty_trial_indices[trial]]
                        
                        rows=len(target_trial)
                        pop_no_array.append(rows)
                        total_no_of_rows=total_no_of_rows + rows
                    
                    fig_all_trials, ax_all_trials = plt.subplots(figsize=(4,total_no_of_rows),ncols=1,nrows=total_no_of_rows, sharex=True)
                    if total_no_of_rows >1 :
                        ax_all_trials=ax_all_trials.ravel()
                    
                        
                 

                 

                    
        non_empty_non_unitary_trial_counter=0
        distances = []
        
        color = sns.color_palette()[exp_id+1]
        
        row_counter=0
        target_pop_index_array=[]
        if spike_plot_parameters[0]=="2D raster plots":
           if "save all trials to one separate file" in spike_plot_parameters:
              row_array=range(0,total_no_of_rows)
        if spike_plot_parameters[0]=="2D raster plots":
           if "save all trials to separate files" in spike_plot_parameters:
              raster_ax_row_counter=0
            
        for trial in range(0,n_trials):
            sim_dir = 'simulations/' + exp_specify[0][exp_id]+'/sim%d'%trial+'/txt'
            ######   
            if n_trials > 1:
               target_cell_array_per_trial=target_cell_array[trial]
            else:
               target_cell_array_per_trial=target_cell_array
            
            if target_cell_array_per_trial !=[]:
               spike_trains = []
               target_pop_index_array_per_trial=[]
               print(" Trial %d is not empty"%(trial))
               for target_pop in range(0,len(target_cell_array_per_trial)):
                   for pop in range(0,no_of_groups):
                       if ('pop%d'%(pop)) in target_cell_array_per_trial[target_pop]:
                          target_pop_index_array_per_trial.append(pop)
                          target_cells = [x for x in target_cell_array_per_trial[target_pop] if isinstance(x,int)]
                          print target_cells
                          for cell in range(0,len(target_cells)):
                              #create target txt file containing spike times
                              if not os.path.isfile('%s/Golgi_pop%d_cell%d.txt'%(sim_dir,pop,target_cells[cell])):
                                 get_spike_times('Golgi_pop%d_cell%d'%(pop,target_cells[cell]),exp_specify[0][exp_id],trial)
                              spikes = np.loadtxt('%s/Golgi_pop%d_cell%d.txt'%(sim_dir,pop,target_cells[cell]))
                              spike_train=pyspike.SpikeTrain(spikes,[0,sim_duration])
                              spike_trains.append(spike_train)
                              print spike_trains
                              if spike_plot_parameters[0]=="2D raster plots":
                                 if spike_plot_parameters[1]==trial:
                                    ax_stack[target_pop].scatter(spikes,np.zeros_like(spikes)+target_cells[cell]+exp_id*(cell_no_array[pop]+1) ,marker='|',s=2,c=color)
                                 if "save all trials to separate files" in spike_plot_parameters:
                                    if n_trials >1:
                                       if len(target_cell_array_per_trial) > 1:
                                          raster_ax_array[raster_ax_row_counter][target_pop].scatter(spikes,np.zeros_like(spikes)+target_cells[cell]+exp_id*(cell_no_array[pop]+1) ,marker='|',s=2,c=color)
                                          
                                       else:
                                          raster_ax_array[raster_ax_row_counter].scatter(spikes,np.zeros_like(spikes)+target_cells[cell]+exp_id*(cell_no_array[pop]+1) ,marker='|',s=2,c=color)
                                          
                                    else:
                                       if len(target_cell_array_per_trial) >1:
                                          ax_stack_one_trial[target_pop].scatter(spikes,np.zeros_like(spikes)+target_cells[cell]+exp_id*(cell_no_array[pop]+1) ,marker='|',s=2,c=color)
                                       else:
                                          ax_stack_one_trial.scatter(spikes,np.zeros_like(spikes)+target_cells[cell]+exp_id*(cell_no_array[pop]+1) ,marker='|',s=2,c=color)
                                 if "save all trials to one separate file" in spike_plot_parameters:
                                    if n_trials >1:
                                       if total_no_of_rows >1 :
                                          ax_all_trials[row_array[row_counter]].scatter(spikes,np.zeros_like(spikes)+target_cells[cell]+exp_id*(cell_no_array[pop]+1) ,marker='|',s=2,c=color)
                                          
                                       else:
                                          ax_all_trials.scatter(spikes,np.zeros_like(spikes)+target_cells[cell]+exp_id*(cell_no_array[pop]+1) ,marker='|',s=2,c=color)
                          if spike_plot_parameters[0]=="2D raster plots":
                             if "save all trials to one separate file" in spike_plot_parameters:
                                row_counter=row_counter+1
               if spike_plot_parameters[0]=="2D raster plots":
                  if "save all trials to separate files" in spike_plot_parameters:

                     raster_ax_row_counter+=1
                  

               

               if spike_plot_parameters[1]==trial:
                  target_trial_index=target_pop_index_array.index(target_pop_index_array_per_trial) 
               

               


               target_pop_index_array.append(target_pop_index_array_per_trial)
               ########   
               print("Length of spike_trains is %d"%len(spike_trains))
               if len(spike_trains) >1:
                  print("Trial %d contains more than one cell; Synchrony metric will be computed for this trial"%(trial))
                  non_empty_non_unitary_trial_counter+=1
                  print non_empty_non_unitary_trial_counter
                  distances.append(pyspike.spike_profile_multi(spike_trains))
               else:
                  print("Trial %d contains one cell; Synchrony metric will not be computed for this trial"%(trial))
               ######## 
               
        # average synchrony index across "non empty" trials
        average_distance = distances[0]
        for distance in distances[1:]:
            average_distance.add(distance)
        average_distance.mul_scalar(1./non_empty_non_unitary_trial_counter)

        # below blocks for saving synchrony and spike raster plots
        
        mark_steps=sim_duration/50
        marks=[]
        for mark in range(0,mark_steps+1):
            Mark=50*mark
            marks.append(Mark)

        xmin = 50
        right_shaded_region=50
        if sim_duration >=1000:
            right_shaded_region=100
        xmax = sim_duration-right_shaded_region
        x, y = average_distance.get_plottable_data()
        ximin = np.searchsorted(x, xmin)
        ximax = np.searchsorted(x, xmax)
        if spike_plot_parameters[0]=="2D raster plots":
           if target_cell_array_target_trial != []:
              target_cell_array_target_trial_indicator=True
              lines.append(ax_stack[no_of_rasters].plot(x[ximin:ximax+1], 1-y[ximin:ximax+1], lw=2, c=color)[0])
              ax_stack[no_of_rasters].plot(x[:ximin+1], 1-y[:ximin+1], lw=2, c=color, alpha=0.4)
              ax_stack[no_of_rasters].plot(x[ximax:], 1-y[ximax:], lw=2, c=color, alpha=0.4)
        if "save sync plot to a separate file" in spike_plot_parameters:
           lines_sep.append(ax_sync.plot(x[ximin:ximax+1], 1-y[ximin:ximax+1], lw=2, c=color)[0])
           ax_sync.plot(x[:ximin+1], 1-y[:ximin+1], lw=2, c=color, alpha=0.4)
           ax_sync.plot(x[ximax:], 1-y[ximax:], lw=2, c=color, alpha=0.4)
        
             
              
    
    if "save sync plot to a separate file" in spike_plot_parameters:
       print("save sync plot to a separate file is specified")
       for tick in ax_sync.xaxis.get_major_ticks():
           tick.label.set_fontsize(general_plot_parameters[4]) 
       for tick in ax_sync.yaxis.get_major_ticks():
           tick.label.set_fontsize(general_plot_parameters[5])
       ax_sync.locator_params(axis='y', tight=True, nbins=10)
       ax_sync.set_xlabel('Time (ms)',fontsize=4)
       ax_sync.set_ylabel('Synchrony index',size=4)
       ax_sync.set_ylim(0,1)
       ax_sync.set_xticks(marks)
       ax_sync.set_title('Synchronization between %s'%general_plot_parameters[1],size=4)
       fig_sync.tight_layout()

       fig_sync.subplots_adjust(top=0.90)
       fig_sync.subplots_adjust(bottom=0.55)
       l=fig_sync.legend(lines_sep,general_plot_parameters[3],title=general_plot_parameters[2],loc='center',ncol=len(general_plot_parameters[3]),bbox_to_anchor=(0.52, 0.25),prop={'size':4})
       plt.setp(l.get_title(),fontsize=4)
          
       fig_sync.savefig('simulations/sync_only_%s.%s'%(general_plot_parameters[0],spike_plot_parameters[-1]))
       print("saved %s in simulations"%'sync_only_%s.%s'%(general_plot_parameters[0],spike_plot_parameters[-1]))
       
    if spike_plot_parameters[0]=="2D raster plots":    
       print("Intend to plot a main figure with representative 2D raster plots")
       #create label array
       if trial_indicator_target:
          print("2D raster plot procedures started")
          for pop in range(0,no_of_rasters):
              label_array=[]
              ytick_array=[]
              for exp in range(0,len(general_plot_parameters[3])):
                  label_array.append("%d"%0)
                  label_array.append("%d"%(cell_no_array[target_pop_index_array[target_trial_index][pop]]-1))

                  if exp==0:
                     ytick_array.append(exp)
                     ytick_array.append(cell_no_array[target_pop_index_array[target_trial_index][pop]]-1)
                     left_value=cell_no_array[target_pop_index_array[target_trial_index][pop]]-1
                  else:
                     ytick_array.append(left_value+2)
                     ytick_array.append(left_value+1+cell_no_array[target_pop_index_array[target_trial_index][pop]])
                     left_value=left_value+2+cell_no_array[target_pop_index_array[target_trial_index][pop]]

              print label_array
              print ytick_array
            
              ax_stack[pop].set_yticks(ytick_array)
              fig_stack.canvas.draw()
              ax_stack[pop].set_ylim(0,(cell_no_array[target_pop_index_array[target_trial_index][pop]]+1)*len(general_plot_parameters[3]) )
              ax_stack[pop].set_ylabel('Cell ids, population %d'%pop,size=4)
              ax_stack[pop].set_yticks([cell_no_array[target_pop_index_array[target_trial_index][pop]]+(cell_no_array[target_pop_index_array[target_trial_index][pop]]+2)*k for k in range(0,len(general_plot_parameters[3]))],minor=True)
              ax_stack[pop].yaxis.grid(False, which='major')
              ax_stack[pop].yaxis.grid(True, which='minor')
           
              labels = [x.get_text() for x in ax_stack[pop].get_yticklabels()]
           
              for label in range(0,len(labels)):
                   labels[label] =label_array[label]

              ax_stack[pop].set_yticklabels(labels)
              if pop==0:
                 ax_stack[pop].set_title('Raster plots for target Golgi cell populations (trial id=%d)'%spike_plot_parameters[1],size=6)
              for pop in range(0,no_of_rasters+1):
                  for tick in ax_stack[pop].xaxis.get_major_ticks():
                      tick.label.set_fontsize(general_plot_parameters[4]) 
                  for tick in ax_stack[pop].yaxis.get_major_ticks():
                      tick.label.set_fontsize(general_plot_parameters[5])
              ax_stack[no_of_rasters].locator_params(axis='y', tight=True, nbins=10)
              ax_stack[no_of_rasters].set_xlabel('Time (ms)',fontsize=6)
              ax_stack[no_of_rasters].set_ylabel('Synchrony index',size=4)
              ax_stack[no_of_rasters].set_ylim(0,1)
              ax_stack[no_of_rasters].set_xticks(marks)
              ax_stack[no_of_rasters].set_title('Synchronization between %s'%general_plot_parameters[1],size=6)
              fig_stack.tight_layout()
       
              fig_stack.subplots_adjust(top=0.80)
              fig_stack.subplots_adjust(bottom=0.15)
              fig_stack.subplots_adjust(hspace=.4)
              l=fig_stack.legend(lines,general_plot_parameters[3],title=general_plot_parameters[2], loc='upper center',ncol=len(general_plot_parameters[3]),bbox_to_anchor=(0.55, 1.0))
              plt.setp(l.get_title(),fontsize=6)
              plt.setp(l.get_texts(), fontsize=6)
              fig_stack.savefig('simulations/%s.%s'%(general_plot_parameters[0],spike_plot_parameters[-1]))
       else:
          print("Intended to plot raster plots for trial %d, but specified region-specific selection of cells produces an empty target array.\nThus a main figure with a representative raster will not be produced.\nHowever, synchrony plot can be saved in a separate file.\nAlternatively, plot a non-empty trial"%(spike_plot_parameters[1]))
       if "save all trials to one separate file" in spike_plot_parameters:
          print target_pop_index_array
          if total_no_of_rows >1:
             row_counter=0
             for trial in range(0,len(non_empty_trial_indices)):
                 if len(target_pop_index_array[trial]) >1:
                    for pop in range(0,len(target_pop_index_array[trial])):
                        label_array=[]
                        ytick_array=[]
                        for exp in range(0,len(general_plot_parameters[3])):
                            label_array.append("%d"%0)
                            label_array.append("%d"%(cell_no_array[target_pop_index_array[trial][pop] ]-1))
                            if exp==0:
                               ytick_array.append(exp)
                               ytick_array.append(cell_no_array[target_pop_index_array[trial][pop]]-1)
                               left_value=cell_no_array[target_pop_index_array[trial][pop]]-1
                            else:
                               ytick_array.append(left_value+2)
                               ytick_array.append(left_value+1+cell_no_array[target_pop_index_array[trial][pop]]   )
                               left_value=left_value+2+cell_no_array[target_pop_index_array[trial][pop]]
                        ax_all_trials[row_counter].set_yticks(ytick_array)
                        #ax_all_trials[row_counter].canvas.draw()
                        ax_all_trials[row_counter].set_ylim(0,(cell_no_array[target_pop_index_array[trial][pop]]+1)*len(general_plot_parameters[3]) )
                        ax_all_trials[row_counter].set_ylabel('Cell ids for pop %d\ntrial %d'%(target_pop_index_array[trial][pop],non_empty_trial_indices[trial]),size=4)
                        ax_all_trials[row_counter].set_yticks([cell_no_array[target_pop_index_array[trial][pop]]+( cell_no_array[target_pop_index_array[trial][pop]]+2)*k for k in range(0,len(general_plot_parameters[3]))],minor=True)
                        ax_all_trials[row_counter].yaxis.grid(False, which='major')
                        ax_all_trials[row_counter].yaxis.grid(True, which='minor')
                        if row_counter==total_no_of_rows-1:
                           ax_all_trials[row_counter].set_xlabel('Time (ms)',fontsize=4)
           
                        labels = [x.get_text() for x in  ax_all_trials[row_counter].get_yticklabels()]
           
                        for label in range(0,len(labels)):
                             labels[label] =label_array[label]

                        ax_all_trials[row_counter].set_yticklabels(labels)
                         
                        for tick in ax_all_trials[row_counter].xaxis.get_major_ticks():
                            tick.label.set_fontsize(general_plot_parameters[4]) 
                        for tick in ax_all_trials[row_counter].yaxis.get_major_ticks():
                            tick.label.set_fontsize(general_plot_parameters[5])
                        row_counter+=1
                 else:
                    label_array=[]
                    ytick_array=[]
                    for exp in range(0,len(general_plot_parameters[3])):
                        label_array.append("%d"%0)
                        label_array.append("%d"%(cell_no_array[target_pop_index_array[trial][0]]-1))
                        if exp==0:
                           ytick_array.append(exp)
                           ytick_array.append(cell_no_array[target_pop_index_array[trial][0]]-1)
                           left_value=cell_no_array[target_pop_index_array[trial][0]]-1
                        else:
                           ytick_array.append(left_value+2)
                           ytick_array.append(left_value+1+cell_no_array[target_pop_index_array[trial][0]]   )
                           left_value=left_value+2+cell_no_array[target_pop_index_array[trial][0]]
                    ax_all_trials[row_counter].set_yticks(ytick_array)
                    ax_all_trials[row_counter].set_ylim(0,(cell_no_array[target_pop_index_array[trial][0]]+1)*len(general_plot_parameters[3]) )
                    ax_all_trials[row_counter].set_ylabel('Cell ids for pop %d\ntrial %d'%(target_pop_index_array[trial][0],non_empty_trial_indices[trial]),size=4)
                    ax_all_trials[row_counter].set_yticks([cell_no_array[target_pop_index_array[trial][0]]+( cell_no_array[target_pop_index_array[trial][0]]+2)*k for k in range(0,len(general_plot_parameters[3]))],minor=True)
                    ax_all_trials[row_counter].yaxis.grid(False, which='major')
                    ax_all_trials[row_counter].yaxis.grid(True, which='minor')
                    if row_counter==total_no_of_rows-1:
                       ax_all_trials[row_counter].set_xlabel('Time (ms)',fontsize=4)
           
                    labels = [x.get_text() for x in  ax_all_trials[row_counter].get_yticklabels()]
           
                    for label in range(0,len(labels)):
                        labels[label] =label_array[label]

                    ax_all_trials[row_counter].set_yticklabels(labels)
                         
                    for tick in ax_all_trials[row_counter].xaxis.get_major_ticks():
                        tick.label.set_fontsize(general_plot_parameters[4]) 
                    for tick in ax_all_trials[row_counter].yaxis.get_major_ticks():
                        tick.label.set_fontsize(general_plot_parameters[5])
                    row_counter+=1

          else:
             label_array=[]
             ytick_array=[]
             for exp in range(0,len(general_plot_parameters[3])):
                 label_array.append("%d"%0)
                 label_array.append("%d"%(cell_no_array[target_pop_index_array[0][0]]-1))
                 if exp==0:
                    ytick_array.append(exp)
                    ytick_array.append(cell_no_array[target_pop_index_array[0][pop]]-1)
                    left_value=cell_no_array[target_pop_index_array[0][0]]-1
                 else:
                    ytick_array.append(left_value+2)
                    ytick_array.append(left_value+1+cell_no_array[target_pop_index_array[0][0]]   )
                    left_value=left_value+2+cell_no_array[target_pop_index_array[0][0]]
             ax_all_trials.set_yticks(ytick_array)
             ax_all_trials.canvas.draw()
             ax_all_trials.set_ylim(0,(cell_no_array[target_pop_index_array[0][0]]+1)*len(general_plot_parameters[3]) )
             ax_all_trials.set_ylabel('Cell ids for pop %d\ntrial %d'%(target_pop_index_array[trial][pop],non_empty_trial_indices[trial]),size=4)
             ax_all_trials.set_yticks([cell_no_array[target_pop_index_array[0][0]]+( cell_no_array[target_pop_index_array[0][0]]+2)*k for k in range(0,len(general_plot_parameters[3]))],minor=True)
             ax_all_trials.yaxis.grid(False, which='major')
             ax_all_trials.yaxis.grid(True, which='minor')
             ax_all_trials.set_xlabel('Time (ms)',fontsize=4)
           
             labels = [x.get_text() for x in  ax_all_trials.get_yticklabels()]
           
             for label in range(0,len(labels)):
                 labels[label] =label_array[label]

             ax_all_trials.set_yticklabels(labels)
                         
             for tick in ax_all_trials.xaxis.get_major_ticks():
                 tick.label.set_fontsize(general_plot_parameters[4]) 
             for tick in ax_all_trials.yaxis.get_major_ticks():
                 tick.label.set_fontsize(general_plot_parameters[5])
          
          fig_all_trials.subplots_adjust(hspace=0.1)
          fig_all_trials.subplots_adjust(top=0.95)
          fig_all_trials.subplots_adjust(bottom=0.1)
          l=fig_all_trials.legend(lines,general_plot_parameters[3],title=general_plot_parameters[2],loc='center',ncol=len(general_plot_parameters[3]),bbox_to_anchor=(0.52, 0.98),prop={'size':4})
          plt.setp(l.get_title(),fontsize=4)

          fig_all_trials.savefig('simulations/all_trials_%s.%s'%(general_plot_parameters[0],spike_plot_parameters[-1]))
          plt.clf() 
             
       if "save all trials to separate files" in spike_plot_parameters:
          if n_trials >1:
             for trial in range(0,len(non_empty_trial_indices)):
                 print("started ploting non-empty trials")
                 if pop_no_array[trial] >1:
                    for pop in range(0,pop_no_array[trial]):
                        label_array=[]
                        ytick_array=[]
                        for exp in range(0,len(general_plot_parameters[3])):
                            label_array.append("%d"%0)
                            label_array.append("%d"%(cell_no_array[target_pop_index_array[trial][pop]]-1))
                            if exp==0:
                               ytick_array.append(exp)
                               ytick_array.append(cell_no_array[target_pop_index_array[trial][pop]]-1)
                               left_value=cell_no_array[target_pop_index_array[trial][pop]]-1
                            else:
                               ytick_array.append(left_value+2)
                               ytick_array.append(left_value+1+cell_no_array[target_pop_index_array[trial][pop]]   )
                               left_value=left_value+2+cell_no_array[target_pop_index_array[trial][pop]]
                        raster_ax_array[trial][pop].set_yticks(ytick_array)
                        raster_fig_array[trial].canvas.draw()
                        raster_ax_array[trial][pop].set_ylim(0,(cell_no_array[target_pop_index_array[trial][pop]]+1)*len(general_plot_parameters[3]) )
                        raster_ax_array[trial][pop].set_ylabel('Cell ids, population %d'%target_pop_index_array[trial][pop],size=4)
                        raster_ax_array[trial][pop].set_yticks([cell_no_array[target_pop_index_array[trial][pop]]+( cell_no_array[target_pop_index_array[trial][pop]]+2)*k for k in range(0,len(general_plot_parameters[3]))],minor=True)
                        raster_ax_array[trial][pop].yaxis.grid(False, which='major')
                        raster_ax_array[trial][pop].yaxis.grid(True, which='minor')
           
                        labels = [x.get_text() for x in raster_ax_array[trial][pop].get_yticklabels()]
           
                        for label in range(0,len(labels)):
                            labels[label] =label_array[label]

                        raster_ax_array[trial][pop].set_yticklabels(labels)
                        if pop==0:
                           raster_ax_array[trial][pop].set_title('Raster plot for Golgi cell populations (trial id=%d)'%non_empty_trial_indices[trial],size=6)
                        if pop==pop_no_array[trial]-1:
                           raster_ax_array[trial][pop].set_xlabel('Time (ms)',fontsize=6)
                        for tick in raster_ax_array[trial][pop].xaxis.get_major_ticks():
                            tick.label.set_fontsize(general_plot_parameters[4]) 
                        for tick in raster_ax_array[trial][pop].yaxis.get_major_ticks():
                            tick.label.set_fontsize(general_plot_parameters[5])
                 else:
                    label_array=[]
                    ytick_array=[]
                    for exp in range(0,len(general_plot_parameters[3])):
                        label_array.append("%d"%0)
                        label_array.append("%d"%(cell_no_array[target_pop_index_array[trial][0]]-1))
                        if exp==0:
                           ytick_array.append(exp)
                           ytick_array.append(cell_no_array[target_pop_index_array[trial][0]]-1)
                           left_value=cell_no_array[target_pop_index_array[trial][0]]-1
                        else:
                           ytick_array.append(left_value+2)
                           ytick_array.append(left_value+1+cell_no_array[target_pop_index_array[trial][0]]   )
                           left_value=left_value+2+cell_no_array[target_pop_index_array[trial][0]]
                        raster_ax_array[trial].set_yticks(ytick_array)
                        raster_fig_array[trial].canvas.draw()
                        raster_ax_array[trial].set_ylim(0,(cell_no_array[target_pop_index_array[trial][0]]+1)*len(general_plot_parameters[3]) )
                        raster_ax_array[trial].set_ylabel('Cell ids, population %d'% target_pop_index_array[trial][0],size=4)
                        raster_ax_array[trial].set_yticks([cell_no_array[target_pop_index_array[trial][0]]+( cell_no_array[target_pop_index_array[trial][0]]+2)*k for k in range(0,len(general_plot_parameters[3]))],minor=True)
                        raster_ax_array[trial].yaxis.grid(False, which='major')
                        raster_ax_array[trial].yaxis.grid(True, which='minor')
           
                        labels = [x.get_text() for x in raster_ax_array[trial].get_yticklabels()]
           
                        for label in range(0,len(labels)):
                            labels[label] =label_array[label]

                        raster_ax_array[trial].set_yticklabels(labels)
                        raster_ax_array[trial].set_title('Raster plot for Golgi cell populations (trial id=%d)'%non_empty_trial_indices[trial],size=6)
                        raster_ax_array[trial].set_xlabel('Time (ms)',fontsize=6)
                        for tick in raster_ax_array[trial].xaxis.get_major_ticks():
                            tick.label.set_fontsize(general_plot_parameters[4]) 
                        for tick in raster_ax_array[trial].yaxis.get_major_ticks():
                            tick.label.set_fontsize(general_plot_parameters[5])
                            
                 raster_fig_array[trial].subplots_adjust(top=0.90)
                 raster_fig_array[trial].subplots_adjust(bottom=0.3)
                 l=raster_fig_array[trial].legend(lines,general_plot_parameters[3],title=general_plot_parameters[2],loc='center',ncol=len(general_plot_parameters[3]),bbox_to_anchor=(0.52, 0.1),prop={'size':4})
                 plt.setp(l.get_title(),fontsize=4)

                 raster_fig_array[trial].savefig('simulations/sim%d_rasters_%s.%s'%(non_empty_trial_indices[trial],general_plot_parameters[0],spike_plot_parameters[-1]))
                   
          else:
             if trial_indicator:
                if pop_no_array[0] >1:
                   for pop in range(0,pop_no_array[0]):
                       label_array=[]
                       ytick_array=[]
                       for exp in range(0,len(general_plot_parameters[3])):
                           label_array.append("%d"%0)
                           label_array.append("%d"%(cell_no_array[target_pop_index_array[0][pop]]-1))
                           if exp==0:
                              ytick_array.append(exp)
                              ytick_array.append(cell_no_array[target_pop_index_array[0][pop]]-1)
                              left_value=cell_no_array[target_pop_index_array[0][pop]]-1
                           else:
                              ytick_array.append(left_value+2)
                              ytick_array.append(left_value+1+cell_no_array[target_pop_index_array[0][pop]]   )
                              left_value=left_value+2+cell_no_array[target_pop_index_array[0][pop]]
                       ax_stack_one_trial[pop].set_yticks(ytick_array)
                       fig_stack_one_trial.canvas.draw()
                       ax_stack_one_trial[pop].set_ylim(0,(cell_no_array[target_pop_index_array[0][pop]]+1)*len(general_plot_parameters[3]) )
                       ax_stack_one_trial[pop].set_ylabel('Cell ids, population %d'%target_pop_index_array[0][pop],size=4)
                       ax_stack_one_trial[pop].set_yticks([cell_no_array[target_pop_index_array[0][pop]]+( cell_no_array[target_pop_index_array[0][pop]]+2)*k for k in range(0,len(general_plot_parameters[3]))],minor=True)
                       ax_stack_one_trial[pop].yaxis.grid(False, which='major')
                       ax_stack_one_trial[pop].yaxis.grid(True, which='minor')
           
                       labels = [x.get_text() for x in ax_stack_one_trial[pop].get_yticklabels()]
           
                       for label in range(0,len(labels)):
                           labels[label] =label_array[label]

                       ax_stack_one_trial[pop].set_yticklabels(labels)
                       if pop==0:
                          ax_stack_one_trial[pop].set_title('Raster plot for Golgi cell populations (trial id=%d)'%spike_plot_parameters[1],size=6)
                       if pop==pop_no_array[0]-1:
                          ax_stack_one_trial[pop].set_xlabel('Time (ms)',fontsize=6)
                       for tick in ax_stack_one_trial[pop].xaxis.get_major_ticks():
                           tick.label.set_fontsize(general_plot_parameters[4]) 
                       for tick in ax_stack_one_trial[pop].yaxis.get_major_ticks():
                           tick.label.set_fontsize(general_plot_parameters[5])
                else:
                   label_array=[]
                   ytick_array=[]
                   for exp in range(0,len(general_plot_parameters[3])):
                       label_array.append("%d"%0)
                       label_array.append("%d"%(cell_no_array[target_pop_index_array[0][0]]-1))
                       if exp==0:
                          ytick_array.append(exp)
                          ytick_array.append(cell_no_array[target_pop_index_array[0][0]]-1)
                          left_value=cell_no_array[target_pop_index_array[0][0]]-1
                       else:
                          ytick_array.append(left_value+2)
                          ytick_array.append(left_value+1+cell_no_array[target_pop_index_array[0][0]]   )
                          left_value=left_value+2+cell_no_array[target_pop_index_array[0][0]]
                   ax_stack_one_trial.set_yticks(ytick_array)
                   fig_stack_one_trial.canvas.draw()
                   ax_stack_one_trial.set_ylim(0,(cell_no_array[target_pop_index_array[0][0]]+1)*len(general_plot_parameters[3]) )
                   ax_stack_one_trial.set_ylabel('Cell ids, population %d'%target_pop_index_array[0][0],size=4)
                   ax_stack_one_trial.set_yticks([cell_no_array[target_pop_index_array[0][0]]+( cell_no_array[target_pop_index_array[0][0]]+2)*k for k in range(0,len(general_plot_parameters[3]))],minor=True)
                   ax_stack_one_trial.yaxis.grid(False, which='major')
                   ax_stack_one_trial.yaxis.grid(True, which='minor')
           
                   labels = [x.get_text() for x in ax_stack_one_trial.get_yticklabels()]
           
                   for label in range(0,len(labels)):
                       labels[label] =label_array[label]

                   ax_stack_one_trial.set_yticklabels(labels)
                   ax_stack_one_trial.set_title('Raster plot for Golgi cell populations (trial id=%d)'%spike_plot_parameters[1],size=6)
                   ax_stack_one_trial.set_xlabel('Time (ms)',fontsize=6)
                   for tick in ax_stack_one_trial.xaxis.get_major_ticks():
                       tick.label.set_fontsize(general_plot_parameters[4]) 
                   for tick in ax_stack_one_trial.yaxis.get_major_ticks():
                       tick.label.set_fontsize(general_plot_parameters[5])
                fig_stack_one_trial.subplots_adjust(top=0.90)
                fig_stack_one_trial.subplots_adjust(bottom=0.3)
                l=fig_stack_one_trial.legend(lines,general_plot_parameters[3],title=general_plot_parameters[2],loc='center',ncol=len(general_plot_parameters[3]),bbox_to_anchor=(0.52, 0.1),prop={'size':4})
                plt.setp(l.get_title(),fontsize=4)

                fig_stack_one_trial.savefig('simulations/sim%d_rasters_%s.%s'%(spike_plot_parameters[1],general_plot_parameters[0],spike_plot_parameters[-1]))
                plt.clf() 
        sim_dir = '../simulations/' + sim_ref
        time = np.loadtxt(sim_dir + '/time.dat')
        spike_trains = []

        raster_index = 0 
        for cell in range(n_cells):
            spikes = np.loadtxt('{}/Golgi_network_reduced_large_{}.SPIKES_min20.spike'.format(sim_dir, cell))
            spike_trains.append(pyspike.add_auxiliary_spikes(spikes, sim_duration))
            if trial==0 and cell in cells_for_raster:
                ax[0].scatter(spikes,
                              np.zeros_like(spikes)+(raster_index+i*n_cells_in_raster),
                              marker='|',
                              s=2,
                              c=color)
                raster_index += 1
        distances.append(pyspike.spike_profile_multi([spike_trains[c] for c in cells_for_distance]))
    
    # average synchrony index across trials
    average_distance = distances[0]
    for distance in distances[1:]:
        average_distance.add(distance)
    average_distance.mul_scalar(1./n_trials)
    synchrony_indices.append(1-average_distance.avrg())
    xmin = 50
    xmax = 1900
    x, y = average_distance.get_plottable_data()
    ximin = np.searchsorted(x, xmin)
    ximax = np.searchsorted(x, xmax)
    lines.append(ax[1].plot(x[ximin:ximax+1], 1-y[ximin:ximax+1], lw=2, c=color)[0])
    labels.append('{:g}'.format(rewiring_p))
    ax[1].plot(x[:ximin+1], 1-y[:ximin+1], lw=2, c=color, alpha=0.4)
def Synchronization_analysis(sim_duration,specify_targets,no_of_groups,exp_specify,spike_plot_parameters,general_plot_parameters):


    cell_no_array=[]
    for exp_id in range(0,len(exp_specify[0]) ):
        if exp_specify[1][1]==True:
           for cell_group in range(0,no_of_groups):
               cell_group_positions=np.loadtxt('simulations/%s/Golgi_pop%d.txt'%(exp_specify[0][exp_id],cell_group))
               dim_array=np.shape(cell_group_positions)
               cell_no_array.append(dim_array[0])
           
        else:
           for cell_group in range(0,no_of_groups):
               cell_group_positions=np.loadtxt('simulations/%s/sim0/Golgi_pop%d.txt'%(exp_specify[0][exp_id],cell_group))
               dim_array=np.shape(cell_group_positions)
               cell_no_array.append(dim_array[0])



    n_trials=exp_specify[2]

    if spike_plot_parameters[0]=="2D raster plots":

       columns=1
       rows=1+no_of_groups

       fig_stack, ax_stack = plt.subplots(figsize=(4,rows),ncols=columns,nrows=rows, sharex=True)
       ax_stack=ax_stack.ravel()
       
       if spike_plot_parameters[2]=="save all simulations to separate files":

          raster_fig_array=[]
          raster_ax_array=[]

          fig_sync, ax_sync=plt.subplots(figsize=(2,1),ncols=1,nrows=1)

          for trial in range(0,n_trials):
              columns=1
              rows=no_of_groups
              fig, ax = plt.subplots(figsize=(4,rows),ncols=columns,nrows=rows, sharex=True)
              if no_of_groups >1:
                 ax=ax.ravel()
              raster_fig_array.append(fig)
              raster_ax_array.append(ax)
    
    if spike_plot_parameters[0]=="3D scatter plot":

       nrows_3D = 1+no_of_groups
       ncols_3D = 1
       
       fig_with_3D_rasters= plt.figure(figsize=(4*ncols_3D,4*nrows_3D))
       ax_3D=[]
       for pop in range(0,no_of_groups):
               ax_3D.append(fig_with_3D_rasters.add_subplot(nrows_3D,ncols_3D,pop+1,projection='3d'))

       ax_3D.append(fig_with_3D_rasters.add_subplot(nrows_3D,ncols_3D,no_of_groups+1))

       if spike_plot_parameters[2]=="save 3D scatter plots separately":

          fig_sync, ax_sync=plt.subplots(figsize=(2,1),ncols=1,nrows=1)

          rows_3D_minus_sync = max(1,math.ceil(no_of_groups/3))
          cols_3D_minus_sync = min(3,no_of_groups)
          
          rasters3D_only=plt.figure(figsize=(4*cols_3D_minus_sync,4*rows_3D_minus_sync))
          ax_3D_rasters_only=[]
          for pop in range(0,no_of_groups):
               ax_3D_rasters_only.append(rasters3D_only.add_subplot(nrows_3D,ncols_3D,pop+1,projection='3d'))

       

    lines = []
    lines_sep=[]
    
    for exp_id in range(0,len(exp_specify[0])):
        #get target ids
        experiment_parameters=[]
        experiment_parameters.append(exp_specify[0][exp_id])
        experiment_parameters.append(exp_specify[1])
        experiment_parameters.append(exp_specify[2])
       
        target_cell_array=methods.get_cell_ids_for_sync_analysis(specify_targets,no_of_groups,experiment_parameters)

        

        #plot_params=["2D raster plot",[0],"save all simulations to separate files","pdf",#"jpeg"or"png",....]         

        #plot_params=["3D raster plot",[0], # the same options !!!!!

        #plot_params=["3D scatter plot", # one plot for each population include all sims; then the same options !!!!!
       
        distances = []
        
        color = sns.color_palette()[exp_id]
        
        
        if spike_plot_parameters[0]=="3D scatter plot":
           spikes_3D=[]
           spike_times_3D=[]
           sim_axis_array=[]
           population_wise_3D_spikes=[]
           population_wise_3D_spike_times=[]
           population_wise_sim_axis_array=[]
        
        
        for trial in range(0,n_trials):
            sim_dir = 'simulations/' + exp_specify[0][exp_id]+'/sim%d'%trial+'/txt'
            spike_trains = []
            if spike_plot_parameters[0]=="3D scatter plot":
               spikes_array_per_trial_3D=[]   
               spike_times_array_per_trial_3D=[]
               sim_axis_array_per_trial=[]
            ######   
            if (specify_targets[0]=="3D region specific") and (not("subtype specific" in specify_targets )):
               if exp_specify[1][1]==True:
                  for pop in range(0,len(target_cell_array)):
                      if spike_plot_parameters[0]=="3D scatter plot":
                         spikes_per_pop_3D=[]   
                         spike_times_per_pop_3D=[]
                         sim_axis_per_pop=[]
                      for cell in range(0,len(target_cell_array[pop])):
                          #create target txt file containing spike times
                          if not os.path.isfile('%s/Golgi_pop%d_cell%d.txt'%(sim_dir,pop,target_cell_array[pop][cell])):
                             methods.get_spike_times('Golgi_pop%d_cell%d'%(pop,target_cell_array[pop][cell]),exp_specify[0][exp_id],trial)
                          spikes = np.loadtxt('%s/Golgi_pop%d_cell%d.txt'%(sim_dir,pop,target_cell_array[pop][cell]))
                          spike_train=pyspike.SpikeTrain(spikes,[0,sim_duration])
                          spike_trains.append(spike_train)
                          if spike_plot_parameters[0]=="2D raster plots":
                             if trial in spike_plot_parameters[1]:
                                ax_stack[pop].scatter(spikes,np.zeros_like(spikes)+(target_cell_array[pop][cell]+exp_id*(cell_no_array[pop]+1)),marker='|',s=2,c=color)
                             if spike_plot_parameters[2]=="save all simulations to separate files":
                                raster_ax_array[trial][pop].scatter(spikes,np.zeros_like(spikes)+(target_cell_array[pop][cell]+exp_id*(cell_no_array[pop]+1)),marker='|',s=2,c=color)
                             
                          if spike_plot_parameters[0]=="3D scatter plot":
                             if cell==0:
                                spikes_per_pop_3D=np.zeros_like(spikes)+(target_cell_array[pop][cell]+ exp_id*cell_no_array[pop])
                                spike_times_per_pop_3D=spikes
                                sim_axis_per_pop=np.zeros_like(spikes)+trial+1  # for display start numbering trials from the index of 1
                             else:
                                spikes_per_pop_3D=spikes_per_pop_3D+np.zeros_like(spikes)+(target_cell_array[pop][cell]+exp_id*cell_no_array[pop])
                                spike_times_per_pop_3D=spike_times_per_pop_3D +spikes
                                sim_axis_per_pop=sim_axis_per_pop+np.zeros_like(spikes)+trial+1
                      if spike_plot_parameters[0]=="3D scatter plot":
                         spikes_array_per_trial_3D.append(spikes_per_pop_3D)
                         spike_times_array_per_trial_3D.append(spike_times_per_pop_3D)
                         sim_axis_array_per_trial.append(sim_axis_per_pop)
                         
               else:
                  for pop in range(0,len(target_cell_array[trial])):
                      if spike_plot_parameters[0]=="3D scatter plot":
                         spikes_per_pop_3D=[]   
                         spike_times_per_pop_3D=[]
                         sim_axis_per_pop=[]
                      if  len(target_cell_array[trial][pop]) > 0:
                          for cell in range(0,len(target_cell_array[trial][pop])):
                              if not os.path.isfile('%s/Golgi_pop%d_cell%d.txt'%(sim_dir,pop,target_cell_array[trial][pop][cell])):
                                 methods.get_spike_times('Golgi_pop%d_cell%d'%(pop,target_cell_array[trial][pop][cell]),exp_specify[0][exp_id],trial)
                              spikes = np.loadtxt('%s/Golgi_pop%d_cell%d.txt'%(sim_dir,pop,target_cell_array[trial][pop][cell]))
                              spike_train=pyspike.SpikeTrain(spikes,[0,sim_duration])
                              spike_trains.append(spike_train)
                              if spike_plot_parameters[0]=="2D raster plots":
                                 if trial in spike_plot_parameters[1]:
                                    ax_stack[pop].scatter(spikes,np.zeros_like(spikes)+(target_cell_array[pop][cell]+exp_id*(cell_no_array[pop]+1)),marker='|',s=2,c=color)
                                 if spike_plot_parameters[2]=="save all simulations to separate files":
                                    raster_ax_array[trial][pop].scatter(spikes,np.zeros_like(spikes)+(target_cell_array[pop][cell]+exp_id*(cell_no_array[pop]+1)),marker='|',s=2,c=color)
                              if spike_plot_parameters[0]=="3D scatter plot":
                                 if cell==0:
                                    spikes_per_pop_3D=np.zeros_like(spikes)+(target_cell_array[trial][pop][cell]+ exp_id*cell_no_array[pop])
                                    spike_times_per_pop_3D=spikes
                                    sim_axis_per_pop=np.zeros_like(spikes)+trial+1  # for display start numbering trials from the index of 1
                                 else:
                                    spikes_per_pop_3D=spikes_per_pop_3D+np.zeros_like(spikes)+(target_cell_array[trial][pop][cell]+exp_id*cell_no_array[pop])
                                    spike_times_per_pop_3D=spike_times_per_pop_3D +spikes
                                    sim_axis_per_pop=sim_axis_per_pop+np.zeros_like(spikes)+trial+1
                          if spike_plot_parameters[0]=="3D scatter plot":
                             spikes_array_per_trial_3D.append(spikes_per_pop_3D)
                             spike_times_array_per_trial_3D.append(spike_times_per_pop_3D)
                             sim_axis_array_per_trial.append(sim_axis_per_pop)
            ######   
            if string.lower(specify_targets[0])=="all":
               for pop in range(0,len(target_cell_array)):
                   if spike_plot_parameters[0]=="3D scatter plot":
                      spikes_per_pop_3D=[]   
                      spike_times_per_pop_3D=[]
                      sim_axis_per_pop=[]
                   for cell in range(0,len(target_cell_array[pop])):
                       #create target txt file containing spike times
                       if not os.path.isfile('%s/Golgi_pop%d_cell%d.txt'%(sim_dir,pop,cell)):
                          methods.get_spike_times('Golgi_pop%d_cell%d'%(pop,cell),exp_specify[0][exp_id],trial)
                       spikes = np.loadtxt('%s/Golgi_pop%d_cell%d.txt'%(sim_dir,pop, cell))
                       spike_train=pyspike.SpikeTrain(spikes,[0,sim_duration])
                       spike_trains.append(spike_train)
                       if spike_plot_parameters[0]=="2D raster plots":
                          if trial in spike_plot_parameters[1]:
                             ax_stack[pop].scatter(spikes,np.zeros_like(spikes)+(cell+exp_id*cell_no_array[pop]),marker='|',s=2,c=color)
                          if spike_plot_parameters[2]=="save all simulations to separate files":
                             raster_ax_array[trial][pop].scatter(spikes,np.zeros_like(spikes)+(cell+exp_id*cell_no_array[pop]),marker='|',s=2,c=color)
                       if spike_plot_parameters[0]=="3D scatter plot":
                           if cell==0:
                              spikes_per_pop_3D=np.zeros_like(spikes)+(cell+exp_id*cell_no_array[pop])
                              spike_times_per_pop_3D=spikes
                              sim_axis_per_pop=np.zeros_like(spikes)+trial+1  # for display start numbering trials from the index of 1
                           else:
                               spikes_per_pop_3D=spikes_per_pop_3D+np.zeros_like(spikes)+(cell+exp_id*cell_no_array[pop])
                               spike_times_per_pop_3D=spike_times_per_pop_3D+spikes
                               sim_axis_per_pop=sim_axis_per_pop+np.zeros_like(spikes)+trial+1
                               
                   if spike_plot_parameters[0]=="3D scatter plot":
                      spikes_array_per_trial_3D.append(spikes_per_pop_3D)
                      spike_times_array_per_trial_3D.append(spike_times_per_pop_3D)
                      sim_axis_array_per_trial.append(sim_axis_per_pop)
            ########
            if (specify_targets[0]=="3D region specific") and ("subtype specific" in specify_targets):
               if exp_specify[1][1]==True:
                  if ("randomly set target ids only once" in specify_targets ) or ("explicit list" in specify_targets):
                     for pop in range(0,len(target_cell_array)):
                         for cell in range(0,len(target_cell_array[pop])):
                             #create target txt file containing spike times
                             if not os.path.isfile('%s/Golgi_pop%d_cell%d.txt'%(sim_dir,pop,target_cell_array[pop][cell])):
                                methods.get_spike_times('Golgi_pop%d_cell%d'%(pop,target_cell_array[pop][cell]),exp_specify[0][exp_id],trial)
                             spikes = np.loadtxt('%s/Golgi_pop%d_cell%d.txt'%(sim_dir,pop,target_cell_array[pop][cell]))
                             spike_train=pyspike.SpikeTrain(spikes,[0,sim_duration])
                             spike_trains.append(spike_train)
                             if spike_plot_parameters[0]=="2D raster plots":
                                if trial in spike_plot_parameters[1]:
                                   ax_stack[pop].scatter(spikes,np.zeros_like(spikes)+(target_cell_array[pop][cell]+exp_id*cell_no_array[pop]),marker='|',s=2,c=color)
                                if spike_plot_parameters[2]=="save all simulations to separate files":
                                   raster_ax_array[trial][pop].scatter(spikes,np.zeros_like(spikes)+(target_cell_array[pop][cell]+exp_id*cell_no_array[pop]),marker='|',s=2,c=color)
                             if spike_plot_parameters[0]=="3D scatter plot":
                                if cell==0:
                                   spikes_per_pop_3D=np.zeros_like(spikes)+(target_cell_array[pop][cell]+ exp_id*cell_no_array[pop])
                                   spike_times_per_pop_3D=spikes
                                   sim_axis_per_pop=np.zeros_like(spikes)+trial+1  # for display start numbering trials from the index of 1
                                else:
                                   spikes_per_pop_3D=spikes_per_pop_3D+np.zeros_like(spikes)+(target_cell_array[pop][cell]+exp_id*cell_no_array[pop])
                                   spike_times_per_pop_3D=spike_times_per_pop_3D+spikes
                                   sim_axis_per_pop=sim_axis_per_pop+np.zeros_like(spikes)+trial+1
                         if spike_plot_parameters[0]=="3D scatter plot":
                            spikes_array_per_trial_3D.append(spikes_per_pop_3D)
                            spike_times_array_per_trial_3D.append(spike_times_per_pop_3D)
                            sim_axis_array_per_trial.append(sim_axis_per_pop)
                  else:
                     for pop in range(0,len(target_cell_array[trial])):
                         for cell in range(0,len(target_cell_array[trial][pop])): 
                             if not os.path.isfile('%s/Golgi_pop%d_cell%d.txt'%(sim_dir,pop,target_cell_array[trial][pop][cell])):
                                methods.get_spike_times('Golgi_pop%d_cell%d'%(pop,target_cell_array[trial][pop][cell]),exp_specify[0][exp_id],trial)
                             spikes = np.loadtxt('%s/Golgi_pop%d_cell%d.txt'%(sim_dir,pop,target_cell_array[trial][pop][cell]))
                             spike_train=pyspike.SpikeTrain(spikes,[0,sim_duration])
                             spike_trains.append(spike_train)
                             if spike_plot_parameters[0]=="2D raster plots":
                                if trial in spike_plot_parameters[1]:
                                   ax_stack[pop].scatter(spikes,np.zeros_like(spikes)+(target_cell_array[trial][pop][cell]+exp_id*cell_no_array[pop]),marker='|',s=2,c=color)
                                if spike_plot_parameters[2]=="save all simulations to separate files":
                                   raster_ax_array[trial][pop].scatter(spikes,np.zeros_like(spikes)+(target_cell_array[trial][pop][cell]+exp_id*cell_no_array[pop]),marker='|',s=2,c=color)
                             if spike_plot_parameters[0]=="3D scatter plot":
                                if cell==0:
                                   spikes_per_pop_3D=np.zeros_like(spikes)+(target_cell_array[trial][pop][cell]+ exp_id*cell_no_array[pop])
                                   spike_times_per_pop_3D=spikes
                                   sim_axis_per_pop=np.zeros_like(spikes)+trial+1  # for display start numbering trials from the index of 1
                                else:
                                   spikes_per_pop_3D=spikes_per_pop_3D+np.zeros_like(spikes)+(target_cell_array[trial][pop][cell]+exp_id*cell_no_array[pop])
                                   spike_times_per_pop_3D=spike_times_per_pop_3D+spikes
                                   sim_axis_per_pop=sim_axis_per_pop+np.zeros_like(spikes)+trial+1
                         if spike_plot_parameters[0]=="3D scatter plot":
                            spikes_array_per_trial_3D.append(spikes_per_pop_3D)
                            spike_times_array_per_trial_3D.append(spike_times_per_pop_3D)
                            sim_axis_array_per_trial.append(sim_axis_per_pop)
               else:
                  for pop in range(0,len(target_cell_array[trial])):
                      for cell in range(0,len(target_cell_array[trial][pop])):
                          if not os.path.isfile('%s/Golgi_pop%d_cell%d.txt'%(sim_dir,pop,target_cell_array[trial][pop][cell])):
                             methods.get_spike_times('Golgi_pop%d_cell%d'%(pop,target_cell_array[trial][pop][cell]),exp_specify[0][exp_id],trial)
                          spikes = np.loadtxt('%s/Golgi_pop%d_cell%d.txt'%(sim_dir,pop,target_cell_array[trial][pop][cell]))
                          spike_train=pyspike.SpikeTrain(spikes,[0,sim_duration])
                          spike_trains.append(spike_train)
                          if spike_plot_parameters[0]=="2D raster plots":
                             if trial in spike_plot_parameters[1]:
                                ax_stack[pop].scatter(spikes,np.zeros_like(spikes)+(target_cell_array[trial][pop][cell]+exp_id*cell_no_array[pop]),marker='|',s=2,c=color)
                             if spike_plot_parameters[2]=="save all simulations to separate files":
                                raster_ax_array[trial][pop].scatter(spikes,np.zeros_like(spikes)+(target_cell_array[trial][pop][cell]+exp_id*cell_no_array[pop]),marker='|',s=2,c=color)
                          if spike_plot_parameters[0]=="3D scatter plot":
                             if cell==0:
                                spikes_per_pop_3D=np.zeros_like(spikes)+(target_cell_array[trial][pop][cell]+ exp_id*cell_no_array[pop])
                                spike_times_per_pop_3D=spikes
                                sim_axis_per_pop=np.zeros_like(spikes)+trial+1  # for display start numbering trials from the index of 1
                             else:
                                spikes_per_pop_3D=spikes_per_pop_3D+np.zeros_like(spikes)+(target_cell_array[trial][pop][cell]+exp_id*cell_no_array[pop])
                                spike_times_per_pop_3D=spike_times_per_pop_3D+spikes
                                sim_axis_per_pop=sim_axis_per_pop+np.zeros_like(spikes)+trial+1
                      if spike_plot_parameters[0]=="3D scatter plot":
                         spikes_array_per_trial_3D.append(spikes_per_pop_3D)
                         spike_times_array_per_trial_3D.append(spike_times_per_pop_3D)
                         sim_axis_array_per_trial.append(sim_axis_per_pop)
            ########
            if string.lower(specify_targets[0])=="subtype specific":
               if specify_targets[2]=="randomly set target ids only once" or specify_targets[1]=="explicit list":
                  for pop in range(0,len(target_cell_array)):
                      for cell in range(0,len(target_cell_array[pop])):
                          #create target txt file containing spike times
                          if not os.path.isfile('%s/Golgi_pop%d_cell%d.txt'%(sim_dir,pop,target_cell_array[pop][cell])):
                             methods.get_spike_times('Golgi_pop%d_cell%d'%(pop,target_cell_array[pop][cell]),exp_specify[0][exp_id],trial)
                          spikes = np.loadtxt('%s/Golgi_pop%d_cell%d.txt'%(sim_dir,pop,target_cell_array[pop][cell]))
                          spike_train=pyspike.SpikeTrain(spikes,[0,sim_duration])
                          spike_trains.append(spike_train)
                          if spike_plot_parameters[0]=="2D raster plots":
                             if trial in spike_plot_parameters[1]:
                                ax_stack[pop].scatter(spikes,np.zeros_like(spikes)+(target_cell_array[pop][cell]+exp_id*(cell_no_array[pop]+1)),marker='|',s=2,c=color)
                             if spike_plot_parameters[2]=="save all simulations to separate files":
                                raster_ax_array[trial][pop].scatter(spikes,np.zeros_like(spikes)+(target_cell_array[pop][cell]+exp_id*(cell_no_array[pop]+1)),marker='|',s=2,c=color)
                          if spike_plot_parameters[0]=="3D scatter plot":
                             if cell==0:
                                spikes_per_pop_3D=np.zeros_like(spikes)+(target_cell_array[pop][cell]+ exp_id*(cell_no_array[pop]+1))
                                spike_times_per_pop_3D=spikes
                                sim_axis_per_pop=np.zeros_like(spikes)+trial+1  # for display start numbering trials from the index of 1
                             else:
                                spikes_per_pop_3D=np.append(spikes_per_pop_3D,np.zeros_like(spikes)+(target_cell_array[pop][cell]+exp_id*(cell_no_array[pop]+1)))
                                spike_times_per_pop_3D=np.append(spike_times_per_pop_3D,spikes)
                                sim_axis_per_pop=np.append(sim_axis_per_pop,np.zeros_like(spikes)+trial+1)

                      if spike_plot_parameters[0]=="3D scatter plot":
                         spikes_array_per_trial_3D.append(spikes_per_pop_3D)
                         spike_times_array_per_trial_3D.append(spike_times_per_pop_3D)
                         sim_axis_array_per_trial.append(sim_axis_per_pop)
                       
               else:
                  for pop in range(0,len(target_cell_array[trial])):
                      for cell in range(0,len(target_cell_array[trial][pop]) ):
                          #create target txt file containing spike times
                          if not os.path.isfile('%s/Golgi_pop%d_cell%d.txt'%(sim_dir,pop,target_cell_array[trial][pop][cell])):
                             methods.get_spike_times('Golgi_pop%d_cell%d'%(pop,target_cell_array[trial][pop][cell]),exp_specify[0][exp_id],trial)
                          spikes = np.loadtxt('%s/Golgi_pop%d_cell%d.txt'%(sim_dir,pop,target_cell_array[trial][pop][cell]))
                          spike_train=pyspike.SpikeTrain(spikes,[0,sim_duration])
                          spike_trains.append(spike_train)
                          if spike_plot_parameters[0]=="2D raster plots":
                             if trial in spike_plot_parameters[1]:
                                ax_stack[pop].scatter(spikes,np.zeros_like(spikes)+(target_cell_array[trial][pop][cell]+exp_id*(cell_no_array[pop]+1)),marker='|',s=2,c=color)
                             if spike_plot_parameters[2]=="save all simulations to separate files":
                                raster_ax_array[trial][pop].scatter(spikes,np.zeros_like(spikes)+(target_cell_array[trial][pop][cell]+exp_id*(cell_no_array[pop]+1)),marker='|',s=2,c=color)
                          if spike_plot_parameters[0]=="3D scatter plot":
                             if cell==0:
                                spikes_per_pop_3D=np.zeros_like(spikes)+(target_cell_array[trial][pop][cell]+ exp_id*(cell_no_array[pop]+1))
                                spike_times_per_pop_3D=spikes
                                sim_axis_per_pop=np.zeros_like(spikes)+trial+1  # for display start numbering trials from the index of 1
                             else:
                                spikes_per_pop_3D=np.append(spikes_per_pop_3D,np.zeros_like(spikes)+(target_cell_array[trial][pop][cell]+exp_id*cell_no_array[pop]))
                                spike_times_per_pop_3D=np.append(spike_times_per_pop_3D,spikes)
                                sim_axis_per_pop=np.append(sim_axis_per_pop,np.zeros_like(spikes)+trial+1)

                      if spike_plot_parameters[0]=="3D scatter plot":
                         spikes_array_per_trial_3D.append(spikes_per_pop_3D)
                         spike_times_array_per_trial_3D.append(spike_times_per_pop_3D)
                         sim_axis_array_per_trial.append(sim_axis_per_pop)
                      
            ########           
            if spike_plot_parameters[0]=="3D scatter plot":
               spikes_3D.append(spikes_array_per_trial_3D)
               spike_times_3D.append(spike_times_array_per_trial_3D)
               sim_axis_array.append(sim_axis_array_per_trial)
                  
            distances.append(pyspike.spike_profile_multi(spike_trains))
            ######## 
        ######    
        if spike_plot_parameters[0]=="3D scatter plot":
           for pop in range(0,no_of_groups):
               population_wise_3D_spikes.append(spikes_3D[0][pop])
               population_wise_3D_spike_times.append(spike_times_3D[0][pop])
               population_wise_sim_axis_array.append(sim_axis_array[0][pop])
           for pop in range(0,no_of_groups):
               for trial in range(1,n_trials):
                   population_wise_3D_spikes[pop]=np.append(population_wise_3D_spikes[pop],spikes_3D[trial][pop])
                   population_wise_3D_spike_times[pop]=np.append(population_wise_3D_spike_times[pop],spike_times_3D[trial][pop])
                   population_wise_sim_axis_array[pop]=np.append(population_wise_sim_axis_array[pop],sim_axis_array[trial][pop])

           for pop in range(0,no_of_groups):
               ax_3D[pop].scatter(population_wise_3D_spike_times[pop],population_wise_sim_axis_array[pop],population_wise_3D_spikes[pop],marker='|',s=2,c=color)

           if spike_plot_parameters[2]=="save 3D scatter plots separately":
              for pop in range(0,no_of_groups):
                  ax_3D_rasters_only[pop].scatter(population_wise_3D_spike_times[pop],population_wise_sim_axis_array[pop],population_wise_3D_spikes[pop],marker='|',s=2,c=color)
        ######         
            
            
        # average synchrony index across trials
        average_distance = distances[0]
        for distance in distances[1:]:
            average_distance.add(distance)
        average_distance.mul_scalar(1./exp_specify[2])

        # below blocks for saving synchrony and spike raster plots
        
        mark_steps=sim_duration/50
        marks=[]
        for mark in range(0,mark_steps+1):
            Mark=50*mark
            marks.append(Mark)

        xmin = 50
        right_shaded_region=50
        if sim_duration >=1000:
            right_shaded_region=100
        xmax = sim_duration-right_shaded_region
        x, y = average_distance.get_plottable_data()
        ximin = np.searchsorted(x, xmin)
        ximax = np.searchsorted(x, xmax)
        if spike_plot_parameters[0]=="2D raster plots":
           lines.append(ax_stack[no_of_groups].plot(x[ximin:ximax+1], 1-y[ximin:ximax+1], lw=2, c=color)[0])
           ax_stack[no_of_groups].plot(x[:ximin+1], 1-y[:ximin+1], lw=2, c=color, alpha=0.4)
           ax_stack[no_of_groups].plot(x[ximax:], 1-y[ximax:], lw=2, c=color, alpha=0.4)
           if spike_plot_parameters[2]=="save all simulations to separate files":
              lines_sep.append(ax_sync.plot(x[ximin:ximax+1], 1-y[ximin:ximax+1], lw=2, c=color)[0])
              ax_sync.plot(x[:ximin+1], 1-y[:ximin+1], lw=2, c=color, alpha=0.4)
              ax_sync.plot(x[ximax:], 1-y[ximax:], lw=2, c=color, alpha=0.4)
        if spike_plot_parameters[0]=="3D scatter plot":
           lines.append(ax_3D[no_of_groups].plot(x[ximin:ximax+1], 1-y[ximin:ximax+1], lw=2, c=color)[0])
           ax_3D[no_of_groups].plot(x[:ximin+1], 1-y[:ximin+1], lw=2, c=color, alpha=0.4)
           ax_3D[no_of_groups].plot(x[ximax:], 1-y[ximax:], lw=2, c=color, alpha=0.4)
           #ax_3D[no_of_groups].locator_params(axis='y', tight=True, nbins=mark_steps+1)
           if spike_plot_parameters[2]=="save 3D scatter plots separately":
              lines_sep.append(ax_sync.plot(x[ximin:ximax+1], 1-y[ximin:ximax+1], lw=2, c=color)[0])
              ax_sync.plot(x[:ximin+1], 1-y[:ximin+1], lw=2, c=color, alpha=0.4)
              ax_sync.plot(x[ximax:], 1-y[ximax:], lw=2, c=color, alpha=0.4)
              #ax_sync.locator_params(axis='y', tight=True, nbins=mark_steps+1)
             
              
    if spike_plot_parameters[0]=="3D scatter plot":
       for pop in range(0,no_of_groups):
           label_array=[]
           ztick_array=[]
           for exp in range(0,len(general_plot_parameters[3])):
               label_array.append("%d"%0)
               label_array.append("%d"%(cell_no_array[pop]-1))

               if exp==0:
                  ztick_array.append(exp)
                  ztick_array.append(cell_no_array[pop]-1)
                  left_value=cell_no_array[pop]-1
               else:
                  ztick_array.append(left_value+2)
                  ztick_array.append(left_value+2+cell_no_array[pop])
                  left_value=left_value+2+cell_no_array[pop]
           print label_array
           print ztick_array
            
           ax_3D[pop].set_zticks(ztick_array)
           fig_with_3D_rasters.canvas.draw()
           ax_3D[pop].set_zlim(0,(cell_no_array[pop]+1)*len(general_plot_parameters[3]) )
           ax_3D[pop].set_zlabel('Cell id, population %d'%pop,size=4)
           ax_3D[pop].set_zticks([cell_no_array[pop]+(cell_no_array[pop]+2)*k for k in range(0,len(general_plot_parameters[3]))],minor=True)
           ax_3D[pop].zaxis.grid(False, which='major')
           ax_3D[pop].zaxis.grid(True, which='minor')
           
           labels = [x.get_text() for x in ax_3D[pop].get_zticklabels()]
           
           for label in range(0,len(labels)):
               labels[label] =label_array[label]

           ax_3D[pop].set_zticklabels(labels)
           if pop==0:
              ax_3D[pop].set_title('3D spike plots for Golgi cell populations across trials',size=6)
           ax_3D[pop].set_xticks(marks)
           ax_3D[pop].set_xlabel('Time (ms)')
           ax_3D[pop].set_yticks(range(0,n_trials+1))
           ax_3D[pop].set_ylabel('Simulation number')
       
       for pop in range(0,no_of_groups+1):
           for tick in ax_3D[pop].xaxis.get_major_ticks():
               tick.label.set_fontsize(general_plot_parameters[4]) 
           for tick in ax_3D[pop].yaxis.get_major_ticks():
               tick.label.set_fontsize(general_plot_parameters[5])
       ax_3D[no_of_groups].locator_params(axis='y', tight=True, nbins=10)
       ax_3D[no_of_groups].set_xlabel('Time (ms)',fontsize=6)
       ax_3D[no_of_groups].set_ylabel('Synchrony index',size=4)
       ax_3D[no_of_groups].set_xticks(marks)
       ax_3D[no_of_groups].set_title('Synchronization between %s'%general_plot_parameters[1],size=6)
       fig_with_3D_rasters.tight_layout()
       
       fig_with_3D_rasters.subplots_adjust(top=0.80)
       fig_with_3D_rasters.subplots_adjust(bottom=0.15)
       fig_with_3D_rasters.subplots_adjust(hspace=.4)
       l=fig_with_3D_rasters.legend(lines,general_plot_parameters[3],title=general_plot_parameters[2], loc='upper center',ncol=len(general_plot_parameters[3]),bbox_to_anchor=(0.55, 1.0))
       plt.setp(l.get_title(),fontsize=6)
       plt.setp(l.get_texts(), fontsize=6)
       fig_with_3D_rasters.savefig('simulations/%s.%s'%(general_plot_parameters[0],spike_plot_parameters[3]))
       

       if spike_plot_parameters[2]=="save 3D scatter plots separately":
          for tick in ax_sync.xaxis.get_major_ticks():
              tick.label.set_fontsize(general_plot_parameters[4]) 
          for tick in ax_sync.yaxis.get_major_ticks():
              tick.label.set_fontsize(general_plot_parameters[5])
          #ax_sync.locator_params(axis='y', tight=True, nbins=10)
          ax_sync.set_xlabel('Time (ms)')
          ax_sync.set_ylabel('Synchrony index: %s'%general_plot_parameters[1],size=5)
          ax_sync.set_xticks(marks)
          plt.tight_layout()
          fig_sync.legend(lines_sep,general_plot_parameters[3],title=general_plot_parameters[2], loc='upper center',ncol=len(general_plot_parameters[3]))
          fig_sync.savefig('simulations/sync_only_3D_%s.%s'%(general_plot_parameters[0],spike_plot_parameters[3]))
          plt.clf()
          for pop in range(0,no_of_groups):
              label_array=[]
              ztick_array=[]
              for exp in range(0,len(general_plot_parameters[3])):
                  label_array.append("%d"%0)
                  label_array.append("%d"%(cell_no_array[pop]-1))

                  if exp==0:
                     ztick_array.append(exp)
                     ztick_array.append(cell_no_array[pop]-1)
                     left_value=cell_no_array[pop]-1
                  else:
                     ztick_array.append(left_value+2)
                     ztick_array.append(left_value+2+cell_no_array[pop])
                     left_value=left_value+2+cell_no_array[pop]
           
              ax_3D_rasters_only[pop].set_zticks(ztick_array)
              rasters3D_only.canvas.draw()
              ax_3D_rasters_only[pop].set_zlim(0,(cell_no_array[pop]+1)*len(general_plot_parameters[3]) )
              ax_3D_rasters_only[pop].set_zlabel('Cell id, population %d'%pop,size=4)
              ax_3D_rasters_only[pop].set_zticks([cell_no_array[pop]+(cell_no_array[pop]+2)*k for k in range(0,len(general_plot_parameters[3]))],minor=True)
              ax_3D_rasters_only[pop].zaxis.grid(False, which='major')
              ax_3D_rasters_only[pop].zaxis.grid(True, which='minor')
           
              labels = [x.get_text() for x in ax_3D_rasters_only[pop].get_zticklabels()]
           
              for label in range(0,len(labels)):
                  labels[label] =label_array[label]

              ax_3D_rasters_only[pop].set_zticklabels(labels)
              if pop==0:
                 ax_3D_rasters_only[pop].set_title('3D spike plots for Golgi cell populations across trials',size=6)
                 ax_3D_rasters_only[pop].set_xticks(marks)
                 ax_3D_rasters_only[pop].set_xlabel('Time (ms)')
                 ax_3D_rasters_only[pop].set_yticks(range(0,n_trials+1))
                 ax_3D_rasters_only[pop].set_ylabel('Simulation number')
              
          for pop in range(0,no_of_groups):
              for tick in ax_3D_rasters_only[pop].xaxis.get_major_ticks():
                  tick.label.set_fontsize(general_plot_parameters[4]) 
              for tick in ax_3D_rasters_only[pop].yaxis.get_major_ticks():
                  tick.label.set_fontsize(general_plot_parameters[5])
          
          rasters3D_only.subplots_adjust(top=0.80)
          rasters3D_only.subplots_adjust(bottom=0.15)
          rasters3D_only.subplots_adjust(hspace=.4)
          l=rasters3D_only.legend(lines_sep,general_plot_parameters[3],title=general_plot_parameters[2], loc='upper center',ncol=len(general_plot_parameters[3]),bbox_to_anchor=(0.55, 1.0))
          plt.setp(l.get_title(),fontsize=6)
          plt.setp(l.get_texts(), fontsize=6)
          rasters3D_only.savefig('simulations/scatter3D_only_%s.%s'%(general_plot_parameters[0],spike_plot_parameters[3]))
          plt.clf()
       
    if spike_plot_parameters[0]=="2D raster plots":    
       #create label array

       for pop in range(0,no_of_groups):
           label_array=[]
           ytick_array=[]
           for exp in range(0,len(general_plot_parameters[3])):
               label_array.append("%d"%0)
               label_array.append("%d"%(cell_no_array[pop]-1))

               if exp==0:
                  ytick_array.append(exp)
                  ytick_array.append(cell_no_array[pop]-1)
                  left_value=cell_no_array[pop]-1
               else:
                  ytick_array.append(left_value+2)
                  ytick_array.append(left_value+2+cell_no_array[pop])
                  left_value=left_value+2+cell_no_array[pop]
           print label_array
           print ytick_array
            
           ax_stack[pop].set_yticks(ytick_array)
           fig_stack.canvas.draw()
           ax_stack[pop].set_ylim(0,(cell_no_array[pop]+1)*len(general_plot_parameters[3]) )
           ax_stack[pop].set_ylabel('Cell id, population %d'%pop,size=4)
           ax_stack[pop].set_yticks([cell_no_array[pop]+(cell_no_array[pop]+2)*k for k in range(0,len(general_plot_parameters[3]))],minor=True)
           ax_stack[pop].yaxis.grid(False, which='major')
           ax_stack[pop].yaxis.grid(True, which='minor')
           
           labels = [x.get_text() for x in ax_stack[pop].get_yticklabels()]
           
           for label in range(0,len(labels)):
               labels[label] =label_array[label]

           ax_stack[pop].set_yticklabels(labels)
           if pop==0:
              ax_stack[pop].set_title('Raster plots for Golgi cell populations (trial id=%d)'%spike_plot_parameters[1][0],size=6)
       for pop in range(0,no_of_groups+1):
           for tick in ax_stack[pop].xaxis.get_major_ticks():
               tick.label.set_fontsize(general_plot_parameters[4]) 
           for tick in ax_stack[pop].yaxis.get_major_ticks():
               tick.label.set_fontsize(general_plot_parameters[5])
       ax_stack[no_of_groups].locator_params(axis='y', tight=True, nbins=10)
       ax_stack[no_of_groups].set_xlabel('Time (ms)',fontsize=6)
       ax_stack[no_of_groups].set_ylabel('Synchrony index',size=4)
       ax_stack[no_of_groups].set_xticks(marks)
       ax_stack[no_of_groups].set_title('Synchronization between %s'%general_plot_parameters[1],size=6)
       fig_stack.tight_layout()
       
       fig_stack.subplots_adjust(top=0.80)
       fig_stack.subplots_adjust(bottom=0.15)
       fig_stack.subplots_adjust(hspace=.4)
       l=fig_stack.legend(lines,general_plot_parameters[3],title=general_plot_parameters[2], loc='upper center',ncol=len(general_plot_parameters[3]),bbox_to_anchor=(0.55, 1.0))
       plt.setp(l.get_title(),fontsize=6)
       plt.setp(l.get_texts(), fontsize=6)
       fig_stack.savefig('simulations/%s.%s'%(general_plot_parameters[0],spike_plot_parameters[3]))
       
       if spike_plot_parameters[2]=="save all simulations to separate files":
          for tick in ax_sync.xaxis.get_major_ticks():
              tick.label.set_fontsize(general_plot_parameters[4]) 
          for tick in ax_sync.yaxis.get_major_ticks():
              tick.label.set_fontsize(general_plot_parameters[5])
          ax_sync.locator_params(axis='y', tight=True, nbins=10)
          ax_sync.set_xlabel('Time (ms)',fontsize=6)
          ax_sync.set_ylabel('Synchrony index',size=4)
          ax_sync.set_xticks(marks)
          ax_sync.set_title('Synchronization between %s'%general_plot_parameters[1],size=6)
          plt.tight_layout()
          fig_sync.legend(lines_sep,general_plot_parameters[3],title=general_plot_parameters[2], loc='upper center',ncol=len(general_plot_parameters[3]),bbox_to_anchor=(1.05, 0.55))
          fig_sync.savefig('simulations/sync_only_%s.%s'%(general_plot_parameters[0],spike_plot_parameters[3]))
          
          for trial in range(0,n_trials):
              if no_of_groups >1:
                 for pop in range(0,no_of_groups):
                     raster_ax_array[trial][pop].set_xticks(marks) 
                     raster_ax_array[trial][pop].set_yticks([cell_no_array[pop] * k for k in range(len(general_plot_parameters[3]))])
                     raster_ax_array[trial][pop].set_ylim(((cell_no_array[pop]*len(general_plot_parameters[3]))-1, 0))
                     #raster_ax_array[trial][pop].locator_params(axis='y',tight=True, nbins=len(general_plot_parameters[3]))
                     raster_ax_array[trial][pop].set_ylabel('Cell number, population %d'%pop,size=5)
                 for pop in range(0,no_of_groups):
                     for tick in raster_ax_array[trial][pop].xaxis.get_major_ticks():
                         tick.label.set_fontsize(general_plot_parameters[4]) 
                     for tick in raster_ax_array[trial][pop].yaxis.get_major_ticks():
                         tick.label.set_fontsize(general_plot_parameters[5])
                 #plt.tight_layout()
              else:
                  raster_ax_array[trial].set_xticks(marks) 
                  raster_ax_array[trial].set_yticks([cell_no_array[0] * k for k in range(len(general_plot_parameters[3]))])
                  raster_ax_array[trial].set_ylim(((cell_no_array[0]*len(general_plot_parameters[3]))-1, 0))
                  #raster_ax_array[trial].locator_params(axis='y',tight=True, nbins=len(general_plot_parameters[3]))
                  raster_ax_array[trial].set_ylabel('Cell number, population %d'%pop,size=5)
              raster_fig_array[trial].legend(lines_sep,general_plot_parameters[3],title=general_plot_parameters[2], loc='upper center',ncol=len(general_plot_parameters[3]))
              raster_fig_array[trial].savefig('simulations/sim%d_rasters_%s.%s'%(trial,general_plot_parameters[0],spike_plot_parameters[3]))
              plt.clf()