import sys
from pyneuroml.analysis import generate_current_vs_frequency_curve
    
nogui = '-nogui' in sys.argv  # Used to supress GUI in tests for Travis-CI
    
generate_current_vs_frequency_curve('NML2_SingleCompHHCell.nml', 
                                    'hhcell', 
                                    start_amp_nA =         0.0, 
                                    end_amp_nA =           0.2, 
                                    step_nA =              0.01, 
                                    analysis_duration =    1000, 
                                    analysis_delay =       50,
                                    plot_voltage_traces =  not nogui,
                                    plot_if =              not nogui)
def analyse_cell(dataset_id, type, nogui = False):
    
    
    reference = '%s_%s'%(type,dataset_id)
    cell_file = '%s.cell.nml'%(reference)
    
    images = 'summary/%s_%s.png'
    
    generate_current_vs_frequency_curve(cell_file, 
                                        reference, 
                                        simulator = 'jNeuroML_NEURON',
                                        start_amp_nA =         -0.1, 
                                        end_amp_nA =           0.4, 
                                        step_nA =              0.01, 
                                        analysis_duration =    1000, 
                                        analysis_delay =       50,
                                        plot_voltage_traces =  False,
                                        plot_if =              not nogui,
                                        plot_iv =              not nogui, 
                                        xlim_if =              [-200, 400],
                                        ylim_if =              [-10, 120],
                                        xlim_iv =              [-200, 400],
                                        ylim_iv =              [-120, -40],
                                        save_if_figure_to=images%(reference, 'if'), 
                                        save_iv_figure_to=images%(reference, 'iv'),
                                        show_plot_already = False)
               
    temp_dir = 'temp/'
    
    shutil.copy(cell_file, temp_dir)
    
    net_file = generate_network_for_sweeps(type, dataset_id, '%s.cell.nml'%(reference), reference, temp_dir)
    
    lems_file_name = 'LEMS_Test_%s_%s.xml'%(type,dataset_id)
    
    generate_lems_file_for_neuroml('Test_%s_%s'%(dataset_id,type),
                                   net_file,
                                   'network_%s_%s'%(dataset_id,type), 
                                   1500, 
                                   0.01, 
                                   lems_file_name,
                                   temp_dir,
                                   gen_plots_for_all_v=False,
                                   copy_neuroml = False)
    
    simulator = "jNeuroML_NEURON"
    
    if simulator == "jNeuroML":
        results = pynml.run_lems_with_jneuroml(temp_dir+lems_file_name, 
                                                nogui=True, 
                                                load_saved_data=True, 
                                                plot=False,
                                                show_plot_already=False)
    elif simulator == "jNeuroML_NEURON":
        results = pynml.run_lems_with_jneuroml_neuron(temp_dir+lems_file_name, 
                                                nogui=True, 
                                                load_saved_data=True, 
                                                plot=False,
                                                show_plot_already=False)
                                                
    x = []
    y = []
    
    print results.keys()
    
    tt = [t*1000 for t in results['t']]
    for i in range(len(results)-1):
        x.append(tt)
        y.append([v*1000 for v in results['Pop0/%i/%s_%s/v'%(i,type,dataset_id)]])
        
    pynml.generate_plot(x,
                y, 
                "Cell: %s"%dataset_id, 
                xaxis = "Time (ms)", 
                yaxis = "Membrane potential (mV)",
                show_plot_already=False,
                ylim = [-120, 60],
                save_figure_to = images%(reference, 'traces'))
def analyse_cell(dataset_id, type, info, nogui = False, densities=False, analysis_dir='../../data/'):
    
    reference = '%s_%s'%(type,dataset_id)
    cell_file = '%s/%s.cell.nml'%(type,reference)
    
    print("====================================\n\n   Analysing cell: %s, dataset %s\n"%(cell_file,dataset_id))
    
    nml_doc = pynml.read_neuroml2_file(cell_file)
    notes = nml_doc.cells[0].notes if len(nml_doc.cells)>0 else nml_doc.izhikevich2007_cells[0].notes
    meta_nml = eval(notes[notes.index('{'):])
    summary = "Fitness: %s (max evals: %s, pop: %s)"%(meta_nml['fitness'],meta_nml['max_evaluations'],meta_nml['population_size'])
    print summary
    
    images = 'summary/%s_%s.png'
    if_iv_data_files = 'summary/%s_%s.dat'
    

    data, v_sub, curents_sub, freqs, curents_spike = get_if_iv_for_dataset('%s%s_analysis.json'%(analysis_dir,dataset_id))
    
    if densities:

        dataset = {}
        seed = meta_nml['seed']
        if isinstance(seed, tuple):
            seed = seed[0]
        layer = str(data['location'].split(',')[-1].strip().replace(' ',''))
        ref = '%s_%s_%s'%(dataset_id,layer,int(seed))

        dataset['id'] = dataset_id
        dataset['reference'] = ref
        metas = ['aibs_cre_line','aibs_dendrite_type','location']
        for m in metas:
            dataset[m] = str(data[m])

        metas2 = ['fitness','population_size','seed']
        for m in metas2:
            dataset[m] = meta_nml[m]
            
        # Assume images below already generated...
        if type=='HH':
            
            
            cell = nml_doc.cells[0]
            
            sgv_files, all_info = generate_channel_density_plots(cell_file, text_densities=True, passives_erevs=True)
            sgv_file =sgv_files[0]
            for c in all_info:
                if c == cell.id:
                    cc = 'tuned_cell_info'
                else:
                    cc = c
                dataset[cc] = all_info[c]
        
            info['datasets'][ref] = dataset
            
        elif type=='Izh':
            
            dataset['tuned_cell_info'] = {}
            izh_cell = nml_doc.izhikevich2007_cells[0]
                        
            for p in ['C','a','b','c','d','k','vpeak','vr','vt']:
            
                dataset['tuned_cell_info'][p] = get_value_in_si(getattr(izh_cell, p))
            
            '''
            sgv_files, all_info = generate_channel_density_plots(cell_file, text_densities=True, passives_erevs=True)
            sgv_file =sgv_files[0]
            for c in all_info:
                if c == cell.id:
                    cc = 'tuned_cell_info'
                else:
                    cc = c
                dataset[cc] = all_info[c]'''
        
        info['datasets'][ref] = dataset
        
    else:

        traces_ax, if_ax, iv_ax = generate_current_vs_frequency_curve(cell_file, 
                                            reference, 
                                            simulator = 'jNeuroML_NEURON',
                                            start_amp_nA =         -0.1, 
                                            end_amp_nA =           0.4, 
                                            step_nA =              0.01, 
                                            analysis_duration =    1000, 
                                            analysis_delay =       50,
                                            plot_voltage_traces =  False,
                                            plot_if =              not nogui,
                                            plot_iv =              not nogui, 
                                            xlim_if =              [-200, 400],
                                            ylim_if =              [-10, 120],
                                            xlim_iv =              [-200, 400],
                                            ylim_iv =              [-120, -40],
                                            save_if_figure_to =    images%(reference, 'if'), 
                                            save_iv_figure_to =    images%(reference, 'iv'),
                                            save_if_data_to =      if_iv_data_files%(reference, 'if'), 
                                            save_iv_data_to =      if_iv_data_files%(reference, 'iv'), 
                                            show_plot_already = False,
                                            return_axes = True)


        iv_ax.plot(curents_sub, v_sub,   color='#ff2222',marker='o', linestyle='',zorder=1)   
        if_ax.plot(curents_spike, freqs ,color='#ff2222',marker='o', linestyle='',zorder=1)

        iv_ax.get_figure().savefig(images%(reference, 'iv'),bbox_inches='tight')
        if_ax.get_figure().savefig(images%(reference, 'if'),bbox_inches='tight')
        
        
        offset = 100 # mV 
        
        ifv_x = []
        ifv_y = []
        markers = []
        lines = []
        colors = []
        
        cols = {'Izh':'r','HH':'g','AllenHH':'b'}
        
        for ii in ['if','iv']:
            for tt in ['Izh','HH','AllenHH']:
                rr = '%s_%s'%(tt,dataset_id)
                f = if_iv_data_files%(rr, ii)
                if os.path.isfile(f):
                    print("--- Opening: %s"%f)
                    data, indeces = reload_standard_dat_file(f)
                    
                    ifv_x.append(data['t'])
                    
                    if ii=='if':
                        ifv_y.append([ff-offset for ff in data[0]])
                    else:
                        ifv_y.append([vv for vv in data[0]])
                        
                    
                    markers.append('')
                    colors.append(cols[tt])
                    lines.append('-')
                    
        ifv_x.append(curents_sub)
        vvsub = [vv for vv in v_sub]
        
        ifv_y.append(vvsub)
        
        sub_color = '#888888'
        markers.append('D')
        colors.append('k')
        lines.append('')
        
        ifv_x.append(curents_spike)
        ifv_y.append([ff-offset for ff in freqs])
        
        markers.append('o')
        colors.append(sub_color)
        lines.append('')
        
        import matplotlib
        import matplotlib.pyplot as plt

        print ifv_x
        print ifv_y
        ylim = [-105, -20]
        font_size = 18
        ax1 = pynml.generate_plot(ifv_x,
                    ifv_y, 
                    summary, 
                    markers=markers,
                    colors=colors,
                    linestyles=lines,
                    show_plot_already=False,
                    xlim = [-100, 400],
                    font_size = font_size,
                    ylim = ylim,
                    title_above_plot=False)
                    
        plt.xlabel('Input current (pA)', fontsize = font_size)
        plt.ylabel("Steady membrane potential (mV)", fontsize = font_size)
        
        ax2 = ax1.twinx()
        plt.ylim([ylim[0]+offset,ylim[1]+offset])
        plt.ylabel('Firing frequency (Hz)', color=sub_color, fontsize = font_size)
        ax2.tick_params(axis='y', colors=sub_color)
        
        
        #plt.axis('off')
        
        plt.savefig(images%(reference, 'if_iv'+"_FIG"),bbox_inches='tight')
        

        temp_dir = 'temp/'

        print("Copying %s to %s"%(cell_file, temp_dir))
        shutil.copy(cell_file, temp_dir)

        net_file = generate_network_for_sweeps(type, dataset_id, '%s.cell.nml'%(reference), reference, temp_dir, data_dir=analysis_dir)

        lems_file_name = 'LEMS_Test_%s_%s.xml'%(type,dataset_id)

        generate_lems_file_for_neuroml('Test_%s_%s'%(dataset_id,type),
                                       net_file,
                                       'network_%s_%s'%(dataset_id,type), 
                                       1500, 
                                       0.01, 
                                       lems_file_name,
                                       temp_dir,
                                       gen_plots_for_all_v=False,
                                       copy_neuroml = False)

        simulator = "jNeuroML_NEURON"

        if simulator == "jNeuroML":
            results = pynml.run_lems_with_jneuroml(temp_dir+lems_file_name, 
                                                    nogui=True, 
                                                    load_saved_data=True, 
                                                    plot=False,
                                                    show_plot_already=False)
        elif simulator == "jNeuroML_NEURON":
            results = pynml.run_lems_with_jneuroml_neuron(temp_dir+lems_file_name, 
                                                    nogui=True, 
                                                    load_saved_data=True, 
                                                    plot=False,
                                                    show_plot_already=False)

        x = []
        y = []

        print results.keys()

        tt = [t*1000 for t in results['t']]
        for i in range(len(results)-1):
            x.append(tt)
            y.append([v*1000 for v in results['Pop0/%i/%s_%s/v'%(i,type,dataset_id)]])

        pynml.generate_plot(x,
                    y, 
                    summary, 
                    show_plot_already=False,
                    ylim = [-120, 60],
                    save_figure_to = images%(reference, 'traces'),
                    title_above_plot=True)
                 
        ax = pynml.generate_plot(x,
                    y, 
                    summary, 
                    show_plot_already=False,
                    ylim = [-120, 60],
                    title_above_plot=False)
                    
        ax.set_xlabel(None)
        ax.set_ylabel(None)
        plt.axis('off')
        
        fig_file = images%(reference, 'traces'+"_FIG")
        plt.savefig(fig_file, bbox_inches='tight', pad_inches=0)
        from PIL import Image
        img = Image.open(fig_file)

        img2 = img.crop((60, 40, 660, 480))
        img2.save(fig_file)
def dashboard_cells(net_id,
                    net_file_name,
                    config_array,
                    global_dt,
                    if_params,
                    elec_len_list,
                    dt_list,
                    generate_dashboards=True,
                    compare_to_neuroConstruct=False,
                    regenerate_nml2=False,
                    show_plot_already=False,
                    proj_string_neuroConstruct=None,
                    shell=None,
                    nc_home=None):
            
    ################### check whether use of neuroConstruct python/java interface is needed ########################
    
    if regenerate_nml2:
    
       use_NeuroConstruct(compare_to_neuroConstruct=compare_to_neuroConstruct,
                          regenerate_nml2=regenerate_nml2,
                          proj_string=proj_string_neuroConstruct,
                          global_dt=global_dt,
                          config_array=config_array,
                          elec_len_list=elec_len_list,
                          shell=shell,
                          nc_home=nc_home)
                             
    else:
       
          
       use_NeuroConstruct(compare_to_neuroConstruct=compare_to_neuroConstruct,
                          regenerate_nml2=regenerate_nml2,
                          proj_string=proj_string_neuroConstruct,
                          global_dt=global_dt,
                          config_array=config_array,
                          shell=shell,
                          nc_home=nc_home)     
                             
            
                             
    ############################################################################################################
        
    if generate_dashboards:    
       
       cell_id_list=[]
       
       config_list=[]
       
       analysis_header_list=[]
       
       nC_vs_NML2Curve_list=[]
       
       IFcurve_list=[]
       
       for cellModel in config_array.keys():
       
           cell_id_list.append(cellModel)
           
           config_list.append(config_array[cellModel]['Analysis'])
        
           save_to_path="../"+cellModel
        
           if not os.path.exists(save_to_path):
              print("Creating a new directory %s"%save_to_path)
              os.makedirs(save_to_path)
           else:
              print("A directory %s already exists"%save_to_path)
           
           pathToConfig="../"+config_array[cellModel]['Analysis']
           
           try:
              
              with open(os.path.join(pathToConfig,"compSummary.json"),'r') as f:
              
                   comp_info=json.load(f)
                   
           except IOError:
           
              print "cannot open file %s"%os.path.join(pathToConfig,"compSummary.json")
              
           cell_morph_summary=comp_info[config_array[cellModel]['Analysis']]
           
           src_files = os.listdir(pathToConfig)
           
           num_dx_configs=0
           
           dx_array=[]
           
           found_all_compartmentalizations=False
           
           dx_configs={}
        
           target_v=None
           
           found_default=False
           
           for file_name in src_files:
           
               full_file_path=os.path.join(pathToConfig,file_name)
               
               if (os.path.isdir(full_file_path)) and "_default" in file_name:
               
                  found_default=True
            
                  original_LEMS_target=os.path.join(full_file_path,"LEMS_Target.xml")
            
                  ###################################################################################
                  if -1 in elec_len_list and "-1" in cell_morph_summary.keys():
                  
                      dx_configs[cell_morph_summary["-1"]["IntDivs"]]=original_LEMS_target
                     
                      default_num_of_comps=cell_morph_summary["-1"]["IntDivs"]
                      
                      dx_array.append(int(default_num_of_comps))
                     
                      num_dx_configs+=1
                  ##################################################################################      
                  print("%s is a directory"%full_file_path)
                  print("will generate the IF curve for %s.cell.nml"%cellModel)
                  generate_current_vs_frequency_curve(os.path.join(full_file_path,cellModel+".cell.nml"), 
                                      cellModel, 
                                      start_amp_nA =     if_params['start_amp_nA'], 
                                      end_amp_nA =       if_params['end_amp_nA'], 
                                      step_nA =          if_params['step_nA'], 
                                      analysis_duration =if_params['analysis_duration'], 
                                      analysis_delay =   if_params['analysis_delay'],
                                      dt=                if_params['dt'],
                                      temperature=       if_params['temperature'],
                                      plot_voltage_traces=if_params['plot_voltage_traces'],
                                      plot_if=            if_params['plot_if'],
                                      plot_iv=            if_params['plot_iv'],
                                      show_plot_already=  show_plot_already,
                                      save_if_figure_to='%s/IF_%s.png'%(save_to_path,cellModel),
                                      save_iv_figure_to='%s/IV_%s.png'%(save_to_path,cellModel),
                                      simulator=         if_params['simulator'])
                                        
                  IFcurve="IF_%s"%cellModel
                  
                  IFcurve_list.append(IFcurve)
                  
                  IVcurve="IV_%s"%cellModel
                  
                  nml2_file_path=os.path.join(full_file_path,net_file_name+".net.nml")      
                  
                  net_doc = pynml.read_neuroml2_file(nml2_file_path)
                  net=net_doc.networks[0]
                  pop=net.populations[0]
                  popID=pop.id
                  
                  target_v="%s/0/%s/v"%(popID,cellModel)
               
                  ########################################################################################
               
                  if if_params['simulator'] == 'jNeuroML':
                     results = pynml.run_lems_with_jneuroml(original_LEMS_target, nogui=True, load_saved_data=True, plot=False, verbose=False)
                  if if_params['simulator'] == 'jNeuroML_NEURON':
                     results = pynml.run_lems_with_jneuroml_neuron(original_LEMS_target, nogui=True, load_saved_data=True, plot=False, verbose=False)
                  
                  t = results['t']
                  v = results[target_v]
                  
                  if compare_to_neuroConstruct:
                  
                     print("will generate the comparison between the nC model and NeuroML2 model")
                     
                     PlotNC_vs_NML2({'NML2':[{'t':t,'v':v}],'nC':[config_array[cellModel]['OriginalTag']],
                                     'subplotTitles':['NeuroML2 versus nC model: simulations in NEURON with dt=%f'%global_dt]},
                                     {'cols':8,'rows':5},
                                     legend=True,
                                     show=False,
                                     save_to_file='%s/nC_vs_NML2_%s.png'%(save_to_path,config_array[cellModel]['Analysis']),
                                     nCcellPath=os.path.join(save_to_path,config_array[cellModel]['Analysis'])   )
                                    
                     analysis_string1="nC_vs_NML2_%s"%config_array[cellModel]['Analysis']
                     
                     analysis_header1="Comparison between the original nC model and NeuroML2 model: simulations in NEURON with dt=%f"%global_dt
                     
                     analysis_header_list.append(analysis_header1)
                     
                     nC_vs_NML2Curve_list.append(analysis_string1)
                              
                  else:
                  
                     print("will generate the plot for the NeuroML2 model")
                     
                     generate_nml2_plot({'NML2':[{'t':t,'v':v}],'subplotTitles':['NeuroML2 model: simulations in NEURON with dt=%f'%global_dt]},
                                        {'cols':8,'rows':5},
                                        show=False,
                                        save_to_file='%s/NML2_%s.png'%(save_to_path,config_array[cellModel]['Analysis']))
                                            
                     analysis_string1="NML2_%s"%config_array[cellModel]['Analysis']
                     
                     analysis_header1="NeuroML2 model: simulations in NEURON with dt=%f"%global_dt    
                     
                     analysis_header_array.append(analysis_header1) 
                     
                     nC_vs_NML2Curve_array.append(analysis_string1)
                     
                  smallest_dt=min(dt_list)  
                              
                  ########################################################################################
                  print("will generate the spike times vs dt curve for %s.cell.nml"%cellModel)
                  analyse_spiketime_vs_dt(nml2_file_path, 
                                          net_id,
                                          get_sim_duration(os.path.join(full_file_path,"LEMS_%s.xml"%net_id)),
                                          if_params['simulator'],
                                          target_v,
                                          dt_list,
                                          verbose=False,
                                          spike_threshold_mV = 0,
                                          show_plot_already=show_plot_already,
                                          save_figure_to="%s/Dt_%s.png"%(save_to_path,cellModel),
                                          num_of_last_spikes=None)
                                          
                  dt_curve="Dt_%s"%cellModel
                  
               if not found_all_compartmentalizations:
                  
                  for elecLen in range(0,len(elec_len_list)):
               
                      elec_len=str(elec_len_list[elecLen]) 
                      
                      if elec_len != "-1":
                  
                         if (elec_len  in file_name) and (elec_len in cell_morph_summary.keys() ):
                      
                            dx_configs[cell_morph_summary[elec_len]["IntDivs"]]=os.path.join(full_file_path,"LEMS_Target.xml")
                      
                            num_dx_configs+=1
                         
                            dx_array.append(int(cell_morph_summary[elec_len]["IntDivs"] ) )
                      
                            break
                         
               if num_dx_configs==len(elec_len_list):
                  
                  found_all_compartmentalizations=True 
                      
           if not found_default:
           
              print("default configuration for %s analysis is not found; execution will terminate; set regenerate_nml2 to True to generate target dirs."%cellModel)
              
              quit()
                      
           if found_all_compartmentalizations:
           
              dx_array=list(np.sort(dx_array) )
                  
              maximum_int_divs=max(dx_array)
           
              print("testing the presence of cell configs with different levels of spatial discretization")
              
              analyse_spiketime_vs_dx(dx_configs, 
                                      if_params['simulator'],
                                      target_v,
                                      verbose=False,
                                      spike_threshold_mV = 0,
                                      show_plot_already=show_plot_already,
                                      save_figure_to="%s/Dx_%s.png"%(save_to_path,cellModel),
                                      num_of_last_spikes=3) 
               
              dx_curve="Dx_%s"%cellModel
                
           else:
              print("not all of the target configurations were recompartmentalized; execution will terminate; set regenerate_nml2 to True to obtain all of the target configurations.")
              quit() 
              
           if config_array[cellModel]['Analysis'] != config_array[cellModel]['SpikeProfile']:    
        
              pathToProfileConfig="../"+config_array[cellModel]['SpikeProfile']+"/"+config_array[cellModel]['SpikeProfile']+"_default"
           
              original_LEMS_target=os.path.join(pathToProfileConfig,"LEMS_Target.xml")
               
              if if_params['simulator'] == 'jNeuroML':
                 results = pynml.run_lems_with_jneuroml(original_LEMS_target, nogui=True, load_saved_data=True, plot=False, verbose=False)
              if if_params['simulator'] == 'jNeuroML_NEURON':
                 results = pynml.run_lems_with_jneuroml_neuron(original_LEMS_target, nogui=True, load_saved_data=True, plot=False, verbose=False)
                
              if 'SpikeProfileTag' in config_array[cellModel].keys():
                 
                  tag=config_array[cellModel]['SpikeProfileTag']+"_0_wtime"
                 
              else:
                 
                  tag=config_array[cellModel]['OriginalTag']
                  
              if 'SpikeProfileCellTag' in config_array[cellModel].keys() and 'SpikeProfileTag' in config_array[cellModel].keys():
                
                 target_v="%s/0/%s/v"%(config_array[cellModel]['SpikeProfileTag'],config_array[cellModel]['SpikeProfileCellTag'])
                    
              t = results['t']
              v = results[target_v]
        
              if compare_to_neuroConstruct:
               
                 print("will generate the comparison between the nC model and NeuroML2 model")
                 
                 PlotNC_vs_NML2({'NML2':[{'t':t,'v':v}],'nC':[tag],
                                 'subplotTitles':['NML2 versus nC model: simulations in NEURON with dt=%f'%global_dt]},
                                 {'cols':8,'rows':5},
                                 legend=True,
                                 show=show_plot_already,
                                 save_to_file='%s/nC_vs_NML2_%s.png'%(save_to_path,config_array[cellModel]['SpikeProfile']),
                                 nCcellPath=os.path.join(save_to_path,config_array[cellModel]['SpikeProfile'])   )
                               
                 analysis_string2="nC_vs_NML2_%s"%config_array[cellModel]['SpikeProfile']
           
                 analysis_header2="Comparison between the original nC model and NeuroML2 model: simulations in NEURON with dt=%f"%global_dt
           
              else:
        
                 print("will generate the plot for the NeuroML2 model")
                 
                 generate_nml2_plot({'NML2':[{'t':t,'v':v}],'subplotTitles':['NeuroML2 model: simulations in NEURON with dt=%f'%global_dt]},
                                        {'cols':8,'rows':5},
                                        show=False,
                                        save_to_file='%s/NML2_%s.png'%(save_to_path,config_array[cellModel]['SpikeProfile']))
           
                                         
                 analysis_string2="NML2_%s"%config_array[cellModel]['SpikeProfile']
                     
                 analysis_header2="NeuroML2 model: simulations in NEURON with dt=%f"%global_dt
              
              cwd=os.getcwd()
               
              os.chdir(save_to_path)
        
              readme = ''' 
         
## Model: %(CellID)s

### Original neuroConstruct config ID: %(SpikeProfile)s

**%(AnalysisHeader2)s**

![Simulation](%(SpikeProfileCurve)s.png)

### Original neuroConstruct config ID: %(Config)s

**%(AnalysisHeader1)s**

![Simulation](%(nC_vs_NML2Curve)s.png)

**IF curve for the NeuroML2 model simulated in NEURON**

![Simulation](%(IFcurve)s.png)

**IV curve for the NeuroML2 model simulated in NEURON**

![Simulation](%(IVcurve)s.png)

**Spike times versus time step: the NeuroML2 model simulated in NEURON.
Dashed black lines - spike times at the %(Smallest_dt)s ms time step; Green - spike times at the following time steps (in ms): %(DtArray)s.**

![Simulation](%(DtCurve)s.png)

**Spike times versus spatial discretization: the NeuroML2 model simulated in NEURON.
Default value for the number of internal divs is %(default_divs)s.
Dashed black lines - spike times at the %(MaximumDivs)s internal divisions; Blue - spike times at the following values of internal divisions:
%(IntDivsArray)s.**

![Simulation](%(DxCurve)s.png)'''

              readme_file = open('README.md','w')
              
              readme_final=readme%{"CellID":cellModel,
                                   "IFcurve":IFcurve,
                                   "IVcurve":IVcurve,
                                   "Config":config_array[cellModel]['Analysis'],
                                   "DtCurve":dt_curve,
                                   "DxCurve":dx_curve,
                                   "nC_vs_NML2Curve":analysis_string1,
                                   "AnalysisHeader1":analysis_header1,
                                   "SpikeProfileCurve":analysis_string2,
                                   "AnalysisHeader2":analysis_header2,
                                   "default_divs":default_num_of_comps,
                                   "SpikeProfile":config_array[cellModel]['SpikeProfile'],
                                   "Smallest_dt":smallest_dt,
                                   "DtArray":dt_list,
                                   "IntDivsArray":dx_array,
                                   "MaximumDivs":maximum_int_divs}
                           
              readme_file.write(readme_final)
              
              readme_file.close()

              os.chdir(cwd)
      
           else:  
           
              cwd=os.getcwd()
               
              os.chdir(save_to_path)
        
              readme = ''' 
         
## Model: %(CellID)s

### Original neuroConstruct config ID: %(Config)s

**%(AnalysisHeader1)s**

![Simulation](%(nC_vs_NML2Curve)s.png)

**IF curve for the NeuroML2 model simulated in NEURON**

![Simulation](%(IFcurve)s.png)

**IV curve for the NeuroML2 model simulated in NEURON**

![Simulation](%(IVcurve)s.png)

**Spike times versus time step: the NeuroML2 model simulated in NEURON.
Dashed black lines - spike times at the %(Smallest_dt)s ms time step; Green - spike times for the following time steps (in ms): %(DtArray)s.**

![Simulation](%(DtCurve)s.png)

**Spike times versus spatial discretization: the NeuroML2 model simulated in NEURON.
Default value for the number of internal divs is %(default_divs)s.
Dashed black lines - spike times at the %(MaximumDivs)s internal divisions; Blue - spike times at the following values of internal divisions:
%(IntDivsArray)s.**

![Simulation](%(DxCurve)s.png)'''

              readme_file = open('README.md','w')
              
              readme_final=readme%{"CellID":cellModel,
                                   "IFcurve":IFcurve,
                                   "IVcurve":IVcurve,
                                   "Config":config_array[cellModel]['Analysis'],
                                   "DtCurve":dt_curve,
                                   "DxCurve":dx_curve,
                                   "nC_vs_NML2Curve":analysis_string1,
                                   "AnalysisHeader1":analysis_header1,
                                   "default_divs":default_num_of_comps,
                                   "Smallest_dt":smallest_dt,
                                   "DtArray":dt_list,
                                   "IntDivsArray":dx_array,
                                   "MaximumDivs":maximum_int_divs}
                           
              readme_file.write(readme_final)
              readme_file.close()
              os.chdir(cwd)                                
              
       cwd=os.getcwd()
               
       os.chdir(os.path.dirname(cwd))
        
       readme = ''' 
      
## Conversion of Thalamocortical cell models to NeuroML2

'''
       readme_file = open('README.md','w')

       for cell_index in range(0,len(cell_id_list)):
       
           readme_cell='''
           
## Model: %(CellID)s

### Original neuroConstruct config ID: %(Config)s

**%(AnalysisHeader)s**

![Simulation](%(nC_vs_NML2Curve)s.png)

**IF curve for the NeuroML2 model simulated in NEURON**

![Simulation](%(IFcurve)s.png)'''

           readme_cell=readme_cell%{"CellID":cell_id_list[cell_index],
                                    "Config":config_list[cell_index],
                                    "AnalysisHeader":analysis_header_list[cell_index],
                                    "nC_vs_NML2Curve":os.path.join(cell_id_list[cell_index],nC_vs_NML2Curve_list[cell_index]),
                                    "IFcurve":os.path.join(cell_id_list[cell_index],IFcurve_list[cell_index])}
                                    
           readme=readme+readme_cell
                                
       readme_file.write(readme)
       readme_file.close()
       os.chdir(cwd)     
Пример #5
0
def plot_cell_firing(cell_file,
                     num_processors=1,
                     quick=False,
                     show_plot=True,
                     plot2_duration=8000):

    cell_id = cell_file.split('/')[-1].split('.')[0]

    simulator = 'jNeuroML_NEURON' if num_processors == 1 else 'jNeuroML_NetPyNE'

    custom_amps_nA = [
        -0.1, -0.08, -0.06, -0.04, -0.02, 0.0, 0.02, 0.04, 0.06, 0.08, 0.1,
        0.12
    ]
    if quick:
        custom_amps_nA = [-0.08, -0.04, 0.0, 0.04, 0.08, 0.12]

    curve = generate_current_vs_frequency_curve(
        cell_file,
        cell_id,
        custom_amps_nA=custom_amps_nA,
        analysis_duration=1000,
        pre_zero_pulse=100,
        post_zero_pulse=100,
        analysis_delay=0,
        dt=0.025,
        simulator=simulator,
        num_processors=num_processors,
        plot_voltage_traces=True,
        plot_if=False,
        plot_iv=False,
        temperature='34degC',
        title_above_plot=True,
        save_voltage_traces_to="%s_traces.png" % cell_id,
        show_plot_already=show_plot,
        verbose=False)

    # Longer duration, more points

    if not quick:
        curve = generate_current_vs_frequency_curve(
            cell_file,
            cell_id,
            start_amp_nA=-0.1,
            end_amp_nA=0.4,
            step_nA=0.025,
            analysis_duration=plot2_duration,
            dt=0.025,
            pre_zero_pulse=0,
            post_zero_pulse=0,
            analysis_delay=100,
            simulator=simulator,
            num_processors=num_processors,
            plot_voltage_traces=False,
            plot_if=True,
            plot_iv=True,
            temperature='34degC',
            save_if_figure_to="%s_IF.png" % cell_id,
            save_iv_figure_to="%s_IV.png" % cell_id,
            title_above_plot=True,
            save_if_data_to="%s_IF.dat" % cell_id,
            save_iv_data_to="%s_IV.dat" % cell_id,
            show_plot_already=show_plot,
            verbose=False)
Пример #6
0
import sys
from pyneuroml.analysis import generate_current_vs_frequency_curve

nogui = '-nogui' in sys.argv  # Used to supress GUI in tests for Travis-CI

generate_current_vs_frequency_curve('NML2_SingleCompHHCell.nml',
                                    'hhcell',
                                    start_amp_nA=-0.1,
                                    end_amp_nA=0.2,
                                    step_nA=0.01,
                                    analysis_duration=1000,
                                    analysis_delay=50,
                                    plot_voltage_traces=not nogui,
                                    plot_if=not nogui,
                                    plot_iv=not nogui)
def analyse_cell(dataset_id, type, nogui=False):

    reference = '%s_%s' % (type, dataset_id)
    cell_file = '%s.cell.nml' % (reference)

    images = 'summary/%s_%s.png'

    generate_current_vs_frequency_curve(
        cell_file,
        reference,
        simulator='jNeuroML_NEURON',
        start_amp_nA=-0.1,
        end_amp_nA=0.4,
        step_nA=0.01,
        analysis_duration=1000,
        analysis_delay=50,
        plot_voltage_traces=False,
        plot_if=not nogui,
        plot_iv=not nogui,
        xlim_if=[-200, 400],
        ylim_if=[-10, 120],
        xlim_iv=[-200, 400],
        ylim_iv=[-120, -40],
        save_if_figure_to=images % (reference, 'if'),
        save_iv_figure_to=images % (reference, 'iv'),
        show_plot_already=False)

    temp_dir = 'temp/'

    shutil.copy(cell_file, temp_dir)

    net_file = generate_network_for_sweeps(type, dataset_id,
                                           '%s.cell.nml' % (reference),
                                           reference, temp_dir)

    lems_file_name = 'LEMS_Test_%s_%s.xml' % (type, dataset_id)

    generate_lems_file_for_neuroml('Test_%s_%s' % (dataset_id, type),
                                   net_file,
                                   'network_%s_%s' % (dataset_id, type),
                                   1500,
                                   0.01,
                                   lems_file_name,
                                   temp_dir,
                                   gen_plots_for_all_v=False,
                                   copy_neuroml=False)

    simulator = "jNeuroML_NEURON"

    if simulator == "jNeuroML":
        results = pynml.run_lems_with_jneuroml(temp_dir + lems_file_name,
                                               nogui=True,
                                               load_saved_data=True,
                                               plot=False,
                                               show_plot_already=False)
    elif simulator == "jNeuroML_NEURON":
        results = pynml.run_lems_with_jneuroml_neuron(temp_dir +
                                                      lems_file_name,
                                                      nogui=True,
                                                      load_saved_data=True,
                                                      plot=False,
                                                      show_plot_already=False)

    x = []
    y = []

    print results.keys()

    tt = [t * 1000 for t in results['t']]
    for i in range(len(results) - 1):
        x.append(tt)
        y.append([
            v * 1000
            for v in results['Pop0/%i/%s_%s/v' % (i, type, dataset_id)]
        ])

    pynml.generate_plot(x,
                        y,
                        "Cell: %s" % dataset_id,
                        xaxis="Time (ms)",
                        yaxis="Membrane potential (mV)",
                        show_plot_already=False,
                        ylim=[-120, 60],
                        save_figure_to=images % (reference, 'traces'))
Пример #8
0
import sys
from pyneuroml.analysis import generate_current_vs_frequency_curve
    
nogui = '-nogui' in sys.argv  # Used to supress GUI in tests for Travis-CI
    
generate_current_vs_frequency_curve('NML2_SingleCompHHCell.nml', 
                                    'hhcell', 
                                    0.01, 
                                    0.2, 
                                    0.01, 
                                    1000, 
                                    50,
                                    plot_voltage_traces=not nogui,
                                    plot_if=not nogui)
def analyse_cell(dataset_id,
                 type,
                 info,
                 nogui=False,
                 densities=False,
                 analysis_dir='../../data/'):

    reference = '%s_%s' % (type, dataset_id)
    cell_file = '%s/%s.cell.nml' % (type, reference)

    print(
        "====================================\n\n   Analysing cell: %s, dataset %s\n"
        % (cell_file, dataset_id))

    nml_doc = pynml.read_neuroml2_file(cell_file)
    notes = nml_doc.cells[0].notes if len(
        nml_doc.cells) > 0 else nml_doc.izhikevich2007_cells[0].notes
    meta_nml = eval(notes[notes.index('{'):])
    summary = "Fitness: %s (max evals: %s, pop: %s)" % (
        meta_nml['fitness'], meta_nml['max_evaluations'],
        meta_nml['population_size'])
    print summary

    images = 'summary/%s_%s.png'
    if_iv_data_files = 'summary/%s_%s.dat'

    data, v_sub, curents_sub, freqs, curents_spike = get_if_iv_for_dataset(
        '%s%s_analysis.json' % (analysis_dir, dataset_id))

    if densities:

        dataset = {}
        seed = meta_nml['seed']
        if isinstance(seed, tuple):
            seed = seed[0]
        layer = str(data['location'].split(',')[-1].strip().replace(' ', ''))
        ref = '%s_%s_%s' % (dataset_id, layer, int(seed))

        dataset['id'] = dataset_id
        dataset['reference'] = ref
        metas = ['aibs_cre_line', 'aibs_dendrite_type', 'location']
        for m in metas:
            dataset[m] = str(data[m])

        metas2 = ['fitness', 'population_size', 'seed']
        for m in metas2:
            dataset[m] = meta_nml[m]

        # Assume images below already generated...
        if type == 'HH':

            cell = nml_doc.cells[0]

            sgv_files, all_info = generate_channel_density_plots(
                cell_file, text_densities=True, passives_erevs=True)
            sgv_file = sgv_files[0]
            for c in all_info:
                if c == cell.id:
                    cc = 'tuned_cell_info'
                else:
                    cc = c
                dataset[cc] = all_info[c]

            info['datasets'][ref] = dataset

        elif type == 'Izh':

            dataset['tuned_cell_info'] = {}
            izh_cell = nml_doc.izhikevich2007_cells[0]

            for p in ['C', 'a', 'b', 'c', 'd', 'k', 'vpeak', 'vr', 'vt']:

                dataset['tuned_cell_info'][p] = get_value_in_si(
                    getattr(izh_cell, p))
            '''
            sgv_files, all_info = generate_channel_density_plots(cell_file, text_densities=True, passives_erevs=True)
            sgv_file =sgv_files[0]
            for c in all_info:
                if c == cell.id:
                    cc = 'tuned_cell_info'
                else:
                    cc = c
                dataset[cc] = all_info[c]'''

        info['datasets'][ref] = dataset

    else:

        traces_ax, if_ax, iv_ax = generate_current_vs_frequency_curve(
            cell_file,
            reference,
            simulator='jNeuroML_NEURON',
            start_amp_nA=-0.1,
            end_amp_nA=0.4,
            step_nA=0.01,
            analysis_duration=1000,
            analysis_delay=50,
            plot_voltage_traces=False,
            plot_if=not nogui,
            plot_iv=not nogui,
            xlim_if=[-200, 400],
            ylim_if=[-10, 120],
            xlim_iv=[-200, 400],
            ylim_iv=[-120, -40],
            save_if_figure_to=images % (reference, 'if'),
            save_iv_figure_to=images % (reference, 'iv'),
            save_if_data_to=if_iv_data_files % (reference, 'if'),
            save_iv_data_to=if_iv_data_files % (reference, 'iv'),
            show_plot_already=False,
            return_axes=True)

        iv_ax.plot(curents_sub,
                   v_sub,
                   color='#ff2222',
                   marker='o',
                   linestyle='',
                   zorder=1)
        if_ax.plot(curents_spike,
                   freqs,
                   color='#ff2222',
                   marker='o',
                   linestyle='',
                   zorder=1)

        iv_ax.get_figure().savefig(images % (reference, 'iv'),
                                   bbox_inches='tight')
        if_ax.get_figure().savefig(images % (reference, 'if'),
                                   bbox_inches='tight')

        offset = 100  # mV

        ifv_x = []
        ifv_y = []
        markers = []
        lines = []
        colors = []

        cols = {'Izh': 'r', 'HH': 'g', 'AllenHH': 'b'}

        for ii in ['if', 'iv']:
            for tt in ['Izh', 'HH', 'AllenHH']:
                rr = '%s_%s' % (tt, dataset_id)
                f = if_iv_data_files % (rr, ii)
                if os.path.isfile(f):
                    print("--- Opening: %s" % f)
                    data, indeces = reload_standard_dat_file(f)

                    ifv_x.append(data['t'])

                    if ii == 'if':
                        ifv_y.append([ff - offset for ff in data[0]])
                    else:
                        ifv_y.append([vv for vv in data[0]])

                    markers.append('')
                    colors.append(cols[tt])
                    lines.append('-')

        ifv_x.append(curents_sub)
        vvsub = [vv for vv in v_sub]

        ifv_y.append(vvsub)

        sub_color = '#888888'
        markers.append('D')
        colors.append('k')
        lines.append('')

        ifv_x.append(curents_spike)
        ifv_y.append([ff - offset for ff in freqs])

        markers.append('o')
        colors.append(sub_color)
        lines.append('')

        import matplotlib
        import matplotlib.pyplot as plt

        print ifv_x
        print ifv_y
        ylim = [-105, -20]
        font_size = 18
        ax1 = pynml.generate_plot(ifv_x,
                                  ifv_y,
                                  summary,
                                  markers=markers,
                                  colors=colors,
                                  linestyles=lines,
                                  show_plot_already=False,
                                  xlim=[-100, 400],
                                  font_size=font_size,
                                  ylim=ylim,
                                  title_above_plot=False)

        plt.xlabel('Input current (pA)', fontsize=font_size)
        plt.ylabel("Steady membrane potential (mV)", fontsize=font_size)

        ax2 = ax1.twinx()
        plt.ylim([ylim[0] + offset, ylim[1] + offset])
        plt.ylabel('Firing frequency (Hz)',
                   color=sub_color,
                   fontsize=font_size)
        ax2.tick_params(axis='y', colors=sub_color)

        #plt.axis('off')

        plt.savefig(images % (reference, 'if_iv' + "_FIG"),
                    bbox_inches='tight')

        temp_dir = 'temp/'

        print("Copying %s to %s" % (cell_file, temp_dir))
        shutil.copy(cell_file, temp_dir)

        net_file = generate_network_for_sweeps(type,
                                               dataset_id,
                                               '%s.cell.nml' % (reference),
                                               reference,
                                               temp_dir,
                                               data_dir=analysis_dir)

        lems_file_name = 'LEMS_Test_%s_%s.xml' % (type, dataset_id)

        generate_lems_file_for_neuroml('Test_%s_%s' % (dataset_id, type),
                                       net_file,
                                       'network_%s_%s' % (dataset_id, type),
                                       1500,
                                       0.01,
                                       lems_file_name,
                                       temp_dir,
                                       gen_plots_for_all_v=False,
                                       copy_neuroml=False)

        simulator = "jNeuroML_NEURON"

        if simulator == "jNeuroML":
            results = pynml.run_lems_with_jneuroml(temp_dir + lems_file_name,
                                                   nogui=True,
                                                   load_saved_data=True,
                                                   plot=False,
                                                   show_plot_already=False)
        elif simulator == "jNeuroML_NEURON":
            results = pynml.run_lems_with_jneuroml_neuron(
                temp_dir + lems_file_name,
                nogui=True,
                load_saved_data=True,
                plot=False,
                show_plot_already=False)

        x = []
        y = []

        print results.keys()

        tt = [t * 1000 for t in results['t']]
        for i in range(len(results) - 1):
            x.append(tt)
            y.append([
                v * 1000
                for v in results['Pop0/%i/%s_%s/v' % (i, type, dataset_id)]
            ])

        pynml.generate_plot(x,
                            y,
                            summary,
                            show_plot_already=False,
                            ylim=[-120, 60],
                            save_figure_to=images % (reference, 'traces'),
                            title_above_plot=True)

        ax = pynml.generate_plot(x,
                                 y,
                                 summary,
                                 show_plot_already=False,
                                 ylim=[-120, 60],
                                 title_above_plot=False)

        ax.set_xlabel(None)
        ax.set_ylabel(None)
        plt.axis('off')

        fig_file = images % (reference, 'traces' + "_FIG")
        plt.savefig(fig_file, bbox_inches='tight', pad_inches=0)
        from PIL import Image
        img = Image.open(fig_file)

        img2 = img.crop((60, 40, 660, 480))
        img2.save(fig_file)
Пример #10
0
import sys
from pyneuroml.analysis import generate_current_vs_frequency_curve
    
nogui = '-nogui' in sys.argv  # Used to supress GUI in tests for Travis-CI
    
generate_current_vs_frequency_curve(nml2_file =           'WangBuzsakiCell.xml', 
                                    cell_id =             'wb1', 
                                    start_amp_nA =         -0.002, 
                                    end_amp_nA =           0.022, 
                                    step_nA =              0.001, 
                                    analysis_duration =    500, 
                                    analysis_delay =       50,
                                    temperature =          "35degC",
                                    spike_threshold_mV =   0.0,
                                    plot_voltage_traces =  False, # not nogui,
                                    plot_if =              True,  # not nogui,
                                    plot_iv =              False,  # not nogui,
                                    include_included =     False)
Пример #11
0
from pyneuroml.analysis import generate_current_vs_frequency_curve

simulator = 'jNeuroML'

res_1_jnml = generate_current_vs_frequency_curve(nml2_file =          'Granule_98.cell.nml', 
                                                 cell_id =            'Granule_98', 
                                                 start_amp_nA =       0, 
                                                 end_amp_nA =         0.08, 
                                                 step_nA =            0.005, 
                                                 analysis_duration =  1500, 
                                                 analysis_delay =     50,
                                                 dt =                 0.01,
                                                 plot_voltage_traces= False,
                                                 temperature=         "32degC",
                                                 simulator =          simulator,
                                                 plot_if =            False)

simulator = 'jNeuroML_NEURON'

res_1_jnrn = generate_current_vs_frequency_curve(nml2_file =          'Granule_98.cell.nml', 
                                                 cell_id =            'Granule_98', 
                                                 start_amp_nA =       0, 
                                                 end_amp_nA =         0.08, 
                                                 step_nA =            0.005, 
                                                 analysis_duration =  1500, 
                                                 analysis_delay =     50,
                                                 dt =                 0.01,
                                                 plot_voltage_traces= False,
                                                 temperature=         "32degC",
                                                 simulator =          simulator,
Пример #12
0
def dashboard_cells(net_id,
                    net_file_name,
                    config_array,
                    global_dt,
                    if_params,
                    elec_len_list,
                    dt_list,
                    generate_dashboards=True,
                    compare_to_neuroConstruct=False,
                    regenerate_nml2=False,
                    show_plot_already=False,
                    proj_string_neuroConstruct=None,
                    shell=None,
                    nc_home=None):

    ################### check whether use of neuroConstruct python/java interface is needed ########################

    if regenerate_nml2:

        use_NeuroConstruct(compare_to_neuroConstruct=compare_to_neuroConstruct,
                           regenerate_nml2=regenerate_nml2,
                           proj_string=proj_string_neuroConstruct,
                           global_dt=global_dt,
                           config_array=config_array,
                           elec_len_list=elec_len_list,
                           shell=shell,
                           nc_home=nc_home)

    else:

        use_NeuroConstruct(compare_to_neuroConstruct=compare_to_neuroConstruct,
                           regenerate_nml2=regenerate_nml2,
                           proj_string=proj_string_neuroConstruct,
                           global_dt=global_dt,
                           config_array=config_array,
                           shell=shell,
                           nc_home=nc_home)

    ############################################################################################################

    if generate_dashboards:

        cell_id_list = []

        config_list = []

        analysis_header_list = []

        nC_vs_NML2Curve_list = []

        IFcurve_list = []

        for cellModel in config_array.keys():

            cell_id_list.append(cellModel)

            config_list.append(config_array[cellModel]['Analysis'])

            save_to_path = "../" + cellModel

            if not os.path.exists(save_to_path):
                print("Creating a new directory %s" % save_to_path)
                os.makedirs(save_to_path)
            else:
                print("A directory %s already exists" % save_to_path)

            pathToConfig = "../" + config_array[cellModel]['Analysis']

            try:

                with open(os.path.join(pathToConfig, "compSummary.json"),
                          'r') as f:

                    comp_info = json.load(f)

            except IOError:

                print "cannot open file %s" % os.path.join(
                    pathToConfig, "compSummary.json")

            cell_morph_summary = comp_info[config_array[cellModel]['Analysis']]

            src_files = os.listdir(pathToConfig)

            num_dx_configs = 0

            dx_array = []

            found_all_compartmentalizations = False

            dx_configs = {}

            target_v = None

            found_default = False

            for file_name in src_files:

                full_file_path = os.path.join(pathToConfig, file_name)

                if (os.path.isdir(full_file_path)) and "_default" in file_name:

                    found_default = True

                    original_LEMS_target = os.path.join(
                        full_file_path, "LEMS_Target.xml")

                    ###################################################################################
                    if -1 in elec_len_list and "-1" in cell_morph_summary.keys(
                    ):

                        dx_configs[cell_morph_summary["-1"]
                                   ["IntDivs"]] = original_LEMS_target

                        default_num_of_comps = cell_morph_summary["-1"][
                            "IntDivs"]

                        dx_array.append(int(default_num_of_comps))

                        num_dx_configs += 1
                    ##################################################################################
                    print("%s is a directory" % full_file_path)
                    print("will generate the IF curve for %s.cell.nml" %
                          cellModel)
                    generate_current_vs_frequency_curve(
                        os.path.join(full_file_path, cellModel + ".cell.nml"),
                        cellModel,
                        start_amp_nA=if_params['start_amp_nA'],
                        end_amp_nA=if_params['end_amp_nA'],
                        step_nA=if_params['step_nA'],
                        analysis_duration=if_params['analysis_duration'],
                        analysis_delay=if_params['analysis_delay'],
                        dt=if_params['dt'],
                        temperature=if_params['temperature'],
                        plot_voltage_traces=if_params['plot_voltage_traces'],
                        plot_if=if_params['plot_if'],
                        plot_iv=if_params['plot_iv'],
                        show_plot_already=show_plot_already,
                        save_if_figure_to='%s/IF_%s.png' %
                        (save_to_path, cellModel),
                        save_iv_figure_to='%s/IV_%s.png' %
                        (save_to_path, cellModel),
                        simulator=if_params['simulator'])

                    IFcurve = "IF_%s" % cellModel

                    IFcurve_list.append(IFcurve)

                    IVcurve = "IV_%s" % cellModel

                    nml2_file_path = os.path.join(full_file_path,
                                                  net_file_name + ".net.nml")

                    net_doc = pynml.read_neuroml2_file(nml2_file_path)
                    net = net_doc.networks[0]
                    pop = net.populations[0]
                    popID = pop.id

                    target_v = "%s/0/%s/v" % (popID, cellModel)

                    ########################################################################################

                    if if_params['simulator'] == 'jNeuroML':
                        results = pynml.run_lems_with_jneuroml(
                            original_LEMS_target,
                            nogui=True,
                            load_saved_data=True,
                            plot=False,
                            verbose=False)
                    if if_params['simulator'] == 'jNeuroML_NEURON':
                        results = pynml.run_lems_with_jneuroml_neuron(
                            original_LEMS_target,
                            nogui=True,
                            load_saved_data=True,
                            plot=False,
                            verbose=False)

                    t = results['t']
                    v = results[target_v]

                    if compare_to_neuroConstruct:

                        print(
                            "will generate the comparison between the nC model and NeuroML2 model"
                        )

                        PlotNC_vs_NML2(
                            {
                                'NML2': [{
                                    't': t,
                                    'v': v
                                }],
                                'nC': [config_array[cellModel]['OriginalTag']],
                                'subplotTitles': [
                                    'NeuroML2 versus nC model: simulations in NEURON with dt=%f'
                                    % global_dt
                                ]
                            }, {
                                'cols': 8,
                                'rows': 5
                            },
                            legend=True,
                            show=False,
                            save_to_file='%s/nC_vs_NML2_%s.png' %
                            (save_to_path,
                             config_array[cellModel]['Analysis']),
                            nCcellPath=os.path.join(
                                save_to_path,
                                config_array[cellModel]['Analysis']))

                        analysis_string1 = "nC_vs_NML2_%s" % config_array[
                            cellModel]['Analysis']

                        analysis_header1 = "Comparison between the original nC model and NeuroML2 model: simulations in NEURON with dt=%f" % global_dt

                        analysis_header_list.append(analysis_header1)

                        nC_vs_NML2Curve_list.append(analysis_string1)

                    else:

                        print("will generate the plot for the NeuroML2 model")

                        generate_nml2_plot(
                            {
                                'NML2': [{
                                    't': t,
                                    'v': v
                                }],
                                'subplotTitles': [
                                    'NeuroML2 model: simulations in NEURON with dt=%f'
                                    % global_dt
                                ]
                            }, {
                                'cols': 8,
                                'rows': 5
                            },
                            show=False,
                            save_to_file='%s/NML2_%s.png' %
                            (save_to_path,
                             config_array[cellModel]['Analysis']))

                        analysis_string1 = "NML2_%s" % config_array[cellModel][
                            'Analysis']

                        analysis_header1 = "NeuroML2 model: simulations in NEURON with dt=%f" % global_dt

                        analysis_header_array.append(analysis_header1)

                        nC_vs_NML2Curve_array.append(analysis_string1)

                    smallest_dt = min(dt_list)

                    ########################################################################################
                    print(
                        "will generate the spike times vs dt curve for %s.cell.nml"
                        % cellModel)
                    analyse_spiketime_vs_dt(
                        nml2_file_path,
                        net_id,
                        get_sim_duration(
                            os.path.join(full_file_path,
                                         "LEMS_%s.xml" % net_id)),
                        if_params['simulator'],
                        target_v,
                        dt_list,
                        verbose=False,
                        spike_threshold_mV=0,
                        show_plot_already=show_plot_already,
                        save_figure_to="%s/Dt_%s.png" %
                        (save_to_path, cellModel),
                        num_of_last_spikes=None)

                    dt_curve = "Dt_%s" % cellModel

                if not found_all_compartmentalizations:

                    for elecLen in range(0, len(elec_len_list)):

                        elec_len = str(elec_len_list[elecLen])

                        if elec_len != "-1":

                            if (elec_len in file_name) and (
                                    elec_len in cell_morph_summary.keys()):

                                dx_configs[cell_morph_summary[elec_len]
                                           ["IntDivs"]] = os.path.join(
                                               full_file_path,
                                               "LEMS_Target.xml")

                                num_dx_configs += 1

                                dx_array.append(
                                    int(cell_morph_summary[elec_len]
                                        ["IntDivs"]))

                                break

                if num_dx_configs == len(elec_len_list):

                    found_all_compartmentalizations = True

            if not found_default:

                print(
                    "default configuration for %s analysis is not found; execution will terminate; set regenerate_nml2 to True to generate target dirs."
                    % cellModel)

                quit()

            if found_all_compartmentalizations:

                dx_array = list(np.sort(dx_array))

                maximum_int_divs = max(dx_array)

                print(
                    "testing the presence of cell configs with different levels of spatial discretization"
                )

                analyse_spiketime_vs_dx(dx_configs,
                                        if_params['simulator'],
                                        target_v,
                                        verbose=False,
                                        spike_threshold_mV=0,
                                        show_plot_already=show_plot_already,
                                        save_figure_to="%s/Dx_%s.png" %
                                        (save_to_path, cellModel),
                                        num_of_last_spikes=3)

                dx_curve = "Dx_%s" % cellModel

            else:
                print(
                    "not all of the target configurations were recompartmentalized; execution will terminate; set regenerate_nml2 to True to obtain all of the target configurations."
                )
                quit()

            if config_array[cellModel]['Analysis'] != config_array[cellModel][
                    'SpikeProfile']:

                pathToProfileConfig = "../" + config_array[cellModel][
                    'SpikeProfile'] + "/" + config_array[cellModel][
                        'SpikeProfile'] + "_default"

                original_LEMS_target = os.path.join(pathToProfileConfig,
                                                    "LEMS_Target.xml")

                if if_params['simulator'] == 'jNeuroML':
                    results = pynml.run_lems_with_jneuroml(
                        original_LEMS_target,
                        nogui=True,
                        load_saved_data=True,
                        plot=False,
                        verbose=False)
                if if_params['simulator'] == 'jNeuroML_NEURON':
                    results = pynml.run_lems_with_jneuroml_neuron(
                        original_LEMS_target,
                        nogui=True,
                        load_saved_data=True,
                        plot=False,
                        verbose=False)

                if 'SpikeProfileTag' in config_array[cellModel].keys():

                    tag = config_array[cellModel][
                        'SpikeProfileTag'] + "_0_wtime"

                else:

                    tag = config_array[cellModel]['OriginalTag']

                if 'SpikeProfileCellTag' in config_array[cellModel].keys(
                ) and 'SpikeProfileTag' in config_array[cellModel].keys():

                    target_v = "%s/0/%s/v" % (
                        config_array[cellModel]['SpikeProfileTag'],
                        config_array[cellModel]['SpikeProfileCellTag'])

                t = results['t']
                v = results[target_v]

                if compare_to_neuroConstruct:

                    print(
                        "will generate the comparison between the nC model and NeuroML2 model"
                    )

                    PlotNC_vs_NML2(
                        {
                            'NML2': [{
                                't': t,
                                'v': v
                            }],
                            'nC': [tag],
                            'subplotTitles': [
                                'NML2 versus nC model: simulations in NEURON with dt=%f'
                                % global_dt
                            ]
                        }, {
                            'cols': 8,
                            'rows': 5
                        },
                        legend=True,
                        show=show_plot_already,
                        save_to_file='%s/nC_vs_NML2_%s.png' %
                        (save_to_path,
                         config_array[cellModel]['SpikeProfile']),
                        nCcellPath=os.path.join(
                            save_to_path,
                            config_array[cellModel]['SpikeProfile']))

                    analysis_string2 = "nC_vs_NML2_%s" % config_array[
                        cellModel]['SpikeProfile']

                    analysis_header2 = "Comparison between the original nC model and NeuroML2 model: simulations in NEURON with dt=%f" % global_dt

                else:

                    print("will generate the plot for the NeuroML2 model")

                    generate_nml2_plot(
                        {
                            'NML2': [{
                                't': t,
                                'v': v
                            }],
                            'subplotTitles': [
                                'NeuroML2 model: simulations in NEURON with dt=%f'
                                % global_dt
                            ]
                        }, {
                            'cols': 8,
                            'rows': 5
                        },
                        show=False,
                        save_to_file='%s/NML2_%s.png' %
                        (save_to_path,
                         config_array[cellModel]['SpikeProfile']))

                    analysis_string2 = "NML2_%s" % config_array[cellModel][
                        'SpikeProfile']

                    analysis_header2 = "NeuroML2 model: simulations in NEURON with dt=%f" % global_dt

                cwd = os.getcwd()

                os.chdir(save_to_path)

                readme = ''' 
         
## Model: %(CellID)s

### Original neuroConstruct config ID: %(SpikeProfile)s

**%(AnalysisHeader2)s**

![Simulation](%(SpikeProfileCurve)s.png)

### Original neuroConstruct config ID: %(Config)s

**%(AnalysisHeader1)s**

![Simulation](%(nC_vs_NML2Curve)s.png)

**IF curve for the NeuroML2 model simulated in NEURON**

![Simulation](%(IFcurve)s.png)

**IV curve for the NeuroML2 model simulated in NEURON**

![Simulation](%(IVcurve)s.png)

**Spike times versus time step: the NeuroML2 model simulated in NEURON.
Dashed black lines - spike times at the %(Smallest_dt)s ms time step; Green - spike times at the following time steps (in ms): %(DtArray)s.**

![Simulation](%(DtCurve)s.png)

**Spike times versus spatial discretization: the NeuroML2 model simulated in NEURON.
Default value for the number of internal divs is %(default_divs)s.
Dashed black lines - spike times at the %(MaximumDivs)s internal divisions; Blue - spike times at the following values of internal divisions:
%(IntDivsArray)s.**

![Simulation](%(DxCurve)s.png)'''

                readme_file = open('README.md', 'w')

                readme_final = readme % {
                    "CellID": cellModel,
                    "IFcurve": IFcurve,
                    "IVcurve": IVcurve,
                    "Config": config_array[cellModel]['Analysis'],
                    "DtCurve": dt_curve,
                    "DxCurve": dx_curve,
                    "nC_vs_NML2Curve": analysis_string1,
                    "AnalysisHeader1": analysis_header1,
                    "SpikeProfileCurve": analysis_string2,
                    "AnalysisHeader2": analysis_header2,
                    "default_divs": default_num_of_comps,
                    "SpikeProfile": config_array[cellModel]['SpikeProfile'],
                    "Smallest_dt": smallest_dt,
                    "DtArray": dt_list,
                    "IntDivsArray": dx_array,
                    "MaximumDivs": maximum_int_divs
                }

                readme_file.write(readme_final)

                readme_file.close()

                os.chdir(cwd)

            else:

                cwd = os.getcwd()

                os.chdir(save_to_path)

                readme = ''' 
         
## Model: %(CellID)s

### Original neuroConstruct config ID: %(Config)s

**%(AnalysisHeader1)s**

![Simulation](%(nC_vs_NML2Curve)s.png)

**IF curve for the NeuroML2 model simulated in NEURON**

![Simulation](%(IFcurve)s.png)

**IV curve for the NeuroML2 model simulated in NEURON**

![Simulation](%(IVcurve)s.png)

**Spike times versus time step: the NeuroML2 model simulated in NEURON.
Dashed black lines - spike times at the %(Smallest_dt)s ms time step; Green - spike times for the following time steps (in ms): %(DtArray)s.**

![Simulation](%(DtCurve)s.png)

**Spike times versus spatial discretization: the NeuroML2 model simulated in NEURON.
Default value for the number of internal divs is %(default_divs)s.
Dashed black lines - spike times at the %(MaximumDivs)s internal divisions; Blue - spike times at the following values of internal divisions:
%(IntDivsArray)s.**

![Simulation](%(DxCurve)s.png)'''

                readme_file = open('README.md', 'w')

                readme_final = readme % {
                    "CellID": cellModel,
                    "IFcurve": IFcurve,
                    "IVcurve": IVcurve,
                    "Config": config_array[cellModel]['Analysis'],
                    "DtCurve": dt_curve,
                    "DxCurve": dx_curve,
                    "nC_vs_NML2Curve": analysis_string1,
                    "AnalysisHeader1": analysis_header1,
                    "default_divs": default_num_of_comps,
                    "Smallest_dt": smallest_dt,
                    "DtArray": dt_list,
                    "IntDivsArray": dx_array,
                    "MaximumDivs": maximum_int_divs
                }

                readme_file.write(readme_final)
                readme_file.close()
                os.chdir(cwd)

        cwd = os.getcwd()

        os.chdir(os.path.dirname(cwd))

        readme = ''' 
      
## Conversion of Thalamocortical cell models to NeuroML2

'''
        readme_file = open('README.md', 'w')

        for cell_index in range(0, len(cell_id_list)):

            readme_cell = '''
           
## Model: %(CellID)s

### Original neuroConstruct config ID: %(Config)s

**%(AnalysisHeader)s**

![Simulation](%(nC_vs_NML2Curve)s.png)

**IF curve for the NeuroML2 model simulated in NEURON**

![Simulation](%(IFcurve)s.png)'''

            readme_cell = readme_cell % {
                "CellID":
                cell_id_list[cell_index],
                "Config":
                config_list[cell_index],
                "AnalysisHeader":
                analysis_header_list[cell_index],
                "nC_vs_NML2Curve":
                os.path.join(cell_id_list[cell_index],
                             nC_vs_NML2Curve_list[cell_index]),
                "IFcurve":
                os.path.join(cell_id_list[cell_index],
                             IFcurve_list[cell_index])
            }

            readme = readme + readme_cell

        readme_file.write(readme)
        readme_file.close()
        os.chdir(cwd)