SURE-tools 2.4.22__py3-none-any.whl → 2.4.43__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.

Potentially problematic release.


This version of SURE-tools might be problematic. Click here for more details.

@@ -0,0 +1,1414 @@
1
+ import pyro
2
+ import pyro.distributions as dist
3
+ from pyro.optim import ExponentialLR
4
+ from pyro.infer import SVI, JitTraceEnum_ELBO, TraceEnum_ELBO, config_enumerate
5
+
6
+ import torch
7
+ import torch.nn as nn
8
+ from torch.utils.data import DataLoader
9
+ from torch.distributions.utils import logits_to_probs, probs_to_logits, clamp_probs
10
+ from torch.distributions import constraints
11
+ from torch.distributions.transforms import SoftmaxTransform
12
+
13
+ from .utils.custom_mlp import MLP, Exp, ZeroBiasMLP
14
+ from .utils.utils import CustomDataset, CustomDataset2, CustomDataset4, tensor_to_numpy, convert_to_tensor
15
+
16
+
17
+ import os
18
+ import argparse
19
+ import random
20
+ import numpy as np
21
+ import datatable as dt
22
+ from tqdm import tqdm
23
+ from scipy import sparse
24
+
25
+ import scanpy as sc
26
+ from .atac import binarize
27
+
28
+ from typing import Literal
29
+
30
+ import warnings
31
+ warnings.filterwarnings("ignore")
32
+
33
+ import dill as pickle
34
+ import gzip
35
+ from packaging.version import Version
36
+ torch_version = torch.__version__
37
+
38
+
39
+ def set_random_seed(seed):
40
+ # Set seed for PyTorch
41
+ torch.manual_seed(seed)
42
+
43
+ # If using CUDA, set the seed for CUDA
44
+ if torch.cuda.is_available():
45
+ torch.cuda.manual_seed(seed)
46
+ torch.cuda.manual_seed_all(seed) # For multi-GPU setups.
47
+
48
+ # Set seed for NumPy
49
+ np.random.seed(seed)
50
+
51
+ # Set seed for Python's random module
52
+ random.seed(seed)
53
+
54
+ # Set seed for Pyro
55
+ pyro.set_rng_seed(seed)
56
+
57
+ class DensityFlowLinear(nn.Module):
58
+ def __init__(self,
59
+ input_size: int,
60
+ codebook_size: int = 200,
61
+ cell_factor_size: int = 0,
62
+ turn_off_cell_specific: bool = False,
63
+ supervised_mode: bool = False,
64
+ z_dim: int = 10,
65
+ z_dist: Literal['normal','studentt','laplacian','cauchy','gumbel'] = 'gumbel',
66
+ loss_func: Literal['negbinomial','poisson','multinomial','bernoulli'] = 'negbinomial',
67
+ dispersion: float = 8.0,
68
+ use_zeroinflate: bool = False,
69
+ hidden_layers: list = [500],
70
+ hidden_layer_activation: Literal['relu','softplus','leakyrelu','linear'] = 'relu',
71
+ nn_dropout: float = 0.1,
72
+ post_layer_fct: list = ['layernorm'],
73
+ post_act_fct: list = None,
74
+ config_enum: str = 'parallel',
75
+ use_cuda: bool = True,
76
+ seed: int = 42,
77
+ zero_bias: bool|list = True,
78
+ dtype = torch.float32, # type: ignore
79
+ ):
80
+ super().__init__()
81
+
82
+ self.input_size = input_size
83
+ self.cell_factor_size = cell_factor_size
84
+ self.dispersion = dispersion
85
+ self.latent_dim = z_dim
86
+ self.hidden_layers = hidden_layers
87
+ self.decoder_hidden_layers = hidden_layers[::-1]
88
+ self.allow_broadcast = config_enum == 'parallel'
89
+ self.use_cuda = use_cuda
90
+ self.loss_func = loss_func
91
+ self.options = None
92
+ self.code_size=codebook_size
93
+ self.supervised_mode=supervised_mode
94
+ self.latent_dist = z_dist
95
+ self.dtype = dtype
96
+ self.use_zeroinflate=use_zeroinflate
97
+ self.nn_dropout = nn_dropout
98
+ self.post_layer_fct = post_layer_fct
99
+ self.post_act_fct = post_act_fct
100
+ self.hidden_layer_activation = hidden_layer_activation
101
+ if type(zero_bias) == list:
102
+ self.use_bias = [not x for x in zero_bias]
103
+ else:
104
+ self.use_bias = [not zero_bias] * self.cell_factor_size
105
+ #self.use_bias = not zero_bias
106
+ self.turn_off_cell_specific = turn_off_cell_specific
107
+
108
+ self.codebook_weights = None
109
+
110
+ self.seed = seed
111
+ set_random_seed(seed)
112
+ self.setup_networks()
113
+
114
+ print(f"🧬 DensityFlowLinear Initialized:")
115
+ print(f" - Latent Dimension: {self.latent_dim}")
116
+ print(f" - Gene Dimension: {self.input_size}")
117
+ print(f" - Hidden Dimensions: {self.hidden_layers}")
118
+ print(f" - Device: {self.get_device()}")
119
+ print(f" - Parameters: {sum(p.numel() for p in self.parameters()):,}")
120
+
121
+ def setup_networks(self):
122
+ latent_dim = self.latent_dim
123
+ hidden_sizes = self.hidden_layers
124
+
125
+ nn_layer_norm, nn_batch_norm, nn_layer_dropout = False, False, False
126
+ na_layer_norm, na_batch_norm, na_layer_dropout = False, False, False
127
+
128
+ if self.post_layer_fct is not None:
129
+ nn_layer_norm=True if ('layernorm' in self.post_layer_fct) or ('layer_norm' in self.post_layer_fct) else False
130
+ nn_batch_norm=True if ('batchnorm' in self.post_layer_fct) or ('batch_norm' in self.post_layer_fct) else False
131
+ nn_layer_dropout=True if 'dropout' in self.post_layer_fct else False
132
+
133
+ if self.post_act_fct is not None:
134
+ na_layer_norm=True if ('layernorm' in self.post_act_fct) or ('layer_norm' in self.post_act_fct) else False
135
+ na_batch_norm=True if ('batchnorm' in self.post_act_fct) or ('batch_norm' in self.post_act_fct) else False
136
+ na_layer_dropout=True if 'dropout' in self.post_act_fct else False
137
+
138
+ if nn_layer_norm and nn_batch_norm and nn_layer_dropout:
139
+ post_layer_fct = lambda layer_ix, total_layers, layer: nn.Sequential(nn.Dropout(self.nn_dropout),nn.BatchNorm1d(layer.module.out_features), nn.LayerNorm(layer.module.out_features))
140
+ elif nn_layer_norm and nn_layer_dropout:
141
+ post_layer_fct = lambda layer_ix, total_layers, layer: nn.Sequential(nn.Dropout(self.nn_dropout), nn.LayerNorm(layer.module.out_features))
142
+ elif nn_batch_norm and nn_layer_dropout:
143
+ post_layer_fct = lambda layer_ix, total_layers, layer: nn.Sequential(nn.Dropout(self.nn_dropout), nn.BatchNorm1d(layer.module.out_features))
144
+ elif nn_layer_norm and nn_batch_norm:
145
+ post_layer_fct = lambda layer_ix, total_layers, layer: nn.Sequential(nn.BatchNorm1d(layer.module.out_features), nn.LayerNorm(layer.module.out_features))
146
+ elif nn_layer_norm:
147
+ post_layer_fct = lambda layer_ix, total_layers, layer: nn.LayerNorm(layer.module.out_features)
148
+ elif nn_batch_norm:
149
+ post_layer_fct = lambda layer_ix, total_layers, layer:nn.BatchNorm1d(layer.module.out_features)
150
+ elif nn_layer_dropout:
151
+ post_layer_fct = lambda layer_ix, total_layers, layer: nn.Dropout(self.nn_dropout)
152
+ else:
153
+ post_layer_fct = lambda layer_ix, total_layers, layer: None
154
+
155
+ if na_layer_norm and na_batch_norm and na_layer_dropout:
156
+ post_act_fct = lambda layer_ix, total_layers, layer: nn.Sequential(nn.Dropout(self.nn_dropout),nn.BatchNorm1d(layer.module.out_features), nn.LayerNorm(layer.module.out_features))
157
+ elif na_layer_norm and na_layer_dropout:
158
+ post_act_fct = lambda layer_ix, total_layers, layer: nn.Sequential(nn.Dropout(self.nn_dropout), nn.LayerNorm(layer.module.out_features))
159
+ elif na_batch_norm and na_layer_dropout:
160
+ post_act_fct = lambda layer_ix, total_layers, layer: nn.Sequential(nn.Dropout(self.nn_dropout), nn.BatchNorm1d(layer.module.out_features))
161
+ elif na_layer_norm and na_batch_norm:
162
+ post_act_fct = lambda layer_ix, total_layers, layer: nn.Sequential(nn.BatchNorm1d(layer.module.out_features), nn.LayerNorm(layer.module.out_features))
163
+ elif na_layer_norm:
164
+ post_act_fct = lambda layer_ix, total_layers, layer: nn.LayerNorm(layer.module.out_features)
165
+ elif na_batch_norm:
166
+ post_act_fct = lambda layer_ix, total_layers, layer:nn.BatchNorm1d(layer.module.out_features)
167
+ elif na_layer_dropout:
168
+ post_act_fct = lambda layer_ix, total_layers, layer: nn.Dropout(self.nn_dropout)
169
+ else:
170
+ post_act_fct = lambda layer_ix, total_layers, layer: None
171
+
172
+ if self.hidden_layer_activation == 'relu':
173
+ activate_fct = nn.ReLU
174
+ elif self.hidden_layer_activation == 'softplus':
175
+ activate_fct = nn.Softplus
176
+ elif self.hidden_layer_activation == 'leakyrelu':
177
+ activate_fct = nn.LeakyReLU
178
+ elif self.hidden_layer_activation == 'linear':
179
+ activate_fct = nn.Identity
180
+
181
+ if self.supervised_mode:
182
+ self.encoder_n = MLP(
183
+ [self.input_size] + hidden_sizes + [self.code_size],
184
+ activation=activate_fct,
185
+ output_activation=None,
186
+ post_layer_fct=post_layer_fct,
187
+ post_act_fct=post_act_fct,
188
+ allow_broadcast=self.allow_broadcast,
189
+ use_cuda=self.use_cuda,
190
+ )
191
+ else:
192
+ self.encoder_n = MLP(
193
+ [self.latent_dim] + hidden_sizes + [self.code_size],
194
+ activation=activate_fct,
195
+ output_activation=None,
196
+ post_layer_fct=post_layer_fct,
197
+ post_act_fct=post_act_fct,
198
+ allow_broadcast=self.allow_broadcast,
199
+ use_cuda=self.use_cuda,
200
+ )
201
+
202
+ self.encoder_zn = MLP(
203
+ [self.input_size] + hidden_sizes + [[latent_dim, latent_dim]],
204
+ activation=activate_fct,
205
+ output_activation=[None, Exp],
206
+ post_layer_fct=post_layer_fct,
207
+ post_act_fct=post_act_fct,
208
+ allow_broadcast=self.allow_broadcast,
209
+ use_cuda=self.use_cuda,
210
+ )
211
+
212
+ if self.cell_factor_size>0:
213
+ self.cell_factor_effect = nn.ModuleList()
214
+ for i in np.arange(self.cell_factor_size):
215
+ if self.use_bias[i]:
216
+ if self.turn_off_cell_specific:
217
+ self.cell_factor_effect.append(MLP(
218
+ [1] + self.decoder_hidden_layers + [self.latent_dim],
219
+ activation=activate_fct,
220
+ output_activation=None,
221
+ post_layer_fct=post_layer_fct,
222
+ post_act_fct=post_act_fct,
223
+ allow_broadcast=self.allow_broadcast,
224
+ use_cuda=self.use_cuda,
225
+ )
226
+ )
227
+ else:
228
+ self.cell_factor_effect.append(MLP(
229
+ [self.latent_dim+1] + self.decoder_hidden_layers + [self.latent_dim],
230
+ activation=activate_fct,
231
+ output_activation=None,
232
+ post_layer_fct=post_layer_fct,
233
+ post_act_fct=post_act_fct,
234
+ allow_broadcast=self.allow_broadcast,
235
+ use_cuda=self.use_cuda,
236
+ )
237
+ )
238
+ else:
239
+ if self.turn_off_cell_specific:
240
+ self.cell_factor_effect.append(ZeroBiasMLP(
241
+ [1] + self.decoder_hidden_layers + [self.latent_dim],
242
+ activation=activate_fct,
243
+ output_activation=None,
244
+ post_layer_fct=post_layer_fct,
245
+ post_act_fct=post_act_fct,
246
+ allow_broadcast=self.allow_broadcast,
247
+ use_cuda=self.use_cuda,
248
+ )
249
+ )
250
+ else:
251
+ self.cell_factor_effect.append(ZeroBiasMLP(
252
+ [self.latent_dim+1] + self.decoder_hidden_layers + [self.latent_dim],
253
+ activation=activate_fct,
254
+ output_activation=None,
255
+ post_layer_fct=post_layer_fct,
256
+ post_act_fct=post_act_fct,
257
+ allow_broadcast=self.allow_broadcast,
258
+ use_cuda=self.use_cuda,
259
+ )
260
+ )
261
+
262
+ self.decoder_log_mu = MLP(
263
+ [self.latent_dim] + self.decoder_hidden_layers + [self.input_size],
264
+ activation=activate_fct,
265
+ output_activation=None,
266
+ post_layer_fct=post_layer_fct,
267
+ post_act_fct=post_act_fct,
268
+ allow_broadcast=self.allow_broadcast,
269
+ use_cuda=self.use_cuda,
270
+ )
271
+
272
+ if self.latent_dist == 'studentt':
273
+ self.codebook = MLP(
274
+ [self.code_size] + hidden_sizes + [[latent_dim,latent_dim]],
275
+ activation=activate_fct,
276
+ output_activation=[Exp,None],
277
+ post_layer_fct=post_layer_fct,
278
+ post_act_fct=post_act_fct,
279
+ allow_broadcast=self.allow_broadcast,
280
+ use_cuda=self.use_cuda,
281
+ )
282
+ else:
283
+ self.codebook = MLP(
284
+ [self.code_size] + hidden_sizes + [latent_dim],
285
+ activation=activate_fct,
286
+ output_activation=None,
287
+ post_layer_fct=post_layer_fct,
288
+ post_act_fct=post_act_fct,
289
+ allow_broadcast=self.allow_broadcast,
290
+ use_cuda=self.use_cuda,
291
+ )
292
+
293
+ if self.use_cuda:
294
+ self.cuda()
295
+
296
+ def get_device(self):
297
+ return next(self.parameters()).device
298
+
299
+ def cutoff(self, xs, thresh=None):
300
+ eps = torch.finfo(xs.dtype).eps
301
+
302
+ if not thresh is None:
303
+ if eps < thresh:
304
+ eps = thresh
305
+
306
+ xs = xs.clamp(min=eps)
307
+
308
+ if torch.any(torch.isnan(xs)):
309
+ xs[torch.isnan(xs)] = eps
310
+
311
+ return xs
312
+
313
+ def softmax(self, xs):
314
+ #xs = SoftmaxTransform()(xs)
315
+ xs = dist.Multinomial(total_count=1, logits=xs).mean
316
+ return xs
317
+
318
+ def sigmoid(self, xs):
319
+ #sigm_enc = nn.Sigmoid()
320
+ #xs = sigm_enc(xs)
321
+ #xs = clamp_probs(xs)
322
+ xs = dist.Bernoulli(logits=xs).mean
323
+ return xs
324
+
325
+ def softmax_logit(self, xs):
326
+ eps = torch.finfo(xs.dtype).eps
327
+ xs = self.softmax(xs)
328
+ xs = torch.logit(xs, eps=eps)
329
+ return xs
330
+
331
+ def logit(self, xs):
332
+ eps = torch.finfo(xs.dtype).eps
333
+ xs = torch.logit(xs, eps=eps)
334
+ return xs
335
+
336
+ def dirimulti_param(self, xs):
337
+ xs = self.dirimulti_mass * self.sigmoid(xs)
338
+ return xs
339
+
340
+ def multi_param(self, xs):
341
+ xs = self.softmax(xs)
342
+ return xs
343
+
344
+ def model1(self, xs):
345
+ pyro.module('DensityFlowLinear', self)
346
+
347
+ eps = torch.finfo(xs.dtype).eps
348
+ batch_size = xs.size(0)
349
+ self.options = dict(dtype=xs.dtype, device=xs.device)
350
+
351
+ if self.loss_func=='negbinomial':
352
+ dispersion = pyro.param("dispersion", self.dispersion *
353
+ xs.new_ones(self.input_size), constraint=constraints.positive)
354
+
355
+ if self.use_zeroinflate:
356
+ gate_logits = pyro.param("dropout_rate", xs.new_zeros(self.input_size))
357
+
358
+ acs_scale = pyro.param("codebook_scale", xs.new_ones(self.latent_dim), constraint=constraints.positive)
359
+
360
+ I = torch.eye(self.code_size)
361
+ if self.latent_dist=='studentt':
362
+ acs_dof,acs_loc = self.codebook(I)
363
+ else:
364
+ acs_loc = self.codebook(I)
365
+
366
+ with pyro.plate('data'):
367
+ prior = torch.zeros(batch_size, self.code_size, **self.options)
368
+ ns = pyro.sample('n', dist.OneHotCategorical(logits=prior))
369
+
370
+ zn_loc = torch.matmul(ns,acs_loc)
371
+ #zn_scale = torch.matmul(ns,acs_scale)
372
+ zn_scale = acs_scale
373
+
374
+ if self.latent_dist == 'studentt':
375
+ prior_dof = torch.matmul(ns,acs_dof)
376
+ zns = pyro.sample('zn', dist.StudentT(df=prior_dof, loc=zn_loc, scale=zn_scale).to_event(1))
377
+ elif self.latent_dist == 'laplacian':
378
+ zns = pyro.sample('zn', dist.Laplace(zn_loc, zn_scale).to_event(1))
379
+ elif self.latent_dist == 'cauchy':
380
+ zns = pyro.sample('zn', dist.Cauchy(zn_loc, zn_scale).to_event(1))
381
+ elif self.latent_dist == 'normal':
382
+ zns = pyro.sample('zn', dist.Normal(zn_loc, zn_scale).to_event(1))
383
+ elif self.latent_dist == 'gumbel':
384
+ zns = pyro.sample('zn', dist.Gumbel(zn_loc, zn_scale).to_event(1))
385
+
386
+ zs = zns
387
+ log_mu = self.decoder_log_mu(zs)
388
+ if self.loss_func in ['bernoulli']:
389
+ log_theta = log_mu
390
+ elif self.loss_func in ['negbinomial']:
391
+ mu = log_mu.exp()
392
+ else:
393
+ rate = log_mu.exp()
394
+ theta = dist.DirichletMultinomial(total_count=1, concentration=rate).mean
395
+ if self.loss_func == 'poisson':
396
+ rate = theta * torch.sum(xs, dim=1, keepdim=True)
397
+
398
+ if self.loss_func == 'negbinomial':
399
+ logits = (mu.log()-dispersion.log()).clamp(min=-15, max=15)
400
+ if self.use_zeroinflate:
401
+ pyro.sample('x', dist.ZeroInflatedDistribution(dist.NegativeBinomial(total_count=dispersion,
402
+ logits=logits),gate_logits=gate_logits).to_event(1), obs=xs)
403
+ else:
404
+ pyro.sample('x', dist.NegativeBinomial(total_count=dispersion, logits=logits).to_event(1), obs=xs)
405
+ elif self.loss_func == 'poisson':
406
+ if self.use_zeroinflate:
407
+ pyro.sample('x', dist.ZeroInflatedDistribution(dist.Poisson(rate=rate),gate_logits=gate_logits).to_event(1), obs=xs.round())
408
+ else:
409
+ pyro.sample('x', dist.Poisson(rate=rate).to_event(1), obs=xs.round())
410
+ elif self.loss_func == 'multinomial':
411
+ pyro.sample('x', dist.Multinomial(total_count=int(1e8), probs=theta), obs=xs)
412
+ elif self.loss_func == 'bernoulli':
413
+ if self.use_zeroinflate:
414
+ pyro.sample('x', dist.ZeroInflatedDistribution(dist.Bernoulli(logits=log_theta),gate_logits=gate_logits).to_event(1), obs=xs)
415
+ else:
416
+ pyro.sample('x', dist.Bernoulli(logits=log_theta).to_event(1), obs=xs)
417
+
418
+ def guide1(self, xs):
419
+ with pyro.plate('data'):
420
+ #zn_loc, zn_scale = self.encoder_zn(xs)
421
+ zn_loc, zn_scale = self._get_basal_embedding(xs)
422
+ zns = pyro.sample('zn', dist.Normal(zn_loc, zn_scale).to_event(1))
423
+
424
+ alpha = self.encoder_n(zns)
425
+ ns = pyro.sample('n', dist.OneHotCategorical(logits=alpha))
426
+
427
+ def model2(self, xs, us=None):
428
+ pyro.module('DensityFlowLinear', self)
429
+
430
+ eps = torch.finfo(xs.dtype).eps
431
+ batch_size = xs.size(0)
432
+ self.options = dict(dtype=xs.dtype, device=xs.device)
433
+
434
+ if self.loss_func=='negbinomial':
435
+ dispersion = pyro.param("dispersion", self.dispersion *
436
+ xs.new_ones(self.input_size), constraint=constraints.positive)
437
+
438
+ if self.use_zeroinflate:
439
+ gate_logits = pyro.param("dropout_rate", xs.new_zeros(self.input_size))
440
+
441
+ acs_scale = pyro.param("codebook_scale", xs.new_ones(self.latent_dim), constraint=constraints.positive)
442
+
443
+ I = torch.eye(self.code_size)
444
+ if self.latent_dist=='studentt':
445
+ acs_dof,acs_loc = self.codebook(I)
446
+ else:
447
+ acs_loc = self.codebook(I)
448
+
449
+ with pyro.plate('data'):
450
+ prior = torch.zeros(batch_size, self.code_size, **self.options)
451
+ ns = pyro.sample('n', dist.OneHotCategorical(logits=prior))
452
+
453
+ zn_loc = torch.matmul(ns,acs_loc)
454
+ #zn_scale = torch.matmul(ns,acs_scale)
455
+ zn_scale = acs_scale
456
+
457
+ if self.latent_dist == 'studentt':
458
+ prior_dof = torch.matmul(ns,acs_dof)
459
+ zns = pyro.sample('zn', dist.StudentT(df=prior_dof, loc=zn_loc, scale=zn_scale).to_event(1))
460
+ elif self.latent_dist == 'laplacian':
461
+ zns = pyro.sample('zn', dist.Laplace(zn_loc, zn_scale).to_event(1))
462
+ elif self.latent_dist == 'cauchy':
463
+ zns = pyro.sample('zn', dist.Cauchy(zn_loc, zn_scale).to_event(1))
464
+ elif self.latent_dist == 'normal':
465
+ zns = pyro.sample('zn', dist.Normal(zn_loc, zn_scale).to_event(1))
466
+ elif self.latent_dist == 'gumbel':
467
+ zns = pyro.sample('zn', dist.Gumbel(zn_loc, zn_scale).to_event(1))
468
+
469
+ '''if self.cell_factor_size>0:
470
+ zus = self._total_shifts(zns, us)
471
+ zs = zns+zus
472
+ else:
473
+ zs = zns'''
474
+
475
+ zs = zns
476
+ log_mu = self.decoder_log_mu(zs)
477
+ for i in np.arange(self.cell_factor_size):
478
+ zus = self._cell_shift(zs, i, us[:,i].reshape(-1,1))
479
+ log_mu += self.decoder_log_mu(zus)
480
+
481
+ if self.loss_func in ['bernoulli']:
482
+ log_theta = log_mu
483
+ elif self.loss_func in ['negbinomial']:
484
+ mu = log_mu.exp()
485
+ else:
486
+ rate = log_mu.exp()
487
+ theta = dist.DirichletMultinomial(total_count=1, concentration=rate).mean
488
+ if self.loss_func == 'poisson':
489
+ rate = theta * torch.sum(xs, dim=1, keepdim=True)
490
+
491
+ if self.loss_func == 'negbinomial':
492
+ logits = (mu.log()-dispersion.log()).clamp(min=-15, max=15)
493
+ if self.use_zeroinflate:
494
+ pyro.sample('x', dist.ZeroInflatedDistribution(dist.NegativeBinomial(total_count=dispersion,
495
+ logits=logits),gate_logits=gate_logits).to_event(1), obs=xs)
496
+ else:
497
+ pyro.sample('x', dist.NegativeBinomial(total_count=dispersion,
498
+ logits=logits).to_event(1), obs=xs)
499
+ elif self.loss_func == 'poisson':
500
+ if self.use_zeroinflate:
501
+ pyro.sample('x', dist.ZeroInflatedDistribution(dist.Poisson(rate=rate),gate_logits=gate_logits).to_event(1), obs=xs.round())
502
+ else:
503
+ pyro.sample('x', dist.Poisson(rate=rate).to_event(1), obs=xs.round())
504
+ elif self.loss_func == 'multinomial':
505
+ pyro.sample('x', dist.Multinomial(total_count=int(1e8), probs=theta), obs=xs)
506
+ elif self.loss_func == 'bernoulli':
507
+ if self.use_zeroinflate:
508
+ pyro.sample('x', dist.ZeroInflatedDistribution(dist.Bernoulli(logits=log_theta),gate_logits=gate_logits).to_event(1), obs=xs)
509
+ else:
510
+ pyro.sample('x', dist.Bernoulli(logits=log_theta).to_event(1), obs=xs)
511
+
512
+ def guide2(self, xs, us=None):
513
+ with pyro.plate('data'):
514
+ #zn_loc, zn_scale = self.encoder_zn(xs)
515
+ zn_loc, zn_scale = self._get_basal_embedding(xs)
516
+ zns = pyro.sample('zn', dist.Normal(zn_loc, zn_scale).to_event(1))
517
+
518
+ alpha = self.encoder_n(zns)
519
+ ns = pyro.sample('n', dist.OneHotCategorical(logits=alpha))
520
+
521
+ def model3(self, xs, ys, embeds=None):
522
+ pyro.module('DensityFlowLinear', self)
523
+
524
+ eps = torch.finfo(xs.dtype).eps
525
+ batch_size = xs.size(0)
526
+ self.options = dict(dtype=xs.dtype, device=xs.device)
527
+
528
+ if self.loss_func=='negbinomial':
529
+ dispersion = pyro.param("dispersion", self.dispersion *
530
+ xs.new_ones(self.input_size), constraint=constraints.positive)
531
+
532
+ if self.use_zeroinflate:
533
+ gate_logits = pyro.param("dropout_rate", xs.new_zeros(self.input_size))
534
+
535
+ acs_scale = pyro.param("codebook_scale", xs.new_ones(self.latent_dim), constraint=constraints.positive)
536
+
537
+ I = torch.eye(self.code_size)
538
+ if self.latent_dist=='studentt':
539
+ acs_dof,acs_loc = self.codebook(I)
540
+ else:
541
+ acs_loc = self.codebook(I)
542
+
543
+ with pyro.plate('data'):
544
+ #prior = torch.zeros(batch_size, self.code_size, **self.options)
545
+ prior = self.encoder_n(xs)
546
+ ns = pyro.sample('n', dist.OneHotCategorical(logits=prior), obs=ys)
547
+
548
+ zn_loc = torch.matmul(ns,acs_loc)
549
+ #prior_scale = torch.matmul(ns,acs_scale)
550
+ zn_scale = acs_scale
551
+
552
+ if self.latent_dist=='studentt':
553
+ prior_dof = torch.matmul(ns,acs_dof)
554
+ if embeds is None:
555
+ zns = pyro.sample('zn', dist.StudentT(df=prior_dof, loc=zn_loc, scale=zn_scale).to_event(1))
556
+ else:
557
+ zns = pyro.sample('zn', dist.StudentT(df=prior_dof, loc=zn_loc, scale=zn_scale).to_event(1), obs=embeds)
558
+ elif self.latent_dist=='laplacian':
559
+ if embeds is None:
560
+ zns = pyro.sample('zn', dist.Laplace(zn_loc, zn_scale).to_event(1))
561
+ else:
562
+ zns = pyro.sample('zn', dist.Laplace(zn_loc, zn_scale).to_event(1), obs=embeds)
563
+ elif self.latent_dist=='cauchy':
564
+ if embeds is None:
565
+ zns = pyro.sample('zn', dist.Cauchy(zn_loc, zn_scale).to_event(1))
566
+ else:
567
+ zns = pyro.sample('zn', dist.Cauchy(zn_loc, zn_scale).to_event(1), obs=embeds)
568
+ elif self.latent_dist=='normal':
569
+ if embeds is None:
570
+ zns = pyro.sample('zn', dist.Normal(zn_loc, zn_scale).to_event(1))
571
+ else:
572
+ zns = pyro.sample('zn', dist.Normal(zn_loc, zn_scale).to_event(1), obs=embeds)
573
+ elif self.z_dist == 'gumbel':
574
+ if embeds is None:
575
+ zns = pyro.sample('zn', dist.Gumbel(zn_loc, zn_scale).to_event(1))
576
+ else:
577
+ zns = pyro.sample('zn', dist.Gumbel(zn_loc, zn_scale).to_event(1), obs=embeds)
578
+
579
+ zs = zns
580
+
581
+ log_mu = self.decoder_log_mu(zs)
582
+ if self.loss_func in ['bernoulli']:
583
+ log_theta = log_mu
584
+ elif self.loss_func in ['negbinomial']:
585
+ mu = log_mu.exp()
586
+ else:
587
+ rate = log_mu.exp()
588
+ theta = dist.DirichletMultinomial(total_count=1, concentration=rate).mean
589
+ if self.loss_func == 'poisson':
590
+ rate = theta * torch.sum(xs, dim=1, keepdim=True)
591
+
592
+ if self.loss_func == 'negbinomial':
593
+ logits = (mu.log()-dispersion.log()).clamp(min=-15, max=15)
594
+ if self.use_zeroinflate:
595
+ pyro.sample('x', dist.ZeroInflatedDistribution(dist.NegativeBinomial(total_count=dispersion,
596
+ logits=logits),gate_logits=gate_logits).to_event(1), obs=xs)
597
+ else:
598
+ pyro.sample('x', dist.NegativeBinomial(total_count=dispersion, logits=logits).to_event(1), obs=xs)
599
+ elif self.loss_func == 'poisson':
600
+ if self.use_zeroinflate:
601
+ pyro.sample('x', dist.ZeroInflatedDistribution(dist.Poisson(rate=rate),gate_logits=gate_logits).to_event(1), obs=xs.round())
602
+ else:
603
+ pyro.sample('x', dist.Poisson(rate=rate).to_event(1), obs=xs.round())
604
+ elif self.loss_func == 'multinomial':
605
+ pyro.sample('x', dist.Multinomial(total_count=int(1e8), probs=theta), obs=xs)
606
+ elif self.loss_func == 'bernoulli':
607
+ if self.use_zeroinflate:
608
+ pyro.sample('x', dist.ZeroInflatedDistribution(dist.Bernoulli(logits=log_theta),gate_logits=gate_logits).to_event(1), obs=xs)
609
+ else:
610
+ pyro.sample('x', dist.Bernoulli(logits=log_theta).to_event(1), obs=xs)
611
+
612
+ def guide3(self, xs, ys, embeds=None):
613
+ with pyro.plate('data'):
614
+ if embeds is None:
615
+ #zn_loc, zn_scale = self.encoder_zn(xs)
616
+ zn_loc, zn_scale = self._get_basal_embedding(xs)
617
+ zns = pyro.sample('zn', dist.Normal(zn_loc, zn_scale).to_event(1))
618
+ else:
619
+ zns = embeds
620
+
621
+ def model4(self, xs, us, ys, embeds=None):
622
+ pyro.module('DensityFlowLinear', self)
623
+
624
+ eps = torch.finfo(xs.dtype).eps
625
+ batch_size = xs.size(0)
626
+ self.options = dict(dtype=xs.dtype, device=xs.device)
627
+
628
+ if self.loss_func=='negbinomial':
629
+ dispersion = pyro.param("dispersion", self.dispersion *
630
+ xs.new_ones(self.input_size), constraint=constraints.positive)
631
+
632
+ if self.use_zeroinflate:
633
+ gate_logits = pyro.param("dropout_rate", xs.new_zeros(self.input_size))
634
+
635
+ acs_scale = pyro.param("codebook_scale", xs.new_ones(self.latent_dim), constraint=constraints.positive)
636
+
637
+ I = torch.eye(self.code_size)
638
+ if self.latent_dist=='studentt':
639
+ acs_dof,acs_loc = self.codebook(I)
640
+ else:
641
+ acs_loc = self.codebook(I)
642
+
643
+ with pyro.plate('data'):
644
+ #prior = torch.zeros(batch_size, self.code_size, **self.options)
645
+ prior = self.encoder_n(xs)
646
+ ns = pyro.sample('n', dist.OneHotCategorical(logits=prior), obs=ys)
647
+
648
+ zn_loc = torch.matmul(ns,acs_loc)
649
+ #prior_scale = torch.matmul(ns,acs_scale)
650
+ zn_scale = acs_scale
651
+
652
+ if self.latent_dist=='studentt':
653
+ prior_dof = torch.matmul(ns,acs_dof)
654
+ if embeds is None:
655
+ zns = pyro.sample('zn', dist.StudentT(df=prior_dof, loc=zn_loc, scale=zn_scale).to_event(1))
656
+ else:
657
+ zns = pyro.sample('zn', dist.StudentT(df=prior_dof, loc=zn_loc, scale=zn_scale).to_event(1), obs=embeds)
658
+ elif self.latent_dist=='laplacian':
659
+ if embeds is None:
660
+ zns = pyro.sample('zn', dist.Laplace(zn_loc, zn_scale).to_event(1))
661
+ else:
662
+ zns = pyro.sample('zn', dist.Laplace(zn_loc, zn_scale).to_event(1), obs=embeds)
663
+ elif self.latent_dist=='cauchy':
664
+ if embeds is None:
665
+ zns = pyro.sample('zn', dist.Cauchy(zn_loc, zn_scale).to_event(1))
666
+ else:
667
+ zns = pyro.sample('zn', dist.Cauchy(zn_loc, zn_scale).to_event(1), obs=embeds)
668
+ elif self.latent_dist=='normal':
669
+ if embeds is None:
670
+ zns = pyro.sample('zn', dist.Normal(zn_loc, zn_scale).to_event(1))
671
+ else:
672
+ zns = pyro.sample('zn', dist.Normal(zn_loc, zn_scale).to_event(1), obs=embeds)
673
+ elif self.z_dist == 'gumbel':
674
+ if embeds is None:
675
+ zns = pyro.sample('zn', dist.Gumbel(zn_loc, zn_scale).to_event(1))
676
+ else:
677
+ zns = pyro.sample('zn', dist.Gumbel(zn_loc, zn_scale).to_event(1), obs=embeds)
678
+
679
+ '''if self.cell_factor_size>0:
680
+ zus = self._total_shifts(zns, us)
681
+ zs = zns+zus
682
+ else:
683
+ zs = zns'''
684
+
685
+ zs = zns
686
+ log_mu = self.decoder_log_mu(zs)
687
+ for i in np.arange(self.cell_factor_size):
688
+ zus = self._cell_shift(zs, i, us[:,i].reshape(-1,1))
689
+ log_mu += self.decoder_log_mu(zus)
690
+
691
+ if self.loss_func in ['bernoulli']:
692
+ log_theta = log_mu
693
+ elif self.loss_func in ['negbinomial']:
694
+ mu = log_mu.exp()
695
+ else:
696
+ rate = log_mu.exp()
697
+ theta = dist.DirichletMultinomial(total_count=1, concentration=rate).mean
698
+ if self.loss_func == 'poisson':
699
+ rate = theta * torch.sum(xs, dim=1, keepdim=True)
700
+
701
+ if self.loss_func == 'negbinomial':
702
+ logits = (mu.log()-dispersion.log()).clamp(min=-15, max=15)
703
+ if self.use_zeroinflate:
704
+ pyro.sample('x', dist.ZeroInflatedDistribution(dist.NegativeBinomial(total_count=dispersion, logits=logits),gate_logits=gate_logits).to_event(1), obs=xs)
705
+ else:
706
+ pyro.sample('x', dist.NegativeBinomial(total_count=dispersion, logits=logits).to_event(1), obs=xs)
707
+ elif self.loss_func == 'poisson':
708
+ if self.use_zeroinflate:
709
+ pyro.sample('x', dist.ZeroInflatedDistribution(dist.Poisson(rate=rate),gate_logits=gate_logits).to_event(1), obs=xs.round())
710
+ else:
711
+ pyro.sample('x', dist.Poisson(rate=rate).to_event(1), obs=xs.round())
712
+ elif self.loss_func == 'multinomial':
713
+ pyro.sample('x', dist.Multinomial(total_count=int(1e8), probs=theta), obs=xs)
714
+ elif self.loss_func == 'bernoulli':
715
+ if self.use_zeroinflate:
716
+ pyro.sample('x', dist.ZeroInflatedDistribution(dist.Bernoulli(logits=log_theta),gate_logits=gate_logits).to_event(1), obs=xs)
717
+ else:
718
+ pyro.sample('x', dist.Bernoulli(logits=log_theta).to_event(1), obs=xs)
719
+
720
+ def guide4(self, xs, us, ys, embeds=None):
721
+ with pyro.plate('data'):
722
+ if embeds is None:
723
+ #zn_loc, zn_scale = self.encoder_zn(xs)
724
+ zn_loc, zn_scale = self._get_basal_embedding(xs)
725
+ zns = pyro.sample('zn', dist.Normal(zn_loc, zn_scale).to_event(1))
726
+ else:
727
+ zns = embeds
728
+
729
+ def _total_shifts(self, zns, us):
730
+ zus = None
731
+ for i in np.arange(self.cell_factor_size):
732
+ if i==0:
733
+ #if self.turn_off_cell_specific:
734
+ # zus = self.cell_factor_effect[i](us[:,i].reshape(-1,1))
735
+ #else:
736
+ # zus = self.cell_factor_effect[i]([zns,us[:,i].reshape(-1,1)])
737
+ zus = self._cell_shift(zns, i, us[:,i].reshape(-1,1))
738
+ else:
739
+ #if self.turn_off_cell_specific:
740
+ # zus = zus + self.cell_factor_effect[i](us[:,i].reshape(-1,1))
741
+ #else:
742
+ # zus = zus + self.cell_factor_effect[i]([zns,us[:,i].reshape(-1,1)])
743
+ zus = zus + self._cell_shift(zns, i, us[:,i].reshape(-1,1))
744
+ return zus
745
+
746
+ def _get_codebook_identity(self):
747
+ return torch.eye(self.code_size, **self.options)
748
+
749
+ def _get_codebook(self):
750
+ I = torch.eye(self.code_size, **self.options)
751
+ if self.latent_dist=='studentt':
752
+ _,cb = self.codebook(I)
753
+ else:
754
+ cb = self.codebook(I)
755
+ return cb
756
+
757
+ def get_codebook(self):
758
+ """
759
+ Return the mean part of metacell codebook
760
+ """
761
+ cb = self._get_codebook()
762
+ cb = tensor_to_numpy(cb)
763
+ return cb
764
+
765
+ def _get_basal_embedding(self, xs):
766
+ loc, scale = self.encoder_zn(xs)
767
+ return loc, scale
768
+
769
+ def get_basal_embedding(self,
770
+ xs,
771
+ batch_size: int = 1024):
772
+ """
773
+ Return cells' basal latent representations
774
+
775
+ Parameters
776
+ ----------
777
+ xs
778
+ Single-cell expression matrix. It should be a Numpy array or a Pytorch Tensor.
779
+ batch_size
780
+ Size of batch processing.
781
+ use_decoder
782
+ If toggled on, the latent representations will be reconstructed from the metacell codebook
783
+ soft_assign
784
+ If toggled on, the assignments of cells will use probabilistic values.
785
+ """
786
+ xs = self.preprocess(xs)
787
+ xs = convert_to_tensor(xs, device=self.get_device())
788
+ dataset = CustomDataset(xs)
789
+ dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False)
790
+
791
+ Z = []
792
+ with tqdm(total=len(dataloader), desc='', unit='batch') as pbar:
793
+ for X_batch, _ in dataloader:
794
+ zns,_ = self._get_basal_embedding(X_batch)
795
+ Z.append(tensor_to_numpy(zns))
796
+ pbar.update(1)
797
+
798
+ Z = np.concatenate(Z)
799
+ return Z
800
+
801
+ def _code(self, xs):
802
+ if self.supervised_mode:
803
+ alpha = self.encoder_n(xs)
804
+ else:
805
+ #zns,_ = self.encoder_zn(xs)
806
+ zns,_ = self._get_basal_embedding(xs)
807
+ alpha = self.encoder_n(zns)
808
+ return alpha
809
+
810
+ def code(self, xs, batch_size=1024):
811
+ xs = self.preprocess(xs)
812
+ xs = convert_to_tensor(xs, device=self.get_device())
813
+ dataset = CustomDataset(xs)
814
+ dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False)
815
+
816
+ A = []
817
+ with tqdm(total=len(dataloader), desc='', unit='batch') as pbar:
818
+ for X_batch, _ in dataloader:
819
+ a = self._code(X_batch)
820
+ A.append(tensor_to_numpy(a))
821
+ pbar.update(1)
822
+
823
+ A = np.concatenate(A)
824
+ return A
825
+
826
+ def _soft_assignments(self, xs):
827
+ alpha = self._code(xs)
828
+ alpha = self.softmax(alpha)
829
+ return alpha
830
+
831
+ def soft_assignments(self, xs, batch_size=1024):
832
+ """
833
+ Map cells to metacells and return the probabilistic values of metacell assignments
834
+ """
835
+ xs = self.preprocess(xs)
836
+ xs = convert_to_tensor(xs, device=self.get_device())
837
+ dataset = CustomDataset(xs)
838
+ dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False)
839
+
840
+ A = []
841
+ with tqdm(total=len(dataloader), desc='', unit='batch') as pbar:
842
+ for X_batch, _ in dataloader:
843
+ a = self._soft_assignments(X_batch)
844
+ A.append(tensor_to_numpy(a))
845
+ pbar.update(1)
846
+
847
+ A = np.concatenate(A)
848
+ return A
849
+
850
+ def _hard_assignments(self, xs):
851
+ alpha = self._code(xs)
852
+ res, ind = torch.topk(alpha, 1)
853
+ ns = torch.zeros_like(alpha).scatter_(1, ind, 1.0)
854
+ return ns
855
+
856
+ def hard_assignments(self, xs, batch_size=1024):
857
+ """
858
+ Map cells to metacells and return the assigned metacell identities.
859
+ """
860
+ xs = self.preprocess(xs)
861
+ xs = convert_to_tensor(xs, device=self.get_device())
862
+ dataset = CustomDataset(xs)
863
+ dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False)
864
+
865
+ A = []
866
+ with tqdm(total=len(dataloader), desc='', unit='batch') as pbar:
867
+ for X_batch, _ in dataloader:
868
+ a = self._hard_assignments(X_batch)
869
+ A.append(tensor_to_numpy(a))
870
+ pbar.update(1)
871
+
872
+ A = np.concatenate(A)
873
+ return A
874
+
875
+ def predict(self, xs, us, perturbs_predict:list, perturbs_reference:list, library_sizes=None):
876
+ perturbs_reference = np.array(perturbs_reference)
877
+
878
+ # basal embedding
879
+ zs = self.get_basal_embedding(xs)
880
+ log_mu = self.get_log_mu(zs)
881
+
882
+ for pert in perturbs_predict:
883
+ pert_idx = int(np.where(perturbs_reference==pert)[0])
884
+ us_i = us[:,pert_idx].reshape(-1,1)
885
+
886
+ # factor effect of xs
887
+ dzs0 = self.get_cell_shift(zs, perturb_idx=pert_idx, perturb_us=us_i)
888
+
889
+ # perturbation effect
890
+ ps = np.ones_like(us_i)
891
+ if np.sum(np.abs(ps-us_i))>=1:
892
+ dzs = self.get_cell_shift(zs, perturb_idx=pert_idx, perturb_us=ps)
893
+ delta = dzs0 + dzs
894
+ else:
895
+ delta = dzs0
896
+
897
+ log_mu = log_mu + self.get_log_mu(delta)
898
+
899
+ if library_sizes is None:
900
+ library_sizes = np.sum(xs, axis=1, keepdims=True)
901
+ elif type(library_sizes) == list:
902
+ library_sizes = np.array(library_sizes)
903
+ library_sizes = library_sizes.reshape(-1,1)
904
+ elif len(library_sizes.shape)==1:
905
+ library_sizes = library_sizes.reshape(-1,1)
906
+
907
+ counts = self.get_counts(log_mu, library_sizes=library_sizes)
908
+
909
+ return counts, log_mu
910
+
911
+ def _cell_shift(self, zs, perturb_idx, perturb):
912
+ #zns,_ = self.encoder_zn(xs)
913
+ #zns,_ = self._get_basal_embedding(xs)
914
+ zns = zs
915
+ if perturb.ndim==2:
916
+ if self.turn_off_cell_specific:
917
+ ms = self.cell_factor_effect[perturb_idx](perturb)
918
+ else:
919
+ ms = self.cell_factor_effect[perturb_idx]([zns, perturb])
920
+ else:
921
+ if self.turn_off_cell_specific:
922
+ ms = self.cell_factor_effect[perturb_idx](perturb.reshape(-1,1))
923
+ else:
924
+ ms = self.cell_factor_effect[perturb_idx]([zns, perturb.reshape(-1,1)])
925
+
926
+ return ms
927
+
928
+ def get_cell_shift(self,
929
+ zs,
930
+ perturb_idx,
931
+ perturb_us,
932
+ batch_size: int = 1024):
933
+ """
934
+ Return cells' changes in the latent space induced by specific perturbation of a factor
935
+
936
+ """
937
+ #xs = self.preprocess(xs)
938
+ zs = convert_to_tensor(zs, device=self.get_device())
939
+ ps = convert_to_tensor(perturb_us, device=self.get_device())
940
+ dataset = CustomDataset2(zs,ps)
941
+ dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False)
942
+
943
+ Z = []
944
+ with tqdm(total=len(dataloader), desc='', unit='batch') as pbar:
945
+ for Z_batch, P_batch, _ in dataloader:
946
+ zns = self._cell_shift(Z_batch, perturb_idx, P_batch)
947
+ Z.append(tensor_to_numpy(zns))
948
+ pbar.update(1)
949
+
950
+ Z = np.concatenate(Z)
951
+ return Z
952
+
953
+ def _log_mu(self, zs):
954
+ return self.decoder_log_mu(zs)
955
+
956
+ def get_log_mu(self, zs, batch_size: int = 1024):
957
+ """
958
+ Return cells' changes in the feature space induced by specific perturbation of a factor
959
+
960
+ """
961
+ zs = convert_to_tensor(zs, device=self.get_device())
962
+ dataset = CustomDataset(zs)
963
+ dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False)
964
+
965
+ R = []
966
+ with tqdm(total=len(dataloader), desc='', unit='batch') as pbar:
967
+ for Z_batch, _ in dataloader:
968
+ r = self._log_mu(Z_batch)
969
+ R.append(tensor_to_numpy(r))
970
+ pbar.update(1)
971
+
972
+ R = np.concatenate(R)
973
+ return R
974
+
975
+ def _count(self, log_mu, library_size=None):
976
+ if self.loss_func == 'bernoulli':
977
+ #counts = self.sigmoid(concentrate)
978
+ counts = dist.Bernoulli(logits=log_mu).to_event(1).mean
979
+ elif self.loss_func == 'multinomial':
980
+ theta = dist.Multinomial(total_count=int(1e8), logits=log_mu).mean
981
+ counts = theta * library_size
982
+ else:
983
+ rate = log_mu.exp()
984
+ theta = dist.DirichletMultinomial(total_count=1, concentration=rate).mean
985
+ counts = theta * library_size
986
+ return counts
987
+
988
+ def get_counts(self, log_mu,
989
+ library_sizes,
990
+ batch_size: int = 1024):
991
+
992
+ log_mu = convert_to_tensor(log_mu, device=self.get_device())
993
+
994
+ if type(library_sizes) == list:
995
+ library_sizes = np.array(library_sizes).reshape(-1,1)
996
+ elif len(library_sizes.shape)==1:
997
+ library_sizes = library_sizes.reshape(-1,1)
998
+ ls = convert_to_tensor(library_sizes, device=self.get_device())
999
+
1000
+ dataset = CustomDataset2(log_mu,ls)
1001
+ dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False)
1002
+
1003
+ E = []
1004
+ with tqdm(total=len(dataloader), desc='', unit='batch') as pbar:
1005
+ for Mu_batch, L_batch, _ in dataloader:
1006
+ counts = self._count(Mu_batch, L_batch)
1007
+ E.append(tensor_to_numpy(counts))
1008
+ pbar.update(1)
1009
+
1010
+ E = np.concatenate(E)
1011
+ return E
1012
+
1013
+ def preprocess(self, xs, threshold=0):
1014
+ if self.loss_func == 'bernoulli':
1015
+ ad = sc.AnnData(xs)
1016
+ binarize(ad, threshold=threshold)
1017
+ xs = ad.X.copy()
1018
+ else:
1019
+ xs = np.round(xs)
1020
+
1021
+ if sparse.issparse(xs):
1022
+ xs = xs.toarray()
1023
+ return xs
1024
+
1025
+ def fit(self, xs,
1026
+ us = None,
1027
+ ys = None,
1028
+ zs = None,
1029
+ num_epochs: int = 500,
1030
+ learning_rate: float = 0.0001,
1031
+ batch_size: int = 256,
1032
+ algo: Literal['adam','rmsprop','adamw'] = 'adam',
1033
+ beta_1: float = 0.9,
1034
+ weight_decay: float = 0.005,
1035
+ decay_rate: float = 0.9,
1036
+ config_enum: str = 'parallel',
1037
+ threshold: int = 0,
1038
+ use_jax: bool = True):
1039
+ """
1040
+ Train the DensityFlowLinear model.
1041
+
1042
+ Parameters
1043
+ ----------
1044
+ xs
1045
+ Single-cell experssion matrix. It should be a Numpy array or a Pytorch Tensor. Rows are cells and columns are features.
1046
+ us
1047
+ cell-level factor matrix.
1048
+ ys
1049
+ Desired factor matrix. It should be a Numpy array or a Pytorch Tensor. Rows are cells and columns are desired factors.
1050
+ num_epochs
1051
+ Number of training epochs.
1052
+ learning_rate
1053
+ Parameter for training.
1054
+ batch_size
1055
+ Size of batch processing.
1056
+ algo
1057
+ Optimization algorithm.
1058
+ beta_1
1059
+ Parameter for optimization.
1060
+ weight_decay
1061
+ Parameter for optimization.
1062
+ decay_rate
1063
+ Parameter for optimization.
1064
+ use_jax
1065
+ If toggled on, Jax will be used for speeding up. CAUTION: This will raise errors because of unknown reasons when it is called in
1066
+ the Python script or Jupyter notebook. It is OK if it is used when runing DensityFlowLinear in the shell command.
1067
+ """
1068
+ xs = self.preprocess(xs, threshold=threshold)
1069
+ xs = convert_to_tensor(xs, dtype=self.dtype, device=self.get_device())
1070
+ if us is not None:
1071
+ us = convert_to_tensor(us, dtype=self.dtype, device=self.get_device())
1072
+ if ys is not None:
1073
+ ys = convert_to_tensor(ys, dtype=self.dtype, device=self.get_device())
1074
+ if zs is not None:
1075
+ zs = convert_to_tensor(zs, dtype=self.dtype, device=self.get_device())
1076
+
1077
+ dataset = CustomDataset4(xs, us, ys, zs)
1078
+ dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True)
1079
+
1080
+ # setup the optimizer
1081
+ optim_params = {'lr': learning_rate, 'betas': (beta_1, 0.999), 'weight_decay': weight_decay}
1082
+
1083
+ if algo.lower()=='rmsprop':
1084
+ optimizer = torch.optim.RMSprop
1085
+ elif algo.lower()=='adam':
1086
+ optimizer = torch.optim.Adam
1087
+ elif algo.lower() == 'adamw':
1088
+ optimizer = torch.optim.AdamW
1089
+ else:
1090
+ raise ValueError("An optimization algorithm must be specified.")
1091
+ scheduler = ExponentialLR({'optimizer': optimizer, 'optim_args': optim_params, 'gamma': decay_rate})
1092
+
1093
+ pyro.clear_param_store()
1094
+
1095
+ # set up the loss(es) for inference, wrapping the guide in config_enumerate builds the loss as a sum
1096
+ # by enumerating each class label form the sampled discrete categorical distribution in the model
1097
+ Elbo = JitTraceEnum_ELBO if use_jax else TraceEnum_ELBO
1098
+ elbo = Elbo(max_plate_nesting=1, strict_enumeration_warning=False)
1099
+ if us is None:
1100
+ if ys is None:
1101
+ guide = config_enumerate(self.guide1, config_enum, expand=True)
1102
+ loss_basic = SVI(self.model1, guide, scheduler, loss=elbo)
1103
+ else:
1104
+ guide = config_enumerate(self.guide3, config_enum, expand=True)
1105
+ loss_basic = SVI(self.model3, guide, scheduler, loss=elbo)
1106
+ else:
1107
+ if ys is None:
1108
+ guide = config_enumerate(self.guide2, config_enum, expand=True)
1109
+ loss_basic = SVI(self.model2, guide, scheduler, loss=elbo)
1110
+ else:
1111
+ guide = config_enumerate(self.guide4, config_enum, expand=True)
1112
+ loss_basic = SVI(self.model4, guide, scheduler, loss=elbo)
1113
+
1114
+ # build a list of all losses considered
1115
+ losses = [loss_basic]
1116
+ num_losses = len(losses)
1117
+
1118
+ with tqdm(total=num_epochs, desc='Training', unit='epoch') as pbar:
1119
+ for epoch in range(num_epochs):
1120
+ epoch_losses = [0.0] * num_losses
1121
+ for batch_x, batch_u, batch_y, batch_z, _ in dataloader:
1122
+ if us is None:
1123
+ batch_u = None
1124
+ if ys is None:
1125
+ batch_y = None
1126
+ if zs is None:
1127
+ batch_z = None
1128
+
1129
+ for loss_id in range(num_losses):
1130
+ if batch_u is None:
1131
+ if batch_y is None:
1132
+ new_loss = losses[loss_id].step(batch_x)
1133
+ else:
1134
+ new_loss = losses[loss_id].step(batch_x, batch_y, batch_z)
1135
+ else:
1136
+ if batch_y is None:
1137
+ new_loss = losses[loss_id].step(batch_x, batch_u)
1138
+ else:
1139
+ new_loss = losses[loss_id].step(batch_x, batch_u, batch_y, batch_z)
1140
+ epoch_losses[loss_id] += new_loss
1141
+
1142
+ avg_epoch_losses_ = map(lambda v: v / len(dataloader), epoch_losses)
1143
+ avg_epoch_losses = map(lambda v: "{:.4f}".format(v), avg_epoch_losses_)
1144
+
1145
+ # store the loss
1146
+ str_loss = " ".join(map(str, avg_epoch_losses))
1147
+
1148
+ # Update progress bar
1149
+ pbar.set_postfix({'loss': str_loss})
1150
+ pbar.update(1)
1151
+
1152
+ @classmethod
1153
+ def save_model(cls, model, file_path, compression=False):
1154
+ """Save the model to the specified file path."""
1155
+ file_path = os.path.abspath(file_path)
1156
+
1157
+ model.eval()
1158
+ if compression:
1159
+ with gzip.open(file_path, 'wb') as pickle_file:
1160
+ pickle.dump(model, pickle_file)
1161
+ else:
1162
+ with open(file_path, 'wb') as pickle_file:
1163
+ pickle.dump(model, pickle_file)
1164
+
1165
+ print(f'Model saved to {file_path}')
1166
+
1167
+ @classmethod
1168
+ def load_model(cls, file_path):
1169
+ """Load the model from the specified file path and return an instance."""
1170
+ print(f'Model loaded from {file_path}')
1171
+
1172
+ file_path = os.path.abspath(file_path)
1173
+ if file_path.endswith('gz'):
1174
+ with gzip.open(file_path, 'rb') as pickle_file:
1175
+ model = pickle.load(pickle_file)
1176
+ else:
1177
+ with open(file_path, 'rb') as pickle_file:
1178
+ model = pickle.load(pickle_file)
1179
+
1180
+ return model
1181
+
1182
+
1183
+ EXAMPLE_RUN = (
1184
+ "example run: DensityFlowLinear --help"
1185
+ )
1186
+
1187
+ def parse_args():
1188
+ parser = argparse.ArgumentParser(
1189
+ description="DensityFlowLinear\n{}".format(EXAMPLE_RUN))
1190
+
1191
+ parser.add_argument(
1192
+ "--cuda", action="store_true", help="use GPU(s) to speed up training"
1193
+ )
1194
+ parser.add_argument(
1195
+ "--jit", action="store_true", help="use PyTorch jit to speed up training"
1196
+ )
1197
+ parser.add_argument(
1198
+ "-n", "--num-epochs", default=200, type=int, help="number of epochs to run"
1199
+ )
1200
+ parser.add_argument(
1201
+ "-enum",
1202
+ "--enum-discrete",
1203
+ default="parallel",
1204
+ help="parallel, sequential or none. uses parallel enumeration by default",
1205
+ )
1206
+ parser.add_argument(
1207
+ "-data",
1208
+ "--data-file",
1209
+ default=None,
1210
+ type=str,
1211
+ help="the data file",
1212
+ )
1213
+ parser.add_argument(
1214
+ "-cf",
1215
+ "--cell-factor-file",
1216
+ default=None,
1217
+ type=str,
1218
+ help="the file for the record of cell-level factors",
1219
+ )
1220
+ parser.add_argument(
1221
+ "-bs",
1222
+ "--batch-size",
1223
+ default=1000,
1224
+ type=int,
1225
+ help="number of cells to be considered in a batch",
1226
+ )
1227
+ parser.add_argument(
1228
+ "-lr",
1229
+ "--learning-rate",
1230
+ default=0.0001,
1231
+ type=float,
1232
+ help="learning rate for Adam optimizer",
1233
+ )
1234
+ parser.add_argument(
1235
+ "-cs",
1236
+ "--codebook-size",
1237
+ default=100,
1238
+ type=int,
1239
+ help="size of vector quantization codebook",
1240
+ )
1241
+ parser.add_argument(
1242
+ "--z-dist",
1243
+ default='gumbel',
1244
+ type=str,
1245
+ choices=['normal','laplacian','studentt','gumbel','cauchy'],
1246
+ help="distribution model for latent representation",
1247
+ )
1248
+ parser.add_argument(
1249
+ "-zd",
1250
+ "--z-dim",
1251
+ default=10,
1252
+ type=int,
1253
+ help="size of the tensor representing the latent variable z variable",
1254
+ )
1255
+ parser.add_argument(
1256
+ "-likeli",
1257
+ "--likelihood",
1258
+ default='negbinomial',
1259
+ type=str,
1260
+ choices=['negbinomial', 'multinomial', 'poisson', 'bernoulli'],
1261
+ help="specify the distribution likelihood function",
1262
+ )
1263
+ parser.add_argument(
1264
+ "-zi",
1265
+ "--zeroinflate",
1266
+ action="store_true",
1267
+ help="use zero-inflated estimation",
1268
+ )
1269
+ parser.add_argument(
1270
+ "-id",
1271
+ "--inverse-dispersion",
1272
+ default=10.0,
1273
+ type=float,
1274
+ help="inverse dispersion prior for negative binomial",
1275
+ )
1276
+ parser.add_argument(
1277
+ "-hl",
1278
+ "--hidden-layers",
1279
+ nargs="+",
1280
+ default=[500],
1281
+ type=int,
1282
+ help="a tuple (or list) of MLP layers to be used in the neural networks "
1283
+ "representing the parameters of the distributions in our model",
1284
+ )
1285
+ parser.add_argument(
1286
+ "-hla",
1287
+ "--hidden-layer-activation",
1288
+ default='relu',
1289
+ type=str,
1290
+ choices=['relu','softplus','leakyrelu','linear'],
1291
+ help="activation function for hidden layers",
1292
+ )
1293
+ parser.add_argument(
1294
+ "-plf",
1295
+ "--post-layer-function",
1296
+ nargs="+",
1297
+ default=['layernorm'],
1298
+ type=str,
1299
+ help="post functions for hidden layers, could be none, dropout, layernorm, batchnorm, or combination, default is 'dropout layernorm'",
1300
+ )
1301
+ parser.add_argument(
1302
+ "-paf",
1303
+ "--post-activation-function",
1304
+ nargs="+",
1305
+ default=['none'],
1306
+ type=str,
1307
+ help="post functions for activation layers, could be none or dropout, default is 'none'",
1308
+ )
1309
+ parser.add_argument(
1310
+ "-64",
1311
+ "--float64",
1312
+ action="store_true",
1313
+ help="use double float precision",
1314
+ )
1315
+ parser.add_argument(
1316
+ "-dr",
1317
+ "--decay-rate",
1318
+ default=0.9,
1319
+ type=float,
1320
+ help="decay rate for Adam optimizer",
1321
+ )
1322
+ parser.add_argument(
1323
+ "--layer-dropout-rate",
1324
+ default=0.1,
1325
+ type=float,
1326
+ help="droput rate for neural networks",
1327
+ )
1328
+ parser.add_argument(
1329
+ "-b1",
1330
+ "--beta-1",
1331
+ default=0.95,
1332
+ type=float,
1333
+ help="beta-1 parameter for Adam optimizer",
1334
+ )
1335
+ parser.add_argument(
1336
+ "--seed",
1337
+ default=None,
1338
+ type=int,
1339
+ help="seed for controlling randomness in this example",
1340
+ )
1341
+ parser.add_argument(
1342
+ "--save-model",
1343
+ default=None,
1344
+ type=str,
1345
+ help="path to save model for prediction",
1346
+ )
1347
+ args = parser.parse_args()
1348
+ return args
1349
+
1350
+ def main():
1351
+ args = parse_args()
1352
+ assert (
1353
+ (args.data_file is not None) and (
1354
+ os.path.exists(args.data_file))
1355
+ ), "data file must be provided"
1356
+
1357
+ if args.seed is not None:
1358
+ set_random_seed(args.seed)
1359
+
1360
+ if args.float64:
1361
+ dtype = torch.float64
1362
+ torch.set_default_dtype(torch.float64)
1363
+ else:
1364
+ dtype = torch.float32
1365
+ torch.set_default_dtype(torch.float32)
1366
+
1367
+ xs = dt.fread(file=args.data_file, header=True).to_numpy()
1368
+ us = None
1369
+ if args.cell_factor_file is not None:
1370
+ us = dt.fread(file=args.cell_factor_file, header=True).to_numpy()
1371
+
1372
+ input_size = xs.shape[1]
1373
+ cell_factor_size = 0 if us is None else us.shape[1]
1374
+
1375
+ ###########################################
1376
+ df = DensityFlowLinear(
1377
+ input_size=input_size,
1378
+ cell_factor_size=cell_factor_size,
1379
+ dispersion=args.dispersion,
1380
+ z_dim=args.z_dim,
1381
+ hidden_layers=args.hidden_layers,
1382
+ hidden_layer_activation=args.hidden_layer_activation,
1383
+ use_cuda=args.cuda,
1384
+ config_enum=args.enum_discrete,
1385
+ use_zeroinflate=args.zeroinflate,
1386
+ loss_func=args.likelihood,
1387
+ nn_dropout=args.layer_dropout_rate,
1388
+ post_layer_fct=args.post_layer_function,
1389
+ post_act_fct=args.post_activation_function,
1390
+ codebook_size=args.codebook_size,
1391
+ z_dist = args.z_dist,
1392
+ dtype=dtype,
1393
+ )
1394
+
1395
+ df.fit(xs, us=us,
1396
+ num_epochs=args.num_epochs,
1397
+ learning_rate=args.learning_rate,
1398
+ batch_size=args.batch_size,
1399
+ beta_1=args.beta_1,
1400
+ decay_rate=args.decay_rate,
1401
+ use_jax=args.jit,
1402
+ config_enum=args.enum_discrete,
1403
+ )
1404
+
1405
+ if args.save_model is not None:
1406
+ if args.save_model.endswith('gz'):
1407
+ DensityFlowLinear.save_model(df, args.save_model, compression=True)
1408
+ else:
1409
+ DensityFlowLinear.save_model(df, args.save_model)
1410
+
1411
+
1412
+
1413
+ if __name__ == "__main__":
1414
+ main()