-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy path_modisco_results.py
More file actions
1127 lines (980 loc) · 38 KB
/
_modisco_results.py
File metadata and controls
1127 lines (980 loc) · 38 KB
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
from __future__ import annotations
import h5py
import matplotlib.colors as mcolors
import matplotlib.pyplot as plt
import numpy as np
import pandas as pd
import seaborn as sns
from loguru import logger
from matplotlib.colors import LinearSegmentedColormap
from matplotlib.patches import Patch
from scipy.cluster.hierarchy import dendrogram, leaves_list, linkage
from crested.pl._utils import render_plot
from crested.tl.modisco._modisco_utils import (
_pattern_to_ppm,
_trim_pattern_by_ic,
compute_ic,
)
from ._utils import _plot_attribution_map
def modisco_results(
classes: list[str],
contribution: str,
contribution_dir: str,
num_seq: int,
viz: str = "contrib",
min_seqlets: int = 0,
verbose: bool = False,
y_min: float = -0.05,
y_max: float = 0.25,
background: list[float] = None,
trim_pattern: bool = True,
trim_ic_threshold: float = 0.1,
**kwargs,
) -> None:
"""
Plot genomic contributions for the given classes.
Requires the modisco results to be present in the specified directory.
The contribution scores are trimmed based on information content (IC).
Parameters
----------
classes
List of classes to plot genomic contributions for.
contribution
Contribution type to plot. Choose either "positive" or "negative".
contribution_dir
Directory containing the modisco results.
Each class should have a separate modisco .h5 results file in the format {class}_modisco_results.h5.
num_seq
Total number of sequences used for the modisco run.
Necessary to calculate the percentage of sequences with the pattern.
viz
Visualization method. Choose either "contrib" or "pwm".
min_seqlets
Minimum number of seqlets required for a pattern to be considered.
verbose
Print verbose output.
y_min
Minimum y-axis limit for the plot if viz is "contrib".
y_max
Maximum y-axis limit for the plot if viz is "contrib".
background
Background probabilities for each nucleotide. Default is [0.27, 0.23, 0.23, 0.27].
trim_pattern
Boolean for trimming modisco patterns.
trim_ic_threshold
If trimming patterns, indicate threshold.
kwargs
Additional keyword arguments for the plot.
See Also
--------
crested.tl.modisco.tfmodisco
crested.pl.render_plot
Examples
--------
>>> crested.pl.patterns.modisco_results(
... classes=["Lamp5", "Pvalb", "Sst", ""Sst-Chodl", "Vip"],
... contribution="positive",
... contribution_dir="/path/to/modisco_results",
... num_seq=1000,
... viz="pwm",
... save_path="/path/to/genomic_contributions.png",
... )
.. image:: ../../../../docs/_static/img/examples/genomic_contributions.png
"""
if background is None:
background = [0.27, 0.23, 0.23, 0.27]
background = np.array(background)
pos_pat = contribution == "positive"
logger.info(f"Starting genomic contributions plot for classes: {classes}")
max_num_patterns = 0
all_patterns = []
for cell_type in classes:
if verbose:
logger.info(cell_type)
hdf5_results = h5py.File(
f"{contribution_dir}/{cell_type}_modisco_results.h5", "r"
)
metacluster_names = list(hdf5_results.keys())
if f"{contribution[:3]}_patterns" not in metacluster_names:
raise ValueError(
f"No {contribution[:3]}_patterns for {cell_type}. Aborting..."
)
for metacluster_name in [f"{contribution[:3]}_patterns"]:
all_pattern_names = list(hdf5_results[metacluster_name])
max_num_patterns = max(max_num_patterns, len(all_pattern_names))
fig, axes = plt.subplots(
nrows=max_num_patterns,
ncols=len(classes),
figsize=(8 * len(classes), 2 * max_num_patterns),
)
if verbose:
logger.info(f"Max patterns for selected classes: {max_num_patterns}")
motif_counter = 1
for idx, cell_type in enumerate(classes):
hdf5_results = h5py.File(
f"{contribution_dir}/{cell_type}_modisco_results.h5", "r"
)
metacluster_names = list(hdf5_results.keys())
if verbose:
logger.info(metacluster_names)
for metacluster_name in [f"{contribution[:3]}_patterns"]:
all_pattern_names = list(hdf5_results[metacluster_name])
for i in range(len(all_pattern_names)):
pattern_name = "pattern_" + str(i)
if len(classes) > 1:
ax = axes[motif_counter - 1, idx]
elif max_num_patterns > 1:
ax = axes[motif_counter - 1]
else:
ax = axes
motif_counter += 1
all_patterns.append((metacluster_name, pattern_name))
pattern = hdf5_results[metacluster_name][pattern_name]
num_seqlets = list(
hdf5_results[metacluster_name][pattern_name]["seqlets"]["n_seqlets"]
)[0]
if verbose:
logger.info(metacluster_name, pattern_name)
logger.info("total seqlets:", num_seqlets)
if num_seqlets < min_seqlets:
break
pattern_trimmed = (
_trim_pattern_by_ic(pattern, pos_pat, trim_ic_threshold)
if trim_pattern
else pattern
)
if viz == "contrib":
ax = _plot_attribution_map(
ax=ax,
saliency_df=np.array(pattern_trimmed["contrib_scores"]),
return_ax=True,
figsize=None,
)
ax.set_ylim([y_min, y_max])
ax.set_title(
f"{cell_type}: {np.around(num_seqlets / num_seq * 100, 2)}% seqlet frequency"
)
elif viz == "pwm":
ppm = _pattern_to_ppm(pattern_trimmed)
ic, ic_pos, ic_mat = compute_ic(ppm)
pwm = np.array(ic_mat)
rounded_mean = np.around(np.mean(pwm), 2)
pwm = pwm.astype(float)
ax = _plot_attribution_map(
ax=ax, saliency_df=pwm, return_ax=True, figsize=None
)
ax.set_title(
f"{cell_type}: {np.around(num_seqlets / num_seq * 100, 2)}% seqlet frequency - Average IC: {rounded_mean:.2f}"
)
ax.set_ylim([0, 2])
else:
raise ValueError(
'Invalid visualization method. Choose either "contrib" or "pwm". Aborting...'
)
motif_counter = 1
plt.tight_layout()
if "width" not in kwargs:
kwargs["width"] = 6 * len(classes)
if "height" not in kwargs:
kwargs["height"] = 2 * max_num_patterns
return render_plot(fig, **kwargs)
def clustermap_tomtom_similarities(
sim_matrix: np.ndarray,
ids: list[str],
pattern_dict: dict[str, dict],
group_info: list[tuple[list[str], dict[str, str]]] = None,
query_id: str | None = None,
threshold: float | None = None,
min_seqlets: int = 0,
class_names: list[str] | None = None,
figsize: tuple[int, int] = (10, 10),
dendrogram_ratio: tuple[float, float] = (0.05, 0.05),
logo_width_fraction: float = 0.35,
logo_x_padding: float = 0.5,
show_pwms: bool = True,
save_path: str | None = None,
) -> sns.matrix.ClusterGrid:
"""
Create a Seaborn clustermap of TOMTOM similarity scores with optional PWM logo display and filtering.
Parameters
----------
sim_matrix
2D square array of TOMTOM similarity scores (-log10 p-values), shape (N, N).
ids
List of pattern identifiers corresponding to rows/columns of sim_matrix.
pattern_dict
Dictionary mapping pattern IDs to metadata. Each entry should contain:
- 'n_seqlets': number of seqlets contributing to the pattern.
- 'contrib_scores': DataFrame or array used for PWM logo plotting.
group_info
List of (group_labels, color_map) tuples. Each group_labels list has the same length as ids,
and each color_map assigns colors to group values.
query_id
If provided, only show motifs with similarity > `threshold` to this ID.
threshold
Minimum TOMTOM score for similarity filtering (used only with `query_id`).
min_seqlets
Minimum number of seqlets required for a pattern to be shown.
class_names
If provided, only keep patterns whose class name (parsed as '_'.join(id.split('_')[:-3]))
is in this list.
figsize
Base size of the clustermap figure in inches.
dendrogram_ratio : tuple[float, float]
Ratio of dendrogram size to figure size for rows and columns.
logo_width_fraction
Width of the PWM logo strip relative to the heatmap width.
logo_x_padding
Horizontal space between the PWM logos and the heatmap.
show_pwms
Whether to display PWM logos to the left of the heatmap.
save_path
If provided, the figure is saved to this path (e.g., as a PNG or PDF).
Returns
-------
sns.matrix.ClusterGrid
The Seaborn clustermap object containing the heatmap and dendrograms.
"""
if group_info is None:
group_info = []
ids_arr = np.array(ids)
# --- Step 0: Filter by min_seqlets and class_names ---
ids_filtered = []
for i in ids_arr:
ct = '_'.join(i.split('_')[:-3])
if pattern_dict[i]['n_seqlets'] >= min_seqlets and (class_names is None or ct in class_names):
ids_filtered.append(i)
keep_idx = [i for i, x in enumerate(ids_arr) if x in ids_filtered]
sim_matrix = sim_matrix[np.ix_(keep_idx, keep_idx)]
ids_arr = ids_arr[keep_idx]
group_info = [([g[i] for i in keep_idx], colors) for g, colors in group_info]
# --- Step 1: Optional similarity filter ---
if query_id is not None and threshold is not None:
assert query_id in ids_arr, f"{query_id} not in filtered IDs"
idx = np.where(ids_arr == query_id)[0][0]
scores = sim_matrix[idx]
keep_indices = np.where((scores > threshold) & (np.arange(len(scores)) != idx))[0]
keep_indices = np.append(keep_indices, idx)
sim_matrix = sim_matrix[np.ix_(keep_indices, keep_indices)]
ids_arr = ids_arr[keep_indices]
group_info = [([g[i] for i in keep_indices], colors) for g, colors in group_info]
# --- Step 2: Build row_colors matrix ---
row_colors = []
try:
for group_labels, group_colors in group_info:
row_colors.append([group_colors[g] for g in group_labels])
except KeyError as e:
print("!! KeyError in color mapping:", e)
raise
row_colors = np.array(row_colors) # shape (n_groups, n_rows)
# --- Step 3: Clustermap ---
g = sns.clustermap(
sim_matrix,
cmap='viridis',
xticklabels=ids_arr,
yticklabels=ids_arr,
row_colors=row_colors,
col_colors=row_colors,
figsize=figsize,
dendrogram_ratio=dendrogram_ratio,
)
g.ax_heatmap.set_xticklabels(g.ax_heatmap.get_xticklabels(), rotation=90)
# --- Step 4: PWM logos ---
if show_pwms:
row_order = g.dendrogram_row.reordered_ind
reordered_ids = [ids_arr[i] for i in row_order]
fig = g.fig
original_width = figsize[0]
extra_width = logo_width_fraction * original_width
fig.set_size_inches(original_width + extra_width, figsize[1])
heatmap_pos = g.ax_heatmap.get_position()
logo_width = logo_width_fraction * heatmap_pos.width
logo_height = heatmap_pos.height / len(reordered_ids)
for i, motif_id in enumerate(reordered_ids):
y_start = heatmap_pos.y0 + (len(reordered_ids) - 1 - i) * logo_height
x_start = heatmap_pos.x0 - logo_width - logo_width * logo_x_padding
ppm = pattern_dict[motif_id]['contrib_scores']
pwm_ax = fig.add_axes([x_start, y_start, logo_width, logo_height])
_plot_attribution_map(
ax=pwm_ax,
saliency_df=ppm,
return_ax=True,
figsize=(8, 2),
rotate=False,
)
pwm_ax.axis("off")
# --- Step 5: Move colorbar out of the way ---
heatmap_pos = g.ax_heatmap.get_position()
cbar = g.cax
cbar_height = heatmap_pos.height / 4
cbar_width = heatmap_pos.width / 20
cbar_x = heatmap_pos.x1 + 0.02
cbar_y = heatmap_pos.y0 - 0.2
cbar.set_position([cbar_x, cbar_y, cbar_width, cbar_height])
g.cax.set_ylabel("Motif similarity (−log₁₀ p-value)", rotation=270, labelpad=15)
# --- Step 6: Add a legend for the first group ---
if group_info:
group_labels, group_colors = group_info[0]
legend_elements = [
Patch(facecolor=color, edgecolor='black', label=label)
for label, color in group_colors.items()
]
fig = g.fig
fig.legend(
handles=legend_elements,
title="Class",
loc='lower left',
bbox_to_anchor=(-0.06, 0.05),
frameon=True,
framealpha=0.9,
borderpad=0.6,
fontsize=11,
title_fontsize=11
)
if save_path is not None:
plt.savefig(save_path, bbox_inches="tight")
plt.show()
return g
def clustermap(
pattern_matrix: np.ndarray,
classes: list[str],
subset: list[str] | None = None,
figsize: tuple[int, int] = (25, 8),
grid: bool = False,
cmap: str = "coolwarm",
center: float = 0,
method: str = "average",
dy: float = 0.002,
save_path: str | None = None,
pat_seqs: list[tuple[str, np.ndarray]] | None = None,
dendrogram_ratio: tuple[float, float] = (0.05, 0.2),
importance_threshold: float = 0,
) -> sns.matrix.ClusterGrid:
"""
Create a clustermap from the given pattern matrix and class labels with customizable options.
Parameters
----------
pattern_matrix
2D NumPy array containing pattern data.
classes
List of class labels, matching the rows of the pattern matrix.
subset
List of class labels to subset the matrix.
figsize
Size of the figure.
grid
Whether to add a grid to the heatmap.
cmap
Colormap for the clustermap.
center
Value at which to center the colormap.
method
Clustering method to use.
dy
Scaling parameter for vertical distance between nucleotides (if pat_seqs is not None) in xticklabels.
save_path
Path to save the figure.
pat_seqs
List of sequences to use as xticklabels.
dendrogram_ratio
Ratio of dendograms in x and y directions.
importance_threshold
Minimal pattern importance threshold over all classes to retain the pattern before clustering and plotting.
See Also
--------
crested.tl.modisco.create_pattern_matrix
crested.tl.modisco.generate_nucleotide_sequences
Examples
--------
>>> pat_seqs = crested.tl.modisco.generate_nucleotide_sequences(all_patterns)
>>> crested.pl.patterns.clustermap(
... pattern_matrix,
... classes=list(adata.obs_names)
... subset=["Lamp5", "Pvalb", "Sst", "Sst-Chodl", "Vip"],
... figsize=(25, 8),
... grid=True,
... )
.. image:: ../../../../docs/_static/img/examples/pattern_clustermap.png
"""
# Subset the pattern_matrix and classes if subset is provided
if subset is not None:
subset_indices = [
i for i, class_label in enumerate(classes) if class_label in subset
]
pattern_matrix = pattern_matrix[subset_indices, :]
classes = [classes[i] for i in subset_indices]
# Filter columns based on importance threshold
max_importance = np.max(np.abs(pattern_matrix), axis=0)
above_threshold = max_importance > importance_threshold
pattern_matrix = pattern_matrix[:, above_threshold]
if pat_seqs is not None:
pat_seqs = [pat_seqs[i] for i in np.where(above_threshold)[0]]
data = pd.DataFrame(pattern_matrix)
if pat_seqs is not None:
plt.rc("text", usetex=False) # Turn off LaTeX to speed up rendering
g = sns.clustermap(
data,
cmap=cmap,
figsize=figsize,
row_colors=None,
yticklabels=classes,
center=center,
xticklabels=True
if pat_seqs is None
else False, # Disable default xticklabels if pat_seqs provided. #xticklabels=xtick_labels,
method=method,
dendrogram_ratio=dendrogram_ratio,
cbar_pos=(1.05, 0.4, 0.01, 0.3),
)
col_order = g.dendrogram_col.reordered_ind
cbar = g.ax_heatmap.collections[0].colorbar
cbar.set_label(
"Motif importance", rotation=270, labelpad=20
) # Rotate label and add padding
g.ax_heatmap.set_yticklabels(g.ax_heatmap.get_yticklabels(), rotation=0)
# Get the reordered column indices from the clustermap
col_order = g.dendrogram_col.reordered_ind
# Reorder the pat_seqs to follow the column order
if pat_seqs is not None:
reordered_pat_seqs = [pat_seqs[i] for i in col_order]
ax = g.ax_heatmap
x_positions = (
np.arange(len(reordered_pat_seqs)) + 0.5
) # Shift labels by half a tick to the right
constant = (1 / figsize[1]) * 64
for i, (letters, scores) in enumerate(reordered_pat_seqs):
previous_spacing = 0
for _, (letter, score) in enumerate(
zip(reversed(letters), reversed(scores))
):
fontsize = score * 10
vertical_spacing = max(
(constant * score * dy), constant * 0.1 * dy
) # Spacing proportional to figsize[1]
ax.text(
x_positions[i],
-(constant * 0.002)
- previous_spacing, # Adjust y-position based on spacing
letter,
fontsize=fontsize, # Constant font size
ha="center", # Horizontal alignment
va="top", # Vertical alignment
rotation=90, # Rotate the labels vertically
transform=ax.get_xaxis_transform(), # Ensure the text is placed relative to x-axis
)
previous_spacing += vertical_spacing
# Ensure x-ticks are visible
ax.set_xticks(x_positions)
if grid:
ax = g.ax_heatmap
# Define the grid positions (between cells, hence the +0.5 offset)
x_positions = np.arange(pattern_matrix.shape[1] + 1)
y_positions = np.arange(len(pattern_matrix) + 1)
# Add horizontal grid lines
for y in y_positions:
ax.hlines(y, *ax.get_xlim(), color="grey", linewidth=0.25)
# Add vertical grid lines
for x in x_positions:
ax.vlines(x, *ax.get_ylim(), color="grey", linewidth=0.25)
g.fig.canvas.draw()
if save_path is not None:
plt.savefig(save_path, bbox_inches="tight")
plt.show()
def clustermap_with_pwm_logos(
pattern_matrix: np.ndarray,
classes: list[str],
pattern_dict: dict,
subset: list[str] | None = None,
figsize: tuple[int, int] = (25, 8),
grid: bool = False,
cmap: str = "coolwarm",
center: float = 0,
method: str = "average",
save_path: str | None = None,
dendrogram_ratio: tuple[float, float] = (0.05, 0.2),
importance_threshold: float = 0,
logo_height_fraction: float = 0.35,
logo_y_padding: float = 0.3,
pwm_or_contrib: str = "pwm",
) -> sns.matrix.ClusterGrid:
"""
Create a clustermap with additional PWM logo plots below the heatmap.
Parameters
----------
pattern_matrix:
A 2D array representing the data matrix for clustering.
classes:
The class labels for the rows of the matrix.
pattern_dict:
A dictionary containing PWM patterns for x-tick plots.
subset
List of class labels to subset the matrix.
figsize:
Size of the clustermap figure (width, height). Default is (25, 8).
grid:
Whether to overlay grid lines on the heatmap. Default is False.
cmap:
Colormap for the heatmap. Default is "coolwarm".
center:
The value at which to center the colormap. Default is 0.
method:
Linkage method for hierarchical clustering. Default is "average".
save_path:
Path to save the final figure. If None, the figure is not saved. Default is None.
dendrogram_ratio:
Ratios for the size of row and column dendrograms. Default is (0.05, 0.2).
importance_threshold:
Threshold for filtering columns based on maximum absolute importance. Default is 0.
logo_height_fraction:
Fraction of clustermap height to allocate for PWM logos. Default is 0.35.
logo_y_padding:
Vertical padding for the PWM logos relative to the heatmap. Default is 0.3.
pwm_or_contrib:
Whether to use the pwm or contrib score representation of the pattern in the plotting.
Returns
-------
sns.matrix.ClusterGrid: A seaborn ClusterGrid object containing the clustermap with the PWM logos.
"""
# Subset the pattern_matrix and classes if subset is provided
if subset is not None:
subset_indices = [
i for i, class_label in enumerate(classes) if class_label in subset
]
pattern_matrix = pattern_matrix[subset_indices, :]
classes = [classes[i] for i in subset_indices]
# Filter columns based on importance threshold
max_importance = np.max(np.abs(pattern_matrix), axis=0)
above_threshold = max_importance > importance_threshold
pattern_matrix = pattern_matrix[:, above_threshold]
# Subset the pattern_dict to match filtered columns
selected_patterns = [pattern_dict[str(i)] for i in np.where(above_threshold)[0]]
selected_indices = list(np.where(above_threshold)[0])
data = pd.DataFrame(pattern_matrix)
# Generate the clustermap with the specified figsize
g = sns.clustermap(
data,
cmap=cmap,
figsize=figsize,
row_colors=None,
yticklabels=classes,
center=center,
xticklabels=False,
method=method,
dendrogram_ratio=dendrogram_ratio,
cbar_pos=(1.05, 0.4, 0.01, 0.3),
)
col_order = g.dendrogram_col.reordered_ind
cbar = g.ax_heatmap.collections[0].colorbar
cbar.set_label("Motif importance", rotation=270, labelpad=20)
# Reorder selected_patterns based on clustering
reordered_patterns = [selected_patterns[i] for i in col_order]
reordered_indices = [selected_indices[i] for i in col_order]
# Compute space for x-tick images
original_height = figsize[1]
extra_height = logo_height_fraction * original_height
total_height = original_height + extra_height
# Update the figure size to accommodate the logos
fig = g.fig
fig.set_size_inches(figsize[0], total_height)
# Adjust width and height of logos
logo_width = g.ax_heatmap.get_position().width / len(reordered_patterns) * 2.5
logo_height = logo_height_fraction * g.ax_heatmap.get_position().height
ratio = logo_height / logo_width
for i, pattern in enumerate(reordered_patterns):
plot_start_x = (
g.ax_heatmap.get_position().x0
+ ((i - 0.75) / len(reordered_patterns)) * g.ax_heatmap.get_position().width
)
plot_start_y = (
g.ax_heatmap.get_position().y0 - logo_height - logo_height * logo_y_padding
)
pwm_ax = fig.add_axes([plot_start_x, plot_start_y, logo_width, logo_height])
pwm_ax.clear()
pwm = None
if pwm_or_contrib == "pwm":
ppm = _pattern_to_ppm(pattern["pattern"])
ic, ic_pos, ic_mat = compute_ic(ppm)
pwm = np.array(ic_mat)
elif pwm_or_contrib == "contrib":
pwm = np.array(pattern["pattern"]["contrib_scores"])
else:
raise ValueError(
'Invalid visualization method. Choose either "contrib" or "pwm" in the pwm_or_contrib parameter. Aborting...'
)
pwm_ax = _plot_attribution_map(
ax=pwm_ax,
saliency_df=pwm,
return_ax=True,
figsize=(8 * ratio, 8),
rotate=True,
)
pwm_ax.axis("off")
if grid:
ax = g.ax_heatmap
x_positions = np.arange(pattern_matrix.shape[1] + 1)
y_positions = np.arange(len(pattern_matrix) + 1)
# Add horizontal grid lines
for y in y_positions:
ax.hlines(y, *ax.get_xlim(), color="grey", linewidth=0.25)
# Add vertical grid lines
for x in x_positions:
ax.vlines(x, *ax.get_ylim(), color="grey", linewidth=0.25)
g.fig.canvas.draw()
ax = g.ax_heatmap
ax.xaxis.tick_bottom()
ax.set_xticks(np.arange(pattern_matrix.shape[1]) + 0.5)
ax.set_xticklabels([str(i) for i in reordered_indices], rotation=90)
for tick in ax.get_xticklabels():
tick.set_verticalalignment("top")
if save_path is not None:
plt.savefig(save_path, bbox_inches="tight", dpi=600)
plt.show()
return g
def selected_instances(
pattern_dict: dict,
idcs: list[int],
save_path: str = None,
) -> None:
"""
Plot the patterns specified by the indices in `idcs` from the `pattern_dict`.
Parameters
----------
pattern_dict
A dictionary containing pattern data. Each key corresponds to a pattern ID, and the value is a nested structure containing
contribution scores and metadata for the pattern. Refer to the output of `crested.tl.modisco.process_patterns`.
idcs
A list of indices specifying which patterns to plot. The indices correspond to keys in the `pattern_dict`.
save_path
File to save plot to.
See Also
--------
crested.tl.modisco.process_patterns
Examples
--------
>>> pattern_indices = [0, 1, 2]
>>> crested.pl.patterns.selected_instances(pattern_dict, pattern_indices)
.. image:: ../../../../docs/_static/img/examples/pattern_selected_instances.png
"""
figure, axes = plt.subplots(nrows=len(idcs), ncols=1, figsize=(8, 2 * len(idcs)))
if len(idcs) == 1:
axes = [axes]
for i, idx in enumerate(idcs):
ax = _plot_attribution_map(
ax=axes[i],
saliency_df=np.array(pattern_dict[str(idx)]["pattern"]["contrib_scores"]),
return_ax=True,
figsize=None,
)
ax.set_title(pattern_dict[str(idx)]["pattern"]["id"])
plt.tight_layout()
if save_path:
plt.savefig(save_path, bbox_inches='tight')
plt.show()
def class_instances(
pattern_dict: dict, idx: int, class_representative: bool = False, save_path: str = None,
) -> None:
"""
Plot instances of a specific pattern, either the representative pattern per class or all instances for a given pattern index.
Parameters
----------
pattern_dict
A dictionary containing pattern data. Each key corresponds to a pattern ID, and each value contains instances of the pattern
across different classes, along with their contribution scores. Refer to the output of `crested.tl.modisco.process_patterns`.
idx
The index specifying which pattern's instances to plot. This corresponds to a key in the `pattern_dict`.
class_representative
If True, only the best representative instance of each class is plotted. If False (default), all instances of the pattern
within each class are plotted.
save_path
File to save plot to.
See Also
--------
crested.tl.modisco.process_patterns
Examples
--------
>>> crested.pl.patterns.class_instances(pattern_dict, 0, class_representative=False)
.. image:: ../../../../docs/_static/img/examples/pattern_class_instances.png
"""
if class_representative:
key = "classes"
else:
key = "instances"
n_instances = len(pattern_dict[str(idx)][key])
figure, axes = plt.subplots(
nrows=n_instances, ncols=1, figsize=(8, 2 * n_instances)
)
if n_instances == 1:
axes = [axes]
instance_classes = list(pattern_dict[str(idx)][key].keys())
for i, cl in enumerate(instance_classes):
ax = _plot_attribution_map(
ax=axes[i],
saliency_df=np.array(pattern_dict[str(idx)][key][cl]["contrib_scores"]),
return_ax=True,
figsize=None,
)
ax.set_title(pattern_dict[str(idx)][key][cl]["id"])
plt.tight_layout()
if save_path:
plt.savefig(save_path, bbox_inches='tight')
plt.show()
def similarity_heatmap(
similarity_matrix: np.ndarray,
indices: list,
fig_size: tuple[int, int] = (30, 15),
fig_path: str | None = None,
) -> None:
"""
Plot a similarity heatmap of all pattern indices.
Parameters
----------
similarity_matrix
A 2D numpy array containing the similarity values.
indices
List of pattern indices.
fig_size
Size of the figure for the heatmap.
fig_path
Path to save the figure. If None, the figure will be shown but not saved.
See Also
--------
crested.tl.modisco.calculate_similarity_matrix
Examples
--------
>>> sim_matrix, indices = crested.tl.modisco.calculate_similarity_matrix(
... all_patterns
... )
>>> crested.pl.patterns.similarity_heatmap(sim_matrix, indices, fig_size=(42, 17))
.. image:: ../../../../docs/_static/img/examples/pattern_similarity_heatmap.png
"""
fig, ax = plt.subplots(figsize=fig_size)
heatmap = sns.heatmap(
similarity_matrix,
ax=ax,
cmap="coolwarm",
annot=True,
fmt=".2f",
xticklabels=indices,
yticklabels=indices,
annot_kws={"size": 8},
)
for _, spine in heatmap.spines.items():
spine.set_visible(True)
spine.set_color("grey")
spine.set_linewidth(0.5)
plt.title("Pattern Similarity Heatmap", fontsize=20)
plt.xlabel("Pattern Index", fontsize=15)
plt.ylabel("Pattern Index", fontsize=15)
if fig_path is not None:
plt.savefig(fig_path)
plt.show()
def tf_expression_per_cell_type(
df: pd.DataFrame,
tf_list: list,
log_transform: bool = False,
title: str = "TF Expression per Cell Type",
) -> None:
"""
Plot the expression levels of specified transcription factors (TFs) per cell type.
Parameters
----------
df
The DataFrame containing mean gene expression data per cell type.
tf_list
A list of transcription factors (TFs) to plot.
log_transform
Whether to log-transform the TF expression values.
title
The title of the plot.
"""
# Check if all specified TFs are in the DataFrame
missing_tfs = [tf for tf in tf_list if tf not in df.columns]
if missing_tfs:
raise ValueError(
f"The following TFs are not found in the DataFrame: {missing_tfs}"
)
# Subset the DataFrame to include only the specified TFs
tf_expression_df = df[tf_list]
# Apply log transformation if specified
if log_transform:
tf_expression_df = np.log(tf_expression_df + 1)
# Plot the TF expression per cell type
ax = tf_expression_df.plot(kind="bar", figsize=(12, 5), width=0.8)
ax.set_title(title)
ax.set_xlabel("Cell Type")
ax.set_ylabel("Log Mean TF Expression" if log_transform else "Mean TF Expression")
ax.legend(title="Transcription Factors")
plt.xticks(rotation=45, ha="right")
plt.tight_layout()
plt.show()
def clustermap_tf_motif(
data: np.ndarray,
heatmap_dim: str = "gex",
dot_dim: str = "contrib",
class_labels: list[str] | None = None,
subset_classes: list[str] | None = None,
pattern_labels: list[str] | None = None,
fig_size: tuple[int, int] | None = None,
save_path: str | None = None,
cluster_rows: bool = True,
cluster_columns: bool = True,
cbar_pad: float = 0.05,
) -> None:
"""
Generate a heatmap where one modality is represented as color, and the other as dot size.
Parameters
----------
data : numpy.ndarray
3D numpy array with shape (len(classes), #patterns, 2).
heatmap_dim : str
Either 'gex' or 'contrib', indicating which third dimension to use for heatmap colors.
dot_dim : str
Either 'gex' or 'contrib', indicating which third dimension to use for dot sizes.
class_labels : list[str] | None
Labels for the classes.
subset_classes : list[str] | None
Subset of classes to include in the heatmap. Rows in `data` are filtered accordingly.
pattern_labels : list[str] | None
Labels for the patterns.
fig_size : tuple[int, int] | None
Size of figure. If None, it will be auto-configured.
save_path : str | None
File path to save figure to.
cluster_rows : bool
Whether to cluster the rows (classes). Default is True.
cluster_columns : bool
Whether to cluster the columns (patterns). Default is True.
cbar_pad : float
Horizontal padding between heatmap and colorbar in figure coordinates.
Examples
--------
>>> clustermap_tf_motif_v2(
... data,
... heatmap_dim="gex",
... dot_dim="contrib",
... class_labels=classes,
... pattern_labels=patterns,
... cluster_rows=True,
... cluster_columns=True,
... )
"""
assert data.shape[2] == 2, "The third dimension of the data must be 2."
# Set default labels if not provided
if class_labels is None:
class_labels = [f"Class {i}" for i in range(data.shape[0])]
if pattern_labels is None:
pattern_labels = [f"Pattern {i}" for i in range(data.shape[1])]
# Subset classes if specified
if subset_classes is not None:
subset_indices = [
i for i, label in enumerate(class_labels) if label in subset_classes
]
if not subset_indices: