-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathBSP.py
544 lines (474 loc) · 26.2 KB
/
BSP.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
import numpy as np
import pandas as pd
import sys, time, datetime, os
from scipy import stats
from scipy.spatial import distance
from sklearn.preprocessing import minmax_scale
from scipy.stats import gmean
import glob
import argparse
parser = argparse.ArgumentParser(description='Detecting Spatial Variable Gene using Big-Small Patch algorithm')
# Input and output
parser.add_argument('--datasetName', type=str, default='MOB', help='dataset: subfolder under data/. MOB as the example')
parser.add_argument('--inputDir', type=str, default='data/', help='Directory of input: default(data/)')
parser.add_argument('--spaLocFilename', type=str, default='Rep11_MOB_spa.csv', help='spatial location inputfile: default(%(default)s). Format: Loc*(x,y) with header')
parser.add_argument('--expFilename', type=str, default='Rep11_MOB_count.csv', help='expression inputfile: default(%(default)s). Format: Loc*Gene with header')
parser.add_argument('--outputDir', type=str, default='./', help='Directory of output: default(./)')
parser.add_argument('--outputFilename', type=str, default='P_values.csv', help='Filename of output: default(%(default)s)')
# Parameters
parser.add_argument('--D1', type=float, default=1.0, help='radius of small patch (default: %(default)s)')
parser.add_argument('--D2', type=float, default=3.0, help='radius of big patch (default: %(default)s)')
parser.add_argument('--distType', type=str, default='euclidean', help='euclidean/cityblock (default: %(default)s)')
parser.add_argument('--scaleFactor', type=float, default=1.0, help='alpha>0 (default: %(default)s)')
parser.add_argument('--edgeFillingTag', action='store_true', default=False, help='Test: fill nodes on the edge')
# For 3D transcriptomics
parser.add_argument('--for3DTag', action='store_true', default=False, help='For 3D')
# IO for large scale analysis
parser.add_argument('--oneFileTag', action='store_true', default=False, help='Use One file')
parser.add_argument('--inputFile', type=str, default='Rep11_MOB_merge.csv', help='Input file combining X Y and expression')
parser.add_argument('--useDirTag', action='store_true', default=False, help='Use all csv in the dir')
# Normalization
parser.add_argument('--normalize', type=str, default='minmax', help='scale (default: %(default)s)')
parser.add_argument('--noinputCellTag', action='store_true', default=False, help='Whether input file has no cell column (default: %(default)s)')
parser.add_argument('--notransTag', action='store_true', default=False, help='Whether input file has transposed (default: %(default)s)')
parser.add_argument('--logTransform', action='store_true', default=False, help='Whether logtransform (default: %(default)s)')
# Select Fitting Distribution
parser.add_argument('--fitDist', type=str, default='lognormal', help='Select fitting distribution lognormal/beta (default: %(default)s)')
parser.add_argument('--adjustP', action='store_true', default=False, help='Whether adjust Pvalue: No for lognormal distribution, Yes for beta distribution')
# Output top genes with user defined empirical quantiles
parser.add_argument('--empirical', action='store_true', default=False, help='Rank all the genes by test score, and output top genes by empirical quantiles')
parser.add_argument('--quantiles', type=str, default='0.05', help='Top percentage of genes ordered by test score (default: %(default)s)')
# Adjust for low throughput tech, like starmap
parser.add_argument('--noExtraNullGenes', action='store_true', default=False, help='Default: add extra 1000* null genes if the input genes are fewer than extraNullGeneNumberThres')
parser.add_argument('--extraNullGeneNumberThres', type=int, default=50, help='if less than extra Null Gene Number, add null genes (default: %(default)s)')
parser.add_argument('--nullGeneNumber', type=int, default=1000, help='extra Null Gene Number (default: %(default)s)')
parser.add_argument('--ManyNullGenes', action='store_true', default=False, help='1000 or 1000* null genes (default: %(default)s)')
parser.add_argument('--nullDebug', action='store_true', default=False, help='Debug information for output null genes (default: %(default)s)')
# If the data has many isolated patches
parser.add_argument('--isolated', action='store_true', default=False, help='Default: if the input is very sparse and has many isolated patches')
# Scaling
parser.add_argument('--noScaling', action='store_true', default=False, help='Default: scaling')
parser.add_argument('--quantileScaling', action='store_true', default=False, help='Default: minmax scaling. QuantileScaling is preferred to tolerate noises')
# debug
parser.add_argument('--memory', action='store_true', default=False, help='Output perform info in mem usage')
parser.add_argument('--debugperform', action='store_true', default=False, help='Output perform info in mem usage and computation time')
args = parser.parse_args()
scaleFactor = args.scaleFactor
if not os.path.exists(args.outputDir):
os.makedirs(args.outputDir)
def check_param():
'''Check valid parameters'''
if args.D1>=args.D2:
print("Radius of small patch D1 should be smaller than big patch D2, please check")
sys.exit(0)
def debuginfoStr(info):
'''
Default: output memory and computational time
'''
print('---'+str(datetime.timedelta(seconds=int(time.time()-start_time)))+'---'+info)
if args.memory:
if sys.platform == "linux" or sys.platform == "linux2" or sys.platform == "darwin":
# linux or OSX
import resource
mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
print('Mem consumption: '+str(mem))
else:
print('Non-linux system does not support memory consumption statistics')
def debugperformStr():
'''
For performance comparison usage, output memory and computational time
'''
if args.debugperform:
print('Running time: '+str(time.time()-alg_time))
if sys.platform == "linux" or sys.platform == "linux2" or sys.platform == "darwin":
# linux or OSX
import resource
mem = resource.getrusage(resource.RUSAGE_SELF).ru_maxrss
print('Mem consumption: '+str(mem))
else:
print('Non-linux system does not support memory consumption statistics')
def normalizeScalFactor(args,spatialMatrix):
'''
Scaling to normalize the spots in different scales: e.g.100 spots in 100*100: sqrt(100*100)/sqrt(100)=10
'''
scalFactor = 1.0
# default: scaling
if not args.noScaling:
# quantileScaling for noisy data
if args.quantileScaling:
if args.for3DTag:
scalFactor = gmean(np.quantile(spatialMatrix,0.975,axis=0)-np.quantile(spatialMatrix,0.025,axis=0))/(spatialMatrix.shape[0])**(1/3)
else:
scalFactor = gmean(np.quantile(spatialMatrix,0.975,axis=0)-np.quantile(spatialMatrix,0.025,axis=0))/np.sqrt(spatialMatrix.shape[0])
else:
# default: min-max
if args.for3DTag:
scalFactor = gmean(np.max(spatialMatrix,axis=0)-np.min(spatialMatrix,axis=0))/(spatialMatrix.shape[0])**(1/3)
else:
scalFactor = gmean(np.max(spatialMatrix,axis=0)-np.min(spatialMatrix,axis=0))/np.sqrt(spatialMatrix.shape[0])
D1 = args.D1*scalFactor
D2 = args.D2*scalFactor
print("Scaled small patch radius:"+str(D1)+"\tScaled big patch radius:"+str(D2))
return D1,D2
def checkNullGenes(expMatrix):
'''
Add Null genes if the input gene number is so small, especially for low-throughput techs as FISH
'''
# print(args.noExtraNullGenes)
# print(args.extraNullGeneNumberThres)
addNullNum = 0
if not args.noExtraNullGenes:
if expMatrix.shape[0] < args.extraNullGeneNumberThres:
print('Add 1000* null genes')
nullMatrix = expMatrix.copy()
# print(nullMatrix.shape)
# Option 1: (Not used) 1000 null genes
if not args.ManyNullGenes:
nullMatrix = np.tile(nullMatrix,(1 + (1000 // nullMatrix.shape[0]), 1))[:1000, :]
# Option 2: 1000*genes null genes
else:
nullMatrix = np.repeat(nullMatrix,args.nullGeneNumber,axis=0)
addNullNum = nullMatrix.shape[0]
# print(nullMatrix.shape)
# print('Start Permutation')
for i in range(len(nullMatrix)):
nullMatrix[i] = np.random.permutation(nullMatrix[i])
expMatrix = np.concatenate((expMatrix,nullMatrix),axis=0)
# print(expMatrix.shape)
# expMatrix: (originalGeneNumber+1000,locNumber)
return expMatrix,addNullNum
def granp(spatialMatrix, expMatrix, D1 = 1.0, D2 = 2.5 ):
'''calculate the p-values for a given array'''
# calculate the statistics for a given radius D
def targetstatisticsbyD(radiusD):
# define the patch for each centerpoint
def patch(CenterPoint):
# calculate the distance between cells for each center cell
CenterCoord = spatialMatrix[CenterPoint,:].reshape(1,-1)
DistList = distance.cdist(CenterCoord, spatialMatrix, args.distType)
## Option 2: select kth nearest cells
# DistListOrder = DistList.argsort()[0]
# PatchCells = [DistListOrder[i] for i in np.arange(0,K+1) if DistList[0,DistListOrder[i]] <= radiusD]
## Distance
PatchCells =[i for i,v in enumerate(DistList[0]) if (v <= radiusD and v>0.0)]
# Fix a bug, if the patchCells has 0 cells, then just include itself, to aviod NaN error.
if len(PatchCells)==0:
PatchCells.append(CenterPoint)
return(PatchCells)
# define the function to calculate variance of X_kpj for each gene j
def patchvar():
# define the function to calcualte X_kpj for each gene j and each cell p
def patchmeans(CenterPoint):
# Test for edge effects: May be delete
if args.edgeFillingTag:
if radiusD == 1.0:
edgeFixNum = 4
elif radiusD == 4.3:
edgeFixNum = 48
if len(PatchesCells[CenterPoint])>=edgeFixNum:
X_kpj = np.mean(Norm_Exp[:,PatchesCells[CenterPoint]],axis=1)
else:
padding_num = edgeFixNum-len(PatchesCells[CenterPoint])
tmp_mat = np.mean(Norm_Exp,axis=1)
tmp_mat = tmp_mat.reshape(tmp_mat.shape[0],1)
ori_mat = Norm_Exp[:,PatchesCells[CenterPoint]]
for i in range(padding_num):
ori_mat = np.concatenate((ori_mat,tmp_mat),axis=1)
X_kpj = np.mean(ori_mat,axis=1)
else:
X_kpj = np.mean(Norm_Exp[:,PatchesCells[CenterPoint]],axis=1)
return(X_kpj)
X_kj = np.zeros([spatialMatrix.shape[0], expMatrix.shape[0]])
# calculate the variance
for p in np.arange(spatialMatrix.shape[0]):
X_kj[p,:] = patchmeans(p)
return(np.var(X_kj,axis=0))
debuginfoStr('Start Define Patches')
# define the cell of patches
PatchesCells = [patch(p) for p in np.arange(spatialMatrix.shape[0])]
debuginfoStr('Calculating Variances of Each Patch')
# min max normalization
if args.normalize == 'minmax':
Norm_Exp = minmax_scale(expMatrix,axis=1)
else:
Norm_Exp = expMatrix
var_X_K = patchvar()
return(var_X_K)
# p-value corrections
def adjpvalue(p):
p = np.asfarray(p)
by_descend = p.argsort()[::-1]
by_orig = by_descend.argsort()
steps = float(len(p)) / np.arange(float(len(p)), 0, -1)
q = np.minimum(1, np.minimum.accumulate(steps * p[by_descend]))
return q[by_orig]
debuginfoStr('Start BSP Calculating')
# calculate the summary statistics
Var_X = [targetstatisticsbyD(K) for K in [D1] + [D2]]
Var_X_0_Add = [np.var(expMatrix[i,:]) for i in range(expMatrix.shape[0])]
Var_X_0_Add = (Var_X_0_Add/max(Var_X_0_Add))**scaleFactor
Var_X = np.asarray(Var_X)
# Calculate the test statistics:
## Debug for isolated data, replace the 0 value, but may takes some time
if args.isolated:
np.where(Var_X[0]==0,Var_X[0]+0.0001*np.random.rand(),Var_X[0])
T_matrix_sum = Var_X[1]/Var_X[0]*Var_X_0_Add
## Debug for further exploration, some data return error
if args.isolated:
np.where(T_matrix_sum==0,T_matrix_sum+0.0001*np.random.rand(),T_matrix_sum)
debuginfoStr('Start calculate p-value')
# print(np.max(T_matrix_sum))
# print(np.min(T_matrix_sum))
# calculate p-values
T_matrix_sum_upper90 = np.quantile(T_matrix_sum, 0.90)
T_matrix_sum_mid = [i for i in T_matrix_sum if i < T_matrix_sum_upper90]
# print(np.max(T_matrix_sum_mid))
# print(np.min(T_matrix_sum_mid))
## Select the fitting distribution
if args.fitDist == 'lognormal':
debuginfoStr('Start lognormal fit')
LogNormPar = [np.mean(np.log(T_matrix_sum_mid)), np.std(np.log(T_matrix_sum_mid))]
debuginfoStr('Start calculate pvalue')
pvalues = [1 - stats.lognorm.cdf(i, scale=np.exp(LogNormPar[0]), s = LogNormPar[1]) for i in T_matrix_sum]
elif args.fitDist == 'beta':
debuginfoStr('Start beta fit')
BetaPar = stats.beta.fit(T_matrix_sum_mid, floc=0, fscale=1)
a0 = BetaPar[0]
b0 = BetaPar[1]
debuginfoStr('Start calculate pvalue')
pvalues = [1-stats.beta.cdf(i, a0, b0) for i in T_matrix_sum]
else:
print('Please select appropriate fitting distribution: lognormal/beta')
sys.exit()
## whether adjust pvalue, or not
if args.adjustP:
adjpvalues = adjpvalue(pvalues)
debuginfoStr('End adjust pvalue')
else:
adjpvalues = pvalues
return(adjpvalues)
if __name__ == "__main__":
start_time = time.time()
debuginfoStr('Start')
check_param()
# if 3D:
# The example data comes from Vickovic, S., Schapiro, D., Carlberg, K. et al. Three-dimensional spatial transcriptomics uncovers cell type localizations in the human rheumatoid arthritis synovium. Commun Biol 5, 129 (2022). https://doi.org/10.1038/s42003-022-03050-3
# https://github.com/mssanjavickovic/3dst
if args.for3DTag:
if not args.useDirTag:
spaLocFile = args.inputDir + args.datasetName + '/' + args.spaLocFilename
expFile = args.inputDir + args.datasetName + '/' + args.expFilename
outputFile = args.outputDir + args.datasetName + '_' +args.outputFilename
# data pre-processing
debuginfoStr('Loading data and preprocessing')
spatialMatrix = pd.read_csv(spaLocFile)
spatialMatrix = spatialMatrix[['x','y','z']]
spatialMatrix = spatialMatrix.to_numpy() #For MOB: (262,2)
if args.noinputCellTag:
expMatrix = pd.read_csv(expFile)
else:
expMatrix = pd.read_csv(expFile,index_col=0)
print('Input dim: '+str(expMatrix.shape))
# drop genes with all zeros
expMatrix = expMatrix.loc[~expMatrix.apply(lambda row: (row==0.0).all(), axis=1)]
# expMatrix = expMatrix.loc[:, expMatrix.any()]
print('Nonzero dim: '+str(expMatrix.shape))
if not args.notransTag:
expMatrix = expMatrix.transpose()
# print(expMatrix)
geneIndex = expMatrix.index
expMatrix = expMatrix.to_numpy()
# for data with very few genes, add null genes from permutations
expMatrix, addNullNum=checkNullGenes(expMatrix)
# logTransform:
if args.logTransform:
expMatrix = np.log(expMatrix+1)
# Scaling to normalize the spots in different scales: e.g.100 spots in 100*100: sqrt(100*100)/sqrt(100)=10
D1,D2=normalizeScalFactor(args=args,spatialMatrix=spatialMatrix)
alg_time = time.time()
#============================ calculate granularity ==========================#
P_values = granp(spatialMatrix, expMatrix, D1 = D1, D2 = D2)
debugperformStr()
if not args.nullDebug:
if addNullNum !=0 :
# 1000* null genes
if args.ManyNullGenes:
P_values=P_values[:-addNullNum]
# 1000 null genes
else:
P_values=P_values[:-1000]
#================================= generate outputs ==========================#
debuginfoStr('Post processing')
if args.nullDebug:
outputData = pd.DataFrame(P_values, columns = ["p_values"])
else:
outputData = pd.DataFrame(P_values,
columns = ["p_values"],
index = geneIndex)
# Users can output the top percentage of genes regardless of the pvalues
if args.empirical:
rowcount=int(len(outputData)*float(args.quantiles))
outputData = outputData.nsmallest(rowcount, 'p_values')
outputData.to_csv(outputFile)
debuginfoStr('BSP Finished')
else:
path = args.inputDir
files = glob.glob(path+"*.csv")
for filename in files:
InputData = pd.read_csv(filename)
debuginfoStr('Loading data and preprocessing:'+filename)
spatialMatrix = InputData[['x','y','z']]
spatialMatrix = spatialMatrix.to_numpy()
expMatrix = InputData.drop(['x','y','z'], axis = 1)
print('Input dim: '+str(expMatrix.shape))
# drop genes with all zeros
expMatrix = expMatrix.loc[~expMatrix.apply(lambda row: (row==0.0).all(), axis=1)]
# expMatrix = expMatrix.loc[:, expMatrix.any()]
print('Nonzero dim: '+str(expMatrix.shape))
expMatrix = expMatrix.transpose()
geneIndex = expMatrix.index
expMatrix = expMatrix.to_numpy()
# for data with very few genes, add null genes from permutations
expMatrix, addNullNum=checkNullGenes(expMatrix)
# logTransform:
if args.logTransform:
expMatrix = np.log(expMatrix+1)
# Scaling to normalize the spots in different scales: e.g.100 spots in 100*100: sqrt(100*100)/sqrt(100)=10
D1,D2=normalizeScalFactor(args=args,spatialMatrix=spatialMatrix)
#============================ calculate granularity ==========================#
P_values = granp(spatialMatrix, expMatrix, D1 = D1, D2 = D2)
if not args.nullDebug:
if addNullNum !=0 :
# 1000* null genes
if args.ManyNullGenes:
P_values=P_values[:-addNullNum]
# 1000 null genes
else:
P_values=P_values[:-1000]
#================================= generate outputs ==========================#
debuginfoStr('Post processing')
if args.nullDebug:
outputData = pd.DataFrame(P_values, columns = ["p_values"])
else:
outputData = pd.DataFrame(P_values,
columns = ["p_values"],
index = geneIndex)
# Users can output the top percentage of genes regardless of the pvalues
if args.empirical:
rowcount=int(len(outputData)*float(args.quantiles))
outputData = outputData.nsmallest(rowcount, 'p_values')
outputData.to_csv(args.outputDir+filename.split('/')[-1].split('.csv')[0]+'_P_values.csv')
debuginfoStr('BSP Finished')
# 2D
else:
if not args.useDirTag:
spaLocFile = args.inputDir + args.datasetName + '/' + args.spaLocFilename
expFile = args.inputDir + args.datasetName + '/' + args.expFilename
outputFile = args.outputDir + args.datasetName + '_' +args.outputFilename
# data pre-processing
debuginfoStr('Loading data and preprocessing')
# Simulation data only in one file
if args.oneFileTag:
InputData = pd.read_csv(args.inputDir + args.datasetName + '/' + args.inputFile)
spatialMatrix = InputData[['x','y']]
spatialMatrix = spatialMatrix.to_numpy()
expMatrix = InputData.drop(['x','y'], axis = 1)
expMatrix = expMatrix.transpose()
else:
spatialMatrix = pd.read_csv(spaLocFile)
spatialMatrix = spatialMatrix[['x','y']]
spatialMatrix = spatialMatrix.to_numpy()
if args.noinputCellTag:
expMatrix = pd.read_csv(expFile)
else:
expMatrix = pd.read_csv(expFile,index_col=0)
if not args.notransTag:
# drop genes with all zeros
expMatrix = expMatrix.loc[:, expMatrix.any()]
expMatrix = expMatrix.transpose()
print('Input dim:'+str(expMatrix.shape)) #(Genes,locus) (12602,262) for MOB
# filtering
mat = expMatrix.to_numpy()
pp=np.sum(mat,axis=1)
ppuse = [i for i in range(mat.shape[0]) if pp[i] >= 15]
expMatrix=expMatrix.iloc[ppuse]
geneIndex = expMatrix.index
expMatrix = expMatrix.to_numpy()
print('Input dim after filter: '+str(expMatrix.shape)) #(Genes,locus) (12602,262) for MOB
# for data with very few genes, add null genes from permutations
expMatrix, addNullNum=checkNullGenes(expMatrix)
# logTransform:
if args.logTransform:
expMatrix = np.log(expMatrix+1)
# Scaling to normalize the spots in different scales: e.g.100 spots in 100*100: sqrt(100*100)/sqrt(100)=10
D1,D2=normalizeScalFactor(args=args,spatialMatrix=spatialMatrix)
alg_time = time.time()
#============================ calculate granularity ==========================#
P_values = granp(spatialMatrix, expMatrix, D1 = D1, D2 = D2)
debugperformStr()
if not args.nullDebug:
if addNullNum !=0 :
# print(len(P_values))
# 1000* null genes
if args.ManyNullGenes:
P_values=P_values[:-addNullNum]
# 1000 null genes
else:
P_values=P_values[:-1000]
# print(len(P_values))
#================================= generate outputs ==========================#
debuginfoStr('Post processing')
if args.nullDebug:
outputData = pd.DataFrame(P_values, columns = ["p_values"])
else:
outputData = pd.DataFrame(P_values,
columns = ["p_values"],
index = geneIndex)
# Users can output the top percentage of genes regardless of the pvalues
if args.empirical:
rowcount=int(len(outputData)*float(args.quantiles))
outputData = outputData.nsmallest(rowcount, 'p_values')
outputData.to_csv(outputFile)
debuginfoStr('BSP Finished')
else:
# Use files in the dir, for the simulation
# path = args.inputDir + args.datasetName + '/'
path = args.inputDir
files = glob.glob(path+"*.csv")
for filename in files:
InputData = pd.read_csv(filename)
spatialMatrix = InputData[['x','y']]
spatialMatrix = spatialMatrix.to_numpy()
expMatrix = InputData.drop(['x','y'], axis = 1)
expMatrix = expMatrix.transpose()
geneIndex = expMatrix.index
expMatrix = expMatrix.to_numpy()
# for data with very few genes, add null genes from permutations
expMatrix, addNullNum=checkNullGenes(expMatrix)
# logTransform:
if args.logTransform:
expMatrix = np.log(expMatrix+1)
# Scaling to normalize the spots in different scales: e.g.100 spots in 100*100: sqrt(100*100)/sqrt(100)=10
D1,D2=normalizeScalFactor(args=args,spatialMatrix=spatialMatrix)
#============================ calculate granularity ==========================#
P_values = granp(spatialMatrix, expMatrix, D1 = D1, D2 = D2)
if not args.nullDebug:
if addNullNum !=0 :
# 1000* null genes
if args.ManyNullGenes:
P_values=P_values[:-addNullNum]
# 1000 null genes
else:
P_values=P_values[:-1000]
#================================= generate outputs ==========================#
if args.nullDebug:
outputData = pd.DataFrame(P_values, columns = ["p_values"])
else:
outputData = pd.DataFrame(P_values,
columns = ["p_values"],
index = geneIndex)
# Users can output the top percentage of genes regardless of the pvalues
if args.empirical:
rowcount=int(len(outputData)*float(args.quantiles))
outputData = outputData.nsmallest(rowcount, 'p_values')
outputData.to_csv(args.outputDir+filename.split('/')[-1].split('.csv')[0]+'_P_values.csv')