Genome_database / Genome_database.py
wyxu's picture
Update Genome_database.py
4dfcfec
raw
history blame
6.08 kB
import datasets
from Bio import SeqIO
from Bio.SeqUtils import gc_fraction
from typing import Any, Dict, List, Tuple
import os
import gzip
import re
class GenomeDatasetConfig(datasets.BuilderConfig):
def __init__(self,*args, num_urls: int, **kwargs):
super(GenomeDatasetConfig, self).__init__(**kwargs)
self.num_urls = num_urls
class GenomeDataset(datasets.GeneratorBasedBuilder):
VERSION = datasets.Version("1.1.0")
BUILDER_CONFIG_CLASS = GenomeDatasetConfig
def _info(self):
return datasets.DatasetInfo(
features=datasets.Features({
"DNA_id": datasets.Value("string"),
"organism": datasets.Value("string"),
"year": datasets.Value("string"),
"region_type": datasets.Value("string"),
"specific_class": datasets.Value("string"),
"product": datasets.Value("string"),
"sequence": datasets.Value("string"),
"gc_content": datasets.Value("float"),
"translation_code": datasets.Value("string"),
"start_postion": datasets.Value("int32"),
"end_position": datasets.Value("int32"),
})
)
# def load_genome_dataset(num_urls=None):
# builder_kwargs = {}
# if num_urls is not None:
# builder_kwargs['config'] = GenomeDatasetConfig(num_urls=num_urls)
# return load_dataset("GenomeDataset", builder_kwargs=builder_kwargs)
def _split_generators(self, dl_manager: datasets.DownloadManager) -> List[datasets.SplitGenerator]:
urls_filepath = dl_manager.download_and_extract('urlfile.txt')
with open(urls_filepath) as urls_file:
downloaded_files = [line.rstrip() for line in urls_file]
num_urls = self.config.num_urls or len(downloaded_files)
downloaded_files = downloaded_files[:num_urls]
train_files = downloaded_files[:int(len(downloaded_files) * 0.8)] # first 80% for training
test_files = downloaded_files[int(len(downloaded_files) * 0.8):] # last 20% for testing
return [
datasets.SplitGenerator(
name=datasets.Split.TRAIN,
gen_kwargs={"filepaths": train_files}
),
datasets.SplitGenerator(
name=datasets.Split.TEST,
gen_kwargs={"filepaths": test_files}
)
]
def _generate_examples(self, filepaths: List[str]) -> Tuple[str, Dict[str, Any]]:
split_regex = re.compile('-')
id_ = 0
for filepath in filepaths:
if filepath.endswith(".seq.gz"):
with gzip.open(filepath, 'rt') as handle:
for record in SeqIO.parse(handle, "genbank"):
if 'molecule_type' in record.annotations and record.annotations['molecule_type'] == 'DNA':
organism = record.annotations.get('organism', 'unknown')
collection_date = record.annotations.get('date', 'unknown')
year = split_regex.split(collection_date)[-1] if '-' in collection_date else collection_date
for feature in record.features:
seq = feature.extract(record.seq)
gc_content = gc_fraction(seq)
start_position = int(feature.location.start)
end_position = int(feature.location.end)
if feature.type in ['rRNA', 'tRNA','CDS','tmRNA','mRNA','mat_peptide','sig_peptide','propeptide']:
region_type = 'coding'
product = feature.qualifiers.get('product', ['Unknown'])[0]
if feature.type == 'CDS':
translation = feature.qualifiers.get('translation', ['NA'])[0]
specific_class = 'Protein'
else:
translation = 'NA'
specific_class = feature.type
elif feature.type == 'regulatory':
region_type = feature.type
specific_class = feature.qualifiers.get('regulatory_class', ['regulatory'])[0]
translation = 'NA'
product = feature.qualifiers.get('product', ['NA'])[0]
elif feature.type == 'gene':
continue
else:
if 'product' in feature.qualifiers:
product = feature.qualifiers.get('product')[0]
region_type = 'coding'
specific_class = feature.type
else:
product = 'NA'
region_type = feature.type
specific_class = 'NA'
translation = 'NA'
yield str(id_), {
'DNA_id': record.id,
'organism': organism,
'year': year,
'region_type': region_type,
'specific_class': specific_class,
'product': product,
'sequence': str(seq),
'gc_content': gc_content,
'translation_code': translation,
'start_postion': start_position,
'end_position': end_position
}
id_+= 1