scVAEIT 1.0.0__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.
scVAEIT/VAEIT.py ADDED
@@ -0,0 +1,392 @@
1
+ import warnings
2
+ from typing import Optional, Union
3
+ from types import SimpleNamespace
4
+
5
+ import tensorflow as tf
6
+
7
+ import scVAEIT.model as model
8
+ import scVAEIT.train as train
9
+ from scVAEIT.utils import check_arr_type
10
+
11
+ from sklearn.preprocessing import OneHotEncoder, StandardScaler
12
+ from sklearn.preprocessing import OrdinalEncoder
13
+
14
+ from sklearn.model_selection import train_test_split
15
+ import numpy as np
16
+
17
+ import scanpy as sc
18
+
19
+
20
+
21
+ class VAEIT():
22
+ """
23
+ Variational Inference for integration and transfer learning.
24
+ """
25
+ def __init__(self, config: SimpleNamespace, data, masks, id_dataset=None, batches_cate=None, batches_cont=None, conditions=None
26
+ ):
27
+ '''
28
+ Initialize the VAEIT model with the provided configuration and data.
29
+
30
+ Parameters
31
+ ----------
32
+ config : SimpleNamespace
33
+ Configuration object containing model parameters.
34
+ data : np.array
35
+ The cell-by-feature matrix representing the input data.
36
+ masks : np.array
37
+ Masks indicating missingness, where 1 represents missing and 0 represents observed.
38
+ This can be a full mask matrix with the same shape as `data`, or a condensed matrix indexed by `id_dataset`.
39
+ id_dataset : np.array, optional
40
+ Integer IDs for each cell in the dataset. Required if `masks` is a condensed matrix.
41
+ batches_cate : np.array, optional
42
+ Categorical batch information for each cell.
43
+ batches_cont : np.array, optional
44
+ Continuous batch information for each cell.
45
+ conditions : np.array, optional
46
+ Conditions for each cell, used for calculating MMD loss if `config.gamma` is not 0.
47
+
48
+ Returns
49
+ -------
50
+ None
51
+ '''
52
+ self.dict_method_scname = {
53
+ 'PCA' : 'X_pca',
54
+ 'UMAP' : 'X_umap',
55
+ 'TSNE' : 'X_tsne',
56
+ 'diffmap' : 'X_diffmap',
57
+ 'draw_graph' : 'X_draw_graph_fa'
58
+ }
59
+
60
+ self.data = tf.convert_to_tensor(data, dtype=tf.keras.backend.floatx())
61
+
62
+ # prprocessing config
63
+ if 'dim_input_arr' not in config:
64
+ config['dim_input_arr'] = data.shape[1]
65
+ if np.isscalar(config['dim_input_arr']):
66
+ config['dim_input_arr'] = np.array([config['dim_input_arr']], dtype=np.int32)
67
+ n_modal = len(config['dim_input_arr'])
68
+ n_block = len(config['dim_block']) if 'dim_block' in config else n_modal
69
+
70
+
71
+ config = dict(filter(lambda item: item[1] is not None, config.items()))
72
+
73
+
74
+ config = {**{
75
+ 'beta_kl':2., # weight for beta-VAE
76
+ 'beta_reverse':0., # weight for reverse prediction (use masked out features to predict the observed features)
77
+ 'beta_modal':np.ones(n_modal, dtype=np.float32), # weight for each modality
78
+ 'p_modal':None,
79
+
80
+ 'uni_block_names':np.char.add(np.repeat('M-', n_modal), np.arange(n_modal).astype(str)),
81
+ 'block_names':np.char.add(np.repeat('M-', n_block), np.arange(n_block).astype(str)),
82
+ 'dist_block':np.repeat('NB', n_block),
83
+ 'dim_block':np.array(config['dim_input_arr'], dtype=np.int32),
84
+ 'dim_block_enc':np.zeros(n_block, dtype=np.int32),
85
+ 'dim_block_dec':np.zeros(n_block, dtype=np.int32),
86
+
87
+
88
+ 'skip_conn':False, # whether to use skip connection in decoder
89
+ 'max_vals':None,
90
+
91
+ 'gamma':0.
92
+ }, **config}
93
+
94
+ if isinstance(config, dict):
95
+ config = SimpleNamespace(**config)
96
+
97
+
98
+ config.dimensions = check_arr_type(config.dimensions, np.int32)
99
+ config.dist_block = check_arr_type(config.dist_block, str)
100
+
101
+ if np.isscalar(config.dim_block_embed):
102
+ config.dim_block_embed = np.full(n_block, config.dim_block_embed, dtype=np.int32)
103
+ config.dim_block_enc = check_arr_type(config.dim_block_enc, np.int32)
104
+ config.dim_block_dec = check_arr_type(config.dim_block_dec, np.int32)
105
+
106
+
107
+ # preprocess batch
108
+ self.batches = np.array([], dtype=np.float32).reshape((data.shape[0],0))
109
+ if batches_cate is not None:
110
+ batches_cate = np.array(batches_cate)
111
+ self.cat_enc = OneHotEncoder(drop='first').fit(batches_cate)
112
+ self.batches = self.cat_enc.transform(batches_cate).toarray()
113
+ if batches_cont is not None:
114
+ self.cont_enc = StandardScaler()
115
+ batches_cont = self.cont_enc.fit_transform(batches_cont)
116
+ batches_cont = np.nan_to_num(batches_cont)
117
+ batches_cont = np.array(batches_cont, dtype=np.float32)
118
+ self.batches = np.c_[self.batches, batches_cont]
119
+ self.batches = tf.convert_to_tensor(self.batches, dtype=tf.keras.backend.floatx())
120
+
121
+ if conditions is not None and config.gamma != 0.:
122
+ ## observations with np.nan will not participant in calculating mmd_loss
123
+ conditions = np.array(conditions)
124
+ if len(conditions.shape)<2:
125
+ conditions = conditions[:,None]
126
+ self.conditions = OrdinalEncoder(dtype=int, encoded_missing_value=-1).fit_transform(conditions) + int(1)
127
+
128
+ else:
129
+ config.gamma = 0.
130
+ self.conditions = np.zeros((data.shape[0],1), dtype=np.int32)
131
+ self.conditions = tf.cast(self.conditions, tf.int32)
132
+
133
+
134
+
135
+ # [num_cells, num_features]
136
+ self.masks = tf.convert_to_tensor(masks, dtype=tf.keras.backend.floatx())
137
+
138
+ if self.masks.shape==self.data.shape:
139
+ self.id_dataset = self.masks
140
+ self.full_masks = True
141
+ else:
142
+ self.id_dataset = tf.convert_to_tensor(id_dataset, dtype=tf.int32)
143
+ self.full_masks = False
144
+
145
+ if config.max_vals is None:
146
+ segment_ids = np.repeat(np.arange(n_block), config.dim_block)
147
+ config.max_vals = np.zeros(segment_ids.max()+1)
148
+ np.maximum.at(config.max_vals, segment_ids, np.max(data,axis=0))
149
+ for i, dist in enumerate(config.dist_block):
150
+ if dist != 'NB':
151
+ config.max_vals[i] = tf.constant(float('nan'))
152
+ elif np.isscalar(config.max_vals):
153
+ config.max_vals = tf.constant(config.max_vals, shape=n_block, dtype=tf.keras.backend.floatx())
154
+ config.max_vals = tf.convert_to_tensor(config.max_vals, dtype=tf.keras.backend.floatx())
155
+
156
+ self.batch_size_inference = 512
157
+ self.config = config
158
+ self.reset()
159
+ print(self.config, self.masks.shape, self.data.shape, self.batches.shape, flush = True)
160
+
161
+
162
+ def reset(self):
163
+ train.clear_session()
164
+ if hasattr(self, 'vae'):
165
+ del self.vae
166
+ import gc
167
+ gc.collect()
168
+ self.vae = model.VariationalAutoEncoder(self.config, self.masks)
169
+
170
+
171
+ def train(self, valid = False, stratify = False, test_size = 0.1, random_state: int = 0,
172
+ learning_rate: float = 1e-3, batch_size: Optional[int] = None, batch_size_inference: Optional[int] = None,
173
+ L: int = 1, num_epoch: int = 200, num_step_per_epoch: Optional[int] = None, save_every_epoch: Optional[int] = 25, init_epoch: Optional[int] = 1,
174
+ early_stopping_patience: int = 10, early_stopping_tolerance: float = 1e-4,
175
+ early_stopping_relative: bool = True, verbose: bool = False,
176
+ checkpoint_dir: Optional[str] = None, delete_existing: Optional[str] = True, eval_func = None):
177
+ '''
178
+ Train the VAEIT model with the specified parameters.
179
+
180
+ Parameters
181
+ ----------
182
+ valid : bool, optional
183
+ Whether to use a validation set during training. Default is False.
184
+ stratify : bool, optional
185
+ Whether to stratify the split when creating the validation set. Default is False.
186
+ test_size : float or int, optional
187
+ The proportion or size of the validation set. Default is 0.1.
188
+ random_state : int, optional
189
+ The random state for data splitting. Default is 0.
190
+ learning_rate : float, optional
191
+ The initial learning rate for the Adam optimizer. Default is 1e-3.
192
+ batch_size : int, optional
193
+ The batch size for training. Default is 256 when using full mask matrices, or 64 otherwise.
194
+ batch_size_inference : int, optional
195
+ The batch size for inference. Default is 256 when using full mask matrices, or 64 otherwise.
196
+ L : int, optional
197
+ The number of Monte Carlo samples. Default is 1.
198
+ num_epoch : int, optional
199
+ The maximum number of epochs. Default is 200.
200
+ num_step_per_epoch : int, optional
201
+ The number of steps per epoch. If None, it will be inferred from the number of cells and batch size. Default is None.
202
+ save_every_epoch : int, optional
203
+ Frequency (in epochs) to save model checkpoints. Default is 25.
204
+ init_epoch : int, optional
205
+ The initial epoch number. Default is 1.
206
+ early_stopping_patience : int, optional
207
+ The number of epochs to wait for improvement before early stopping. Default is 10.
208
+ early_stopping_tolerance : float, optional
209
+ The minimum change in loss to be considered as an improvement. Default is 1e-4.
210
+ early_stopping_relative : bool, optional
211
+ Whether to monitor the relative change in loss for early stopping. Default is True.
212
+ verbose : bool, optional
213
+ Whether to print the training process. Default is False.
214
+ checkpoint_dir : str, optional
215
+ Directory to save model checkpoints. Default is None.
216
+ delete_existing : bool, optional
217
+ Whether to delete existing checkpoints in the directory. Default is True.
218
+ eval_func : function, optional
219
+ A function to evaluate the model, which takes the VAE as an input. Default is None.
220
+
221
+ Returns
222
+ -------
223
+ hist : dict
224
+ A dictionary containing the history of training and validation losses.
225
+ '''
226
+
227
+ if batch_size is None:
228
+ batch_size = 256 if self.full_masks else 64
229
+ if batch_size_inference is None:
230
+ batch_size_inference = batch_size
231
+
232
+ if valid:
233
+ if stratify is False:
234
+ stratify = None
235
+
236
+ id_train, id_valid = train_test_split(
237
+ np.arange(self.data.shape[0]),
238
+ test_size=test_size,
239
+ stratify=stratify,
240
+ random_state=random_state)
241
+
242
+ self.dataset_train = tf.data.Dataset.from_tensor_slices((
243
+ self.data[id_train], self.batches[id_train], self.id_dataset[id_train], self.conditions[id_train]
244
+ )).shuffle(buffer_size = len(id_train), seed=0,
245
+ reshuffle_each_iteration=True).batch(batch_size, drop_remainder=True).prefetch(tf.data.experimental.AUTOTUNE)
246
+
247
+ self.dataset_valid = tf.data.Dataset.from_tensor_slices((
248
+ self.data[id_valid], self.batches[id_valid], self.id_dataset[id_valid], self.conditions[id_valid]
249
+ )).batch(batch_size_inference).prefetch(tf.data.experimental.AUTOTUNE)
250
+ else:
251
+ id_train = np.arange(self.data.shape[0])
252
+ self.dataset_train = tf.data.Dataset.from_tensor_slices((
253
+ self.data, self.batches, self.id_dataset, self.conditions
254
+ )).shuffle(buffer_size = len(id_train), seed=0,
255
+ reshuffle_each_iteration=True).batch(batch_size, drop_remainder=True).prefetch(tf.data.experimental.AUTOTUNE)
256
+ self.dataset_valid = None
257
+
258
+ if num_step_per_epoch is None:
259
+ num_step_per_epoch = len(id_train)//batch_size
260
+
261
+ if checkpoint_dir is not None:
262
+ if init_epoch==1 and delete_existing and tf.io.gfile.exists(checkpoint_dir):
263
+ print("Deleting old log directory at {}".format(checkpoint_dir))
264
+ tf.io.gfile.rmtree(checkpoint_dir)
265
+ tf.io.gfile.makedirs(checkpoint_dir)
266
+
267
+ self.vae, hist = train.train(
268
+ self.dataset_train,
269
+ self.dataset_valid,
270
+ self.vae,
271
+ checkpoint_dir,
272
+ learning_rate,
273
+ int(L),
274
+ int(num_epoch),
275
+ int(num_step_per_epoch),
276
+ int(save_every_epoch),
277
+ init_epoch,
278
+ early_stopping_patience,
279
+ early_stopping_tolerance,
280
+ early_stopping_relative,
281
+ self.full_masks,
282
+ verbose,
283
+ eval_func
284
+ )
285
+ return hist
286
+
287
+
288
+ def save_model(self, path_to_weights):
289
+ checkpoint = tf.train.Checkpoint(net=self.vae)
290
+ manager = tf.train.CheckpointManager(
291
+ checkpoint, path_to_weights, max_to_keep=None
292
+ )
293
+ save_path = manager.save()
294
+ print("Saved checkpoint: {}".format(save_path), flush = True)
295
+
296
+
297
+ def load_model(self, path_to_weights):
298
+ checkpoint = tf.train.Checkpoint(net=self.vae)
299
+ status = checkpoint.restore(path_to_weights)
300
+ print("Loaded checkpoint: {}".format(status), flush = True)
301
+
302
+
303
+ def set_dataset(self, batch_size_inference=512):
304
+ if not hasattr(self, 'dataset_full') or batch_size_inference != self.batch_size_inference:
305
+ id_samples = np.arange(self.data.shape[0])
306
+ self.dataset_full = tf.data.Dataset.from_tensor_slices((
307
+ self.data, self.batches, self.id_dataset, tf.constant(id_samples)
308
+ )).shuffle(
309
+ buffer_size = len(id_samples), seed=0,
310
+ reshuffle_each_iteration=True
311
+ ).batch(batch_size_inference).prefetch(tf.data.experimental.AUTOTUNE)
312
+ self.batch_size_inference = batch_size_inference
313
+
314
+
315
+ def get_latent_z(self, masks=None, zero_out=True, batch_size_inference=512):
316
+ ''' get the posterier mean of current latent space z (encoder output)
317
+
318
+ Returns
319
+ ----------
320
+ z : np.array
321
+ \([N,d]\) The latent means.
322
+ '''
323
+ self.set_dataset(batch_size_inference)
324
+ return self.vae.get_z(self.dataset_full, self.full_masks, masks, zero_out)
325
+
326
+
327
+ def get_denoised_data(self, masks=None, zero_out=True, batch_size_inference=256, return_mean=True, L=50):
328
+ self.set_dataset(batch_size_inference)
329
+
330
+ return self.vae.get_recon(self.dataset_full, self.full_masks, masks, zero_out, return_mean, L)
331
+
332
+
333
+ def update_z(self, masks=None, zero_out=True, batch_size_inference=512, **kwargs):
334
+ self.z = self.get_latent_z(masks, zero_out, batch_size_inference)
335
+ self.adata = sc.AnnData(self.z)
336
+ sc.pp.neighbors(self.adata, **kwargs)
337
+
338
+
339
+ def visualize_latent(self, method: str = "UMAP",
340
+ color = None, **kwargs):
341
+ '''
342
+ visualize the current latent space z using the scanpy visualization tools
343
+
344
+ Parameters
345
+ ----------
346
+ method : str, optional
347
+ Visualization method to use. The default is "draw_graph" (the FA plot). Possible choices include "PCA", "UMAP",
348
+ "diffmap", "TSNE" and "draw_graph"
349
+ color : TYPE, optional
350
+ Keys for annotations of observations/cells or variables/genes, e.g., 'ann1' or ['ann1', 'ann2'].
351
+ The default is None. Same as scanpy.
352
+ **kwargs :
353
+ Extra key-value arguments that can be passed to scanpy plotting functions (scanpy.pl.XX).
354
+
355
+ Returns
356
+ -------
357
+ None.
358
+
359
+ '''
360
+
361
+ if method not in ['PCA', 'UMAP', 'TSNE', 'diffmap', 'draw_graph']:
362
+ raise ValueError("visualization method should be one of 'PCA', 'UMAP', 'TSNE', 'diffmap' and 'draw_graph'")
363
+
364
+ temp = list(self.adata.obsm.keys())
365
+ if method == 'PCA' and not 'X_pca' in temp:
366
+ print("Calculate PCs ...")
367
+ sc.tl.pca(self.adata)
368
+ elif method == 'UMAP' and not 'X_umap' in temp:
369
+ print("Calculate UMAP ...")
370
+ sc.tl.umap(self.adata)
371
+ elif method == 'TSNE' and not 'X_tsne' in temp:
372
+ print("Calculate TSNE ...")
373
+ sc.tl.tsne(self.adata)
374
+ elif method == 'diffmap' and not 'X_diffmap' in temp:
375
+ print("Calculate diffusion map ...")
376
+ sc.tl.diffmap(self.adata)
377
+ elif method == 'draw_graph' and not 'X_draw_graph_fa' in temp:
378
+ print("Calculate FA ...")
379
+ sc.tl.draw_graph(self.adata)
380
+
381
+ if method == 'PCA':
382
+ axes = sc.pl.pca(self.adata, color = color, **kwargs)
383
+ elif method == 'UMAP':
384
+ axes = sc.pl.umap(self.adata, color = color, **kwargs)
385
+ elif method == 'TSNE':
386
+ axes = sc.pl.tsne(self.adata, color = color, **kwargs)
387
+ elif method == 'diffmap':
388
+ axes = sc.pl.diffmap(self.adata, color = color, **kwargs)
389
+ elif method == 'draw_graph':
390
+ axes = sc.pl.draw_graph(self.adata, color = color, **kwargs)
391
+
392
+ return axes
scVAEIT/__init__.py ADDED
@@ -0,0 +1,13 @@
1
+ __all__ = ['VAEIT', 'reset_random_seeds']
2
+
3
+ from scVAEIT.VAEIT import VAEIT
4
+ from scVAEIT.utils import reset_random_seeds
5
+
6
+ __author__ = "Jin-Hong Du"
7
+ __copyright__ = "Copyright 2024, The Cross-Modalilty Transfer Learning Project"
8
+
9
+ __license__ = "MIT"
10
+ __version__ = "1.0.0"
11
+ __maintainer__ = "Jin-Hong Du"
12
+ __email__ = "jinhongd@andrew.cmu.edu"
13
+ __status__ = "Development"