-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathMain_Script_PLS_Analysis
More file actions
1874 lines (1355 loc) · 99.1 KB
/
Copy pathMain_Script_PLS_Analysis
File metadata and controls
1874 lines (1355 loc) · 99.1 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
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import sklearn as scikitlearn
import scipy
import bokeh as bokeh
import enigmatoolbox
import os as os
import nilearn as nl
import nibabel as nibl
from nilearn import plotting
from nilearn import image
import statsmodels
import pingouin
import sympy as symbol_py
#This is to check WHERE your data are
dir_good = "/Users/alexander_bailey/Desktop/QPN_fMRI_Data"
!nib-ls /Users/alexander_bailey/Desktop/QPN_fMRI_Data/*/func/*MNI152NLin2009cAsym_res-2_desc-preproc_bold.nii.gz
#Now, I want to select my specific fMRI files, so let's use glob.glob to do just that
dir_path = dir_good
# Which subjects to consider for main process
sub_index = np.array(data_frame_neuropsych_main_composites['ID'])
print(sub_index)
#Let's set up our pathnames
indexes_files_good = []
for sub in range(len(sub_index)):
indexes_files_good.append(dir_path + '/' + str(sub_index[sub]))
import glob as glob
rest_files = []
for i in range(len(indexes_files_good)):
rest_files.append(glob.glob(str(indexes_files_good[i]) + '/func/*_ses-01_task-rest_run-1_space-MNI152NLin2009cAsym_res-2_desc-preproc_bold.nii.gz'))
confound_files = []
for i in range(len(indexes_files_good)):
confound_files.append(glob.glob(str(indexes_files_good[i]) + '/func/*_ses-01_task-rest_run-1_desc-confounds_timeseries.tsv'))
#Wonderfully, THIS FOR LOOP WORKS!!! This is the correct code to find our participants and in their proper order
## Now, let's get our data into the correct file format (notice that you need to concatenate in order to have a single array/vector, or Python will NOT be happy!
rest_files = list(np.concatenate(rest_files, axis=None))
confound_files = list(np.concatenate(confound_files, axis=None))
#Now, let's begin the process of making our rsfMRI Corr Plot and get our values; note that we need our confounds to do so
from nilearn import interfaces
confounds_nilearn_full = list()
for i in range(len(rest_files)):
j = interfaces.fmriprep.load_confounds(rest_files[i], global_signal='power2')
confounds_nilearn_full.append(pd.DataFrame(j[0])) #Needed to place it as the 0th index for each j because of the way that nilearn works for this selection process
pd.DataFrame(confounds_nilearn_full) #just to see what we have
#Now, let's get our parcellations up and running
from nilearn import datasets
atlas_schaefer = datasets.fetch_atlas_schaefer_2018(n_rois=400, yeo_networks=17, resolution_mm=1, data_dir=None, base_url=None, resume=True, verbose=1)
atlas_schaefer.labels = np.insert(atlas_schaefer.labels, 0, 'Background')
print(atlas_schaefer)
atlas_schaefer.maps
# Location of Schaefer parcellation atlas
sch_yeo_atlas_file = atlas_schaefer.maps
# Visualize parcellation atlas
plotting.plot_roi(sch_yeo_atlas_file, draw_cross=False, annotate=False);
#Set labels
labels = atlas_schaefer.labels[0:]
#Set our masker
from nilearn.input_data import NiftiLabelsMasker
masker = NiftiLabelsMasker(labels_img=atlas_schaefer.maps, standardize=True, verbose=1, memory="nilearn_cache", memory_level=2)
#Now, let's get our time-series data per ROI
time_series_schaefer = list()
for i in range(len(rest_files)):
index = masker.fit_transform(rest_files[i], confounds = confounds_nilearn_full[i])
time_series_schaefer.append(np.array(index))
print("Now completed: " + " participant" + str(i))#Needed to place it as the 0th index for each j because of the way that nilearn works for this selection process
len(time_series_schaefer)
time_series_schaefer[0] #To check that we have values
#Now, let's make our connectivity matrix
from nilearn.connectome import ConnectivityMeasure
correlation_measure = ConnectivityMeasure(kind='correlation')
correlation_matrix = list()
for i in range(len(time_series_schaefer)):
correlation_matrix.append(correlation_measure.fit_transform([time_series_schaefer[i]])[0])
for i in range(len(time_series_schaefer)):
np.fill_diagonal(correlation_matrix[i], 0)
#Now, let's get this into the proper format
from nilearn.connectome import sym_matrix_to_vec
array = []
for i in range(len(time_series_schaefer)):
array.append(sym_matrix_to_vec(correlation_matrix[i]))
full_array = np.array(array)
np.shape(full_array) #Now we're talking! Double check that the number of rows is equal to the participants that you have. The number of columns should now be in the tens of thousands
#This is our UN-standardized corr matrix
main_df_original = pd.DataFrame(full_array)
#Let's save it to avoid any issues
main_df_original.to_csv('/Users/alexander_bailey/Sharp_Lab/Data/Temp/NEUR608_Main_DF_Original_2.csv', compression={'method': 'gzip', 'compresslevel': 1, 'mtime': 1}, index = False)
data_frame_PLS_fMRI = pd.read_csv('/Users/alexander_bailey/Sharp_Lab/Data/Temp/NEUR608_Main_DF_Original_2.csv', compression= 'gzip')
#Let's edit our labels
corrected_labels = labels[1:]
np.shape(corrected_labels)
corrected_labels
new_corrected_labels = np.array(corrected_labels, dtype = '<U45')
new_corrected_labels = np.char.replace(new_corrected_labels, '17Networks_LH_', 'LH_')
new_corrected_labels = np.char.replace(new_corrected_labels, '17Networks_RH_', 'RH_')
#Now, let's make some new labels (which we can use to show the interaction between ROIs)
names_dataframes = np.array(new_corrected_labels)
labels_new = []
for i in range(len(names_dataframes)):
for j in range(len(names_dataframes)):
labels_new.append(str(names_dataframes[i]) + ' by ' + str(names_dataframes[j]))
labels_new_array = np.array(labels_new) #let's now try to get this back into an array for some easier data wrangling
reshaped_thing = labels_new_array.reshape(400,400)
reshaped_labels_df = pd.DataFrame(reshaped_thing)
reshaped_labels_df #Now we have our labels, but we only need HALF the triangle
work_around = pd.DataFrame(np.triu(reshaped_labels_df)) #Let'd do just that
names_almost = work_around.to_numpy().flatten()
names_perfected = names_almost[names_almost != 0] #This will now reflect ONLY those indices that we have for our rsfMRI Func. Connectivity matrix
names_perfected = np.array(names_perfected, dtype = '<U120') #To make sure that we have all the names
#Let's now add our labels
data_frame_PLS_fMRI.columns = names_perfected
#Let's save it again!
main_df_original.to_csv('/Users/alexander_bailey/Sharp_Lab/Data/Temp/NEUR608_Main_DF_Proper_Labels.csv', compression={'method': 'gzip', 'compresslevel': 1, 'mtime': 1}, index = False)
#Now, let's standardize our dataframe
#Two ways of doing so
#Method 1
import scipy
from scipy import stats
main_df_original_df_standardized = stats.zscore(data_frame_PLS_fMRI)
main_df_original_df_standardized = main_df_original_df_standardized.fillna(0)
#Method 2
from sklearn.preprocessing import StandardScaler
scaler = StandardScaler()
main_df_original_df_standardized_2 = scaler.fit_transform(data_frame_PLS_fMRI)
main_df_original_df_standardized_2 = scaler.fit_transform(data_frame_PLS_fMRI)
scikit_learn_standardized = pd.DataFrame(main_df_original_df_standardized_2)
scikit_learn_standardized.columns = names_perfected
#Now we save again!
main_df_original_df_standardized.to_csv('/Users/alexander_bailey/Sharp_Lab/Data/Temp/NEUR608_Main_DF_Proper_Labels_Standardized.csv', compression={'method': 'gzip', 'compresslevel': 1, 'mtime': 1}, index=False)
## Now It's Time FOR PLS Analysis!!! (PLS-Behavioural)
Initial Step: Make certain that Y Matrix is prepared
Because PLS does not function well with NAs/NANs, we must use imputation
Given that we have a small dataset (n), however, we can use the k nearest neighbours imputation method from VIM; the following code is done in R
library(tidyverse)
library(VIM)
Main_to_add<-read_csv("/Users/alexander_bailey/Sharp_Lab/Data/Temp/NEUR608_2022_UnStandardized_Main_Sample_Variables_to_combine")
Main_to_add$RCFT_Delayed
Indep_to_add<-read_csv("/Users/alexander_bailey/Sharp_Lab/Data/Temp/NEUR608_2022_UnStandardized_Independent_Sample_Variables_to_combine")
Main_to_impute<-Main_to_add %>% bind_rows(Indep_to_add) %>% group_by(New_Groups) %>% arrange(desc(MoCA), .by_group = TRUE) %>% ungroup()
Main_to_impute_group<-Main_to_add %>% bind_rows(Indep_to_add) %>% group_by(New_Groups) %>% arrange(desc(MoCA), .by_group = TRUE)
#But what if we still group?
set.seed(20222210)
total_KNN_grouped<- kNN(Main_to_impute_group, imp_var = FALSE)
total_KNN_grouped #So does the same thing
total_KNN_grouped$RCFT_Delayed
total_KNN$RCFT_Delayed
Main_to_impute
set.seed(20222210)
total_KNN<- kNN(Main_to_impute, imp_var = FALSE)
total_KNN
Main_Ids<- read_csv("/Users/alexander_bailey/Sharp_Lab/Data/Temp/NEUR608_2022_ID_for_seperation.csv") %>% rename(ID = `c(main_test$ID)`)
main_indermediate<- tibble(Main_to_add$ID) %>% rename(ID = `Main_to_add$ID`)
main_indermediate %>% left_join(total_KNN)
main_sample<- main_indermediate %>% left_join(total_KNN)
main_sample #Now we're on our way!
independent_intermediate<- tibble(Indep_to_add$ID) %>% rename(ID = `Indep_to_add$ID`)
independent_sample <- independent_intermediate %>% left_join(total_KNN)
independent_sample #Now, we have our completed sample!
temp_backup_KNN_2_standardized<- scale(temp_backup_KNN_2, center = TRUE, scale = TRUE)
temp_backup_KNN_2_standardized<-as.tibble(temp_backup_KNN_2_standardized)
temp_backup_KNN_2_standardized
main_sample_good_to_standardize<- main_sample %>% select(3:length(main_sample))
indep_sample_good_to_standardize<- independent_sample %>% select(3:length(independent_sample))
Main_KNN_2_standardized<- scale(main_sample_good_to_standardize, center = TRUE, scale = TRUE)
Main_KNN_2_standardized<-as.tibble(Main_KNN_2_standardized)
Main_KNN_2_standardized
Indep_KNN_2_standardized<- scale(indep_sample_good_to_standardize, center = TRUE, scale = TRUE)
Indep_KNN_2_standardized<-as.tibble(Indep_KNN_2_standardized)
Indep_KNN_2_standardized
write_csv(main_sample_good_to_standardize, "/Users/alexander_bailey/Sharp_Lab/Data/Temp/NEUR608_2022_UnStandardized_Main_Sample_Variables_Dec_7_TO_USE.csv") #This is corrected standardized data (more precise for the purposes of PLS-B) - AND IMPORTANTLY! CORRECT FOR ALEX for PLS mappings!
write_csv(indep_sample_good_to_standardize, "/Users/alexander_bailey/Sharp_Lab/Data/Temp/NEUR608_2022_UnStandardized_Independent_Sample_Variables_Dec_7_TO_USE.csv") #This is corrected standardized data (more precise for the purposes of PLS-B) - AND IMPORTANTLY! CORRECT FOR ALEX for PLS mappings!
write_csv(Main_KNN_2_standardized, "/Users/alexander_bailey/Sharp_Lab/Data/Temp/NEUR608_2022_UnStandardized_Main_Sample_Variables_Dec_7_KNN_standardized_TO_USE.csv") #This is corrected standardized data (more precise for the purposes of PLS-B) - AND IMPORTANTLY! CORRECT FOR ALEX!
write_csv(Indep_KNN_2_standardized, "/Users/alexander_bailey/Sharp_Lab/Data/Temp/NEUR608_2022_UnStandardized_Independent_Sample_Variables_Dec_7_KNN_standardized_TO_USE.csv") #This is corrected standardized data (more precise for the purposes of PLS-B) - AND IMPORTANTLY! CORRECT FOR ALEX!
#Step 1 PLS: Import R dataframe with complete demographics and cognitive performance (with all tasks standardized!) - check
#Note that this will become our Y matrix in the PLS formula R = Y'X == U*S*V'
data_frame_neuropsych_main_variables = pd.read_csv("/Users/alexander_bailey/Sharp_Lab/Data/Temp/NEUR608_2022_Standardized_Original_Sample_Variables.csv")
data_frame_neuropsych_main_variables = pd.read_csv(""/Users/alexander_bailey/Sharp_Lab/Data/Temp/NEUR608_2022_UnStandardized_Main_Sample_Variables_Dec_7_KNN_standardized_TO_USE.csv")
#Please note that this particular matrix IS standardized, to help out pyls (thank you Dr. Misic and Dr. Markello!)
#Step 2 PLS: Ensure that we have a standardized X matrix (this will be our FC connections)
#This should be equal to our time series data FOR ALL PARTICIPANTS!
#Note that we also want to standardize this - check out to see if our toolbox (see Step 3) - does this
X_matrix = main_df_original_df_standardized #X_matrix is actually the corr plot that we just made
Y_matrix = data_frame_neuropsych_main_variables
Y_matrix_good_use = Y_matrix.iloc[:, 2:(len(Y_matrix)+1)] #This is to get ONLY those columns that we need (no IDs or Groups!)
#Say that we wanted to add IDs to subset (do not need to use this code, but I played around with it earlier)
Y_matrix_good_test = Y_matrix_good_use.dropna() #There shouldn't be any, due to data imputation with mice
X_matrix.insert(loc = 0,
column = 'IDs',
value = sub_index[0:])
ID_array_key = np.array(Y_matrix_good_test['ID'])
X_matrix_reduced = X_matrix[X_matrix['IDs'].isin(ID_array_key)]
X_matrix_corrected = X_matrix_reduced.drop('IDs', axis=1)
#BACK TO CODE
X_matrix_PLS = X_matrix_corrected.loc[:, (X_matrix_PLS != 0).any(axis=0)]
X_matrix_PLS.shape
##Step 3: Load the PLS function that we have from our cool toolbox!
import pyls as pyls
from pyls import behavioral_pls
help(behavioral_pls) #Just to read more about our function
#behavioral_pls(X, Y, groups=groups, n_cond=n_cond, n_boot = 5000, ci = 95, n_perm = 5000, seed = 20222110)
# BORIS/Bratislav/Neur 608 Tip: Maximal var can be acheived in PLS by NOT USING GROUPS. We can look at groups afterwards for a post-hoc
X_matrix_PLS = X_matrix_corrected
#Now, let's run it!
PD_MCI_PLS = behavioral_pls(X_matrix_PLS, Y_matrix_good_use,groups=None, n_cond=1, n_boot = 5000, ci = 95, n_perm = 5000, seed = 20222110)
#Can't have NAs! AND it wants the matrices to be unstandardized to work.
#IF YOU DIVIDE ZERO BY ZERO YOU GET AN NA! SO!!!! ALEX! DROP NAs from X matrix!
#Note that this take several hours to process! To avoid having to re-run things (or after running, catch yourself from making a mistake to affect the results), let's save our file on our computer
pyls.save_results('/Users/alexander_bailey/Data/Temp', PD_MCI_PLS) #Notice format is "location", then name of file (different from in R!)
PD_MCI_PLS = pyls.load_results('/Users/alexander_bailey/Data/Temp')
print(PD_MCI_PLS) #This will tell you what this new object contains
#How many latent variables do we need? Let's graph it out!
#Method A:
plt.plot(PD_MCI_PLS['varexp'])
plt.axhline(y = 1/(len(PD_MCI_PLS['varexp']), color = 'g') #I just like green for lines
#Method B (get cumulative summary of variance explained):
cum_var_data = []
for i in range(len(PD_MCI_PLS['varexp'])):
if i == 0:
cum_var_data.append(PD_MCI_PLS['varexp'][i])
else:
cum_var_data.append(PD_MCI_PLS['varexp'][i] + cum_data[i-1])
#Let's give a quick look
plt.plot(np.arange(1, 21), cum_data)
plt.axhline(y = .70, color = 'g')
#This should also agree with the previous interpretation
#Method C (in R):
Scree_plot<- read_csv("/Users/alexander_bailey/NEUR608/Data/Temp/Scree_plot_data.csv")
Scree_plot_data<- Scree_plot$`0`
#Now, graph it!
ggplot(Scree_plot, mapping = aes(c(1:21), Scree_plot_data)) +
geom_point() + geom_line() +
xlab("Latent Variable") +
ylab("Variance Explained") +
ggtitle("A) Scree Plot for PLS") +
ylim(0, 0.30) + geom_hline(yintercept=1/21, linetype="dashed", color = "red")
Cumulative_Var<- read_csv("/Users/alexander_bailey/NEUR608/Data/Temp/Cumulative_Variance_data.csv")
vector_var<-c(Cumulative_Var$`0`)
#Now, graph our second plot!
ggplot(Cumulative_Var, mapping = aes(c(1:21), vector_var)) +
geom_point() + geom_line() +
xlab("Latent Variable") +
ylab("Variance Explained") +
ggtitle("B) Cumulative Variance Plot for PLS") +
ylim(0,1) + geom_hline(yintercept=.70, linetype="dashed", color = "red")
#END OF R Analyses (for now!)
#Note: Making a Correlation Plot (Visualize per participant)
#Full plot
plotting.plot_matrix(correlation_matrix[0], figure=(10, 8), labels=labels[1:],
vmax=1, vmin=-1, reorder=True, auto_fit = True)
#Note that at the moment there are A LOT of labels! Working on it to try to adjust this, however!
#Triangle
plotting.plot_matrix(correlation_matrix[0], figure=(10, 8), labels=labels[1:],
vmax=1, vmin=-1, reorder=True, tri='diag', auto_fit = True)
#Post-Hoc Code Coming Up!
#After doing PLS and gotten the number of LCs, checked for permutation significance:
PD_MCI_PLS['permres']['pvals']
PLS_p_values = PD_MCI_PLS['permres']['pvals']
PLS_p_values_for_correction = PLS_p_values[0:6] #Based on choosing 5 LCs
import statsmodels.stats.multitest
from statsmodels.stats.multitest import fdrcorrection
fdrcorrection(PLS_p_values_for_correction, alpha=0.05, method='indep', is_sorted=False)
#Generally, to make graphs, used the following code:
L_x_good = pd.DataFrame(PD_MCI_PLS['x_scores'])
L_y_good = pd.DataFrame(PD_MCI_PLS['y_scores'])
#For Correlation between composites (per LC):
composite_i = sns.scatterplot(L_x_good[i], L_y_good[i], hue = cues)
#Now, we've got it!
#Note i = LC
composite_i.set(xlabel ="RSFC Composite Scores (Lxi)", ylabel = "Behavioural Composite Scores (Lyi)", title ='Correlation Between Composite Scores for LCi')
composite_i.set_xlim(-a, a) #Where a = maximum threshold to ensure for visibility of results
scipy.stats.pearsonr(L_x_good[i], L_y_good[i])
#Next, let's make graphs
import seaborn as sns
%matplotlib inline
cues = Y_matrix["Groups"]
composite_i = sns.scatterplot(L_x_good[0], L_y_good[0], hue = cues) #We got it! Almost!
#Now, we've got it!
composite_i.set(xlabel ="RSFC Composite Scores (Lxi)", ylabel = "Behavioural Composite Scores (Lyi)", title ='Correlation Between Composite Scores for LCi')
composite_i.set_xlim(-b, b) #Where b = maximum threshold to ensure for visibility of results
scipy.stats.pearsonr(L_x_good[0], L_y_good[0])
#Next, we make our bar graphs using Seaborn and Matplotlib
import seaborn as sns
%matplotlib inline
data_frame_RSCF_i = pd.DataFrame(
{'RSFC Composite Scores':L_x_good[i], 'Groups':cues})
data_frame_Behavioural_i = pd.DataFrame(
{'Behavioural Composite Scores':L_y_good[i], 'Groups':cues})
a = sns.barplot(data = data_frame, x = "Groups", y = "XYZ Composite Scores") # data_frame = data_frame_RSCF_i OR data_frame_Behavioural_i ; XYZ == either RSFC Composite Scores OR Behavioural Composite Scores
a.set(title ='Group Differences Between RSFC Composite Scores for LCi')
#Next, we look at statisitcal sign.
groupi_HC_RSFC = np.array(data_frame_RSCF_i.where(data_frame.Groups == "HC").dropna()['RSFC Composite Scores'])
groupi_PD_MCI_RSFC = np.array(data_frame_RSCF_i.where(data_frame_2_comp_2.Groups == "PD_MCI").dropna()['RSFC Composite Scores'])
groupi_PD_NC_RSFC = np.array(data_frame_RSCF_i.where(data_frame_2_comp_2.Groups == "PD_NC").dropna()['RSFC Composite Scores'])
pingouin.ttest(group1_HC_RSFC, group1_PD_MCI_RSFC)
pingouin.ttest(group1_HC_RSFC, group2_PD_NC)
pingouin.ttest(group1_PD_NC_RSFC, group1_PD_MCI_RSFC)
#Then, select p-values from the above pingouin output
p_values_rest_i = np.array([p_val1, p_val2, p_val3])
fdrcorrection(p_values_rest_i, alpha=0.05, method='indep', is_sorted=False)
#Then do the same thing for behaviour
groupi_HC_beh = np.array(data_frame_Behavioural_i.where(data_frame_Behavioural_i.Groups == "HC").dropna()['Behavioural Composite Scores'])
groupi_PD_MCI_beh = np.array(data_frame_Behavioural_i.where(data_frame_Behavioural_i.Groups == "PD_MCI").dropna()['Behavioural Composite Scores'])
groupi_PD_NC_beh = np.array(data_frame_Behavioural_i.where(data_frame_Behavioural_i.Groups == "PD_NC").dropna()['Behavioural Composite Scores'])
pingouin.ttest(groupi_HC_beh, groupi_PD_MCI_beh)
pingouin.ttest(groupi_HC_beh, groupi_PD_NC_beh)
pingouin.ttest(groupi_PD_NC_beh, groupi_PD_MCI_beh)
#Then, select p-values from the above pingouin output
p_values_rest_i_behav = np.array([p_val_test_beh_1, p_val_test_beh_2, p_val_test_beh_3])
fdrcorrection(p_values_rest_i_behav, alpha=0.05, method='indep', is_sorted=False)
#####R Code for Transforming X Matrix Data -------------------------------------------------------------------
#Part 1: PLS for Main Dataset
```{r PLS}
#Template
#read_csv("/Users/alexander_bailey/Sharp_Lab/Data/Temp/Cleaned_Df_Data_Wrangling_August_2022/my_data_August_10_2022.csv")
#1) First, let's load our new and improved Lx
PLS_matrix_loadings<- read_csv("/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_PLS_loadings.csv")
PLS_matrix_loadings
#L_x_composite_full_initial<- read_csv("/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_LV_x_df.csv")
L_x_composite_full_initial<- read_csv('/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_LV_x_df_Main_Dec_7_2022_To_USE.csv')
L_x_composite_full_initial #This is what we require; EDITED AND CORRECT!
#Need to verify that L_x is calculated correctly - INDEED IT IS! So don't need this
L_x_composite_edited<- read_csv('/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_LV_x_df_edited.csv')
L_x_composite_edited
#2) Then let's load X matrix
X_matrix_Complete<- read_csv('/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Main_DF_Proper_Labels.csv')
X_matrix<- read_csv('/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_X_Matrix_df_Main_Dec_7_2022_To_USE.csv') #Add original X Matrix
dim(X_matrix)
X_matrix_Bootstrapped_Std_Error<- read_csv("/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Bootstrapped_X_Std_Err.csv")
#This is useful but thankfully workable given that we have the standard errors from the edited weights!
X_matrix_Bootstrapped_Std_Error #R can handle big data! Just needs to be in the proper save format! Thank you R!!
#X_matrix_good<- X_matrix %>% select(2:length(X_matrix))
#dim(X_matrix_good)
```
#Setting up Correlation and Bootstrapped SDs
```{r PLS}
X_matrix_good <- X_matrix
Latent_Variables_DF<- L_x_composite_full_initial %>% select(1,2,3,4, 5) %>% rename(LxC1 = `0`, LxC2 = `1`, LxC3 = `2`, LxC4 = `3`, LxC5 = `4`)
Latent_Variables_DF
First_latent_variable<- L_x_composite_full_initial$`0`
Second_latent_variable<-L_x_composite_full_initial$`1`
Third_latent_variable<-L_x_composite_full_initial$`2`
Forth_latent_variable<-L_x_composite_full_initial$`3`
length(First_latent_variable)
X_matrix_good<- X_matrix_good %>% na_if(0)
X_matrix_good
#X_matrix_good_Prepare_for_Corr <-X_matrix_good[ , colSums(is.na(X_matrix_good))==0] #No longer need to use this code as I made the switch in Python (faster, less worrisome)
X_matrix_good_Prepare_for_Corr <- X_matrix_good
dim(X_matrix_good_Prepare_for_Corr)
X_matrix_good_Prepare_for_Corr_Stnd<- read_csv("/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Main_DF_Proper_Labels_Standardized_Nov_21_2022.csv")
X_matrix_good_Prepare_for_Corr_Stnd
```
#PLS Correlation between X and LX
```{r PLS Script}
#3) Now, let's make a correlation (this will be used for thresholded and unthresholded info)
X_matrix_PLS_Corr<- X_matrix_good_Prepare_for_Corr_Stnd %>% summarize(across(.cols = everything(), ~cor(.x, First_latent_variable, method = 'pearson'))) #This is to actually do the correlation - I didn't see it, but I do now!
#X_matrix_PLS_Corr_Unstandardized_1 <-X_matrix_good_Prepare_for_Corr %>% summarize(across(.cols = everything(), ~cor(.x, Latent_Variables_DF$LxC1, method = 'pearson')))
X_matrix_PLS_Corr_Unstandardized_1 <-X_matrix_good %>% summarize(across(.cols = everything(), ~cor(.x, Latent_Variables_DF$LxC1, method = 'pearson'))) #TO USE
X_matrix_PLS_Corr_Unstandardized_1 #This is the corrected dataframe after doing the correlation
X_matrix_PLS_Corr_Unstandardized_1
write_csv(X_matrix_PLS_Corr_Unstandardized_1, "/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Main_DF_Proper_Labels_Dec_7_2022_Correlations_Original_DF_Unstandardized_LxC1_TO_USE.csv")
#write_csv(X_matrix_PLS_Corr_Unstandardized_1, "/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Main_DF_Proper_Labels_Nov_24_2022_Correlations_Original_DF_Unstandardized_LxC1.csv")
X_matrix_PLS_Corr_Unstandardized_2 <-X_matrix_good_Prepare_for_Corr %>% summarize(across(.cols = everything(), ~cor(.x, Latent_Variables_DF$LxC2, method = 'pearson')))
X_matrix_PLS_Corr_Unstandardized_2
write_csv(X_matrix_PLS_Corr_Unstandardized_2, "/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Main_DF_Proper_Labels_Dec_7_2022_Correlations_Original_DF_Unstandardized_LxC2_To_USE.csv")
#write_csv(X_matrix_PLS_Corr_Unstandardized_2, "/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Main_DF_Proper_Labels_Nov_24_2022_Correlations_Original_DF_Unstandardized_LxC2.csv")
X_matrix_PLS_Corr_Unstandardized_3 <-X_matrix_good_Prepare_for_Corr %>% summarize(across(.cols = everything(), ~cor(.x, Latent_Variables_DF$LxC3, method = 'pearson')))
X_matrix_PLS_Corr_Unstandardized_3
write_csv(X_matrix_PLS_Corr_Unstandardized_3, "/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Main_DF_Proper_Labels_Dec_7_2022_Correlations_Original_DF_Unstandardized_LxC3_To_Use.csv")
#write_csv(X_matrix_PLS_Corr_Unstandardized_3, "/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Main_DF_Proper_Labels_Nov_24_2022_Correlations_Original_DF_Unstandardized_LxC3.csv")
X_matrix_PLS_Corr_Unstandardized_4 <-X_matrix_good_Prepare_for_Corr %>% summarize(across(.cols = everything(), ~cor(.x, Latent_Variables_DF$LxC4, method = 'pearson')))
X_matrix_PLS_Corr_Unstandardized_4
write_csv(X_matrix_PLS_Corr_Unstandardized_4, "/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Main_DF_Proper_Labels_Dec_7_2022_Correlations_Original_DF_Unstandardized_LxC4_To_USE.csv")
#write_csv(X_matrix_PLS_Corr_Unstandardized_4, "/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Main_DF_Proper_Labels_Nov_24_2022_Correlations_Original_DF_Unstandardized_LxC4.csv")
X_matrix_PLS_Corr_Unstandardized_5 <-X_matrix_good_Prepare_for_Corr %>% summarize(across(.cols = everything(), ~cor(.x, Latent_Variables_DF$LxC5, method = 'pearson')))
X_matrix_PLS_Corr_Unstandardized_5
write_csv(X_matrix_PLS_Corr_Unstandardized_5, "/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Main_DF_Proper_Labels_Dec_7_2022_Correlations_Original_DF_Unstandardized_LxC5_To_USE.csv")
#This will then save our files
#And this will work!!!
#write_csv(X_matrix_PLS_Corr, "/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Main_DF_Proper_Labels_Standardized_Nov_21_2022_Correlations_Original.csv")
X_matrix_PLS_Corr<- read_csv("/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Main_DF_Proper_Labels_Standardized_Nov_21_2022_Correlations_Original.csv") #This is the standardized version. As we'll see not too too useful except for one thing that helps make the data wrangling a bit easier
```
#Let's Now Get Boostrapping!
```{r}
#make this example reproducible; set a seed!
#load boot library
library(boot)
#define dataset
X_matrix_good_Prepare_for_Corr_Stnd_df <- as.data.frame(X_matrix_good_Prepare_for_Corr_Stnd) #Here, I don't think that we need standardized data.
typeof(X_matrix_good_Prepare_for_Corr_Stnd_df)
test<- X_matrix_good_Prepare_for_Corr_Stnd_df$`LH_VisCent_ExStr_1 by LH_VisCent_ExStr_2`
mean(replicate(500, sd(sample(test_value, replace=T))))
#Make a bootstap function
main_bootstrapped_standard_dev <- function(test_value) {
temp_C <- mean(replicate(1000, sd(sample(test_value, replace=T))))
return(temp_C)
}
set.seed(12345)
#apply(X_matrix_good_Prepare_for_Corr_Stnd, 2, main_bootstrapped_standard_dev) #THIS WORKS!
set.seed(12345) #But this helps to put everything in a slightly more interpretable way
X_matrix_good_Prepare_for_Corr_Stnd_Boot_SD <- X_matrix_good_Prepare_for_Corr_Stnd %>% summarise(across(.cols = everything(), ~main_bootstrapped_standard_dev(.x))) #How to get bootstrapping correctly - not actually
X_matrix_good_Prepare_for_Corr_Stnd_Boot_SD
#Test if X is un-standardized
set.seed(12345) #But this helps to put everything in a slightly more interpretable way
X_matrix_good_Prepare_for_Corr_Stnd_Boot_SD_Unstandardized <- X_matrix_good_Prepare_for_Corr %>% summarise(across(.cols = everything(), ~main_bootstrapped_standard_dev(.x))) #How to get bootstrapping correctly - USE THIS
X_matrix_good_Prepare_for_Corr_Stnd_Boot_SD_Unstandardized
write_csv(X_matrix_good_Prepare_for_Corr_Stnd_Boot_SD_Unstandardized, '/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_X_matrix_good_Prepare_for_Corr_Stnd_Boot_SD_Dec_7_2022_Unstandardized_To_Use_Boot_1000.csv')
write_csv(X_matrix_good_Prepare_for_Corr_Stnd_Boot_SD_Unstandardized, '/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_X_matrix_good_Prepare_for_Corr_Stnd_Boot_SD_Dec_7_2022_Unstandardized_To_Use.csv')
#write_csv(X_matrix_good_Prepare_for_Corr_Stnd_Boot_SD_Unstandardized, '/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_X_matrix_good_Prepare_for_Corr_Stnd_Boot_SD_Nov_22_2022_Unstandardized.csv')
#write_csv(X_matrix_good_Prepare_for_Corr_Stnd_Boot_SD, '/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_X_matrix_good_Prepare_for_Corr_Stnd_Boot_SD_Nov_22_2022.csv')
```
#Code to Transform Vectors into Proper Format for Transformation Back to Matrix - WE NEED TO LOAD THIS BEFORE WE GET TO THE NEXT SECTION!!! Why? Because of the Comparison variable - helps to make things WAY easier!
```{r PLS Script}
X_matrix_PLS_Corr #This provides the data, but now, we need our zeroes again!
Comparison<- X_matrix_Complete[1, ]
Comparison
Full_Correlation_Original<- bind_rows(Comparison, X_matrix_PLS_Corr)[2,]
#write_csv(Full_Correlation_Original, "/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Full_Correlation_Original_Nov_21_2022.csv")
Main_df_to_adjust<- read_csv("/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Full_Correlation_Original_Nov_21_2022.csv") #This provides us with the proper file format that can be changed in Python
```
Check out Boostrap Differences
```{r}
#SD_unstandardized<- read_csv('/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_X_matrix_good_Prepare_for_Corr_Stnd_Boot_SD_Dec_7_2022_Unstandardized_To_Use.csv') Boot 500
SD_unstandardized<- read_csv('/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_X_matrix_good_Prepare_for_Corr_Stnd_Boot_SD_Dec_7_2022_Unstandardized_To_Use_Boot_1000.csv')
#read_csv('/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_X_matrix_good_Prepare_for_Corr_Stnd_Boot_SD_Nov_22_2022_Unstandardized.csv')
#SD_standardized<- read_csv('/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_X_matrix_good_Prepare_for_Corr_Stnd_Boot_SD_Nov_22_2022.csv')
SD_unstandardized
SD_standardized #This is a bit too much variance. Ok! So, going with what I've been doing the whole of today that's providing results that make sense!
#Let's now get our Z-scores
sd_bootstrapped_original_data<- as.numeric(as.vector(SD_unstandardized))
sd_bootstrapped_original_data
Name_to_Use<- c(names(X_matrix_PLS_Corr_Unstandardized_4))
Name_to_Use
X_matrix_Lx1<- as.numeric(as.vector(X_matrix_PLS_Corr_Unstandardized_1))
X_matrix_Lx2<- as.numeric(as.vector(X_matrix_PLS_Corr_Unstandardized_2))
X_matrix_Lx3<- as.numeric(as.vector(X_matrix_PLS_Corr_Unstandardized_3))
X_matrix_Lx4<- as.numeric(as.vector(X_matrix_PLS_Corr_Unstandardized_4))
X_matrix_Lx5<- as.numeric(as.vector(X_matrix_PLS_Corr_Unstandardized_5))
length(X_matrix_Lx1)
length(sd_bootstrapped_original_data)
#Step 5: Make Z-scores
adjusted_Z_score_original_data_Px1<- c(X_matrix_Lx1/sd_bootstrapped_original_data)
adjusted_Z_score_original_data_Px2<- c(X_matrix_Lx2/sd_bootstrapped_original_data)
adjusted_Z_score_original_data_Px3<- c(X_matrix_Lx3/sd_bootstrapped_original_data)
adjusted_Z_score_original_data_Px4<- c(X_matrix_Lx4/sd_bootstrapped_original_data)
adjusted_Z_score_original_data_Px5<- c(X_matrix_Lx5/sd_bootstrapped_original_data)
Px1_matrix<-tibble(Name_to_Use, adjusted_Z_score_original_data_Px1)
Px2_matrix<-tibble(Name_to_Use, adjusted_Z_score_original_data_Px2)
Px3_matrix<-tibble(Name_to_Use, adjusted_Z_score_original_data_Px3)
Px4_matrix<-tibble(Name_to_Use, adjusted_Z_score_original_data_Px4)
Px5_matrix<-tibble(Name_to_Use, adjusted_Z_score_original_data_Px5)
#Now let's get our significance (p) values!
Px1_matrix_corrected<- Px1_matrix %>% mutate(p_values = (2*pnorm(Px1_matrix$adjusted_Z_score_original_data_Px1, lower.tail=FALSE)))
p_val_Px1<- c(Px1_matrix_corrected$p_values)
FDR_corr_p_val_Px1 <- p.adjust(p_val_Px1, method = "BH")
FDR_corr_p_val_Px1
Corr_1<- X_matrix_Lx1
Corr_1
#X_matrix_Lx1[1]
Px1_matrix_corrected_to_go<- Px1_matrix_corrected %>% mutate(FDR_p = FDR_corr_p_val_Px1, Corr_1 = X_matrix_Lx1)
Px1_matrix_corrected_to_go
Lx1_X_DF_Original_Data<- Px1_matrix_corrected_to_go %>% mutate(Corrected_Pearson_R = ifelse(FDR_p < .05, Corr_1, NA)) %>% mutate(Corrected_p_Values = ifelse(FDR_p < .05, FDR_p, NA))
write_csv(Lx1_X_DF_Original_Data, '/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Lx1_X_DF_Original_Data_Dec_7_2022_To_Use.csv')
#write_csv(Lx1_X_DF_Original_Data, '/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Lx1_X_DF_Original_Data_Nov_22_2022.csv')
#Now, let's edit 2
Px2_matrix_corrected<- Px2_matrix %>% mutate(p_values = (2*pnorm(Px2_matrix$adjusted_Z_score_original_data_Px2, lower.tail=FALSE)))
p_val_Px2<- c(Px2_matrix_corrected$p_values)
FDR_corr_p_val_Px2 <- p.adjust(p_val_Px2, method = "BH")
Px2_matrix_corrected_to_go<- Px2_matrix_corrected %>% mutate(FDR_p = FDR_corr_p_val_Px2, Corr_2 = X_matrix_Lx2)
Px2_matrix_corrected_to_go
Lx2_X_DF_Original_Data<- Px2_matrix_corrected_to_go %>% mutate(Corrected_Pearson_R = ifelse(FDR_p < .05, Corr_2, NA)) %>% mutate(Corrected_p_Values = ifelse(FDR_p < .05, FDR_p, NA))
write_csv(Lx2_X_DF_Original_Data, '/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Lx2_X_DF_Original_Data_Dec_7_2022_To_Use.csv')
#write_csv(Lx2_X_DF_Original_Data, '/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Lx2_X_DF_Original_Data_Nov_22_2022.csv')
#Now we do the same for 3
Px3_matrix_corrected<- Px3_matrix %>% mutate(p_values = (2*pnorm(Px3_matrix$adjusted_Z_score_original_data_Px3, lower.tail=FALSE)))
p_val_Px3<- c(Px3_matrix_corrected$p_values)
FDR_corr_p_val_Px3 <- p.adjust(p_val_Px3, method = "BH")
FDR_corr_p_val_Px3
Px3_matrix_corrected_to_go<- Px3_matrix_corrected %>% mutate(FDR_p = FDR_corr_p_val_Px3, Corr_3 = X_matrix_Lx3)
Px3_matrix_corrected_to_go
Lx3_X_DF_Original_Data<-Px3_matrix_corrected_to_go %>% mutate(Corrected_Pearson_R = ifelse(FDR_p < .05, Corr_3, NA)) %>% mutate(Corrected_p_Values = ifelse(FDR_p < .05, FDR_p, NA))
Lx3_X_DF_Original_Data
write_csv(Lx3_X_DF_Original_Data, '/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Lx3_X_DF_Original_Data_Dec_7_2022_To_Use.csv')
#write_csv(Lx3_X_DF_Original_Data, '/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Lx3_X_DF_Original_Data_Nov_22_2022.csv')
#And lastly 4
Px4_matrix_corrected<- Px4_matrix %>% mutate(p_values = (2*pnorm(Px4_matrix$adjusted_Z_score_original_data_Px4, lower.tail=FALSE)))
p_val_Px4<- c(Px4_matrix_corrected$p_values)
p_val_Px4
FDR_corr_p_val_Px4 <- p.adjust(p_val_Px4, method = "BH") #Bless you FDR/BH corrections in R!
FDR_corr_p_val_Px4
Px4_matrix_corrected_to_go<- Px4_matrix_corrected %>% mutate(FDR_p = FDR_corr_p_val_Px4, Corr_4 = X_matrix_Lx4)
Px4_matrix_corrected_to_go
#Ok, so this gives us the proper thing
#Now, we want to do a special ifelse (more lenient for this case) for one last column, and then we'll be good to go!
Lx4_X_DF_Original_Data <-Px4_matrix_corrected_to_go %>% mutate(Corrected_Pearson_R = ifelse(FDR_p < .05, Corr_4, NA)) %>% mutate(Corrected_p_Values = ifelse(FDR_p < .05, FDR_p, NA))
Lx4_X_DF_Original_Data
write_csv(Lx4_X_DF_Original_Data, '/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Lx4_X_DF_Original_Data_Dec_7_2022_To_Use.csv')
#write_csv(Lx4_X_DF_Original_Data, '/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Lx4_X_DF_Original_Data_Nov_22_2022.csv')
Px5_matrix_corrected<- Px5_matrix %>% mutate(p_values = (2*pnorm(Px5_matrix$adjusted_Z_score_original_data_Px5, lower.tail=FALSE)))
p_val_Px5<- c(Px5_matrix_corrected$p_values)
p_val_Px5
FDR_corr_p_val_Px5 <- p.adjust(p_val_Px5, method = "BH") #Bless you FDR/BH corrections in R!
FDR_corr_p_val_Px5
Px5_matrix_corrected_to_go<- Px5_matrix_corrected %>% mutate(FDR_p = FDR_corr_p_val_Px5, Corr_5 = X_matrix_Lx5)
Px5_matrix_corrected_to_go
#Ok, so this gives us the proper thing
#Now, we want to do a special ifelse (more lenient for this case) for one last column, and then we'll be good to go!
Lx5_X_DF_Original_Data <-Px5_matrix_corrected_to_go %>% mutate(Corrected_Pearson_R = ifelse(FDR_p < .05, Corr_5, NA)) %>% mutate(Corrected_p_Values = ifelse(FDR_p < .05, FDR_p, NA))
Lx5_X_DF_Original_Data
#Hang on! We JUST need the adjusted p-values to help us to solve this! That is, we make a selection of the values based on the values of this (see above for ifelse statement for this very reason)
#Remember: These are our fundamental values
FDR_corr_p_val_Px1
X_matrix_PLS_Corr_Unstandardized_1
#Now, let's take that value for Correlation out and use that as our mapping, along with the mapping that we have for the unstandardized matrix. We'll use these guys as our friends for the matrices. Then we should be good to go!
X_matrix_corrected_R_Lx1<- c(Lx1_X_DF_Original_Data$Corrected_Pearson_R)
X_matrix_corrected_R_Lx1
X_matrix_corrected_R_Lx2<- c(Lx2_X_DF_Original_Data$Corrected_Pearson_R)
X_matrix_corrected_R_Lx3<- c(Lx3_X_DF_Original_Data$Corrected_Pearson_R)
X_matrix_corrected_R_Lx4<- c(Lx4_X_DF_Original_Data$Corrected_Pearson_R)
X_matrix_corrected_R_Lx5<- c(Lx5_X_DF_Original_Data$Corrected_Pearson_R)
X_matrix_corrected_p_Lx1<- c(Lx1_X_DF_Original_Data$Corrected_p_Values)
X_matrix_corrected_p_Lx1
X_matrix_corrected_p_Lx2<- c(Lx2_X_DF_Original_Data$Corrected_p_Values)
X_matrix_corrected_p_Lx3<- c(Lx3_X_DF_Original_Data$Corrected_p_Values)
X_matrix_corrected_p_Lx4<- c(Lx4_X_DF_Original_Data$Corrected_p_Values)
X_matrix_corrected_p_Lx5<- c(Lx5_X_DF_Original_Data$Corrected_p_Values)
#This is what I've been waiting for!
X_matrix_PLS_Corr_Unstandardized_1_Corrected<- rbind.data.frame(X_matrix_PLS_Corr_Unstandardized_1, X_matrix_corrected_R_Lx1, X_matrix_corrected_p_Lx1)
X_matrix_PLS_Corr_Unstandardized_2_Corrected<- rbind.data.frame(X_matrix_PLS_Corr_Unstandardized_2, X_matrix_corrected_R_Lx2, X_matrix_corrected_p_Lx2)
X_matrix_PLS_Corr_Unstandardized_3_Corrected<- rbind.data.frame(X_matrix_PLS_Corr_Unstandardized_3, X_matrix_corrected_R_Lx3, X_matrix_corrected_p_Lx3)
X_matrix_PLS_Corr_Unstandardized_4_Corrected<- rbind.data.frame(X_matrix_PLS_Corr_Unstandardized_4, X_matrix_corrected_R_Lx4, X_matrix_corrected_p_Lx4)
X_matrix_PLS_Corr_Unstandardized_5_Corrected<- rbind.data.frame(X_matrix_PLS_Corr_Unstandardized_5, X_matrix_corrected_R_Lx5, X_matrix_corrected_p_Lx5)
#Almost! Hang on! We need an easy to use way of knowing which values are correct! The above is useful for potential graphing on a brain, however, there is one more step!
#That step: ADD YOUR p-VALUES AND R values AFTER SUBSETTING!!!
#Now, we can do the thing!!! Namely, get our data into the proper format and ready for production of X Matrix
Full_Correlation_Original_X_Lx1<- bind_rows(Comparison, X_matrix_PLS_Corr_Unstandardized_1_Corrected)
Full_Correlation_Original_X_Lx1
X_matrix_PLS_Corr_Unstandardized_1_Corrected
Full_Corr_matrix_vector_Lx1<- Full_Correlation_Original_X_Lx1[2,]
Full_Corr_matrix_vector_Lx1
Thresholded_matrix_vector_Lx1<- Full_Correlation_Original_X_Lx1[3,]
Thresholded_matrix_vector_Lx1
p_values_thresholded_Lx1<- Full_Correlation_Original_X_Lx1[4,]
Full_Correlation_Original_X_Lx2<- bind_rows(Comparison, X_matrix_PLS_Corr_Unstandardized_2_Corrected)
Full_Corr_matrix_vector_Lx2<- Full_Correlation_Original_X_Lx2[2,]
Thresholded_matrix_vector_Lx2<- Full_Correlation_Original_X_Lx2[3,]
p_values_thresholded_Lx2<- Full_Correlation_Original_X_Lx2[4,]
Full_Correlation_Original_X_Lx3<- bind_rows(Comparison, X_matrix_PLS_Corr_Unstandardized_3_Corrected)
Full_Correlation_Original_X_Lx3
Full_Corr_matrix_vector_Lx3<- Full_Correlation_Original_X_Lx3[2,]
Thresholded_matrix_vector_Lx3<- Full_Correlation_Original_X_Lx3[3,]
p_values_thresholded_Lx3<- Full_Correlation_Original_X_Lx3[4,]
Full_Correlation_Original_X_Lx4<- bind_rows(Comparison, X_matrix_PLS_Corr_Unstandardized_4_Corrected)
Full_Correlation_Original_X_Lx4
Full_Corr_matrix_vector_Lx4<- Full_Correlation_Original_X_Lx4[2,]
Thresholded_matrix_vector_Lx4<- Full_Correlation_Original_X_Lx4[3,]
p_values_thresholded_Lx4<- Full_Correlation_Original_X_Lx4[4,]
Full_Correlation_Original_X_Lx5<- bind_rows(Comparison, X_matrix_PLS_Corr_Unstandardized_5_Corrected)
Full_Correlation_Original_X_Lx5
Full_Corr_matrix_vector_Lx5<- Full_Correlation_Original_X_Lx5[2,]
Thresholded_matrix_vector_Lx5<- Full_Correlation_Original_X_Lx5[3,]
p_values_thresholded_Lx5<- Full_Correlation_Original_X_Lx5[4,]
#Save values for Lx1
write_csv(Full_Corr_matrix_vector_Lx1, "/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Full_Corr_matrix_vector_Lx1_Original_DF_Dec_7_2022.csv")
write_csv(Thresholded_matrix_vector_Lx1, "/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Thresholded_matrix_vector_Lx1_Original_DF_Dec_7_2022.csv")
write_csv(p_values_thresholded_Lx1, "/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_p_values_thresholded_Lx1_Original_DF_Nov_Dec_7_2022.csv")
#Save values for Lx2
write_csv(Full_Corr_matrix_vector_Lx2, "/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Full_Corr_matrix_vector_Lx2_Original_DF_Dec_7_2022.csv")
write_csv(Thresholded_matrix_vector_Lx2, "/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Thresholded_matrix_vector_Lx2_Original_DF_Dec_7_2022.csv")
write_csv(p_values_thresholded_Lx2, "/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_p_values_thresholded_Lx2_Original_DF_Dec_7_2022.csv")
#Save values for Lx3
write_csv(Full_Corr_matrix_vector_Lx3, "/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Full_Corr_matrix_vector_Lx3_Original_DF_Dec_7_2022.csv")
write_csv(Thresholded_matrix_vector_Lx3, "/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Thresholded_matrix_vector_Lx3_Original_DF_Dec_7_2022.csv")
write_csv(p_values_thresholded_Lx3, "/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_p_values_thresholded_Lx3_Original_DF_Dec_7_2022.csv")
#Save values for Lx4
write_csv(Full_Corr_matrix_vector_Lx4, "/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Full_Corr_matrix_vector_Lx4_Original_DF_Dec_7_2022.csv")
write_csv(Thresholded_matrix_vector_Lx4, "/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Thresholded_matrix_vector_Lx4_Original_DF_Dec_7_2022.csv")
write_csv(p_values_thresholded_Lx4, "/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_p_values_thresholded_Lx4_Original_DF_Dec_7_2022.csv")
#Save values for Lx5
write_csv(Full_Corr_matrix_vector_Lx5, "/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Full_Corr_matrix_vector_Lx5_Original_DF_Dec_7_2022.csv")
write_csv(Thresholded_matrix_vector_Lx5, "/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Thresholded_matrix_vector_Lx5_Original_DF_Dec_7_2022.csv")
write_csv(p_values_thresholded_Lx5, "/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_p_values_thresholded_Lx5_Original_DF_Dec_7_2022.csv")
```
Now, let's load our correlation maps/heatmaps for our fMRI data - Return to Python
%matplotlib inline
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
import sklearn as scikitlearn
import scipy
import bokeh as bokeh
import enigmatoolbox
import os as os
import nilearn as nl
import nibabel as nibl
from nilearn import plotting
from nilearn import image
import statsmodels
import pingouin
import plotly
from nilearn.connectome import ConnectivityMeasure
correlation_measure = ConnectivityMeasure(kind='correlation')
from nilearn.connectome import vec_to_sym_matrix
#As an example, let's select the first LC
Full_Corr_matrix_vector_Lx1 = pd.read_csv("/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Full_Corr_matrix_vector_Lx1_Original_DF_Dec_7_2022.csv")
Thresholded_matrix_vector_Lx1 = pd.read_csv("/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Thresholded_matrix_vector_Lx1_Original_DF_Dec_7_2022.csv")
p_values_thresholded_Lx1 = pd.read_csv("/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_p_values_thresholded_Lx1_Original_DF_Nov_Dec_7_2022.csv")
Full_Corr_matrix_vector_Lx1_array = np.array(Full_Corr_matrix_vector_Lx1)
Thresholded_matrix_vector_Lx1_array = np.array(Thresholded_matrix_vector_Lx1)
p_values_thresholded_Lx1_array = np.array(p_values_thresholded_Lx1)
new_corrected_labels = pd.read_csv('/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Correct_Label_Names_Nov_24_2022.csv')
#Let's now add the labels that we have for the Schaefer-17 400 atlas
#LX1 Unthresholded (TOTAL):
new_corrected_labels = pd.read_csv('/Users/alexander_bailey/NEUR608/Data/Temp/NEUR608_Correct_Label_Names_Nov_24_2022.csv')
Main_Original_PLS_LxC1_Matrix_TOTAL_Nov_25_2022 = pd.DataFrame(vec_to_sym_matrix(Full_Corr_matrix_vector_Lx1_array)[0]) #OVERALL CODE TO DO THE WHOLE TRANSITION
Main_Original_PLS_LxC1_Matrix_TOTAL_Nov_25_2022.columns = new_corrected_labels
Main_Original_PLS_LxC1_Matrix_TOTAL_Nov_25_2022.index = new_corrected_labels
Main_Original_PLS_LxC1_Matrix_TOTAL_Nov_25_2022 = Main_Original_PLS_LxC1_Matrix_TOTAL_Nov_25_2022.fillna(0)
plotting.plot_matrix(Main_Original_PLS_LxC1_Matrix_TOTAL_Nov_25_2022, cmap = 'RdBu')
plt.axhline(y = 24, color = 'orange', linestyle = '-')
plt.axhline(y = 59, color = 'orange', linestyle = '-')
plt.axhline(y = 85, color = 'orange', linestyle = '-')
plt.axhline(y = 108, color = 'orange', linestyle = '-')
plt.axhline(y = 120, color = 'orange', linestyle = '-')
plt.axhline(y = 148, color = 'orange', linestyle = '-')
plt.axhline(y = 194, color = 'orange', linestyle = '-')
plt.axhline(y = 200, color = 'orange', linestyle = '-')
plt.axhline(y = 224, color = 'orange', linestyle = '-')
plt.axhline(y = 259, color = 'orange', linestyle = '-')
plt.axhline(y = 285, color = 'orange', linestyle = '-')
plt.axhline(y = 308, color = 'orange', linestyle = '-')
plt.axhline(y = 320, color = 'orange', linestyle = '-')
plt.axhline(y = 348, color = 'orange', linestyle = '-')
plt.axhline(y = 394, color = 'orange', linestyle = '-')
plt.axvline(x = 24, color = 'orange', label = 'axvline - full height')
plt.axvline(x = 59, color = 'orange', label = 'axvline - full height')
plt.axvline(x = 85, color = 'orange', label = 'axvline - full height')
plt.axvline(x = 108, color = 'orange', label = 'axvline - full height')
plt.axvline(x = 120, color = 'orange', label = 'axvline - full height')
plt.axvline(x = 148, color = 'orange', label = 'axvline - full height')
plt.axvline(x = 194, color = 'orange', label = 'axvline - full height')
plt.axvline(x = 200, color = 'orange', label = 'axvline - full height')
plt.axvline(x = 224, color = 'orange', label = 'axvline - full height')
plt.axvline(x = 259, color = 'orange', label = 'axvline - full height')
plt.axvline(x = 285, color = 'orange', label = 'axvline - full height')
plt.axvline(x = 308, color = 'orange', label = 'axvline - full height')
plt.axvline(x = 320, color = 'orange', label = 'axvline - full height')
plt.axvline(x = 348, color = 'orange', label = 'axvline - full height')
plt.axvline(x = 394, color = 'orange', label = 'axvline - full height')
tickloc = [12.5, 42, 72.5, 97, 114.5, 134.5, 171.5, 197.5, 212.5, 242, 272.5, 297, 314.5, 334.5, 371.5, 397.5]
labels = ["Visual_L", "SM_L", "DAtt_L", "VAtt_L", "Limbic_L", "Control_L", "DMN_L", "Temp_Par_L", "Visual_R", "SM_R", "DAtt_R", "VAtt_R", "Limbic_R", "Control_R", "DMN_R", "Temp_Par_R"]
plt.title('Unthresholded RSFC Correlations')
plt.xticks(tickloc, labels, rotation='vertical')
plt.yticks(tickloc, labels)
plt.show()
#Main_Original_PLS_LxC1_Matrix_TOTAL_Nov_25_2022.to_csv('/Users/alexander_bailey/NEUR608/Data/Temp/Original_DF_PLS_LxC1_Matrix_TOTAL_Dec_9_2022.csv')
#LX1 Thresholded:
Main_Original_PLS_LxC1_Matrix_THRESHOLDED_Nov_25_2022 = pd.DataFrame(vec_to_sym_matrix(Thresholded_matrix_vector_Lx1_array)[0]) #OVERALL CODE TO DO THE WHOLE TRANSITION
Main_Original_PLS_LxC1_Matrix_THRESHOLDED_Nov_25_2022.columns = new_corrected_labels
Main_Original_PLS_LxC1_Matrix_THRESHOLDED_Nov_25_2022.index = new_corrected_labels
Main_Original_PLS_LxC1_Matrix_THRESHOLDED_Nov_25_2022 = Main_Original_PLS_LxC1_Matrix_THRESHOLDED_Nov_25_2022.fillna(0)
plotting.plot_matrix(Main_Original_PLS_LxC1_Matrix_THRESHOLDED_Nov_25_2022, cmap = 'viridis')
plt.axhline(y = 24, color = 'orange', linestyle = '-')
plt.axhline(y = 59, color = 'orange', linestyle = '-')
plt.axhline(y = 85, color = 'orange', linestyle = '-')
plt.axhline(y = 108, color = 'orange', linestyle = '-')
plt.axhline(y = 120, color = 'orange', linestyle = '-')
plt.axhline(y = 148, color = 'orange', linestyle = '-')
plt.axhline(y = 194, color = 'orange', linestyle = '-')
plt.axhline(y = 200, color = 'orange', linestyle = '-')
plt.axhline(y = 224, color = 'orange', linestyle = '-')
plt.axhline(y = 259, color = 'orange', linestyle = '-')
plt.axhline(y = 285, color = 'orange', linestyle = '-')
plt.axhline(y = 308, color = 'orange', linestyle = '-')
plt.axhline(y = 320, color = 'orange', linestyle = '-')
plt.axhline(y = 348, color = 'orange', linestyle = '-')
plt.axhline(y = 394, color = 'orange', linestyle = '-')
plt.axvline(x = 24, color = 'orange', label = 'axvline - full height')
plt.axvline(x = 59, color = 'orange', label = 'axvline - full height')
plt.axvline(x = 85, color = 'orange', label = 'axvline - full height')
plt.axvline(x = 108, color = 'orange', label = 'axvline - full height')
plt.axvline(x = 120, color = 'orange', label = 'axvline - full height')
plt.axvline(x = 148, color = 'orange', label = 'axvline - full height')
plt.axvline(x = 194, color = 'orange', label = 'axvline - full height')
plt.axvline(x = 200, color = 'orange', label = 'axvline - full height')