File size: 27,257 Bytes
665b219
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6655e6
 
 
 
665b219
c6655e6
665b219
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
c6655e6
 
 
 
 
665b219
 
 
 
 
 
 
c6655e6
 
 
 
 
 
 
 
 
665b219
c6655e6
665b219
 
 
c6655e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
665b219
 
c6655e6
 
 
 
 
 
 
 
 
 
 
 
 
 
 
665b219
 
 
 
 
 
 
 
 
 
 
 
 
 
c6655e6
 
 
665b219
c6655e6
 
665b219
 
 
 
c6655e6
 
 
 
 
 
665b219
c6655e6
 
 
 
 
 
665b219
 
 
c6655e6
 
 
 
 
 
 
 
 
 
 
665b219
 
 
 
 
 
c6655e6
665b219
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
library(tidyverse)
library(arrow)
library(here)

# these are the protein coding non dubious loci
mahendrawada_features = arrow::read_parquet("~/code/hf/mahendrawada_2025/features_mahendrawada_2025.parquet")


# read in and prepare the perturbation response data
perturbation_response_data = list(
    mahendrawada_rnaseq = arrow::read_parquet("~/code/hf/mahendrawada_2025/rnaseq_reprocessed.parquet") %>%
        filter(target_locus_tag %in% mahendrawada_features$locus_tag) %>%
        replace_na(list(log2FoldChange = 0, pvalue = 1)) %>%
        mutate(abs_log2fc = abs(log2FoldChange)),
    # kemmeren requires deduplicating instances where there are multiple probes
    # to the same locus_tag. Take the max
    kemmeren = arrow::open_dataset("~/code/hf/kemmeren_2014/kemmeren_2014.parquet") %>%
        filter(target_locus_tag %in% mahendrawada_features$locus_tag,
               str_detect(regulator_locus_tag, "WT-", negate=TRUE)) %>%
        select(sample_id, regulator_locus_tag, target_locus_tag, Madj, pval) %>%
        arrow::to_duckdb() %>%
        group_by(sample_id, target_locus_tag) %>%
        mutate(rn = row_number(desc(abs(Madj)))) %>%
        filter(rn == 1) %>%
        select(-rn) %>%
        ungroup() %>%
        collect(),
    hackett = arrow::read_parquet("~/code/hf/hackett_2020/hackett_2020.parquet") %>%
        filter(target_locus_tag %in% mahendrawada_features$locus_tag,
               str_detect(regulator_locus_tag, "WT-", negate=TRUE)) %>%
        select(sample_id, regulator_locus_tag, target_locus_tag, log2_shrunken_timecourses) %>%
        arrow::to_duckdb() %>%
        group_by(sample_id, target_locus_tag) %>%
        mutate(rn = row_number(desc(abs(log2_shrunken_timecourses)))) %>%
        filter(rn == 1) %>%
        select(-rn) %>%
        ungroup() %>%
        collect() %>%
        # add this for consistency with the other datasets
        mutate(pvalue = 0),
    hu_reimand = arrow::read_parquet("~/code/hf/hu_2007_reimand_2010/hu_2007_reimand_2010.parquet") %>%
        filter(target_locus_tag %in% mahendrawada_features$locus_tag) %>%
        select(sample_id, regulator_locus_tag, target_locus_tag, effect, pval) %>%
        arrow::to_duckdb() %>%
        group_by(sample_id, target_locus_tag) %>%
        mutate(rn = row_number(desc(abs(effect)))) %>%
        filter(rn == 1) %>%
        select(-rn) %>%
        ungroup() %>%
        collect(),
    hughes_ko = arrow::read_parquet("~/code/hf/hughes_2006/knockout.parquet") %>%
        filter(target_locus_tag %in% mahendrawada_features$locus_tag) %>%
        select(sample_id, regulator_locus_tag, target_locus_tag, mean_norm_log2fc) %>%
        arrow::to_duckdb() %>%
        group_by(sample_id, target_locus_tag) %>%
        mutate(rn = row_number(desc(abs(mean_norm_log2fc)))) %>%
        filter(rn == 1) %>%
        select(-rn) %>%
        ungroup() %>%
        collect() %>%
        # add this for consistency with the other datasets
        mutate(pvalue = 0),
    hughes_oe = arrow::read_parquet("~/code/hf/hughes_2006/overexpression.parquet") %>%
        filter(target_locus_tag %in% mahendrawada_features$locus_tag) %>%
        select(sample_id, regulator_locus_tag, target_locus_tag, mean_norm_log2fc) %>%
        arrow::to_duckdb() %>%
        group_by(sample_id, target_locus_tag) %>%
        mutate(rn = row_number(desc(abs(mean_norm_log2fc)))) %>%
        filter(rn == 1) %>%
        select(-rn) %>%
        ungroup() %>%
        collect() %>%
        # add this for consistency with the other datasets
        mutate(pvalue = 0)
    )

composite_cc = arrow::open_dataset("~/code/hf/callingcards/annotated_features_combined") %>%
    collect() %>%
    left_join(arrow::read_parquet("~/code/hf/callingcards/annotated_features_combined_meta.parquet")) %>%
    dplyr::rename(id = genome_map_id_set)

single_cc_meta = arrow::read_parquet("~/code/hf/callingcards/annotated_features_meta.parquet") %>%
    filter(batch != "composite")

single_cc = arrow::open_dataset("~/code/hf/callingcards/annotated_features") %>%
    filter(id %in% single_cc_meta$id) %>%
    collect() %>%
    left_join(single_cc_meta) %>%
    mutate(id = as.character(id))

binding_data = list(
    cc = single_cc %>%
        select(intersect(colnames(.), colnames(composite_cc))) %>%
        bind_rows(composite_cc %>%
                      select(intersect(colnames(.), colnames(single_cc)))),
    harbison = arrow::read_parquet("~/code/hf/harbison_2004/harbison_2004.parquet") %>%
        replace_na(list(effect = 0, pvalue = 1)) %>%
        group_by(sample_id, target_locus_tag) %>%
        slice_max(abs(effect), n = 1, with_ties = FALSE) %>%
        ungroup(),
    chipexo = arrow::read_parquet("~/code/hf/rossi_2021/rossi_2021_af_combined.parquet") %>%
        left_join(arrow::read_parquet("~/code/hf/rossi_2021/rossi_2021_metadata_sample.parquet")),
    mahendrawada_chec = arrow::read_parquet("~/code/hf/mahendrawada_2025/chec_mahendrawada_m2025_af_combined.parquet") %>%
        left_join(arrow::read_parquet("~/code/hf/mahendrawada_2025/chec_mahendrawada_m2025_af_combined_meta.parquet"))
)

mahendrawada_rnaseq_dto_background = map(binding_data, ~{
    .x %>%
        ungroup() %>%
        select(target_locus_tag) %>%
        distinct() %>%
        filter(target_locus_tag %in% unique(perturbation_response_data$mahendrawada_rnaseq$target_locus_tag))
    })

mahendrawada_rnaseq_dto = list(
    cc = list(
        binding = binding_data$cc %>%
            filter(poisson_pval <= 0.1) %>%
            filter(regulator_locus_tag %in% unique(perturbation_response_data$mahendrawada_rnaseq$regulator_locus_tag),
                   target_locus_tag %in% unique(perturbation_response_data$mahendrawada_rnaseq$target_locus_tag)) %>%
            group_by(id) %>%
            arrange(desc(callingcards_enrichment)) %>%
            mutate(pvalue_rank = rank(poisson_pval, ties.method = 'min')) %>%
            dplyr::rename(sample_id = id) %>%
            group_by(sample_id),
        pr = perturbation_response_data$mahendrawada_rnaseq %>%
            filter(pvalue <= 0.1) %>%
            filter(regulator_locus_tag %in% unique(binding_data$cc$regulator_locus_tag),
                   target_locus_tag %in% unique(binding_data$cc$target_locus_tag)) %>%
            group_by(sample_id) %>%
            mutate(abs_log2fc_rank = rank(-abs_log2fc, ties.method = 'min'),
                   pvalue_rank = rank(pvalue, ties.method = 'min')) %>%
            group_by(sample_id)),
    harbison = list(
        binding = binding_data$harbison %>%
            filter(pvalue <= 0.1) %>%
            filter(regulator_locus_tag %in% unique(perturbation_response_data$mahendrawada_rnaseq$regulator_locus_tag),
                   target_locus_tag %in% unique(perturbation_response_data$mahendrawada_rnaseq$target_locus_tag)) %>%
            group_by(sample_id) %>%
            arrange(desc(effect)) %>%
            mutate(pvalue_rank = rank(pvalue, ties.method = 'min')) %>%
            group_by(sample_id),
        pr = perturbation_response_data$mahendrawada_rnaseq %>%
            filter(pvalue <= 0.1) %>%
            filter(regulator_locus_tag %in% unique(binding_data$harbison$regulator_locus_tag),
                   target_locus_tag %in% unique(binding_data$harbison$target_locus_tag)) %>%
            group_by(sample_id) %>%
            mutate(abs_log2fc_rank = rank(-abs_log2fc, ties.method = 'min'),
                   pvalue_rank = rank(pvalue, ties.method = 'min')) %>%
            group_by(sample_id)),
    chipexo = list(
        binding = binding_data$chipexo %>%
            filter(log_poisson_pval <= log(0.1)) %>%
            filter(regulator_locus_tag %in% unique(perturbation_response_data$mahendrawada_rnaseq$regulator_locus_tag),
                   target_locus_tag %in% unique(perturbation_response_data$mahendrawada_rnaseq$target_locus_tag)) %>%
            group_by(sample_id) %>%
            arrange(desc(enrichment)) %>%
            mutate(pvalue_rank = rank(log_poisson_pval, ties.method = 'min')) %>%
            group_by(sample_id),
        pr = perturbation_response_data$mahendrawada_rnaseq %>%
            filter(pvalue <= 0.1) %>%
            filter(regulator_locus_tag %in% unique(binding_data$chipexo$regulator_locus_tag),
                   target_locus_tag %in% unique(binding_data$chipexo$target_locus_tag)) %>%
            group_by(sample_id) %>%
            mutate(abs_log2fc_rank = rank(-abs_log2fc, ties.method = 'min'),
                   pvalue_rank = rank(pvalue, ties.method = 'min')) %>%
            group_by(sample_id)),
    mahendrawada_chec = list(
        binding = binding_data$mahendrawada_chec %>%
            filter(log_poisson_pval <= log(0.1)) %>%
            filter(regulator_locus_tag %in% unique(perturbation_response_data$mahendrawada_rnaseq$regulator_locus_tag),
                   target_locus_tag %in% unique(perturbation_response_data$mahendrawada_rnaseq$target_locus_tag)) %>%
            group_by(sample_id) %>%
            arrange(desc(enrichment)) %>%
            mutate(pvalue_rank = rank(log_poisson_pval, ties.method = 'min')) %>%
            group_by(sample_id),
        pr = perturbation_response_data$mahendrawada_rnaseq %>%
            filter(pvalue <= 0.1) %>%
            filter(regulator_locus_tag %in% unique(binding_data$mahendrawada_chec$regulator_locus_tag),
                   target_locus_tag %in% unique(binding_data$mahendrawada_chec$target_locus_tag)) %>%
            group_by(sample_id) %>%
            mutate(abs_log2fc_rank = rank(-abs_log2fc, ties.method = 'min'),
                   pvalue_rank = rank(pvalue, ties.method = 'min')) %>%
            group_by(sample_id))
)

# Function to create DTO for a given PR dataset
create_pr_dto = function(pr_data, pr_effect_col, pr_pval_col, binding_data_list) {

    # Standardize column names for the PR data
    pr_standardized = pr_data %>%
        ungroup() %>%
        # remove the target observation for the perturbed locus
        # NOTE: this is also done for the binding data, though i don't
        # remove it from the background
        filter(regulator_locus_tag != target_locus_tag)

    # Handle effect column renaming
    if (pr_effect_col != "effect") {
        pr_standardized = pr_standardized %>%
            rename(effect = !!sym(pr_effect_col))
    }

    # Handle pvalue column renaming
    if (pr_pval_col != "pvalue") {
        # If renaming a different column to pvalue, drop existing pvalue column first
        if ("pvalue" %in% colnames(pr_standardized)) {
            pr_standardized = pr_standardized %>%
                select(-pvalue)
        }
        pr_standardized = pr_standardized %>%
            rename(pvalue = !!sym(pr_pval_col))
    }

    # Create DTOs for each binding dataset
    dto_list = list(
        cc = list(
            binding = binding_data_list$cc %>%
                filter(regulator_locus_tag != target_locus_tag) %>%
                filter(poisson_pval <= 0.1) %>%
                filter(regulator_locus_tag %in% unique(pr_standardized$regulator_locus_tag),
                       target_locus_tag %in% unique(pr_standardized$target_locus_tag)) %>%
                group_by(id) %>%
                arrange(desc(callingcards_enrichment)) %>%
                mutate(pvalue_rank = rank(poisson_pval, ties.method = 'min')) %>%
                dplyr::rename(sample_id = id) %>%
                group_by(sample_id),
            pr = pr_standardized %>%
                filter(pvalue <= 0.1) %>%
                filter(regulator_locus_tag %in% unique(binding_data_list$cc$regulator_locus_tag),
                       target_locus_tag %in% unique(binding_data_list$cc$target_locus_tag)) %>%
                group_by(sample_id) %>%
                mutate(abs_effect_rank = rank(-abs(effect), ties.method = 'min'),
                       pvalue_rank = rank(pvalue, ties.method = 'min')) %>%
                group_by(sample_id)),

        harbison = list(
            binding = binding_data_list$harbison %>%
                filter(regulator_locus_tag != target_locus_tag) %>%
                filter(pvalue <= 0.1) %>%
                filter(regulator_locus_tag %in% unique(pr_standardized$regulator_locus_tag),
                       target_locus_tag %in% unique(pr_standardized$target_locus_tag)) %>%
                group_by(sample_id) %>%
                arrange(desc(effect)) %>%
                mutate(pvalue_rank = rank(pvalue, ties.method = 'min')) %>%
                group_by(sample_id),
            pr = pr_standardized %>%
                filter(pvalue <= 0.1) %>%
                filter(regulator_locus_tag %in% unique(binding_data_list$harbison$regulator_locus_tag),
                       target_locus_tag %in% unique(binding_data_list$harbison$target_locus_tag)) %>%
                group_by(sample_id) %>%
                mutate(abs_effect_rank = rank(-abs(effect), ties.method = 'min'),
                       pvalue_rank = rank(pvalue, ties.method = 'min')) %>%
                group_by(sample_id)),

        chipexo = list(
            binding = binding_data_list$chipexo %>%
                filter(regulator_locus_tag != target_locus_tag) %>%
                filter(log_poisson_pval <= log(0.1)) %>%
                filter(regulator_locus_tag %in% unique(pr_standardized$regulator_locus_tag),
                       target_locus_tag %in% unique(pr_standardized$target_locus_tag)) %>%
                group_by(sample_id) %>%
                arrange(desc(enrichment)) %>%
                mutate(pvalue_rank = rank(log_poisson_pval, ties.method = 'min')) %>%
                group_by(sample_id),
            pr = pr_standardized %>%
                filter(pvalue <= 0.1) %>%
                filter(regulator_locus_tag %in% unique(binding_data_list$chipexo$regulator_locus_tag),
                       target_locus_tag %in% unique(binding_data_list$chipexo$target_locus_tag)) %>%
                group_by(sample_id) %>%
                mutate(abs_effect_rank = rank(-abs(effect), ties.method = 'min'),
                       pvalue_rank = rank(pvalue, ties.method = 'min')) %>%
                group_by(sample_id)),

        mahendrawada_chec = list(
            binding = binding_data_list$mahendrawada_chec %>%
                filter(regulator_locus_tag != target_locus_tag) %>%
                filter(log_poisson_pval <= log(0.1)) %>%
                filter(regulator_locus_tag %in% unique(pr_standardized$regulator_locus_tag),
                       target_locus_tag %in% unique(pr_standardized$target_locus_tag)) %>%
                group_by(sample_id) %>%
                arrange(desc(enrichment)) %>%
                mutate(pvalue_rank = rank(log_poisson_pval, ties.method = 'min')) %>%
                group_by(sample_id),
            pr = pr_standardized %>%
                filter(pvalue <= 0.1) %>%
                filter(regulator_locus_tag %in% unique(binding_data_list$mahendrawada_chec$regulator_locus_tag),
                       target_locus_tag %in% unique(binding_data_list$mahendrawada_chec$target_locus_tag)) %>%
                group_by(sample_id) %>%
                mutate(abs_effect_rank = rank(-abs(effect), ties.method = 'min'),
                       pvalue_rank = rank(pvalue, ties.method = 'min')) %>%
                group_by(sample_id))
    )

    return(dto_list)
}

# Create all DTOs
all_pr_dtos = list(
    mahendrawada_rnaseq = create_pr_dto(
        perturbation_response_data$mahendrawada_rnaseq,
        pr_effect_col = "log2FoldChange",
        pr_pval_col = "padj",
        binding_data_list = binding_data
    ),

    kemmeren = create_pr_dto(
        perturbation_response_data$kemmeren,
        pr_effect_col = "Madj",
        pr_pval_col = "pval",
        binding_data_list = binding_data
    ),

    hackett = create_pr_dto(
        perturbation_response_data$hackett,
        pr_effect_col = "log2_shrunken_timecourses",
        pr_pval_col = "pvalue",
        binding_data_list = binding_data
    ),

    hu_reimand = create_pr_dto(
        perturbation_response_data$hu_reimand,
        pr_effect_col = "effect",
        pr_pval_col = "pval",
        binding_data_list = binding_data
    ),

    hughes_ko = create_pr_dto(
        perturbation_response_data$hughes_ko,
        pr_effect_col = "mean_norm_log2fc",
        pr_pval_col = "pvalue",
        binding_data_list = binding_data
    ),

    hughes_oe = create_pr_dto(
        perturbation_response_data$hughes_oe,
        pr_effect_col = "mean_norm_log2fc",
        pr_pval_col = "pvalue",
        binding_data_list = binding_data
    )
)

# Write out DTO ranked lists

write_out_pr_dto_lists = function(pr_dataset_name,
                                  binding_pr_set_name,
                                  all_pr_dtos_list,
                                  base_outdir=here("results/dto")) {

    output_path = file.path(base_outdir, pr_dataset_name)

    binding_pr_set = all_pr_dtos_list[[pr_dataset_name]][[binding_pr_set_name]]

    binding_split = binding_pr_set$binding %>%
        group_split()
    names(binding_split) = pull(group_keys(binding_pr_set$binding), sample_id)

    pr_split = binding_pr_set$pr %>%
        group_split()
    names(pr_split) = pull(group_keys(binding_pr_set$pr), sample_id)

    curr_output_path = list(
        binding = file.path(output_path, binding_pr_set_name, "binding"),
        pr_effect = file.path(output_path, binding_pr_set_name, "pr", "effect"),
        pr_pvalue = file.path(output_path, binding_pr_set_name, "pr", "pvalue")
    )

    map(curr_output_path, dir.create, recursive = TRUE, showWarnings = FALSE)

    # Write out binding lists
    map(names(binding_split), ~{
        binding_split[[.x]] %>%
            select(target_locus_tag, pvalue_rank) %>%
            arrange(pvalue_rank) %>%
            write_csv(file.path(curr_output_path$binding, paste0(.x, ".csv")),
                      col_names = FALSE)
    })

    # Write out effect-ranked pr lists
    map(names(pr_split), ~{
        pr_split[[.x]] %>%
            select(target_locus_tag, abs_effect_rank) %>%
            arrange(abs_effect_rank) %>%
            write_csv(file.path(curr_output_path$pr_effect, paste0(.x, ".csv")),
                      col_names = FALSE)
    })

    # Write out pvalue pr lists
    map(names(pr_split), ~{
        pr_split[[.x]] %>%
            select(target_locus_tag, pvalue_rank) %>%
            arrange(pvalue_rank) %>%
            write_csv(file.path(curr_output_path$pr_pvalue, paste0(.x, ".csv")),
                      col_names = FALSE)
    })
}

# Generalized function to write background
write_pr_background = function(pr_dataset_name,
                               binding_pr_set_name,
                               background_list,
                               base_outdir = here("results/dto")) {
    output_path = file.path(base_outdir, pr_dataset_name)

    background_list[[binding_pr_set_name]] %>%
        write_csv(file.path(output_path, binding_pr_set_name, "background.csv"),
                  col_names = FALSE)
}

# Generalized function to create lookups
create_pr_lookups = function(pr_dataset_name, binding_pr_set_name,
                             all_pr_dtos_list,
                             scratch_path = "/scratch/mblab/chasem/dto") {
    # Get binding and PR sample IDs
    binding_samples = all_pr_dtos_list[[pr_dataset_name]][[binding_pr_set_name]]$binding %>%
        ungroup() %>%
        dplyr::select(sample_id, regulator_locus_tag) %>%
        distinct() %>%
        dplyr::rename(binding_id = sample_id)

    pr_samples = all_pr_dtos_list[[pr_dataset_name]][[binding_pr_set_name]]$pr %>%
        ungroup() %>%
        dplyr::select(sample_id, regulator_locus_tag) %>%
        distinct() %>%
        dplyr::rename(pr_id = sample_id)

    # Full join to identify incomplete cases - use relationship = "many-to-many"
    lookup_df = binding_samples %>%
        full_join(pr_samples, by = "regulator_locus_tag", relationship = "many-to-many") %>%
        mutate(binding = if_else(!is.na(binding_id),
                                 file.path(scratch_path, pr_dataset_name,
                                           binding_pr_set_name, "binding",
                                           paste0(binding_id, ".csv")),
                                 NA_character_),
               pr_effect = if_else(!is.na(pr_id),
                                   file.path(scratch_path, pr_dataset_name,
                                             binding_pr_set_name, "pr", "effect",
                                             paste0(pr_id, ".csv")),
                                   NA_character_),
               pr_pvalue = if_else(!is.na(pr_id),
                                   file.path(scratch_path, pr_dataset_name,
                                             binding_pr_set_name, "pr", "pvalue",
                                             paste0(pr_id, ".csv")),
                                   NA_character_))

    # Separate complete and incomplete cases
    complete_lookup = lookup_df %>%
        filter(!is.na(binding_id) & !is.na(pr_id)) %>%
        select(binding, pr_effect, pr_pvalue)

    incomplete_after_filtering = lookup_df %>%
        filter(is.na(binding_id) | is.na(pr_id)) %>%
        mutate(missing_type = case_when(
            is.na(binding_id) & is.na(pr_id) ~ "both",
            is.na(binding_id) ~ "binding",
            is.na(pr_id) ~ "pr",
            TRUE ~ "unknown"
        )) %>%
        select(regulator_locus_tag, binding_id, pr_id, missing_type) %>%
        distinct()  # Add distinct here too to avoid duplicate incomplete rows

    return(list(
        lookup = complete_lookup,
        incomplete_after_filtering = incomplete_after_filtering
    ))
}
# Create background lists for all PR datasets (if not already created)
all_pr_backgrounds = map(names(all_pr_dtos), ~{
    map(binding_data, function(bd) {
        bd %>%
            ungroup() %>%
            select(target_locus_tag) %>%
            distinct() %>%
            filter(target_locus_tag %in% unique(all_pr_dtos[[.x]][[1]]$pr$target_locus_tag))
    })
})
names(all_pr_backgrounds) = names(all_pr_dtos)

# Write out all DTOs for all PR datasets
lookup_results = list()

dto_input_outdir = here("results/dto")
for (pr_name in names(all_pr_dtos)) {
    lookup_results[[pr_name]] = list()

    for (binding_name in names(all_pr_dtos[[pr_name]])) {
        write_out_pr_dto_lists(pr_name, binding_name, all_pr_dtos)
        write_pr_background(pr_name, binding_name, all_pr_backgrounds[[pr_name]])

        lookup_result = create_pr_lookups(pr_name, binding_name, all_pr_dtos)
        lookup_results[[pr_name]][[binding_name]] = lookup_result

        # Write complete lookups only
        lookup_result$lookup %>%
            write_tsv(file.path(dto_input_outdir, pr_name, binding_name, "lookup.txt"),
                      col_names = FALSE)

        # Write incomplete cases for reference
        if (nrow(lookup_result$incomplete_after_filtering) > 0) {
            lookup_result$incomplete_after_filtering %>%
                write_csv(file.path(dto_input_outdir, pr_name, binding_name, "incomplete.csv"))
        }
    }
}

# Summary of incomplete cases across all datasets
incomplete_summary = map_dfr(names(lookup_results), ~{
    map_dfr(names(lookup_results[[.x]]), function(binding_name) {
        lookup_results[[.x]][[binding_name]]$incomplete_after_filtering %>%
            mutate(pr_dataset = .x, binding_dataset = binding_name)
    })
})

print(incomplete_summary %>% count(pr_dataset, binding_dataset, missing_type))

dto_results_path_list = list.files(base_outdir,
                              "*.json",
                              recursive = TRUE)

## Parse the results -- note that this needs to be adjusted for the
## expanded set of perturbation response

dto_results_frames_list = map(file.path(base_outdir, dto_results_path_list),
                              ~as_tibble(jsonlite::read_json(.x)))
names(dto_results_frames_list) = dto_results_path_list
dto_results_frame = bind_rows(dto_results_frames_list, .id = 'path')

curr_dto_res = arrow::open_dataset("~/code/hf/yeast_comparative_analysis/dto") %>%
    collect()

results_df = tibble(
    combined_id = str_remove(basename(dto_results_list), ".json"),
    binding_source = dirname(dirname(dirname(dirname(dto_results_list)))),
    pr_scoring = basename(dirname(dto_results_list)),
    path = dto_results_path_list) %>%
    separate_wider_delim(combined_id,
                         names = c('binding_sampleid', 'pr_sampleid'),
                         delim = '-_-') %>%
    left_join(dto_results_frame) %>%
    select(-path) %>%
    mutate(
        binding_id = case_when(
            binding_source == "cc" & str_detect(binding_sampleid, "-")
            ~ paste0("BrentLab/callingcards;annotated_features_combined",
                     binding_sampleid),
            binding_source == "cc" & str_detect(binding_sampleid, "-", negate=TRUE)
            ~ paste0("BrentLab/callingcards;annotated_features",
                     binding_sampleid),
            binding_source == "chipexo"
            ~ paste0("BrentLab/rossi_2021;rossi_2021_af_combined",
                     binding_sampleid),
            binding_source == "harbison"
            ~ paste0("BrentLab/harbison_2004;harbison_2004",
                     binding_sampleid),
            binding_source == "mahendrawada_chec"
            ~ paste0("BrentLab/mahendrawada_2025;chec_mahendrawada_m2025_af_combined",
                     binding_sampleid)),
        perturbation_id = paste0("BrentLab/mahendrawada_2025/rnaseq_reprocessed", pr_sampleid),
        binding_repo_dataset = case_when(
            binding_source == "cc" & str_detect(binding_sampleid, "-")
            ~ "callingcards-annotated_features_combined",
            binding_source == "cc" & str_detect(binding_sampleid, "-", negate=TRUE)
            ~ "callingcards-annotated_features",
            binding_source == "chipexo"
            ~ "rossi_2021-rossi_2021_af_combined",
            binding_source == "harbison"
            ~ paste0("harbison_2004-harbison_2004"),
            binding_source == "mahendrawada_chec"
            ~ "mahendrawada_2025-chec_mahendrawada_m2025_af_combined"),
        perturbation_repo_dataset = "mahendrawada_2025-rnaseq_reprocessed") %>%
    dplyr::rename(binding_rank_threshold = rank1,
                  perturbation_rank_threshold = rank2,
                  binding_set_size = set1_len,
                  perturbation_set_size = set2_len,
                  dto_fdr = fdr,
                  dto_empirical_pvalue = empirical_pvalue) %>%
    select(binding_id, perturbation_id,
           binding_rank_threshold, perturbation_rank_threshold,
           binding_set_size, perturbation_set_size,
           dto_fdr, dto_empirical_pvalue,
           binding_repo_dataset, perturbation_repo_dataset)

# arrow::write_dataset(
#     results_df,
#     path = "/home/chase/code/hf/yeast_comparative_analysis/dto",
#     format = "parquet",
#     partitioning = c("binding_repo_dataset", "perturbation_repo_dataset"),
#     existing_data_behavior = "overwrite",
#     compression = "zstd",
#     write_statistics = TRUE,
#     use_dictionary = c(
#         binding_id = TRUE,
#         perturbation_id = TRUE
#     )
# )