-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathEnformer_experiments.py
10335 lines (8527 loc) · 429 KB
/
Enformer_experiments.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# -*- coding: utf-8 -*-
# ---
# jupyter:
# jupytext:
# formats: ipynb,py:percent
# text_representation:
# extension: .py
# format_name: percent
# format_version: '1.3'
# jupytext_version: 1.14.0
# kernelspec:
# display_name: Python [conda env:anaconda-sequencemodelbenchmark]
# language: python
# name: conda-env-anaconda-sequencemodelbenchmark-py
# ---
# %% [markdown]
# # Enformer experiments
#
# The following notebook contains all the analysis for our paper **Current sequence-based models of gene expression captures causal determinants of promoters but mostly ignore distal enhancers**.
# %% [markdown]
# # Setup
# %% [markdown] id="MCDk7UQPG0Lr"
# ## Imports
# %% id="NRI9KisU11bM"
import itertools
import functools
import collections
import random
import re
import glob
import math
import os
import json
import pickle
import pyranges as pr
#os.environ["TF_FORCE_GPU_ALLOW_GROWTH"] = "true"
#import joblib
import gzip
import kipoiseq
from kipoiseq import Interval
import pyfaidx
import pandas as pd
import numpy as np
import scipy
import matplotlib.pyplot as plt
import matplotlib as mpl
from matplotlib import cm
from matplotlib.colors import ListedColormap, LinearSegmentedColormap
import seaborn as sns
import statannot
import plotnine as p9
import sklearn
from sklearn import ensemble
from sklearn import pipeline
import statsmodels
import statsmodels.api as sm
import statsmodels.formula.api as smf
import patsy
# %matplotlib inline
# %config InlineBackend.figure_format = 'retina'
# %% id="hTGOLrbZxNHK"
import tensorflow_hub as hub
import tensorflow as tf
# Make sure the GPU is enabled
assert tf.config.list_physical_devices('GPU')
# %%
from Code.Utilities.seq_utils import one_hot_encode, rev_comp_sequence, rev_comp_one_hot, compute_offset_to_center_landmark
from Code.Utilities.enformer_utils import *
import Code.Utilities.basenji2_utils as basenji2_utils
import Code.Utilities.basenji1_utils as basenji1_utils
import kipoi
# %% id="g0F1A9AaCrkQ"
transform_path = 'gs://dm-enformer/models/enformer.finetuned.SAD.robustscaler-PCA500-robustscaler.transform.pkl'
model_path = 'https://tfhub.dev/deepmind/enformer/1'
fasta_file = 'Data/Genome/genome.fa'
fasta_file_hg19 = 'Data/Genome/genome_hg19.fa'
gtf_file = 'Data/Genome/genes.gtf'
# %% [markdown] id="Q8ZhswycGux3"
# ## Download files
# %% colab={"base_uri": "https://localhost:8080/", "height": 240} id="OlE6JAVfI08a" outputId="61f72dd8-e5f5-4764-d765-b6cbd47f6e90"
# Download targets from Basenji2 dataset
# Cite: Kelley et al Cross-species regulatory sequence activity prediction. PLoS Comput. Biol. 16, e1008050 (2020).
targets_txt = 'https://raw.githubusercontent.com/calico/basenji/master/manuscripts/cross2020/targets_human.txt'
df_targets = pd.read_csv(targets_txt, sep='\t')
df_targets.head(3)
# %%
df_targets.to_csv("Data/Targets/targets.tsv",sep="\t",index=None)
# %% [markdown] id="dowTJknFJOHu"
# Download and index the reference genome fasta file
#
# Credit to Genome Reference Consortium: https://www.ncbi.nlm.nih.gov/grc
#
# Schneider et al 2017 http://dx.doi.org/10.1101/gr.213611.116: Evaluation of GRCh38 and de novo haploid genome assemblies demonstrates the enduring quality of the reference assembly
# %% colab={"base_uri": "https://localhost:8080/"} id="flOUYxP7Fjvh" outputId="2f729a7e-1916-4998-ef4e-1794079037ea"
# !wget -O - http://hgdownload.cse.ucsc.edu/goldenPath/hg38/bigZips/hg38.fa.gz | gunzip -c > {fasta_file}
pyfaidx.Faidx(fasta_file)
# %% [markdown]
# Download and index hg19 reference genome fasta file
# %%
# !wget -O - http://hgdownload.cse.ucsc.edu/goldenPath/hg19/bigZips/hg19.fa.gz | gunzip -c > {fasta_file_hg19}
pyfaidx.Faidx(fasta_file_hg19)
# %% [markdown] id="A5xbQNZ6ljxm"
# Download the reference gtf
# %% colab={"base_uri": "https://localhost:8080/"} id="LjygWNOtlkN3" outputId="cd494e4e-4d3d-4fb3-d8da-3479dd291a7c"
# !wget -O - https://ftp.ebi.ac.uk/pub/databases/gencode/Gencode_human/release_39/gencode.v39.basic.annotation.gtf.gz | gunzip -c > {gtf_file}
# %% [markdown] id="Omj-KERcwSdB"
# ## Utility Code
# %%
def pearsonr_ci(x,y,alpha=0.05):
''' calculate Pearson correlation along with the confidence interval using scipy and numpy
Parameters
----------
x, y : iterable object such as a list or np.array
Input for correlation calculation
alpha : float
Significance level. 0.05 by default
Returns
-------
r : float
Pearson's correlation coefficient
pval : float
The corresponding p value
lo, hi : float
The lower and upper bound of confidence intervals
'''
r, p = scipy.stats.pearsonr(x,y)
r_z = np.arctanh(r)
se = 1/np.sqrt(x.size-3)
z = scipy.stats.norm.ppf(1-alpha/2)
lo_z, hi_z = r_z-z*se, r_z+z*se
lo, hi = np.tanh((lo_z, hi_z))
return r, p, lo, hi
def pearson_scorer(estimator, X, y):
y_pred = estimator.predict(X)
return scipy.stats.pearsonr(y, y_pred)[0]
class Kmerizer:
def __init__(self, k, log=False, divide=False):
self.k = k
self.kmers = {"".join(x):i for i,x in zip(range(4**k), itertools.product("ACGT",repeat=k))}
self.log = log
self.divide = divide
def kmerize(self, seq):
counts = np.zeros(4**self.k)
i = 0
while i < len(seq) - self.k:
kmer = seq[i:i+self.k]
counts[self.kmers[kmer]] += 1
i += 1
if self.divide:
counts = counts/len(seq)
if self.log:
counts = np.log(counts + 1)
return counts
# %%
def plot_a(ax, base, left_edge, height, color):
a_polygon_coords = [
np.array([
[0.0, 0.0],
[0.5, 1.0],
[0.5, 0.8],
[0.2, 0.0],
]),
np.array([
[1.0, 0.0],
[0.5, 1.0],
[0.5, 0.8],
[0.8, 0.0],
]),
np.array([
[0.225, 0.45],
[0.775, 0.45],
[0.85, 0.3],
[0.15, 0.3],
])
]
for polygon_coords in a_polygon_coords:
ax.add_patch(mpl.patches.Polygon((np.array([1,height])[None,:]*polygon_coords
+ np.array([left_edge,base])[None,:]),
facecolor=color, edgecolor=color))
def plot_c(ax, base, left_edge, height, color):
ax.add_patch(mpl.patches.Ellipse(xy=[left_edge+0.65, base+0.5*height], width=1.3, height=height,
facecolor=color, edgecolor=color))
ax.add_patch(mpl.patches.Ellipse(xy=[left_edge+0.65, base+0.5*height], width=0.7*1.3, height=0.7*height,
facecolor='white', edgecolor='white'))
ax.add_patch(mpl.patches.Rectangle(xy=[left_edge+1, base], width=1.0, height=height,
facecolor='white', edgecolor='white', fill=True))
def plot_g(ax, base, left_edge, height, color):
ax.add_patch(mpl.patches.Ellipse(xy=[left_edge+0.65, base+0.5*height], width=1.3, height=height,
facecolor=color, edgecolor=color))
ax.add_patch(mpl.patches.Ellipse(xy=[left_edge+0.65, base+0.5*height], width=0.7*1.3, height=0.7*height,
facecolor='white', edgecolor='white'))
ax.add_patch(mpl.patches.Rectangle(xy=[left_edge+1, base], width=1.0, height=height,
facecolor='white', edgecolor='white', fill=True))
ax.add_patch(mpl.patches.Rectangle(xy=[left_edge+0.825, base+0.085*height], width=0.174, height=0.415*height,
facecolor=color, edgecolor=color, fill=True))
ax.add_patch(mpl.patches.Rectangle(xy=[left_edge+0.625, base+0.35*height], width=0.374, height=0.15*height,
facecolor=color, edgecolor=color, fill=True))
def plot_t(ax, base, left_edge, height, color):
ax.add_patch(mpl.patches.Rectangle(xy=[left_edge+0.4, base],
width=0.2, height=height, facecolor=color, edgecolor=color, fill=True))
ax.add_patch(mpl.patches.Rectangle(xy=[left_edge, base+0.8*height],
width=1.0, height=0.2*height, facecolor=color, edgecolor=color, fill=True))
default_colors = {0:'green', 1:'blue', 2:'orange', 3:'red'}
default_plot_funcs = {0:plot_a, 1:plot_c, 2:plot_g, 3:plot_t}
def plot_weights_given_ax(ax, array,
figsize=(20,2),
height_padding_factor=0.2,
length_padding=1.0,
subticks_frequency=1.0,
colors=default_colors,
plot_funcs=default_plot_funcs,
highlight={},
ylabel=""):
if len(array.shape)==3:
array = np.squeeze(array)
assert len(array.shape)==2, array.shape
if (array.shape[0]==4 and array.shape[1] != 4):
array = array.transpose(1,0)
assert array.shape[1]==4
max_pos_height = 0.0
min_neg_height = 0.0
heights_at_positions = []
depths_at_positions = []
for i in range(array.shape[0]):
#sort from smallest to highest magnitude
acgt_vals = sorted(enumerate(array[i,:]), key=lambda x: abs(x[1]))
positive_height_so_far = 0.0
negative_height_so_far = 0.0
for letter in acgt_vals:
plot_func = plot_funcs[letter[0]]
color=colors[letter[0]]
if (letter[1] > 0):
height_so_far = positive_height_so_far
positive_height_so_far += letter[1]
else:
height_so_far = negative_height_so_far
negative_height_so_far += letter[1]
plot_func(ax=ax, base=height_so_far, left_edge=i, height=letter[1], color=color)
max_pos_height = max(max_pos_height, positive_height_so_far)
min_neg_height = min(min_neg_height, negative_height_so_far)
heights_at_positions.append(positive_height_so_far)
depths_at_positions.append(negative_height_so_far)
#now highlight any desired positions; the key of
#the highlight dict should be the color
for color in highlight:
for start_pos, end_pos in highlight[color]:
assert start_pos >= 0.0 and end_pos <= array.shape[0]
min_depth = np.min(depths_at_positions[start_pos:end_pos])
max_height = np.max(heights_at_positions[start_pos:end_pos])
ax.add_patch(
mpl.patches.Rectangle(xy=[start_pos,min_depth],
width=end_pos-start_pos,
height=max_height-min_depth,
edgecolor=color, fill=False))
ax.set_xlim(-length_padding, array.shape[0]+length_padding)
ax.xaxis.set_ticks(np.arange(0.0, array.shape[0]+1, subticks_frequency))
height_padding = max(abs(min_neg_height)*(height_padding_factor),
abs(max_pos_height)*(height_padding_factor))
ax.set_ylim(min_neg_height-height_padding, max_pos_height+height_padding)
ax.set_ylabel(ylabel)
ax.yaxis.label.set_fontsize(15)
def plot_weights(array,
figsize=(20,2),
despine=False,
**kwargs):
fig = plt.figure(figsize=figsize)
ax = fig.add_subplot(111)
plot_weights_given_ax(ax=ax, array=array,**kwargs)
if despine:
plt.axis('off')
plt.show()
return fig,ax
def plot_score_track_given_ax(arr, ax, threshold=None, **kwargs):
ax.plot(np.arange(len(arr)), arr, **kwargs)
if (threshold is not None):
ax.plot([0, len(arr)-1], [threshold, threshold])
ax.set_xlim(0,len(arr)-1)
def plot_score_track(arr, threshold=None, figsize=(20,2), **kwargs):
fig = plt.figure(figsize=figsize)
ax = fig.add_subplot(111)
plot_score_track_given_ax(arr, threshold=threshold, ax=ax, **kwargs)
plt.show()
# %% [markdown]
# ## Code to do predictions
# %%
def xpresso_batcherator(sample_generator,
xpresso_model,
batch_size=2,
verbose=True):
results = []
debug_output_dict = {}
done = False
batch_idx = 0
while True:
batch = []
# fill batch
for i in range(batch_size):
try:
sample = next(sample_generator)
batch.append(sample)
except StopIteration:
done = True
break
if len(batch) == 0:
break
if len(batch) == 1:
batch_seq = one_hot_encode(batch[0][0])[np.newaxis]
else:
batch_seq = np.stack([one_hot_encode(x[0]) for x in batch])
# predict
mean_half_life_features = np.zeros((batch_seq.shape[0],6), dtype='float32')
predictions = xpresso_model.predict_on_batch([batch_seq,mean_half_life_features]).reshape(-1)
# collect relevant data
for idx, sample in enumerate(batch):
_, metadata = sample
result_dict = {k:v for k,v in metadata.items()}
result_dict["sample_idx"] = batch_idx*batch_size + idx
result_dict["Prediction"] = predictions[idx]
results.append(result_dict)
batch_idx += 1
if verbose and (batch_idx % 100 == 0):
print(batch_idx*batch_size)
if done:
break
return results#, debug_output_dict
# %%
def batcherator(sample_generator,
track_dict,
batch_size=2,
revcomp=True,
verbose=True):
results = []
debug_output_dict = {}
done = False
batch_idx = 0
while True:
batch = []
# fill batch
for i in range(batch_size):
try:
sample = next(sample_generator)
batch.append(sample)
except StopIteration:
done = True
break
if len(batch) == 0:
break
if len(batch) == 1:
batch_seq = one_hot_encode(batch[0][0])[np.newaxis]
else:
batch_seq = np.stack([one_hot_encode(x[0]) for x in batch])
# predict
predictions = model.predict_on_batch(batch_seq)['human']
if revcomp:
predictions_rc = model.predict_on_batch(rev_comp_one_hot(batch_seq))['human']
# collect relevant track data
for idx, sample in enumerate(batch):
_, metadata = sample
result_dict = {k:v for k,v in metadata.items()}
result_dict["sample_idx"] = batch_idx*batch_size + idx
minbin = result_dict["minbin"]
maxbin = result_dict["maxbin"]
landmarkbin = result_dict["landmarkbin"]
for track in track_dict:
#result_dict[track] = predictions[idx,minbin:maxbin,track_dict[track]].copy()
result_dict[track] = np.max(predictions[idx,minbin-1:maxbin+1,track_dict[track]])
result_dict[track + "arg"] = np.argmax(predictions[idx,minbin-1:maxbin+1,track_dict[track]])
result_dict[track + "_sum"] = np.sum(predictions[idx,minbin-1:maxbin+1,track_dict[track]])
result_dict[track + "_localsum"] = np.sum(predictions[idx,minbin-1:maxbin+1,track_dict[track]][max(landmarkbin-1,0):landmarkbin+2])
if revcomp:
result_dict[track + "_rc"] = np.max(predictions_rc[idx,minbin-1:maxbin+1,track_dict[track]])
result_dict[track + "arg_rc"] = np.argmax(predictions_rc[idx,minbin-1:maxbin+1,track_dict[track]])
result_dict[track + "_sum_rc"] = np.sum(predictions_rc[idx,minbin-1:maxbin+1,track_dict[track]])
result_dict[track + "_localsum_rc"] = np.sum(predictions_rc[idx,minbin-1:maxbin+1,track_dict[track]][max(landmarkbin-1,0):landmarkbin+2])
results.append(result_dict)
batch_idx += 1
if verbose and (batch_idx % 5 == 0):
print(batch_idx*batch_size)
if done:
break
return results#, debug_output_dict
# %% [markdown] id="axJyXU13uuUC"
# # Prepare fasta, gtf and enformer
# %% id="5m1IEvOxux_t"
# import target df
target_df = pd.read_csv("Data/Targets/targets.tsv",sep="\t")
target_df_basenji1 = pd.read_csv("Models/Basenji/basenji1_targets.txt",sep="\t", names=["identifier","file","description"])
print("done")
# import gtf
gtf_df = pr.read_gtf(gtf_file)
# %%
# import fasta extractor
fasta_extractor = FastaStringExtractor(fasta_file)
# %% id="21USv_1VIXHz"
# import model
model = Enformer(model_path)
# %% [markdown] id="zEwfoz3cwOzt"
# ## Test that enformer is loaded correctly
# %% id="8u8Gt8WWyG53"
target_interval = kipoiseq.Interval('chr11', 35_082_742, 35_197_430) # @param
sequence_one_hot = one_hot_encode(fasta_extractor.extract(target_interval.resize(SEQUENCE_LENGTH)))
predictions = model.predict_on_batch(sequence_one_hot[np.newaxis])['human'][0]
# %%
tracks = {'DNASE:CD14-positive monocyte female': predictions[:, 41],
'DNASE:keratinocyte female': predictions[:, 42],
'CHIP:H3K27ac:keratinocyte female': predictions[:, 706],
'CAGE:Keratinocyte - epidermal': np.log10(1 + predictions[:, 4799])}
plot_tracks(tracks, target_interval)
# %% [markdown] id="qomUc3saGZj-"
# # Observations about input/output
#
# This section contains some FYI about the model we considered useful to keep in mind during our analyses
# %% [markdown]
# ## Enformer
# %% [markdown]
# - Coordinates appear to be zero-based
# - Enformer takes as input 393216bp
# - Actually processed are 196608bp
# - It predicts for the central 114688, i.e. 896 128bp bins
# - The Plot tracks function only works for this size, it does not clip to display shorter intervals!
# - The center is at the boundary of bin 447 and bin 448
# - CAGE tracks start at channel 4675
# %% [markdown]
# ## Basenji2
#
# It is not super clear (to us) what the Basenji2 receptive field actually is. Below is an attempt to compute it.
# %%
basenji2 = tf.keras.models.load_model(
"Data/Bassenji2/model_human.h5",
custom_objects={
"StochasticShift": basenji2_utils.StochasticShift,
"GELU": basenji2_utils.GELU})
# %% [markdown]
# General formula:
#
# $r_l = s_l \times r_{l-1} + (k_l - s_l)$
#
# where:
# - $s_l$: stride
# - $k_l$: kernel size
# - $r_{l-1}$: receptive field size (after layer l)
#
# For dilation, adapt kernel to:
#
# - $k_l = \alpha (K_l - 1) + 1$, where $K_l$ is the undilated kernel size and $\alpha$ is the dilation rate
# %%
layers = []
layers += [(15,1),(2,2)]
layers += [(5,1),(2,2)]*6
dilation_rates = [basenji2.get_layer("conv1d_{}".format(i)).dilation_rate[0] for i in range(7,7 + 2*11, 2)]
layers += [(d*(3 - 1) + 1, 1) for d in dilation_rates]
r = 0
for layer in layers[::-1]:
r = layer[1]*r + (layer[0] - layer[1])
print(r)
# %% [markdown]
# # Run Xpresso
#
# For analyses where it makes sense, we also compare Xpresso.
#
# Since Xpresso runs very quickly, we simply do it in the notebook.
#
# Xpresso takes sequence as:
#
# - 7000 bp upstream of TSS
# - 3500 bp downstream of TSS
# %% [markdown]
# ## Xpresso - Segal
# %%
base_path_data = "Data/Segal_promoter/"
base_path_results = "Results/Segal_promoter_Xpresso/"
# %%
# Imports
Xpresso = kipoi.get_model("Models/Xpresso/human_median",source="dir")
# %%
Xpresso.model.summary()
# %%
with open(base_path_data + "PZDONOR EF1alpha Cherry ACTB GFP synthetic core promoter library (Ns).gbk") as file:
plasmid_sequence = ""
started_reading = False
for line in file.readlines():
if started_reading:
line = line.strip().replace(" ","").replace("/","")
line = re.sub(r'[0-9]+', '', line)
plasmid_sequence += line
if line.startswith("ORIGIN"):
started_reading = True
plasmid_sequence = plasmid_sequence.upper()
# %%
# extract different components
egfp_seq = rev_comp_sequence(plasmid_sequence[4189:4909])
# %%
# variable region: 4658 - 4822 (0-based)
full_insert = plasmid_sequence[658:6742]
# %% id="fZeyVTNflr5G"
# AAVS1: (PPP1R12C-201, intron 1)
#aavs1 = kipoiseq.Interval(chrom="chr19",start=55116972,end=55117385)
aavs1 = kipoiseq.Interval(chrom="chr19",start=55_115_750,end=55_115_780)
# %%
segal_df = pd.read_csv(base_path_data + "GSM3323461_oligos_measurements_processed_data.tab",sep="\t")
# %% [markdown]
# ### Test insertion
# %%
aavs1
# %%
idx = 15749 #15136#15749
prom = segal_df.loc[idx]["Oligo_sequence"] #15136
insert = full_insert[:4658] + prom + full_insert[4822:]
landmark = len(full_insert[:4658] + prom)
offset = compute_offset_to_center_landmark(landmark,insert)
modified_sequence, minbin, maxbin, landmarkbin = insert_sequence_at_landing_pad(insert, aavs1, fasta_extractor,landmark=landmark, shift_five_end=offset)
modified_sequence = modified_sequence[SEQUENCE_LENGTH//2-7000:SEQUENCE_LENGTH//2+3500]
sequence_one_hot = one_hot_encode(modified_sequence)
sequence_one_hot = sequence_one_hot[np.newaxis,...]
mean_half_life_features = np.zeros((sequence_one_hot.shape[0],6), dtype='float32')
pred = Xpresso.model.predict_on_batch([sequence_one_hot, mean_half_life_features])
# %%
re.search(prom,modified_sequence)
# %% [markdown]
# ### Run it
# %%
15753*7*2
# %%
len(segal_df) * 7*2
# %%
def segal_sample_generator_factory(fasta_extractor):
for crs_row in segal_df.iterrows():
crs_row = crs_row[1]
crs = crs_row["Oligo_sequence"]
for insert_type in ["full", "minimal"]:
if insert_type in ["full"]:
insert = full_insert[:4658] + crs + full_insert[4822:]
landmark = len(full_insert[:4658]) + len(crs)
elif insert_type in ["minimal"]:
insert = crs + egfp_seq
landmark = len(crs)
ideal_offset = compute_offset_to_center_landmark(landmark, insert)
for offset in [-64,-32,-3,0,3,32,64]:
modified_sequence, minbin, maxbin, landmarkbin = \
insert_sequence_at_landing_pad(insert,aavs1,
fasta_extractor,
shift_five_end=ideal_offset + offset,
landmark=landmark)
modified_sequence = modified_sequence[SEQUENCE_LENGTH//2-7000:SEQUENCE_LENGTH//2+3500]
yield modified_sequence, {"Oligo_index":crs_row["Oligo_index"],
"offset":offset,
"insert_type":insert_type}
# prepare generator
sample_generator = \
segal_sample_generator_factory(fasta_extractor=fasta_extractor)
# %%
# write jobs
xpresso_predictions = xpresso_batcherator(sample_generator, Xpresso.model, batch_size=512)
# %%
xpresso_predictions = pd.DataFrame(xpresso_predictions)
# %%
xpresso_predictions.to_csv(base_path_results + "xpresso_predictions.tsv", sep="\t", index=None)
# %% [markdown]
# ### Analysis
# %%
merged_df = pd.read_csv(base_path_results + "xpresso_predictions.tsv", sep="\t")
# %%
pred_col = "Prediction"
# %%
native_df = pd.read_csv(base_path_data + "native_core_promoters.tsv",sep="\t").rename(columns={"GFP_RFP_ratio(mean exp)":"mean_exp"})
native_df["Set"] = "Native"
pic_df = pd.read_csv(base_path_data + "pic_binding_sites.tsv",sep="\t").rename(columns={"GFP_RFP_ratio(mean exp)":"mean_exp"})
elements_df = pd.read_csv(base_path_data + "synthetic_configurations_of_core_promoters.tsv",sep="\t").rename(columns={"GFP_RFP_ratio(mean exp)":"mean_exp"})
tata_shift_df = pd.read_csv(base_path_data + "tata_inr_shift.tsv",sep="\t").rename(columns={"GFP_RFP_ratio(mean exp)":"mean_exp"})
tf_activity_df = pd.read_csv(base_path_data + "tf_activity_screen.tsv", sep="\t").rename(columns={"GFP_RFP_ratio(mean exp)":"mean_exp"})
tf_multiplicity_df = pd.read_csv(base_path_data + "tf_multiplicity_screen.tsv", sep="\t").rename(columns={"GFP_RFP_ratio(mean exp)":"mean_exp"})
# %% [markdown]
# ### Test impact of offset
# %%
native_tested = merged_df.merge(native_df,on="Oligo_index").dropna(subset=["mean_exp"])
pic_tested = merged_df.merge(pic_df,on="Oligo_index").dropna(subset=["mean_exp"])
columns = [pred_col, "Oligo_index", "mean_exp", "CV(std/mean)", "insert_type", "offset"]
endogenous = pd.concat([native_tested[columns],pic_tested[columns]])
for insert_type in ["full","minimal"]:
print(insert_type)
for offset in [-64,-32,-3,0,3,32,64]:
print(offset)
subset = endogenous.query('offset == @offset & insert_type == @insert_type')
print(scipy.stats.pearsonr(subset[pred_col],
np.log2(subset["mean_exp"])))
print(scipy.stats.spearmanr(subset[pred_col],subset["mean_exp"]))
# %% [markdown]
# ## Xpresso TSS
# %%
base_path_results = "Results/TSS_Xpresso/"
base_path_data = "Data/TSS_sim/"
base_path_model = "Models/Xpresso/"
base_path_data_gtex = "Data/GTEX/"
# %% [markdown]
# ### Run it
# %%
name_list = [
"ts_id", "ts_ver", "ts_type", "chr", "strand", "ts_start", "ts_end", "tss",
"ensembl_canonical", "mane", "tsl", "gene_id", "gene_name"
]
# conversion functions for some tsv columns
conv_funs = {
"strand": lambda x: "+" if x == "1" else "-",
"ensembl_canonical": lambda x: True if x == "1" else False,
"mane": lambda x: x if not x == "" else pd.NA,
"tsl": lambda x: x.split(" ")[0] if not x.split(" ")[0] == "" else pd.NA
}
# strand, ensembl_canonical, mane and tsl are handled by their converters
dtype_dict = {
"ts_id": str,
"ts_ver": int,
"ts_type": str,
"chr": str,
"ts_start": int,
"ts_end": int,
"tss": int,
"gene_id": str,
"gene_name": str
}
# create the dataframe
tss_loc_df = pd.read_csv(os.path.join(base_path_data,
"bigly_tss_from_biomart.txt"),
sep="\t",
dtype=dtype_dict,
names=name_list,
converters=conv_funs,
header=0)
# get protein_coding ensembl_canonical transcripts on the standard chromosomes
tss_loc_df = tss_loc_df[(tss_loc_df["ts_type"] == "protein_coding")
& (tss_loc_df["ensembl_canonical"])
& (tss_loc_df["chr"].isin(
list(map(lambda x: str(x), range(1, 23))) +
["MT", "X", "Y"]))]
# needed to translate chromosome symbols from biomart output to fasta
chromosome_dict = {
"1": "chr1",
"2": "chr2",
"3": "chr3",
"4": "chr4",
"5": "chr5",
"6": "chr6",
"7": "chr7",
"8": "chr8",
"9": "chr9",
"10": "chr10",
"11": "chr11",
"12": "chr12",
"13": "chr13",
"14": "chr14",
"15": "chr15",
"16": "chr16",
"17": "chr17",
"18": "chr18",
"19": "chr19",
"20": "chr20",
"21": "chr21",
"22": "chr22",
"MT": "chrM",
"X": "chrX",
"Y": "chrY"
}
# %%
stranded_fasta_extractor = kipoiseq.extractors.FastaStringExtractor(fasta_file, use_strand=True)
Xpresso = kipoi.get_model("Models/Xpresso/human_median",source="dir")
# %%
def tss_xpresso_sample_generator_factory():
for crs_row in tss_loc_df.iterrows():
crs_row = crs_row[1]
tss = crs_row["tss"]
chrom = chromosome_dict[crs_row["chr"]]
strand = crs_row["strand"]
if tss < 7000:
continue
if strand == "+":
tss_interval = kipoiseq.Interval(chrom=chrom,start=tss-1-7000,end=tss-1+3500, strand=strand)
else:
tss_interval = kipoiseq.Interval(chrom=chrom,start=tss-1-3500,end=tss-1+7000, strand=strand)
seq = stranded_fasta_extractor.extract(tss_interval).upper()
if len(seq) != 7000+3500:
seq = seq + "N"*(7000+3500-len(seq))
yield seq, {"gene_id":crs_row["gene_id"]}
# %%
# run
xpresso_predictions = xpresso_batcherator(tss_xpresso_sample_generator_factory(), Xpresso.model, batch_size=512)
# %%
xpresso_pred_df = pd.DataFrame(xpresso_predictions)
# %%
xpresso_pred_df.to_csv(base_path_results + "xpresso_preds.tsv", sep="\t", index=None)
# %% [markdown] id="ypHneLKBYNAX"
# # Weingarten-Gabbay et al. (Segal lab) Promoter MPRA
#
# This section contains our analysis for the Weingarten-Gabbay et al. promoter MPRA.
# %% [markdown]
# Some background info, to keep in mind
#
# Experimental design:
#
# - Tested ~15k different promoters at the AAVS1 site
#
# - Cell type: K562
#
# Makeup of the insert (in genbank file, 1-based)
#
# - 659-1462: left homology arm
# - 1481-2815: EF1alpha promoter
# - 2832-3456: Kozak + mCherry
# - 3594-3818: BGH Poly(A)
# - 3931-4152: (rc) sv40 polyA
# - 4190-4909: (rc) eGFP
# - 4995-5127: (rc) chimeric intron
# - 5317-5480: (rc) crs region
# - 5905-6742: right homology arm
# %% [markdown] id="xgclGqIoouDn"
# The relevant columns are:
#
# \["Oligo_index", "Set", "GFP_RFP_ratio(mean exp)", "CV(std/mean)", "Oligo_Sequence"\]
#
# NB: Native core promoters have no column "Set"
# %%
base_path_data = "Data/Segal_promoter/"
base_path_results = "Results/Segal_promoter/"
base_path_results_xpresso = "Results/Segal_promoter_Xpresso/"
# %%
with open(base_path_data + "PZDONOR EF1alpha Cherry ACTB GFP synthetic core promoter library (Ns).gbk") as file:
plasmid_sequence = ""
started_reading = False
for line in file.readlines():
if started_reading:
line = line.strip().replace(" ","").replace("/","")
line = re.sub(r'[0-9]+', '', line)
plasmid_sequence += line
if line.startswith("ORIGIN"):
started_reading = True
plasmid_sequence = plasmid_sequence.upper()
# %%
# extract different components
egfp_seq = rev_comp_sequence(plasmid_sequence[4189:4909])
# %%
# variable region: 4658 - 4822 (0-based)
full_insert = plasmid_sequence[658:6742]
# %% id="fZeyVTNflr5G"
# AAVS1: (PPP1R12C-201, intron 1)
#aavs1 = kipoiseq.Interval(chrom="chr19",start=55116972,end=55117385)
aavs1 = kipoiseq.Interval(chrom="chr19",start=55_115_750,end=55_115_780)
# %%
segal_df = pd.read_csv(base_path_data + "GSM3323461_oligos_measurements_processed_data.tab",sep="\t")
# %%
len(segal_df)
# %%
segal_df["Oligo_sequence"].str.len().describe()
# %% [markdown]
# ## Test insertion
#
# We try out a particular promoter, to see if Enformer understands what we are trying to do at all
# %%
aavs1
# %%
def test_segal_insertion(insert, landmark, extra_offset=0, verbose=True):
offset = compute_offset_to_center_landmark(landmark,insert)
modified_sequence, minbin, maxbin, landmarkbin = insert_sequence_at_landing_pad(insert, aavs1, fasta_extractor,landmark=landmark, shift_five_end=offset + extra_offset)
sequence_one_hot = one_hot_encode(modified_sequence)
predictions = model.predict_on_batch(sequence_one_hot[np.newaxis])['human'][0]
if verbose:
tracks = {'DNASE:K562': predictions[:, 121],
'CAGE:chronic myelogenous leukemia cell line:K562': np.log10(1 + predictions[:, 4828]),
}
plot_tracks(tracks, target_interval)
print(predictions[minbin-1:maxbin+1, 4828])
print(predictions[landmarkbin, 4828])
print(sum(predictions[minbin-1:maxbin+1, 4828]))
else:
return (predictions[landmarkbin, 4828], sum(predictions[landmarkbin-1:landmarkbin+2, 4828]))
# %%
idx = 15136#15749
prom = segal_df.loc[idx]["Oligo_sequence"] #15136
insert = full_insert[:4658] + prom + full_insert[4822:]
landmark = len(full_insert[:4658]) + len(prom)//2
target_interval = kipoiseq.Interval(chrom="chr19",
start=(aavs1.start+aavs1.end)//2 - 114688//2,
end=(aavs1.start+aavs1.end)//2 + 114688//2,
)
# %%
#basal
sequence_one_hot = one_hot_encode(fasta_extractor.extract(target_interval.resize(SEQUENCE_LENGTH)))
predictions = model.predict_on_batch(sequence_one_hot[np.newaxis])['human'][0]
tracks = {'DNASE:K562': predictions[:, 121],
'CAGE:chronic myelogenous leukemia cell line:K562': np.log10(1 + predictions[:, 4828]),
}
plot_tracks(tracks, target_interval)
print(predictions[446:449, 4828])
# %%
test_segal_insertion(insert, landmark)
# %%
test_segal_insertion(insert, landmark, extra_offset = -64)
# %%
# revcomp
insert_rc = rev_comp_sequence(full_insert[:4658] + prom + full_insert[4822:])
landmark_rc = len(full_insert[4822:]) + len(prom)//2
test_segal_insertion(insert_rc, landmark_rc, extra_offset = 0)
# %%
test_segal_insertion(insert_rc, landmark_rc, extra_offset = -64)
# %% [markdown]
# ### Remove everything except the core promoter and the egfp
#
# This produces a decent amount of expression...
# %%
# with no offset
insert_min = prom + egfp_seq
landmark_min = len(prom)//2
test_segal_insertion(insert_min, landmark_min, extra_offset = 0)
# %%
# with -64 offset
test_segal_insertion(insert_min, landmark_min, extra_offset = -64)
# %% [markdown]
# ### Only insert a coding sequence
#
# Reassuringly, this does not create expression
# %%
insert_egfp = egfp_seq
landmark = len(egfp_seq)//2
test_segal_insertion(insert_egfp, landmark, extra_offset = -64)
# %% [markdown]
# ## Analysis
# %%
# load enformer
pred_col = 'CAGE:chronic myelogenous leukemia cell line:K562 ENCODE, biol__landmark_sum'
pred_col_dnase = 'DNASE:K562_landmark_sum'
merged_df = pd.read_csv(base_path_results + "segal_promoters-enformer-latest_results.tsv", sep='\t')
merged_df = (merged_df
.groupby(["Oligo_index","insert_type"])[[col for col in merged_df.keys() if col.startswith("CAGE") or col.startswith("DNASE")]]
.mean()
.reset_index())
merged_df_full = merged_df.query('insert_type == "full"')
merged_df_fullrv = merged_df.query('insert_type == "full_rv"')
merged_df_min = merged_df.query('insert_type == "minimal"')