-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtemplate.jl.jl
More file actions
executable file
ยท239 lines (167 loc) ยท 7.74 KB
/
template.jl.jl
File metadata and controls
executable file
ยท239 lines (167 loc) ยท 7.74 KB
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
# This unit computes classification accuracy on a database
# and can be used to compare several cov matrix estimators,
# including shrinkage and tyler M-estimator.
DBDir = homedir()*"/Documents/My Data/EEG data/npz"
using LinearAlgebra, PosDefManifold, PosDefManifoldML, CovarianceEstimation,
Dates, Distributions, PDMats, Revise, BenchmarkTools, Plots, GR
push!(LOAD_PATH, joinpath(@__DIR__, "Modules"))
using EEGio, FileSystem, EEGpreprocessing, System, ERPs,
DelphiApplications, Tyler, EEGtomography
lse, nlse = LinearShrinkage, AnalyticalNonlinearShrinkage
function classify(o; shuffle=false)
# multivariate regression ERP mean with data-driven weights
w=[[1/(norm(o.X[o.cstim[i][j]+o.offset:o.cstim[i][j]+o.offset+o.wl-1,:])^2) for j=1:length(o.cstim[i])] for i=1:o.nc]
Y=mean(o.X, o.wl, o.cstim; weights=w)[2]
# PCA to keep only 4 components
Y=Y*eigvecs(cov(SimpleCovariance(), Y))[:, o.ne-3:o.ne]
# encoding
# sample covariance matrix
๐lw=โVector([โ(cov(SimpleCovariance(), [X Y])) for X โ o.trials])
# linear shrinkage
#๐lw=โVector([โ(cov(lse(ConstantCorrelation()), [X Y])) for X โ o.trials])
# non-linear estimator (gives numerical problems)
#๐lw=โVector([โ(cov(nlse(), [X Y])) for X โ o.trials])
# TME estimator
๐lw=โVector([โ(Mest([X Y]')) for X โ o.trials])
# nrTME estimator
# ๐lw=โVector([โ(nrMest([X Y]'; reg=:LW)) for X โ o.trials])
# regularization (necessary for non-linear shrinkage)
#R=Hermitian(Matrix{eltype(๐lw[1])}(I, size(๐lw[1]))*0.001)
#for C in ๐lw C+=R end
# trace normalization
#for i=1:length(๐lw) ๐lw[i]=๐lw[i]/tr(๐lw[i]) end
# det normalization
for i=1:length(๐lw) ๐lw[i]=det1(๐lw[i]) end
# classification
args=(shuffle=shuffle, tol=1e-6, verbose=false)
cvlw = cvAcc(ENLR(Fisher), ๐lw, o.y; args...)
return cvlw.avgAcc, cvlw.stdAcc
end
function processDB(dbName, Dir, paradigm)
# find out the directory where the database is
dbDir=DBDir*"/"*paradigm*"/"*dbName
# get the complete list of file paths
files=loadNYdb(dbDir)
# get memory for storing results
meanA=Vector{Float64}(undef, length(files)); sdA = similar(meanA)
# read files, do computations and waste them, one by one
println("\nProcessing DB "*dbName*"; # files: $(length(files))")
for (i, file) โ enumerate(files)
o=readNY(file; bandpass=(1, 16)) # read files and create the o structure
print(rpad("$i.", 4), rpad("sj: $(o.subject), ss: $(o.session), run $(o.run): ", 26));
โ = now()
meanA[i], sdA[i] = classify(o; shuffle=false)
println(rpad(round(meanA[i]; digits=4), 6), " (", rpad(round(sdA[i]; digits=4), 6), ") done in ", now()-โ)
waste(o) # release memory
end
println("")
return meanA, sdA
end
# Run Classification
using Plots
paradigm = "P300"
dbName = "BI.EEG.2013-Sorted"
dbDir=DBDir*"/"*paradigm*"/"*dbName
DirCS = dbDir*"/Sujet1/Base1"
files = loadNYdb(DirCS)
files = loadNYdbCS(dbDir)
meanA=Vector{Float64}(undef, length(files)); sdA = similar(meanA)
for (i, file) โ enumerate(files)
o=readNY(file; bandpass=(1, 16)) # read files and create the o structure
print(rpad("$i.", 4), rpad("sj: $(o.subject), ss: $(o.session), run $(o.run): ", 26));
โ = now()
meanA[i], sdA[i] = classify(o)
println(rpad(round(meanA[i]; digits=4), 6), " (", rpad(round(sdA[i]; digits=4), 6), ") done in ", now()-โ)
waste(o) # release memory
end
println("")
return meanA, sdA
a, b = processDB("BI.EEG.2012-GIPSA", DBDir, "P300")
bar(sort(a, rev=true), ylim=(0.5, 1))
x
## Tools
#=
# get the data of one file
o=readNY(files[10]; bandpass=(1, 16))
# weighted multivariate regression ERP mean estimation
Z=mean(o.X, o.wl, o.cstim, true; weights=:a)
eegPlot(Z[2], o.sensors)
# send data to CSTP
erpPlot(o.X, o.sr, o.wl, o.offset, 16, o.sensors, o.stim, o.clabels)
# arithmetic mean
Y=fVec(mean, ๐Vector([o.trials[i] for i in eachindex(o.trials) if o.y[i]==2]))
eegPlot(Y, o.sensors)
# easy way to get the arithmetic mean
Z=mean(o.X, o.wl, o.cstim, false)
sr, stim, (ns, ne) = info["acquisition"]["samplingrate"], data["stim"], size(data["data"])
# offset for trial starting sample, trial duration, # of classes
offset, td, z = info["stim"]["offset"], info["stim"]["windowlength"], info["stim"]["nclasses"]
ICoNargs=(msg="\x1b[33m"*"Please wait while the Wave Editor runs", )
# PRE-PROCESSING
################
BPfilter = digitalfilter(Bandpass(1/(sr/2), 16/(sr/2)), Butterworth(2))
# Winsor standardize BP-filtered EEG and convert to Float64 if necessary
EEG = standardizeEEG(filtfilt(BPfilter, data["data"]); prop=0.25)./200
# Write EEG Data file for visualization
showEEG && eegPlot(resample(EEG, 1//4), info["acquisition"]["sensors"]; ICoNargs...)
# EXTRACT TRIALS
################
# vectors of samples where the trials start for each class 1, 2,...
trig=[[i+offset for i in eachindex(stim) if stim[i]==j && i+offset+td<=ns] for j=1:z]
# Get Trials
๐=[EEG[trig[i][j]:trig[i][j]+td-1,:] for i=1:z for j=1:length(trig[i])]
# Get Labels
y=[i for i=1:z for j=1:length(trig[i])]
# ENCODING
##########
# arithmetic mean ERP of TargetTrial
Y=fVec(mean, ๐Vector([๐[i] for i in eachindex(๐) if y[i]==2]))
showEEG && eegPlot(resample(Y, 1//4), info["acquisition"]["sensors"]; ICoNargs...)
# Show topograpic maps of geometric means
if showTopoMaps
Means=โVector([mean(Fisher, โVector([โ(๐[i][1:ne, 1:ne]) for i=1:length(๐) if y[i]==j])) for j=1:z])
zlabels=Array{String, 1}(collect(keys(info["stim"]["labels"])))
topoPlot(Means, info["acquisition"]["sensors"];
title="Class Means",
mapLabels=zlabels,
monopolar=true,
scaleMode=:global)
end
# Minimum Distance to Mean
args=(shuffle=true, tol=1e-5)
cvMDM = cvAcc(MDM(Fisher), ๐, y; args...)
cvMDMscm = cvAcc(MDM(Fisher), ๐scm, y; args...)
cvMDMlw = cvAcc(MDM(Fisher), ๐lw, y; args...)
cvMDMnlw = cvAcc(MDM(Fisher), ๐nlw, y; args...)
# Lasso Logistic Regression (TS)
args=(shuffle=true, tol=1e-5, w=:b)
# Lasso Logistic Regression (TS) with reduced tangent vectors
cvLASSO = cvAcc(ENLR(Fisher), ๐, y; vecRange=1:ne, args...)
# Elastic-Net Logistic Regression (TS) with reduced tangent vectors
cvElNet05r = cvAcc(ENLR(Fisher), ๐, y; vecRange=1:ne, alpha=0.5, args...)
cvLASSOscm = cvAcc(ENLR(Fisher), ๐scm, y; vecRange=1:ne, args...)
cvLASSOlw = cvAcc(ENLR(Fisher), ๐lw, y; vecRange=1:ne, args...)
cvLASSOnl = cvAcc(ENLR(Fisher), ๐nl, y; vecRange=1:ne, args...)
# TArget geometric mean
# TAgm, iter, conv = gMean(โVector([๐[i] for i in eachindex(๐) if y[i]==2]); โฐ=true)
# Non Target geometric mean
# NTgm, iter, conv = gMean(โVector([๐[i] for i in eachindex(๐) if y[i]==1]); โฐ=true)
# using Plots
# heatmap(Matrix(TAgm); c=:bluesreds)
################ Example for working with a particular file, e.g., file 10
o=readNY(files[10]; bandpass=(1, 16), msg="read file: $(basename(file))")
# type `o` (letter o) and press the ENTER key in the REPL to see the structure
# multivariate regression ERP mean with data-driven weights
w=[[1/(norm(o.X[o.cstim[i][j]+o.offset:o.cstim[i][j]+o.offset+o.wl-1,:])^2) for j=1:length(o.cstim[i])] for i=1:o.nc]
Y=mean(o.X, o.wl, o.cstim; weights=w)[2]
# PCA to keep only 4 components
Y=Y*eigvecs(cov(SimpleCovariance(), Y))[:, o.ne-3:o.ne]
# encoding
covEstimator=LinearShrinkage(ConstantCorrelation())
๐lw=โVector([โ(cov(covEstimator, [X Y])) for X โ o.trials])
# MDM classification
args=(shuffle=true, tol=1e-5)
cvMDMlw = cvAcc(MDM(Fisher), ๐lw, o.y; args...)
# release memory
waste(o)
=#