Commit ·
dfced34
1
Parent(s): 3e877aa
first commit
Browse filesFiles changed (5)
52 unmodified lines53545552 unmodified lines*.jpg filter=lfs diff=lfs merge=lfs -text*.jpeg filter=lfs diff=lfs merge=lfs -text*.webp filter=lfs diff=lfs merge=lfs -text52 unmodified lines53545556575852 unmodified lines*.jpg filter=lfs diff=lfs merge=lfs -text*.jpeg filter=lfs diff=lfs merge=lfs -text*.webp filter=lfs diff=lfs merge=lfs -texttranscript_expression/expression_values_v1.csv filter=lfs diff=lfs merge=lfs -texttranscript_expression/expression_values_v2.csv filter=lfs diff=lfs merge=lfs -texttranscript_expression/transcript_coordinates.csv filter=lfs diff=lfs merge=lfs -text
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366import logging
import datasetsimport gzipimport osimport pandas as pdimport reimport shutilimport urllibfrom abc import ABC, abstractmethodfrom datasets import DatasetInfofrom pathlib import Pathfrom pyfaidx import Fastafrom tqdm import tqdmfrom typing import List
"""--------------------------------------------------------------------------------------------Reference Genome URLS:-------------------------------------------------------------------------------------------"""H38_REFERENCE_GENOME_URL = ( "https://hgdownload.soe.ucsc.edu/goldenPath/hg38/bigZips/" "hg38.fa.gz")
"""--------------------------------------------------------------------------------------------Task Specific Handlers:-------------------------------------------------------------------------------------------"""
logger = logging.getLogger("multi_omics_bulk_rna")logger.setLevel("INFO")
class GenomicLRATaskHandler(ABC): """ Abstract method for the Genomic LRA task handlers. Each handler """
@abstractmethod def __init__(self, **kwargs): pass
@abstractmethod def get_info(self, description: str) -> DatasetInfo: """ Returns the DatasetInfo for the task """ pass
def split_generators( self, dl_manager, cache_dir_root ) -> List[datasets.SplitGenerator]: """ Downloads required files using dl_manager and separates them by split. """ return [ datasets.SplitGenerator( name=datasets.Split.TRAIN, gen_kwargs={"handler": self, "split": "train"}, ), datasets.SplitGenerator( name=datasets.Split.TEST, gen_kwargs={"handler": self, "split": "test"} ), ]
@abstractmethod def generate_examples(self, split): """ A generator that yields examples for the specified split. """ pass
@staticmethod def hook(t): last_b = [0]
def inner(b=1, bsize=1, tsize=None): """ b : int, optional Number of blocks just transferred [default: 1]. bsize : int, optional Size of each block (in tqdm units) [default: 1]. tsize : int, optional Total size (in tqdm units). If [default: None] remains unchanged. """ if tsize is not None: t.total = tsize t.update((b - last_b[0]) * bsize) last_b[0] = b
return inner
def download_and_extract_gz(self, file_url, cache_dir_root): """ Downloads and extracts a gz file into the given cache directory. Returns the full file path of the extracted gz file. Args: file_url: url of the gz file to be downloaded and extracted. cache_dir_root: Directory to extract file into. """ file_fname = Path(file_url).stem file_complete_path = os.path.join(cache_dir_root, "downloads", file_fname)
if not os.path.exists(file_complete_path): if not os.path.exists(file_complete_path + ".gz"): with tqdm( unit="B", unit_scale=True, unit_divisor=1024, miniters=1, desc=file_url.split("/")[-1], ) as t: urllib.request.urlretrieve( file_url, file_complete_path + ".gz", reporthook=self.hook(t) ) with gzip.open(file_complete_path + ".gz", "rb") as file_in: with open(file_complete_path, "wb") as file_out: shutil.copyfileobj(file_in, file_out) return file_complete_path
class TranscriptExpressionHandler(GenomicLRATaskHandler): """ Handler for the Bulk RNA Expression task. """
DEFAULT_LENGTH = 200000 DEFAULT_FILTER_OUT_LENGTH = 196608
def __init__( self, sequence_length: int = DEFAULT_LENGTH, filter_out_sequence_length: int = DEFAULT_FILTER_OUT_LENGTH, **kwargs, ): """ Creates a new handler for the Bulk RNA Expression Prediction Task. Args: sequence_length: Length of the sequence around the TSS_CAGE start site Instance Vars: reference_genome: The Fasta extracted reference genome. coordinate_csv_file: The csv file that stores the coordinates and filename of the target labels_csv_file: The csv file that stores the labels with one sample per row. sequence_length: Sequence length for this handler. """ self.reference_genome = None self.coordinate_csv_file = None self.labels_csv_file = None self.sequence_length = sequence_length self.filter_out_sequence_length = filter_out_sequence_length
if filter_out_sequence_length is not None: assert isinstance(filter_out_sequence_length, int) assert ( sequence_length <= filter_out_sequence_length ), f"{sequence_length=} > {filter_out_sequence_length=}" assert isinstance(sequence_length, int)
def get_info(self, description: str) -> DatasetInfo: """ Returns the DatasetInfor for the Bulk RNA Expression dataset. Each example includes a genomic sequence and a list of label values. """ features = datasets.Features( { # DNA sequence "DNA": datasets.Value("string"), # list of expression values in each tissue "labels": datasets.Sequence(datasets.Value("float32")), "labels_name": datasets.Sequence(datasets.Value("string")), # chromosome number "chromosome": datasets.Value(dtype="string"), "RNA": datasets.Value("string"), "Protein": datasets.Value("string"), } ) return datasets.DatasetInfo( # This is the description that will appear on the datasets page. description=description, # This defines the different columns of the dataset and their types features=features, )
def split_generators(self, dl_manager, cache_dir_root): """ Separates files by split and stores filenames in instance variables. The Bulk RNA Expression dataset requires the reference hg19 genome, coordinate csv file,and label csv file to be saved. """ # Manually download the reference genome since there are difficulties when streaming reference_genome_file = self.download_and_extract_gz( H38_REFERENCE_GENOME_URL, cache_dir_root ) self.reference_genome = Fasta(reference_genome_file, one_based_attributes=False)
self.coordinate_csv_file = dl_manager.download_and_extract( "bulk_rna_expression/transcript_coordinates.csv" )
self.labels_csv_file = dl_manager.download_and_extract( "bulk_rna_expression/rna_expression_values.csv" )
return super().split_generators(dl_manager, cache_dir_root)
def generate_examples(self, split): """ A generator which produces examples for the given split, each with a sequence and the corresponding labels. The sequences are padded to the correct sequence length and standardized before returning. """ coordinates_df = pd.read_csv(self.coordinate_csv_file) labels_name = coordinates_df.columns[2:] coordinates_split_df = coordinates_df[coordinates_df["split"] == split]
key = 0 for idx, coordinates_row in coordinates_split_df.iterrows(): start = ( coordinates_row["position"] - 1 ) # -1 since vcf coords are 1-based
chromosome = coordinates_row["chr"] labels_row = coordinates_row.loc[idx].values[2:] padded_sequence = pad_sequence( chromosome=self.reference_genome[chromosome], start=start, sequence_length=self.sequence_length, negative_strand=coordinates_row["strand"] == "-", filter_out_sequence_length=self.filter_out_sequence_length, ) if padded_sequence: yield key, { "labels_name": labels_name, "labels": labels_row, "DNA": standardize_sequence(padded_sequence), "chromosome": re.sub("chr", "", chromosome), "RNA": coordinates_row["RNA"], "Protein": coordinates_row["Protein"], } key += 1 logger.info( f"filtering out {len(coordinates_split_df)-key} " f"elements from the dataset" )
"""--------------------------------------------------------------------------------------------Dataset loader:-------------------------------------------------------------------------------------------"""
_DESCRIPTION = """Dataset for benchmark of genomic deep learning models. """
# define dataset configsclass GenomicsLRAConfig(datasets.BuilderConfig): """ BuilderConfig. """
def __init__(self, *args, task_name: str, **kwargs): # type: ignore """BuilderConfig for the location tasks dataset. Args: **kwargs: keyword arguments forwarded to super. """ super().__init__() self.handler = TranscriptExpressionHandler(**kwargs)
# DatasetBuilderclass GenomicsLRATasks(datasets.GeneratorBasedBuilder): """ Tasks to annotate human genome. """
VERSION = datasets.Version("1.1.0") BUILDER_CONFIG_CLASS = GenomicsLRAConfig
def _info(self) -> DatasetInfo: return self.config.handler.get_info(description=_DESCRIPTION)
def _split_generators( self, dl_manager: datasets.DownloadManager ) -> List[datasets.SplitGenerator]: """ Downloads data files and organizes it into train/test/val splits """ return self.config.handler.split_generators(dl_manager, self._cache_dir_root)
def _generate_examples(self, handler, split): """ Read data files and create examples(yield) Args: handler: The handler for the current task split: A string in ['train', 'test', 'valid'] """ yield from handler.generate_examples(split)
"""--------------------------------------------------------------------------------------------Global Utils:-------------------------------------------------------------------------------------------"""
def standardize_sequence(sequence: str): """ Standardizes the sequence by replacing all unknown characters with N and converting to all uppercase. Args: sequence: genomic sequence to standardize """ pattern = "[^ATCG]" # all characters to upper case sequence = sequence.upper() # replace all characters that are not A,T,C,G with N sequence = re.sub(pattern, "N", sequence) return sequence
def pad_sequence( chromosome, start, sequence_length, negative_strand=False, filter_out_sequence_length=None,): """ Extends a given sequence to length sequence_length. If padding to the given length is outside the gene, returns None. Args: chromosome: Chromosome from pyfaidx extracted Fasta. start: Start index of original sequence. sequence_length: Desired sequence length. If sequence length is odd, the remainder is added to the end of the sequence. end: End index of original sequence. If no end is specified, it creates a centered sequence around the start index. negative_strand: If negative_strand, returns the reverse compliment of the sequence """
pad = sequence_length // 2 end = start + pad + (sequence_length % 2) start = start - pad
if filter_out_sequence_length is not None: filter_out_pad = filter_out_sequence_length // 2 filter_out_end = start + filter_out_pad + (filter_out_sequence_length % 2) filter_out_start = start - filter_out_pad
if filter_out_start < 0 or filter_out_end >= len(chromosome): return
if start < 0 or end >= len(chromosome): return
if negative_strand: return chromosome[start:end].reverse.complement.seq return chromosome[start:end].seq123version https://git-lfs.github.com/spec/v1oid sha256:8928bee330ed539c90ad9b564f34cabead155e705f88d60495d480d023332578size 111402901123version https://git-lfs.github.com/spec/v1oid sha256:324538a478fa8a5ff441203888b27938551ae498b47c069867c983c1bfbd41f8size 194364132123version https://git-lfs.github.com/spec/v1oid sha256:256d406ada1bea51a6cd42b8100de7e10d436e71f72fd2be5ac1f75e9baebe5fsize 6423912.gitattributes+3
multi_omics_transcript_expression.pyAdded+366
transcript_expression/expression_values_v1.csvAdded+3
transcript_expression/expression_values_v2.csvAdded+3
transcript_expression/transcript_coordinates.csvAdded+3