Download data_utils.py from nicolynnvila/pre-train_variability_af250: direct link, hf CLI and curl.
- Browser
- Download file 1.83 kB
-
https://huggingface.co/datasets/nicolynnvila/pre-train_variability_af250/resolve/main/data_utils.py
- Command line
-
hf download hf://datasets/nicolynnvila/pre-train_variability_af250/data_utils.py
-
curl -L -o data_utils.py https://huggingface.co/datasets/nicolynnvila/pre-train_variability_af250/resolve/main/data_utils.py
1.83 kB
| import os | |
| import numpy as np | |
| import random | |
| import torch | |
| from torch.utils.data import Dataset, DataLoader | |
| class Hg38VariableDataset(Dataset): | |
| def __init__(self, data_dir='data', window_size=10_000): | |
| self.data_dir = data_dir | |
| self.window_size = window_size | |
| self.chromosomes = self._load_chromosomes() | |
| self.chromosome_lengths = {k: v.shape[-1] for k, v in self.chromosomes.items()} | |
| self.chromosome_names = list(self.chromosomes.keys()) | |
| self.nucleotides = np.array(['A', 'T', 'G', 'C', 'N']) | |
| def _load_chromosomes(self): | |
| chromosomes = {} | |
| for filename in sorted(os.listdir(self.data_dir)): | |
| if filename.endswith(".npz"): | |
| chrom_name = filename.split(".")[0] # Use file name (e.g., "chr1") | |
| matrix = np.load(os.path.join(self.data_dir, filename))['data'] | |
| chromosomes[chrom_name] = matrix | |
| return chromosomes | |
| def select_nucleotide_fast(self, matrix): | |
| choices = np.argmax(matrix * np.random.rand(*matrix.shape), axis=0) | |
| return ''.join(self.nucleotides[choices]) | |
| def __len__(self): | |
| return sum(self.chromosome_lengths.values()) | |
| def __getitem__(self, idx): | |
| chrom = random.choice(self.chromosome_names) | |
| chrom_length = self.chromosome_lengths[chrom] | |
| start = np.random.randint(0, chrom_length - self.window_size) | |
| sequence = self.select_nucleotide_fast(self.chromosomes[chrom][:, start:start + self.window_size]) | |
| return { | |
| 'chromosome': chrom, | |
| 'start': start, | |
| 'sequence': sequence | |
| } | |
| # # # Example usage | |
| # dataset = Hg38VariableDataset() | |
| # data_loader = DataLoader(dataset, batch_size=32, shuffle=True) | |
| # # Iterate over batches | |
| # for batch in data_loader: | |
| # break | |