From 9b307e9c8dd795cc65e3c03ec7568ef3dcc8209a Mon Sep 17 00:00:00 2001 From: anilbey Date: Thu, 1 Feb 2024 13:51:25 +0100 Subject: [PATCH] replace bluecellulab.neuron -> neuron (#122) * replace bluecellulab.neuron -> neuron Import neuron directly for simplicity. --- bluecellulab/cell/core.py | 31 +++++----- bluecellulab/cell/injector.py | 46 +++++++-------- bluecellulab/cell/plotting.py | 19 ++++--- bluecellulab/cell/section_distance.py | 13 ++--- bluecellulab/cell/stimuli_generator.py | 32 +++++------ bluecellulab/cell/template.py | 6 +- bluecellulab/circuit/config/sections.py | 3 +- bluecellulab/connection.py | 16 +++--- bluecellulab/psection.py | 3 +- bluecellulab/psegment.py | 20 ++++--- bluecellulab/rngsettings.py | 16 +++--- bluecellulab/simulation/neuron_globals.py | 20 +++---- bluecellulab/simulation/simulation.py | 8 +-- bluecellulab/ssim.py | 3 +- bluecellulab/synapse/synapse_types.py | 19 ++++--- bluecellulab/tools.py | 5 +- tests/test_ballstick.py | 59 ++++++++++---------- tests/test_cell/test_core.py | 39 +++++-------- tests/test_cell/test_injector.py | 19 ++++--- tests/test_cell/test_random.py | 2 +- tests/test_cell/test_stimuli_generator.py | 6 +- tests/test_neuron_interpreter.py | 5 +- tests/test_rngsettings.py | 12 ++-- tests/test_simulation/test_neuron_globals.py | 24 ++++---- 24 files changed, 215 insertions(+), 211 deletions(-) diff --git a/bluecellulab/cell/core.py b/bluecellulab/cell/core.py index 2c00003a..af5b1c80 100644 --- a/bluecellulab/cell/core.py +++ b/bluecellulab/cell/core.py @@ -22,11 +22,12 @@ from typing import Optional from typing_extensions import deprecated +import neuron import numpy as np import pandas as pd import bluecellulab -from bluecellulab import neuron, psection +from bluecellulab import psection from bluecellulab.cell.injector import InjectableMixin from bluecellulab.cell.plotting import PlottableMixin from bluecellulab.cell.section_distance import EuclideanSectionDistance @@ -328,9 +329,9 @@ def area(self) -> float: x_s = np.arange(1.0 / (2 * section.nseg), 1.0, 1.0 / (section.nseg)) for x in x_s: - area += bluecellulab.neuron.h.area(x, sec=section) + area += neuron.h.area(x, sec=section) # for segment in section: - # area += bluecellulab.neuron.h.area(segment.x, sec=section) + # area += neuron.h.area(segment.x, sec=section) return area def add_recording(self, var_name: str, dt: Optional[float] = None) -> None: @@ -346,11 +347,11 @@ def add_recording(self, var_name: str, dt: Optional[float] = None) -> None: # This float_epsilon stuff is some magic from M. Hines to make # the time points fall exactly on the dts recording.record( - eval_neuron(var_name, self=self, neuron=bluecellulab.neuron), + eval_neuron(var_name, self=self, neuron=neuron), self.get_precise_record_dt(dt), ) else: - recording.record(eval_neuron(var_name, self=self, neuron=bluecellulab.neuron)) + recording.record(eval_neuron(var_name, self=self, neuron=neuron)) self.recordings[var_name] = recording @staticmethod @@ -506,7 +507,7 @@ def create_netcon_spikedetector(self, target: HocObjectType, location: str, thre source = public_hoc_cell(self.cell).axon[1](0.5)._ref_v else: raise ValueError("Spike detection location must be soma or AIS") - netcon = bluecellulab.neuron.h.NetCon(source, target, sec=sec) + netcon = neuron.h.NetCon(source, target, sec=sec) netcon.threshold = threshold return netcon @@ -519,7 +520,7 @@ def start_recording_spikes(self, target: HocObjectType, location: str, threshold threshold: spike detection threshold """ nc = self.create_netcon_spikedetector(target, location, threshold) - spike_vec = bluecellulab.neuron.h.Vector() + spike_vec = neuron.h.Vector() nc.record(spike_vec) self.recordings[f"spike_detector_{location}_{threshold}"] = spike_vec @@ -576,18 +577,18 @@ def add_replay_minis(self, if spont_minis_rate is not None and spont_minis_rate > 0: sec = self.get_hsection(post_sec_id) # add the *minis*: spontaneous synaptic events - self.ips[synapse_id] = bluecellulab.neuron.h.\ + self.ips[synapse_id] = neuron.h.\ InhPoissonStim(location, sec=sec) - self.syn_mini_netcons[synapse_id] = bluecellulab.neuron.h.\ + self.syn_mini_netcons[synapse_id] = neuron.h.\ NetCon(self.ips[synapse_id], synapse.hsynapse, sec=sec) self.syn_mini_netcons[synapse_id].delay = 0.1 self.syn_mini_netcons[synapse_id].weight[0] = weight * weight_scalar # set netcon type nc_param_name = 'nc_type_param_{}'.format( synapse.hsynapse).split('[')[0] - if hasattr(bluecellulab.neuron.h, nc_param_name): - nc_type_param = int(getattr(bluecellulab.neuron.h, nc_param_name)) + if hasattr(neuron.h, nc_param_name): + nc_type_param = int(getattr(neuron.h, nc_param_name)) # NC_SPONTMINI self.syn_mini_netcons[synapse_id].weight[nc_type_param] = 1 @@ -602,10 +603,10 @@ def add_replay_minis(self, self.cell_id.id + 250, seed2 + 350) else: - exprng = bluecellulab.neuron.h.Random() + exprng = neuron.h.Random() self.persistent.append(exprng) - uniformrng = bluecellulab.neuron.h.Random() + uniformrng = neuron.h.Random() self.persistent.append(uniformrng) if self.rng_settings.mode == 'Compatibility': @@ -636,9 +637,9 @@ def add_replay_minis(self, self.ips[synapse_id].setRNGs(exprng, uniformrng) - tbins_vec = bluecellulab.neuron.h.Vector(1) + tbins_vec = neuron.h.Vector(1) tbins_vec.x[0] = 0.0 - rate_vec = bluecellulab.neuron.h.Vector(1) + rate_vec = neuron.h.Vector(1) rate_vec.x[0] = spont_minis_rate self.persistent.append(tbins_vec) self.persistent.append(rate_vec) diff --git a/bluecellulab/cell/injector.py b/bluecellulab/cell/injector.py index 853a14d6..deb10d2e 100644 --- a/bluecellulab/cell/injector.py +++ b/bluecellulab/cell/injector.py @@ -17,10 +17,10 @@ import warnings import logging +import neuron import numpy as np from typing_extensions import deprecated -import bluecellulab from bluecellulab.cell.stimuli_generator import ( gen_ornstein_uhlenbeck, gen_shotnoise_signal, @@ -60,7 +60,7 @@ def relativity_proportion(self, stim_mode: ClampMode) -> float: def add_pulse(self, stimulus): """Inject pulse stimulus for replay.""" - tstim = bluecellulab.neuron.h.TStim(0.5, sec=self.soma) + tstim = neuron.h.TStim(0.5, sec=self.soma) tstim.train(stimulus.delay, stimulus.duration, stimulus.amp_start, @@ -74,7 +74,7 @@ def add_step(self, start_time, stop_time, level, section=None, segx=0.5): if section is None: section = self.soma - tstim = bluecellulab.neuron.h.TStim(segx, sec=section) + tstim = neuron.h.TStim(segx, sec=section) duration = stop_time - start_time tstim.pulse(start_time, duration, level) self.persistent.append(tstim) @@ -86,7 +86,7 @@ def add_ramp(self, start_time, stop_time, start_level, stop_level, if section is None: section = self.soma - tstim = bluecellulab.neuron.h.TStim(segx, sec=section) + tstim = neuron.h.TStim(segx, sec=section) tstim.ramp( 0.0, @@ -133,7 +133,7 @@ def add_voltage_clamp( section = self.soma if current_record_dt is None: current_record_dt = self.record_dt - vclamp = bluecellulab.neuron.h.SEClamp(segx, sec=section) + vclamp = neuron.h.SEClamp(segx, sec=section) self.persistent.append(vclamp) vclamp.amp1 = level @@ -142,7 +142,7 @@ def add_voltage_clamp( if rs is not None: vclamp.rs = rs - current = bluecellulab.neuron.h.Vector() + current = neuron.h.Vector() if current_record_dt is None: current.record(vclamp._ref_i) else: @@ -156,16 +156,16 @@ def add_voltage_clamp( def _get_noise_step_rand(self, noisestim_count): """Return rng for noise step stimulus.""" if self.rng_settings.mode == "Compatibility": - rng = bluecellulab.neuron.h.Random(self.cell_id.id + noisestim_count) + rng = neuron.h.Random(self.cell_id.id + noisestim_count) elif self.rng_settings.mode == "UpdatedMCell": - rng = bluecellulab.neuron.h.Random() + rng = neuron.h.Random() rng.MCellRan4( noisestim_count * 10000 + 100, self.rng_settings.base_seed + self.rng_settings.stimulus_seed + self.cell_id.id * 1000) elif self.rng_settings.mode == "Random123": - rng = bluecellulab.neuron.h.Random() + rng = neuron.h.Random() rng.Random123( noisestim_count + 100, self.rng_settings.stimulus_seed + 500, @@ -181,11 +181,11 @@ def add_noise_step(self, section, duration, seed=None, noisestim_count=0): """Inject a step current with noise on top.""" if seed is not None: - rand = bluecellulab.neuron.h.Random(seed) + rand = neuron.h.Random(seed) else: rand = self._get_noise_step_rand(noisestim_count) - tstim = bluecellulab.neuron.h.TStim(segx, rand, sec=section) + tstim = neuron.h.TStim(segx, rand, sec=section) tstim.noise(delay, duration, mean, variance) self.persistent.append(rand) self.persistent.append(tstim) @@ -213,7 +213,7 @@ def add_replay_noise( def add_replay_hypamp(self, stimulus: Hyperpolarizing): """Inject hypamp for the replay.""" - tstim = bluecellulab.neuron.h.TStim(0.5, sec=self.soma) # type: ignore + tstim = neuron.h.TStim(0.5, sec=self.soma) # type: ignore if self.hypamp is None: # type: ignore raise BluecellulabError("Cell.hypamp must be set for hypamp stimulus") amp: float = self.hypamp # type: ignore @@ -223,7 +223,7 @@ def add_replay_hypamp(self, stimulus: Hyperpolarizing): def add_replay_relativelinear(self, stimulus): """Add a relative linear stimulus.""" - tstim = bluecellulab.neuron.h.TStim(0.5, sec=self.soma) + tstim = neuron.h.TStim(0.5, sec=self.soma) amp = stimulus.percent_start / 100.0 * self.threshold tstim.pulse(stimulus.delay, stimulus.duration, amp) self.persistent.append(tstim) @@ -238,7 +238,7 @@ def _get_ornstein_uhlenbeck_rand(self, stim_count, seed): seed3 = self.cell_id.id + 123 if seed is None else seed # GID logger.debug("Using ornstein_uhlenbeck process seeds %d %d %d" % (seed1, seed2, seed3)) - rng = bluecellulab.neuron.h.Random() + rng = neuron.h.Random() rng.Random123(seed1, seed2, seed3) else: raise BluecellulabError("Shot noise stimulus requires Random123") @@ -254,7 +254,7 @@ def _get_shotnoise_step_rand(self, shotnoise_stim_count, seed=None): seed3 = self.cell_id.id + 123 if seed is None else seed logger.debug("Using shot noise seeds %d %d %d" % (seed1, seed2, seed3)) - rng = bluecellulab.neuron.h.Random() + rng = neuron.h.Random() rng.Random123(seed1, seed2, seed3) else: raise BluecellulabError("Shot noise stimulus requires Random123") @@ -264,7 +264,7 @@ def _get_shotnoise_step_rand(self, shotnoise_stim_count, seed=None): def inject_current_clamp_signal(self, section, segx, tvec, svec): """Inject any signal via current clamp.""" - cs = bluecellulab.neuron.h.IClamp(segx, sec=section) + cs = neuron.h.IClamp(segx, sec=section) cs.dur = tvec[-1] svec.play(cs._ref_amp, tvec, 1) @@ -279,7 +279,7 @@ def inject_dynamic_clamp_signal(self, section, segx, tvec, svec, reversal): Args: reversal (float): reversal potential of conductance (mV) """ - clamp = bluecellulab.neuron.h.SEClamp(segx, sec=section) + clamp = neuron.h.SEClamp(segx, sec=section) clamp.dur1 = tvec[-1] clamp.amp1 = reversal # support delay with initial zero @@ -287,7 +287,7 @@ def inject_dynamic_clamp_signal(self, section, segx, tvec, svec, reversal): svec.insrt(0, 0) # replace svec with inverted and clamped signal # rs is in MOhm, so conductance is in uS (micro Siemens) - svec = bluecellulab.neuron.h.Vector( + svec = neuron.h.Vector( [1 / x if x > 1E-9 and x < 1E9 else 1E9 for x in svec]) svec.play(clamp._ref_rs, tvec, 1) @@ -400,14 +400,14 @@ def inject_current_waveform(self, t_content, i_content, section=None, """Inject a custom current to the cell.""" start_time = t_content[0] stop_time = t_content[-1] - time = bluecellulab.neuron.h.Vector() - currents = bluecellulab.neuron.h.Vector() + time = neuron.h.Vector() + currents = neuron.h.Vector() time = time.from_python(t_content) currents = currents.from_python(i_content) if section is None: section = self.soma - pulse = bluecellulab.neuron.h.IClamp(segx, sec=section) + pulse = neuron.h.IClamp(segx, sec=section) self.persistent.append(pulse) self.persistent.append(time) self.persistent.append(currents) @@ -443,7 +443,7 @@ def add_sin_current(self, amp, start_time, duration, frequency, """Add a sinusoidal current to the cell.""" if section is None: section = self.soma - tstim = bluecellulab.neuron.h.TStim(segx, sec=section) + tstim = neuron.h.TStim(segx, sec=section) tstim.sin(amp, start_time, duration, frequency) self.persistent.append(tstim) return tstim @@ -458,7 +458,7 @@ def add_alpha_synapse( segx=0.5, ) -> HocObjectType: """Add an AlphaSynapse NEURON point process stimulus to the cell.""" - syn = bluecellulab.neuron.h.AlphaSynapse(segx, sec=section) + syn = neuron.h.AlphaSynapse(segx, sec=section) syn.onset = onset syn.tau = tau syn.gmax = gmax diff --git a/bluecellulab/cell/plotting.py b/bluecellulab/cell/plotting.py index e863d334..bfddea9a 100644 --- a/bluecellulab/cell/plotting.py +++ b/bluecellulab/cell/plotting.py @@ -15,6 +15,8 @@ from __future__ import annotations +import neuron + import bluecellulab @@ -76,26 +78,27 @@ def add_dendrogram( def init_callbacks(self): """Initialize the callback function (if necessary).""" if not self.delayed_weights.empty(): - self.fih_weights = bluecellulab.neuron.h.FInitializeHandler( + self.fih_weights = neuron.h.FInitializeHandler( 1, self.weights_callback) if self.plot_callback_necessary: - self.fih_plots = bluecellulab.neuron.h.FInitializeHandler(1, self.plot_callback) + self.fih_plots = neuron.h.FInitializeHandler(1, self.plot_callback) def weights_callback(self): """Callback function that updates the delayed weights, when a certain delay has been reached.""" while not self.delayed_weights.empty() and \ - abs(self.delayed_weights.queue[0][0] - bluecellulab.neuron.h.t) < \ - bluecellulab.neuron.h.dt: + abs(self.delayed_weights.queue[0][0] - neuron.h.t) < \ + neuron.h.dt: (_, (sid, weight)) = self.delayed_weights.get() if sid in self.connections: if self.connections[sid].post_netcon is not None: self.connections[sid].post_netcon.weight[0] = weight if not self.delayed_weights.empty(): - bluecellulab.neuron.h.cvode.event(self.delayed_weights.queue[0][0], - self.weights_callback) + neuron.h.cvode.event( + self.delayed_weights.queue[0][0], self.weights_callback + ) def plot_callback(self): """Update all the windows.""" @@ -104,5 +107,5 @@ def plot_callback(self): for cell_dendrogram in self.cell_dendrograms: cell_dendrogram.redraw() - bluecellulab.neuron.h.cvode.event( - bluecellulab.neuron.h.t + 1, self.plot_callback) + neuron.h.cvode.event( + neuron.h.t + 1, self.plot_callback) diff --git a/bluecellulab/cell/section_distance.py b/bluecellulab/cell/section_distance.py index 9babb001..3885bfb1 100644 --- a/bluecellulab/cell/section_distance.py +++ b/bluecellulab/cell/section_distance.py @@ -13,10 +13,9 @@ # limitations under the License. """Distance computing functionality between Neuron sections.""" +import neuron import numpy as np -import bluecellulab - class EuclideanSectionDistance: """Calculate euclidian distance between positions on two sections. @@ -72,7 +71,7 @@ def __call__( def grindaway(hsection): """Grindaway.""" # get the data for the section - n_segments = int(bluecellulab.neuron.h.n3d(sec=hsection)) + n_segments = int(neuron.h.n3d(sec=hsection)) n_comps = hsection.nseg xs = np.zeros(n_segments) @@ -80,10 +79,10 @@ def grindaway(hsection): zs = np.zeros(n_segments) lengths = np.zeros(n_segments) for index in range(n_segments): - xs[index] = bluecellulab.neuron.h.x3d(index, sec=hsection) - ys[index] = bluecellulab.neuron.h.y3d(index, sec=hsection) - zs[index] = bluecellulab.neuron.h.z3d(index, sec=hsection) - lengths[index] = bluecellulab.neuron.h.arc3d(index, sec=hsection) + xs[index] = neuron.h.x3d(index, sec=hsection) + ys[index] = neuron.h.y3d(index, sec=hsection) + zs[index] = neuron.h.z3d(index, sec=hsection) + lengths[index] = neuron.h.arc3d(index, sec=hsection) # to use Vector class's .interpolate() # must first scale the independent variable diff --git a/bluecellulab/cell/stimuli_generator.py b/bluecellulab/cell/stimuli_generator.py index f48cddf5..de2ac6ac 100644 --- a/bluecellulab/cell/stimuli_generator.py +++ b/bluecellulab/cell/stimuli_generator.py @@ -14,10 +14,10 @@ """Generates stimuli to be injected into cells.""" import math - import logging -import bluecellulab +import neuron + from bluecellulab.cell.random import gamma logger = logging.getLogger(__name__) @@ -39,9 +39,9 @@ def gen_shotnoise_signal(tau_D, tau_R, rate, amp_mean, amp_var, """ if rng is None: logger.info("Using a default RNG for shot noise generation") - rng = bluecellulab.neuron.h.Random() # Creates a default RNG + rng = neuron.h.Random() # Creates a default RNG - tvec = bluecellulab.neuron.h.Vector() + tvec = neuron.h.Vector() tvec.indgen(0, duration, dt) # time vector ntstep = len(tvec) # total number of timesteps @@ -51,22 +51,22 @@ def gen_shotnoise_signal(tau_D, tau_R, rate, amp_mean, amp_var, exp_scale = 1 / rate # scale parameter of exponential distribution of time intervals rng.negexp(exp_scale) - iei = bluecellulab.neuron.h.Vector(napprox) + iei = neuron.h.Vector(napprox) iei.setrand(rng) # generate inter-event intervals - ev = bluecellulab.neuron.h.Vector() + ev = neuron.h.Vector() ev.integral(iei, 1).mul(1000) # generate events in ms # add events if last event falls short of duration while ev[-1] < duration: - iei_new = bluecellulab.neuron.h.Vector(100) # generate 100 new inter-event intervals + iei_new = neuron.h.Vector(100) # generate 100 new inter-event intervals iei_new.setrand(rng) # here rng is still negexp - ev_new = bluecellulab.neuron.h.Vector() + ev_new = neuron.h.Vector() ev_new.integral(iei_new, 1).mul(1000).add(ev[-1]) # generate new shifted events in ms ev.append(ev_new) # append new events ev.where("<", duration) # remove events exceeding duration ev.div(dt) # divide events by timestep - nev = bluecellulab.neuron.h.Vector([round(x) for x in ev]) # round to integer timestep index + nev = neuron.h.Vector([round(x) for x in ev]) # round to integer timestep index nev.where("<", ntstep) # remove events exceeding number of timesteps sign = 1 @@ -80,7 +80,7 @@ def gen_shotnoise_signal(tau_D, tau_R, rate, amp_mean, amp_var, # sample gamma-distributed amplitudes amp = gamma(rng, gamma_shape, gamma_scale, len(nev)) - E = bluecellulab.neuron.h.Vector(ntstep, 0) # full signal + E = neuron.h.Vector(ntstep, 0) # full signal for n, A in zip(nev, amp): E.x[int(n)] += sign * A # add impulses, may overlap due to rounding to timestep @@ -95,8 +95,8 @@ def gen_shotnoise_signal(tau_D, tau_R, rate, amp_mean, amp_var, t_peak = math.log(R / D) / (R - D) A = (a / b - 1) / (a ** t_peak - b ** t_peak) - P = bluecellulab.neuron.h.Vector(ntstep, 0) - B = bluecellulab.neuron.h.Vector(ntstep, 0) + P = neuron.h.Vector(ntstep, 0) + B = neuron.h.Vector(ntstep, 0) # composite autoregressive process with exact solution # P[n] = b * (a ^ n - b ^ n) / (a - b) @@ -143,15 +143,15 @@ def gen_ornstein_uhlenbeck(tau, sigma, mean, duration, dt=0.25, rng=None): if rng is None: logger.info("Using a default RNG for Ornstein-Uhlenbeck process") - rng = bluecellulab.neuron.h.Random() # Creates a default RNG + rng = neuron.h.Random() # Creates a default RNG - tvec = bluecellulab.neuron.h.Vector() + tvec = neuron.h.Vector() tvec.indgen(0, duration, dt) # time vector ntstep = len(tvec) # total number of timesteps - svec = bluecellulab.neuron.h.Vector(ntstep, 0) # stim vector + svec = neuron.h.Vector(ntstep, 0) # stim vector - noise = bluecellulab.neuron.h.Vector(ntstep) # Gaussian noise + noise = neuron.h.Vector(ntstep) # Gaussian noise rng.normal(0.0, 1.0) noise.setrand(rng) # generate Gaussian noise diff --git a/bluecellulab/cell/template.py b/bluecellulab/cell/template.py index 3bc2a4f8..8706bc6f 100644 --- a/bluecellulab/cell/template.py +++ b/bluecellulab/cell/template.py @@ -22,8 +22,8 @@ import string from typing import Optional -import bluecellulab -from bluecellulab import neuron +import neuron + from bluecellulab.circuit import EmodelProperties from bluecellulab.exceptions import BluecellulabError from bluecellulab.type_aliases import HocObjectType @@ -132,7 +132,7 @@ def load(self, template_filename: str) -> str: template_content, ) - bluecellulab.neuron.h(template_content) + neuron.h(template_content) return template_name diff --git a/bluecellulab/circuit/config/sections.py b/bluecellulab/circuit/config/sections.py index 4ceb8dd9..c85283f0 100644 --- a/bluecellulab/circuit/config/sections.py +++ b/bluecellulab/circuit/config/sections.py @@ -20,6 +20,7 @@ from pydantic.dataclasses import dataclass from libsonata._libsonata import Conditions as LibSonataConditions +import neuron import bluecellulab @@ -138,7 +139,7 @@ class ConnectionOverrides: @classmethod def validate_mod_override(cls, value): """Make sure the mod file to override is present.""" - if isinstance(value, str) and not hasattr(bluecellulab.neuron.h, value): + if isinstance(value, str) and not hasattr(neuron.h, value): raise bluecellulab.ConfigError( f"Mod file for {value} is not found.") return value diff --git a/bluecellulab/connection.py b/bluecellulab/connection.py index 8d092f0c..644b2ec3 100644 --- a/bluecellulab/connection.py +++ b/bluecellulab/connection.py @@ -15,9 +15,9 @@ from typing import Optional +import neuron import numpy as np -import bluecellulab from bluecellulab.cell.core import Cell from bluecellulab.circuit import SynapseProperty @@ -57,10 +57,10 @@ def __init__( "a negative time, this is not supported by " "NEURON's Vecstim: %s" % str(self.pre_spiketrain)) - t_vec = bluecellulab.neuron.h.Vector(self.pre_spiketrain) - vecstim = bluecellulab.neuron.h.VecStim() + t_vec = neuron.h.Vector(self.pre_spiketrain) + vecstim = neuron.h.VecStim() vecstim.play(t_vec, stim_dt) - self.post_netcon = bluecellulab.neuron.h.NetCon( + self.post_netcon = neuron.h.NetCon( vecstim, self.post_synapse.hsynapse, spike_threshold, self.post_netcon_delay, @@ -68,8 +68,8 @@ def __init__( # set netcon type nc_param_name = 'nc_type_param_{}'.format( self.post_synapse.hsynapse).split('[')[0] - if hasattr(bluecellulab.neuron.h, nc_param_name): - nc_type_param = int(getattr(bluecellulab.neuron.h, nc_param_name)) + if hasattr(neuron.h, nc_param_name): + nc_type_param = int(getattr(neuron.h, nc_param_name)) self.post_netcon.weight[nc_type_param] = 2 # NC_REPLAY self.persistent.append(t_vec) self.persistent.append(vecstim) @@ -84,8 +84,8 @@ def __init__( # set netcon type nc_param_name = 'nc_type_param_{}'.format( self.post_synapse.hsynapse).split('[')[0] - if hasattr(bluecellulab.neuron.h, nc_param_name): - nc_type_param = int(getattr(bluecellulab.neuron.h, nc_param_name)) + if hasattr(neuron.h, nc_param_name): + nc_type_param = int(getattr(neuron.h, nc_param_name)) self.post_netcon.weight[nc_type_param] = 0 # NC_PRESYN @property diff --git a/bluecellulab/psection.py b/bluecellulab/psection.py index 0032b92b..8ad8db30 100644 --- a/bluecellulab/psection.py +++ b/bluecellulab/psection.py @@ -13,8 +13,9 @@ # limitations under the License. """Represents a python version of NEURON Section (for drawing).""" +import neuron + import bluecellulab -from bluecellulab import neuron class PSection: diff --git a/bluecellulab/psegment.py b/bluecellulab/psegment.py index 132a9054..0a1f5a34 100644 --- a/bluecellulab/psegment.py +++ b/bluecellulab/psegment.py @@ -13,7 +13,8 @@ # limitations under the License. """Represent a NEURON Segment in Python (for drawing).""" -import bluecellulab +import neuron + from bluecellulab.neuron_interpreter import eval_neuron type_colormap = {'apical': 'm', 'basal': 'r', 'somatic': 'k', 'axonal': 'b', 'myelin': 'g'} @@ -72,14 +73,15 @@ def redraw(self): def getVariableValue(self, variable): """Get a variable value in a segment.""" - if variable == "v" or \ - bluecellulab.neuron.h.execute1("{%s.%s(%f)}" % - (bluecellulab.neuron.h.secname( - sec=self.parentsection.hsection), - variable, - self.hsegment.x), - 0): + if variable == "v" or neuron.h.execute1( + "{%s.%s(%f)}" + % ( + neuron.h.secname(sec=self.parentsection.hsection), + variable, + self.hsegment.x, + ), + 0, + ): return eval_neuron(f"self.hsegment.{variable}", self=self) - else: return None diff --git a/bluecellulab/rngsettings.py b/bluecellulab/rngsettings.py index 3baffcf9..ccfb90b1 100644 --- a/bluecellulab/rngsettings.py +++ b/bluecellulab/rngsettings.py @@ -17,7 +17,7 @@ from typing import Optional -import bluecellulab +import neuron from bluecellulab import Singleton from bluecellulab.circuit.circuit_access import CircuitAccess from bluecellulab.exceptions import UndefinedRNGException @@ -57,23 +57,23 @@ def __init__( self.base_seed = circuit_access.config.base_seed if circuit_access else 0 else: self.base_seed = base_seed - bluecellulab.neuron.h.globalSeed = self.base_seed + neuron.h.globalSeed = self.base_seed if self._mode == 'Random123': - rng = bluecellulab.neuron.h.Random() + rng = neuron.h.Random() rng.Random123_globalindex(self.base_seed) self.synapse_seed = circuit_access.config.synapse_seed if circuit_access else 0 - bluecellulab.neuron.h.synapseSeed = self.synapse_seed + neuron.h.synapseSeed = self.synapse_seed self.ionchannel_seed = circuit_access.config.ionchannel_seed if circuit_access else 0 - bluecellulab.neuron.h.ionchannelSeed = self.ionchannel_seed + neuron.h.ionchannelSeed = self.ionchannel_seed self.stimulus_seed = circuit_access.config.stimulus_seed if circuit_access else 0 - bluecellulab.neuron.h.stimulusSeed = self.stimulus_seed + neuron.h.stimulusSeed = self.stimulus_seed self.minis_seed = circuit_access.config.minis_seed if circuit_access else 0 - bluecellulab.neuron.h.minisSeed = self.minis_seed + neuron.h.minisSeed = self.minis_seed @property def mode(self): @@ -90,7 +90,7 @@ def mode(self, new_val): % (self.mode, list(options.keys())) ) else: - bluecellulab.neuron.h.rngMode = options[new_val] + neuron.h.rngMode = options[new_val] self._mode = new_val def __repr__(self) -> str: diff --git a/bluecellulab/simulation/neuron_globals.py b/bluecellulab/simulation/neuron_globals.py index b26f637f..e557f7eb 100644 --- a/bluecellulab/simulation/neuron_globals.py +++ b/bluecellulab/simulation/neuron_globals.py @@ -13,7 +13,7 @@ # limitations under the License. """Module that handles the global NEURON parameters.""" -import bluecellulab +import neuron from bluecellulab.circuit.config.sections import Conditions, MechanismConditions from bluecellulab.exceptions import error_context @@ -22,11 +22,11 @@ def set_global_condition_parameters(condition_parameters: Conditions) -> None: """Sets the global condition parameters in NEURON objects if GluSynapse is available.""" if condition_parameters.extracellular_calcium is not None and hasattr( - bluecellulab.neuron.h, "cao_CR_GluSynapse" + neuron.h, "cao_CR_GluSynapse" ): cao_cr_glusynapse = condition_parameters.extracellular_calcium with error_context("mechanism/s for cao_CR_GluSynapse need to be compiled"): - bluecellulab.neuron.h.cao_CR_GluSynapse = cao_cr_glusynapse + neuron.h.cao_CR_GluSynapse = cao_cr_glusynapse mechanism_conditions = condition_parameters.mech_conditions if mechanism_conditions is not None: @@ -38,30 +38,30 @@ def set_init_depleted_values(mech_conditions: MechanismConditions) -> None: """Set the init_depleted values in NEURON.""" with error_context("mechanism/s for init_depleted need to be compiled"): if mech_conditions.glusynapse and mech_conditions.glusynapse.init_depleted is not None: - bluecellulab.neuron.h.init_depleted_GluSynapse = mech_conditions.glusynapse.init_depleted + neuron.h.init_depleted_GluSynapse = mech_conditions.glusynapse.init_depleted if mech_conditions.ampanmda and mech_conditions.ampanmda.init_depleted is not None: - bluecellulab.neuron.h.init_depleted_ProbAMPANMDA_EMS = mech_conditions.ampanmda.init_depleted + neuron.h.init_depleted_ProbAMPANMDA_EMS = mech_conditions.ampanmda.init_depleted if mech_conditions.gabaab and mech_conditions.gabaab.init_depleted is not None: - bluecellulab.neuron.h.init_depleted_ProbGABAAB_EMS = mech_conditions.gabaab.init_depleted + neuron.h.init_depleted_ProbGABAAB_EMS = mech_conditions.gabaab.init_depleted def set_minis_single_vesicle_values(mech_conditions: MechanismConditions) -> None: """Set the minis_single_vesicle values in NEURON.""" with error_context("mechanism/s for minis_single_vesicle need to be compiled"): if mech_conditions.ampanmda and mech_conditions.ampanmda.minis_single_vesicle is not None: - bluecellulab.neuron.h.minis_single_vesicle_ProbAMPANMDA_EMS = ( + neuron.h.minis_single_vesicle_ProbAMPANMDA_EMS = ( mech_conditions.ampanmda.minis_single_vesicle ) if mech_conditions.gabaab and mech_conditions.gabaab.minis_single_vesicle is not None: - bluecellulab.neuron.h.minis_single_vesicle_ProbGABAAB_EMS = ( + neuron.h.minis_single_vesicle_ProbGABAAB_EMS = ( mech_conditions.gabaab.minis_single_vesicle ) if mech_conditions.glusynapse and mech_conditions.glusynapse.minis_single_vesicle is not None: - bluecellulab.neuron.h.minis_single_vesicle_GluSynapse = ( + neuron.h.minis_single_vesicle_GluSynapse = ( mech_conditions.glusynapse.minis_single_vesicle ) def set_tstop_value(tstop: float) -> None: """Set the tstop value required by Tstim noise stimuli.""" - bluecellulab.neuron.h.tstop = tstop + neuron.h.tstop = tstop diff --git a/bluecellulab/simulation/simulation.py b/bluecellulab/simulation/simulation.py index e6e69be1..122ded34 100644 --- a/bluecellulab/simulation/simulation.py +++ b/bluecellulab/simulation/simulation.py @@ -13,14 +13,14 @@ # limitations under the License. """Simulation class of bluecellulab.""" - +import contextlib import sys from typing import Optional import logging +import neuron + import bluecellulab -import contextlib -from bluecellulab.importer import neuron logger = logging.getLogger(__name__) @@ -157,7 +157,7 @@ def run( if self.pc is not None: for cell in self.cells: - self.pc.prcellstate(cell.cell_id.id, f"bluecellulab_t={bluecellulab.neuron.h.t}") + self.pc.prcellstate(cell.cell_id.id, f"bluecellulab_t={neuron.h.t}") try: neuron.h.continuerun(neuron.h.tstop) diff --git a/bluecellulab/ssim.py b/bluecellulab/ssim.py index 240429b5..25fd0054 100644 --- a/bluecellulab/ssim.py +++ b/bluecellulab/ssim.py @@ -21,6 +21,7 @@ from typing import Optional import logging +import neuron import numpy as np import pandas as pd from pydantic.types import NonNegativeInt @@ -89,7 +90,7 @@ def __init__( self.simulation_access = BluepySimulationAccess(simulation_config) SimulationValidator(self.circuit_access).validate() - self.pc = bluecellulab.neuron.h.ParallelContext() if print_cellstate else None + self.pc = neuron.h.ParallelContext() if print_cellstate else None self.rng_settings = bluecellulab.RNGSettings( rng_mode, diff --git a/bluecellulab/synapse/synapse_types.py b/bluecellulab/synapse/synapse_types.py index f8e4eb18..75c700b1 100644 --- a/bluecellulab/synapse/synapse_types.py +++ b/bluecellulab/synapse/synapse_types.py @@ -15,10 +15,11 @@ from __future__ import annotations from typing import Any, NamedTuple, Optional -import pandas as pd import logging -import bluecellulab +import neuron +import pandas as pd + from bluecellulab.circuit import SynapseProperty from bluecellulab.circuit.node_id import CellId from bluecellulab.rngsettings import RNGSettings @@ -138,7 +139,7 @@ def apply_hoc_configuration(self, hoc_configure_params: list[str]) -> None: cmd = cmd.replace('%s', '\n%(syn)s') hoc_cmd = cmd % {'syn': self.hsynapse.hname()} # type: ignore hoc_cmd = '{%s}' % hoc_cmd - bluecellulab.neuron.h(hoc_cmd) + neuron.h(hoc_cmd) def _set_gabaab_ampanmda_rng(self) -> None: """Setup the RNG for the gabaab and ampanmd helpers. @@ -156,7 +157,7 @@ def _set_gabaab_ampanmda_rng(self) -> None: self.randseed2, self.randseed3) else: - rndd = bluecellulab.neuron.h.Random() + rndd = neuron.h.Random() if self.rng_settings.mode == "Compatibility": self.randseed1 = self.syn_id.sid * 100000 + 100 self.randseed2 = self.post_cell_id.id + \ @@ -252,7 +253,7 @@ def use_glusynapse_helper(self) -> None: """ self.mech_name = 'GluSynapse' - self.hsynapse = bluecellulab.neuron.h.GluSynapse( + self.hsynapse = neuron.h.GluSynapse( self.hoc_args.location, sec=self.hoc_args.section ) @@ -271,7 +272,7 @@ def use_glusynapse_helper(self) -> None: self.hsynapse.gmax_d_AMPA = self.syn_description["gmax_d_AMPA"] self.hsynapse.gmax_p_AMPA = self.syn_description["gmax_p_AMPA"] - if self.hsynapse.rho0_GB > bluecellulab.neuron.h.rho_star_GB_GluSynapse: + if self.hsynapse.rho0_GB > neuron.h.rho_star_GB_GluSynapse: self.hsynapse.gmax0_AMPA = self.hsynapse.gmax_p_AMPA self.hsynapse.Use = self.hsynapse.Use_p else: @@ -321,13 +322,13 @@ def use_gabaab_helper(self, randomize_gaba_risetime: bool) -> None: """ self.mech_name = 'ProbGABAAB_EMS' - self.hsynapse = bluecellulab.neuron.h.ProbGABAAB_EMS( + self.hsynapse = neuron.h.ProbGABAAB_EMS( self.hoc_args.location, sec=self.hoc_args.section ) if randomize_gaba_risetime is True: - rng = bluecellulab.neuron.h.Random() + rng = neuron.h.Random() if self.rng_settings.mode == "Compatibility": rng.MCellRan4( self.syn_id.sid * 100000 + 100, @@ -397,7 +398,7 @@ def use_ampanmda_helper(self) -> None: """ self.mech_name = 'ProbAMPANMDA_EMS' - self.hsynapse = bluecellulab.neuron.h.ProbAMPANMDA_EMS( + self.hsynapse = neuron.h.ProbAMPANMDA_EMS( self.hoc_args.location, sec=self.hoc_args.section, ) diff --git a/bluecellulab/tools.py b/bluecellulab/tools.py index ee4ddd1f..ce49c53e 100644 --- a/bluecellulab/tools.py +++ b/bluecellulab/tools.py @@ -26,6 +26,7 @@ from typing import Any, Optional, Tuple import logging +import neuron import numpy as np import bluecellulab @@ -170,7 +171,7 @@ def holding_current_subprocess(v_hold, enable_ttx, cell_kwargs): if enable_ttx: cell.enable_ttx() - vclamp = bluecellulab.neuron.h.SEClamp(0.5, sec=cell.soma) + vclamp = neuron.h.SEClamp(0.5, sec=cell.soma) vclamp.rs = 0.01 vclamp.dur1 = 2000 vclamp.amp1 = v_hold @@ -666,7 +667,7 @@ def __exit__(self, *args): def check_empty_topology() -> bool: """Return true if NEURON simulator topology command is empty.""" with get_stdout() as stdout: - bluecellulab.neuron.h.topology() + neuron.h.topology() return stdout == ['', ''] diff --git a/tests/test_ballstick.py b/tests/test_ballstick.py index d5fbd8a8..e74cb4ef 100644 --- a/tests/test_ballstick.py +++ b/tests/test_ballstick.py @@ -6,6 +6,7 @@ import os +import neuron import numpy as np import bluecellulab @@ -37,13 +38,13 @@ def __init__(self): cell = bluecellulab.Cell(self.templatefile, self.morphfile) self.soma_L, self.soma_D, self.soma_A = \ - cell.soma.L, cell.soma.diam, bluecellulab.neuron.h.area( + cell.soma.L, cell.soma.diam, neuron.h.area( 0.5, sec=cell.soma) # print 'SOMA L=%f, diam=%f,surf=%f' % (self.soma_L, self.soma_D, # self.soma_A) self.dend0_L, self.dend0_D, self.dend0_A = cell.basal[0].L, cell.basal[ - 0].diam, bluecellulab.neuron.h.area( + 0].diam, neuron.h.area( 0.5, sec=cell.basal[0]) self.dend0_NSEG = cell.basal[0].nseg @@ -62,7 +63,7 @@ def __init__(self): def run_pyneuron(soma_l, soma_d, params): """Run ballstick with PyNeuron""" - soma = bluecellulab.neuron.h.Section() + soma = neuron.h.Section() soma.L = soma_l soma.diam = soma_d soma.nseg = 1 @@ -73,7 +74,7 @@ def run_pyneuron(soma_l, soma_d, params): soma(0.5).e_pas = params.EL soma(0.5).g_pas = 1.0 / params.RM - dend = bluecellulab.neuron.h.Section() + dend = neuron.h.Section() dend.L = params.dend0_L dend.diam = params.dend0_D dend.nseg = params.dend0_NSEG @@ -86,26 +87,26 @@ def run_pyneuron(soma_l, soma_d, params): seg.g_pas = 1.0 / params.RM dend.connect(soma, 0.5, 0) # mid-soma to begin-den - syn = bluecellulab.neuron.h.ExpSyn(params.SYN_LOC, sec=dend) + syn = neuron.h.ExpSyn(params.SYN_LOC, sec=dend) syn.tau = params.SYN_DECAY syn.e = params.SYN_E - ns = bluecellulab.neuron.h.NetStim() + ns = neuron.h.NetStim() ns.interval = 100000 ns.number = 1 ns.start = params.SYN_ACTIVATION_T ns.noise = 0 - nc = bluecellulab.neuron.h.NetCon(ns, syn, 0, params.SYN_DELAY, params.SYN_G) + nc = neuron.h.NetCon(ns, syn, 0, params.SYN_DELAY, params.SYN_G) - v_vec = bluecellulab.neuron.h.Vector() - t_vec = bluecellulab.neuron.h.Vector() + v_vec = neuron.h.Vector() + t_vec = neuron.h.Vector() v_vec.record(soma(0.5)._ref_v) - t_vec.record(bluecellulab.neuron.h._ref_t) + t_vec.record(neuron.h._ref_t) - bluecellulab.neuron.h.finitialize(params.V_INIT) - bluecellulab.neuron.h.dt = params.DT - bluecellulab.neuron.run(params.T_STOP) + neuron.h.finitialize(params.V_INIT) + neuron.h.dt = params.DT + neuron.run(params.T_STOP) voltage = np.array(v_vec) time = np.array(t_vec) @@ -120,28 +121,28 @@ def run_pyneuron(soma_l, soma_d, params): def run_pyneuron_with_template(params): """Run ballstick with PyNeuron and template""" - bluecellulab.neuron.h.load_file(params.templatefile) - cell = bluecellulab.neuron.h.ballstick_cell(0, params.morphfile) + neuron.h.load_file(params.templatefile) + cell = neuron.h.ballstick_cell(0, params.morphfile) basal = cell.getCell().dend[0] soma = cell.getCell().soma[0] - syn = bluecellulab.neuron.h.ExpSyn(params.SYN_LOC, sec=basal) + syn = neuron.h.ExpSyn(params.SYN_LOC, sec=basal) syn.tau = params.SYN_DECAY syn.e = params.SYN_E - ns = bluecellulab.neuron.h.NetStim() + ns = neuron.h.NetStim() ns.interval = 100000 ns.number = 1 ns.start = params.SYN_ACTIVATION_T ns.noise = 0 - nc = bluecellulab.neuron.h.NetCon(ns, syn, 0, params.SYN_DELAY, params.SYN_G) + nc = neuron.h.NetCon(ns, syn, 0, params.SYN_DELAY, params.SYN_G) - v_vec = bluecellulab.neuron.h.Vector() - t_vec = bluecellulab.neuron.h.Vector() + v_vec = neuron.h.Vector() + t_vec = neuron.h.Vector() v_vec.record(soma(0.5)._ref_v) - t_vec.record(bluecellulab.neuron.h._ref_t) + t_vec.record(neuron.h._ref_t) - bluecellulab.neuron.h.finitialize(params.V_INIT) - bluecellulab.neuron.h.dt = params.DT - bluecellulab.neuron.run(params.T_STOP) + neuron.h.finitialize(params.V_INIT) + neuron.h.dt = params.DT + neuron.run(params.T_STOP) voltage = np.array(v_vec) time = np.array(t_vec) @@ -159,15 +160,15 @@ def run_pyneuron_with_template(params): def run_bluecellulab(params): """Run ballstick with bluecellulab""" cell = bluecellulab.Cell(params.templatefile, params.morphfile) - syn = bluecellulab.neuron.h.ExpSyn(params.SYN_LOC, sec=cell.basal[0]) + syn = neuron.h.ExpSyn(params.SYN_LOC, sec=cell.basal[0]) syn.tau = params.SYN_DECAY syn.e = params.SYN_E - ns = bluecellulab.neuron.h.NetStim() + ns = neuron.h.NetStim() ns.interval = 100000 ns.number = 1 ns.start = params.SYN_ACTIVATION_T ns.noise = 0 - nc = bluecellulab.neuron.h.NetCon(ns, syn, 0, params.SYN_DELAY, params.SYN_G) + nc = neuron.h.NetCon(ns, syn, 0, params.SYN_DELAY, params.SYN_G) sim = bluecellulab.Simulation() sim.add_cell(cell) @@ -278,10 +279,10 @@ def test_ballstick_load(): cell = bluecellulab.Cell(params.templatefile, params.morphfile) assert abs(cell.soma.L - 19.6) < 0.001 assert abs(cell.soma.diam - 10.229) < 0.001 - assert abs(bluecellulab.neuron.h.area(0.5, sec=cell.soma) - 872.567) < 0.001 + assert abs(neuron.h.area(0.5, sec=cell.soma) - 872.567) < 0.001 assert abs(cell.basal[0].L - 200.0) < 0.001 assert abs(cell.basal[0].diam - 3.0) < 0.001 - assert abs(bluecellulab.neuron.h.area(0.5, sec=cell.basal[0]) - 9.424) < 0.001 + assert abs(neuron.h.area(0.5, sec=cell.basal[0]) - 9.424) < 0.001 del cell diff --git a/tests/test_cell/test_core.py b/tests/test_cell/test_core.py index 4da114b4..b111d41d 100644 --- a/tests/test_cell/test_core.py +++ b/tests/test_cell/test_core.py @@ -4,12 +4,13 @@ import random import warnings from pathlib import Path -from bluecellulab.circuit.circuit_access import EmodelProperties +import neuron import numpy as np import pytest import bluecellulab +from bluecellulab.circuit.circuit_access import EmodelProperties from bluecellulab.cell.template import NeuronTemplate, shorten_and_hash_string from bluecellulab.exceptions import BluecellulabError from bluecellulab.ssim import SSim @@ -71,8 +72,8 @@ def teardown_method(self): def test_fields(self): """Cell: Test the fields of a Cell object""" - assert isinstance(self.cell.soma, bluecellulab.neuron.nrn.Section) - assert isinstance(self.cell.axonal[0], bluecellulab.neuron.nrn.Section) + assert isinstance(self.cell.soma, neuron.nrn.Section) + assert isinstance(self.cell.axonal[0], neuron.nrn.Section) assert math.fabs(self.cell.threshold - 0.184062) < 0.00001 assert math.fabs(self.cell.hypamp - -0.070557) < 0.00001 # Lowered precision because of commit @@ -88,7 +89,7 @@ def test_fields(self): def test_get_hsection(self): """Cell: Test cell.get_hsection""" assert isinstance( - self.cell.get_hsection(0), bluecellulab.neuron.nrn.Section) + self.cell.get_hsection(0), neuron.nrn.Section) def test_add_recording(self): """Cell: Test cell.add_recording""" @@ -168,28 +169,14 @@ def test_euclid_section_distance(self): location1=location1, location2=location2, projection='xyz') - - x1 = bluecellulab.neuron.h.x3d(0, - sec=hsection1) - y1 = bluecellulab.neuron.h.y3d(0, - sec=hsection1) - z1 = bluecellulab.neuron.h.z3d(0, - sec=hsection1) - x2 = bluecellulab.neuron.h.x3d( - bluecellulab.neuron.h.n3d( - sec=hsection2) - 1, - sec=hsection2) - y2 = bluecellulab.neuron.h.y3d( - bluecellulab.neuron.h.n3d( - sec=hsection2) - 1, - sec=hsection2) - z2 = bluecellulab.neuron.h.z3d( - bluecellulab.neuron.h.n3d( - sec=hsection2) - 1, - sec=hsection2) - import numpy as np - distance_hand = np.sqrt((x1 - x2) ** 2 - + (y1 - y2) ** 2 + (z1 - z2) ** 2) + x1 = neuron.h.x3d(0, sec=hsection1) + y1 = neuron.h.y3d(0, sec=hsection1) + z1 = neuron.h.z3d(0, sec=hsection1) + x2 = neuron.h.x3d(neuron.h.n3d(sec=hsection2) - 1, sec=hsection2) + y2 = neuron.h.y3d(neuron.h.n3d(sec=hsection2) - 1, sec=hsection2) + z2 = neuron.h.z3d(neuron.h.n3d(sec=hsection2) - 1, sec=hsection2) + + distance_hand = np.sqrt((x1 - x2) ** 2 + (y1 - y2) ** 2 + (z1 - z2) ** 2) assert distance_euclid == distance_hand diff --git a/tests/test_cell/test_injector.py b/tests/test_cell/test_injector.py index 63da23aa..1bb8ccac 100644 --- a/tests/test_cell/test_injector.py +++ b/tests/test_cell/test_injector.py @@ -3,6 +3,7 @@ import math from pathlib import Path +import neuron import numpy as np from pydantic import ValidationError import pytest @@ -297,11 +298,11 @@ def test_add_ornstein_uhlenbeck(self): def test_inject_current_clamp_signal(self): """Unit test for inject_current_clamp_signal.""" - tvec = bluecellulab.neuron.h.Vector(np.arange(10)) - svec = bluecellulab.neuron.h.Vector(np.random.normal(0, 0.1, 10)) + tvec = neuron.h.Vector(np.arange(10)) + svec = neuron.h.Vector(np.random.normal(0, 0.1, 10)) - original_tvec = bluecellulab.neuron.h.Vector().copy(tvec) - original_svec = bluecellulab.neuron.h.Vector().copy(svec) + original_tvec = neuron.h.Vector().copy(tvec) + original_svec = neuron.h.Vector().copy(svec) soma = self.cell.soma segx = 0.5 @@ -337,11 +338,11 @@ def test_inject_current_clamp_via_shotnoise_signal(self): def test_inject_dynamic_clamp_signal(self): """Unit test for inject_dynamic_clamp_signal.""" - tvec = bluecellulab.neuron.h.Vector(np.arange(10)) - svec = bluecellulab.neuron.h.Vector(np.random.normal(0, 0.1, 10)) + tvec = neuron.h.Vector(np.arange(10)) + svec = neuron.h.Vector(np.random.normal(0, 0.1, 10)) - original_tvec = bluecellulab.neuron.h.Vector().copy(tvec) - original_svec = bluecellulab.neuron.h.Vector().copy(svec) + original_tvec = neuron.h.Vector().copy(tvec) + original_svec = neuron.h.Vector().copy(svec) soma = self.cell.soma segx = 0.5 @@ -477,7 +478,7 @@ def test_add_alpha_synapse(self): section = self.cell.cell.getCell().dend[15] syn = self.cell.add_alpha_synapse(onset, tau, gmax, e, section) - current_vector = bluecellulab.neuron.h.Vector() + current_vector = neuron.h.Vector() current_vector.record(syn._ref_i) sim = bluecellulab.Simulation() sim.add_cell(self.cell) diff --git a/tests/test_cell/test_random.py b/tests/test_cell/test_random.py index d6534f89..49992ceb 100644 --- a/tests/test_cell/test_random.py +++ b/tests/test_cell/test_random.py @@ -1,7 +1,7 @@ """Unit tests for cell/random module.""" +import neuron from pytest import approx -from bluecellulab import neuron from bluecellulab.cell.random import gamma diff --git a/tests/test_cell/test_stimuli_generator.py b/tests/test_cell/test_stimuli_generator.py index d91e408a..316b2119 100644 --- a/tests/test_cell/test_stimuli_generator.py +++ b/tests/test_cell/test_stimuli_generator.py @@ -2,7 +2,7 @@ from pytest import approx -import bluecellulab +import neuron from bluecellulab.cell.stimuli_generator import ( gen_shotnoise_signal, get_relative_shotnoise_params, @@ -12,7 +12,7 @@ def test_gen_shotnoise_signal(): """Test if the shotnoise signal is generated correctly.""" - rng = bluecellulab.neuron.h.Random() + rng = neuron.h.Random() rng.Random123(1, 2, 3) time_vec, stim_vec = gen_shotnoise_signal(4.0, 0.4, 2E3, 40E-3, 16E-4, 2, rng=rng) @@ -37,7 +37,7 @@ def test_get_relative_shotnoise_params(): def test_gen_ornstein_uhlenbeck(): """Test if the ornstein uhlenbeck signal is generated correctly.""" - rng = bluecellulab.neuron.h.Random() + rng = neuron.h.Random() rng.Random123(1, 2, 3) time_vec, stim_vec = gen_ornstein_uhlenbeck(2.8, 0.0042, 0.029, 2, rng=rng) assert list(time_vec) == approx([0, 0.25, 0.5, 0.75, 1.0, 1.25, 1.5, diff --git a/tests/test_neuron_interpreter.py b/tests/test_neuron_interpreter.py index 0ec2b6c4..a5a21407 100644 --- a/tests/test_neuron_interpreter.py +++ b/tests/test_neuron_interpreter.py @@ -2,6 +2,7 @@ import os +import neuron from pytest import raises import pytest @@ -14,11 +15,11 @@ def test_eval_neuron(): """Unit test for the eval_neuron function.""" - eval_neuron("bluecellulab.neuron.h.nil", bluecellulab=bluecellulab) + eval_neuron("neuron.h.nil", neuron=neuron) with raises(NeuronEvalError): eval_neuron("1+1") with raises(NeuronEvalError): - eval_neuron("bluecellulab.neuron.h.nil; 2-1", bluecellulab=bluecellulab) + eval_neuron("neuron.h.nil; 2-1", neuron=neuron) with raises(NeuronEvalError): eval_neuron("a=1") diff --git a/tests/test_rngsettings.py b/tests/test_rngsettings.py index 29f67493..8335746d 100644 --- a/tests/test_rngsettings.py +++ b/tests/test_rngsettings.py @@ -1,5 +1,7 @@ """Unit tests for the RNGSettings class.""" +import neuron + import bluecellulab from bluecellulab.exceptions import UndefinedRNGException @@ -7,20 +9,20 @@ def test_setting_rngmodes(): """Test the setting of rng mode.""" rng_obj = bluecellulab.RNGSettings(mode="Compatibility") - assert bluecellulab.neuron.h.rngMode == 0 + assert neuron.h.rngMode == 0 rng_obj.mode = "Random123" - assert bluecellulab.neuron.h.rngMode == 1 + assert neuron.h.rngMode == 1 rng_obj.mode = "UpdatedMCell" - assert bluecellulab.neuron.h.rngMode == 2 + assert neuron.h.rngMode == 2 bluecellulab.RNGSettings(mode="Random123") - assert bluecellulab.neuron.h.rngMode == 1 + assert neuron.h.rngMode == 1 assert rng_obj.mode == "Random123" bluecellulab.RNGSettings() - assert bluecellulab.neuron.h.rngMode == 1 + assert neuron.h.rngMode == 1 assert rng_obj.mode == "Random123" try: diff --git a/tests/test_simulation/test_neuron_globals.py b/tests/test_simulation/test_neuron_globals.py index be7b8281..2b90ca1c 100644 --- a/tests/test_simulation/test_neuron_globals.py +++ b/tests/test_simulation/test_neuron_globals.py @@ -1,21 +1,23 @@ from unittest import mock + import pytest -import bluecellulab +import neuron + from bluecellulab.circuit.config.sections import ConditionEntry, Conditions, MechanismConditions from bluecellulab.simulation.neuron_globals import set_global_condition_parameters, set_init_depleted_values, set_minis_single_vesicle_values, set_tstop_value def test_set_tstop_value(): set_tstop_value(100.0) - assert bluecellulab.neuron.h.tstop == 100.0 + assert neuron.h.tstop == 100.0 -@mock.patch("bluecellulab.neuron.h") +@mock.patch("neuron.h") def test_set_global_condition_parameters_no_mechs(mocked_h): del mocked_h.cao_CR_GluSynapse # delete the attribute for the mock calcium_condition = Conditions(extracellular_calcium=2.0) set_global_condition_parameters(calcium_condition) - assert not hasattr(bluecellulab.neuron.h, "cao_CR_GluSynapse") + assert not hasattr(neuron.h, "cao_CR_GluSynapse") mech_conditions = Conditions(mech_conditions=MechanismConditions(None, None, None)) set_global_condition_parameters(mech_conditions) @@ -25,7 +27,7 @@ def test_set_global_condition_parameters_no_mechs(mocked_h): def test_set_global_condition_parameters(): calcium_condition = Conditions(extracellular_calcium=2.015) set_global_condition_parameters(calcium_condition) - assert bluecellulab.neuron.h.cao_CR_GluSynapse == 2.015 + assert neuron.h.cao_CR_GluSynapse == 2.015 @pytest.mark.v6 @@ -36,9 +38,9 @@ def test_set_init_depleted_values(): glusynapse=ConditionEntry(minis_single_vesicle=None, init_depleted=None), ) set_init_depleted_values(mech_conditions) - assert bluecellulab.neuron.h.init_depleted_ProbAMPANMDA_EMS == 1.0 - assert bluecellulab.neuron.h.init_depleted_ProbGABAAB_EMS == 0.0 - assert bluecellulab.neuron.h.init_depleted_GluSynapse == 0.0 + assert neuron.h.init_depleted_ProbAMPANMDA_EMS == 1.0 + assert neuron.h.init_depleted_ProbGABAAB_EMS == 0.0 + assert neuron.h.init_depleted_GluSynapse == 0.0 @pytest.mark.v6 @@ -49,6 +51,6 @@ def test_set_minis_single_vesicle_values(): glusynapse=ConditionEntry(minis_single_vesicle=None, init_depleted=None), ) set_minis_single_vesicle_values(mech_conditions) - assert bluecellulab.neuron.h.minis_single_vesicle_ProbAMPANMDA_EMS == 1.0 - assert bluecellulab.neuron.h.minis_single_vesicle_ProbGABAAB_EMS == 0.0 - assert bluecellulab.neuron.h.minis_single_vesicle_GluSynapse == 0.0 + assert neuron.h.minis_single_vesicle_ProbAMPANMDA_EMS == 1.0 + assert neuron.h.minis_single_vesicle_ProbGABAAB_EMS == 0.0 + assert neuron.h.minis_single_vesicle_GluSynapse == 0.0