-
Notifications
You must be signed in to change notification settings - Fork 9
Expand file tree
/
Copy path_tfmodisco.py
More file actions
1637 lines (1373 loc) · 55.5 KB
/
_tfmodisco.py
File metadata and controls
1637 lines (1373 loc) · 55.5 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 os
import re
import anndata
import h5py
import modiscolite as modisco
import numpy as np
import pandas as pd
import scanpy as sc
from loguru import logger
from crested.utils._logging import log_and_raise
from ._modisco_utils import (
_pattern_to_ppm,
_trim_pattern_by_ic,
compute_ic,
match_score_patterns,
read_html_to_dataframe,
write_to_meme,
)
def _calculate_window_offsets(center: int, window_size: int) -> tuple:
return (center - window_size // 2, center + window_size // 2)
@log_and_raise(Exception)
def tfmodisco(
contrib_dir: os.PathLike = "modisco_results",
class_names: list[str] | None = None,
output_dir: os.PathLike = "modisco_results",
max_seqlets: int = 5000,
min_metacluster_size: int = 100,
min_final_cluster_size: int = 20,
window: int = 500,
n_leiden: int = 2,
report: bool = False,
meme_db: str = None,
verbose: bool = True,
fdr: float = 0.05,
sliding_window_size: int = 20,
flank_size: int = 5,
top_n_regions: int | None = None,
):
"""
Run tf-modisco on one-hot encoded sequences and contribution scores stored in .npz files.
Parameters
----------
contrib_dir
Directory containing the contribution score and one hot encoded regions npz files.
class_names
list of class names to process. If None, all class names found in the output directory will be processed.
output_dir
Directory where output files will be saved.
max_seqlets
Maximum number of seqlets per metacluster.
min_metacluster_size
Minimum number of seqlets per metacluster.
min_final_cluster_size
Minimum size of final cluster.
window
The window surrounding the peak center that will be considered for motif discovery.
n_leiden
Number of Leiden clusterings to perform with different random seeds.
report
Generate a modisco report.
meme_db
Path to a MEME file (.meme) containing motifs. Required if report is True.
verbose
Print verbose output.
fdr
False discovery rate of seqlet finding.
sliding_window_size
Sliding window size for seqlet finding in tfmodiscolite.
flank_size
Flank size of seqlets.
top_n_regions
The top n regions from the one hot encoded sequences and contribution scores to run modisco on.
See Also
--------
crested.tl.Crested.calculate_contribution_scores
Examples
--------
>>> evaluator = crested.tl.Crested(...)
>>> evaluator.load_model(/path/to/trained/model.keras)
>>> evaluator.tfmodisco_calculate_and_save_contribution_scores(
... adata, class_names=["Astro", "Vip"], method="expected_integrated_grad"
... )
>>> crested.tl.modisco.tfmodisco(
... contrib_dir="modisco_results",
... class_names=["Astro", "Vip"],
... output_dir="modisco_results",
... window=1000,
... )
"""
"""Code adapted from https://github.com/jmschrei/tfmodisco-lite/blob/main/modisco."""
if not os.path.exists(output_dir):
os.makedirs(output_dir)
# Check if .npz exist in the contribution directory
if not os.path.exists(contrib_dir):
raise FileNotFoundError(f"Contribution directory not found: {contrib_dir}")
files = os.listdir(contrib_dir)
if not any(f.endswith(".npz") for f in files):
raise FileNotFoundError("No .npz files found in the contribution directory")
# Use all class names found in the contribution directory if class_names is not provided
if class_names is None:
class_names = [
re.match(r"(.+?)_oh\.npz$", f).group(1)
for f in os.listdir(contrib_dir)
if f.endswith("_oh.npz")
]
class_names = list(set(class_names))
logger.info(
f"No class names provided, using all found in the contribution directory: {class_names}"
)
# Iterate over each class and calculate contribution scores
for class_name in class_names:
try:
# Load the one-hot sequences and contribution scores from the .npz files
one_hot_path = os.path.join(contrib_dir, f"{class_name}_oh.npz")
contrib_path = os.path.join(contrib_dir, f"{class_name}_contrib.npz")
if not (os.path.exists(one_hot_path) and os.path.exists(contrib_path)):
raise FileNotFoundError(f"Missing .npz files for class: {class_name}")
one_hot_seqs = np.load(one_hot_path)["arr_0"]
contribution_scores = np.load(contrib_path)["arr_0"]
if one_hot_seqs.shape[2] < window:
print(one_hot_seqs.shape[2])
raise ValueError(
f"Window ({window}) cannot be longer than the sequences ({one_hot_seqs.shape[1]})"
)
center = one_hot_seqs.shape[2] // 2
start, end = _calculate_window_offsets(center, window)
sequences = one_hot_seqs[:, :, start:end]
attributions = contribution_scores[:, :, start:end]
if top_n_regions:
top_n = (
top_n_regions if top_n_regions < len(sequences) else len(sequences)
)
top_n = max(top_n, 1) # avoid faulty inputs
sequences = sequences[:top_n]
attributions = attributions[:top_n]
sequences = sequences.transpose(0, 2, 1)
attributions = attributions.transpose(0, 2, 1)
sequences = sequences.astype("float32")
attributions = attributions.astype("float32")
# Define filenames for the output files
output_file = os.path.join(output_dir, f"{class_name}_modisco_results.h5")
report_dir = os.path.join(output_dir, f"{class_name}_report")
# Check if the modisco results .h5 file does not exist for the class
if not os.path.exists(output_file):
logger.info(f"Running modisco for class: {class_name}")
pos_patterns, neg_patterns = modisco.tfmodisco.TFMoDISco(
hypothetical_contribs=attributions,
one_hot=sequences,
max_seqlets_per_metacluster=max_seqlets,
sliding_window_size=sliding_window_size,
flank_size=flank_size,
target_seqlet_fdr=fdr,
n_leiden_runs=n_leiden,
verbose=verbose,
min_metacluster_size=min_metacluster_size,
final_min_cluster_size=min_final_cluster_size,
)
modisco.io.save_hdf5(
output_file, pos_patterns, neg_patterns, window_size=window
)
else:
print(f"Modisco results already exist for class: {class_name}")
# Generate the modisco report
if report and not os.path.exists(report_dir):
modisco.report.report_motifs(
output_file,
report_dir,
meme_motif_db=meme_db,
top_n_matches=3,
is_writing_tomtom_matrix=False,
img_path_suffix="./",
)
except KeyError as e:
logger.error(f"Missing data for class: {class_name}, error: {e}")
def get_pwms_from_modisco_file(
modisco_file: str,
min_ic: float = 0.1,
output_meme_file: str | None = None,
metacluster_name: str | None = None,
pattern_indices: list[int] | None = None,
):
"""
Extract PPMs (Position Probability Matrices) from a Modisco HDF5 results file.
Optionally, save the extracted PPMs in MEME format.
Parameters
----------
modisco_file : str
Path to the Modisco HDF5 results file.
min_ic : float
Threshold to trim pattern. The higher, the more it gets trimmed.
output_meme_file : str | None
Path to save the extracted PPMs in MEME format. If None, PPMs are not saved.
metacluster_name : str | None
The name of the metacluster to process (e.g., 'pos_patterns' or 'neg_patterns').
If None, all metaclusters are processed.
pattern_indices : list[int] | None
List of pattern indices to include from the selected metacluster.
If None, all patterns are processed.
Returns
-------
dict[str, np.ndarray]
A dictionary where keys are pattern IDs (e.g., "pos_patterns_pattern_0")
and values are numpy arrays of PPMs.
"""
ppms = {}
# Issue a warning if pattern_indices are provided without a metacluster_name
if pattern_indices and not metacluster_name:
logger.info(
"Pattern indices are specified, but no metacluster name is provided. "
"Pattern indices will be ignored."
)
pattern_indices = None
# Open the HDF5 file
with h5py.File(modisco_file, "r") as hdf5_results:
# Select specific metacluster or iterate through all metaclusters
metaclusters_to_process = (
[metacluster_name] if metacluster_name else hdf5_results.keys()
)
for metacluster in metaclusters_to_process:
if metacluster not in hdf5_results:
raise ValueError(
f"Metacluster '{metacluster}' not found in the HDF5 file."
)
pos_pat = metacluster == "pos_patterns"
metacluster_data = hdf5_results[metacluster]
# Select specific patterns or iterate through all patterns
patterns_to_process = (
pattern_indices if pattern_indices else range(len(metacluster_data))
)
for i in patterns_to_process:
pattern_name = f"pattern_{i}"
if pattern_name not in metacluster_data:
raise ValueError(
f"Pattern '{pattern_name}' not found in metacluster '{metacluster}'."
)
pattern = metacluster_data[pattern_name]
pattern_trimmed = _trim_pattern_by_ic(pattern, pos_pat, min_ic)
# Extract the PPM as a numpy array
ppm = np.array(pattern_trimmed["sequence"])
# Save the PPM with a unique key
ppms[f"{metacluster}_{pattern_name}"] = ppm
# Optionally write PPMs to a MEME file
if output_meme_file:
write_to_meme(ppms, output_meme_file)
return ppms
def add_pattern_to_dict(
p: dict[str, np.ndarray],
idx: int,
cell_type: str,
pos_pattern: bool,
all_patterns: dict,
) -> dict:
"""
Add a pattern to the dictionary.
Parameters
----------
p
Pattern to add.
idx
Index for the new pattern.
cell_type
Cell type of the pattern.
pos_pattern
Indicates if the pattern is a positive pattern.
all_patterns
dictionary containing all patterns.
Returns
-------
Updated dictionary with the new pattern.
"""
ppm = _pattern_to_ppm(p)
ic, ic_pos, ic_mat = compute_ic(ppm)
p["ppm"] = ppm
p["ic"] = np.mean(ic_pos)
all_patterns[str(idx)] = {}
all_patterns[str(idx)]["pattern"] = p
all_patterns[str(idx)]["pos_pattern"] = pos_pattern
all_patterns[str(idx)]["ppm"] = ppm
all_patterns[str(idx)]["ic"] = np.mean(
ic_pos
) # np.mean(_get_ic(p["contrib_scores"], pos_pattern))
all_patterns[str(idx)]["instances"] = {}
all_patterns[str(idx)]["instances"][p["id"]] = p
all_patterns[str(idx)]["classes"] = {}
all_patterns[str(idx)]["classes"][cell_type] = p
return all_patterns
def match_to_patterns(
p: dict,
idx: int,
cell_type: str,
pattern_id: str,
pos_pattern: bool,
all_patterns: dict[str, dict[str, str | list[float]]],
sim_threshold: float = 7.0,
ic_threshold: float = 0.15,
verbose: bool = False,
) -> dict:
"""
Match the pattern to existing patterns and updates the dictionary.
Parameters
----------
p
Pattern to match.
idx
Index of the pattern.
cell_type
Cell type of the pattern.
pattern_id
ID of the pattern.
pos_pattern
Indicates if the pattern is a positive pattern.
all_patterns
dictionary containing all patterns.
sim_threshold
Similarity threshold for matching patterns.
ic_threshold
Information content threshold for matching patterns.
verbose
Flag to enable verbose output.
Returns
-------
Updated dictionary with matched patterns.
"""
p["id"] = pattern_id
p["pos_pattern"] = pos_pattern
p["n_seqlets"] = p["seqlets"]["n_seqlets"][0]
if not all_patterns:
return add_pattern_to_dict(p, 0, cell_type, pos_pattern, all_patterns)
match = False
match_idx = None
max_sim = 0
ppm = _pattern_to_ppm(p)
ic, ic_pos, ic_mat = compute_ic(ppm)
p_ic = np.mean(ic_pos)
p["ic"] = p_ic
p["ppm"] = ppm
p["class"] = cell_type
all_patterns_list = [pat['pattern'] for pat in all_patterns.values()]
sim_matrix1 = match_score_patterns(p, all_patterns_list)
sim_matrix2 = match_score_patterns(all_patterns_list, p).T # for some reason changing the order can give different results
sim_matrix = np.maximum(sim_matrix1, sim_matrix2)
max_sim = np.max(sim_matrix)
if max_sim > sim_threshold:
match = True
match_idx = np.argmax(sim_matrix[0])
if not match:
pattern_idx = len(all_patterns.keys())
return add_pattern_to_dict(p, pattern_idx, cell_type, pos_pattern, all_patterns)
if verbose:
print(
f'Match between {pattern_id} and {all_patterns[str(match_idx)]["pattern"]["id"]} with similarity score {max_sim:.2f}'
)
all_patterns[str(match_idx)]["instances"][pattern_id] = p
if cell_type in all_patterns[str(match_idx)]["classes"].keys():
ic_class_representative = all_patterns[str(match_idx)]["classes"][cell_type][
"ic"
]
n_seqlets_class_representative = all_patterns[str(match_idx)]["classes"][
cell_type
]["n_seqlets"]
if p_ic > ic_class_representative:
all_patterns[str(match_idx)]["classes"][cell_type] = p
all_patterns[str(match_idx)]["classes"][cell_type]["n_seqlets"] = (
n_seqlets_class_representative + p["n_seqlets"]
) # We add to the total number of seqlets for this class
else:
all_patterns[str(match_idx)]["classes"][cell_type] = p
if p_ic > all_patterns[str(match_idx)]["ic"]:
all_patterns[str(match_idx)]["ic"] = p_ic
all_patterns[str(match_idx)]["pattern"] = p
all_patterns[str(match_idx)]["ppm"] = ppm
return all_patterns
def post_hoc_merging(
all_patterns: dict,
sim_threshold: float = 0.5,
ic_discard_threshold: float = 0.15,
verbose: bool = False,
return_info: bool = False,
) -> dict | tuple[dict, list[tuple[str, str, float]]]:
"""
Double-checks the similarity of all patterns and merges them if they exceed the threshold.
Filters out patterns with IC below the discard threshold at the last step and updates the keys.
Parameters
----------
all_patterns
Dictionary of all patterns with metadata. Each pattern must include 'pattern', 'ic', and 'classes'.
sim_threshold
Similarity threshold for merging patterns.
ic_discard_threshold
IC threshold below which patterns are discarded unless they belong to multiple classes.
verbose
Flag to enable verbose output of merged patterns.
return_info
If True, also return a list of all performed merges as (pattern_id_1, pattern_id_2, similarity).
Returns
-------
Updated patterns after merging and filtering with sequential keys.
If `return_info=True`, also returns a list of performed merges.
"""
current_meta = list(all_patterns.values())
all_merges = []
iteration = 0
while True:
iteration += 1
N = len(current_meta)
raw_patterns = [m["pattern"] for m in current_meta]
raw_ids = [m["pattern"]["id"] for m in current_meta]
S = match_score_patterns(raw_patterns, raw_patterns)
S = np.maximum(S, S.T)
np.fill_diagonal(S, -np.inf)
candidates = np.argwhere(S > sim_threshold)
candidates = [(i, j, S[i, j]) for i, j in candidates if i < j]
if not candidates:
if verbose:
print(f"Iteration {iteration}: no more matches above {sim_threshold}")
break
candidates.sort(key=lambda x: x[2], reverse=True)
matched = set()
merges = []
for i, j, score in candidates:
if i in matched or j in matched:
continue
matched.add(i)
matched.add(j)
merges.append((i, j, score))
all_merges.append((raw_ids[i], raw_ids[j], score))
if verbose:
print(f"Iteration {iteration}: performing {len(merges)} merges")
for i, j, score in merges:
print(f" -> merging {raw_ids[i]} + {raw_ids[j]} (sim={score:.3f})")
new_meta = []
used = set()
for i, j, _ in merges:
merged = merge_patterns(current_meta[i], current_meta[j])
new_meta.append(merged)
used.update({i, j})
for idx in range(N):
if idx not in used:
new_meta.append(current_meta[idx])
current_meta = new_meta
final = {}
idx = 0
for m in current_meta:
if m["ic"] >= ic_discard_threshold or len(m["classes"]) > 1:
final[str(idx)] = m
idx += 1
elif verbose:
print(f"Dropping {m['pattern']['id']} (IC={m['ic']:.3f})")
if verbose:
print(f"Done after {iteration} iterations; {len(final)} patterns remain.")
return (final, all_merges) if return_info else final
def post_hoc_merging_old(
all_patterns: dict,
sim_threshold: float = 0.5,
ic_discard_threshold: float = 0.15,
verbose: bool = False,
) -> dict:
"""
Double-checks the similarity of all patterns and merges them if they exceed the threshold.
Filters out patterns with IC below the discard threshold at the last step and updates the keys.
Parameters
----------
all_patterns
dictionary of all patterns with metadata.
sim_threshold
Similarity threshold for merging patterns.
ic_discard_threshold
IC threshold below which patterns are discarded.
verbose
Flag to enable verbose output of merged patterns.
Returns
-------
Updated patterns after merging and filtering with sequential keys.
"""
pattern_list = list(all_patterns.items())
def should_merge(p1, p2):
"""Check if two patterns should merge based on the similarity threshold."""
sim = max(
match_score_patterns(p1["pattern"], p2["pattern"]),
match_score_patterns(p2["pattern"], p1["pattern"]),
)
return sim > sim_threshold, sim
iterations = 0 # Track number of iterations for debugging
while True:
merged_patterns = {}
new_index = 0
merged_indices = set()
any_merged = False
# Keep track of which pairs have been compared and the result
for i, (idx1, pattern1) in enumerate(pattern_list):
if idx1 in merged_indices:
continue
merged_indices.add(idx1)
merged_pattern = pattern1.copy()
for j, (idx2, pattern2) in enumerate(pattern_list):
if i >= j or idx2 in merged_indices:
continue
should_merge_result, similarity = should_merge(pattern1, pattern2)
if should_merge_result:
merged_indices.add(idx2)
merged_pattern = merge_patterns(merged_pattern, pattern2)
any_merged = True
if verbose:
print(
f'Merged patterns {pattern1["pattern"]["id"]} and {pattern2["pattern"]["id"]} with similarity {similarity}'
)
# Add the merged pattern to the new set of patterns
merged_patterns[str(new_index)] = merged_pattern
new_index += 1
# If nothing merged in this pass, break out
if not any_merged:
break
iterations += 1 # Increment number of iterations
if verbose:
print(f"Iteration {iterations}: Merging complete, checking again")
# Rebuild pattern list from merged patterns for the next iteration
pattern_list = list(merged_patterns.items())
# Final filtering based on IC discard threshold
filtered_patterns = {}
discarded_ids = []
for k, v in merged_patterns.items():
if v["ic"] >= ic_discard_threshold or len(v["classes"]) > 1:
filtered_patterns[k] = v
else:
discarded_ids.append(v["pattern"]["id"])
if verbose:
discarded_count = len(merged_patterns) - len(filtered_patterns)
print(
f"Discarded {discarded_count} patterns below IC threshold {ic_discard_threshold} and with a single class instance:"
)
print(discarded_ids)
# Reindex the filtered patterns
final_patterns = {
str(new_idx): v for new_idx, (k, v) in enumerate(filtered_patterns.items())
}
if verbose:
print(f"Total iterations: {iterations}")
return final_patterns
def merge_patterns(pattern1: dict, pattern2: dict) -> dict:
"""
Merge two patterns into one. The resulting pattern will have the highest IC pattern as the representative pattern.
Parameters
----------
pattern1
First pattern with metadata.
pattern2
Second pattern with metadata.
Returns
-------
Merged pattern with updated metadata.
"""
merged_classes = {}
for cell_type in pattern1["classes"].keys():
if cell_type in pattern2["classes"].keys():
ic_a = pattern1["classes"][cell_type]["ic"]
n_seqlets_a = pattern1["classes"][cell_type]["n_seqlets"]
ic_b = pattern2["classes"][cell_type]["ic"]
n_seqlets_b = pattern2["classes"][cell_type]["n_seqlets"]
merged_classes[cell_type] = (
pattern1["classes"][cell_type]
if ic_a > ic_b
else pattern2["classes"][cell_type]
)
merged_classes[cell_type]["n_seqlets"] = n_seqlets_a + n_seqlets_b
else:
merged_classes[cell_type] = pattern1["classes"][cell_type]
for cell_type in pattern2["classes"].keys():
if cell_type not in merged_classes.keys():
merged_classes[cell_type] = pattern2["classes"][cell_type]
merged_instances = {**pattern1["instances"], **pattern2["instances"]}
if pattern2["ic"] > pattern1["ic"]:
representative_pattern = pattern2["pattern"]
highest_ic = pattern2["ic"]
else:
representative_pattern = pattern1["pattern"]
highest_ic = pattern1["ic"]
return {
"pattern": representative_pattern,
"ic": highest_ic,
"classes": merged_classes,
"instances": merged_instances,
}
def pattern_similarity(all_patterns: dict, idx1: int, idx2: int) -> float:
"""
Compute the similarity between two patterns.
Parameters
----------
all_patterns
dictionary containing all patterns.
idx1
Index of the first pattern.
idx2
Index of the second pattern.
Returns
-------
Similarity score between the two patterns.
"""
sim = max(
match_score_patterns(
all_patterns[str(idx1)]["pattern"], all_patterns[str(idx2)]["pattern"]
),
match_score_patterns(
all_patterns[str(idx2)]["pattern"], all_patterns[str(idx1)]["pattern"]
),
)
return sim
def normalize_rows(arr: np.ndarray) -> np.ndarray:
"""
Normalize the rows of an array such that the positive values are scaled by their maximum and negative values by their minimum absolute value.
Parameters
----------
arr
Input array to be normalized.
Returns
-------
The row-normalized array.
"""
normalized_array = np.zeros_like(arr)
for i in range(arr.shape[0]):
pos_values = arr[i, arr[i] > 0]
neg_values = arr[i, arr[i] < 0]
if pos_values.size > 0:
max_pos = np.max(pos_values)
normalized_array[i, arr[i] > 0] = pos_values / max_pos
if neg_values.size > 0:
min_neg = np.min(neg_values)
normalized_array[i, arr[i] < 0] = neg_values / abs(min_neg)
return normalized_array
def find_pattern(pattern_id: str, pattern_dict: dict) -> int | None:
"""
Find the index of a pattern by its ID.
Parameters
----------
pattern_id
The ID of the pattern to find.
pattern_dict
A dictionary containing pattern data.
Returns
-------
The index of the pattern if found, otherwise None.
"""
for idx, p in enumerate(pattern_dict):
if pattern_id == pattern_dict[p]["pattern"]["id"]:
return idx
for c in pattern_dict[p]["classes"]:
if pattern_id == pattern_dict[p]["classes"][c]["id"]:
return idx
return None
def match_h5_files_to_classes(
contribution_dir: str, classes: list[str]
) -> dict[str, str | None]:
"""
Match .h5 files in a given directory with a list of class names and returns a dictionary mapping.
Parameters
----------
contribution_dir
Directory containing .h5 files.
classes
list of class names to match against file names.
See Also
--------
crested.tl.modisco.tfmodisco
Returns
-------
A dictionary where keys are class names and values are paths to the corresponding .h5 files if matched, None otherwise.
"""
h5_files = [file for file in os.listdir(contribution_dir) if file.endswith(".h5")]
matched_files = dict.fromkeys(classes, None)
for file in h5_files:
base_name = os.path.splitext(file)[0][:-16]
for class_name in classes:
if base_name == class_name:
matched_files[class_name] = os.path.join(contribution_dir, file)
break
return matched_files
def _read_and_trim_patterns(
cell_type: str,
file_list: str | list[str],
trim_ic_threshold: float,
verbose: bool
) -> tuple[list[dict], list[str], list[bool]]:
"""
Read and trim patterns from HDF5 files for a specific cell type.
This function iterates over all HDF5 files associated with a cell type, reads the patterns stored in each metacluster,
trims them using an information content threshold, and collects associated metadata.
Parameters
----------
cell_type
The name of the cell type whose patterns are being processed.
file_list
Path(s) to HDF5 file(s) containing patterns for the cell type.
trim_ic_threshold
Information content threshold for trimming each pattern.
verbose
Whether to print diagnostic information during reading and processing.
Returns
-------
trimmed_patterns
A list of trimmed pattern dictionaries, one per pattern found.
pattern_ids
A list of pattern identifiers, each uniquely naming a pattern.
is_pattern_pos
A list of boolean flags indicating whether the pattern came from the "pos_patterns" metacluster.
"""
trimmed_patterns = []
pattern_ids = []
is_pattern_pos = []
if isinstance(file_list, str):
file_list = [file_list]
for h5_file in file_list:
if verbose:
print(f"Reading file {h5_file}")
try:
with h5py.File(h5_file) as hdf5_results:
for metacluster_name in list(hdf5_results.keys()):
pattern_idx = 0
for i in range(len(list(hdf5_results[metacluster_name]))):
p = "pattern_" + str(i)
pattern_ids.append(
f"{cell_type.replace(' ', '_')}_{metacluster_name}_{pattern_idx}"
)
is_pos = metacluster_name == "pos_patterns"
pattern = _trim_pattern_by_ic(
hdf5_results[metacluster_name][p],
is_pos,
trim_ic_threshold,
)
pattern["file_path"] = h5_file
trimmed_patterns.append(pattern)
is_pattern_pos.append(is_pos)
pattern_idx += 1
except OSError:
print(f"File error at {h5_file}")
continue
return trimmed_patterns, pattern_ids, is_pattern_pos
def calculate_tomtom_similarity_per_pattern(
matched_files: dict[str, str | list[str] | None],
trim_ic_threshold: float = 0.05,
use_ppm: bool = False,
background_freqs: list | None = None,
verbose: bool = False,
) -> tuple[np.ndarray, list[str], dict[str, dict]]:
"""
Compute pairwise similarity between all trimmed patterns across matched HDF5 files using TOMTOM.
This function reads in motif patterns from HDF5 files (e.g., from a TF-MoDISco pipeline),
trims them based on information content, converts them to PPMs, and computes a full pairwise
similarity matrix using TOMTOM. It also returns pattern metadata, including the contribution
scores and the number of seqlets per pattern.
Parameters
----------
matched_files
Dictionary mapping cell type names (or class names) to HDF5 file paths or list of paths
containing TF-MoDISco results. A value of None indicates no data for that cell type.
trim_ic_threshold
Threshold for trimming low-information-content ends of patterns.
Defaults to 0.05.
verbose
If True, prints progress messages.
Returns
-------
similarity_matrix
A 2D square NumPy array of shape (N, N), where N is the number of trimmed patterns across
all cell types. Each entry [i, j] contains the TOMTOM similarity score (-log10 p-value)
between pattern i and pattern j.
all_pattern_ids
A list of unique pattern identifiers, corresponding to the rows and columns in
`similarity_matrix`.
pattern_dict
A dictionary mapping each pattern ID to a dictionary containing:
- 'contrib_scores': the contribution score matrix (for visualization),
- 'n_seqlets': the number of seqlets contributing to the pattern.
Notes
-----
- Patterns are first trimmed using `_read_and_trim_patterns`.
- PPMs are computed using `_pattern_to_ppm` and inserted into each pattern dictionary.
- Similarity is computed using `match_score_patterns`, which uses TOMTOM under the hood.
- The function assumes the presence of external dependencies like `_read_and_trim_patterns`,
`_pattern_to_ppm`, and `match_score_patterns`, typically from a motif analysis library.
"""
if background_freqs is None:
background_freqs = [0.28, 0.22, 0.22, 0.28]
background_freqs = np.array(background_freqs)
all_trimmed_patterns = []
all_pattern_ids = []
for cell_type in matched_files:
trimmed_patterns, pattern_ids, is_pattern_pos = _read_and_trim_patterns(
cell_type,
matched_files[cell_type],
trim_ic_threshold,
verbose
)
all_trimmed_patterns += trimmed_patterns
all_pattern_ids += pattern_ids
# Add PPMs to each pattern
pattern_ppms = [_pattern_to_ppm(p) for p in all_trimmed_patterns]
for i, pat in enumerate(all_trimmed_patterns):
pat['ppm'] = pattern_ppms[i]
if verbose:
print('Total patterns:', len(all_trimmed_patterns))
# Compute pairwise TOMTOM similarity
similarity_matrix = match_score_patterns(all_trimmed_patterns, all_trimmed_patterns, use_ppm=use_ppm, background_freqs=background_freqs)
# Construct output metadata dictionary
pattern_dict = {
pid: {
'contrib_scores': all_trimmed_patterns[i]['contrib_scores'],
'n_seqlets': all_trimmed_patterns[i]['seqlets']['n_seqlets']
}
for i, pid in enumerate(all_pattern_ids)
}
return similarity_matrix, all_pattern_ids, pattern_dict
def process_patterns(
matched_files: dict[str, str | list[str] | None],
sim_threshold: float = 6.0,
trim_ic_threshold: float = 0.025,
discard_ic_threshold: float = 0.1,
verbose: bool = False,
) -> dict[str, dict[str, str | list[float]]]:
"""
Process genomic patterns from matched HDF5 files, trim based on information content, and match to known patterns.
Parameters
----------
matched_files
dictionary with class names as keys and paths to HDF5 files as values.
sim_threshold
Similarity threshold for matching patterns (-log10(pval), pval obtained through TOMTOM matching from memesuite-lite)
trim_ic_threshold
Information content threshold for trimming patterns.
discard_ic_threshold
Information content threshold for discarding patterns.
verbose
Flag to enable verbose output.
See Also
--------
crested.tl.modisco.match_h5_files_to_classes
Returns
-------
All processed patterns with metadata.
"""
all_patterns = {}
for cell_type in matched_files: