-
Notifications
You must be signed in to change notification settings - Fork 1
/
synthetic_Visium_withPathway.py
2865 lines (2330 loc) · 119 KB
/
synthetic_Visium_withPathway.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
import os
#import glob
import pandas as pd
#import shutil
import copy
import csv
import numpy as np
import sys
import altair as alt
from collections import defaultdict
import stlearn as st
import scanpy as sc
import qnorm
import scipy
import pickle
import gzip
import matplotlib.pyplot as plt
from scipy import sparse
from scipy.sparse import csr_matrix
from scipy.sparse.csgraph import connected_components
from sklearn.metrics.pairwise import euclidean_distances
from kneed import KneeLocator
import argparse
parser = argparse.ArgumentParser()
parser.add_argument( '--data_path', type=str, default='/cluster/home/t116508uhn/64630/cellrangere/' , help='The path to dataset') #'/cluster/projects/schwartzgroup/fatema/pancreatic_cancer_visium/210827_A00827_0396_BHJLJTDRXY_Notta_Karen/V10M25-61_D1_PDA_64630_Pa_P_Spatial10x_new/outs/'
parser.add_argument( '--data_name', type=str, default='V10M25-61_D1_PDA_64630_Pa_P_Spatial10x_new', help='The name of dataset')
parser.add_argument( '--generated_data_path', type=str, default='generated_data/', help='The folder to store the generated data')
parser.add_argument( '--embedding_data_path', type=str, default='new_alignment/Embedding_data_ccc_rgcn/' , help='The path to attention') #'/cluster/projects/schwartzgroup/fatema/pancreatic_cancer_visium/210827_A00827_0396_BHJLJTDRXY_Notta_Karen/V10M25-61_D1_PDA_64630_Pa_P_Spatial10x_new/outs/'
args = parser.parse_args()
threshold_distance = 1.6 #2 = path equally spaced
k_nn = 10 # #5 = h
distance_measure = 'threshold_dist' #'knn' # <-----------
datatype = 'path_equally_spaced' #'path_uniform_distribution' #
'''
distance_measure = 'knn' #'threshold_dist' # <-----------
datatype = 'pattern_high_density_grid' #'pattern_equally_spaced' #'mixture_of_distribution' #'equally_spaced' #'high_density_grid' 'uniform_normal' # <-----------'dt-pattern_high_density_grid_lrc1_cp20_lrp1_randp0_all_same_midrange_overlap'
'''
cell_percent = 100 # choose at random N% ligand cells
lr_gene_count = 1000 #24 #8 #100 #20 #100 #20 #50 # and 25 pairs
rec_start = lr_gene_count//2 #
ligand_gene_list = []
for i in range (0, rec_start):
ligand_gene_list.append(i)
receptor_gene_list = []
for i in range (rec_start, lr_gene_count):
receptor_gene_list.append(i)
# ligand_gene_list = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21]
# receptor_gene_list = [22,23,24, 25, 26, 27,28,29,30,31,32,33,34,35,36,37,38,39,40,41,42, 43]
non_lr_genes = 10000 - lr_gene_count
# 1000/10000 = 10%
gene_ids = []
for i in range (0, lr_gene_count):
gene_ids.append(i)
gene_info=dict()
for gene in gene_ids:
gene_info[gene]=''
gene_index=dict()
i = 0
for gene in gene_ids:
gene_index[gene] = i
i = i+1
###############################################
lr_database = []
for i in range (0, 12): #len(ligand_gene_list)):
lr_database.append([ligand_gene_list[i],receptor_gene_list[i]])
ligand_dict_dataset = defaultdict(dict)
for i in range (0, len(lr_database)):
ligand_dict_dataset[lr_database[i][0]][lr_database[i][1]] = i
ligand_list = list(ligand_dict_dataset.keys())
# just print the lr_database
TP_LR_genes = []
for i in range (0, len(lr_database)):
print('%d: %d - %d'%(i, lr_database[i][0], lr_database[i][1]))
TP_LR_genes.append(lr_database[i][0])
TP_LR_genes.append(lr_database[i][1])
'''
0: 0 - 22
1: 1 - 23
2: 2 - 24
3: 3 - 25
4: 4 - 26
5: 5 - 27
6: 6 - 28
7: 7 - 29
8: 8 - 30
9: 9 - 31
10: 10 - 32
11: 11 - 33
12: 12 - 34
13: 13 - 35
14: 14 - 36
15: 15 - 37
16: 16 - 38
17: 17 - 39
18: 18 - 40
19: 19 - 41
20: 20 - 42
21: 21 - 43
'''
#pattern_list = [[[0, 1],[2, 3]], [[4, 5], [6, 7]]]
max_lr_pair_id = 80 #len(lr_database)//2
connection_count_max = 2 # for each pair of cells
pattern_list = []
i = 0
stop_flag = 0
while i < (len(lr_database)-connection_count_max*2):
pattern = []
j = i
connection_count = 0
while connection_count < connection_count_max:
pattern.append([j, j+1])
j = j + 2
connection_count = connection_count + 1
if j == max_lr_pair_id or j+1 == max_lr_pair_id:
stop_flag = 1
break
i = j
if stop_flag==1:
continue
pattern_list.append(pattern)
pattern_list = [[[0, 1], [2, 3]], [[4, 5], [6, 7]], [[8, 9], [10, 11]]]
'''
In [8]: pattern_list
Out[8]:
[[[0, 1], [2, 3]],
[[4, 5], [6, 7]],
[[8, 9], [10, 11]],
[[12, 13], [14, 15]],
[[16, 17], [18, 19]]]
'''
################# Now create some arbitrary pairs that will be false positives #########
for i in range (12, len(ligand_gene_list)-3):
# lr_database.append([ligand_gene_list[i],receptor_gene_list[i]])
# lr_database.append([ligand_gene_list[i],receptor_gene_list[i+1]])
# lr_database.append([ligand_gene_list[i],receptor_gene_list[i+2]])
for j in range (0, 3):
lr_database.append([ligand_gene_list[i],receptor_gene_list[i+j]])
ligand_dict_dataset = defaultdict(dict)
for i in range (0, len(lr_database)):
ligand_dict_dataset[lr_database[i][0]][lr_database[i][1]] = i
ligand_list = list(ligand_dict_dataset.keys())
''''''
########################################################################################
noise_add = 0 #2 #2 #1
noise_percent = 30
random_active_percent = 0
active_type = 'random_overlap' #'highrange_overlap' #
def get_data(datatype):
if datatype == 'path_equally_spaced':
x_max = 50 #50
x_min = 0
y_max = 60 #20 #30
y_min = 0
temp_x = []
temp_y = []
index_dict = defaultdict(dict)
i = x_min
# row major order, bottom up
k = 0
while i < x_max:
j = y_min
while j < y_max:
temp_x.append(i)
temp_y.append(j)
index_dict[i][j] = k
k = k+1
j = j + 1
i = i + 1
#0, 2, 4, ...24, 26, 28
temp_x = np.array(temp_x)
temp_y = np.array(temp_y)
return temp_x, temp_y, 0
elif datatype == 'path_uniform_distribution':
datapoint_size = 5000
x_max = 150 #500
x_min = 0
y_max = 150 #300
y_min = 0
a = x_min
b = x_max
#coord_x = np.random.randint(a, b, size=(datapoint_size))
coord_x = (b - a) * np.random.random_sample(size=datapoint_size) + a
a = y_min
b = y_max
coord_y = (b - a) * np.random.random_sample(size=datapoint_size) + a
#coord_y = np.random.randint(a, b, size=(datapoint_size))
temp_x = coord_x
temp_y = coord_y
region_list = []
'''
coord_x_t = np.random.normal(loc=200, scale=5, size=datapoint_size//8)
coord_y_t = np.random.normal(loc=150, scale=5, size=datapoint_size//8)
temp_x = np.concatenate((temp_x, coord_x_t))
temp_y = np.concatenate((temp_y, coord_y_t))
region_list.append([min(coord_x_t), max(coord_x_t), min(coord_y_t), max(coord_y_t)])
coord_x_t = np.random.normal(loc=100, scale=10, size=datapoint_size//8)
coord_y_t = np.random.normal(loc=100, scale=10, size=datapoint_size//8)
temp_x = np.concatenate((temp_x, coord_x_t))
temp_y = np.concatenate((temp_y, coord_y_t))
#region_list.append([min(coord_x_t), max(coord_x_t), min(coord_y_t), max(coord_y_t)])
coord_x_t = np.random.normal(loc=400,scale=15,size=datapoint_size//8)
coord_y_t = np.random.normal(loc=100,scale=15,size=datapoint_size//8)
temp_x = np.concatenate((temp_x, coord_x_t))
temp_y = np.concatenate((temp_y, coord_y_t))
#region_list.append([min(coord_x_t), max(coord_x_t), min(coord_y_t), max(coord_y_t)])
coord_x_t = np.random.normal(loc=400,scale=20,size=datapoint_size//8)
coord_y_t = np.random.normal(loc=200,scale=20,size=datapoint_size//8)
temp_x = np.concatenate((temp_x, coord_x_t))
temp_y = np.concatenate((temp_y, coord_y_t))
region_list.append([min(coord_x_t), max(coord_x_t), min(coord_y_t), max(coord_y_t)])
region_list.append([200, 350, 200, 300])
'''
discard_points = dict()
'''
for i in range (0, temp_x.shape[0]):
if i not in discard_points:
for j in range (i+1, temp_x.shape[0]):
if j not in discard_points:
if euclidean_distances(np.array([[temp_x[i],temp_y[i]]]), np.array([[temp_x[j],temp_y[j]]]))[0][0] < 1 :
print('i: %d and j: %d'%(i,j))
discard_points[j]=''
'''
coord_x = []
coord_y = []
for i in range (0, temp_x.shape[0]):
if i not in discard_points:
coord_x.append(temp_x[i])
coord_y.append(temp_y[i])
temp_x = coord_x
temp_y = coord_y
ccc_regions = []
for i in range (0, len(temp_x)):
for region in region_list:
x_max = region[1]
x_min = region[0]
y_min = region[2]
y_max = region[3]
if temp_x[i]>=x_min and temp_x[i]<=x_max and temp_y[i]>=y_min and temp_y[i]<=y_max:
ccc_regions.append(i)
temp_x = np.array(temp_x)
temp_y = np.array(temp_y)
return temp_x, temp_y, ccc_regions
#################################
temp_x, temp_y, ccc_region = get_data(datatype)
#############################################
print(len(temp_x))
plt.gca().set_aspect(1)
plt.scatter(x=np.array(temp_x), y=np.array(temp_y), s=1)
save_path = '/cluster/home/t116508uhn/64630/'
plt.savefig(save_path+'synthetic_spatial_plot_'+datatype+'.svg', dpi=400)
plt.clf()
get_cell = defaultdict(dict)
available_cells = []
for i in range (0, temp_x.shape[0]):
get_cell[temp_x[i]][temp_y[i]] = i
available_cells.append(i)
datapoint_size = temp_x.shape[0]
coordinates = np.zeros((temp_x.shape[0],2))
for i in range (0, datapoint_size):
coordinates[i][0] = temp_x[i]
coordinates[i][1] = temp_y[i]
distance_matrix = euclidean_distances(coordinates, coordinates)
########### weighted edge, based on neighborhood ##########
dist_X = np.zeros((distance_matrix.shape[0], distance_matrix.shape[1]))
cell_neighborhood = []
for i in range (0, datapoint_size):
cell_neighborhood.append([])
for j in range(0, distance_matrix.shape[1]):
max_value=np.max(distance_matrix[:,j])
min_value=np.min(distance_matrix[:,j])
for i in range(distance_matrix.shape[0]):
dist_X[i,j] = 1-(distance_matrix[i,j]-min_value)/(max_value-min_value)
if distance_measure=='knn':
list_indx = list(np.argsort(dist_X[:,j]))
k_higher = list_indx[len(list_indx)-k_nn:len(list_indx)]
for i in range(0, distance_matrix.shape[0]):
if i not in k_higher:
dist_X[i,j] = 0 #-1
else:
cell_neighborhood[i].append([j, dist_X[i,j]])
else:
for i in range(0, distance_matrix.shape[0]):
# i to j: ligand is i
if distance_matrix[i,j] > threshold_distance: #i not in k_higher:
dist_X[i,j] = 0 #-1
else:
cell_neighborhood[i].append([j, dist_X[i,j]])
for cell in range (0, len(cell_neighborhood)):
cell_neighborhood_temp = cell_neighborhood[cell]
cell_neighborhood_temp = sorted(cell_neighborhood_temp, key = lambda x: x[1], reverse=True) # sort based on distance
cell_neighborhood[cell] = [] # to record the neighbor cells in that order
for items in cell_neighborhood_temp:
cell_neighborhood[cell].append(items[0])
#np.random.shuffle(cell_neighborhood[cell])
####################################################################################
# take lr_gene_count normal distributions where each distribution has len(temp_x) datapoints.
# https://docs.scipy.org/doc/scipy/reference/generated/scipy.stats.pareto.html
i_am_whose = []
for i in range (0, datapoint_size):
i_am_whose.append([])
for i in range (0, datapoint_size):
for j in range (0, datapoint_size):
if i in cell_neighborhood[j] and j not in cell_neighborhood[i]:
i_am_whose[i].append(j)
max_neighbor = 0
for i in range (0, len(cell_neighborhood)):
if len(cell_neighborhood[i])>max_neighbor:
max_neighbor = len(cell_neighborhood[i])
print('max neighborhood: %d'%max_neighbor)
cell_count = len(temp_x)
gene_distribution_active = np.zeros((lr_gene_count + non_lr_genes, cell_count))
gene_distribution_inactive = np.zeros((lr_gene_count + non_lr_genes, cell_count))
#gene_distribution_inactive_lrgenes = np.zeros((lr_gene_count + non_lr_genes, cell_count))
gene_distribution_noise = np.zeros((lr_gene_count + non_lr_genes, cell_count))
################
start_loc = 20
rec_gene = lr_gene_count//2
for i in range (0, 12): #lr_gene_count//2):
gene_exp_list = np.random.normal(loc=start_loc+(i%2),scale=2,size=len(temp_x)) #loc=start_loc+(i%15) from loc=start_loc+(i%5) -- gave more variations so more FP
np.random.shuffle(gene_exp_list)
gene_distribution_inactive[i,:] = gene_exp_list
#print('%d: inactive: %g to %g'%(i, np.min(gene_distribution_inactive[i,:]),np.max(gene_distribution_inactive[i,:]) ))
gene_exp_list = np.random.normal(loc=start_loc+(i%2),scale=2,size=len(temp_x))
np.random.shuffle(gene_exp_list)
gene_distribution_inactive[rec_gene ,:] = gene_exp_list
#print('%d: inactive: %g to %g'%(rec_gene, np.min(gene_distribution_inactive[rec_gene,:]),np.max(gene_distribution_inactive[rec_gene,:]) ))
rec_gene = rec_gene + 1
# np.min(gene_distribution_inactive[i,:])-3, scale=.5
################
start_loc = 20
for i in range (12, lr_gene_count//2): ##):
gene_exp_list = np.random.normal(loc=start_loc+(i%2),scale=4,size=len(temp_x))
np.random.shuffle(gene_exp_list)
gene_distribution_inactive[i,:] = gene_exp_list
print('%d: inactive: %g to %g'%(i, np.min(gene_distribution_inactive[i,:]),np.max(gene_distribution_inactive[i,:]) ))
###############
gene_exp_list = np.random.normal(loc=start_loc+(i%2),scale=4,size=len(temp_x))
np.random.shuffle(gene_exp_list)
#gene_distribution_inactive_lrgenes[i,:] = gene_exp_list
#print('%d: inactive: %g to %g'%(i, np.min(gene_distribution_inactive[i,:]),np.max(gene_distribution_inactive[i,:]) ))
################
gene_exp_list = np.random.normal(loc=start_loc+(i%2),scale=4,size=len(temp_x))
np.random.shuffle(gene_exp_list)
gene_distribution_inactive[rec_gene ,:] = gene_exp_list
print('%d: inactive: %g to %g'%(rec_gene, np.min(gene_distribution_inactive[rec_gene,:]),np.max(gene_distribution_inactive[rec_gene,:]) ))
###################
gene_exp_list = np.random.normal(loc=start_loc+(i%2),scale=4,size=len(temp_x))
np.random.shuffle(gene_exp_list)
#gene_distribution_inactive_lrgenes[rec_gene ,:] = gene_exp_list
#print('%d: inactive: %g to %g'%(rec_gene, np.min(gene_distribution_inactive[rec_gene,:]),np.max(gene_distribution_inactive[rec_gene,:]) ))
rec_gene = rec_gene + 1
###################################################
start_loc = 15
for i in range (rec_gene, lr_gene_count + non_lr_genes):
gene_exp_list = np.random.normal(loc=start_loc+(i%10),scale=6,size=len(temp_x))
np.random.shuffle(gene_exp_list)
gene_distribution_inactive[i,:] = gene_exp_list
#print('%d: inactive: %g to %g'%(i, np.min(gene_distribution_inactive[i,:]),np.max(gene_distribution_inactive[i,:]) ))
#################
start_loc = 35 #np.max(gene_distribution_inactive)-10
rec_gene = lr_gene_count//2
scale_active_distribution = 1 #0.01
for i in range (0, 12):
gene_exp_list = np.random.normal(loc=start_loc+(i%5),scale=scale_active_distribution,size=len(temp_x)) #
np.random.shuffle(gene_exp_list)
gene_distribution_active[i,:] = gene_exp_list
#print('%d: active: %g to %g'%(i, np.min(gene_distribution_active[i,:]),np.max(gene_distribution_active[i,:]) ))
gene_exp_list = np.random.normal(loc=start_loc+(i%5),scale=scale_active_distribution,size=len(temp_x)) #
np.random.shuffle(gene_exp_list)
gene_distribution_active[rec_gene ,:] = gene_exp_list
#print('%d: active: %g to %g'%(rec_gene, np.min(gene_distribution_active[rec_gene,:]),np.max(gene_distribution_active[rec_gene,:]) ))
rec_gene = rec_gene + 1
#start_loc = 30 #np.max(gene_distribution_inactive)+2
for i in range (12, lr_gene_count//2):
gene_exp_list = np.random.normal(loc=start_loc+(i%5),scale=scale_active_distribution,size=len(temp_x)) #
np.random.shuffle(gene_exp_list)
gene_distribution_active[i,:] = gene_exp_list
#print('%d: active: %g to %g'%(i, np.min(gene_distribution_active[i,:]),np.max(gene_distribution_active[i,:]) ))
gene_exp_list = np.random.normal(loc=start_loc+(i%5),scale=scale_active_distribution,size=len(temp_x)) #
np.random.shuffle(gene_exp_list)
gene_distribution_active[rec_gene ,:] = gene_exp_list
#print('%d: active: %g to %g'%(rec_gene, np.min(gene_distribution_active[rec_gene,:]),np.max(gene_distribution_active[rec_gene,:]) ))
rec_gene = rec_gene + 1
#################################################
min_lr_gene_count = np.min(gene_distribution_inactive)
print('min_lr_gene_count %d'%min_lr_gene_count)
#min_lr_gene_count = 0
#########################
cell_vs_gene = np.zeros((cell_count,lr_gene_count + non_lr_genes))
# initially all are in inactive state
for i in range (0, lr_gene_count + non_lr_genes):
cell_vs_gene[:,i] = gene_distribution_inactive[i,:]
###############################################################
# record true positive connections
lig_rec_dict_TP = []
datapoint_size = temp_x.shape[0]
for i in range (0, datapoint_size):
lig_rec_dict_TP.append([])
for j in range (0, datapoint_size):
lig_rec_dict_TP[i].append([])
lig_rec_dict_TP[i][j] = []
P_class = 0
active_spot_in_pattern = []
neighbour_of_actives_in_pattern = []
for i in range (0, len(pattern_list)):
active_spot_in_pattern.append(dict())
neighbour_of_actives_in_pattern.append(dict())
active_spot = dict()
neighbour_of_actives = dict()
# Pick the regions for Ligands
'''
cells_ligand_vs_receptor = []
for i in range (0, cell_vs_gene.shape[0]):
cells_ligand_vs_receptor.append([])
for i in range (0, cell_vs_gene.shape[0]):
for j in range (0, cell_vs_gene.shape[0]):
cells_ligand_vs_receptor[i].append([])
cells_ligand_vs_receptor[i][j] = []
'''
flag_stop = 0
pattern_count = len(pattern_list)
for pattern_type in range (0, 3): #8): #pattern_count):
discard_cells = list(active_spot.keys()) # + list(neighbour_of_actives.keys())
ligand_cells = list(set(np.arange(cell_count)) - set(discard_cells))
max_ligand_count = 250 #100 #cell_count//(pattern_count*6) # 10. 1/N th of the all cells are following this pattern, where, N = total patterns
np.random.shuffle(ligand_cells)
print("pattern_type_index %d, ligand_cell count %d"%(pattern_type, max_ligand_count ))
#print(ligand_cells[0:10])
set_ligand_cells = []
for i in ligand_cells:
set_ligand_cells.append([temp_x[i], temp_y[i]])
k= -1
for i in ligand_cells:
# choose which L-R are working for this ligand i
if k > max_ligand_count:
break
a_cell = i
temp_neighborhood = []
for neighbor_cell in cell_neighborhood[a_cell]:
if neighbor_cell != a_cell:
temp_neighborhood.append(neighbor_cell)
if (len(temp_neighborhood)<1):
continue
b_cell = temp_neighborhood[len(temp_neighborhood)-1] # take the last one to make the pattern complex
temp_neighborhood = []
for neighbor_cell in cell_neighborhood[b_cell]:
if neighbor_cell != a_cell and neighbor_cell != b_cell:
temp_neighborhood.append(neighbor_cell)
if len(temp_neighborhood)<1:
continue
c_cell = temp_neighborhood[len(temp_neighborhood)-1] # take the last one to make the pattern complex
#if a_cell in neighbour_of_actives or b_cell in neighbour_of_actives or c_cell in neighbour_of_actives:
# continue
if a_cell in active_spot or b_cell in active_spot or c_cell in active_spot:
continue
if a_cell in neighbour_of_actives_in_pattern[pattern_type] or b_cell in neighbour_of_actives_in_pattern[pattern_type] or c_cell in neighbour_of_actives_in_pattern[pattern_type]:
continue
#if a_cell in active_spot_in_pattern[pattern_type] or b_cell in active_spot_in_pattern[pattern_type] or c_cell in active_spot_in_pattern[pattern_type]: # or cell_neighborhood[cell_neighborhood[cell_neighborhood[i][0]][0]][0] in neighbour_of_actives:
# continue
gene_group = pattern_list[pattern_type]
k = k + 1
##########################################
a_cell_active_genes = []
b_cell_active_genes = []
c_cell_active_genes = []
edge_list = []
###########################################
for gene_pair in gene_group:
a = gene_pair[0]
b = gene_pair[1]
lr_i = a
ligand_gene = lr_database[lr_i][0]
receptor_gene = lr_database[lr_i][1]
cell_id = a_cell
cell_vs_gene[cell_id, ligand_gene] = gene_distribution_active[ligand_gene, cell_id]
a_cell_active_genes.append(ligand_gene)
cell_id = b_cell
cell_vs_gene[cell_id, receptor_gene] = gene_distribution_active[receptor_gene, cell_id]
b_cell_active_genes.append(receptor_gene)
edge_list.append([a_cell, b_cell, ligand_gene, receptor_gene])
#########################################
lr_i = b
ligand_gene = lr_database[lr_i][0]
receptor_gene = lr_database[lr_i][1]
cell_id = b_cell
cell_vs_gene[cell_id, ligand_gene] = gene_distribution_active[ligand_gene, cell_id]
b_cell_active_genes.append(ligand_gene)
cell_id = c_cell
cell_vs_gene[cell_id, receptor_gene] = gene_distribution_active[receptor_gene, cell_id]
edge_list.append([b_cell, c_cell, ligand_gene, receptor_gene])
c_cell_active_genes.append(receptor_gene)
#################
ligand_receptor_genes = ligand_gene_list + receptor_gene_list
for gene in ligand_receptor_genes:
if gene not in a_cell_active_genes:
cell_vs_gene[a_cell, gene] = min_lr_gene_count #-10
for gene in ligand_receptor_genes:
if gene not in b_cell_active_genes:
cell_vs_gene[b_cell, gene] = min_lr_gene_count #-10
for gene in ligand_receptor_genes:
if gene not in c_cell_active_genes:
cell_vs_gene[c_cell, gene] = min_lr_gene_count #-10
##########################################
#print('%d, %d, %d'%(a_cell, b_cell, c_cell))
gene_off_list = a_cell_active_genes + b_cell_active_genes + c_cell_active_genes # all the ligand, receptor genes involve in this pattern
gene_off_list = list(set(gene_off_list )) # to remove duplicate entries
################################
# extend this list by adding the ligand / receptor who are involved with gene_off_list
'''
additional_gene = []
for gene in ligand_gene_list:
# if there is any ligand gene who has a receptor gene in gene_off_list, the add that ligand gene to the list as well
for receptor_gene in list(ligand_dict_dataset[gene].keys()):
if receptor_gene in gene_off_list:
additional_gene.append(gene)
break
for gene in gene_off_list:
if gene in ligand_gene_list:
# all receptor genes of this ligand gene should be included to the list as well
for receptor_gene in list(ligand_dict_dataset[gene].keys()):
additional_gene.append(receptor_gene)
gene_off_list = gene_off_list + additional_gene
gene_off_list = list(set(gene_off_list )) # to remove duplicate entries
'''
################################
active_spot[a_cell] = ''
active_spot[b_cell] = ''
active_spot[c_cell] = ''
turn_off_cell_list = list(set(cell_neighborhood[a_cell] + i_am_whose[a_cell]))
for cell in turn_off_cell_list: #cell_neighborhood[a_cell]:
if cell in [a_cell, b_cell, c_cell]:
continue
if cell in active_spot:
continue
neighbour_of_actives[cell]=''
neighbour_of_actives_in_pattern[pattern_type][cell] = ''
for gene in gene_off_list: #[0, 1, 2, 3, 8, 9, 10, 11]:
cell_vs_gene[cell, gene] = min_lr_gene_count #-10
turn_off_cell_list = list(set(cell_neighborhood[b_cell] + i_am_whose[b_cell]))
for cell in turn_off_cell_list:
if cell in [a_cell, b_cell, c_cell]:
continue
if cell in active_spot:
continue
neighbour_of_actives[cell]=''
neighbour_of_actives_in_pattern[pattern_type][cell] = ''
for gene in gene_off_list: #[0, 1, 2, 3, 8, 9, 10, 11]:
cell_vs_gene[cell, gene] = min_lr_gene_count #-10
turn_off_cell_list = list(set(cell_neighborhood[c_cell] + i_am_whose[c_cell]))
for cell in turn_off_cell_list:
if cell in [a_cell, b_cell, c_cell]:
continue
if cell in active_spot:
continue
neighbour_of_actives[cell]=''
neighbour_of_actives_in_pattern[pattern_type][cell] = ''
for gene in gene_off_list: #[0, 1, 2, 3, 8, 9, 10, 11]:
cell_vs_gene[cell, gene] = min_lr_gene_count #-10
active_spot_in_pattern[pattern_type][a_cell] = ''
active_spot_in_pattern[pattern_type][b_cell] = ''
active_spot_in_pattern[pattern_type][c_cell] = ''
##########################################
for edge in edge_list:
c1 = edge[0]
c2 = edge[1]
ligand_gene = edge[2]
receptor_gene = edge[3]
#########
communication_score = cell_vs_gene[c1,ligand_gene] * cell_vs_gene[c2,receptor_gene]
#communication_score = max(communication_score, 0)
if communication_score > 0:
lig_rec_dict_TP[c1][c2].append(ligand_dict_dataset[ligand_gene][receptor_gene])
P_class = P_class+1
else:
print('zero value found %g'%communication_score )
flag_stop = 1
break
#cells_ligand_vs_receptor[c1][c2].append([ligand_gene, receptor_gene, communication_score, ligand_dict_dataset[ligand_gene][receptor_gene]])
#########
if flag_stop == 1:
break
print('pattern %d is formed %d times'%(pattern_type, k))
print('P_class %d'%P_class)
cell_vs_gene_org = copy.deepcopy(cell_vs_gene)
#########################################################
############################
## Add false positives by randomly picking some cells and assigning them expressions from active distribution but without forming pattern ##
available_cells = []
for cell in range (0, cell_vs_gene.shape[0]):
if cell not in active_spot:
available_cells.append(cell)
np.random.shuffle(available_cells)
gene_id = np.arange(lr_gene_count)
gene_id = list(set(gene_id)-set(TP_LR_genes))
for i in range (0, (len(available_cells)*1)//1):
cell = available_cells[i]
np.random.shuffle(gene_id)
for j in range (0, 40): #
cell_vs_gene[cell, gene_id[j]] = gene_distribution_active[gene_id[j], cell]
######################################
if noise_percent > 0:
cell_count = cell_vs_gene.shape[0]
if noise_add == 1:
noise_percent = 30
noise_cells = list(np.random.randint(0, cell_count, size=(cell_count*noise_percent)//100)) #“discrete uniform” distribution #ccc_region #
gene_distribution_noise = np.zeros((len(noise_cells), cell_vs_gene.shape[1]))
for j in range (0, cell_vs_gene.shape[1]):
gene_distribution_noise[:, j] = np.random.normal(loc=0, scale=1, size = len(noise_cells))
np.random.shuffle(gene_distribution_noise[:, j])
print('noise: %g to %g'%(np.min(gene_distribution_noise),np.max(gene_distribution_noise) ))
elif noise_add == 2:
noise_percent = 30
'''
discard_cells = list(active_spot.keys())
noise_cells = list(set(np.arange(cell_count)) - set(discard_cells))
np.random.shuffle(noise_cells)
noise_cells = noise_cells[0:(cell_count*noise_percent)//100]
'''
noise_cells = list(np.random.randint(0, cell_count, size=(cell_count*noise_percent)//100)) #“discrete uniform” distribution #ccc_region #
gene_distribution_noise = np.zeros((len(noise_cells), cell_vs_gene.shape[1]))
for j in range (0, cell_vs_gene.shape[1]):
gene_distribution_noise[:, j] = np.random.normal(loc=0, scale=3, size = len(noise_cells))
np.random.shuffle(gene_distribution_noise[:, j])
print('noise: %g to %g'%(np.min(gene_distribution_noise),np.max(gene_distribution_noise) ))
for i in range (0, len(noise_cells)):
cell = noise_cells[i]
cell_vs_gene[cell, :] = cell_vs_gene[cell, :] + gene_distribution_noise[i,:]
#####################################################################
##############################
'''
# to reduce number of conections
#cell_vs_gene[:,7] = min_lr_gene_count #-10
#cell_vs_gene[:,15] = min_lr_gene_count #-10
#cell_vs_gene[:,6] = min_lr_gene_count #-10
#cell_vs_gene[:,14] = min_lr_gene_count #-10
available_cells = []
for cell in range (0, cell_vs_gene.shape[0]):
if cell not in active_spot:
available_cells.append(cell)
np.random.shuffle(available_cells)
for i in range (0, (len(available_cells)*1)//2):
cell = available_cells[i]
gene_id = np.arange(lr_gene_count)
for j in range (0, (len(gene_id)*2//3)): #
cell_vs_gene[cell, gene_id[j]] = min_lr_gene_count
'''
##############################
# take quantile normalization.
cell_vs_gene_notNormalized = copy.deepcopy(cell_vs_gene)
temp = qnorm.quantile_normalize(np.transpose(cell_vs_gene)) #, axis=0
adata_X = np.transpose(temp)
cell_vs_gene = adata_X
# cell_vs_gene = copy.deepcopy(cell_vs_gene_org)
cell_percentile = []
for i in range (0, cell_vs_gene.shape[0]):
y = sorted(cell_vs_gene[i])
'''
y_1 = np.histogram(cell_vs_gene[i])[0] # density:
x = range(0, len(y_1))
kn = KneeLocator(x, y_1, curve='convex', direction='decreasing')
kn_value = np.histogram(cell_vs_gene[i])[1][kn.knee]
'''
x = range(1, len(y)+1)
kn = KneeLocator(x, y, curve='convex', direction='increasing')
kn_value = y[kn.knee-1]
cell_percentile.append([np.percentile(y, 10), np.percentile(y, 20),np.percentile(y, 98), np.percentile(y, 99) , kn_value])
###############
# ready to go
################################################################################################
# do the usual things
''''''
cells_ligand_vs_receptor = []
for i in range (0, cell_vs_gene.shape[0]):
cells_ligand_vs_receptor.append([])
for i in range (0, cell_vs_gene.shape[0]):
for j in range (0, cell_vs_gene.shape[0]):
cells_ligand_vs_receptor[i].append([])
cells_ligand_vs_receptor[i][j] = []
count = 0
available_edges_to_drop = []
for i in range (0, cell_vs_gene.shape[0]): # ligand
for j in range (0, cell_vs_gene.shape[0]): # receptor
if dist_X[i,j] <= 0: #distance_matrix[i,j] > threshold_distance:
continue
#if i in neighbour_of_actives or j in neighbour_of_actives:
# continue
for gene in ligand_list:
rec_list = list(ligand_dict_dataset[gene].keys())
for gene_rec in rec_list:
'''
if i in noise_cells:
cell_vs_gene[i][gene_index[gene]] = cell_vs_gene[i][gene_index[gene]] + gene_distribution_noise[i]
if j in noise_cells:
cell_vs_gene[j][gene_index[gene_rec]] = cell_vs_gene[j][gene_index[gene_rec]] + gene_distribution_noise[j]
'''
if cell_vs_gene[i][gene_index[gene]] > cell_percentile[i][2] and cell_vs_gene[j][gene_index[gene_rec]] > cell_percentile[j][2]:
communication_score = cell_vs_gene[i][gene_index[gene]] * cell_vs_gene[j][gene_index[gene_rec]] #* dist_X[i,j]
communication_score = max(communication_score, 0)
if communication_score>0:
cells_ligand_vs_receptor[i][j].append([gene, gene_rec, communication_score, ligand_dict_dataset[gene][gene_rec]])
count = count + 1
#key = str(i)+'-'+str(j)+str(gene)+'-'+str(gene_rec)
#if ligand_dict_dataset[gene][gene_rec] not in lig_rec_dict_TP[i][j]:
# available_edges_to_drop.append([key, communication_scores])
print('total edges %d'%count)
#################
min_score = 1000
max_score = -1000
count = 0
dist = []
for i in range (0, len(lig_rec_dict_TP)):
flag_debug = 0
for j in range (0, len(lig_rec_dict_TP)):
for l in range (0, len(lig_rec_dict_TP[i][j])):
flag_found = 0
for k in range (0, len(cells_ligand_vs_receptor[i][j])):
if lig_rec_dict_TP[i][j][l]==cells_ligand_vs_receptor[i][j][k][3]:
dist.append(cells_ligand_vs_receptor[i][j][k][2])
count = count + 1
if cells_ligand_vs_receptor[i][j][k][2]>max_score:
max_score=cells_ligand_vs_receptor[i][j][k][2]
if cells_ligand_vs_receptor[i][j][k][2]<min_score:
min_score=cells_ligand_vs_receptor[i][j][k][2]
flag_found=1
break
#if flag_found==1:
print('P_class=%d, found=%d, %g, %g, %g'%(P_class, count, min_score, max_score, np.std(dist)))
#################
ccc_index_dict = dict()
row_col = []
edge_weight = []
lig_rec = []
count_edge = 0
max_local = 0
local_list = np.zeros((20))
for i in range (0, len(cells_ligand_vs_receptor)):
for j in range (0, len(cells_ligand_vs_receptor)):
if dist_X[i,j] > 0: #distance_matrix[i][j] <= threshold_distance:
count_local = 0
if len(cells_ligand_vs_receptor[i][j])>0:
# if not
for k in range (0, len(cells_ligand_vs_receptor[i][j])):
gene = cells_ligand_vs_receptor[i][j][k][0]
gene_rec = cells_ligand_vs_receptor[i][j][k][1]
count_edge = count_edge + 1
count_local = count_local + 1
#print(count_edge)
mean_ccc = cells_ligand_vs_receptor[i][j][k][2]
#mean_ccc = .1 + (cells_ligand_vs_receptor[i][j][k][2]-min_score_global)/(max_score_global-min_score_global)*(1-0.1) # cells_ligand_vs_receptor[i][j][k][2] #cells_ligand_vs_receptor[i][j][k][2] #*dist_X[i,j]
row_col.append([i,j])
ccc_index_dict[i] = ''
ccc_index_dict[j] = ''
edge_weight.append([dist_X[i,j], mean_ccc, cells_ligand_vs_receptor[i][j][k][3] ])
lig_rec.append(cells_ligand_vs_receptor[i][j][k][3])
if max_local < count_local:
max_local = count_local
'''
else: #elif i in neighbour_of_actives and j in neighbour_of_actives:
row_col.append([i,j])
edge_weight.append([dist_X[i,j], 0])
lig_rec.append(['', '']),
'''
''' '''
#local_list[count_local] = local_list[count_local] + 1
print('len row col %d'%len(row_col))
print('max local %d'%max_local)
#print('random_activation %d'%len(random_activation_index))
#print('ligand_cells %d'%len(ligand_cells))
print('P_class %d'%P_class)
options = 'dt-'+datatype+'_lrc'+str(len(lr_database))+'_cp'+str(cell_percent)+'_noise'+str(noise_percent)#'_close'
if noise_add == 1:
options = options + '_lowNoise'
if noise_add == 2:
options = options + '_heavyNoise'
total_cells = len(temp_x)
options = options+ '_' + active_type + '_' + distance_measure + '_cellCount' + str(total_cells)
#options = options + '_f'
options = options + '_3dim' + '_3patterns'+'_temp'
#options = options + '_scaled'
save_lig_rec_dict_TP = copy.deepcopy(lig_rec_dict_TP)
#lig_rec_dict_TP = copy.deepcopy(save_lig_rec_dict_TP)
lig_rec_dict_TP_temp = defaultdict(dict)
for i in range (0, len(lig_rec_dict_TP)):
for j in range (0, len(lig_rec_dict_TP)):
if len(lig_rec_dict_TP[i][j]) > 0:
lig_rec_dict_TP_temp[i][j] = []
for i in range (0, len(lig_rec_dict_TP)):
for j in range (0, len(lig_rec_dict_TP)):
if len(lig_rec_dict_TP[i][j]) > 0:
for k in range (0, len(lig_rec_dict_TP[i][j])):
lig_rec_dict_TP_temp[i][j].append(lig_rec_dict_TP[i][j][k])
lig_rec_dict_TP = 0
lig_rec_dict_TP = lig_rec_dict_TP_temp
with gzip.open("/cluster/projects/schwartzgroup/fatema/find_ccc/" + 'synthetic_data_ccc_roc_control_model_'+ options +'_'+'cellvsgene', 'wb') as fp:
pickle.dump(cell_vs_gene, fp)
#with gzip.open("/cluster/projects/schwartzgroup/fatema/find_ccc/" + 'synthetic_data_ccc_roc_control_model_'+ options +'_'+'_cellvsgene_'+ 'not_quantileTransformed', 'wb') as fp:
# pickle.dump(cell_vs_gene_notNormalized, fp)
with gzip.open("/cluster/projects/schwartzgroup/fatema/find_ccc/" + 'adjacency_records_synthetic_data_ccc_roc_control_model_'+ options, 'wb') as fp: # at least one of lig or rec has exp > respective knee point
pickle.dump([row_col, edge_weight, lig_rec], fp)