-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcode.py
More file actions
2244 lines (1813 loc) · 83.2 KB
/
code.py
File metadata and controls
2244 lines (1813 loc) · 83.2 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
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import torch
import pandas as pd
import numpy as np
from scipy import stats
import unittest
from torch.utils.data import Dataset
def generate_bigram_sequence(n_tokens = 5, seqlen = 1000, sparsity = 0):
'''Generates a random sequence with random bigram statistics.'''
# Initial distribution of tokens
probs_initial = np.random.dirichlet(np.ones(n_tokens))
# Initialize conditional probability matrix
probs_cond = np.zeros((n_tokens, n_tokens))
# Set up conditional distributions
for token_n in range(n_tokens):
# Sample from a dirichlet distribution
probs_cond[token_n, :] = np.random.dirichlet(np.ones(n_tokens))
# Initialize sequence
sequence = np.zeros(seqlen,dtype=int)
# Sample initial token
sequence[0] = np.random.choice(n_tokens, 1, p = probs_initial)+1
# Generate subsequent samples
for pos in range(1, seqlen):
sequence[pos] = np.random.choice(n_tokens, 1, p = probs_cond[(sequence[pos-1]-1),:])+1
# Make some tokens zero
mask = np.random.rand(seqlen) < sparsity
sequence[mask] = 0
return sequence, probs_cond
pass
# Test
# def Bigram_Unit_Test(n_tokens):
n_tokens = 5
sequence, probs_cond = generate_bigram_sequence(n_tokens=n_tokens, seqlen=10000, sparsity=0)
# Test 1: Check sequence length
assert len(sequence) == 10000, "Sequence length is incorrect."
# Test 2: Check token range (1 to n_tokens)
assert np.all((sequence >= 1) & (sequence <= n_tokens)), "Tokens are out of range."
# Test 3: Check first token is not zero
assert sequence[0] != 0, "The first token should not be zero."
# Test 4: Check conditional probabilities are similar
# Find all the places we see one
# Find all the times you see a two afterwards
empirical_prob = np.zeros_like(probs_cond)
for i in range(n_tokens):
for j in range(n_tokens):
location_i = np.where(sequence==i+1)[0]
location_j = np.where(sequence==j+1)[0]
count = 0
for k in location_i:
if k + 1 in location_j:
count += 1
empirical_prob[i, j] = count/len(location_i)
print(abs(empirical_prob - probs_cond)/probs_cond)
# If all 4 tests pass, print "All tests passed!"
print("All tests passed!")
~~~
import matplotlib.pyplot as plt
import seaborn as sns
# Function to plot a heatmap for a matrix
def plot_heatmap(matrix, title="Heatmap", x_labels=None, y_labels=None):
plt.figure(figsize=(8, 6))
sns.heatmap(matrix, annot=True, cmap="coolwarm", cbar=True, xticklabels=x_labels, yticklabels=y_labels)
plt.title(title)
plt.show()
# Example labels for visualization
labels = [f"Token {i+1}" for i in range(n_tokens)]
# Plot heatmaps for both empirical and conditional probabilities
plot_heatmap(empirical_prob, title="Empirical Probability Heatmap", x_labels=labels, y_labels=labels)
plot_heatmap(probs_cond, title="Conditional Probability Heatmap", x_labels=labels, y_labels=labels)
# *** Add both Bigram_Unit_Test & Heatmap to github models if needed ***
~~~
# Write a small python program, using Numpy, which computes this gradient, using only linear algebra and hand-coded derivative calculations
# Loop over this program to perform gradient descent on the network and plot the loss over all epochs/iterations (100)
import numpy as np
import matplotlib.pyplot as plt
def compute_gradient(W, x, y_true):
# Step 1: Compute the predicted output y_pred = W * x
y_pred = np.dot(W, x)
# Step 2: Compute the error e = y_pred - y_true
e = y_pred - y_true
# Step 3: Compute the gradient of loss with respect to weights, dL/dW = e * x
gradient = e * x.T
# The gradient is computed as the error (e) multiplied by the transposed input vector (x)
return y_pred, gradient
def gradient_descent(W, x, y_true, learning_rate, epochs):
# Perform gradient descent for a fixed number (100) of epochs
# Where we store loss values for plotting purposes
losses = []
for i in range(epochs):
# Compute the predicted output and gradient
y_pred, gradient = compute_gradient(W, x, y_true)
# Update the weights using gradient descent rule
W = W - learning_rate * gradient
# Print the loss for tracking purposes
loss = 0.5 * np.square(y_pred - y_true)
# Store the loss values for plotting purposes
losses.append(loss.item())
print(f"Epoch {i+1}: Loss = {loss}, Weights = {W}")
return W, losses
# Define input vector x, weight matrix W, true output y_true, learning rate, and number of iterations (epochs)
x = np.array([[1], [2], [3]]) # Input vector (3x1)
W = np.array([[0.2, 0.4, 0.6]]) # Initial weight matrix (1x3)
y_true = np.array([[1]]) # True output (scalar)
learning_rate = 0.01 # Learning rate (Seemed reasonable based on what I could find online, also saw 3e-4 aka The Adam Optimizer)
epochs = 100 # Number of iterations
# Perform gradient descent to optimize the weights
optimized_W, losses = gradient_descent(W, x, y_true, learning_rate, epochs)
# Plot the loss over all the iterations
plt.plot(range(epochs), losses)
plt.xlabel('Epoch')
plt.ylabel('Loss')
plt.title('Loss over Training Iterations/Epochs')
plt.grid(True)
plt.show()
# Print the final optimized weights
print("Final optimized weights:", optimized_W)
~~~
import numpy as np
import plotly.graph_objects as go
def visualize_3d_surface():
# Define the parameter space with an (x, y) grid for the surface
x_vals = np.linspace(-2, 2, 50)
y_vals = np.linspace(-2, 2, 50)
x, y = np.meshgrid(x_vals, y_vals)
# Define the surface (a combination of quadratic and sinusoidal shapes)
z = x**2 - y**2 + np.sin(3*x)*np.cos(3*y)
# Create a 3D surface plot
fig = go.Figure(data=[go.Surface(z = z, x = x, y = y, colorscale='Viridis')])
# Update layout
fig.update_layout(
title = 'Gradient Descent Visualization',
scene = dict(
xaxis_title = "X",
yaxis_title = "Y",
zaxis_title = "Z"
),
scene_camera = dict(
up = dict(x=0, y=0, z=1),
)
)
# Show the plot & visualize the surface
fig.show()
visualize_3d_surface()
~~~
# Generate Synthetic EEG Data
import numpy as np
import matplotlib.pyplot as plt
# Generate synthetic EEG data with delta, theta, alpha, beta, and gamma waves
def generate_synthetic_eeg_with_multiple_waves(duration = 10, sampling_rate = 250, noise_level = 0.5):
time = np.arange(0, duration, 1/sampling_rate)
# 250 samples per second over a duration of 10 sec so 2500 samples
# Generate different EEG frequency components (choose average of range)
delta_wave = np.sin(2 * np.pi * 2.25 * time) # Delta (0.5-4 Hz)
theta_wave = np.sin(2 * np.pi * 6 * time) # Theta (4-8 Hz)
alpha_wave = np.sin(2 * np.pi * 10 * time) # Alpha (8-12 Hz)
beta_wave = np.sin(2 * np.pi * 21 * time) # Beta (12-30 Hz)
gamma_wave = np.sin(2 * np.pi * 65 * time) # Gamma (30-100 Hz)
# Combine the different waves into a single EEG signal
eeg_signal = delta_wave + theta_wave + alpha_wave + beta_wave + gamma_wave
# Add random noise to simulate real EEG data
noise = noise_level * np.random.randn(len(time))
# np.random.randn was chosen due to having a standard normal distribution with a mean of 0 and a standard deviation of 1
# Combine the signal with noise
return time, eeg_signal + noise
# Generate the synthetic EEG signal with multiple waves
time, synthetic_eeg = generate_synthetic_eeg_with_multiple_waves()
# Plotting the synthetic EEG signal
plt.figure(figsize=(10, 4))
plt.plot(time, synthetic_eeg)
plt.title('Synthetic EEG Data')
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.show()
~~~
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import stft, istft
# Use synthetic EEG signal generated earlier
time, synthetic_eeg = generate_synthetic_eeg_with_multiple_waves()
# STFT parameters
window = 'hann'
nperseg = 256 # Length of each segment for STFT
noverlap = 128 # Overlap between segments
# Apply STFT to decompose into time-frequency representation
frequencies, times, Zxx = stft(synthetic_eeg, fs=250, window=window, nperseg=nperseg, noverlap=noverlap)
# Reconstruct the signal for each EEG frequency band
def reconstruct_band(frequencies, Zxx, fmin, fmax):
# Create a mask for the desired frequency range
band_mask = (frequencies >= fmin) & (frequencies <= fmax)
# Zero out all frequencies outside the band
Zxx_band = np.copy(Zxx)
Zxx_band[~band_mask, :] = 0
# Perform the inverse STFT to reconstruct the signal in this band
_, reconstructed_signal = istft(Zxx_band, fs=250, window=window, nperseg=nperseg, noverlap=noverlap)
return reconstructed_signal
# Reconstruct signals for each frequency band
delta_wave_reconstructed = reconstruct_band(frequencies, Zxx, 0.5, 4)
theta_wave_reconstructed = reconstruct_band(frequencies, Zxx, 4, 8)
alpha_wave_reconstructed = reconstruct_band(frequencies, Zxx, 8, 12)
beta_wave_reconstructed = reconstruct_band(frequencies, Zxx, 12, 30)
gamma_wave_reconstructed = reconstruct_band(frequencies, Zxx, 30, 100)
# Adjust the length of the reconstructed signal to match the original time array
min_length = min(len(time), len(delta_wave_reconstructed))
# Trim all reconstructed waves to match the length of the original time array
delta_wave_reconstructed = delta_wave_reconstructed[:min_length]
theta_wave_reconstructed = theta_wave_reconstructed[:min_length]
alpha_wave_reconstructed = alpha_wave_reconstructed[:min_length]
beta_wave_reconstructed = beta_wave_reconstructed[:min_length]
gamma_wave_reconstructed = gamma_wave_reconstructed[:min_length]
# Also, trim the time array if necessary
time_trimmed = time[:min_length]
# Plot the original EEG signal and the reconstructed sine waves from each frequency band
plt.figure(figsize=(12, 10))
plt.subplot(6, 1, 1)
plt.plot(time_trimmed, synthetic_eeg[:min_length], label="Original Synthetic EEG Signal")
plt.title("Original EEG Signal")
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.subplot(6, 1, 2)
plt.plot(time_trimmed, delta_wave_reconstructed, label="Delta Wave (0.5-4 Hz)", color='blue')
plt.title("Reconstructed Delta Wave (0.5-4 Hz)")
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.subplot(6, 1, 3)
plt.plot(time_trimmed, theta_wave_reconstructed, label="Theta Wave (4-8 Hz)", color='green')
plt.title("Reconstructed Theta Wave (4-8 Hz)")
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.subplot(6, 1, 4)
plt.plot(time_trimmed, alpha_wave_reconstructed, label="Alpha Wave (8-12 Hz)", color='red')
plt.title("Reconstructed Alpha Wave (8-12 Hz)")
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.subplot(6, 1, 5)
plt.plot(time_trimmed, beta_wave_reconstructed, label="Beta Wave (12-30 Hz)", color='purple')
plt.title("Reconstructed Beta Wave (12-30 Hz)")
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.subplot(6, 1, 6)
plt.plot(time_trimmed, gamma_wave_reconstructed, label="Gamma Wave (30-100 Hz)", color='orange')
plt.title("Reconstructed Gamma Wave (30-100 Hz)")
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.tight_layout()
plt.show()
~~~
# DWT Decomposition and Reconstruction
!pip install PyWavelets
import pywt
def dwt_decompose_reconstruct(signal):
# Perform single-level DWT decomposition using 'db4' (Daubechies wavelet)
coeffs = pywt.wavedec(signal, 'db4', level=4)
reconstructed_signal = pywt.waverec(coeffs, 'db4')
return reconstructed_signal
# Decompose and reconstruct the synthetic EEG signal
reconstructed_eeg = dwt_decompose_reconstruct(synthetic_eeg)
# Plot original vs reconstructed
plt.figure(figsize=(10, 6))
plt.subplot(2, 1, 1)
plt.plot(time, synthetic_eeg, label="Original Synthetic EEG Signal")
plt.title("Original EEG Signal")
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.subplot(2, 1, 2)
plt.plot(time[:len(reconstructed_eeg)], reconstructed_eeg, label="Reconstructed EEG Signal", color='orange')
plt.title("Reconstructed EEG Signal from DWT")
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.tight_layout()
plt.show()
~~~
from scipy.signal import stft, istft
sampling_rate = 250
# Short-Time Fourier Transform (STFT)
def compute_stft(signal, sampling_rate):
f, t, Zxx = stft(signal, fs=sampling_rate, nperseg=256)
return f, t, Zxx
# Compute STFT
frequencies, times, Zxx = compute_stft(synthetic_eeg, sampling_rate)
# Plot the STFT Magnitude (Spectrogram)
plt.pcolormesh(times, frequencies, np.abs(Zxx), shading='gouraud')
plt.title('STFT Magnitude Spectrogram')
plt.ylabel('Frequency [Hz]')
plt.xlabel('Time [sec]')
plt.colorbar()
plt.show()
~~~
import numpy as np
import matplotlib.pyplot as plt
from scipy.signal import stft, istft
# Set the parameters for the EEG-like signal
duration = 10 # Total duration in seconds
sampling_rate = 250 # Sampling rate in Hz
time = np.arange(0, duration, 1 / sampling_rate)
# Define token-specific frequencies and amplitudes
frequencies = {'delta': 2, 'alpha': 10, 'gamma': 40} # Hz for each token
amplitudes = {'delta': 2.0, 'alpha': 1.5, 'gamma': 0.8} # Arbitrary amplitudes for each token
# Generate a synthetic EEG signal by concatenating chunks for each token
def generate_token_chunk(frequency, amplitude, duration, sampling_rate):
t = np.arange(0, duration, 1 / sampling_rate)
return amplitude * np.sin(2 * np.pi * frequency * t)
# Concatenate chunks for each token in sequence (without noise initially)
delta_chunk = generate_token_chunk(frequencies['delta'], amplitudes['delta'], duration/3, sampling_rate)
alpha_chunk = generate_token_chunk(frequencies['alpha'], amplitudes['alpha'], duration/3, sampling_rate)
gamma_chunk = generate_token_chunk(frequencies['gamma'], amplitudes['gamma'], duration/3, sampling_rate)
synthetic_eeg_no_noise = np.concatenate((delta_chunk, alpha_chunk, gamma_chunk))
# Plot the synthetic EEG data without noise
plt.figure(figsize=(12, 4))
plt.plot(np.arange(len(synthetic_eeg_no_noise)) / sampling_rate, synthetic_eeg_no_noise)
plt.title("Synthetic EEG Signal without Noise")
plt.xlabel("Time (s)")
plt.ylabel("Amplitude")
plt.show()
# Apply STFT to the synthetic EEG signal
frequencies, times, Zxx = stft(synthetic_eeg_no_noise, fs=sampling_rate, nperseg=128)
# Plot the magnitude of STFT without noise
plt.figure(figsize=(12, 6))
plt.pcolormesh(times, frequencies, np.abs(Zxx), shading='gouraud')
plt.title("STFT Magnitude of Synthetic EEG Signal without Noise")
plt.xlabel("Time (s)")
plt.ylabel("Frequency (Hz)")
plt.colorbar(label="Magnitude")
plt.show()
# Now, add random noise to the signal and recompute STFT
noise_level = 0.5 # Adjust based on desired noise strength
synthetic_eeg_with_noise = synthetic_eeg_no_noise + noise_level * np.random.randn(len(synthetic_eeg_no_noise))
# Apply STFT to the noisy signal
frequencies, times, Zxx_noisy = stft(synthetic_eeg_with_noise, fs=sampling_rate, nperseg=128)
# Plot the magnitude of STFT with noise
plt.figure(figsize=(12, 6))
plt.pcolormesh(times, frequencies, np.abs(Zxx_noisy), shading='gouraud')
plt.title("STFT Magnitude of Synthetic EEG Signal with Noise")
plt.xlabel("Time (s)")
plt.ylabel("Frequency (Hz)")
plt.colorbar(label="Magnitude")
plt.show()
# Threshold the STFT magnitude to detect significant events
amplitude_threshold = 0.25 # Adjust based on noise level and sensitivity (0.25 seems to be optimal in this model)
event_mask = np.abs(Zxx_noisy) > amplitude_threshold
# Plot events over the STFT magnitude
plt.figure(figsize=(12, 6))
plt.pcolormesh(times, frequencies, np.abs(Zxx_noisy), shading='gouraud')
plt.contour(times, frequencies, event_mask, colors='red', linewidths=0.5)
plt.title("Detected Events in Noisy STFT Signal (Thresholded)")
plt.xlabel("Time (s)")
plt.ylabel("Frequency (Hz)")
plt.show()
~~~
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve, auc
from scipy.signal import stft
# Parameters
duration = 3.333
sampling_rate = 250
frequencies = [2, 6, 10] # delta, theta, alpha
amplitudes = [1.0, 0.8, 0.6] # Amplitudes for each wavelet
ngram = 3
n_tokens = 3
seqlen = 100
noise_level = 0.2 # Standard deviation of the noise
# Generate synthetic EEG with Morlet wavelets
def generate_wavelet_signal(sequence, frequencies, amplitudes, duration, sampling_rate):
signal = []
chunk_length = int(duration * sampling_rate)
t = np.linspace(-1, 1, chunk_length)
gaussian_envelope = np.exp(-t**2)
for token in sequence:
f = frequencies[token]
a = amplitudes[token]
t = np.arange(0, duration, 1 / sampling_rate)
wavelet = a * np.sin(2 * np.pi * f * t)
wavelet = wavelet[:chunk_length] # Trim wavelet to match chunk length
signal.append(wavelet * gaussian_envelope)
return np.concatenate(signal)
# Generate n-gram sequence
def get_ngram_sequence(ngram, n_tokens, seqlen):
probs = np.zeros([n_tokens] * ngram)
for indices in np.ndindex(*probs.shape[:-1]):
probs[(*indices, slice(None))] = np.random.dirichlet(np.ones(n_tokens))
sequence = np.zeros(seqlen, dtype=int)
for pos in range(ngram):
sequence[pos] = np.random.choice(n_tokens, p=np.mean(probs, axis=tuple(range(ngram - (pos + 1))))[tuple(sequence[:pos])])
for pos in range(ngram, seqlen):
sequence[pos] = np.random.choice(n_tokens, p=probs[tuple(sequence[pos - ngram + 1:pos])])
return sequence
# Generate synthetic EEG signal with noise
sequence = get_ngram_sequence(ngram, n_tokens, seqlen)
morlet_signal = generate_wavelet_signal(sequence, frequencies, amplitudes, duration, sampling_rate)
noise = noise_level * np.random.randn(len(morlet_signal))
morlet_signal_noisy = morlet_signal + noise
# Location of wavelets
wavelet_indices = [np.where(sequence == i)[0] for i in range(n_tokens)]
chunk_length = int(duration * sampling_rate)
where_frequency = np.zeros([3, chunk_length * seqlen])
for i, indices in enumerate(wavelet_indices):
for j in indices:
where_frequency[i, (chunk_length * j): (chunk_length * (j + 1))] = 1
# Compute STFT
f, t, Zxx_noisy = stft(morlet_signal_noisy, fs=sampling_rate, nperseg=256)
# Create boundaries to test threshold values on delta, theta, and alpha waves
frequency_boundaries = [0, 4, 8, 12, 30, 100]
delta_row_indices = np.where((f >= frequency_boundaries[0]) & (f < frequency_boundaries[1]))[0]
theta_row_indices = np.where((f >= frequency_boundaries[1]) & (f < frequency_boundaries[2]))[0]
alpha_row_indices = np.where((f >= frequency_boundaries[2]) & (f < frequency_boundaries[3]))[0]
amplitude_threshold = noise_level # Set threshold based on noise level
delta_power_detected = np.mean(np.abs(Zxx_noisy[delta_row_indices, :]) > amplitude_threshold, axis=0)
theta_power_detected = np.mean(np.abs(Zxx_noisy[theta_row_indices, :]) > amplitude_threshold, axis=0)
alpha_power_detected = np.mean(np.abs(Zxx_noisy[alpha_row_indices, :]) > amplitude_threshold, axis=0)
# Threshold f(x)
def threshold_stft(Zxx_noisy, amplitude_threshold, row_indices):
return np.mean(np.abs(Zxx_noisy[row_indices, :]), axis=0) > amplitude_threshold
# Plot the noisy signal
plt.figure()
plt.plot(where_frequency[0,:])
plt.plot(morlet_signal_noisy)
plt.show()
# Plot the power detection of delta waves
plt.figure()
plt.plot(t, delta_power_detected, label="Delta Power Detected")
plt.legend()
plt.show()
plt.figure(figsize=(12, 6))
plt.pcolormesh(t, f, np.abs(Zxx_noisy), shading='gouraud')
plt.title("STFT Magnitude of Synthetic EEG Signal with Noise")
plt.xlabel("Time (s)")
plt.ylabel("Frequency (Hz)")
plt.colorbar(label="Magnitude")
plt.show()
~~~
# Code to find the closest frequency indices in the STFT output for extracting relevant frequency bands
# Find closest frequency indices
freq_indices = [np.abs(f - target_freq).argmin() for target_freq in frequencies]
# Downsample ground truth to match STFT time bins
ground_truth = (np.array(sequence) == 1).astype(int)
# upsample to length of band power instead of downsampling
downsampled_ground_truth = np.interp(t, np.linspace(0, len(sequence), len(sequence)), ground_truth)
# Events detected
for i in np.arange(2, 0, -.1):
delta_power_detected = threshold_stft(Zxx_noisy, i, delta_row_indices)
theta_power_detected = threshold_stft(Zxx_noisy, i, theta_row_indices)
alpha_power_detected = threshold_stft(Zxx_noisy, i, alpha_row_indices)
def event_combiner(power_detected):
rolled = np.roll(power_detected, 1)
rolled[0] == 0
power_detected[-1] == 0
stay_same = np.roll(power_detected, 1) == power_detected
change = np.roll(power_detected, 1) != power_detected
locations = np.where(change)
location_begin = locations[0::2]
location_end = locations[1::2]
return locations
event_combiner(delta_power_detected)
~~~
# ROC Analysis
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve, auc
from scipy.signal import stft
import pandas as pd
from tqdm import tqdm
# Parameters
duration = 3.333
sampling_rate = 250
# Delta, Theta, Alpha, Beta, & amma waves
frequencies = [2, 6, 10, 20, 40]
# Decreased amplitudes for higher frequencies to match realistic EEG characteristics
amplitudes = [1.0, 0.8, 0.6, 0.4, 0.3]
ngram = 5
n_tokens = 5
seqlen = 100
noise_levels = [0.1, 0.2, 0.5, 1.0, 2.0]
wave_names = ['Delta', 'Theta', 'Alpha', 'Beta', 'Gamma']
frequency_boundaries = [0, 4, 8, 12, 30, 100]
# Generate synthetic EEG with Morlet wavelets
def generate_wavelet_signal(sequence, frequencies, amplitudes, duration, sampling_rate):
signal = []
chunk_length = int(duration * sampling_rate)
for token in sequence:
t = np.linspace(-1, 1, chunk_length)
gaussian_envelope = np.exp(-t**2)
f = frequencies[token]
a = amplitudes[token]
t = np.arange(0, duration, 1 / sampling_rate)
wavelet = a * np.sin(2 * np.pi * f * t)
wavelet = wavelet[:chunk_length]
signal.append(wavelet * gaussian_envelope)
return np.concatenate(signal)
# Generate n-gram sequence
def get_ngram_sequence(ngram, n_tokens, seqlen):
sequence = np.random.choice(n_tokens, seqlen)
return sequence
# Function to calculate ROC for multiple thresholds
def calculate_roc_for_thresholds(signal, ground_truth, thresholds, wave_type, noise_level):
results = []
for threshold in thresholds:
detected = signal > threshold
fpr, tpr, _ = roc_curve(ground_truth, signal)
roc_auc = auc(fpr, tpr)
# Calculate precision
true_positives = np.sum(detected & ground_truth.astype(bool))
false_positives = np.sum(detected & ~ground_truth.astype(bool))
precision = true_positives / (true_positives + false_positives) if (true_positives + false_positives) > 0 else 0
results.append({
'Wave': wave_type,
'Noise': noise_level,
'Threshold': threshold,
'AUC': roc_auc,
'Precision': precision,
'FPR': fpr,
'TPR': tpr
})
return results
# Helper function to generate and visualize sample signals
def visualize_sample_signals():
plt.figure(figsize=(15, 20))
# Generate one sample with all wave types for comparison
plt.subplot(len(noise_levels)+1, 2, 1)
for i, (freq, amp) in enumerate(zip(frequencies, amplitudes)):
t = np.arange(0, 1, 1/sampling_rate)
wavelet = amp * np.sin(2 * np.pi * freq * t)
t_gaussian = np.linspace(-1, 1, len(wavelet))
gaussian_envelope = np.exp(-t_gaussian**2)
plt.plot(wavelet * gaussian_envelope, label=f"{wave_names[i]} ({freq} Hz)")
plt.title("Sample of All Wave Types")
plt.legend()
plt.xlabel("Sample")
plt.ylabel("Amplitude")
# Generate noise level samples
for i, noise_level in enumerate(noise_levels):
sequence = get_ngram_sequence(ngram, n_tokens, 5) # Short sequence for visualization
clean_signal = generate_wavelet_signal(sequence, frequencies, amplitudes, duration, sampling_rate)
noisy_signal = clean_signal + noise_level * np.random.randn(len(clean_signal))
plt.subplot(len(noise_levels)+1, 2, i*2+3)
plt.plot(clean_signal)
plt.title(f'Clean Signal Sample (Noise={noise_level})')
plt.xlabel('Sample')
plt.ylabel('Amplitude')
plt.subplot(len(noise_levels)+1, 2, i*2+4)
plt.plot(noisy_signal)
plt.title(f'Noisy Signal Sample (Noise={noise_level})')
plt.xlabel('Sample')
plt.ylabel('Amplitude')
plt.tight_layout()
plt.savefig('eeg_signal_samples.png', dpi=300)
plt.show()
# Main experiment runner
def run_eeg_wavelet_experiments(noise_levels, n_repeats=5):
all_results = []
# Visualize sample signals first
visualize_sample_signals()
for noise_level in tqdm(noise_levels, desc="Processing noise levels"):
# Adjust threshold range based on noise level
max_threshold = max(3 * noise_level, 1.0)
thresholds = np.linspace(0, max_threshold, 20)
for repeat in range(n_repeats):
# Generate data
sequence = get_ngram_sequence(ngram, n_tokens, seqlen)
morlet_signal = generate_wavelet_signal(sequence, frequencies, amplitudes, duration, sampling_rate)
noise = noise_level * np.random.randn(len(morlet_signal))
morlet_signal_noisy = morlet_signal + noise
# Ground truth wavelet locations
wavelet_indices = [np.where(sequence == i)[0] for i in range(n_tokens)]
chunk_length = int(duration * sampling_rate)
where_frequency = np.zeros([n_tokens, chunk_length * seqlen])
for i, indices in enumerate(wavelet_indices):
for j in indices:
where_frequency[i, (chunk_length * j): (chunk_length * (j + 1))] = 1
# Compute STFT with adjusted window size for higher noise levels
nperseg = 256
noverlap = 192
f, t, Zxx_noisy = stft(morlet_signal_noisy, fs=sampling_rate, nperseg=nperseg, noverlap=noverlap)
# Create time-aligned ground truth by interpolating
time_step = duration * seqlen / t.shape[0]
aligned_truth = []
for i in range(n_tokens):
# Interpolate ground truth to match STFT time points
interp_truth = np.zeros(t.shape[0])
for j in range(t.shape[0]):
time_point = j * time_step
idx = int(time_point * sampling_rate)
if idx < where_frequency.shape[1]:
interp_truth[j] = where_frequency[i, idx]
aligned_truth.append(interp_truth)
# Extract frequency bands
band_indices = []
for i in range(len(frequency_boundaries) - 1):
indices = np.where((f >= frequency_boundaries[i]) & (f < frequency_boundaries[i+1]))[0]
band_indices.append(indices)
for i in range(n_tokens):
# Calculate power in each frequency band
# For Gamma, use additional smoothing for noise reduction
if i == 4: # Gamma
# Use a more robust method for high frequency detection
band_power = np.mean(np.abs(Zxx_noisy[band_indices[i], :]), axis=0)
# Apply smoothing
window_size = 3
band_power = np.convolve(band_power, np.ones(window_size)/window_size, mode='same')
else:
band_power = np.mean(np.abs(Zxx_noisy[band_indices[i], :]), axis=0)
# Calculate ROC statistics for this band
results = calculate_roc_for_thresholds(
band_power,
aligned_truth[i],
thresholds,
wave_names[i],
noise_level
)
all_results.extend(results)
return pd.DataFrame(all_results)
# Plot functions to generate a color palette
def get_wave_colors(wave_names):
# Define a specific color for each wave type
colors = {
'Delta': '#1f77b4', # blue
'Theta': '#ff7f0e', # orange
'Alpha': '#2ca02c', # green
'Beta': '#d62728', # red
'Gamma': '#9467bd' # purple
}
return [colors[wave] for wave in wave_names]
# Run experiments and analyze results
def analyze_and_plot_results():
# Run the experiments
results_df = run_eeg_wavelet_experiments(noise_levels)
# Get colors for each wave type
colors = get_wave_colors(wave_names)
# Plot ROC curves for each wave type and noise level
plt.figure(figsize=(15, 15))
for i, noise in enumerate(noise_levels):
plt.subplot(3, 2, i+1)
for j, wave in enumerate(wave_names):
wave_results = results_df[(results_df['Wave'] == wave) & (results_df['Noise'] == noise)]
if not wave_results.empty:
best_result = wave_results.loc[wave_results['Precision'].idxmax()]
plt.plot(
best_result['FPR'],
best_result['TPR'],
label=f"{wave} (AUC={best_result['AUC']:.2f})",
color=colors[j]
)
plt.plot([0, 1], [0, 1], 'k--')
plt.xlabel('False Positive Rate')
plt.ylabel('True Positive Rate')
plt.title(f'ROC Curves for Noise Level {noise}')
plt.legend()
plt.grid(True, alpha=0.3)
plt.tight_layout()
plt.savefig('eeg_wavelet_roc_curves.png', dpi=300)
plt.show()
# Plot AUC vs Noise Level for each wave type
plt.figure(figsize=(10, 6))
for j, wave in enumerate(wave_names):
best_results = []
for noise in noise_levels:
wave_results = results_df[(results_df['Wave'] == wave) & (results_df['Noise'] == noise)]
if not wave_results.empty:
best_result = wave_results.loc[wave_results['Precision'].idxmax()]
best_results.append({
'Noise': noise,
'AUC': best_result['AUC']
})
noise_vs_auc = pd.DataFrame(best_results)
plt.plot(noise_vs_auc['Noise'], noise_vs_auc['AUC'], 'o-', label=wave, color=colors[j])
plt.xlabel('Noise Level')
plt.ylabel('AUC Score')
plt.title('AUC Score vs Noise Level for Different Wave Types')
plt.legend()
plt.grid(True, alpha=0.3)
plt.savefig('eeg_wavelet_auc_vs_noise.png', dpi=300)
plt.show()
# Plot Precision vs Noise Level
plt.figure(figsize=(10, 6))
for j, wave in enumerate(wave_names):
best_results = []
for noise in noise_levels:
wave_results = results_df[(results_df['Wave'] == wave) & (results_df['Noise'] == noise)]
if not wave_results.empty:
best_result = wave_results.loc[wave_results['Precision'].idxmax()]
best_results.append({
'Noise': noise,
'Precision': best_result['Precision']
})
noise_vs_precision = pd.DataFrame(best_results)
plt.plot(noise_vs_precision['Noise'], noise_vs_precision['Precision'], 'o-', label=wave, color=colors[j])
plt.xlabel('Noise Level')
plt.ylabel('Precision')
plt.title('Precision vs Noise Level for Different Wave Types')
plt.legend()
plt.grid(True, alpha=0.3)
plt.savefig('eeg_wavelet_precision_vs_noise.png', dpi=300)
plt.show()
# Generate performance summary table
performance_summary = results_df.groupby(['Wave', 'Noise']).apply(
lambda x: x.loc[x['Precision'].idxmax()]
)[['AUC', 'Precision', 'Threshold']].reset_index()
print("Performance Summary (Best Precision for Each Wave Type and Noise Level):")
print(performance_summary.to_string(index=False))
# Plot a combined visualization of all wave types at optimal thresholds
plt.figure(figsize=(15, 10))
best_thresholds = {}
for wave in wave_names:
# Get median best threshold for this wave type
wave_results = performance_summary[performance_summary['Wave'] == wave]
median_threshold = wave_results['Threshold'].median()
best_thresholds[wave] = median_threshold
# Generate a sample with all wave types
t = np.arange(0, 2, 1/sampling_rate)
combined_signal = np.zeros_like(t)
for i, (wave, freq, amp) in enumerate(zip(wave_names, frequencies, amplitudes)):
component = amp * np.sin(2 * np.pi * freq * t) * np.exp(-(t-1)**2)
combined_signal += component
plt.plot(t, component, label=f"{wave} ({freq} Hz)", color=colors[i], alpha=0.5)
plt.plot(t, combined_signal, 'k-', label='Combined Signal', linewidth=2)
plt.xlabel('Time (s)')
plt.ylabel('Amplitude')
plt.title('EEG Wave Components')
plt.legend()
plt.grid(True, alpha=0.3)
plt.savefig('eeg_wave_components.png', dpi=300)
plt.show()
return results_df, performance_summary
# Run the analysis directly
results_df, performance_summary = analyze_and_plot_results()
~~~
# ROC Analysis - White Noise Version
import numpy as np
import matplotlib.pyplot as plt
from sklearn.metrics import roc_curve, auc
from scipy.signal import stft
import pandas as pd
from tqdm import tqdm
# Parameters
duration = 3.333
sampling_rate = 250
# Delta, Theta, Alpha, Beta, & Gamma waves
frequencies = [2, 6, 10, 20, 40]
# Decreased amplitudes for higher frequencies to match realistic EEG characteristics
amplitudes = [1.0, 0.8, 0.6, 0.4, 0.3]
ngram = 5
n_tokens = 5
seqlen = 100
# Extended noise levels to push all frequencies to AUC of 0.5 or below
noise_levels = [0.1, 0.2, 0.5, 1.0, 2.0, 5.0, 10.0, 20.0, 50.0, 100.0, 200.0, 500.0]
wave_names = ['Delta', 'Theta', 'Alpha', 'Beta', 'Gamma']
frequency_boundaries = [0, 4, 8, 12, 30, 100]
# Generate synthetic EEG with Morlet wavelets
def generate_wavelet_signal(sequence, frequencies, amplitudes, duration, sampling_rate):
signal = []
chunk_length = int(duration * sampling_rate)
for token in sequence:
t = np.linspace(-1, 1, chunk_length)
gaussian_envelope = np.exp(-t**2)
f = frequencies[token]
a = amplitudes[token]
t = np.arange(0, duration, 1 / sampling_rate)
wavelet = a * np.sin(2 * np.pi * f * t)
wavelet = wavelet[:chunk_length]
signal.append(wavelet * gaussian_envelope)
return np.concatenate(signal)
# Generate n-gram sequence
def get_ngram_sequence(ngram, n_tokens, seqlen):
sequence = np.random.choice(n_tokens, seqlen)
return sequence
# Function to calculate ROC for multiple thresholds
def calculate_roc_for_thresholds(signal, ground_truth, thresholds, wave_type, noise_level):
results = []
for threshold in thresholds:
detected = signal > threshold
fpr, tpr, _ = roc_curve(ground_truth, signal)
roc_auc = auc(fpr, tpr)
# Calculate precision
true_positives = np.sum(detected & ground_truth.astype(bool))
false_positives = np.sum(detected & ~ground_truth.astype(bool))
precision = true_positives / (true_positives + false_positives) if (true_positives + false_positives) > 0 else 0
results.append({
'Wave': wave_type,
'Noise': noise_level,
'Threshold': threshold,
'AUC': roc_auc,
'Precision': precision,
'FPR': fpr,
'TPR': tpr
})
return results
# Bright and visually appealing color palette function
def get_bright_colors(wave_names):
# Define bright, visually appealing colors for each wave type
colors = {
'Delta': '#4169E1', # royal blue
'Theta': '#FF8C00', # dark orange