SURE-tools 2.1.87__py3-none-any.whl → 2.4.3__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.

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