OSCR

Dissecting epigenetic heterogeneity in single-cell DNA methylomes with a unified framework.

Code ↔ Paper

12 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.

The 12 matches · 1 of them tie a paragraph to a whole file, not to given lines: a weak match, whose lines are not tinted
  1. [1] § Methods › Identification of hypo-DMRs ↔ scMethCraft/function/DMR.py, the whole file · a weak match · score 0.73 · log2 fold change, hypo DMRs, thresholds, rank, methylation
  2. [2] § Methods › The model architecture of scMethCraft ↔ scMethCraft/model/scmethcraft_model.py, lines 114–199 · score 0.63 · hot encodes, DNA sequence, scMethCraft models, mer, chromosome, position
  3. [3] § Methods › The model architecture of scMethCraft ↔ scMethCraft/model/scmethcraft_model.py, lines 114–199 · score 0.63 · hot encodes, DNA sequence, scMethCraft models, mer, chromosome, position
  4. [4] § Results › Design principles of scMethCraft inspire single-cell omics data modeling ↔ tutorial/tutorial_model_training.ipynb, lines 27–83 · score 0.62 · entire training process, genomic sequences, epoch, sequence feature, encoding, mer
  5. [5] § Results › Design principles of scMethCraft inspire single-cell omics data modeling ↔ scMethCraft/model/scmethcraft_model.py, lines 114–199 · score 0.58 · hot encoding, genomic position, single cell, mer, DNA, sequence
  6. [6] § Results › Design principles of scMethCraft inspire single-cell omics data modeling ↔ scMethCraft/model/scmethcraft_model.py, lines 114–199 · score 0.58 · hot encoding, genomic position, single cell, mer, DNA, sequence
  7. [7] § Methods › Implementation details of downstream analyses ↔ ldscore/regressions.py, lines 538–677 · score 0.57 · score regression, LD scores, genetic, heritability, enrichment, partitioned
  8. [8] § Methods › The model architecture of scMethCraft ↔ scMethCraft/model/scmethcraft_model.py, lines 311–426 · score 0.57 · dense layer, batch normalization, Hidden, GELU, dropout, activation
  9. [9] § Methods › The model architecture of scMethCraft ↔ scMethCraft/model/scmethcraft_model.py, lines 311–426 · score 0.57 · dense layer, batch normalization, Hidden, GELU, dropout, activation
  10. [10] § Methods › Implementation details of downstream analyses ↔ ldsc.py, lines 1–43 · score 0.54 · LD scores, score regression, command, genetic, heritability, partitioned
  11. [11] § Methods › The model architecture of scMethCraft ↔ scMethCraft/model/scmethcraft_model.py, lines 311–426 · score 0.54 · Dense layer, batch normalization, GELU, dropout, activation, model
  12. [12] § Methods › The model architecture of scMethCraft ↔ scMethCraft/model/scmethcraft_model.py, lines 311–426 · score 0.54 · Dense layer, batch normalization, GELU, dropout, activation, model

Paper

Loaded from Europe PMC by your browser, not stored by OSCR: doi.org · Europe PMC

The paper is loaded when this pane is shown.

The authors' code

Python · 762 lines · 25 KB · MIT · 4 matches

  1. import math
  2. from typing import List
  3. import sys
  4. import random
  5. import torch
  6. import torch.nn as nn
  7. import numpy as np
  8. import h5py
  9. import pandas as pd
  10. import sklearn.metrics as metrics
  11. import scanpy as sc
  12. import anndata as ad
  13. from scipy.special import expit
  14. from .utils_model import *
  15. from .layers import ConvLayer, DenseLayer
  16. from .utils_model import m_round
  17. device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
  18. def sigmoid(x):
  19. s = 1 / (1 + np.exp(-x))
  20. return s
  21. def _col_round(x):
  22. frac = x - math.floor(x)
  23. if frac <= 0.5:
  24. return math.floor(x)
  25. return math.ceil(x)
  26. def m_get_filter_dim(seq_length: int, pooling_sizes: List[int]):
  27. filter_dim = seq_length
  28. for ps in pooling_sizes:
  29. filter_dim = _col_round(filter_dim / ps)
  30. return int(filter_dim/2)
  31. # =========================
  32. # Chromosome length maps
  33. # =========================
  34. # Used for genomic position normalization in positional encoding.
  35. # Key: chromosome ID
  36. # Value: chromosome length (bp)
  37. p_max_map_human = dict(pd.DataFrame([[1, 2,3, 4, 5, 6, 7, 8, 9, 10,11,12,13,14,15,16,17,18,19,20,21,22,23,24,25],[248956422, 242193529, 198295559, 190214555,
  38. 181538259, 170805979, 159345973, 145138636, 138394717,
  39. 133797422, 135086622, 133275309, 114364328, 107043718,
  40. 101991189, 90338345, 83257441, 80373285, 58617616, 64444167,
  41. 46709983, 50818468, 156040895, 57227415,16569]]).T.values)
  42. p_max_map_mouse = dict(pd.DataFrame([['1', '2', '3', '4', '5', '6', '7', '8', '9', '10',
  43. '11', '12', '13', '14', '15', '16', '17', '18', '19','23', '24','25'],[195471971, 182113224, 160039680, 156508116,
  44. 151834684, 149736546, 145441459, 129401213, 124595110,
  45. 130694993, 122082543, 120129022, 120421639, 124902244,
  46. 104043685, 98207768, 94987271, 90702639, 61431566, 171031299, 91744698,10000]]).astype(int).T.values)
  47. # =========================
  48. # Sequence loading utilities
  49. # =========================
  50. def load_seq(input_path,filename,load_range,mode= "onehot"):
  51. """
  52. Load sequence data from HDF5 file.
  53. Args:
  54. input_path (str): Path to input directory
  55. filename (str): HDF5 file name
  56. load_range (tuple or None): Subset range (start, end)
  57. mode (str): "onehot", "kmer", or "both"
  58. Returns:
  59. Tensor(s) depending on mode:
  60. - onehot: (N, 4, L)
  61. - kmer: (N, K)
  62. - both: (onehot, kmer, position)
  63. """
  64. if mode == "onehot":
  65. with h5py.File(input_path+filename) as file:
  66. if load_range != False:
  67. onehot = file["X"][load_range[0]:load_range[1]]
  68. else:
  69. onehot = file["X"]
  70. onehot = torch.nn.functional.one_hot(torch.tensor(onehot).to(torch.int64)).transpose(-2, -1)
  71. return onehot.to(torch.float)
  72. if mode == "kmer":
  73. with h5py.File(input_path+filename) as file:
  74. if load_range != False:
  75. kmer = file["Kmer"][load_range[0]:load_range[1]]
  76. else:
  77. kmer = file["Kmer"]
  78. return torch.tensor(kmer).to(torch.float)
  79. if mode == "both":
  80. with h5py.File(input_path+filename) as file:
  81. if load_range != False:
  82. onehot = file["X"][load_range[0]:load_range[1]]
  83. kmer = file["Kmer"][load_range[0]:load_range[1]]
  84. else:
  85. onehot = file["X"]
  86. kmer = file["Kmer"]
  87. pos = file["Pos"]
  88. onehot = torch.nn.functional.one_hot(torch.tensor(onehot).to(torch.int64)).transpose(-2, -1)
  89. return onehot.to(torch.float),torch.tensor(kmer).to(torch.float),torch.tensor(pos)
  90. # =========================
  91. # Dataset definition
  92. # =========================
  93. class MethyDataset(torch.utils.data.Dataset):
  94. """
  95. Dataset for single-cell methylation modeling.
  96. Each sample consists of:
  97. - DNA sequence (one-hot encoded)
  98. - Cell-level methylation state
  99. - k-mer representation
  100. - Genomic positional embedding
  101. """
  102. def __init__(self, h5_path, state_path, d_emb=64, load_range=None,p_max_map = "HUMAN"):
  103. self.h5_path = h5_path
  104. self.d_emb = d_emb
  105. if p_max_map == "HUMAN":
  106. self.p_max_map = p_max_map_human
  107. elif p_max_map == "MOUSE":
  108. self.p_max_map = p_max_map_mouse
  109. else:
  110. self.p_max_map = p_max_map
  111. self.load_range = load_range
  112. self.state_data = np.load(state_path)
  113. self.cell = self.state_data.shape[1]
  114. with h5py.File(self.h5_path, 'r') as f:
  115. self.total_len = f['X'].shape[0]
  116. def __len__(self):
  117. return self.total_len if self.load_range is None else (self.load_range[1] - self.load_range[0])
  118. def get_pos_embedding(self, raw_pos):
  119. """
  120. Generate sinusoidal-like positional embedding.
  121. Args:
  122. raw_pos: [chromosome_id, start, end]
  123. Returns:
  124. Tensor of shape (d_emb,)
  125. """
  126. chr_id = int(raw_pos[0])
  127. p_max = self.p_max_map.get(chr_id, 248956422) # 防止 key 错误
  128. p = (raw_pos[1] + raw_pos[2]) / 2
  129. t = torch.tensor([p / p_max], dtype=torch.float)
  130. w = 2 * 3.14159 * t
  131. # 计算编码
  132. pe_list = []
  133. for j in range(self.d_emb):
  134. if j <= 1:
  135. pe_list.append(t)
  136. elif j % 2 == 0:
  137. f_val = 1e-4 + (j/2 - 1) * (self.d_emb/2 - 1 - 1e-4) / (self.d_emb/2 - 1)
  138. pe_list.append(torch.cos(f_val * w))
  139. else:
  140. f_val = 1e-4 + ((j-1)/2 - 1) * (self.d_emb/2 - 1 - 1e-4) / (self.d_emb/2 - 1)
  141. pe_list.append(torch.sin(f_val * w))
  142. return torch.cat(pe_list) # 返回 [d_emb] 向量
  143. def __getitem__(self, index):
  144. """
  145. Retrieve a single sample.
  146. Returns:
  147. onehot: (4, L)
  148. state: (n_cells,)
  149. kmer: (K,)
  150. pos_embedding: (d_emb,)
  151. """
  152. if self.load_range:
  153. index += self.load_range[0]
  154. with h5py.File(self.h5_path, 'r') as f:
  155. # 读取原始数据
  156. x = f['X'][index]
  157. kmer = f['Kmer'][index]
  158. pos_info = f['Pos'][index] # 获取 [chr_id, start, end]
  159. onehot = torch.nn.functional.one_hot(torch.tensor(x, dtype=torch.long), num_classes=4).transpose(-2, -1).to(torch.float)
  160. pe_emb = self.get_pos_embedding(pos_info)
  161. state = torch.tensor(self.state_data[index], dtype=torch.float)
  162. kmer_tensor = torch.tensor(kmer, dtype=torch.float)
  163. return onehot, state, kmer_tensor, pe_emb
  164. class SimilarityLayer_fast(nn.Module):
  165. """
  166. Fast approximation of similarity propagation.
  167. Instead of explicitly constructing an NxN similarity matrix,
  168. this layer factorizes it into two low-rank matrices:
  169. A ≈ A1 @ A2^T
  170. This reduces computation from O(N^2) to O(N * dim_n).
  171. """
  172. def __init__(
  173. self,
  174. n_cells: int,
  175. dim_n :int = 256,
  176. dropout_rate: float = 0.1,
  177. batch_norm = True,
  178. device = device,
  179. ):
  180. super().__init__()
  181. self.similarity_matrix=torch.nn.Parameter(torch.rand(n_cells,dim_n))
  182. self.n_cells = n_cells
  183. self.dim_n = dim_n
  184. self.dropout_rate = dropout_rate
  185. self.dropout = self.dropout_rate
  186. self.device = device
  187. self.batch_norm = (
  188. nn.BatchNorm1d(n_cells) if batch_norm else nn.Identity()
  189. )
  190. def forward(
  191. self,
  192. input_vector: torch.Tensor,
  193. ):
  194. A_fixed = torch.abs(self.similarity_matrix)
  195. m1 = (torch.rand(self.n_cells, 1, device=self.device) > self.dropout_rate).float()
  196. m2 = (torch.rand(self.n_cells, 1, device=self.device) > self.dropout_rate).float()
  197. A1 = A_fixed * m1 / (1 - self.dropout_rate)
  198. A2 = A_fixed * m2 / (1 - self.dropout_rate)
  199. XA = torch.matmul(input_vector, A1)
  200. SX = torch.matmul(XA, A2.t())
  201. diag_S = torch.sum(A1 * A2, dim=1)
  202. output_vector = SX - input_vector * diag_S
  203. return self.batch_norm(output_vector)
  204. class SimilarityLayer(nn.Module):
  205. """
  206. Full similarity matrix version (exact but O(N^2)).
  207. Learns a symmetric similarity matrix and applies dropout masking.
  208. """
  209. def __init__(
  210. self,
  211. n_cells: int,
  212. dropout_rate: float = 0.1,
  213. batch_norm = True
  214. ):
  215. super().__init__()
  216. self.similarity_matrix=torch.nn.Parameter(torch.rand(n_cells,n_cells))
  217. self.n_cells = n_cells
  218. self.alpha = 0
  219. self.dropout_rate = dropout_rate
  220. self.dropout = self.dropout_rate
  221. self.eyematrix = 1-torch.eye(self.n_cells,self.n_cells, device=device)
  222. self.batch_norm = (
  223. nn.BatchNorm1d(n_cells) if batch_norm else nn.Identity()
  224. )
  225. def my_dropout(self,input_matrix):
  226. dropout_matrix = (torch.rand(self.n_cells,self.n_cells, device=device)>self.dropout).float()
  227. dropout_matrix = torch.mul(dropout_matrix,self.eyematrix)
  228. input_matrix = torch.mul(dropout_matrix, input_matrix)
  229. input_matrix = input_matrix/(1-self.dropout)
  230. if self.alpha>0:
  231. input_matrix = input_matrix+self.alpha*self.n_cells*torch.mean(input_matrix)*torch.eye(self.n_cells,self.n_cells, device=device)
  232. return input_matrix
  233. def forward(
  234. self,
  235. input_vector: torch.Tensor,
  236. ):
  237. fixed_similarity_matrix = self.similarity_matrix
  238. fixed_similarity_matrix = torch.abs(fixed_similarity_matrix+fixed_similarity_matrix.T)/2
  239. fixed_similarity_matrix = self.my_dropout(fixed_similarity_matrix)
  240. output_vector = torch.matmul(input_vector,fixed_similarity_matrix)/(1+self.alpha)
  241. output_vector = self.batch_norm(output_vector)
  242. return output_vector
  243. class Sequence_extraction(nn.Module):
  244. """
  245. Core feature extraction module combining:
  246. - sequence (one-hot CNN)
  247. - k-mer representation
  248. - positional embedding
  249. """
  250. def __init__(
  251. self,
  252. n_cells: int,
  253. K:int = 8,
  254. n_filters_init: int = 256,
  255. n_repeat_blocks_tower: int =2,
  256. filters_mult: float = 1.41421,
  257. n_filters_pre_bottleneck: int = 256,
  258. n_bottleneck_layer: int = 25,
  259. dropout_rate_similarity: float = 0.3,
  260. batch_norm: bool = True,
  261. embedding_dim: int = 16,
  262. dropout: float = 0.0,
  263. genomic_seq_length: int = 10000, ):
  264. super().__init__()
  265. self.stem = ConvLayer(
  266. in_channels=4,
  267. out_channels=n_filters_init,
  268. kernel_size=12,
  269. pool_size=4,
  270. dropout=dropout,
  271. batch_norm=batch_norm,
  272. )
  273. tower_layers = []
  274. curr_n_filters = n_filters_init
  275. for i in range(n_repeat_blocks_tower):
  276. tower_layers.append(
  277. ConvLayer(
  278. in_channels=curr_n_filters,
  279. out_channels=m_round(curr_n_filters * filters_mult),
  280. kernel_size=5,
  281. pool_size=2,
  282. dropout=dropout,
  283. batch_norm=batch_norm,
  284. )
  285. )
  286. curr_n_filters = m_round(curr_n_filters * filters_mult)
  287. self.tower = nn.Sequential(*tower_layers)
  288. self.pre_bottleneck = ConvLayer(
  289. in_channels=curr_n_filters,
  290. out_channels=n_filters_pre_bottleneck,
  291. kernel_size=1,
  292. dropout=dropout,
  293. batch_norm=batch_norm,
  294. pool_size=2,
  295. )
  296. # get pooling sizes of the upstream conv layers
  297. pooling_sizes = [4] + [2] * n_repeat_blocks_tower + [1]
  298. # get filter dimensionality to account for variable sequence length
  299. filter_dim = m_get_filter_dim(seq_length=genomic_seq_length, pooling_sizes=pooling_sizes)
  300. self.hidden_onehot = DenseLayer(
  301. in_features=n_filters_pre_bottleneck * filter_dim,
  302. out_features=n_bottleneck_layer,
  303. use_bias=True,
  304. batch_norm=True,
  305. dropout=0.2,
  306. activation_fn=nn.Identity(),
  307. )
  308. self.hidden_pos_1 = KANLinear(
  309. in_features=64,
  310. out_features=32,
  311. )
  312. self.hidden_pos_2 = KANLinear(
  313. in_features=32,
  314. out_features=n_bottleneck_layer*2,
  315. )
  316. self.Kmer1 = DenseLayer(
  317. in_features=4 ** K,
  318. out_features=4 ** int(K/2),
  319. use_bias=True,
  320. batch_norm=True,
  321. dropout=0.2,
  322. activation_fn=nn.GELU(),
  323. )
  324. self.pos_embedding_attention = nn.Embedding(256,embedding_dim)
  325. self.hidden_Kmer = DenseLayer(
  326. in_features=4**int(K/2),
  327. out_features=n_bottleneck_layer,
  328. use_bias=True,
  329. batch_norm=True,
  330. dropout=0.2,
  331. activation_fn=nn.GELU(),
  332. )
  333. self.kmer_embedding_linear = DenseLayer(
  334. in_features=1,
  335. out_features=embedding_dim,
  336. use_bias=True,
  337. batch_norm=False,
  338. dropout=0,
  339. activation_fn=nn.GELU(),
  340. )
  341. self.transformer = torch.nn.TransformerEncoderLayer(embedding_dim,4,batch_first=True)
  342. self.kmer_embedding_linear_inverse = DenseLayer(
  343. in_features=embedding_dim,
  344. out_features=1,
  345. use_bias=True,
  346. batch_norm=False,
  347. dropout=0,
  348. activation_fn=nn.GELU(),
  349. )
  350. self.final = nn.Linear(n_bottleneck_layer*2, n_cells)
  351. def forward(
  352. self,
  353. onehot: torch.Tensor,
  354. kmer: torch.Tensor,
  355. pos:torch.Tensor
  356. ):
  357. onehot = self.stem(onehot)
  358. onehot = self.tower(onehot)
  359. onehot = self.pre_bottleneck(onehot)
  360. onehot = onehot.view(onehot.shape[0], -1)
  361. onehot = self.hidden_onehot(onehot)
  362. kmer = self.Kmer1(kmer)
  363. res_kmer = kmer
  364. kmer = self.kmer_embedding_linear(kmer.unsqueeze(2))
  365. kmer_seq_embedding = kmer + self.pos_embedding_attention.weight
  366. kmer_seq_embedding = self.transformer(kmer_seq_embedding)
  367. kmer = self.kmer_embedding_linear_inverse(kmer_seq_embedding).squeeze(2)
  368. kmer = kmer + res_kmer
  369. kmer = self.hidden_Kmer(kmer)
  370. pos = self.hidden_pos_1(pos)
  371. pos = self.hidden_pos_2(pos)
  372. latent = torch.cat((onehot,kmer),1)
  373. res_latent = latent
  374. latent = torch.mul(latent, pos)
  375. latent = latent + res_latent
  376. latent = self.final(latent)
  377. return latent
  378. class Similarity_weighting(nn.Module):
  379. def __init__(
  380. self,
  381. n_cells: int,
  382. dropout_rate: float = 0.1,
  383. batch_norm = True
  384. ):
  385. super().__init__()
  386. self.SimilarityLayer1 = SimilarityLayer(n_cells,dropout_rate,batch_norm)
  387. def train(self):
  388. self.SimilarityLayer1.train()
  389. self.SimilarityLayer1.dropout = self.SimilarityLayer1.dropout_rate
  390. self.SimilarityLayer1.alpha = 0
  391. def eval(self):
  392. self.SimilarityLayer1.eval()
  393. self.SimilarityLayer1.dropout = 0
  394. self.SimilarityLayer1.alpha = 0.2
  395. def forward(self, methy_level_vector: torch.Tensor):
  396. methy_level_vector = self.SimilarityLayer1(methy_level_vector)
  397. return methy_level_vector
  398. class Similarity_weighting_fast(nn.Module):
  399. def __init__(
  400. self,
  401. n_cells: int,
  402. dim_n :int = 256,
  403. dropout_rate: float = 0.1,
  404. batch_norm = True,
  405. device = device
  406. ):
  407. super().__init__()
  408. self.SimilarityLayer1 = SimilarityLayer_fast(n_cells,dim_n,dropout_rate,batch_norm,device = device)
  409. def train(self):
  410. self.SimilarityLayer1.dropout = self.SimilarityLayer1.dropout_rate
  411. def eval(self):
  412. self.SimilarityLayer1.dropout = 0
  413. def forward(self, methy_level_vector: torch.Tensor):
  414. methy_level_vector = self.SimilarityLayer1(methy_level_vector)
  415. return methy_level_vector
  416. class KANLinear(torch.nn.Module):
  417. def __init__(
  418. self,
  419. in_features,
  420. out_features,
  421. grid_size=5,
  422. spline_order=3,
  423. scale_noise=0.1,
  424. scale_base=1.0,
  425. scale_spline=1.0,
  426. enable_standalone_scale_spline=True,
  427. base_activation=torch.nn.SiLU,
  428. grid_eps=0.02,
  429. grid_range=[-1, 1],
  430. ):
  431. super(KANLinear, self).__init__()
  432. self.in_features = in_features
  433. self.out_features = out_features
  434. self.grid_size = grid_size
  435. self.spline_order = spline_order
  436. h = (grid_range[1] - grid_range[0]) / grid_size
  437. grid = (
  438. (
  439. torch.arange(-spline_order, grid_size + spline_order + 1) * h
  440. + grid_range[0]
  441. )
  442. .expand(in_features, -1)
  443. .contiguous()
  444. )
  445. self.register_buffer("grid", grid)
  446. self.base_weight = torch.nn.Parameter(torch.Tensor(out_features, in_features))
  447. self.spline_weight = torch.nn.Parameter(
  448. torch.Tensor(out_features, in_features, grid_size + spline_order)
  449. )
  450. if enable_standalone_scale_spline:
  451. self.spline_scaler = torch.nn.Parameter(
  452. torch.Tensor(out_features, in_features)
  453. )
  454. self.scale_noise = scale_noise
  455. self.scale_base = scale_base
  456. self.scale_spline = scale_spline
  457. self.enable_standalone_scale_spline = enable_standalone_scale_spline
  458. self.base_activation = base_activation()
  459. self.grid_eps = grid_eps
  460. self.reset_parameters()
  461. def reset_parameters(self):
  462. torch.nn.init.kaiming_uniform_(self.base_weight, a=math.sqrt(5) * self.scale_base)
  463. with torch.no_grad():
  464. noise = (
  465. (
  466. torch.rand(self.grid_size + 1, self.in_features, self.out_features)
  467. - 1 / 2
  468. )
  469. * self.scale_noise
  470. / self.grid_size
  471. )
  472. self.spline_weight.data.copy_(
  473. (self.scale_spline if not self.enable_standalone_scale_spline else 1.0)
  474. * self.curve2coeff(
  475. self.grid.T[self.spline_order : -self.spline_order],
  476. noise,
  477. )
  478. )
  479. if self.enable_standalone_scale_spline:
  480. # torch.nn.init.constant_(self.spline_scaler, self.scale_spline)
  481. torch.nn.init.kaiming_uniform_(self.spline_scaler, a=math.sqrt(5) * self.scale_spline)
  482. def b_splines(self, x: torch.Tensor):
  483. """
  484. Compute the B-spline bases for the given input tensor.
  485. Args:
  486. x (torch.Tensor): Input tensor of shape (batch_size, in_features).
  487. Returns:
  488. torch.Tensor: B-spline bases tensor of shape (batch_size, in_features, grid_size + spline_order).
  489. """
  490. assert x.dim() == 2 and x.size(1) == self.in_features
  491. grid: torch.Tensor = (
  492. self.grid
  493. ) # (in_features, grid_size + 2 * spline_order + 1)
  494. x = x.unsqueeze(-1)
  495. bases = ((x >= grid[:, :-1]) & (x < grid[:, 1:])).to(x.dtype)
  496. for k in range(1, self.spline_order + 1):
  497. bases = (
  498. (x - grid[:, : -(k + 1)])
  499. / (grid[:, k:-1] - grid[:, : -(k + 1)])
  500. * bases[:, :, :-1]
  501. ) + (
  502. (grid[:, k + 1 :] - x)
  503. / (grid[:, k + 1 :] - grid[:, 1:(-k)])
  504. * bases[:, :, 1:]
  505. )
  506. assert bases.size() == (
  507. x.size(0),
  508. self.in_features,
  509. self.grid_size + self.spline_order,
  510. )
  511. return bases.contiguous()
  512. def curve2coeff(self, x: torch.Tensor, y: torch.Tensor):
  513. """
  514. Compute the coefficients of the curve that interpolates the given points.
  515. Args:
  516. x (torch.Tensor): Input tensor of shape (batch_size, in_features).
  517. y (torch.Tensor): Output tensor of shape (batch_size, in_features, out_features).
  518. Returns:
  519. torch.Tensor: Coefficients tensor of shape (out_features, in_features, grid_size + spline_order).
  520. """
  521. assert x.dim() == 2 and x.size(1) == self.in_features
  522. assert y.size() == (x.size(0), self.in_features, self.out_features)
  523. A = self.b_splines(x).transpose(
  524. 0, 1
  525. ) # (in_features, batch_size, grid_size + spline_order)
  526. B = y.transpose(0, 1) # (in_features, batch_size, out_features)
  527. solution = torch.linalg.lstsq(
  528. A, B
  529. ).solution # (in_features, grid_size + spline_order, out_features)
  530. result = solution.permute(
  531. 2, 0, 1
  532. ) # (out_features, in_features, grid_size + spline_order)
  533. assert result.size() == (
  534. self.out_features,
  535. self.in_features,
  536. self.grid_size + self.spline_order,
  537. )
  538. return result.contiguous()
  539. @property
  540. def scaled_spline_weight(self):
  541. return self.spline_weight * (
  542. self.spline_scaler.unsqueeze(-1)
  543. if self.enable_standalone_scale_spline
  544. else 1.0
  545. )
  546. def forward(self, x: torch.Tensor):
  547. assert x.dim() == 2 and x.size(1) == self.in_features
  548. base_output = torch.nn.functional.linear(self.base_activation(x), self.base_weight)
  549. spline_output = torch.nn.functional.linear(
  550. self.b_splines(x).view(x.size(0), -1),
  551. self.scaled_spline_weight.view(self.out_features, -1),
  552. )
  553. return base_output + spline_output
  554. @torch.no_grad()
  555. def update_grid(self, x: torch.Tensor, margin=0.01):
  556. assert x.dim() == 2 and x.size(1) == self.in_features
  557. batch = x.size(0)
  558. splines = self.b_splines(x) # (batch, in, coeff)
  559. splines = splines.permute(1, 0, 2) # (in, batch, coeff)
  560. orig_coeff = self.scaled_spline_weight # (out, in, coeff)
  561. orig_coeff = orig_coeff.permute(1, 2, 0) # (in, coeff, out)
  562. unreduced_spline_output = torch.bmm(splines, orig_coeff) # (in, batch, out)
  563. unreduced_spline_output = unreduced_spline_output.permute(
  564. 1, 0, 2
  565. ) # (batch, in, out)
  566. # sort each channel individually to collect data distribution
  567. x_sorted = torch.sort(x, dim=0)[0]
  568. grid_adaptive = x_sorted[
  569. torch.linspace(
  570. 0, batch - 1, self.grid_size + 1, dtype=torch.int64, device=x.device
  571. )
  572. ]
  573. uniform_step = (x_sorted[-1] - x_sorted[0] + 2 * margin) / self.grid_size
  574. grid_uniform = (
  575. torch.arange(
  576. self.grid_size + 1, dtype=torch.float32, device=x.device
  577. ).unsqueeze(1)
  578. * uniform_step
  579. + x_sorted[0]
  580. - margin
  581. )
  582. grid = self.grid_eps * grid_uniform + (1 - self.grid_eps) * grid_adaptive
  583. grid = torch.concatenate(
  584. [
  585. grid[:1]
  586. - uniform_step
  587. * torch.arange(self.spline_order, 0, -1, device=x.device).unsqueeze(1),
  588. grid,
  589. grid[-1:]
  590. + uniform_step
  591. * torch.arange(1, self.spline_order + 1, device=x.device).unsqueeze(1),
  592. ],
  593. dim=0,
  594. )
  595. self.grid.copy_(grid.T)
  596. self.spline_weight.data.copy_(self.curve2coeff(x, unreduced_spline_output))
  597. def regularization_loss(self, regularize_activation=1.0, regularize_entropy=1.0):
  598. """
  599. Compute the regularization loss.
  600. This is a dumb simulation of the original L1 regularization as stated in the
  601. paper, since the original one requires computing absolutes and entropy from the
  602. expanded (batch, in_features, out_features) intermediate tensor, which is hidden
  603. behind the F.linear function if we want an memory efficient implementation.
  604. The L1 regularization is now computed as mean absolute value of the spline
  605. weights. The authors implementation also includes this term in addition to the
  606. sample-based regularization.
  607. """
  608. l1_fake = self.spline_weight.abs().mean(-1)
  609. regularization_loss_activation = l1_fake.sum()
  610. p = l1_fake / regularization_loss_activation
  611. regularization_loss_entropy = -torch.sum(p * p.log())
  612. return (
  613. regularize_activation * regularization_loss_activation
  614. + regularize_entropy * regularization_loss_entropy
  615. )
  616. def output_model(MethyBasset_part1,MethyBasset_part2,savepath = f"../sample_data/output/"):
  617. import os
  618. if not os.path.exists(savepath):
  619. os.makedirs(savepath)
  620. print("Folder created")
  621. else:
  622. print("Folder already exists")
  623. torch.save(MethyBasset_part1.state_dict(), f"{savepath}/scMethCraft_part1.pth")
  624. torch.save(MethyBasset_part2.state_dict(), f"{savepath}/scMethCraft_part2.pth")

scmethcraft_model.py at commit 6c2ef56, under MIT · at the source

Overview

Authors: Songming Tang1, Siyu Li1, Guangxin Zhang2, Aoran Lyu3, Han Li1,4, Shengquan Chen1,5
  1. School of Mathematical Sciences and LPMC, Nankai University,Tianjin, China
  2. SeekGene BioSciences, Beijing, China
  3. Department of Mechanical and Aerospace Engineering, The University of Manchester,Manchester, UK
  4. Sheffield Institute for Translational Neuroscience, University of Sheffield,Sheffield, UK
  5. Academy for Advanced Interdisciplinary Studies, Nankai University,Tianjin, China
Institutions: Nankai University (China); University of Manchester (United Kingdom); University of Sheffield (United Kingdom)
Journal: Nature communications, volume 17, issue 1, article 6469
Dates: received 12 August 2025; accepted 30 April 2026; published online 15 May 2026
Type: Research article · Language: English
License: CC BY-NC-ND
Identifiers: DOI 10.1038/s41467-026-73171-4 · PMID 42140984 · PMCID PMC13376737 · OpenAlex W7161287819
Open access: gold, a free copy (OpenAlex)
Status: code verified
Categories: genetics / omics (modality), human (organism), cellular / molecular (subfield)
Methods: Statistics, Smoothing, state filtering, decompositions, Connectivity, Machine learning
Keywords: Computational models, Data mining, Machine learning, Genome informatics, Epigenetics
MeSH: DNA Methylation*, Epigenesis, Genetic*, Epigenome*, Epigenomics*, Single-Cell Analysis*, Animals, Genetic Heterogeneity, Humans (* major topic)
Topic: Epigenetics and DNA Methylation (Molecular Biology, Biochemistry, Genetics and Molecular Biology), according to OpenAlex
Citations: cited by 2 papers (Europe PMC); 56 references in the paper

Abstract

The abstract is not reproduced here: the paper's license (CC BY-NC-ND) does not allow it. Read it in the paper, at the publisher or on Europe PMC.

Repositories

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

bulik/ldsc

License: GPL-3.0
State: the link answers, verified on 26 September 2026
Evidence: files inventoried
Commit: 2fdeeb3b44379408794154993dbd6101b8946b7e, 16 January 2026
Languages: Python (19), MATLAB (4), Perl (1), R (1)
Size: 1,093 files, 25 scripts
Software Heritage: archived
Found in: the text, “Implementation details of downstream analyses”
Holds: README, license file, environment (environment.yml, requirements.txt, setup.py), tests
Not found: CITATION.cff, continuous integration, documentation
Tools: NumPy (18 files), pandas (11 files), SciPy (5 files), BEDTools (2 files)
Availability: 1 check, the latest on 26 September 2026: the link answers
  • 26 September 2026: the link answers
27 files

BioX-NKU/scMethCraft

License: MIT
State: the link answers, verified on 28 September 2026
Evidence: files inventoried
Commit: 6c2ef5613c1edd87036d1a982d2ffea118955f05, 10 September 2026
Languages: Python (21), Jupyter (16)
Size: 71 files, 37 scripts
Software Heritage: not archived
Found in: “Code availability”
Holds: README, license file, environment (setup.py), 8 notebooks
Not found: CITATION.cff, tests, continuous integration, documentation
Tools: Scanpy (17 files), NumPy (12 files), PyTorch (11 files), SciPy (9 files), pandas (8 files), anndata (5 files), scikit-learn (5 files), h5py (4 files), pysam (3 files), seaborn (2 files), Matplotlib (1 file)
Availability: 1 check, the latest on 28 September 2026: the link answers
  • 28 September 2026: the link answers
39 files

Zenodo 19549979

License: MIT
State: the link answers, verified on 28 September 2026
Evidence: files inventoried
Size: 1 file
Software Heritage: not checked
Found in: the references
Not found: README, license file, CITATION.cff, environment file, tests, continuous integration, documentation
Tools: NumPy (11 files), Scanpy (11 files), PyTorch (9 files), pandas (7 files), SciPy (6 files), anndata (4 files), h5py (4 files), scikit-learn (4 files), pysam (3 files), seaborn (2 files), Matplotlib (1 file)
Availability: 1 check, the latest on 28 September 2026: the link answers (HTTP 200)
  • 28 September 2026: the link answers (HTTP 200)
31 files
At the source:

Code availability statement

The paper has a code availability statement. Its license (CC BY-NC-ND) does not allow reproducing it here; in short, from what the harvester recognized in it:

Read it in the paper: doi.org/10.1038/s41467-026-73171-4.

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:

  • 3 repositories of the authors' code, each at its verified commit, with its license and how the link was found in the paper;
  • 91 scripts, each with its path and the digest of its content;
  • 12 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

Datasets cited

Data availability statement

The paper has a data availability statement. Its license (CC BY-NC-ND) does not allow reproducing it here; in short, from what the harvester recognized in it:

Read it in the paper: doi.org/10.1038/s41467-026-73171-4.

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, 28 September 2026: the first record

Recorded: type, language, journal, volume, issue, pages, dates, 6 authors, 5 keywords, 8 MeSH terms, 1 funder, 55 references.

Cite

This paper

Tang, S., Li, S., Zhang, G., Lyu, A., Li, H., & Chen, S. (2026). Dissecting epigenetic heterogeneity in single-cell DNA methylomes with a unified framework. Nature communications, 17(1), 6469. https://doi.org/10.1038/s41467-026-73171-4

BibTeX

@article{tang2026dissecting,
author = {Tang, Songming and Li, Siyu and Zhang, Guangxin and Lyu, Aoran and Li, Han and Chen, Shengquan},
title = {{Dissecting epigenetic heterogeneity in single-cell DNA methylomes with a unified framework}},
journal = {Nature communications},
year = {2026},
month = may,
volume = {17},
number = {1},
pages = {6469},
publisher = {Nature Publishing Group},
issn = {2041-1723},
doi = {10.1038/s41467-026-73171-4},
url = {https://doi.org/10.1038/s41467-026-73171-4},
pmid = {42140984},
pmcid = {PMC13376737}
}

RIS

TY - JOUR
AU - Tang, Songming
AU - Li, Siyu
AU - Zhang, Guangxin
AU - Lyu, Aoran
AU - Li, Han
AU - Chen, Shengquan
TI - Dissecting epigenetic heterogeneity in single-cell DNA methylomes with a unified framework
T2 - Nature communications
J2 - Nat Commun
PY - 2026
DA - 2026/05/15
VL - 17
IS - 1
SP - 6469
SN - 2041-1723
PB - Nature Publishing Group
DO - 10.1038/s41467-026-73171-4
UR - https://doi.org/10.1038/s41467-026-73171-4
LA - en
ER -

CSL-JSON

{
"id": "10.1038/s41467-026-73171-4",
"type": "article-journal",
"title": "Dissecting epigenetic heterogeneity in single-cell DNA methylomes with a unified framework",
"container-title": "Nature communications",
"author": [
{
"family": "Tang",
"given": "Songming"
},
{
"family": "Li",
"given": "Siyu"
},
{
"family": "Zhang",
"given": "Guangxin"
},
{
"family": "Lyu",
"given": "Aoran"
},
{
"family": "Li",
"given": "Han"
},
{
"family": "Chen",
"given": "Shengquan"
}
],
"container-title-short": "Nat Commun",
"volume": "17",
"issue": "1",
"page": "6469",
"DOI": "10.1038/s41467-026-73171-4",
"PMID": "42140984",
"PMCID": "PMC13376737",
"ISSN": "2041-1723",
"publisher": "Nature Publishing Group",
"URL": "https://doi.org/10.1038/s41467-026-73171-4",
"language": "en",
"issued": {
"date-parts": [
[
2026,
5,
15
]
]
}
}

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.1002/advs.77524 [code]
MethyAnno: An Interpretable Automated Annotation Method Leveraging Multi-Scale Information and Metric Learning Framework for scDNAm Data.
Journal: Advanced science (Weinheim, Baden-Wurttemberg, Germany)
In common: anndata, Scanpy, PyTorch, 6 other tools, genetics / omics, 10 references, author Shengquan Chen
[2] doi:10.1101/gr.281350.125 [code]
High-fidelity bidirectional translation between single-cell transcriptomes and DNA methylomes with scBOND.
Journal: Genome research
In common: BEDTools, anndata, Scanpy, 8 other tools, genetics / omics, cellular / molecular, 7 references
[3] doi:10.1038/s42003-026-10462-y [code]
SpaDC enables sequence-based integrative analysis and regulatory inference of spatial chromatin accessibility data.
Journal: Communications biology
In common: pysam, BEDTools, anndata, 7 other tools, genetics / omics, 7 references
[4] doi:10.1038/s41592-026-03057-2 [code]
CREsted: modeling genomic and synthetic cell-type-specific enhancers across tissues and species.
Journal: Nature methods
In common: pysam, BEDTools, anndata, 9 other tools, genetics / omics, 3 references
[5] doi:10.1038/s41467-026-71803-3 [code]
Charting the transition from in vitro gliogenesis to the in vivo maturation of human glial progenitor cells transplanted into the hypomyelinated mouse brain.
Journal: Nature communications
In common: BEDTools, anndata, Scanpy, 8 other tools, genetics / omics, cellular / molecular, 2 references
[6] doi:10.1093/bioinformatics/btag652 [code]
mmVelo: a deep generative model for estimating cell state-dependent dynamics across multiple modalities.
Journal: Bioinformatics (Oxford, England)
In common: pysam, BEDTools, anndata, 8 other tools, genetics / omics, 1 reference
[7] doi:10.1016/j.celrep.2026.117110 [code]
Single-nucleus multiome analysis in the human prefrontal cortex identifies gene expression and cis-regulatory elements associated with aging.
Journal: Cell reports
In common: pysam, BEDTools, anndata, 7 other tools, genetics / omics, cellular / molecular, 1 reference
[8] doi:10.1038/s44320-026-00208-7 [code]
Interpretable deep generative ensemble learning for single-cell omics with Hydra.
Journal: Molecular systems biology
In common: pysam, anndata, Scanpy, 8 other tools, cellular / molecular, 1 reference
[9] doi:10.1093/bib/bbag485 [code]
Single-cell-level perturbation-induced and condition-related signal estimation with batch effect removal using NDreamer.
Journal: Briefings in bioinformatics
In common: anndata, Scanpy, PyTorch, 6 other tools, genetics / omics, 4 references
[10] doi:10.1016/j.celrep.2026.117073 [code]
Single-cell epigenomics uncovers heterochromatin instability and transcription factor dysfunction during mouse brain aging.
Journal: Cell reports
In common: pysam, BEDTools, anndata, 6 other tools, genetics / omics, cellular / molecular, 2 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.

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: questions and error reports about this paper and its code, from signed-in readers and its authors. It opens with sign-in.

Reproductions: reports from readers who ran the authors' code: what they reproduced, with which environment, commit and data. It opens with sign-in.

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