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: REST
DeepSHAP scores path: /users/amtseng/tfmodisco/results/importance_scores/multitask_profile/REST_multitask_profile_fold5/REST_multitask_profile_fold5_imp_scores.h5
TF-MoDISco results path: /users/amtseng/tfmodisco/results/tfmodisco/multitask_profile/REST_multitask_profile_fold5/REST_multitask_profile_fold5_count_tfm.h5
Importance score key: count_hyp_scores
Saved TF-MoDISco-derived motifs cache: /users/amtseng/tfmodisco/results/reports/tfmodisco_results//cache/multitask_profile/REST_multitask_profile_fold5/REST_multitask_profile_fold5_count
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%|██████████| 287/287 [04:50<00:00,  1.01s/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/14

7527 seqlets

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

Pattern 2/14

3527 seqlets

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

Pattern 3/14

746 seqlets

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

Pattern 4/14

610 seqlets

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

Pattern 5/14

401 seqlets

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

Pattern 6/14

333 seqlets

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

Pattern 7/14

302 seqlets

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

Pattern 8/14

217 seqlets

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

Pattern 9/14

202 seqlets

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

Pattern 10/14

196 seqlets

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

Pattern 11/14

103 seqlets

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

Pattern 12/14

50 seqlets

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

Pattern 13/14

50 seqlets

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

Pattern 14/14

42 seqlets

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

Metacluster 2/2

Pattern 1/12

123 seqlets

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

Pattern 2/12

101 seqlets

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

Pattern 3/12

99 seqlets

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

Pattern 4/12

83 seqlets

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

Pattern 5/12

74 seqlets

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

Pattern 6/12

61 seqlets

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

Pattern 7/12

59 seqlets

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

Pattern 8/12

49 seqlets

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

Pattern 9/12

47 seqlets

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

Pattern 10/12

43 seqlets

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

Pattern 11/12

35 seqlets

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

Pattern 12/12

30 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

/users/amtseng/tfmodisco/src/plot/viz_sequence.py:152: RuntimeWarning: More than 20 figures have been opened. Figures created through the pyplot interface (`matplotlib.pyplot.figure`) are retained until explicitly closed and may consume too much memory. (To control this warning, see the rcParam `figure.max_open_warning`).
  fig = plt.figure(figsize=figsize)
#SeqletsForwardReverse
17527
23527
3746
4610
5401
6333
7302
8217
9202
10196
11103
1250
1350
1442

Metacluster 2/2

#SeqletsForwardReverse
1123
2101
399
483
574
661
759
849
947
1043
1135
1230

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

Motif IDq-valPWM
MA0138.2_REST4.91729e-19
REST_HUMAN.H11MO.0.A8.15999e-15

Motif 2/14

Motif IDq-valPWM
MA0138.2_REST0.05232869999999999
REST_HUMAN.H11MO.0.A0.05232869999999999

Motif 3/14

Motif IDq-valPWM
CTCFL_HUMAN.H11MO.0.A1.9877200000000002e-10
MA0139.1_CTCF6.61583e-10
CTCF_HUMAN.H11MO.0.A6.61583e-10
MA1102.2_CTCFL9.601290000000001e-05
MA1568.1_TCF21(var.2)0.21750799999999998
MA1638.1_HAND20.28835500000000003Not shown
SNAI1_HUMAN.H11MO.0.C0.342736Not shown

Motif 4/14

Motif IDq-valPWM
MA0138.2_REST0.189672
REST_HUMAN.H11MO.0.A0.189672

Motif 5/14

Motif IDq-valPWM
REST_HUMAN.H11MO.0.A0.0915238
MA0138.2_REST0.228921

Motif 6/14

Motif IDq-valPWM
REST_HUMAN.H11MO.0.A0.000999753
MA0138.2_REST0.000999753

Motif 7/14

No TOMTOM matches passing threshold

Motif 8/14

Motif IDq-valPWM
MA1102.2_CTCFL1.98326e-05
CTCFL_HUMAN.H11MO.0.A2.3115700000000003e-05
CTCF_HUMAN.H11MO.0.A0.00020047200000000001
MA0139.1_CTCF0.000961791
SP2_HUMAN.H11MO.0.A0.00187518
SP3_HUMAN.H11MO.0.B0.020635499999999998Not shown
SP4_HUMAN.H11MO.0.A0.030369999999999998Not shown
MA0830.2_TCF40.0711043Not shown
ZFX_HUMAN.H11MO.0.A0.0711043Not shown
MA1648.1_TCF12(var.2)0.0722591Not shown

Motif 9/14

No TOMTOM matches passing threshold

Motif 10/14

Motif IDq-valPWM
MA0138.2_REST0.357047
REST_HUMAN.H11MO.0.A0.439213

Motif 11/14

Motif IDq-valPWM
TBX20_HUMAN.H11MO.0.D0.311367
MAFA_HUMAN.H11MO.0.D0.311367
MA0138.2_REST0.311367
MYOD1_HUMAN.H11MO.0.A0.40315700000000004
REST_HUMAN.H11MO.0.A0.40315700000000004

Motif 12/14

Motif IDq-valPWM
ZN549_HUMAN.H11MO.0.C0.264219
MA0138.2_REST0.423857

Motif 13/14

Motif IDq-valPWM
KAISO_HUMAN.H11MO.1.A0.00510202
MA0527.1_ZBTB330.00510202
KAISO_HUMAN.H11MO.0.A0.00510202
SP1_HUMAN.H11MO.1.A0.0397595
SP2_HUMAN.H11MO.0.A0.06489840000000001
MA0163.1_PLAG10.0949189Not shown
SP1_HUMAN.H11MO.0.A0.120227Not shown
SP3_HUMAN.H11MO.0.B0.19906400000000002Not shown
MA1513.1_KLF150.271044Not shown
ZBED1_HUMAN.H11MO.0.D0.271044Not shown

Motif 14/14

Motif IDq-valPWM
ATF6A_HUMAN.H11MO.0.B0.183195
FEZF1_HUMAN.H11MO.0.C0.407117
ZN549_HUMAN.H11MO.0.C0.407117

Metacluster 2/2

Motif 1/12

No TOMTOM matches passing threshold

Motif 2/12

No TOMTOM matches passing threshold

Motif 3/12

No TOMTOM matches passing threshold

Motif 4/12

No TOMTOM matches passing threshold

Motif 5/12

No TOMTOM matches passing threshold

Motif 6/12

No TOMTOM matches passing threshold

Motif 7/12

Motif IDq-valPWM
SP1_HUMAN.H11MO.0.A0.054585
SP2_HUMAN.H11MO.0.A0.054585
SP3_HUMAN.H11MO.0.B0.054585
MA0146.2_Zfx0.0645759
MA1630.1_Znf2810.06852749999999999
ZFX_HUMAN.H11MO.1.A0.0985537Not shown
MA0779.1_PAX10.101475Not shown
MA0781.1_PAX90.101475Not shown
ZN335_HUMAN.H11MO.0.A0.10798900000000002Not shown
ZFX_HUMAN.H11MO.0.A0.10798900000000002Not shown

Motif 8/12

Motif IDq-valPWM
SP2_HUMAN.H11MO.0.A0.00492306
SP3_HUMAN.H11MO.0.B0.0258524
KLF3_HUMAN.H11MO.0.B0.0258524
SP1_HUMAN.H11MO.0.A0.0258524
THAP1_HUMAN.H11MO.0.C0.0258524
EGR4_HUMAN.H11MO.0.D0.0325433Not shown
MA0872.1_TFAP2A(var.3)0.0475047Not shown
KLF16_HUMAN.H11MO.0.D0.0475047Not shown
RFX1_HUMAN.H11MO.0.B0.0475047Not shown
MA0815.1_TFAP2C(var.3)0.0475047Not shown

Motif 9/12

Motif IDq-valPWM
SP2_HUMAN.H11MO.0.A0.03281269999999999
SP1_HUMAN.H11MO.0.A0.03281269999999999
SP3_HUMAN.H11MO.0.B0.0458125
TAL1_HUMAN.H11MO.0.A0.0458125
MLXPL_HUMAN.H11MO.0.D0.0744884
MA0753.2_ZNF7400.0928667Not shown
MA1102.2_CTCFL0.134818Not shown
ZFX_HUMAN.H11MO.1.A0.134818Not shown
AP2D_HUMAN.H11MO.0.D0.134818Not shown
CTCF_HUMAN.H11MO.0.A0.134818Not shown

Motif 10/12

Motif IDq-valPWM
SP2_HUMAN.H11MO.0.A0.00021703
SP1_HUMAN.H11MO.0.A0.00155883
SP3_HUMAN.H11MO.0.B0.00831969
USF2_HUMAN.H11MO.0.A0.0105791
RFX1_HUMAN.H11MO.0.B0.0105791
MA0104.4_MYCN0.0105791Not shown
MA0147.3_MYC0.043055199999999995Not shown
PATZ1_HUMAN.H11MO.0.C0.043055199999999995Not shown
EGR4_HUMAN.H11MO.0.D0.043055199999999995Not shown
THAP1_HUMAN.H11MO.0.C0.043055199999999995Not shown

Motif 11/12

Motif IDq-valPWM
THAP1_HUMAN.H11MO.0.C0.340985

Motif 12/12

Motif IDq-valPWM
CTCFL_HUMAN.H11MO.0.A0.0318043
REST_HUMAN.H11MO.0.A0.049133300000000005
MA0139.1_CTCF0.06426040000000001
CTCF_HUMAN.H11MO.0.A0.06426040000000001
MA0138.2_REST0.0755135
MA1587.1_ZNF1350.492317Not shown