-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathSRT_nEphys Network Topological Metrics.py
2139 lines (1938 loc) · 123 KB
/
SRT_nEphys Network Topological Metrics.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
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
# -*- coding: utf-8 -*-
"""
Created on Dec 12 2021
@author: BIONICS_LAB
@company: DZNE
"""
import matplotlib.pyplot as plt
from scipy.signal import butter, lfilter, hilbert
from scipy import signal,stats
import networkx as nx
import h5py
import numpy as np
import pandas as pd
import threading
import json
from ast import literal_eval
import matplotlib.markers as markers
import os
import seaborn as sns
import scipy.sparse as sp_sparse
import matplotlib.image as mpimg
import help_functions.LFP_denoising as LFP_denosing
import help_functions.LFPAnalysis_Parameters as LFPp
from matplotlib.axes._axes import _log as matplotlib_axes_logger
import connectivipy
matplotlib_axes_logger.setLevel('ERROR')
"""
The following input parameters are used for calculating network topology metrics from SRT and nEphys datasets.
To compare conditions put the path for datasets in the input parameters and label condition name i.e. SD and ENR and assign desired color
"""
rows = 64
cols = 64
Start_time = 0
Stop_time = 30
column_list = ["IEGs"] ### "Hipoo Signaling Pathway","Synaptic Vescicles_Adhesion","Receptors and channels","Synaptic plasticity","Hippoocampal Neurogenesis","IEGs"
conditions = ['SD', 'ENR']
condition1_path = r'Z:/ANALYSES/SPATIOSCALES- 10X genomics/Data/SD/'
condition2_path = r'Z:/ANALYSES/SPATIOSCALES- 10X genomics/Data/ENR/'
color = ['silver', 'dodgerblue'] # color for pooled plotting of conditions
color_choose = ['silver', 'dodgerblue', 'green', 'orange', 'purple', 'black'] # color for multiple gene plots
network_topology_metric = ['Clustering Coefficient',"Centrality","Degree",'Betweenness']
Region = ['Cortex', 'Hippo']
Cortex = ['EC', 'PC']
Hippo = ['DG','Hilus','CA3','CA1','EC','PC']
class MEASeqX_Project:
def __init__(self, srcfilepath):
self.srcfilepath = srcfilepath # main path
self.clusters = ['DG', 'Hilus', 'CA3', 'CA1', 'EC', 'PC']
def get_filename_path(self, filepath, filetype):
"""
Search the provided path for all files that match the filetype specified.
Parameters
----------
filepath : string
The folder path.
filetype: string
The file type(e.g. .bxr, .xlsx).
Returns
-------
Returns the paths for all files math the filetype.
"""
filename = []
Root = []
for root, dirs, files in os.walk(filepath):
for i in files:
if filetype in i:
filename.append(i)
Root.append(root)
return filename, Root
def getRawdata(self, start, stop, expFile, channel, thr=2000):
'''
Get network topology metric raw data
'''
filehdf5 = h5py.File(expFile, 'r')
# CONSTANT
MaxValue = 4096.
MaxVolt = np.asarray(filehdf5["3BRecInfo"]["3BRecVars"]["MaxVolt"])[0]
MinVolt = np.asarray(filehdf5["3BRecInfo"]["3BRecVars"]["MinVolt"])[0]
NRecFrames = np.asarray(filehdf5["3BRecInfo"]["3BRecVars"]["NRecFrames"])[0]
SignInversion = np.asarray(filehdf5["3BRecInfo"]["3BRecVars"]["SignalInversion"])[0]
stepVolt = (MaxVolt - MinVolt) / MaxValue
version = int(filehdf5["3BData"].attrs['Version'])
rawData = filehdf5["3BData"]["Raw"]
if start < 0:
start = 0
if stop >= NRecFrames:
stop = NRecFrames - 1
if isinstance(channel, int) or isinstance(channel, float):
# get one Single channel
if version == 100:
raw = ((rawData[int(start):int(stop), channel] - (
4096.0 / 2)) * stepVolt * SignInversion)
else:
raw = rawData[int(start) * 4096:int(stop) * 4096]
raw = raw.reshape((len(raw) // 4096.0, 4096.0))
raw = (raw[:, channel] - (4096.0 / 2)) * stepVolt * SignInversion
elif isinstance(channel, str):
# Get all channels
if version == 100:
raw = ((rawData[int(start):int(stop), :] - (4096.0 / 2))) * SignInversion
else:
raw = rawData[int(start) * 4096:int(stop) * 4096]
raw = raw.reshape((len(raw) // 4096, 4096))
raw = (raw - (4096.0 / 2)) * SignInversion
# Put to 0 saturation sample
index = np.where(raw > thr)
raw[index[0], index[1]] = 0
raw = raw * float(stepVolt)
elif isinstance(channel, np.ndarray):
# Get an array of channels
if version == 100:
raw = ((rawData[int(start):int(stop), channel] - (
4096.0 / 2))) * stepVolt * SignInversion
else:
raw = rawData[int(start) * 4096:int(stop) * 4096]
raw = raw.reshape((len(raw) // 4096, 4096))
raw = (raw[:, channel] - (4096.0 / 2)) * stepVolt * SignInversion
return raw
def filter_data(self, data, SamplingRate, low, high, order=2):
# Determine Nyquist frequency
nyq = SamplingRate / 2
# Set bands
low = low / nyq
high = high / nyq
# Calculate coefficients
b, a = butter(order, [low, high], btype='band')
# Filter signal
filtered_data = lfilter(b, a, data)
return filtered_data
def downsample_data(self,data, sf, target_sf):
"""Because the LFP signal does not contain high frequency components anymore the original sampling rate can be reduced.
This will lower the size of the data and speed up calculations. Therefore we define a short down-sampling function."""
factor = sf / target_sf
if factor <= 10:
data_down = signal.decimate(data, factor)
else:
factor = 10
data_down = data
while factor > 1:
data_down = signal.decimate(data_down, factor)
sf = sf / factor
factor = int(min([10, sf / target_sf]))
return data_down, sf
def threshold_cluster(self,Data_set, threshold):
# change all to one list
stand_array = np.asarray(Data_set).ravel('C')
stand_Data = pd.Series(stand_array)
index_list, class_k = [], []
while stand_Data.any():
if len(stand_Data) == 1:
index_list.append(list(stand_Data.index))
class_k.append(list(stand_Data))
stand_Data = stand_Data.drop(stand_Data.index)
else:
class_data_index = stand_Data.index[0]
class_data = stand_Data[class_data_index]
stand_Data = stand_Data.drop(class_data_index)
if (abs(stand_Data - class_data) <= threshold).any():
args_data = stand_Data[abs(stand_Data - class_data) <= threshold]
stand_Data = stand_Data.drop(args_data.index)
index_list.append([class_data_index] + list(args_data.index))
class_k.append([class_data] + list(args_data))
else:
index_list.append([class_data_index])
class_k.append([class_data])
return index_list, class_k
def read_related_files(self):
"""
Read the related files.
File input needed:
-------
- 'filtered_feature_bc_matrix.h5' (spaceranger_count pipeline output)
- 'scalefactors_json.json' (spaceranger_count pipeline output)
- 'tissue_positions_list.csv' (spaceranger_count pipeline output)
- 'tissue_lowres_image.png' (spaceranger_count pipeline output)
- 'Loupe Clusters.csv' (independently generated tissue structural clusters using Loupe Browser)
Returns
-------
csv_file: pandas.DataFrame tissue_positions_list.xlsx
'filtered_feature_bc_matrix.h5': parameters as followed
-tissue_lowres_scalef.
-features_name.
-matr_raw
-barcodes
img: png 'tissue_lowres_image.png'
csv_file_cluster:pandas.DataFrame 'Loupe Clusters.csv'
"""
##########################
h5_file_name = 'filtered_feature_bc_matrix.h5'
print(self.srcfilepath)
h5_file, json_Root = self.get_filename_path(self.srcfilepath, h5_file_name)
print(json_Root)
for i in range(len(h5_file)):
if h5_file[i][0] != '.':
h5_root = json_Root[i] + '/' + h5_file[i]
#############################################
filehdf5_10x = h5py.File(h5_root, 'r')
matrix = np.asarray(filehdf5_10x["matrix"])
shape = np.asarray(filehdf5_10x["matrix"]['shape'])
barcodes = np.asarray(filehdf5_10x["matrix"]["barcodes"])
# print(len(barcodes))
indices = np.asarray(filehdf5_10x["matrix"]["indices"])
indptr = np.asarray(filehdf5_10x["matrix"]["indptr"])
data = np.asarray(filehdf5_10x["matrix"]["data"])
features_name = np.asarray(filehdf5_10x["matrix"]["features"]['name'])
matr_raw = sp_sparse.csc_matrix((data, indices, indptr), shape=shape).toarray()
# Read json file to get the tissue_hires_scalef values to transfor the dots in csv to images
json_file_name = 'scalefactors_json.json'
json_file, json_Root = self.get_filename_path(self.srcfilepath, json_file_name)
for i in range(len(json_file)):
if json_file[i][0] != '.':
json_root = json_Root[i] + '/' + json_file[i]
with open(json_root) as json_file:
data = json.load(json_file)
spot_diameter_fullres = data['spot_diameter_fullres']
tissue_hires_scalef = data['tissue_hires_scalef']
fiducial_diameter_fullres = data['fiducial_diameter_fullres']
tissue_lowres_scalef = data['tissue_lowres_scalef']
column_list = ["barcode", "selection", "y", "x", "pixel_y", "pixel_x"]
######################
csv_file_name = 'tissue_positions_list.csv'
csv_file, csv_Root = self.get_filename_path(self.srcfilepath, csv_file_name)
for i in range(len(csv_file)):
if csv_file[i][0] != '.':
csv_root = csv_Root[i] + '/' + csv_file[i]
csv_file = pd.read_csv(csv_root, names=column_list)
csv_file.to_excel(self.srcfilepath + "tissue_positions_list.xlsx", index=False)
##################################
img_file_name = 'tissue_lowres_image.png'
img_file, img_Root = self.get_filename_path(self.srcfilepath, img_file_name)
for i in range(len(img_file)):
if img_file[i][0] != '.':
img_root = img_Root[i] + '/' + img_file[i]
img = mpimg.imread(img_root)
# color_map,Cluster_list = self.get_cluster_for_SRT(self, id = ix_filter, csv_file=csv_file)
csv_file_cluster_name = 'Loupe Clusters.csv'
csv_file_cluster_file, csv_file_cluster_Root = self.get_filename_path(self.srcfilepath, csv_file_cluster_name)
for i in range(len(csv_file_cluster_file)):
if csv_file_cluster_file[i][0] != '.':
csv_file_cluster_root = csv_file_cluster_Root[i] + '/' + csv_file_cluster_file[i]
#############################################
csv_file_cluster = pd.read_csv(csv_file_cluster_root)
return csv_file,tissue_lowres_scalef,features_name,matr_raw,barcodes,img,csv_file_cluster
def get_Groupid_SRT(self,Lfps_ID,barcode_cluster =None,nEphys_cluster =None,data = None):
Channel_ID = [data['Channel ID'][i] for i in range(len(data))]
Channel_Barcodes = [str(data['Barcodes_Channel_ID'][i])[2:-1] for i in range(len(data))]
Corr_id = [data['Corr_id'][i] for i in range(len(data))]
Corr_Barcodes = [str(data['Barcodes_Corr_id'][i])[2:-1] for i in range(len(data))]
id_all,indices = np.unique(Channel_ID+Corr_id,return_index=True)
Barcodes_uni = [(Channel_Barcodes+Corr_Barcodes)[i] for i in indices]
# ########################################################
cluster_ids = []
clusters_ID = [] #group by clusters
for i in range(len(self.clusters)):
cluster_ID = []
for k in range(len(id_all)):
if nEphys_cluster[list(barcode_cluster).index(Barcodes_uni[k])] == self.clusters[i]:
cluster_ids.append(id_all[k])
cluster_ID.append(id_all[k])
clusters_ID.append(cluster_ID)
colorMap = []
for id in Lfps_ID:
for i in range(len(self.clusters)):
if id in clusters_ID[i]:
colorMap.append(i)
return cluster_ids,clusters_ID,colorMap
def get_Groupid_nEphys(self,ChsGroups=None):
# ########################################################
cluster_ids = []
clusters_ID = [] # group by clusters
for i in range(len(self.clusters)):
for j in range(len(ChsGroups['Name'])):
if ChsGroups['Name'][j] == self.clusters[i]:
chsLabel = ChsGroups['Chs'][j]
chsIdx = [(el[0] - 1) * 64 + (el[1] - 1) for el in chsLabel]
cluster_ids.extend(chsIdx)
clusters_ID.append(chsIdx)
return cluster_ids,clusters_ID
def get_Groupid_nEphys_hub(self,Lfps_ID_1,ChsGroups=None,MeaStreams =None):
dictChsId = {}
clustersList = ChsGroups
for clusterToBeAnalyzed in ChsGroups['Name']:
for idx in range(clustersList.shape[0]):
if str(clustersList[idx][0]) == clusterToBeAnalyzed:
chsLabel = clustersList[idx]['Chs']
chsIdx = []
for el in chsLabel:
chsIdx.append((el[0] - 1)* 64 + (el[1] - 1))
dictChsId[clusterToBeAnalyzed] = chsIdx
colorMap = np.array(np.zeros(len(MeaStreams[:]), dtype=int))
for tempKey in dictChsId.keys():
for i in range(len(ChsGroups['Name'])):
if tempKey == ChsGroups['Name'][i]:
colorMap[dictChsId[tempKey]] = i+1
colorMap_Temp = []
Lfps_ID,colormap,Clusters,cluster_name = self.Class_ID_detect(Lfps_ID_1,ChsGroups=ChsGroups)
for i in Lfps_ID:
colorMap_Temp.append(colorMap[i])
return colorMap_Temp
def Class_ID_detect(self, Lfps_ID_1, ChsGroups=None):
Class_LFPs_ID = Lfps_ID_1
colormap = []
Clusters = []
cluster_name = []
clusters_names = np.unique(ChsGroups['Name'])
a = [0] * len(ChsGroups['Chs'])
cluster_ids = []
for i in range(len(ChsGroups['Chs'])):
cluster_id = []
Clusters.append(ChsGroups['Name'][i])
################################################################################sort the cluster_name
for k in range(len(clusters_names)):
if ChsGroups['Name'][i] == clusters_names[k]:
l = k
################################################################################
for j in range(len(ChsGroups['Chs'][i])):
cluster_id.append((ChsGroups['Chs'][i][j][0] - 1) * 64 + (ChsGroups['Chs'][i][j][1] - 1))
cluster_ids.append(cluster_id)
for k in Class_LFPs_ID:
for i in range(len(cluster_ids)):
if k in cluster_ids[i]:
colormap.append(i)
cluster_name.append(ChsGroups['Name'][i])
return Class_LFPs_ID, colormap, Clusters, cluster_name
def DTF(self, A, sigma=None, n_fft=None):
"""Direct Transfer Function (DTF)
Parameters
----------
A : ndarray, shape (p, N, N)
The AR coefficients where N is the number of signals
and p the order of the model.
sigma : array, shape (N, )
The noise for each time series
n_fft : int
The length of the FFT
Returns
-------
D : ndarray, shape (n_fft, N, N)
The estimated DTF
"""
p, N, N = A.shape
import math
if n_fft is None:
n_fft = max(int(2 ** np.math.ceil(np.log2(p))), 512)
H, freqs = self.spectral_density(A, n_fft)
D = np.zeros((n_fft, N, N))
if sigma is None:
sigma = np.ones(N)
for i in range(n_fft):
S = H[i]
V = (S * sigma[None, :]).dot(S.T.conj())
V = np.abs(np.diag(V))
D[i] = np.abs(S * np.sqrt(sigma[None, :])) / np.sqrt(V)[:, None]
return D, freqs
def spectral_density(self, A, n_fft=None):
"""Estimate PSD from AR coefficients
Parameters
----------
A : ndarray, shape (p, N, N)
The AR coefficients where N is the number of signals
and p the order of the model.
n_fft : int
The length of the FFT
Returns
-------
fA : ndarray, shape (n_fft, N, N)
The estimated spectral density.
"""
import scipy
p, N, N = A.shape
if n_fft is None:
n_fft = max(int(2 ** np.math.ceil(np.log2(p))), 512)
A2 = np.zeros((n_fft, N, N))
A2[1:p + 1, :, :] = A # start at 1 !
fA = scipy.fft.fft(A2, axis=0)
freqs = np.fft.fftfreq(n_fft)
I = np.eye(N)
for i in range(n_fft):
fA[i] = scipy.linalg.inv(I - fA[i])
return fA, freqs
def node_strength_detect(self, G, percent=0.05):
'''degree 20% of all the metrics
'''
degree_centrality = G.degree()
#######################
degree_sort = sorted(degree_centrality, key=lambda k: k[1], reverse=True)
n = int(round(len(degree_sort) * percent))
indices = []
for i in degree_sort[:n]:
indices.append(i[0])
#######################
# print('degree_centrality',indices)
return indices
def clustering_coefficient_detect(self, G, percent=0.05):
clustering_coefficient = nx.clustering(G)
degree_centrality_sort = sorted(clustering_coefficient.items(), key=lambda k: k[1], reverse=True)
n = int(round(len(degree_centrality_sort) * percent))
betweenness_centrality_indices = []
for i in degree_centrality_sort[:n]:
betweenness_centrality_indices.append(i[0])
return betweenness_centrality_indices
def efficiency_detect(self, G, Class_LFPs_ID, Corr_ID, percent=0.05):
Class_LFPs_ID = list(Class_LFPs_ID)
Corr_ID = list(Corr_ID)
efficiency_list = [nx.algorithms.efficiency(G, Class_LFPs_ID[i], Corr_ID[i]) for i in range(len(Class_LFPs_ID))]
conbin = []
for i in range(len(Class_LFPs_ID)):
conbin.append((Class_LFPs_ID[i], Corr_ID[i], efficiency_list[i]))
def takeOne(elem):
return elem[2]
conbin.sort(key=takeOne)
Class_LFPs_ID_temp = []
Corr_ID_temp = []
efficiency_list_temp = []
for j in range(len(conbin)):
Class_LFPs_ID_temp.append(conbin[j][0])
Corr_ID_temp.append(conbin[j][1])
efficiency_list_temp.append(conbin[j][2])
value = int(percent * len(Class_LFPs_ID_temp))
return Class_LFPs_ID_temp[0:value]
def degree_detect(self, raw_id, Corr_id, Degree_raw):
'''degree 20% of all the metrics
'''
degree_id = []
corr_id = []
degree_centrality_sort = sorted(Degree_raw, reverse=True)
n = int(round(len(degree_centrality_sort) * 0.05))
for i in range(len(Degree_raw)):
if Degree_raw[i] >= degree_centrality_sort[n]:
degree_id.append(raw_id[i])
corr_id.append(Corr_id[i])
return degree_id, corr_id
def nEphys_functional_connectivity(self, low=5, high=100, denosing=False, Analysis_Item = 'LFPs',Start_Time = 0,Stop_Time = 1000):
"""
Calculate functional connectivity from nEphys data
File input needed:
-------
- '[file].bxr'
- denoising files
Parameters
-------
Returns
-------
File output:
-------
- '[file]_nEphys_functional_connectivity.xlsx'
"""
filetype_bxr = '.bxr'
filename_bxr, Root = self.get_filename_path(self.srcfilepath, filetype_bxr)
def to_excel(file_list, i):
expFile = file_list[i]
if expFile[0] != '.':
print(expFile)
file_brw = self.srcfilepath + expFile[:-4] + '.brw'
filehdf5_bxr = h5py.File(self.srcfilepath + expFile, 'r') # read LFPs bxr files
samplingRate = np.asarray(filehdf5_bxr["3BRecInfo"]["3BRecVars"]["SamplingRate"])[0]
ChsGroups = np.asarray(filehdf5_bxr["3BUserInfo"]["ChsGroups"])
MeaChs2ChIDsVector = np.asarray(filehdf5_bxr["3BResults"]["3BInfo"]["MeaChs2ChIDsVector"])
#######################################################only get the cluster id
if os.path.exists(self.srcfilepath + expFile[:-4] + '_denosed_LfpChIDs' + '.npy') and os.path.exists(
self.srcfilepath + expFile[:-4] + '_denosed_LfpTimes' + '.npy'):
lfpChId_raw = np.load(self.srcfilepath + expFile[:-4] + '_denosed_LfpChIDs' + '.npy')
lfpTimes_raw = np.load(self.srcfilepath + expFile[:-4] + '_denosed_LfpTimes' + '.npy')
else:
Analysis = LFP_denosing.LFPAnalysis_Function(self.srcfilepath, condition_choose='BS') # condition_choose ='OB' or 'BS'
lfpChId_raw, lfpTimes_raw, LfpForms = Analysis.AnalyzeExp(expFile=expFile)
########################
start = (Start_Time / 1000)
stop = (Stop_Time / 1000)
start_time = min(lfpTimes_raw, key=lambda x: abs(x - start))
start_ID = min(i for i, v in enumerate(lfpTimes_raw) if v == start_time)
stop_time = min(lfpTimes_raw, key=lambda x: abs(x - stop))
stop_ID = max(i for i, v in enumerate(lfpTimes_raw) if v == stop_time)
lfpChId_raw = list(lfpChId_raw[int(start_ID):int(stop_ID)])
lfpTimes_raw = list(lfpTimes_raw[int(start_ID):int(stop_ID)]) # change to ms
index_list, Event_group = self.threshold_cluster(np.unique(lfpTimes_raw), 0.3) ###bin size for correlation
lfpTimes_raw = [i * samplingRate for i in lfpTimes_raw]
Lfps_ID_new_all = []
Corr_id_all = []
coor_Value_all = []
start_time_all = []
stop_time_all = []
count = 0
for event in Event_group:
print('Event: ' + str(count))
Start_time = np.min(event)
Stop_time = np.max(event)
begin = int(Start_time * samplingRate)
end = int(Stop_time * samplingRate)
dataChannels = self.getRawdata(begin, end, file_brw, 'all')
################################################
start_time = min(lfpTimes_raw, key=lambda x: abs(x - begin))
start_ID = min(i for i, v in enumerate(lfpTimes_raw) if v == start_time)
stop_time = min(lfpTimes_raw, key=lambda x: abs(x - end))
stop_ID = max(i for i, v in enumerate(lfpTimes_raw) if v == stop_time)
LfpsChIDs = lfpChId_raw[int(start_ID):int(stop_ID)]
LfpsTimes = lfpTimes_raw[int(start_ID):int(stop_ID)]
#################################################
Lfps_ID, indices = np.unique(LfpsChIDs, return_index=True)
cluster_ids = [(ChsGroups['Chs'][i][j][0] - 1) * 64 + (ChsGroups['Chs'][i][j][1] - 1) for i in
range(len(ChsGroups['Chs'])) for j in range(len(ChsGroups['Chs'][i]))]
Lfps_ID = [i for i in Lfps_ID if i in cluster_ids]
###########################################
time_series_raw = [
np.abs(
hilbert(self.filter_data(dataChannels[:, i], samplingRate, low=low, high=high))) - np.mean(
np.abs(hilbert(self.filter_data(dataChannels[:, i], samplingRate, low=low, high=high)))) for
i in Lfps_ID if len(self.filter_data(dataChannels[:, i], samplingRate, low=low, high=high)) > 0]
Lfps_ID = [i for i in Lfps_ID if
len(self.filter_data(dataChannels[:, i], samplingRate, low=low, high=high)) > 0]
if len(Lfps_ID) > 2:
Corr_matrix = np.corrcoef(np.asarray(time_series_raw))
time_series = np.asarray(time_series_raw).T
##################################
MVAR = connectivipy.mvarmodel.Mvar
result = MVAR.fit(time_series.T)[0]
D, freqs = self.DTF(result)
value = np.ndarray.mean(D[freqs > 0, :, :]) + 2 * np.std(D[freqs > 0, :, :])
Lfps_ID_new = [Lfps_ID[i] for i in range(len(Lfps_ID)) for j in range(i + 1, len(Lfps_ID)) if
np.mean(D[freqs > 0, i, j]) >= value]
Corr_id = [Lfps_ID[j] for i in range(len(Lfps_ID)) for j in range(i + 1, len(Lfps_ID)) if
np.mean(D[freqs > 0, i, j]) >= value]
coor_Value = [Corr_matrix[i, j] for i in range(len(Lfps_ID)) for j in range(i + 1, len(Lfps_ID))
if np.mean(D[freqs > 0, i, j]) >= value]
# Lfps_ID_new, Corr_id, coor_Value = self.Spatio_temporal_filter(Lfps_ID_new, Corr_id, LfpsTimes,
# coor_Value, Lfps_ID, indices,
# samplingRate, MeaChs2ChIDsVector)
print('Count of Active_ID after filtering:', len(Lfps_ID_new))
if len(Lfps_ID_new) == len(Corr_id) and len(Lfps_ID_new) == len(coor_Value):
Lfps_ID_new_all.extend(Lfps_ID_new)
Corr_id_all.extend(Corr_id)
coor_Value_all.extend(coor_Value)
start_time_all.extend([Start_time] * len(coor_Value))
stop_time_all.extend([Stop_time] * len(coor_Value))
else:
Lfps_ID_new_all.extend(
[Lfps_ID_new[i] for i in range(min(len(Lfps_ID_new), len(Corr_id), len(coor_Value)))])
Corr_id_all.extend(
[Corr_id[i] for i in range(min(len(Lfps_ID_new), len(Corr_id), len(coor_Value)))])
coor_Value_all.extend(
[coor_Value[i] for i in range(min(len(Lfps_ID_new), len(Corr_id), len(coor_Value)))])
start_time_all.extend([Start_time] * len(
[coor_Value[i] for i in range(min(len(Lfps_ID_new), len(Corr_id), len(coor_Value)))]))
stop_time_all.extend([Stop_time] * len(
[coor_Value[i] for i in range(min(len(Lfps_ID_new), len(Corr_id), len(coor_Value)))]))
count += 1
New_ID = [i for i in range(len(coor_Value_all)) if coor_Value_all[i] > 0]
Lfps_ID_new_all = [Lfps_ID_new_all[i] for i in New_ID]
Corr_id_all = [Corr_id_all[i] for i in New_ID]
coor_Value_all = [coor_Value_all[i] for i in New_ID]
start_time_all = [start_time_all[i] for i in New_ID]
stop_time_all = [stop_time_all[i] for i in New_ID]
max_time_all = [max(stop_time_all) for i in New_ID]
a = {'Class_LFPs_ID_Per': Lfps_ID_new_all, 'Corr_ID_Per': Corr_id_all, 'coor_Per_data': coor_Value_all,
'start_time_all': start_time_all, 'stop_time_all': stop_time_all, 'max_time_all': max_time_all}
dataframe = pd.DataFrame.from_dict(a, orient='index').T
name = file_brw[file_brw.rfind('/') + 1:]
desfilepath = self.srcfilepath
if not os.path.exists(desfilepath):
os.mkdir(desfilepath)
dataframe.to_excel(desfilepath + name[:-4] + "_nEphys_functional_connectivity.xlsx", index=False)
threads = []
x = 0
for t in range(len(filename_bxr)):
t = threading.Thread(target=to_excel, args=(filename_bxr, x))
threads.append(t)
x += 1
for thr in threads:
thr.start()
thr.join()
print("all over")
def nEphys_functional_connectivity_excel_to_gephi(self):
"""
Obtain .gexf file from nEphys functional connectivity
File input needed:
-------
- '[file].bxr'
- '[file]_nEphys_functional_connectivity.xlsx'
Parameters
-------
Returns
-------
File output:
-------
- '[file]_nEphys_functional_connectivity.gexf'
"""
path = self.srcfilepath[:self.srcfilepath.rfind('/')]
desfilepath = path + '/Network_Connectivity/'
if not os.path.exists(desfilepath):
os.mkdir(desfilepath)
filetype_bxr = '.bxr'
filename_bxr, Root = self.get_filename_path(self.srcfilepath, filetype_bxr)
for expFile in filename_bxr:
if expFile[0] != '.':
print(expFile)
if expFile[0] != '.':
filetype_xlsx = expFile[:-4] + '_nEphys_functional_connectivity.xlsx'
filehdf5_bxr = h5py.File(self.srcfilepath + expFile, 'r') # read LFPs bxr files
ChsGroups = np.asarray(filehdf5_bxr["3BUserInfo"]["ChsGroups"])
if type(ChsGroups['Name'][0]) != str:
ChsGroups['Name'] = [i.decode("utf-8") for i in ChsGroups['Name']]
MeaChs2ChIDsVector = np.asarray(filehdf5_bxr["3BResults"]["3BInfo"]["MeaChs2ChIDsVector"])
filename_xlsx, Root = self.get_filename_path(self.srcfilepath, filetype_xlsx)
if len(filename_xlsx) > 0:
data = pd.read_excel(Root[0] + '/' + filename_xlsx[0])
data_new = data.copy()
data_new = data_new[data_new['coor_Per_data'] > 0]
df = nx.from_pandas_edgelist(data_new, source='Class_LFPs_ID_Per', target='Corr_ID_Per',
edge_attr=True)
cluster_ids = []
clusters_ID = []
########################################################
for i in range(len(self.clusters)):
cluster_ID = []
for k in range(len(ChsGroups['Name'])):
print(ChsGroups['Name'][k])
if ChsGroups['Name'][k] == self.clusters[i]:
for j in range(len(ChsGroups['Chs'][k])):
cluster_ids.append(
(ChsGroups['Chs'][k][j][0] - 1) * 64 + (ChsGroups['Chs'][k][j][1] - 1))
cluster_ID.append(
(ChsGroups['Chs'][k][j][0] - 1) * 64 + (ChsGroups['Chs'][k][j][1] - 1))
clusters_ID.append(cluster_ID)
############all links
hub_rich_club_nodes_all = df.nodes()
data_filter = [[data['Class_LFPs_ID_Per'][i], data['Corr_ID_Per'][i]] for i in range(len(data))]
weight_fiter = [data['coor_Per_data'][i] for i in range(len(data))]
start_time = [data['start_time_all'][i] for i in range(len(data_filter)) if
data_filter[i][0] in cluster_ids and data_filter[i][1] in cluster_ids]
print("Start Time:", start_time)
stop_time = [data['stop_time_all'][i] for i in range(len(data_filter)) if
data_filter[i][0] in cluster_ids and data_filter[i][1] in cluster_ids]
max_time = [data['max_time_all'][i] for i in range(len(data_filter)) if
data_filter[i][0] in cluster_ids and data_filter[i][1] in cluster_ids]
data_all_links = [data for data in data_filter if
data[0] in hub_rich_club_nodes_all and data[1] in hub_rich_club_nodes_all]
weight_all_links = [weight_fiter[data] for data in range(len(data_filter)) if
data_filter[data][0] in hub_rich_club_nodes_all and data_filter[data][
1] in hub_rich_club_nodes_all]
########################
All_id = []
Class_LFPs_nodes = [int(i[0]) for i in data_all_links]
Corr_ID_nodes = [int(i[1]) for i in data_all_links]
All_id.extend(Class_LFPs_nodes)
All_id.extend(Corr_ID_nodes)
# All_id = np.unique(All_id)
print("All ID:", All_id)
######################
longitude = [MeaChs2ChIDsVector["Col"][i] - 1 for i in All_id]
latitude = [64 - (MeaChs2ChIDsVector["Row"][i] - 1) for i in All_id]
start_time_all = []
start_time_all.extend(start_time)
start_time_all.extend(start_time)
stop_time_all = []
stop_time_all.extend(stop_time)
stop_time_all.extend(stop_time)
max_time_all = []
max_time_all.extend(max_time)
max_time_all.extend(max_time)
All_nodes_clusters = [self.clusters[j] for i in range(len(All_id)) for j in
range(len(clusters_ID)) if All_id[i] in clusters_ID[j]]
nodes = pd.DataFrame({'id': list(All_id), 'cluster': All_nodes_clusters, 'latitude': latitude,
'longitude': longitude, 'start_time': start_time_all,
'stop_time': stop_time_all, 'max_time': max_time_all})
edges = pd.DataFrame({'source': [int(i[0]) for i in data_all_links],
'target': [int(i[1]) for i in data_all_links],
'weight': weight_all_links})
G = nx.from_pandas_edgelist(edges, 'source', 'target', edge_attr='weight')
nx.set_node_attributes(G, pd.Series(nodes.latitude.values, index=nodes.id).to_dict(),
'latitude')
nx.set_node_attributes(G, pd.Series(nodes.longitude.values, index=nodes.id).to_dict(),
'longitude')
nx.set_node_attributes(G, pd.Series(nodes.cluster.values, index=nodes.id).to_dict(), 'cluster')
nx.set_node_attributes(G, pd.Series(nodes.start_time.values, index=nodes.id).to_dict(),
'start_time')
nx.set_node_attributes(G, pd.Series(nodes.stop_time.values, index=nodes.id).to_dict(),
'stop_time')
nx.set_node_attributes(G, pd.Series(nodes.max_time.values, index=nodes.id).to_dict(),
'max_time')
print("Writing GEXF file to:", desfilepath + filename_xlsx[0][:-5] + '.gexf')
nx.write_gexf(G, desfilepath + filename_xlsx[0][:-5] + '.gexf')
def SRT_mutual_information_connectivity_excel_to_gephi(self, gene_list_name=None, Given_gene_list=False):
"""
Obtain .gexf file from SRT mutual information.
File input needed:
-------
- '[gene_list]_SRT_mutual_information_connectivity.xlsx' (obtained from SRT Gene Expression.py)
- 'SRT_nEphys_Multiscale_Coordinates.xlsx'
Parameters
-------
Returns
-------
File output:
-------
- '[gene_list]_SRT_mutual_information_connectivity.gexf'
"""
if Given_gene_list == True:
gene_list_name = 'Selected_genes'
filetype_xlsx = gene_list_name + '_SRT_mutual_information_connectivity' + ".xlsx"
path = self.srcfilepath[:self.srcfilepath.rfind('/')]
desfilepath = path + '/Network_Connectivity/'
if not os.path.exists(desfilepath):
os.mkdir(desfilepath)
data = pd.read_excel(self.srcfilepath + filetype_xlsx)
Barcodes_Channel_ID = [str(i)[2:-1] for i in data['Barcodes_Channel_ID']]
Barcodes_Corr_id = [str(i)[2:-1] for i in data['Barcodes_Corr_id']]
filetype_SRT_nEphys_Coordinates = 'SRT_nEphys_Multiscale_Coordinates.xlsx'
data_SRT_nEphys_Coordinates = pd.read_excel(self.srcfilepath + filetype_SRT_nEphys_Coordinates)
Barcodes = [str(i) for i in data_SRT_nEphys_Coordinates['Barcodes']]
# SRT_coordinate = [literal_eval(i) for i in data_SRT_nEphys_Coordinates['Coordinates in SRT']]
# x_SRT = [i[0] for i in SRT_coordinate]
# y_SRT = [i[1] for i in SRT_coordinate]
# Cluster = [i for i in data_SRT_nEphys_Coordinates['Cluster']]
filter_id = [i for i in range(len(Barcodes_Channel_ID)) if
Barcodes_Channel_ID[i] in Barcodes and Barcodes_Corr_id[i] in Barcodes]
Barcodes_Channel_ID = [Barcodes_Channel_ID[i] for i in filter_id]
Barcodes_Corr_id = [Barcodes_Corr_id[i] for i in filter_id]
Channel_ID = [data['Channel ID'][i] for i in filter_id]
Corr_id = [data['Corr_id'][i] for i in filter_id]
csv_file, tissue_lowres_scalef, features_name, matr_raw, barcodes, img, csv_file_cluster = self.read_related_files()
barcode_cluster = np.asarray(csv_file_cluster["Barcode"])
scatter_x = np.asarray(csv_file["pixel_x"] * tissue_lowres_scalef)
scatter_y = np.asarray(csv_file["pixel_y"] * tissue_lowres_scalef)
group = np.asarray(csv_file["selection"])
barcode_CSV = np.asarray(csv_file["barcode"])
g = 1
ix = np.where(group == g)
import re
gene_name = [str(features_name[i])[2:-1] for i in range(len(features_name))]
filter_gene_id = [i for i in range(len(gene_name)) if
len(re.findall(r'^SRS', gene_name[i], flags=re.IGNORECASE)) > 0 or len(
re.findall(r'^Mrp', gene_name[i], flags=re.IGNORECASE)) > 0 or len(
re.findall(r'^Rp', gene_name[i], flags=re.IGNORECASE)) > 0 or len(
re.findall(r'^mt', gene_name[i], flags=re.IGNORECASE)) > 0 or len(
re.findall(r'^Ptbp', gene_name[i], flags=re.IGNORECASE)) > 0]
matr = np.delete(matr_raw, filter_gene_id, axis=0)
genes_per_cell = np.asarray((matr > 0).sum(axis=0)).squeeze()
###############delete the nodes with less then 1000 gene count
deleted_notes = [i for i in range(len(genes_per_cell)) if genes_per_cell[i] <= 1000]
###############delete the nodes not in clusters
deleted_notes_cluster = [i for i in range(len(genes_per_cell)) if str(barcodes[i])[2:-1] not in barcode_cluster]
deleted_notes.extend(deleted_notes_cluster)
deleted_notes = list(np.unique(deleted_notes))
##########################################################
new_id = [j for i in barcode_CSV for j in range(len(barcodes)) if str(barcodes[j])[2:-1] == i]
x_filter = [scatter_x[ix][i] for i in range(len(scatter_x[ix])) if new_id[i] not in deleted_notes]
y_filter = [scatter_y[ix][i] for i in range(len(scatter_y[ix])) if new_id[i] not in deleted_notes]
barcode_CSV_filter = [barcode_CSV[ix][i] for i in range(len(scatter_y[ix])) if new_id[i] not in deleted_notes]
mask_id = [i for i in range(len(group)) if group[i] == 1]
extent = [min([scatter_x[i] for i in mask_id]), max([scatter_x[i] for i in mask_id]),
min([scatter_y[i] for i in mask_id]), max([scatter_y[i] for i in mask_id])]
x_coordinate, y_coordinate = x_filter - extent[0], y_filter - extent[2]
# print(len(x_coordinate),len(barcode_CSV_filter))
######################
data_all_links = [[Channel_ID[i], Corr_id[i]] for i in range(len(Channel_ID))]
weight_all_links = [data['coor_Per_data'][i] for i in filter_id]
All_id, indices = np.unique(Channel_ID + Corr_id, return_index=True)
All_Barcode = Barcodes_Channel_ID + Barcodes_Corr_id
All_Barcode = [All_Barcode[i] for i in indices]
######################
longitude = []
latitude = []
All_nodes_clusters = []
for id in range(len(All_id)):
# index_in_SRT = list(Barcodes).index(All_Barcode[id])
# latitude.append(SRT_coordinate[index_in_SRT][1]-min(y_SRT)) #y
# longitude.append(SRT_coordinate[index_in_SRT][0]-min(x_SRT)) #x
# All_nodes_clusters.append(Cluster[index_in_SRT]) # x
#########################
index_in_Raw = list(barcode_CSV_filter).index(All_Barcode[id])
latitude.append(y_coordinate[index_in_Raw]) # y
longitude.append(x_coordinate[index_in_Raw]) # x
All_nodes_clusters.append(
csv_file_cluster["Loupe Clusters"][list(barcode_cluster).index(All_Barcode[id])]) # x
nodes = pd.DataFrame(
{'id': list(All_id), 'cluster': All_nodes_clusters, 'latitude': latitude, 'longitude': longitude})
edges = pd.DataFrame(
{'source': [int(i[0]) for i in data_all_links if int(i[0]) in list(All_id)],
'target': [int(i[1]) for i in data_all_links if int(i[1]) in list(All_id)],
'weight': weight_all_links})
G = nx.from_pandas_edgelist(edges, 'source', 'target', edge_attr='weight')
nx.set_node_attributes(G, pd.Series(nodes.latitude.values, index=nodes.id).to_dict(), 'latitude')
nx.set_node_attributes(G, pd.Series(nodes.longitude.values, index=nodes.id).to_dict(), 'longitude')
nx.set_node_attributes(G, pd.Series(nodes.cluster.values, index=nodes.id).to_dict(), 'cluster')
nx.write_gexf(G, desfilepath + gene_list_name + '_SRT_mutual_information_connectivity' + '.gexf')
def network_topological_metrics(self): # run grapth_matrix firstly
"""
Determine specified network topological metrics from nEphys data.
File input needed:
-------
- '[file].bxr'
- '[file]_nEphys_functional_connectivity.xlsx'
- 'SRT_nEphys_Multiscale_Coordinates.xlsx'
Parameters
-------
Returns
-------
File output:
-------
- '[file]_network_topological_metrics_per_cluster.xlsx'
"""
filetype_bxr = '.bxr'
filename_bxr, Root = self.get_filename_path(self.srcfilepath, filetype_bxr)
for i in range(len(filename_bxr)):
expFile = filename_bxr[i]
if expFile[0]!='.':
filehdf5_bxr = h5py.File(Root[i] + expFile, 'r') # read LFPs bxr files
ChsGroups = np.asarray(filehdf5_bxr["3BUserInfo"]["ChsGroups"])
if type(ChsGroups['Name'][0]) != str:
ChsGroups['Name'] = [i.decode("utf-8") for i in ChsGroups['Name']]
MeaChs2ChIDsVector = np.asarray(filehdf5_bxr["3BResults"]["3BInfo"]["MeaChs2ChIDsVector"])
cluster_ids,clusters_ID = self.get_Groupid_nEphys(ChsGroups=ChsGroups)
print (filename_bxr)
filetype_xlsx = expFile[:-4] + '_nEphys_functional_connectivity.xlsx'
filename_xlsx, Root = self.get_filename_path(self.srcfilepath, filetype_xlsx)
print(filetype_xlsx)
data = pd.read_excel(Root[0] + '/' + filename_xlsx[0])
data_new = data.copy()
Channel_ID_cluster = []
for id in data_new['Class_LFPs_ID_Per']:
print (data_new)
for i in range(len(self.clusters)):
if i < len(clusters_ID) and id in clusters_ID[i]:
if i < len(self.clusters):
Channel_ID_cluster.append(self.clusters[i])
# Channel_ID_cluster = [self.clusters[i] for id in data_new['Class_LFPs_ID_Per'] for i in range(len(self.clusters)) if id in clusters_ID[i]]
Corr_id_cluster = []
for id in data_new['Corr_ID_Per']:
for i in range(len(self.clusters)):
if i < len(clusters_ID) and i < len(self.clusters) and id in clusters_ID[i]:
Corr_id_cluster.append(self.clusters[i])
# Corr_id_cluster = [self.clusters[i] for id in data_new['Corr_ID_Per'] for i in range(len(self.clusters)) if id in clusters_ID[i]]
df_add = pd.DataFrame({'Channel_ID_cluster': Channel_ID_cluster, 'Corr_id_cluster': Corr_id_cluster})
new_df = pd.concat([data_new, df_add], axis=1)
cluster = []
channel_ID = []
coordinates = []
result_clustering_coefficient = [] # clustering coefficient
result_average_node_connectivity = []
result_degree = []
result_betweenness = []
df_new = nx.from_pandas_edgelist(new_df, source='Class_LFPs_ID_Per', target='Corr_ID_Per', edge_attr=True)
clustering_coefficient = nx.clustering(df_new)
degree_centrality = nx.algorithms.centrality.degree_centrality(df_new)
betweenness_centrality = nx.algorithms.centrality.betweenness_centrality(df_new)
for i in range(len(self.clusters)):
if i < len(clusters_ID):
for id in clusters_ID[i]:
if id in list(df_new.nodes):
channel_ID.append(id)
coordinates.append([MeaChs2ChIDsVector["Col"][id]-1,MeaChs2ChIDsVector["Row"][id]-1])
if id in clustering_coefficient.keys():
result_clustering_coefficient.append(clustering_coefficient[id])
result_degree.append(df_new.degree(id))
result_average_node_connectivity.append(degree_centrality[id])
result_betweenness.append(betweenness_centrality[id])
cluster.append(self.clusters[i])
else:
result_clustering_coefficient.append(0)
result_degree.append(0)
result_average_node_connectivity.append(0)
result_betweenness.append(0)
cluster.append(self.clusters[i])
a = {'Channel ID': channel_ID, 'Clustering Coefficient':result_clustering_coefficient, "Centrality": result_average_node_connectivity,
"Degree": result_degree, 'Betweenness': result_betweenness,'Cluster':cluster, 'Coordinates': coordinates}
df = pd.DataFrame.from_dict(a, orient='index').T
df.to_excel(self.srcfilepath + expFile[:-4] +'_network_topological_metrics_per_cluster' + ".xlsx",index=False)
def coordinates_for_network_topological_metrics(self): # run grapth_matrix firstly
"""
Provide the transcriptomic and electrophysiologic overlay coordinates for network topological metrics.
File input needed:
-------
- related files
- '[file].bxr'
- 'SRT_nEphys_Multiscale_Coordinates.xlsx'
- '[file]_network_topological_metrics_per_cluster.xlsx'
Parameters
-------
Returns
-------
File output:
-------
- 'SRT_nEphys_Multiscale_Coordinates_for_network_topological_metrics.xlsx'
"""
filetype_SRT_nEphys_Coordinates = 'SRT_nEphys_Multiscale_Coordinates.xlsx'
filename_SRT_nEphys_Coordinates, Root = self.get_filename_path(self.srcfilepath, filetype_SRT_nEphys_Coordinates)
for i in range(len(filename_SRT_nEphys_Coordinates)):
if filename_SRT_nEphys_Coordinates[i][0] != '.':
SRT_nEphys_Coordinates_root = Root[i] + '/' + filename_SRT_nEphys_Coordinates[i]
# column_list = ["Synaptic plasticity", "Hippo Signaling Pathway", "Hippocampal Neurogenesis", "Synaptic Vescicles/Adhesion", "Receptors and channels", "IEGs"]
data_SRT_nEphys_Coordinates = pd.read_excel(SRT_nEphys_Coordinates_root)
filehdf5_bxr_name = '.bxr'
filehdf5_bxr_file, filehdf5_bxr_Root = self.get_filename_path(self.srcfilepath, filehdf5_bxr_name)
for i in range(len(filehdf5_bxr_file)):
if filehdf5_bxr_file[i][0] != '.':
filehdf5_bxr_root = filehdf5_bxr_Root[i] + '/' + filehdf5_bxr_file[i]
expFile = filehdf5_bxr_file[i]
data_nEphys = pd.read_excel(self.srcfilepath + expFile[:-4] + '_network_topological_metrics_per_cluster' + ".xlsx")
filehdf5_bxr = h5py.File(filehdf5_bxr_root, 'r')