-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmake_repeat_report.R
More file actions
executable file
·1679 lines (1522 loc) · 73.4 KB
/
Copy pathmake_repeat_report.R
File metadata and controls
executable file
·1679 lines (1522 loc) · 73.4 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
#!/usr/bin/env Rscript
# make_repeat_report.R
# Generates a standalone interactive HTML repeat annotation report.
# Usage: make_repeat_report.R --output_dir <dir> [options]
suppressPackageStartupMessages({
library(optparse)
library(rtracklayer)
library(IRanges)
library(GenomicRanges)
library(jsonlite)
})
source(file.path(dirname(sub("^--file=", "",
grep("^--file=", commandArgs(FALSE), value = TRUE)[1])), "classification.R"))
# ═══════════════════════════════════════════════════════════════════════════
# A. ARGUMENT PARSING
# ═══════════════════════════════════════════════════════════════════════════
option_list <- list(
make_option("--output_dir", type = "character", help = "Pipeline output directory [required]"),
make_option("--bin_width", type = "integer", default = 100000L,
help = "Density track bin width in bp [default %default]"),
make_option("--min_len_chart", type = "integer", default = 500000L,
help = "Min seq length for own bar in composition chart [default %default]"),
make_option("--min_len_tracks", type = "integer", default = 1000000L,
help = "Min seq length for density track panel [default %default]"),
make_option("--max_tracks", type = "integer", default = 50L,
help = "Max sequences in density track dropdown [default %default]"),
make_option("--top_sat_clusters", type = "integer", default = 10L,
help = "Top N satellite clusters shown in section 5 [default %default]")
)
opt <- parse_args(OptionParser(option_list = option_list))
if (is.null(opt$output_dir)) stop("--output_dir is required")
outdir <- normalizePath(opt$output_dir, mustWork = TRUE)
`%||%` <- function(a, b) if (!is.null(a) && length(a) > 0 && !is.na(a[1])) a else b
# Build one report section defensively. On ANY error, log a WARNING and return
# NULL so the caller renders a "not generated" placeholder (via %||% in
# assemble_html) instead of aborting the whole report — one bad panel (e.g. a
# density plot hitting a large-genome edge case) must not lose the rest of the
# report, nor fail the pipeline. `expr` is a lazy promise: it is only evaluated
# inside the tryCatch, so its errors are caught here.
safe_build <- function(label, expr) {
tryCatch(expr, error = function(e) {
message(sprintf(
"WARNING: section '%s' not generated (%s) — placeholder shown, report continues.",
label, conditionMessage(e)))
NULL
})
}
# In-report placeholder for a section that produced no chart — either because
# there was no data for it or because safe_build() caught an error. Rendered as
# a visible amber note so a missing panel is obvious in the HTML.
not_generated_html <- function(what)
sprintf(paste0('<p style="padding:10px 12px;border-left:4px solid #e0a800;',
'background:#fff8e1;color:#000;margin:8px 0;border-radius:3px">',
'⚠ %s was <b>not generated</b> (no data, or an error while ',
'building it — see <code>logs/make_repeat_report.err</code>). ',
'The rest of the report is unaffected.</p>'),
what)
# ═══════════════════════════════════════════════════════════════════════════
# B. DATA LOADING
# ═══════════════════════════════════════════════════════════════════════════
# ── B1. Genome sequence info from FAI ──────────────────────────────────────
load_genome_info <- function(outdir) {
fai <- file.path(outdir, "genome_cleaned.fasta.fai")
if (!file.exists(fai)) stop("FAI file not found: ", fai)
df <- read.table(fai, header = FALSE, sep = "\t",
col.names = c("seqname", "length", "offset", "linebases", "linewidth"))
df[, c("seqname", "length")]
}
# ── B2. Repeat composition from summary_statistics.csv ────────────────────
load_composition <- function(outdir) {
f <- file.path(outdir, "summary_statistics.csv")
df <- read.table(f, header = TRUE, sep = "\t", quote = '"', check.names = FALSE)
colnames(df) <- c("type", "bp", "pct")
df$bp <- as.numeric(df$bp)
df$pct <- as.numeric(df$pct)
df <- df[!is.na(df$bp), ]
df
}
# ── B2b. Run provenance from JSON ─────────────────────────────────────────
# Read run_provenance.json (written by run_pipeline.py + commits 3+4 of
# the versioning rollout). Returns NULL if absent — the footer will
# render an "unknown version" placeholder instead.
load_provenance <- function(outdir) {
f <- file.path(outdir, "run_provenance.json")
if (!file.exists(f)) return(NULL)
if (!requireNamespace("jsonlite", quietly = TRUE)) return(NULL)
tryCatch(jsonlite::fromJSON(f, simplifyVector = TRUE),
error = function(e) NULL)
}
# ── B3. DANTE_LTR stats from GFF3 ─────────────────────────────────────────
# Count only *complete* LTR-RTs for the "Complete TEs" column of the
# classification table. DANTE_LTR labels the element's completeness via
# its Rank attribute:
# DL, DLT, DLP, DLTP → complete (domains + LTRs + optional PBS / TSD)
# D → partial — an LTR-RT region with protein
# domains identified but no reconstructed LTR
# sequences; the element boundaries are therefore
# unknown.
# Including Rank=D over-counts by ~3x on a typical plant genome (most
# of the D-rank calls are fragmented / solo-LTR-less copies without
# reliable coordinates).
DANTE_LTR_COMPLETE_RANKS <- c("DL", "DLT", "DLP", "DLTP")
load_dante_ltr_stats <- function(outdir) {
gff <- file.path(outdir, "DANTE_LTR", "DANTE_LTR.gff3")
if (!file.exists(gff) || file.size(gff) == 0) return(NULL)
gr <- tryCatch(import(gff), error = function(e) NULL)
if (is.null(gr) || length(gr) == 0) return(NULL)
te <- gr[gr$type == "transposable_element"]
if (length(te) == 0) return(NULL)
if (!is.null(te$Rank)) {
te <- te[as.character(te$Rank) %in% DANTE_LTR_COMPLETE_RANKS]
}
if (length(te) == 0) return(NULL)
cls <- te$Final_Classification
if (is.null(cls)) cls <- te$Name
cls_path <- canonicalise(cls, source = "DANTE_LTR", validate = FALSE)
tmp_df <- data.frame(path = cls_path, count = 1L, bp = as.numeric(width(te)))
agg <- aggregate(cbind(count, bp) ~ path, data = tmp_df, FUN = sum)
agg
}
# ── B4. DANTE_TIR stats from summary txt ──────────────────────────────────
load_dante_tir_stats <- function(outdir) {
f <- file.path(outdir, "DANTE_TIR", "TIR_classification_summary.txt")
if (!file.exists(f) || file.size(f) == 0) return(NULL)
df <- read.table(f, header = TRUE, sep = "\t", check.names = FALSE)
colnames(df) <- c("raw_name", "count")
df$path <- canonicalise(df$raw_name, source = "DANTE_TIR", validate = FALSE)
df[, c("path", "count")]
}
# ── B5. DANTE_LINE stats from GFF3 ────────────────────────────────────────
load_dante_line_stats <- function(outdir) {
gff <- file.path(outdir, "DANTE_LINE", "DANTE_LINE.gff3")
if (!file.exists(gff) || file.size(gff) == 0) return(list(regions = 0, bp = 0))
gr <- tryCatch(import(gff), error = function(e) NULL)
if (is.null(gr) || length(gr) == 0) return(list(regions = 0, bp = 0))
le <- gr[gr$type == "LINE_element"]
if (length(le) == 0) return(list(regions = 0, bp = 0))
list(regions = length(le), bp = sum(as.numeric(width(le))))
}
# ── B6. Discover BigWig files ──────────────────────────────────────────────
discover_bw_files <- function(outdir, bin_width) {
suffix <- if (bin_width == 100000) "_100k.bw" else "_10k.bw"
bw_dir_rm <- file.path(outdir, "Repeat_density_by_class_bigwig",
if (bin_width == 100000) "100k" else "10k")
bw_dir_tc <- file.path(outdir, "Tandem_repeats_TideCluster_split_by_family_bigwig",
if (bin_width == 100000) "100k" else "10k")
tc_agg <- file.path(outdir,
paste0("Tandem_repeats_TideCluster", suffix))
find_bw <- function(dir, pattern) {
if (!dir.exists(dir)) return(character(0))
list.files(dir, pattern = pattern, full.names = TRUE)
}
rm_files <- find_bw(bw_dir_rm, "[.]bw$")
names(rm_files) <- sub(paste0(suffix, "$"), "", basename(rm_files))
tc_cluster_files <- find_bw(bw_dir_tc, "[.]bw$")
names(tc_cluster_files) <- sub(paste0(suffix, "$"), "", basename(tc_cluster_files))
list(
rm = rm_files,
tc_agg = if (file.exists(tc_agg)) tc_agg else NULL,
tc_cluster = tc_cluster_files
)
}
# ═══════════════════════════════════════════════════════════════════════════
# C. DATA PROCESSING
# ═══════════════════════════════════════════════════════════════════════════
# ── C1. Apply sequence length thresholds ──────────────────────────────────
apply_seq_thresholds <- function(genome_info, min_len_chart, min_len_tracks, max_tracks) {
gi <- genome_info[order(-genome_info$length), ]
list(
chart_seqs = gi$seqname[gi$length >= min_len_chart],
track_seqs = head(gi$seqname[gi$length >= min_len_tracks], max_tracks),
n_other = sum(gi$length < min_len_chart),
other_bp = sum(gi$length[gi$length < min_len_chart])
)
}
# Fixed top-level category order for the classification table and the sunburst
# (we no longer reorder categories by content, which was confusing). Anything
# not listed is appended after these, ordered by size. rDNA_45S/rDNA_5S are kept
# for the pre-rDNA-restructure layout; once rDNA is nested they collapse to the
# single "rDNA" top node.
CATEGORY_ORDER <- c("Class_I", "Class_II", "rDNA", "rDNA_45S", "rDNA_5S",
"Tandem_repeats", "Simple_repeat", "Low_complexity", "Unknown")
# For the report's table and pie ONLY, collapse rDNA sub-array subunits
# (18S/25S/5.8S/ITS/IGS/5S) into their parent family (rDNA/45S_rDNA,
# rDNA/5S_rDNA). The subunits are structural parts of one rDNA monomer, not
# sub-families, so the composition view stops at the family level (like not
# breaking Ty1_copia into "LTR"/"GAG"/... parts). Total bp is preserved; the
# data outputs (GFF3s, density BigWigs) keep the full subunit detail.
collapse_rdna_subunits <- function(comp) {
if (nrow(comp) == 0) return(comp)
for (fam in c("rDNA/45S_rDNA", "rDNA/5S_rDNA")) {
desc <- startsWith(comp$type, paste0(fam, "/"))
if (!any(desc)) next
add_bp <- sum(comp$bp[desc]); add_pct <- sum(comp$pct[desc])
comp <- comp[!desc, , drop = FALSE] # drop subunit rows
if (fam %in% comp$type) { # fold into the family row
comp$bp[comp$type == fam] <- comp$bp[comp$type == fam] + add_bp
comp$pct[comp$type == fam] <- comp$pct[comp$type == fam] + add_pct
} else { # family only existed as a prefix
comp <- rbind(comp, data.frame(type = fam, bp = add_bp, pct = add_pct,
stringsAsFactors = FALSE))
}
}
comp
}
# ── C2. Build sunburst hierarchy from composition CSV ─────────────────────
# Genome-relative: the first ring reads Repeats vs Non-repetitive, so every
# %entry equals % of genome and matches the classification table. With
# branchvalues="remainder" the "Repeats" container's own value is 0 and its
# children sum to the repeat total; "Non-repetitive" carries genome - repeats.
build_sunburst_data <- function(comp, genome_size = NULL) {
pal <- c(
"Class_I" = "#4575b4",
"Class_II" = "#d73027",
"Tandem_repeats" = "#1a9850",
"Simple_repeat" = "#878787",
"Low_complexity"= "#bdbdbd",
"rDNA" = "#762a83",
"rDNA_45S" = "#762a83",
"rDNA_5S" = "#9e6faf",
"Unknown" = "#d9d9d9"
)
get_color <- function(id) {
# Distinct colours for the two LTR superfamilies — otherwise both inherit the
# Class_I blue and are indistinguishable in the pie.
if (grepl("Ty1_copia", id, fixed = TRUE)) return("#4575b4") # copia — blue
if (grepl("Ty3_gypsy", id, fixed = TRUE)) return("#e08214") # gypsy — orange
top <- strsplit(id, "/")[[1]][1]
col <- pal[top]
if (is.na(col)) "#aaaaaa" else col
}
csv_ids <- comp$type
csv_bp <- comp$bp
csv_pct <- comp$pct
# Compute the closure: all parent paths needed
all_prefixes <- unique(unlist(lapply(csv_ids, function(id) {
parts <- strsplit(id, "/")[[1]]
if (length(parts) <= 1) return(character(0))
sapply(seq_len(length(parts) - 1), function(n) paste(parts[1:n], collapse = "/"))
})))
synthetic_ids <- setdiff(all_prefixes, csv_ids)
# Combine CSV nodes + synthetic nodes
all_ids <- c(csv_ids, synthetic_ids)
all_bp <- c(csv_bp, rep(0, length(synthetic_ids)))
all_pct <- c(csv_pct, rep(0, length(synthetic_ids)))
labels <- sapply(strsplit(all_ids, "/"), function(x) x[length(x)])
# Single-component categories are re-parented under the synthetic "Repeats"
# node so the inner ring is Repeats vs Non-repetitive.
parents <- sapply(all_ids, function(id) {
p <- strsplit(id, "/")[[1]]
if (length(p) == 1) "Repeats" else paste(p[-length(p)], collapse = "/")
})
colors <- sapply(all_ids, get_color)
# Fixed top-level order (Change 1): categories directly under "Repeats" are
# ordered by CATEGORY_ORDER; deeper nodes keep size-descending order. sort is
# disabled in json_sunburst so plotly honours this input order.
is_top <- parents == "Repeats"
top_rank <- ifelse(is_top, match(labels, CATEGORY_ORDER), Inf)
top_rank[is_top & is.na(top_rank)] <- Inf
ord <- order(top_rank, -all_bp)
all_ids <- all_ids[ord]; all_bp <- all_bp[ord]; all_pct <- all_pct[ord]
labels <- labels[ord]; parents <- parents[ord]; colors <- colors[ord]
total_repeat_bp <- sum(as.numeric(csv_bp))
if (is.null(genome_size)) genome_size <- total_repeat_bp
nonrep_bp <- max(0, genome_size - total_repeat_bp)
rep_pct <- if (genome_size > 0) total_repeat_bp / genome_size * 100 else 0
nonrep_pct <- if (genome_size > 0) nonrep_bp / genome_size * 100 else 0
list(
ids = c("root", "Repeats", "Non-repetitive", all_ids),
labels = c("Genome", "Repeats", "Non-repetitive", labels),
parents = c("", "root", "root", parents),
values = c(0, 0, nonrep_bp, all_bp),
text = c("",
sprintf("%.3f%%", rep_pct),
sprintf("%.3f%%", nonrep_pct),
ifelse(all_pct > 0, sprintf("%.3f%%", all_pct), "")),
colors = c("#ffffff", "#737373", "#e0e0e0", colors)
)
}
# ── C3. Build composition tree for hierarchical table ─────────────────────
build_comp_tree <- function(comp, ltr_stats, tir_stats, line_stats = NULL,
genome_size = NULL) {
# Compute the closure of all node paths (CSV rows + synthetic parents)
csv_ids <- comp$type
csv_bp <- setNames(comp$bp, comp$type)
csv_pct <- setNames(comp$pct, comp$type)
all_prefixes <- unique(unlist(lapply(csv_ids, function(id) {
parts <- strsplit(id, "/")[[1]]
if (length(parts) <= 1) return(character(0))
sapply(seq_len(length(parts) - 1), function(n) paste(parts[1:n], collapse = "/"))
})))
synthetic_ids <- setdiff(all_prefixes, csv_ids)
all_ids <- c(csv_ids, synthetic_ids)
# Parent map
parent_of <- sapply(all_ids, function(id) {
p <- strsplit(id, "/")[[1]]
if (length(p) == 1) NA_character_ else paste(p[-length(p)], collapse = "/")
})
# Children map
children_of <- lapply(setNames(all_ids, all_ids), function(id) {
all_ids[!is.na(parent_of) & parent_of == id]
})
# Subtree bp sum (recursive)
subtree_bp <- function(id) {
own <- unname(csv_bp[id] %||% 0) # unname() prevents sapply name-collision
kids <- children_of[[id]]
if (length(kids) == 0) return(own)
own + sum(sapply(kids, subtree_bp))
}
subtree_bp_cache <- sapply(all_ids, subtree_bp)
if (is.null(genome_size)) genome_size <- sum(as.numeric(comp$bp)) # fallback
# genome_size is the total assembly size, NOT the repeat content
# Build DANTE lookup: path → count
dante_counts <- setNames(integer(0), character(0))
if (!is.null(ltr_stats) && nrow(ltr_stats) > 0) {
for (i in seq_len(nrow(ltr_stats))) {
p <- ltr_stats$path[i]
dante_counts[p] <- (dante_counts[p] %||% 0L) + ltr_stats$count[i]
}
}
if (!is.null(tir_stats) && nrow(tir_stats) > 0) {
for (i in seq_len(nrow(tir_stats))) {
p <- tir_stats$path[i]
dante_counts[p] <- (dante_counts[p] %||% 0L) + tir_stats$count[i]
}
}
# LINE elements: count at the Class_I/LINE node if it exists
if (!is.null(line_stats) && !is.null(line_stats$regions) && line_stats$regions > 0) {
line_path <- grep("LINE$", all_ids, value = TRUE)
if (length(line_path) > 0)
dante_counts[line_path[1]] <- as.integer(line_stats$regions)
}
# DFS pre-order traversal
rows <- list()
dfs <- function(id, depth) {
own_bp <- unname(csv_bp[id] %||% 0)
tot_bp <- unname(subtree_bp_cache[id])
kids <- children_of[[id]]
has_kids <- length(kids) > 0
label <- strsplit(id, "/")[[1]]
label <- label[length(label)]
dc_raw <- dante_counts[id]
dc <- if (length(dc_raw) > 0 && !is.na(dc_raw)) unname(dc_raw) else NA_integer_
if (has_kids) {
# Total row
rows[[length(rows) + 1]] <<- list(
path = id,
label = label,
row_type = "total",
depth = depth,
bp = tot_bp,
pct = tot_bp / genome_size * 100,
dante_count = NA_integer_
)
# Unspecified row (own CSV value) only if non-zero
if (own_bp > 0) {
rows[[length(rows) + 1]] <<- list(
path = id,
label = label,
row_type = "unspecified",
depth = depth + 1L,
bp = own_bp,
pct = unname(csv_pct[id] %||% 0),
dante_count = NA_integer_
)
}
# Recurse into children sorted by subtree bp descending
kids_sorted <- kids[order(-subtree_bp_cache[kids])]
for (k in kids_sorted) dfs(k, depth + 1L)
} else {
# Leaf row — show DANTE count if available
rows[[length(rows) + 1]] <<- list(
path = id,
label = label,
row_type = "leaf",
depth = depth,
bp = own_bp,
pct = unname(csv_pct[id] %||% 0),
dante_count = dc
)
}
}
# Find top-level nodes (no parent in all_ids). Fixed category order
# (CATEGORY_ORDER); anything unlisted is appended, ordered by size.
top_nodes <- all_ids[is.na(parent_of)]
top_nodes <- top_nodes[order(match(top_nodes, CATEGORY_ORDER),
-subtree_bp_cache[top_nodes])]
for (id in top_nodes) dfs(id, 0L)
do.call(rbind, lapply(rows, as.data.frame, stringsAsFactors = FALSE))
}
# ── C4. Bin a BigWig file for a set of sequences ──────────────────────────
bin_bw <- function(bw_path, seqnames, seq_lengths, bin_width) {
if (is.null(bw_path) || !file.exists(bw_path)) return(NULL)
bw <- tryCatch(import(bw_path, as = "RleList"), error = function(e) NULL)
if (is.null(bw)) return(NULL)
result <- vector("list", length(seqnames))
names(result) <- seqnames
for (s in seqnames) {
if (!s %in% names(bw)) {
result[[s]] <- rep(0, ceiling(seq_lengths[s] / bin_width))
next
}
rle_v <- bw[[s]]
len <- seq_lengths[s]
starts <- seq(1L, len, by = bin_width)
ends <- pmin(starts + bin_width - 1L, len)
v <- Views(rle_v, start = starts, end = ends)
result[[s]] <- pmax(0, viewMeans(v, na.rm = TRUE))
}
result
}
# Sum multiple binned BW arrays element-wise
sum_bw_arrays <- function(arrays_list, seqnames) {
arrays_list <- Filter(Negate(is.null), arrays_list)
if (length(arrays_list) == 0) return(NULL)
Reduce(function(a, b) {
mapply(function(x, y) pmin(1, x + y), a, b, SIMPLIFY = FALSE)
}, arrays_list)
}
# ── Helpers for concatenated density track plots ───────────────────────────
# Centred rolling mean — NA at both ends (creates gaps at sequence boundaries)
smooth_vec <- function(x, N) {
if (N <= 1L || length(x) < N) return(as.numeric(x))
padded <- c(rep(0, N - 1L), x, rep(0, N - 1L))
sm <- as.numeric(stats::filter(padded, rep(1/N, N), sides = 2))
sm <- sm[N:(N + length(x) - 1L)]
sm[1:(N - 1L)] <- NA
sm[(length(sm) - N + 2L):length(sm)] <- NA
sm
}
# Ramer-Douglas-Peucker simplification for a monotonic-x time series.
# NA values in y are always preserved (they mark visual segment breaks).
# Returns integer indices of points to keep.
rdp_simplify <- function(x, y, epsilon) {
n <- length(x)
if (n <= 2L || epsilon <= 0) return(seq_len(n))
keep <- logical(n)
# Iterative (explicit-stack) segmentation. The classic RDP recursion can reach
# depth O(n) on adversarial input (e.g. a long NA-poisoned run peels one point
# per split), which overflows R's fixed C stack — fatal on large genomes with
# hundreds of thousands of density points. An explicit LIFO of (a, b) segments
# has no such limit; the visited set of points is identical to the recursion.
# sa/sb/top are locals of this function mutated in-place by the while loop, so
# only keep[] (in the parent scope) needs <<- — exactly as the recursion did.
rdp_seg_iter <- function(a0, b0) {
cap <- 2L * as.integer(b0 - a0) + 16L
sa <- integer(cap); sb <- integer(cap); top <- 1L
sa[1L] <- a0; sb[1L] <- b0
while (top > 0L) {
a <- sa[top]; b <- sb[top]; top <- top - 1L
keep[a] <<- TRUE
keep[b] <<- TRUE
if (b <= a + 1L) next
xi <- x[(a + 1L):(b - 1L)]
yi <- y[(a + 1L):(b - 1L)]
frac <- (xi - x[a]) / (x[b] - x[a])
dists <- abs(yi - (y[a] + frac * (y[b] - y[a])))
dists[is.na(dists)] <- Inf # NA interior points are always splitting candidates
j <- which.max(dists)
if (dists[j] > epsilon) {
mid <- a + j
if (top + 2L > length(sa)) { # grow defensively (amortised O(1))
sa <- c(sa, integer(length(sa)))
sb <- c(sb, integer(length(sb)))
}
# Push [a, mid] then [mid, b]; LIFO pops [mid, b] first, matching the
# recursion's rdp_seg(a, mid); rdp_seg(mid, b) visitation order.
top <- top + 1L; sa[top] <- a; sb[top] <- mid
top <- top + 1L; sa[top] <- mid; sb[top] <- b
}
}
}
is_na <- is.na(y)
keep[is_na] <- TRUE # preserve NA gap markers
non_na <- which(!is_na)
if (length(non_na) > 0) {
# identify start/end of each run of non-NA values
brk <- c(TRUE, diff(non_na) > 1L)
seg_s <- non_na[brk]
seg_e <- non_na[c(brk[-1L], TRUE)]
for (k in seq_along(seg_s))
rdp_seg_iter(seg_s[k], seg_e[k])
}
sort(which(keep))
}
# Find lineage-level BigWig files in a repeat-annotation directory
discover_lineage_bw_files <- function(rm_dir, bin_width) {
suffix <- if (bin_width == 100000L) "_100k.bw" else "_10k.bw"
known <- c("Ale","Alesia","Angela","Bianca","Bryco","Gymco-I","Gymco-II","Gymco-III",
"Gymco-IV","Ikeros","Ivana","Lyco","Osser","SIRE","TAR","Tork","Chlamyvir",
"chromo-unclass","CRM","Galadriel","Reina","Tcn1","Tekay","Athila","Ogre",
"Retand","TatI","TatII","TatIII","Phygy","Selgy")
if (!dir.exists(rm_dir)) return(list())
pat <- paste0("LTR\\.Ty.*", gsub("\\.", "\\\\.", suffix), "$")
fnames <- list.files(rm_dir, pattern = pat, full.names = FALSE)
if (length(fnames) == 0) return(list())
lnames <- gsub("_100k\\.bw$|_10k\\.bw$", "", fnames)
lnames <- gsub(".*\\.", "", lnames)
keep <- lnames %in% known
fnames <- fnames[keep]; lnames <- lnames[keep]
if (length(fnames) == 0) return(list())
ord <- order(match(lnames, known))
setNames(as.list(file.path(rm_dir, fnames[ord])), lnames[ord])
}
# Find TRC satellite BigWig files and label them with monomer sizes
discover_trc_bw_files <- function(outdir, bin_width) {
res <- if (bin_width == 100000L) "100k" else "10k"
suffix <- paste0("_", res, ".bw")
trc_dir <- file.path(outdir, "Tandem_repeats_TideCluster_split_by_family_bigwig", res)
mon_f <- file.path(outdir, "TideCluster", "default", "TideCluster_kite",
"monomer_size_best_estimate_stat.csv")
if (!dir.exists(trc_dir)) return(list())
bw_f <- list.files(trc_dir, pattern = "\\.bw$", full.names = FALSE)
tnames <- gsub(paste0(gsub("\\.", "\\\\.", suffix), "$"), "", bw_f)
tidx <- suppressWarnings(as.numeric(sub("TRC_", "", tnames)))
valid <- !is.na(tidx)
bw_f <- bw_f[valid]; tnames <- tnames[valid]; tidx <- tidx[valid]
if (length(bw_f) == 0) return(list())
ord <- order(tidx)
N <- min(20L, length(bw_f))
bw_f <- bw_f[ord][seq_len(N)]; tnames <- tnames[ord][seq_len(N)]
mon_sizes <- setNames(rep("?", N), tnames)
if (file.exists(mon_f)) {
ms <- tryCatch(read.table(mon_f, header = TRUE, sep = "\t", check.names = FALSE),
error = function(e) NULL)
if (!is.null(ms) && all(c("TRC_ID", "position") %in% names(ms))) {
for (tn in tnames) {
sub <- ms[ms$TRC_ID == tn, ]
if (nrow(sub) > 0)
mon_sizes[tn] <- names(sort(table(sub$position), decreasing = TRUE)[1])
}
}
}
setNames(as.list(file.path(trc_dir, bw_f)),
paste0(tnames, " (", mon_sizes, "bp)"))
}
# ── C5. Build density track arrays for selected sequences ─────────────────
build_density_arrays <- function(bw_files, seqnames, seq_lengths_vec, bin_width) {
result <- list()
for (label in names(bw_files)) {
paths <- bw_files[[label]]
if (is.null(paths)) next
if (length(paths) == 1) {
arr <- bin_bw(paths, seqnames, seq_lengths_vec, bin_width)
} else {
arr_list <- lapply(paths, bin_bw, seqnames = seqnames,
seq_lengths = seq_lengths_vec, bin_width = bin_width)
arr <- sum_bw_arrays(arr_list, seqnames)
}
if (!is.null(arr)) result[[label]] <- arr
}
result
}
# ── C6. Per-sequence repeat composition (from the unified GFF3) ────────────
# Computed at base precision from the unified annotation's Level-1 features —
# NOT from the smoothed density BigWigs (whose 10-bin moving average inflates the
# integral). Each bar segment is the exact union bp of a class on a sequence, so
# the stack sums to that sequence's true union repeat fraction.
# Bar categories, in stacking order. "Other repeats" is the catch-all for classes
# not named here (DIRS/SINE/Penelope/bare nodes) so every bar sums to the union.
BAR_CATEGORIES <- c("Ty1/copia", "Ty3/gypsy", "LINE", "Class II", "Pararetrovirus",
"Tandem_repeats", "rDNA", "Simple repeats", "Low complexity",
"Other repeats", "Unknown")
# Map a vector of canonical classifications to bar categories. Patterns are
# mutually exclusive; default is "Other repeats".
repeat_category <- function(cls) {
out <- rep("Other repeats", length(cls))
out[grepl("Ty1_copia", cls)] <- "Ty1/copia"
out[grepl("Ty3_gypsy", cls)] <- "Ty3/gypsy"
out[grepl("Class_I/LINE", cls, fixed = TRUE)]<- "LINE"
out[grepl("pararetrovirus", cls)] <- "Pararetrovirus"
out[grepl("^Class_II", cls)] <- "Class II"
out[grepl("^Satellite", cls)] <- "Tandem_repeats"
out[grepl("^rDNA", cls)] <- "rDNA"
out[grepl("^Simple_repeat", cls)] <- "Simple repeats"
out[grepl("^Low_complexity", cls)] <- "Low complexity"
out[grepl("^Unknown", cls)] <- "Unknown"
out
}
# Per-sequence union bp per category from Level-1 features. Returns a matrix
# [sequence x category] of base pairs (union within each category).
compute_seq_category_bp <- function(l1, seqnames_all) {
mat <- matrix(0, nrow = length(seqnames_all), ncol = length(BAR_CATEGORIES),
dimnames = list(seqnames_all, BAR_CATEGORIES))
if (length(l1) == 0) return(mat)
cat <- repeat_category(as.character(l1$classification))
for (cc in BAR_CATEGORIES) {
sub <- l1[cat == cc]
if (length(sub) == 0) next
r <- reduce(sub, ignore.strand = TRUE)
by_seq <- tapply(width(r), as.character(seqnames(r)), sum)
idx <- intersect(names(by_seq), seqnames_all)
if (length(idx)) mat[idx, cc] <- by_seq[idx]
}
mat
}
# ── C7. Satellite cluster coverage ────────────────────────────────────────
build_satellite_coverage <- function(tc_cluster_files, seqnames, seq_lengths_vec,
bin_width, top_n) {
if (length(tc_cluster_files) == 0) return(list(totals = NULL, arrays = NULL))
totals <- vapply(names(tc_cluster_files), function(cl) {
gr <- tryCatch(import(tc_cluster_files[[cl]]), error = function(e) NULL)
if (is.null(gr) || length(gr) == 0) return(0)
sum(score(gr) * width(gr), na.rm = TRUE)
}, numeric(1))
top_clusters <- names(sort(totals, decreasing = TRUE))[seq_len(min(top_n, length(totals)))]
per_seq_mat <- matrix(0, nrow = length(seqnames), ncol = length(top_clusters),
dimnames = list(seqnames, top_clusters))
for (cl in top_clusters) {
gr <- tryCatch(import(tc_cluster_files[[cl]]), error = function(e) NULL)
if (is.null(gr)) next
by_seq <- tapply(score(gr) * width(gr), as.character(seqnames(gr)), sum, na.rm = TRUE)
for (s in intersect(names(by_seq), seqnames)) {
per_seq_mat[s, cl] <- by_seq[s] / seq_lengths_vec[s]
}
}
density_arrays <- build_density_arrays(
setNames(as.list(tc_cluster_files[top_clusters]), top_clusters),
seqnames, seq_lengths_vec, bin_width
)
list(totals = totals[top_clusters], per_seq = per_seq_mat, arrays = density_arrays)
}
# ═══════════════════════════════════════════════════════════════════════════
# D. JSON / PLOTLY GENERATION
# ═══════════════════════════════════════════════════════════════════════════
J <- function(x) toJSON(x, auto_unbox = TRUE, null = "null")
TRACK_COLORS <- c(
"Tandem_repeats" = "#1a9850",
"Ty1/copia" = "#4575b4",
"Ty3/gypsy" = "#e08214",
"LINE" = "#74add1",
"Class II" = "#d73027",
"Pararetrovirus" = "#f46d43",
"Simple repeats" = "#878787",
"Low complexity" = "#bdbdbd",
"rDNA" = "#762a83",
"Unknown" = "#d9d9d9",
"Other repeats" = "#fee08b"
)
# ── D1. Sunburst JSON ──────────────────────────────────────────────────────
json_sunburst <- function(sb) {
trace <- list(
type = "sunburst",
ids = sb$ids,
labels = sb$labels,
parents = sb$parents,
values = sb$values,
branchvalues = "remainder",
hovertemplate = paste0(
"<b>%{label}</b><br>",
"%{value:,.0f} bp<br>",
"%{customdata}<br>",
"<extra></extra>"
),
customdata = sb$text,
textinfo = "label+percent entry",
marker = list(colors = sb$colors),
sort = FALSE,
maxdepth = 4
)
layout <- list(
margin = list(t = 10, l = 10, r = 10, b = 10),
height = 520
)
list(traces = list(trace), layout = layout)
}
# ── D2. Per-sequence stacked composition bar ──────────────────────────────
# Pure renderer. cov_mat: rows already ordered (sequences then an optional
# "Other" aggregate), columns = BAR_CATEGORIES, values = fraction of the row's
# length. y_labels: one label per row. genome_avg_frac: the single reference
# line (= GFF Level-1 union / genome = length-weighted mean of all rows).
json_composition_bar <- function(cov_mat, y_labels, genome_avg_frac) {
cats <- colnames(cov_mat)
max_x <- max(rowSums(cov_mat), genome_avg_frac, 0.05) * 1.15
traces <- lapply(cats, function(cat) list(
type = "bar",
orientation = "h",
name = cat,
# I() forces JSON arrays — with a single row, auto_unbox would otherwise
# collapse length-1 x/y to scalars and Plotly draws no bar.
x = I(unname(cov_mat[, cat])),
y = I(y_labels),
marker = list(color = TRACK_COLORS[[cat]] %||% "#aaaaaa"),
hovertemplate = paste0(cat, ": %{x:.3f}<extra></extra>")
))
shapes <- list(list(type = "line", x0 = genome_avg_frac, x1 = genome_avg_frac,
y0 = 0, y1 = 1, yref = "paper",
line = list(color = "#333333", width = 1.5, dash = "dash")))
# Genome-average label sits ABOVE the top bar (yref=paper, y>1), anchored to
# the line; anchor side flips near the right edge so it never clips off-plot.
lab_anchor <- if (genome_avg_frac > 0.5 * max_x) "right" else "left"
annotations <- list(
list(x = genome_avg_frac, y = 1.04, xref = "x", yref = "paper",
text = sprintf("genome avg %.1f%%", genome_avg_frac * 100),
showarrow = FALSE, xanchor = lab_anchor, yanchor = "bottom",
font = list(size = 10, color = "#333333"))
)
layout <- list(
barmode = "stack",
height = max(320, nrow(cov_mat) * 26 + 135),
# Generous top (genome-avg label) and bottom (x-axis title ABOVE the legend).
margin = list(l = 200, r = 35, t = 42, b = 115),
xaxis = list(title = list(text = "Fraction of sequence", standoff = 8),
range = c(0, max_x)),
# Pin row order to y_labels (rev: first label at top).
yaxis = list(title = "", automargin = TRUE,
categoryorder = "array", categoryarray = rev(y_labels)),
legend = list(orientation = "h", y = -0.3, yanchor = "top",
x = 0, xanchor = "left"),
showlegend = TRUE,
shapes = shapes,
annotations = annotations
)
list(traces = traces, layout = layout)
}
# ── D3. Concatenated density track plot (matches summary_plots.pdf design) ─
# All sequences concatenated on a single x-axis; tracks stacked vertically
# with a SHARED y-scale (global ymax across all tracks).
# Two lines per track: thin gray (raw) + thicker red (smoothed).
# Track labels on the right; chromosome names on x-axis.
json_concat_density_plot <- function(bw_map, seq_info, bin_width, n_smooth = 10) {
bw_map <- Filter(function(p) !is.null(p) && file.exists(unlist(p)), bw_map)
if (length(bw_map) == 0) return(NULL)
track_names <- names(bw_map)
n_tracks <- length(track_names)
# All sequences sorted by length descending (matches PDF order)
seq_info <- seq_info[order(-seq_info$length), ]
seqnames <- seq_info$seqname
seq_len <- setNames(seq_info$length, seqnames)
# Cumulative x offsets (Mb): cum_mb[i] = start of sequence i
cum_mb <- c(0, cumsum(seq_len / 1e6))
x_ticks <- unname((cum_mb[-length(cum_mb)] + cum_mb[-1]) / 2) # midpoints
x_sep <- unname(cum_mb[-c(1, length(cum_mb))]) # internal boundaries
total_mb <- cum_mb[length(cum_mb)]
# Build raw + smoothed arrays per track, concatenated across sequences
x_all <- numeric(0)
track_y_raw <- list()
track_y_sm <- list()
built_x <- FALSE
for (lbl in track_names) {
p <- unlist(bw_map[[lbl]])
bw <- tryCatch(import(p, as = "RleList"), error = function(e) NULL)
raw_cat <- numeric(0)
sm_cat <- numeric(0)
for (si in seq_along(seqnames)) {
s <- seqnames[si]
len <- seq_len[s]
starts <- seq(1L, len, by = bin_width)
ends <- pmin(starts + bin_width - 1L, len)
n_bins <- length(starts)
if (!is.null(bw) && s %in% names(bw)) {
v <- Views(bw[[s]], start = starts, end = ends)
raw <- pmax(0, viewMeans(v, na.rm = TRUE))
} else {
raw <- rep(0, n_bins)
}
sm <- smooth_vec(raw, n_smooth)
raw_cat <- c(raw_cat, raw)
sm_cat <- c(sm_cat, sm)
if (!built_x)
# as.numeric() BEFORE the sum: on a large genome starts/ends are R
# integers and a bin midpoint on a chromosome > ~1.07 Gbp makes
# `starts + ends` exceed 2^31, silently producing NA (integer overflow).
# Those NAs then poison the x-axis and drive rdp_simplify into O(n)
# recursion ("C stack usage too close to the limit"). Doubles don't wrap.
x_all <- c(x_all, round((as.numeric(starts) + as.numeric(ends)) / 2 / 1e6 + cum_mb[si], 3))
}
built_x <- TRUE
track_y_raw[[lbl]] <- raw_cat
track_y_sm[[lbl]] <- sm_cat
}
# Global ymax shared across all tracks
ymax <- max(sapply(track_y_raw, max, na.rm = TRUE), na.rm = TRUE)
if (!is.finite(ymax) || ymax == 0) ymax <- 1
y_step <- 1.1 * ymax
# RDP epsilon relative to the global y range
eps_raw <- ymax * 0.01 # 1 % of range — aggressive (raw is decorative)
eps_sm <- ymax * 0.002 # 0.2 % of range — conservative (smooth is informative)
# Build traces: for each track, raw (gray thin) + smooth (red thick)
traces <- list()
tidx <- 0L
for (ti in seq_along(track_names)) {
lbl <- track_names[ti]
y_off <- (ti - 1) * y_step
raw_y <- track_y_raw[[lbl]] + y_off
idx_rw <- rdp_simplify(x_all, raw_y, eps_raw)
# Raw gray line
tidx <- tidx + 1L
traces[[tidx]] <- list(
type = "scattergl", mode = "lines",
x = x_all[idx_rw], y = raw_y[idx_rw],
showlegend = FALSE, hoverinfo = "skip",
line = list(width = 0.5, color = "#00000030"),
name = paste0(lbl, "_raw")
)
sm_y <- track_y_sm[[lbl]] + y_off
idx_sm <- rdp_simplify(x_all, sm_y, eps_sm)
# Smoothed red line (NA values create gaps at sequence boundaries)
tidx <- tidx + 1L
traces[[tidx]] <- list(
type = "scattergl", mode = "lines",
x = x_all[idx_sm], y = sm_y[idx_sm],
showlegend = FALSE, connectgaps = FALSE,
name = lbl,
line = list(width = 1.5, color = "#cc0000bb"),
hovertemplate = paste0(lbl, ": %{y:.4f} at %{x:.2f} Mb<extra></extra>")
)
}
# Shapes drawn BELOW all traces (layer="below") so they don't obscure density
# lines even on short contigs.
# Horizontal grid lines at every track boundary
h_shapes <- lapply(seq(0L, n_tracks), function(ti)
list(type = "line", layer = "below",
x0 = 0, x1 = 1, xref = "paper",
y0 = ti * y_step, y1 = ti * y_step, yref = "y",
line = list(color = "#bbbbbb", width = 0.8)))
# Vertical chromosome boundary lines — clearly visible grid
v_shapes <- lapply(x_sep, function(xb)
list(type = "line", layer = "below",
x0 = xb, x1 = xb, xref = "x",
y0 = 0, y1 = 1, yref = "paper",
line = list(color = "#999999", width = 1.0)))
# Track label annotations (right side, in data y coordinates)
annots <- lapply(seq_along(track_names), function(ti) {
list(
x = 1.01, xref = "paper", xanchor = "left",
y = (ti - 1) * y_step + ymax * 0.5, yref = "y",
text = track_names[ti], showarrow = FALSE,
font = list(size = 9, color = "#333333"),
bgcolor = "rgba(255,255,255,0.85)", borderpad = 2
)
})
layout <- list(
height = max(200L, n_tracks * 55L + 90L),
margin = list(l = 40, r = 140, t = 10, b = 95),
xaxis = list(
range = c(0, total_mb),
tickvals = x_ticks,
ticktext = seqnames,
tickangle = -90,
tickfont = list(size = 7),
title = "Genome position (Mb)",
showgrid = FALSE
),
yaxis = list(
range = c(-0.02 * ymax, n_tracks * y_step + 0.05 * ymax),
showticklabels = FALSE,
zeroline = FALSE, showgrid = FALSE, title = ""
),
showlegend = FALSE,
annotations = annots,
shapes = unname(c(h_shapes, v_shapes))
)
list(traces = traces, layout = layout)
}
# ── D4. Satellite cluster stacked bar ─────────────────────────────────────
json_satellite_bar <- function(sat_data, seq_info) {
if (is.null(sat_data$per_seq) || nrow(sat_data$per_seq) == 0) return(NULL)
mat <- sat_data$per_seq
seq_names <- rownames(mat)
clusters <- colnames(mat)
ord <- order(-rowSums(mat))
mat <- mat[ord, , drop = FALSE]
seq_names <- seq_names[ord]
seq_len_mb <- seq_info$length[match(seq_names, seq_info$seqname)] / 1e6
y_labels <- sprintf("%s (%.1f Mb)", seq_names, seq_len_mb)
cluster_pal <- colorRampPalette(c("#1a9850","#66bd63","#a6d96a","#d9ef8b",
"#fee08b","#fdae61","#f46d43","#d73027"))(length(clusters))
traces <- lapply(seq_along(clusters), function(i) {
list(
type = "bar",
orientation = "h",
name = clusters[i],
x = mat[, clusters[i]],
y = y_labels,
marker = list(color = cluster_pal[i]),
hovertemplate = paste0(clusters[i], ": %{x:.4f}<extra></extra>")
)
})
layout <- list(
barmode = "stack",
height = max(280, length(seq_names) * 22 + 80),
margin = list(l = 200, r = 20, t = 30, b = 60),
xaxis = list(title = "Fraction of sequence"),
yaxis = list(title = "", automargin = TRUE),
legend = list(orientation = "h", y = -0.18),
showlegend = TRUE
)
list(traces = traces, layout = layout)
}
# ═══════════════════════════════════════════════════════════════════════════
# E. HTML ASSEMBLY
# ═══════════════════════════════════════════════════════════════════════════
# ── E1. Load Plotly.js ─────────────────────────────────────────────────────
# Writes plotly.min.js as a sibling file of the report and returns a
# <script src="plotly.min.js"> tag, rather than inlining ~4.5 MB into every
# report. A smaller HTML document parses faster (the inline copy was a major
# contributor to the browser stall on large genomes) and the library can be
# browser-cached. Falls back to the CDN if the library can't be staged.
load_plotly_js <- function(outdir) {
url <- "https://cdn.plot.ly/plotly-2.35.2.min.js"
sibling <- file.path(outdir, "plotly.min.js")