How to use the neuron.h.ParallelContext function in NEURON

To help you get started, we’ve selected a few NEURON examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github nrnhines / ringtest / ringuniform.py View on Github external
nring=64
ncell=8 # number of cells per ring

nsomachild = 16
nbranch = 32

print "nring=%d\ncell per ring=%d"%(nring, ncell)

tstop=100
randomize_parameters = False

from neuron import h
h.load_file('nrngui.hoc')
pc = h.ParallelContext()
rank = int(pc.id())
nhost = int(pc.nhost())
#from cell import BallStick
h.load_file("celluniform.hoc")

class Ring(object):

  def __init__(self, ncell, nbranch, gidstart):
    #print "construct ", self
    self.gids = []
    self.delay = 1
    self.ncell = int(ncell)
    self.gidstart = gidstart
    self.mkring(self.ncell, nbranch, nsomachild)
    self.mkstim()
github AllenInstitute / bmtk / bmtk / simulator / bionet / modules / record_netcons.py View on Github external
from .sim_module import SimulatorMod
from bmtk.simulator.bionet.biocell import BioCell
# from bmtk.simulator.bionet.io_tools import io
# from bmtk.simulator.bionet.pointprocesscell import PointProcessCell
from bmtk.utils.reports import CompartmentReport

try:
    # Check to see if h5py is built to run in parallel
    if h5py.get_config().mpi:
        MembraneRecorder = CompartmentReport  # cell_vars.CellVarRecorderParallel
    else:
        MembraneRecorder = CompartmentReport  # cell_vars.CellVarRecorder
except Exception as e:
    MembraneRecorder = CompartmentReport  # cell_vars.CellVarRecorder

pc = h.ParallelContext()
MPI_RANK = int(pc.id())
N_HOSTS = int(pc.nhost())


class NetconReport(SimulatorMod):
    def __init__(self, tmp_dir, file_name, variable_name, cells, sections='all', syn_type='Exp2Syn', buffer_data=True,
                 transform={}):
        """Module used for saving NEURON cell properities at each given step of the simulation.

        :param tmp_dir:
        :param file_name: name of h5 file to save variable.
        :param variables: list of cell variables to record
        :param gids: list of gids to to record
        :param sections:
        :param buffer_data: Set to true then data will be saved to memory until written to disk during each block, reqs.
        more memory but faster. Set to false and data will be written to disk on each step (default: True)
github AllenInstitute / bmtk / bmtk / simulator / bionet / morphology.py View on Github external
# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
# products derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
import numpy as np
from neuron import h


pc = h.ParallelContext()  # object to access MPI methods


class Morphology(object):
    """Methods for processing morphological data"""
    def __init__(self, hobj):
        """reuse hoc object from one of the cells which share the same morphology/model"""
        self.hobj = hobj
        self.sec_type_swc = {'soma': 1, 'somatic': 1,  # convert section name and section list names
                             'axon': 2, 'axonal': 2,  # into a consistent swc notation
                             'dend': 3, 'basal': 3,
                             'apic': 4, 'apical': 4}
        self.nseg = self.get_nseg()
        self._segments = {}

    def get_nseg(self):
        nseg = 0
github AllenInstitute / bmtk / bmtk / simulator / bionet / bionetwork.py View on Github external
from bmtk.simulator.core.simulator_network import SimNetwork
from bmtk.simulator.bionet.biocell import BioCell
from bmtk.simulator.bionet.pointprocesscell import PointProcessCell
from bmtk.simulator.bionet.pointsomacell import PointSomaCell
from bmtk.simulator.bionet.virtualcell import VirtualCell
from bmtk.simulator.bionet.morphology import Morphology
from bmtk.simulator.bionet.io_tools import io
from bmtk.simulator.bionet import nrn
from bmtk.simulator.bionet.sonata_adaptors import BioNodeAdaptor, BioEdgeAdaptor
from .gids import GidPool

# TODO: leave this import, it will initialize some of the default functions for building neurons/synapses/weights.
import bmtk.simulator.bionet.default_setters


pc = h.ParallelContext()  # object to access MPI methods
MPI_size = int(pc.nhost())
MPI_rank = int(pc.id())


class BioNetwork(SimNetwork):
    model_type_col = 'model_type'

    def __init__(self):
        # property_schema = property_schema if property_schema is not None else DefaultPropertySchema
        super(BioNetwork, self).__init__()
        self._io = io

        # TODO: Find a better way that will allow users to register their own class
        self._model_type_map = {
            'biophysical': BioCell,
            'point_process': PointProcessCell,
github AllenInstitute / bmtk / bmtk / simulator / bionet / biosimulator.py View on Github external
import time
from six import string_types
from neuron import h
from bmtk.simulator.core.simulator import Simulator
from bmtk.simulator.bionet.io_tools import io
from bmtk.simulator.bionet.iclamp import IClamp
from bmtk.simulator.bionet import modules as mods
from bmtk.simulator.core.node_sets import NodeSet
import bmtk.simulator.utils.simulation_reports as reports
import bmtk.simulator.utils.simulation_inputs as inputs
from bmtk.utils.io import spike_trains

from bmtk.utils.reports.spike_trains import SpikeTrains


pc = h.ParallelContext()    # object to access MPI methods


class BioSimulator(Simulator):
    """Includes methods to run and control the simulation"""

    def __init__(self, network, dt, tstop, v_init, celsius, nsteps_block, start_from_state=False):
        self.net = network

        self._start_from_state = start_from_state
        self.dt = dt
        self.tstop = tstop
        self.tstart = 0.0

        self._v_init = v_init
        self._celsius = celsius
        self._h = h
github AllenInstitute / bmtk / bmtk / simulator / bionet / io_tools.py View on Github external
# 3. Neither the name of the copyright holder nor the names of its contributors may be used to endorse or promote
# products derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
from neuron import h

from bmtk.simulator.core.io_tools import IOUtils

pc = h.ParallelContext()
MPI_Rank = int(pc.id())
MPI_Size = int(pc.nhost())


class NEURONIOUtils(IOUtils):
    def __init__(self):
        super(NEURONIOUtils, self).__init__()
        self.mpi_rank = MPI_Rank
        self.mpi_size = MPI_Size

    def barrier(self):
        pc.barrier()


io = NEURONIOUtils()
github AllenInstitute / bmtk / bmtk / simulator / bionet / pointprocesscell.py View on Github external
# products derived from this software without specific prior written permission.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
from neuron import h
import six
from bmtk.simulator.bionet.cell import Cell


pc = h.ParallelContext()    # object to access MPI methods


class PointProcessCell(Cell):
    """Implimentation of a Leaky Integrate-and-file neuron type cell."""
    def __init__(self, node, bionetwork):
        super(PointProcessCell, self).__init__(node)
        self.set_spike_detector()
        self._src_gids = []
        self._src_nets = []
        self._edge_type_ids = []

    def set_spike_detector(self):
        nc = h.NetCon(self.hobj, None)
        pc.cell(self.gid, nc)

    def set_im_ptr(self):
github AllenInstitute / bmtk / docs / examples / simulator / bionet / 14cells_multinode / run_bionet.py View on Github external
from bmtk.simulator.bionet import io, nrn
from bmtk.simulator.bionet.simulation import Simulation
from bmtk.analyzer.spikes_analyzer import spike_files_equal
from bmtk.simulator.bionet.biograph import BioGraph
from bmtk.simulator.bionet.bionetwork import BioNetwork
from bmtk.simulator.bionet.io import print2log0

from bmtk.utils.io import TabularNetwork_AI
from bmtk.simulator.bionet.property_schemas import AIPropertySchema


import set_weights
import set_cell_params
import set_syn_params

pc = h.ParallelContext()
MPI_RANK = int(pc.id())


def check_cellvars(gid, conf):
    expected_file = 'expected/cellvars/{}.h5'.format(gid)
    results_file = os.path.join(conf['output']['cell_vars_dir'], '{}.h5'.format(gid))
    assert (os.path.exists(results_file))

    results_h5 = h5py.File(results_file, 'r')
    expected_h5 = h5py.File(expected_file, 'r')
    for variable in conf['run']['save_cell_vars']:
        assert (variable in results_h5)
        results_data = results_h5[variable].value
        expected_data = expected_h5[variable].value
        # consider using np.allclose() since the percision can vary depending on neuron version
        assert (np.array_equal(results_data, expected_data))
github AllenInstitute / bmtk / bmtk / simulator / bionet / biocell.py View on Github external
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES,
# INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
# DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
# SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
# SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
# WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
# OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
#
import numpy as np
from bmtk.simulator.bionet import utils, nrn
from bmtk.simulator.bionet.cell import Cell
import six

from neuron import h

pc = h.ParallelContext()    # object to access MPI methods


class BioCell(Cell):
    """Implemntation of a morphologically and biophysically detailed type cell.

    """
    def __init__(self, node, bionetwork):
        super(BioCell, self).__init__(node)

        # Set up netcon object that can be used to detect and communicate cell spikes.
        self.set_spike_detector(bionetwork.spike_threshold)

        self._morph = None
        self._seg_coords = {}

        # Determine number of segments and store a list of all sections.
github Neurosim-lab / netpyne / netpyne / conversion / neuromlFormat.py View on Github external
Contains functions related to neuroml conversion (import from and export to) 

Contributors: salvadordura@gmail.com
"""


try:
    import neuroml
    from pyneuroml import pynml
    from pyneuroml import __version__ as pynml_ver
    from distutils.version import StrictVersion
    min_pynml_ver_required = '0.3.11' # pyNeuroML will have a dependency on the correct version of libNeuroML...
    
    if not StrictVersion(pynml_ver)>=StrictVersion(min_pynml_ver_required):
        from neuron import h
        pc = h.ParallelContext() # MPI: Initialize the ParallelContext class
        if int(pc.id()) == 0: 
            print('Note: pyNeuroML version %s is installed but at least v%s is required'%(pynml_ver,min_pynml_ver_required))
            neuromlExists = False
    else:
        neuromlExists = True
        
except ImportError:
    from neuron import h
    pc = h.ParallelContext() # MPI: Initialize the ParallelContext class
    if int(pc.id()) == 0:  # only print for master node
        print('Note: NeuroML import failed; import/export functions for NeuroML will not be available. \n  To install the pyNeuroML & libNeuroML Python packages visit: https://www.neuroml.org/getneuroml')
    neuromlExists = False

import pprint; pp = pprint.PrettyPrinter(depth=6)
import math
from collections import OrderedDict