-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy path31_depth_analysis.py
More file actions
2492 lines (2124 loc) · 85.1 KB
/
Copy path31_depth_analysis.py
File metadata and controls
2492 lines (2124 loc) · 85.1 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
import os
import sys
sys.path.append(os.path.dirname(os.path.abspath(__file__)))
from skype_utils import *
from circos_plotting import render_total_coverage_circos
from skype_vcf_writer import write_vcf_record_with_fallback
from nclose_tracking import (
bnd_event_keys,
bed_visible_ecdna_indices_across_stages,
calculate_event_weights,
compressed_bnd_event_keys,
count_ecdna_circuit_events,
ecdna_circuit_event_keys,
format_nclose_ids,
load_event_catalog,
load_filter_status,
load_path_usage,
nclose_event_id_by_key,
reconcile_filter_status_catalog,
replace_catalog_ecdna_events,
save_filter_status,
save_path_usage,
write_nclose_report,
)
import numpy as np
import pandas as pd
import pickle as pkl
import csv
import ast
import h5py
import logging
import argparse
import collections
import scipy.stats
import vcfpy
import glob
import re
from scipy.signal import butter, filtfilt
from collections import defaultdict
from collections import Counter
# logging 설정(레벨/포맷)은 skype_utils 에서 중앙 관리한다 (LOG_LEVEL).
logging.info("31_depth_analysis start")
BREAKEND_REMARKABLE_CN_RATIO = 0.05
TELOMERE_REMARKABLE_CN_RATIO = 0.05
VCF_FILTER_DEPTH_N = 0.1
SKYPE_VCF_SOURCE = "SKYPE"
SKYPE_VCF_POSTPROCESSED_SOURCE = "SKYPE post-processed input VCF"
SKYPE_VCF_POSTPROCESSED_SOURCE_SUFFIX = f";{SKYPE_VCF_POSTPROCESSED_SOURCE}"
RAW_TRANSLOCATION_RESULT_PKL = 'raw_translocation_result.pkl'
RAW_TRANSLOCATION_REPORT_TSV = 'raw_translocation_read_counts.tsv'
BND_TYPE = 0
CTG_IN_TYPE = 1
TEL_TYPE = 2
CTG_NAM = 0
CTG_LEN = 1
CTG_STR = 2
CTG_END = 3
CTG_DIR = 4
CHR_NAM = 5
CHR_LEN = 6
CHR_STR = 7
CHR_END = 8
CTG_MAPQ = 9
CTG_TYP = 10
CTG_STRND = 11
CTG_ENDND = 12
CTG_TELCHR = 13
CTG_TELDIR = 14
CTG_TELCON = 15
CTG_RPTCHR = 16
CTG_RPTCASE = 17
CTG_MAINFLOWDIR = 18
CTG_MAINFLOWCHR = 19
NODE_NAME = 1
CHR_CHANGE_IDX = 2
DIR_CHANGE_IDX = 3
ABS_MAX_COVERAGE_RATIO = 3
MAX_PATH_CNT = 100
DIR_FOR = 1
DIR_BAK = 0
TELOMERE_EXPANSION = 5 * K
CONJOINED_CONTIG_MINIMUM_LENGTH = 200*K
SIM_COMPARE_RAITO = 1.2
TYPE2_FLANKING_LENGTH = 5*M
TYPE2_SIM_COMPARE_RAITO = 1.5
TYPE34_BREAK_CHUKJI_LIMIT = 1*M
NCLOSE_SIM_COMPARE_RAITO = 1.2
CTG_INTYPE_CHECK_MIN_LENGTH = 100 * K
CTG_INTYPE_INSERT_MIN_SEGMENT_LENGTH = 10 * K
CTG_INTYPE_INSERT_MIN_RATIO = 0.2
def similar_check(v1, v2, ratio=TYPE2_SIM_COMPARE_RAITO):
try:
assert(v1 >= 0 and v2 >= 0)
except:
logging.error(f"Invalid values for similarity check: v1={v1}, v2={v2}")
assert(False)
mi, ma = sorted([v1, v2])
return False if mi == 0 else (ma / mi <= ratio) or ma - mi < NCLOSE_SIM_DIFF_THRESHOLD
def exist_near_bnd(chrom, inside_st, inside_nd):
# subset of df for the given chromosome
df_chr = df[df['chr'] == chrom]
def mean_depth(start, end):
"""Return mean meandepth over windows overlapping [start, end)."""
mask = (df_chr['nd'] > start) & (df_chr['st'] < end)
return df_chr.loc[mask, 'meandepth'].mean()
# for inside_st
st_depth = mean_depth(inside_st - TYPE2_FLANKING_LENGTH, inside_st)
nd_depth = mean_depth(inside_nd, inside_nd + TYPE2_FLANKING_LENGTH)
if np.isnan(st_depth) or np.isnan(nd_depth):
return True
# print(chrom, inside_st, inside_nd, not similar_check(st_depth, nd_depth))
return not similar_check(st_depth, nd_depth, NCLOSE_SIM_COMPARE_RAITO)
def import_index_path(file_path : str) -> list:
file_path_list = file_path.split('/')
key = file_path_list[-2]
cnt = int(file_path_list[-1].split('.')[0]) - 1
return path_list_dict[key][cnt][0]
def extract_groups(lst):
if not lst:
return []
result = []
seen = set()
current = lst[0]
result.append(current)
seen.add(current)
for num in lst[1:]:
if num != current:
# 새로운 숫자가 등장했는데 이미 이전에 등장한 적이 있다면 에러 처리
if num in seen:
raise ValueError(f"Error: {num}가 연속된 구간 이후에 다시 등장합니다.")
result.append(num)
seen.add(num)
current = num
return result
def find_chr_len(file_path : str) -> dict:
chr_data_file = open(file_path, "r")
chr_len = {}
for curr_data in chr_data_file:
curr_data = curr_data.split("\t")
chr_len[curr_data[0]] = int(curr_data[1])
chr_data_file.close()
return chr_len
def import_telo_data(file_path : str, chr_len : dict) -> dict :
fai_file = open(file_path, "r")
telo_data = []
for curr_data in fai_file:
temp_list = curr_data.split("\t")
int_induce_idx = [1, 2]
for i in int_induce_idx:
temp_list[i] = int(temp_list[i])
if temp_list[1]>chr_len[temp_list[0]]/2:
temp_list[1]-=TELOMERE_EXPANSION
temp_list.append('b')
else:
temp_list.append('f')
temp_list[2]+=TELOMERE_EXPANSION
telo_data.append(tuple(temp_list))
fai_file.close()
return telo_data
def distance_checker(node_a : tuple, node_b : tuple) -> int :
if max(int(node_a[CHR_STR]), int(node_b[CHR_STR])) < min(int(node_a[CHR_END]), int(node_b[CHR_END])):
return 0
else:
return min(abs(int(node_b[CHR_STR]) - int(node_a[CHR_END])), abs(int(node_b[CHR_END]) - int(node_a[CHR_STR])))
def distance_checker_tuple(node_a : tuple, node_b : tuple) -> int :
if max(int(node_a[0]), int(node_b[0])) < min(int(node_a[1]), int(node_b[1])):
return 0
else:
return min(abs(int(node_b[0]) - int(node_a[1])), abs(int(node_b[1]) - int(node_a[0])))
def chr2int(x):
chrXY2int = {'chrX' : 24, 'chrY' : 25}
if x in chrXY2int:
return chrXY2int[x]
else:
return int(x[3:])
def extract_telomere_connect_contig(telo_info_path : str) -> list:
telomere_connect_contig = []
with open(telo_info_path) as f:
for curr_data in f:
curr_data = curr_data.rstrip()
temp_list = curr_data.split("\t")
chr_info = temp_list[0]
contig_id = ast.literal_eval(temp_list[1])
telomere_connect_contig.append((chr_info, contig_id[1]))
return telomere_connect_contig
def highpass_filter(data, cutoff, fs, order=3):
"""
Butterworth high-pass filter를 이용하여 저주파 성분을 제거합니다.
Parameters:
- data: 1D array, 입력 신호 (CN 값)
- cutoff: float, 컷오프 주파수
- fs: float, 샘플링 주파수 (데이터 포인트 간 간격)
- order: int, 필터 차수
Returns:
- 필터링된 신호 (노이즈 성분 추출)
"""
nyq = 0.5 * fs # Nyquist 주파수
normal_cutoff = cutoff / nyq
b, a = butter(order, normal_cutoff, btype='high', analog=False)
return filtfilt(b, a, data)
def rebin_dataframe(df: pd.DataFrame, n: int) -> pd.DataFrame:
"""
Group rows in the DataFrame into bins spanning n consecutive units.
The unit is determined from the 'length' of the first row in each chromosome group.
For each group:
- The new start (st) is taken from the first row.
- The new end (nd) is taken from the last row in the group.
- For a complete group (n rows), values are summed.
- For an incomplete group (fewer than n rows), the new bin's length is the sum of the available lengths,
and new covsite and totaldepth are computed as the weighted average:
new_value = sum( value_i * length_i ) / sum(length_i)
- New coverage (cov) is computed as (new_covsite / new_length) * 100.
- New mean depth (meandepth) is computed as new_totaldepth / new_length.
Parameters:
df (pd.DataFrame): Input DataFrame with columns ['chr', 'st', 'nd', 'length',
'covsite', 'totaldepth', 'cov', 'meandepth'].
n (int): Number of consecutive units (rows) to combine into each bin.
Returns:
pd.DataFrame: New DataFrame with binned rows.
"""
new_rows = []
# Process each chromosome separately.
for chrom, sub_df in df.groupby('chr'):
# Sort rows by starting position.
sub_df = sub_df.sort_values('st').reset_index(drop=True)
# Group rows in chunks of size n.
for i in range(0, len(sub_df), n):
chunk = sub_df.iloc[i:i+n]
new_st = chunk['st'].iloc[0]
new_nd = chunk['nd'].iloc[-1]
# Use the actual sum of lengths in the chunk.
sum_length = chunk['length'].sum()
new_meandepth = np.sum(chunk['totaldepth']) / sum_length
new_rows.append({
'chr': chrom,
'st': new_st,
'nd': new_nd,
'meandepth': new_meandepth
})
return pd.DataFrame(new_rows)
def rebin_dataframe_B(df: pd.DataFrame, n: int) -> np.array:
new_rows = dict()
# Process each chromosome separately.
for chrom, sub_df in df.groupby('chr'):
chr_mean_list = []
sub_df = sub_df.sort_values('st').reset_index(drop=True)
# Group rows in chunks of size n.
for i in range(0, len(sub_df), n):
chunk = sub_df.iloc[i:i+n]
new_st = chunk['st'].iloc[0]
new_nd = chunk['nd'].iloc[-1]
# Use the actual sum of lengths in the chunk.
sum_length = chunk['length'].sum()
new_meandepth = np.sum(chunk['totaldepth']) / sum_length
chr_mean_list.extend([new_meandepth for _ in range(len(chunk))])
new_rows[chrom] = np.asarray(chr_mean_list)
ans_B = []
for c in chr_order_list:
ans_B.append(new_rows[c])
return np.hstack(ans_B)
def import_data2(file_path : str) -> list :
paf_file = open(file_path, "r")
contig_data = []
for curr_contig in paf_file:
temp_list = curr_contig.split("\t")
int_induce_idx = [
CTG_LEN, CTG_STR, CTG_END, \
CHR_LEN, CHR_STR, CHR_END, \
CTG_MAPQ, CTG_TYP, CTG_STRND, CTG_ENDND,]
for i in int_induce_idx:
temp_list[i] = int(temp_list[i])
contig_data.append(tuple(temp_list))
paf_file.close()
return contig_data
def import_path_paf_rows(file_path : str) -> list:
rows = []
with open(file_path, "r") as paf_file:
for curr_contig in paf_file:
curr_contig = curr_contig.rstrip()
if not curr_contig:
continue
temp_list = curr_contig.split("\t")
int_induce_idx = [
CTG_LEN, CTG_STR, CTG_END,
CHR_LEN, CHR_STR, CHR_END,
CTG_MAPQ,
]
for i in int_induce_idx:
temp_list[i] = int(temp_list[i])
rows.append(tuple(temp_list))
return rows
def import_bed(bed_path : str) -> dict:
bed_data_file = open(bed_path, "r")
chr_len = collections.defaultdict(list)
for curr_data in bed_data_file:
curr_data = curr_data.split("\t")
chr_len[curr_data[0]].append((int(curr_data[1]), int(curr_data[2])))
bed_data_file.close()
return chr_len
def inclusive_checker(tuple_a : tuple, tuple_b : tuple) -> bool :
if int(tuple_a[0]) <= int(tuple_b[0]) and int(tuple_b[1]) <= int(tuple_a[1]):
return True
else:
return False
def bnd_alt(t, mate_chr, mate_pos, form):
"""
Build ALT per the 4 canonical breakend forms:
"t[p[", "t]p]", "]p]t", "[p[t"
"""
p = f"{mate_chr}:{mate_pos}"
if form == "t[p[":
return f"{t}[{p}["
if form == "t]p]":
return f"{t}]{p}]"
if form == "]p]t":
return f"]{p}]{t}"
if form == "[p[t":
return f"[{p}[{t}"
assert(False)
def choose_alt_forms(dir_a, dir_b):
"""
Map SKYPE path directions (dir_a, dir_b) to a VCF 4.3 breakend ALT pair.
Convention: a = arm1 (junction at its contig-3' end), b = arm2 (junction at its contig-5' end).
- dir_a decides whether a's retained sequence is left ('+': t-prefix) or right ('-': t-suffix).
- dir_b decides whether the joined arm2 piece extends right of p forward ('+': '[') or
is the reverse-complement extending left of p ('-': ']').
Verified against VCFv4.3 §5.4 (Fig.1 all-orientations, Fig.7 RR0 transloc, Fig.8 INV0 inversion);
valid reciprocal mate pairs are t[p[ <-> ]p]t , t]p] <-> t]p] , [p[t <-> [p[t .
"""
if dir_a == '+' and dir_b == '+':
return ("t[p[", "]p]t")
if dir_a == '+' and dir_b == '-':
return ("t]p]", "t]p]")
if dir_a == '-' and dir_b == '+':
return ("[p[t", "[p[t")
if dir_a == '-' and dir_b == '-':
return ("]p]t", "t[p[")
assert(False)
def make_strands(dir_a, dir_b):
"""
Compose VCF breakend STRANDS from SKYPE path directions.
SKYPE nclose notation records traversal as A_dir => B_dir. VCF STRANDS
records the two breakpoint sides that are newly adjacent. The A exit side
is A_dir, while the B entry side is the opposite of B_dir.
"""
a = dir_a if dir_a in ('+', '-') else '.'
b = invert_strand(dir_b) if dir_b in ('+', '-') else '.'
return f"{a}{b}"
def build_vcf_header(contig_lengths):
header = vcfpy.Header(lines=[
vcfpy.HeaderLine("fileformat", "VCFv4.3"),
vcfpy.HeaderLine("source", SKYPE_VCF_SOURCE),
])
for alt_id, description in (
("BND", "Breakend"),
("INV", "Inversion"),
("DEL", "Deletion"),
("DUP", "Duplication"),
):
header.add_line(vcfpy.AltAlleleHeaderLine.from_mapping(
collections.OrderedDict([
("ID", alt_id),
("Description", description),
])
))
for info_id, number, type_, description in (
("SVTYPE", 1, "String", "Type of structural variant"),
("END", 1, "Integer", "End position of SV"),
("SVLEN", 1, "Integer", "Length of the SV"),
("WEIGHT", 1, "Float", "Depth for breakend"),
("CTG_NAME", 1, "String", "Name of contig for supporting variant"),
("SVCLASS", 1, "String", "SKYPE event class"),
("STRANDS", 1, "String", "Breakpoint strandedness"),
("MATEID", 1, "String", "ID of mate breakend"),
("MERGE_MATEID", 1, "String", "ID of merged breakend"),
):
header.add_info_line(collections.OrderedDict([
("ID", info_id),
("Number", number),
("Type", type_),
("Description", description),
]))
for chrom, length in contig_lengths.items():
header.add_contig_line(collections.OrderedDict([
("ID", chrom),
("length", int(length)),
]))
return header
def vcf_filter_values(filter_str):
if filter_str in (None, "", "."):
return []
return str(filter_str).split(";")
def write_bnd_vcf_pair(
writer,
sv_id_base,
chr_a,
pos_a,
dir_a,
chr_b,
pos_b,
dir_b,
weight_N,
ctg_name,
quality=60,
filter_str='.',
merge_mate_ids=None,
):
pos_a = max(1, int(pos_a))
pos_b = max(1, int(pos_b))
strands = make_strands(dir_a, dir_b)
form_a, form_b = choose_alt_forms(dir_a, dir_b)
sv_id_a = f"{sv_id_base}_1"
sv_id_b = f"{sv_id_base}_2"
ref = "N"
alt_a = bnd_alt(ref, chr_b, pos_b, form_a)
alt_b = bnd_alt(ref, chr_a, pos_a, form_b)
for chrom, pos, sv_id, alt, mate_id in (
(chr_a, pos_a, sv_id_a, alt_a, sv_id_b),
(chr_b, pos_b, sv_id_b, alt_b, sv_id_a),
):
info = collections.OrderedDict([
("SVTYPE", "BND"),
("WEIGHT", round(weight_N, 2)),
("CTG_NAME", ctg_name),
("STRANDS", strands),
("MATEID", mate_id),
])
if merge_mate_ids:
info["MERGE_MATEID"] = ",".join(merge_mate_ids)
writer.write_record(vcfpy.Record(
CHROM=chrom,
POS=pos,
ID=[sv_id],
REF=ref,
ALT=[vcfpy.Substitution(type_="BND", value=alt)],
QUAL=quality,
FILTER=vcf_filter_values(filter_str),
INFO=info,
))
def write_symbolic_vcf_record(
writer,
chrom,
pos,
sv_id,
svtype,
end,
svlen,
weight,
ctg_name,
svclass=None,
):
info = collections.OrderedDict([
("SVTYPE", svtype),
("END", int(end)),
("SVLEN", int(svlen)),
("WEIGHT", round(weight, 2)),
("CTG_NAME", ctg_name),
])
if svclass is not None:
info["SVCLASS"] = svclass
writer.write_record(vcfpy.Record(
CHROM=chrom,
POS=int(pos),
ID=[sv_id],
REF="N",
ALT=[vcfpy.SymbolicAllele(svtype)],
QUAL=60,
FILTER=[],
INFO=info,
))
def invert_strand(strand):
return '-' if strand == '+' else '+'
def make_breakend_endpoint(chrom, pos, strand):
return {
'chrom': chrom,
'pos': int(pos),
'strand': strand,
}
def infer_path_strand_from_paf_rows(rows : list, idx : int) -> str:
chrom = rows[idx][CHR_NAM]
curr_mid = (rows[idx][CHR_STR] + rows[idx][CHR_END]) // 2
if idx + 1 < len(rows) and rows[idx + 1][CHR_NAM] == chrom:
next_mid = (rows[idx + 1][CHR_STR] + rows[idx + 1][CHR_END]) // 2
if next_mid != curr_mid:
return '+' if next_mid > curr_mid else '-'
if idx > 0 and rows[idx - 1][CHR_NAM] == chrom:
prev_mid = (rows[idx - 1][CHR_STR] + rows[idx - 1][CHR_END]) // 2
if curr_mid != prev_mid:
return '+' if curr_mid > prev_mid else '-'
return rows[idx][CTG_DIR] if rows[idx][CTG_DIR] in {'+', '-'} else '+'
def paf_row_entry_endpoint(row, strand):
pos = row[CHR_STR] if strand == '+' else row[CHR_END]
return make_breakend_endpoint(row[CHR_NAM], pos, strand)
def paf_row_exit_endpoint(row, strand):
pos = row[CHR_END] if strand == '+' else row[CHR_STR]
return make_breakend_endpoint(row[CHR_NAM], pos, strand)
def append_ctg_intype_interrupt_segment(
segments : list,
row,
strand : str,
length : int,
row_idx : int,
):
if length <= 0:
return
chrom = row[CHR_NAM]
if segments and segments[-1]['chrom'] == chrom:
segments[-1]['exit'] = paf_row_exit_endpoint(row, strand)
segments[-1]['length'] += length
segments[-1]['last_idx'] = row_idx
else:
segments.append({
'chrom': chrom,
'strand': strand,
'entry': paf_row_entry_endpoint(row, strand),
'exit': paf_row_exit_endpoint(row, strand),
'length': length,
'first_idx': row_idx,
'last_idx': row_idx,
})
def nearest_different_chrom_row(rows : list, row_idx : int, step : int, chrom : str):
idx = row_idx + step
while 0 <= idx < len(rows):
if rows[idx][CHR_NAM] != chrom:
return idx
idx += step
return None
def attach_ctg_intype_interrupt_flanks(segments : list, rows : list):
for segment in segments:
left_idx = nearest_different_chrom_row(
rows, segment['first_idx'], -1, segment['chrom']
)
if left_idx is not None:
left_strand = infer_path_strand_from_paf_rows(rows, left_idx)
segment['left_flank_exit'] = paf_row_exit_endpoint(rows[left_idx], left_strand)
right_idx = nearest_different_chrom_row(
rows, segment['last_idx'], 1, segment['chrom']
)
if right_idx is not None:
right_strand = infer_path_strand_from_paf_rows(rows, right_idx)
segment['right_flank_entry'] = paf_row_entry_endpoint(rows[right_idx], right_strand)
def get_ctg_intype_interrupt_segments(key_int : int, endpoint_chroms : set) -> list:
"""
Coordinate-bearing mirror of 30_virtual_sky.get_ctg_intype_interrupt_pieces().
Keep the same chromosome selection/filtering; only attach entry/exit coords.
"""
paf_loc = f"{output_folder}/{key_int}.paf"
if not os.path.isfile(paf_loc):
return []
rows = import_path_paf_rows(paf_loc)
if not rows:
return []
row_lengths = [abs(row[CHR_END] - row[CHR_STR]) for row in rows]
total_length = sum(row_lengths)
if total_length <= CTG_INTYPE_CHECK_MIN_LENGTH:
return []
foreign_chrom_lengths = Counter()
for row, length in zip(rows, row_lengths):
chrom = row[CHR_NAM]
if chrom not in endpoint_chroms:
foreign_chrom_lengths[chrom] += length
interrupt_chroms = {
chrom for chrom, length in foreign_chrom_lengths.items()
if length / total_length >= CTG_INTYPE_INSERT_MIN_RATIO
}
if not interrupt_chroms:
return []
segments = []
for i, (row, length) in enumerate(zip(rows, row_lengths)):
chrom = row[CHR_NAM]
if chrom not in interrupt_chroms:
continue
if length < CTG_INTYPE_INSERT_MIN_SEGMENT_LENGTH:
continue
strand = infer_path_strand_from_paf_rows(rows, i)
append_ctg_intype_interrupt_segment(segments, row, strand, length, i)
attach_ctg_intype_interrupt_flanks(segments, rows)
return segments
def append_chrom_change_break(ordered_breaks : list, left : dict, right : dict):
if left['chrom'] != right['chrom']:
ordered_breaks.append((left, right))
def get_karyotype_next_state(curr_node, prev_node_name : int, curr_node_name : int):
if curr_node_name > prev_node_name:
next_incr = curr_node[CTG_DIR]
else:
next_incr = '-' if curr_node[CTG_DIR] == '+' else '+'
next_ref = curr_node[CHR_STR] if next_incr == '+' else curr_node[CHR_END]
return [curr_node[CHR_NAM], next_incr], next_ref
def build_ctg_intype_split_bnds(weights, min_weight):
split_weight_by_key = defaultdict(float)
split_parent_weight = defaultdict(float)
for path_idx, (paf_loc, key_int_list) in enumerate(paf_ans_list):
if path_idx >= len(weights):
break
path_weight = float(weights[path_idx])
if path_weight <= min_weight:
continue
path = import_index_path(paf_loc)
if len(path[0]) < 4:
path[0] = tuple([0] + list(path[0]))
if len(path[-1]) < 4:
path[-1] = tuple([0] + list(path[-1]))
ctg_intype_key_by_edge = {}
for key_int in key_int_list:
key_type, key_value = int2key[key_int]
if key_type == CTG_IN_TYPE:
ctg_intype_key_by_edge[key_value] = key_int
curr_incr = '+' if path[0][NODE_NAME][-1] == 'f' else '-'
first_real_node = contig_data[path[1][NODE_NAME]]
curr_chr = [first_real_node[CHR_NAM], curr_incr]
curr_ref = first_real_node[CHR_STR] if curr_incr == '+' else first_real_node[CHR_END]
for i in range(1, len(path) - 1):
prev_node_name = path[i - 1][1]
curr_node_name = path[i][1]
if not isinstance(prev_node_name, int) or not isinstance(curr_node_name, int):
continue
last_node = contig_data[prev_node_name]
curr_node = contig_data[curr_node_name]
edge_key = (
(path[i - 1][0], prev_node_name),
(path[i][0], curr_node_name),
)
key_int = ctg_intype_key_by_edge.get(edge_key)
interrupt_segments = []
if key_int is not None:
endpoint_chroms = {last_node[CHR_NAM], curr_node[CHR_NAM]}
interrupt_segments = get_ctg_intype_interrupt_segments(key_int, endpoint_chroms)
if not (
path[i][CHR_CHANGE_IDX] > path[i - 1][CHR_CHANGE_IDX]
or path[i][DIR_CHANGE_IDX] > path[i - 1][DIR_CHANGE_IDX]
or interrupt_segments
):
continue
if interrupt_segments:
parent_nclose = tuple(sorted([prev_node_name, curr_node_name]))
parent_nclose_idx = nclose2idx.get(parent_nclose)
if parent_nclose_idx is not None:
left_pos = last_node[CHR_END] if curr_incr == '+' else last_node[CHR_STR]
left_endpoint = interrupt_segments[0].get('left_flank_exit')
if left_endpoint is None or left_endpoint['chrom'] != curr_chr[0]:
left_endpoint = make_breakend_endpoint(curr_chr[0], left_pos, curr_chr[1])
next_chr, _next_ref = get_karyotype_next_state(
curr_node, prev_node_name, curr_node_name
)
right_pos = curr_node[CHR_STR] if next_chr[1] == '+' else curr_node[CHR_END]
right_endpoint = interrupt_segments[-1].get('right_flank_entry')
if right_endpoint is None or right_endpoint['chrom'] != next_chr[0]:
right_endpoint = make_breakend_endpoint(next_chr[0], right_pos, next_chr[1])
ordered_breaks = []
append_chrom_change_break(
ordered_breaks, left_endpoint, interrupt_segments[0]['entry']
)
for segment_idx in range(len(interrupt_segments) - 1):
append_chrom_change_break(
ordered_breaks,
interrupt_segments[segment_idx]['exit'],
interrupt_segments[segment_idx + 1]['entry'],
)
append_chrom_change_break(
ordered_breaks, interrupt_segments[-1]['exit'], right_endpoint
)
if ordered_breaks:
split_parent_weight[parent_nclose_idx] += path_weight
ctg_name = last_node[CTG_NAM]
for split_idx, (left, right) in enumerate(ordered_breaks, start=1):
split_key = (
parent_nclose_idx,
split_idx,
left['chrom'],
int(left['pos']),
left['strand'],
right['chrom'],
int(right['pos']),
right['strand'],
ctg_name,
)
split_weight_by_key[split_key] += path_weight
curr_chr, curr_ref = get_karyotype_next_state(
curr_node, prev_node_name, curr_node_name
)
return split_weight_by_key, split_parent_weight
def parse_optional_float(value):
if value is None or value == '*':
return None
try:
parsed = float(value)
except (TypeError, ValueError):
return None
return parsed if np.isfinite(parsed) else None
def load_raw_translocation_report(prefix):
report_path = f'{prefix}/{RAW_TRANSLOCATION_REPORT_TSV}'
if not os.path.isfile(report_path):
return {}
rows_by_pair = {}
with open(report_path, 'r') as f:
for row in csv.DictReader(f, delimiter='\t'):
try:
pair_id = int(row['pair_id'])
except (KeyError, TypeError, ValueError):
continue
rows_by_pair[pair_id] = row
return rows_by_pair
def finite_mean(values):
finite_values = [
float(value) for value in values
if value is not None and np.isfinite(value)
]
if not finite_values:
return None
return sum(finite_values) / len(finite_values)
def estimate_raw_virtual_inv_depth(record, report_row=None):
estimate = record.get('depth_weighted_nclose_estimate', {})
expected_depth = parse_optional_float(estimate.get('weighted_expected_nclose_depth'))
if expected_depth is not None:
return expected_depth
if report_row is not None:
expected_depth = parse_optional_float(report_row.get('weighted_expected_nclose_depth'))
if expected_depth is not None:
return expected_depth
counts = record.get('read_counts', {})
point_depth = record.get('point_500k_depth', {})
side_inputs = [
(point_depth.get('point_a', {}), counts.get('d1', 0), counts.get('d2', 0)),
(point_depth.get('point_b', {}), counts.get('d4', 0), counts.get('d3', 0)),
]
weighted_sum = 0.0
weight_sum = 0
for depth_pair, nclose_count, point_count in side_inputs:
point_mean = finite_mean([depth_pair.get('front'), depth_pair.get('back')])
if point_mean is None:
continue
try:
weight = int(nclose_count) + int(point_count)
nclose_count = int(nclose_count)
except (TypeError, ValueError):
continue
if weight <= 0:
continue
weighted_sum += point_mean * (nclose_count / weight) * weight
weight_sum += weight
if weight_sum == 0:
return None
return weighted_sum / weight_sum
def record_depth_is_balanced(record, report_row=None):
if 'depth_balanced_translocation' in record:
return bool(record.get('depth_balanced_translocation'))
return report_row is not None
def raw_false_value(value):
return value is False or value == 0 or value == 'False' or value == 'false'
def record_has_both_point_spans(record):
raw_no_span = record.get('raw_point_no_spanning')
if isinstance(raw_no_span, dict):
return raw_false_value(raw_no_span.get('point_a')) and raw_false_value(raw_no_span.get('point_b'))
side_records = record.get('side_records', [])
if len(side_records) < 2:
return False
side_flags = [
side.get('raw_point_no_spanning', side.get('no_spanning_rawread'))
for side in side_records[:2]
]
return raw_false_value(side_flags[0]) and raw_false_value(side_flags[1])
def raw_virtual_inv_vafs(record, report_row=None):
estimate = record.get('depth_weighted_nclose_estimate', {})
point_a_vaf = parse_optional_float(estimate.get('point_a_nclose_vaf'))
point_b_vaf = parse_optional_float(estimate.get('point_b_nclose_vaf'))
if point_a_vaf is not None and point_b_vaf is not None:
return point_a_vaf, point_b_vaf
if report_row is not None:
if point_a_vaf is None:
point_a_vaf = parse_optional_float(report_row.get('point_a_nclose_vaf'))
if point_b_vaf is None:
point_b_vaf = parse_optional_float(report_row.get('point_b_nclose_vaf'))
if point_a_vaf is not None and point_b_vaf is not None:
return point_a_vaf, point_b_vaf
counts = record.get('read_counts', {})
try:
d1 = int(counts.get('d1', 0))
d2 = int(counts.get('d2', 0))
d3 = int(counts.get('d3', 0))
d4 = int(counts.get('d4', 0))
except (TypeError, ValueError):
return point_a_vaf, point_b_vaf
if point_a_vaf is None and d1 + d2 > 0:
point_a_vaf = d1 / (d1 + d2)
if point_b_vaf is None and d4 + d3 > 0:
point_b_vaf = d4 / (d4 + d3)
return point_a_vaf, point_b_vaf
def record_passes_virtual_inv_vaf(record, report_row=None, min_vaf=RAW_VIRTUAL_INV_MIN_VAF):
point_a_vaf, point_b_vaf = raw_virtual_inv_vafs(record, report_row)
if point_a_vaf is None or point_b_vaf is None:
return False
return point_a_vaf > min_vaf and point_b_vaf > min_vaf
def directed_entry_coord(endpoint):
return int(endpoint['ref_st']) if endpoint['dir'] == '+' else int(endpoint['ref_nd'])
def record_display_points(record, report_row=None):
if report_row is not None:
chrom_a = report_row.get('chrom_a')
chrom_b = report_row.get('chrom_b')
try:
point_a = int(report_row.get('point_a'))
point_b = int(report_row.get('point_b'))
except (TypeError, ValueError):
chrom_a = chrom_b = None
else:
if chrom_a and chrom_b:
return chrom_a, point_a, chrom_b, point_b
chrom_pair = record.get('chrom_pair', ('*', '*'))
layout_a = record.get('layout_a', {})
layout_b = record.get('layout_b', {})
endpoints_a = list(layout_a.get('endpoints', ()))
endpoints_b = list(layout_b.get('endpoints', ()))
side_records = record.get('side_records', [])
chrom_a = chrom_pair[0] if len(chrom_pair) > 0 else '*'
chrom_b = chrom_pair[1] if len(chrom_pair) > 1 else '*'
coord_a = None
coord_b = None
if len(endpoints_b) > 0:
coord_a = directed_entry_coord(endpoints_b[0])
elif len(side_records) > 0:
coord_a = int(side_records[0]['inner_st'])
if len(endpoints_a) > 1:
coord_b = directed_entry_coord(endpoints_a[1])
elif len(side_records) > 1:
coord_b = int(side_records[1]['inner_nd'])
return chrom_a, coord_a, chrom_b, coord_b
def point_to_chrom_end_interval(chrom, point, side, contig_lengths):
chrom_len = int(contig_lengths[chrom])
point = max(0, min(int(point), chrom_len))
if side == 'left':
st, nd = 0, point
else:
st, nd = point, chrom_len
if nd <= st:
return None
return st, nd
def layout_side(record, layout_name, side_idx, default='right'):
sides = record.get(layout_name, {}).get('sides', ())
if side_idx < len(sides):
return sides[side_idx]
return default
def read_component_ref_intervals(prefix, key_int, cache):
if key_int in cache:
return cache[key_int]
by_chrom = defaultdict(list)
paf_path = f'{prefix}/21_pat_depth/{key_int}.paf'
if not os.path.isfile(paf_path):
cache[key_int] = by_chrom
return by_chrom
with open(paf_path, 'r') as f:
for line in f:
if not line.strip():
continue
fields = line.rstrip('\n').split('\t')
if len(fields) <= CHR_END:
continue
try:
st = int(fields[CHR_STR])
nd = int(fields[CHR_END])
except ValueError:
continue