suke-sho commited on
Commit
782fb0c
1 Parent(s): be408c8

Upload plant-multi-species-genomes.py

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