OSCR

PVAED: prior-guided variational autoencoders with diffusion denoising for interpretable single-cell representation learning.

Code ↔ Paper

6 matches between paragraphs of the paper and lines of its authors' code, computed by the harvester (lexical-v1). Click a colored paragraph or line to see its counterpart.

3 blocks of code here have a permanent identifier (oscr:b:…), listed with the matches below: citable for good, with a page of its own. Select a match and press Cite to copy it. What a block identifier is.

The 6 matches
  1. [1] § Materials and methods › Clustering metrics ↔ PVAED/down_stream.ipynb, lines 31 to 48 · score 0.84 · Adjusted Mutual, Adjusted Rand, Normalized Mutual, AMI, Homogeneity, ARI · Report a mismatch
  2. [2] § Materials and methods › PVAED loss function ↔ PVAED/main.py, lines 142 to 182 · score 0.64 · KL divergence, reconstruction loss, neighbors, trustworthiness · block oscr:b:1377122Z2VP6K-T · Report a mismatch
  3. [3] § Materials and methods › PVAED loss function ↔ PVAED/main_joint_fine_tunning.py, lines 161 to 185 · score 0.64 · KL divergence, reconstruction loss, neighbors, trustworthiness · block oscr:b:BCRAJHBV8VRKF-F · Report a mismatch
  4. [4] § Materials and methods › PVAED loss function ↔ PVAED/main.py, lines 142 to 182 · score 0.63 · reconstruction loss, loss function, Gaussian, KL, divergence, Trustworthiness · block oscr:b:1377122Z2VP6K-T · Report a mismatch
  5. [5] § Materials and methods › PVAED loss function ↔ PVAED/main_joint_fine_tunning.py, lines 161 to 185 · score 0.63 · reconstruction loss, loss function, Gaussian, KL, divergence, Trustworthiness · block oscr:b:BCRAJHBV8VRKF-F · Report a mismatch
  6. [6] § Materials and methods › Prior knowledge informed architectural design of PVAED ↔ PVAED/main_joint_fine_tunning.py, lines 38 to 70 · score 0.58 · joint fine tuning, gene interactions, DDPM, diffusion, encoder, VAE · block oscr:b:B4PC85YXJ4WPY-0 · Report a mismatch

Paper

Loaded from Europe PMC by your browser; OSCR does not store it: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

Python · 387 lines · 17 KB · no license · 3 matches

  1. import torch
  2. from torch import optim
  3. import torch.nn.functional as F
  4. from torch.utils.data import DataLoader
  5. from torchvision import transforms, datasets
  6. from torchvision.utils import save_image
  7. from vae import VAE
  8. import matplotlib.pyplot as plt
  9. import argparse
  10. import os
  11. import shutil
  12. import numpy as np
  13. import pandas as pd
  14. import openpyxl
  15. import scanpy as sc
  16. import time
  17. import networkx as nx
  18. import torch.nn as nn
  19. from scipy.sparse import csr_matrix
  20. from scipy.sparse import save_npz
  21. from scipy.sparse import load_npz
  22. from scipy.stats import spearmanr
  23. import DDPM
  24. # plt.style.use("ggplot")
  25. from DDPM import build_network
  26. from DDPM import train
  27. from DDPM import DDPM
  28. import sklearn
  29. from sklearn.manifold import trustworthiness
  30. from utils_joint import save_file
  31. cuda = torch.cuda.is_available()
  32. device = torch.device("cuda" if cuda else "cpu")
  33. #device = 'cuda'
  34. parser = argparse.ArgumentParser(description="Variational Auto-Encoder MNIST Example")
  35. parser.add_argument('--dataset_name', type=str, default='data_GSE204684_developing_human_cerebral_cortex', metavar='N', help='dataset name')
  36. args_ini = parser.parse_args()
  37. parser.add_argument('--vae_pre_dir', type=str, default='./%s/checkPoint'%args_ini.dataset_name, metavar='N', help='model saving directory')
  38. parser.add_argument('--vae_pre_result_dir', type=str, default='./%s/VAEResult'%args_ini.dataset_name, metavar='DIR', help='output directory')
  39. parser.add_argument('--vae_after_dir', type=str, default='./%s/vae_after/checkPoint'%args_ini.dataset_name, metavar='N', help='model saving directory')
  40. parser.add_argument('--vae_after_result_dir', type=str, default='./%s/vae_after/VAEResult'%args_ini.dataset_name, metavar='N', help='model saving directory')
  41. parser.add_argument('--scData_dir', type=str, default='./data_hvg5000.h5ad', metavar='DIR', help='scData directory')
  42. parser.add_argument('--fine_scData_dir', type=str, default='./data_hvg5000.h5ad', metavar='DIR', help='scData directory')
  43. parser.add_argument('--pathway_dir', type=str, default='./prior_data_results/pathway_use_allgenes_maskedmatrix_filtered_geneNumberOver5.csv', metavar='DIR', help='pathway directory')
  44. parser.add_argument('--complex_dir', type=str, default='./prior_data_results/complex_use_allgenes_maskedmatrix_filtered_geneNumberOver5.csv', metavar='DIR', help='complex directory')
  45. parser.add_argument('--TF_dir', type=str, default='./prior_data_results/TF_use_allgenes_maskedmatrix_filtered_geneNumberOver5.csv', metavar='DIR', help='TF directory')
  46. parser.add_argument('--adjMatrix_kegg_dir', type=str, default='./prior_data_results/pathway_common_with_KEGGgraph_adj_matrix_Sparse.npz', metavar='DIR', help='adjMatrix directory')
  47. parser.add_argument('--adjMatrix_reactom_dir', type=str, default='./prior_data_results/reactome_gene_interaction_adj_matrix_Sparse.npz', metavar='DIR', help='TF directory')
  48. parser.add_argument('--num_workers', type=int, default=2, metavar='N', help='the number of workers')
  49. parser.add_argument('--cell_type_key', type=str, default='cell_type', metavar='N', help='cell type key in scData.obs')
  50. parser.add_argument('--batch_size', type=int, default=3000, metavar='N', help='batch size for training(default: 128)')
  51. parser.add_argument('--epochs', type=int, default=10, metavar='N', help='number of epochs to train(default: 200)')
  52. parser.add_argument('--seed', type=int, default=1, metavar='S', help='random seed(default: 1)')
  53. parser.add_argument('--resume', type=str, default='', metavar='PATH', help='path to latest checkpoint(default: None)')
  54. parser.add_argument('--test_every', type=int, default=10, metavar='N', help='test after every epochs')
  55. parser.add_argument('--num_worker', type=int, default=1, metavar='N', help='the number of workers')
  56. parser.add_argument('--lr', type=float, default=1e-4, help='learning rate(default: 0.001)')
  57. parser.add_argument('--z_dim', type=int, default=100, metavar='N', help='the dim of latent variable z(default: 20)')
  58. parser.add_argument('--input_dim', type=int, default=1000, metavar='N')
  59. parser.add_argument('--place_holders', type=int, default=5, metavar='N', help='place holder number(default: 5)')
  60. parser.add_argument('--n_steps', type=int, default=200, metavar='N', help='diffusion steps(default: 200)')
  61. parser.add_argument('--sample_back_steps', type=int, default=30, metavar='N', help='diffusion sample_back_steps(default: 30)')
  62. parser.add_argument('--ddpm_pre_model_path', type=str, default='./%s/ddpm/model_best.pth'%args_ini.dataset_name, metavar='N', help='ddpm pre model saving directory')
  63. parser.add_argument('--ddpm_after_model_path', type=str, default='./%s/ddpm_after/model_best.pth'%args_ini.dataset_name, metavar='N', help='ddpm after model saving directory')
  64. args = parser.parse_args()
  65. kwargs = {'num_workers': 2, 'pin_memory': True} if cuda else {}
  66. os.makedirs('./%s/ddpm_after'%args_ini.dataset_name, exist_ok=True)
  67. def dataloader(batch_size=args.batch_size, num_workers=2):
  68. transform = transforms.Compose([
  69. transforms.ToTensor(),
  70. ])
  71. oriData = sc.read_h5ad(args.scData_dir)
  72. mtx_mask_0 = pd.read_csv(args.pathway_dir)
  73. mtx_mask_0 = mtx_mask_0.values
  74. print('pathway shape: ', mtx_mask_0.shape)
  75. mtx_mask_1 = pd.read_csv(args.complex_dir)
  76. mtx_mask_1 = mtx_mask_1.values
  77. print('complex shape: ', mtx_mask_1.shape)
  78. mtx_mask_2 = pd.read_csv(args.TF_dir)
  79. mtx_mask_2 = mtx_mask_2.values
  80. print('TF shape: ', mtx_mask_2.shape)
  81. mtx_mask = np.concatenate((mtx_mask_0,mtx_mask_1,mtx_mask_2),axis=1)
  82. print('final shape: ', mtx_mask.shape)
  83. sparse_adjmatrix_loaded = load_npz(args.adjMatrix_kegg_dir) #not symmetric
  84. gene_adj_mtx = sparse_adjmatrix_loaded.toarray()
  85. gene_adj_mtx = gene_adj_mtx + gene_adj_mtx.T
  86. gene_adj_mtx = gene_adj_mtx + np.eye(gene_adj_mtx.shape[0])
  87. reactom_adjmatrix_loaded = load_npz(args.adjMatrix_reactom_dir)
  88. reactom_gene_regu = reactom_adjmatrix_loaded.toarray()
  89. gene_adj_mtx = gene_adj_mtx + reactom_gene_regu
  90. gene_adj_mtx[gene_adj_mtx > 1] = 9
  91. ############################################
  92. n = args.place_holders
  93. if n != 0:
  94. vec = np.ones((mtx_mask.shape[0], n),dtype=int)
  95. mtx_mask = np.hstack((mtx_mask, vec))
  96. #gene_adj_mtx = np.hstack((gene_adj_mtx, vec))
  97. ############################################
  98. # fine-tunning data followed
  99. #####################################################
  100. fine_Data = sc.read_h5ad(args.fine_scData_dir)
  101. fine_gene = set(fine_Data.var_names.tolist())
  102. oriData_gene = set(oriData.var_names.tolist())
  103. intersect_gene = fine_gene.intersection(oriData_gene)
  104. gene_idx_ori = []
  105. gene_idx_fine = []
  106. for gene in intersect_gene:
  107. gene_idx_ori.append(oriData.var_names.tolist().index(gene))
  108. gene_idx_fine.append(fine_Data.var_names.tolist().index(gene))
  109. fineData_final = np.zeros((fine_Data.shape[0], oriData.shape[1]))
  110. data = fine_Data.X.toarray()
  111. for i in range(len(intersect_gene)):
  112. fineData_final[:, gene_idx_ori[i]] = data[:, gene_idx_fine[i]]
  113. #oriData_gene_num = oriData.shape[1]
  114. #fineData_gene_num = fine_Data.shape[1]
  115. #padding = np.zeros((fineData.shape[0], oriData_gene_num-fineData_gene_num),dtype=float)
  116. #fineData_final = np.hstack((data, padding))
  117. #####################################################
  118. cat = fineData_final
  119. cat = torch.Tensor(cat)
  120. label = fine_Data.obs[args.cell_type_key].tolist()
  121. label = [0 for x in label]
  122. lbls = torch.tensor(label)
  123. cat_Tdata = torch.utils.data.TensorDataset(cat, lbls)
  124. train_loader = torch.utils.data.DataLoader(dataset=cat_Tdata, batch_size=batch_size, shuffle=True)
  125. cat_test = fineData_final
  126. cat_test = torch.Tensor(cat_test)
  127. label_test = fine_Data.obs[args.cell_type_key].tolist()
  128. label_test = [0 for x in label_test]
  129. lbls_test = torch.tensor(label_test)
  130. cat_test_Tdata = torch.utils.data.TensorDataset(cat_test, lbls_test)
  131. test_loader = torch.utils.data.DataLoader(dataset=cat_test_Tdata, batch_size=batch_size, shuffle=True)
  132. classes = ('0', '1', '2', '3', '4', '5', '6', '7', '8', '9')
  133. return test_loader, train_loader, classes, mtx_mask, gene_adj_mtx
  134. def pdist(a,dim=2, p=2):
  135. dist_matrix = torch.norm(a[:, None]-a, dim, p)
  136. return dist_matrix
  137. def pdists(A, squared = False, eps = 1e-8):
  138. prod = torch.mm(A, A.t())
  139. norm = prod.diag().unsqueeze(1).expand_as(prod)
  140. res = (norm + norm.t() - 2 * prod).clamp(min = 0)
  141. if squared:
  142. return res
  143. else:
  144. res = res.clamp(min = eps).sqrt()
  145. return res
  146. def loss_function(x_hat, x, mu, log_var):
  147. """
  148. Calculate the loss. Note that the loss includes two parts.
  149. :param x_hat:
  150. :param x:
  151. :param mu:
  152. :param log_var:
  153. :return: total loss, BCE and KLD of our model
  154. """
  155. # 1. the reconstruction loss.
  156. # We regard the MNIST as binary classification
  157. x = x.view(x.shape[0],1,1,x.shape[-1])
  158. #BCE = F.binary_cross_entropy(x_hat, x, reduction='sum')
  159. BCE = F.mse_loss(x_hat, x, reduction='sum')
  160. # 2. KL-divergence
  161. # D_KL(Q(z|X) || P(z)); calculate in closed form as both dist. are Gaussian
  162. # here we assume that \Sigma is a diagonal matrix, so as to simplify the computation
  163. KLD = 0.5 * torch.sum(torch.exp(log_var) + torch.pow(mu, 2) - 1. - log_var)
  164. x_f = x.view(x.shape[0],x.shape[-1])
  165. graph_adj_loss = trustworthiness(x_f.cpu().detach().numpy() , mu.cpu().detach().numpy() , n_neighbors=25, metric='euclidean')
  166. graph_adj_loss = 1 - graph_adj_loss
  167. print('graph_adj_loss is: ',graph_adj_loss)
  168. loss = BCE + KLD +graph_adj_loss
  169. return loss, BCE, KLD
  170. def save_checkpoint(state, net, is_best, outdir):
  171. """
  172. 每训练一定的epochs后, 判断损失函数是否是目前最优的,并保存模型的参数
  173. :param state: 需要保存的参数,数据类型为dict
  174. :param is_best: 说明是否为目前最优的
  175. :param outdir: 保存文件夹
  176. :return:
  177. """
  178. if not os.path.exists(outdir):
  179. os.makedirs(outdir)
  180. checkpoint_file = os.path.join(outdir, 'checkpoint.pth')
  181. best_file = os.path.join(outdir, 'model_best.pth')
  182. torch.save(state, checkpoint_file)
  183. if is_best:
  184. shutil.copyfile(checkpoint_file, best_file)
  185. torch.save(net.state_dict(), args.ddpm_after_model_path)
  186. def test(model_vae, model_df, net, optimizer, mnist_test, epoch, best_test_loss):
  187. test_avg_loss = 0.0
  188. with torch.no_grad():
  189. for test_batch_index, (test_x, _) in enumerate(mnist_test):
  190. test_x = test_x.to(device)
  191. test_x_hat, test_mu, test_log_var = model_vae(test_x)
  192. test_loss, test_BCE, test_KLD = loss_function(test_x_hat, test_x, test_mu, test_log_var)
  193. img_shape = get_shape()
  194. current_batch_size = test_mu.shape[0]
  195. test_mu = test_mu.view(current_batch_size, 1, img_shape[1], img_shape[2])
  196. test_mu = test_mu.to(device)
  197. test_t = torch.randint(0, args.n_steps, (current_batch_size, )).to(device)
  198. eps = torch.randn_like(test_mu, dtype=torch.float).to(device)
  199. test_mu_t = model_df.sample_forward(test_mu, test_t, eps)
  200. test_mu_t = test_mu_t.to(device)
  201. eps_theta = net(test_mu_t, test_t.reshape(current_batch_size, 1))
  202. #loss_fn = nn.MSELoss(reduction='sum')
  203. loss_fn = nn.MSELoss()
  204. loss_df = loss_fn(eps_theta, eps)
  205. test_loss = test_loss + loss_df
  206. test_avg_loss += test_loss
  207. test_avg_loss /= len(mnist_test.dataset)
  208. is_best = test_avg_loss < best_test_loss
  209. best_test_loss = min(test_avg_loss, best_test_loss)
  210. save_checkpoint({
  211. 'epoch': epoch,
  212. 'best_test_loss': best_test_loss,
  213. 'state_dict': model_vae.state_dict(),
  214. 'optimizer': optimizer.state_dict(),
  215. }, net, is_best, args.vae_after_dir)
  216. return best_test_loss
  217. def get_shape():
  218. return (1, 10, 10)
  219. def main():
  220. mnist_test, mnist_train, classes, mtx_mask, gene_adj_mtx= dataloader(args.batch_size, args.num_worker)
  221. x, label = iter(mnist_train).__next__()
  222. print("mask_mtx.size = ", mtx_mask.shape)
  223. print("pathway_connect_sum = ", sum(mtx_mask))
  224. print("Max(pathway_connect_sum) = ", max(sum(mtx_mask)))
  225. print("Min(pathway_connect_sum) = ", min(sum(mtx_mask)))
  226. print("mask_sum = ", np.sum(mtx_mask))
  227. print("zero_genes_pathway = ", np.sum(sum(mtx_mask)==0))
  228. print("zero_pathway_genes = ", np.sum(np.sum(mtx_mask,axis=1)==0))
  229. model_vae = VAE(mask_mtx=mtx_mask, gene_adj_mtx=gene_adj_mtx,z_dim=args.z_dim)
  230. model_vae.load_state_dict(torch.load("%s/model_best.pth"%args.vae_pre_dir)['state_dict'])
  231. model_vae = model_vae.to(device)
  232. print('The structure of our model is shown below: \n')
  233. print(model_vae)
  234. convnet_small_cfg = {
  235. 'type': 'ConvNet',
  236. 'intermediate_channels': [10, 20],
  237. 'pe_dim': 128
  238. }
  239. convnet_medium_cfg = {
  240. 'type': 'ConvNet',
  241. 'intermediate_channels': [10, 10, 20, 20, 40, 40, 80, 80],
  242. 'pe_dim': 256,
  243. 'insert_t_to_all_layers': True
  244. }
  245. convnet_big_cfg = {
  246. 'type': 'ConvNet',
  247. 'intermediate_channels': [20, 20, 40, 40, 80, 80, 160, 160],
  248. 'pe_dim': 256,
  249. 'insert_t_to_all_layers': True
  250. }
  251. unet_1_cfg = {'type': 'UNet',
  252. 'channels': [10, 20, 40, 80],
  253. 'pe_dim': 128}
  254. unet_res_cfg = {
  255. 'type': 'UNet',
  256. 'channels': [10, 20, 40, 80],
  257. 'pe_dim': 128,
  258. 'residual': True
  259. }
  260. configs = [convnet_small_cfg, convnet_medium_cfg, convnet_big_cfg, unet_1_cfg, unet_res_cfg]
  261. n_epochs = args.epochs
  262. n_steps = args.n_steps
  263. sample_back_steps = args.sample_back_steps
  264. config_id = 4
  265. config = configs[config_id]
  266. net = build_network(config, n_steps)
  267. net.load_state_dict(torch.load(args.ddpm_pre_model_path))
  268. net = net.to(device)
  269. model_df = DDPM(device, n_steps, sample_back_steps)
  270. #optimizer = optim.Adam(model_vae.parameters(), lr=args.lr)
  271. optimizer = optim.Adam(list(model_vae.parameters()) + list(net.parameters()), lr=args.lr)
  272. # Step 3: optionally resume from a checkpoint
  273. start_epoch = 0
  274. best_test_loss = np.finfo('f').max
  275. if args.resume:
  276. if os.path.isfile(args.resume):
  277. print('=> loading checkpoint %s' % args.resume)
  278. checkpoint = torch.load(args.resume)
  279. start_epoch = checkpoint['epoch'] + 1
  280. best_test_loss = checkpoint['best_test_loss']
  281. model.load_state_dict(checkpoint['state_dict'])
  282. optimizer.load_state_dict(checkpoint['optimizer'])
  283. print('=> loaded checkpoint %s' % args.resume)
  284. else:
  285. print('=> no checkpoint found at %s' % args.resume)
  286. if not os.path.exists(args.vae_after_result_dir):
  287. os.makedirs(args.vae_after_result_dir)
  288. loss_epoch = []
  289. for epoch in range(start_epoch, args.epochs):
  290. time_start = time.time()
  291. loss_batch = []
  292. for batch_index, (x, _) in enumerate(mnist_train):
  293. #x = x.view(x.shape[0],1,1,x.shape[1])
  294. x = x.to(device)
  295. x_hat, mu, log_var = model_vae(x)
  296. loss_vae, BCE, KLD = loss_function(x_hat, x, mu, log_var)
  297. img_shape = get_shape()
  298. current_batch_size = mu.shape[0]
  299. mu = mu.view(current_batch_size, 1, img_shape[1], img_shape[2])
  300. mu = mu.to(device)
  301. t = torch.randint(0, args.n_steps, (current_batch_size, )).to(device)
  302. eps = torch.randn_like(mu).to(device)
  303. mu_t = model_df.sample_forward(mu, t, eps)
  304. mu_t = mu_t.to(device)
  305. #print("mu_t is on:", mu_t.device)
  306. #print("t is on:", t.device)
  307. eps_theta = net(mu_t, t.reshape(current_batch_size, 1))
  308. loss_fn = nn.MSELoss()
  309. loss_df = loss_fn(eps_theta, eps) * current_batch_size
  310. loss = loss_vae + loss_df
  311. loss_batch.append(loss_vae.item() + loss_df.item())
  312. optimizer.zero_grad()
  313. loss.backward()
  314. optimizer.step()
  315. # print statistics every 100 batch
  316. if (batch_index + 1) % 10 == 0:
  317. print('Epoch [{}/{}], Batch [{}/{}] : Total-loss = {:.4f}, BCE-Loss = {:.4f}, KLD-loss = {:.4f}, DDPM-loss = {:.4f}'
  318. .format(epoch + 1, args.epochs, batch_index + 1, len(mnist_train.dataset) // args.batch_size,
  319. loss.item() / args.batch_size, BCE.item() / args.batch_size,
  320. KLD.item() / args.batch_size, loss_df.item() / args.batch_size))
  321. loss_epoch.append(np.sum(loss_batch) / len(mnist_train.dataset))
  322. time_end = time.time()
  323. time_used = time_end - time_start
  324. print("VAE epoch %s used time: %s sec."%(str(epoch),format(time_end-time_start, '.5f')))
  325. if (epoch + 1) % args.test_every == 0:
  326. best_test_loss = test(model_vae,model_df,net, optimizer, mnist_test, epoch, best_test_loss)
  327. return loss_epoch
  328. if __name__ == '__main__':
  329. loss_epoch = main()
  330. #print(loss_epoch)
  331. save_file(args.dataset_name, args.ddpm_after_model_path,args.batch_size,args.num_workers, args.scData_dir,args.fine_scData_dir, args.pathway_dir,args.complex_dir,args.TF_dir,args.adjMatrix_kegg_dir,args.adjMatrix_reactom_dir,args.place_holders, args.vae_after_dir, args.n_steps, args.sample_back_steps)

main_joint_fine_tunning.py at commit ff4ab8e, no license · at the source

Overview

Authors: Yawei Niu1, Yichu Chen1, Wenji Ma1
ORCID iDs: Yawei Niu, Wenji Ma
  1. Center for Single-Cell Omics, School of Public Health, Shanghai Jiao Tong University School of Medicine, Shanghai, China
Institutions: Shanghai Jiao Tong University (China)
Journal: Briefings in bioinformatics, volume 27, issue 3, article bbag259
Dates: received 19 December 2025; accepted 30 April 2026; published online 27 May 2026; in print May 2026
Type: Research article · Language: English
License: CC BY-NC
Identifiers: DOI 10.1093/bib/bbag259 · PMID 42202286 · PMCID PMC13215596 · OpenAlex W7162508230
Open access: gold, a free copy (OpenAlex)
Status: code verified (how the code is found and verified)
Categories: genetics / omics (modality), human (organism)
Methods: Connectivity, Machine learning
Keywords: scRNA-seq, dimension reduction, prior knowledge, VAE model, diffusion model
MeSH: Single-Cell Analysis*, Algorithms, Animals, Autoencoder, Dimensionality Reduction, Humans, Representation Machine Learning, Sequence Analysis, RNA, Single-Cell Gene Expression Analysis (* major topic)
Journal subjects: Problem Solving Protocol
Topic: Single-cell and spatial transcriptomics (Molecular Biology, Biochemistry, Genetics and Molecular Biology), according to OpenAlex
Citations: not cited yet (Europe PMC); 49 references in the paper

Abstract

Single-cell RNA sequencing data rely heavily on dimensionality reduction methods to uncover underlying structures and patterns. Nonlinear dimensionality-reduction methods such as uniform manifold approximation and t-distributed stochastic neighbor embedding have been routinely used for this task. However, gene expression data alone often fails to capture and identify changes in cellular pathways, protein complexes, and TF-targets, which are more enlightening at the regulation level. To address this limitation, we present PVAED, a dimensionality reduction framework that integrates biological prior knowledge into a variational autoencoder (VAE) and further refines its latent embeddings with a diffusion-based denoising module. In addition, we incorporate a neighborhood-preserving loss term to ensure local similarity among cells in the reduced space. Across multiple benchmarks, PVAED achieves an average 43% improvement in low-dimensional cell representation compared to standard VAEs (evaluated across seven clustering metrics) and delivers a 34% (44%) gain in projection quality relative to classical or VAE-based approaches in terms of global (local) structure preservation. Beyond performance, PVAED offers improved interpretability through its prior-based encoder design, enabling prioritization and modeling of interpretable biological variables as hypergraphs. This framework facilitates the identification of critical regulatory factors associated with disease pathology and could also be utilized to predict potentially related genes for known pathways. Finally, we demonstrate the utility of PVAED by revealing pre-committed neuronal subpopulations in the differentiation of migrating neurons within the mammalian cerebral cortex.

Reproduced under the paper's license (CC BY-NC), from the paper cited above.

Repositories

Its files are read in the Code ↔ Paper reader above, with 6 matches between paragraphs and lines of code.

MaLab-scGenomics/PriorVAED

License: none: the authors keep all their rights
State: the link answers, verified on 27 September 2026
Evidence: files inventoried
Commit: ff4ab8e2273c04635f5075cfe5ac79af17d4e775, 4 November 2025
Languages: Python (9), JavaScript (6), Jupyter (3)
Size: 697 files, 18 scripts
Software Heritage: not archived
Found in: “Code availability”
Holds: README, environment (PVAED/environment.yml, PVAED/docs/requirements.txt), documentation, 3 notebooks
Not found: license file, CITATION.cff, tests, continuous integration
Tools: NumPy (9 files), pandas (9 files), Scanpy (9 files), PyTorch (8 files), SciPy (6 files), Matplotlib (4 files), scikit-learn (4 files), anndata (2 files), NetworkX (2 files)
Availability: 1 check, the latest on 27 September 2026: the link answers
  • 27 September 2026: the link answers
19 files

pvaed.readthedocs.io

License: none: the authors keep all their rights
State: the link answers, verified on 27 September 2026
Evidence: the link answers
Software Heritage: not checked
Found in: “Code availability”
Not found: README, license file, CITATION.cff, environment file, tests, continuous integration, documentation
Availability: 1 check, the latest on 27 September 2026: the link answers (HTTP 200)
  • 27 September 2026: the link answers (HTTP 200)

Code availability

The current version of source code and software implementation for PVAED is available at: https://github.com/MaLab-scGenomics/PriorVAED. Basic tutorial is available at Read the Docs website: https://pvaed.readthedocs.io/en/master/index.html.

Reproduced under the paper's license (CC BY-NC), from the paper cited above.

Tracing map

Proposed by the machine: these links were found in the paper and verified at the source, without human review. The map will receive a Zenodo DOI once one of the paper's authors has validated it with their ORCID.

What the map holds:

  • 2 repositories of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
  • 18 scripts, each with its path and the digest of its content;
  • 6 matches between paragraphs of the paper and lines of the code (method lexical-v1);
  • neither the text of the paper nor the code itself.

Its JSON (tracing-map.json) is deposited on Zenodo with its DOI once the map is validated.

Data

No dataset and no data link were found in the paper.

Data availability

PBMC 3k and 10k data are downloaded from 10x genomics website under the corresponding keywords at https://www.10xgenomics.com/. Up to now, all the GEO data used in this work are freely accessed in GEO database under the corresponding accession number, which are GSE165657 (human cerebellar development), GSE204684 (human cerebral cortex development), GSE212606 (AD samples in mammalian brain), GSE131907 (LUAD samples), and GSE153164 (mouse cerebral cortex diversification). The NEMO data SCR_016152 (human hypothalamus development) is downloaded from https://assets.nemoarchive.org/dat-jx4eu3g.

Reproduced under the paper's license (CC BY-NC), from the paper cited above.

Versions

The history of this record: each version stored by the harvester or made by a correction of its authors or of the maintainers of its code, and what changed in its facts. The texts of the paper (its abstract, its availability statements) are not part of it; versions that changed only those are not listed.

Version 1, 27 September 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 3 authors, 5 keywords, 9 MeSH terms, 49 references.

Cite

This paper

Niu, Y., Chen, Y., & Ma, W. (2026). PVAED: prior-guided variational autoencoders with diffusion denoising for interpretable single-cell representation learning. Briefings in bioinformatics, 27(3), bbag259. https://doi.org/10.1093/bib/bbag259

BibTeX

@article{niu2026pvaed,
author = {Niu, Yawei and Chen, Yichu and Ma, Wenji},
title = {{PVAED: prior-guided variational autoencoders with diffusion denoising for interpretable single-cell representation learning}},
journal = {Briefings in bioinformatics},
year = {2026},
month = may,
volume = {27},
number = {3},
pages = {bbag259},
publisher = {Oxford University Press},
issn = {1467-5463},
doi = {10.1093/bib/bbag259},
url = {https://doi.org/10.1093/bib/bbag259},
pmid = {42202286},
pmcid = {PMC13215596}
}

RIS

TY - JOUR
AU - Niu, Yawei
AU - Chen, Yichu
AU - Ma, Wenji
TI - PVAED: prior-guided variational autoencoders with diffusion denoising for interpretable single-cell representation learning
T2 - Briefings in bioinformatics
J2 - Brief Bioinform
PY - 2026
DA - 2026/05/01
VL - 27
IS - 3
SP - bbag259
SN - 1467-5463
PB - Oxford University Press
DO - 10.1093/bib/bbag259
UR - https://doi.org/10.1093/bib/bbag259
LA - en
ER -

CSL-JSON

{
"id": "10.1093/bib/bbag259",
"type": "article-journal",
"title": "PVAED: prior-guided variational autoencoders with diffusion denoising for interpretable single-cell representation learning",
"container-title": "Briefings in bioinformatics",
"author": [
{
"family": "Niu",
"given": "Yawei"
},
{
"family": "Chen",
"given": "Yichu"
},
{
"family": "Ma",
"given": "Wenji"
}
],
"container-title-short": "Brief Bioinform",
"volume": "27",
"issue": "3",
"page": "bbag259",
"DOI": "10.1093/bib/bbag259",
"PMID": "42202286",
"PMCID": "PMC13215596",
"ISSN": "1467-5463",
"publisher": "Oxford University Press",
"URL": "https://doi.org/10.1093/bib/bbag259",
"language": "en",
"issued": {
"date-parts": [
[
2026,
5,
1
]
]
}
}

The tracing map gets a citation of its own once an author has validated it and it has a DOI.

Similar papers

The papers with a page that share the most with this one: the tools found in their code, their categories, datasets, cited references and authors, the rarest counting most.

[1] doi:10.1186/s13059-023-02850-y [code]
siVAE: interpretable deep generative models for single-cell transcriptomes.
Journal: Genome biology
In common: anndata, Scanpy, PyTorch, 5 other tools, genetics / omics, 9 references
[2] doi:10.1016/j.xgen.2024.100739 [code]
CSI-GEP: A GPU-based unsupervised machine learning approach for recovering gene expression programs in atlas-scale single-cell RNA-seq data.
Journal: Cell genomics
In common: anndata, Scanpy, NetworkX, 6 other tools, genetics / omics, 6 references
[3] doi:10.1038/s41467-021-25534-2 [code]
Learning interpretable cellular and gene signature embeddings from single-cell transcriptomic data.
Journal: Nature communications
In common: anndata, Scanpy, PyTorch, 5 other tools, genetics / omics, 6 references
[4] doi:10.1093/nar/gkag706 [code]
scDifformer: diffusion-based post-training for virtual cell modeling across large-scale single-cell data.
Journal: Nucleic acids research
In common: anndata, Scanpy, NetworkX, 6 other tools, 4 references
[5] doi:10.1186/s12864-026-12965-8 [code]
Systematic evaluation of single-cell foundation model interpretability: attention-derived edge scores add no incremental value over gene-level features for perturbation-target prediction.
Journal: BMC genomics
In common: anndata, Scanpy, NetworkX, 6 other tools, 4 references
[6] doi:10.1038/s41588-025-02120-6 [code]
Quantitative characterization of cell niches in spatially resolved omics data.
Journal: Nature genetics
In common: anndata, Scanpy, NetworkX, 6 other tools, genetics / omics, 4 references
[7] doi:10.1038/s41467-026-71759-4 [code]
CellNiche represents cellular microenvironments in atlas-scale spatial omics data with contrastive learning.
Journal: Nature communications
In common: anndata, Scanpy, NetworkX, 6 other tools, 4 references
[8] doi:10.1038/s41467-024-53971-2 [code]
scPair: Boosting single cell multimodal analysis by leveraging implicit feature selection and single cell atlases.
Journal: Nature communications
In common: anndata, Scanpy, PyTorch, 5 other tools, genetics / omics, 4 references
[9] doi:10.1038/s42003-025-07872-9 [code]
Infusing structural assumptions into dimensionality reduction for single-cell RNA sequencing data to identify small gene sets.
Journal: Communications biology
In common: anndata, Scanpy, scikit-learn, 4 other tools, genetics / omics, 4 references
[10] doi:10.1101/gr.280803.125 [code]
Unified integration of spatial transcriptomics across platforms with LLOKI.
Journal: Genome research
In common: anndata, Scanpy, PyTorch, 4 other tools, genetics / omics, 4 references

Contribute

The authors of this paper can claim it, correct its record and validate its tracing map, and the maintainers of its code (its owner, or a public member of its organization) correct what it says of their repository; anyone signed in can ask for its removal. Every request goes to OSCR's own machine, which answers it; your account page follows them.

Sign in with ORCID to claim this paper as one of its authors, correct its record or validate its tracing map: when the paper's metadata lists your ORCID iD, you are recognized at once. Maintainers of its code: sign in with GitHub, then claim the repository on your account page.

Add the badge to the code's README

OSCR: the badge of this paper

If you are an author or a maintainer of this paper's code, you can add this badge. It says what OSCR knows of the paper (its code, its validated tracing map) and links the code to this page. Paste one of these snippets under the README's title. Keep the two marks around it, so that the badge can be replaced in place and is never added twice. OSCR changes nothing in your repository.

Markdown
<!-- oscr-badge:start -->
[![OSCR](https://openscicode.org/badge/doi/10.1093/bib/bbag259.svg)](https://openscicode.org/badge/doi/10.1093/bib/bbag259)
<!-- oscr-badge:end -->
reStructuredText
.. oscr-badge:start

.. image:: https://openscicode.org/badge/doi/10.1093/bib/bbag259.svg
   :target: https://openscicode.org/badge/doi/10.1093/bib/bbag259
   :alt: OSCR

.. oscr-badge:end
HTML
<!-- oscr-badge:start -->
<a href="https://openscicode.org/badge/doi/10.1093/bib/bbag259"><img src="https://openscicode.org/badge/doi/10.1093/bib/bbag259.svg" alt="OSCR"></a>
<!-- oscr-badge:end -->

On GitHub, open the README, choose Edit (the pencil), paste the snippet under the title, then "Commit changes".

If you choose to, you can have the badge kept up to date for you, with oscr badge --write from the command line or with the GitHub Action in your repository's workflows. Every other form and option (a card, AsciiDoc, LaTeX, shields.io) is on the badge page.

Request its removal

To ask OSCR to remove this record, the copies of its authors' scripts or its tracing map, use the removal request page: signed in, you say who you are, what to remove and why, then review and confirm the request. Published rules decide every request (how).

Discussion, reproductions, activity

Discussion: code errors and mismatches between the code and the paper about this paper and its code, from readers and its authors, beside the paper and its tracing map.

Report a mismatch between the code and the paper · Report a code error (signed in)

Reproductions: reports from readers who ran the authors' code and did not get the paper's result, what they ran, with which environment, commit and data.

Report a reproduction failure (signed in)

Versions of its code: the releases of its code tied to a version of this paper (the preprint, the accepted manuscript, the version of record…), each with the tracing map versioned with it.

Activity: what happens around this paper: new versions of its record, its map's validation, discussions and reproductions. It opens with sign-in.