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|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 1 |
+
import os
|
| 2 |
+
import numpy as np
|
| 3 |
+
from enum import IntEnum
|
| 4 |
+
import datasets
|
| 5 |
+
|
| 6 |
+
|
| 7 |
+
logger = datasets.logging.get_logger(__name__)
|
| 8 |
+
|
| 9 |
+
|
| 10 |
+
_CITATION = """\
|
| 11 |
+
@article{iwano2022generative,
|
| 12 |
+
title={Generative aptamer discovery using RaptGen},
|
| 13 |
+
author={Iwano, Natsuki and Adachi, Tatsuo and Aoki, Kazuteru and Nakamura, Yoshikazu and Hamada, Michiaki},
|
| 14 |
+
journal={Nature Computational Science},
|
| 15 |
+
pages={1--9},
|
| 16 |
+
year={2022},
|
| 17 |
+
publisher={Nature Publishing Group}
|
| 18 |
+
}
|
| 19 |
+
"""
|
| 20 |
+
|
| 21 |
+
_DESCRIPTION = """\
|
| 22 |
+
https://github.com/hmdlab/raptgen/blob/master/raptgen/data.py
|
| 23 |
+
"""
|
| 24 |
+
|
| 25 |
+
|
| 26 |
+
class SNV(IntEnum):
|
| 27 |
+
Mutation = 0
|
| 28 |
+
Insertion = 1
|
| 29 |
+
Deletion = 2
|
| 30 |
+
|
| 31 |
+
|
| 32 |
+
class SequenceGenerator():
|
| 33 |
+
def __init__(self, num_motifs=1, motif_length=10, motifs=None,
|
| 34 |
+
target_length=20, fix_random_region_length=True, error_rate=0, generate_motifs=True, middle_insert_range=(2, 6),
|
| 35 |
+
seed=0, add_primer=True, forward_primer="AAAAA", reverse_primer="GGGGG", one_side_proba=0.5, paired=False):
|
| 36 |
+
np.random.seed(seed)
|
| 37 |
+
|
| 38 |
+
if generate_motifs:
|
| 39 |
+
self.motifs = ["".join(np.random.choice(
|
| 40 |
+
list("ATGC"), motif_length)) for _ in range(num_motifs)]
|
| 41 |
+
else:
|
| 42 |
+
self.motifs = motifs
|
| 43 |
+
|
| 44 |
+
self.error_indices = 1 + \
|
| 45 |
+
np.argsort(np.random.random(size=motif_length-1))[:3]
|
| 46 |
+
self.mut_idx, self.ins_idx, self.del_idx = self.error_indices
|
| 47 |
+
|
| 48 |
+
logger.info(f"error rate is {error_rate*100:.1f}%")
|
| 49 |
+
for idx, motif in enumerate(self.motifs):
|
| 50 |
+
seq = [ch for ch in motif]
|
| 51 |
+
mut = self.mutate(seq[self.mut_idx])
|
| 52 |
+
if error_rate != 0:
|
| 53 |
+
seq[self.mut_idx] = f"[{seq[self.mut_idx]}>{mut}]"
|
| 54 |
+
seq[self.ins_idx] = f"[+]{seq[self.ins_idx]}"
|
| 55 |
+
seq[self.del_idx] = f"{seq[self.del_idx].lower()}"
|
| 56 |
+
seq = "".join(seq)
|
| 57 |
+
logger.info(f"motif {idx} is {seq}")
|
| 58 |
+
|
| 59 |
+
self.num_motifs = num_motifs
|
| 60 |
+
self.error_rate = error_rate
|
| 61 |
+
self.target_length = target_length
|
| 62 |
+
self.forward_primer = forward_primer
|
| 63 |
+
self.reverse_primer = reverse_primer
|
| 64 |
+
self.add_primer = add_primer
|
| 65 |
+
|
| 66 |
+
self.one_side_proba = one_side_proba
|
| 67 |
+
self.middle_insert_range = middle_insert_range
|
| 68 |
+
self.paired = paired
|
| 69 |
+
|
| 70 |
+
def mutate(self, char):
|
| 71 |
+
return "TGCA"["ATGC".index(char)]
|
| 72 |
+
|
| 73 |
+
def sample_motif(self, n):
|
| 74 |
+
motif_indices = np.random.randint(self.num_motifs, size=n)
|
| 75 |
+
has_errors = np.random.random(size=n) < self.error_rate
|
| 76 |
+
# mutation, insertion, deletion
|
| 77 |
+
error_types = np.random.choice(SNV, size=n)
|
| 78 |
+
sequences = []
|
| 79 |
+
for motif_index, has_error, error_type in zip(motif_indices, has_errors, error_types):
|
| 80 |
+
motif = self.motifs[motif_index]
|
| 81 |
+
seq = [ch for ch in motif]
|
| 82 |
+
if has_error:
|
| 83 |
+
if error_type == SNV.Mutation:
|
| 84 |
+
seq[self.mut_idx] = self.mutate(seq[self.mut_idx])
|
| 85 |
+
elif error_type == SNV.Insertion:
|
| 86 |
+
seq[self.ins_idx] = np.random.choice(
|
| 87 |
+
list("ATGC")) + seq[self.ins_idx]
|
| 88 |
+
elif error_type == SNV.Deletion:
|
| 89 |
+
seq[self.del_idx] = ""
|
| 90 |
+
else:
|
| 91 |
+
raise NotImplementedError
|
| 92 |
+
seq = "".join(seq)
|
| 93 |
+
sequences.append(seq)
|
| 94 |
+
return sequences, motif_indices.tolist()
|
| 95 |
+
|
| 96 |
+
def sample(self, n=1, with_indices=True):
|
| 97 |
+
motifs, motif_indices = self.sample_motif(n)
|
| 98 |
+
sequences = []
|
| 99 |
+
paired_indices = []
|
| 100 |
+
for seq in motifs:
|
| 101 |
+
if self.paired:
|
| 102 |
+
seq, idx = self.insert_in_the_middle(
|
| 103 |
+
seq, nrange=self.middle_insert_range, one_side_proba=self.one_side_proba)
|
| 104 |
+
paired_indices += [idx]
|
| 105 |
+
random_region = "".join(np.random.choice(
|
| 106 |
+
list("ATGC"), size=self.target_length-len(seq)))
|
| 107 |
+
l = np.random.randint(len(random_region))
|
| 108 |
+
if self.add_primer:
|
| 109 |
+
sequences.append(
|
| 110 |
+
self.forward_primer + random_region[:l] + seq + random_region[l:] + self.reverse_primer)
|
| 111 |
+
else:
|
| 112 |
+
sequences.append(random_region[:l] + seq + random_region[l:])
|
| 113 |
+
|
| 114 |
+
if self.paired and with_indices:
|
| 115 |
+
return sequences, motif_indices, paired_indices
|
| 116 |
+
elif with_indices:
|
| 117 |
+
return sequences, motif_indices
|
| 118 |
+
return sequences
|
| 119 |
+
|
| 120 |
+
def insert_in_the_middle(self, sequence, nrange=(2, 6), one_side_proba=0.5):
|
| 121 |
+
n = np.random.randint(*nrange)
|
| 122 |
+
if np.random.random() < one_side_proba:
|
| 123 |
+
if np.random.choice(["l", "r"]) == "l":
|
| 124 |
+
l_motif = sequence[:len(sequence)//2]
|
| 125 |
+
r_motif = ""
|
| 126 |
+
idx = 1
|
| 127 |
+
else:
|
| 128 |
+
l_motif = ""
|
| 129 |
+
r_motif = sequence[len(sequence)//2:]
|
| 130 |
+
idx = 2
|
| 131 |
+
else:
|
| 132 |
+
l_motif = sequence[:len(sequence)//2]
|
| 133 |
+
r_motif = sequence[len(sequence)//2:]
|
| 134 |
+
idx = 0
|
| 135 |
+
return l_motif + "".join(np.random.choice(list("ATGC"), size=n)) + r_motif, idx
|
| 136 |
+
|
| 137 |
+
|
| 138 |
+
|
| 139 |
+
class SimulationConfig(datasets.BuilderConfig):
|
| 140 |
+
def __init__(self, n_seq, num_motifs=1, motif_length=10, error_rate=0.0, seed=0, add_primer=False, **kwargs):
|
| 141 |
+
super(SimulationConfig, self).__init__(**kwargs)
|
| 142 |
+
self.n_seq = n_seq
|
| 143 |
+
self.num_motifs = num_motifs
|
| 144 |
+
self.motif_length = motif_length
|
| 145 |
+
self.error_rate = error_rate
|
| 146 |
+
self.seed = seed
|
| 147 |
+
self.add_primer = add_primer
|
| 148 |
+
if kwargs['name']=="paired":
|
| 149 |
+
self.paired = True
|
| 150 |
+
else:
|
| 151 |
+
self.paired = False
|
| 152 |
+
|
| 153 |
+
|
| 154 |
+
class Simulation(datasets.GeneratorBasedBuilder):
|
| 155 |
+
|
| 156 |
+
BUILDER_CONFIGS = [
|
| 157 |
+
SimulationConfig(name="multiple", num_motifs=10, error_rate=0.1, n_seq=10000, seed=0),
|
| 158 |
+
SimulationConfig(name="paired", n_seq=5000, seed=0)
|
| 159 |
+
]
|
| 160 |
+
|
| 161 |
+
DEFAULT_CONFIG_NAME = "multiple"
|
| 162 |
+
|
| 163 |
+
def _info(self):
|
| 164 |
+
return datasets.DatasetInfo(
|
| 165 |
+
description=_DESCRIPTION,
|
| 166 |
+
features=datasets.Features(
|
| 167 |
+
{
|
| 168 |
+
"id": datasets.Value("int32"),
|
| 169 |
+
"seq": datasets.Value("string"),
|
| 170 |
+
"motif_ids": datasets.Value("int32"),
|
| 171 |
+
"motif": datasets.Value("string"),
|
| 172 |
+
}
|
| 173 |
+
),
|
| 174 |
+
homepage="https://github.com/hmdlab/raptgen/blob/master/raptgen/data.py",
|
| 175 |
+
citation=_CITATION,
|
| 176 |
+
)
|
| 177 |
+
|
| 178 |
+
def _split_generators(self, dl_manager):
|
| 179 |
+
# downloaded_files = dl_manager.download_and_extract(self.config.url)
|
| 180 |
+
gen_kwargs = {"num_motifs": self.config.num_motifs,
|
| 181 |
+
"motif_length": self.config.motif_length,
|
| 182 |
+
"error_rate": self.config.error_rate,
|
| 183 |
+
"seed": self.config.seed,
|
| 184 |
+
"add_primer": self.config.add_primer,
|
| 185 |
+
"sample_num": self.config.n_seq
|
| 186 |
+
}
|
| 187 |
+
return [
|
| 188 |
+
datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs=gen_kwargs),
|
| 189 |
+
]
|
| 190 |
+
|
| 191 |
+
def _generate_examples(self, num_motifs, motif_length, error_rate, seed, add_primer, sample_num):
|
| 192 |
+
# """This function returns the examples in the raw (text) form."""
|
| 193 |
+
# logger.info("generating examples from = %s", filepath)
|
| 194 |
+
simulator = SequenceGenerator(num_motifs=num_motifs, motif_length=motif_length,
|
| 195 |
+
error_rate=error_rate, seed=seed,
|
| 196 |
+
add_primer=add_primer)
|
| 197 |
+
data = simulator.sample(sample_num)
|
| 198 |
+
motifs = simulator.motifs
|
| 199 |
+
for key, (seq, motif_ids, label) in enumerate(zip(data[0], data[1], data[-1])):
|
| 200 |
+
yield key, {"id": key,
|
| 201 |
+
"seq": seq,
|
| 202 |
+
"motif_ids": label,
|
| 203 |
+
"motif": motifs[motif_ids]
|
| 204 |
+
}
|
| 205 |
+
|
| 206 |
+
|
| 207 |
+
if __name__=="__main__":
|
| 208 |
+
from datasets import load_dataset
|
| 209 |
+
dataset = load_dataset("simulation.py", name="paired", split="all")
|
| 210 |
+
print(dataset)
|
| 211 |
+
dataset = load_dataset("simulation.py", name="multiple", split="all")
|
| 212 |
+
print(dataset)
|
| 213 |
+
|
| 214 |
+
|