Repository navigation
Expand file tree
/
Copy pathdata_preprocess_CellNEST.py
More file actions
563 lines (456 loc) · 28 KB
/
Copy pathdata_preprocess_CellNEST.py
File metadata and controls
563 lines (456 loc) · 28 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
# Written By
# Fatema Tuz Zohora
print('package loading')
import numpy as np
import pickle
from scipy import sparse
import numpy as np
import qnorm
from scipy.sparse import csr_matrix
from collections import defaultdict
import pandas as pd
import gzip
import argparse
import os
import scanpy as sc
import json
import gc
from sklearn.neighbors import NearestNeighbors
from sklearn.metrics.pairwise import euclidean_distances
import matplotlib.pyplot as plt
print('user input reading')
if __name__ == "__main__":
parser = argparse.ArgumentParser()
################## Mandatory ####################################################################
parser.add_argument( '--data_name', type=str, help='Name of the dataset', required=True)
parser.add_argument( '--data_from', type=str, required=True, help='Path to the dataset to read from. Space Ranger outs/ folder is preferred. Otherwise, provide the *.mtx file of the gene expression matrix.')
################# default is set ################################################################
parser.add_argument( '--data_type', type=str, default='anndata', help='Set one of these two types [visium, anndata]. visium refers to spot based Visium file.')
parser.add_argument( '--data_to', type=str, default='input_graph/', help='Path to save the input graph (to be passed to GAT)')
parser.add_argument( '--metadata_to', type=str, default='metadata/', help='Path to save the metadata')
parser.add_argument( '--filter_min_cell', type=int, default=1 , help='Minimum number of cells for gene filtering')
parser.add_argument( '--threshold_gene_exp', type=float, default=98, help='Threshold percentile for gene expression. Genes above this percentile are considered active.')
parser.add_argument( '--tissue_position_file', type=str, default='None', help='If your --data_from argument points to a *.mtx file instead of Space Ranger, then please provide the path to tissue position file.')
parser.add_argument( '--juxtacrine_distance', type=float, default=-1, help='Distance for filtering ligand-receptor pairs based on cell-cell contact information. Automatically calculated unless provided. It has the same unit as the coordinates (for Visium, that is pixel).')
parser.add_argument( '--split', type=int, default=0 , help='Set to 1 if you plan to run training by splitting the input graph into multiple subgraphs')
parser.add_argument( '--distance_measure', type=str, default='fixed' , help='Set neighborhood cutoff criteria. Choose from [knn, fixed]')
parser.add_argument( '--k', type=int, default=50 , help='Set neighborhood cutoff number. This will be used if --distance_measure=knn')
parser.add_argument( '--neighborhood_threshold', type=float, default=0 , help='Set neighborhood threshold distance in terms of same unit as the coordinates')
parser.add_argument( '--block_autocrine', type=int, default=0 , help='Set to 1 if you want to ignore autocrine signals.')
parser.add_argument( '--block_juxtacrine', type=int, default=0, help='Set to 1 if you want to ignore juxtacrine signals.')
parser.add_argument( '--database_path', type=str, default='database/CellNEST_database.csv' , help='Provide your desired ligand-receptor database path here. Default database is a combination of CellChat and NicheNet database. It should have Ligand and Receptor columns')
parser.add_argument( '--set_ROI', type=int, default=0, help='Set to 1 if you want to use ROI')
parser.add_argument( '--x_min', type=int, default=-1, help='Set if you want to use ROI')
parser.add_argument( '--x_max', type=int, default=-1, help='Set if you want to use ROI')
parser.add_argument( '--y_min', type=int, default=-1, help='Set if you want to use ROI')
parser.add_argument( '--y_max', type=int, default=-1, help='Set if you want to use ROI')
parser.add_argument( '--keep_target_genes', type=int, default=0, help='Set to 1 if you want to keep target genes.')
parser.add_argument( '--target_gene_threshold', type=float, default=80, help='Set to desired gene threshold for target genes.')
parser.add_argument( '--target_genes_file', type=str, default="", help='Set to the CSV file having target genes under column geneset')
parser.add_argument( '--target_genes_list', type=str, default="", help='String of target gene names to keep, separated by comma.')
parser.add_argument( '--skip_normalize', type=int, default=0, help='Set to 1 if you have QC data, so want to skip normalization')
parser.add_argument( '--use_celltype', type=int, default=0, help='Set to 1 to use cell types as node features. Provide the --celltype_path as well.')
parser.add_argument( '--celltype_path', type=str, default='database/celltype_annotation.csv',
help='If you want to use cell types as node features then provide the annotation (type/state/etc.) csv file path. ' \
'It should have two columns: Barcode and Type.')
parser.add_argument( '--plot_only', type=int, default=-1, help='Set to 1 if you just want to plot spatial data')
args = parser.parse_args()
if args.data_to == 'input_graph/':
args.data_to = args.data_to + args.data_name + '/'
if not os.path.exists(args.data_to):
os.makedirs(args.data_to)
if args.metadata_to == 'metadata/':
args.metadata_to = args.metadata_to + args.data_name + '/'
if not os.path.exists(args.metadata_to):
os.makedirs(args.metadata_to)
if args.keep_target_genes == 1:
if args.target_genes_list != "":
keep_gene_set = target_genes_list.split(',')
elif args.target_genes_file != "":
target_gene_file = pd.read_csv(args.target_genes_file)
keep_gene_set = list(target_gene_file['geneset'])
else:
print('Please provide the target gene list using --target_genes_list or --target_genes_file parameters.')
exit(0)
keep_gene_set = list(set(keep_gene_set))
print('Target gene set.')
else:
keep_gene_set = []
####### get the gene id, cell barcode, cell coordinates ######
print('Input data reading')
if args.tissue_position_file == 'None': # Data is available in Space Ranger output format
if args.data_type == 'visium': # spot-based
adata_h5 = sc.read_visium(path=args.data_from, count_file='filtered_feature_bc_matrix.h5')
print('input data read done')
gene_count_before = len(list(adata_h5.var_names) )
sc.pp.filter_genes(adata_h5, min_cells=args.filter_min_cell)
gene_count_after = len(list(adata_h5.var_names) )
print('Gene filtering done. Number of genes reduced from %d to %d'%(gene_count_before, gene_count_after))
gene_ids = list(adata_h5.var_names)
gene_ids = [gene_id.upper() for gene_id in gene_ids]
coordinates = adata_h5.obsm['spatial']
cell_barcode = np.array(adata_h5.obs.index)
print('Number of barcodes: %d'%cell_barcode.shape[0])
if args.skip_normalize == 0:
print('Applying quantile normalization')
temp = qnorm.quantile_normalize(np.transpose(sparse.csr_matrix.toarray(adata_h5.X))) #https://en.wikipedia.org/wiki/Quantile_normalization
cell_vs_gene = np.transpose(temp)
else:
cell_vs_gene = sparse.csr_matrix.toarray(adata_h5.X)
row_mins = cell_vs_gene.min(axis=1)
cell_vs_gene = cell_vs_gene - row_mins[:, np.newaxis]
####### use the spot diameter as the --juxtacrine_distance
if args.juxtacrine_distance == -1:
file = open(args.data_from+'/spatial/scalefactors_json.json', 'r')
data = json.load(file)
spot_diameter = data["spot_diameter_fullres"]
args.juxtacrine_distance = spot_diameter
elif args.data_type == 'anndata':
adata_h5 = sc.read_h5ad(args.data_from)
print('input data read done')
if args.plot_only == 1:
coordinates = np.array(adata_h5.obsm['spatial'])
## spatial image
plt.clf()
plt.scatter(coordinates[:,0], coordinates[:,1])
plt.savefig(args.data_name+'_spatialPlot.png', dpi=300, bbox_inches='tight')
print('Plot saved:'+args.data_name+'_spatialPlot.png')
exit(0)
gene_count_before = len(list(adata_h5.var_names))
sc.pp.filter_genes(adata_h5, min_cells=args.filter_min_cell)
gene_count_after = len(list(adata_h5.var_names) )
print('Gene filtering done. Number of genes reduced from %d to %d'%(gene_count_before, gene_count_after))
gene_ids = list(adata_h5.var_names)
gene_ids = [gene_id.upper() for gene_id in gene_ids]
coordinates = np.array(adata_h5.obsm['spatial'])
if args.set_ROI == 1:
if args.x_min == -1:
args.x_min = np.min(coordinates[:][0])
if args.x_max == -1:
args.x_max = np.max(coordinates[:][0])
if args.y_min == -1:
args.y_min = np.min(coordinates[:][1])
if args.y_max == -1:
args.y_max = np.max(coordinates[:][1])
keep_cells = []
for i in range(0, coordinates.shape[0]):
if args.x_min <= coordinates[i][0] and coordinates[i][0] <= args.x_max:
if args.y_min <= coordinates[i][1] and coordinates[i][1] <= args.y_max:
keep_cells.append(i)
adata_h5 = adata_h5[keep_cells]
print('after ROI cropping:')
print(adata_h5)
cell_barcode = np.array(adata_h5.obs_names) #obs.index)
print('Number of barcodes: %d'%cell_barcode.shape[0])
if args.skip_normalize == 0:
print('Applying quantile normalization')
temp = qnorm.quantile_normalize(np.transpose(sparse.csr_matrix.toarray(adata_h5.X))) #https://en.wikipedia.org/wiki/Quantile_normalization
cell_vs_gene = np.transpose(temp)
else:
cell_vs_gene = sparse.csr_matrix.toarray(adata_h5.X)
row_mins = cell_vs_gene.min(axis=1)
cell_vs_gene = cell_vs_gene - row_mins[:, np.newaxis]
else: # Data is not available in Space Ranger output format
# read the mtx file
temp = sc.read_10x_mtx(args.data_from)
print('*.mtx file read done')
gene_count_before = len(list(temp.var_names) )
sc.pp.filter_genes(temp, min_cells=args.filter_min_cell)
gene_count_after = len(list(temp.var_names) )
print('Gene filtering done. Number of genes reduced from %d to %d'%(gene_count_before, gene_count_after))
gene_ids = list(temp.var_names)
gene_ids = [gene_id.upper() for gene_id in gene_ids]
cell_barcode = np.array(temp.obs.index)
print('Number of barcodes: %d'%cell_barcode.shape[0])
if args.skip_normalize == 0:
print('Applying quantile normalization')
temp = qnorm.quantile_normalize(np.transpose(sparse.csr_matrix.toarray(temp.X))) #https://en.wikipedia.org/wiki/Quantile_normalization
cell_vs_gene = np.transpose(temp)
else:
cell_vs_gene = sparse.csr_matrix.toarray(temp.X)
row_mins = cell_vs_gene.min(axis=1)
cell_vs_gene = cell_vs_gene - row_mins[:, np.newaxis]
# now read the tissue position file. It has the format:
df = pd.read_csv(args.tissue_position_file, sep=",", header=None)
tissue_position = df.values
barcode_vs_xy = dict() # record the x and y coordinates for each spot/cell
for i in range (0, tissue_position.shape[0]):
barcode_vs_xy[tissue_position[i][0]] = [tissue_position[i][4], tissue_position[i][5]] # x and y coordinates
coordinates = np.zeros((cell_barcode.shape[0], 2)) # insert the coordinates in the order of cell_barcodes
for i in range (0, cell_barcode.shape[0]):
coordinates[i,0] = barcode_vs_xy[cell_barcode[i]][0]
coordinates[i,1] = barcode_vs_xy[cell_barcode[i]][1]
## spatial image
plt.clf()
plt.scatter(coordinates[:,0], coordinates[:,1])
plt.savefig(args.data_name+'_spatialPlot.png', dpi=300, bbox_inches='tight')
print('Plot saved:'+args.data_name+'_spatialPlot.png')
##################### make metadata: barcode_info ###################################
i=0
barcode_info=[]
for cell_code in cell_barcode:
barcode_info.append([cell_code, coordinates[i,0],coordinates[i,1], 0]) # last entry will hold the component number later
i=i+1
################################################
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
# build physical distance matrix
print('Build physical distance matrix')
if args.distance_measure == 'fixed':
# then you need to set the args.neighborhood_threshold
if args.neighborhood_threshold == 0:
distance_matrix = euclidean_distances(coordinates, coordinates)
#### then automatically calculate the min distance between two nodes #########
sorted_first_row = np.sort(distance_matrix[0,:])
distance_a_b = sorted_first_row[1]
args.neighborhood_threshold = distance_a_b * 4 # 4 times the distance between two nodes
distance_matrix = 0
gc.collect()
nbrs = NearestNeighbors(radius=args.neighborhood_threshold, algorithm='kd_tree', n_jobs=-1)
nbrs.fit(coordinates)
distances, indices = nbrs.kneighbors(coordinates)
print('Neighborhood distance is set to be %g (same unit as the coordinates)'%(args.neighborhood_threshold))
else:
print('Neighborhood distance is set to be %d nearest neighbors'%args.k)
nbrs = NearestNeighbors(n_neighbors=args.k, algorithm='kd_tree', n_jobs=-1)
nbrs.fit(coordinates)
distances, indices = nbrs.kneighbors(coordinates)
unique_distances = np.unique(distances)
distance_a_b = sorted(unique_distances)[1]
# distances: array of shape (n_cells, k) with the Euclidean distance from
# each cell to its k neighbors.
# indices: array of shape (n_cells, k) with the neighbor indices (row indices of X).
# each cell 'j' will receive signal from its neighbors 'i' in descending order of weights
print('Assign weight to the neighborhood relations based on neighborhood distance')
weightdict_i_to_j = defaultdict(dict)
for cell_idx in range (0, indices.shape[0]):
max_value = np.max(distances[cell_idx,:])
min_value = np.min(distances[cell_idx,:])
for neigh_idx in range (0, indices.shape[1]):
neigh_cell_idx = indices[cell_idx][neigh_idx]
distance_neigh_cell = distances[cell_idx][neigh_idx]
flipped_distance_neigh_cell = 1-(distance_neigh_cell-min_value)/(max_value-min_value)
# i = neigh_cell_idx, j = cell_idx
weightdict_i_to_j[neigh_cell_idx][cell_idx] = flipped_distance_neigh_cell
#### automatically set the args.juxtacrine_distance ############
if args.juxtacrine_distance == -1:
args.juxtacrine_distance = distance_a_b
if args.block_juxtacrine == 0:
print("Auto calculated juxtacrine distance is %g. To change it use --juxtacrine_distance"%args.juxtacrine_distance)
#### sort the nodes in the ascending order of x and y coordinates ####################
i=0
node_id_sorted_xy=[]
for cell_code in cell_barcode:
node_id_sorted_xy.append([i, coordinates[i,0],coordinates[i,1]])
i=i+1
node_id_sorted_xy = sorted(node_id_sorted_xy, key = lambda x: (x[1], x[2]))
#### needed if split data is used ##############
if args.split>0:
with gzip.open(args.metadata_to + args.data_name+'_'+'node_id_sorted_xy', 'wb') as fp: #b, a:[0:5]
pickle.dump(node_id_sorted_xy, fp)
####################################################################
# ligand - receptor database
print('ligand-receptor database reading.')
df = pd.read_csv(args.database_path, sep=",")
'''
Ligand Receptor Annotation Reference
0 TGFB1 TGFBR1 Secreted Signaling KEGG: hsa04350
1 TGFB1 TGFBR2 Secreted Signaling KEGG: hsa04350
'''
print('ligand-receptor database reading done.')
print('Preprocess start.')
ligand_dict_dataset = defaultdict(list)
cell_cell_contact = dict()
count_pair = 0
for i in range (0, df["Ligand"].shape[0]):
ligand = df["Ligand"][i]
if ligand not in gene_info: # not found in the dataset
continue
receptor = df["Receptor"][i]
if receptor not in gene_info: # not found in the dataset
continue
ligand_dict_dataset[ligand].append(receptor)
gene_info[ligand] = 'included'
gene_info[receptor] = 'included'
count_pair = count_pair + 1
if df["Annotation"][i] == 'Cell-Cell Contact':
cell_cell_contact[receptor] = '' # keep track of which ccc are labeled as cell-cell-contact
print('number of ligands %d '%len(ligand_dict_dataset.keys()))
included_gene=[]
for gene in gene_info.keys():
if gene_info[gene] == 'included':
included_gene.append(gene)
print('Total genes in this dataset: %d, number of genes working as ligand and/or receptor: %d '%(len(gene_ids),len(included_gene)))
# assign id to each entry in the ligand-receptor database
l_r_pair = dict()
lr_id = 0
for gene in list(ligand_dict_dataset.keys()):
ligand_dict_dataset[gene]=list(set(ligand_dict_dataset[gene]))
l_r_pair[gene] = dict()
for receptor_gene in ligand_dict_dataset[gene]:
l_r_pair[gene][receptor_gene] = lr_id
lr_id = lr_id + 1
print('number of ligand-receptor pairs in this dataset %d '%lr_id)
###################################################################################
#####################################################################################
# Set threshold gene percentile
cell_percentile = []
for i in range (0, cell_vs_gene.shape[0]):
y = sorted(cell_vs_gene[i]) # sort each row/cell in ascending order of gene expressions
## inter ##
active_cutoff = np.percentile(y, args.threshold_gene_exp)
if active_cutoff == min(cell_vs_gene[i][:]):
times = 1
while active_cutoff == min(cell_vs_gene[i][:]):
new_threshold = args.threshold_gene_exp + 5 * times
if new_threshold >= 100:
active_cutoff = max(cell_vs_gene[i][:])
if active_cutoff == min(cell_vs_gene[i][:]): # still same as the min --> flat curve: something wrong
active_cutoff = max(cell_vs_gene[i][:]) + 1 # This cell will be skipped
break
active_cutoff = np.percentile(y, new_threshold)
times = times + 1
cell_percentile.append(active_cutoff)
print('set threshold gene percentile done')
if args.keep_target_genes == 1:
# Set threshold gene percentile for target gene set
cell_percentile_80th = []
for i in range (0, cell_vs_gene.shape[0]):
y = sorted(cell_vs_gene[i]) # sort each row/cell in ascending order of gene expressions
## inter ##
active_cutoff = np.percentile(y, args.target_gene_threshold)
if active_cutoff == min(cell_vs_gene[i][:]):
times = 1
while active_cutoff == min(cell_vs_gene[i][:]):
new_threshold = args.threshold_gene_exp + 2 * times
if new_threshold >= 100:
active_cutoff = max(cell_vs_gene[i][:])
break
active_cutoff = np.percentile(y, new_threshold)
times = times + 1
cell_percentile_80th.append(active_cutoff)
print('set threshold gene percentile for target gene done')
##############################################################################
# some preprocessing before making the input graph
count_total_edges = 0
cells_ligand_vs_receptor = defaultdict(dict)
ligand_list = list(ligand_dict_dataset.keys())
start_index = 0 #args.slice
end_index = len(ligand_list) #min(len(ligand_list), start_index+100)
print('some preprocessing before making the input graph')
for g in range(start_index, end_index):
gene = ligand_list[g]
for i in weightdict_i_to_j:
if cell_vs_gene[i][gene_index[gene]] < cell_percentile[i]:
# before skipping, check again if it is a target gene
if gene in keep_gene_set:
if cell_vs_gene[i][gene_index[gene]] < cell_percentile_80th[i]:
continue
else:
continue
for j in weightdict_i_to_j[i]: # receptor
if args.block_autocrine == 1 and i==j:
continue
for gene_rec in ligand_dict_dataset[gene]:
if cell_vs_gene[j][gene_index[gene_rec]] < cell_percentile[j]:
# before skipping, check again if it is a target gene
if gene_rec in keep_gene_set:
if cell_vs_gene[j][gene_index[gene_rec]] < cell_percentile_80th[j]:
continue
else:
continue
if (gene_rec in cell_cell_contact) and (args.block_juxtacrine==1 or euclidean_distances(coordinates[i:i+1],coordinates[j:j+1]) > args.juxtacrine_distance):
continue
communication_score = cell_vs_gene[i][gene_index[gene]] * cell_vs_gene[j][gene_index[gene_rec]]
relation_id = l_r_pair[gene][gene_rec]
if communication_score<=0:
print('zero valued ccc score found. Might be a potential ERROR!! ')
continue
#cells_ligand_vs_receptor[i][j].append([gene, gene_rec, communication_score, relation_id])
if i in cells_ligand_vs_receptor:
if j in cells_ligand_vs_receptor[i]:
cells_ligand_vs_receptor[i][j].append([gene, gene_rec, communication_score, relation_id])
else:
cells_ligand_vs_receptor[i][j] = []
cells_ligand_vs_receptor[i][j].append([gene, gene_rec, communication_score, relation_id])
else:
cells_ligand_vs_receptor[i][j] = []
cells_ligand_vs_receptor[i][j].append([gene, gene_rec, communication_score, relation_id])
count_total_edges = count_total_edges + 1
print('%d/%d ligand genes processed'%(g+1, len(ligand_list)), end='\r')
print('')
#print('total number of edges in the input graph %d '%count_total_edges)
################################################################################
# input graph generation
ccc_index_dict = dict()
row_col = [] # list of input edges, row = from node, col = to node
edge_weight = [] # 3D edge features in the same order as row_col
lig_rec = [] # ligand and receptors corresponding to the edges in the same order as row_col
self_loop_found = defaultdict(dict) # to keep track of self-loops -- used later during visualization plotting
for i in cells_ligand_vs_receptor.keys():
#ccc_j = []
for j in cells_ligand_vs_receptor[i].keys():
if i in weightdict_i_to_j and j in weightdict_i_to_j[i]: #dist_X[i,j]>0: #distance_matrix[i][j] <= args.neighborhood_threshold:
count_local = 0
if len(cells_ligand_vs_receptor[i][j])>0:
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]
ligand_receptor_coexpression_score = cells_ligand_vs_receptor[i][j][k][2]
row_col.append([i,j])
edge_weight.append([weightdict_i_to_j[i][j], ligand_receptor_coexpression_score, cells_ligand_vs_receptor[i][j][k][3]])
lig_rec.append([gene, gene_rec])
if i==j: # self-loop
self_loop_found[i][j] = ''
total_num_cell = cell_vs_gene.shape[0]
print('total number of nodes is %d, and edges is %d in the input graph'%(total_num_cell, len(row_col)))
print('preprocess done.')
print('writing data ...')
################## input graph #################################################
with gzip.open(args.data_to + args.data_name + '_adjacency_records', 'wb') as fp:
pickle.dump([row_col, edge_weight, lig_rec, total_num_cell], fp)
print('Saved: '+ args.data_to + args.data_name + '_adjacency_records')
################# metadata #####################################################
with gzip.open(args.metadata_to + args.data_name +'_self_loop_record', 'wb') as fp:
pickle.dump(self_loop_found, fp)
print("Saved: " + args.metadata_to + args.data_name +'_self_loop_record')
with gzip.open(args.metadata_to + args.data_name +'_barcode_info', 'wb') as fp:
pickle.dump(barcode_info, fp)
print("Saved: " + args.metadata_to + args.data_name +'_barcode_info')
################## required for the CellNEST interactive version ###################
df = pd.DataFrame(gene_ids)
df.to_csv(args.metadata_to + 'gene_ids_'+args.data_name+'.csv', index=False, header=False)
df = pd.DataFrame(cell_barcode)
df.to_csv(args.metadata_to + 'cell_barcode_'+args.data_name+'.csv', index=False, header=False)
df = pd.DataFrame(coordinates)
df.to_csv(args.metadata_to + 'coordinates_'+args.data_name+'.csv', index=False, header=False)
######### optional #############################################################
# we do not need this to use anywhere. But just for debug purpose we are saving this. We can skip this if we have space issue.
with gzip.open(args.data_to + args.data_name + '_cell_vs_gene_quantile_transformed', 'wb') as fp:
pickle.dump(cell_vs_gene, fp)
# read cell type annotation and generate node feature vector using that
if args.use_celltype == 1 and args.celltype_path != '':
cell_annotation = pd.read_csv(args.celltype_path, sep=",")
# keep only those whose barcodes are saved: cell_barcode
cell_vs_annotation = dict()
for i in range(0, len(cell_annotation)):
cell_vs_annotation[cell_annotation['Barcode'][i]] = cell_annotation['Type'][i]
unique_annots = np.unique(list(cell_annotation['Type']))
unique_annots_count = len(unique_annots)
print('unique type found %d'%unique_annots_count)
type_vs_id = dict()
for i in range(0, len(unique_annots)):
type_vs_id[unique_annots[i]] = i
# one-hot vector node features
node_features = np.zeros((len(cell_barcode), unique_annots_count))
for i in range(0, len(cell_barcode)):
node_features[i][type_vs_id[cell_vs_annotation[cell_barcode[i]]]] = 1
with gzip.open(args.data_to + args.data_name + '_cell_vs_feature', 'wb') as fp:
pickle.dump(node_features, fp)
print('write data done')