From a1ba157be2c48c6e6c0092f53d0418fc65ed4ed5 Mon Sep 17 00:00:00 2001 From: Eleftherios Zisis Date: Thu, 12 Nov 2026 13:19:42 +0100 Subject: [PATCH 1/5] Speed up compute_memodel_properties with one reused Cell. Avoid spawning a process and rebuilding the cell for every SS/threshold probe; keep origin/main numerical results via a dedicated regression test. --- bluecellulab/tools.py | 82 +++++++++++++++++++++++++++++++++++++------ tests/test_tools.py | 19 +++++++++- 2 files changed, 89 insertions(+), 12 deletions(-) diff --git a/bluecellulab/tools.py b/bluecellulab/tools.py index 5d8ef214..494c9ce6 100644 --- a/bluecellulab/tools.py +++ b/bluecellulab/tools.py @@ -530,6 +530,62 @@ 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 + + cell = bluecellulab.Cell(**cell_kwargs) + cvode = template_accepts_cvode(cell_kwargs["template_path"]) + + def clear_stims() -> None: + for stim in cell.persistent: + del stim + 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, @@ -544,20 +600,24 @@ 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") + + 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, holding_current, spike_threshold_voltage], + ) return {"holding_current": holding_current, "rheobase": rheobase, "rin": rin} diff --git a/tests/test_tools.py b/tests/test_tools.py index 41d83ac0..c5cfa09e 100644 --- a/tests/test_tools.py +++ b/tests/test_tools.py @@ -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_v2 from bluecellulab.cell.section_tools import currents_vars, mechs_vars @@ -250,6 +250,23 @@ 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_v2(self): """Unit test compute_memodel_properties_v2.""" resp_dict = compute_memodel_properties_v2( From 6a2120f4e7f58f987572df9399d91e4c93fc7cd4 Mon Sep 17 00:00:00 2001 From: Eleftherios Zisis Date: Thu, 12 Nov 2026 16:15:01 +0100 Subject: [PATCH 2/5] Cover compute_memodel_properties_subprocess in-process. IsolatedProcess workers are not measured by coverage; exercise the worker body directly and the missing-emodel_properties error path. --- tests/test_tools.py | 25 ++++++++++++++++++++++++- 1 file changed, 24 insertions(+), 1 deletion(-) diff --git a/tests/test_tools.py b/tests/test_tools.py index c5cfa09e..1c621e78 100644 --- a/tests/test_tools.py +++ b/tests/test_tools.py @@ -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, 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 @@ -267,6 +267,20 @@ def test_compute_memodel_properties(self): 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( @@ -322,6 +336,15 @@ 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 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), \ From 15c8b35168e05c8c5eddd256121a9b89003a33ee Mon Sep 17 00:00:00 2001 From: Eleftherios Zisis Date: Wed, 18 Nov 2026 14:11:33 +0100 Subject: [PATCH 3/5] Restore main parity for holding current and StochKv RNG in compute_memodel_properties. --- bluecellulab/tools.py | 25 ++++++++++-- tests/test_tools.py | 89 +++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 111 insertions(+), 3 deletions(-) diff --git a/bluecellulab/tools.py b/bluecellulab/tools.py index 494c9ce6..d8ee0231 100644 --- a/bluecellulab/tools.py +++ b/bluecellulab/tools.py @@ -545,8 +545,6 @@ def compute_memodel_properties_subprocess( cvode = template_accepts_cvode(cell_kwargs["template_path"]) def clear_stims() -> None: - for stim in cell.persistent: - del stim cell.persistent.clear() def steady_voltage(amp: float) -> float: @@ -607,6 +605,27 @@ def compute_memodel_properties( 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 + + # StochKv templates: keep per-probe IsolatedProcess so MCellRan4 streams + # do not carry over between probes (re_init_rng would change unseeded templates). + if not template_accepts_cvode(params.template_filepath): + rheobase = calculate_rheobase( + cell=cell, + section="soma[0]", + segx=0.5, + threshold_voltage=spike_threshold_voltage, + ) + rin = calculate_input_resistance( + template_path=params.template_filepath, + morphology_path=params.morph_filepath, + template_format=params.template_format, + emodel_properties=params.emodel_properties, + ) + return {"holding_current": holding_current, "rheobase": rheobase, "rin": rin} + cell_kwargs = { "template_path": params.template_filepath, "morphology_path": params.morph_filepath, @@ -616,7 +635,7 @@ def compute_memodel_properties( with IsolatedProcess() as runner: rheobase, rin = runner.apply( compute_memodel_properties_subprocess, - [cell_kwargs, holding_current, spike_threshold_voltage], + [cell_kwargs, search_holding, spike_threshold_voltage], ) return {"holding_current": holding_current, "rheobase": rheobase, "rin": rin} diff --git a/tests/test_tools.py b/tests/test_tools.py index 1c621e78..65b96ca2 100644 --- a/tests/test_tools.py +++ b/tests/test_tools.py @@ -345,6 +345,95 @@ def test_compute_memodel_properties_requires_emodel_properties(): 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.template_accepts_cvode", return_value=True), patch( + "bluecellulab.tools.IsolatedProcess", return_value=runner + ), patch("bluecellulab.tools.set_neuron_globals"): + result = compute_memodel_properties(cell) + + 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_stochkv_uses_legacy_path(): + """StochKv templates keep the per-probe path for RNG parity with main.""" + cell = _memodel_cell_mock(hypamp=None, holding_current=-0.05) + with patch("bluecellulab.tools.template_accepts_cvode", return_value=False), patch( + "bluecellulab.tools.calculate_rheobase", return_value=0.0968 + ) as rheobase, patch( + "bluecellulab.tools.calculate_input_resistance", return_value=241.44 + ) as rin, patch( + "bluecellulab.tools.compute_memodel_properties_subprocess" + ) as worker, patch("bluecellulab.tools.set_neuron_globals"): + result = compute_memodel_properties(cell) + + rheobase.assert_called_once() + rin.assert_called_once() + worker.assert_not_called() + assert result == {"holding_current": 0.0, "rheobase": 0.0968, "rin": 241.44} + + +def test_compute_memodel_properties_cvode_uses_single_cell_path(): + """Deterministic templates use 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.template_accepts_cvode", return_value=True), 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), \ From 13fef2575059acf459e5f39dc51d18cf0a22e363 Mon Sep 17 00:00:00 2001 From: Eleftherios Zisis Date: Wed, 18 Nov 2026 15:06:32 +0100 Subject: [PATCH 4/5] Use single-Cell worker for StochKv as well in compute_memodel_properties. --- bluecellulab/tools.py | 17 ----------------- tests/test_tools.py | 33 +++++++-------------------------- 2 files changed, 7 insertions(+), 43 deletions(-) diff --git a/bluecellulab/tools.py b/bluecellulab/tools.py index d8ee0231..a0724b1e 100644 --- a/bluecellulab/tools.py +++ b/bluecellulab/tools.py @@ -609,23 +609,6 @@ def compute_memodel_properties( # cell.hypamp for non-v6 templates without getHypAmp(). search_holding = params.emodel_properties.holding_current - # StochKv templates: keep per-probe IsolatedProcess so MCellRan4 streams - # do not carry over between probes (re_init_rng would change unseeded templates). - if not template_accepts_cvode(params.template_filepath): - rheobase = calculate_rheobase( - cell=cell, - section="soma[0]", - segx=0.5, - threshold_voltage=spike_threshold_voltage, - ) - rin = calculate_input_resistance( - template_path=params.template_filepath, - morphology_path=params.morph_filepath, - template_format=params.template_format, - emodel_properties=params.emodel_properties, - ) - return {"holding_current": holding_current, "rheobase": rheobase, "rin": rin} - cell_kwargs = { "template_path": params.template_filepath, "morphology_path": params.morph_filepath, diff --git a/tests/test_tools.py b/tests/test_tools.py index 65b96ca2..10fc30aa 100644 --- a/tests/test_tools.py +++ b/tests/test_tools.py @@ -365,44 +365,25 @@ def test_compute_memodel_properties_uses_emodel_holding_for_search(): runner.__enter__.return_value = runner runner.__exit__.return_value = False - with patch("bluecellulab.tools.template_accepts_cvode", return_value=True), patch( - "bluecellulab.tools.IsolatedProcess", return_value=runner - ), patch("bluecellulab.tools.set_neuron_globals"): + 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_stochkv_uses_legacy_path(): - """StochKv templates keep the per-probe path for RNG parity with main.""" - cell = _memodel_cell_mock(hypamp=None, holding_current=-0.05) - with patch("bluecellulab.tools.template_accepts_cvode", return_value=False), patch( - "bluecellulab.tools.calculate_rheobase", return_value=0.0968 - ) as rheobase, patch( - "bluecellulab.tools.calculate_input_resistance", return_value=241.44 - ) as rin, patch( - "bluecellulab.tools.compute_memodel_properties_subprocess" - ) as worker, patch("bluecellulab.tools.set_neuron_globals"): - result = compute_memodel_properties(cell) - - rheobase.assert_called_once() - rin.assert_called_once() - worker.assert_not_called() - assert result == {"holding_current": 0.0, "rheobase": 0.0968, "rin": 241.44} - - -def test_compute_memodel_properties_cvode_uses_single_cell_path(): - """Deterministic templates use the single-Cell worker.""" +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.template_accepts_cvode", return_value=True), patch( - "bluecellulab.tools.IsolatedProcess", return_value=runner - ), patch( + with patch("bluecellulab.tools.IsolatedProcess", return_value=runner), patch( "bluecellulab.tools.calculate_rheobase" ) as rheobase, patch( "bluecellulab.tools.calculate_input_resistance" From 28a927bfa4f42b206dc53bfbd543e546ad4ac5ae Mon Sep 17 00:00:00 2001 From: Eleftherios Zisis Date: Wed, 18 Nov 2026 16:36:35 +0100 Subject: [PATCH 5/5] Document RNG reuse assumption for compute_memodel_properties_subprocess. --- bluecellulab/tools.py | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/bluecellulab/tools.py b/bluecellulab/tools.py index a0724b1e..a3c5a296 100644 --- a/bluecellulab/tools.py +++ b/bluecellulab/tools.py @@ -541,6 +541,10 @@ def compute_memodel_properties_subprocess( 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"])