cnmodel.util package

Utility routines used within cnmodel

cnmodel.util.Params

class cnmodel.util.Params.ParamTests(methodName='runTest')[source]

Bases: unittest.case.TestCase

Create an instance of the class that will use the named test method when executed. Raises a ValueError if the instance does not have a method with the specified name.

setUp()[source]
class cnmodel.util.Params.Params(**kwds)[source]

Bases: object

Utility class to create parameter lists create using: p = Params(abc=2.0, defg = 3.0, lunch=’sandwich’) reference using: p.abc, p.defg, etc. Supports getting the keys, finding whether a key exists, returning the strucure as a simple dictionary, and printing (show) the parameter structure.

additem(key, value)[source]
getkeys()[source]

Get the keys in the current dictionary

haskey(key)[source]

Find out if the param list has a specific key in it

show(printFlag=True)[source]

print the parameter block created in Parameter Init

todict()[source]

convert param list to standard dictionary Useful when writing the data

cnmodel.util.ccstim

cnmodel.util.ccstim.ccstim(stim, dt, pulsetype='square')[source]

Create stimulus pulse waveforms of different types.

Parameters:
  • stim (dict) – a dictionary with keys [required] delay (delay to start of pulse train, msec [all] duration: duration of pulses in train, msec [all] Sfreq: stimulus train frequency (Hz) [timedSpikes] PT: post-train test delay [all] NP: number of pulses in the train [timedSpikes, exp] amp: amplitude of the pulses in the train [all] hypamp: amplitude of prehyperpolarizing pulse [hyp] hypdur: duration of prehyperpolarizing pulse [hyp] spikeTimes” times of spikes [timedSpikes]
  • dt (time (microseconds) [required]) – step time, in microseconds. Required parameter
  • pulsetype (string (default: 'square')) – Type of pulse to generate: one of square, hyp, timedspikes or exp square produces a train of “square” (retangular) pulses levels 0 and ampitude hyp is like square, but precedes the pulse train with a single prepulse of hypamp and hypdur timedspikes is like square, excpet the pulses are generated at times specified in the spikeTimes key in the stim dictionary exp: pulses with an exponential decay.
  • DO (TO) – add pulsetypes, including sine wave, rectified sine wave, etc.
Returns:

maxtime(float), timebase (numpy array)]

Return type:

list containing [waveform (numpy array),

cnmodel.util.expfitting

expfitting.py Provide single or double exponential fits to data.

class cnmodel.util.expfitting.ExpFitting(nexp=1, initpars=None, bounds=None)[source]
Parameters:
  • nexp (int) – 1 or 2 for single or double exponential fit
  • initpars (dict) – dict of initial parameters. For example: {‘dc’: 0., ‘a1’: 1., ‘t1’: 3, ‘a2’ : 0.5, ‘delta’: 3.}, where delta determines the ratio between the time constants.
  • bounds (dict) – dictionary of bounds for each parameter, with a list of lower and upper values.
static exp1(x, dc, t1, a1)[source]
exp1_err(p, x, y)[source]
static exp2(x, dc, t1, a1, a2, delta)[source]
exp2_err(p, x, y)[source]
fit(x, y, p, verbose=False)[source]

cnmodel.util.filelock

class cnmodel.util.filelock.FileLock(file_name, timeout=10, delay=0.05)[source]

Bases: object

A file locking mechanism that has context-manager support so you can use it in a with statement. This should be relatively cross compatible as it doesn’t rely on msvcrt or fcntl for the locking.

Prepare the file locker. Specify the file to lock and optionally the maximum timeout and the delay between each attempt to lock.

acquire()[source]

Acquire the lock, if possible. If the lock is in use, it check again every wait seconds. It does this until it either gets the lock or exceeds timeout number of seconds, in which case it throws an exception.

lock_count = {}
lock_handles = {}
release()[source]

Get rid of the lock by deleting the lockfile. When working in a with statement, this gets automatically called at the end.

exception cnmodel.util.filelock.FileLockException[source]

Bases: exceptions.Exception

cnmodel.util.find_point

cnmodel.util.find_point.find_crossing(data, start=0, direction=1, threshold=0)[source]

Return the index at which data crosses threshold, starting at index start and proceeding in direction (+/-1).

The value returned is a float indicating the interpolated index position where the data crosses threshold, or NaN if the threshold was never crossed.

cnmodel.util.find_point.find_point(x, y, peakindex, val, direction='left', limits=None)[source]

Given a waveform defined by x and y arrays, return the first time at which the waveform crosses (y[peakindex] * val). The search begins at peakindex and proceeds in direction.

Optionally, limits may specify a smaller search region in the form of (t0, t1, dt).

cnmodel.util.fitting

cnmodel.util.get_anspikes

class cnmodel.util.get_anspikes.ManageANSpikes[source]

ManageANSpikes is a class to read the output of the Zilany et al. 2009 AN model into python, and provides services to access that data.

Basic usage is to create an instance of the class, and specify the data directory if necessary.

You may then get the data in the format of a list using one of the “get” routines. The data is pulled from the nearest CF or the specified CF.

combine_reps(spkl)[source]

Just turns the spike list into one big linear sequence. :param spkl: a spike train (nreps of numpy arrays) :return: all the spikes in one long array.

display(spkl, k, n, mg)[source]
flatten(sequence) → list[source]

Returns a single, flat list which contains all elements retrieved from the sequence and all recursively contained sub-sequences (iterables).

getANatFandSPL(spontclass='MS', freq=10000.0, CF=None, SPL=0)[source]

Get the AN data at a particular frequency and SPL. Note that the tone freq is specified, but the CF of the fiber might be different. If CF is None, we try to get the closest fiber data to the tone Freq. Other arguments are the spontaneous rate and the SPL level. The data must exist, or we epically fail.

Parameters:
  • spontclass – ‘HS’, ‘MS’, or ‘LS’ for high, middle or low spont groups (1,2,3 in Zilany et al model)
  • freq – The stimulus frequency, in Hz
  • CF – The ‘characteristic frequency’ of the desired AN fiber, in Hz
  • SPL – The sound pressure level, in dB SPL for the stimulus
Returns:

an array of nReps of spike times.

getANatSPL(spl=None)[source]
get_AN_at_SPL(spl=None)[source]

grabs the AN data for the requested SPL for the data set currently loaded The data must exist, or we epically fail.

Parameters:spl – sound pressure level, in dB SPL
Returns:spike trains (times) as a list of nReps numpy arrays.
get_AN_info()[source]
Returns:Dictionary of nReps and SPLs that are in the current data set (instance).
get_CF_map()[source]
get_dataType()[source]
get_data_dir()[source]
get_data_read()[source]
make_fig()[source]
plot_RI_vs_F(freq=10000.0, spontclass='HS', display=False)[source]
plot_Rate_vs_F(freq=10000.0, spontclass='HS', display=False, SPL=0.0)[source]

assumes we have done a “read all”

Parameters:
  • freq
  • spontclass
  • display
  • SPL
Returns:

read_AN_data(freq=10000, CF=5300, spontclass='HS', display=False, stim='BFTone', setflag=True, ignoreflag=True)[source]

read responses of auditory nerve model of Zilany et al. (2009). display = True plots the psth’s for all ANF channels in the dataset Request response to stimulus at Freq, for fiber with CF and specified spont rate This version is for rate-intensity runs March 2014. Returns: Nothing

read_all_ANdata(freq=10000.0, CFList=None, spontclass='HS', stim='BFTone')[source]

Reads a bank of AN data, across frequency and intensity, for a given stimulus frequency Assumptions: the bank of data is consistent in terms of nReps and SPLs

Parameters:
  • freq – Tone stimulus frequency (if stim is Tone or BFTone)
  • CFList – A list of the CFs to read
  • spontclass – ‘HS’, ‘MS’, or ‘LS’, corresponding to spont rate groups
  • stim – Stimulus type - Tone/BFTone, or Noise
Returns:

Nothing. The data are stored in an array accessible directly or through a selector function

read_cmrr_data(P, signal='S0', display=False)[source]

read responses of auditory nerve model of Zilany et al. (2009). The required parameters are passed via the class P. This includes:

the SN (s2m) is the signal-to-masker ratio to select the mode is ‘CMR’, ‘CMD’ (deviant) or ‘REF’ (reference, no flanking bands), ‘Tone’, or ‘Noise’ the Spont rate group

signal is either ‘S0’ (signal present) or ‘NS’ (no signal) display = True plots the psth’s for all ANF channels in the dataset Returns: tuple of (spikelist and frequency list for modulated tones)

retrieve_from_all_AN(cf, SPL)[source]
Parameters:
  • cf
  • SPL
Returns:

spike list (all nreps) at the cf and SPL requested, for the loaded stimulus set

set_CF_map(low, high, nfreq)[source]
set_dataType(datatype)[source]
set_data_dir(directory)[source]

cnmodel.util.matlab_proc

Simple system for interfacing with a MATLAB process using stdin/stdout pipes.

exception cnmodel.util.matlab_proc.MatlabError(error, output)[source]

Bases: exceptions.Exception

class cnmodel.util.matlab_proc.MatlabFunction(proc, name)[source]

Bases: object

Proxy to a MATLAB function.

Calling this object transfers the arguments to MATLAB, invokes the function remotely, and then transfers the return value back to Python.

nargout

Number of output arguments for this function.

For some functions, requesting nargout() will fail. In these cases, the nargout property must be set manually before calling the function.

class cnmodel.util.matlab_proc.MatlabProcess(executable=None, **kwds)[source]

Bases: object

This class starts a new matlab process, allowing remote control of the interpreter and transfer of data between python and matlab.

close()[source]
exist(name)[source]
class cnmodel.util.matlab_proc.MatlabReference(proc, name)[source]

Bases: object

Reference to a variable in the matlab workspace.

clear()[source]
get()[source]
name

cnmodel.util.nrnutils

Wrapper classes to make working with NEURON easier.

Author: Andrew P. Davison, UNIC, CNRS

class cnmodel.util.nrnutils.Mechanism(name, **parameters)[source]

Bases: object

Examples: >>> leak = Mechanism(‘pas’, {‘e’: -65, ‘g’: 0.0002}) >>> hh = Mechanism(‘hh’) added set_parameters to allow post-instantiation parameter modification

insert_into(section)[source]
set_parameters(parameters)[source]
cnmodel.util.nrnutils.alias(attribute_path)[source]

Returns a new property, mapping an attribute nested in an object hierarchy to a simpler name

For example, suppose that an object of class A has an attribute b which itself has an attribute c which itself has an attribute d. Then placing e = alias(‘b.c.d’) in the class definition of A makes A.e an alias for A.b.c.d

cnmodel.util.nrnutils.uniform_property(section_list, attribute_path)[source]

Define a property that will have a uniform value across a list of sections.

For example, suppose we define a neuron model as a class A, which contains three compartments: soma, dendrite and axon. Then placing

gnabar = uniform_property([“soma”, “axon”], “hh.gnabar”)

in the class definition of A means that setting a.gnabar (where a is an instance of A) will set the value of hh.gnabar in both the soma and axon, i.e.

a.gnabar = 0.01

is equivalent to:

for sec in [a.soma, a.axon]:
for seg in sec:
seg.hh.gnabar = 0.01

cnmodel.util.process

Utility class for spawning and controlling CLI processes. See: http://stackoverflow.com/questions/375427/non-blocking-read-on-a-subprocess-pipe-in-python

class cnmodel.util.process.PipePrinter(pipe)[source]

Bases: object

For debugging writes to a pipe.

write(strn)[source]
class cnmodel.util.process.PipeQueue(pipe)[source]

Bases: Queue.Queue

Queue that starts a second process to monitor a PIPE for new data. This is needed to allow non-blocking pipe reads.

static enqueue_output(out, queue)[source]
read()[source]

Read all available lines from the queue, concatenated into a single string.

readline(timeout=None)[source]

Read a single line from the queue.

class cnmodel.util.process.Process(exec_args, cwd=None)[source]

Bases: object

Process encapsulates a subprocess with queued stderr/stdout pipes. Wraps most methods from subprocess.Popen.

For non-blocking reads, use proc.stdout.get_nowait() or proc.stdout.get(timeout=0.1).

cnmodel.util.pynrnutilities

cnmodel.util.pynrnutilities.all_mechanism_types()[source]

Return a dictionary of all available mechanism types.

Each dictionary key is the name of a mechanism and each value is another dictionary containing information about the mechanism:

mechanism_types = {
    'mech_name1': {
        'point_process': bool,
        'artificial_cell': bool,
        'netcon_target': bool,
        'has_netevent': bool,
        'internal_type': int,
        'globals': {name:size, ...},
        'parameters': {name:size, ...},
        'assigned': {name:size, ...},
        'state': {name:size, ...},
    },
    'mech_name2': {...},
    'mech_name3': {...},
    ...
}
  • point_process: False for distributed mechanisms, True for point
    processes and artificial cells.
  • artificial_cell: True for artificial cells, False otherwise
  • netcon_target: True if the mechanism can receive NetCon events
  • has_netevent: True if the mechanism can emit NetCon events
  • internal_type: Integer specifying the NEURON internal type index of
    the mechanism
  • globals: dict of the name and vector size of the mechanism’s global
    variables
  • parameters: dict of the name and vector size of the mechanism’s
    parameter variables
  • assigned: dict of the name and vector size of the mechanism’s
    assigned variables
  • state: dict of the name and vector size of the mechanism’s state
    variables

Note: The returned data structure is cached; do not modify it.

For more information on global, parameter, assigned, and state variables see: http://www.neuron.yale.edu/neuron/static/docs/help/neuron/nmodl/nmodl.html

cnmodel.util.pynrnutilities.all_objects()[source]

Return a dict of all objects known to NEURON.

Keys are ‘Section’, ‘Segment’, ‘Mechanism’, ‘Vector’, ‘PointProcess’, ‘NetCon’, …

cnmodel.util.pynrnutilities.alpha(alpha=0.1, delay=1, amp=1.0, tdur=50.0, dt=0.01)[source]
cnmodel.util.pynrnutilities.an_syn(alpha=0.1, spont=10, driven=100, delay=50, dur=100, post=20, amp=0.1, dt=0.02, N=1, makewave=True)[source]
cnmodel.util.pynrnutilities.custom_init(v_init=-60.0)[source]

Perform a custom initialization of the current model/section.

This initialization follows the scheme outlined in the NEURON book, 8.4.2, p 197 for initializing to steady state.

N.B.: For a complex model with dendrites/axons and different channels, this initialization will not find the steady-state the whole cell, leading to initial transient currents. In that case, this initialization should be followed with a 0.1-5 second run (depends on the rates in the various channel mechanisms) with no current injection or active point processes to allow the system to settle to a steady- state. Use either h.svstate or h.batch_save to save states and restore them. Batch is preferred

Parameters:v_init (float (default: -60 mV)) – Voltage to start the initialization process. This should be close to the expected resting state.
cnmodel.util.pynrnutilities.findspikes(t, v, thresh)[source]

findspikes identifies the times of action potential in the trace v, with the times in t. An action potential is simply timed at the first point that exceeds the threshold.

cnmodel.util.pynrnutilities.get_sections(h)[source]

go through all the sections and find the names of the sections and all of their parts (ids). Returns a dict, of sec: [id0, id1…]

cnmodel.util.pynrnutilities.isi_cv(splist, binwidth=1, t0=0, t1=300, tgrace=25)[source]

compute the cv and regularity according to Young et al., J. Neurophys, 60: 1, 1988. Analysis is limited to isi’s starting at or after t0 but before t1, and ending completely before t1 + tgrace(to avoid end effects). t1 should correspond to the the end of the stimulus Version using a list of numpy arrays for cvisi

cnmodel.util.pynrnutilities.isi_cv2(splist, binwidth=1, t0=0, t1=300, tgrace=25)[source]

compute the cv and regularity according to Young et al., J. Neurophys, 60: 1, 1988. Analysis is limited to isi’s starting at or after t0 but before t1, and ending completely before t1 + tgrace(to avoid end effects). t1 should correspond to the the end of the stimulus VERSION using dictionary for cvisi

cnmodel.util.pynrnutilities.mask(x, xm, x0, x1)[source]
cnmodel.util.pynrnutilities.measure(mode, x, y, x0, x1)[source]

return the mean and standard deviation of y in the window x0 to x1

cnmodel.util.pynrnutilities.mho2ns(mho, somaarea)[source]
cnmodel.util.pynrnutilities.nstomho(ns, somaarea, refarea=None)[source]
cnmodel.util.pynrnutilities.reset(raiseError=True)[source]

Introspect the NEURON kernel to verify that no objects are left over from previous simulation runs.

cnmodel.util.pynrnutilities.spherearea(dia)[source]

given diameter in microns, return sphere area in cm2

cnmodel.util.pynrnutilities.syns(alpha=0.1, rate=10, delay=0, dur=50, amp=1.0, dt=0.02, N=1, mindur=120, makewave=True)[source]

Calculate a poisson train of alpha waves with mean rate rate, with a delay and duration (in mseco) dt in msec. N specifies the number of such independent waveforms to sum

cnmodel.util.pynrnutilities.vector_strength(spikes, freq)[source]

Calculate vector strength and related parameters from a spike train, for the specified frequency :param spikes: Spike train, in msec. :param freq: Stimulus frequency in Hz :return: a dictionary containing:

r: vector strength n: number of spikes R: Rayleigh coefficient p: p value (is distribution not flat?) ph: the circularized spike train over period of the stimulus freq, freq, in radians d: the “dispersion” computed according to Ashida et al., 2010, etc.

cnmodel.util.random_seed

cnmodel.util.random_seed.current_seed()[source]

Return the currently-set global random seed.

cnmodel.util.random_seed.set_seed(seed)[source]

Set the random seed to be used globally. If a string is supplied, it will be converted to int using hash().

This immediately seeds the numpy RNG. Any other RNGs must be seeded using current_seed()

cnmodel.util.sound

Tools for generating auditory stimuli.

class cnmodel.util.sound.ClickTrain(**kwds)[source]

Bases: cnmodel.util.sound.Sound

One or more clicks (rectangular pulses).

Parameters:
  • rate (float) – Sample rate in Hz
  • dbspl (float) – Maximum amplitude of click in dB SPL.
  • click_duration (float) – Duration of each click including ramp time. Must be at least 1/rate.
  • click_starts (array-like) – Start times of each click
generate()[source]
class cnmodel.util.sound.FMSweep(**kwds)[source]

Bases: cnmodel.util.sound.Sound

Create an FM sweep with either linear or logarithmic rates, of a specified duration between two frequencies.

Parameters:
  • rate (float) – Sample rate in Hz
  • duration (float) – Total duration of the sweep
  • start (float) – t times of each pip
  • freqs (list) – [f0, f1]: the start and stop times for the sweep
  • ramp (string) – valid input for type of sweep (linear, logarithmic, etc)
  • dbspl (float) – Maximum amplitude of pip in dB SPL.
generate()[source]

Call to actually compute the the FM sweep

Returns:generated waveform
Return type:array
class cnmodel.util.sound.NoisePip(**kwds)[source]

Bases: cnmodel.util.sound.Sound

One or more noise pips with cosine-ramped edges.

Parameters:
  • rate (float) – Sample rate in Hz
  • duration (float) – Total duration of the sound
  • seed (int >= 0) – Random seed
  • dbspl (float) – Maximum amplitude of tone in dB SPL.
  • pip_duration (float) – Duration of each pip including ramp time. Must be at least 2 * ramp_duration.
  • pip_start (array-like) – Start times of each pip
  • ramp_duration (float) – Duration of a single ramp period (from minimum to maximum). This may not be more than half of pip_duration.
generate()[source]

Call to compute the noise pips

Returns:generated waveform
Return type:array
class cnmodel.util.sound.ReadWavefile(wavefile, rate, channel=0, dbspl=None, scale=None, delay=0.0, maxdur=None)[source]

Bases: cnmodel.util.sound.Sound

Read a .wav file from disk, possibly converting the sample rate and the scale for use in driving the auditory nerve fiber model.

Parameters:
  • wavefile (str) – name of the .wav file to read
  • rate (float) – Sample rate in Hz (waveform will be resampled to this rate)
  • channel (int (default: 0)) – If wavefile has 2 channels, select 0 or 1 for the channel to read
  • dbspl (float or None) – If specified, the wave file is scaled such that its overall dBSPL (measured from RMS of the entire waveform) is equal to this value. Either dbspl or scale must be specified.
  • scale (float or None) – If specified, the wave data is multiplied by this value to yield values in dBSPL. Either dbspl or scale must be specified.
  • delay (float (default: 0.)) – Silent delay time to start sound, in s. Allows anmodel and cells to run to steady-state
  • maxdur (float or None (default: None)) – If specified, maxdur defines the total duration of generated waveform to return (in seconds). If None, the generated waveform duration will be the sum of any delay value and the duration of the waveform from the wavefile.
Returns:

waveform

Return type:

array

generate()[source]

Read the wave file from disk, clip duration, resample if necessary, and scale

Returns:array
Return type:generated waveform
class cnmodel.util.sound.SAMNoise(**kwds)[source]

Bases: cnmodel.util.sound.Sound

One or more gaussian noise pips with cosine-ramped edges, sinusoidally modulated.

Parameters:
  • rate (float) – Sample rate in Hz
  • duration (float) – Total duration of the sound
  • seed (int >= 0) – Random seed
  • dbspl (float) – Maximum amplitude of pip in dB SPL.
  • pip_duration (float) – Duration of each pip including ramp time. Must be at least 2 * ramp_duration.
  • pip_start (array-like) – Start times of each pip
  • ramp_duration (float) – Duration of a single ramp period (from minimum to maximum). This may not be more than half of pip_duration.
  • fmod (float) – SAM modulation frequency
  • dmod (float) – Modulation depth
Returns:

waveform

Return type:

array

generate()[source]
class cnmodel.util.sound.SAMTone(**kwds)[source]

Bases: cnmodel.util.sound.Sound

SAM tones with cosine-ramped edges.

Parameters:
  • rate (float) – Sample rate in Hz
  • duration (float) – Total duration of the sound
  • f0 (float or array-like) – Tone frequency in Hz. Must be less than half of the sample rate.
  • dbspl (float) – Maximum amplitude of tone in dB SPL.
  • pip_duration (float) – Duration of each pip including ramp time. Must be at least 2 * ramp_duration.
  • pip_start (array-like) – Start times of each pip
  • ramp_duration (float) – Duration of a single ramp period (from minimum to maximum). This may not be more than half of pip_duration.
  • fmod (float) – SAM modulation frequency, Hz
  • dmod (float) – Modulation depth, %
generate()[source]

Call to compute a SAM tone

Returns:generated waveform
Return type:array
class cnmodel.util.sound.Sound(duration, rate=100000.0, **kwds)[source]

Bases: object

Base class for all sound stimulus generators.

Parameters:
  • duration (float (no default):) – duration of the stimulus, in seconds
  • rate (float (default: 100000.)) – sample rate for sound generation
dt

float – the sample period (time step between samples).

duration

float – The duration of the sound

generate()[source]

Generate and return the sound output. This method is defined by subclasses.

key()[source]

The sound can be recreated using create(**key). dict: Return dict of parameters needed to completely describe this sound.

measure_dbspl(tstart, tend)[source]

Measure the sound pressure for the waveform in a window of time

Parameters:
  • tstart – time to start spl measurement (seconds).
  • tend – ending time for spl measurement (seconds).
Returns:

float

Return type:

The measured amplitude (dBSPL) of the sound from tstart to tend

num_samples

int – The number of samples in the sound array.

sound

array – The generated sound array, expressed in Pascals.

time

array – The array of time values, expressed in seconds.

class cnmodel.util.sound.TonePip(**kwds)[source]

Bases: cnmodel.util.sound.Sound

Create one or more tone pips with cosine-ramped edges.

Parameters:
  • rate (float) – Sample rate in Hz
  • duration (float) – Total duration of the sound
  • f0 (float or array-like) – Tone frequency in Hz. Must be less than half of the sample rate.
  • dbspl (float) – Maximum amplitude of tone in dB SPL.
  • pip_duration (float) – Duration of each pip including ramp time. Must be at least 2 * ramp_duration.
  • pip_start (array-like) – Start times of each pip
  • ramp_duration (float) – Duration of a single ramp period (from minimum to maximum). This may not be more than half of pip_duration.
generate()[source]

Call to compute the tone pips

Returns:generated waveform
Return type:array
cnmodel.util.sound.clicks(t, Fs, dBSPL, click_duration, click_starts)[source]

Create a waveform with multiple retangular clicks. Output is in Pascals.

Parameters:
  • t (array) – array of time values
  • Fs (float) – sample frequency (Hz)
  • click_start (float (seconds)) – delay to first click in train
  • click_duration (float (seconds)) – duration of each click
  • click_interval (float (seconds)) – interval between click starts
  • nclicks (int) – number of clicks in the click train
  • dspl (float) – maximum sound pressure level of pip
Returns:

waveform

Return type:

array

cnmodel.util.sound.create(type, **kwds)[source]

Create a Sound instance using a key returned by Sound.key().

cnmodel.util.sound.dbspl_to_pa(dbspl, ref=2e-05)[source]

Convert dBSPL to Pascals (rms). By default, the reference pressure is 20 uPa.

cnmodel.util.sound.fmsweep(t, start, duration, freqs, ramp, dBSPL)[source]

Create a waveform for an FM sweep over time. Output is in Pascals.

Parameters:
  • t (array) – time array for waveform
  • start (float (seconds)) – start time for sweep
  • duration (float (seconds)) – duration of sweep
  • freqs (array (Hz)) – Two-element array specifying the start and end frequency of the sweep
  • ramp (str) – The shape of time course of the sweep (linear, logarithmic)
  • dBSPL (float) – maximum sound pressure level of sweep
Returns:

waveform

Return type:

array

cnmodel.util.sound.linearramp(pin, mxpts, irpts)[source]

Apply linear ramps to pin.

Parameters:
  • pin (array) – input waveform to apply ramp to
  • mxpts (int) – point in array to start ramp down
  • irpts (int) – duration of the ramp
Returns:

waveform

Return type:

array

Original (adapted from Manis; makeANF_CF_RI.m):

function [out] = ramp(pin, mxpts, irpts)
    out = pin;
    out(1:irpts)=pin(1:irpts).*(0:(irpts-1))/irpts;
    out((mxpts-irpts):mxpts)=pin((mxpts-irpts):mxpts).*(irpts:-1:0)/irpts;
    return;
end
cnmodel.util.sound.modnoise(t, rt, Fs, F0, dur, start, dBSPL, FMod, DMod, phaseshift, seed)[source]

Generate an amplitude-modulated noise with linear ramps.

Parameters:
  • t (array) – array of waveform time values
  • rt (float) – ramp duration
  • Fs (float) – sample rate
  • F0 (float) – tone frequency
  • dur (float) – duration of noise
  • start (float) – start time for noise
  • dBSPL (float) – sound pressure of stimulus
  • FMod (float) – modulation frequency
  • DMod (float) – modulation depth percent
  • phaseshift (float) – modulation phase
  • seed (int) – seed for random number generator
Returns:

waveform

Return type:

array

cnmodel.util.sound.pa_to_dbspl(pa, ref=2e-05)[source]

Convert Pascals (rms) to dBSPL. By default, the reference pressure is 20 uPa.

cnmodel.util.sound.pipnoise(t, rt, Fs, dBSPL, pip_dur, pip_start, seed)[source]

Create a waveform with multiple sine-ramped noise pips. Output is in Pascals.

Parameters:
  • t (array) – array of time values
  • rt (float) – ramp duration
  • Fs (float) – sample rate
  • dBSPL (float) – maximum sound pressure level of pip
  • pip_dur (float) – duration of pip including ramps
  • pip_start (float) – list of starting times for multiple pips
  • seed (int) – random seed
Returns:

waveform

Return type:

array

cnmodel.util.sound.piptone(t, rt, Fs, F0, dBSPL, pip_dur, pip_start)[source]

Create a waveform with multiple sine-ramped tone pips. Output is in Pascals.

Parameters:
  • t (array) – array of time values
  • rt (float) – ramp duration
  • Fs (float) – sample rate
  • F0 (float) – pip frequency
  • dBSPL (float) – maximum sound pressure level of pip
  • pip_dur (float) – duration of pip including ramps
  • pip_start (float) – list of starting times for multiple pips
Returns:

waveform

Return type:

array

cnmodel.util.sound.sinusoidal_modulation(t, basestim, tstart, fmod, dmod, phaseshift)[source]

Impose a sinusoidal amplitude-modulation on the input waveform. For dmod=100%, the envelope max is 2, the min is 0; for dmod = 0, the max and min are 1 maintains equal energy for all modulation depths. Equation from Rhode and Greenberg, J. Neurophys, 1994 (adding missing parenthesis) and Sayles et al. J. Physiol. 2013 The envelope can be phase shifted (useful for co-deviant stimuli).

Parameters:
  • t (array) – array of waveform time values (seconds)
  • basestim (array) – array of waveform values that will be subject to sinulsoidal envelope modulation
  • tstart (float) – time at which the base sound starts (modulation starts then, with 0 phase crossing) (seconds)
  • fmod (float) – modulation frequency (Hz)
  • dmod (float) – modulation depth (percent)
  • phaseshift (float) – modulation phase shift (starting phase, radians)

cnmodel.util.stim

cnmodel.util.stim.make_pulse(stim)[source]

Generate a pulse train for current / voltage command. Returns a tuple.

Parameters:stim (dict) –

Holds parameters that determine stimulus shape:

  • delay : time before first pulse
  • Sfreq : frequency of pulses
  • dur : duration of one pulse or main pulse
  • predur : duration of prepulse (default should be 0 for no prepulse)
  • amp : pulse amplitude
  • preamp : amplitude of prepulse
  • PT : delay between end of train and test pulse (0 for no test)
  • NP : number of pulses
  • hold : holding level (optional)
  • dt : timestep
Returns:
  • w (stimulus waveform)
  • maxt (duration of waveform)
  • tstims (index of each pulse in the train)

cnmodel.util.user_tester

class cnmodel.util.user_tester.UserTester(key, *args, **kwds)[source]

Bases: object

Base class for testing when a human is required to verify the results.

When a test is passed by the user, its output is saved and used as a basis for future tests. If future test results do not match the stored results, then the user is asked to decide whether to fail the test, or pass the test and store new results.

Subclasses must reimplement run_test() to return a dictionary of results to store. Optionally, compare_results and audit_result may also be reimplemented to customize the testing behavior.

By default, test results are stored in a ‘test_data’ directory relative to the file that defines the UserTester subclass in use.

Initialize with a string key that provides a short, unique description of this test. All other arguments are passed to run_test().

key is used to determine the file name for storing test results.

assert_test_info(*args, **kwds)[source]

Test cell and raise exception if the results do not match prior data.

audit_result(info, expect)[source]

Display results and ask the user to decide whether the test passed. Return True for pass, False for fail.

If expect is None, then no previous test results were stored.

compare_results(info, expect)[source]

Compare result of the current test against the previously stored result expect. If expect is None, then no previous result was stored.

If result and expect do not match, then raise an exception.

data_dir = 'test_data'
load_test_result()[source]

Load prior test results for self.key. If there are no prior results, return None.

result_file()[source]

Return a file name to be used for storing / retrieving test results given self.key.

run_test(*args, **kwds)[source]

Exceute the test. All arguments are taken from __init__. Return a picklable dictionary of test results.

save_test_result(result)[source]

Store test results for self.key. Th e*result* argument must be picklable.