nept Modules

The nept modules are used for the analysis of neural electrophysiological recording data and associated behaviors.

nept.co_occurrence module

nept.co_occurrence.bool_counts(count_matrix, min_spikes=1)[source]

Converts count matrix to boolean of whether bin active or not

Parameters:

count_matrix : np.array

num_neurons by num_bins

min_spikes : int

Minimum number of spikes in a bin for that bin to be considered active. The defaule is set to 1.

Returns:

activity_matrix : np.array

num_neurons by num_bins, boolean (1 or 0)

nept.co_occurrence.compute_cooccur(count_matrix, tetrode_mask, num_shuffles=10000)[source]

Computes the probabilities for co-occurrence

Parameters:

count_matrix : np.array

num_neurons by num_bins

tetrode_mask : np.array

n_neurons by n_neurons. Boolean of True (same tetrode) or False (different tetrode)

Returns:

prob_active : np.array

prob_expected : ap.array

prob_observed : ap.array

prob_zscore : np.array

nept.co_occurrence.expected_cooccur(prob_active, tetrode_mask)[source]

Expected co-occurrence, multiply single cell probabilities

Parameters:

prob_active : np.array

Fraction of bins each cell participates in individually

tetrode_mask : np.array

n_neurons by n_neurons. Boolean of True (same tetrode) or False (different tetrode).

Returns:

prob_expected : np.array

\[p(x|y)\]
nept.co_occurrence.get_tetrode_mask(spikes)[source]
nept.co_occurrence.observed_cooccur(activity_matrix, tetrode_mask)[source]

Observed co-occurrences

Parameters:

activity_matrix : np.array

num_neurons by num_bins, boolean (1 or 0)

tetrode_mask : np.array

n_neurons by n_neurons. Boolean of True (same tetrode) or False (different tetrode).

Returns:

prob_observed : np.array

\[p(x,y)\]
nept.co_occurrence.prob_active_neuron(activity_matrix)[source]

Get expected co-occurrence under independence assumption

Parameters:

activity_matrix : np.array

num_neurons by num_bins, boolean (1 or 0)

Returns:

prob_active : np.array

Fraction of bins each cell participates in individually

nept.co_occurrence.shuffle_cooccur(activity_matrix, num_shuffles)[source]

Compute shuffle matrices from experimental observations

Parameters:

activity_matrix : np.array

num_neurons by num_bins, boolean (1 or 0)

num_shuffle : int

Number of times to shuffle the activity matrix.

Returns:

prob_shuffle : np.array

nept.co_occurrence.spike_counts(spikes, epochs, window=None)[source]

Get spike counts for specific interval.

Parameters:

spikes : list

Containing nept.SpikeTrain for each neuron.

interval_times : nept.Epoch

window : float

When window is set, takes the spike times for this window length around the center of the interval times. The default is set to None. Suggested window size is 0.1.

Returns:

count_matrix : np.array

num_neurons x num_bins

nept.co_occurrence.vector_from_array(array)[source]

Get triangle of output in vector from a correlation-type array

Parameters:array : np.array
Returns:vector (np.array)

Notes

Old Matlab code indexes by column (aka.Fortran-style), so to get the indices of the top triangle, we have to do some reshaping. Otherwise, if the vector made up by rows is OK, then simply : triangle = np.triu_indices(array.size, k=1), out = array[triangle]

nept.co_occurrence.zscore_cooccur(prob_observed, prob_shuffle)[source]

Compare co-occurrence observed probabilities with shuffle

Parameters:

prob_observed : np.array

prob_shuffle : np.array

Returns:

prob_zscore : np.array

nept.decoding module

nept.decoding.bayesian_prob(counts, tuning_curves, binsize, min_neurons, min_spikes)[source]

Computes the bayesian probability of location based on spike counts.

Parameters:

counts : nept.AnalogSignal

Where each inner array is the number of spikes (int) in each bin for an individual neuron.

tuning_curves : np.array

Where each inner array is the tuning curve (floats) for an individual neuron.

binsize : float

Size of the time bins.

min_neurons : int

Mininum number of neurons active in a given bin.

min_spikes : int

Mininum number of spikes in a given bin.

Returns:

prob : np.array

Where each inner array is the probability (floats) for an individual neuron by location bins.

Notes

If a bin does not meet the min_neuron/min_spikes requirement, that bin’s probability is set to nan. To convert it to 0s instead, use : prob[np.isnan(prob)] = 0 on the output.

nept.decoding.decode_location(likelihood, pos_centers, time_centers)[source]

Finds the decoded location based on the centers of the position bins.

Parameters:

likelihood : np.array

With shape(n_timebins, n_positionbins)

pos_centers : np.array

time_centers : np.array

Returns:

decoded : nept.Position

Estimate of decoded position.

nept.decoding.remove_teleports(position, speed_thresh, min_length)[source]

Removes positions above a certain speed threshold

Parameters:

position : nept.Position

speed_thresh : int

Maximum speed to consider natural rat movements. Anything above this theshold will not be included in the filtered positions.

min_length : int

Minimum length for a sequence to be included in filtered positions.

Returns:

filtered_position : nept.Epoch

nept.lfp_filtering module

nept.lfp_filtering.butter_bandpass(signal, thresh, fs, order=4)[source]

Filters signal using butterworth filter

Parameters:

signal : nept.LFP

fs : int

Eg. 2000. Should get this from experiment-specifics.

thresh : tuple

With format (lowcut, highcut). Typically (140.0, 250.0) for sharp-wave ripple detection.

order : int

Default set to 4.

Returns:

filtered_butter : np.array

nept.lfp_filtering.detect_swr_hilbert(lfp, fs, thresh, z_thresh=3, power_thresh=3, merge_thresh=0.02, min_length=0.01)[source]

Finds sharp-wave ripple (SWR) times and indices.

Parameters:

lfp : nept.LocalFieldPotential

fs : int

Experiment-specific, something in the range of 2000 typical.

thresh : tuple

With format (lowcut, highcut). Typically (140.0, 250.0) for sharp-wave ripple detection.

z_thres : int or float

The default is set to 3

power_thres : int or float

The default is set to 3

merge_thres : int or float

The default is set to 0.02

min_length : float

Any sequence less than this amount is not considered a sharp-wave ripple. The default is set to 0.01.

Returns:

swrs : nept.Epoch

Containing nept.LocalFieldPotential for each SWR event

nept.lfp_filtering.mean_coherence(perievent_lfp1, perievent_lfp2, window, fs)[source]

Computes the mean coherence between perievent slices

Parameters:

perievent_lfp1 : nept.AnalogSignal

perievent_lfp2 : nept.AnalogSignal

window : int

fs : int

Returns:

freq : np.array

coherence : np.array

nept.lfp_filtering.mean_coherencegram(perievent_lfp1, perievent_lfp2, dt, window, fs, extend=0.3)[source]
Computes the mean coherence over time between perievent slices
(e.g. “coherencegram” because it’s a combination of a coherence and a spectrogram)
Parameters:

perievent_lfp1 : nept.AnalogSignal

perievent_lfp2 : nept.AnalogSignal

dt : float

window : int

fs : int

extend : float

Defaults to 0.3

Returns:

timebins : np.array

freq : np.array

coherencegram : np.array

nept.lfp_filtering.mean_csd(perievent_lfp1, perievent_lfp2, window, fs)[source]

Computes the mean Cross-Spectral Density (CSD) between perievent slices

Parameters:

perievent_lfp1 : nept.AnalogSignal

perievent_lfp2 : nept.AnalogSignal

window : int

fs : int

Returns:

freq : np.array

power : np.array

nept.lfp_filtering.mean_psd(perievent_lfps, window, fs)[source]

Computes the mean Power Spectral Density (PSD) of perievent slices

Parameters:

perievent_lfps : nept.AnalogSignal

window : int

fs : int

Returns:

freq : np.array

power : np.array

nept.lfp_filtering.next_regular(target)[source]

Find the next regular number greater than or equal to target. Regular numbers are composites of the prime factors 2, 3, and 5. Also known as 5-smooth numbers or Hamming numbers, these are the optimal size for inputs to fast-fourier transforms (FFTPACK).

Parameters:target : positive int
Returns:match : int

Notes

This function was taken from the scipy.signal.signaltools module. See http://scipy.org/scipylib/

nept.lfp_filtering.power_in_db(power)[source]

Computes the power in dB for plotting

Parameters:power : np.array
Returns:np.array

nept.loaders_mclust module

nept.loaders_mclust.get_spiketrain(spike_times, label)[source]

Converts spike times to nept.SpikeTrain.

Parameters:

spike_times: np.array

label: str

Returns:

spiketrain: nept.SpikeTrain

nept.loaders_mclust.load_mclust_header(filename)[source]

Loads a mclust .t tetrode file.

Parameters:filename: str
Returns:times: np.array
nept.loaders_mclust.load_mclust_t(filename)[source]

Loads a mclust .t tetrode file.

Parameters:filename: str
Returns:times: np.array
nept.loaders_mclust.load_spikes(filepath, load_questionable=True)[source]

Loads spikes from multiple tetrode spike files from a given session.

Parameters:

filepath: str

Session folder

load_questionable: boolean

Loads *.t and *._t spiketrains if True (default).

Returns:

spikes: list of nept.SpikeTrain

nept.loaders_medpc module

nept.loaders_medpc.get_data(contents)[source]

Extracts content from a *.mpc file

Parameters:

contents: list

Returns:

header: dict

data: dict

nept.loaders_medpc.get_events(event_list)[source]

Finds timestamps associated with each event.

Parameters:

event_list : list

Returns:

events : dict

With event type as key, timestamps as values.

nept.loaders_medpc.get_subject(subject_content, data_key='b')[source]

Gets header and data from MedPC file for a single subject.

Parameters:

subject_content: str

data_key: str

Default set to ‘b’

Returns:

header: dict

data: list

nept.loaders_medpc.load_medpc(filename, f_assign_label)[source]

Loads MedPC data file.

Parameters:

filename: MedPC file

f_assign_label: module

Returns:

rats_data: dict

With each subject as keys. Contains dict of event as nept.Epochs.

nept.loaders_medpc.read_file(filename)[source]

Reads the contents of a *.mpc file

Parameters:filename: str
Returns:contents: list

nept.loaders_neuralynx module

nept.loaders_neuralynx.load_events(filename, labels)[source]

Loads neuralynx events

Parameters:

filename: str

labels: dict

With event name as the key and Neuralynx event string as the value.

Returns:

timestamps: dict

nept.loaders_neuralynx.load_lfp(filename)[source]

Loads LFP as nept.LocalFieldPotential

Parameters:filename: str
Returns:lfp: nept.LocalFieldPotential
nept.loaders_neuralynx.load_ncs(filename)[source]

Loads a neuralynx .ncs electrode file.

Parameters:

filename: str

Returns:

cscs: np.array

Voltage trace (V)

times: np.array

Timestamps (microseconds)

nept.loaders_neuralynx.load_neuralynx_header(filename)[source]

Loads a neuralynx header.

Parameters:filename: str
Returns:header: byte str
nept.loaders_neuralynx.load_nev(filename)[source]

Loads a neuralynx .nev file.

Parameters:

filename: str

Returns:

nev_data: dict

With time (uint64), id (uint16), nttl (uint16), and event_str (charx128) as the most usable keys.

nept.loaders_neuralynx.load_ntt(filename)[source]

Loads a neuralynx .ntt tetrode spike file.

Parameters:

filename: str

Returns:

timestamps: np.array

Spikes as (num_spikes, length_waveform, num_channels)

spikes: np.array

Spike times as uint64 (us)

frequency: float

Sampling frequency in waveforms (Hz)

Usage:

timestamps, spikes, frequency = load_ntt(‘TT13.ntt’)

nept.loaders_neuralynx.load_nvt(filename)[source]

Loads a neuralynx .nvt file.

Parameters:

filename: str

Returns:

nvt_data: dict

With time, x, and y as keys.

nept.loaders_neuralynx.load_position(filename, pxl_to_cm)[source]

Loads videotracking position as nept.Position

Parameters:

filename: str

pxl_to_cm: tuple

With (x, y) conversion factors

Returns:

position: nept.Position

nept.medpc_core module

class nept.medpc_core.Rat(rat_id, group1=None, group2=None)[source]

Bases: object

add_session(mags, pellets, lights1, lights2, sounds1, sounds2, trial1, trial2, trial3, trial4, group=False)[source]

Sorts cues into appropriate trials (1, 2, 3, 4), using intersect between trial and cue epochs.

add_session_medpc(mags, pellets, lights1, lights2, sounds1, sounds2, n_unique=8, delay=5.02, tolerance=1e-08)[source]

Sorts cues into appropriate trials (1, 2, 3, 4), using specified delay between light and sound cues.

class nept.medpc_core.Session(mags, pellets)[source]

Bases: object

add_missing_trial(cue, trial_type)[source]

Adds trial placeholders for missing trials.

Parameters:

cue: str

Typically either ‘light’ or ‘sound’

trial_type: int

Typically 1, 2, 3, or 4

add_trial(epoch, cue, trial_type)[source]

Adds trial to session

Parameters:

epoch: nept.Epoch object

cue: str

Typically either ‘light’ or ‘sound’

trial_type: int

Typically 1, 2, 3, or 4

class nept.medpc_core.Trial(cue, trial_type, durations, numbers, latency, responses)[source]

Bases: object

nept.medpc_core.combine_rats(data, rats, n_sessions, only_sound=False)[source]

Combines behavioral measures from multiple rats, sessions and trials.

Parameters:

data: dict

With rat (str) as key, contains Rat objects for each rat

rats: list

With rat_id (str)

n_sessions: int

only_sound: boolean

Returns:

df: pd.DataFrame

nept.medpc_core.f_analyze(trial, measure)[source]

Extracts appropriate analysis metric.

Parameters:

trial: emi_biconditional Trial object

measure: str

One of ‘durations’, ‘numbers’, ‘latency’, or ‘responses’

Returns:

output: analysis metric for a given trial

nept.medpc_core.fix_missing_trials(df)[source]

Replaces nan values with mean for that trial type

Parameters:

df: pd.DataFrame

Note: this is a hack to handle sessions where there were fewer trials than expected.

This function finds those trials and replaces the values with the mean for that

trial type across the session.

nept.place_fields module

nept.place_fields.consecutive(array, stepsize=1)[source]
Parameters:array : np.array
Returns:List of np.arrays, split when jump greater than stepsize
nept.place_fields.find_fields(tuning, hz_thresh=5, min_length=1, max_length=20, max_mean_firing=10)[source]
Parameters:

tuning : list of np.arrays

Where each inner array contains the tuning curves for an individual neuron.

hz_thresh : int or float

Any bin with firing above this value is considered to be part of a field.

min_length : int

Minimum length of field (in tuning curve bin units, eg. if bin size is 3cm, min_length=1 is 3cm.

max_length : int

Maximum length of field (in tuning curve bin units, eg. if bin size is 3cm, min_length=10 is 3cm*10 = 30cm.

max_mean_firing : int or float

Only neurons with a mean firing rate less than this amount are considered for having place fields. The default is set to 10.

Returns:

with_fields : dict

Where the key is the neuron number (int), value is a list of arrays (int) that are indices into the tuning curve where the field occurs. Each inner array contains the indices for a given place field.

nept.place_fields.get_heatmaps(neuron_list, spikes, pos, num_bins=100)[source]

Gets the 2D heatmaps for firing of a given set of neurons.

Parameters:

neuron_list : list of ints

These will be the indices into the full list of neuron spike times

spikes : list

Containing nept.SpikeTrain for each neuron.

pos : nept.Position

Must be 2D.

num_bins : int

This will specify how the 2D space is broken up, the greater the number the more specific the heatmap will be. The default is set at 100.

Returns:

heatmaps : dict of lists

Where the key is the neuron number and the value is the heatmap for that individual neuron.

nept.place_fields.get_single_field(fields)[source]

Finds neurons with and indices of single fields.

Parameters:

fields : dict

Where the key is the neuron number (int), value is a list of arrays (int). Each inner array contains the indices for a given place field. Eg. Neurons 7, 3, 11 that have 2, 1, and 3 place fields respectively would be: {7: [[field], [field]], 3: [[field]], 11: [[field], [field], [field]]}

Returns:

fields : dict

Where the key is the neuron number (int), value is a list of arrays (int). Each inner array contains the indices for a given place field. Eg. For the above input, only neuron 3 would be output in this dict: {3: [[field]]}

nept.tuning_curves module

nept.tuning_curves.binned_position(position, binsize)[source]

Bins 1D position by the binsize.

Parameters:

position : nept.Position

Must be a 1D position

binsize : int

Returns:

edges : np.array

nept.tuning_curves.tuning_curve(position, spikes, binsize, gaussian_std=None)[source]

Computes tuning curves for neurons relative to linear position.

Parameters:

position : nept.Position

Must be a linear position (1D).

spikes : list

Containing nept.SpikeTrain for each neuron.

binsize : int

gaussian_std : int or None

No smoothing if None.

Returns:

out_tc : list of np.arrays

Where each inner array contains the tuning curves for an individual neuron.

Notes

Input position and spikes should be from the same time period. Eg. when the animal is running on the track.

nept.tuning_curves.tuning_curve_2d(position, spikes, xedges, yedges, occupied_thresh=0, gaussian_sigma=None)[source]

Creates 2D tuning curves based on spikes and 2D position.

Parameters:

position : nept.Position

Must be a 2D position.

spikes : list

Containing nept.SpikeTrain for each neuron.

xedges : np.array

yedges : np.array

sampling_rate : float

occupied_thresh: float

gaussian_sigma : float

Sigma used in gaussian filter if filtering.

Returns:

tuning_curves : np.array

Where each inner array is the tuning curve for an individual neuron.

nept.utils module

nept.utils.bin_spikes(spikes, position, window_size, window_advance, gaussian_std=None, n_gaussian_std=5, normalized=True)[source]

Bins spikes using a sliding window.

Parameters:

spikes: list

Of nept.SpikeTrain

position: nept.AnalogSignal

window_size: float

window_advance: float

gaussian_std: float or None

n_gaussian_std: int

normalized: boolean

Returns:

binned_spikes: nept.AnalogSignal

nept.utils.cartesian(xcenters, ycenters)[source]

Finds every combination of elements in two arrays.

Parameters:

xcenters : np.array

ycenters : np.array

Returns:

cartesian : np.array

With shape(n_sample, 2).

nept.utils.expand_line(start_pt, stop_pt, line, expand_by=6)[source]

Creates buffer zone around a line.

Parameters:

start_pt : Shapely’s Point object

stop_pt : Shapely’s Point object

line : Shapely’s LineString object

expand_by : int

This sets by how much you wish to expand the line. Defaults to 6.

Returns:

zone : Shapely’s Polygon object

nept.utils.find_multi_in_epochs(spikes, epochs, min_involved)[source]

Finds epochs with minimum number of participating neurons.

Parameters:

spikes: np.array

Of nept.SpikeTrain objects

epochs: nept.Epoch

min_involved: int

Returns:

multi_epochs: nept.Epoch

nept.utils.find_nearest_idx(array, val)[source]

Finds nearest index in array to value.

Parameters:

array : np.array

val : float

Returns:

Index into array that is closest to val

nept.utils.find_nearest_indices(array, vals)[source]

Finds nearest index in array to value.

Parameters:

array : np.array

This is the array you wish to index into.

vals : np.array

This is the array that you are getting your indices from.

Returns:

Indices into array that is closest to vals.

Notes

Wrapper around find_nearest_idx().

nept.utils.get_edges(position, binsize, lastbin=True)[source]

Finds edges based on linear time

Parameters:

position : nept.AnalogSignal

binsize : float

This is the desired size of bin. Typically set around 0.020 to 0.040 seconds.

lastbin : boolean

Determines whether to include the last bin. This last bin may not have the same binsize as the other bins.

Returns:

edges : np.array

nept.utils.get_sort_idx(tuning_curves)[source]

Finds indices to sort neurons by max firing in tuning curve.

Parameters:

tuning_curves : list of lists

Where each inner list is the tuning curves for an individual neuron.

Returns:

sorted_idx : list

List of integers that correspond to the neuron in sorted order.

nept.utils.get_xyedges(position, binsize=3)[source]

Gets edges based on position min and max.

Parameters:

position: 2D nept.Position

binsize: int

Returns:

xedges: np.array

yedges: np.array

nept.utils.perievent_slice(analogsignal, events, t_before, t_after, dt=None)[source]

Slices the analogsignal data into perievent chunks. Unlike time_slice, the resulting AnalogSignal will be multidimensional. Only works for 1D signals.

Parameters:

analogsignal : nept.AnalogSignal

events : np.array

t_before : float

t_after : float

dt : float

Returns:

nept.AnalogSignal

nept.utils.speed_threshold(position, t_smooth=0.5, speed_limit=0.4)[source]

Finds positions above a certain speed threshold

Parameters:

position : nept.Position

t_smooth : float

speed_limit : float

Returns:

position_run : nept.Position