Exemplo n.º 1
0
    def test_2_runs(self):
        """
        Test setup for 2 cells and their records which should be the same.

        After each creation of the Simulation object, the Record object is cleaned up
        (inside vector is empty) however on other Hoc object is removed eg. Sections.
        That means - each new sections and cell are retained in the current NEURON run.
        """

        def run_and_get_rec():
            rec = Record(self.soma(0.5))
            iclamp = IClamp(segment=self.soma(0.5))
            iclamp.stim(delay=25, dur=3, amp=3)
            sim = Simulation(init_v=-70, warmup=20)
            sim.run(100)
            return rec

        rec1 = run_and_get_rec()
        r1 = rec1.as_numpy('v').records

        self.tearDown()
        self.setUp()

        rec2 = run_and_get_rec()
        r2 = rec2.as_numpy('v').records

        sim = Simulation(init_v=-70, warmup=20)
        sim.run(100)

        # Make assertions
        self.assertEqual(4011, r1.size)
        self.assertEqual(4011, r2.size)
        self.assertTrue(np.alltrue(r1 == r2))
Exemplo n.º 2
0
 def run_and_get_rec():
     rec = Record(self.soma(0.5))
     iclamp = IClamp(segment=self.soma(0.5))
     iclamp.stim(delay=25, dur=3, amp=3)
     sim = Simulation(init_v=-70, warmup=20)
     sim.run(100)
     return rec
Exemplo n.º 3
0
    def test_netstim_after_sim(self):
        """
        NetStim created after simulation run has no effect, it won't go on this simulation at all.

        However NetStim start is in the absolute time.
        """
        # Record
        rec = Record(self.soma(0.5))
        # Run
        sim = Simulation(init_v=-70, warmup=20)
        sim.run(1)

        # Netstim to synapse
        stim = NetStimCell("stim").add_netstim(start=25, number=10, interval=2)
        self.cell.add_synapse(source=stim, netcon_weight=0.5, mod_name="ExpSyn", delay=1,
                              seg=self.apic1(0.5))
        sim.run(100)
        r = rec.as_numpy(variable="v")

        # Make assertions
        self.assertEqual(4051, r.size)
        self.assertEqual(-67.1917, round(r.records.max(), 4))
        self.assertEqual(-70.0, round(r.records.min(), 4))

        self.assertEqual(3, r.records.argmax())
        # time in ms of max mV value
        self.assertEqual(6, r.time[r.records.argmax()])

        stim.remove_immediate_from_neuron()
        sim.remove_immediate_from_neuron()
        rec.remove_immediate_from_neuron()
Exemplo n.º 4
0
    def test_iclamp_after_sim(self):
        """
        IClamp works in a regular way after simulation run. in this case (amplitude 3 pA)
        we have spike at the soma.

        However IClamp delay is in the absolute time.
        """
        # Record
        rec = Record(self.soma(0.5))

        # Run
        sim = Simulation(init_v=-70, warmup=20)
        sim.run(1)

        # IClamp to soma
        iclamp = IClamp(segment=self.soma(0.5))
        iclamp.stim(delay=25, dur=3, amp=3)

        sim.run(100)
        r = rec.as_numpy(variable="v")

        sim.remove_immediate_from_neuron()
        rec.remove_immediate_from_neuron()
        iclamp.remove_immediate_from_neuron()

        # Make assertions
        self.assertEqual(4051, r.size)
        self.assertEqual(34.3815, round(r.records.max(), 4))
        self.assertEqual(-75.3247, round(r.records.min(), 4))

        self.assertEqual(330, r.records.argmax())
        # time in ms of max mV value
        self.assertEqual(28, round(r.time[r.records.argmax()], 4))
Exemplo n.º 5
0
    def test_netstim_before_sim(self):
        """
        NetStim run in a regular way before Simulation run, in this cale (netcon weight=1.0)
        we have spike of the soma.

        However NetStim start is in the absolute time.
        """
        # Netstim to synapse
        stim = NetStimCell("stim").add_netstim(start=25, number=10, interval=2)
        self.cell.add_synapse(source=stim, netcon_weight=1.0, mod_name="ExpSyn", delay=1,
                              seg=self.apic1(0.5))
        # Record
        rec = Record(self.soma(0.5))
        # Run
        sim = Simulation(init_v=-70, warmup=20)
        sim.run(1)

        sim.run(100)
        r = rec.as_numpy(variable="v")

        stim.remove_immediate_from_neuron()
        sim.remove_immediate_from_neuron()
        rec.remove_immediate_from_neuron()

        # Make assertions
        self.assertEqual(4051, r.size)
        self.assertEqual(34.5205, round(r.records.max(), 4))
        self.assertEqual(-75.3053, round(r.records.min(), 4))

        self.assertEqual(319, r.records.argmax())
        # time in ms of max mV value
        self.assertEqual(27.725, round(r.time[r.records.argmax()], 4))
Exemplo n.º 6
0
    def test_netcon_event_after_sim(self):
        syn = self.cell.add_synapse(source=None, netcon_weight=1.0, mod_name="ExpSyn", delay=1,
                                    seg=self.apic1(0.5))
        # Record
        rec = Record(self.soma(0.5))
        # Run
        sim = Simulation(init_v=-70, warmup=20)
        sim.run(1)

        syn.make_event(50)

        sim.run(100)
        r = rec.as_numpy(variable="v")

        syn.remove_immediate_from_neuron()
        sim.remove_immediate_from_neuron()
        rec.remove_immediate_from_neuron()

        # Make assertions
        self.assertEqual(4051, r.size)
        self.assertEqual(34.4582, round(r.records.max(), 4))
        self.assertEqual(-75.3478, round(r.records.min(), 4))

        self.assertEqual(2159, r.records.argmax())
        # time in ms of max mV value
        self.assertEqual(73.725, round(r.time[r.records.argmax()], 4))
Exemplo n.º 7
0
    def test_add_netcon_and_make_event_separately(self):
        g1 = self.cell.filter_synaptic_group(mod_name="Exp2Syn", tag="aa")
        nc = g1.add_netcon(source=None)

        exp2syn_rec = Record(g1['Exp2Syn'][0], variables='i')
        expsyn_rec = Record(g1['ExpSyn'][0], variables='i')

        sim = Simulation()
        sim.run(1)
        nc['Exp2Syn'][0].make_event(10)
        nc['ExpSyn'][0].make_event(20)
        sim.run(100)

        exp2syn_np = exp2syn_rec.as_numpy('i')
        stim_time_exp2syn = exp2syn_np.time[(exp2syn_np.records != 0).argmax()]
        expsyn_np = expsyn_rec.as_numpy('i')
        stim_time_expsyn = expsyn_np.time[(expsyn_np.records != 0).argmax()]

        self.assertEqual(12.05, round(stim_time_exp2syn, 4))
        self.assertEqual(22.025, round(stim_time_expsyn, 4))

        # Remove variables and clear NEURON
        nc['Exp2Syn'][0].remove_immediate_from_neuron()
        nc['ExpSyn'][0].remove_immediate_from_neuron()
        nc = {}
        g1.remove_immediate_from_neuron()
        exp2syn_rec.remove_immediate_from_neuron()
        expsyn_rec.remove_immediate_from_neuron()
        sim.remove_immediate_from_neuron()
Exemplo n.º 8
0
    def test_record_before_sim(self):
        """
        Record created before simulation run is full of data
        """
        # Record
        rec = Record(self.soma(0.5))

        # IClamp to soma
        iclamp = IClamp(segment=self.soma(0.5))
        iclamp.stim(delay=25, dur=3, amp=3)

        # Run
        sim = Simulation(init_v=-70, warmup=20)
        sim.run(1)
        print(h.t)

        sim.run(100)
        r = rec.as_numpy(variable="v")

        # Make assertions
        self.assertEqual(4051, r.size)
        self.assertEqual(34.3815, round(r.records.max(), 4))
        self.assertEqual(-75.3247, round(r.records.min(), 4))

        self.assertEqual(330, r.records.argmax())
        # time in ms of max mV value
        self.assertEqual(28, round(r.time[r.records.argmax()], 4))
    def setUpClass(cls):
        morpho_path = os.path.join(path, "..",
                                   "commons/morphologies/asc/cell2.asc")

        # Create cell
        cell = Cell(name="cell")
        cell.load_morpho(filepath=morpho_path)
        cell.insert("pas")
        cell.insert("hh")

        soma = cell.filter_secs("soma")
        dend = cell.filter_secs("apic[10]")
        syn = cell.add_synapse(source=None, mod_name="ExpSyn", seg=dend(0.5))

        # Prepare EPSP and AP (IClamp) protocols
        experiment = Experiment(iti=40)
        experiment.add_epsp(num=3,
                            synapse=syn,
                            init=20,
                            interval=20,
                            weight=0.02)
        experiment.add_iclamp(num=3,
                              segment=soma(0.5),
                              init=60,
                              interval=20,
                              dur=3,
                              amp=1.6)
        experiment.build()

        # Prepare plots
        rec = Record([soma(0.5), dend(0.5)], variables='v')

        # Run
        sim = Simulation(init_v=-70,
                         warmup=20,
                         with_neuron_gui=False,
                         constant_timestep=True)
        sim.run(runtime=100)

        cls.v_soma = rec.as_numpy('v', segment_name=soma(.5).name)
        cls.v_apic = rec.as_numpy('v', segment_name=dend(.5).name)

        syn.remove_immediate_from_neuron()
        soma.remove_immediate_from_neuron()
        dend.remove_immediate_from_neuron()
        rec.remove_immediate_from_neuron()
        experiment.remove_immediate_from_neuron()
        cell.remove_immediate_from_neuron()
        sim.remove_immediate_from_neuron()

        cls.sections_left = len(list(h.allsec()))
Exemplo n.º 10
0
    def test_timestep_constant(self):
        rec = Record(self.soma(0.5))

        sim = Simulation(constant_timestep=True, dt=1)
        sim.run(100)
        r1 = rec.as_numpy('v')

        sim = Simulation(constant_timestep=False, dt=1)
        sim.run(100)
        r2 = rec.as_numpy('v')

        sim = Simulation(constant_timestep=False, dt=10)
        sim.run(100)
        r3 = rec.as_numpy('v')

        sim = Simulation(constant_timestep=False, dt=0.0001)
        sim.run(100)
        r4 = rec.as_numpy('v')

        sim.remove_immediate_from_neuron()
        rec.remove_immediate_from_neuron()

        self.assertEqual(101, r1.size)
        self.assertEqual(188, r2.size)
        self.assertEqual(180, r3.size)
        self.assertEqual(189, r4.size)
Exemplo n.º 11
0
    def test_init_v(self):
        rec = Record(self.soma(0.5))

        sim = Simulation(init_v=-100)
        sim.run(100)
        r1 = rec.as_numpy('v')

        sim = Simulation(init_v=100)
        sim.run(100)
        r2 = rec.as_numpy('v')

        sim.remove_immediate_from_neuron()
        rec.remove_immediate_from_neuron()

        self.assertEqual(-100, r1.records[0])
        self.assertEqual(100, r2.records[0])
Exemplo n.º 12
0
    def test_dt(self):
        rec = Record(self.soma(0.5))

        sim = Simulation(dt=10)
        sim.run(100)
        r1 = rec.as_numpy('v')

        sim = Simulation(dt=0.01)
        sim.run(100)
        r2 = rec.as_numpy('v')

        sim.remove_immediate_from_neuron()
        rec.remove_immediate_from_neuron()

        self.assertEqual(11, r1.size)
        self.assertEqual(10001, r2.size)
Exemplo n.º 13
0
    def test_stim_syns(self):
        gs = self.cell.filter_synaptic_group()

        gs0_exp2syn_rec = Record(gs[0]['Exp2Syn'][0], variables='i')
        gs0_expsyn_rec = Record(gs[0]['ExpSyn'][0], variables='i')

        gs1_exp2syn_rec = Record(gs[1]['Exp2Syn'][0], variables='i')
        gs1_expsyn_rec = Record(gs[1]['ExpSyn'][0], variables='i')

        sim = Simulation()
        sim.run(1)

        gs[0].make_event(10)
        gs[1].make_event(20)

        sim.run(100)

        # Test stim time of synaptic group 1
        gs0_exp2syn_np = gs0_exp2syn_rec.as_numpy('i')
        stim_time_gs0_exp2syn = gs0_exp2syn_np.time[(gs0_exp2syn_np.records != 0).argmax()]

        gs0_expsyn_np = gs0_expsyn_rec.as_numpy('i')
        stim_time_gs0_expsyn = gs0_expsyn_np.time[(gs0_expsyn_np.records != 0).argmax()]

        self.assertEqual(round(stim_time_gs0_exp2syn, 1), round(stim_time_gs0_expsyn, 1))

        # Test stim time of synaptic group 2
        gs1_exp2syn_np = gs1_exp2syn_rec.as_numpy('i')
        stim_time_gs1_exp2syn = gs1_exp2syn_np.time[(gs1_exp2syn_np.records != 0).argmax()]

        gs1_expsyn_np = gs1_expsyn_rec.as_numpy('i')
        stim_time_gs1_expsyn = gs1_expsyn_np.time[(gs1_expsyn_np.records != 0).argmax()]

        self.assertEqual(round(stim_time_gs1_exp2syn, 1), round(stim_time_gs1_expsyn, 1))

        # Test values of mV in soma
        self.assertEqual(31.3285, round(gs0_exp2syn_np.records.max(), 4))
        self.assertEqual(-61.309, round(gs0_exp2syn_np.records.min(), 4))

        # Remove variables and clear NEURON
        gs0_exp2syn_rec.remove_immediate_from_neuron()
        gs0_expsyn_rec.remove_immediate_from_neuron()
        gs1_exp2syn_rec.remove_immediate_from_neuron()
        gs1_expsyn_rec.remove_immediate_from_neuron()
        gs[0].remove_immediate_from_neuron()
        gs[1].remove_immediate_from_neuron()
        sim.remove_immediate_from_neuron()
Exemplo n.º 14
0
    def test_record_after_sim(self):
        """
        record created after simulation run is empty
        """
        # IClamp to soma
        iclamp = IClamp(segment=self.soma(0.5))
        iclamp.stim(delay=25, dur=3, amp=3)

        # Run
        sim = Simulation(init_v=-70, warmup=20)
        sim.run(1)
        print(h.t)

        # Record
        rec = Record(self.soma(0.5))

        sim.run(100)
        r = rec.as_numpy(variable="v")

        # Make assertion
        self.assertEqual(0, r.size)
Exemplo n.º 15
0
    def test_warmup(self):
        rec = Record(self.soma(0.5))

        value_error = False
        try:
            sim = Simulation(warmup=-100)
            sim.run(100)
            r1 = rec.as_numpy('v')
        except ValueError:
            value_error = True
        self.assertTrue(value_error)

        sim = Simulation(warmup=100, dt=1)
        sim.run(100)
        r2 = rec.as_numpy('v')

        sim = Simulation(warmup=100, dt=1, warmup_dt=1)
        sim.run(100)
        r3 = rec.as_numpy('v')

        sim.remove_immediate_from_neuron()
        rec.remove_immediate_from_neuron()

        self.assertEqual(111, r2.size)
        self.assertEqual(201, r3.size)
Exemplo n.º 16
0
    # make VecStim
    vs_cell = VecStimCell("vecstim_cell")
    stim2 = vs_cell.make_vecstim(np.array([WARMUP+50]))

    # make synapses with spines
    syns_4p, heads = cell.add_synapses_with_spine(source=None, secs=cell.secs, number=100, netcon_weight=WEIGHT,
                                                  mod_name="Syn4PAChDa", delay=1, **cell.params_4p_syn)
    for s, h in zip(syns_4p, heads):
        syn_ach = cell.add_synapse(source=stim1, mod_name="SynACh", seg=h(1.0), netcon_weight=0.1, delay=1)
        syn_da = cell.add_synapse(source=stim2, mod_name="SynDa", seg=h(1.0), netcon_weight=0.1, delay=1)
        cell.set_synaptic_pointers(s, syn_ach, syn_da)

    # add mechanisms
    cell.make_default_mechanisms()
    cell.make_apical_mechanisms(sections='head neck')

    # make plots
    rec_4psyn = Record(cell.filter_point_processes(mod_name="Syn4PAChDa", name="head[0]"), variables="w")

    # init and run
    sim = Simulation(init_v=-70, warmup=WARMUP)
    sim.run(runtime=200)

    # Event delivery
    syns_4p[0].make_event(10)

    sim.run(runtime=200)

    # plot
    rec_4psyn.plot()
Exemplo n.º 17
0
        cell.group_synapses(tag="input_syn", synapses=[s, syn_ach, syn_da])

    # add mechanisms
    cell.make_default_mechanisms()
    cell.make_apical_mechanisms(sections='dend head neck')

    soma = cell.filter_secs("soma")

    syns = cell.filter_synaptic_group()
    syn4p = syns[0]['Syn4PAChDa']
    synach = syns[0]['SynACh']

    rec_syn = Record(syn4p, variables="w stdp_ach ach_stdp ACh ACh_w")
    rec_soma = Record(soma(0.5), variables="v")

    sim = Simulation(init_v=-80, warmup=WARMUP, warmup_on_create=True)

    event = 0
    inter = 5
    for i in range(10):
        for syn in syns:
            syn['Syn4PAChDa'][0].make_event(event)
            syn['SynACh'][0].make_event(event)
            event += inter

    sim.run(runtime=150)

    # plot
    rec_soma.plot()
    rec_syn.plot()
Exemplo n.º 18
0
    soma = cell.filter_secs("soma")

    # Netstim to synapse
    stim = NetStimCell("stim").add_netstim(start=WARMUP,
                                           number=REPS,
                                           interval=interval)
    syn = cell.add_synapse(source=stim,
                           netcon_weight=WEIGHT,
                           mod_name="Syn4P",
                           delay=1,
                           seg=cell.filter_secs('apic[1]')(0.5))

    # IClamp to soma
    iclamp = IClamp(segment=cell.filter_secs("soma")(0.5))
    for i in range(REPS):
        start_t = WARMUP + delta_t + i * interval
        iclamp.stim(delay=start_t, dur=DUR, amp=AMP)

    # Record
    rec = Record([s(0.5) for s in cell.filter_secs("apic[1],apic[50]")])

    # Run
    sim = Simulation(init_v=-70, warmup=WARMUP, dt=DT)
    total_time = REPS * interval + COOL_DOWN
    sim.run(total_time)

    # Plot
    rec.plot(position="merge")
    plt.show()
Exemplo n.º 19
0
    connector.build()
    pop1.record()

    # Create population 2
    pop2 = Population("pop_2")
    pop2.add_cells(num=4, cell_function=cell_function)

    connector = pop2.connect(cell_connection_proba=connection_proba,
                             seg_dist=NormalTruncatedSegDist(0.5, 0.1))
    connector.set_source([c.filter_secs("soma")(0.5) for c in pop1.cells])
    connector.set_target([d(0.5) for c in pop1.cells for d in c.filter_secs("dend")])
    syn_adder = connector.add_synapse("Exp2Syn")
    syn_adder.add_netcon(weight=weight_dist)

    connector.build()
    pop2.record()

    # Create connectivity graph grouped by populations, with weighs and spike rates updated
    graph = NetworkGraph(populations=[pop1, pop2])
    graph.plot()

    # Run
    sim = Simulation(init_v=-70, warmup=20)
    for i in range(1000):
        sim.run(runtime=1)
        pop1.plot(animate=True)
        pop2.plot(animate=True)

        #graph.update_weights()
        #graph.update_spikes()
Exemplo n.º 20
0
class AgentCore:
    def __init__(self, input_max_hz, default_stepsize):
        """
        Before Agent step() you need to call:
          1. agent.build()
          2. agent.init()

        :param input_max_hz:
        :param default_stepsize:
        """
        self.reward_syns = []
        self.punish_syns = []

        self.input_max_hz = input_max_hz
        self.default_stepsize = default_stepsize
        self.max_input_stim_per_stepsize = (default_stepsize *
                                            input_max_hz) / 1000

        if self.max_input_stim_per_stepsize < 1:
            raise ValueError(
                "Agent's self.max_input_stim_per_stepsize must be > 1, choose "
                "input_max_hz and stepsize params carefully.")
        print("max_input_stim_per_stepsize:", self.max_input_stim_per_stepsize)

        self.sim = None
        self.warmup = None

        self.input_size = None
        self.input_shape = None
        self.input_cell_num = None

        self.input_cells = None
        self.output_cells = None

        self._built = False

    def init(self,
             input_cells: List[Cell],
             output_cells: List[Cell],
             reward_syns: List[Synapse] = (),
             punish_syns: List[Synapse] = (),
             init_v=-70,
             warmup=0,
             dt=0.1):
        """
        Before Agent step() you need to call:
          1. agent.build()
          2. agent.init()

        :param input_cells:
            list of input cells
        :param output_cells:
            list of output cells
        :param init_v:
        :param warmup:
        :param dt:
        """
        self.input_cells = input_cells
        self.output_cells = output_cells

        self.reward_syns = reward_syns
        self.punish_syns = punish_syns

        if self.sim is not None:
            raise RuntimeError(
                "Simulation cannot been run before initialization.")

        self.warmup = warmup
        self.sim = Simulation(init_v=init_v,
                              warmup=warmup,
                              dt=dt,
                              warmup_on_create=True)

    def step(self,
             observation: np.array,
             output_type="time",
             sort_func=None,
             poisson=False,
             stepsize=None):
        """
        :param observation:
            numpy array. 1 or 2 dim are allowed
        :param output_type:
            "time": returns time of first spike for each motor cells.
            "rate": returns number of spikes for each motor cells OR -1 if there were no spike for
            the cell.
            "raw": returns raw array for each motor cell of all spikes in time in ms.
        :param sort_func:
            Optional function which define sorting on list of AgentOutput objects.
        :param poisson:
            if use Poisson distribution for each pixel stimulation. Default is False.
        :param stepsize:
            in ms. If None - it will use self.default_stepsize.
        :return:
            list(AgentOutput(index, cell_name, value))
        """
        # Check agent's built and initialization before step
        if not self._built:
            raise RuntimeError(
                "Before step you need to build() agent and then initialize by calling init() "
                "function first.")

        if self.sim is None:
            raise RuntimeError(
                "Before step you need to initialize the Agent by calling init() function first."
            )

        if self.input_cells is None or len(self.input_cells) == 0:
            raise LookupError(
                "Method self._build_network() must return tuple(input_cells, output_cells), "
                "however input_cells were not defined.")

        self._make_observation(observation=observation,
                               poisson=poisson,
                               stepsize=stepsize)

        # Run
        self._make_sim(stepsize)

        # Make output
        output = self._get_output(output_type)
        if sort_func:
            output = sorted(output, key=sort_func)
        return output

    def reward_step(self, reward, stepsize=None):
        """
        It allows to sense the reward by the agent for stepsize time.

        :param reward:
            the value of the reward
        :param stepsize:
            in ms. If None - it will use self.default_stepsize.
        """
        self._make_reward(reward)
        self._make_sim(stepsize)

    @staticmethod
    def get_kernel_size(w, f, p, s):
        """
        Naming convention comes from the Convolutional Neural Networks.

        :param w:
            image size of one of dimentions
        :param f:
            convolution size of one of dimentions
        :param p:
            padding
        :param s:
            stride
        :return:
            size of kernel for one of dimention
        """
        return math.floor((w - f + 2 * p) / s + 1)

    @abc.abstractmethod
    def build(self, **kwargs):
        raise NotImplementedError()

    @abc.abstractmethod
    def _make_observation(self, observation, poisson=False, stepsize=None):
        raise NotImplementedError()

    def _build(self, input_shape, input_size, input_cell_num):
        """

        :param input_shape:
        :param input_size:
        :param input_cell_num:
        """
        if self._built or self.sim is not None:
            raise RuntimeError(
                "You must first build agent before initialisation and run "
                "the simulation.")

        self.input_shape = input_shape
        self.input_size = input_size
        self.input_cell_num = input_cell_num
        self._built = True

    def _make_sim(self, stepsize=None):
        if stepsize is None:
            stepsize = self.default_stepsize
        self.sim.run(stepsize)

    def _make_reward(self, reward):
        if not self._built:
            raise RuntimeError(
                "Before making reward you need to build the Agent by calling "
                "build() function first.")
        if self.sim is None:
            raise RuntimeError(
                "Before making reward you need to initialize the Agent by calling "
                "init() function first.")

        if reward > 0:
            for s in self.reward_syns:
                s.make_event(1)
        elif reward < 0:
            for s in self.punish_syns:
                s.make_event(1)

    def _get_output(self, output_type):
        """
        :param output_type:
            "time": returns time of first spike for each motor cells.
            "rate": returns number of spikes for each motor cells OR -1 if there were no spike for
            the cell.
            "raw": returns raw array for each motor cell of all spikes in time in ms.
        :return:
            list(AgentOutput(index, value))
        """
        outputs = []
        min_time = self.sim.t - self.sim.current_runtime
        for i, c in enumerate(self.output_cells):
            spikes = np.array([i for i in c.spikes() if i >= min_time])

            if output_type == "rate":
                s = len(spikes) if len(spikes) > 0 else -1
            elif output_type == "time":
                s = spikes[0] if len(spikes) > 0 else -1
            elif output_type == "raw":
                s = spikes
            else:
                raise TypeError(
                    "Output type can be only string of: 'rate' or 'time', "
                    "but provided %s" % output_type)
            outputs.append(AgentOutput(index=i, cell_name=c.name, value=s))

        return outputs

    def _make_single_observation(self,
                                 observation,
                                 syns,
                                 poisson,
                                 stepsize=None):
        """
        The core observation method which match observation flat array (1D) to the list of synapses.
        observation and syns need to be of the same length.

        :param observation:
            1 dim array of numbers
        :param syns:
            1 d array of synapses
        """
        if len(observation) != len(syns):
            raise ValueError(
                "Single 1D observation or flatten kernel of 2D observation "
                "must have the same length as provided subgroup of synapses.")

        for pixel, syn in zip(observation, syns):
            if pixel > 0:
                stim_num, interval = self._get_stim_values(
                    pixel, poisson, stepsize)
                next_event = 0
                for e in range(stim_num):
                    syn.make_event(next_event)
                    next_event += interval

    def _get_stim_values(self, pixel, poisson=False, stepsize=None):
        """
        Returns number of events and their interval for a single synaptic stimulation

        :param pixel:
            single pixel value
        :param poisson:
            If use poisson distribution, Default is False.
        :param stepsize:
            stepsize for this observation. if default None - it will take self.default_stepsize
        :return:
            tuple(number of events, interval between events)
        """
        stim_num = 0
        stim_int = 0

        if pixel <= 0:
            return stim_num, stim_int

        if stepsize is None:
            stepsize = self.default_stepsize
            max_stim = self.max_input_stim_per_stepsize
        else:
            max_stim = (stepsize * self.input_max_hz) / 1000

        stim_num = int(round(pixel * max_stim))
        if poisson:
            stim_num = np.random.poisson(stim_num, 1)[0]
        if stim_num > 0:
            stim_int = stepsize / stim_num
        return stim_num, stim_int

    def _add_output_spike_detectors(self):
        for oc in self.output_cells:

            if not hasattr(oc, "_spike_detector"):
                raise TypeError(
                    "Output cells must be of type NetConCell and have spike detection "
                    "mechanism.")

            if oc._spike_detector is None:
                soma = oc.filter_secs("soma")
                if isinstance(soma, list):
                    raise LookupError(
                        "Output cells need to setup spike detector or at least have "
                        "a single 'soma' section so that spike detection can be "
                        "implemented automatically.")

                oc.make_spike_detector(soma(0.5))

    def _get_recursive_cells(self, obj):
        acc = []
        if isinstance(obj, CoreCell):
            acc.append(obj)
        elif isinstance(obj, Population):
            acc.extend(obj.cells)
        elif isinstance(obj, list):
            for o in obj:
                ac = self._get_recursive_cells(o)
                acc.extend(ac)
        return acc
    cell = Cell("cell", compile_paths=filepath)
    soma = cell.add_sec("soma", diam=20, l=20, nseg=10)
    cell.insert('pas')
    cell.insert('hh')

    w = 0.003  # LTP
    #w = 0.0022  # LTD
    syn = cell.add_synapse(source=None, netcon_weight=w, seg=soma(0.5), mod_name="ExcSigma3Exp2SynAchDa")
    pp = syn.point_process
    ach_netcon = cell.add_netcon(source=None, point_process=pp,
                                 netcon_weight=0.1+pp.hoc.ach_substractor, delay=1)
    da_netcon = cell.add_netcon(source=None, point_process=syn.point_process,
                                netcon_weight=0.1+pp.hoc.da_substractor, delay=1)
    # prepare plots and spike detector
    rec_v = Record(soma(0.5), variables="v")
    rec_w = Record(syn, variables="w")

    # run
    sim = Simulation(init_v=-68, warmup=5)
    syn.make_event(5)
    da_netcon.make_event(7)

    syn.make_event(50)
    ach_netcon.make_event(52)
    sim.run(runtime=100)

    # plot
    rec_w.plot()
    rec_v.plot()
    plt.show()
Exemplo n.º 22
0
ns_cell = NetStimCell("stim_cell")
ns = ns_cell.make_netstim(start=30, number=5, interval=10)

syns = cell.add_synapses_with_spine(source=ns,
                                    secs=cell.filter_secs("apic"),
                                    mod_name="ExpSyn",
                                    netcon_weight=0.01,
                                    delay=1,
                                    number=100)
soma = cell.filter_secs("soma")

# Create IClamp
ic = IClamp(segment=soma(0.5))
ic.stim(delay=100, dur=10, amp=0.1)

# prepare plots and spike detector
rec_v = Record(soma(0.5), variables="v")
cell.make_spike_detector(soma(0.5))

# run
sim = Simulation(init_v=-65,
                 warmup=20,
                 init_sleep=2,
                 with_neuron_gui=True,
                 shape_plots=[make_shape_plot()])
sim.run(runtime=200, stepsize=1, delay_between_steps=500)

# plot
cell.plot_spikes()
rec_v.plot()
plt.show()
Exemplo n.º 23
0
                     spine_number=10,
                     spine_secs_names="apic",
                     spine_seed=13)

soma = cell.filter_secs("soma")
syns = cell.filter_complex_synapses(tag="combe")

# Prepare STDP protocol
stdp = Experiment()
stdp.make_protocol("3xEPSP[int=10] 3xAP[int=10,dur=3,amp=1.6]",
                   start=1,
                   isi=10,
                   epsp_synapse=syns[0],
                   i_clamp_section=soma)

# Prepare plots
v_soma_rec = Record([soma(0.5), syns[0].parent], variables='v')
cai_head0_rec = Record(syns[0].parent, variables='cai')

# Run
sim = Simulation(init_v=-70,
                 warmup=20,
                 with_neuron_gui=True,
                 constant_timestep=False)
sim.run(runtime=100, debug=True)

# Plot
cai_head0_rec.plot()
v_soma_rec.plot()
v_soma_rec.to_csv("vrec.csv")
Exemplo n.º 24
0
from neuronpp.utils.record import Record
from neuronpp.utils.simulation import Simulation

path = os.path.dirname(os.path.abspath(__file__))

if __name__ == '__main__':
    # Prepare cell
    filepath = os.path.join(path, "..",
                            "commons/mods/sigma3syn")
    cell = Cell("cell", compile_paths=filepath)
    soma = cell.add_sec("soma", diam=20, l=20, nseg=10)
    cell.insert('pas')
    cell.insert('hh')

    w = 0.003  # LTP
    #w = 0.0022  # LTD
    syn = cell.add_synapse(source=None, netcon_weight=w, seg=soma(0.5), mod_name="ExcSigma3Exp2Syn")

    # prepare plots and spike detector
    rec_v = Record(soma(0.5), variables="v")
    rec_w = Record(syn, variables="w")

    # run
    sim = Simulation(init_v=-68, warmup=5)
    syn.make_event(5)
    sim.run(runtime=50)

    # plot
    rec_w.plot()
    rec_v.plot()
Exemplo n.º 25
0
class SynapticDebugger:
    def __init__(self, init_v=-70, warmup=0, delay_between_steps=0):
        """

        :param init_v:
        :param warmup:
        :param delay_between_steps:
            in ms
        """
        self.syns = defaultdict(list)
        self.secs = []

        self.syn_recs = []
        self.sec_recs = []

        self.init_v = init_v
        self.warmup_time = warmup
        self.delay_between_steps = delay_between_steps / 1000
        self.sim = None

    def add_syn(self,
                syn: Synapse,
                syn_variables=None,
                key_press=None,
                plot=True):
        if not isinstance(syn, Synapse):
            raise TypeError(
                "Param 'syn' must be of type Synapse, but provided '%s'" %
                syn.__class__)
        if plot and syn_variables:
            rec = Record(elements=syn, variables=syn_variables)
            self.syn_recs.append(rec)

        name = key_press
        if name is None:
            name = str(len(self.syns))
        self.syns[name].append(syn)

    def add_con(self, con: NetCon, key_press=None):
        if not isinstance(con, NetCon):
            raise TypeError(
                "Param 'con' must be of type NetCon, but provided '%s'" %
                con.__class__)
        name = key_press
        if name is None:
            name = str(len(self.syns))
        self.syns[name].append(con)

    def add_seg(self, seg: Seg, sec_variables='v'):
        if not isinstance(seg, Seg):
            raise TypeError(
                "Param 'seg' must be of type Seg, but provided '%s'" %
                seg.__class__)
        rec = Record(elements=seg, variables=sec_variables)
        self.sec_recs.append(rec)

    def warmup(self):
        if self.sim is None:
            self.sim = Simulation(init_v=self.init_v, warmup=self.warmup_time)

    def debug(self, i=None, name=None, stim_time=0, run_time=1):
        self.warmup()

        if run_time <= stim_time:
            raise ValueError(
                "Param 'run_time' cannot be smaller than 'stim_time'.")

        for syns in self._get_syns(name):
            if i is None:
                for s in syns:
                    s.make_event(stim_time)
            else:
                self.syns[i].make_event(stim_time)

        self.run(run_time)

    def stim(self, index=None, name=None, stim_time=1):
        """
        :param index:
            Index of the synapse. If None - all will be stim
        :param stim_time:
            in ms
        :return:
        """
        self.warmup()

        if index is None:
            for s in self._get_syns(name):
                s.make_event(stim_time)
        else:
            self.syns[index].make_event(stim_time)

    def run(self, run_time=1, plot_steps=10000):
        """

        :param run_time:
        in ms
        :return:
        """
        self.warmup()

        for _ in range(run_time):
            self.sim.run(1)
            if self.delay_between_steps > 0:
                time.sleep(self.delay_between_steps)
            self._make_plots(plot_steps)

    def debug_interactive(self, index=None, plot_steps=10000, interval=1):
        """
        :param index:
            Index of the synapse. If None - all will be stim
        :param interval:
            in ms
        :return:
        """
        self.warmup()
        keys = ['']

        def key_press(key):
            keys[0] = key

        key_release_listener(key_press)

        while True:
            key_pressed = keys[0]

            for stim_key_name in self.syns.keys():
                if len(key_pressed) > 0:
                    if key_pressed == stim_key_name:
                        self.stim(index=index, name=stim_key_name)
                        keys[0] = ''
                        break

            self.run(interval, plot_steps=plot_steps)

    def _get_syns(self, name):
        if name is None:
            return [s for syns in self.syns.values() for s in syns]
        else:
            return self.syns[name]

    def _make_plots(self, plot_steps):
        for syn_rec in self.syn_recs:
            syn_rec.plot(animate=True, steps=plot_steps)
        for sec_rec in self.sec_recs:
            sec_rec.plot(animate=True, steps=plot_steps)