Skip to content
This repository has been archived by the owner on Mar 31, 2024. It is now read-only.

Commit

Permalink
Some refactoring
Browse files Browse the repository at this point in the history
  • Loading branch information
Tanguy Pierre Louis Damart committed Jul 26, 2022
1 parent 5ec9824 commit a57b3b8
Show file tree
Hide file tree
Showing 8 changed files with 75 additions and 139 deletions.
12 changes: 9 additions & 3 deletions bluepyopt/ephys/models.py
Original file line number Diff line number Diff line change
Expand Up @@ -488,6 +488,7 @@ class LFPyCellModel(Model):
def __init__(
self,
name,
electrode=None,
morph=None,
mechs=None,
params=None,
Expand Down Expand Up @@ -525,7 +526,9 @@ def __init__(

# Cell instantiation in simulator
self.icell = None
self.LFPyCell = None
self.lfpy_cell = None
self.electrode = electrode
self.lfpy_electrode = None

self.dt = dt
self.v_init = v_init
Expand Down Expand Up @@ -656,7 +659,8 @@ def create_empty_cell(name, sim, seclist_names=None, secarray_names=None):

def instantiate(self, sim=None):
"""Instantiate model in simulator"""
import LFPy
from LFPy import Cell
from lfpykit import RecExtElectrode

# TODO replace this with the real template name
if not hasattr(sim.neuron.h, self.name):
Expand All @@ -673,7 +677,7 @@ def instantiate(self, sim=None):

self.morphology.instantiate(sim=sim, icell=self.icell)

self.LFPyCell = LFPy.Cell(
self.lfpy_cell = Cell(
morphology=sim.neuron.h.allsec(),
dt=self.dt,
v_init=self.v_init,
Expand All @@ -682,6 +686,8 @@ def instantiate(self, sim=None):
nsegs_method=None,
)

self.lfpy_electrode = RecExtElectrode(self.lfpy_cell, probe=self.electrode)

if self.mechanisms is not None:
for mechanism in self.mechanisms:
mechanism.instantiate(sim=sim, icell=self.icell)
Expand Down
2 changes: 1 addition & 1 deletion bluepyopt/ephys/parameters.py
Original file line number Diff line number Diff line change
Expand Up @@ -196,7 +196,7 @@ def __init__(
value_scaler (float): value used to scale the parameter value
locations (list of ephys.locations.Location): locations on which
to instantiate the parameter
param_dependencies (list): dependencies needed to intantiate
param_dependencies (list): dependencies needed to instantiate
the parameter
"""

Expand Down
46 changes: 21 additions & 25 deletions bluepyopt/ephys/protocols.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,7 @@
"""Protocol classes"""
from .recordings import LFPRecording
from .simulators import LFPySimulator
from .stimuli import LFPySquarePulse

"""
Copyright (c) 2016-2020, EPFL/Blue Brain Project
Expand Down Expand Up @@ -193,23 +196,17 @@ def _run_func(self, cell_model, param_values, sim=None):
cell_model.freeze(param_values)
cell_model.instantiate(sim=sim)

if isinstance(cell_model, models.LFPyCellModel):
LFPyCell = cell_model.LFPyCell
else:
LFPyCell = None

self.instantiate(
sim=sim, icell=cell_model.icell, LFPyCell=LFPyCell
)

if hasattr(sim, "electrode"):
if any(["LFP" in rec.name for rec in self.recordings]):
sim.effective_electrode = sim.electrode
else:
sim.effective_electrode = None
self.instantiate(sim=sim, cell_model=cell_model)

try:
sim.run(self.total_duration, cvode_active=self.cvode_active)
if isinstance(sim, LFPySimulator):
sim.run(
lfpy_cell=cell_model.lfpy_cell,
lfpy_electrode=cell_model.lfpy_electrode,
tstop=self.total_duration,
cvode_active=self.cvode_active)
else:
sim.run(tstop=self.total_duration, cvode_active=self.cvode_active)
except (RuntimeError, simulators.NrnSimulatorException):
logger.debug(
'SweepProtocol: Running of parameter set {%s} generated '
Expand Down Expand Up @@ -284,23 +281,22 @@ def _reduce_method(meth):
sim=sim)
return responses

def instantiate(self, sim=None, icell=None, LFPyCell=None):
def instantiate(self, sim=None, cell_model=None):
"""Instantiate"""

for stimulus in self.stimuli:
if LFPyCell is not None:
stimulus.instantiate(sim=sim, icell=icell, LFPyCell=LFPyCell)
if isinstance(stimulus, LFPySquarePulse):
stimulus.instantiate(lfpy_cell=cell_model.lfpy_cell)
else:
stimulus.instantiate(sim=sim, icell=icell)
stimulus.instantiate(sim=sim, icell=cell_model.icell)

for recording in self.recordings:
try:
# try to instantiate as an LFPy recording
try:
recording.instantiate(sim=sim, icell=icell,
LFPyCell=LFPyCell)
except Exception as e:
recording.instantiate(sim=sim, icell=icell)
if isinstance(recording, LFPRecording):
recording.instantiate(sim=sim, lfpy_cell=cell_model.lfpy_cell,
electrode=cell_model.lfpy_electrode)
else:
recording.instantiate(sim=sim, icell=cell_model.icell)
except locations.EPhysLocInstantiateException:
logger.debug(
'SweepProtocol: Instantiating recording generated '
Expand Down
12 changes: 7 additions & 5 deletions bluepyopt/ephys/recordings.py
Original file line number Diff line number Diff line change
Expand Up @@ -141,10 +141,10 @@ def response(self):
return None
self.tvector = self.cell.tvec
return responses.TimeLFPResponse(
self.name, self.tvector, self.sim.lfpyelectrode.data
self.name, self.tvector, self.electrode.data
)

def instantiate(self, sim=None, icell=None, LFPyCell=None):
def instantiate(self, sim=None, lfpy_cell=None, electrode=None):
import LFPy

"""Instantiate recording"""
Expand All @@ -154,10 +154,11 @@ def instantiate(self, sim=None, icell=None, LFPyCell=None):
)

assert isinstance(
LFPyCell, LFPy.Cell
lfpy_cell, LFPy.Cell
), "LFPRecording is only available for LFPCellModel"
self.cell = LFPyCell
self.cell = lfpy_cell
self.tvector = None
self.electrode = electrode
self.sim = sim

self.instantiated = True
Expand All @@ -168,7 +169,8 @@ def destroy(self, sim=None):
self.electrode = None
self.LFP = None
self.tvector = None

self.electrode = None
self.cell = None
self.instantiated = False

def __str__(self):
Expand Down
29 changes: 7 additions & 22 deletions bluepyopt/ephys/responses.py
Original file line number Diff line number Diff line change
Expand Up @@ -86,35 +86,20 @@ def plot(self, axes):
self.name)


class TimeLFPResponse(Response):
class TimeLFPResponse(TimeVoltageResponse):

"""Response to stimulus"""

def __init__(self, name, time=None, LFP=None):
def __init__(self, name, time=None, lfp=None):
"""Constructor
Args:
name (str): name of this object
time (list of floats): time series
LFP (list of floats): voltage series
lfp (list of floats): voltage series
"""

super(TimeLFPResponse, self).__init__(name)
super(TimeLFPResponse, self).__init__(name, time=time, voltage=None)
self.response["voltage"] = lfp

self.response = {}
self.response["time"] = time
self.response["voltage"] = LFP

def read_csv(self, filename):
"""Load response from csv file"""

self.response = pandas.read_csv(filename)

def to_csv(self, filename):
"""Write response to csv file"""

self.response.to_csv(filename)

def __getitem__(self, index):
"""Return item at index"""

return self.response.__getitem__(index)
def plot(self, axes):
raise NotImplementedError
96 changes: 19 additions & 77 deletions bluepyopt/ephys/simulators.py
Original file line number Diff line number Diff line change
Expand Up @@ -184,18 +184,16 @@ def __init__(self, message, original):
self.original = original


class LFPySimulator(object):
class LFPySimulator(NrnSimulator):

"""LFPy simulator"""

def __init__(self, LFPyCellModel, electrode=None, cvode_active=True,
cvode_minstep=None, random123_globalindex=None,
mechanisms_directory=None):
def __init__(self, dt=None, cvode_active=True, cvode_minstep=None,
random123_globalindex=None, mechanisms_directory=None):
"""Constructor
Args:
LFPyCellModel (LFPyCellModel): the LFPy cell model
electrode (MEAutility.MEA): the MEAutility probe used to compute
extracellular signals
dt (float): the integration time step used by neuron.
cvode_active (bool): should neuron use the variable time step
integration method
cvode_minstep (float): the minimum time step allowed for a cvode
Expand All @@ -208,81 +206,30 @@ def __init__(self, LFPyCellModel, electrode=None, cvode_active=True,
"./data/".
"""

self.LFPyCellModel = LFPyCellModel
self.electrode = electrode
self.effective_electrode = electrode

self.lfpyelectrode = None

if platform.system() == "Windows":
# hoc.so does not exist on NEURON Windows
# although \\hoc.pyd can work here, it gives an error for
# nrn_nobanner_ line
self.disable_banner = False
self.banner_disabled = False
else:
self.disable_banner = True
self.banner_disabled = False

self.mechanisms_directory = mechanisms_directory
self.neuron.h.load_file('stdrun.hoc')

self.cvode_active = cvode_active
self.cvode_minstep_value = cvode_minstep

self.random123_globalindex = random123_globalindex

@staticmethod
def _nrn_disable_banner():
"""Disable Neuron banner"""

nrnpy_path = os.path.join(imp.find_module("neuron")[1])
import glob

hoc_so_list = glob.glob(os.path.join(nrnpy_path, "hoc*.so"))

if len(hoc_so_list) != 1:
warnings.warn(
"Unable to find Neuron hoc shared library in %s, "
"not disabling banner" % nrnpy_path
)
else:
hoc_so = hoc_so_list[0]
nrndll = ctypes.cdll[hoc_so]
ctypes.c_int.in_dll(nrndll, "nrn_nobanner_").value = 1

@property
def neuron(self):
"""Return neuron module"""

if self.disable_banner and not self.banner_disabled:
NrnSimulator._nrn_disable_banner()
self.banner_disabled = True

import neuron # NOQA
if self.mechanisms_directory is not None:
neuron.load_mechanisms(
self.mechanisms_directory, warn_if_already_loaded=False
)

return neuron
super(LFPySimulator, self).__init__(
dt=dt,
cvode_active=cvode_active,
cvode_minstep=cvode_minstep,
random123_globalindex=random123_globalindex,
mechanisms_directory=mechanisms_directory
)

def run(
self,
lfpy_cell,
lfpy_electrode,
tstop=None,
dt=None,
cvode_active=None,
random123_globalindex=None):
"""Run protocol"""
import LFPy
# import neuron mechanisms
_ = self.neuron

self.LFPyCellModel.LFPyCell.tstart = 0.0
self.LFPyCellModel.LFPyCell.tstop = tstop
lfpy_cell.tstart = 0.0
lfpy_cell.tstop = tstop

if dt is not None:
self.LFPyCellModel.LFPyCell.dt = dt
lfpy_cell.LFPyCell.dt = dt

if cvode_active and dt is not None:
raise ValueError(
Expand All @@ -302,12 +249,7 @@ def run(
rng = self.neuron.h.Random()
rng.Random123_globalindex(random123_globalindex)

if self.effective_electrode is not None:
self.lfpyelectrode = LFPy.RecExtElectrode(
self.LFPyCellModel.LFPyCell, probe=self.electrode)
probes = [self.lfpyelectrode]
else:
probes = None
probes = [lfpy_electrode] if lfpy_electrode is not None else None

sim_params = {
"probes": probes,
Expand All @@ -324,7 +266,7 @@ def run(
}

try:
self.LFPyCellModel.LFPyCell.simulate(**sim_params)
lfpy_cell.simulate(**sim_params)
except Exception as e:
raise LFPySimulatorException("LFPy simulator error", e)

Expand Down
8 changes: 4 additions & 4 deletions bluepyopt/ephys/stimuli.py
Original file line number Diff line number Diff line change
Expand Up @@ -357,7 +357,7 @@ def __init__(self,
self.total_duration = total_duration
self.iclamp = None

def instantiate(self, sim=None, icell=None, LFPyCell=None):
def instantiate(self, lfpy_cell=None):
"""Run stimulus"""
import LFPy
from .locations import NrnSomaDistanceCompLocation
Expand All @@ -366,8 +366,8 @@ def instantiate(self, sim=None, icell=None, LFPyCell=None):
sec_index = self.location.sec_index
elif isinstance(self.location, NrnSomaDistanceCompLocation):
# compute sec_index closest to soma_distance
cell_seg_locs = np.array([LFPyCell.x, LFPyCell.y, LFPyCell.z]).T
soma_loc = LFPyCell.somapos
cell_seg_locs = np.array([lfpy_cell.x, lfpy_cell.y, lfpy_cell.z]).T
soma_loc = lfpy_cell.somapos
dist_from_soma = np.array(
[np.linalg.norm(loc - soma_loc) for loc in cell_seg_locs]
)
Expand All @@ -381,7 +381,7 @@ def instantiate(self, sim=None, icell=None, LFPyCell=None):
)

self.iclamp = LFPy.StimIntElectrode(
cell=LFPyCell,
cell=lfpy_cell,
idx=sec_index,
pptype="IClamp",
amp=self.step_amplitude,
Expand Down
Loading

0 comments on commit a57b3b8

Please sign in to comment.