Module LFPy

Initialization of LFPy, a module for simulating extracellular potentials.

Group of Computational Neuroscience (compneuro.umb.no), Department of Mathematical Sciences and Technology, Norwegian University of Life Sciences.

Copyright (C) 2012 Computational Neuroscience Group, UMB.

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

Classes:
  • Cell - The pythonic neuron object itself laying on top of NEURON
  • Synapse - Convenience class for inserting synapses onto Cell objects
  • StimIntraElectrode - Convenience class for inserting electrodes onto Cell objects
  • RecExtElectrode - Class for performing simulations of extracellular potentials
  • RecExtElectrdoeThreaded - same as above using multiprocessing to distribute contact points across cores
Modules:
  • lfpcalc - functions used by RecExtElectrode class
  • tools - some convenient functions
  • inputgenerators - functions for synaptic input time generation

class Cell

class LFPy.Cell(morphology, v_init=-65.0, Ra=150, rm=30000, cm=1.0, e_pas=-65.0, passive=True, timeres_NEURON=0.125, timeres_python=0.125, tstartms=0, tstopms=100, nsegs_method='lambda100', max_nsegs_length=30, lambda_f=100, custom_code=None, custom_fun=None, custom_fun_args=None, verbose=False)

Bases: object

The main cell class used in LFPy.

Arguments:

morphology : path to morphology file;

v_init: initial potential;
passive: passive mechs are initialized if True;
Ra: axial resistance;
rm: membrane resistivity;
cm: membrane capacitance;
e_pas: passive mechanism reversal potential;

timeres_NEURON: internal dt for NEURON simulation;
timeres_python: overall dt for python simulation;

tstartms: initialization time for simulation <= 0 ms
tstopms: stop time for simulation > 0 ms

nsegs_method: method for setting the number of segments;
max_nsegs_length: max segment length for method 'fixed_length';
lambda_f: AC frequency for method 'lambda_f';

custom_code: list of model-specific code files ([.py/.hoc]);
custom_fun: list of model-specific functions to be called with args:
custom_fun_args: list of arguments passed to custom_fun functions
verbose: switching verbose output on/off

Usage of cell class:

import LFPy
cellParameters = {                          
    'morphology' : 'path/to/morphology.hoc',
    'rm' : 30000,
    'cm' : 1.0,
    'Ra' : 150,
    'timeres_NEURON' : 0.1,
    'timeres_python' : 0.1,
    'tstartms' : -50,
    'tstopms' : 50,
}
cell = LFPy.Cell(**cellParameters)
cell.simulate()
cellpickler(filename)

Save data in cell to filename, using cPickle. It will however destroy any neuron.h objects upon saving, as they cannot be pickled

Usage:

cell.cellpickler('cell.cpickle')

To load this cell again in another session:

import cPickle
f = file('cell.cpickle', 'rb')
cell = cPickle.load(f)
f.close()
import LFPy cell = LFPy.tools.load(‘cell.cpickle’)
get_closest_idx(x=0, y=0, z=0, section='allsec')

Get the index number of a segment in specified section which midpoint is closest to the coordinates defined by the user

get_idx(section='allsec', z_min=-10000, z_max=10000)

Returns neuron idx of segments on interval [z_min, z_max]

get_idx_children(parent='soma[0]')

Get the idx of parent’s children sections, i.e. compartments ids of sections connected to parent-argument

get_idx_parent_children(parent='soma[0]')

Get all idx of segments of parent and children sections, i.e. segment idx of sections connected to parent-argument, and also of the parent segments

get_idx_section(section='soma[0]')

Get the idx of segments in any section-argument, uses hoc naming instead of general terms as in self.get_idx().

For example:

cell.get_idx_section(section='soma[0]')

will output something like

array([0])

To list all sections in the cell object, type

for sec in cell.allseclist:
    print sec.name()
get_intersegment_distance(idx0=0, idx1=0)

Return the Euclidean distance between midpoints of two segments with indices idx0 and idx1. Will return a float in unit of micrometers.

get_intersegment_vector(idx0=0, idx1=0)

Return the distance between midpoints of two segments with index idx0 and idx1. The argument returned is a vector [x, y, z], where x = self.xmid[idx1] - self.xmid[idx0] etc.

get_rand_idx_area_norm(section='allsec', nidx=1, z_min=-10000, z_max=10000)

Return nidx segment indices in section with random probability normalized to the membrane area of segment on interval [z_min, z_max]

get_rand_prob_area_norm(section='allsec', z_min=-10000, z_max=10000)

Return the probability (0-1) for synaptic coupling on segments in section sum(prob)=1 over all segments in section. Prob. determined by area.

get_rand_prob_area_norm_from_idx(idx=array([0]), z_min=-10000, z_max=10000)

Return the normalized probability (0-1) for synaptic coupling on segments in idx-array. Normalised probability determined by area of segments.

loadspikes()

Initialize spiketimes from netcon if they exist

set_point_process(idx, pptype, record_current=False, **kwargs)

Insert pptype-electrode type pointprocess on segment numbered idx on cell object, with keyword arguments according to types: SEClamp, VClamp, IClamp, SinIClamp, ChirpIClamp. idx, pptype, **kwargs is passed on from PointProcessElectrode class.

set_pos(xpos=0, ypos=0, zpos=0)

Move the cell geometry so that midpoint of soma section is in (xpos, ypos, zpos). If no soma pos, use the first segment

set_rotation(x=None, y=None, z=None)

Rotate geometry of cell object around the x-, y-, z-axis in that order. Input should be angles in radians.

using rotation matrices, takes dict with rot. angles, where x, y, z are the rotation angles around respective axes. All rotation angles are optional.

Usage:

cell = LFPy.Cell(**kwargs)
rotation = {'x' : 1.233, 'y' : 0.236, 'z' : np.pi}
cell.set_rotation(**rotation)
set_synapse(idx, syntype, record_current=False, record_potential=False, weight=None, **kwargs)

Insert syntype (e.g. ExpSyn) synapse on segment with index idx, **kwargs passed on from class PointProcessSynapse.

simulate(electrode=None, rec_imem=False, rec_vmem=False, rec_ipas=False, rec_icap=False, rec_isyn=False, rec_vmemsyn=False, rec_istim=False)

This is the main function running the simulation of the NEURON model. Start NEURON simulation and record variables specified by arguments.

Arguments:

electrode:  Either an LFPy.RecExtElectrode object or a list of such.
            If supplied, LFPs will be calculated at every time step
            and accessible as electrode.LFP. If a list of objects
            is given, accessible as electrode[0].LFP etc.
rec_imem:   If true, segment membrane currents will be recorded
            If no electrode argument is given, it is necessary to
            set rec_imem=True in order to calculate LFP later on.
rec_vmem:   record segment membrane voltages
rec_ipas:   record passive segment membrane currents
rec_icap:   record capacitive segment membrane currents
rec_isyn:   record synaptic currents of from Synapse class instances
rec_vmemsyn:    record membrane voltage of segments with Synapse
rec_istim:  record currents of StimIntraElectrode
strip_hoc_objects()

Destroy any NEURON hoc objects in the cell object

class PointProcess

class LFPy.PointProcess(cell, idx, color='k', marker='o', record_current=False, **kwargs)

Superclass on top of Synapse, StimIntElectrode, just to import and set some shared variables.

Arguments:

cell    : LFPy.Cell object
idx     : index of segment
color   : color in plot (optional) 
marker  : marker in plot (optional) 
record_current : Must be set True for recording of pointprocess currents
kwargs  : pointprocess specific variables passed on to cell/neuron
update_pos(cell)

Extract coordinates of point-process

class Synapse

class LFPy.Synapse(cell, idx, syntype, color='r', marker='o', record_current=False, **kwargs)

Bases: LFPy.pointprocess.PointProcess

The synapse class, pointprocesses that spawn membrane currents. See http://www.neuron.yale.edu/neuron/static/docs/help/neuron/neuron/mech.html#pointprocesses for details, or corresponding mod-files.

This class is meant to be used with synaptic mechanisms, giving rise to currents that will be part of the membrane currents.

Usage:

#!/usr/bin/env python

import LFPy
import pylab as pl

pl.interactive(1)

cellParameters = {
    'morphology' :  'morphologies/L5_Mainen96_LFPy.hoc',
    'tstopms' :     50, 
}
cell = LFPy.Cell(**cellParameters)

synapseParameters = {
    'idx' : cell.get_closest_idx(x=0, y=0, z=800),
    'e' : 0,                                # reversal potential
    'syntype' : 'ExpSyn',                   # synapse type
    'tau' : 2,                              # syn. time constant
    'weight' : 0.01,                        # syn. weight
    'record_current' : True                 # syn. current record
}
synapse = LFPy.Synapse(cell, **synapseParameters)
synapse.set_spike_times(pl.array([10, 15, 20, 25]))
cell.simulate(rec_isyn=True)

pl.subplot(211)
pl.plot(cell.tvec, synapse.i)
pl.title('Synapse current (nA)')
pl.subplot(212)
pl.plot(cell.tvec, cell.somav)
pl.title('Somatic potential (mV)')
collect_current(cell)

Collect synapse current

collect_potential(cell)

Collect membrane potential of segment with synapse

set_spike_times(sptimes=array([], dtype=float64))

Set the spike times

class StimIntElectrode

class LFPy.StimIntElectrode(cell, idx, pptype='SEClamp', color='p', marker='*', record_current=False, **kwargs)

Bases: LFPy.pointprocess.PointProcess

Class for NEURON point processes, ie VClamp, SEClamp and ICLamp, SinIClamp, ChirpIClamp with arguments. Electrode currents go here. Membrane currents will no longer sum to zero if these mechanisms are used.

Refer to NEURON documentation @ neuron.yale.edu for kwargs

Usage example:

#/usr/bin/python

import LFPy
import pylab as pl

pl.interactive(1)

#define a list of different electrode implementations from NEURON
pointprocesses = [
    {
        'idx' : 0,
        'record_current' : True,
        'pptype' : 'IClamp',
        'amp' : 1,
        'dur' : 20,
        'delay' : 10,
    },
    {
        'idx' : 0,
        'record_current' : True,
        'pptype' : 'VClamp',
        'amp[0]' : -65,
        'dur[0]' : 10,
        'amp[1]' : 0,
        'dur[1]' : 20,
        'amp[2]' : -65,
        'dur[2]' : 10,
    },
    {
        'idx' : 0,
        'record_current' : True,
        'pptype' : 'SEClamp',
        'dur1' : 10,
        'amp1' : -65,
        'dur2' : 20,
        'amp2' : 0,
        'dur3' : 10,
        'amp3' : -65,
    },
]

#create a cell instance for each electrode
for pointprocess in pointprocesses:
    cell = LFPy.Cell(morphology='morphologies/L5_Mainen96_LFPy.hoc')
    stimulus = LFPy.StimIntElectrode(cell, **pointprocess)
    cell.simulate(rec_istim=True)
    
    pl.subplot(211)
    pl.plot(cell.tvec, stimulus.i, label=pointprocess['pptype'])
    pl.legend(loc='best')
    pl.title('Stimulus currents (nA)')
    
    pl.subplot(212)
    pl.plot(cell.tvec, cell.somav, label=pointprocess['pptype'])
    pl.legend(loc='best')
    pl.title('Somatic potential (mV)')
collect_current(cell)

Fetch electrode current from recorder list

collect_potential(cell)

Collect membrane potential of segment with PointProcess

class RecExtElectrodeSetup

class LFPy.RecExtElectrodeSetup(cell=None, sigma=0.3, x=100, y=0, z=0, N=None, r=None, n=None, r_z=None, perCellLFP=False, method='linesource', color='g', marker='o', from_file=False, cellfile=None, verbose=False, seedvalue=None)

RecExtElectrode superclass. If (optional) cell argument is given then the it is imported, otherwise the cell argument has to be passed later on to calc_lfp. The argument cell can be an LFPy.cell.Cell object or either a list or a dictionary containing such Cell objects. Keyword arguments determine properties of later LFP-calculations

Arguments:

sigma   : extracellular conductivity
x, y, z : coordinates or arrays of coordinates. Must be same length
N       : Normal vector [x, y, z] of contact surface, default None
r       : radius of contact surface, default None
n       : if N != None and r > 0, the number of points to use for each
          contact point in order to calculate average
color   : color of electrode contact points in plots
marker  : marker of electrode contact points in plots
from_file   : if True, load cell object from file
cellfile    : path to cell pickle
verbose : Flag for verbose output
seedvalue : fixed seed when finding random position on contact with r >0
class cell

Empty object that cell-specific variables are stored in

class RecExtElectrode

class LFPy.RecExtElectrode(cell=None, sigma=0.3, x=100, y=0, z=0, N=None, r=None, n=0, r_z=None, perCellLFP=False, method='linesource', color='g', marker='o', from_file=False, cellfile=None, verbose=False, seedvalue=12345)

Bases: LFPy.recextelectrode.RecExtElectrodeSetup

RecExtElectrode class with inheritance from LFPy.RecExtElectrodeSetup able to actually calculate local field potentials from LFPy.Cell objects. **kwargs are passed on to LFPy.RecExtElectrodeSetup

Usage:

import LFPy
import pylab as pl

N = pl.empty((16, 3))
for i in xrange(N.shape[0]): N[i,] = [1, 0, 0] #normal unit vec. to contacts
electrodeParameters = {             #parameters for RecExtElectrode class
    'sigma' : 0.3,              #Extracellular potential
    'x' : pl.zeros(16)+25,      #Coordinates of electrode contacts
    'y' : pl.zeros(16),
    'z' : pl.linspace(-500,1000,16),
    'n' : 20,
    'r' : 10,
    'N' : N,
}

cellParameters = {                          
    'morphology' : 'L5_Mainen96_LFPy.hoc',  # morphology file
    'rm' : 30000,                           # membrane resistivity
    'cm' : 1.0,                             # membrane capacitance
    'Ra' : 150,                             # axial resistivity
    'timeres_NEURON' : 2**-4,                # dt for NEURON sim.
    'timeres_python' : 2**-4,                 # dt for python output
    'tstartms' : -50,                         # start t of simulation
    'tstopms' : 50,                        # end t of simulation
}

cell = LFPy.Cell(**cellParameters)

synapseParameters = {
    'idx' : cell.get_closest_idx(x=0, y=0, z=800), # compartment
    'e' : 0,                                # reversal potential
    'syntype' : 'ExpSyn',                   # synapse type
    'tau' : 2,                              # syn. time constant
    'weight' : 0.01,                       # syn. weight
    'record_current' : True                 # syn. current record
}

synapse = LFPy.PointProcessSynapse(cell, **synapseParameters)
synapse.set_spike_times(cell, pl.array([10, 15, 20, 25]))

cell.simulate()

electrode = LFPy.RecExtElectrode(cell, **electrodeParameters)
electrode.calc_lfp()
pl.matshow(electrode.LFP)
calc_lfp(t_indices=None, cell=None)

Calculate LFP on electrode geometry from all cell instances. Will chose distributed calculated if electrode contain ‘n’, ‘N’, and ‘r’

submodule lfpcalc

Copyright (C) 2012 Computational Neuroscience Group, UMB.

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

LFPy.lfpcalc.calc_lfp_choose()

Determine which method to use, line-source for soma default

LFPy.lfpcalc.calc_lfp_linesource()

Calculate electric field potential using the line-source method, all compartments treated as line sources, even soma.

LFPy.lfpcalc.calc_lfp_pointsource()

Calculate local field potentials using the point-source equation on all compartments

LFPy.lfpcalc.calc_lfp_som_as_point()

Calculate electric field potential using the line-source method, soma is treated as point/sphere source

submodule tools

Copyright (C) 2012 Computational Neuroscience Group, UMB.

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

LFPy.tools.load(filename)[source]

Generic loading of cPickled objects from file

LFPy.tools.noise_brown(ncols, nrows=1, weight=1, filter=None, filterargs=None)[source]

Return 1/f^2 noise of shape(nrows, ncols obtained by taking the cumulative sum of gaussian white noise, with rms weight.

If filter != None, this function will apply the filter coefficients obtained by:

>>> b, a = filter(**filterargs)
>>> signal = scipy.signal.lfilter(b, a, signal)

submodule inputgenerators

Copyright (C) 2012 Computational Neuroscience Group, UMB.

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.

LFPy.inputgenerators.get_normal_input_times(n, mu, sigma, tstart, tstop)[source]

Generates n normal-distributed prosesses with mean mu and deviation sigma

LFPy.inputgenerators.get_normal_spike_times(nsyn, mu, sigma, tstart, tstop)[source]

Generate nsyn normal-distributed processes with mean mu and deviation sigma

LFPy.inputgenerators.get_rand_spike_times(synpos, nspikes, tstart, tstop)[source]

Return synpos times nspikes random spike times on the interval [tstart, tstop]

LFPy.inputgenerators.stationary_gamma(tstart, tstop, k=2, theta=10, tmin=-1000.0, tmax=100000.0)[source]

Generate spiketimes with interspike interval statistics according to gamma-distribution with ‘shape’ k and ‘scale’ theta between tstart and tstop. Spiketimes from tmin up to tmax is calculated, times between 0 and tstop are returned

LFPy.inputgenerators.stationary_poisson(nsyn, lambd, tstart, tstop)[source]

Generate nsyn stationary possion processes with rate lambda between tstart and tstop

LFPy.inputgenerators.test_spiketimes(spiketime)[source]

Test and sort spike times

submodule run_simulation

Copyright (C) 2012 Computational Neuroscience Group, UMB.

This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.

This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details.