Exemplo n.º 1
0
 def load_project(self, fname):
     file = File(fname)
     print 'Loading project file: ', file.getAbsolutePath()
     pm = ProjectManager()
     project = pm.loadProject(file)
     print pm.status()
     return project
def testAll(argv=None):
    if argv is None:
        argv = sys.argv

    print "Loading project from "+ projFile.getCanonicalPath()
    
    projectManager = ProjectManager()
    project = projectManager.loadProject(projFile)

    assert(len(project.getProjectDescription())>0)

    assert(len(project.cellManager.getAllCells())>=7)

    assert(len(project.cellGroupsInfo.getAllCellGroupNames())>=4)

    assert(project.simulationParameters.getDt()-0.0125<=1e-6)

    assert(project.neuronSettings.isVarTimeStep())

    assert(project.neuronSettings.getDataSaveFormat().equals(NeuronSettings.DataSaveFormat.TEXT_NC))

    assert(project.simulationParameters.getTemperature()- 6.3<=1e-6)
    
    defSimConfig = project.simConfigInfo.getSimConfig("Default Simulation Configuration")
    assert(str(defSimConfig.getCellGroups())=='[CellGroup_1]')
    assert(project.cellGroupsInfo.getCellType("CellGroup_1")=='L5PC')


    print "\n**************************************"
    print "    All tests passed!"
    print "**************************************\n"
def testAll(argv=None):
    if argv is None:
        argv = sys.argv

    print "Loading project from "+ projFile.getCanonicalPath()
    
    projectManager = ProjectManager()
    project = projectManager.loadProject(projFile)

    assert(len(project.getProjectDescription())>0)

    assert(len(project.cellManager.getAllCells())>=6)

    #assert(project.proj3Dproperties.getDisplayOption() == Display3DProperties.DISPLAY_SOMA_SOLID_NEURITE_LINE)

    assert(abs(project.simulationParameters.getDt()-0.005)<=1e-9)
    
    assert(abs(project.simulationParameters.getTemperature() - 10) < 1e-6)

    assert(not project.neuronSettings.isVarTimeStep())

    assert(project.neuronSettings.getDataSaveFormat().equals(NeuronSettings.DataSaveFormat.TEXT_NC))

    #assert(project.genesisSettings.isSymmetricCompartments())

    assert(project.genesisSettings.isSIUnits())

    print "\n**************************************"
    print "    All tests passed!"
    print "**************************************\n"
Exemplo n.º 4
0
def testAll(argv=None):
    if argv is None:
        argv = sys.argv

    print "Loading project from " + projFile.getCanonicalPath()

    projectManager = ProjectManager()
    project = projectManager.loadProject(projFile)

    assert (len(project.getProjectDescription()) > 0)

    assert (len(project.cellManager.getAllCells()) >= 6)

    #assert(project.proj3Dproperties.getDisplayOption() == Display3DProperties.DISPLAY_SOMA_SOLID_NEURITE_LINE)

    assert (abs(project.simulationParameters.getDt() - 0.01) <= 1e-9)

    assert (abs(project.simulationParameters.getTemperature() - 6.3) < 1e-6)

    assert (not project.neuronSettings.isVarTimeStep())

    assert (project.neuronSettings.getDataSaveFormat().equals(
        NeuronSettings.DataSaveFormat.TEXT_NC))

    assert (project.genesisSettings.isSymmetricCompartments())

    assert (project.genesisSettings.isSIUnits())

    defSimConfig = project.simConfigInfo.getSimConfig(
        "Default Simulation Configuration")
    assert (str(defSimConfig.getCellGroups()) == '[baskets, pyramidals]')

    smallNetSimConfig = project.simConfigInfo.getSimConfig("SmallNetwork")

    assert (smallNetSimConfig.getCellGroups().size() == 2)
    assert (smallNetSimConfig.getNetConns().size() == 4)
    assert (smallNetSimConfig.getInputs().size() == 1)
    assert (project.cellGroupsInfo.getCellPackingAdapter(
        "pyramidals_48").getMaxNumberCells() == 48)
    assert (project.cellGroupsInfo.getCellPackingAdapter(
        "baskets_12").getMaxNumberCells() == 12)

    print "\n**************************************"
    print "    All tests passed!"
    print "**************************************\n"
Exemplo n.º 5
0
def testAll(argv=None):
    if argv is None:
        argv = sys.argv

    print "Loading project from " + projFile.getCanonicalPath()

    projectManager = ProjectManager()
    project = projectManager.loadProject(projFile)

    assert len(project.getProjectDescription()) > 0

    assert len(project.cellManager.getAllCells()) >= 22

    assert len(project.cellGroupsInfo.getAllCellGroupNames()) >= 6

    assert project.proj3Dproperties.getDisplayOption() == Display3DProperties.DISPLAY_SOMA_SOLID_NEURITE_LINE

    assert project.simulationParameters.getDt() - 0.025 <= 1e-6

    assert not project.neuronSettings.isVarTimeStep()

    assert project.neuronSettings.getDataSaveFormat().equals(NeuronSettings.DataSaveFormat.TEXT_NC)

    assert project.simulationParameters.getTemperature() == 34

    sci = project.simConfigInfo
    cgi = project.cellGroupsInfo

    assert cgi.getCellType("Channeltestgroup") == "Channeltest_Cell"
    assert cgi.getCellType("CMLtestGroup") == "CMLtest_Cell"
    assert cgi.getCellType("pyr_group") == "LarkumPyr"
    assert cgi.getCellType("pyrCML_group") == "LarkumPyr_NML"

    arrayListsIdentical(
        sci.getSimConfig("Default Simulation Configuration").getCellGroups(), ["Channeltestgroup", "CMLtestGroup"]
    )
    arrayListsIdentical(sci.getSimConfig("test_IClamp").getCellGroups(), ["pyr_group", "pyrCML_group"])
    arrayListsIdentical(sci.getSimConfig("background activity").getCellGroups(), ["pyr_group"])

    print "\n**************************************"
    print "    All tests passed!"
    print "**************************************\n"
 def __init__(self, pconf):
     configDict = pconf.parse_project_data()
     self.pconf = pconf
     self.logger = pconf.get_logger("neurosim")
     self.proj_path = self.pconf.local_path(configDict["proj_path"])
     self.pm = ProjectManager()
     
     projFile = File(self.proj_path)
     self.sim_timeout = self.pconf.get_float("sim_timeout", "Simulation")
     self.myProject = self.pm.loadProject(projFile)
     self.simConfig = self.myProject.simConfigInfo.getSimConfig(self.pconf.get("sim_config", "Simulation"))
Exemplo n.º 7
0
def testAll(argv=None):
    if argv is None:
        argv = sys.argv

    print "Loading project from "+ projFile.getCanonicalPath()
    
    projectManager = ProjectManager()
    project = projectManager.loadProject(projFile)

    assert(len(project.getProjectDescription())>0)

    assert(len(project.cellManager.getAllCells())>=6)

    #assert(project.proj3Dproperties.getDisplayOption() == Display3DProperties.DISPLAY_SOMA_SOLID_NEURITE_LINE)

    assert(abs(project.simulationParameters.getDt()-0.01)<=1e-9)
    
    assert(abs(project.simulationParameters.getTemperature() - 6.3) < 1e-6)

    assert(not project.neuronSettings.isVarTimeStep())

    assert(project.neuronSettings.getDataSaveFormat().equals(NeuronSettings.DataSaveFormat.TEXT_NC))

    assert(project.genesisSettings.isSymmetricCompartments())

    assert(project.genesisSettings.isSIUnits())
    
    defSimConfig = project.simConfigInfo.getSimConfig("Default Simulation Configuration")
    assert(str(defSimConfig.getCellGroups())=='[baskets, pyramidals]')
    
    smallNetSimConfig = project.simConfigInfo.getSimConfig("SmallNetwork")
    
    assert(smallNetSimConfig.getCellGroups().size()==2)
    assert(smallNetSimConfig.getNetConns().size()==4)
    assert(smallNetSimConfig.getInputs().size()==1)
    assert(project.cellGroupsInfo.getCellPackingAdapter("pyramidals_48").getMaxNumberCells()==48)
    assert(project.cellGroupsInfo.getCellPackingAdapter("baskets_12").getMaxNumberCells()==12)

    print "\n**************************************"
    print "    All tests passed!"
    print "**************************************\n"
Exemplo n.º 8
0
def testAll(argv=None):
    if argv is None:
        argv = sys.argv

    print "Loading project from " + projFile.getCanonicalPath()

    projectManager = ProjectManager()
    project = projectManager.loadProject(projFile)

    assert (len(project.getProjectDescription()) > 0)

    assert (len(project.cellManager.getAllCells()) >= 7)

    assert (len(project.cellGroupsInfo.getAllCellGroupNames()) >= 4)

    assert (project.simulationParameters.getDt() - 0.0125 <= 1e-6)

    assert (project.neuronSettings.isVarTimeStep())

    assert (project.neuronSettings.getDataSaveFormat().equals(
        NeuronSettings.DataSaveFormat.TEXT_NC))

    assert (project.simulationParameters.getTemperature() == 34)
    '''
    sci = project.simConfigInfo
    cgi = project.cellGroupsInfo

    assert(cgi.getCellType("Channeltestgroup") == "Channeltest_Cell")
    assert(cgi.getCellType("CMLtestGroup") == "CMLtest_Cell")
    assert(cgi.getCellType("pyr_group") == "LarkumPyr")
    assert(cgi.getCellType("pyrCML_group") == "LarkumPyr_NML")

    arrayListsIdentical(sci.getSimConfig("Default Simulation Configuration").getCellGroups(), ["Channeltestgroup", "CMLtestGroup"])
    arrayListsIdentical(sci.getSimConfig("test_IClamp").getCellGroups(), ["pyr_group", "pyrCML_group"])
    arrayListsIdentical(sci.getSimConfig("background activity").getCellGroups(), ["pyr_group"])
    '''

    print "\n**************************************"
    print "    All tests passed!"
    print "**************************************\n"
def testAll(argv=None):
    if argv is None:
        argv = sys.argv

    print "Loading project from "+ projFile.getCanonicalPath()
    
    projectManager = ProjectManager()
    project = projectManager.loadProject(projFile)

    assert(len(project.getProjectDescription())>0)

    assert(len(project.cellManager.getAllCells())>=7)

    assert(len(project.cellGroupsInfo.getAllCellGroupNames())>=4)

    assert(project.simulationParameters.getDt()-0.0125<=1e-6)

    assert(project.neuronSettings.isVarTimeStep())

    assert(project.neuronSettings.getDataSaveFormat().equals(NeuronSettings.DataSaveFormat.TEXT_NC))

    assert(project.simulationParameters.getTemperature() == 34)

    '''
    sci = project.simConfigInfo
    cgi = project.cellGroupsInfo

    assert(cgi.getCellType("Channeltestgroup") == "Channeltest_Cell")
    assert(cgi.getCellType("CMLtestGroup") == "CMLtest_Cell")
    assert(cgi.getCellType("pyr_group") == "LarkumPyr")
    assert(cgi.getCellType("pyrCML_group") == "LarkumPyr_NML")

    arrayListsIdentical(sci.getSimConfig("Default Simulation Configuration").getCellGroups(), ["Channeltestgroup", "CMLtestGroup"])
    arrayListsIdentical(sci.getSimConfig("test_IClamp").getCellGroups(), ["pyr_group", "pyrCML_group"])
    arrayListsIdentical(sci.getSimConfig("background activity").getCellGroups(), ["pyr_group"])
    '''

    print "\n**************************************"
    print "    All tests passed!"
    print "**************************************\n"
Exemplo n.º 10
0
def testAll(argv=None):
    if argv is None:
        argv = sys.argv

    print "Loading project from " + projFile.getCanonicalPath()

    projectManager = ProjectManager()
    project = projectManager.loadProject(projFile)

    assert (len(project.getProjectDescription()) > 0)

    assert (len(project.cellManager.getAllCells()) >= 1)

    #assert(project.proj3Dproperties.getDisplayOption() == Display3DProperties.DISPLAY_SOMA_SOLID_NEURITE_LINE)

    assert (abs(project.simulationParameters.getDt() - 0.02) <= 1e-9)

    assert (abs(project.simulationParameters.getTemperature() - 6.3) < 1e-6)

    assert (not project.neuronSettings.isVarTimeStep())

    assert (project.neuronSettings.getDataSaveFormat().equals(
        NeuronSettings.DataSaveFormat.TEXT_NC))

    assert (project.genesisSettings.isSIUnits())

    defSimConfig = project.simConfigInfo.getSimConfig(
        "Default Simulation Configuration")
    assert (str(defSimConfig.getCellGroups()) == '[SampleCellGroup]')

    assert (defSimConfig.getCellGroups().size() == 1)

    assert (defSimConfig.getInputs().size() == 1)

    print "\n**************************************"
    print "    All tests passed!"
    print "**************************************\n"
def testAll(argv=None):
    if argv is None:
        argv = sys.argv

    print "Loading project from "+ projFile.getCanonicalPath()
    
    projectManager = ProjectManager()
    project = projectManager.loadProject(projFile)

    assert(len(project.getProjectDescription())>0)

    assert(len(project.cellManager.getAllCells())>=1)

    #assert(project.proj3Dproperties.getDisplayOption() == Display3DProperties.DISPLAY_SOMA_SOLID_NEURITE_LINE)

    assert(abs(project.simulationParameters.getDt()-0.02)<=1e-9)
    
    assert(abs(project.simulationParameters.getTemperature() - 6.3) < 1e-6)

    assert(not project.neuronSettings.isVarTimeStep())

    assert(project.neuronSettings.getDataSaveFormat().equals(NeuronSettings.DataSaveFormat.TEXT_NC))

    assert(project.genesisSettings.isSIUnits())
    
    defSimConfig = project.simConfigInfo.getSimConfig("Default Simulation Configuration")
    assert(str(defSimConfig.getCellGroups())=='[SampleCellGroup]')
    
    assert(defSimConfig.getCellGroups().size()==1)
    
    assert(defSimConfig.getInputs().size()==1)
    

    print "\n**************************************"
    print "    All tests passed!"
    print "**************************************\n"
except ImportError:
    print "Note: this file should be run using ..\\nC.bat -python XXX.py' or './nC.sh -python XXX.py'"
    print "See http://www.neuroconstruct.org/docs/python.html for more details"
    quit()

from ucl.physiol.neuroconstruct.project import ProjectManager

from math import *


# Load an existing neuroConstruct project

projFile = File("TestPython/TestPython.neuro.xml")
print "Loading project from file: " + projFile.getAbsolutePath() + ", exists: " + str(projFile.exists())

pm = ProjectManager()
myProject = pm.loadProject(projFile)
print "Loaded project: " + myProject.getProjectName()


# Add a number of cells to the generatedCellPositions, connections to generatedNetworkConnections
# and electrical inputs to generatedElecInputs
numCells = 12

for i in range(0, numCells):
    x = 100 * sin(i * 2 * pi / numCells)
    y = 100 * cos(i * 2 * pi / numCells)
    myProject.generatedCellPositions.addPosition("SampleCellGroup", i, x, y, 0)

    if i != numCells - 1:
        myProject.generatedNetworkConnections.addSynapticConnection("NC1", i, i + 1)
Exemplo n.º 13
0
def testAll(argv=None):
    if argv is None:
        argv = sys.argv

    # Load an existing neuroConstruct project
    projFile = File("../CElegans.ncx")
    print "Loading project from file: " + projFile.getAbsolutePath()+", exists: "+ str(projFile.exists())

    pm = ProjectManager()
    project = pm.loadProject(projFile)
    print "Loaded project: " + project.getProjectName()


    defSimConfig = project.simConfigInfo.getDefaultSimConfig()
    cellsOnlySimConfig = project.simConfigInfo.getSimConfig("CellsOnly")
    pharyngealSimConfig = project.simConfigInfo.getSimConfig("PharyngealNeurons")
    mdl08SimConfig = project.simConfigInfo.getSimConfig("MDL08Connections")

    expectedNumberCells = 302 

    
    ##########################
    
    print "\n----- Test 1: Check number of cells in sim config "+defSimConfig.getName()+"..."


    pm.doGenerate(defSimConfig.getName(), 1234)

    while pm.isGenerating():
            print "Waiting for the project to be generated with Simulation Configuration: "+str(defSimConfig)
            sleep(2)

    numGenerated = project.generatedCellPositions.getNumberInAllCellGroups()

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

    assert numGenerated == expectedNumberCells

    print "Correct number of cells generated!"

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

    print "\n---- Test 2: number of cells in sim config "+cellsOnlySimConfig.getName()+"..."


    pm.doGenerate(cellsOnlySimConfig.getName(), 1234)

    while pm.isGenerating():
            print "Waiting for the project to be generated with Simulation Configuration: "+str(cellsOnlySimConfig)
            sleep(2)

    numGenerated = project.generatedCellPositions.getNumberInAllCellGroups()

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

    assert numGenerated == expectedNumberCells

    print "Correct number of cells generated!"
    
    ##########################

    filename = "../../CElegansNeuronTables.xls"
    print "\n---- Test 3: confirm settings in project match those in  "+filename+"..."

    from xlrd import open_workbook
    rb = open_workbook(filename)

    print "Opened Excel file: "+ filename

    confirmed = 0
    prefix = "NCXLS_"

    for row in range(1,rb.sheet_by_index(0).nrows):
      pre = rb.sheet_by_index(0).cell(row,0).value
      post = rb.sheet_by_index(0).cell(row,1).value
      syntype = rb.sheet_by_index(0).cell(row,2).value
      num = int(rb.sheet_by_index(0).cell(row,3).value)
      synclass = rb.sheet_by_index(0).cell(row,4).value

      #print "------------------------------------------\nConnection %i has %i from %s to %s (type: %s, synapse: %s)" %(row, num, pre, post, syntype, synclass)


      netConnName = prefix+pre+"_"+post

      if "GapJunction" in syntype:
            netConnName = netConnName + "_GJ"

      src = project.morphNetworkConnectionsInfo.getSourceCellGroup(netConnName)
      tgt = project.morphNetworkConnectionsInfo.getTargetCellGroup(netConnName)

      synlist = project.morphNetworkConnectionsInfo.getSynapseList(netConnName)

      #print synlist

      assert synclass == synlist[0].getSynapseType()

      if '_GJ' in synclass and synclass != 'Generic_GJ':
        print "Only allowed gap junction synapse is Generic_GJ, not "+synclass
        assert synclass == 'Generic_GJ'
      

      if not (src == pre and tgt == post):
          print "------------------------------------------\nConnection %i has %i from %s to %s (type: %s, synapse: %s)" %(row, num, pre, post, syntype, synclass)
          print "*** Couldn't find connection: %s, src: %s, tgt: %s"%(netConnName, src, tgt)
          assert src == pre
          assert tgt == post

      if src == tgt:
          print "------------------------------------------\nConnection %i has %i from %s to %s (type: %s, synapse: %s)" %(row, num, pre, post, syntype, synclass)
          print "*** This connection is from: %s, src: %s, tgt: %s, synaptic connection on same cell!!"%(netConnName, src, tgt)

      confirmed += 1

    print "Confirmed %i connections in project match spreadsheet"%confirmed

    havePrefix = 0
    allNetConnNames = project.morphNetworkConnectionsInfo.getAllSimpleNetConnNames()
    for name in allNetConnNames:
        if name.startswith(prefix):
            havePrefix +=1

    print "Project contains %i Network connections starting with %s"%(havePrefix, prefix)

    assert havePrefix == confirmed

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

    print "\n---- Test 4: number of cells in sim config "+pharyngealSimConfig.getName()+"..."


    pm.doGenerate(pharyngealSimConfig.getName(), 1234471)

    while pm.isGenerating():
            print "Waiting for the project to be generated with Simulation Configuration: "+str(pharyngealSimConfig)
            sleep(2)

    numCells = project.generatedCellPositions.getNumberInAllCellGroups()
    numConns = project.generatedNetworkConnections.getNumAllSynConns()

    print "Number of cells: %i, number of connections: %i"%(numCells,numConns)

    expectedCells = 20
    expectedNetConns = 269
    assert numCells == expectedCells
    assert numConns == expectedNetConns

    print "Correct number of cells & connections generated!"
    ##########################
    

    print "\n---- Test 5: number of cells in sim config "+mdl08SimConfig.getName()+"..."


    pm.doGenerate(mdl08SimConfig.getName(), 1234471)

    while pm.isGenerating():
            print "Waiting for the project to be generated with Simulation Configuration: "+str(mdl08SimConfig)
            sleep(2)

    numCells = project.generatedCellPositions.getNumberInAllCellGroups()
    numConns = project.generatedNetworkConnections.getNumAllSynConns()

    print "Number of cells: %i, number of connections: %i"%(numCells,numConns)

    expectedCells = 9
    expectedNetConns = 21
    assert numCells == expectedCells
    assert numConns == expectedNetConns

    print "Correct number of cells & connections generated!"

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

    

    print "\n---- Test 6: General neuroConstruct project settings..."


    assert(project.proj3Dproperties.getDisplayOption() == Display3DProperties.DISPLAY_SOMA_NEURITE_SOLID)

    assert(abs(project.simulationParameters.getDt()-0.025)<=1e-9)

    assert(not project.neuronSettings.isVarTimeStep())

    assert(project.neuronSettings.getDataSaveFormat().equals(NeuronSettings.DataSaveFormat.TEXT_NC))

    assert(abs(project.simulationParameters.getTemperature() - 20.0) < 1e-6)

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


    print "\n------------------------------------------All tests completed!\n"

    exit()
Exemplo n.º 14
0
def testAll(argv=None):
    if argv is None:
        argv = sys.argv

    # Load an existing neuroConstruct project
    projFile = File("../CElegans.ncx")
    print "Loading project from file: " + projFile.getAbsolutePath() + ", exists: " + str(projFile.exists())

    pm = ProjectManager()
    project = pm.loadProject(projFile)
    print "Loaded project: " + project.getProjectName()

    defSimConfig = project.simConfigInfo.getDefaultSimConfig()
    cellsOnlySimConfig = project.simConfigInfo.getSimConfig("CellsOnly")
    pharyngealSimConfig = project.simConfigInfo.getSimConfig("PharyngealNeurons")

    expectedNumberCells = 302

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

    print "\n----- Test 1: Check number of cells in sim config " + defSimConfig.getName() + "..."

    pm.doGenerate(defSimConfig.getName(), 1234)

    while pm.isGenerating():
        print "Waiting for the project to be generated with Simulation Configuration: " + str(defSimConfig)
        sleep(2)

    numGenerated = project.generatedCellPositions.getNumberInAllCellGroups()

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

    assert numGenerated == expectedNumberCells

    print "Correct number of cells generated!"

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

    print "\n---- Test 2: number of cells in sim config " + cellsOnlySimConfig.getName() + "..."

    pm.doGenerate(cellsOnlySimConfig.getName(), 1234)

    while pm.isGenerating():
        print "Waiting for the project to be generated with Simulation Configuration: " + str(cellsOnlySimConfig)
        sleep(2)

    numGenerated = project.generatedCellPositions.getNumberInAllCellGroups()

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

    assert numGenerated == expectedNumberCells

    print "Correct number of cells generated!"

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

    filename = "../../CElegansNeuronTables.xls"
    print "\n---- Test 3: confirm settings in project match those in  " + filename + "..."

    from xlrd import open_workbook

    rb = open_workbook(filename)

    print "Opened Excel file: " + filename

    confirmed = 0
    prefix = "NCXLS_"

    for row in range(1, rb.sheet_by_index(0).nrows):
        pre = rb.sheet_by_index(0).cell(row, 0).value
        post = rb.sheet_by_index(0).cell(row, 1).value
        syntype = rb.sheet_by_index(0).cell(row, 2).value
        num = int(rb.sheet_by_index(0).cell(row, 3).value)
        synclass = rb.sheet_by_index(0).cell(row, 4).value

        # print "------------------------------------------\nConnection %i has %i from %s to %s (type: %s, synapse: %s)" %(row, num, pre, post, syntype, synclass)

        netConnName = prefix + pre + "_" + post

        if "GapJunction" in syntype:
            netConnName = netConnName + "_GJ"

        src = project.morphNetworkConnectionsInfo.getSourceCellGroup(netConnName)
        tgt = project.morphNetworkConnectionsInfo.getTargetCellGroup(netConnName)

        if not (src == pre and tgt == post):
            print "------------------------------------------\nConnection %i has %i from %s to %s (type: %s, synapse: %s)" % (
                row,
                num,
                pre,
                post,
                syntype,
                synclass,
            )
            print "*** Couldn't find connection: %s, src: %s, tgt: %s" % (netConnName, src, tgt)
            assert src == pre
            assert tgt == post

        if src == tgt:
            print "------------------------------------------\nConnection %i has %i from %s to %s (type: %s, synapse: %s)" % (
                row,
                num,
                pre,
                post,
                syntype,
                synclass,
            )
            print "*** This connection is from: %s, src: %s, tgt: %s, synaptic connection on same cell!!" % (
                netConnName,
                src,
                tgt,
            )

        confirmed += 1

    print "Confirmed %i connections in project match spreadsheet" % confirmed

    havePrefix = 0
    allNetConnNames = project.morphNetworkConnectionsInfo.getAllSimpleNetConnNames()
    for name in allNetConnNames:
        if name.startswith(prefix):
            havePrefix += 1

    print "Project contains %i Network connections starting with %s" % (havePrefix, prefix)

    assert havePrefix == confirmed

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

    print "\n---- Test 4: number of cells in sim config " + pharyngealSimConfig.getName() + "..."

    pm.doGenerate(pharyngealSimConfig.getName(), 1234471)

    while pm.isGenerating():
        print "Waiting for the project to be generated with Simulation Configuration: " + str(pharyngealSimConfig)
        sleep(2)

    numCells = project.generatedCellPositions.getNumberInAllCellGroups()
    numConns = project.generatedNetworkConnections.getNumAllSynConns()

    print "Number of cells: %i, number of connections: %i" % (numCells, numConns)

    expectedCells = 20
    expectedNetConns = 269
    assert numCells == expectedCells
    assert numConns == expectedNetConns

    print "Correct number of cells & connections generated!"

    print "\n------------------------------------------All tests completed!\n"

    exit()
    set_tonic_GABA(work_dir, total_GABA_conductance_in_nS)

    # scale excitatory conductance by modifying the AMPA and NMDA
    # synaptic models. In general, the amplitude of the excitatory
    # conductances is inversely proportional to the number of
    # dendrites divided by 4, with the exc_cond_scaling parameter as
    # the proportionality constant. If this is set to zero, the
    # conductances are not scaled.
    if point.exc_cond_scaling:
        exc_scaling_factor = point.exc_cond_scaling / (float(point.n_grc_dend)/4)
        scale_excitatory_conductances(work_dir, exc_scaling_factor)

    # load project and initialise
    project_file = java.io.File(work_dir + "/" + project_filename)
    print ('Loading project from file: ' + project_file.getAbsolutePath() + ", exists: " + str(project_file.exists()))
    pm = ProjectManager(None, None)
    project = pm.loadProject(project_file)
    print 'Loaded project: ' + project.getProjectName()

    # load existing simulation configurations and set sim duration and a
    # couple of neuron options
    sim_config = project.simConfigInfo.getSimConfig(sim_config_name)
    sim_config.setSimDuration(point.sim_duration)
    project.neuronSettings.setNoConsole()
    project.neuronSettings.setCopySimFiles(1)

    # generate network
    generate_nC_network(point, pm, project, sim_config)

    # generate saves
    generate_nC_saves(point, project)
Exemplo n.º 16
0
except ImportError:
    print "Note: this file should be run using ..\\nC.bat -python XXX.py' or './nC.sh -python XXX.py'"
    print "See http://www.neuroconstruct.org/docs/python.html for more details"
    quit()

from ucl.physiol.neuroconstruct.project import ProjectManager

from math import *

# Load an existing neuroConstruct project

projFile = File("TestPython/TestPython.neuro.xml")
print "Loading project from file: " + projFile.getAbsolutePath(
) + ", exists: " + str(projFile.exists())

pm = ProjectManager()
myProject = pm.loadProject(projFile)
print "Loaded project: " + myProject.getProjectName()

# Add a number of cells to the generatedCellPositions, connections to generatedNetworkConnections
# and electrical inputs to generatedElecInputs
numCells = 12

for i in range(0, numCells):
    x = 100 * sin(i * 2 * pi / numCells)
    y = 100 * cos(i * 2 * pi / numCells)
    myProject.generatedCellPositions.addPosition("SampleCellGroup", i, x, y, 0)

    if i != numCells - 1:
        myProject.generatedNetworkConnections.addSynapticConnection(
            "NC1", i, i + 1)
Exemplo n.º 17
0
except ImportError:
    print "Note: this file should be run using ..\\nC.bat -python XXX.py' or './nC.sh -python XXX.py'"
    print "See http://www.neuroconstruct.org/docs/python.html for more details"
    quit()

from ucl.physiol.neuroconstruct.project import ProjectManager
from ucl.physiol.neuroconstruct.project import SimConfig

from math import *
from random import *

# Load an existing neuroConstruct project
projFile = File("../../CElegans.ncx")
print "Loading project from file: " + projFile.getAbsolutePath()+", exists: "+ str(projFile.exists())

pm = ProjectManager()
project = pm.loadProject(projFile)
print "Loaded project: " + project.getProjectName()


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

newSimConfig = "MDL08Connections"
newSimConfigDesc = "Generates a subset of the CElegans neural system consisting of the MDL08 muscle and motor neurons which connect to it. See https://github.com/openworm/OpenWorm/issues/53"
cells = ["AS1", "AS2", "DA1", "DA2", "DB1", "DD1", "SMDDL", "SMDDR", "MDL08"]


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

simConfig = SimConfig(newSimConfig, newSimConfigDesc)
Exemplo n.º 18
0
	def generateV_ICurve(self,
                         projFile,
                         simulator,
                         simConfig,
                         stimAmpLow, stimAmpInc, stimAmpHigh,
                         stimDur,
                         simDuration,
                         maxNumSimultaneousSims = 4):

			# Load neuroConstruct project

			print "Loading project from file: " + projFile.getAbsolutePath()+", exists: "+ str(projFile.exists())

			pm = ProjectManager()
			self.myProject = pm.loadProject(projFile)
			self.simulator = simulator

			simConfig = self.myProject.simConfigInfo.getSimConfig(simConfig)

			simConfig.setSimDuration(simDuration)

			pm.doGenerate(simConfig.getName(), self.neuroConstructSeed)

			while pm.isGenerating():
					print "Waiting for the project to be generated with Simulation Configuration: "+str(simConfig)
					time.sleep(2)

			numGenerated = self.myProject.generatedCellPositions.getNumberInAllCellGroups()

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

			simReferences = {}


			if numGenerated > 0:

					print "Generating scripts for simulator: %s..."%simulator

					if simulator == 'NEURON':
						self.myProject.neuronFileManager.setQuitAfterRun(1) # Remove this line to leave the NEURON sim windows open after finishing
						self.myProject.neuronSettings.setCopySimFiles(1) # 1 copies hoc/mod files to PySim_0 etc. and will allow multiple sims to run at once
						self.myProject.neuronSettings.setGraphicsMode(0) # 0 hides graphs during execution
                        
					if simulator == 'GENESIS':
						self.myProject.genesisFileManager.setQuitAfterRun(1) # Remove this line to leave the NEURON sim windows open after finishing
						self.myProject.genesisSettings.setCopySimFiles(1) # 1 copies hoc/mod files to PySim_0 etc. and will allow multiple sims to run at once
						self.myProject.genesisSettings.setGraphicsMode(0) # 0 hides graphs during execution


					stimAmp = stimAmpLow

					ADD_TO_BEFORE_INIT = self.myProject.neuronSettings.getNativeBlock(NativeCodeLocation.BEFORE_INITIAL)
					ADD_TO_RECORD_I = self.myProject.neuronSettings.getNativeBlock(NativeCodeLocation.AFTER_SIMULATION)
					ADD_TO_START_FINITIALIZE = self.myProject.neuronSettings.getNativeBlock(NativeCodeLocation.START_FINITIALIZE)

					while stimAmp <= stimAmpHigh:

							while (len(self.simsRunning)>=maxNumSimultaneousSims):
									print "Sims currently running: "+str(self.simsRunning)
									print "Waiting..."
									time.sleep(3) # wait a while...
									self.updateSimsRunning()


							simRef = "PySim_"+str(float(stimAmp))

							print "Going to run simulation: "+simRef

							########  Adjusting the amplitude of the Voltage clamp ###############

                                                        TEXT_BEFORE_CREATION = "objref clampobj" + "\n" + "objref record_current" + "\n" + "objref data_save" + "\n"

                                                        # TEXT_BEFORE_INIT = "GranuleCell_mod_tonic[0].Soma {\n" + "clampobj = new SEClamp(0.5)\n" + "clampobj.dur1 = 150.0" + "\n" + "clampobj.amp1 = -100.0" + "\n" + "clampobj.dur2 = " + str(stimDur) + "\n" + "clampobj.amp2 = " + str(stimAmp) + "\n" + "clampobj.dur3 = 150.0" + "\n" + "clampobj.amp3 = -100.0" + "\n" + "clampobj.rs = 0.00001\n " + "}\n" # This should do the trick

                                                        # TEXT_BEFORE_INIT = TEXT_BEFORE_INIT + ADD_TO_BEFORE_INIT

                                                        TEXT_START_FINITIALIZE = "GranuleCell_mod_tonic[0].Soma {\n" + "clampobj = new SEClamp(0.5)\n" + "clampobj.dur1 = 150.0" + "\n" + "clampobj.amp1 = -100.0" + "\n" + "clampobj.dur2 = " + str(stimDur) + "\n" + "clampobj.amp2 = " + str(stimAmp) + "\n" + "clampobj.dur3 = 150.0" + "\n" + "clampobj.amp3 = -40.0" + "\n" + "clampobj.rs = 0.00001\n" + "record_current = new Vector()" + "\n" + "record_current.record(&clampobj.i)" + "\n" + "}\n" #This should do the trick

                                                        TEXT_START_FINITIALIZE = TEXT_START_FINITIALIZE + ADD_TO_START_FINITIALIZE

                                                        TEXT_TO_RECORD_I = """data_save = new File() \n""" + """strdef filename \n""" + """sprint(filename, """" + self.myProject.getProjectMainDirectory().getAbsolutePath() + """/simulations/current%.3f.txt", clampobj.amp2) \n""" + """data_save.wopen(filename) \n""" + """record_current.printf(data_save) \n""" + """data_save.close() \n"""

                                                        TEXT_TO_RECORD_I = TEXT_TO_RECORD_I + ADD_TO_RECORD_I

                                                        self.myProject.neuronSettings.setNativeBlock(NativeCodeLocation.BEFORE_CELL_CREATION, TEXT_BEFORE_CREATION)
                                                        # self.myProject.neuronSettings.setNativeBlock(NativeCodeLocation.BEFORE_INITIAL, TEXT_BEFORE_INIT)
                                                        self.myProject.neuronSettings.setNativeBlock(NativeCodeLocation.START_FINITIALIZE, TEXT_START_FINITIALIZE)
                                                        self.myProject.neuronSettings.setNativeBlock(NativeCodeLocation.AFTER_SIMULATION, TEXT_TO_RECORD_I)

					
							print "Next stim: "+ str(stimAmp)

							self.myProject.simulationParameters.setReference(simRef)

							if simulator == "NEURON":
									self.myProject.neuronFileManager.generateTheNeuronFiles(simConfig,
																							None,
																							NeuronFileManager.RUN_HOC,
																							self.simulatorSeed)

									print "Generated NEURON files for: "+simRef

									compileProcess = ProcessManager(self.myProject.neuronFileManager.getMainHocFile())

									compileSuccess = compileProcess.compileFileWithNeuron(0,0)

									print "Compiled NEURON files for: "+simRef

									if compileSuccess:
													pm.doRunNeuron(simConfig)
													print "Set running simulation: "+simRef
													self.simsRunning.append(simRef)

							if simulator == "GENESIS":
									compartmentalisation = GenesisCompartmentalisation()

									self.myProject.genesisFileManager.generateTheGenesisFiles(simConfig,
																							None,
																							compartmentalisation,
																							self.simulatorSeed)
									print "Generated GENESIS files for: "+simRef

									pm.doRunGenesis(simConfig)
									print "Set running simulation: "+simRef
									self.simsRunning.append(simRef)

							time.sleep(1) # Wait for sim to be kicked off
							simReferences[simRef] = stimAmp
							stimAmp = stimAmp +stimAmpInc

					print
					print "Finished running "+str(len(simReferences))+" simulations for project "+ projFile.getAbsolutePath()
					print "These can be loaded and replayed in the previous simulation browser in the GUI"
					print

			while (len(self.simsRunning)>0):
					print "Sims currently running: "+str(self.simsRunning)
					print "Waiting..."
					time.sleep(4) # wait a while...
					self.updateSimsRunning()

			#simReferences = {'PySim_0.3':0.3,'PySim_0.4':0.4,'PySim_0.5':0.5}

			plotFrameVI = PlotManager.getPlotterFrame("V-I curve from project: "+str(self.myProject.getProjectFile())+" on "+simulator , 1, 1)


			plotFrameVI.setViewMode(PlotCanvas.INCLUDE_ORIGIN_VIEW)

			info = "V-I curve for Simulation Configuration: "+str(simConfig)

			dataSet = DataSet(info, info, "mV", "nA", "Voltage", "Current")
			dataSet.setGraphFormat(PlotCanvas.USE_CIRCLES_FOR_PLOT)

			simList = simReferences.keys()
			simList.sort()

			for sim in simList:

					simDir = File(projFile.getParentFile(), "/neuroConstruct/models/Dan_GranCell/simulations/"+sim)
					print
					print "--- Reloading data from simulation in directory: %s"%simDir.getCanonicalPath()
					try:
							simData = SimulationData(simDir)
							simData.initialise()
							print "Data loaded: "
							print simData.getAllLoadedDataStores()
							times = simData.getAllTimes()
							cellSegmentRef = simConfig.getCellGroups().get(0)+"_0"

							cfilename = "E:/neuroConstruct/models/Dan_GranCell/simulations/" + sim + "/current.txt"
							trace = "E:/neuroConstruct/models/Dan_GranCell/simulations/" + sim + ".txt"
							# cFILE = open(cfilename, "r")
							
							
							strom = 0.0
							
							volts = simData.getVoltageAtAllTimes(cellSegmentRef)
							

							traceInfo = "Voltage at: %s in simulation: %s"%(cellSegmentRef, sim)

							stimAmp = simReferences[sim]
							print "Current at %f mV in sim %s: %f"%(stimAmp, sim, float(strom))
							
							dataSet.addPoint(stimAmp,float(strom))
					except:
							print "Error analysing simulation data from: %s"%simDir.getCanonicalPath()
							print sys.exc_info()[0]


			plotFrameVI.addDataSet(dataSet)
Exemplo n.º 19
0
from ucl.physiol.neuroconstruct.gui.plotter import PlotManager
from ucl.physiol.neuroconstruct.gui.plotter import PlotCanvas
from ucl.physiol.neuroconstruct.dataset import DataSet
from math import *
import time
import shutil
import random
import os
import subprocess

# Load the original project
projName = "LarkumEtAl2009"
projFile = File("/home/matteo/neuroConstruct/models/"+projName+"/"+projName+".ncx")

print "Loading project from file: " + projFile.getAbsolutePath()+", exists: "+ str(projFile.exists())
pm = ProjectManager()
myProject = pm.loadProject(projFile)
simConfig = myProject.simConfigInfo.getSimConfig("Default Simulation Configuration")#
randomseed = random.randint(1000,5000)
pm.doGenerate(simConfig.getName(),  randomseed)
while pm.isGenerating():
    print "Waiting for the project to be generated..."
    time.sleep(2)    
numGenerated = myProject.generatedCellPositions.getNumberInAllCellGroups()

simsRunning = []
def updateSimsRunning():
    simsFinished = []
    for sim in simsRunning:
        timeFile = File(myProject.getProjectMainDirectory(), "simulations/"+sim+"/time.dat")
        #print "Checking file: "+timeFile.getAbsolutePath() +", exists: "+ str(timeFile.exists())
Exemplo n.º 20
0
def runColumnSimulation(simConfig="TempSimConfig",
                        simDuration=100,
                        simDt=0.025,
                        neuroConstructSeed=1234,
                        simulatorSeed=1234,
                        simulators=["NEURON"],
                        simRefPrefix="Net_",
                        suggestedRemoteRunTime=120,
                        defaultSynapticDelay=0.05,
                        mpiConf=MpiSettings.LOCAL_SERIAL,
                        scaleCortex=0.1,
                        scaleThalamus=0,
                        gabaScaling=1,
                        l4ssAmpaScaling=1,
                        l5PyrGapScaling=1,
                        inNrtTcrNmdaScaling=1,
                        pyrSsNmdaScaling=1,
                        deepBiasCurrent=-1,
                        maxElecLenFRB=0.01,
                        maxElecLenRS=0.01,
                        maxElecLenIN=0.01,
                        maxElecLenSS=0.01,
                        somaNseg=-1,
                        varTimestepNeuron=False,
                        verbose=True,
                        runInBackground=False):

    print "Running new column simulation..."

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

    # Full column populations

    numFRB = 50  #   full model: 50
    numRS = 1000  #   full model: 1000
    numSupBask = 90  #   full model: 90
    numSupAxAx = 90  #   full model: 90
    numSupLTS = 90  #   full model: 90
    numL4SpinStell = 240  #   full model: 240
    numL5TuftIB = 800  #   full model: 800
    numL5TuftRS = 200  #   full model: 200
    numDeepBask = 100  #   full model: 100
    numDeepAxAx = 100  #   full model: 100
    numDeepLTS = 100  #   full model: 100
    numL6NonTuftRS = 500  #   full model: 500

    numTCR = 100  #   full model: 100
    numnRT = 100  #   full model: 100

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

    ### Load neuroConstruct project

    import datetime

    start = datetime.datetime.now()

    print "Loading project %s from at %s " % (projFile.getCanonicalPath(),
                                              start.strftime("%Y-%m-%d %H:%M"))

    pm = ProjectManager()
    project = pm.loadProject(projFile)

    ### Set duration & timestep & simulation configuration

    project.simulationParameters.setDt(simDt)
    simConfig = project.simConfigInfo.getSimConfig(simConfig)
    simConfig.setSimDuration(simDuration)

    ### Set simulation reference

    index = 0
    simRef = "%s%i" % (simRefPrefix, index)

    while File("%s/simulations/%s_N" %
               (project.getProjectMainDirectory().getCanonicalPath(),
                simRef)).exists():
        simRef = "%s%i" % (simRefPrefix, index)
        index = index + 1

    project.simulationParameters.setReference(simRef)

    ### Change num in each cell group

    numFRB = int(scaleCortex * numFRB)
    numRS = int(scaleCortex * numRS)
    numSupBask = int(scaleCortex * numSupBask)
    numSupAxAx = int(scaleCortex * numSupAxAx)
    numSupLTS = int(scaleCortex * numSupLTS)
    numL4SpinStell = int(scaleCortex * numL4SpinStell)
    numL5TuftIB = int(scaleCortex * numL5TuftIB)
    numL5TuftRS = int(scaleCortex * numL5TuftRS)
    numDeepBask = int(scaleCortex * numDeepBask)
    numDeepAxAx = int(scaleCortex * numDeepAxAx)
    numDeepLTS = int(scaleCortex * numDeepLTS)
    numL6NonTuftRS = int(scaleCortex * numL6NonTuftRS)

    numTCR = int(scaleThalamus * numTCR)
    numnRT = int(scaleThalamus * numnRT)

    project.cellGroupsInfo.getCellPackingAdapter(
        "CG3D_L23PyrFRB").setMaxNumberCells(
            numFRB)  # Note only works if RandomCellPackingAdapter
    project.cellGroupsInfo.getCellPackingAdapter(
        "CG3D_L23PyrRS").setMaxNumberCells(numRS)
    project.cellGroupsInfo.getCellPackingAdapter(
        "CG3D_SupBask").setMaxNumberCells(numSupBask)
    project.cellGroupsInfo.getCellPackingAdapter(
        "CG3D_SupAxAx").setMaxNumberCells(numSupAxAx)
    project.cellGroupsInfo.getCellPackingAdapter(
        "CG3D_SupLTS").setMaxNumberCells(numSupLTS)
    project.cellGroupsInfo.getCellPackingAdapter(
        "CG3D_L4SpinStell").setMaxNumberCells(numL4SpinStell)
    project.cellGroupsInfo.getCellPackingAdapter(
        "CG3D_L5TuftIB").setMaxNumberCells(numL5TuftIB)
    project.cellGroupsInfo.getCellPackingAdapter(
        "CG3D_L5TuftRS").setMaxNumberCells(numL5TuftRS)
    project.cellGroupsInfo.getCellPackingAdapter(
        "CG3D_DeepBask").setMaxNumberCells(numDeepBask)
    project.cellGroupsInfo.getCellPackingAdapter(
        "CG3D_DeepAxAx").setMaxNumberCells(numDeepAxAx)
    project.cellGroupsInfo.getCellPackingAdapter(
        "CG3D_DeepLTS").setMaxNumberCells(numDeepLTS)
    project.cellGroupsInfo.getCellPackingAdapter(
        "CG3D_L6NonTuftRS").setMaxNumberCells(numL6NonTuftRS)
    project.cellGroupsInfo.getCellPackingAdapter("CG3D_TCR").setMaxNumberCells(
        numTCR)
    project.cellGroupsInfo.getCellPackingAdapter("CG3D_nRT").setMaxNumberCells(
        numnRT)

    ### Change weights in synapses/gap junctions

    for netConnName in simConfig.getNetConns():

        if gabaScaling != 1:

            SimulationsInfo.addExtraSimProperty("gabaWeightScaling",
                                                str(gabaScaling))
            synList = project.morphNetworkConnectionsInfo.getSynapseList(
                netConnName)

            for index in range(0, len(synList)):
                synName = project.morphNetworkConnectionsInfo.getSynapseList(
                    netConnName).get(index).getSynapseType()
                if synName.count("GABAA") > 0:
                    print "Changing synaptic weight for syn %s in net conn %s by factor %f" % (
                        synName, netConnName, gabaScaling)

                    project.morphNetworkConnectionsInfo.getSynapseList(
                        netConnName).get(index).setWeightsGenerator(
                            NumberGenerator(gabaScaling))

        if l4ssAmpaScaling != 1:

            SimulationsInfo.addExtraSimProperty("l4ssAmpaScaling",
                                                str(l4ssAmpaScaling))
            synList = project.morphNetworkConnectionsInfo.getSynapseList(
                netConnName)

            for index in range(0, len(synList)):
                synName = project.morphNetworkConnectionsInfo.getSynapseList(
                    netConnName).get(index).getSynapseType()
                if synName.count("Syn_AMPA_L4SS_L4SS") > 0:
                    print "Changing synaptic weight for syn %s in net conn %s by factor %f" % (
                        synName, netConnName, l4ssAmpaScaling)

                    project.morphNetworkConnectionsInfo.getSynapseList(
                        netConnName).get(index).setWeightsGenerator(
                            NumberGenerator(l4ssAmpaScaling))

        if l5PyrGapScaling != 1:

            SimulationsInfo.addExtraSimProperty("l5PyrGapScaling",
                                                str(l5PyrGapScaling))
            synList = project.morphNetworkConnectionsInfo.getSynapseList(
                netConnName)

            for index in range(0, len(synList)):
                synName = project.morphNetworkConnectionsInfo.getSynapseList(
                    netConnName).get(index).getSynapseType()
                tgtCG = project.morphNetworkConnectionsInfo.getTargetCellGroup(
                    netConnName)
                if synName.count("Syn_Elect_DeepPyr_DeepPyr"
                                 ) > 0 and tgtCG.count("CG3D_L5") > 0:
                    print "Changing synaptic weight for syn %s in net conn %s by factor %f" % (
                        synName, netConnName, l5PyrGapScaling)

                    project.morphNetworkConnectionsInfo.getSynapseList(
                        netConnName).get(index).setWeightsGenerator(
                            NumberGenerator(l5PyrGapScaling))

        if inNrtTcrNmdaScaling != 1:

            SimulationsInfo.addExtraSimProperty("inNrtTcrNmdaScaling",
                                                str(inNrtTcrNmdaScaling))
            synList = project.morphNetworkConnectionsInfo.getSynapseList(
                netConnName)

            for index in range(0, len(synList)):
                synName = project.morphNetworkConnectionsInfo.getSynapseList(
                    netConnName).get(index).getSynapseType()
                if synName.count("NMDA") > 0 and (
                        synName.endswith("_IN") > 0
                        or synName.endswith("_DeepIN") > 0
                        or synName.endswith("_SupIN") > 0
                        or synName.endswith("_SupFS") > 0
                        or synName.endswith("_DeepFS") > 0
                        or synName.endswith("_SupLTS") > 0
                        or synName.endswith("_DeepLTS") > 0
                        or synName.endswith("_nRT") > 0
                        or synName.endswith("_TCR") > 0):

                    print "Changing synaptic weight for syn %s in net conn %s by factor %f" % (
                        synName, netConnName, inNrtTcrNmdaScaling)

                    project.morphNetworkConnectionsInfo.getSynapseList(
                        netConnName).get(index).setWeightsGenerator(
                            NumberGenerator(inNrtTcrNmdaScaling))

        if pyrSsNmdaScaling != 1:

            SimulationsInfo.addExtraSimProperty("pyrSsNmdaScaling",
                                                str(pyrSsNmdaScaling))
            synList = project.morphNetworkConnectionsInfo.getSynapseList(
                netConnName)

            for index in range(0, len(synList)):
                synName = project.morphNetworkConnectionsInfo.getSynapseList(
                    netConnName).get(index).getSynapseType()
                if synName.count("NMDA") > 0 and (
                        synName.endswith("_SupPyr") > 0
                        or synName.endswith("_DeepPyr") > 0
                        or synName.endswith("_L4SS") > 0
                        or synName.endswith("_L5Pyr") > 0
                        or synName.endswith("_L5RS") > 0
                        or synName.endswith("_L5IB") > 0
                        or synName.endswith("_L6NT") > 0
                        or synName.endswith("_Pyr") > 0):

                    print "Changing synaptic weight for syn %s in net conn %s by factor %f" % (
                        synName, netConnName, pyrSsNmdaScaling)

                    project.morphNetworkConnectionsInfo.getSynapseList(
                        netConnName).get(index).setWeightsGenerator(
                            NumberGenerator(pyrSsNmdaScaling))

    ### Change bias currents

    for inputName in simConfig.getInputs():

        stim = project.elecInputInfo.getStim(inputName)

        if deepBiasCurrent >= 0:

            if stim.getElectricalInput().TYPE == "IClamp" and (
                    stim.getCellGroup() == "CG3D_L5TuftIB"
                    or stim.getCellGroup() == "CG3D_L5TuftRS"
                    or stim.getCellGroup() == "CG3D_L6NonTuftRS"):

                print "Changing offset current in %s to %f" % (
                    stim.getCellGroup(), deepBiasCurrent)

                stim.setAmp(NumberGenerator(deepBiasCurrent))
                project.elecInputInfo.updateStim(stim)

    ### Change spatial discretisation of some cells. This will impact accuracy & simulation speed

    if maxElecLenFRB > 0:
        frbCell = project.cellManager.getCell("L23PyrFRB_varInit")
        info = CellTopologyHelper.recompartmentaliseCell(
            frbCell, maxElecLenFRB, project)
        print "Recompartmentalised FRB cell: " + info
        if somaNseg > 0:
            frbCell.getSegmentWithId(
                0).getSection().setNumberInternalDivisions(somaNseg)

    if maxElecLenRS > 0:
        rsCell = project.cellManager.getCell("L23PyrRS")
        info = CellTopologyHelper.recompartmentaliseCell(
            rsCell, maxElecLenRS, project)
        print "Recompartmentalised RS cell: " + info
        if somaNseg > 0:
            rsCell.getSegmentWithId(0).getSection().setNumberInternalDivisions(
                somaNseg)

    if maxElecLenIN > 0:
        inCells = [
            "SupBasket", "SupAxAx", "SupLTSInter", "DeepBasket", "DeepAxAx",
            "DeepLTSInter"
        ]

        for inCellName in inCells:
            inCell = project.cellManager.getCell(inCellName)
            info = CellTopologyHelper.recompartmentaliseCell(
                inCell, maxElecLenIN, project)
            print "Recompartmentalised " + inCellName + " cell: " + info
            if somaNseg > 0:
                inCell.getSegmentWithId(
                    0).getSection().setNumberInternalDivisions(somaNseg)

    ### Change parallel configuration

    mpiSettings = MpiSettings()
    simConfig.setMpiConf(mpiSettings.getMpiConfiguration(mpiConf))
    print "Parallel configuration: " + str(simConfig.getMpiConf())

    if suggestedRemoteRunTime > 0:
        project.neuronFileManager.setSuggestedRemoteRunTime(
            suggestedRemoteRunTime)
        project.genesisFileManager.setSuggestedRemoteRunTime(
            suggestedRemoteRunTime)

    ### Change synaptic delay associated with each net conn

    for netConnName in simConfig.getNetConns():
        if netConnName.count("gap") == 0:
            print "Changing synaptic delay in %s to %f" % (
                netConnName, defaultSynapticDelay)
            delayGen = NumberGenerator(defaultSynapticDelay)
            for synProps in project.morphNetworkConnectionsInfo.getSynapseList(
                    netConnName):
                synProps.setDelayGenerator(delayGen)

    # defaultSynapticDelay will be recorded in simulation.props and listed in SimulationBrowser GUI
    SimulationsInfo.addExtraSimProperty("defaultSynapticDelay",
                                        str(defaultSynapticDelay))

    ### Generate network structure in neuroConstruct

    pm.doGenerate(simConfig.getName(), neuroConstructSeed)

    while pm.isGenerating():
        print "Waiting for the project to be generated with Simulation Configuration: " + str(
            simConfig)
        sleep(2)

    print "Generated %i cells in %i cell groups" % (
        project.generatedCellPositions.getNumberInAllCellGroups(),
        project.generatedCellPositions.getNumberNonEmptyCellGroups())
    print "Generated %i instances in %i network connections" % (
        project.generatedNetworkConnections.getNumAllSynConns(),
        project.generatedNetworkConnections.getNumNonEmptyNetConns())
    print "Generated %i instances in %i elect inputs" % (
        project.generatedElecInputs.getNumberSingleInputs(),
        project.generatedElecInputs.getNonEmptyInputRefs().size())

    if simulators.count("NEURON") > 0:

        simRefN = simRef + "_N"
        project.simulationParameters.setReference(simRefN)

        nc.generateAndRunNeuron(project,
                                pm,
                                simConfig,
                                simRefN,
                                simulatorSeed,
                                verbose=verbose,
                                runInBackground=runInBackground,
                                varTimestep=varTimestepNeuron)

        sleep(2)  # wait a while before running GENESIS...

    if simulators.count("GENESIS") > 0:

        simRefG = simRef + "_G"
        project.simulationParameters.setReference(simRefG)

        nc.generateAndRunGenesis(project,
                                 pm,
                                 simConfig,
                                 simRefG,
                                 simulatorSeed,
                                 verbose=verbose,
                                 runInBackground=runInBackground)

        sleep(2)  # wait a while before running MOOSE...

    if simulators.count("MOOSE") > 0:

        simRefM = simRef + "_M"
        project.simulationParameters.setReference(simRefM)

        nc.generateAndRunMoose(project,
                               pm,
                               simConfig,
                               simRefM,
                               simulatorSeed,
                               verbose=verbose,
                               runInBackground=runInBackground)

        sleep(2)  # wait a while before running GENESIS...

    print "Finished running all sims, shutting down..."

    stop = datetime.datetime.now()
    print
    print "Started: %s, finished: %s" % (start.strftime("%Y-%m-%d %H:%M"),
                                         stop.strftime("%Y-%m-%d %H:%M"))
    print
Exemplo n.º 21
0
def testAll(argv=None):
    if argv is None:
        argv = sys.argv

    print "Loading project from "+ projFile.getCanonicalPath()
    
    projectManager = ProjectManager()
    project = projectManager.loadProject(projFile)

    assert(len(project.getProjectDescription())>0)

    assert(len(project.cellManager.getAllCells())>=22)

    assert(len(project.cellGroupsInfo.getAllCellGroupNames())>=36)


    synSetupFile = open("netbuild/makeSyns.sh", 'r')

    for line in synSetupFile:
        line = line.strip()

        if len(line)>0 and not line.startswith("#"):
            words = line.split()
            if len(words)>=6 and words[2].startswith("Syn_"):
                synName = words[2]
                cm = project.cellMechanismInfo.getCellMechanism(synName)
                print "Checked syn %s"%cm.getInstanceName()


    netConnList = open("netbuild/netConnList", 'r')



    for line in netConnList:
        line = line.strip()

        if len(line)>0 and not line.startswith("#"):

            #print "\n\n---- Deciphering line: "+ line
            words = line.split()
            source = words[0]
            target = words[1]
            syns = words[2].strip("[]").split(",")
            netConnName = "NC3D_"+source[5:]+"_"+target[5:]
            assert(source == project.morphNetworkConnectionsInfo.getSourceCellGroup(netConnName))
            assert(target == project.morphNetworkConnectionsInfo.getTargetCellGroup(netConnName))
            print "Checked %s"%netConnName


    assert(project.proj3Dproperties.getDisplayOption() == Display3DProperties.DISPLAY_SOMA_SOLID_NEURITE_LINE)

    assert(abs(project.simulationParameters.getDt()-0.025)<=1e-9)

    assert(not project.neuronSettings.isVarTimeStep())

    assert(project.neuronSettings.isForceCorrectInit())

    assert(project.neuronSettings.getDataSaveFormat().equals(NeuronSettings.DataSaveFormat.TEXT_NC))

    assert(not project.genesisSettings.isSymmetricCompartments())

    assert(project.genesisSettings.isPhysiologicalUnits())

    print "\n**************************************"
    print "    All tests passed!"
    print "**************************************\n"
Exemplo n.º 22
0
def runColumnSimulation(simConfig=    			"TempSimConfig",
		        simDuration = 			100,
			simDt = 			0.025, 
			neuroConstructSeed = 		1234,
			simulatorSeed = 		1234,
			simulators = 			["NEURON"],
			simRefPrefix =          	"Net_",
			suggestedRemoteRunTime = 	120,
			defaultSynapticDelay =  	0.05,
			mpiConf = 			MpiSettings.LOCAL_SERIAL,
			scaleCortex = 			0.1,
			scaleThalamus = 		0,
			gabaScaling = 			1,
			l4ssAmpaScaling = 		1,
			l5PyrGapScaling = 		1,
			inNrtTcrNmdaScaling = 		1,
			pyrSsNmdaScaling = 		1,
			deepBiasCurrent = 		-1,
			maxElecLenFRB = 		0.01,
			maxElecLenRS =          	0.01,
			maxElecLenIN =         		0.01,
			maxElecLenSS =         		0.01,
			somaNseg =              	-1,
			varTimestepNeuron =     	False,
			verbose =               	True,
			runInBackground = 		False):
			  
    print "Running new column simulation..."

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

    # Full column populations

    numFRB =                50       #   full model: 50
    numRS =                 1000     #   full model: 1000
    numSupBask =            90       #   full model: 90
    numSupAxAx =            90       #   full model: 90
    numSupLTS =             90       #   full model: 90
    numL4SpinStell =        240      #   full model: 240
    numL5TuftIB =           800      #   full model: 800
    numL5TuftRS =           200      #   full model: 200
    numDeepBask =           100      #   full model: 100
    numDeepAxAx =           100      #   full model: 100
    numDeepLTS =            100      #   full model: 100
    numL6NonTuftRS =        500      #   full model: 500


    numTCR =                100      #   full model: 100
    numnRT =                100      #   full model: 100


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


    ### Load neuroConstruct project


    import datetime

    start = datetime.datetime.now()

    print "Loading project %s from at %s " % (projFile.getCanonicalPath(),start.strftime("%Y-%m-%d %H:%M"))

    pm = ProjectManager()
    project = pm.loadProject(projFile)


    ### Set duration & timestep & simulation configuration

    project.simulationParameters.setDt(simDt)
    simConfig = project.simConfigInfo.getSimConfig(simConfig)
    simConfig.setSimDuration(simDuration)


    ### Set simulation reference

    index = 0
    simRef = "%s%i"%(simRefPrefix,index)


    while File( "%s/simulations/%s_N"%(project.getProjectMainDirectory().getCanonicalPath(), simRef)).exists():
	simRef = "%s%i"%(simRefPrefix,index)
	index = index+1

    project.simulationParameters.setReference(simRef)


    ### Change num in each cell group

    numFRB = int(scaleCortex * numFRB)
    numRS = int(scaleCortex * numRS)
    numSupBask = int(scaleCortex * numSupBask)
    numSupAxAx = int(scaleCortex * numSupAxAx)
    numSupLTS = int(scaleCortex * numSupLTS)
    numL4SpinStell = int(scaleCortex * numL4SpinStell)
    numL5TuftIB = int(scaleCortex * numL5TuftIB)
    numL5TuftRS = int(scaleCortex * numL5TuftRS)
    numDeepBask = int(scaleCortex * numDeepBask)
    numDeepAxAx = int(scaleCortex * numDeepAxAx)
    numDeepLTS = int(scaleCortex * numDeepLTS)
    numL6NonTuftRS = int(scaleCortex * numL6NonTuftRS)

    numTCR = int(scaleThalamus * numTCR)
    numnRT = int(scaleThalamus * numnRT)

    project.cellGroupsInfo.getCellPackingAdapter("CG3D_L23PyrFRB").setMaxNumberCells(numFRB) # Note only works if RandomCellPackingAdapter
    project.cellGroupsInfo.getCellPackingAdapter("CG3D_L23PyrRS").setMaxNumberCells(numRS)
    project.cellGroupsInfo.getCellPackingAdapter("CG3D_SupBask").setMaxNumberCells(numSupBask)
    project.cellGroupsInfo.getCellPackingAdapter("CG3D_SupAxAx").setMaxNumberCells(numSupAxAx)
    project.cellGroupsInfo.getCellPackingAdapter("CG3D_SupLTS").setMaxNumberCells(numSupLTS)
    project.cellGroupsInfo.getCellPackingAdapter("CG3D_L4SpinStell").setMaxNumberCells(numL4SpinStell)
    project.cellGroupsInfo.getCellPackingAdapter("CG3D_L5TuftIB").setMaxNumberCells(numL5TuftIB)
    project.cellGroupsInfo.getCellPackingAdapter("CG3D_L5TuftRS").setMaxNumberCells(numL5TuftRS)
    project.cellGroupsInfo.getCellPackingAdapter("CG3D_DeepBask").setMaxNumberCells(numDeepBask)
    project.cellGroupsInfo.getCellPackingAdapter("CG3D_DeepAxAx").setMaxNumberCells(numDeepAxAx)
    project.cellGroupsInfo.getCellPackingAdapter("CG3D_DeepLTS").setMaxNumberCells(numDeepLTS)
    project.cellGroupsInfo.getCellPackingAdapter("CG3D_L6NonTuftRS").setMaxNumberCells(numL6NonTuftRS)
    project.cellGroupsInfo.getCellPackingAdapter("CG3D_TCR").setMaxNumberCells(numTCR)
    project.cellGroupsInfo.getCellPackingAdapter("CG3D_nRT").setMaxNumberCells(numnRT)



    ### Change weights in synapses/gap junctions

    for netConnName in simConfig.getNetConns():

	if gabaScaling != 1:

	    SimulationsInfo.addExtraSimProperty("gabaWeightScaling", str(gabaScaling))
	    synList = project.morphNetworkConnectionsInfo.getSynapseList(netConnName)
	    
	    for index in range(0, len(synList)):
		synName = project.morphNetworkConnectionsInfo.getSynapseList(netConnName).get(index).getSynapseType()
		if synName.count("GABAA")>0:
		    print "Changing synaptic weight for syn %s in net conn %s by factor %f"%(synName, netConnName, gabaScaling)
		
		    project.morphNetworkConnectionsInfo.getSynapseList(netConnName).get(index).setWeightsGenerator(NumberGenerator(gabaScaling))
		    
	if l4ssAmpaScaling !=1:
	  
	    SimulationsInfo.addExtraSimProperty("l4ssAmpaScaling", str(l4ssAmpaScaling))
	    synList = project.morphNetworkConnectionsInfo.getSynapseList(netConnName)
	    
	    for index in range(0, len(synList)):
		synName = project.morphNetworkConnectionsInfo.getSynapseList(netConnName).get(index).getSynapseType()
		if synName.count("Syn_AMPA_L4SS_L4SS")>0:
		    print "Changing synaptic weight for syn %s in net conn %s by factor %f"%(synName, netConnName, l4ssAmpaScaling)
		
		    project.morphNetworkConnectionsInfo.getSynapseList(netConnName).get(index).setWeightsGenerator(NumberGenerator(l4ssAmpaScaling))
		    
	if l5PyrGapScaling !=1:
	  
	    SimulationsInfo.addExtraSimProperty("l5PyrGapScaling", str(l5PyrGapScaling))
	    synList = project.morphNetworkConnectionsInfo.getSynapseList(netConnName)
	    
	    for index in range(0, len(synList)):
		synName = project.morphNetworkConnectionsInfo.getSynapseList(netConnName).get(index).getSynapseType()
		tgtCG = project.morphNetworkConnectionsInfo.getTargetCellGroup(netConnName)
		if synName.count("Syn_Elect_DeepPyr_DeepPyr")>0 and tgtCG.count("CG3D_L5")>0:
		    print "Changing synaptic weight for syn %s in net conn %s by factor %f"%(synName, netConnName, l5PyrGapScaling)
		
		    project.morphNetworkConnectionsInfo.getSynapseList(netConnName).get(index).setWeightsGenerator(NumberGenerator(l5PyrGapScaling))
		    
	if inNrtTcrNmdaScaling !=1:
	  
	    SimulationsInfo.addExtraSimProperty("inNrtTcrNmdaScaling", str(inNrtTcrNmdaScaling))
	    synList = project.morphNetworkConnectionsInfo.getSynapseList(netConnName)
	    
	    for index in range(0, len(synList)):
		synName = project.morphNetworkConnectionsInfo.getSynapseList(netConnName).get(index).getSynapseType()
		if synName.count("NMDA")>0 and (synName.endswith("_IN")>0 or 
						synName.endswith("_DeepIN")>0 or 
						synName.endswith("_SupIN")>0 or 
						synName.endswith("_SupFS")>0 or 
						synName.endswith("_DeepFS")>0 or 
						synName.endswith("_SupLTS")>0 or 
						synName.endswith("_DeepLTS")>0 or 
						synName.endswith("_nRT")>0 or 
						synName.endswith("_TCR")>0):
						  
		    print "Changing synaptic weight for syn %s in net conn %s by factor %f"%(synName, netConnName, inNrtTcrNmdaScaling)
		
		    project.morphNetworkConnectionsInfo.getSynapseList(netConnName).get(index).setWeightsGenerator(NumberGenerator(inNrtTcrNmdaScaling))
	  
	if pyrSsNmdaScaling !=1:
	  
	    SimulationsInfo.addExtraSimProperty("pyrSsNmdaScaling", str(pyrSsNmdaScaling))
	    synList = project.morphNetworkConnectionsInfo.getSynapseList(netConnName)
	    
	    for index in range(0, len(synList)):
		synName = project.morphNetworkConnectionsInfo.getSynapseList(netConnName).get(index).getSynapseType()
		if synName.count("NMDA")>0 and (synName.endswith("_SupPyr")>0 or
						synName.endswith("_DeepPyr")>0 or
						synName.endswith("_L4SS")>0 or
						synName.endswith("_L5Pyr")>0 or
						synName.endswith("_L5RS")>0 or
						synName.endswith("_L5IB")>0 or
						synName.endswith("_L6NT")>0 or
						synName.endswith("_Pyr")>0):
						  
		    print "Changing synaptic weight for syn %s in net conn %s by factor %f"%(synName, netConnName, pyrSsNmdaScaling)
		
		    project.morphNetworkConnectionsInfo.getSynapseList(netConnName).get(index).setWeightsGenerator(NumberGenerator(pyrSsNmdaScaling))


    ### Change bias currents

    for inputName in simConfig.getInputs():
      
	stim = project.elecInputInfo.getStim(inputName)
      
	if deepBiasCurrent >= 0:
	    
	    if stim.getElectricalInput().TYPE == "IClamp" and (stim.getCellGroup()=="CG3D_L5TuftIB" or stim.getCellGroup()=="CG3D_L5TuftRS" or stim.getCellGroup()=="CG3D_L6NonTuftRS"):
	    
	      print "Changing offset current in %s to %f"%(stim.getCellGroup(), deepBiasCurrent)
	      
	      stim.setAmp(NumberGenerator(deepBiasCurrent))
	      project.elecInputInfo.updateStim(stim)
	  


    ### Change spatial discretisation of some cells. This will impact accuracy & simulation speed

    if maxElecLenFRB > 0:
	frbCell = project.cellManager.getCell("L23PyrFRB_varInit")
	info = CellTopologyHelper.recompartmentaliseCell(frbCell, maxElecLenFRB, project)
	print "Recompartmentalised FRB cell: "+info
	if somaNseg > 0:
	    frbCell.getSegmentWithId(0).getSection().setNumberInternalDivisions(somaNseg)

    if maxElecLenRS > 0:
	rsCell = project.cellManager.getCell("L23PyrRS")
	info = CellTopologyHelper.recompartmentaliseCell(rsCell, maxElecLenRS, project)
	print "Recompartmentalised RS cell: "+info
	if somaNseg > 0:
	    rsCell.getSegmentWithId(0).getSection().setNumberInternalDivisions(somaNseg)

    if maxElecLenIN > 0:
	inCells = ["SupBasket", "SupAxAx","SupLTSInter","DeepBasket", "DeepAxAx","DeepLTSInter"]

	for inCellName in inCells:
	    inCell = project.cellManager.getCell(inCellName)
	    info = CellTopologyHelper.recompartmentaliseCell(inCell, maxElecLenIN, project)
	    print "Recompartmentalised "+inCellName+" cell: "+info
	    if somaNseg > 0:
		inCell.getSegmentWithId(0).getSection().setNumberInternalDivisions(somaNseg)


    ### Change parallel configuration

    mpiSettings = MpiSettings()
    simConfig.setMpiConf(mpiSettings.getMpiConfiguration(mpiConf))
    print "Parallel configuration: "+ str(simConfig.getMpiConf())

    if suggestedRemoteRunTime > 0:
	project.neuronFileManager.setSuggestedRemoteRunTime(suggestedRemoteRunTime)
	project.genesisFileManager.setSuggestedRemoteRunTime(suggestedRemoteRunTime)


    ### Change synaptic delay associated with each net conn

    for netConnName in simConfig.getNetConns():
	if netConnName.count("gap")==0:
	    print "Changing synaptic delay in %s to %f"%(netConnName, defaultSynapticDelay)
	    delayGen = NumberGenerator(defaultSynapticDelay)
	    for synProps in project.morphNetworkConnectionsInfo.getSynapseList(netConnName):
		synProps.setDelayGenerator(delayGen)

    # defaultSynapticDelay will be recorded in simulation.props and listed in SimulationBrowser GUI
    SimulationsInfo.addExtraSimProperty("defaultSynapticDelay", str(defaultSynapticDelay))


    ### Generate network structure in neuroConstruct

    pm.doGenerate(simConfig.getName(), neuroConstructSeed)

    while pm.isGenerating():
	    print "Waiting for the project to be generated with Simulation Configuration: "+str(simConfig)
	    sleep(2)


    print "Generated %i cells in %i cell groups" % (project.generatedCellPositions.getNumberInAllCellGroups(), project.generatedCellPositions.getNumberNonEmptyCellGroups())
    print "Generated %i instances in %i network connections" % (project.generatedNetworkConnections.getNumAllSynConns(), project.generatedNetworkConnections.getNumNonEmptyNetConns())
    print "Generated %i instances in %i elect inputs" % (project.generatedElecInputs.getNumberSingleInputs(), project.generatedElecInputs.getNonEmptyInputRefs().size())


    if simulators.count("NEURON")>0:
	
	simRefN = simRef+"_N"
	project.simulationParameters.setReference(simRefN)

	nc.generateAndRunNeuron(project,
				pm,
				simConfig,
				simRefN,
				simulatorSeed,
				verbose=verbose,
				runInBackground=runInBackground,
				varTimestep=varTimestepNeuron)
	    
	sleep(2) # wait a while before running GENESIS...
	
    if simulators.count("GENESIS")>0:
	
	simRefG = simRef+"_G"
	project.simulationParameters.setReference(simRefG)

	nc.generateAndRunGenesis(project,
				pm,
				simConfig,
				simRefG,
				simulatorSeed,
				verbose=verbose,
				runInBackground=runInBackground)
				
	sleep(2) # wait a while before running MOOSE...


    if simulators.count("MOOSE")>0:

	simRefM = simRef+"_M"
	project.simulationParameters.setReference(simRefM)

	nc.generateAndRunMoose(project,
				pm,
				simConfig,
				simRefM,
				simulatorSeed,
				verbose=verbose,
				runInBackground=runInBackground)
				
	sleep(2) # wait a while before running GENESIS...


    print "Finished running all sims, shutting down..."


    stop = datetime.datetime.now()
    print
    print "Started: %s, finished: %s" % (start.strftime("%Y-%m-%d %H:%M"),stop.strftime("%Y-%m-%d %H:%M"))
    print
Exemplo n.º 23
0
numnRT =                100      #   full model: 100


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


### Load neuroConstruct project


import datetime

start = datetime.datetime.now()

print "Loading project %s from at %s " % (projFile.getCanonicalPath(),start.strftime("%Y-%m-%d %H:%M"))

pm = ProjectManager()
project = pm.loadProject(projFile)


### Set duration & timestep & simulation configuration

project.simulationParameters.setDt(simDt)
simConfig = project.simConfigInfo.getSimConfig(simConfig)
simConfig.setSimDuration(simDuration)


### Set simulation reference

index = 0
simRef = "%s%i"%(simRefPrefix,index)
Exemplo n.º 24
0
	print "Note: this file should be run using ..\\nC.bat -python XXX.py' or './nC.sh -python XXX.py'"
	print "See http://www.neuroconstruct.org/docs/python.html for more details"
	quit()
	
import sys
from time import *

from ucl.physiol.neuroconstruct.project import ProjectManager



# Load an existing neuroConstruct project
projFile = File("../CElegans.ncx")
print "Loading project from file: " + projFile.getAbsolutePath()+", exists: "+ str(projFile.exists())

pm = ProjectManager()
project = pm.loadProject(projFile)
print "Loaded project: " + project.getProjectName()


simConfig = project.simConfigInfo.getSimConfig("CellsOnly")

expectedNumberCells = 302


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


pm.doGenerate(simConfig.getName(), 1234)

while pm.isGenerating():
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")
Exemplo n.º 26
0
numnRT =                100      #   full model: 100


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


### Load neuroConstruct project


import datetime

start = datetime.datetime.now()

print "Loading project %s from at %s " % (projFile.getCanonicalPath(),start.strftime("%Y-%m-%d %H:%M"))

pm = ProjectManager()
project = pm.loadProject(projFile)


### Set duration & timestep & simulation configuration

project.simulationParameters.setDt(simDt)
simConfig = project.simConfigInfo.getSimConfig(simConfig)
simConfig.setSimDuration(simDuration)


### Set simulation reference

index = 0
simRef = "%s%i"%(simRefPrefix,index)
Exemplo n.º 27
0
peakThreshold = 3   # In synchrony, what constitutes a peak

maxRadius = 300

radiusRing = 40

cellGroupName = "CellGroup_1"
inputStimRef = "Input_0"

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

from ucl.physiol.neuroconstruct.project import ProjectManager

print 'Loading project file: ', projFile.getAbsolutePath()

pm = ProjectManager()
project = pm.loadProject(projFile)

print 'Successfully loaded project: ', project.getProjectName()



innerRadius = 0
outerRadius = radiusRing*2.5 #most inner compartment

while innerRadius < maxRadius:


    plotFrame = PlotManager.getPlotterFrame("Analysis of synchrony in ring %f -> %f"%(innerRadius,outerRadius), False)
    plotFrame2 = PlotManager.getPlotterFrame("Peak times in ring %f -> %f"%(innerRadius,outerRadius), False)
Exemplo n.º 28
0
	def make_fF_Curve(self,
                          projFile,
                          simulator,
                          simConfig,
                          nTrains,
                          simDuration,
                          analyseStartTime, analyseStopTime,
                          analyseThreshold,
                          maxNumSimultaneousSims = 4):

			# Load neuroConstruct project

			print "Loading project from file: " + projFile.getAbsolutePath()+", exists: "+ str(projFile.exists())

			pm = ProjectManager()
			self.myProject = pm.loadProject(projFile)
			self.simulator = simulator

			simConfig = self.myProject.simConfigInfo.getSimConfig(simConfig)

			simConfig.setSimDuration(simDuration)

			pm.doGenerate(simConfig.getName(), self.neuroConstructSeed)

			while pm.isGenerating():
					print "Waiting for the project to be generated with Simulation Configuration: "+str(simConfig)
					time.sleep(2)

			numGenerated = self.myProject.generatedCellPositions.getNumberInAllCellGroups()

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

			simReferences = {}


			if numGenerated > 0:

					print "Generating scripts for simulator: %s..."%simulator

					if simulator == 'NEURON':
						self.myProject.neuronFileManager.setQuitAfterRun(1) # Remove this line to leave the NEURON sim windows open after finishing
						self.myProject.neuronSettings.setCopySimFiles(1) # 1 copies hoc/mod files to PySim_0 etc. and will allow multiple sims to run at once
						self.myProject.neuronSettings.setGraphicsMode(0) # 0 hides graphs during execution
                        
					if simulator == 'GENESIS':
						self.myProject.genesisFileManager.setQuitAfterRun(1) # Remove this line to leave the NEURON sim windows open after finishing
						self.myProject.genesisSettings.setCopySimFiles(1) # 1 copies hoc/mod files to PySim_0 etc. and will allow multiple sims to run at once
						self.myProject.genesisSettings.setGraphicsMode(0) # 0 hides graphs during execution


					currentTrain = 0

					ADD_TO_START_FINITIALIZE = self.myProject.neuronSettings.getNativeBlock(NativeCodeLocation.START_FINITIALIZE)
					ADD_TO_RECORD_I = self.myProject.neuronSettings.getNativeBlock(NativeCodeLocation.AFTER_SIMULATION)

					while currentTrain <= nTrains:

							while (len(self.simsRunning)>=maxNumSimultaneousSims):
									print "Sims currently running: "+str(self.simsRunning)
									print "Waiting..."
									time.sleep(3) # wait a while...
									self.updateSimsRunning()


							simRef = "PySim_"+str(currentTrain)

							print "Going to run simulation: "+simRef

							########  Adjusting the amplitude of the Voltage clamp ###############

                                                        TEXT_BEFORE_CREATION = """objref vector, gTrainFile\n""" + "objectvar clamp\n"

                                                        ### TEXT_BEFORE_INIT = "GranuleCell_mod_tonic[0].Soma {\n" + "clampobj = new VClamp(0.5)\n" + "clampobj.dur[0] = " + str(stimDur) + "\n" + "clampobj.amp[0] = " + str(stimAmp) + "\n" +  "}\n" # This should do the trick

                                                        TEXT_START_FINITIALIZE = "\n" + "gTrainFile = new File() \n" + "vector = new Vector(100000) \n" + "access GranuleCell_mod_tonic[0].Soma \n" + "clamp = new SEClamp(0.5) \n" + "clamp.amp1 = 0 \n" + "clamp.dur1 = 1e9 \n" + """gTrainFile.ropen("E:/neuroConstruct/models/Dan_GranCell/gTrains_nS/gAMPA_""" + str(currentTrain) + """.txt") \n""" + "vector.scanf(gTrainFile) \n" + "gTrainFile.close \n" + "for i = 0, vector.size() -1 { \n" + "     if (vector.x[i] <= 0) { \n" + "          vector.x[i] = 1e-20 \n" + "              } \n" + "        } \n" + "for i = 0, vector.size() -1 { \n" + "    vector.x[i] = ( 1 / vector.x[i] ) * 1000 \n" + "    } \n" + "vector.play(&clamp.rs, 0.03) \n" # This

                                                        TEXT_START_FINITIALIZE = TEXT_START_FINITIALIZE + ADD_TO_START_FINITIALIZE

                                                        TEXT_TO_RECORD_I = """// currently not used \n"""

                                                        TEXT_TO_RECORD_I = TEXT_TO_RECORD_I + ADD_TO_RECORD_I

                                                        self.myProject.neuronSettings.setNativeBlock(NativeCodeLocation.BEFORE_CELL_CREATION, TEXT_BEFORE_CREATION)
                                                        self.myProject.neuronSettings.setNativeBlock(NativeCodeLocation.START_FINITIALIZE, TEXT_START_FINITIALIZE)
                                                        self.myProject.neuronSettings.setNativeBlock(NativeCodeLocation.AFTER_SIMULATION, TEXT_TO_RECORD_I)

					
							print "Next Train: "+ str(currentTrain)

							self.myProject.simulationParameters.setReference(simRef)

							if simulator == "NEURON":
									self.myProject.neuronFileManager.generateTheNeuronFiles(simConfig,
																							None,
																							NeuronFileManager.RUN_HOC,
																							self.simulatorSeed)

									print "Generated NEURON files for: "+simRef

									compileProcess = ProcessManager(self.myProject.neuronFileManager.getMainHocFile())

									compileSuccess = compileProcess.compileFileWithNeuron(0,0)

									print "Compiled NEURON files for: "+simRef

									if compileSuccess:
													pm.doRunNeuron(simConfig)
													print "Set running simulation: "+simRef
													self.simsRunning.append(simRef)

							if simulator == "GENESIS":
									compartmentalisation = GenesisCompartmentalisation()

									self.myProject.genesisFileManager.generateTheGenesisFiles(simConfig,
																							None,
																							compartmentalisation,
																							self.simulatorSeed)
									print "Generated GENESIS files for: "+simRef

									pm.doRunGenesis(simConfig)
									print "Set running simulation: "+simRef
									self.simsRunning.append(simRef)

							time.sleep(1) # Wait for sim to be kicked off
							simReferences[simRef] = currentTrain
							currentTrain = currentTrain + 1

					print
					print "Finished running "+str(len(simReferences))+" simulations for project "+ projFile.getAbsolutePath()
					print "These can be loaded and replayed in the previous simulation browser in the GUI"
					print

			while (len(self.simsRunning)>0):
					print "Sims currently running: "+str(self.simsRunning)
					print "Waiting..."
					time.sleep(4) # wait a while...
					self.updateSimsRunning()

			#simReferences = {'PySim_0.3':0.3,'PySim_0.4':0.4,'PySim_0.5':0.5}

			plotFrameFf = PlotManager.getPlotterFrame("F-f curve from project: "+str(self.myProject.getProjectFile())+" on "+simulator , 1, 1)

			plotFrameVolts = PlotManager.getPlotterFrame("VoltageTraces from project: "+str(self.myProject.getProjectFile())+" on "+simulator , 1, 1)

			plotFrameFf.setViewMode(PlotCanvas.INCLUDE_ORIGIN_VIEW)

			info = "F-f curve for Simulation Configuration: "+str(simConfig)

			dataSet = DataSet(info, info, "Hz", "Hz", "Input_Freq", "Output_Freq")
			dataSet.setGraphFormat(PlotCanvas.USE_CIRCLES_FOR_PLOT)

			simList = simReferences.keys()
			simList.sort()
			
		        traininfos = open("E:/neuroConstruct/models/Dan_GranCell/gAMPA_traininfo.txt")
			train_info_list = traininfos.readlines()
			currentTrain = 0

			for sim in simList:

					simDir = File(projFile.getParentFile(), "E:/neuroConstruct/models/Dan_GranCell/simulations/"+sim)
					print
					print "--- Reloading data from simulation in directory: %s"%simDir.getCanonicalPath()
					try:
							simData = SimulationData(simDir)
							simData.initialise()
							print "Data loaded: "
							print simData.getAllLoadedDataStores()
							times = simData.getAllTimes()
							cellSegmentRef = simConfig.getCellGroups().get(0)+"_0"
							volts = simData.getVoltageAtAllTimes(cellSegmentRef)

							time.sleep(2)

							traceInfo = "Voltage at: %s in simulation: %s"%(cellSegmentRef, sim)

							dataSetV = DataSet(traceInfo, traceInfo, "ms", "mV", "Time", "Membrane Potential")

                                                        
                                                        Spike_List = []

                                                        Spike_List.append(0.00)

							for i in range(len(times)):
								dataSetV.addPoint(times[i], volts[i])

							for i in range(len(times)):
								if (volts[i] > 0.0):
                                                                        if (times[i] - Spike_List[len(Spike_List)-1] > 0.50):
                                                                                Spike_List.append(times[i])

                                                                                
                                                        Spike_List.remove(0.00)
        

							plotFrameVolts.addDataSet(dataSetV)

							spikeTimes = SpikeAnalyser.getSpikeTimes(volts, times, analyseThreshold, analyseStartTime, analyseStopTime)

							currentTrain_Freq = float(train_info_list[currentTrain-1])

							
							print "Number of spikes in sim %s: %i"%(sim, len(spikeTimes))
							avgFreq = 0
							if len(Spike_List)>0:
									avgFreq = 1000.0 / ((Spike_List[len(Spike_List)-1] - Spike_List[0]) / (len(Spike_List) -1))
									dataSet.addPoint(currentTrain_Freq,avgFreq)
							currentTrain = currentTrain + 1

							
					except:
							print "Error analysing simulation data from: %s"%simDir.getCanonicalPath()
							print sys.exc_info()[0]


			plotFrameFf.addDataSet(dataSet)
Exemplo n.º 29
0
	def generateF_ICurve(self,
                         projFile,
                         simulator,
                         simConfig,
                         preStimAmp, preStimDel, preStimDur,
                         stimAmpLow, stimAmpInc, stimAmpHigh,
                         stimDel, stimDur,
                         simDuration,
                         analyseStartTime, analyseStopTime,
                         analyseThreshold,
                         maxNumSimultaneousSims = 4):

			# Load neuroConstruct project

			print "Loading project from file: " + projFile.getAbsolutePath()+", exists: "+ str(projFile.exists())

			pm = ProjectManager()
			self.myProject = pm.loadProject(projFile)
			self.simulator = simulator

			simConfig = self.myProject.simConfigInfo.getSimConfig(simConfig)

			simConfig.setSimDuration(simDuration)

			pm.doGenerate(simConfig.getName(), self.neuroConstructSeed)

			while pm.isGenerating():
					print "Waiting for the project to be generated with Simulation Configuration: "+str(simConfig)
					time.sleep(2)

			numGenerated = self.myProject.generatedCellPositions.getNumberInAllCellGroups()

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

			simReferences = {}


			if numGenerated > 0:

					print "Generating scripts for simulator: %s..."%simulator

					if simulator == 'NEURON':
						self.myProject.neuronFileManager.setQuitAfterRun(1) # Remove this line to leave the NEURON sim windows open after finishing
						self.myProject.neuronSettings.setCopySimFiles(1) # 1 copies hoc/mod files to PySim_0 etc. and will allow multiple sims to run at once
						self.myProject.neuronSettings.setGraphicsMode(0) # 0 hides graphs during execution
                        
					if simulator == 'GENESIS':
						self.myProject.genesisFileManager.setQuitAfterRun(1) # Remove this line to leave the NEURON sim windows open after finishing
						self.myProject.genesisSettings.setCopySimFiles(1) # 1 copies hoc/mod files to PySim_0 etc. and will allow multiple sims to run at once
						self.myProject.genesisSettings.setGraphicsMode(0) # 0 hides graphs during execution


					stimAmp = stimAmpLow

					while stimAmp <= stimAmpHigh:

							while (len(self.simsRunning)>=maxNumSimultaneousSims):
									print "Sims currently running: "+str(self.simsRunning)
									print "Waiting..."
									time.sleep(3) # wait a while...
									self.updateSimsRunning()


							simRef = "PySim_"+str(float(stimAmp))

							print "Going to run simulation: "+simRef

							########  Adjusting the amplitude of the current clamp ###############

                                                        # preStim = self.myProject.elecInputInfo.getStim(simConfig.getInputs().get(0))
							preStim = self.myProject.elecInputInfo.getStim("Input_3")

							preStim.setAmp(NumberGenerator(preStimAmp))
							preStim.setDel(NumberGenerator(preStimDel))
							preStim.setDur(NumberGenerator(preStimDur))
							self.myProject.elecInputInfo.updateStim(preStim)


							# stim = self.myProject.elecInputInfo.getStim(simConfig.getInputs().get(1))
							stim = self.myProject.elecInputInfo.getStim("Input_4")
							

							stim.setAmp(NumberGenerator(stimAmp))
							stim.setDel(NumberGenerator(stimDel))
							stim.setDur(NumberGenerator(stimDur))
							self.myProject.elecInputInfo.updateStim(stim)

							print "Next stim: "+ str(stim)

							self.myProject.simulationParameters.setReference(simRef)

							if simulator == "NEURON":
									self.myProject.neuronFileManager.generateTheNeuronFiles(simConfig,
																							None,
																							NeuronFileManager.RUN_HOC,
																							self.simulatorSeed)

									print "Generated NEURON files for: "+simRef

									compileProcess = ProcessManager(self.myProject.neuronFileManager.getMainHocFile())

									compileSuccess = compileProcess.compileFileWithNeuron(0,0)

									print "Compiled NEURON files for: "+simRef

									if compileSuccess:
													pm.doRunNeuron(simConfig)
													print "Set running simulation: "+simRef
													self.simsRunning.append(simRef)

							if simulator == "GENESIS":
									compartmentalisation = GenesisCompartmentalisation()

									self.myProject.genesisFileManager.generateTheGenesisFiles(simConfig,
																							None,
																							compartmentalisation,
																							self.simulatorSeed)
									print "Generated GENESIS files for: "+simRef

									pm.doRunGenesis(simConfig)
									print "Set running simulation: "+simRef
									self.simsRunning.append(simRef)

							time.sleep(1) # Wait for sim to be kicked off
							simReferences[simRef] = stimAmp
							stimAmp = stimAmp +stimAmpInc

					print
					print "Finished running "+str(len(simReferences))+" simulations for project "+ projFile.getAbsolutePath()
					print "These can be loaded and replayed in the previous simulation browser in the GUI"
					print

			while (len(self.simsRunning)>0):
					print "Sims currently running: "+str(self.simsRunning)
					print "Waiting..."
					time.sleep(4) # wait a while...
					self.updateSimsRunning()

			#simReferences = {'PySim_0.3':0.3,'PySim_0.4':0.4,'PySim_0.5':0.5}

			plotFrameFI = PlotManager.getPlotterFrame("F-I curve from project: "+str(self.myProject.getProjectFile())+" on "+simulator , 1, 1)
			plotFrameVolts = PlotManager.getPlotterFrame("VoltageTraces from project: "+str(self.myProject.getProjectFile())+" on "+simulator , 1, 1)

			plotFrameFI.setViewMode(PlotCanvas.INCLUDE_ORIGIN_VIEW)

			info = "F-I curve for Simulation Configuration: "+str(simConfig)

			dataSet = DataSet(info, info, "nA", "Hz", "Current injected", "Firing frequency")
			dataSet.setGraphFormat(PlotCanvas.USE_CIRCLES_FOR_PLOT)

			simList = simReferences.keys()
			simList.sort()

			for sim in simList:

					simDir = File(projFile.getParentFile(), "/neuroConstruct/models/Dan_GranCell/simulations/"+sim)
					print
					print "--- Reloading data from simulation in directory: %s"%simDir.getCanonicalPath()
					try:
							simData = SimulationData(simDir)
							simData.initialise()
							print "Data loaded: "
							print simData.getAllLoadedDataStores()
							times = simData.getAllTimes()
							cellSegmentRef = simConfig.getCellGroups().get(0)+"_0"
							volts = simData.getVoltageAtAllTimes(cellSegmentRef)

							traceInfo = "Voltage at: %s in simulation: %s"%(cellSegmentRef, sim)

							dataSetV = DataSet(traceInfo, traceInfo, "mV", "ms", "Membrane potential", "Time")
							for i in range(len(times)):
									dataSetV.addPoint(times[i], volts[i])

							plotFrameVolts.addDataSet(dataSetV)

							spikeTimes = SpikeAnalyser.getSpikeTimes(volts, times, analyseThreshold, analyseStartTime, analyseStopTime)
							stimAmp = simReferences[sim]
							print "Number of spikes at %f nA in sim %s: %i"%(stimAmp, sim, len(spikeTimes))
							avgFreq = 0
							if len(spikeTimes)>1:
									avgFreq = len(spikeTimes)/ ((analyseStopTime - analyseStartTime)/1000.0)
									dataSet.addPoint(stimAmp,avgFreq)
					except:
							print "Error analysing simulation data from: %s"%simDir.getCanonicalPath()
							print sys.exc_info()[0]


			plotFrameFI.addDataSet(dataSet)
Exemplo n.º 30
0
simDt =                0.01 # ms
neuroConstructSeed =   1234
simulatorSeed =        1111
simRefPrefix =         "SB_"
defaultSynapticDelay = 0.2  # ms
runInBackground =      True

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


# Load neuroConstruct project

print "Loading project from "+ projFile.getCanonicalPath()


pm = ProjectManager()
myProject = pm.loadProject(projFile)

myProject.simulationParameters.setDt(simDt)
index = 0

while File( "%s/simulations/%s%i"%(myProject.getProjectMainDirectory().getCanonicalPath(), simRefPrefix,index)).exists():
    index = index+1

simRef = "%s%i"%(simRefPrefix,index)
myProject.simulationParameters.setReference(simRef)

# Use this so defaultSynapticDelay will be recorded in simulation.props and listed in SimulationBrowser GUI
SimulationsInfo.addExtraSimProperty("defaultSynapticDelay", str(defaultSynapticDelay))

simConfig = myProject.simConfigInfo.getSimConfig(simConfig)
Exemplo n.º 31
0
simConfig = "Propagation delayed connection"
simDuration = 100  # ms
simDt = 0.01  # ms
neuroConstructSeed = 1234
simulatorSeed = 1111
simRefPrefix = "RandomWeights_"
runInBackground = True

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

# Load neuroConstruct project

print "Loading project from " + projFile.getCanonicalPath()

pm = ProjectManager()
myProject = pm.loadProject(projFile)

myProject.simulationParameters.setDt(simDt)
index = 0

while File("%s/simulations/%s%i" %
           (myProject.getProjectMainDirectory().getCanonicalPath(),
            simRefPrefix, index)).exists():
    index = index + 1

simRef = "%s%i" % (simRefPrefix, index)
myProject.simulationParameters.setReference(simRef)

simConfig = myProject.simConfigInfo.getSimConfig(simConfig)
Exemplo n.º 32
0
varTimestepNeuron =     False
verbose =               True
runInBackground=        False

suggestedRemoteRunTime = 120


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


### Load neuroConstruct project

print "Loading project from "+ projFile.getCanonicalPath()

pm = ProjectManager()
project = pm.loadProject(projFile)


### Set duration & timestep & simulation configuration

project.simulationParameters.setDt(simDt)
simConfig = project.simConfigInfo.getSimConfig(simConfig)
simConfig.setSimDuration(simDuration)

if saveDataAsHdf5:
    project.neuronSettings.setDataSaveFormat(NeuronSettings.DataSaveFormat.HDF5_NC)


### Set simulation reference
Exemplo n.º 33
0
	
import sys
from time import *

from ucl.physiol.neuroconstruct.project import ProjectManager
from ucl.physiol.neuroconstruct.neuroml import NeuroMLFileManager
from ucl.physiol.neuroconstruct.neuroml import NeuroMLConstants




# Load an existing neuroConstruct project
projFile = File("../CElegans.ncx")
print "Loading project from file: " + projFile.getAbsolutePath()+", exists: "+ str(projFile.exists())

pm = ProjectManager()
project = pm.loadProject(projFile)
print "Loaded project: " + project.getProjectName()


simConfig = project.simConfigInfo.getSimConfig("CellsOnly")

expectedNumberCells = 302


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


pm.doGenerate(simConfig.getName(), 1234)

while pm.isGenerating():
Exemplo n.º 34
0
#
#   Author: Padraig Gleeson
#
#   This file has been developed as part of the neuroConstruct project
#   This work has been funded by the Medical Research Council and the
#   Wellcome Trust
#
#

try:
	from java.io import File
	from java.lang import System
except ImportError:
	print "Note: this file should be run using ..\\nC.bat -python XXX.py' or './nC.sh -python XXX.py'"
	print "See http://www.neuroconstruct.org/docs/python.html for more details"
	quit()
	

from ucl.physiol.neuroconstruct.project import ProjectManager

file = File("../osb/showcase/neuroConstructShowcase/Ex1_Simple/Ex1_Simple.ncx")
print 'Loading project file: ', file.getAbsolutePath()

pm = ProjectManager()
myProject = pm.loadProject(file)

print pm.status()

#  Remove this line to remain in interactive mode
System.exit(0)
Exemplo n.º 35
0
def testAll(argv=None):
    if argv is None:
        argv = sys.argv

    print "Loading project from " + projFile.getCanonicalPath()

    projectManager = ProjectManager()
    project = projectManager.loadProject(projFile)

    assert (len(project.getProjectDescription()) > 0)

    assert (len(project.cellManager.getAllCells()) >= 22)

    assert (len(project.cellGroupsInfo.getAllCellGroupNames()) >= 36)

    synSetupFile = open("netbuild/makeSyns.sh", 'r')

    for line in synSetupFile:
        line = line.strip()

        if len(line) > 0 and not line.startswith("#"):
            words = line.split()
            if len(words) >= 6 and words[2].startswith("Syn_"):
                synName = words[2]
                syn_dir = "../cellMechanisms/%s" % synName
                if os.path.isdir(syn_dir):
                    cm = project.cellMechanismInfo.getCellMechanism(synName)
                    print "Checked syn %s" % cm.getInstanceName()
                else:
                    print("Problem finding directory: %s!! This is probably due to the synapses not having been generated \n"%syn_dir+ \
                     "from netbuild/makeSyns.sh (they need to be generated loacally; too many to commit to repository)")

    netConnList = open("netbuild/netConnList", 'r')

    for line in netConnList:
        line = line.strip()

        if len(line) > 0 and not line.startswith("#"):

            #print "\n\n---- Deciphering line: "+ line
            words = line.split()
            source = words[0]
            target = words[1]
            syns = words[2].strip("[]").split(",")
            netConnName = "NC3D_" + source[5:] + "_" + target[5:]
            assert (source == project.morphNetworkConnectionsInfo.
                    getSourceCellGroup(netConnName))
            assert (target == project.morphNetworkConnectionsInfo.
                    getTargetCellGroup(netConnName))
            print "Checked %s" % netConnName

    assert (project.proj3Dproperties.getDisplayOption() ==
            Display3DProperties.DISPLAY_SOMA_SOLID_NEURITE_LINE)

    assert (abs(project.simulationParameters.getDt() - 0.025) <= 1e-9)

    assert (not project.neuronSettings.isVarTimeStep())

    assert (project.neuronSettings.isForceCorrectInit())

    assert (project.neuronSettings.getDataSaveFormat().equals(
        NeuronSettings.DataSaveFormat.TEXT_NC))

    assert (not project.genesisSettings.isSymmetricCompartments())

    assert (project.genesisSettings.isPhysiologicalUnits())

    print "\n**************************************"
    print "    All tests passed!"
    print "**************************************\n"
Exemplo n.º 36
0
#
#   Author: Padraig Gleeson
#
#   This file has been developed as part of the neuroConstruct project
#   This work has been funded by the Medical Research Council and the
#   Wellcome Trust
#
#

try:
	from java.io import File
	from java.lang import System
except ImportError:
	print "Note: this file should be run using ..\\nC.bat -python XXX.py' or './nC.sh -python XXX.py'"
	print "See http://www.neuroconstruct.org/docs/python.html for more details"
	quit()
	

from ucl.physiol.neuroconstruct.project import ProjectManager

file = File("../nCexamples/Ex1_Simple/Ex1_Simple.ncx")
print 'Loading project file: ', file.getAbsolutePath()

pm = ProjectManager()
myProject = pm.loadProject(file)

print pm.status()

#  Remove this line to remain in interactive mode
System.exit(0)
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()
Exemplo n.º 38
0
    from java.io import File
except ImportError:
    print "Note: this file should be run using ..\\nC.bat -python XXX.py' or './nC.sh -python XXX.py'"
    print "See http://www.neuroconstruct.org/docs/python.html for more details"
    quit()

from ucl.physiol.neuroconstruct.project import ProjectManager
from ucl.physiol.neuroconstruct.cell.converters import MorphMLConverter

# Load an existing neuroConstruct project

projFile = File("TestPython/TestPython.neuro.xml")
print "Loading project from file: " + projFile.getAbsolutePath(
) + ", exists: " + str(projFile.exists())

pm = ProjectManager()
myProject = pm.loadProject(projFile)
print "Loaded project: " + myProject.getProjectName()

morphDir = File(
    "../osb/showcase/neuroConstructShowcase/Ex3_Morphology/importedMorphologies/"
)
morphmlFile = File(morphDir, "SimplePurkinjeCell.morph.xml")

print "Going to load morphology from: " + morphmlFile.getCanonicalPath()

converter = MorphMLConverter()
cell = converter.loadFromMorphologyFile(morphmlFile, "NewCell")

print "Loaded cell: " + cell.getInstanceName() + " with " + str(
    cell.getAllSegments().size()) + " segments"
Exemplo n.º 39
0
class MultiSim(object):
    pconf = None
    logger = None
    proj_path = None
    pm = None
    myProject = None
    simConfig = None
    stimulation = None
    cellName = None
    simulatorSeed = None
    numGenerated = 0
    maxNumSimultaneousSims = 1
    simsRunning = []

    # A value of 0 or lower deactivates timeout.
    sim_timeout = 0
    
    def __init__(self, pconf):
        configDict = pconf.parse_project_data()
        self.pconf = pconf
        self.logger = pconf.get_logger("neurosim")
        self.proj_path = self.pconf.local_path(configDict["proj_path"])
        self.pm = ProjectManager()
        
        projFile = File(self.proj_path)
        self.sim_timeout = self.pconf.get_float("sim_timeout", "Simulation")
        self.myProject = self.pm.loadProject(projFile)
        self.simConfig = self.myProject.simConfigInfo.getSimConfig(self.pconf.get("sim_config", "Simulation"))
    #-----------------------------------------------------------
    def generate(self):

        neuroConstructSeed = int(self.pconf.get("neuroConstructSeed", "NeuroConstruct"))
        self.stimulation = self.pconf.get("stimulation", "Simulation")
        self.cellName = self.pconf.get("cell", "Simulation")
        self.simulatorSeed = int(self.pconf.get("simulatorSeed", "NeuroConstruct"))
        self.pm.doGenerate(self.simConfig.getName(), neuroConstructSeed)
        self.logger.debug("Waiting for the project to be generated...")
        t = 0.0
        startTime = time.time()
        while self.pm.isGenerating():
            self.logger.debug("Waiting...")
            time.sleep(0.050)
            t += 0.050
            if t > 5.0:
                self.logger.debug("Waiting...")
                t = 0.0
            if self.sim_timeout > 0 and (time.time() - startTime) > self.sim_timeout:
                self.logger.error("Project data could not be created due to timeout.")
                raise SimTimeoutError(self.sim_timeout, "Simulation timeout occured during project generation.")
        self.numGenerated = self.myProject.generatedCellPositions.getNumberInAllCellGroups()
        self.logger.debug("Number of cells generated: " + str(self.numGenerated))

        if self.numGenerated > 0:
            self.logger.info("Generating NEURON scripts...")
            self.myProject.neuronSettings.setCopySimFiles(1) # 1 copies hoc/mod files to PySim_0 etc. and will allow multiple sims to run at once
            # hier kann man entscheiden, ob Bilder angezeigt werden sollen oder nicht: 
                # ist ersteres auskommentiert, werden Bilder angezeigt und bei Einkommentierung des Zweiten auch automatisch wieder geschlossen
            self.myProject.neuronSettings.setNoConsole()

            max_sim_threads = self.pconf.get("maxSimThreads")
            if max_sim_threads == "auto":
                self.maxNumSimultaneousSims = available_cpu_count()
            else:
                self.maxNumSimultaneousSims = max(1, int(max_sim_threads))
    #-----------------------------------------------------------
    def run(self, prefix, dataList):
        """Runs all simulations defined by dataList for the loaded project.

        Each sim will be named (prefix + i) and dataList contains a
        dict with at least "densities", "channels" and "locations" keys.
        """
        try:
            for i in range(len(dataList)):
                self.waitForSimsRunning(self.maxNumSimultaneousSims - 1)
                if not self.runSim(i, prefix, dataList[i]):
                    sys.exit(0)
            self.waitForSimsRunning(0)
            self.logger.info("Finished running " + str(len(dataList)) + " simulations for project " + self.proj_path)
            return
        except (KeyboardInterrupt, SystemExit):
            raise
        except SimTimeoutError, e:
            self.logger.warning("Timeout occured: " + e.msg)
            sys.exit(10)
Vervaeke2012.
"""
import os
import random
import time
from java.lang import System
from java.io import File
from java.util import ArrayList

from ucl.physiol.neuroconstruct.project import ProjectManager
from ucl.physiol.neuroconstruct.neuron import NeuronFileManager
from ucl.physiol.neuroconstruct.nmodleditor.processes import ProcessManager
from ucl.physiol.neuroconstruct.cell.utils import CellTopologyHelper

timestamp = str(time.time())
pm = ProjectManager(None, None)
project_path = '../GJGolgi_ReducedMorph.ncx'
project_file = File(project_path)
project = pm.loadProject(project_file)

sim_config_name = 'dendritic_attenuation'

sim_config = project.simConfigInfo.getSimConfig(sim_config_name)
project.neuronSettings.setNoConsole()

n_points = 18
detailed_distance_bounds = range(10.,190.,10.)
rec_segs_reduced = [0,4,5,6]
dendritic_group = 'apical_dend_2'

# switch off Na channels (TTX)
    set_tonic_GABA(work_dir, total_GABA_conductance_in_nS)

    # scale excitatory conductance by modifying the AMPA and NMDA
    # synaptic models. In general, the amplitude of the excitatory
    # conductances is inversely proportional to the number of
    # dendrites divided by 4, with the exc_cond_scaling parameter as
    # the proportionality constant. If this is set to zero, the
    # conductances are not scaled.
    if point.exc_cond_scaling:
        exc_scaling_factor = point.exc_cond_scaling / (float(point.n_grc_dend)/4)
        scale_excitatory_conductances(work_dir, exc_scaling_factor)

    # load project and initialise
    project_file = java.io.File(work_dir + "/" + project_filename)
    print ('Loading project from file: ' + project_file.getAbsolutePath() + ", exists: " + str(project_file.exists()))
    pm = ProjectManager(None, None)
    project = pm.loadProject(project_file)
    print 'Loaded project: ' + project.getProjectName()

    # load existing simulation configurations and set sim duration and a
    # couple of neuron options
    sim_config = project.simConfigInfo.getSimConfig(sim_config_name)
    sim_config.setSimDuration(point.sim_duration)
    project.neuronSettings.setNoConsole()
    project.neuronSettings.setCopySimFiles(1)

    # generate network
    generate_nC_network(point, pm, project, sim_config)

    # generate saves
    generate_nC_saves(point, project)