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: SPI1
DeepSHAP scores path: /users/amtseng/tfmodisco/results/importance_scores/multitask_profile/SPI1_multitask_profile_fold1/SPI1_multitask_profile_fold1_imp_scores.h5
TF-MoDISco results path: /users/amtseng/tfmodisco/results/tfmodisco/multitask_profile/SPI1_multitask_profile_fold1/SPI1_multitask_profile_fold1_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/SPI1_multitask_profile_fold1/SPI1_multitask_profile_fold1_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%|██████████| 194/194 [03:31<00:00,  1.09s/it]
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/6

13242 seqlets

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

Pattern 2/6

558 seqlets

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

Pattern 3/6

291 seqlets

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

Pattern 4/6

57 seqlets

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

Pattern 5/6

50 seqlets

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

Pattern 6/6

50 seqlets

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

Metacluster 2/2

Pattern 1/7

118 seqlets

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

Pattern 2/7

91 seqlets

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

Pattern 3/7

88 seqlets

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

Pattern 4/7

69 seqlets

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

Pattern 5/7

64 seqlets

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

Pattern 6/7

60 seqlets

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

Pattern 7/7

59 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
113242
2558
3291
457
550
650

Metacluster 2/2

#SeqletsForwardReverse
1118
291
388
469
564
660
759

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/6

Motif IDq-valPWM
SPIB_HUMAN.H11MO.0.A4.40041e-15
MA0081.2_SPIB1.3673899999999999e-12
SPI1_HUMAN.H11MO.0.A1.3673899999999999e-12
BC11A_HUMAN.H11MO.0.A2.2362099999999998e-10
IRF4_HUMAN.H11MO.0.A2.3852900000000005e-10
IRF8_HUMAN.H11MO.0.B7.553319999999999e-10Not shown
MA0080.5_SPI11.4521400000000001e-09Not shown
MA0761.2_ETV17.37487e-05Not shown
MA0062.3_GABPA0.000112366Not shown
MA0050.2_IRF10.000661562Not shown

Motif 2/6

No TOMTOM matches passing threshold

Motif 3/6

Motif IDq-valPWM
MA0081.2_SPIB0.000575067
MA0080.5_SPI10.000575067
SPI1_HUMAN.H11MO.0.A0.000575067
SPIB_HUMAN.H11MO.0.A0.000773473
BC11A_HUMAN.H11MO.0.A0.000990353
IRF4_HUMAN.H11MO.0.A0.00191948Not shown
IRF8_HUMAN.H11MO.0.B0.00312395Not shown
MA0645.1_ETV60.010061200000000001Not shown
MA0761.2_ETV10.017686Not shown
MA0598.3_EHF0.017686Not shown

Motif 4/6

Motif IDq-valPWM
CPEB1_HUMAN.H11MO.0.D0.000170068
PRDM6_HUMAN.H11MO.0.C0.000334463
IRF3_HUMAN.H11MO.0.B0.00163807
MA0080.5_SPI10.00204423
NFAC1_HUMAN.H11MO.0.B0.00866393
VEZF1_HUMAN.H11MO.0.C0.012731399999999999Not shown
ETS2_HUMAN.H11MO.0.B0.012866200000000001Not shown
BC11A_HUMAN.H11MO.0.A0.012866200000000001Not shown
SPIB_HUMAN.H11MO.0.A0.012866200000000001Not shown
STAT1_HUMAN.H11MO.1.A0.013824200000000002Not shown

Motif 5/6

Motif IDq-valPWM
MA0081.2_SPIB5.06852e-07
SPIB_HUMAN.H11MO.0.A5.06852e-07
SPI1_HUMAN.H11MO.0.A6.44472e-07
MA0761.2_ETV13.5970099999999995e-06
MA0598.3_EHF1.21455e-05
MA0062.3_GABPA1.21455e-05Not shown
BC11A_HUMAN.H11MO.0.A1.21455e-05Not shown
MA0080.5_SPI11.21455e-05Not shown
MA1508.1_IKZF11.39104e-05Not shown
MA0473.3_ELF10.00017444099999999998Not shown

Motif 6/6

Motif IDq-valPWM
CPEB1_HUMAN.H11MO.0.D2.34948e-05
MA1125.1_ZNF3840.0175916
PRDM6_HUMAN.H11MO.0.C0.0232365
FOXL1_HUMAN.H11MO.0.D0.0323931
FOXG1_HUMAN.H11MO.0.D0.0592592
ANDR_HUMAN.H11MO.0.A0.11618099999999999Not shown
FOXJ3_HUMAN.H11MO.0.A0.117448Not shown
MA0679.2_ONECUT10.122423Not shown
MA0080.5_SPI10.158621Not shown
FUBP1_HUMAN.H11MO.0.D0.176738Not shown

Metacluster 2/2

Motif 1/7

No TOMTOM matches passing threshold

Motif 2/7

Motif IDq-valPWM
ELF5_HUMAN.H11MO.0.A0.00713276
SPIB_HUMAN.H11MO.0.A0.00713276
MA0081.2_SPIB0.00713276
SPI1_HUMAN.H11MO.0.A0.00713276
ETV7_HUMAN.H11MO.0.D0.008378499999999999
BC11A_HUMAN.H11MO.0.A0.008378499999999999Not shown
MA0687.1_SPIC0.00886668Not shown
ELF3_HUMAN.H11MO.0.A0.0108616Not shown
IRF8_HUMAN.H11MO.0.B0.0108616Not shown
MA0080.5_SPI10.0108616Not shown

Motif 3/7

Motif IDq-valPWM
MA0765.2_ETV50.0235034
SPI1_HUMAN.H11MO.0.A0.0235034
MA0080.5_SPI10.0235034
MA0062.3_GABPA0.0235034
ELK3_HUMAN.H11MO.0.D0.0235034
ELF2_HUMAN.H11MO.0.C0.0235034Not shown
MA0076.2_ELK40.0235034Not shown
ELK4_HUMAN.H11MO.0.A0.0235034Not shown
ELF1_HUMAN.H11MO.0.A0.0235034Not shown
MA0750.2_ZBTB7A0.0235034Not shown

Motif 4/7

No TOMTOM matches passing threshold

Motif 5/7

Motif IDq-valPWM
MA0080.5_SPI12.89586e-05
PRDM1_HUMAN.H11MO.0.A2.9627199999999996e-05
MA0081.2_SPIB7.79217e-05
SPIB_HUMAN.H11MO.0.A7.79217e-05
SPI1_HUMAN.H11MO.0.A9.382780000000001e-05
BC11A_HUMAN.H11MO.0.A0.000128493Not shown
STAT1_HUMAN.H11MO.1.A0.00016973799999999998Not shown
IRF2_HUMAN.H11MO.0.A0.00019297900000000002Not shown
STAT2_HUMAN.H11MO.0.A0.00021676400000000001Not shown
IRF8_HUMAN.H11MO.0.B0.00021676400000000001Not shown

Motif 6/7

No TOMTOM matches passing threshold

Motif 7/7

No TOMTOM matches passing threshold