コード例 #1
0
    def __init__(self,
                 t_trial,
                 n_trials,
                 seed,
                 path,
                 dt=0.05,
                 do_parallel=False):
        Simulation.__init__(self, dt, t_trial, n_trials, seed)
        global _loaded
        if not _loaded:
            h.nrn_load_dll(path + "/x86_64/.libs/libnrnmech.so")
            h.load_file("stdrun.hoc")
            _loaded = True

        self.do_parallel = do_parallel
        if do_parallel:
            self.pc = h.ParallelContext()
            self.id = int(self.pc.id())
            self.nhost = int(self.pc.nhost())
        else:
            self.id = 0
            self.nhost = 1
        print("I am {} of {}".format(self.id, self.nhost))
        h.celsius = 34
        h.dt = self.dt
        h.steps_per_ms = 1.0 / self.dt
        self._gif_fun = dict()
        self._inner_current = dict()
        self._connections = []
        self.synapses = dict()
        self.randoms = [seed]
        self.spikes = dict()
コード例 #2
0
ファイル: controls.py プロジェクト: uricohen/neuronvisio
 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
コード例 #3
0
ファイル: controls.py プロジェクト: Rauell/neuron
 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)
コード例 #4
0
ファイル: simulator.py プロジェクト: JoelChavas/PyNN
def load_mechanisms(path):
    """
    Search for and load NMODL mechanisms from the path given.

    This a stricter version of NEURON's own load_mechanisms function, which will
    raise an IOError if no mechanisms are found at the given path. This function
    will not load a mechanism path twice.

    The path should specify the directory in which nrnivmodl was run, and in
    which the directory 'i686' (or 'x86_64' or 'powerpc' depending on your
    platform) was created.
    """
    import platform

    global nrn_dll_loaded
    if path in nrn_dll_loaded:
        logger.warning("Mechanisms already loaded from path: %s" % path)
        return
    # in case NEURON is assuming a different architecture to Python,
    # we try multiple possibilities
    arch_list = [platform.machine(), 'i686', 'x86_64', 'powerpc', 'umac']
    for arch in arch_list:
        lib_path = os.path.join(path, arch, '.libs', 'libnrnmech.so')
        if os.path.exists(lib_path):
            h.nrn_load_dll(lib_path)
            nrn_dll_loaded.append(path)
            return
    raise IOError("NEURON mechanisms not found in %s. You may need to run 'nrnivmodl' in this directory." % path)
コード例 #5
0
ファイル: controls.py プロジェクト: malei-pku/neuronvisio
    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
コード例 #6
0
ファイル: simulator.py プロジェクト: sbillaudelle/PyNN
def load_mechanisms(path):
    """
    Search for and load NMODL mechanisms from the path given.

    This a stricter version of NEURON's own load_mechanisms function, which will
    raise an IOError if no mechanisms are found at the given path. This function
    will not load a mechanism path twice.

    The path should specify the directory in which nrnivmodl was run, and in
    which the directory 'i686' (or 'x86_64' or 'powerpc' depending on your
    platform) was created.
    """
    import platform

    global nrn_dll_loaded
    if path in nrn_dll_loaded:
        logger.warning("Mechanisms already loaded from path: %s" % path)
        return
    # in case NEURON is assuming a different architecture to Python,
    # we try multiple possibilities
    arch_list = [platform.machine(), 'i686', 'x86_64', 'powerpc', 'umac']
    for arch in arch_list:
        lib_path = os.path.join(path, arch, '.libs', 'libnrnmech.so')
        if os.path.exists(lib_path):
            h.nrn_load_dll(lib_path)
            nrn_dll_loaded.append(path)
            return
    raise IOError(
        "NEURON mechanisms not found in %s. You may need to run 'nrnivmodl' in this directory."
        % path)
コード例 #7
0
ファイル: utils.py プロジェクト: appukuttan-shailesh/eFELunit
 def load_mod_files(self):
     os.chdir(self.base_path)
     libpath = "x86_64/.libs/libnrnmech.so.0"
     os.system("nrnivmodl mechanisms")   # do nrnivmodl in mechanisms directory
     if not os.path.isfile(os.path.join(self.base_path, libpath)):
         raise IOError("Error in compiling mod files!")
     h.nrn_load_dll(str(libpath))
     os.chdir(self.owd)
コード例 #8
0
ファイル: utils.py プロジェクト: tbardouille/hnn-core
def load_custom_mechanisms():
    if platform.system() == 'Windows':
        mech_fname = op.join(op.dirname(__file__), '..', 'mod', 'nrnmech.dll')
    else:
        mech_fname = op.join(op.dirname(__file__), '..', 'mod', 'x86_64',
                             '.libs', 'libnrnmech.so')
    h.nrn_load_dll(mech_fname)
    print('Loading custom mechanism files from %s' % mech_fname)
コード例 #9
0
ファイル: __init__.py プロジェクト: asanin-epfl/hoc2swc
def load_mod():
    import fnmatch, os, platform
    from neuron import h

    # Mod files might have already been loaded, loading them again crashes NEURON
    # Need to test if they've been loaded already
    # I cannot find a NEURON function that lists loaded mechanisms, but...
    # Trying to access them directly in Python results in an error - if the mechanism has been loaded
    # The strategy here is to check if tryting to access those mod files throws that error
    mod_files = [
        file.replace('.mod', '') for file in os.listdir('.')
        if file.endswith('.mod')
    ]

    mod_loaded = False
    for mod in mod_files:
        try:
            getattr(
                h, mod
            )  # Results in TypeError if mod file has been loaded, else AttributeError
        except AttributeError:
            pass
        except TypeError:
            mod_loaded = True
            break

    # If none of the mod files have been loaded, load them
    if not mod_loaded:

        # First figure out where the compiled mod binaries are (platform dependent)
        dll_path = None
        target = "nrnmech.dll" if platform.system(
        ) == "Windows" else "libnrnmech.so"

        try:
            for root, dirnames, filenames in os.walk('.'):
                for filename in fnmatch.filter(filenames, target):
                    dll_path = os.path.join(root, filename)
                    raise StopIteration()  # Stop looking once found

        except StopIteration:
            pass

        if dll_path is None:
            raise Exception(
                "Could not find compiled NEURON .mod files. Their compilation failed or they "
                "are located somewhere else. Looked for " + target +
                " here (inc. sub-dirs): " + os.getcwd())

        # Load the mod files from the binary
        from neuron import h
        h.nrn_load_dll(dll_path)
コード例 #10
0
ファイル: __init__.py プロジェクト: BlueBrain/neuronunit
    def __init__(self, name="Golding"):
        """ Constructor. """

        modelpath = "./hippounit/models/hoc_models/Golding_dichotomy/fig08/"
        libpath = "x86_64/.libs/libnrnmech.so.0"

        if os.path.isfile(modelpath + libpath) is False:
            os.system("cd " + modelpath + "; nrnivmodl")

        h.nrn_load_dll(modelpath + libpath)

        #self.dendA5_01111111100 = h.Section(name='foo', cell=self)

        self.dendrite = None
        self.name = "Golding"
        self.threshold = -40
        self.stim = None
        self.soma = "somaA"

        sciunit.Model.__init__(self, name=name)

        self.c_step_start = 0.00004
        self.c_step_stop = 0.000004
        self.c_minmax = numpy.array([0.00004, 0.004])
        self.dend_loc = [["dendA5_00", 0.275], ["dendA5_00", 0.925],
                         ["dendA5_01100", 0.15], ["dendA5_01100", 0.76],
                         ["dendA5_0111100", 0.115], ["dendA5_0111100", 0.96],
                         ["dendA5_01111100", 0.38], ["dendA5_01111100", 0.98],
                         ["dendA5_0111101", 0.06], ["dendA5_0111101", 0.937]]
        self.trunk_dend_loc_distr = [["dendA5_01111111111111", 0.68],
                                     ["dendA5_01111111111111", 0.136],
                                     ["dendA5_01111111111111", 0.864],
                                     ["dendA5_011111111111111", 0.5],
                                     ["dendA5_0111111111111111", 0.5],
                                     ["dendA5_0111111111111", 0.786],
                                     ["dendA5_0111111111111", 0.5]]
        self.trunk_dend_loc_clust = ["dendA5_01111111111111", 0.68]

        self.AMPA_tau1 = 0.1
        self.AMPA_tau2 = 2
        self.start = 150

        self.ns = None
        self.ampa = None
        self.nmda = None
        self.ampa_nc = None
        self.nmda_nc = None
        self.ndend = None
        self.xloc = None
コード例 #11
0
ファイル: simulator.py プロジェクト: astoeckel/PyNN
def load_mechanisms(path=pyNN_path[0]):
    # this now exists in the NEURON distribution, so could probably be removed
    global nrn_dll_loaded
    if path not in nrn_dll_loaded:
        arch_list = [platform.machine(), 'i686', 'x86_64', 'powerpc']
        # in case NEURON is assuming a different architecture to Python, we try multiple possibilities
        for arch in arch_list:
            lib_path = os.path.join(path, 'hoc', arch, '.libs',
                                    'libnrnmech.so')
            if os.path.exists(lib_path):
                h.nrn_load_dll(lib_path)
                nrn_dll_loaded.append(path)
                return
        raise Exception("NEURON mechanisms not found in %s." %
                        os.path.join(path, 'hoc'))
コード例 #12
0
    def __init__(self, hoc_model, path_mods, setting):
        """
        Parameters
        ----------
        hoc_model : str
            the path to model in .hoc
        path_mods : str
            the path to the directory containing the .mod files
        setting : dict
            the dictionary containing setting
        """
        self.setting = setting
        h.nrn_load_dll(path_mods + 'nrnmech.dll')
        h.xopen(hoc_model)

        self.CA1 = h.CA1_PC_Tomko()
        self.soma = self.CA1.soma[0]
        self.all = list(self.CA1.all)
        self.apical = list(self.CA1.apical)
        self.basal = list(self.CA1.basal)

        self.v_vec = h.Vector().record(self.soma(0.5)._ref_v)
        self.t_vec = h.Vector().record(h._ref_t)
        self.t_rs_vec = h.Vector().record(
            h._ref_t, self.setting['simulation']['RECORDING_STEP'])
        self.cai_vecs = {}
        self.cal2_ica_vecs = {}
        self.dend_vecs = {}
        self.ina_vecs = {}
        self.nmda_ica_vecs = {}

        self.apc = None
        self.apc_vec = h.Vector()

        self.bcm = None
        self.alpha_scout_vec = h.Vector()
        self.d_vec = h.Vector()
        self.p_vec = h.Vector()

        self.syn_AMPA_count = 0
        self.syn_NMDA_count = 0
        self.synapses = {}
        self.net_cons = []
        self.net_stims = []

        self.vBoxShape = None
        self.shplot = None
コード例 #13
0
def INIT_NEURON(reinit=False):
    """ Initialise NEURON

    - Compile mod files in `settings.MOD_PATH`. Files are recompiled if there are changes or
        `settings.NEURON_RECOMPILE` is True.
    - Load mod files into neuron


    :param reinit:
    :type reinit:
    :return:
    :rtype:
    """
    global initialised, t_vec, __KWARGS__
    if initialised and not reinit:
        return True
    else:
        initialised = True
    # compile mod files
    if __mod_files_changed(settings.MOD_PATH) or settings.NEURON_RECOMPILE:
        from src.utils.compile_mod import compile_mod
        output = compile_mod(path=settings.MOD_PATH, mod=True)
        if "Error" in str(output):
            raise Exception("MOD FILES not compiled successfully")
    # load mod files
    h.nrn_load_dll(settings.NRNMECH_PATH)
    # load hoc files including usefulFns.hoc
    for hoc_file in glob.glob(settings.HOC_PATH + "/*.hoc"):
        h.load_file(hoc_file.replace("\\", "/"))
    # show GUI
    if settings.NEURON_GUI:
        # noinspection PyUnresolvedReferences
        from neuron import gui
        h.showRunControl()

    # general properties
    h.celsius = 37
    h.v_init = -65
    h.random_stream_offset_ = settings.RANDOM_STREAM_OFFSET
    logger.info("celsius={} and v_init={}".format(h.celsius, h.v_init))
    t_vec = h.Vector()
    np.random.seed(settings.RANDOM_SEED)

    # reset __KWARGS__
    __KWARGS__ = {}
    env_var(celsius=h.celsius, v_init=h.v_init)
コード例 #14
0
 def __init__(self):
     #
     self.model_scale = "cells"
     self.model_name = "PC2015Masoli"
     # check that the NEURON model is compiled if not compile
     model_mod_path, model_lib_path = \
             gmlp( model_scale = self.model_scale,
                   model_name = self.model_name )
     ccm(model_mod_path, model_lib_path)
     #print(model_mod_path, model_lib_path, os.getcwd())
     #
     # load NEURON model library
     h.nrn_load_dll(model_lib_path)
     #
     # fixed time-step only
     Fixed_step = h.CVode()
     Fixed_step.active(0) #model doesn't work with variable time-step
     #
     # instantiate cell template
     #cwd = os.getcwd()
     #os.chdir(cwd + os.sep + "models" + os.sep + "cells" \
     #           + os.sep + "PC2015Masoli"
     self.cell = Purkinje()
     #os.chdir(cwd)  # reset to original directory
     #
     # discover no.cores in 1CPU & activate multisplit to use all cores
     dcam(h)
     #
     # =========attributed inherited from sciunit.Model===============
     # pc.name defaults to class name, i.e, PurkinjeCell
     self.name = "Masoli et al. 2015 model of PurkinjeCell"
     self.description = "Masoli et al. 2015 model of PurkinjeCell (PC) and published in 10.3389/fncel.2015.00047 This is general PC model unlike special Z+ or Z- models. The model is based on adult (P90 or 3 months) Guinea pig. PC in younger ones are not mature and they grow until P90. This model is the SciUnit wrapped version of the NEURON model in modelDB accession # 229585."
     #
     # =========model predictions attached to the model object========
     # Note: this is not part of inherited attributes from sciuni.Model
     self.predictions = {}  # added 21 Sept 2017
     # =====save the predictions in model-predictions subfolders======
     self.prediction_dir_path = cmdir( "model-predictions",
                                        self.model_scale,
                                        self.model_name )
     # =====specify cell_regions from which you want predictions======
     # created 22 Sept 2017
     self.cell_regions = {"vm_soma": 0.0, "vm_NOR3": 0.0}
コード例 #15
0
def load_custom_mechanisms():
    import platform
    import os.path as op

    if _is_loaded_mechanisms():
        return

    if platform.system() == 'Windows':
        mech_fname = op.join(op.dirname(__file__), 'mod', 'nrnmech.dll')
    else:
        mech_fname = op.join(op.dirname(__file__), 'mod', 'x86_64', '.libs',
                             'libnrnmech.so')
    if not op.exists(mech_fname):
        raise FileNotFoundError(f'The file {mech_fname} could not be found')

    h.nrn_load_dll(mech_fname)
    print('Loading custom mechanism files from %s' % mech_fname)
    if not _is_loaded_mechanisms():
        raise ValueError('The custom mechanisms could not be loaded')
コード例 #16
0
    def __init__(self, name="4 Compartments", model_dir="."):
        sciunit.Model.__init__(self, name=name)

        base_dir = os.path.abspath(model_dir)
        mod_path = os.path.join(base_dir, "x86_64/.libs/libnrnmech.so.0")
        hoc_path = os.path.join(base_dir, "mosinit.hoc")

        if not os.path.isfile(mod_path):
            os.system("cd " + base_dir + "; nrnivmodl NMODL")
            sleep(2)  # 2 seconds
            while (not os.path.isfile(mod_path)):
                # wait for nmodl compilation
                sleep(1)  # 1 second

        # to supress hoc output from Jupyter notebook
        save_stdout = sys.stdout
        sys.stdout = open('/dev/stdout', 'w')
        h.nrn_load_dll(mod_path)
        h.load_file(hoc_path)
        sys.stdout = save_stdout  #setting output back to before
コード例 #17
0
def load_mechanisms(path, mechname=None):
    ''' Rewrite of NEURON's native load_mechanisms method to ensure Windows and Linux compatibility.

        :param path: full path to directory containing the MOD files of the mechanisms to load.
        :param mechname (optional): name of specific mechanism to check for untracked changes
        in source file.
    '''

    # Get OS
    OS = platform.system()

    # If Darwin, call native NEURON function and return
    if OS == 'Darwin':
        return load_mechanisms_native(path)

    # Otherwise, get platform-dependent path to compiled library file
    if OS == 'Windows':
        lib_path = os.path.join(path, 'nrnmech.dll')
    elif OS == 'Linux':
        lib_path = os.path.join(path, platform.machine(), '.libs', 'libnrnmech.so')
    else:
        raise OSError('Mechanisms loading on "{}" currently not handled.'.format(platform.system()))
    if not os.path.isfile(lib_path):
        raise RuntimeError('Compiled library file not found for mechanisms in "{}"'.format(path))

    # If mechanisms of input path are already loaded, return silently
    global nrn_dll_loaded
    if path in nrn_dll_loaded:
        return

    # If mechanism name is provided, check for untracked changes in source file
    if mechname is not None:
        mod_path = os.path.join(path, '{}.mod'.format(mechname))
        if not os.path.isfile(mod_path):
            raise RuntimeError('"{}.mod" not found in "{}"'.format(mechname, path))
        if os.path.getmtime(mod_path) > os.path.getmtime(lib_path):
            raise UserWarning('"{}.mod" more recent than compiled library'.format(mechname))

    # Load library file and add directory to list of loaded libraries
    h.nrn_load_dll(lib_path)
    nrn_dll_loaded.append(path)
コード例 #18
0
ファイル: __init__.py プロジェクト: BlueBrain/neuronunit
    def __init__(self, name="Bianchi"):
        """ Constructor. """

        modelpath = "./hippounit/models/hoc_models/Ca1_Bianchi/experiment/"
        libpath = "x86_64/.libs/libnrnmech.so.0"

        if os.path.isfile(modelpath + libpath) is False:
            os.system("cd " + modelpath + "; nrnivmodl")

        h.nrn_load_dll(modelpath + libpath)

        self.name = "Bianchi"
        self.threshold = -20
        self.stim = None
        self.soma = "soma[0]"

        sciunit.Model.__init__(self, name=name)

        self.c_step_start = 0.00004
        self.c_step_stop = 0.000004
        self.c_minmax = numpy.array([0.00004, 0.004])
        self.dend_loc = [[112, 0.375], [112, 0.875], [118, 0.167], [118, 0.99],
                         [30, 0.167], [30, 0.83], [107, 0.25], [107, 0.75],
                         [114, 0.01], [114, 0.75]]
        self.trunk_dend_loc_distr = [[65, 0.5], [69, 0.5], [71,
                                                            0.5], [64, 0.5],
                                     [62, 0.5], [60, 0.5], [81, 0.5]]
        self.trunk_dend_loc_clust = [65, 0.5]

        self.AMPA_tau1 = 0.1
        self.AMPA_tau2 = 2
        self.start = 150

        self.ns = None
        self.ampa = None
        self.nmda = None
        self.ampa_nc = None
        self.nmda_nc = None
        self.ndend = None
        self.xloc = None
コード例 #19
0
ファイル: __init__.py プロジェクト: BlueBrain/neuronunit
    def __init__(self, name="Migliore"):
        """ Constructor. """

        modelpath = "./hippounit/models/hoc_models/Migliore_Schizophr/"
        libpath = "x86_64/.libs/libnrnmech.so.0"

        if os.path.isfile(modelpath + libpath) is False:
            os.system("cd " + modelpath + "; nrnivmodl")

        h.nrn_load_dll(modelpath + libpath)

        self.name = "Migliore"
        self.threshold = -20
        self.stim = None
        self.soma = "soma[0]"
        sciunit.Model.__init__(self, name=name)

        self.c_step_start = 0.00004
        self.c_step_stop = 0.000004
        self.c_minmax = numpy.array([0.00004, 0.004])
        self.dend_loc = [[17, 0.3], [17, 0.9], [24, 0.3], [24, 0.7], [22, 0.3],
                         [22, 0.7], [25, 0.2], [25, 0.5], [30, 0.1], [30, 0.5]]
        self.trunk_dend_loc_distr = [[10, 0.167], [10, 0.5], [10, 0.83],
                                     [11, 0.5], [9, 0.5], [8, 0.5], [7, 0.5]]
        self.trunk_dend_loc_clust = [10, 0.167]

        self.AMPA_tau1 = 0.1
        self.AMPA_tau2 = 2
        self.start = 150

        self.ns = None
        self.ampa = None
        self.nmda = None
        self.ampa_nc = None
        self.nmda_nc = None
        self.ndend = None
        self.xloc = None
コード例 #20
0
ファイル: __init__.py プロジェクト: BlueBrain/neuronunit
    def __init__(self, name="Kali"):
        """ Constructor. """

        modelpath = "./hippounit/models/hoc_models/Kali_Freund_modell/scppinput/"
        libpath = "x86_64/.libs/libnrnmech.so.0"

        if os.path.isfile(modelpath + libpath) is False:
            os.system("cd " + modelpath + "; nrnivmodl")

        h.nrn_load_dll(modelpath + libpath)

        self.name = name
        self.threshold = -20
        self.stim = None
        self.soma = "soma"
        sciunit.Model.__init__(self, name=name)

        self.c_step_start = 0.00004
        self.c_step_stop = 0.000004
        self.c_minmax = numpy.array([0.00004, 0.004])
        self.dend_loc = [[80, 0.27], [80, 0.83], [54, 0.16], [54, 0.95],
                         [52, 0.38], [52, 0.83], [53, 0.17], [53, 0.7],
                         [28, 0.35], [28, 0.78]]

        self.AMPA_tau1 = 0.1
        self.AMPA_tau2 = 2
        self.start = 150

        self.ns = None
        self.ampa = None
        self.nmda = None
        self.ampa_nc = None
        self.nmda_nc = None

        self.ndend = None
        self.xloc = None
コード例 #21
0
def load_compiled_mechanisms(path='precompiled'):
    """Loads precompiled mechanisms in pyDentate unless
    path defines the full path to a compiled mechanism file."""
    if path != 'precompiled':
        h.nrn_load_dll(path)
    else:
        if platform.system() == 'Windows':
            h.nrn_load_dll(windows_precompiled)
        else:
            h.nrn_load_dll(linux_precompiled)
コード例 #22
0
import os

import numpy as np
from nrn_wrapper import Cell

from optimization.simulate import currents_given_v
from optimization.problems import CellFitProblem, get_channel_list, get_ionlist, convert_units
from optimization.linear_regression import linear_regression, plot_fit

__author__ = 'caro'

# TODO
from neuron import h
from optimization.problems import complete_mechanismdir
m_dir = '../../../model/channels/icgenealogy/Kchannels'
h.nrn_load_dll(complete_mechanismdir(m_dir))
m_dir = '../../../model/channels/icgenealogy/Nachannels'
h.nrn_load_dll(complete_mechanismdir(m_dir))

# parameter
save_dir = '../../../results/linear_regression/dapmodelnaka/'
n_trials = 1

params = {
          'name': 'CellFitProblem',
          'maximize': False,
          'normalize': True,
          'model_dir': '../../../model/cells/dapmodelnaka.json',
          'mechanism_dir': '../../../model/channels/schmidthieber',
          'variables': [],
          'data_dir': '../../../data/2015_08_11d/merged/step_dap_zap.csv',
コード例 #23
0
ファイル: neuronmodel.py プロジェクト: sunzhenyang2018/NEAT
import os
import posix
import copy

import numpy as np

from ....trees.morphtree import MorphLoc
from ....trees.phystree import PhysTree, PhysNode

import neuron
from neuron import h
h.load_file("stdlib.hoc")  # contains the lambda rule
h.nrn_load_dll(
    os.path.join(os.path.dirname(__file__),
                 'x86_64/.libs/libnrnmech.so'))  # load all mechanisms
# neuron.load_mechanisms(os.path.join(os.path.dirname(__file__),
#                             'x86_64/.libs/libnrnmech.so')) # load all mechanisms
# mechanism_name_translation NEURON


class MechName(object):
    def __init__(self):
        self.names = {'L': 'pas', 'ca': 'CaDyn'}

    def __getitem__(self, key):
        if key in self.names:
            return self.names[key]
        else:
            return 'I' + key
            # 'TestChannel': 'ITestChannel', 'TestChannel2': 'ITestChannel2',
            # 'h': 'Ih', 'h_HAY': 'Ih_HAY',
コード例 #24
0
import sys
import h5py
import numpy as np
from matplotlib import pyplot as plt

from mpi4py import MPI
comm = MPI.COMM_WORLD

from neuron import h
from neuron import gui
pc = h.ParallelContext()
rank = int(pc.id())
size = int(pc.nhost())

h.nrn_load_dll('$i386/')

soma = h.Section()
soma.diam = 10
soma.L = 100 / (3.14 * soma.diam)
soma.insert('hh')

soma2 = h.Section()
soma2.diam = 10
soma2.L = 100 / (3.14 * soma2.diam)
soma2.insert('hh')

if (rank == 0):
    stim = h.IClamp(.5)
    stim.amp = 0.5
    stim.dur = 0.1
コード例 #25
0
ファイル: __init__.py プロジェクト: tomko-neuron/HippoUnit
    def load_mod_files(self):

        h.nrn_load_dll(self.modelpath + 'nrnmech.dll')
コード例 #26
0
ファイル: neuronSim.py プロジェクト: travis-open/acq4
import sys, os

# Try standard locations to find neuron library
for nrnpath in ['/usr/local/nrn/lib/python']:
    if os.path.isdir(nrnpath):
        sys.path.append(nrnpath)
from neuron import h
import neuron

# try to load extra mechanisms
for name in ('i386', 'x86_64'):
    mechlib = os.path.join(os.path.dirname(__file__),
                           name + '/.libs/libnrnmech.so')
    print "NEURON load:", mechlib
    if os.path.isfile(mechlib):
        h.nrn_load_dll(mechlib)

h.celsius = 22

soma = h.Section()
soma.insert('hh')
soma.insert('pas')
#soma.insert('hcno')
soma.L = 20
soma.diam = 20
soma(0.5).pas.g = 2e-5
#soma(0.5).hcno.gbar = 15e-4

ic = h.IClamp(soma(0.5))
ic.dur = 1e9
ic.delay = 0
コード例 #27
0
                    format='%(asctime)s %(funcName)s: %(message)s',
                    filemode='w')

logger = logging.getLogger('mb_model')

if sys.platform == 'win32':
    os.environ['NEURONHOME'] = 'c:\\nrn'
    sys.path += [
        'c:\\nrn\\lib\\python', 'd:\\subhasis_ggn\\model\\common',
        'd:\\subhasis_ggn\\model\\morphutils',
        'd:\\subhasis_ggn\\model\\mb\\network'
    ]
    # The mod files are in the directory `mod` and nrnmech.dll is created there
    dll = os.path.join(os.path.dirname(__file__), 'mod', 'nrnmech.dll')
    print('nrnmech', dll)
    h.nrn_load_dll(dll)
else:
    # os.environ['NEURONHOME'] = '/usr/local/apps/neuron/nrn-7.4/'
    sys.path += [
        '/home/rays3/projects/ggn/mb', '/home/rays3/projects/ggn/common',
        '/home/rays3/projects/ggn/morphutils', '/home/rays3/projects/ggn/nrn',
        '/home/rays3/projects/ggn/mb/network'
    ]

logger.info('sys.path={}'.format(str(sys.path)))
h.load_file('stdrun.hoc')

from pint import UnitRegistry

ur = UnitRegistry()
Q_ = ur.Quantity
コード例 #28
0
ファイル: test_cli.py プロジェクト: Hjorthmedh/Snudda
    def test_workflow(self):

        #with self.subTest(stage="create"):
        #    run_cli_command("create test-project --overwrite")

        if True:
            network_path = "test-project"
            if os.path.exists(network_path):
                import shutil
                shutil.rmtree(network_path)

                os.mkdir(network_path)
                os.chdir(network_path)

        with self.subTest(stage="setup-parallel"):
            os.environ["IPYTHONDIR"] = os.path.join(
                os.path.abspath(os.getcwd()), ".ipython")
            os.environ["IPYTHON_PROFILE"] = "Snudda_local"
            os.system(
                "ipcluster start -n 4 --profile=$IPYTHON_PROFILE --ip=127.0.0.1&"
            )
            time.sleep(10)

        # with self.subTest(stage="init-parallel-BIG"):
        #     run_cli_command("init tiny_parallel --size 1000000 --overwrite")

        # with self.subTest(stage="place-parallel-BIG"):
        #     run_cli_command("place tiny_parallel --parallel")

        with self.subTest(stage="init-parallel"):
            run_cli_command("init tiny_parallel --size 100 --overwrite")

        # Lets reinit but a smaller network that contains all types of cells, to speed things up
        with self.subTest(stage="small-reinit-1"):
            config_name = os.path.join("tiny_parallel", "network-config.json")
            cnc = SnuddaInit(struct_def={},
                             config_file=config_name,
                             random_seed=123456)
            cnc.define_striatum(num_dSPN=4,
                                num_iSPN=4,
                                num_FS=2,
                                num_LTS=2,
                                num_ChIN=2,
                                volume_type="cube")
            cnc.write_json(config_name)

        with self.subTest(stage="place-parallel"):
            run_cli_command("place tiny_parallel --parallel --raytraceBorders")

        with self.subTest(stage="detect-parallel"):
            run_cli_command("detect tiny_parallel --parallel")

        with self.subTest(stage="prune-parallel"):
            run_cli_command("prune tiny_parallel --parallel")

        from shutil import copyfile
        print(f"listdir: {os.listdir()}")
        print(f"parent listdir: {os.listdir('..')}")
        input_file = os.path.join(os.path.dirname(__file__), os.path.pardir,
                                  "snudda", "data", "input_config",
                                  "input-v10-scaled.json")
        copyfile(input_file, os.path.join("tiny_parallel", "input.json"))

        with self.subTest(stage="input"):
            run_cli_command(
                "input tiny_parallel --input tiny_parallel/input.json --parallel"
            )

        # with self.subTest(stage="init-parallel-full"):
        #     run_cli_command("init large_parallel --size 1670000 --overwrite")

        # with self.subTest(stage="place-parallel-full"):
        #    run_cli_command("place large_parallel --parallel")

        with self.subTest(stage="parallel-stop"):
            os.system("ipcluster stop")

        #  Only serial tests below this line, we stopped ipcluster.

        with self.subTest(stage="simulate"):
            print("Running nrnivmodl:")
            mech_dir = os.path.join(os.path.dirname(__file__), os.path.pardir,
                                    "snudda", "data", "neurons", "mechanisms")

            if not os.path.exists("mechanisms"):
                print("----> Copying mechanisms")
                # os.symlink(mech_dir, "mechanisms")
                from distutils.dir_util import copy_tree
                copy_tree(mech_dir, "mechanisms")
            else:
                print("------------->   !!! mechanisms already exists")

            eval_str = f"nrnivmodl mechanisms"  # f"nrnivmodl {mech_dir}
            print(f"Running: {eval_str}")
            os.system(eval_str)

            # print("---> Testing to run simulate using os.system instead")
            # os.system("snudda simulate tiny_parallel --time 0.1 --voltOut default")

            # For the unittest we for some reason need to load mechansism
            # separately
            from mpi4py import MPI  # This must be imported before neuron, to run parallel
            from neuron import h  # , gui
            import neuron

            # For some reason we need to import modules manually
            # when running the unit test.
            if os.path.exists("x86_64/.libs/libnrnmech.so"):
                print("!!! Manually loading libraries")
                try:
                    h.nrn_load_dll("x86_64/.libs/libnrnmech.so")
                except:
                    import traceback
                    tstr = traceback.format_exc()
                    print(tstr)

            if False:
                try:
                    from snudda.simulate.simulate import SnuddaSimulate
                    ss = SnuddaSimulate(network_path="tiny_parallel")
                    ss.run(100)
                    ss.write_spikes()
                except:
                    import traceback
                    tstr = traceback.format_exc()
                    print(tstr)
                    import pdb
                    pdb.set_trace()

            print("Time to run simulation...")
            run_cli_command(
                "simulate tiny_parallel --time 0.1 --voltOut default")

        os.environ["SLURM_JOBID"] = "1234"

        with self.subTest(stage="init-serial"):
            # Remove the old folder if it exists
            if os.path.exists("tiny_serial"):
                import shutil
                shutil.rmtree("tiny_serial")

            run_cli_command("init tiny_serial --size 100 --profile")

        with self.subTest(stage="init-overwrite-fail"):
            # Should not allow overwriting of existing folder if --overwrite is not specified
            self.assertRaises(AssertionError, run_cli_command,
                              "init tiny_serial --size 100")

        # Again, let us reinit to a smaller network to speed things up
        with self.subTest(stage="small-reinit-2"):
            config_name = os.path.join("tiny_serial", "network-config.json")
            cnc = SnuddaInit(struct_def={},
                             config_file=config_name,
                             random_seed=1234)
            cnc.define_striatum(num_dSPN=3,
                                num_iSPN=3,
                                num_FS=2,
                                num_LTS=2,
                                num_ChIN=2,
                                volume_type="cube")
            cnc.write_json(config_name)

        with self.subTest(stage="place-serial"):
            run_cli_command("place tiny_serial --h5legacy")

        with self.subTest(stage="detect-serial"):
            run_cli_command(
                "detect tiny_serial --volumeID Striatum --hvsize 120 --randomseed 123 --verbose --h5legacy"
            )

        with self.subTest(stage="detect-serial-cont"):
            run_cli_command(
                "detect tiny_serial --volumeID Striatum --hvsize 120 --cont --h5legacy"
            )

        with self.subTest(stage="prune-serial"):
            run_cli_command("prune tiny_serial --h5legacy")

        input_file = os.path.join(os.path.dirname(__file__), os.path.pardir,
                                  "snudda", "data", "input_config",
                                  "input-v10-scaled.json")
        copyfile(input_file, "tiny_serial/input.json")
        with self.subTest(stage="input"):
            run_cli_command(
                "input tiny_serial --time 1.0 --inputFile tiny_serial/input-spikes.hdf5"
            )
コード例 #29
0
 def compile_load_mod_files(self):
     if not os.path.isfile(self.lib_path):
         os.system("cd " + self.mod_files_path + "; nrnivmodl")
     h.nrn_load_dll(str(self.lib_path))
コード例 #30
0
from neuron import h
h.nrn_load_dll("E:\\Google Drive\\Github\\Spinal-Cord-Modeling\\nrnmech.dll")
import helper_functions as hf
from Ia_template import Ia
from Mn_template import Mn

class Ia_network:

    def __init__(self, N = 2, syn_w = 0.15, syn_delay = 1):
        self._N = N;
        self.cells = []             # Cells in the net
        self.nclist = []            # NetCon list
        self.syn_w = syn_w          # Synaptic weight
        self.syn_delay = syn_delay  # Synaptic delay
        self.t_vec = h.Vector()     # Spike time of all cells
        self.id_vec = h.Vector()    # Ids of spike times
        self.set_numcells(N)        # Actually build the net.
    #
    def set_numcells(self, N):
        """Create, layout, and connect N cells."""
        self._N = N
        self.create_cells(N)
        self.connect_cells()
   #
    def create_cells(self, N):
        """Create and layout N cells in the network."""
        self.cells = []
        r = 50 # Radius of cell locations from origin (0,0,0) in microns
        N = self._N
        position_factor = 5e3;
        sim_params = hf.get_net_params(hf.get_tempdata_address())
コード例 #31
0
from neuron import h
h.nrn_load_dll("E:\\Google Drive\\Github\\Spinal-Cord-Modeling\\nrnmech.dll")
import helper_functions as hf
from Ia_template import Ia
from Mn_template import Mn


class Ia_network:
    def __init__(self, N=2, syn_w=0.15, syn_delay=1):
        self._N = N
        self.cells = []  # Cells in the net
        self.nclist = []  # NetCon list
        self.syn_w = syn_w  # Synaptic weight
        self.syn_delay = syn_delay  # Synaptic delay
        self.t_vec = h.Vector()  # Spike time of all cells
        self.id_vec = h.Vector()  # Ids of spike times
        self.set_numcells(N)  # Actually build the net.

    #
    def set_numcells(self, N):
        """Create, layout, and connect N cells."""
        self._N = N
        self.create_cells(N)
        self.connect_cells()
#

    def create_cells(self, N):
        """Create and layout N cells in the network."""
        self.cells = []
        r = 50  # Radius of cell locations from origin (0,0,0) in microns
        N = self._N
コード例 #32
0
def load_mechanism_dir(mechanism_dir):
    h.nrn_load_dll(complete_mechanismdir(str(mechanism_dir)))
コード例 #33
0
              "dentategyrusnet2005\\nrnmech.dll"),
             "C:\\Users\\daniel\\Repos\\nrnmech.dll",
             ("C:\\Users\\Holger\\danielm\\models_dentate\\"
              "dentate_gyrus_Santhakumar2005_and_Yim_patterns\\"
              "dentategyrusnet2005\\nrnmech.dll"),
             ("C:\\Users\\Daniel\\repos\\"
              "dentate_gyrus_Santhakumar2005_and_Yim_patterns\\"
              "dentategyrusnet2005\\nrnmech.dll"),
             ("/home/daniel/repos/pyDentate/mechs_7-6_linux/"
              "x86_64/.libs/libnrnmech.so")]

for x in dll_files:
    if os.path.isfile(x):
        dll_dir = x
print("DLL loaded from: " + dll_dir)
h.nrn_load_dll(dll_dir)

# Seed the numpy random number generator for replication
np.random.seed(seed)

# Randomly choose target cells for the PP lines
gauss_gc = stats.norm(loc=1000, scale=input_scale)
gauss_bc = stats.norm(loc=12, scale=(input_scale / 2000.0) * 24)
pdf_gc = gauss_gc.pdf(np.arange(2000))
pdf_gc = pdf_gc / pdf_gc.sum()
pdf_bc = gauss_bc.pdf(np.arange(24))
pdf_bc = pdf_bc / pdf_bc.sum()
GC_indices = np.arange(2000)
start_idc = np.random.randint(0, 1999, size=400)

PP_to_GCs = []
コード例 #34
0
## So now we take the TEP model from first_tep.py where we really jsut used the defautl model times 3 
# and we add predictions. we ant to see what happens when a tap comes in at certain delays after the pulse
#-------------------------------------
#Init
#-------------------------------------
        


from neuron import h
h.nrn_load_dll('C:\\Users\\ckohl\\Miniconda3\\Lib\\site-packages\\hnn_core\\nrnmech.dll')
import os.path as op
from hnn_core import simulate_dipole, Params, Network, read_params
import json
import numpy as np
import matplotlib.pyplot as plt
import sys        
sys.path.append('C:\\Users\\ckohl\\Desktop\\Current\\TMS\\git-TEP_Analysis\\hnn_core_for_TEP')
import my_hnn_core_functions as m
from pptx import Presentation #https://python-pptx.readthedocs.io/en/latest/user/quickstart.html
from pptx.util import Inches

saving_dpl=False
my_param_out_dir='C:\\Users\\ckohl\\hnn_out\\'
dump_dir="C:\\Users\\ckohl\\Desktop\\Current\\TMS\\Core output"     


#-------------------------------------
#PPT init
#-------------------------------------
left = 0
top=Inches(0.25)
コード例 #35
0
# -*- coding: utf-8 -*-
"""
Created on Thu Jan 04 15:26:50 2018

@author: DanielM
"""

from neuron import h, gui
import numpy as np
import matplotlib.pyplot as plt
from pyDentate.mossycell_cat import MossyCell
from pyDentate.basketcell import BasketCell

h.nrn_load_dll("C:\\Users\\DanielM\\Repos\\models_dentate\\dentate_gyrus_Santhakumar2005_and_Yim_patterns\\dentategyrusnet2005\\nrnmech.dll")

stim_periods = [1000, 100, 33, 20]

for period in stim_periods:
    """Setup stimulation pattern"""
    t_pattern = np.arange(100, 100+10*period, period)
    vecstim = h.VecStim()
    pattern_vec = h.Vector(t_pattern)
    vecstim.play(pattern_vec)

    """Setup tmgsyn"""
    mc_tmgsyn = MossyCell()

    mc_tmgsyn_syn = h.tmgsyn(mc_tmgsyn.all_secs[1](0.5))
    mc_tmgsyn_syn.e = 0
    mc_tmgsyn_syn.tau_facil = 0 # This parameter gives the frequency dependence of facilitation
    mc_tmgsyn_syn.tau_1 = 6.2