SURE-tools 2.1.22__py3-none-any.whl → 2.1.25__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 CHANGED
@@ -196,7 +196,7 @@ class PerturbFlow(nn.Module):
196
196
  if self.cell_factor_size>0:
197
197
  self.cell_factor_effect = nn.ModuleList()
198
198
  for i in np.arange(self.cell_factor_size):
199
- self.cell_factor_effect.append(ZeroBiasMLP(
199
+ self.cell_factor_effect.append(MLP(
200
200
  [self.latent_dim+1] + hidden_sizes + [self.latent_dim],
201
201
  activation=activate_fct,
202
202
  output_activation=None,
SURE/SURE.py CHANGED
@@ -10,7 +10,7 @@ from torch.distributions.utils import logits_to_probs, probs_to_logits, clamp_pr
10
10
  from torch.distributions import constraints
11
11
  from torch.distributions.transforms import SoftmaxTransform
12
12
 
13
- from .utils.custom_mlp import MLP, Exp
13
+ from .utils.custom_mlp import MLP, Exp, ZeroBiasMLP
14
14
  from .utils.utils import CustomDataset, CustomDataset2, CustomDataset4, tensor_to_numpy, convert_to_tensor
15
15
 
16
16
 
SURE/utils/custom_mlp.py CHANGED
@@ -239,6 +239,6 @@ class ZeroBiasMLP(nn.Module):
239
239
  def forward(self, x):
240
240
  y = self.mlp(x)
241
241
  mask = torch.zeros_like(y)
242
- mask[x[1]>0,:] = 1
242
+ mask[x[1][:,0]>0,:] = 1
243
243
  return y*mask
244
244
 
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: SURE-tools
3
- Version: 2.1.22
3
+ Version: 2.1.25
4
4
  Summary: Succinct Representation of Single Cells
5
5
  Home-page: https://github.com/ZengFLab/SURE
6
6
  Author: Feng Zeng
@@ -1,6 +1,5 @@
1
- SURE/PerturbFlow.py,sha256=gHrIHTAmFsG3FwS1ov7K3KwRMS0aw_IFQM-3HDIWnaA,50946
2
- SURE/SURE.py,sha256=xMD6VBYsgk-bZ_xBWzpdGyxEAleonNRoPkZAxAX467s,47444
3
- SURE/SURE2.py,sha256=8wlnMwb1xuf9QUksNkWdWx5ZWq-xIy9NLx8RdUnE82o,48501
1
+ SURE/PerturbFlow.py,sha256=P5YebRbhyEIueyStdaMkFvLq43MJSBCcYd-pI09eTBQ,50938
2
+ SURE/SURE.py,sha256=hVEjJtFVQkk_rX3KEaQgWoDTfxpDHf1p6j38UJjNkyY,47457
4
3
  SURE/__init__.py,sha256=NOJI_K-eCqPgStXXvgl3wIEMp6d8saMTDYLJ7Ga9MqE,293
5
4
  SURE/assembly/__init__.py,sha256=jxZLURXKPzXe21LhrZ09LgZr33iqdjlQy4oSEj5gR2Q,172
6
5
  SURE/assembly/assembly.py,sha256=6IMdelPOiRO4mUb4dC7gVCoF1Uvfw86-Map8P_jnUag,21477
@@ -12,16 +11,15 @@ SURE/codebook/codebook.py,sha256=ZlN6gRX9Gj2D2u3P5KeOsbZri0MoMAiJo9lNeL-MK-I,171
12
11
  SURE/flow/__init__.py,sha256=rsAjYsh1xVIrxBCuwOE0Q_6N5th1wBgjJceV0ABPG3c,183
13
12
  SURE/flow/flow_stats.py,sha256=3F3waCuEbIQ7bsiGga4cUvJphYdWA307SyGwEh8EzM8,10514
14
13
  SURE/flow/plot_quiver.py,sha256=wC42yLKfXYOGrrd4u9AbZS_6QiPUJ9QBXaOso55LjdA,8110
15
- SURE/flow/quiver.py,sha256=_euFqSaRrDoZ_oOabOx20LOoUTJ__XPhLW-vzLNQfAo,1859
16
14
  SURE/perturb/__init__.py,sha256=ouxShhbxZM4r5Gf7GmKiutrsmtyq7QL8rHjhgF0BU08,32
17
15
  SURE/perturb/perturb.py,sha256=CqO3xPfNA3cG175tadDidKvGsTu_yKfJRRLn_93awKM,3303
18
16
  SURE/utils/__init__.py,sha256=Htqv4KqVKcRiaaTBsR-6yZ4LSlbhbzutjNKXGD9-uds,660
19
- SURE/utils/custom_mlp.py,sha256=WYIrCqZypa2a4icrXnknPULIC_rSxhA3qYRumzq68X0,8100
17
+ SURE/utils/custom_mlp.py,sha256=PCnXhJdK_g6z51JJqCdrNGBoOU_SjN5XYAOhB_2BxNo,8105
20
18
  SURE/utils/queue.py,sha256=E_5PA5EWcBoGAZj8BkKQnkCK0p4C-4-xcTPqdIXaPXU,1892
21
19
  SURE/utils/utils.py,sha256=IUHjDDtYaAYllCWsZyIzqQwaLul6fJRvHRH4vIYcR-c,8462
22
- sure_tools-2.1.22.dist-info/licenses/LICENSE,sha256=TFHKwmrAViXQbSX5W-NDItkWFjm45HWOeUniDrqmnu0,1065
23
- sure_tools-2.1.22.dist-info/METADATA,sha256=e6LTOaCIRdsq4LgyYrF-iwfvWHMX1twop4BQsci3Vog,2651
24
- sure_tools-2.1.22.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
25
- sure_tools-2.1.22.dist-info/entry_points.txt,sha256=-nJI8rVe_qqrR0HmfAODzj-JNfEqCcSsyVh6okSqyHk,83
26
- sure_tools-2.1.22.dist-info/top_level.txt,sha256=BtFTebdiJeqra4r6mm-uEtwVRFLZ_IjYsQ7OnalrOvY,5
27
- sure_tools-2.1.22.dist-info/RECORD,,
20
+ sure_tools-2.1.25.dist-info/licenses/LICENSE,sha256=TFHKwmrAViXQbSX5W-NDItkWFjm45HWOeUniDrqmnu0,1065
21
+ sure_tools-2.1.25.dist-info/METADATA,sha256=ITglLMC3_2A_bAxJS--dB1mkJkuxomRO-NLN3wn0YpI,2651
22
+ sure_tools-2.1.25.dist-info/WHEEL,sha256=_zCd3N1l69ArxyTb8rzEoP9TpbYXkqRFSNOD5OuxnTs,91
23
+ sure_tools-2.1.25.dist-info/entry_points.txt,sha256=-nJI8rVe_qqrR0HmfAODzj-JNfEqCcSsyVh6okSqyHk,83
24
+ sure_tools-2.1.25.dist-info/top_level.txt,sha256=BtFTebdiJeqra4r6mm-uEtwVRFLZ_IjYsQ7OnalrOvY,5
25
+ sure_tools-2.1.25.dist-info/RECORD,,
SURE/SURE2.py DELETED
@@ -1,1236 +0,0 @@
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, CustomDataset3, 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 SURE2(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 = MLP(
236
- [self.cell_factor_size] + self.decoder_hidden_layers + [self.latent_dim],
237
- activation=activate_fct,
238
- output_activation=None,
239
- post_layer_fct=post_layer_fct,
240
- post_act_fct=post_act_fct,
241
- allow_broadcast=self.allow_broadcast,
242
- use_cuda=self.use_cuda,
243
- )
244
-
245
- self.decoder_concentrate = MLP(
246
- [self.latent_dim] + self.decoder_hidden_layers + [self.input_size],
247
- activation=activate_fct,
248
- output_activation=None,
249
- post_layer_fct=post_layer_fct,
250
- post_act_fct=post_act_fct,
251
- allow_broadcast=self.allow_broadcast,
252
- use_cuda=self.use_cuda,
253
- )
254
-
255
- if self.latent_dist == 'studentt':
256
- self.codebook = MLP(
257
- [self.code_size] + hidden_sizes + [[latent_dim,latent_dim,latent_dim]],
258
- activation=activate_fct,
259
- output_activation=[Exp,None,Exp],
260
- post_layer_fct=post_layer_fct,
261
- post_act_fct=post_act_fct,
262
- allow_broadcast=self.allow_broadcast,
263
- use_cuda=self.use_cuda,
264
- )
265
- else:
266
- self.codebook = MLP(
267
- [self.code_size] + hidden_sizes + [[latent_dim,latent_dim]],
268
- activation=activate_fct,
269
- output_activation=[None,Exp],
270
- post_layer_fct=post_layer_fct,
271
- post_act_fct=post_act_fct,
272
- allow_broadcast=self.allow_broadcast,
273
- use_cuda=self.use_cuda,
274
- )
275
-
276
- if self.use_cuda:
277
- self.cuda()
278
-
279
- def get_device(self):
280
- return next(self.parameters()).device
281
-
282
- def cutoff(self, xs, thresh=None):
283
- eps = torch.finfo(xs.dtype).eps
284
-
285
- if not thresh is None:
286
- if eps < thresh:
287
- eps = thresh
288
-
289
- xs = xs.clamp(min=eps)
290
-
291
- if torch.any(torch.isnan(xs)):
292
- xs[torch.isnan(xs)] = eps
293
-
294
- return xs
295
-
296
- def softmax(self, xs):
297
- #xs = SoftmaxTransform()(xs)
298
- xs = dist.Multinomial(total_count=1, logits=xs).mean
299
- return xs
300
-
301
- def sigmoid(self, xs):
302
- #sigm_enc = nn.Sigmoid()
303
- #xs = sigm_enc(xs)
304
- #xs = clamp_probs(xs)
305
- xs = dist.Bernoulli(logits=xs).mean
306
- return xs
307
-
308
- def softmax_logit(self, xs):
309
- eps = torch.finfo(xs.dtype).eps
310
- xs = self.softmax(xs)
311
- xs = torch.logit(xs, eps=eps)
312
- return xs
313
-
314
- def logit(self, xs):
315
- eps = torch.finfo(xs.dtype).eps
316
- xs = torch.logit(xs, eps=eps)
317
- return xs
318
-
319
- def dirimulti_param(self, xs):
320
- xs = self.dirimulti_mass * self.sigmoid(xs)
321
- return xs
322
-
323
- def multi_param(self, xs):
324
- xs = self.softmax(xs)
325
- return xs
326
-
327
- def model1(self, xs):
328
- pyro.module('sure', self)
329
-
330
- eps = torch.finfo(xs.dtype).eps
331
- batch_size = xs.size(0)
332
- self.options = dict(dtype=xs.dtype, device=xs.device)
333
-
334
- if self.loss_func=='negbinomial':
335
- total_count = pyro.param("inverse_dispersion", self.inverse_dispersion *
336
- xs.new_ones(self.input_size), constraint=constraints.positive)
337
-
338
- if self.use_zeroinflate:
339
- gate_logits = pyro.param("dropout_rate", xs.new_zeros(self.input_size))
340
-
341
- #acs_scale = pyro.param("codebook_scale", xs.new_ones(self.latent_dim), constraint=constraints.positive)
342
-
343
- I = torch.eye(self.code_size)
344
- if self.latent_dist=='studentt':
345
- acs_dof,acs_loc,acs_scale = self.codebook(I)
346
- else:
347
- acs_loc,acs_scale = self.codebook(I)
348
-
349
- with pyro.plate('data'):
350
- prior = torch.zeros(batch_size, self.code_size, **self.options)
351
- ns = pyro.sample('n', dist.OneHotCategorical(logits=prior))
352
-
353
- zn_loc = torch.matmul(ns,acs_loc)
354
- zn_scale = torch.matmul(ns,acs_scale)
355
- #zn_scale = acs_scale
356
-
357
- if self.latent_dist == 'studentt':
358
- prior_dof = torch.matmul(ns,acs_dof)
359
- zns = pyro.sample('zn', dist.StudentT(df=prior_dof, loc=zn_loc, scale=zn_scale).to_event(1))
360
- elif self.latent_dist == 'laplacian':
361
- zns = pyro.sample('zn', dist.Laplace(zn_loc, zn_scale).to_event(1))
362
- elif self.latent_dist == 'cauchy':
363
- zns = pyro.sample('zn', dist.Cauchy(zn_loc, zn_scale).to_event(1))
364
- elif self.latent_dist == 'normal':
365
- zns = pyro.sample('zn', dist.Normal(zn_loc, zn_scale).to_event(1))
366
- elif self.latent_dist == 'gumbel':
367
- zns = pyro.sample('zn', dist.Gumbel(zn_loc, zn_scale).to_event(1))
368
-
369
- zs = zns
370
- concentrate = self.decoder_concentrate(zs)
371
- if self.loss_func == 'bernoulli':
372
- log_theta = concentrate
373
- else:
374
- rate = concentrate.exp()
375
- if self.loss_func != 'poisson':
376
- theta = dist.DirichletMultinomial(total_count=1, concentration=rate).mean
377
-
378
- if self.loss_func == 'negbinomial':
379
- if self.use_zeroinflate:
380
- pyro.sample('x', dist.ZeroInflatedDistribution(dist.NegativeBinomial(total_count=total_count, probs=theta),gate_logits=gate_logits).to_event(1), obs=xs)
381
- else:
382
- pyro.sample('x', dist.NegativeBinomial(total_count=total_count, probs=theta).to_event(1), obs=xs)
383
- elif self.loss_func == 'poisson':
384
- if self.use_zeroinflate:
385
- pyro.sample('x', dist.ZeroInflatedDistribution(dist.Poisson(rate=rate),gate_logits=gate_logits).to_event(1), obs=xs.round())
386
- else:
387
- pyro.sample('x', dist.Poisson(rate=rate).to_event(1), obs=xs.round())
388
- elif self.loss_func == 'multinomial':
389
- pyro.sample('x', dist.Multinomial(total_count=int(1e8), probs=theta), obs=xs)
390
- elif self.loss_func == 'bernoulli':
391
- if self.use_zeroinflate:
392
- pyro.sample('x', dist.ZeroInflatedDistribution(dist.Bernoulli(logits=log_theta),gate_logits=gate_logits).to_event(1), obs=xs)
393
- else:
394
- pyro.sample('x', dist.Bernoulli(logits=log_theta).to_event(1), obs=xs)
395
-
396
- def guide1(self, xs):
397
- with pyro.plate('data'):
398
- zn_loc, zn_scale = self.encoder_zn(xs)
399
- zns = pyro.sample('zn', dist.Normal(zn_loc, zn_scale).to_event(1))
400
-
401
- alpha = self.encoder_n(zns)
402
- ns = pyro.sample('n', dist.OneHotCategorical(logits=alpha))
403
-
404
- def model2(self, xs, us=None):
405
- pyro.module('sure', self)
406
-
407
- eps = torch.finfo(xs.dtype).eps
408
- batch_size = xs.size(0)
409
- self.options = dict(dtype=xs.dtype, device=xs.device)
410
-
411
- if self.loss_func=='negbinomial':
412
- total_count = pyro.param("inverse_dispersion", self.inverse_dispersion *
413
- xs.new_ones(self.input_size), constraint=constraints.positive)
414
-
415
- if self.use_zeroinflate:
416
- gate_logits = pyro.param("dropout_rate", xs.new_zeros(self.input_size))
417
-
418
- #acs_scale = pyro.param("codebook_scale", xs.new_ones(self.latent_dim), constraint=constraints.positive)
419
-
420
- I = torch.eye(self.code_size)
421
- if self.latent_dist=='studentt':
422
- acs_dof,acs_loc,acs_scale = self.codebook(I)
423
- else:
424
- acs_loc,acs_scale = self.codebook(I)
425
-
426
- with pyro.plate('data'):
427
- prior = torch.zeros(batch_size, self.code_size, **self.options)
428
- ns = pyro.sample('n', dist.OneHotCategorical(logits=prior))
429
-
430
- zn_loc = torch.matmul(ns,acs_loc)
431
- zn_scale = torch.matmul(ns,acs_scale)
432
- #zn_scale = acs_scale
433
-
434
- if self.latent_dist == 'studentt':
435
- prior_dof = torch.matmul(ns,acs_dof)
436
- zns = pyro.sample('zn', dist.StudentT(df=prior_dof, loc=zn_loc, scale=zn_scale).to_event(1))
437
- elif self.latent_dist == 'laplacian':
438
- zns = pyro.sample('zn', dist.Laplace(zn_loc, zn_scale).to_event(1))
439
- elif self.latent_dist == 'cauchy':
440
- zns = pyro.sample('zn', dist.Cauchy(zn_loc, zn_scale).to_event(1))
441
- elif self.latent_dist == 'normal':
442
- zns = pyro.sample('zn', dist.Normal(zn_loc, zn_scale).to_event(1))
443
- elif self.latent_dist == 'gumbel':
444
- zns = pyro.sample('zn', dist.Gumbel(zn_loc, zn_scale).to_event(1))
445
-
446
- if self.cell_factor_size>0:
447
- zus = self.cell_factor_effect(us)
448
- zs = zns + zus
449
- else:
450
- zs = zns
451
-
452
- concentrate = self.decoder_concentrate(zs)
453
- if self.loss_func == 'bernoulli':
454
- log_theta = concentrate
455
- else:
456
- rate = concentrate.exp()
457
- if self.loss_func != 'poisson':
458
- theta = dist.DirichletMultinomial(total_count=1, concentration=rate).mean
459
-
460
- if self.loss_func == 'negbinomial':
461
- if self.use_zeroinflate:
462
- pyro.sample('x', dist.ZeroInflatedDistribution(dist.NegativeBinomial(total_count=total_count, probs=theta),gate_logits=gate_logits).to_event(1), obs=xs)
463
- else:
464
- pyro.sample('x', dist.NegativeBinomial(total_count=total_count, probs=theta).to_event(1), obs=xs)
465
- elif self.loss_func == 'poisson':
466
- if self.use_zeroinflate:
467
- pyro.sample('x', dist.ZeroInflatedDistribution(dist.Poisson(rate=rate),gate_logits=gate_logits).to_event(1), obs=xs.round())
468
- else:
469
- pyro.sample('x', dist.Poisson(rate=rate).to_event(1), obs=xs.round())
470
- elif self.loss_func == 'multinomial':
471
- pyro.sample('x', dist.Multinomial(total_count=int(1e8), probs=theta), obs=xs)
472
- elif self.loss_func == 'bernoulli':
473
- if self.use_zeroinflate:
474
- pyro.sample('x', dist.ZeroInflatedDistribution(dist.Bernoulli(logits=log_theta),gate_logits=gate_logits).to_event(1), obs=xs)
475
- else:
476
- pyro.sample('x', dist.Bernoulli(logits=log_theta).to_event(1), obs=xs)
477
-
478
- def guide2(self, xs, us=None):
479
- with pyro.plate('data'):
480
- zn_loc, zn_scale = self.encoder_zn(xs)
481
- zns = pyro.sample('zn', dist.Normal(zn_loc, zn_scale).to_event(1))
482
-
483
- alpha = self.encoder_n(zns)
484
- ns = pyro.sample('n', dist.OneHotCategorical(logits=alpha))
485
-
486
- def model3(self, xs, ys, embeds=None):
487
- pyro.module('sure', self)
488
-
489
- eps = torch.finfo(xs.dtype).eps
490
- batch_size = xs.size(0)
491
- self.options = dict(dtype=xs.dtype, device=xs.device)
492
-
493
- if self.loss_func=='negbinomial':
494
- total_count = pyro.param("inverse_dispersion", self.inverse_dispersion *
495
- xs.new_ones(self.input_size), constraint=constraints.positive)
496
-
497
- if self.use_zeroinflate:
498
- gate_logits = pyro.param("dropout_rate", xs.new_zeros(self.input_size))
499
-
500
- #acs_scale = pyro.param("codebook_scale", xs.new_ones(self.latent_dim), constraint=constraints.positive)
501
-
502
- I = torch.eye(self.code_size)
503
- if self.latent_dist=='studentt':
504
- acs_dof,acs_loc,acs_scale = self.codebook(I)
505
- else:
506
- acs_loc,acs_scale = self.codebook(I)
507
-
508
- with pyro.plate('data'):
509
- #prior = torch.zeros(batch_size, self.code_size, **self.options)
510
- prior = self.encoder_n(xs)
511
- ns = pyro.sample('n', dist.OneHotCategorical(logits=prior), obs=ys)
512
-
513
- zn_loc = torch.matmul(ns,acs_loc)
514
- zn_scale = torch.matmul(ns,acs_scale)
515
- #zn_scale = acs_scale
516
-
517
- if self.latent_dist=='studentt':
518
- prior_dof = torch.matmul(ns,acs_dof)
519
- if embeds is None:
520
- zns = pyro.sample('zn', dist.StudentT(df=prior_dof, loc=zn_loc, scale=zn_scale).to_event(1))
521
- else:
522
- zns = pyro.sample('zn', dist.StudentT(df=prior_dof, loc=zn_loc, scale=zn_scale).to_event(1), obs=embeds)
523
- elif self.latent_dist=='laplacian':
524
- if embeds is None:
525
- zns = pyro.sample('zn', dist.Laplace(zn_loc, zn_scale).to_event(1))
526
- else:
527
- zns = pyro.sample('zn', dist.Laplace(zn_loc, zn_scale).to_event(1), obs=embeds)
528
- elif self.latent_dist=='cauchy':
529
- if embeds is None:
530
- zns = pyro.sample('zn', dist.Cauchy(zn_loc, zn_scale).to_event(1))
531
- else:
532
- zns = pyro.sample('zn', dist.Cauchy(zn_loc, zn_scale).to_event(1), obs=embeds)
533
- elif self.latent_dist=='normal':
534
- if embeds is None:
535
- zns = pyro.sample('zn', dist.Normal(zn_loc, zn_scale).to_event(1))
536
- else:
537
- zns = pyro.sample('zn', dist.Normal(zn_loc, zn_scale).to_event(1), obs=embeds)
538
- elif self.z_dist == 'gumbel':
539
- if embeds is None:
540
- zns = pyro.sample('zn', dist.Gumbel(zn_loc, zn_scale).to_event(1))
541
- else:
542
- zns = pyro.sample('zn', dist.Gumbel(zn_loc, zn_scale).to_event(1), obs=embeds)
543
-
544
- zs = zns
545
-
546
- concentrate = self.decoder_concentrate(zs)
547
- if self.loss_func == 'bernoulli':
548
- log_theta = concentrate
549
- else:
550
- rate = concentrate.exp()
551
- if self.loss_func != 'poisson':
552
- theta = dist.DirichletMultinomial(total_count=1, concentration=rate).mean
553
-
554
- if self.loss_func == 'negbinomial':
555
- if self.use_zeroinflate:
556
- pyro.sample('x', dist.ZeroInflatedDistribution(dist.NegativeBinomial(total_count=total_count, probs=theta),gate_logits=gate_logits).to_event(1), obs=xs)
557
- else:
558
- pyro.sample('x', dist.NegativeBinomial(total_count=total_count, probs=theta).to_event(1), obs=xs)
559
- elif self.loss_func == 'poisson':
560
- if self.use_zeroinflate:
561
- pyro.sample('x', dist.ZeroInflatedDistribution(dist.Poisson(rate=rate),gate_logits=gate_logits).to_event(1), obs=xs.round())
562
- else:
563
- pyro.sample('x', dist.Poisson(rate=rate).to_event(1), obs=xs.round())
564
- elif self.loss_func == 'multinomial':
565
- pyro.sample('x', dist.Multinomial(total_count=int(1e8), probs=theta), obs=xs)
566
- elif self.loss_func == 'bernoulli':
567
- if self.use_zeroinflate:
568
- pyro.sample('x', dist.ZeroInflatedDistribution(dist.Bernoulli(logits=log_theta),gate_logits=gate_logits).to_event(1), obs=xs)
569
- else:
570
- pyro.sample('x', dist.Bernoulli(logits=log_theta).to_event(1), obs=xs)
571
-
572
- def guide3(self, xs, ys, embeds=None):
573
- with pyro.plate('data'):
574
- if embeds is None:
575
- zn_loc, zn_scale = self.encoder_zn(xs)
576
- zns = pyro.sample('zn', dist.Normal(zn_loc, zn_scale).to_event(1))
577
-
578
- def model4(self, xs, us, ys, embeds=None):
579
- pyro.module('sure', self)
580
-
581
- eps = torch.finfo(xs.dtype).eps
582
- batch_size = xs.size(0)
583
- self.options = dict(dtype=xs.dtype, device=xs.device)
584
-
585
- if self.loss_func=='negbinomial':
586
- total_count = pyro.param("inverse_dispersion", self.inverse_dispersion *
587
- xs.new_ones(self.input_size), constraint=constraints.positive)
588
-
589
- if self.use_zeroinflate:
590
- gate_logits = pyro.param("dropout_rate", xs.new_zeros(self.input_size))
591
-
592
- #acs_scale = pyro.param("codebook_scale", xs.new_ones(self.latent_dim), constraint=constraints.positive)
593
-
594
- I = torch.eye(self.code_size)
595
- if self.latent_dist=='studentt':
596
- acs_dof,acs_loc,acs_scale = self.codebook(I)
597
- else:
598
- acs_loc,acs_scale = self.codebook(I)
599
-
600
- with pyro.plate('data'):
601
- #prior = torch.zeros(batch_size, self.code_size, **self.options)
602
- prior = self.encoder_n(xs)
603
- ns = pyro.sample('n', dist.OneHotCategorical(logits=prior), obs=ys)
604
-
605
- zn_loc = torch.matmul(ns,acs_loc)
606
- zn_scale = torch.matmul(ns,acs_scale)
607
- #zn_scale = acs_scale
608
-
609
- if self.latent_dist=='studentt':
610
- prior_dof = torch.matmul(ns,acs_dof)
611
- if embeds is None:
612
- zns = pyro.sample('zn', dist.StudentT(df=prior_dof, loc=zn_loc, scale=zn_scale).to_event(1))
613
- else:
614
- zns = pyro.sample('zn', dist.StudentT(df=prior_dof, loc=zn_loc, scale=zn_scale).to_event(1), obs=embeds)
615
- elif self.latent_dist=='laplacian':
616
- if embeds is None:
617
- zns = pyro.sample('zn', dist.Laplace(zn_loc, zn_scale).to_event(1))
618
- else:
619
- zns = pyro.sample('zn', dist.Laplace(zn_loc, zn_scale).to_event(1), obs=embeds)
620
- elif self.latent_dist=='cauchy':
621
- if embeds is None:
622
- zns = pyro.sample('zn', dist.Cauchy(zn_loc, zn_scale).to_event(1))
623
- else:
624
- zns = pyro.sample('zn', dist.Cauchy(zn_loc, zn_scale).to_event(1), obs=embeds)
625
- elif self.latent_dist=='normal':
626
- if embeds is None:
627
- zns = pyro.sample('zn', dist.Normal(zn_loc, zn_scale).to_event(1))
628
- else:
629
- zns = pyro.sample('zn', dist.Normal(zn_loc, zn_scale).to_event(1), obs=embeds)
630
- elif self.z_dist == 'gumbel':
631
- if embeds is None:
632
- zns = pyro.sample('zn', dist.Gumbel(zn_loc, zn_scale).to_event(1))
633
- else:
634
- zns = pyro.sample('zn', dist.Gumbel(zn_loc, zn_scale).to_event(1), obs=embeds)
635
-
636
- if self.cell_factor_size>0:
637
- zus = self.cell_factor_effect(us)
638
- zs = zus + zns
639
- else:
640
- zs = zns
641
-
642
- concentrate = self.decoder_concentrate(zs)
643
- if self.loss_func == 'bernoulli':
644
- log_theta = concentrate
645
- else:
646
- rate = concentrate.exp()
647
- if self.loss_func != 'poisson':
648
- theta = dist.DirichletMultinomial(total_count=1, concentration=rate).mean
649
-
650
- if self.loss_func == 'negbinomial':
651
- if self.use_zeroinflate:
652
- pyro.sample('x', dist.ZeroInflatedDistribution(dist.NegativeBinomial(total_count=total_count, probs=theta),gate_logits=gate_logits).to_event(1), obs=xs)
653
- else:
654
- pyro.sample('x', dist.NegativeBinomial(total_count=total_count, probs=theta).to_event(1), obs=xs)
655
- elif self.loss_func == 'poisson':
656
- if self.use_zeroinflate:
657
- pyro.sample('x', dist.ZeroInflatedDistribution(dist.Poisson(rate=rate),gate_logits=gate_logits).to_event(1), obs=xs.round())
658
- else:
659
- pyro.sample('x', dist.Poisson(rate=rate).to_event(1), obs=xs.round())
660
- elif self.loss_func == 'multinomial':
661
- pyro.sample('x', dist.Multinomial(total_count=int(1e8), probs=theta), obs=xs)
662
- elif self.loss_func == 'bernoulli':
663
- if self.use_zeroinflate:
664
- pyro.sample('x', dist.ZeroInflatedDistribution(dist.Bernoulli(logits=log_theta),gate_logits=gate_logits).to_event(1), obs=xs)
665
- else:
666
- pyro.sample('x', dist.Bernoulli(logits=log_theta).to_event(1), obs=xs)
667
-
668
- def guide4(self, xs, us, ys, embeds=None):
669
- with pyro.plate('data'):
670
- if embeds is None:
671
- zn_loc, zn_scale = self.encoder_zn(xs)
672
- zns = pyro.sample('zn', dist.Normal(zn_loc, zn_scale).to_event(1))
673
-
674
- def _get_codebook(self):
675
- I = torch.eye(self.code_size, **self.options)
676
- if self.latent_dist=='studentt':
677
- _,cb,_ = self.codebook(I)
678
- else:
679
- cb,_ = self.codebook(I)
680
- return cb
681
-
682
- def get_codebook(self):
683
- """
684
- Return the mean part of metacell codebook
685
- """
686
- cb = self._get_metacell_coordinates()
687
- cb = tensor_to_numpy(cb)
688
- return cb
689
-
690
- def _get_cell_embedding(self, xs):
691
- zns, _ = self.encoder_zn(xs)
692
- return zns
693
-
694
- def get_cell_embedding(self,
695
- xs,
696
- batch_size: int = 1024):
697
- """
698
- Return cells' latent representations
699
-
700
- Parameters
701
- ----------
702
- xs
703
- Single-cell expression matrix. It should be a Numpy array or a Pytorch Tensor.
704
- batch_size
705
- Size of batch processing.
706
- use_decoder
707
- If toggled on, the latent representations will be reconstructed from the metacell codebook
708
- soft_assign
709
- If toggled on, the assignments of cells will use probabilistic values.
710
- """
711
- xs = self.preprocess(xs)
712
- xs = convert_to_tensor(xs, device=self.get_device())
713
- dataset = CustomDataset(xs)
714
- dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False)
715
-
716
- Z = []
717
- with tqdm(total=len(dataloader), desc='', unit='batch') as pbar:
718
- for X_batch, _ in dataloader:
719
- zns = self._get_cell_embedding(X_batch)
720
- Z.append(tensor_to_numpy(zns))
721
- pbar.update(1)
722
-
723
- Z = np.concatenate(Z)
724
- return Z
725
-
726
- def _code(self, xs):
727
- if self.supervised_mode:
728
- alpha = self.encoder_n(xs)
729
- else:
730
- zns,_ = self.encoder_zn(xs)
731
- alpha = self.encoder_n(zns)
732
- return alpha
733
-
734
- def code(self, xs, batch_size=1024):
735
- xs = self.preprocess(xs)
736
- xs = convert_to_tensor(xs, device=self.get_device())
737
- dataset = CustomDataset(xs)
738
- dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False)
739
-
740
- A = []
741
- with tqdm(total=len(dataloader), desc='', unit='batch') as pbar:
742
- for X_batch, _ in dataloader:
743
- a = self._code(X_batch)
744
- A.append(tensor_to_numpy(a))
745
- pbar.update(1)
746
-
747
- A = np.concatenate(A)
748
- return A
749
-
750
- def _soft_assignments(self, xs):
751
- alpha = self._code(xs)
752
- alpha = self.softmax(alpha)
753
- return alpha
754
-
755
- def soft_assignments(self, xs, batch_size=1024):
756
- """
757
- Map cells to metacells and return the probabilistic values of metacell assignments
758
- """
759
- xs = self.preprocess(xs)
760
- xs = convert_to_tensor(xs, device=self.get_device())
761
- dataset = CustomDataset(xs)
762
- dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False)
763
-
764
- A = []
765
- with tqdm(total=len(dataloader), desc='', unit='batch') as pbar:
766
- for X_batch, _ in dataloader:
767
- a = self._soft_assignments(X_batch)
768
- A.append(tensor_to_numpy(a))
769
- pbar.update(1)
770
-
771
- A = np.concatenate(A)
772
- return A
773
-
774
- def _hard_assignments(self, xs):
775
- alpha = self._code(xs)
776
- res, ind = torch.topk(alpha, 1)
777
- ns = torch.zeros_like(alpha).scatter_(1, ind, 1.0)
778
- return ns
779
-
780
- def hard_assignments(self, xs, batch_size=1024):
781
- """
782
- Map cells to metacells and return the assigned metacell identities.
783
- """
784
- xs = self.preprocess(xs)
785
- xs = convert_to_tensor(xs, device=self.get_device())
786
- dataset = CustomDataset(xs)
787
- dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=False)
788
-
789
- A = []
790
- with tqdm(total=len(dataloader), desc='', unit='batch') as pbar:
791
- for X_batch, _ in dataloader:
792
- a = self._hard_assignments(X_batch)
793
- A.append(tensor_to_numpy(a))
794
- pbar.update(1)
795
-
796
- A = np.concatenate(A)
797
- return A
798
-
799
- def preprocess(self, xs, threshold=0):
800
- if self.loss_func == 'bernoulli':
801
- ad = sc.AnnData(xs)
802
- binarize(ad, threshold=threshold)
803
- xs = ad.X.copy()
804
- else:
805
- xs = np.round(xs)
806
-
807
- if sparse.issparse(xs):
808
- xs = xs.toarray()
809
- return xs
810
-
811
- def fit(self, xs,
812
- us = None,
813
- ys = None,
814
- zs = None,
815
- num_epochs: int = 200,
816
- learning_rate: float = 0.0001,
817
- batch_size: int = 256,
818
- algo: Literal['adam','rmsprop','adamw'] = 'adam',
819
- beta_1: float = 0.9,
820
- weight_decay: float = 0.005,
821
- decay_rate: float = 0.9,
822
- config_enum: str = 'parallel',
823
- threshold: int = 0,
824
- use_jax: bool = False):
825
- """
826
- Train the SURE model.
827
-
828
- Parameters
829
- ----------
830
- xs
831
- Single-cell experssion matrix. It should be a Numpy array or a Pytorch Tensor. Rows are cells and columns are features.
832
- us
833
- cell-level factor matrix.
834
- ys
835
- Desired factor matrix. It should be a Numpy array or a Pytorch Tensor. Rows are cells and columns are desired factors.
836
- num_epochs
837
- Number of training epochs.
838
- learning_rate
839
- Parameter for training.
840
- batch_size
841
- Size of batch processing.
842
- algo
843
- Optimization algorithm.
844
- beta_1
845
- Parameter for optimization.
846
- weight_decay
847
- Parameter for optimization.
848
- decay_rate
849
- Parameter for optimization.
850
- use_jax
851
- If toggled on, Jax will be used for speeding up. CAUTION: This will raise errors because of unknown reasons when it is called in
852
- the Python script or Jupyter notebook. It is OK if it is used when runing SURE in the shell command.
853
- """
854
- xs = self.preprocess(xs, threshold=threshold)
855
- xs = convert_to_tensor(xs, dtype=self.dtype, device=self.get_device())
856
- if us is not None:
857
- us = convert_to_tensor(us, dtype=self.dtype, device=self.get_device())
858
- if ys is not None:
859
- ys = convert_to_tensor(ys, dtype=self.dtype, device=self.get_device())
860
- if zs is not None:
861
- zs = convert_to_tensor(zs, dtype=self.dtype, device=self.get_device())
862
-
863
- dataset = CustomDataset4(xs, us, ys, zs)
864
- dataloader = DataLoader(dataset, batch_size=batch_size, shuffle=True)
865
-
866
- # setup the optimizer
867
- optim_params = {'lr': learning_rate, 'betas': (beta_1, 0.999), 'weight_decay': weight_decay}
868
-
869
- if algo.lower()=='rmsprop':
870
- optimizer = torch.optim.RMSprop
871
- elif algo.lower()=='adam':
872
- optimizer = torch.optim.Adam
873
- elif algo.lower() == 'adamw':
874
- optimizer = torch.optim.AdamW
875
- else:
876
- raise ValueError("An optimization algorithm must be specified.")
877
- scheduler = ExponentialLR({'optimizer': optimizer, 'optim_args': optim_params, 'gamma': decay_rate})
878
-
879
- pyro.clear_param_store()
880
-
881
- # set up the loss(es) for inference, wrapping the guide in config_enumerate builds the loss as a sum
882
- # by enumerating each class label form the sampled discrete categorical distribution in the model
883
- Elbo = JitTraceEnum_ELBO if use_jax else TraceEnum_ELBO
884
- elbo = Elbo(max_plate_nesting=1, strict_enumeration_warning=False)
885
- if us is None:
886
- if ys is None:
887
- guide = config_enumerate(self.guide1, config_enum, expand=True)
888
- loss_basic = SVI(self.model1, guide, scheduler, loss=elbo)
889
- else:
890
- guide = config_enumerate(self.guide3, config_enum, expand=True)
891
- loss_basic = SVI(self.model3, guide, scheduler, loss=elbo)
892
- else:
893
- if ys is None:
894
- guide = config_enumerate(self.guide2, config_enum, expand=True)
895
- loss_basic = SVI(self.model2, guide, scheduler, loss=elbo)
896
- else:
897
- guide = config_enumerate(self.guide4, config_enum, expand=True)
898
- loss_basic = SVI(self.model4, guide, scheduler, loss=elbo)
899
-
900
- # build a list of all losses considered
901
- losses = [loss_basic]
902
- num_losses = len(losses)
903
-
904
- with tqdm(total=num_epochs, desc='Training', unit='epoch') as pbar:
905
- for epoch in range(num_epochs):
906
- epoch_losses = [0.0] * num_losses
907
- for batch_x, batch_u, batch_y, batch_z, _ in dataloader:
908
- if us is None:
909
- batch_u = None
910
- if ys is None:
911
- batch_y = None
912
- if zs is None:
913
- batch_z = None
914
-
915
- for loss_id in range(num_losses):
916
- if batch_u is None:
917
- if batch_y is None:
918
- new_loss = losses[loss_id].step(batch_x)
919
- else:
920
- new_loss = losses[loss_id].step(batch_x, batch_y, batch_z)
921
- else:
922
- if batch_y is None:
923
- new_loss = losses[loss_id].step(batch_x, batch_u)
924
- else:
925
- new_loss = losses[loss_id].step(batch_x, batch_u, batch_y, batch_z)
926
- epoch_losses[loss_id] += new_loss
927
-
928
- avg_epoch_losses_ = map(lambda v: v / len(dataloader), epoch_losses)
929
- avg_epoch_losses = map(lambda v: "{:.4f}".format(v), avg_epoch_losses_)
930
-
931
- # store the loss
932
- str_loss = " ".join(map(str, avg_epoch_losses))
933
-
934
- # Update progress bar
935
- pbar.set_postfix({'loss': str_loss})
936
- pbar.update(1)
937
-
938
- @classmethod
939
- def save_model(cls, model, file_path, compression=False):
940
- """Save the model to the specified file path."""
941
- file_path = os.path.abspath(file_path)
942
-
943
- model.eval()
944
- if compression:
945
- with gzip.open(file_path, 'wb') as pickle_file:
946
- pickle.dump(model, pickle_file)
947
- else:
948
- with open(file_path, 'wb') as pickle_file:
949
- pickle.dump(model, pickle_file)
950
-
951
- print(f'Model saved to {file_path}')
952
-
953
- @classmethod
954
- def load_model(cls, file_path):
955
- """Load the model from the specified file path and return an instance."""
956
- print(f'Model loaded from {file_path}')
957
-
958
- file_path = os.path.abspath(file_path)
959
- if file_path.endswith('gz'):
960
- with gzip.open(file_path, 'rb') as pickle_file:
961
- model = pickle.load(pickle_file)
962
- else:
963
- with open(file_path, 'rb') as pickle_file:
964
- model = pickle.load(pickle_file)
965
-
966
- return model
967
-
968
-
969
- EXAMPLE_RUN = (
970
- "example run: SURE --help"
971
- )
972
-
973
- def parse_args():
974
- parser = argparse.ArgumentParser(
975
- description="SURE\n{}".format(EXAMPLE_RUN))
976
-
977
- parser.add_argument(
978
- "--cuda", action="store_true", help="use GPU(s) to speed up training"
979
- )
980
- parser.add_argument(
981
- "--jit", action="store_true", help="use PyTorch jit to speed up training"
982
- )
983
- parser.add_argument(
984
- "-n", "--num-epochs", default=200, type=int, help="number of epochs to run"
985
- )
986
- parser.add_argument(
987
- "-enum",
988
- "--enum-discrete",
989
- default="parallel",
990
- help="parallel, sequential or none. uses parallel enumeration by default",
991
- )
992
- parser.add_argument(
993
- "-data",
994
- "--data-file",
995
- default=None,
996
- type=str,
997
- help="the data file",
998
- )
999
- parser.add_argument(
1000
- "-cf",
1001
- "--cell-factor-file",
1002
- default=None,
1003
- type=str,
1004
- help="the file for the record of cell-level factors",
1005
- )
1006
- parser.add_argument(
1007
- "-delta",
1008
- "--delta",
1009
- default=0.0,
1010
- type=float,
1011
- help="penalty weight for zero inflation loss",
1012
- )
1013
- parser.add_argument(
1014
- "-64",
1015
- "--float64",
1016
- action="store_true",
1017
- help="use double float precision",
1018
- )
1019
- parser.add_argument(
1020
- "--z-dist",
1021
- default='normal',
1022
- type=str,
1023
- choices=['normal','laplacian','studentt','cauchy'],
1024
- help="distribution model for latent representation",
1025
- )
1026
- parser.add_argument(
1027
- "-cs",
1028
- "--codebook-size",
1029
- default=100,
1030
- type=int,
1031
- help="size of vector quantization codebook",
1032
- )
1033
- parser.add_argument(
1034
- "-zd",
1035
- "--z-dim",
1036
- default=10,
1037
- type=int,
1038
- help="size of the tensor representing the latent variable z variable",
1039
- )
1040
- parser.add_argument(
1041
- "-hl",
1042
- "--hidden-layers",
1043
- nargs="+",
1044
- default=[500],
1045
- type=int,
1046
- help="a tuple (or list) of MLP layers to be used in the neural networks "
1047
- "representing the parameters of the distributions in our model",
1048
- )
1049
- parser.add_argument(
1050
- "-hla",
1051
- "--hidden-layer-activation",
1052
- default='relu',
1053
- type=str,
1054
- choices=['relu','softplus','leakyrelu','linear'],
1055
- help="activation function for hidden layers",
1056
- )
1057
- parser.add_argument(
1058
- "-plf",
1059
- "--post-layer-function",
1060
- nargs="+",
1061
- default=['layernorm'],
1062
- type=str,
1063
- help="post functions for hidden layers, could be none, dropout, layernorm, batchnorm, or combination, default is 'dropout layernorm'",
1064
- )
1065
- parser.add_argument(
1066
- "-paf",
1067
- "--post-activation-function",
1068
- nargs="+",
1069
- default=['none'],
1070
- type=str,
1071
- help="post functions for activation layers, could be none or dropout, default is 'none'",
1072
- )
1073
- parser.add_argument(
1074
- "-id",
1075
- "--inverse-dispersion",
1076
- default=10.0,
1077
- type=float,
1078
- help="inverse dispersion prior for negative binomial",
1079
- )
1080
- parser.add_argument(
1081
- "-lr",
1082
- "--learning-rate",
1083
- default=0.0001,
1084
- type=float,
1085
- help="learning rate for Adam optimizer",
1086
- )
1087
- parser.add_argument(
1088
- "-dr",
1089
- "--decay-rate",
1090
- default=0.9,
1091
- type=float,
1092
- help="decay rate for Adam optimizer",
1093
- )
1094
- parser.add_argument(
1095
- "--layer-dropout-rate",
1096
- default=0.1,
1097
- type=float,
1098
- help="droput rate for neural networks",
1099
- )
1100
- parser.add_argument(
1101
- "-b1",
1102
- "--beta-1",
1103
- default=0.95,
1104
- type=float,
1105
- help="beta-1 parameter for Adam optimizer",
1106
- )
1107
- parser.add_argument(
1108
- "-bs",
1109
- "--batch-size",
1110
- default=1000,
1111
- type=int,
1112
- help="number of cells to be considered in a batch",
1113
- )
1114
- parser.add_argument(
1115
- "-gp",
1116
- "--gate-prior",
1117
- default=0.6,
1118
- type=float,
1119
- help="gate prior for zero-inflated model",
1120
- )
1121
- parser.add_argument(
1122
- "-likeli",
1123
- "--likelihood",
1124
- default='negbinomial',
1125
- type=str,
1126
- choices=['negbinomial', 'multinomial', 'poisson', 'gaussian','lognormal'],
1127
- help="specify the distribution likelihood function",
1128
- )
1129
- parser.add_argument(
1130
- "-dirichlet",
1131
- "--use-dirichlet",
1132
- action="store_true",
1133
- help="use Dirichlet distribution over gene frequency",
1134
- )
1135
- parser.add_argument(
1136
- "-mass",
1137
- "--dirichlet-mass",
1138
- default=1,
1139
- type=float,
1140
- help="mass param for dirichlet model",
1141
- )
1142
- parser.add_argument(
1143
- "-zi",
1144
- "--zero-inflation",
1145
- default='exact',
1146
- type=str,
1147
- choices=['none','exact','inexact'],
1148
- help="use zero-inflated estimation",
1149
- )
1150
- parser.add_argument(
1151
- "--seed",
1152
- default=None,
1153
- type=int,
1154
- help="seed for controlling randomness in this example",
1155
- )
1156
- parser.add_argument(
1157
- "--save-model",
1158
- default=None,
1159
- type=str,
1160
- help="path to save model for prediction",
1161
- )
1162
- args = parser.parse_args()
1163
- return args
1164
-
1165
- def main():
1166
- args = parse_args()
1167
- assert (
1168
- (args.data_file is not None) and (
1169
- os.path.exists(args.data_file))
1170
- ), "data file must be provided"
1171
-
1172
- if args.seed is not None:
1173
- set_random_seed(args.seed)
1174
-
1175
- if args.float64:
1176
- dtype = torch.float64
1177
- torch.set_default_dtype(torch.float64)
1178
- else:
1179
- dtype = torch.float32
1180
- torch.set_default_dtype(torch.float32)
1181
-
1182
- xs = dt.fread(file=args.data_file, header=True).to_numpy()
1183
- us = None
1184
- if args.cell_factor_file is not None:
1185
- us = dt.fread(file=args.cell_factor_file, header=True).to_numpy()
1186
-
1187
- input_size = xs.shape[1]
1188
- cell_factor_size = 0 if us is None else us.shape[1]
1189
-
1190
- latent_dist = args.z_dist
1191
-
1192
- ###########################################
1193
- sure = SURE2(
1194
- input_size=input_size,
1195
- cell_factor_size=cell_factor_size,
1196
- inverse_dispersion=args.inverse_dispersion,
1197
- latent_dim=args.latent_dim,
1198
- hidden_layers=args.hidden_layers,
1199
- hidden_layer_activation=args.hidden_layer_activation,
1200
- use_cuda=args.cuda,
1201
- config_enum=args.enum_discrete,
1202
- use_dirichlet=args.use_dirichlet,
1203
- zero_inflation=args.zero_inflation,
1204
- gate_prior=args.gate_prior,
1205
- delta=args.delta,
1206
- loss_func=args.likelihood,
1207
- dirichlet_mass=args.dirichlet_mass,
1208
- nn_dropout=args.layer_dropout_rate,
1209
- post_layer_fct=args.post_layer_function,
1210
- post_act_fct=args.post_activation_function,
1211
- codebook_size=args.codebook_size,
1212
- latent_dist = latent_dist,
1213
- dtype=dtype,
1214
- )
1215
-
1216
- sure.fit(xs, us=us,
1217
- num_epochs=args.num_epochs,
1218
- learning_rate=args.learning_rate,
1219
- batch_size=args.batch_size,
1220
- beta_1=args.beta_1,
1221
- decay_rate=args.decay_rate,
1222
- use_jax=args.jit,
1223
- config_enum=args.enum_discrete,
1224
- )
1225
-
1226
- if args.save_model is not None:
1227
- if args.save_model.endswith('gz'):
1228
- SURE2.save_model(sure, args.save_model, compression=True)
1229
- else:
1230
- SURE2.save_model(sure, args.save_model)
1231
-
1232
-
1233
-
1234
- if __name__ == "__main__":
1235
-
1236
- main()
SURE/flow/quiver.py DELETED
@@ -1,52 +0,0 @@
1
- import numpy as np
2
- import matplotlib.pyplot as plt
3
- from sklearn.decomposition import PCA
4
- import scanpy as sc
5
-
6
- def plot_quiver_high_dim(z_points, delta_z, method='umap', figsize=(6,4), dpi=200):
7
- """
8
- 从高维潜在空间选择2个维度进行quiver可视化
9
- """
10
- if method == 'variance':
11
- # 方法1: 选择方差最大的2个维度
12
- variances = np.var(z_points, axis=0)
13
- dims = np.argsort(variances)[-2:] # 选择方差最大的两个维度
14
- dim_names = [f'z[{d}]' for d in dims]
15
-
16
- elif method == 'pca':
17
- # 方法2: 使用PCA的前两个主成分
18
- pca = PCA(n_components=2)
19
- z_2d = pca.fit_transform(z_points)
20
- delta_z_2d = pca.transform(z_points + delta_z) - z_2d
21
- dim_names = ['PC1', 'PC2']
22
-
23
- elif method == 'manual':
24
- # 方法3: 手动选择感兴趣的维度
25
- dims = [0, 1] # 选择前两个维度
26
- z_2d = z_points[:, dims]
27
- delta_z_2d = delta_z[:, dims]
28
- dim_names = [f'z[{d}]' for d in dims]
29
-
30
- elif method == 'umap':
31
- ad = sc.AnnData(np.vstack([z_points, z_points+delta_z]))
32
- sc.pp.neighbors(ad)
33
- sc.tl.umap(ad)
34
- z_2d = ad[:z_points.shape[0]].obsm['X_umap']
35
- delta_z_2d = ad[z_points.shape[0]:] - z_2d
36
- dim_names = ['UMAP1', 'UMAP2']
37
-
38
- # 绘制quiver图
39
- plt.figure(figsize=figsize, dpi=dpi)
40
- plt.quiver(z_2d[:, 0], z_2d[:, 1],
41
- delta_z_2d[:, 0], delta_z_2d[:, 1],
42
- angles='xy', scale_units='xy', scale=1,
43
- color='blue', alpha=0.6, width=0.005)
44
-
45
- plt.scatter(z_2d[:, 0], z_2d[:, 1], c='gray', alpha=0.5, s=10)
46
- plt.xlabel(dim_names[0])
47
- plt.ylabel(dim_names[1])
48
- plt.title(f"Latent Space Movement ({method} projection)")
49
- plt.grid(alpha=0.3)
50
- plt.show()
51
-
52
- return z_2d, delta_z_2d