Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
88 changes: 77 additions & 11 deletions bluecellulab/tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -530,6 +530,64 @@ def resolve_source_nodes(source, report_type, cells, population):
return node_ids, compartment_nodes


def compute_memodel_properties_subprocess(
cell_kwargs: dict,
holding_current: float,
spike_threshold_voltage: float,
) -> Tuple[float, float]:
"""Compute rheobase and Rin in one process, reusing a single Cell."""
section, segx = "soma[0]", 0.5
current_delta = -0.02
inj_start, inj_stop = 300.0, 1000.0
precision = 0.005

# The Cell is reused across probes. Stochastic channels must restart their RNG
# stream on each run (StochKv/StochKv3 do this for Random123 in INITIAL).
# Templates that seed with MCellRan4 Random objects, or older StochKv3 builds
# without nrnran123_setseq in INITIAL, would see different noise than main.
cell = bluecellulab.Cell(**cell_kwargs)
cvode = template_accepts_cvode(cell_kwargs["template_path"])

def clear_stims() -> None:
cell.persistent.clear()

def steady_voltage(amp: float) -> float:
clear_stims()
sec = cell.get_section(section)
cell.add_voltage_recording(cell.sections[section], segx)
cell.add_ramp(500, 5000, amp, amp, section=sec, segx=segx)
bluecellulab.Simulation().run(1000, cvode=cvode)
t = cell.get_time()
v = cell.get_voltage_recording(section=sec, segx=segx)
return float(np.mean(v[(t <= 1000) & (t > 800)]))

def spikes(amp: float) -> bool:
clear_stims()
sec = cell.get_section(section)
cell.add_voltage_recording(cell.sections[section], segx)
cell.add_ramp(0, 5000, holding_current, holding_current, section=sec, segx=segx)
cell.add_ramp(inj_start, inj_stop, amp, amp, section=sec, segx=segx)
bluecellulab.Simulation().run(int(inj_stop), cvode=cvode)
t = cell.get_time()
v = cell.get_voltage_recording(section=sec, segx=segx)
return detect_spike(v[(t > inj_start) & (t < inj_stop)], spike_threshold_voltage)

try:
rmp = steady_voltage(0.0)
rin = (steady_voltage(current_delta) - rmp) / current_delta

low, high = holding_current, min((spike_threshold_voltage - rmp) / rin, 2.0)
while abs(high - low) >= precision:
mid = low + abs(low - high) / 2
if spikes(mid):
high = mid
else:
low = mid
return high, rin
finally:
cell.delete()


def compute_memodel_properties(
cell,
spike_threshold_voltage=-30,
Expand All @@ -544,20 +602,28 @@ def compute_memodel_properties(
v_init (float, optional): Initial membrane potential. Default is -80 mV.
celsius (float, optional): Temperature in Celsius. Default is 34.0 C.
"""
# set initial voltage and temperature
set_neuron_globals(temperature=celsius, v_init=v_init)

# get me-model properties
holding_current = cell.hypamp if cell.hypamp else 0.0
rheobase = calculate_rheobase(
cell=cell, section="soma[0]", segx=0.5, threshold_voltage=spike_threshold_voltage
)
rin = calculate_input_resistance(
template_path=cell.template_params.template_filepath,
morphology_path=cell.template_params.morph_filepath,
template_format=cell.template_params.template_format,
emodel_properties=cell.template_params.emodel_properties,
)
params = cell.template_params
if params.emodel_properties is None:
raise ValueError("emodel_properties cannot be None")

# Match calculate_rheobase: search uses emodel holding, which can differ from
# cell.hypamp for non-v6 templates without getHypAmp().
search_holding = params.emodel_properties.holding_current

cell_kwargs = {
"template_path": params.template_filepath,
"morphology_path": params.morph_filepath,
"template_format": params.template_format,
"emodel_properties": params.emodel_properties,
}
with IsolatedProcess() as runner:
rheobase, rin = runner.apply(
compute_memodel_properties_subprocess,
[cell_kwargs, search_holding, spike_threshold_voltage],
)

return {"holding_current": holding_current, "rheobase": rheobase, "rin": rin}

Expand Down
112 changes: 111 additions & 1 deletion tests/test_tools.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,7 +25,7 @@
from bluecellulab.circuit.circuit_access import EmodelProperties
from bluecellulab.circuit.node_id import create_cell_id
from bluecellulab.exceptions import UnsteadyCellError
from bluecellulab.tools import calculate_SS_voltage, calculate_SS_voltage_subprocess, calculate_input_resistance, detect_hyp_current, detect_spike, detect_spike_step, detect_spike_step_subprocess, holding_current, holding_current_subprocess, search_threshold_current, template_accepts_cvode, check_empty_topology, calculate_max_thresh_current, calculate_rheobase, validate_section_and_segment, compute_memodel_properties_v2
from bluecellulab.tools import calculate_SS_voltage, calculate_SS_voltage_subprocess, calculate_input_resistance, detect_hyp_current, detect_spike, detect_spike_step, detect_spike_step_subprocess, holding_current, holding_current_subprocess, search_threshold_current, template_accepts_cvode, check_empty_topology, calculate_max_thresh_current, calculate_rheobase, validate_section_and_segment, compute_memodel_properties, compute_memodel_properties_subprocess, compute_memodel_properties_v2
from bluecellulab.cell.section_tools import currents_vars, mechs_vars


Expand Down Expand Up @@ -250,6 +250,37 @@ def test_detect_spike_step_subprocess(self):
)
assert spike_occurred is True

def test_compute_memodel_properties(self):
"""Unit test compute_memodel_properties.

Expected values from origin/main on this cADpyr_L2TPC example cell.
"""
cell = Cell(
template_path=self.template_name,
morphology_path=self.morphology_path,
template_format=self.template_format,
emodel_properties=self.emodel_properties,
)
resp_dict = compute_memodel_properties(cell)

assert resp_dict["holding_current"] == pytest.approx(-0.11)
assert resp_dict["rheobase"] == pytest.approx(0.13921147797816324)
assert resp_dict["rin"] == pytest.approx(334.1378411934045)

def test_compute_memodel_properties_subprocess(self):
"""Cover compute_memodel_properties_subprocess in-process (IsolatedProcess is not measured)."""
cell_kwargs = {
"template_path": self.template_name,
"morphology_path": self.morphology_path,
"template_format": self.template_format,
"emodel_properties": self.emodel_properties,
}
rheobase, rin = compute_memodel_properties_subprocess(
cell_kwargs, holding_current=-0.11, spike_threshold_voltage=-30
)
assert rheobase == pytest.approx(0.1392, abs=1e-4)
assert rin == pytest.approx(334.14, abs=0.1)

def test_compute_memodel_properties_v2(self):
"""Unit test compute_memodel_properties_v2."""
resp_dict = compute_memodel_properties_v2(
Expand Down Expand Up @@ -305,6 +336,85 @@ def test_check_empty_topology():
assert check_empty_topology() is False


def test_compute_memodel_properties_requires_emodel_properties():
"""compute_memodel_properties rejects cells without emodel_properties."""
cell = MagicMock()
cell.hypamp = None
cell.template_params.emodel_properties = None
with pytest.raises(ValueError, match="emodel_properties cannot be None"):
compute_memodel_properties(cell)


def _memodel_cell_mock(hypamp, holding_current, template_path="template.hoc"):
cell = MagicMock()
cell.hypamp = hypamp
cell.template_params.template_filepath = template_path
cell.template_params.morph_filepath = "morph.asc"
cell.template_params.template_format = "v5"
cell.template_params.emodel_properties = EmodelProperties(
threshold_current=0.0, holding_current=holding_current
)
return cell


def test_compute_memodel_properties_uses_emodel_holding_for_search():
"""Search holding comes from emodel_properties; returned holding from hypamp."""
cell = _memodel_cell_mock(hypamp=None, holding_current=-0.05)
runner = MagicMock()
runner.apply.return_value = (0.1, 200.0)
runner.__enter__.return_value = runner
runner.__exit__.return_value = False

with patch("bluecellulab.tools.IsolatedProcess", return_value=runner), patch(
"bluecellulab.tools.set_neuron_globals"
):
result = compute_memodel_properties(cell)

assert runner.apply.call_args.args[0] is compute_memodel_properties_subprocess
assert runner.apply.call_args.args[1][1] == -0.05
assert result == {"holding_current": 0.0, "rheobase": 0.1, "rin": 200.0}


def test_compute_memodel_properties_always_uses_single_cell_path():
"""StochKv and deterministic templates share the single-Cell worker."""
cell = _memodel_cell_mock(hypamp=-0.11, holding_current=-0.11)
runner = MagicMock()
runner.apply.return_value = (0.14, 334.0)
runner.__enter__.return_value = runner
runner.__exit__.return_value = False

with patch("bluecellulab.tools.IsolatedProcess", return_value=runner), patch(
"bluecellulab.tools.calculate_rheobase"
) as rheobase, patch(
"bluecellulab.tools.calculate_input_resistance"
) as rin, patch("bluecellulab.tools.set_neuron_globals"):
result = compute_memodel_properties(cell)

rheobase.assert_not_called()
rin.assert_not_called()
assert runner.apply.call_args.args[0] is compute_memodel_properties_subprocess
assert result == {"holding_current": -0.11, "rheobase": 0.14, "rin": 334.0}


@pytest.mark.v5
def test_compute_memodel_properties_v5_cstut():
"""Golden values from origin/main on cSTUT_7 with emodel holding -0.05 nA."""
emodel_properties = EmodelProperties(
threshold_current=0.0, holding_current=-0.05
)
cell = Cell(
template_path=script_dir / "examples/cell_example_cstut/cSTUT_7.hoc",
morphology_path=script_dir / "examples/cell_example_cstut",
template_format="v5",
emodel_properties=emodel_properties,
)
resp_dict = compute_memodel_properties(cell)

assert resp_dict["holding_current"] == pytest.approx(0.0)
assert resp_dict["rheobase"] == pytest.approx(0.0968098129791797)
assert resp_dict["rin"] == pytest.approx(241.439121257406)


def test_calculate_max_thresh_current(mock_cell, mock_calculate_SS_voltage, mock_calculate_input_resistance):
"""Test the calculate_max_thresh_current function."""
with patch('bluecellulab.tools.calculate_SS_voltage', mock_calculate_SS_voltage), \
Expand Down
Loading