Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.
"""
# Check that data is a list of SpikeTrains
if not all([isinstance(elem, neo.SpikeTrain) for elem in data]):
raise TypeError(
'data must be a list of SpikeTrains')
# Check that all spiketrains have same t_start and same t_stop
if not all([st.t_start == data[0].t_start for st in data]) or not all(
[st.t_stop == data[0].t_stop for st in data]):
raise AttributeError(
'All spiketrains must have the same t_start and t_stop')
if report not in ['a', '#', '3d#']:
raise ValueError(
"report has to assume of the following values:" +
" 'a', '#' and '3d#,' got {} instead".format(report))
# Binning the data and clipping (binary matrix)
binary_matrix = conv.BinnedSpikeTrain(
data, binsize).to_sparse_bool_array().tocoo()
# Computing the context and the binary matrix encoding the relation between
# objects (window positions) and attributes (spikes,
# indexed with a number equal to neuron idx*winlen+bin idx)
context, transactions, rel_matrix = _build_context(binary_matrix, winlen)
# By default, set the maximum pattern size to the maximum number of
# spikes in a window
if max_spikes is None:
max_spikes = np.max((int(np.max(np.sum(rel_matrix, axis=1))),
min_spikes + 1))
# By default, set maximum number of occurrences to number of non-empty
# windows
if max_occ is None:
max_occ = int(np.sum(np.sum(rel_matrix, axis=1) > 0))
# Check if fim.so available and use it
if HAVE_FIM:
>>> plt.plot(freqs, sfc[:,1])
>>> plt.xlabel('Frequency [Hz]')
>>> plt.ylabel('SFC')
>>> plt.xlim((0, 60))
>>> plt.show()
"""
if not hasattr(scipy.signal, 'coherence'):
raise AttributeError('scipy.signal.coherence is not available. The sfc '
'function uses scipy.signal.coherence for '
'the coherence calculation. This function is '
'available for scipy version 0.16 or newer. '
'Please update you scipy version.')
# spiketrains type check
if not isinstance(spiketrain, (SpikeTrain, BinnedSpikeTrain)):
raise TypeError(
"spiketrain must be of type SpikeTrain or BinnedSpikeTrain, "
"not %s." % type(spiketrain))
# checks on analogsignal
if not isinstance(signal, AnalogSignal):
raise TypeError(
"Signal must be an AnalogSignal, not %s." % type(signal))
if len(signal.shape) > 1:
# num_signals: number of individual traces in the analog signal
num_signals = signal.shape[1]
elif len(signal.shape) == 1:
num_signals = 1
else:
raise ValueError("Empty analog signal.")
len_signals = signal.shape[0]
simulation_end : float
The simulation end time.
neo_spiketrains : list
A list of Neo spiketrains.
Returns
-------
time : None
values : 2D array
The pairwise Pearson's correlation coefficients.
"""
if len(spiketrains) == 0:
return None, None
binned_sts = elephant.conversion.BinnedSpikeTrain(spiketrains,
binsize=self.corrcoef_bin_size*self.units)
corrcoef = elephant.spike_train_correlation.corrcoef(binned_sts)
return None, corrcoef
_quantities_almost_equal(st.t_stop, t_stop_max)):
msg = 'SpikeTrain %d is shorter than the required time ' % i + \
'span: t_stop (%s) < %s' % (st.t_stop, t_stop_max)
raise ValueError(msg)
# For both x and y axis, cut all SpikeTrains between t_start and t_stop
sts_x = [st.time_slice(t_start=t_start_x, t_stop=t_stop_x)
for st in spiketrains]
sts_y = [st.time_slice(t_start=t_start_y, t_stop=t_stop_y)
for st in spiketrains]
# Compute imat either by matrix multiplication (~20x faster) or by
# nested for loops (more memory efficient)
try: # try the fast version
# Compute the binned spike train matrices, along both time axes
bsts_x = conv.BinnedSpikeTrain(
sts_x, binsize=binsize,
t_start=t_start_x, t_stop=t_stop_x).to_bool_array()
bsts_y = conv.BinnedSpikeTrain(
sts_y, binsize=binsize,
t_start=t_start_y, t_stop=t_stop_y).to_bool_array()
# Compute the number of spikes in each bin, for both time axes
spikes_per_bin_x = bsts_x.sum(axis=0)
spikes_per_bin_y = bsts_y.sum(axis=0)
# Compute the intersection matrix imat
N_bins = len(spikes_per_bin_x)
imat = np.zeros((N_bins, N_bins), dtype=float)
for ii in range(N_bins):
# Compute the ii-th row of imat
bin_ii = bsts_x[:, ii].reshape(-1, 1)
raise ValueError(msg)
# For both x and y axis, cut all SpikeTrains between t_start and t_stop
sts_x = [st.time_slice(t_start=t_start_x, t_stop=t_stop_x)
for st in spiketrains]
sts_y = [st.time_slice(t_start=t_start_y, t_stop=t_stop_y)
for st in spiketrains]
# Compute imat either by matrix multiplication (~20x faster) or by
# nested for loops (more memory efficient)
try: # try the fast version
# Compute the binned spike train matrices, along both time axes
bsts_x = conv.BinnedSpikeTrain(
sts_x, binsize=binsize,
t_start=t_start_x, t_stop=t_stop_x).to_bool_array()
bsts_y = conv.BinnedSpikeTrain(
sts_y, binsize=binsize,
t_start=t_start_y, t_stop=t_stop_y).to_bool_array()
# Compute the number of spikes in each bin, for both time axes
spikes_per_bin_x = bsts_x.sum(axis=0)
spikes_per_bin_y = bsts_y.sum(axis=0)
# Compute the intersection matrix imat
N_bins = len(spikes_per_bin_x)
imat = np.zeros((N_bins, N_bins), dtype=float)
for ii in range(N_bins):
# Compute the ii-th row of imat
bin_ii = bsts_x[:, ii].reshape(-1, 1)
imat[ii, :] = (bin_ii * bsts_y).sum(axis=0)
# Normalize the row according to the specified normalization
if norm == 0 or norm is None or bin_ii.sum() == 0:
warnings.warn(
"Spiketrains have different t_stop values -- "
"using minimum t_stop as t_stop.")
else:
min_tstop = conv._get_start_stop_from_input(spiketrains)[1]
t_stop = min_tstop
if not all([min_tstop == t.t_stop for t in spiketrains]):
warnings.warn(
"Spiketrains have different t_stop values -- "
"using minimum t_stop as t_stop.")
sts_cut = [st.time_slice(t_start=t_start, t_stop=t_stop) for st in
spiketrains]
# Bin the spike trains and sum across columns
bs = conv.BinnedSpikeTrain(sts_cut, t_start=t_start, t_stop=t_stop,
binsize=binsize)
if binary:
bin_hist = bs.to_sparse_bool_array().sum(axis=0)
else:
bin_hist = bs.to_sparse_array().sum(axis=0)
# Flatten array
bin_hist = np.ravel(bin_hist)
# Renormalise the histogram
if output == 'counts':
# Raw
bin_hist = bin_hist * pq.dimensionless
elif output == 'mean':
# Divide by number of input spike trains
bin_hist = bin_hist * 1. / len(spiketrains) * pq.dimensionless
elif output == 'rate':
winsize_bintime * binsize))
if winstep_bintime * binsize != winstep:
warnings.warn(
"ratio between winstep and binsize is not integer -- "
"the actual number for window size is " + str(
winstep_bintime * binsize))
num_tr, N = np.shape(data)[:2]
n_bins = int((t_stop - t_start) / binsize)
mat_tr_unit_spt = np.zeros((len(data), N, n_bins))
for tr, sts in enumerate(data):
sts = list(sts)
bs = conv.BinnedSpikeTrain(
sts, t_start=t_start, t_stop=t_stop, binsize=binsize)
if binary is True:
mat = bs.to_bool_array()
else:
raise ValueError(
"The method only works on the zero_one matrix at the moment")
mat_tr_unit_spt[tr] = mat
num_win = len(t_winpos)
Js_win, n_exp_win, n_emp_win = (np.zeros(num_win) for _ in range(3))
rate_avg = np.zeros((num_win, N))
indices_win = {}
for i in range(num_tr):
indices_win['trial' + str(i)] = []
for i, win_pos in enumerate(t_winpos_bintime):
the cumulative probability matrix. pmat[i, j] represents the
estimated probability of having an overlap between bins i and j
STRICTLY LOWER THAN the observed overlap, under the null hypothesis
of independence of the input spike trains.
x_edges : numpy.ndarray
edges of the bins used for the horizontal axis of pmat. If pmat is
a matrix of shape (n, n), x_edges has length n+1
y_edges : numpy.ndarray
edges of the bins used for the vertical axis of pmat. If pmat is
a matrix of shape (n, n), y_edges has length n+1
'''
# Bin the spike trains
t_stop_x = None if t_start_x is None else t_start_x + dt
t_stop_y = None if t_start_y is None else t_start_y + dt
bsts_x = conv.BinnedSpikeTrain(
spiketrains, binsize=binsize, t_start=t_start_x, t_stop=t_stop_x)
bsts_y = conv.BinnedSpikeTrain(
spiketrains, binsize=binsize, t_start=t_start_y, t_stop=t_stop_y)
bsts_x_matrix = bsts_x.to_bool_array()
bsts_y_matrix = bsts_y.to_bool_array()
# Check that the duration and nr. neurons is identical between the two axes
if bsts_x_matrix.shape != bsts_y_matrix.shape:
raise ValueError(
'Different spike train durations along the x and y axis!')
# Define the firing rate profiles
# If rates are to be estimated, create the rate profiles as Quantity
# objects obtained by boxcar-kernel convolution
ValueError
If mat is not zero-one matrix.
Examples
---------
>>> mat = np.array([[1, 0, 0, 1, 1],
>>> [1, 0, 0, 1, 0]])
>>> pattern_hash = np.array([1,3])
>>> n_emp, n_emp_indices = n_emp_mat(mat, pattern_hash)
>>> print(n_emp)
[ 0. 2.]
>>> print(n_emp_indices)
[array([]), array([0, 3])]
"""
# check if the mat is zero-one matrix
if not is_binary(mat):
raise ValueError("entries of mat should be either one or zero")
h = hash_from_pattern(mat, base=base)
N_emp = np.zeros(len(pattern_hash))
indices = []
for idx_ph, ph in enumerate(pattern_hash):
indices_tmp = np.where(h == ph)[0]
indices.append(indices_tmp)
N_emp[idx_ph] = len(indices_tmp)
return N_emp, indices
>>> pattern_hash = np.array([4,6])
>>> N = 3
>>> n_emp_sum_trial, n_emp_sum_trial_idx = \
>>> n_emp_mat_sum_trial(mat, N,pattern_hash)
>>> n_emp_sum_trial
array([ 1., 3.])
>>> n_emp_sum_trial_idx
[[array([0]), array([3])], [array([], dtype=int64), array([2, 4])]]
"""
num_patt = len(pattern_hash)
N_emp = np.zeros(num_patt)
idx_trials = []
# check if the mat is zero-one matrix
if not is_binary(mat):
raise ValueError("entries of mat should be either one or zero")
for mat_tr in mat:
N_emp_tmp, indices_tmp = n_emp_mat(mat_tr, pattern_hash, base=2)
idx_trials.append(indices_tmp)
N_emp += N_emp_tmp
return N_emp, idx_trials