Ejemplo n.º 1
0
 def load_hoc_model(self, model_dir, hoc_file):
     """Load an hoc files. It compiles the mod 
     before loading the hoc."""
     try:
         os.path.isfile(os.path.join (model_dir, hoc_file))
     except IOError:
         logger.error("Not existing file: %s" %e.value)
         
     old_dir = os.path.abspath(os.getcwd())
     logger.info("Path changed to %s" %(os.path.abspath(model_dir)))
     if model_dir != '' :
         os.chdir(model_dir)
     try:
         # Add all mod files into current directory
         self.find_mod_files()
     
         # If windows
         if os.name == 'nt':                
             self.windows_compile_mod_files('.')
             from neuron import h
             h.nrn_load_dll('./nrnmech.dll')
         else: # Anything else.
             call(['nrnivmodl'])
             import neuron            
             neuron.load_mechanisms('.') # Auto loading. Not needed anymore.
         from neuron import gui # to not freeze neuron gui
         from neuron import h
         logger.info("Loading model in %s from %s"%(model_dir, hoc_file))
         h.load_file(hoc_file)
     except Exception as e:
         logger.warning("Error running model: " + e.message)
     logger.info("Path changed back to %s" %old_dir)
     os.chdir(old_dir)
     return True
Ejemplo n.º 2
0
    def return_cell(self):

        self.model_path = join(root_path+'TC_neuron')
        neuron.load_mechanisms(self.model_path)

        cell_parameters = {
            'morphology': join(self.model_path, 'soma.hoc'),
            'passive':False,
            'v_init' : -60,
            'extracellular':False,
            'nsegs_method': 'none',
            # 'timeres_NEURON':0.1,
            # 'timeres_python':0.1,
            'dt' : 0.1,
            'tstop':2000,
            'tstart':0,
            'templatefile': join(self.model_path, 'TC_GH2.hoc'),
            'templatename':'sTC',
            'templateargs':None,
            'delete_sections':False
        }

        cell = LFPy.TemplateCell(**cell_parameters)

        return cell
Ejemplo n.º 3
0
def test(verbosity=2):
    '''
    Run tests for the LFPy module implemented using the unittest module.
    
    Note:
    if the NEURON extension file LFPy/sinsyn.mod could not be compiled using the
    neuron-provided nrnivmodl script (linux/OSX) upon installation of LFPy,
    tests will fail. Consider reinstalling LFPy e.g., issuing
    ::
        
        pip install LFPy --upgrade
    or
    ::
        
        cd /path/to/LFPy/sources
        python setup.py install
    
    Arguments:
    ::
        
        verbosity : int
            unittest.TextTestRunner verbosity level
    '''
    #load sinusoid synapse currrent mechanism
    neuron.load_mechanisms(LFPy.__path__[0])

    #check if sinsyn.mod is compiled, if it isn't, some tests will fail
    if not hasattr(neuron.h, 'SinSyn'):
        warn(
            'tests will fail because the sinsyn.mod mechanism is not compiled')

    #load and execute testing suite
    suite = unittest.TestLoader().loadTestsFromTestCase(testLFPy)
    unittest.TextTestRunner(verbosity=verbosity).run(suite)
Ejemplo n.º 4
0
def test(verbosity=2):
    '''
    Run tests for the LFPy module implemented using the unittest module.
    
    Note:
    if the NEURON extension file LFPy/sinsyn.mod could not be compiled using the
    neuron-provided nrnivmodl script (linux/OSX) upon installation of LFPy,
    tests will fail. Consider reinstalling LFPy e.g., issuing
    ::
        
        pip install LFPy --upgrade
    or
    ::
        
        cd /path/to/LFPy/sources
        python setup.py install
    
    Arguments:
    ::
        
        verbosity : int
            unittest.TextTestRunner verbosity level
    '''
    #load sinusoid synapse currrent mechanism
    neuron.load_mechanisms(LFPy.__path__[0])

    #check if sinsyn.mod is compiled, if it isn't, some tests will fail
    if not hasattr(neuron.h, 'SinSyn'):
        warn('tests will fail because the sinsyn.mod mechanism is not compiled')
        
    #load and execute testing suite
    suite = unittest.TestLoader().loadTestsFromTestCase(testLFPy)
    unittest.TextTestRunner(verbosity=verbosity).run(suite)
Ejemplo n.º 5
0
 def run_extracted_model(self, mod):
     model_dir = mod.get_dir()
     if os.path.exists(os.path.join (model_dir, 'mosinit.hoc')):
         old_dir = os.path.abspath(os.getcwd())
         logger.info("Path changed to %s" %(os.path.abspath(model_dir)))
         os.chdir(model_dir)
         try:
             # If windows
             if os.name == 'nt':                
                 self.windows_compile_mod_files('.')
                 from neuron import h
                 h.nrn_load_dll('./nrnmech.dll')
             else: # Anything else.
                 call(['nrnivmodl'])
                 import neuron            
                 neuron.load_mechanisms('./')
             from neuron import gui # to not freeze neuron gui
             from neuron import h
             logger.info("Loading model in %s" %model_dir)
             h.load_file('mosinit.hoc')
         except Exception as e:
             logger.warning("Error running model: "+e.message)
         logger.info("Path changed back to %s" %old_dir)
         os.chdir(old_dir)
     else: 
         response = """We didn't find any mosinit.hoc . Unfortunately we can't 
         automatically run the model. Check the README, maybe there is an 
         hint."""
         logging.warning(response)
         path_info = "You can find the extracted model in %s" %model_dir
         mod.browse()
         logging.info(path_info)
Ejemplo n.º 6
0
Archivo: nrn.py Proyecto: shixnya/bmtk
def load_neuron_modules(mechanisms_dir, templates_dir, default_templates=True):
    """

    :param mechanisms_dir:
    :param templates_dir:
    :param default_templates:
    """
    h.load_file('stdgui.hoc')

    bionet_dir = os.path.dirname(__file__)
    h.load_file(os.path.join(bionet_dir, 'import3d.hoc').replace(
        "\\", "/"))  # customized import3d.hoc to supress warnings
    h.load_file(
        os.path.join(bionet_dir, 'default_templates',
                     'advance.hoc').replace("\\", "/"))

    if isinstance(mechanisms_dir, list):
        for mdir in mechanisms_dir:
            neuron.load_mechanisms(str(mdir))

    elif mechanisms_dir is not None:
        neuron.load_mechanisms(str(mechanisms_dir))

    if default_templates:
        load_templates(os.path.join(bionet_dir, 'default_templates'))

    if templates_dir:
        load_templates(templates_dir)
Ejemplo n.º 7
0
def return_cell():

    neuron.load_mechanisms("HallermannEtAl2012")
    # Define cell parameters
    cell_parameters = {          # various cell parameters,
        'morphology' : 'unmyelinated_axon_Hallermann.hoc', # Mainen&Sejnowski, 1996
        'v_init' : -80.,    # initial crossmembrane potential
        'passive' : False,   # switch off passive mechs
        'nsegs_method' : 'lambda_f',
        'lambda_f' : 1000.,
        'dt' : 2.**-7,   # [ms] dt's should be in powers of 2
        'tstart' : -200.,    # start time of simulation, recorders start at t=0
        'tstop' : 2.,   # stop simulation at 2 ms.
    }

    cell = LFPy.Cell(**cell_parameters)
    cell.set_pos(x=-np.max(cell.xmid) / 2, z=2.5)

    #  To induce a spike:
    synapseParameters = {
        'idx' : 0,               # insert synapse on index "0", the soma
        'e' : 0.,                # reversal potential of synapse
        'syntype' : 'Exp2Syn',   # conductance based double-exponential synapse
        'tau1' : 0.1,            # Time constant, decay
        'tau2' : 0.1,            # Time constant, decay
        'weight' : 0.004,         # Synaptic weight
        'record_current' : False, # Will enable synapse current recording
    }

    # attach synapse with parameters and input time
    synapse = LFPy.Synapse(cell, **synapseParameters)
    synapse.set_spike_times(np.array([0.1]))

    cell.simulate(rec_vmem=True, rec_imem=True)
    return cell
Ejemplo n.º 8
0
def _compile_nmodl(nineml_component, weight_variables, hierarchical_mode=None): # weight variables should really be within component
    """
    Generate NMODL code for the 9ML component, run "nrnivmodl" and then load
    the mechanisms into NEURON.
    """
    if not os.path.exists(NMODL_DIR):
        os.makedirs(NMODL_DIR)
    cwd = os.getcwd()
    os.chdir(NMODL_DIR)

    xml_file = "%s.xml" % nineml_component.name
    logger.debug("Writing NineML component to %s" % xml_file)
    nineml_component.write(xml_file)
    
    from nineml2nmodl import write_nmodl, write_nmodldirect
    mod_filename = nineml_component.name + ".mod"
    write_nmodldirect(component=nineml_component, mod_filename=mod_filename, weight_variables=weight_variables) 
    #write_nmodl(xml_file, weight_variables) # weight variables should really come from xml file


    print "Running 'nrnivmodl' from %s"%NMODL_DIR
    import nineml2nmodl
    nineml2nmodl.call_nrnivmodl()



    os.chdir(cwd)
    neuron.load_mechanisms(NMODL_DIR)
Ejemplo n.º 9
0
    def return_cell(self):

        self.model_path = join(root_path+'cortex_neurons')
        neuron.load_mechanisms(self.model_path)

        cell_parameters = {
            'morphology': join(self.model_path, 'soma.hoc'),
            'passive':False,
            'v_init' : -70,
            'extracellular':False,
            'nsegs_method': 'lambda_f',
            'lambda_f': 50,
            #'timeres_NEURON':0.1,
            #'timeres_python':0.1,
            'dt' : 0.1,
            'tstop':2000,
            'tstart':0,
            'templatefile': join(self.model_path, 'sPY_template'),
            'templatename':'sPY',
            'templateargs':None,
            'custom_fun': None,
            'delete_sections':False
        }

        cell = LFPy.TemplateCell(**cell_parameters)
        cell.set_rotation(x=-1.57, y=0.0, z=0.0)

        return cell
Ejemplo n.º 10
0
def _compile_nmodl(nineml_component,
                   weight_variables,
                   hierarchical_mode=None
                   ):  # weight variables should really be within component
    """
    Generate NMODL code for the 9ML component, run "nrnivmodl" and then load
    the mechanisms into NEURON.
    """
    wdir = os.path.join(NMODL_DIR, nineml_component.name)
    if not os.path.exists(wdir):
        os.makedirs(wdir)
    cwd = os.getcwd()
    os.chdir(wdir)

    xml_file = "%s.xml" % nineml_component.name
    logger.debug("Writing NineML component to %s" % xml_file)
    nineml_component.write(xml_file)
    mod_filename = nineml_component.name + ".mod"
    write_nmodldirect(component=nineml_component,
                      mod_filename=mod_filename,
                      weight_variables=weight_variables)
    #write_nmodl(xml_file, weight_variables) # weight variables should really come from xml file

    print("Running 'nrnivmodl' from %s" % wdir)
    import nineml2nmodl
    call_nrnivmodl()
    os.chdir(cwd)
    neuron.load_mechanisms(wdir)
Ejemplo n.º 11
0
    def __init__(self, model_path, special_path, base=os.getcwd()):
        self.base_directory = base
        os.chdir(self.base_directory)
        print('*********** NEURON ' + neuron.__version__ +
              ' LOADED ***********')
        self.special = None if special_path == 'None' else special_path
        self.model = model_path
        self.model_dir = ('/').join(self.model.rsplit('/')[0:-1])
        if self.special:
            neuron.load_mechanisms(self.special)

        self.hoc_obj = first_hoc_cls.__new__(first_hoc_cls)
        self.hoc_obj.__dict__.update(first_hoc_dict)
        self.hoc_obj.load_file(1, str(self.model))
        self.hoc_obj.load_file("stdrun.hoc")
        self.vec = self.hoc_obj.Vector()
        self.stimulus = None
        self.record = []
        self.spike_times = None
        self.sections = {}
        for n in self.hoc_obj.allsec():
            self.sections[str(self.hoc_obj.secname(sec=n))] = n
        self.channels = {}
        for sec in self.hoc_obj.allsec():
            for seg in sec:
                for mech in seg:
                    self.channels[str(mech.name())] = mech
Ejemplo n.º 12
0
    def load_hoc_model(self, model_dir, hoc_file):
        """Load an hoc files. It compiles the mod 
        before loading the hoc."""
        try:
            os.path.isfile(os.path.join(model_dir, hoc_file))
        except IOError:
            logger.error("Not existing file: %s" % e.value)

        old_dir = os.path.abspath(os.getcwd())
        logger.info("Path changed to %s" % (os.path.abspath(model_dir)))
        if model_dir != '':
            os.chdir(model_dir)
        try:
            # Add all mod files into current directory
            self.find_mod_files()

            # If windows
            if os.name == 'nt':
                self.windows_compile_mod_files('.')
                from neuron import h
                h.nrn_load_dll('./nrnmech.dll')
            else:  # Anything else.
                call(['nrnivmodl'])
                import neuron
                neuron.load_mechanisms(
                    '.')  # Auto loading. Not needed anymore.
            from neuron import gui  # to not freeze neuron gui
            from neuron import h
            logger.info("Loading model in %s from %s" % (model_dir, hoc_file))
            h.load_file(hoc_file)
        except Exception as e:
            logger.warning("Error running model: " + e.message)
        logger.info("Path changed back to %s" % old_dir)
        os.chdir(old_dir)
        return True
Ejemplo n.º 13
0
    def importNet(self, configFile, replaceAxon=True, setdLNseg=True):

        self.configFile = configFile
        self.replaceAxon = replaceAxon
        self.setdLNseg = setdLNseg

        # read config files
        filename = os.path.abspath(configFile)
        rootFolder = os.path.dirname(configFile)

        self.config = load_json(filename)
        self.substitutes = {
            '../': '%s/../' % rootFolder,
            './': '%s/' % rootFolder,
            '.': '%s/' % rootFolder,
            '${configdir}': '%s' % rootFolder
        }

        if 'network' in self.config:
            self.network_config = load_json(self.subs(self.config['network']))
        else:
            self.network_config = self.config

        if 'simulation' in self.config:
            self.simulation_config = load_json(
                self.subs(self.config['simulation']))
        else:
            self.simulation_config = None

        for m in self.network_config['manifest']:
            path = self.subs(self.network_config['manifest'][m])
            self.substitutes[m] = path

        for m in self.simulation_config['manifest']:
            path = self.subs(self.simulation_config['manifest'][m])
            self.substitutes[m] = path

        # create and initialize sim object
        sim.initialize()

        # create netpyne simConfig
        self.createSimulationConfig()

        # add compiled mod folder
        modFolder = self.subs(
            self.network_config['components']['mechanisms_dir']) + '/modfiles'
        neuron.load_mechanisms(str(modFolder))

        # create pops
        self.createPops()

        # create stimulation (before createCells since spkTimes added to pops)
        self.createStims()

        # create cells
        self.createCells()

        # create connections
        self.createConns()
Ejemplo n.º 14
0
def load_mechanisms_from_neuron_model(cell_name):
    neuron_model = '/home/baran/Desktop/neuron_models/' + cell_name
    cwd = os.getcwd()
    mechanisms_folder = neuron_model + '/mechanisms'
    os.chdir(mechanisms_folder)
    os.system('nrnivmodl')  #Compiling mechanisms
    os.chdir(cwd)
    neuron.load_mechanisms(mechanisms_folder)
Ejemplo n.º 15
0
def set_parameters(morphology, X, Y, Z, sigma=0.3, cell_model=None):
    """set cell, synapse and electrode parameters"""

    model_folder = join("cell_models", "EyalEtAl2018")
    morph_path = join(model_folder, "Morphs", morphology)

    if cell_model == None:
        cell_parameters = {
            'v_init': -70,
            'morphology': morph_path,
            'passive_parameters': {'g_pas' : 1./30000, 'e_pas' : -70}, # S/cm^2, mV
            'Ra' : 150, # Ω cm
            'cm' : 1, # µF/cm^2
            'nsegs_method': "lambda_f",
            "lambda_f": 100,
            'dt': 2**-4,  # [ms] Should be a power of 2
            'tstart': -10,  # [ms] Simulation start time
            'tstop': 100,  # [ms] Simulation end time
            "pt3d": True,
            'passive': True
            }
    else:
        mod_folder = join(model_folder, 'ActiveMechanisms')
        model_path = join(model_folder, "ActiveModels", cell_model + '_mod')
        neuron.load_mechanisms(mod_folder)

        cell_parameters = {
                'morphology': morph_path,
                'templatefile': model_path + '.hoc',
                'templatename': cell_model,
                'templateargs': morph_path,
                'v_init': -86,
                'passive': False,
                'dt': 2**-4,  # [ms] Should be a power of 2
                'tstart': -200,  # [ms] Simulation start time
                'tstop': 100,  # [ms] Simulation end time
                "pt3d": True,
                'nsegs_method': "lambda_f",
                "lambda_f": 100,
        }

    synapse_parameters = {'e': 0., # reversal potential
                      # 'tau': 5., # synapse time constant (first fig version)
                      'weight': 0.002, # 0.001, # synapse weight
                      'record_current': True, # record synapse current
                      # parameters not included in first version of fig
                      'syntype': 'Exp2Syn',
                      'tau1': 1., #Time constant, rise
                      'tau2': 3., #Time constant, decay
                      }

    grid_electrode_parameters = {'sigma': sigma,
                                 'x': X.flatten(),
                                 'y': Y.flatten(),
                                 'z': Z.flatten()
                                 }
    return cell_parameters, synapse_parameters, grid_electrode_parameters
Ejemplo n.º 16
0
def load_neuron_modules(conf, **cm):
    h.load_file('stdgui.hoc')

    bionet_dir = os.path.dirname(__file__)
    h.load_file(bionet_dir+'/import3d.hoc') # loads hoc files from package directory ./import3d. It is used because read_swc.hoc is modified to suppress some warnings.
    h.load_file(bionet_dir+'/advance.hoc')

    neuron.load_mechanisms(str(conf["components"]["mechanisms_dir"]))
    load_templates(conf["components"]["templates_dir"])
Ejemplo n.º 17
0
def run_sim():
    # Folder that contains x86_64 folder
    NETPYNE_WORKDIR_PATH = "../../../"
    neuron.load_mechanisms(NETPYNE_WORKDIR_PATH)

    netParams = sim.loadNetParams("./netParams.json", None, False)
    simConfig = sim.loadSimCfg("./simConfig.json", None, False)

    sim.createSimulate(netParams, simConfig)
    sim.saveData()
Ejemplo n.º 18
0
def compile_neuron_mod_dir(pkg_dir):
    try:
        print('Compiling {}'.format(pkg_dir))
        os.system('nrnivmodl {}'.format(pkg_dir))
        from neuron import load_mechanisms
        load_mechanisms(pkg_dir)
        print(' Compilation of support folder mod files successful')
    except Exception as err:
        print(' Error compiling support folder mod files')
        print(err)
        return
Ejemplo n.º 19
0
def run():
    # Folder that contains x86_64 folder
    NETPYNE_WORKDIR_PATH = "../../../"
    neuron.load_mechanisms(NETPYNE_WORKDIR_PATH)

    # read cfg and netParams from command line arguments if available; otherwise use default
    simConfig, netParams = sim.readCmdLineArgs(simConfigDefault="cfg.py",
                                               netParamsDefault="netParams.py")

    # Create network and run simulation
    sim.createSimulate(netParams=netParams, simConfig=simConfig)
    sim.saveData()
Ejemplo n.º 20
0
def importCellsFromNet(netParams, fileName, labelList, condsList,
                       cellNamesList, importSynMechs):
    """
    importCellsFromNet
    Import cell from HOC template or python file into framework format (dict of sections, with geom, topol, mechs, syns)
    """

    h.initnrn()

    if fileName.endswith('.hoc') or fileName.endswith('.tem'):
        print('Importing from .hoc network not yet supported')
        return
        # h.load_file(fileName)
        # for cellName in cellNames:
        #     cell = getattr(h, cellName) # create cell using template, passing dict with args
        #     secDic, secListDic, synMechs = getCellParams(cell)

    elif fileName.endswith('.py'):
        origDir = os.getcwd()
        filePath, fileNameOnly = os.path.split(
            fileName)  # split path from filename
        if filePath not in sys.path:  # add to path if not there (need to import module)
            sys.path.insert(0, filePath)
            removeFilePath = True
        else:
            removeFilePath = False
        moduleName = fileNameOnly.split('.py')[
            0]  # remove .py to obtain module name
        os.chdir(filePath)
        print('\nRunning network in %s to import cells into NetPyNE ...\n' %
              (fileName))
        from neuron import load_mechanisms
        load_mechanisms(filePath)
        tempModule = importlib.import_module(moduleName)
        modulePointer = tempModule
        if removeFilePath: sys.path.remove(filePath)
    else:
        print("File name should be either .hoc or .py file")
        return

    for label, conds, cellName in zip(labelList, condsList, cellNamesList):
        print('\nImporting %s from %s ...' % (cellName, fileName))
        exec('cell = tempModule' + '.' + cellName)
        #cell = getattr(modulePointer, cellName) # get cell object
        varList = mechVarList()
        origGlob = getGlobals(
            list(varList['mechs'].keys()) + list(varList['pointps'].keys()))
        secs, secLists, synMechs = getCellParams(cell, varList, origGlob)
        cellRule = {'conds': conds, 'secs': secs, 'secLists': secLists}
        netParams.addCellParams(label, cellRule)
        if importSynMechs:
            for synMech in synMechs:
                netParams.addSynMechParams(synMech.pop('label'), synMech)
Ejemplo n.º 21
0
def return_cell(synaptic_y_pos=900, conductance_type='active', weight=0.001, input_spike_train=np.array([10.])):
    """
    Runs a NEURON simulation and returns an LFPy cell object for a single synaptic input.
    :param synaptic_y_pos: position along the apical dendrite where the synapse is inserted.
    :param conductance_type: Either 'active' or 'passive'. If 'active' all original ion-channels are included,
           if 'passive' they are all removed, yielding a passive cell model.
    :param weight: Strength of synaptic input.
    :param input_spike_train: Numpy array containing synaptic spike times
    :return: cell object where cell.imem gives transmembrane currents, cell.vmem gives membrane potentials.
             See LFPy documentation for more details and examples.
    """
    nrn('forall delete_section()')
    model_path = join('hay_model')
    neuron.load_mechanisms(join(model_path, 'mod'))
    cell_parameters = {
        'morphology': join(model_path, 'cell1.hoc'),
        'v_init': -65,
        'passive': False,
        'nsegs_method': 'lambda_f',
        'lambda_f': 100,
        'timeres_NEURON': 2**-3,  # Should be a power of 2
        'timeres_python': 2**-3,
        'tstartms': -200,
        'tstopms': 200,
        'custom_code': [join(model_path, 'custom_codes.hoc')],
        'custom_fun': [active_declarations],
        'custom_fun_args': [{'conductance_type': conductance_type}],
    }
    cell = LFPy.Cell(**cell_parameters)
    synapse_parameters = {
        # 'idx': cell.get_closest_idx(x=0., y=synaptic_y_pos, z=0.),
        'e': 0.,
        'syntype': 'ExpSyn',
        'tau': 10.,
        'weight': 0.004, #weight,
        'record_current': True,
    }

    # synapse = LFPy.Synapse(cell, **synapse_parameters)
    # synapse.set_spike_times(input_spike_train)

    n = 0
    ypos = np.linspace(400,900,5)
    while n < len(ypos):
        synapse_parameters['idx'] = cell.get_closest_idx(x=0., y=ypos[n], z=0.)
        synapse = LFPy.Synapse(cell,**synapse_parameters)
        synapse.set_spike_times(input_spike_train)
        print 'Synapse ', n, ' inserted!'
        n += 1

    cell.simulate(rec_imem=True, rec_vmem=True)
    return cell
Ejemplo n.º 22
0
def compile_and_load_mods(mod_folders):
    if isinstance(mod_folders, str):
        mod_folders = mod_folders.split(" ")

    mod_folders = [m for m in mod_folders if m not in mods_loaded]

    if len(mod_folders) > 0:
        comp = CompileMOD()
        targ_path = os.path.join(os.getcwd(), "compiled",
                                 "mods%s" % len(mods_loaded))
        comp.compile(source_paths=mod_folders, target_path=targ_path)
        neuron.load_mechanisms(targ_path)
        mods_loaded.extend(mod_folders)
Ejemplo n.º 23
0
    def compileModMechFiles(self, compileMod, modFolder):
        #Create Symbolic link
        if compileMod:
            modPath = os.path.join(str(modFolder), "x86_64")

            subprocess.call(["rm", "-r", modPath])

            os.chdir(modFolder)
            subprocess.call(["nrnivmodl"])

        # Load mechanism if mod path is passed
        if modFolder:
            neuron.load_mechanisms(str(modFolder))
Ejemplo n.º 24
0
def test_ca_initiation():

    timeres = 2**-2
    cut_off = 0
    tstopms = 6000
    tstartms = -cut_off
    model_path = join('lfpy_version')
    neuron.load_mechanisms('mod')
    cell_params = {
        'morphology': join(model_path, 'morphologies', 'cell1.hoc'),
        #'rm' : 30000,               # membrane resistance
        #'cm' : 1.0,                 # membrane capacitance
        #'Ra' : 100,                 # axial resistance
        'v_init': -60,             # initial crossmembrane potential
        'passive': False,           # switch on passive mechs
        'nsegs_method': 'lambda_f',  # method for setting number of segments,
        'lambda_f': 100,           # segments are isopotential at this frequency
        'timeres_NEURON': timeres,   # dt of LFP and NEURON simulation.
        'timeres_python': 1,
        'tstartms': tstartms,          # start time, recorders start at t=0
        'tstopms': tstopms,
        'custom_code': [join(model_path, 'custom_codes.hoc')],
        'custom_fun': [active_declarations],  # will execute this function
        'custom_fun_args': [{'conductance_type': 'active',
                             'hold_potential': -60}],
    }
    cell = LFPy.Cell(**cell_params)
    cell.simulate(rec_vmem=True, rec_imem=True)
    plt.subplots_adjust(wspace=0.6, hspace=0.6)
    plt.subplot(231, title='Membrane potential soma')
    plt.plot(cell.tvec, cell.vmem[0, :])
    plt.ylim([-61.5, -59.8])
    plt.subplot(232, title='Calcium current soma')
    plt.plot(cell.tvec, cell.rec_variables['ica'][0, :])
    plt.ylim([0, -0.000008])
    plt.subplot(233, title='Calcium concentration soma')
    plt.plot(cell.tvec, cell.rec_variables['cai'][0, :])
    plt.ylim([0, 0.00015])

    apic_idx = cell.get_closest_idx(x=0, y=0, z=1000)
    plt.subplot(234, title='Membrane potential apic')
    plt.plot(cell.tvec, cell.vmem[apic_idx, :])
    plt.ylim([-61.5, -59.8])
    plt.subplot(235, title='Calcium current apic')
    plt.plot(cell.tvec, cell.rec_variables['ica'][apic_idx, :])
    plt.ylim([0, -0.000008])
    plt.subplot(236, title='Calcium concentration apic')
    plt.plot(cell.tvec, cell.rec_variables['cai'][apic_idx, :])
    plt.ylim([0, 0.00015])
    # plt.savefig('ca_initiation_init.png')
    plt.show()
Ejemplo n.º 25
0
    def test_tut4(self):
        print("------------------------------------")
        print("Tutorial 4 Instantiation:")
        print("------------------------------------")
        modelpath = os.path.join(self.path, 'tut4')
        subprocess.call(["rm", "-r", os.path.join(modelpath, "x86_64")])
        owd = os.getcwd()
        os.chdir(modelpath)
        p = subprocess.check_output(["nrnivmodl"])
        os.chdir(owd)
        neuron.load_mechanisms(modelpath)

        from netpyne_ui.examples.tut4.tut4 import netParams, simConfig
        self.getGeppettoModel(netParams, simConfig)
Ejemplo n.º 26
0
    def neuron(self):
        """Return neuron module"""

        if self.disable_banner and not self.banner_disabled:
            NrnSimulator._nrn_disable_banner()
            self.banner_disabled = True

        import neuron  # NOQA

        if self.mechanisms_directory is not None:
            neuron.load_mechanisms(self.mechanisms_directory,
                                   warn_if_already_loaded=False)

        return neuron
Ejemplo n.º 27
0
def example_white_noise(synaptic_y_pos=0,
                        conductance_type='active',
                        weight=0.001):
    """
    Runs a NEURON simulation and returns an LFPy cell object for a single synaptic input.
    :param synaptic_y_pos: position along the apical dendrite where the synapse is inserted.
    :param conductance_type: Either 'active' or 'passive'. If 'active' all original ion-channels are included,
           if 'passive' they are all removed, yielding a passive cell model.
    :param weight: Strength of synaptic input.
    :param input_spike_train: Numpy array containing synaptic spike times
    :return: cell object where cell.imem gives transmembrane currents, cell.vmem gives membrane potentials.
             See LFPy documentation for more details and examples.
    """

    #  Making cell
    model_path = join('hay_model')
    neuron.load_mechanisms(join(model_path, 'mod'))

    # Repeat same stimuli and save only the last
    repeats = 2
    sim_time = 1000

    cell_parameters = {
        'morphology': join(model_path, 'cell1.hoc'),
        'v_init': -65,
        'passive': False,
        'nsegs_method': 'lambda_f',
        'lambda_f': 100,
        'timeres_NEURON': 2**-3,  # Should be a power of 2
        'timeres_python': 2**-3,
        'tstartms': 0,
        'tstopms': sim_time * repeats,
        'custom_code': [join(model_path, 'custom_codes.hoc')],
        'custom_fun': [active_declarations],
        'custom_fun_args': [{
            'conductance_type': conductance_type
        }],
    }
    cell = LFPy.Cell(**cell_parameters)
    input_idx = cell.get_closest_idx(x=0., y=synaptic_y_pos, z=0.)

    cell, synapse, noiseVec = make_white_noise(cell, weight, input_idx)
    cell.simulate(rec_imem=True, rec_vmem=True)
    if not repeats is None:
        cut_off_idx = (len(cell.tvec) - 1) / repeats
        cell.tvec = cell.tvec[-cut_off_idx:] - cell.tvec[-cut_off_idx]
        cell.imem = cell.imem[:, -cut_off_idx:]
        cell.vmem = cell.vmem[:, -cut_off_idx:]

    plot_electrode_signal(cell, input_idx, True)
Ejemplo n.º 28
0
def neuron_import(request):
    """Provides an instance of neuron h and rxd for tests"""

    # to use NEURON with MPI, mpi4py must be imported first.
    if request.config.getoption("--mpi"):
        from mpi4py import MPI  # noqa: F401

    # we may not be not running in the test path so we have to load the mechanisms
    import neuron

    neuron.load_mechanisms(osp.abspath(osp.dirname(__file__)))
    from neuron import h, rxd

    return h, rxd
Ejemplo n.º 29
0
 def setUpClass(cls):
     HERE = os.path.dirname(os.path.realpath(__file__))
     ROOT = os.path.dirname(HERE)
     cls.path = NETPYNE_WORKDIR_PATH
     modelpath = os.path.join(NETPYNE_WORKDIR_PATH, 'mod')
     subprocess.call(["rm", "-r", os.path.join(modelpath, "x86_64")])
     owd = os.getcwd()
     os.chdir(modelpath)
     p = subprocess.check_output(["nrnivmodl"])
     os.chdir(owd)
     try:
         neuron.load_mechanisms(modelpath)
     except:
         logging.error("Error loading mechanisms", exc_info=True)
Ejemplo n.º 30
0
 def __init__(self, component, parameters, initial_values, expected_spike_times, run_time):
     configure(1e-6)
     self.component = component
     build_dir = write_and_compile_nmodl(component)
     load_mechanisms(build_dir)
     self.name = component.name
     self.section = h.Section()
     self.cell = getattr(h, self.name)(0.5, sec=self.section)
     for param, value in parameters.items():
         setattr(self.cell, param, value)
     self.initial_values = initial_values
     initializer.register(self)
     self.setup_recording()
     self.expected_spike_times = numpy.array(expected_spike_times)
     self.run_time = run_time
Ejemplo n.º 31
0
def compileModMechFiles(compileMod, modFolder):
    # Create Symbolic link
    if compileMod:
        modPath = os.path.join(str(modFolder), "x86_64")

        if os.path.exists(modPath):
            shutil.rmtree(modPath)

        os.chdir(modFolder)
        subprocess.call(["nrnivmodl"])
        os.chdir('..')

        try:
            neuron.load_mechanisms(str(modFolder))
        except:
            raise
Ejemplo n.º 32
0
def load_neuron_modules(mechanisms_dir, templates_dir, default_templates=True):
    """

    :param mechanisms_dir:
    :param templates_dir:
    :param default_templates:
    """
    h.load_file('stdgui.hoc')

    bionet_dir = os.path.dirname(__file__)
    # h.load_file(os.path.join(bionet_dir, 'import3d.hoc'))  # customized import3d.hoc to supress warnings
    # h.load_file('import3d.hoc')
    h.load_file(os.path.join(bionet_dir,'default_templates',  'advance.hoc'))

    if mechanisms_dir is not None:
        neuron.load_mechanisms(str(mechanisms_dir))
Ejemplo n.º 33
0
 def __init__(self, component, parameters, initial_values,
              expected_spike_times, run_time):
     configure(1e-6)
     self.component = component
     build_dir = write_and_compile_nmodl(component)
     load_mechanisms(build_dir)
     self.name = component.name
     self.section = h.Section()
     self.cell = getattr(h, self.name)(0.5, sec=self.section)
     for param, value in parameters.items():
         setattr(self.cell, param, value)
     self.initial_values = initial_values
     initializer.register(self)
     self.setup_recording()
     self.expected_spike_times = numpy.array(expected_spike_times)
     self.run_time = run_time
Ejemplo n.º 34
0
def create_functional_network(cellParamName, nwParamName):
    '''
    Public interface:
    used for creating fixed functional connectivity.
    cellParamName - parameter file of postsynaptic neuron
    nwParamName - parameter file of anatomical network
    '''
    preParam = build_parameters(cellParamName)
    neuronParam = preParam.neuron
    nwParam = build_parameters(nwParamName)
    for mech in nwParam.NMODL_mechanisms.values():
        neuron.load_mechanisms(mech)
    parser = cell_parser.CellParser(neuronParam.filename)
    parser.spatialgraph_to_cell()
    nwMap = NetworkMapper(parser.cell, nwParam)
    nwMap.create_functional_realization()
Ejemplo n.º 35
0
    def test_M1detailed(self):
        print("------------------------------------")
        print("M1 detailed Instantiation:")
        print("------------------------------------")
        modelpath = os.path.join(self.path, 'M1detailed')
        modpath = os.path.join(modelpath, 'mod')
        subprocess.call(["rm", "-r", os.path.join(modpath, "x86_64")])
        owd = os.getcwd()
        os.chdir(modpath)
        p = subprocess.check_output(["nrnivmodl"])
        neuron.load_mechanisms(modpath)
        os.chdir(modelpath)

        from netpyne_ui.examples.M1detailed.init import netParams, cfg
        self.getGeppettoModel(netParams, cfg)

        os.chdir(owd)
Ejemplo n.º 36
0
    def __init__(self, 
                 biochemical_filename, 
                 big_spine, 
                 dt, 
                 hoc_path="hoc",
                 mod_path="mod", 
                 msn=True, 
                 spines_dist=None):
        """Load and initiate all the hoc and mod file. Can load the model of the neuron
        or otherwise can just expose general method"""
        
        # Mod file are always in a mod directory
        if not os.path.exists(mod_path) :
            print "ERROR mod path %s doesn't exist" %os.path.realpath(mod_path)
            sys.exit(1)
        neuron.load_mechanisms(mod_path)
        
        if not os.path.exists(hoc_path):
            print "ERROR hoc path %s doesn't exist" %os.path.realpath(hoc_path)
            sys.exit(1)
        # Hoc file assumes all the file are launched from a top directory
        head, tail  = os.path.split(os.path.realpath(hoc_path))

        preface_pos = head
        
        h('strdef preface, dirstr') # preface and dirstr used in each hoc
        preface_string = "preface = \"" + preface_pos + "\""
        h(preface_string)
        
        if msn:
            # Loading the MSN model
            h.load_file(os.path.join(hoc_path, "nacb_main.hoc"))
            self._set_geometry()
            
            self.biochemical_filename = biochemical_filename
            # Adding the spines
            self.distribute_spines(spines_dist, big_spine)
        
        h.load_file("stdrun.hoc")
        h.v_init = -87.75 #Setting the vinit
        self.dt = h.dt = dt #setting internally and externally 
Ejemplo n.º 37
0
def nrnivmodl(directory='.', suppress=False):
    """
    Should avoid using relative paths as neuron will complain on
    running neuron.load_mechanisms twice on the same directory path.

    E.g. :
    Don't do this.
        os.chdir(mech_1)
        LFPy_util.other.nrnivmodl(".")
        os.chdir(mech_2)
        LFPy_util.other.nrnivmodl(".")
    Do this.
        LFPy_util.other.nrnivmodl(mech_1)
        LFPy_util.other.nrnivmodl(mech_2)
    """
    tmp = os.getcwd()
    with suppress_stdout_stderr(suppress):
        os.chdir(directory)
        devnull = open(os.devnull, 'w') if suppress else None
        subprocess.call(['nrnivmodl'], stdout=devnull, shell=True)
        neuron.load_mechanisms(directory)
    os.chdir(tmp)
Ejemplo n.º 38
0
    def initRegionIndices(self, marksFile):

        nrn.load_mechanisms(os.path.join(self.packagePrefix, 'etc'))

        for sec in self.allsec.values():
            sec.insert('regionInd')

        marksFle = open(marksFile, 'r')

        #skip commented lines
        tempStr = '#'
        startChar = tempStr[0]
        while (startChar == '#') or (startChar == '\n'):
            tempStr = marksFle.readline()
            startChar = tempStr[0]

        tempStr = tempStr.rstrip('\n')
        marksFle.close()
        tempWords = tempStr.split('\t')
        branchPointMark = tempWords[0]
        regionMarks = tempWords[1:len(self.subTreesLabels) + 1]

        self.regionMarkSecs = [0] * len(self.subTreesLabels)
        regionMarksDone = 0

        for secName, sec in self.allsec.iteritems():

            secName = sec.name()
            if secName == branchPointMark:
                self.branchPointSec = sec
            elif (secName in regionMarks) and (regionMarksDone < len(self.subTreesLabels)):
                self.regionMarkSecs[regionMarks.index(secName)] = sec
                regionMarksDone += 1

        for secInd in range(len(self.regionMarkSecs)):
            regionMarkSectionPtr = self.getPtr(self.regionMarkSecs[secInd])
            self.setRegionIndex(secInd + 1, regionMarkSectionPtr)
            #include the demarkating section in the active zone.
            regionMarkSectionPtr.sec().regionInd.index = 0
Ejemplo n.º 39
0
def importCellsFromNet (netParams, fileName, labelList, condsList, cellNamesList, importSynMechs):
    h.initnrn()

    ''' Import cell from HOC template or python file into framework format (dict of sections, with geom, topol, mechs, syns)'''
    if fileName.endswith('.hoc'):
        print 'Importing from .hoc network not yet supported'
        return
        # h.load_file(fileName)
        # for cellName in cellNames:
        #     cell = getattr(h, cellName) # create cell using template, passing dict with args
        #     secDic, secListDic, synMechs = getCellParams(cell)

    elif fileName.endswith('.py'):
        origDir = os.getcwd()
        filePath,fileNameOnly = os.path.split(fileName)  # split path from filename
        if filePath not in sys.path:  # add to path if not there (need to import module)
            sys.path.insert(0, filePath)
        moduleName = fileNameOnly.split('.py')[0]  # remove .py to obtain module name
        os.chdir(filePath)
        print '\nRunning network in %s to import cells into NetPyNE ...\n'%(fileName)
        from neuron import load_mechanisms
        load_mechanisms(filePath)
        exec('import ' + moduleName + ' as tempModule') in globals(), locals() # import module dynamically
        modulePointer = tempModule
        sys.path.remove(filePath)
    else:
        print "File name should be either .hoc or .py file"
        return

    for label, conds, cellName in zip(labelList, condsList, cellNamesList):
        print '\nImporting %s from %s ...'%(cellName, fileName)
        exec('cell = tempModule' + '.' + cellName)
        #cell = getattr(modulePointer, cellName) # get cell object
        secs, secLists, synMechs = getCellParams(cell)
        cellRule = {'conds': conds, 'secs': secs, 'secLists': secLists}
        netParams.addCellParams(label, cellRule)
        if importSynMechs:
            for synMech in synMechs: netParams.addSynMechParams(synMech.pop('label'), synMech)
Ejemplo n.º 40
0
Archivo: base.py Proyecto: tclose/PyPe9
 def load_libraries(cls, _, install_dir):
     load_mechanisms(os.path.dirname(install_dir))
Ejemplo n.º 41
0
                                                os.path.join(NMODL,
                                                         '.')))
    os.chdir(NMODL)
    if "win32" in sys.platform:
        warn("no autompile of NMODL (.mod) files on Windows. " 
         + "Run mknrndll from NEURON bash in the folder %s and rerun example script" % NMODL)
    else:
        os.system('nrnivmodl')        
    os.chdir(CWD)
COMM.Barrier()
if "win32" in sys.platform:
    if not NMODL in neuron.nrn_dll_loaded:
        neuron.h.nrn_load_dll(NMODL+"/nrnmech.dll")
    neuron.nrn_dll_loaded.append(NMODL)
else:
    neuron.load_mechanisms(NMODL)

os.chdir(CWD)

FIGS = 'hoc_combos_syn.1_0_10.allfigures'
if not os.path.isdir(FIGS):
    os.mkdir(FIGS)


#load the LFPy SinSyn mechanism for stimulus
if "win32" in sys.platform:
    pth = os.path.join(LFPy.__path__[0], "test").replace(os.sep, posixpath.sep)
    if not pth in neuron.nrn_dll_loaded:
        neuron.h.nrn_load_dll(pth + "/nrnmech.dll")
    neuron.nrn_dll_loaded.append(pth)
else:
Ejemplo n.º 42
0
    for s in string:
        for ss in s.split(':'):
            savefolder += ss + '_'
    savefolder += uuid.uuid4().hex
    os.mkdir(savefolder)
    os.system("cp %s  '%s'" % (__file__, savefolder + '/.'))
else:
    savefolder = None
savefolder = COMM.bcast(savefolder, root=0)



##### load NMODL mechanisms ####################################################
#neuron.h.load_file('stdlib.hoc')
#neuron.h.load_file('nrngui.hoc')
neuron.load_mechanisms("modfiles")


################################################################################
# PARAMETERS
################################################################################

tstart = 0
tend = 60000
dt = 0.05

#set up base parameter file for the LFPy.Cell or LFPy.TemplateCell class,
#without specifying cell model.
cellParameters = {
    'v_init' : -65,
    'passive' : False,
Ejemplo n.º 43
0
################# Initialization of MPI stuff ##################################
COMM = MPI.COMM_WORLD
SIZE = COMM.Get_size()
RANK = COMM.Get_rank()

#if True, execute full model. If False, do only the plotting. Simulation results
#must exist.
properrun = True


#check if mod file for synapse model specified in alphaisyn.mod is loaded
if not hasattr(neuron.h, 'AlphaISyn'):
    if RANK == 0:
        os.system('nrnivmodl')
    COMM.Barrier()
    neuron.load_mechanisms('.')


################################################################################
## PARAMETERS
################################################################################

#Set up parameters using the NeuroTools.parameters.ParameterSet class.

#Access parameters defined in example script implementing the network using
#pynest, brunel_alpha_nest.py, adapted from the NEST v2.4.1 release. This will
#not execute the network model, but see below.
import brunel_alpha_nest as BN


#set up file destinations differentiating between certain output
Ejemplo n.º 44
0
    myzip.close()

#compile mod files every time, because of incompatibility with Hay2011 files:
if "win32" in sys.platform:
    pth = "cells"
    warn("no autompile of NMODL (.mod) files on Windows. " 
         + "Run mknrndll from NEURON bash in the folder cells and rerun example script")
    if not pth in neuron.nrn_dll_loaded:
        neuron.h.nrn_load_dll(pth+"/nrnmech.dll")
    neuron.nrn_dll_loaded.append(pth)
else:
    os.system('''
              cd cells
              nrnivmodl
              ''')
    neuron.load_mechanisms('cells')

################################################################################
# Define parameters, using dictionaries
# It is possible to set a few more parameters for each class or functions, but
# we chose to show only the most important ones here.
################################################################################

#define cell parameters used as input to cell-class
cellParameters = {
    'morphology' : 'morphologies/L5_Mainen96_wAxon_LFPy.hoc',
    'cm' : 1.0,                 # membrane capacitance
    'Ra' : 150,                 # axial resistance
    'v_init' : -65,             # initial crossmembrane potential
    'passive' : True,           # turn on passive mechanism
    'passive_parameters' : {'g_pas' : 1./30000, 'e_pas' : -65}, # passive params
        os.chdir(PSET.NMODL)
        # patch faulty ProbGABAAB_EMS.mod file (otherwise stochastic inhibitory synapses will stay closed except at first activation)
        diff = '''319c319
<                 urand = scop_random(1)
---
>                 value = scop_random(1)
'''
        f = open('ProbGABAAB_EMS.patch', 'w')
        f.writelines(diff)
        f.close()
        os.system('patch ProbGABAAB_EMS.mod ProbGABAAB_EMS.patch')
        
        os.system('nrnivmodl')
        os.chdir(PSET.CWD)
COMM.Barrier()
neuron.load_mechanisms(PSET.NMODL)
os.chdir(PSET.CWD)


# Fill in dictionary of population-specific cell parameters
for NRN in PSET.populationParameters['me_type']:
    os.chdir(os.path.join(PSET.CWD, PSET.CELLPATH, NRN))
    
    #get the template name
    f = open("template.hoc", 'r')
    templatename = get_templatename(f)
    f.close()
    
    #get biophys template name
    f = open("biophysics.hoc", 'r')
    biophysics = get_templatename(f)
def runsimulation(legtext,amp1,dur1,start1):
	def recvolt(seg):
		rec_v=neuron.h.Vector()
		rec_v.record(seg._ref_v)
		return rec_v

	def rectime(seg):
		rec_t=neuron.h.Vector()
		rec_t.record(seg._ref_t)
		return rec_t


	def setstim(seg,amp,duration,start,segdist):
		stim=neuron.h.IClamp(seg(segdist))
		stim.delay=start
		stim.dur=duration
		stim.amp=amp
		return stim

	load_mechanisms("/home/ben/boxing_bk/neuron_model/downloaded_models/Figure5/")


		
	#neuron.h.create soma
	cell1=cell(maxNa,maxK,maxLeak,NaRev,KRev,LeakRev)

	rec_v_cell1=recvolt(cell1.soma(0.5))

	###SPECIFY THE VALUES OF THE SECTION TO BE RECORDED##
	#record time from NEURON (neuron.h._ref_t)
	rec_t=neuron.h.Vector()
	rec_t.record(neuron.h._ref_t)
	#record voltage from center of the soma

	#for i in dends:



	cell1_stim=setstim(cell1.soma,amp1,dur1,start1,0.5)



	'''ATTRIBUTES OF ELECTRODE
	amp: Amplitude of the injected current
	delay: Time of activation in ms
	dur: Duration of the stimulation
	'''

	#initialize the value of the voltage
	neuron.h.finitialize(-65)
	#set time of the simulation
	tstop=300

	#create ndendrites
	ndend=1
	dends=range(ndend)

	#Run the simulation
	neuron.run(tstop)

	#PLOT THE RESULT
	time=rec_t.as_numpy()

	cell1_volt=rec_v_cell1.as_numpy()

	plt.plot(time,cell1_volt,color=colors[cellnum],linewidth=3.0)
	legendlist.append(legtext)

	plt.legend(legendlist)
	global cellnum
	if cellnum==4:
		cellnum=0
	else:
		cellnum=cellnum+1
		
	#plt.plot(time,cell2_volt,color='k',linewidth=3.0)
	plt.xlabel("Time (ms)")
	plt.ylabel("Voltage (mV)")

	#plt.axis(xmin=210,xmax=216,\
		 #ymin=min(cell1_volt)-5,ymax=max(cell1_volt)+5)

	plt.show()
Ejemplo n.º 47
0
    myzip.close()

#compile mod files every time, because of incompatibility with Mainen96 files:
if "win32" in sys.platform:
    pth = "L5bPCmodelsEH/mod/"
    warn("no autompile of NMODL (.mod) files on Windows.\n" 
         + "Run mknrndll from NEURON bash in the folder L5bPCmodelsEH/mod and rerun example script")
    if not pth in neuron.nrn_dll_loaded:
        neuron.h.nrn_load_dll(pth+"nrnmech.dll")
    neuron.nrn_dll_loaded.append(pth)
else:
    os.system('''
              cd L5bPCmodelsEH/mod/
              nrnivmodl
              ''')
    neuron.load_mechanisms('L5bPCmodelsEH/mod/')

    

################################################################################
# Simulation parameters
################################################################################

##define cell parameters used as input to cell-class
cellParameters = {
    'morphology'    : 'L5bPCmodelsEH/morphologies/cell1.asc',
    'templatefile'  : ['L5bPCmodelsEH/models/L5PCbiophys3.hoc',
                       'L5bPCmodelsEH/models/L5PCtemplate.hoc'],
    'templatename'  : 'L5PCtemplate',
    'templateargs'  : 'L5bPCmodelsEH/morphologies/cell1.asc',
    'passive' : False,
Ejemplo n.º 48
0
        else:
            raise Exception("synapse type does not have an attribute '%s'" % name)
    return property(_get, _set)
setattr(Connection, 'U', generate_synapse_property('U'))
setattr(Connection, 'tau_rec', generate_synapse_property('tau_rec'))
setattr(Connection, 'tau_facil', generate_synapse_property('tau_facil'))
setattr(Connection, 'u0', generate_synapse_property('u0'))

def generate_stdp_property(name):
    def _get(self):
        return getattr(self.weight_adjuster, name)
    def _set(self, val):
        setattr(self.weight_adjuster, name, val)
    return property(_get, _set)
setattr(Connection, 'w_max', generate_stdp_property('wmax'))
setattr(Connection, 'w_min', generate_stdp_property('wmin'))
setattr(Connection, 'A_plus', generate_stdp_property('aLTP'))
setattr(Connection, 'A_minus', generate_stdp_property('aLTD'))
setattr(Connection, 'tau_plus', generate_stdp_property('tauLTP'))
setattr(Connection, 'tau_minus', generate_stdp_property('tauLTD'))


# --- Initialization, and module attributes ------------------------------------

mech_path = os.path.join(pyNN_path[0], 'neuron', 'nmodl')
load_mechanisms(mech_path) # maintains a list of mechanisms that have already been imported
state = _State()  # a Singleton, so only a single instance ever exists
del _State
initializer = _Initializer()
del _Initializer
Ejemplo n.º 49
0
        #unzip:
        myzip = zipfile.ZipFile('L5bPCmodelsEH.zip', 'r')
        myzip.extractall('.')
        myzip.close()
    
        #compile NMODL language files
        os.system('''
                  cd L5bPCmodelsEH/mod/
                  nrnivmodl
                  cd -
                  ''')
    COMM.Barrier()


##### load NEURON mechanisms from Hay et al. 2011 ##############################
neuron.load_mechanisms("L5bPCmodelsEH/mod")


################################################################################
# PARAMETERS
################################################################################

#set up base parameter file for the LFPy.Cell or LFPy.TemplateCell class,
#without specifying cell model. 
cellParameters = {
    'v_init' : -80,
    'passive' : False,
    'nsegs_method' : None,
    'timeres_NEURON' : 2**-5,
    'timeres_python' : 2**-5,
    'tstartms' : 0.,
Ejemplo n.º 50
0
#
######################################################################################

# MODIFIED HISTORY
# 2015.04.30 This code is eddited for al_V2

from neuron import h
import neuron as nrn
import os.path
import numpy as np
import csv
import operator
import random

import swc
nrn.load_mechanisms("./mod")
h.load_file("../input/swc/CellSwc_Ver2.hoc")

def CalcDistance(cmpt1, cmpt2):
    #cmpt means compartment
    cmpt1.push()
    sr1 = h.SectionRef(sec=cmpt1)
    x1 = h.x3d(0.5)
    y1 = h.y3d(0.5)
    z1 = h.z3d(0.5)
    h.pop_section()

    cmpt2.push()
    sr2 = h.SectionRef(sec=cmpt2)
    x2 = h.x3d(0.5)
    y2 = h.y3d(0.5)
Ejemplo n.º 51
0
 def load_libraries(self, name, url):
     install_dir = self.get_install_dir(name, url)
     load_mechanisms(os.path.dirname(install_dir))
Ejemplo n.º 52
0
import os
import posixpath
import unittest
import numpy as np
import LFPy
import neuron

# for nosetests to run load mechanisms
if "win32" in sys.platform:
    pth = os.path.join(LFPy.__path__[0], 'test', 'nrnmech.dll')
    pth = pth.replace(os.sep, posixpath.sep)
    if not pth in neuron.nrn_dll_loaded:
        neuron.h.nrn_load_dll(pth)
        neuron.nrn_dll_loaded.append(pth)
else:
    neuron.load_mechanisms(os.path.join(LFPy.__path__[0], 'test'))

class testPointProcess(unittest.TestCase):
    """
    test class LFPy.PointProcess
    """
    def test_PointProcess_00(self):
        cell = LFPy.Cell(morphology=os.path.join(LFPy.__path__[0], 'test',
                                                 'ball_and_sticks.hoc'))
        pp = LFPy.PointProcess(cell=cell, idx=0)
        self.assertTrue(np.alltrue(np.array([pp.x, pp.y, pp.z])==cell.somapos))
        self.assertEqual(pp.idx, 0)
    

class testSynapse(unittest.TestCase):
    """
Ejemplo n.º 53
0
	stim.delay=delay
	stim.dur=dur
	stim.amp=amp
	return stim

def recvolt(seg):
	rec_v=neuron.h.Vector()
	rec_v.record(seg._ref_v)
	return rec_v

def rectime(seg):
	rec_t=neuron.h.Vector()
	rec_t.record(seg._ref_t)
	return rec_t

load_mechanisms('/home/ben/Desktop/5ht3a_project/neuron_model/downloaded_neuron_models/Hipp_paper_code/')

h.xopen('/home/ben/Desktop/5ht3a_project/neuron_model/downloaded_neuron_models/Hipp_paper_code/basket_cell17S.hoc')
h.xopen('/home/ben/Desktop/5ht3a_project/neuron_model/downloaded_neuron_models/Hipp_paper_code/pyramidal_cell_14Vb.hoc')
h.xopen('/home/ben/Desktop/5ht3a_project/neuron_model/downloaded_neuron_models/Hipp_paper_code/olm_cell2.hoc')


pyrstren=np.arange(.005,.01,.001)
pvstren=np.arange(0,0.3,.05)


olmexcstren=np.arange(.05,.055,.001)
olmstren=np.arange(.04,.05,.002)
olmcombs=itertools.product(olmexcstren,olmstren)
pvpyrcombs=itertools.product(pyrstren,pvstren)
Ejemplo n.º 54
0
'''

import os
from os.path import join
import sys
from glob import glob
import numpy as np
import matplotlib
matplotlib.use('Agg')
import pylab as plt
import neuron
import LFPy

neuron.h.load_file("stdrun.hoc")
neuron.h.load_file("import3d.hoc")
neuron.load_mechanisms('mods')


def get_templatename(f):
    '''
    Assess from hoc file the templatename being specified within

    Arguments
    ---------
    f : file, mode 'r'

    Returns
    -------
    templatename : str

    '''