forked from jzhoulab/orca
-
Notifications
You must be signed in to change notification settings - Fork 0
/
orca_predict.py
executable file
·3347 lines (3115 loc) · 125 KB
/
orca_predict.py
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
"""
This module provides functions for using Orca models for various
types of the predictions. This is the main module that you need for
interacting with Orca models.
To use any of the prediction functions, `load_resources` has to be
called first to load the necessary resources.
The coordinates used in Orca are 0-based, inclusive for the start
coordinate and exclusive for the end coordinate, consistent with
python conventions.
"""
import os
import pathlib
import numpy as np
import torch
from scipy.stats import spearmanr
from selene_utils2 import MemmapGenome, Genomic2DFeatures
import selene_sdk
from selene_sdk.sequences import Genome
from orca_models import H1esc, Hff, H1esc_1M, Hff_1M, H1esc_256M, Hff_256M
from orca_utils import (
genomeplot,
genomeplot_256Mb,
StructuralChange2,
process_anno,
coord_round,
coord_clip,
)
try:
from seqstr import seqstr
except ImportError:
seqstr = None
ORCA_PATH = str(pathlib.Path(__file__).parent.absolute())
model_dict_global, target_dict_global = {}, {}
def load_resources(models=["32M"], use_cuda=True, use_memmapgenome=True):
"""
Load resources for Orca predictions including the specified
Orca models and hg38 reference genome. It also creates Genomic2DFeatures
objects for experimental micro-C datasets (for comparison with prediction).
Load resourced are accessible as global variables.
The list of globl variables generated is here:
Global Variables
----------------
hg38 : selene_utils2.MemmapGenome or selene_sdk.sequences.Genome
If `use_memmapgenome==True` and the resource file for hg38 mmap exists,
use MemmapGenome instead of Genome.
h1esc : orca_models.H1esc
1-32Mb Orca H1-ESC model
hff : orca_models.Hff
1-32Mb Orca HFF model
h1esc_256m : orca_models.H1esc_256M
32-256Mb Orca H1-ESC model
hff_256m : orca_models.Hff_256M
32-256Mb Orca HFF model
h1esc_1m : orca_models.H1esc_1M
1Mb Orca H1-ESC model
hff_1m : orca_models.Hff_1M
1Mb Orca HFF model
target_h1esc : selene_utils2.Genomic2DFeatures
Genomic2DFeatures object that load H1-ESC micro-C dataset 4DNFI9GMP2J8
at 4kb resolution, used for comparison with 1-32Mb models.
target_hff : selene_utils2.Genomic2DFeatures
Genomic2DFeatures object that load HFF micro-C dataset 4DNFI643OYP9
at 4kb resolution, used for comparison with 1-32Mb models.
target_h1esc_256m : selene_utils2.Genomic2DFeatures
Genomic2DFeatures object that load H1-ESC micro-C dataset 4DNFI9GMP2J8
at 32kb resolution, used for comparison with 32-256Mb models.
target_hff_256m : selene_utils2.Genomic2DFeatures
Genomic2DFeatures object that load HFF micro-C dataset 4DNFI643OYP9
at 32kb resolution, used for comparison with 32-256Mb models.
target_h1esc_1m : selene_utils2.Genomic2DFeatures
Genomic2DFeatures object that load H1-ESC micro-C dataset 4DNFI9GMP2J8
at 32kb resolution, used for comparison with 1Mb models.
target_hff_1m : selene_utils2.Genomic2DFeatures
Genomic2DFeatures object that load HFF micro-C dataset 4DNFI643OYP9
at 1kb resolution, used for comparison with 1Mb models.
target_available : bool
Indicate whether the micro-C dataset resource file is available.
Parameters
----------
models : list(str)
List of model types to load, supported model types includes
"32M", "256M", "1M", corresponding to 1-32Mb, 32-256Mb, and 1Mb
models. Lower cases are also accepted.
use_cuda : bool, optional
Default is True. If true, loaded models are moved to GPU.
use_memmapgenome : bool, optional
Default is True. If True and the resource file for hg38 mmap exists,
use MemmapGenome instead of Genome.
"""
global hg38, hg19, target_hff, target_h1esc, target_hff_256m, target_h1esc_256m, target_hff_1m, target_h1esc_1m, target_available
if "32M" in models or "32m" in models:
global h1esc, hff
h1esc = H1esc()
h1esc.eval()
hff = Hff()
hff.eval()
if use_cuda:
h1esc.cuda()
hff.cuda()
else:
h1esc.cpu()
hff.cpu()
model_dict_global["h1esc"] = h1esc
model_dict_global["hff"] = hff
if "1M" in models or "1m" in models:
global h1esc_1m, hff_1m
h1esc_1m = H1esc_1M()
h1esc_1m.eval()
hff_1m = Hff_1M()
hff_1m.eval()
if use_cuda:
h1esc_1m.cuda()
hff_1m.cuda()
else:
h1esc_1m.cpu()
hff_1m.cpu()
model_dict_global["h1esc_1m"] = h1esc_1m
model_dict_global["hff_1m"] = hff_1m
if "256M" in models or "256m" in models:
global h1esc_256m, hff_256m
h1esc_256m = H1esc_256M()
h1esc_256m.eval()
hff_256m = Hff_256M()
hff_256m.eval()
if use_cuda:
h1esc_256m.cuda()
hff_256m.cuda()
else:
h1esc_256m.cpu()
hff_256m.cpu()
model_dict_global["h1esc_256m"] = h1esc_256m
model_dict_global["hff_256m"] = hff_256m
if (
use_memmapgenome
and pathlib.Path("/resources/Homo_sapiens.GRCh38.dna.primary_assembly.fa.mmap").exists()
):
hg38 = MemmapGenome(
input_path=ORCA_PATH + "/resources/Homo_sapiens.GRCh38.dna.primary_assembly.fa",
memmapfile=ORCA_PATH + "/resources/Homo_sapiens.GRCh38.dna.primary_assembly.fa.mmap",
)
if os.path.exists(ORCA_PATH + '/resources/Homo_sapiens.GRCh37.75.dna.primary_assembly.fa'):
hg19 = MemmapGenome(
input_path=ORCA_PATH + "/resources/Homo_sapiens.GRCh37.75.dna.primary_assembly.fa",
memmapfile=ORCA_PATH + "/resources/Homo_sapiens.GRCh37.75.dna.primary_assembly.fa.mmap",
)
else:
hg19 = None
else:
hg38 = Genome(
input_path=ORCA_PATH + "/resources/Homo_sapiens.GRCh38.dna.primary_assembly.fa",
)
if os.path.exists(ORCA_PATH + '/resources/Homo_sapiens.GRCh37.75.dna.primary_assembly.fa'):
hg19 = Genome(
input_path=ORCA_PATH + "/resources/Homo_sapiens.GRCh37.75.dna.primary_assembly.fa",
)
else:
hg19 = None
target_available = True
if os.path.exists(ORCA_PATH + "/resources/4DNFI643OYP9.rebinned.mcool"):
target_hff = Genomic2DFeatures(
[ORCA_PATH + "/resources/4DNFI643OYP9.rebinned.mcool::/resolutions/4000"],
["r4000"],
(8000, 8000),
cg=True,
)
target_hff_256m = Genomic2DFeatures(
[ORCA_PATH + "/resources/4DNFI643OYP9.rebinned.mcool::/resolutions/32000"],
["r32000"],
(8000, 8000),
cg=True,
)
target_hff_1m = Genomic2DFeatures(
[ORCA_PATH + "/resources/4DNFI643OYP9.rebinned.mcool::/resolutions/1000"],
["r1000"],
(8000, 8000),
cg=True,
)
target_dict_global['hff'] = target_hff
target_dict_global['hff_256m'] = target_hff_256m
target_dict_global['hff_1m'] = target_hff_1m
else:
target_available = False
if os.path.exists(ORCA_PATH + "/resources/4DNFI9GMP2J8.rebinned.mcool"):
target_h1esc = Genomic2DFeatures(
[ORCA_PATH + "/resources/4DNFI9GMP2J8.rebinned.mcool::/resolutions/4000"],
["r4000"],
(8000, 8000),
cg=True,
)
target_h1esc_256m = Genomic2DFeatures(
[ORCA_PATH + "/resources/4DNFI9GMP2J8.rebinned.mcool::/resolutions/32000"],
["r32000"],
(8000, 8000),
cg=True,
)
target_h1esc_1m = Genomic2DFeatures(
[ORCA_PATH + "/resources/4DNFI9GMP2J8.rebinned.mcool::/resolutions/1000"],
["r1000"],
(8000, 8000),
cg=True,
)
target_dict_global['h1esc'] = target_h1esc
target_dict_global['h1esc_256m'] = target_h1esc_256m
target_dict_global['h1esc_1m'] = target_h1esc_1m
else:
target_available = False
def genomepredict(
sequence, mchr, mpos=-1, wpos=-1, models=["h1esc", "hff"], targets=None, annotation=None, use_cuda=True, nan_thresh=1,
):
"""Multiscale prediction for a 32Mb sequence
input, zooming into the position specified when generating a series
of 32Mb, 16Mb, 8Mb, 4Mb, 2Mb and 1Mb predictions with increasing
resolutions (up to 4kb). This function also processes
information used only for plotting including targets and annotation.
For larger sequence and interchromosomal predictions, you can use
256Mb input with genomepredict_256Mb.
Parameters
----------
sequence : numpy.ndarray
One-hot sequence encoding of shape 1 x 32000000 x 4.
The encoding can be generated with `selene_sdk.Genome.sequence_to_encoding()`.
mchr : str
Chromosome name. This is used for annotation purpose only.
mpos : int, optional
The coordinate to zoom into for multiscale prediction.
wpos : int, optional
The coordinate of the center position of the sequence, which is
start position + 16000000.
models : list(torch.nn.Module or str), optional
Models to use. Default is H1-ESC and HFF Orca models.
targets : list(numpy.ndarray), optional
The observed balanced contact matrices from the
32Mb region. Used only for plotting when used with genomeplot. The length and
order of the list of targets should match the models specified (default is
H1-ESC and HFF Orca models).
The dimensions of the arrays should be 8000 x 8000 (1kb resolution).
annotation : str or None, optional
List of annotations for plotting. The annotation can be generated with
See orca_utils.process_anno and see its documentation for more details.
use_cuda : bool, optional
Default is True. If False, use CPU.
nan_thresh : int, optional
Default is 1. Specify the threshold of the proportion of NaNs values
allowed during downsampling for the observed matrices. Only relevant for plotting.
The lower resolution observed matrix value are computed by averaging multiple
bins into one. By default, we allow missing values and only average over the
non-missing values, and the values with more than the specified proprotion
of missing values will be filled with NaN.
Returns
----------
output : dict
Result dictionary that can be used as input for genomeplot. The dictionary
has the following keys:
- predictions : list(list(numpy.ndarray), list(numpy.ndarray))
Multi-level predictions for H1-ESC and HFF cell types.
- experiments : list(list(numpy.ndarray), list(numpy.ndarray))
Observations for H1-ESC and HFF cell types that matches the predictions.
Exists if `targets` is specified.
- normmats : list(list(numpy.ndarray), list(numpy.ndarray))
Background distance-based expected balanced contact matrices for
H1-ESC and HFF cell types that matches the predictions.
- start_coords : list(int)
Start coordinates for the prediction at each level.
- end_coords : list(int)
End coordinates for the prediction at each level.
- chr : str
The chromosome name.
- annos : list(list(...))
Annotation information. The format is as outputed by orca_utils.process_anno
Exists if `annotation` is specified.
"""
model_objs = []
for m in models:
if isinstance(m, torch.nn.Module):
model_objs.append(m)
else:
try:
if m in model_dict_global:
model_objs.append(model_dict_global[m])
except KeyError:
load_resources(models=["32M"], use_cuda=use_cuda)
if m in model_dict_global:
model_objs.append(model_dict_global[m])
models = model_objs
n_models = len(models)
with torch.no_grad():
allpreds = []
allstarts = []
if targets:
alltargets = []
if annotation is not None:
allannos = []
for iii, seq in enumerate(
[
torch.FloatTensor(sequence),
torch.FloatTensor(sequence[:, ::-1, ::-1].copy()),
]
):
for ii, model in enumerate(models):
if targets and iii == 0:
target = targets[ii]
(encoding1, encoding2, encoding4, encoding8, encoding16, encoding32,) = model.net(
model.net0(torch.Tensor(seq.float()).transpose(1, 2).cuda())
if use_cuda
else model.net0(torch.Tensor(seq.float()).transpose(1, 2))
)
encodings = {
1: encoding1,
2: encoding2,
4: encoding4,
8: encoding8,
16: encoding16,
32: encoding32,
}
def eval_step(level, start, coarse_pred=None):
distenc = torch.log(
torch.FloatTensor(model.normmats[level][(None,)*(4-model.normmats[level].ndim)]).cuda()
if use_cuda
else torch.FloatTensor(model.normmats[level][(None,)*(4-model.normmats[level].ndim)])
).expand(sequence.shape[0], -1, -1, -1)
if coarse_pred is not None:
if level == 1:
pred = model.denets[level].forward(
encodings[level][
:, :, int(start / level) : int(start / level) + 250
],
distenc,
coarse_pred,
) + model.denet_1_pt.forward(
encodings[level][
:, :, int(start / level) : int(start / level) + 250
]
)
else:
pred = model.denets[level].forward(
encodings[level][
:, :, int(start / level) : int(start / level) + 250
],
distenc,
coarse_pred,
)
else:
pred = model.denets[level].forward(
encodings[level][:, :, int(start / level) : int(start / level) + 250],
distenc,
)
return pred
preds = []
starts = [0]
if targets and iii == 0:
ts = []
if annotation is not None and iii == 0:
annos = []
for j, level in enumerate([32, 16, 8, 4, 2, 1]):
if j == 0:
pred = eval_step(level, starts[j])
else:
pred = eval_step(
level,
starts[j],
preds[j - 1][
:,
:,
start_index : start_index + 125,
start_index : start_index + 125,
],
)
if targets and iii == 0:
target_r = np.nanmean(
np.nanmean(
np.reshape(
target[
:,
starts[j] : starts[j] + 250 * level,
starts[j] : starts[j] + 250 * level,
].numpy(),
(target.shape[0], 250, level, 250, level),
),
axis=4,
),
axis=2,
)
target_nan = np.mean(
np.mean(
np.isnan(
np.reshape(
target[
:,
starts[j] : starts[j] + 250 * level,
starts[j] : starts[j] + 250 * level,
].numpy(),
(target.shape[0], 250, level, 250, level),
)
),
axis=4,
),
axis=2,
)
target_r[target_nan > nan_thresh] = np.nan
if target_r.shape[0]==1:
target_np = np.log(
(target_r + model.epss[level])
/ (model.normmats[level] + model.epss[level]))[0, :, :]
else:
target_np = np.log(
(target_r + model.epss[level])
/ (model.normmats[level] + model.epss[level]))
ts.append(target_np)
if annotation is not None and iii == 0:
newstart = starts[j] / 8000.0
newend = (starts[j] + 250 * level) / 8000.0
anno_r = []
for r in annotation:
if len(r) == 3:
if not (r[0] >= newend or r[1] <= newstart):
anno_r.append(
(
np.fmax((r[0] - newstart) / (newend - newstart), 0,),
np.fmin((r[1] - newstart) / (newend - newstart), 1,),
r[2],
)
)
else:
if r[0] >= newstart and r[0] < newend:
anno_r.append(((r[0] - newstart) / (newend - newstart), r[1]))
annos.append(anno_r)
if iii == 0:
start_index = int(
np.clip(
np.floor(
(
(mpos - level * 1000000 / 4)
- (wpos - 16000000 + starts[j] * 4000)
)
/ (4000 * level)
),
0,
125,
)
)
else:
start_index = int(
np.clip(
np.ceil(
(
(wpos + 16000000 - starts[j] * 4000)
- (mpos + level * 1000000 / 4)
)
/ (4000 * level)
),
0,
125,
)
)
starts.append(starts[j] + start_index * level)
preds.append(pred)
allpreds.append(preds)
if iii == 0:
if targets:
alltargets.append(ts)
if annotation is not None:
allannos.append(annos)
allstarts.append(starts[:-1])
output = {}
output["predictions"] = [[] for _ in range(n_models)]
for i in range(n_models):
for j in range(len(allpreds[i])):
if allpreds[i][j].shape[1] == 1:
output["predictions"][i].append(
allpreds[i][j].cpu().detach().numpy()[0, 0, :, :] * 0.5
+ allpreds[i + n_models][j].cpu().detach().numpy()[0, 0, ::-1, ::-1] * 0.5
)
else:
output["predictions"][i].append(
allpreds[i][j].cpu().detach().numpy()[0, :, :, :] * 0.5
+ allpreds[i + n_models][j].cpu().detach().numpy()[0, :, ::-1, ::-1] * 0.5
)
if targets:
output["experiments"] = alltargets
else:
output["experiments"] = None
output["start_coords"] = [wpos - 16000000 + s * 4000 for s in allstarts[0]]
output["end_coords"] = [
int(output["start_coords"][ii] + 32000000 / 2 ** (ii)) for ii in range(6)
]
output["chr"] = mchr
if annotation is not None:
output["annos"] = allannos[0]
else:
output["annos"] = None
output["normmats"] = [
[model.normmats[ii] for ii in [32, 16, 8, 4, 2, 1]] for model in models
]
return output
def genomepredict_256Mb(
sequence,
mchr,
normmats,
chrlen,
mpos=-1,
wpos=-1,
models=["h1esc_256m", "hff_256m"],
targets=None,
annotation=None,
padding_chr=None,
use_cuda=True,
nan_thresh=1,
):
"""Multiscale prediction for a 256Mb sequence
input, zooming into the position specified when generating a series
of 256Mb, 128Mb, 64Mb, and 32Mb predictions with increasing
resolutions (up to 128kb). This function also processes
information used only for plotting including targets and annotation.
This function accepts multichromosal input sequence. Thus it needs an
extra input `normmats` to encode the chromosomal information. See documentation
for normmats argument for details.
Parameters
----------
sequence : numpy.ndarray
One-hot sequence encoding of shape 1 x 256000000 x 4.
The encoding can be generated with `selene_sdk.Genome.sequence_to_encoding()`.
mchr : str
The chromosome name of the first chromosome included in the seqeunce.
This is used for annotation purpose only.
normmats : list(numpy.ndarray)
A list of distance-based background matrices for H1-ESC and HFF.The
normmats contains arrays with dimensions 8000 x 8000 (32kb resolution).
Interchromosomal interactions are filled with the expected balanced contact
score for interchromomsal interactions.
chrlen : int
The coordinate of the end of the first chromosome in the input, which is the
chromosome that will be zoomed into.
mpos : int, optional
Default is -1. The coordinate to zoom into for multiscale prediction. If neither
`mpos` nor `wpos` are specified, it zooms into the center of the input by default.
wpos : int, optional
Default is -1. The coordinate of the center position of the sequence, which is
start position + 16000000. If neither `mpos` nor `wpos` are specified, it zooms
into the center of the input by default.
models : list(torch.nn.Module or str), optional
Models to use. Default is H1-ESC(256Mb) and HFF(256Mb) Orca models.
targets : list(numpy.ndarray), optional
The observed balanced contact matrices from the 256Mb sequence.
Used only for plotting when used with genomeplot. The length and
order of the list of targets should match the models specified (default is
H1-ESC and HFF Orca models). The dimensions of the arrays should be
8000 x 8000 (32kb resolution).
annotation : str or None, optional
Default is None. List of annotations for plotting. The annotation can be generated with
See orca_utils.process_anno and see its documentation for more details.
padding_chr : str, None, optional
Default is None. Name of the padding chromosome after the first. Used for annotation
only. TODO: be more flexible in the support for multiple chromosomes.
use_cuda : bool, optional
Default is True. If False, use CPU.
nan_thresh : int, optional
Default is 1. Specify the threshold of the proportion of NaNs values
allowed during downsampling for the observed matrices. Only relevant for plotting.
The lower resolution observed matrix value are computed by averaging multiple
bins into one. By default, we allow missing values and only average over the
non-missing values, and the values with more than the specified proprotion
of missing values will be filled with NaN.
Returns
----------
output : dict
Result dictionary that can be used as input for genomeplot. The dictionary
has the following keys:
- predictions : list(list(numpy.ndarray), list(numpy.ndarray))
Multi-level predictions for H1-ESC and HFF cell types.
- experiments : list(list(numpy.ndarray), list(numpy.ndarray))
Observations for H1-ESC and HFF cell types that matches the predictions.
Exists if `targets` is specified.
- normmats : list(list(numpy.ndarray), list(numpy.ndarray))
Background distance-based expected balanced contact matrices for
H1-ESC and HFF cell types that matches the predictions.
- start_coords : list(int)
Start coordinates for the prediction at each level.
- end_coords : list(int)
End coordinates for the prediction at each level.
- chr : str
The chromosome name.
- annos : list(list(...))
Annotation information. The format is as outputed by orca_utils.process_anno
Exists if `annotation` is specified.
"""
model_objs = []
for m in models:
if isinstance(m, torch.nn.Module):
model_objs.append(m)
else:
try:
if m in model_dict_global:
model_objs.append(model_dict_global[m])
except KeyError:
load_resources(models=["256M"], use_cuda=use_cuda)
if m in model_dict_global:
model_objs.append(model_dict_global[m])
models = model_objs
n_models = len(models)
with torch.no_grad():
allpreds = []
allstarts = []
allnormmats = []
if targets:
alltargets = []
if annotation is not None:
allannos = []
for iii, seq in enumerate(
[
torch.FloatTensor(sequence),
torch.FloatTensor(sequence[:, ::-1, ::-1].copy()),
]
):
for ii, model in enumerate(models):
normmat = normmats[ii]
normmat_nan = np.isnan(normmat)
if np.any(normmat_nan):
normmat[normmat_nan] = np.nanmin(normmat[~normmat_nan])
if targets and iii == 0:
target = targets[ii]
(encoding32, encoding64, encoding128, encoding256) = model.net(
model.net1(
model.net0(
torch.Tensor(seq.float()).transpose(1, 2).cuda()
if use_cuda
else torch.Tensor(seq.float()).transpose(1, 2)
)
)[-1]
)
encodings = {
32: encoding32,
64: encoding64,
128: encoding128,
256: encoding256,
}
def eval_step(level, start, coarse_pred=None):
distenc = torch.log(
torch.FloatTensor(ns[level][None, :, :]).cuda()
if use_cuda
else torch.FloatTensor(ns[level][None, :, :])
).expand(sequence.shape[0], -1, -1, -1)
if coarse_pred is not None:
pred = model.denets[level].forward(
encodings[level][
:, :, int(start / (level // 8)) : int(start / (level // 8)) + 250,
],
distenc if iii == 0 else torch.flip(distenc, [2, 3]),
coarse_pred,
)
else:
pred = model.denets[level].forward(
encodings[level][
:, :, int(start / (level // 8)) : int(start / (level // 8)) + 250,
],
distenc if iii == 0 else torch.flip(distenc, [2, 3]),
)
return pred
preds = []
starts = [0]
ns = {}
if targets and iii == 0:
ts = []
if annotation is not None and iii == 0:
annos = []
for j, level in enumerate([256, 128, 64, 32]):
normmat_r = np.nanmean(
np.nanmean(
np.reshape(
normmat[
starts[j] : starts[j] + 250 * level // 8,
starts[j] : starts[j] + 250 * level // 8,
],
(1, 250, level // 8, 250, level // 8),
),
axis=4,
),
axis=2,
)
ns[level] = normmat_r
if j == 0:
pred = eval_step(level, starts[j])
else:
pred = eval_step(
level,
starts[j],
preds[j - 1][
:,
:,
start_index : start_index + 125,
start_index : start_index + 125,
],
)
if targets and iii == 0:
target_r = np.nanmean(
np.nanmean(
np.reshape(
target[
:,
starts[j] : starts[j] + 250 * level // 8,
starts[j] : starts[j] + 250 * level // 8,
].numpy(),
(target.shape[0], 250, level // 8, 250, level // 8),
),
axis=4,
),
axis=2,
)
target_nan = np.mean(
np.mean(
np.isnan(
np.reshape(
target[
:,
starts[j] : starts[j] + 250 * level // 8,
starts[j] : starts[j] + 250 * level // 8,
].numpy(),
(target.shape[0], 250, level // 8, 250, level // 8,),
)
),
axis=4,
),
axis=2,
)
target_r[target_nan > nan_thresh] = np.nan
eps = np.nanmin(normmat_r)
if target_r.shape[0]==1:
target_np = np.log((target_r + eps) / (normmat_r + eps))[0, :, :]
else:
target_np = np.log((target_r + eps) / (normmat_r + eps))
ts.append(target_np)
if annotation is not None and iii == 0:
newstart = starts[j] / 8000.0
newend = (starts[j] + 250 * level // 8) / 8000.0
anno_r = []
for r in annotation:
if len(r) == 3:
if not (r[0] >= newend or r[1] <= newstart):
anno_r.append(
(
np.fmax((r[0] - newstart) / (newend - newstart), 0,),
np.fmin((r[1] - newstart) / (newend - newstart), 1,),
r[2],
)
)
else:
if r[0] >= newstart and r[0] < newend:
anno_r.append(((r[0] - newstart) / (newend - newstart), r[1]))
annos.append(anno_r)
if iii == 0:
proposed_start = (mpos - level * 1000000 / 4) - (
wpos - 128000000 + starts[j] * 4000 * 8
)
else:
proposed_start = (mpos - level * 1000000 / 4) - (
wpos + 128000000 - starts[j] * 4000 * 8 - level * 1000000
)
if chrlen is not None:
bounds = [
0 - (wpos - 128000000),
chrlen - level * 1000000 / 2 - (wpos - 128000000),
]
if bounds[0] < bounds[1]:
proposed_start = np.clip(proposed_start, bounds[0], bounds[1])
else:
proposed_start = bounds[0]
start_index = int(np.clip(np.floor(proposed_start / (4000 * level)), 0, 125,))
if iii != 0:
start_index = 250 - (start_index + 125)
starts.append(starts[j] + start_index * level // 8)
preds.append(pred)
allpreds.append(preds)
allnormmats.append(ns)
if iii == 0:
if targets:
alltargets.append(ts)
if annotation is not None:
allannos.append(annos)
allstarts.append(starts[:-1])
output = {}
output["predictions"] = [[] for _ in range(n_models)]
for i in range(n_models):
for j in range(len(allpreds[i])):
if allpreds[i][j].shape[1] == 1:
output["predictions"][i].append(
allpreds[i][j].cpu().detach().numpy()[0, 0, :, :] * 0.5
+ allpreds[i + n_models][j].cpu().detach().numpy()[0, 0, ::-1, ::-1] * 0.5
)
else:
output["predictions"][i].append(
allpreds[i][j].cpu().detach().numpy()[0, :, :, :] * 0.5
+ allpreds[i + n_models][j].cpu().detach().numpy()[0, :, ::-1, ::-1] * 0.5
)
if targets:
output["experiments"] = alltargets
else:
output["experiments"] = None
output["start_coords"] = [wpos - 128000000 + s * 32000 for s in allstarts[0]]
output["end_coords"] = [
np.fmin(int(output["start_coords"][ii] + 256000000 / 2 ** (ii)), chrlen) for ii in range(4)
]
if annotation is not None:
output["annos"] = allannos[0]
else:
output["annos"] = None
output["chr"] = mchr
output["padding_chr"] = padding_chr
output["normmats"] = allnormmats
return output
def _retrieve_multi(regionlist, genome, target=True, normmat=True, normmat_regionlist=None):
sequences = []
for region in regionlist:
if len(region) == 4:
chrom, start, end, strand = region
sequences.append(genome.get_encoding_from_coords(chrom, start, end, strand))
else:
chrom, start, end = region
sequences.append(genome.get_encoding_from_coords(chrom, start, end, "+"))
sequence = np.vstack(sequences)[None, :, :]
if isinstance(target, list):
target_objs = target
has_target = True
elif target and target_available:
target_objs = [target_h1esc_256m, target_hff_256m]
has_target = True
else:
has_target = False
if has_target:
targets = []
for target_obj in target_objs:
targets_ = []
for region in regionlist:
if len(region) == 4:
chrom, start, end, strand = region
else:
chrom, start, end = region
strand = "+"
t = []
for region2 in regionlist:
if len(region2) == 4:
chrom2, start2, end2, strand2 = region2
else:
chrom2, start2, end2 = region2
strand = "+"
t.append(
target_obj.get_feature_data(
chrom, start, end, chrom2=chrom2, start2=start2, end2=end2
)
)
if strand == "-":
t[-1] = t[-1][::-1, :]
if strand2 == "-":
t[-1] = t[-1][:, ::-1]
targets_.append(t)
targets_= np.vstack([np.hstack(l) for l in targets_])
targets.append(targets_)
targets = [
torch.FloatTensor(l[None, :, :]) for l in targets
]
if normmat:
if isinstance(normmat, list):
normmat_objs = normmat
else:
normmat_objs = [h1esc_256m, hff_256m]
if normmat_regionlist is None:
normmat_regionlist = regionlist
normmats = []
for normmat_obj in normmat_objs:
normmats_ = []
for chrom, start, end, strand in normmat_regionlist:
b = []
for chrom2, start2, end2, strand2 in normmat_regionlist:
if chrom2 != chrom:
b.append(
np.full(
(int((end - start) / 32000), int((end2 - start2) / 32000)),
normmat_obj.background_trans,
)
)
else:
binsize = 32000
acoor = np.linspace(start, end, int((end - start) / 32000) + 1)[:-1]
bcoor = np.linspace(start2, end2, int((end2 - start2) / 32000) + 1)[:-1]
b.append(
normmat_obj.background_cis[
(np.abs(acoor[:, None] - bcoor[None, :]) / binsize).astype(int)
]
)
if strand == "-":
b[-1] = b[-1][::-1, :]
if strand2 == "-":
b[-1] = b[-1][:, ::-1]
normmats_.append(b)
normmats_ = np.vstack([np.hstack(l) for l in normmats_])
normmats.append(normmats_)
datatuple = (sequence,)
if normmat:
datatuple = datatuple + (normmats,)
if has_target:
datatuple = datatuple + (targets,)
return datatuple
def process_region(
mchr,
mstart,
mend,
genome,
file=None,
custom_models=None,
target=True,
show_genes=True,
show_tracks=False,
window_radius=16000000,
padding_chr="chr1",
model_labels=None,
use_cuda=True,
):
"""
Generate multiscale genome interaction predictions for
the specified region.