-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathfeats_batchcorrection.py
More file actions
490 lines (331 loc) · 14.4 KB
/
feats_batchcorrection.py
File metadata and controls
490 lines (331 loc) · 14.4 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
import numpy as np
import pandas as pd
from sklearn.metrics import pairwise_distances
from singlecelldata import SingleCell
def ComputeMNNPairs(X_ref, X, k):
# X_ref, X - (d x n) gene expression matrix
# k - number of nearest neighbours
n1 = X_ref.shape[1]
n2 = X.shape[1]
mnn_pair1 = np.zeros([n1, n2], dtype = bool)
mnn_pair2 = np.zeros([n1, n2], dtype = bool)
# Pairwise distance between X_ref and X
D = pairwise_distances(X = X_ref.T, Y = X.T, metric = "euclidean")
for i in range(n1):
idx = np.argsort(D[i, :])
idx = idx[0:k]
mnn_pair1[i, idx] = True
for i in range(n2):
idx = np.argsort(D[:, i])
idx = idx[0:k]
mnn_pair2[idx, i] = True
return np.logical_and(mnn_pair1, mnn_pair2), D
"""
===============================
Method Name: RemoveBatchEffects
===============================
Method Description: This method implements the MNN algorithm for removal of
batch effects in multiple datasets.
Arguments:
==========
batches - a list containing batches in the form of single cell object. The first batch will be taken as the reference batch.
Returns:
========
"""
def ReducedMean(X, idx):
idx_unique = np.unique(idx)
X_redmean = np.empty([X.shape[0], idx_unique.shape[0]])
for i in range(idx_unique.shape[0]):
idx_bool = (idx == idx_unique[i])
if (np.sum(idx_bool) == 1):
X_redmean[:, i] = np.squeeze(X[:, idx_bool])
elif (np.sum(idx_bool) > 1):
X_redmean[:, i] = np.squeeze(np.mean(X[:, idx_bool], axis=1, keepdims = True))
return X_redmean, idx_unique
def LogspaceAdd(log_array):
l = log_array.shape[0]
cum = np.zeros(l)
total = 0
for i in range(l):
if (i == 0):
total = log_array[i]
else:
total = np.logaddexp(total, log_array[i])
cum[i] = total
return total, cum
def ComputeCorrectionVectors(V, X, tar_idx, sigma):
ncells = X.shape[1]
d = V.shape[0]
nmnns = V.shape[1]
weights = np.empty([nmnns, ncells])
for i in range(nmnns):
weights[i, :] = -np.sum((X - X[:, tar_idx[i]].reshape(d,1))**2, axis=0)/(2*(sigma**2))
top_weights = np.amax(weights, axis = 0)
weights = np.exp(weights - top_weights)
#weights = np.exp(weights)
weights = weights / np.sum(weights, axis = 0)
C_vecs = np.dot(V, weights) # Correction vectors in columns
return C_vecs
def ComputeSpan(X, idx, svd_dim):
# Center the data
mu = np.mean(X[:, idx], axis = 1, keepdims=True)
X_cen = X[:, idx] - mu
U, _, _ = np.linalg.svd(X_cen)
U = U[:, 0:svd_dim]
return U
# This is a vectorized fuction
def SqDistToLine(ref, grad, point):
# ref - (d x 1), the reference on which the correction is applied
# grad - (d x 1), l2 normalized correction vector
# point - (d x n), other points in the target batch
d = ref.shape[0]
n = point.shape[1]
grad = grad.reshape(d, 1)
w = ref.reshape(d, 1) - point
scale = np.dot(grad.T, w)
w = w - (scale * np.tile(grad, (1, n)))
nrm = np.sum(w**2, axis = 0)
return nrm
def AdjustShiftVariance(X_ref, X, Corr, sigma):
# X_ref - (d x n1) matrix of reference batch
# X - (d x n2) gene expression for the target batch
#
#
ncells = Corr.shape[1]
scaling_factor = np.zeros(ncells)
# Computing the l2 norm of correction vector and normalizing to unit l2 norm
l2_norm = np.sum(Corr**2, axis = 0)
Corr_norm = Corr / l2_norm
# Projection of reference and target batch cells onto the correction vectors. (_ref represents reference batch quantities)
Proj = np.dot(Corr_norm.T, X)
Proj_ref = np.dot(Corr_norm.T, X_ref)
for i in range(ncells):
Nrm_same = SqDistToLine(X[:, i], Corr_norm[:, i], X)
log_prob = -Nrm_same/sigma
mask = (Proj[i, i] > Proj[i, :])
prob, _ = LogspaceAdd(log_prob[mask])
totalprob, _ = LogspaceAdd(log_prob)
prob = prob - totalprob
Nrm_other = SqDistToLine(X[:, i], Corr_norm[:, i], X_ref)
log_prob_ref = -Nrm_other/sigma
proj_ref_i = Proj_ref[i, :]
proj_ref_i_idx = np.argsort(proj_ref_i)
proj_ref_i = proj_ref_i[proj_ref_i_idx]
log_prob_ref = log_prob_ref[proj_ref_i_idx]
totalprob_ref, cumsum_ref = LogspaceAdd(log_prob_ref)
target = prob + totalprob_ref
mask2 = (cumsum_ref >= target)
if (np.sum(mask2) < 2):
ref_quan = np.flip(proj_ref_i)
else:
ref_quan = proj_ref_i[mask2]
scaling_factor[i] = (ref_quan[0] - Proj[i, i])/l2_norm[i]
return scaling_factor
def RemoveBatchEffects(ref_batch, tar_batch, k , sigma, svd_dim, adj_var):
# Get the expression of the reference batch and normalize
X_ref = ref_batch.getCounts()
X_tar = tar_batch.getCounts()
# Compute the mutual nearest neighbours (MNN's)
mnn, _ = ComputeMNNPairs(X_ref, X_tar, k)
ref_idxs, tar_idxs = np.nonzero(mnn)
# Compute batch effect as the vector difference of the reference and target batches
V = X_ref[:, ref_idxs] - X_tar[:, tar_idxs]
# Take the average of correction vectors for the target cells
V, tar_idx_uni = ReducedMean(V, tar_idxs)
# Compute the correction vectors for all the cells in the target batch using Gaussian kernel smoothing
C = ComputeCorrectionVectors(V, X_tar, tar_idx_uni, sigma)
# Compute biological span and remove the batch vector components parallel to biological basis vectors
if (svd_dim > 0):
ref_idx_uni = np.unique(ref_idxs)
U_ref = ComputeSpan(X_ref, ref_idx_uni, svd_dim)
U_tar = ComputeSpan(X_tar, tar_idx_uni, svd_dim)
for U in (U_tar, U_ref):
bio_comp = np.dot(C.T, U)
bio_comp = np.dot(bio_comp, U.T)
C = C - bio_comp.T
# Adjust shift variance
if (adj_var):
scaling = AdjustShiftVariance(X_ref, X_tar, C, sigma)
# print(scaling)
# print (np.sum(scaling))
scaling = np.maximum(scaling, 1)
# print(np.sum(scaling))
C = scaling * C
X_tar = X_tar + C
# Modify the expression values of the ref and tar batches
tar_batch.setCounts(X_tar)
ref_batch.setCounts(X_ref)
# Create a list
batches = [ref_batch, tar_batch]
# Merge the reference and target batches and return
sc = MergeBatches(batches)
return sc
def IntegrateBatches(batches, name_by):
"""
Integrates a list of SingleCell objects storing single-cell data. This function
first finds common genes across all the datasets in the list and then merges all
the datasets together in one SingleCell object. If no common genes are found between
the datasets, then an error is generated with a message.
Parameters
----------
batches : list
A Python list of SingleCell objects (datasets) to integrate.
name_by : list
A list of str representing column names in the SingleCell objects where gene names
are stored. The order in this list is same as the order of SingleCell objects in
the batches list.
Returns
-------
SingleCell
A merged dataset where the number of rows (d) is equal to the number of common genes in all the
datasets and the number columns (n) is the sum of the number of cells in all the datasets.
Raises
------
ValueError
If no common genes are found between the SingleCell datasets in the batches list.
"""
print ("Integrating Batches . . .")
# Incorporate batch info to sc object
for i in range(len(batches)):
batch_no = [batches[i].dataset] * batches[i].dim[1]
batches[i].addCellData(col_data = batch_no, col_name = 'batch')
# Find common genes in all the datasets
keep_genes = set()
for i in range(len(batches)):
gene_list = batches[i].getGeneData(name_by[i]).tolist()
if len(keep_genes) == 0:
keep_genes = set(gene_list)
else:
keep_genes &= set(gene_list)
#print ("Num genes: ", len(keep_genes))
# Warn user and exit if no common genes are found
if len(keep_genes) == 0:
raise ValueError('No common genes found in all datasets! Check if datasets have common genes.')
# Print the number of common genes in all datasets
print("Number of common genes in all batches: ", len(keep_genes))
# Filter the sc object
ret_genes = np.array(sorted(keep_genes))
for i in range(len(batches)):
# Remove duplicate genes.
genes = batches[i].getGeneData(name_by[i]).tolist()
uniq_genes, uniq_idx = np.unique(genes, return_index=True)
Xi = batches[i].getCounts()
Xi = Xi[uniq_idx, :]
sort_idx = np.argsort(uniq_genes)
gene_idx = []
for idx in sort_idx:
if (uniq_genes[idx] in ret_genes):
gene_idx.append(idx)
assert(np.array_equal(uniq_genes[gene_idx], ret_genes))
# Combine the dataframes of the batches together
Xi = Xi[gene_idx, :]
data = pd.DataFrame(Xi)
celldata = batches[i].celldata
genedata = pd.DataFrame(ret_genes, index = data.index, columns = ['gene_names'])
batches[i] = SingleCell(dataset = batches[i].dataset, data = data, celldata = celldata, genedata = genedata)
batches = MergeBatches(batches)
return batches
def MergeBatches(batches):
"""
Merges a list of SingleCell objects storing single-cell data. This function
assumes that the datasets are already integrated and the number and type of genes
in all the datasets are the same. If this is not the case, then an error is generated.
Parameters
----------
batches : list
A Python list of SingleCell objects (datasets) to merge. It is assumed that the
SingleCell datasets are already integrated.
Returns
-------
SingleCell
A merged dataset where the number of rows (d) is equal to the number genes the datasets
(which is the same for all the datasets) and the number columns (n) is the sum of the number
of cells in all the datasets.
Raises
------
ValueError
If the number and type of genes are not the same in all the datasets.
"""
print("Merging Batches . . .")
data_frames = [batches[0].data]
cell_data_frames = [batches[0].celldata]
merged_name = batches[0].dataset
for i in range(1, len(batches)):
data_frames.append(batches[i].data)
cell_data_frames.append(batches[i].celldata)
merged_name = merged_name + '+' + batches[i].dataset
# Return the combined object with a batches in the celldata array indicating the batch number/dataset name
merged_data = pd.concat(data_frames, axis = 1, ignore_index = True, sort = False)
merged_celldata = pd.concat(cell_data_frames, axis = 0, ignore_index = True, sort = False)
# Assuming that the genes in all the batches is the same, i.e., batches have been integrated using IntegrateBatches
merged_genedata = batches[0].genedata
#print(merged_data.shape)
#print(merged_celldata.shape)
# Create a new singlecell object
sc = SingleCell(dataset = merged_name, data = merged_data, celldata = merged_celldata, genedata = merged_genedata)
return sc
def CorrectBatches(batches, correct_order, k = 20, sigma = 10, svd_dim = 0, adj_var = True):
"""
Implements the Mutual Nearest Neighbour (MNN) approach to correcting batch effects in the integrated
and merged datasets.
Parameters
----------
batches : SingleCell
An integrated and merged SingleCell object (dataset) to correct. This dataset should have a 'batch' column
in the celldata dataframe with batch information.
correct_order : list
A Python list by the batch number or name representing the order in which to correct the batches.
The first batch in the list is the reference batch.
k : int, optional
The number of Mutual Nearest Neighbours to compute between the datasets to be corrected. default (20).
signa : float, optional
A parameter controlling the width of the Gaussian kernel smoothing function.
svd_dim : int, optional
The dimensionality of U when computing the SVD of data, where U, S, V^T = svd(X). default (0).
adj_var : bool, optional
Whether or not to adjust the variance of the computed batch vectors. True (default) if adjust
the variance, False if not.
Returns
-------
SingleCell
The corrected dataset.
Raises
------
ValueError
If the length of 'correct_order' is less than 2, and if no batch information is found in
the input parameter 'batches'.
"""
# Check the following:
# 1. at least two batches must be present
# 2. if 'integrated == False', name_by must be a list with the same length as batches
if (len(correct_order) < 2):
print('<correct_order> - specifies less than two batches are to be merged. Specify two or more batches to be corrected.')
batch_info = batches.getCellData('batch')
correct_order_split = correct_order[0].split('+')
if (len(correct_order_split) == 1):
idx = (batch_info == correct_order[0])
else:
idx = np.zeros(batches.dim[1], dtype = bool)
for i in range(len(correct_order_split)):
idx = np.logical_or(idx, (batch_info == correct_order_split[i]))
ref_batch = batches[:, idx.tolist()]
# print(ref_batch.dim)
ref_batch.dataset = correct_order[0]
for i in range(1, len(correct_order)):
correct_order_split = correct_order[i].split('+')
if (len(correct_order_split) == 1):
idx = (batch_info == correct_order[i])
else:
idx = np.zeros(batches.dim[1], dtype = bool)
for j in range(len(correct_order_split)):
idx = np.logical_or(idx, (batch_info == correct_order_split[j]))
tar_batch = batches[:, idx.tolist()]
tar_batch.dataset = correct_order[i]
print('Correcting batches <', ref_batch.dataset, ' and ', tar_batch.dataset, '>' )
ref_batch = RemoveBatchEffects( ref_batch,
tar_batch,
k = k,
sigma = sigma,
svd_dim = svd_dim,
adj_var = adj_var)
return ref_batch