numGenerated = project.generatedCellPositions.getNumberInAllCellGroups()

print "Number of cells generated: " + str(numGenerated)

assert numGenerated == expectedNumberCells

print "Correct number of cells generated!"

nmlFileName = "GeneratedNeuroML.xml"


NeuroMLFileManager.saveNetworkStructureXML(project,
                                       File(nmlFileName),
                                       False,
                                       False,
                                       simConfig.getName(),
                                       "Physiological Units",
                                       NeuroMLConstants.NeuroMLVersion.NEUROML_VERSION_1,
                                       None);

nmlFileName = "GeneratedNeuroML2.xml"

NeuroMLFileManager.saveNetworkStructureXML(project,
                                       File(nmlFileName),
                                       False,
                                       False,
                                       simConfig.getName(),
                                       "Physiological Units",
                                       NeuroMLConstants.NeuroMLVersion.NEUROML_VERSION_2_BETA,
                                       None);
def SingleCellNML2generator(projString=" ",
                            ConfigDict={},
                            ElecLenList=[],
                            somaNseg=None,
                            savingDir=None):

    projFile = File(os.getcwd(), projString)
    pm = ProjectManager()
    compSummary = {}
    for config in ConfigDict.keys():

        project = pm.loadProject(projFile)

        nmlfm = NeuroMLFileManager(project)

        compSummary[config] = {}
        if " " in config:
            configPath = config.replace(" ", "_")
        else:
            configPath = config

        for maxElecLen in ElecLenList:
            compSummary[config][str(maxElecLen)] = {}
            cell = project.cellManager.getCell(ConfigDict[config])

            if maxElecLen > 0:

                info = CellTopologyHelper.recompartmentaliseCell(
                    cell, maxElecLen, project)
                print "Recompartmentalising cell %s" % ConfigDict[config]
                if somaNseg != None:
                    cell.getSegmentWithId(
                        0).getSection().setNumberInternalDivisions(somaNseg)
                if savingDir != None:
                    cellpath = r'../../NeuroML2/%s/%s/%s_%f' % (
                        savingDir, configPath, configPath, maxElecLen)
                else:
                    cellpath = r'../../NeuroML2/%s/%s_%f' % (
                        configPath, configPath, maxElecLen)

            else:
                if savingDir != None:
                    cellpath = r'../../NeuroML2/%s/%s/%s_default' % (
                        savingDir, configPath, configPath)
                else:
                    cellpath = r'../../NeuroML2/%s/%s_default' % (configPath,
                                                                  configPath)

            summary = str(cell.getMorphSummary())
            summary_string = summary.split("_")
            for feature in summary_string:
                feature_split = feature.split(":")
                compSummary[config][str(maxElecLen)][
                    feature_split[0]] = feature_split[1]

# the format of summary :  Segs:122_Secs:61_IntDivs:1458
            print("Will be printing a cell morphology summary")
            print compSummary[config][str(maxElecLen)]
            ######### it turns out that this does not save recompartmentalized cells - all saved cells have identical spatial discretization;
            ##### generateNeuroML2 receives the parent projFile but not the loaded project which is  modified by the CellTopologyHelper.recompartmentaliseCell()

            ##################### neuroConstruct block #############################################################################

            neuroConstructSeed = 1234
            verbose = True
            pm.doGenerate(config, neuroConstructSeed)

            while pm.isGenerating():
                if verbose:
                    print(
                        "Waiting for the project to be generated with Simulation Configuration: "
                        + config)
                    time.sleep(5)

            simConfig = project.simConfigInfo.getSimConfig(config)

            seed = 1234
            genDir = File(projFile.getParentFile(), "generatedNeuroML2")
            nmlfm.generateNeuroMLFiles(
                simConfig, NeuroMLConstants.NeuroMLVersion.getLatestVersion(),
                LemsConstants.LemsOption.LEMS_WITHOUT_EXECUTE_MODEL,
                OriginalCompartmentalisation(), seed, False, True, genDir,
                "GENESIS Physiological Units", False)

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

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

            src_files = os.listdir("../generatedNeuroML2/")

            for file_name in src_files:
                full_file_name = os.path.join("../generatedNeuroML2/",
                                              file_name)
                if (os.path.isfile(full_file_name)):
                    print("Moving generated NeuroML2 to files to %s" %
                          cellpath)
                    shutil.copy(full_file_name, cellpath)

    #with open("compSummary.json",'w') as fout:
    #json.dump(compSummary, fout)

    subprocess.call(["~/neuroConstruct/nC.sh -python RegenerateNml2.py -f"],
                    shell=True)

    #subprocess.call(["cp compSummary.json ~/Thalamocortical/NeuroML2/"],shell=True)

    quit()
def SingleCellNML2generator(projString=" ",ConfigDict={},ElecLenList=[],somaNseg=None,savingDir=None,shell=None):
    
    projFile=File(os.getcwd(),projString)
    
    pm=ProjectManager()
    
    for config in ConfigDict.keys():
    
        project=pm.loadProject(projFile)
        
        nmlfm = NeuroMLFileManager(project)
        
        compSummary={}
       
        compSummary[config]={}
        
        if " " in config:
           configPath=config.replace(" ","_")
        else:
           configPath=config
           
        if savingDir !=None:
        
           full_path_to_config=r'../%s/%s'%(savingDir,configPath)
           
        else:
        
           full_path_to_config=r'../%s'%(configPath)
        
        for maxElecLen in ElecLenList:
            compSummary[config][str(maxElecLen)]={}
            cell=project.cellManager.getCell(ConfigDict[config])
            
            if maxElecLen > 0:

	       info = CellTopologyHelper.recompartmentaliseCell(cell, maxElecLen, project)
	       print "Recompartmentalising cell %s"%ConfigDict[config]
	       if somaNseg != None:
	          cell.getSegmentWithId(0).getSection().setNumberInternalDivisions(somaNseg)
	       if savingDir !=None: 
	          cellpath = r'../%s/%s/%s_%f'%(savingDir,configPath,configPath,maxElecLen)
	       else:
	          cellpath = r'../%s/%s_%f'%(configPath,configPath,maxElecLen)
	       
	    else:
	       if savingDir !=None:
	          cellpath = r'../%s/%s/%s_default'%(savingDir,configPath,configPath)
	       else:
	          cellpath = r'../%s/%s_default'%(configPath,configPath)
	       
	    summary=str(cell.getMorphSummary()) 
	    summary_string=summary.split("_")
	    for feature in summary_string:
	        feature_split=feature.split(":")
	        compSummary[config][str(maxElecLen)][feature_split[0]]=feature_split[1]
	    # the format of summary :  Segs:122_Secs:61_IntDivs:1458
	    print("Will be printing a cell morphology summary")
	    print compSummary[config][str(maxElecLen)]
	    ######### it turns out that this does not save recompartmentalized cells - all saved cells have identical spatial discretization; 
	    ##### generateNeuroML2 receives the parent projFile but not the loaded project which is  modified by the CellTopologyHelper.recompartmentaliseCell()
	    
	    ##################### neuroConstruct block #############################################################################
	    
	    neuroConstructSeed=1234
	    verbose=True
	    pm.doGenerate(config, neuroConstructSeed)

            while pm.isGenerating():
                  if verbose: 
                     print("Waiting for the project to be generated with Simulation Configuration: "+config)
                     time.sleep(5)
                     
	    simConfig = project.simConfigInfo.getSimConfig(config)
	    
	    seed=1234
	    genDir = File(projFile.getParentFile(), "generatedNeuroML2")
            nmlfm.generateNeuroMLFiles(simConfig,
                                       NeuroMLConstants.NeuroMLVersion.getLatestVersion(),
                                       LemsConstants.LemsOption.LEMS_WITHOUT_EXECUTE_MODEL,
                                       OriginalCompartmentalisation(),
                                       seed,
                                       False,
                                       True,
                                       genDir,
                                       "GENESIS Physiological Units",
                                       False)
            
            ########################################################################################################################
            
            if not os.path.exists(cellpath):
               print("Creating a new directory %s"%cellpath)
               os.makedirs(cellpath)
            else:
               print("A directory %s already exists"%cellpath)
              
               
            src_files = os.listdir("../../neuroConstruct/generatedNeuroML2/")
            for file_name in src_files:
                full_file_name = os.path.join("../../neuroConstruct/generatedNeuroML2/", file_name)
                if (os.path.isfile(full_file_name)):
                   print("Moving generated NeuroML2 to files to %s"%cellpath)
                   shutil.copy(full_file_name, cellpath)
                      
        with open(os.path.join(full_path_to_config,"compSummary.json"),'w') as fout:
             json.dump(compSummary, fout)          
      
    if shell ==None:
       extension='sh'
    else:
       extension=shell      
    
    os.chdir("../../neuroConstruct/pythonScripts")  
      
    subprocess.call("%s/nC.%s -python ../../neuroConstruct/pythonScripts/RegenerateNml2.py -f"%(os.environ["NC_HOME"],extension),shell=True)
    
    os.chdir("../../NeuroML2/pythonScripts")