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