In [1]:
import os
import sys
sys.path.append(os.path.abspath("/users/amtseng/tfmodisco/src/"))
from tfmodisco.run_tfmodisco import import_shap_scores, import_tfmodisco_results
from motif.read_motifs import pfm_info_content, pfm_to_pwm, trim_motif_by_ic
from motif.match_motifs import match_motifs_to_database
from util import figure_to_vdom_image
import plot.viz_sequence as viz_sequence
import numpy as np
import h5py
import matplotlib.pyplot as plt
import vdom.helpers as vdomh
from IPython.display import display

Define constants and paths

In [2]:
# Define parameters/fetch arguments
tf_name = os.environ["TFM_TF_NAME"]
shap_scores_path = os.environ["TFM_SHAP_PATH"]
tfm_results_path = os.environ["TFM_TFM_PATH"]
hyp_score_key = os.environ["TFM_HYP_SCORE_KEY"]
if "TFM_MOTIF_CACHE" in os.environ:
    tfm_motifs_cache_dir = os.environ["TFM_MOTIF_CACHE"]
else:
    tfm_motifs_cache_dir = None

print("TF name: %s" % tf_name)
print("DeepSHAP scores path: %s" % shap_scores_path)
print("TF-MoDISco results path: %s" % tfm_results_path)
print("Importance score key: %s" % hyp_score_key)
print("Saved TF-MoDISco-derived motifs cache: %s" % tfm_motifs_cache_dir)
TF name: GABPA
DeepSHAP scores path: /users/amtseng/tfmodisco/results/importance_scores/multitask_profile/GABPA_multitask_profile_fold2/GABPA_multitask_profile_fold2_imp_scores.h5
TF-MoDISco results path: /users/amtseng/tfmodisco/results/tfmodisco/multitask_profile/GABPA_multitask_profile_fold2/GABPA_multitask_profile_fold2_profile_tfm.h5
Importance score key: profile_hyp_scores
Saved TF-MoDISco-derived motifs cache: /users/amtseng/tfmodisco/results/reports/tfmodisco_results//cache/multitask_profile/GABPA_multitask_profile_fold2/GABPA_multitask_profile_fold2_profile
In [3]:
# Define paths and constants
input_length = 2114
shap_score_center_size = 400
In [4]:
if tfm_motifs_cache_dir:
    os.makedirs(tfm_motifs_cache_dir, exist_ok=True)

Import SHAP scores and TF-MoDISco results

In [5]:
# Import SHAP coordinates and one-hot sequences
hyp_scores, _, one_hot_seqs, shap_coords = import_shap_scores(shap_scores_path, hyp_score_key, center_cut_size=shap_score_center_size)
# This cuts the sequences/scores off just as how TF-MoDISco saw them, but the coordinates are uncut
Importing SHAP scores: 100%|██████████| 104/104 [01:23<00:00,  1.25it/s]
In [6]:
# Import the TF-MoDISco results object
tfm_obj = import_tfmodisco_results(tfm_results_path, hyp_scores, one_hot_seqs, shap_score_center_size)

Plot some SHAP score tracks

Plot the central region of some randomly selected actual importance scores

In [7]:
plot_slice = slice(int(shap_score_center_size / 4), int(3 * shap_score_center_size / 4))
for index in np.random.choice(hyp_scores.shape[0], size=5, replace=False):
    viz_sequence.plot_weights((hyp_scores[index] * one_hot_seqs[index])[plot_slice], subticks_frequency=100)

Plot TF-MoDISco results

Plot all motifs by metacluster

In [8]:
motif_pfms, motif_hcwms, motif_cwms = [], [], []  # Save the trimmed PFMs, hCWMs, and CWMs
motif_pfms_short = []  # PFMs that are even more trimmed (for TOMTOM)
num_seqlets = []  # Number of seqlets for each motif
motif_seqlets = []  # Save seqlets of each motif
metaclusters = tfm_obj.metacluster_idx_to_submetacluster_results
num_metaclusters = len(metaclusters.keys())
if tfm_motifs_cache_dir:
    motif_hdf5 = h5py.File(os.path.join(tfm_motifs_cache_dir, "all_motifs.h5"), "w")
for metacluster_i, metacluster_key in enumerate(metaclusters.keys()):
    metacluster = metaclusters[metacluster_key]
    display(vdomh.h3("Metacluster %d/%d" % (metacluster_i + 1, num_metaclusters)))
    patterns = metacluster.seqlets_to_patterns_result.patterns
    if not patterns:
        break
    motif_pfms.append([])
    motif_hcwms.append([])
    motif_cwms.append([])
    motif_pfms_short.append([])
    num_seqlets.append([])
    motif_seqlets.append([])
    num_patterns = len(patterns)
    for pattern_i, pattern in enumerate(patterns):
        seqlets = pattern.seqlets
        display(vdomh.h4("Pattern %d/%d" % (pattern_i + 1, num_patterns)))
        display(vdomh.p("%d seqlets" % len(seqlets)))
        
        pfm = pattern["sequence"].fwd
        hcwm = pattern["task0_hypothetical_contribs"].fwd
        cwm = pattern["task0_contrib_scores"].fwd
        
        pfm_fig = viz_sequence.plot_weights(pfm, subticks_frequency=10, return_fig=True)
        hcwm_fig = viz_sequence.plot_weights(hcwm, subticks_frequency=10, return_fig=True)
        cwm_fig = viz_sequence.plot_weights(cwm, subticks_frequency=10, return_fig=True)
        pfm_fig.tight_layout()
        hcwm_fig.tight_layout()
        cwm_fig.tight_layout()
        
        motif_table = vdomh.table(
            vdomh.tr(
                vdomh.td("Sequence (PFM)"),
                vdomh.td(figure_to_vdom_image(pfm_fig))
            ),
            vdomh.tr(
                vdomh.td("Hypothetical contributions (hCWM)"),
                vdomh.td(figure_to_vdom_image(hcwm_fig))
            ),
            vdomh.tr(
                vdomh.td("Actual contributions (CWM)"),
                vdomh.td(figure_to_vdom_image(cwm_fig))
            )
        )
        display(motif_table)
        plt.close("all")  # Remove all standing figures
        
        # Trim motif based on information content
        short_trimmed_pfm = trim_motif_by_ic(pfm, pfm)
        motif_pfms_short[-1].append(short_trimmed_pfm)
        
        # Expand trimming to +/- 4bp on either side
        trimmed_pfm = trim_motif_by_ic(pfm, pfm, pad=4)
        trimmed_hcwm = trim_motif_by_ic(pfm, hcwm, pad=4)
        trimmed_cwm = trim_motif_by_ic(pfm, cwm, pad=4)
        
        motif_pfms[-1].append(trimmed_pfm)
        motif_hcwms[-1].append(trimmed_hcwm)
        motif_cwms[-1].append(trimmed_cwm)
        
        num_seqlets[-1].append(len(seqlets))
        
        if tfm_motifs_cache_dir:
            # Save results and figures
            motif_id = "%d_%d" % (metacluster_i, pattern_i)
            pfm_fig.savefig(os.path.join(tfm_motifs_cache_dir, motif_id + "_pfm_full.png"))
            hcwm_fig.savefig(os.path.join(tfm_motifs_cache_dir, motif_id + "_hcwm_full.png"))
            cwm_fig.savefig(os.path.join(tfm_motifs_cache_dir, motif_id + "_cwm_full.png"))
            motif_dset = motif_hdf5.create_group(motif_id)
            motif_dset.create_dataset("pfm_full", data=pfm, compression="gzip")
            motif_dset.create_dataset("hcwm_full", data=hcwm, compression="gzip")
            motif_dset.create_dataset("cwm_full", data=cwm, compression="gzip")
            motif_dset.create_dataset("pfm_trimmed", data=trimmed_pfm, compression="gzip")
            motif_dset.create_dataset("hcwm_trimmed", data=trimmed_hcwm, compression="gzip")
            motif_dset.create_dataset("cwm_trimmed", data=trimmed_cwm, compression="gzip")
            motif_dset.create_dataset("pfm_short_trimmed", data=short_trimmed_pfm, compression="gzip")
if tfm_motifs_cache_dir:
    motif_hdf5.close()

Metacluster 1/2

Pattern 1/10

5382 seqlets

Sequence (PFM)
Hypothetical contributions (hCWM)
Actual contributions (CWM)

Pattern 2/10

835 seqlets

Sequence (PFM)
Hypothetical contributions (hCWM)
Actual contributions (CWM)

Pattern 3/10

574 seqlets

Sequence (PFM)
Hypothetical contributions (hCWM)
Actual contributions (CWM)

Pattern 4/10

475 seqlets

Sequence (PFM)
Hypothetical contributions (hCWM)
Actual contributions (CWM)

Pattern 5/10

423 seqlets

Sequence (PFM)
Hypothetical contributions (hCWM)
Actual contributions (CWM)

Pattern 6/10

354 seqlets

Sequence (PFM)
Hypothetical contributions (hCWM)
Actual contributions (CWM)

Pattern 7/10

202 seqlets

Sequence (PFM)
Hypothetical contributions (hCWM)
Actual contributions (CWM)

Pattern 8/10

119 seqlets

Sequence (PFM)
Hypothetical contributions (hCWM)
Actual contributions (CWM)

Pattern 9/10

95 seqlets

Sequence (PFM)
Hypothetical contributions (hCWM)
Actual contributions (CWM)

Pattern 10/10

54 seqlets

Sequence (PFM)
Hypothetical contributions (hCWM)
Actual contributions (CWM)

Metacluster 2/2

Pattern 1/2

502 seqlets

Sequence (PFM)
Hypothetical contributions (hCWM)
Actual contributions (CWM)

Pattern 2/2

56 seqlets

Sequence (PFM)
Hypothetical contributions (hCWM)
Actual contributions (CWM)

Summary of motifs

Motifs are trimmed based on information content, and presented in descending order by number of supporting seqlets. The motifs are separated by metacluster. The motifs are presented as hCWMs. The forward orientation is defined as the orientation that is richer in purines.

In [9]:
colgroup = vdomh.colgroup(
    vdomh.col(style={"width": "5%"}),
    vdomh.col(style={"width": "5%"}),
    vdomh.col(style={"width": "45%"}),
    vdomh.col(style={"width": "45%"})
)
header = vdomh.thead(
    vdomh.tr(
        vdomh.th("#", style={"text-align": "center"}),
        vdomh.th("Seqlets", style={"text-align": "center"}),
        vdomh.th("Forward", style={"text-align": "center"}),
        vdomh.th("Reverse", style={"text-align": "center"})
    )
)

for i in range(len(motif_hcwms)):
    display(vdomh.h3("Metacluster %d/%d" % (i + 1, num_metaclusters)))
    body = []
    for j in range(len(motif_hcwms[i])):
        motif = motif_hcwms[i][j]
        if np.sum(motif[:, [0, 2]]) > 0.5 * np.sum(motif):
            # Forward is purine-rich, reverse-complement is pyrimidine-rich
            f, rc = motif, np.flip(motif, axis=(0, 1))
        else:
            f, rc = np.flip(motif, axis=(0, 1)), motif
            
        f_fig = viz_sequence.plot_weights(f, figsize=(20, 4), return_fig=True)
        f_fig.tight_layout()
        rc_fig = viz_sequence.plot_weights(rc, figsize=(20, 4), return_fig=True)
        rc_fig.tight_layout()
        
        if tfm_motifs_cache_dir:
            # Save results and figures
            motif_id = "%d_%d" % (i, j)
            f_fig.savefig(os.path.join(tfm_motifs_cache_dir, motif_id + "_hcwm_trimmed_fwd.png"))
            rc_fig.savefig(os.path.join(tfm_motifs_cache_dir, motif_id + "_hcwm_trimmed_rev.png"))

        body.append(
            vdomh.tr(
                vdomh.td(str(j + 1)),
                vdomh.td(str(num_seqlets[i][j])),
                vdomh.td(figure_to_vdom_image(f_fig)),
                vdomh.td(figure_to_vdom_image(rc_fig))
            )
        )
    display(vdomh.table(colgroup, header, vdomh.tbody(*body)))
    plt.close("all")

Metacluster 1/2

#SeqletsForwardReverse
15382
2835
3574
4475
5423
6354
7202
8119
995
1054

Metacluster 2/2

#SeqletsForwardReverse
1502
256

Top TOMTOM matches for each motif

Here, the TF-MoDISco motifs are plotted as hCWMs, but the TOMTOM matches are shown as PWMs.

In [10]:
num_matches_to_keep = 10
num_matches_to_show = 5

header = vdomh.thead(
    vdomh.tr(
        vdomh.th("Motif ID", style={"text-align": "center"}),
        vdomh.th("q-val", style={"text-align": "center"}),
        vdomh.th("PWM", style={"text-align": "center"})
    )
)

for i in range(len(motif_pfms)):
    display(vdomh.h3("Metacluster %d/%d" % (i + 1, num_metaclusters)))
    
    # Compute TOMTOM matches for all motifs in the metacluster at once
    out_dir = os.path.join(tfm_motifs_cache_dir, "tomtom", "metacluster_%d" % i) if tfm_motifs_cache_dir else None
    tomtom_matches = match_motifs_to_database(motif_pfms_short[i], top_k=num_matches_to_keep, temp_dir=out_dir)
    
    for j in range(len(motif_pfms[i])):
        display(vdomh.h4("Motif %d/%d" % (j + 1, len(motif_pfms[i]))))
        viz_sequence.plot_weights(motif_hcwms[i][j])
    
        body = []
        for k, (match_name, match_pfm, match_qval) in enumerate(tomtom_matches[j]):
            fig = viz_sequence.plot_weights(pfm_to_pwm(match_pfm), return_fig=True)
            fig.tight_layout()
            if k < num_matches_to_show:
                body.append(
                    vdomh.tr(
                        vdomh.td(match_name),
                        vdomh.td(str(match_qval)),
                        vdomh.td(figure_to_vdom_image(fig))
                    )
                )
                if tfm_motifs_cache_dir:
                    # Save results and figures
                    motif_id = "%d_%d" % (i, j)
                    fig.savefig(os.path.join(out_dir, motif_id + ("_hit-%d.png" % (k + 1))))
            else:
                body.append(
                    vdomh.tr(
                        vdomh.td(match_name),
                        vdomh.td(str(match_qval)),
                        vdomh.td("Not shown")
                    )
                )
        if not body:
            display(vdomh.p("No TOMTOM matches passing threshold"))
        else:
            display(vdomh.table(header, vdomh.tbody(*body)))
        plt.close("all")

Metacluster 1/2

Motif 1/10

Motif IDq-valPWM
ELF2_HUMAN.H11MO.0.C2.8456900000000003e-06
MA0750.2_ZBTB7A2.8456900000000003e-06
GABPA_HUMAN.H11MO.0.A2.8456900000000003e-06
MA0076.2_ELK45.45701e-06
MA0765.2_ETV55.45701e-06
ELK1_HUMAN.H11MO.0.B5.45701e-06Not shown
ETV1_HUMAN.H11MO.0.A5.45701e-06Not shown
ELF1_HUMAN.H11MO.0.A8.35605e-06Not shown
ELK4_HUMAN.H11MO.0.A2.24943e-05Not shown
MA0641.1_ELF42.24943e-05Not shown

Motif 2/10

Motif IDq-valPWM
GABPA_HUMAN.H11MO.0.A0.07725989999999999
MA0772.1_IRF70.117834
MA0076.2_ELK40.117834
MA0640.2_ELF30.156895
MA1484.1_ETS20.156895
MA0765.2_ETV50.156895Not shown
MA1508.1_IKZF10.156895Not shown
ELK4_HUMAN.H11MO.0.A0.156895Not shown
ELK1_HUMAN.H11MO.0.B0.156895Not shown
MA1420.1_IRF50.156895Not shown

Motif 3/10

Motif IDq-valPWM
MA1513.1_KLF150.11646500000000001
MA0748.2_YY20.11646500000000001
THAP1_HUMAN.H11MO.0.C0.11646500000000001
MA0758.1_E2F70.11646500000000001
E2F4_HUMAN.H11MO.1.A0.11646500000000001
TFDP1_HUMAN.H11MO.0.C0.11646500000000001Not shown
TYY2_HUMAN.H11MO.0.D0.145048Not shown
MA0865.1_E2F80.145048Not shown
TYY1_HUMAN.H11MO.0.A0.145048Not shown
E2F4_HUMAN.H11MO.0.A0.145048Not shown

Motif 4/10

Motif IDq-valPWM
ZNF76_HUMAN.H11MO.0.C6.352190000000001e-23
ZN143_HUMAN.H11MO.0.A1.60594e-20
THA11_HUMAN.H11MO.0.B4.60921e-18
MA1573.1_THAP112.37033e-09
MA0088.2_ZNF1430.0126207
STAT3_HUMAN.H11MO.0.A0.0769112Not shown
P63_HUMAN.H11MO.0.A0.0769112Not shown
MA1625.1_Stat5b0.13460999999999998Not shown
MA0519.1_Stat5a::Stat5b0.193752Not shown
MA0525.2_TP630.193752Not shown

Motif 5/10

Motif IDq-valPWM
TAF1_HUMAN.H11MO.0.A0.014150799999999998
SP1_HUMAN.H11MO.1.A0.133278
MA1513.1_KLF150.133278
EGR4_HUMAN.H11MO.0.D0.133278
SP2_HUMAN.H11MO.0.A0.133278
MA0753.2_ZNF7400.133278Not shown
MA0146.2_Zfx0.133278Not shown
MA0748.2_YY20.133278Not shown
MA1596.1_ZNF4600.133278Not shown
MA1630.1_Znf2810.150599Not shown

Motif 6/10

Motif IDq-valPWM
ATF1_HUMAN.H11MO.0.B1.3322899999999999e-05
CREB1_HUMAN.H11MO.0.A5.03372e-05
ATF2_HUMAN.H11MO.2.C0.00169714
CREB5_HUMAN.H11MO.0.D0.00225774
ATF7_HUMAN.H11MO.0.D0.00225774
MA1131.1_FOSL2::JUN(var.2)0.00274098Not shown
MA1127.1_FOSB::JUN0.00299804Not shown
MA0656.1_JDP2(var.2)0.00333503Not shown
MA0605.2_ATF30.00333503Not shown
MA1475.1_CREB3L4(var.2)0.00333503Not shown

Motif 7/10

No TOMTOM matches passing threshold

Motif 8/10

Motif IDq-valPWM
MA0750.2_ZBTB7A0.412832
MA0095.2_YY10.412832
ZN341_HUMAN.H11MO.1.C0.412832
KLF1_HUMAN.H11MO.0.A0.412832
ZBTB6_HUMAN.H11MO.0.C0.412832
MA0146.2_Zfx0.412832Not shown
SP1_HUMAN.H11MO.0.A0.412832Not shown
TYY1_HUMAN.H11MO.0.A0.412832Not shown
SP3_HUMAN.H11MO.0.B0.412832Not shown
SP2_HUMAN.H11MO.0.A0.412832Not shown

Motif 9/10

Motif IDq-valPWM
SP1_HUMAN.H11MO.0.A0.000217227
SP2_HUMAN.H11MO.0.A0.000217227
SP3_HUMAN.H11MO.0.B0.000521602
MA1102.2_CTCFL0.00916169
KLF16_HUMAN.H11MO.0.D0.014021899999999999
PATZ1_HUMAN.H11MO.0.C0.014021899999999999Not shown
SP1_HUMAN.H11MO.1.A0.0160047Not shown
MA1650.1_ZBTB140.0168679Not shown
MA1584.1_ZIC50.0168679Not shown
KLF3_HUMAN.H11MO.0.B0.0168679Not shown

Motif 10/10

Motif IDq-valPWM
SP3_HUMAN.H11MO.0.B2.62376e-07
SP2_HUMAN.H11MO.0.A1.03328e-05
SP4_HUMAN.H11MO.0.A0.000124029
WT1_HUMAN.H11MO.0.C0.000124029
ZN219_HUMAN.H11MO.0.D0.000124029
KLF3_HUMAN.H11MO.0.B0.00016563599999999998Not shown
SP1_HUMAN.H11MO.0.A0.000227705Not shown
VEZF1_HUMAN.H11MO.0.C0.0008941260000000001Not shown
ZN467_HUMAN.H11MO.0.C0.00151307Not shown
TBX15_HUMAN.H11MO.0.D0.00165223Not shown

Metacluster 2/2

Motif 1/2

Motif IDq-valPWM
MA0076.2_ELK43.38879e-05
GABPA_HUMAN.H11MO.0.A0.00025818900000000003
MA0759.1_ELK30.000320677
ETV1_HUMAN.H11MO.0.A0.000320677
MA0765.2_ETV50.000320677
ELK4_HUMAN.H11MO.0.A0.000320677Not shown
MA1483.1_ELF20.000320677Not shown
ELF2_HUMAN.H11MO.0.C0.000320677Not shown
MA0750.2_ZBTB7A0.000320677Not shown
ELF1_HUMAN.H11MO.0.A0.000329839Not shown

Motif 2/2

Motif IDq-valPWM
MA0765.2_ETV50.000150359
MA0076.2_ELK40.00024226
ETV1_HUMAN.H11MO.0.A0.0014965
ELK1_HUMAN.H11MO.0.B0.00156473
ELK4_HUMAN.H11MO.0.A0.00156473
FEV_HUMAN.H11MO.0.B0.00156473Not shown
MA0750.2_ZBTB7A0.00156473Not shown
SP2_HUMAN.H11MO.0.A0.00313441Not shown
MA0474.2_ERG0.00489793Not shown
MA0475.2_FLI10.00519527Not shown