aolabNeuro / aolabNeuro/analyze
add correlation calculations
- 主要語言
- Python
- 星號
- 7
- 分支
- 0
- 平均合併
- 22 小時 29 分鐘
- 30 天內合併 PR
- 2
描述
pavi wrote a bunch of correlation functions. they should be added here:
```
from scipy import stats
def pearson_corr(X):
"""Computes the connectivity matrix for the all neurons using correlations
Args:
X (2d Numpy array): neural data (n_timepoints x n_neurons)
Returns:
estimated_connectivity (np.ndarray): estimated connectivity for the selected neuron, of shape (n_neurons,)
"""
# Pearson Correlation coefficient
A = np.corrcoef(X.T) # finding correlations among units. hence, rows should be units
# n_neurons = len(X)
# S = np.concatenate([X[:, 1:], X[:, :-1]], axis=0) # this correlates activity of each neuron at time t with the activity of other neurons at t+1.
# R = np.corrcoef(S)[:n_neurons, n_neurons:]
return A
def spearman_corr(X):
"""Computes the connectivity matrix for the all neurons using spearman correlation
Args:
X (2d Numpy array): neural data (n_timepoints x n_neurons)
Returns:
correlation (np.ndarray): estimated connectivity for the selected neuron, of shape (n_neurons,)
p value
"""
cor, p = stats.spearmanr(X, axis = 0) #If axis=0 (default), then each column represents a variable, with observations in the rows. If axis=1, the relationship is transposed: each row represents a variable, while the columns contain observations.
return cor, p
def plot_connectivity_matrix(A, ax=None):
"""Plot the (weighted) connectivity matrix A as a heatmap
Args:
A (ndarray): connectivity matrix (n_neurons by n_neurons)
ax: axis on which to display connectivity matrix
"""
if ax is None:
ax = plt.gca()
lim = np.abs(A).max()
im = ax.imshow(A, vmin=-lim, vmax=lim, cmap="coolwarm")
# ax.tick_params(labelsize=10)
ax.xaxis.label.set_size(15)
ax.yaxis.label.set_size(15)
cbar = ax.figure.colorbar(im, ax=ax, ticks=[-lim,0, lim], shrink=.7)
cbar.ax.set_ylabel("Connectivity Strength", rotation=90,
labelpad= 20, va="bottom")
ax.set(xlabel="Connectivity from", ylabel="Connectivity to")
import math
def electrode_distance(elec_pos):
'''
This function returns a matrix of euclidean distance. Each entry in the matrix is the distance between ith and jth electrode channel
'''
n_channels = np.shape(elec_pos[:,1])[0]
dist = np.zeros((n_channels, n_channels))
x_pos = elec_pos[:,0]
y_pos = elec_pos[:,1]
for index, _ in np.ndenumerate(dist):
p1 = index[0]
p2 = index[1]
dist[p1, p2] = math.dist([x_pos[p1], y_pos[p1]], [x_pos[p2], y_pos[p2]])
return dist
def calc_corr_over_elec_distance(acq_data, acq_ch, elec_pos, bins=20, method='spearman', exclude_zero_dist=True):
dist = electrode_distance(elec_pos)
if method == 'spearman':
c, _ = spearman_corr(acq_data)
elif method == 'pearson':
c = pearson_corr(acq_data)
else:
raise ValueError(f"Unknown correlation method {method}")
c_ = c[np.ix_(acq_ch-1, acq_ch-1)] # note use of open mesh to get the right logical index
if exclude_zero_dist:
zero_dist = dist == 0
dist = dist[~zero_dist]
c_ = c_[~zero_dist]
bin_means, bin_edges, _ = stats.binned_statistic(dist.flatten(), np.abs(c_.flatten()), statistic='mean', bins=bins)
return bin_means, bin_edges
def plot_corr_over_elec_distance(acq_data, acq_ch, elec_pos, **kwargs):
corr, dist = calc_corr_over_elec_distance(acq_data, acq_ch, elec_pos)
plt.hlines(corr, dist[:-1], dist[1:], lw=2.5, label='binned statistic of correlation')
plt.xlabel('binned electrode distance (cm)')
plt.ylabel('correlation')
```
貢獻指南
這個儲存庫沒有索引到貢獻指南
評估
這個 Issue 還沒有評估資料。