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