Dissecting epigenetic heterogeneity in single-cell DNA methylomes with a unified framework.
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] § 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] § 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] § 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] § 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] § 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] § 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] § Methods › Implementation details of downstream analyses ↔ ldscore/regressions.py, lines 538–677 · score 0.57 · score regression, LD scores, genetic, heritability, enrichment, partitioned
- [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] § 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] § Methods › Implementation details of downstream analyses ↔ ldsc.py, lines 1–43 · score 0.54 · LD scores, score regression, command, genetic, heritability, partitioned
- [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] § 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
- import math
- from typing import List
- import sys
- import random
- import torch
- import torch.nn as nn
- import numpy as np
- import h5py
- import pandas as pd
- import sklearn.metrics as metrics
- import scanpy as sc
- import anndata as ad
- from scipy.special import expit
- from .utils_model import *
- from .layers import ConvLayer, DenseLayer
- from .utils_model import m_round
- device = torch.device("cuda" if torch.cuda.is_available() else "cpu")
- def sigmoid(x):
- s = 1 / (1 + np.exp(-x))
- return s
- def _col_round(x):
- frac = x - math.floor(x)
- if frac <= 0.5:
- return math.floor(x)
- return math.ceil(x)
- def m_get_filter_dim(seq_length: int, pooling_sizes: List[int]):
- filter_dim = seq_length
- for ps in pooling_sizes:
- filter_dim = _col_round(filter_dim / ps)
- return int(filter_dim/2)
- # =========================
- # Chromosome length maps
- # =========================
- # Used for genomic position normalization in positional encoding.
- # Key: chromosome ID
- # Value: chromosome length (bp)
- 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,
- 181538259, 170805979, 159345973, 145138636, 138394717,
- 133797422, 135086622, 133275309, 114364328, 107043718,
- 101991189, 90338345, 83257441, 80373285, 58617616, 64444167,
- 46709983, 50818468, 156040895, 57227415,16569]]).T.values)
- p_max_map_mouse = dict(pd.DataFrame([['1', '2', '3', '4', '5', '6', '7', '8', '9', '10',
- '11', '12', '13', '14', '15', '16', '17', '18', '19','23', '24','25'],[195471971, 182113224, 160039680, 156508116,
- 151834684, 149736546, 145441459, 129401213, 124595110,
- 130694993, 122082543, 120129022, 120421639, 124902244,
- 104043685, 98207768, 94987271, 90702639, 61431566, 171031299, 91744698,10000]]).astype(int).T.values)
- # =========================
- # Sequence loading utilities
- # =========================
- def load_seq(input_path,filename,load_range,mode= "onehot"):
- """
- Load sequence data from HDF5 file.
- Args:
- input_path (str): Path to input directory
- filename (str): HDF5 file name
- load_range (tuple or None): Subset range (start, end)
- mode (str): "onehot", "kmer", or "both"
- Returns:
- Tensor(s) depending on mode:
- - onehot: (N, 4, L)
- - kmer: (N, K)
- - both: (onehot, kmer, position)
- """
- if mode == "onehot":
- with h5py.File(input_path+filename) as file:
- if load_range != False:
- onehot = file["X"][load_range[0]:load_range[1]]
- else:
- onehot = file["X"]
- onehot = torch.nn.functional.one_hot(torch.tensor(onehot).to(torch.int64)).transpose(-2, -1)
- return onehot.to(torch.float)
- if mode == "kmer":
- with h5py.File(input_path+filename) as file:
- if load_range != False:
- kmer = file["Kmer"][load_range[0]:load_range[1]]
- else:
- kmer = file["Kmer"]
- return torch.tensor(kmer).to(torch.float)
- if mode == "both":
- with h5py.File(input_path+filename) as file:
- if load_range != False:
- onehot = file["X"][load_range[0]:load_range[1]]
- kmer = file["Kmer"][load_range[0]:load_range[1]]
- else:
- onehot = file["X"]
- kmer = file["Kmer"]
- pos = file["Pos"]
- onehot = torch.nn.functional.one_hot(torch.tensor(onehot).to(torch.int64)).transpose(-2, -1)
- return onehot.to(torch.float),torch.tensor(kmer).to(torch.float),torch.tensor(pos)
- # =========================
- # Dataset definition
- # =========================
- class MethyDataset(torch.utils.data.Dataset):
- """
- Dataset for single-cell methylation modeling.
- Each sample consists of:
- - DNA sequence (one-hot encoded)
- - Cell-level methylation state
- - k-mer representation
- - Genomic positional embedding
- """
- def __init__(self, h5_path, state_path, d_emb=64, load_range=None,p_max_map = "HUMAN"):
- self.h5_path = h5_path
- self.d_emb = d_emb
- if p_max_map == "HUMAN":
- self.p_max_map = p_max_map_human
- elif p_max_map == "MOUSE":
- self.p_max_map = p_max_map_mouse
- else:
- self.p_max_map = p_max_map
- self.load_range = load_range
- self.state_data = np.load(state_path)
- self.cell = self.state_data.shape[1]
- with h5py.File(self.h5_path, 'r') as f:
- self.total_len = f['X'].shape[0]
- def __len__(self):
- return self.total_len if self.load_range is None else (self.load_range[1] - self.load_range[0])
- def get_pos_embedding(self, raw_pos):
- """
- Generate sinusoidal-like positional embedding.
- Args:
- raw_pos: [chromosome_id, start, end]
- Returns:
- Tensor of shape (d_emb,)
- """
- chr_id = int(raw_pos[0])
- p_max = self.p_max_map.get(chr_id, 248956422) # 防止 key 错误
- p = (raw_pos[1] + raw_pos[2]) / 2
- t = torch.tensor([p / p_max], dtype=torch.float)
- w = 2 * 3.14159 * t
- # 计算编码
- pe_list = []
- for j in range(self.d_emb):
- if j <= 1:
- pe_list.append(t)
- elif j % 2 == 0:
- f_val = 1e-4 + (j/2 - 1) * (self.d_emb/2 - 1 - 1e-4) / (self.d_emb/2 - 1)
- pe_list.append(torch.cos(f_val * w))
- else:
- f_val = 1e-4 + ((j-1)/2 - 1) * (self.d_emb/2 - 1 - 1e-4) / (self.d_emb/2 - 1)
- pe_list.append(torch.sin(f_val * w))
- return torch.cat(pe_list) # 返回 [d_emb] 向量
- def __getitem__(self, index):
- """
- Retrieve a single sample.
- Returns:
- onehot: (4, L)
- state: (n_cells,)
- kmer: (K,)
- pos_embedding: (d_emb,)
- """
- if self.load_range:
- index += self.load_range[0]
- with h5py.File(self.h5_path, 'r') as f:
- # 读取原始数据
- x = f['X'][index]
- kmer = f['Kmer'][index]
- pos_info = f['Pos'][index] # 获取 [chr_id, start, end]
- onehot = torch.nn.functional.one_hot(torch.tensor(x, dtype=torch.long), num_classes=4).transpose(-2, -1).to(torch.float)
- pe_emb = self.get_pos_embedding(pos_info)
- state = torch.tensor(self.state_data[index], dtype=torch.float)
- kmer_tensor = torch.tensor(kmer, dtype=torch.float)
- return onehot, state, kmer_tensor, pe_emb
- class SimilarityLayer_fast(nn.Module):
- """
- Fast approximation of similarity propagation.
- Instead of explicitly constructing an NxN similarity matrix,
- this layer factorizes it into two low-rank matrices:
- A ≈ A1 @ A2^T
- This reduces computation from O(N^2) to O(N * dim_n).
- """
- def __init__(
- self,
- n_cells: int,
- dim_n :int = 256,
- dropout_rate: float = 0.1,
- batch_norm = True,
- device = device,
- ):
- super().__init__()
- self.similarity_matrix=torch.nn.Parameter(torch.rand(n_cells,dim_n))
- self.n_cells = n_cells
- self.dim_n = dim_n
- self.dropout_rate = dropout_rate
- self.dropout = self.dropout_rate
- self.device = device
- self.batch_norm = (
- nn.BatchNorm1d(n_cells) if batch_norm else nn.Identity()
- )
- def forward(
- self,
- input_vector: torch.Tensor,
- ):
- A_fixed = torch.abs(self.similarity_matrix)
- m1 = (torch.rand(self.n_cells, 1, device=self.device) > self.dropout_rate).float()
- m2 = (torch.rand(self.n_cells, 1, device=self.device) > self.dropout_rate).float()
- A1 = A_fixed * m1 / (1 - self.dropout_rate)
- A2 = A_fixed * m2 / (1 - self.dropout_rate)
- XA = torch.matmul(input_vector, A1)
- SX = torch.matmul(XA, A2.t())
- diag_S = torch.sum(A1 * A2, dim=1)
- output_vector = SX - input_vector * diag_S
- return self.batch_norm(output_vector)
- class SimilarityLayer(nn.Module):
- """
- Full similarity matrix version (exact but O(N^2)).
- Learns a symmetric similarity matrix and applies dropout masking.
- """
- def __init__(
- self,
- n_cells: int,
- dropout_rate: float = 0.1,
- batch_norm = True
- ):
- super().__init__()
- self.similarity_matrix=torch.nn.Parameter(torch.rand(n_cells,n_cells))
- self.n_cells = n_cells
- self.alpha = 0
- self.dropout_rate = dropout_rate
- self.dropout = self.dropout_rate
- self.eyematrix = 1-torch.eye(self.n_cells,self.n_cells, device=device)
- self.batch_norm = (
- nn.BatchNorm1d(n_cells) if batch_norm else nn.Identity()
- )
- def my_dropout(self,input_matrix):
- dropout_matrix = (torch.rand(self.n_cells,self.n_cells, device=device)>self.dropout).float()
- dropout_matrix = torch.mul(dropout_matrix,self.eyematrix)
- input_matrix = torch.mul(dropout_matrix, input_matrix)
- input_matrix = input_matrix/(1-self.dropout)
- if self.alpha>0:
- input_matrix = input_matrix+self.alpha*self.n_cells*torch.mean(input_matrix)*torch.eye(self.n_cells,self.n_cells, device=device)
- return input_matrix
- def forward(
- self,
- input_vector: torch.Tensor,
- ):
- fixed_similarity_matrix = self.similarity_matrix
- fixed_similarity_matrix = torch.abs(fixed_similarity_matrix+fixed_similarity_matrix.T)/2
- fixed_similarity_matrix = self.my_dropout(fixed_similarity_matrix)
- output_vector = torch.matmul(input_vector,fixed_similarity_matrix)/(1+self.alpha)
- output_vector = self.batch_norm(output_vector)
- return output_vector
- class Sequence_extraction(nn.Module):
- """
- Core feature extraction module combining:
- - sequence (one-hot CNN)
- - k-mer representation
- - positional embedding
- """
- def __init__(
- self,
- n_cells: int,
- K:int = 8,
- n_filters_init: int = 256,
- n_repeat_blocks_tower: int =2,
- filters_mult: float = 1.41421,
- n_filters_pre_bottleneck: int = 256,
- n_bottleneck_layer: int = 25,
- dropout_rate_similarity: float = 0.3,
- batch_norm: bool = True,
- embedding_dim: int = 16,
- dropout: float = 0.0,
- genomic_seq_length: int = 10000, ):
- super().__init__()
- self.stem = ConvLayer(
- in_channels=4,
- out_channels=n_filters_init,
- kernel_size=12,
- pool_size=4,
- dropout=dropout,
- batch_norm=batch_norm,
- )
- tower_layers = []
- curr_n_filters = n_filters_init
- for i in range(n_repeat_blocks_tower):
- tower_layers.append(
- ConvLayer(
- in_channels=curr_n_filters,
- out_channels=m_round(curr_n_filters * filters_mult),
- kernel_size=5,
- pool_size=2,
- dropout=dropout,
- batch_norm=batch_norm,
- )
- )
- curr_n_filters = m_round(curr_n_filters * filters_mult)
- self.tower = nn.Sequential(*tower_layers)
- self.pre_bottleneck = ConvLayer(
- in_channels=curr_n_filters,
- out_channels=n_filters_pre_bottleneck,
- kernel_size=1,
- dropout=dropout,
- batch_norm=batch_norm,
- pool_size=2,
- )
- # get pooling sizes of the upstream conv layers
- pooling_sizes = [4] + [2] * n_repeat_blocks_tower + [1]
- # get filter dimensionality to account for variable sequence length
- filter_dim = m_get_filter_dim(seq_length=genomic_seq_length, pooling_sizes=pooling_sizes)
- self.hidden_onehot = DenseLayer(
- in_features=n_filters_pre_bottleneck * filter_dim,
- out_features=n_bottleneck_layer,
- use_bias=True,
- batch_norm=True,
- dropout=0.2,
- activation_fn=nn.Identity(),
- )
- self.hidden_pos_1 = KANLinear(
- in_features=64,
- out_features=32,
- )
- self.hidden_pos_2 = KANLinear(
- in_features=32,
- out_features=n_bottleneck_layer*2,
- )
- self.Kmer1 = DenseLayer(
- in_features=4 ** K,
- out_features=4 ** int(K/2),
- use_bias=True,
- batch_norm=True,
- dropout=0.2,
- activation_fn=nn.GELU(),
- )
- self.pos_embedding_attention = nn.Embedding(256,embedding_dim)
- self.hidden_Kmer = DenseLayer(
- in_features=4**int(K/2),
- out_features=n_bottleneck_layer,
- use_bias=True,
- batch_norm=True,
- dropout=0.2,
- activation_fn=nn.GELU(),
- )
- self.kmer_embedding_linear = DenseLayer(
- in_features=1,
- out_features=embedding_dim,
- use_bias=True,
- batch_norm=False,
- dropout=0,
- activation_fn=nn.GELU(),
- )
- self.transformer = torch.nn.TransformerEncoderLayer(embedding_dim,4,batch_first=True)
- self.kmer_embedding_linear_inverse = DenseLayer(
- in_features=embedding_dim,
- out_features=1,
- use_bias=True,
- batch_norm=False,
- dropout=0,
- activation_fn=nn.GELU(),
- )
- self.final = nn.Linear(n_bottleneck_layer*2, n_cells)
- def forward(
- self,
- onehot: torch.Tensor,
- kmer: torch.Tensor,
- pos:torch.Tensor
- ):
- onehot = self.stem(onehot)
- onehot = self.tower(onehot)
- onehot = self.pre_bottleneck(onehot)
- onehot = onehot.view(onehot.shape[0], -1)
- onehot = self.hidden_onehot(onehot)
- kmer = self.Kmer1(kmer)
- res_kmer = kmer
- kmer = self.kmer_embedding_linear(kmer.unsqueeze(2))
- kmer_seq_embedding = kmer + self.pos_embedding_attention.weight
- kmer_seq_embedding = self.transformer(kmer_seq_embedding)
- kmer = self.kmer_embedding_linear_inverse(kmer_seq_embedding).squeeze(2)
- kmer = kmer + res_kmer
- kmer = self.hidden_Kmer(kmer)
- pos = self.hidden_pos_1(pos)
- pos = self.hidden_pos_2(pos)
- latent = torch.cat((onehot,kmer),1)
- res_latent = latent
- latent = torch.mul(latent, pos)
- latent = latent + res_latent
- latent = self.final(latent)
- return latent
- class Similarity_weighting(nn.Module):
- def __init__(
- self,
- n_cells: int,
- dropout_rate: float = 0.1,
- batch_norm = True
- ):
- super().__init__()
- self.SimilarityLayer1 = SimilarityLayer(n_cells,dropout_rate,batch_norm)
- def train(self):
- self.SimilarityLayer1.train()
- self.SimilarityLayer1.dropout = self.SimilarityLayer1.dropout_rate
- self.SimilarityLayer1.alpha = 0
- def eval(self):
- self.SimilarityLayer1.eval()
- self.SimilarityLayer1.dropout = 0
- self.SimilarityLayer1.alpha = 0.2
- def forward(self, methy_level_vector: torch.Tensor):
- methy_level_vector = self.SimilarityLayer1(methy_level_vector)
- return methy_level_vector
- class Similarity_weighting_fast(nn.Module):
- def __init__(
- self,
- n_cells: int,
- dim_n :int = 256,
- dropout_rate: float = 0.1,
- batch_norm = True,
- device = device
- ):
- super().__init__()
- self.SimilarityLayer1 = SimilarityLayer_fast(n_cells,dim_n,dropout_rate,batch_norm,device = device)
- def train(self):
- self.SimilarityLayer1.dropout = self.SimilarityLayer1.dropout_rate
- def eval(self):
- self.SimilarityLayer1.dropout = 0
- def forward(self, methy_level_vector: torch.Tensor):
- methy_level_vector = self.SimilarityLayer1(methy_level_vector)
- return methy_level_vector
- class KANLinear(torch.nn.Module):
- def __init__(
- self,
- in_features,
- out_features,
- grid_size=5,
- spline_order=3,
- scale_noise=0.1,
- scale_base=1.0,
- scale_spline=1.0,
- enable_standalone_scale_spline=True,
- base_activation=torch.nn.SiLU,
- grid_eps=0.02,
- grid_range=[-1, 1],
- ):
- super(KANLinear, self).__init__()
- self.in_features = in_features
- self.out_features = out_features
- self.grid_size = grid_size
- self.spline_order = spline_order
- h = (grid_range[1] - grid_range[0]) / grid_size
- grid = (
- (
- torch.arange(-spline_order, grid_size + spline_order + 1) * h
- + grid_range[0]
- )
- .expand(in_features, -1)
- .contiguous()
- )
- self.register_buffer("grid", grid)
- self.base_weight = torch.nn.Parameter(torch.Tensor(out_features, in_features))
- self.spline_weight = torch.nn.Parameter(
- torch.Tensor(out_features, in_features, grid_size + spline_order)
- )
- if enable_standalone_scale_spline:
- self.spline_scaler = torch.nn.Parameter(
- torch.Tensor(out_features, in_features)
- )
- self.scale_noise = scale_noise
- self.scale_base = scale_base
- self.scale_spline = scale_spline
- self.enable_standalone_scale_spline = enable_standalone_scale_spline
- self.base_activation = base_activation()
- self.grid_eps = grid_eps
- self.reset_parameters()
- def reset_parameters(self):
- torch.nn.init.kaiming_uniform_(self.base_weight, a=math.sqrt(5) * self.scale_base)
- with torch.no_grad():
- noise = (
- (
- torch.rand(self.grid_size + 1, self.in_features, self.out_features)
- - 1 / 2
- )
- * self.scale_noise
- / self.grid_size
- )
- self.spline_weight.data.copy_(
- (self.scale_spline if not self.enable_standalone_scale_spline else 1.0)
- * self.curve2coeff(
- self.grid.T[self.spline_order : -self.spline_order],
- noise,
- )
- )
- if self.enable_standalone_scale_spline:
- # torch.nn.init.constant_(self.spline_scaler, self.scale_spline)
- torch.nn.init.kaiming_uniform_(self.spline_scaler, a=math.sqrt(5) * self.scale_spline)
- def b_splines(self, x: torch.Tensor):
- """
- Compute the B-spline bases for the given input tensor.
- Args:
- x (torch.Tensor): Input tensor of shape (batch_size, in_features).
- Returns:
- torch.Tensor: B-spline bases tensor of shape (batch_size, in_features, grid_size + spline_order).
- """
- assert x.dim() == 2 and x.size(1) == self.in_features
- grid: torch.Tensor = (
- self.grid
- ) # (in_features, grid_size + 2 * spline_order + 1)
- x = x.unsqueeze(-1)
- bases = ((x >= grid[:, :-1]) & (x < grid[:, 1:])).to(x.dtype)
- for k in range(1, self.spline_order + 1):
- bases = (
- (x - grid[:, : -(k + 1)])
- / (grid[:, k:-1] - grid[:, : -(k + 1)])
- * bases[:, :, :-1]
- ) + (
- (grid[:, k + 1 :] - x)
- / (grid[:, k + 1 :] - grid[:, 1:(-k)])
- * bases[:, :, 1:]
- )
- assert bases.size() == (
- x.size(0),
- self.in_features,
- self.grid_size + self.spline_order,
- )
- return bases.contiguous()
- def curve2coeff(self, x: torch.Tensor, y: torch.Tensor):
- """
- Compute the coefficients of the curve that interpolates the given points.
- Args:
- x (torch.Tensor): Input tensor of shape (batch_size, in_features).
- y (torch.Tensor): Output tensor of shape (batch_size, in_features, out_features).
- Returns:
- torch.Tensor: Coefficients tensor of shape (out_features, in_features, grid_size + spline_order).
- """
- assert x.dim() == 2 and x.size(1) == self.in_features
- assert y.size() == (x.size(0), self.in_features, self.out_features)
- A = self.b_splines(x).transpose(
- 0, 1
- ) # (in_features, batch_size, grid_size + spline_order)
- B = y.transpose(0, 1) # (in_features, batch_size, out_features)
- solution = torch.linalg.lstsq(
- A, B
- ).solution # (in_features, grid_size + spline_order, out_features)
- result = solution.permute(
- 2, 0, 1
- ) # (out_features, in_features, grid_size + spline_order)
- assert result.size() == (
- self.out_features,
- self.in_features,
- self.grid_size + self.spline_order,
- )
- return result.contiguous()
- @property
- def scaled_spline_weight(self):
- return self.spline_weight * (
- self.spline_scaler.unsqueeze(-1)
- if self.enable_standalone_scale_spline
- else 1.0
- )
- def forward(self, x: torch.Tensor):
- assert x.dim() == 2 and x.size(1) == self.in_features
- base_output = torch.nn.functional.linear(self.base_activation(x), self.base_weight)
- spline_output = torch.nn.functional.linear(
- self.b_splines(x).view(x.size(0), -1),
- self.scaled_spline_weight.view(self.out_features, -1),
- )
- return base_output + spline_output
- @torch.no_grad()
- def update_grid(self, x: torch.Tensor, margin=0.01):
- assert x.dim() == 2 and x.size(1) == self.in_features
- batch = x.size(0)
- splines = self.b_splines(x) # (batch, in, coeff)
- splines = splines.permute(1, 0, 2) # (in, batch, coeff)
- orig_coeff = self.scaled_spline_weight # (out, in, coeff)
- orig_coeff = orig_coeff.permute(1, 2, 0) # (in, coeff, out)
- unreduced_spline_output = torch.bmm(splines, orig_coeff) # (in, batch, out)
- unreduced_spline_output = unreduced_spline_output.permute(
- 1, 0, 2
- ) # (batch, in, out)
- # sort each channel individually to collect data distribution
- x_sorted = torch.sort(x, dim=0)[0]
- grid_adaptive = x_sorted[
- torch.linspace(
- 0, batch - 1, self.grid_size + 1, dtype=torch.int64, device=x.device
- )
- ]
- uniform_step = (x_sorted[-1] - x_sorted[0] + 2 * margin) / self.grid_size
- grid_uniform = (
- torch.arange(
- self.grid_size + 1, dtype=torch.float32, device=x.device
- ).unsqueeze(1)
- * uniform_step
- + x_sorted[0]
- - margin
- )
- grid = self.grid_eps * grid_uniform + (1 - self.grid_eps) * grid_adaptive
- grid = torch.concatenate(
- [
- grid[:1]
- - uniform_step
- * torch.arange(self.spline_order, 0, -1, device=x.device).unsqueeze(1),
- grid,
- grid[-1:]
- + uniform_step
- * torch.arange(1, self.spline_order + 1, device=x.device).unsqueeze(1),
- ],
- dim=0,
- )
- self.grid.copy_(grid.T)
- self.spline_weight.data.copy_(self.curve2coeff(x, unreduced_spline_output))
- def regularization_loss(self, regularize_activation=1.0, regularize_entropy=1.0):
- """
- Compute the regularization loss.
- This is a dumb simulation of the original L1 regularization as stated in the
- paper, since the original one requires computing absolutes and entropy from the
- expanded (batch, in_features, out_features) intermediate tensor, which is hidden
- behind the F.linear function if we want an memory efficient implementation.
- The L1 regularization is now computed as mean absolute value of the spline
- weights. The authors implementation also includes this term in addition to the
- sample-based regularization.
- """
- l1_fake = self.spline_weight.abs().mean(-1)
- regularization_loss_activation = l1_fake.sum()
- p = l1_fake / regularization_loss_activation
- regularization_loss_entropy = -torch.sum(p * p.log())
- return (
- regularize_activation * regularization_loss_activation
- + regularize_entropy * regularization_loss_entropy
- )
- def output_model(MethyBasset_part1,MethyBasset_part2,savepath = f"../sample_data/output/"):
- import os
- if not os.path.exists(savepath):
- os.makedirs(savepath)
- print("Folder created")
- else:
- print("Folder already exists")
- torch.save(MethyBasset_part1.state_dict(), f"{savepath}/scMethCraft_part1.pth")
- torch.save(MethyBasset_part2.state_dict(), f"{savepath}/scMethCraft_part2.pth")
scmethcraft_model.py at commit 6c2ef56, under MIT · at the source
Overview
- School of Mathematical Sciences and LPMC, Nankai University,Tianjin, China
- SeekGene BioSciences, Beijing, China
- Department of Mechanical and Aerospace Engineering, The University of Manchester,Manchester, UK
- Sheffield Institute for Translational Neuroscience, University of Sheffield,Sheffield, UK
- Academy for Advanced Interdisciplinary Studies, Nankai University,Tianjin, China
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
2fdeeb3b44379408794154993dbd6101b8946b7e, 16 January 2026Availability: 1 check, the latest on 26 September 2026: the link answers
- 26 September 2026: the link answers
27 files
- ContinuousAnnotations/
quantile_M.pl , Perl, 241 lines - ContinuousAnnotations/
quantile_h2g.r , R, 76 lines - ldsc.py, Python, 660 lines, 1 match
- ldscore/
__init__.py , Python, 1 line - ldscore/
irwls.py , Python, 196 lines - ldscore/
jackknife.py , Python, 514 lines - ldscore/
ldscore.py , Python, 415 lines - ldscore/
parse.py , Python, 292 lines - ldscore/
regressions.py , Python, 743 lines, 1 match - ldscore/
sumstats.py , Python, 581 lines - make_annot.py, Python, 56 lines
- munge_sumstats.py, Python, 745 lines
- setup.py, Python, 20 lines
- test/
parse_test/ , MATLAB, 1 linetest.l2.M - test/
parse_test/ , MATLAB, 1 linetest1.l2.M - test/
parse_test/ , MATLAB, 1 linetest2.l2.M - test/
parse_test/ , MATLAB, 1 linetest_bad.l2.M - test/
simulate.py , Python, 81 lines - test/
test_irwls.py , Python, 69 lines - test/
test_jackknife.py , Python, 267 lines - test/
test_ldscore.py , Python, 111 lines - test/
test_munge_sumstats.py , Python, 358 lines - test/
test_parse.py , Python, 129 lines - test/
test_regressions.py , Python, 342 lines - test/
test_sumstats.py , Python, 487 lines - LICENSE, License, 675 lines
- README.md, Text, 122 lines
BioX-NKU/scMethCraft
6c2ef5613c1edd87036d1a982d2ffea118955f05, 10 September 2026Availability: 1 check, the latest on 28 September 2026: the link answers
- 28 September 2026: the link answers
39 files
- scMethCraft/
__init__.py , Python, 1 line - scMethCraft/
benchmark/ , Python, 1 line__init__.py - scMethCraft/
benchmark/ , Python, 134 linesmethyimp.py - scMethCraft/
function/ , Python, 59 lines, 1 matchDMR.py - scMethCraft/
function/ , Python, 1 line__init__.py - scMethCraft/
function/ , Python, 39 linesannotation.py - scMethCraft/
function/ , Python, 55 linesbatch.py - scMethCraft/
function/ , Python, 20 linesembedding.py - scMethCraft/
function/ , Python, 38 linesenhancement.py - scMethCraft/
model/ , Python, 1 line__init__.py - scMethCraft/
model/ , Python, 41 linescompute_pos.py - scMethCraft/
model/ , Python, 67 lineslayers.py - scMethCraft/
model/ , Python, 762 lines, 4 matchesscmethcraft_model.py - scMethCraft/
model/ , Python, 141 linesscmethcraft_trainning.py - scMethCraft/
model/ , Python, 42 linesutils_model.py - scMethCraft/
postprocessing/ , Python, 1 line__init__.py - scMethCraft/
postprocessing/ , Python, 16 linessimilarity_norm.py - scMethCraft/
preprocessing/ , Python, 1 line__init__.py - scMethCraft/
preprocessing/ , Python, 368 linescreate_count_matrix.py - scMethCraft/
preprocessing/ , Python, 241 linesretrive_sequence.py - setup.py, Python, 34 lines
- tutorial/
.ipynb_checkpoints/ , Jupyter, 30 linestutorial_DMR_identificat ion-checkpoint.ipynb - tutorial/
.ipynb_checkpoints/ , Jupyter, 28 linestutorial_annotation-chec kpoint.ipynb - tutorial/
.ipynb_checkpoints/ , Jupyter, 66 linestutorial_batch_integrati on-checkpoint.ipynb - tutorial/
.ipynb_checkpoints/ , Jupyter, 73 linestutorial_cell_embedding- checkpoint.ipynb - tutorial/
.ipynb_checkpoints/ , Jupyter, 71 linestutorial_create_training _datasets-checkpoint.ipy nb - tutorial/
.ipynb_checkpoints/ , Jupyter, 63 linestutorial_data_enhancemen t-checkpoint.ipynb - tutorial/
.ipynb_checkpoints/ , Jupyter, 83 linestutorial_model_training- checkpoint.ipynb - tutorial/
.ipynb_checkpoints/ , Jupyter, 140 linestutorial_model_training_ detail-checkpoint.ipynb - tutorial/
tutorial_DMR_identificat , Jupyter, 30 linesion.ipynb - tutorial/
tutorial_annotation.ipyn , Jupyter, 28 linesb - tutorial/
tutorial_batch_integrati , Jupyter, 63 lineson.ipynb - tutorial/
tutorial_cell_embedding. , Jupyter, 73 linesipynb - tutorial/
tutorial_create_training , Jupyter, 71 lines_datasets.ipynb - tutorial/
tutorial_data_enhancemen , Jupyter, 63 linest.ipynb - tutorial/
tutorial_model_training. , Jupyter, 83 lines, 1 matchipynb - tutorial/
tutorial_model_training_ , Jupyter, 140 linesdetail.ipynb - LICENSE, License, 21 lines
- README.md, Text, 95 lines
Zenodo 19549979
Availability: 1 check, the latest on 28 September 2026: the link answers (HTTP 200)
- 28 September 2026: the link answers (HTTP 200)
31 files
- scMethCraft/
__init__.py , Python, 1 line - scMethCraft/
benchmark/ , Python, 1 line__init__.py - scMethCraft/
benchmark/ , Python, 134 linesmethyimp.py - scMethCraft/
function/ , Python, 59 linesDMR.py - scMethCraft/
function/ , Python, 1 line__init__.py - scMethCraft/
function/ , Python, 39 linesannotation.py - scMethCraft/
function/ , Python, 55 linesbatch.py - scMethCraft/
function/ , Python, 20 linesembedding.py - scMethCraft/
function/ , Python, 29 linesenhancement.py - scMethCraft/
model/ , Python, 1 line__init__.py - scMethCraft/
model/ , Python, 41 linescompute_pos.py - scMethCraft/
model/ , Python, 67 lineslayers.py - scMethCraft/
model/ , Python, 762 lines, 4 matchesscmethcraft_model.py - scMethCraft/
model/ , Python, 141 linesscmethcraft_trainning.py - scMethCraft/
model/ , Python, 42 linesutils_model.py - scMethCraft/
postprocessing/ , Python, 1 line__init__.py - scMethCraft/
postprocessing/ , Python, 16 linessimilarity_norm.py - scMethCraft/
preprocessing/ , Python, 1 line__init__.py - scMethCraft/
preprocessing/ , Python, 368 linescreate_count_matrix.py - scMethCraft/
preprocessing/ , Python, 240 linesretrive_sequence.py - setup.py, Python, 34 lines
- tutorial/
tutorial_DMR_identificat , Jupyter, 30 linesion.ipynb - tutorial/
tutorial_annotation.ipyn , Jupyter, 28 linesb - tutorial/
tutorial_batch_integrati , Jupyter, 63 lineson.ipynb - tutorial/
tutorial_cell_embedding. , Jupyter, 73 linesipynb - tutorial/
tutorial_create_training , Jupyter, 71 lines_datasets.ipynb - tutorial/
tutorial_data_enhancemen , Jupyter, 63 linest.ipynb - tutorial/
tutorial_model_training. , Jupyter, 83 linesipynb - tutorial/
tutorial_model_training_ , Jupyter, 140 linesdetail.ipynb - LICENSE.txt, License, 21 lines
- README.md, Text, 91 lines
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:
- it points to the authors' code: BioX-NKU/
scMethCraft
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
- geo:GSE130553, at NCBI GEO; found in “Data availability”
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:
- it points to a dataset: NCBI GEO GSE130553
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://
BibTeX
@article{tang2026dissect
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/
url = {https://
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/
VL - 17
IS - 1
SP - 6469
SN - 2041-1723
PB - Nature Publishing Group
DO - 10.1038/
UR - https://
LA - en
ER -
CSL-JSON
{
"id": "10.1038/
"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":
"volume": "17",
"issue": "1",
"page": "6469",
"DOI": "10.1038/
"PMID": "42140984",
"PMCID": "PMC13376737",
"ISSN": "2041-1723",
"publisher": "Nature Publishing Group",
"URL": "https://
"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 researchIn 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 biologyIn 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 methodsIn 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 communicationsIn 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 reportsIn 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 biologyIn 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 bioinformaticsIn 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 reportsIn 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.
Claim this paper
Correct its record
Say what each link of this record is, remove the ones that are not the paper's, add the ones that are missing. The correction becomes a new version of the record, in its Versions section.
Validate its tracing map
You validate the map as this page shows it: 3 repositories of the authors' code, each at its verified commit and with its license, 91 scripts, and 12 matches between paragraphs and code (see the Code and Map sections). It then receives a DOI on Zenodo, with you (your ORCID iD) and OSCR as its creators; the code itself is not deposited.
The map's fingerprint: sha256:a82e401f5c996f1a…
Add the badge to its README
The badge links the code to this page. Copy one of these into the README of the paper's code: only you decide where it goes, and nothing is changed for you.
Markdown
[, paste the snippet at the top, then “Commit changes…” and, to review it first, “Create a new branch and start a pull request”. You open the pull request; OSCR asks for no permission.
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.
