forked from HopkinsPsychedelic/connectome_harmonic_core
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcompute_spectra.py
executable file
·189 lines (174 loc) · 8.64 KB
/
compute_spectra.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
"""
@authors: patricktaylor, bwinston
"""
import numpy as np
import nibabel as nib
import matplotlib.pyplot as plt
from matplotlib.pyplot import figure
from matplotlib.ticker import MaxNLocator
from statistics import stdev
import matplotlib.lines as mlines
import matplotlib.transforms as mtransforms
#from powerlaw import plot_pdf, Fit, pdf
#import powerlaw
import math
from sklearn.metrics import mean_squared_error
import pandas as pd
import os
def get_zeromean(timeseries):
zeromean = np.zeros(np.shape(timeseries))
for i in range(len(timeseries)):
#zeromean is the same as the timeseries, just with zero as the mean
zeromean[i, :] = (timeseries[i, :] - np.mean(timeseries[i, :]))
return zeromean
def rms(spectrum): #reconstruction spectrum (should have negative values)
squares = np.zeros(np.shape(spectrum))
for harmonic in range(len(spectrum)):
for timepoint in range(len(spectrum[0])):
squares[harmonic][timepoint] = spectrum[harmonic][timepoint]**2
rms = np.zeros(len(spectrum))
for harmonic in range(len(spectrum)):
rms[harmonic] = sum(squares[harmonic]) #mean of sum of squares
rms[harmonic] = rms[harmonic]**.5 #square root
return rms
def dynamic_energy_spectrum(timeseries,vecs,vals):
zeromean = get_zeromean(timeseries)
spectrum=np.zeros((len(vecs[0,:]),len(timeseries[0,:])))
for k in range(len(spectrum)):
v=vecs[:,k]
for tp in range(len(zeromean[0,:])):
spectrum[k][tp]=(np.abs(np.dot(v,zeromean[:,tp]))**2)*vals[k]**2
return spectrum
def dynamic_power_spectrum(timeseries,vecs):
zeromean = get_zeromean(timeseries)
#spectrum has dims vecs x timepoints
spectrum=np.zeros((len(vecs[0,:]),len(timeseries[0,:])))
for v in range(len(spectrum)): #for each vec
vec=vecs[:,v] #values in the vec
for tp in range(len(zeromean[0,:])): #for each timepoint
#ev strength at that timepoint is the dot product of
#the ev x the distribution of activity at a timepoint
#these are the same shape (i.e. both 59k vectors)
#dot product is showing how much overlap? why abs?
#no squaring
#for mean, we're taking the average of that for each harmonic over the scan
#each timepoint of spectrum is dot product btwn ev and fmri timeslice
spectrum[v][tp]=np.abs(np.dot(vec,zeromean[:,tp]))
return spectrum
def dynamic_reconstruction_spectrum(timeseries,vecs): #like power but no absolute value
zeromean = get_zeromean(timeseries)
spectrum=np.zeros((len(vecs[0,:]),len(timeseries[0,:])))
for k in range(len(spectrum)):
#print(k)
v=vecs[:,k]
for tp in range(len(zeromean[0,:])):
spectrum[k][tp]=np.dot(v,zeromean[:,tp])
return spectrum
def mean_energy_spectrum(timeseries,vecs,vals):
zeromean = get_zeromean(timeseries)
spectrum=np.zeros(len(vecs[0,:]))
for k in range(len(spectrum)):
v=vecs[:,k]
for tp in range(len(zeromean[0,:])):
spectrum[k]+=np.abs(np.dot(v,zeromean[:,tp]))**2/len(zeromean[0,:])*vals[k]**2
return spectrum
def mean_power_spectrum(timeseries,vecs):
zeromean = get_zeromean(timeseries)
spectrum=np.zeros(len(vecs[0,:]))
for k in range(len(spectrum)):
#print(k)
v=vecs[:,k]
for tp in range(len(zeromean[0,:])):
spectrum[k]+=np.abs(np.dot(v,zeromean[:,tp]))/len(zeromean[0,:])
return spectrum
def normalized_power_spectrum(timeseries,vecs):
zeromean = get_zeromean(timeseries)
spectrum=np.zeros(len(vecs[0,:]))
for k in range(len(spectrum)):
#print(k)
v=vecs[:,k]
for tp in range(len(zeromean[0,:])):
spectrum[k]+=np.abs(np.dot(v,zeromean[:,tp]))/len(zeromean[0,:])/np.linalg.norm(v)/np.linalg.norm(zeromean[:,tp])
return spectrum
def read_functional_timeseries(lhfunc,rhfunc):
l = nib.load(lhfunc).darrays
r = nib.load(rhfunc).darrays
timeseries = np.zeros((2*len(l[0].data), len(r)))
for i in range(len(l)):
lt = np.array(l[i].data)
rt = np.array(r[i].data)
tp = np.concatenate((lt, rt))
timeseries[:, i] = tp
return timeseries
def read_cifti_timeseries_masked(file):
time_series=nib.load(file)
time_series=np.array(time_series.dataobj)[:,:59412]
return time_series.T
def plot_spectrum(spectrum, spectrum_type):
#TODO: replace with args.evecs
ax = plt.figure().gca()
ax.xaxis.set_major_locator(MaxNLocator(integer=True))
plt.xlabel('Wavenumber, Ψ')
plt.ylabel(spectrum_type)
plt.bar(range(20), spectrum)
plt.show()
def criticality(dynamic_spectrum, spectrum_type, comparison_distributions=['exponential', 'truncated_power_law', 'lognormal']):
#alpha is fitted parameter for the powerlaw distribution, sigma the standard error
#R is the loglikelihood ratio between the distributions,
max_spectrum = [max(row) for row in list(dynamic_spectrum)]
std_spectrum = [stdev(row) for row in list(dynamic_spectrum)]
mean_spectrum = [np.mean(row) for row in list(dynamic_spectrum)]
criticality_df_row = pd.DataFrame()
for dist in comparison_distributions:
fit_mean = powerlaw.Fit(mean_spectrum)
fit_max = powerlaw.Fit(max_spectrum)
fit_std = powerlaw.Fit(std_spectrum)
R_mean, p_mean = fit_mean.distribution_compare('power_law', dist)
R_max, p_max = fit_max.distribution_compare('power_law', dist)
R_std, p_std = fit_std.distribution_compare('power_law', dist)
criticality_df_row[f'mps_powerlaw_vs_{dist}'] = [{'R':R_mean, 'p':p_mean, 'alpha':fit_mean.power_law.alpha, 'sigma':fit_mean.power_law.sigma}]
criticality_df_row[f'maxps_powerlaw_vs_{dist}'] = [{'R':R_max, 'p':p_max, 'alpha':fit_max.power_law.alpha, 'sigma':fit_max.power_law.sigma}]
criticality_df_row[f'stdps_powerlaw_vs_{dist}'] = [{'R':R_std, 'p':p_std, 'alpha':fit_std.power_law.alpha, 'sigma':fit_std.power_law.sigma}]
print(f'Mean {spectrum_type} spectrum: ')
print(f'Powerlaw vs. {dist} R: '+str(R_mean)+" p: "+str(p_mean))
print(f'Max {spectrum_type} spectrum: ')
print(f'Powerlaw vs. {dist} R: '+str(R_max)+" p: "+str(p_max))
print(f'STD {spectrum_type} spectrum: ')
print(f'Powerlaw vs. {dist} R: '+str(R_std)+" p: "+str(p_std))
return criticality_df_row
def plot_rmse_criticality(mean_spectrum, dynamic_spectrum, spectrum_type):
#TODO: replace with args.evecs
wavenumbers = list(np.arange(20+1))[1:]
mean_spectrum = list(mean_spectrum)
max_spectrum = [max(row) for row in list(dynamic_spectrum)]
std_spectrum = [stdev(row) for row in list(dynamic_spectrum)]
log_wavenumbers = list(map(lambda x: math.log(x, 10), wavenumbers))
log_mean_spectrum = list(map(lambda x: math.log(x,10), mean_spectrum))
log_std_spectrum = list(map(lambda x: math.log(x,10), max_spectrum))
log_max_spectrum = list(map(lambda x: math.log(x,10), std_spectrum))
fig, axs=plt.subplots(3,1)
axs[0].scatter(log_wavenumbers, log_mean_spectrum)
axs[0].set_ylabel("Mean "+spectrum_type)
coefficient_best_fit_mean = np.polyfit(log_wavenumbers, log_mean_spectrum, 1)
pred_best_fit_mean = list(map(lambda x: x*coefficient_best_fit_mean[0]+coefficient_best_fit_mean[1], log_wavenumbers))
#[[i, pred_best_fit[i]] for i in range(20)],
line_mean = mlines.Line2D(log_wavenumbers, pred_best_fit_mean, color='red')
axs[0].add_line(line_mean)
print("RSME Mean powerlaw fit: "+str(math.sqrt(mean_squared_error(mean_spectrum, pred_best_fit_mean))))
axs[1].scatter(log_wavenumbers, log_std_spectrum)
axs[1].set_ylabel("Std "+spectrum_type)
coefficient_best_fit_std = np.polyfit(log_wavenumbers, log_std_spectrum, 1)
pred_best_fit_std = list(map(lambda x: x*coefficient_best_fit_std[0]+coefficient_best_fit_std[1], log_wavenumbers))
#[[i, pred_best_fit[i]] for i in range(20)],
line_std = mlines.Line2D(log_wavenumbers, pred_best_fit_std, color='red')
axs[1].add_line(line_std)
print("RSME STD powerlaw fit: "+str(math.sqrt(mean_squared_error(std_spectrum, pred_best_fit_mean))))
axs[2].scatter(log_wavenumbers, log_max_spectrum)
axs[2].set_xlabel('Log Wavenumber, Ψ')
axs[2].set_ylabel("Max "+spectrum_type)
coefficient_best_fit_max = np.polyfit(log_wavenumbers, log_max_spectrum, 1)
pred_best_fit_max = list(map(lambda x: x*coefficient_best_fit_max[0]+coefficient_best_fit_max[1], log_wavenumbers))
#[[i, pred_best_fit[i]] for i in range(20)],
line = mlines.Line2D(log_wavenumbers, pred_best_fit_max, color='red')
axs[2].add_line(line)
print("RSME Max powerlaw fit: "+str(math.sqrt(mean_squared_error(max_spectrum, pred_best_fit_max))))