etrop commited on
Commit
ca412e9
1 Parent(s): 98eadaf

update main loader script for new datasets

Browse files
Files changed (1) hide show
  1. genomics-long-range-benchmark.py +407 -56
genomics-long-range-benchmark.py CHANGED
@@ -14,14 +14,12 @@ import pandas as pd
14
  from datasets import DatasetInfo
15
  from pyfaidx import Fasta
16
  from abc import ABC, abstractmethod
17
- from Bio.Seq import Seq
18
- from Bio import SeqIO
19
- import pysam
20
 
21
  """
22
- --------------------------------------------------------------------------------------------
23
  Reference Genome URLS:
24
- -------------------------------------------------------------------------------------------
25
  """
26
  H38_REFERENCE_GENOME_URL = (
27
  "https://hgdownload.soe.ucsc.edu/goldenPath/hg38/bigZips/" "hg38.fa.gz"
@@ -31,9 +29,9 @@ H19_REFERENCE_GENOME_URL = (
31
  )
32
 
33
  """
34
- --------------------------------------------------------------------------------------------
35
  Task Specific Handlers:
36
- -------------------------------------------------------------------------------------------
37
  """
38
 
39
  class GenomicLRATaskHandler(ABC):
@@ -97,8 +95,8 @@ class GenomicLRATaskHandler(ABC):
97
 
98
  def download_and_extract_gz(self, file_url, cache_dir_root):
99
  """
100
- Downloads and extracts a gz file into the given cache directory. Returns the full file path
101
- of the extracted gz file.
102
  Args:
103
  file_url: url of the gz file to be downloaded and extracted.
104
  cache_dir_root: Directory to extract file into.
@@ -138,29 +136,30 @@ class CagePredictionHandler(GenomicLRATaskHandler):
138
  50,
139
  ) # 50 is a subset of CAGE tracks from the original enformer dataset
140
  NPZ_SPLIT = 1000 # number of files per npz file.
141
- NUM_BP_PER_BIN = 128 # number of base pairs per bin in labels
142
 
143
  def __init__(self, sequence_length=DEFAULT_LENGTH, **kwargs):
144
  """
145
  Creates a new handler for the CAGE task.
146
  Args:
147
- sequence_length: allows for increasing sequence context. Sequence length must be a multiple of 128 to align with binned labels. Note: increasing
148
- sequence length may decrease the number of usable samples.
 
149
  """
150
  self.reference_genome = None
151
  self.coordinate_csv_file = None
152
  self.target_files_by_split = {}
153
 
 
154
  assert (sequence_length // 128) % 2 == 0, (
155
- f"Requested sequence length must be an even multuple of 128 to align with the binned labels."
 
156
  )
157
 
158
  self.sequence_length = sequence_length
159
 
160
  if self.sequence_length < self.DEFAULT_LENGTH:
161
-
162
- self.TARGET_SHAPE = (self.sequence_length//128,50)
163
-
164
 
165
  def get_info(self, description: str) -> DatasetInfo:
166
  """
@@ -174,7 +173,11 @@ class CagePredictionHandler(GenomicLRATaskHandler):
174
  # array of sequence length x num_labels
175
  "labels": datasets.Array2D(shape=self.TARGET_SHAPE, dtype="float32"),
176
  # chromosome number
177
- "chromosome":datasets.Value(dtype="string")
 
 
 
 
178
  }
179
  )
180
  return datasets.DatasetInfo(
@@ -192,31 +195,31 @@ class CagePredictionHandler(GenomicLRATaskHandler):
192
  """
193
 
194
  # Manually download the reference genome since there are difficulties when
195
- # streaming the dataset
196
  reference_genome_file = self.download_and_extract_gz(
197
  H38_REFERENCE_GENOME_URL, cache_dir_root
198
  )
199
  self.reference_genome = Fasta(reference_genome_file, one_based_attributes=False)
200
 
201
  self.coordinate_csv_file = dl_manager.download_and_extract(
202
- "cage_prediction/sequences_coordinates.csv"
203
  )
204
 
205
  train_file_dict = {}
206
  for train_key, train_file in self.generate_npz_filenames(
207
- "train", self.NUM_TRAIN, folder="cage_prediction/targets_subset"
208
  ):
209
  train_file_dict[train_key] = dl_manager.download(train_file)
210
 
211
  test_file_dict = {}
212
  for test_key, test_file in self.generate_npz_filenames(
213
- "test", self.NUM_TEST, folder="cage_prediction/targets_subset"
214
  ):
215
  test_file_dict[test_key] = dl_manager.download(test_file)
216
 
217
  valid_file_dict = {}
218
  for valid_key, valid_file in self.generate_npz_filenames(
219
- "valid", self.NUM_VALID, folder="cage_prediction/targets_subset"
220
  ):
221
  valid_file_dict[valid_key] = dl_manager.download(valid_file)
222
 
@@ -225,7 +228,6 @@ class CagePredictionHandler(GenomicLRATaskHandler):
225
  self.target_files_by_split["test"] = test_file_dict
226
  self.target_files_by_split["validation"] = valid_file_dict
227
 
228
-
229
  return [
230
  datasets.SplitGenerator(
231
  name=datasets.Split.TRAIN,
@@ -241,7 +243,6 @@ class CagePredictionHandler(GenomicLRATaskHandler):
241
  ),
242
  ]
243
 
244
-
245
  def generate_examples(self, split):
246
  """
247
  A generator which produces examples for the given split, each with a sequence
@@ -257,10 +258,10 @@ class CagePredictionHandler(GenomicLRATaskHandler):
257
  filtered = coordinates_dataframe[coordinates_dataframe["split"] == split]
258
  for sequential_idx, row in filtered.iterrows():
259
  start, stop = int(row["start"]) - 1, int(
260
- row["stop"]) - 1 # -1 since vcf coords are 1-based
261
 
262
  chromosome = row['chrom']
263
-
264
  padded_sequence = pad_sequence(
265
  chromosome=self.reference_genome[chromosome],
266
  start=start,
@@ -277,21 +278,22 @@ class CagePredictionHandler(GenomicLRATaskHandler):
277
  split == "validation"
278
  ): # npy files are keyed by ["train", "test", "valid"]
279
  split = "valid"
280
- targets = npz_file[f"target-{split}-{row['npy_idx']}.npy"][0] # select 0 since there is extra dimension
281
-
282
-
283
  # subset the targets if sequence length is smaller than 114688 (
284
  # DEFAULT_LENGTH)
285
  if self.sequence_length < self.DEFAULT_LENGTH:
286
  idx_diff = (self.DEFAULT_LENGTH - self.sequence_length) // 2 // 128
287
  targets = targets[idx_diff:-idx_diff]
288
 
289
-
290
  if padded_sequence:
291
  yield key, {
292
  "labels": targets,
293
  "sequence": standardize_sequence(padded_sequence),
294
- "chromosome": re.sub("chr","",chromosome)
 
 
295
  }
296
  key += 1
297
 
@@ -325,7 +327,7 @@ class BulkRnaExpressionHandler(GenomicLRATaskHandler):
325
  Handler for the Bulk RNA Expression task.
326
  """
327
 
328
- DEFAULT_LENGTH = 114688
329
 
330
  def __init__(self, sequence_length=DEFAULT_LENGTH, **kwargs):
331
  """
@@ -351,7 +353,9 @@ class BulkRnaExpressionHandler(GenomicLRATaskHandler):
351
  # list of expression values in each tissue
352
  "labels": datasets.Sequence(datasets.Value("float32")),
353
  # chromosome number
354
- "chromosome":datasets.Value(dtype="string")
 
 
355
  }
356
  )
357
  return datasets.DatasetInfo(
@@ -368,7 +372,7 @@ class BulkRnaExpressionHandler(GenomicLRATaskHandler):
368
  The Bulk RNA Expression dataset requires the reference hg19 genome, coordinate
369
  csv file,and label csv file to be saved.
370
  """
371
- # Manually download the reference genome since there are difficulties when streaming
372
  reference_genome_file = self.download_and_extract_gz(
373
  H19_REFERENCE_GENOME_URL, cache_dir_root
374
  )
@@ -398,7 +402,7 @@ class BulkRnaExpressionHandler(GenomicLRATaskHandler):
398
  key = 0
399
  for idx, coordinates_row in coordinates_split_df.iterrows():
400
  start = coordinates_row[
401
- "CAGE_representative_TSS"] - 1 # -1 since vcf coords are 1-based
402
 
403
  chromosome = coordinates_row["chrom"]
404
  labels_row = labels_df.loc[idx].values
@@ -412,21 +416,22 @@ class BulkRnaExpressionHandler(GenomicLRATaskHandler):
412
  yield key, {
413
  "labels": labels_row,
414
  "sequence": standardize_sequence(padded_sequence),
415
- "chromosome":re.sub("chr","",chromosome)
 
416
  }
417
  key += 1
418
 
419
 
420
- class VariantEffectPredictionHandler(GenomicLRATaskHandler):
421
  """
422
- Handler for the Variant Effect Prediction task.
423
  """
424
 
425
- DEFAULT_LENGTH = 114688
426
 
427
  def __init__(self, sequence_length=DEFAULT_LENGTH, **kwargs):
428
  """
429
- Creates a new handler for the Variant Effect Prediction Task.
430
  Args:
431
  sequence_length: Length of the sequence to pad around the SNP position
432
 
@@ -436,9 +441,9 @@ class VariantEffectPredictionHandler(GenomicLRATaskHandler):
436
 
437
  def get_info(self, description: str) -> DatasetInfo:
438
  """
439
- Returns the DatasetInfo for the Variant Effect Prediction dataset. Each example
440
- includes a genomic sequence with the reference allele as well as the genomic sequence with the alternative allele,
441
- and a binary label.
442
  """
443
  features = datasets.Features(
444
  {
@@ -451,8 +456,10 @@ class VariantEffectPredictionHandler(GenomicLRATaskHandler):
451
  "tissue": datasets.Value(dtype="string"),
452
  # chromosome number
453
  "chromosome": datasets.Value(dtype="string"),
 
 
454
  # distance to nearest tss
455
- "distance_to_nearest_tss":datasets.Value(dtype="int32")
456
  }
457
  )
458
 
@@ -478,7 +485,7 @@ class VariantEffectPredictionHandler(GenomicLRATaskHandler):
478
 
479
  self.reference_genome = Fasta(reference_genome_file, one_based_attributes=False)
480
  self.coordinates_labels_csv_file = dl_manager.download_and_extract(
481
- f"variant_effect_gene_expression/All_Tissues.csv"
482
  )
483
 
484
  return super().split_generators(dl_manager, cache_dir_root)
@@ -496,7 +503,7 @@ class VariantEffectPredictionHandler(GenomicLRATaskHandler):
496
 
497
  key = 0
498
  for idx, row in coordinates_split_df.iterrows():
499
- start = row["POS"] - 1 # sub 1 to create idx since vcf coords are 1-based
500
  alt_allele = row["ALT"]
501
  label = row["label"]
502
  tissue = row['tissue']
@@ -513,8 +520,8 @@ class VariantEffectPredictionHandler(GenomicLRATaskHandler):
513
 
514
  # only if a valid sequence returned
515
  if ref_forward:
516
- # Mutate sequence with the alt allele at the SNP position, which is always
517
- # centered in the string returned from pad_sequence
518
  alt_forward = list(ref_forward)
519
  alt_forward[self.sequence_length // 2] = alt_allele
520
  alt_forward = "".join(alt_forward)
@@ -525,14 +532,351 @@ class VariantEffectPredictionHandler(GenomicLRATaskHandler):
525
  "chromosome": re.sub("chr", "", chromosome),
526
  "ref_forward_sequence": standardize_sequence(ref_forward),
527
  "alt_forward_sequence": standardize_sequence(alt_forward),
528
- "distance_to_nearest_tss": distance
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
529
  }
530
  key += 1
531
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
532
  """
533
- --------------------------------------------------------------------------------------------
534
  Dataset loader:
535
- -------------------------------------------------------------------------------------------
536
  """
537
 
538
  _DESCRIPTION = """
@@ -542,7 +886,13 @@ Dataset for benchmark of genomic deep learning models.
542
  _TASK_HANDLERS = {
543
  "cage_prediction": CagePredictionHandler,
544
  "bulk_rna_expression": BulkRnaExpressionHandler,
545
- "variant_effect_gene_expression": VariantEffectPredictionHandler,
 
 
 
 
 
 
546
  }
547
 
548
 
@@ -558,7 +908,7 @@ class GenomicsLRAConfig(datasets.BuilderConfig):
558
  **kwargs: keyword arguments forwarded to super.
559
  """
560
  super().__init__()
561
- self.handler = _TASK_HANDLERS[task_name](task_name=task_name,**kwargs)
562
 
563
 
564
  # DatasetBuilder
@@ -592,9 +942,9 @@ class GenomicsLRATasks(datasets.GeneratorBasedBuilder):
592
 
593
 
594
  """
595
- --------------------------------------------------------------------------------------------
596
  Global Utils:
597
- -------------------------------------------------------------------------------------------
598
  """
599
 
600
 
@@ -625,7 +975,8 @@ def pad_sequence(chromosome, start, sequence_length, end=None, negative_strand=F
625
  remainder is added to the end of the sequence.
626
  end: End index of original sequence. If no end is specified, it creates a
627
  centered sequence around the start index.
628
- negative_strand: If negative_strand, returns the reverse compliment of the sequence
 
629
  """
630
  if end:
631
  pad = (sequence_length - (end - start)) // 2
 
14
  from datasets import DatasetInfo
15
  from pyfaidx import Fasta
16
  from abc import ABC, abstractmethod
17
+
 
 
18
 
19
  """
20
+ ----------------------------------------------------------------------------------------
21
  Reference Genome URLS:
22
+ ----------------------------------------------------------------------------------------
23
  """
24
  H38_REFERENCE_GENOME_URL = (
25
  "https://hgdownload.soe.ucsc.edu/goldenPath/hg38/bigZips/" "hg38.fa.gz"
 
29
  )
30
 
31
  """
32
+ ----------------------------------------------------------------------------------------
33
  Task Specific Handlers:
34
+ ----------------------------------------------------------------------------------------
35
  """
36
 
37
  class GenomicLRATaskHandler(ABC):
 
95
 
96
  def download_and_extract_gz(self, file_url, cache_dir_root):
97
  """
98
+ Downloads and extracts a gz file into the given cache directory. Returns the
99
+ full file path of the extracted gz file.
100
  Args:
101
  file_url: url of the gz file to be downloaded and extracted.
102
  cache_dir_root: Directory to extract file into.
 
136
  50,
137
  ) # 50 is a subset of CAGE tracks from the original enformer dataset
138
  NPZ_SPLIT = 1000 # number of files per npz file.
139
+ NUM_BP_PER_BIN = 128 # number of base pairs per bin in labels
140
 
141
  def __init__(self, sequence_length=DEFAULT_LENGTH, **kwargs):
142
  """
143
  Creates a new handler for the CAGE task.
144
  Args:
145
+ sequence_length: allows for increasing sequence context. Sequence length
146
+ must be an even multiple of 128 to align with binned labels. Note:
147
+ increasing sequence length may decrease the number of usable samples.
148
  """
149
  self.reference_genome = None
150
  self.coordinate_csv_file = None
151
  self.target_files_by_split = {}
152
 
153
+
154
  assert (sequence_length // 128) % 2 == 0, (
155
+ f"Requested sequence length must be an even multuple of 128 to align "
156
+ f"with the binned labels."
157
  )
158
 
159
  self.sequence_length = sequence_length
160
 
161
  if self.sequence_length < self.DEFAULT_LENGTH:
162
+ self.TARGET_SHAPE = (self.sequence_length // 128, 50)
 
 
163
 
164
  def get_info(self, description: str) -> DatasetInfo:
165
  """
 
173
  # array of sequence length x num_labels
174
  "labels": datasets.Array2D(shape=self.TARGET_SHAPE, dtype="float32"),
175
  # chromosome number
176
+ "chromosome": datasets.Value(dtype="string"),
177
+ # start
178
+ "start": datasets.Value(dtype="int32"),
179
+ # stop
180
+ "stop": datasets.Value(dtype="int32")
181
  }
182
  )
183
  return datasets.DatasetInfo(
 
195
  """
196
 
197
  # Manually download the reference genome since there are difficulties when
198
+ # streaming
199
  reference_genome_file = self.download_and_extract_gz(
200
  H38_REFERENCE_GENOME_URL, cache_dir_root
201
  )
202
  self.reference_genome = Fasta(reference_genome_file, one_based_attributes=False)
203
 
204
  self.coordinate_csv_file = dl_manager.download_and_extract(
205
+ "cage_expression/sequences_coordinates.csv"
206
  )
207
 
208
  train_file_dict = {}
209
  for train_key, train_file in self.generate_npz_filenames(
210
+ "train", self.NUM_TRAIN, folder="cage_expression/targets_subset"
211
  ):
212
  train_file_dict[train_key] = dl_manager.download(train_file)
213
 
214
  test_file_dict = {}
215
  for test_key, test_file in self.generate_npz_filenames(
216
+ "test", self.NUM_TEST, folder="cage_expression/targets_subset"
217
  ):
218
  test_file_dict[test_key] = dl_manager.download(test_file)
219
 
220
  valid_file_dict = {}
221
  for valid_key, valid_file in self.generate_npz_filenames(
222
+ "valid", self.NUM_VALID, folder="cage_expression/targets_subset"
223
  ):
224
  valid_file_dict[valid_key] = dl_manager.download(valid_file)
225
 
 
228
  self.target_files_by_split["test"] = test_file_dict
229
  self.target_files_by_split["validation"] = valid_file_dict
230
 
 
231
  return [
232
  datasets.SplitGenerator(
233
  name=datasets.Split.TRAIN,
 
243
  ),
244
  ]
245
 
 
246
  def generate_examples(self, split):
247
  """
248
  A generator which produces examples for the given split, each with a sequence
 
258
  filtered = coordinates_dataframe[coordinates_dataframe["split"] == split]
259
  for sequential_idx, row in filtered.iterrows():
260
  start, stop = int(row["start"]) - 1, int(
261
+ row["stop"]) - 1 # -1 since coords are 1-based
262
 
263
  chromosome = row['chrom']
264
+
265
  padded_sequence = pad_sequence(
266
  chromosome=self.reference_genome[chromosome],
267
  start=start,
 
278
  split == "validation"
279
  ): # npy files are keyed by ["train", "test", "valid"]
280
  split = "valid"
281
+ targets = npz_file[f"target-{split}-{row['npy_idx']}.npy"][
282
+ 0] # select 0 since there is extra dimension
283
+
284
  # subset the targets if sequence length is smaller than 114688 (
285
  # DEFAULT_LENGTH)
286
  if self.sequence_length < self.DEFAULT_LENGTH:
287
  idx_diff = (self.DEFAULT_LENGTH - self.sequence_length) // 2 // 128
288
  targets = targets[idx_diff:-idx_diff]
289
 
 
290
  if padded_sequence:
291
  yield key, {
292
  "labels": targets,
293
  "sequence": standardize_sequence(padded_sequence),
294
+ "chromosome": re.sub("chr", "", chromosome),
295
+ "start": int(row["start"]),
296
+ "stop": int(row["stop"])
297
  }
298
  key += 1
299
 
 
327
  Handler for the Bulk RNA Expression task.
328
  """
329
 
330
+ DEFAULT_LENGTH = 100000
331
 
332
  def __init__(self, sequence_length=DEFAULT_LENGTH, **kwargs):
333
  """
 
353
  # list of expression values in each tissue
354
  "labels": datasets.Sequence(datasets.Value("float32")),
355
  # chromosome number
356
+ "chromosome": datasets.Value(dtype="string"),
357
+ # position
358
+ "position": datasets.Value(dtype="int32"),
359
  }
360
  )
361
  return datasets.DatasetInfo(
 
372
  The Bulk RNA Expression dataset requires the reference hg19 genome, coordinate
373
  csv file,and label csv file to be saved.
374
  """
375
+
376
  reference_genome_file = self.download_and_extract_gz(
377
  H19_REFERENCE_GENOME_URL, cache_dir_root
378
  )
 
402
  key = 0
403
  for idx, coordinates_row in coordinates_split_df.iterrows():
404
  start = coordinates_row[
405
+ "CAGE_representative_TSS"] - 1 # -1 since coords are 1-based
406
 
407
  chromosome = coordinates_row["chrom"]
408
  labels_row = labels_df.loc[idx].values
 
416
  yield key, {
417
  "labels": labels_row,
418
  "sequence": standardize_sequence(padded_sequence),
419
+ "chromosome": re.sub("chr", "", chromosome),
420
+ "position": coordinates_row["CAGE_representative_TSS"]
421
  }
422
  key += 1
423
 
424
 
425
+ class VariantEffectCausalEqtl(GenomicLRATaskHandler):
426
  """
427
+ Handler for the Variant Effect Causal eQTL task.
428
  """
429
 
430
+ DEFAULT_LENGTH = 100000
431
 
432
  def __init__(self, sequence_length=DEFAULT_LENGTH, **kwargs):
433
  """
434
+ Creates a new handler for the Variant Effect Causal eQTL Task.
435
  Args:
436
  sequence_length: Length of the sequence to pad around the SNP position
437
 
 
441
 
442
  def get_info(self, description: str) -> DatasetInfo:
443
  """
444
+ Returns the DatasetInfo for the Variant Effect Causal eQTL dataset. Each example
445
+ includes a genomic sequence with the reference allele as well as the genomic
446
+ sequence with the alternative allele, and a binary label.
447
  """
448
  features = datasets.Features(
449
  {
 
456
  "tissue": datasets.Value(dtype="string"),
457
  # chromosome number
458
  "chromosome": datasets.Value(dtype="string"),
459
+ # variant position
460
+ "position": datasets.Value(dtype="int32"),
461
  # distance to nearest tss
462
+ "distance_to_nearest_tss": datasets.Value(dtype="int32")
463
  }
464
  )
465
 
 
485
 
486
  self.reference_genome = Fasta(reference_genome_file, one_based_attributes=False)
487
  self.coordinates_labels_csv_file = dl_manager.download_and_extract(
488
+ f"variant_effect_prediction/All_Tissues.csv"
489
  )
490
 
491
  return super().split_generators(dl_manager, cache_dir_root)
 
503
 
504
  key = 0
505
  for idx, row in coordinates_split_df.iterrows():
506
+ start = row["POS"] - 1 # sub 1 to create idx since coords are 1-based
507
  alt_allele = row["ALT"]
508
  label = row["label"]
509
  tissue = row['tissue']
 
520
 
521
  # only if a valid sequence returned
522
  if ref_forward:
523
+ # Mutate sequence with the alt allele at the SNP position,
524
+ # which is always centered in the string returned from pad_sequence
525
  alt_forward = list(ref_forward)
526
  alt_forward[self.sequence_length // 2] = alt_allele
527
  alt_forward = "".join(alt_forward)
 
532
  "chromosome": re.sub("chr", "", chromosome),
533
  "ref_forward_sequence": standardize_sequence(ref_forward),
534
  "alt_forward_sequence": standardize_sequence(alt_forward),
535
+ "distance_to_nearest_tss": distance,
536
+ "position": row["POS"]
537
+ }
538
+ key += 1
539
+
540
+
541
+ class VariantEffectPathogenicHandler(GenomicLRATaskHandler):
542
+ """
543
+ Handler for the Variant Effect Pathogenic Prediction tasks.
544
+ """
545
+
546
+ DEFAULT_LENGTH = 100000
547
+
548
+ def __init__(self, sequence_length=DEFAULT_LENGTH, task_name=None, subset=False,
549
+ **kwargs):
550
+ """
551
+ Creates a new handler for the Variant Effect Pathogenic Tasks.
552
+ Args:
553
+ sequence_length: Length of the sequence to pad around the SNP position
554
+ subset: Whether to return a pre-determined subset of the data.
555
+
556
+ """
557
+ self.sequence_length = sequence_length
558
+
559
+ if task_name == 'variant_effect_pathogenic_coding':
560
+ self.data_file_name = "variant_effect_pathogenic/vep_pathogenic_coding.csv"
561
+ elif task_name == 'variant_effect_pathogenic_non_coding':
562
+ self.data_file_name = "variant_effect_pathogenic/" \
563
+ "vep_pathogenic_non_coding_subset.csv" \
564
+ if subset else "variant_effect_pathogenic/vep_pathogenic_non_coding.csv"
565
+
566
+ def get_info(self, description: str) -> DatasetInfo:
567
+ """
568
+ Returns the DatasetInfo for the Variant Effect Pathogenic datasets. Each example
569
+ includes a genomic sequence with the reference allele as well as the genomic
570
+ sequence with the alternative allele, and a binary label.
571
+ """
572
+ features = datasets.Features(
573
+ {
574
+ # DNA sequence
575
+ "ref_forward_sequence": datasets.Value("string"),
576
+ "alt_forward_sequence": datasets.Value("string"),
577
+ # binary label
578
+ "label": datasets.Value(dtype="int8"),
579
+ # chromosome number
580
+ "chromosome": datasets.Value(dtype="string"),
581
+ # position
582
+ "position": datasets.Value(dtype="int32")
583
+ }
584
+ )
585
+
586
+ return datasets.DatasetInfo(
587
+ # This is the description that will appear on the datasets page.
588
+ description=description,
589
+ # This defines the different columns of the dataset and their types
590
+ features=features,
591
+ )
592
+
593
+ def split_generators(self, dl_manager, cache_dir_root):
594
+ """
595
+ Separates files by split and stores filenames in instance variables.
596
+ The variant effect prediction datasets require the reference hg38 genome and
597
+ coordinates_labels_csv_file to be saved.
598
+ """
599
+
600
+ reference_genome_file = self.download_and_extract_gz(
601
+ H38_REFERENCE_GENOME_URL, cache_dir_root
602
+ )
603
+
604
+ self.reference_genome = Fasta(reference_genome_file, one_based_attributes=False)
605
+ self.coordinates_labels_csv_file = dl_manager.download_and_extract(
606
+ self.data_file_name)
607
+
608
+ if 'non_coding' in self.data_file_name:
609
+ return [
610
+ datasets.SplitGenerator(
611
+ name=datasets.Split.TEST,
612
+ gen_kwargs={"handler": self, "split": "test"}
613
+ ), ]
614
+ else:
615
+ return super().split_generators(dl_manager, cache_dir_root)
616
+
617
+ def generate_examples(self, split):
618
+ """
619
+ A generator which produces examples each with ref/alt allele
620
+ and corresponding binary label. The sequences are extended to
621
+ the desired sequence length and standardized before returning.
622
+ """
623
+
624
+ coordinates_df = pd.read_csv(self.coordinates_labels_csv_file)
625
+ coordinates_split_df = coordinates_df[coordinates_df["split"] == split]
626
+
627
+ key = 0
628
+ for idx, row in coordinates_split_df.iterrows():
629
+ start = row["POS"] - 1 # sub 1 to create idx since coords are 1-based
630
+ alt_allele = row["ALT"]
631
+ label = row["INT_LABEL"]
632
+ chromosome = row["CHROM"]
633
+
634
+ # get reference forward sequence
635
+ ref_forward = pad_sequence(
636
+ chromosome=self.reference_genome[chromosome],
637
+ start=start,
638
+ sequence_length=self.sequence_length,
639
+ negative_strand=False,
640
+ )
641
+
642
+ # only if a valid sequence returned
643
+ if ref_forward:
644
+ # Mutate sequence with the alt allele at the SNP position,
645
+ # which is always centered in the string returned from pad_sequence
646
+ alt_forward = list(ref_forward)
647
+ alt_forward[self.sequence_length // 2] = alt_allele
648
+ alt_forward = "".join(alt_forward)
649
+
650
+ yield key, {
651
+ "label": label,
652
+ "chromosome": re.sub("chr", "", chromosome),
653
+ "ref_forward_sequence": standardize_sequence(ref_forward),
654
+ "alt_forward_sequence": standardize_sequence(alt_forward),
655
+ "position": row['POS']
656
  }
657
  key += 1
658
 
659
+
660
+ class ChromatinFeaturesHandler(GenomicLRATaskHandler):
661
+ """
662
+ Handler for the histone marks and DNA accessibility tasks also referred to
663
+ collectively as Chromatin features.
664
+ """
665
+
666
+ DEFAULT_LENGTH = 100000
667
+
668
+ def __init__(self, task_name=None, sequence_length=DEFAULT_LENGTH, subset=False,
669
+ **kwargs):
670
+ """
671
+ Creates a new handler for the Deep Sea Histone and DNase tasks.
672
+ Args:
673
+ sequence_length: Length of the sequence around and including the
674
+ annotated 200bp bin
675
+ subset: Whether to return a pre-determined subset of the entire dataset.
676
+
677
+ """
678
+ self.sequence_length = sequence_length
679
+
680
+ if sequence_length < 200:
681
+ raise ValueError(
682
+ 'Sequence length for this task must be greater or equal to 200 bp')
683
+
684
+ if 'histone' in task_name:
685
+ self.label_name = 'HISTONES'
686
+ elif 'dnase' in task_name:
687
+ self.label_name = 'DNASE'
688
+
689
+ self.data_file_name = "chromatin_features/histones_and_dnase_subset.csv" if \
690
+ subset else "chromatin_features/histones_and_dnase.csv"
691
+
692
+ def get_info(self, description: str) -> DatasetInfo:
693
+ """
694
+ Returns the DatasetInfo for the histone marks and dna accessibility datasets.
695
+ Each example includes a genomic sequence and a list of label values.
696
+ """
697
+ features = datasets.Features(
698
+ {
699
+ # DNA sequence
700
+ "sequence": datasets.Value("string"),
701
+ # list of binary chromatin marks
702
+ "labels": datasets.Sequence(datasets.Value("int8")),
703
+ # chromosome number
704
+ "chromosome": datasets.Value(dtype="string"),
705
+ # position
706
+ "position": datasets.Value(dtype="int32"),
707
+ }
708
+ )
709
+ return datasets.DatasetInfo(
710
+ # This is the description that will appear on the datasets page.
711
+ description=description,
712
+ # This defines the different columns of the dataset and their types
713
+ features=features,
714
+
715
+ )
716
+
717
+ def split_generators(self, dl_manager, cache_dir_root):
718
+ """
719
+ Separates files by split and stores filenames in instance variables.
720
+ The histone marks and dna accessibility datasets require the reference hg19
721
+ genome and coordinate csv file to be saved.
722
+ """
723
+ reference_genome_file = self.download_and_extract_gz(
724
+ H19_REFERENCE_GENOME_URL, cache_dir_root
725
+ )
726
+ self.reference_genome = Fasta(reference_genome_file, one_based_attributes=False)
727
+
728
+ self.coordinate_csv_file = dl_manager.download_and_extract(self.data_file_name)
729
+
730
+ return super().split_generators(dl_manager, cache_dir_root)
731
+
732
+ def generate_examples(self, split):
733
+ """
734
+ A generator which produces examples for the given split, each with a sequence
735
+ and the corresponding labels. The sequences are padded to the correct sequence
736
+ length and standardized before returning.
737
+ """
738
+ coordinates_df = pd.read_csv(self.coordinate_csv_file)
739
+ coordinates_split_df = coordinates_df[coordinates_df["split"] == split]
740
+
741
+ key = 0
742
+ for idx, coordinates_row in coordinates_split_df.iterrows():
743
+ start = coordinates_row['POS'] - 1 # -1 since saved coords are 1-based
744
+ chromosome = coordinates_row["CHROM"]
745
+
746
+ # literal eval used since lists are saved as strings in csv
747
+ labels_row = literal_eval(coordinates_row[self.label_name])
748
+
749
+ padded_sequence = pad_sequence(
750
+ chromosome=self.reference_genome[chromosome],
751
+ start=start,
752
+ sequence_length=self.sequence_length,
753
+ )
754
+ if padded_sequence:
755
+ yield key, {
756
+ "labels": labels_row,
757
+ "sequence": standardize_sequence(padded_sequence),
758
+ "chromosome": re.sub("chr", "", chromosome),
759
+ "position": coordinates_row['POS']
760
+ }
761
+ key += 1
762
+
763
+
764
+ class RegulatoryElementHandler(GenomicLRATaskHandler):
765
+ """
766
+ Handler for the Regulatory Element Prediction tasks.
767
+ """
768
+ DEFAULT_LENGTH = 100000
769
+
770
+ def __init__(self, task_name=None, sequence_length=DEFAULT_LENGTH, subset=False,
771
+ **kwargs):
772
+ """
773
+ Creates a new handler for the Regulatory Element Prediction tasks.
774
+ Args:
775
+ sequence_length: Length of the sequence around the element/non-element
776
+ subset: Whether to return a pre-determined subset of the entire dataset.
777
+
778
+ """
779
+
780
+ if sequence_length < 200:
781
+ raise ValueError(
782
+ 'Sequence length for this task must be greater or equal to 200 bp')
783
+
784
+ self.sequence_length = sequence_length
785
+
786
+ if 'promoter' in task_name:
787
+ self.data_file_name = 'regulatory_elements/promoter_dataset'
788
+
789
+ elif 'enhancer' in task_name:
790
+ self.data_file_name = 'regulatory_elements/enhancer_dataset'
791
+
792
+ if subset:
793
+ self.data_file_name += '_subset.csv'
794
+ else:
795
+ self.data_file_name += '.csv'
796
+
797
+ def get_info(self, description: str) -> DatasetInfo:
798
+ """
799
+ Returns the DatasetInfo for the Regulatory Element Prediction Tasks.
800
+ Each example includes a genomic sequence and a label.
801
+ """
802
+ features = datasets.Features(
803
+ {
804
+ # DNA sequence
805
+ "sequence": datasets.Value("string"),
806
+ # label corresponding to whether the sequence has
807
+ # the regulatory element of interest or not
808
+ "labels": datasets.Value("int8"),
809
+ # chromosome number
810
+ "chromosome": datasets.Value(dtype="string"),
811
+ # start
812
+ "start": datasets.Value(dtype="int32"),
813
+ # stop
814
+ "stop": datasets.Value(dtype="int32"),
815
+ }
816
+ )
817
+ return datasets.DatasetInfo(
818
+ # This is the description that will appear on the datasets page.
819
+ description=description,
820
+ # This defines the different columns of the dataset and their types
821
+ features=features,
822
+
823
+ )
824
+
825
+ def split_generators(self, dl_manager, cache_dir_root):
826
+ """
827
+ Separates files by split and stores filenames in instance variables.
828
+ """
829
+ reference_genome_file = self.download_and_extract_gz(
830
+ H38_REFERENCE_GENOME_URL, cache_dir_root
831
+ )
832
+ self.reference_genome = Fasta(reference_genome_file, one_based_attributes=False)
833
+
834
+ self.coordinate_csv_file = dl_manager.download_and_extract(
835
+ self.data_file_name
836
+ )
837
+
838
+ return super().split_generators(dl_manager, cache_dir_root)
839
+
840
+ def generate_examples(self, split):
841
+ """
842
+ A generator which produces examples for the given split, each with a sequence
843
+ and the corresponding label. The sequences are padded to the correct sequence
844
+ length and standardized before returning.
845
+ """
846
+ coordinates_df = pd.read_csv(self.coordinate_csv_file)
847
+
848
+ coordinates_split_df = coordinates_df[coordinates_df["split"] == split]
849
+
850
+ key = 0
851
+ for _, coordinates_row in coordinates_split_df.iterrows():
852
+ start = coordinates_row["START"] - 1 # -1 since vcf coords are 1-based
853
+ end = coordinates_row["STOP"] - 1 # -1 since vcf coords are 1-based
854
+ chromosome = coordinates_row["CHROM"]
855
+
856
+ label = coordinates_row['label']
857
+
858
+ padded_sequence = pad_sequence(
859
+ chromosome=self.reference_genome[chromosome],
860
+ start=start,
861
+ end=end,
862
+ sequence_length=self.sequence_length,
863
+ )
864
+
865
+ if padded_sequence:
866
+ yield key, {
867
+ "labels": label,
868
+ "sequence": standardize_sequence(padded_sequence),
869
+ "chromosome": re.sub("chr", "", chromosome),
870
+ "start": coordinates_row["START"],
871
+ "stop": coordinates_row["STOP"]
872
+ }
873
+ key += 1
874
+
875
+
876
  """
877
+ ----------------------------------------------------------------------------------------
878
  Dataset loader:
879
+ ----------------------------------------------------------------------------------------
880
  """
881
 
882
  _DESCRIPTION = """
 
886
  _TASK_HANDLERS = {
887
  "cage_prediction": CagePredictionHandler,
888
  "bulk_rna_expression": BulkRnaExpressionHandler,
889
+ "variant_effect_causal_eqtl": VariantEffectCausalEqtl,
890
+ "variant_effect_pathogenic_clinvar": VariantEffectPathogenicHandler,
891
+ "variant_effect_pathogenic_omim": VariantEffectPathogenicHandler,
892
+ "chromatin_features_histone_marks": ChromatinFeaturesHandler,
893
+ "chromatin_features_dna_accessibility": ChromatinFeaturesHandler,
894
+ "regulatory_element_promoter": RegulatoryElementHandler,
895
+ "regulatory_element_enhancer": RegulatoryElementHandler,
896
  }
897
 
898
 
 
908
  **kwargs: keyword arguments forwarded to super.
909
  """
910
  super().__init__()
911
+ self.handler = _TASK_HANDLERS[task_name](task_name=task_name, **kwargs)
912
 
913
 
914
  # DatasetBuilder
 
942
 
943
 
944
  """
945
+ ----------------------------------------------------------------------------------------
946
  Global Utils:
947
+ ----------------------------------------------------------------------------------------
948
  """
949
 
950
 
 
975
  remainder is added to the end of the sequence.
976
  end: End index of original sequence. If no end is specified, it creates a
977
  centered sequence around the start index.
978
+ negative_strand: If negative_strand, returns the reverse compliment of the
979
+ sequence
980
  """
981
  if end:
982
  pad = (sequence_length - (end - start)) // 2