suke-sho commited on
Commit
bd3d49c
1 Parent(s): 9c15511

Create multi-model-plant-genome-corpus.py

Browse files
Files changed (1) hide show
  1. multi-model-plant-genome-corpus.py +125 -0
multi-model-plant-genome-corpus.py ADDED
@@ -0,0 +1,125 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ from typing import List
2
+ import datasets
3
+ from Bio import SeqIO
4
+ import os
5
+
6
+ _CITATION = ""
7
+ _DESCRIPTION = """
8
+
9
+ Dataset made of model plants genomes available on NCBI.
10
+ Default configuration "6kbp" yields chunks of 6.2kbp (100bp overlap on each side). The chunks of DNA are cleaned and processed so that
11
+ they can only contain the letters A, T, C, G and N.
12
+ """
13
+ _HOMEPAGE = "https://www.ncbi.nlm.nih.gov/"
14
+ _LICENSE = "https://www.ncbi.nlm.nih.gov/home/about/policies/"
15
+ _CHUNK_LENGTHS = [6000,]
16
+
17
+ def filter_fn(char: str) -> str:
18
+ """
19
+ Transforms any letter different from a base nucleotide into an 'N'.
20
+ """
21
+ if char in {'A', 'T', 'C', 'G'}:
22
+ return char
23
+ else:
24
+ return 'N'
25
+
26
+ def clean_sequence(seq: str) -> str:
27
+ """
28
+ Process a chunk of DNA to have all letters in upper and restricted to
29
+ A, T, C, G and N.
30
+ """
31
+ seq = seq.upper()
32
+ seq = map(filter_fn, seq)
33
+ seq = ''.join(list(seq))
34
+ return seq
35
+
36
+ class PlantMultiSpeciesGenomesConfig(datasets.BuilderConfig):
37
+ """BuilderConfig for the Plant Multi Species Pre-training Dataset."""
38
+ Copy codedef __init__(self, *args, chunk_length: int, overlap: int = 100, **kwargs):
39
+ """BuilderConfig for the multi species genomes.
40
+ Args:
41
+ chunk_length (:obj:`int`): Chunk length.
42
+ overlap: (:obj:`int`): Overlap in base pairs for two consecutive chunks (defaults to 100).
43
+ **kwargs: keyword arguments forwarded to super.
44
+ """
45
+ num_kbp = int(chunk_length/1000)
46
+ super().__init__(
47
+ *args,
48
+ name=f'{num_kbp}kbp',
49
+ **kwargs,
50
+ )
51
+ self.chunk_length = chunk_length
52
+ self.overlap = overlap
53
+
54
+ class PlantMultiSpeciesGenomes(datasets.GeneratorBasedBuilder):
55
+ """Genomes from multiple plant species, filtered and split into chunks of consecutive
56
+ nucleotides."""
57
+ Copy codeVERSION = datasets.Version("1.1.0")
58
+ BUILDER_CONFIG_CLASS = PlantMultiSpeciesGenomesConfig
59
+ BUILDER_CONFIGS = [PlantMultiSpeciesGenomesConfig(chunk_length=chunk_length) for chunk_length in _CHUNK_LENGTHS]
60
+ DEFAULT_CONFIG_NAME = "6kbp"
61
+
62
+ def _info(self):
63
+
64
+ features = datasets.Features(
65
+ {
66
+ "sequence": datasets.Value("string"),
67
+ "description": datasets.Value("string"),
68
+ "start_pos": datasets.Value("int32"),
69
+ "end_pos": datasets.Value("int32"),
70
+ }
71
+ )
72
+ return datasets.DatasetInfo(
73
+ description=_DESCRIPTION,
74
+ features=features,
75
+ homepage=_HOMEPAGE,
76
+ license=_LICENSE,
77
+ citation=_CITATION,
78
+ )
79
+
80
+ def _split_generators(self, dl_manager: datasets.DownloadManager) -> List[datasets.SplitGenerator]:
81
+ # Get the list of genome files in the plant_genomes directory
82
+ genome_dir = "plant_genomes"
83
+ genome_files = [os.path.join(genome_dir, f) for f in os.listdir(genome_dir) if f.endswith(".fna.gz")]
84
+
85
+ return [
86
+ datasets.SplitGenerator(name=datasets.Split.TRAIN, gen_kwargs={"files": genome_files, "chunk_length": self.config.chunk_length})
87
+ ]
88
+
89
+ # method parameters are unpacked from `gen_kwargs` as given in `_split_generators`
90
+ def _generate_examples(self, files, chunk_length):
91
+ key = 0
92
+ for file in files:
93
+ with open(file, 'rt') as f:
94
+ fasta_sequences = SeqIO.parse(f, 'fasta')
95
+
96
+ for record in fasta_sequences:
97
+ sequence, description = str(record.seq), record.description
98
+
99
+ # clean chromosome sequence
100
+ sequence = clean_sequence(sequence)
101
+ seq_length = len(sequence)
102
+
103
+ # split into chunks
104
+ num_chunks = (seq_length - 2 * self.config.overlap) // chunk_length
105
+
106
+ if num_chunks < 1:
107
+ continue
108
+
109
+ sequence = sequence[:(chunk_length * num_chunks + 2 * self.config.overlap)]
110
+ seq_length = len(sequence)
111
+
112
+ for i in range(num_chunks):
113
+ # get chunk
114
+ start_pos = i * chunk_length
115
+ end_pos = min(seq_length, (i+1) * chunk_length + 2 * self.config.overlap)
116
+ chunk_sequence = sequence[start_pos:end_pos]
117
+
118
+ # yield chunk
119
+ yield key, {
120
+ 'sequence': chunk_sequence,
121
+ 'description': description,
122
+ 'start_pos': start_pos,
123
+ 'end_pos': end_pos,
124
+ }
125
+ key += 1</document_content>