-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathairtool.qmd
More file actions
executable file
·5355 lines (4564 loc) · 191 KB
/
airtool.qmd
File metadata and controls
executable file
·5355 lines (4564 loc) · 191 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
---
title: "AIR -- This is prototype software, use without warranty."
format:
dashboard:
theme: spacelab
orientation: columns
# embed-resources: true
header-includes:
- '<meta name="color-scheme" content="light">'
resources:
- readme_md_files
server: shiny
---
```{=html}
<style>
.plot-container, .shiny-text-output, .panel, .card {
border: none;
box-shadow: none;
}
.custom-text {
font-size: 20px;
color: green;
font-weight: bold;
}
/* FILE-INPUT */
/* Browse button base look (unchanged colour) */
.shiny-input-container .btn-file{
background:#1976d2 !important;
color:#fff !important;
border:0 !important;
border-radius:4px !important;
box-shadow:none !important;
padding:8px 16px;
text-transform:uppercase;
transition:box-shadow .2s cubic-bezier(.4,0,.2,1);
}
/* Hover / focus — add the same elevation you see on other buttons */
.shiny-input-container .btn-file:hover,
.shiny-input-container .btn-file:focus{
background:#1976d2 !important; /* stay blue */
box-shadow:0 4px 6px rgba(0,0,0,.25); /* subtle, matches rest */
outline:0;
}
/* Active click (tiny dip) */
.shiny-input-container .btn-file:active{
background:#1565c0 !important;
box-shadow:0 2px 4px rgba(0,0,0,.25);
}
/* Progress bar wrapper — push down & fill width */
.shiny-input-container .shiny-file-input-progress{
display:block;
width:100%;
margin:10px 0 0 0; /* 10 px top margin fixes overlap */
}
/* Progress bar track & fill */
.shiny-input-container .progress{
height:8px; /* less “squished” */
margin:0;
border-radius:4px;
}
.shiny-input-container .progress-bar{
background:#1976d2;
border-radius:4px;
}
/* progress bar separation */
/* The bar itself (not the wrapper) needs the margin */
.progress.shiny-file-input-progress {
margin-top: 10px; /* pushes bar below Browse button */
}
/* let the shadow show through */
.shiny-input-container .btn-file {
overflow: visible !important; /* un-clip shadow */
}
/* optional: trim the corner radius a bit more */
.shiny-input-container .btn-file,
.progress.shiny-file-input-progress {
border-radius: 2px !important; /* crisper corners */
}
/* for Browse buttons & progress bar */
.shiny-input-container .btn-file { box-shadow:none; } /* reset */
.shiny-input-container .btn-file:hover,
.shiny-input-container .btn-file:focus { box-shadow:0 4px 8px rgba(0,0,0,.30)!important; }
.progress.shiny-file-input-progress,
.progress.shiny-file-input-progress .progress-bar{
height:12px;
border-radius:4px;
background:#1976d2;
background-image:none!important; /* kill default stripes/dots */
}
/* optional tighter corners */
.shiny-input-container .btn-file { border-radius:2px; }
</style>
<style> .main-container { max-width: unset; } </style>
<div id="style-test" style="background-color: white; color: black; position: absolute; left: -9999px;"></div>
<!-- Hidden element for detecting overridden styles -->
<div id="style-test" style="background-color: white; color: black; display: none;"></div>
<script>
document.addEventListener("DOMContentLoaded", () => {
const testElem = document.getElementById("style-test");
if (!testElem) return;
const computedBg = window.getComputedStyle(testElem).backgroundColor;
const computedColor = window.getComputedStyle(testElem).color;
if (computedBg !== "rgb(255, 255, 255)" || computedColor !== "rgb(0, 0, 0)") {
alert("It appears a dark mode extension might be overriding the styles. Please disable it for the best experience.");
}
});
</script>
```
```{r initial-setup}
#| context: setup
#| echo: false
#| include: false
# Choose conservative defaults for general users
DEFAULT_XMS_GB <- 1 # 1g initial heap
DEFAULT_XMX_GB <- 4 # 4g max heap
# Hard safety ceilings so some lunatic doesn't ask for 5000g on a ThinkPad
MAX_ALLOWED_GB <- 256 # tune this to whatever you consider sane
read_heap_gb <- function(var, default_val) {
raw <- Sys.getenv(var, unset = "")
if (!nzchar(raw)) {
return(default_val)
}
# numeric conversion with basic sanity checks
val <- suppressWarnings(as.numeric(raw))
if (is.na(val)) {
return(default_val)
}
# must be positive
if (val <= 0) {
return(default_val)
}
# cap outrageous requests
val <- min(val, MAX_ALLOWED_GB)
# floor to integer GB (JVM wants clean "16g", not "16.2g")
floor(val)
}
calc_heap_settings <- function() {
xms_gb <- read_heap_gb("AIR_JAVA_XMS_GB", DEFAULT_XMS_GB)
xmx_gb <- read_heap_gb("AIR_JAVA_XMX_GB", DEFAULT_XMX_GB)
# ensure logical ordering: Xms <= Xmx
if (xms_gb > xmx_gb) {
# if user fat-fingered it, bump max up to match min
xmx_gb <- xms_gb
}
list(
xms_gb = xms_gb,
xmx_gb = xmx_gb
)
}
heap <- calc_heap_settings()
params <- c(
paste0("-Xms", heap$xms_gb, "g"),
paste0("-Xmx", heap$xmx_gb, "g")
)
options(shiny.maxRequestSize = Inf)
suppressMessages({
library(AIPW)
library(base64enc)
library(DiagrammeR)
library(DiagrammeRsvg) # SVG export
library(doParallel)
library(dplyr)
library(e1071)
library(earth)
library(foreach)
library(ggplot2)
library(hal9001)
library(hash)
library(here)
library(jsonlite)
library(logger)
library(nnet)
library(rJava)
library(randomForest)
library(readr)
library(rpart)
library(rsvg)
library(scales)
library(sets)
library(shiny)
library(shinyjs)
library(shinyWidgets)
library(sl3)
library(tidyr)
library(tmle3)
library(xgboost)
library(xml2)
})
## ── session-wide defaults ───────────────────────────────────────────────
AIRHome <- here::here()
setwd(AIRHome)
log_dir <- file.path(AIRHome, "logs")
dir.create(log_dir, recursive = TRUE, showWarnings = FALSE)
# ── guard: run heavy log setup only once per R-session ───────────────────
if (exists(".airtool_log_init", envir = .GlobalEnv)) {
log_file <- get(".airtool_log_file", envir = .GlobalEnv)
} else {
log_file <- file.path(
log_dir,
strftime(Sys.time(), "%Y-%m-%d_%H-%M-%S"),
"airtool.log"
)
dir.create(dirname(log_file), recursive = TRUE, showWarnings = FALSE)
assign(".airtool_log_init", TRUE, .GlobalEnv)
assign(".airtool_log_file", log_file, .GlobalEnv)
}
## ── 1. logger setup ----------------------------------------------------
logger::log_threshold("DEBUG")
layout_plain <- function(level, msg, namespace, .logcall, .topcall, .topenv) {
sprintf("%s [%s] %s", level, format(Sys.time(), "%Y-%m-%d %H:%M:%S"), as.character(msg))
}
logger::log_layout(layout_plain)
logger::log_appender(logger::appender_file(log_file))
for (nm in c("debug", "info", "warn", "error")) {
f <- get(paste0("log_", nm), envir = asNamespace("logger"))
assign(paste0("log_", nm), f, .GlobalEnv)
}
log_info("AIR Tool startup – log initialised.")
## ── 2. Logging connections: anchor in globalenv! ------------------------
if (!exists(".airtool_log_con", envir = .GlobalEnv)) {
log_con <- file(log_file, open = "a")
assign(".airtool_log_con", log_con, .GlobalEnv)
} else {
log_con <- get(".airtool_log_con", envir = .GlobalEnv)
}
## Quarto/knitr needs stdout for a while; only divert messages
sink(log_con, append = TRUE, type = "message")
## ── 3. Clean-up: only close what we opened, and ONLY at process end -----
.on_session_end <- function(...) {
# Remove all sinks attached to this connection
if (sink.number(type = "message") > 0)
sink(type = "message")
if (exists(".airtool_log_con", envir = .GlobalEnv)) {
con <- get(".airtool_log_con", .GlobalEnv)
if (isOpen(con)) close(con)
rm(".airtool_log_con", envir = .GlobalEnv)
}
}
reg.finalizer(.GlobalEnv, .on_session_end, onexit = TRUE)
if ("shiny" %in% loadedNamespaces()) {
shiny::onStop(.on_session_end)
} else {
setHook(packageEvent("shiny", "onLoad"),
function(...) shiny::onStop(.on_session_end),
action = "append")
}
## --- JVM streams, stack trace, log pruning as before ---
redirect_java_streams <- function(target) {
fos <- rJava::.jnew("java/io/FileOutputStream", target, TRUE)
os <- rJava::.jcast(fos, "java/io/OutputStream")
ps <- rJava::.jnew("java/io/PrintStream", os)
rJava::.jcall("java/lang/System", "V", "setOut", ps)
rJava::.jcall("java/lang/System", "V", "setErr", ps)
}
options(
shiny.fullstacktrace = TRUE,
error = function() {
logger::log_error(paste(capture.output(traceback(20L)), collapse = "\n"))
invokeRestart("abort")
}
)
time_threshold <- Sys.time() - 30 * 24 * 60 * 60
old_logs <- list.files(log_dir, full.names = TRUE, recursive = TRUE)
old_logs <- old_logs[file.info(old_logs)$mtime < time_threshold]
if (length(old_logs)) file.remove(old_logs)
theme_set(ggplot2::theme_gray(base_family = "DejaVu Sans")) # ggplot, grid, etc.
#options(warn = 2)
#options(shiny.trace = TRUE)
options(
shiny.fullstacktrace = TRUE,
shiny.error = function() {
cat("\n=== SHINY ERROR =========================================\n")
print(sys.calls())
cat("---------------------------------------------------------\n")
# re-throw so Shiny still shows the UI banner
geterrmessage()
}
)
set.seed(123)
## Also tell the R graphics device so axis labels use it too
grDevices::png(type = "cairo") # ensure Pango/Cairo backend
par(family = "DejaVu Sans") # default plotting family
# Constants for Java JDK URLs
TETRAD_PATH <- Sys.getenv("TETRAD_PATH")
if (TETRAD_PATH == "") {
stop("The TETRAD_PATH environment variable is not set. Please set it to the path of the Tetrad jar.")
}
# ––– shield any .jcall from killing R –––––––––––––––––––––––––––––––––
safe_jcall <- function(...) {
tryCatch(
.jcall(...),
Throwable = function(e) {
msg <- .jcall("java/lang/Throwable", "S", "toString", e)
log_debug("Java exception trapped: {msg}", msg = msg)
NULL # propagate safe NULL
}
)
}
# make it visible to Reference-class methods & workers
assign("safe_jcall", safe_jcall, envir = .GlobalEnv)
# ----- Initialize Java and Check Version -----
initialize_java <- function() {
.jinit(parameters = params)
.jaddClassPath(get_tetrad_path())
java_version <- safe_jcall("java/lang/System", "S", "getProperty", "java.version")
print(paste("Java version:", java_version))
}
# ── helper: always return a usable TETRAD class-path ────────────────────
get_tetrad_path <- function() {
if (exists("TETRAD_PATH", envir = .GlobalEnv) &&
nzchar(get("TETRAD_PATH", envir = .GlobalEnv))) {
return(get("TETRAD_PATH", envir = .GlobalEnv))
}
## fall back to the environment variable if the symbol vanished
Sys.getenv("TETRAD_PATH", unset = "")
}
# make it visible everywhere
assign("get_tetrad_path", get_tetrad_path, envir = .GlobalEnv)
initialize_java()
redirect_java_streams(log_file)
# ── one-stop Java ⇢ DOT helper ───────────────────────────────────────
graph_to_dot <- function(graph) {
dot <- safe_jcall(
"edu/cmu/tetrad/graph/GraphSaveLoadUtils",
"Ljava/lang/String;",
"graphToDot",
graph
)
if (is.null(dot) || !nzchar(dot)) {
log_warn("graphToDot() returned empty result.")
return("") # harmless for grViz()
}
dot
}
# make it visible to Reference-class methods & parallel workers
assign("graph_to_dot", graph_to_dot, envir = .GlobalEnv)
```
```{r session-setup}
#| context: server
#| echo: false
# --- Buffers --- #
results_buffer <- reactiveVal(data.frame())
results_out_buffer <- reactiveVal(data.frame())
datafile_buffer <- reactiveVal(NULL)
superlearner_output_buffer <- reactiveVal(list())
graphtxt_buffer <- reactiveVal(NULL)
dotfile_buffer <- reactiveVal(NULL)
rv <- reactiveValues()
locked <- reactiveVal(FALSE)
step1lock <- reactiveVal(FALSE)
# ── NEW: keep TMLE rows, ML rows, and the 1-row summary apart ────────────────
tmle_buffer <- reactiveVal(data.frame()) # 1 row per adjustment set
ml_buffer <- reactiveVal(data.frame()) # 1 row per ML algorithm
combined_buffer <- reactiveVal(data.frame()) # exactly 1 row (ribbon plot)
classifier_buffer <- reactiveVal(NULL) # all 5 classifier ATEs ("No" mode only)
# create a shared reactiveValues object to pass variables around
rv$dot <- NULL # define once in app init
# --- BEGIN INLINE: scripts/AIR_functions.R ---
getLocalTags <- function() {
if (!isLocal()) {
return(NULL)
}
htmltools::tagList(
htmltools::tags$script(paste0(
"$(function() {",
" $(document).on('shiny:disconnected', function(event) {",
" $('#ss-connect-dialog').show();",
" $('#ss-overlay').show();",
" })",
"});"
)),
htmltools::tags$div(
id="ss-connect-dialog", style="display: none;",
htmltools::tags$a(id="ss-reload-link", href="#", onclick="window.location.reload(true);")
),
htmltools::tags$div(id="ss-overlay", style="display: none;")
)
}
isLocal <- function() {
Sys.getenv("SHINY_PORT", "") == ""
}
disconnectMessage <- function(
text = "An error occurred. Please refresh the page and try again.",
refresh = "Refresh",
width = 450,
top = 50,
size = 22,
background = "white",
colour = "#444444",
overlayColour = "black",
overlayOpacity = 0.6,
refreshColour = "#337ab7",
css = ""
) {
checkmate::assert_string(text, min.chars = 1)
checkmate::assert_string(refresh)
checkmate::assert_numeric(size, lower = 0)
checkmate::assert_string(background)
checkmate::assert_string(colour)
checkmate::assert_string(overlayColour)
checkmate::assert_number(overlayOpacity, lower = 0, upper = 1)
checkmate::assert_string(refreshColour)
checkmate::assert_string(css)
if (width == "full") {
width <- "100%"
} else if (is.numeric(width) && width >= 0) {
width <- paste0(width, "px")
} else {
stop("disconnectMessage: 'width' must be either an integer, or the string \"full\".", call. = FALSE)
}
if (top == "center") {
top <- "50%"
ytransform <- "-50%"
} else if (is.numeric(top) && top >= 0) {
top <- paste0(top, "px")
ytransform <- "0"
} else {
stop("disconnectMessage: 'top' must be either an integer, or the string \"center\".", call. = FALSE)
}
htmltools::tagList(
getLocalTags(),
htmltools::tags$head(
htmltools::tags$style(
glue::glue(
.open = "{{", .close = "}}",
"#shiny-disconnected-overlay { display: none !important; }",
"#ss-overlay {
background-color: {{overlayColour}} !important;
opacity: {{overlayOpacity}} !important;
position: fixed !important;
top: 0 !important;
left: 0 !important;
bottom: 0 !important;
right: 0 !important;
z-index: 99998 !important;
overflow: hidden !important;
cursor: not-allowed !important;
}",
"#ss-connect-dialog {
background: {{background}} !important;
color: {{colour}} !important;
width: {{width}} !important;
transform: translateX(-50%) translateY({{ytransform}}) !important;
font-size: {{size}}px !important;
top: {{top}} !important;
position: fixed !important;
bottom: auto !important;
left: 50% !important;
padding: 0.8em 1.5em !important;
text-align: center !important;
height: auto !important;
opacity: 1 !important;
z-index: 99999 !important;
border-radius: 3px !important;
box-shadow: rgba(0, 0, 0, 0.3) 3px 3px 10px !important;
}",
"#ss-connect-dialog::before { content: '{{text}}' }",
"#ss-connect-dialog label { display: none !important; }",
"#ss-connect-dialog a {
display: {{ if (refresh == '') 'none' else 'block' }} !important;
color: {{refreshColour}} !important;
font-size: 0 !important;
margin-top: {{size}}px !important;
font-weight: normal !important;
}",
"#ss-connect-dialog a::before {
content: '{{refresh}}';
font-size: {{size}}px;
}",
"#ss-connect-dialog { {{ htmltools::HTML(css) }} }"
)
)
)
)
}
#' Show a nice message when a shiny app disconnects or errors
#'
#' This function is a version of disconnectMessage() with a pre-set combination
#' of parameters that results in a large centered message.
#' @export
disconnectMessage2 <- function() {
disconnectMessage(
text = "Your session has timed out.",
refresh = "",
size = 70,
colour = "white",
background = "rgba(64, 64, 64, 0.9)",
width = "full",
top = "center",
overlayColour = "#999",
overlayOpacity = 0.7,
css = "padding: 15px !important; box-shadow: none !important;"
)
}
# ── tiny validation helpers ──────────────────────────────────────────────
check_numeric <- function(x, min = -Inf, max = Inf, id = "") {
shiny::validate(
shiny::need(is.numeric(x) && length(x) == 1 && is.finite(x),
sprintf("[%s] must be a single numeric value", id)),
shiny::need(x >= min && x <= max,
sprintf("[%s] must be between %g and %g", id, min, max))
)
x
}
check_column_exists <- function(df, col, id = "") {
shiny::validate(
shiny::need(!is.null(df),
sprintf("Data not loaded, can’t check %s yet", id)),
shiny::need(col %in% names(df),
sprintf("Column “%s” not found (%s)", col, id))
)
col
}
escape_dot <- function(x) gsub('[^\\w\\s]', '_', x, perl = TRUE) # DOT-safe
# keeps thresholds inside the data range and numeric
safe_thresh <- function(val, vec, id) {
rng <- range(vec, na.rm = TRUE)
check_numeric(val, rng[1], rng[2], id)
}
fix_knowledge <- function(df){
# Store original column names
original_colnames <- colnames(df)
# Detect numeric vs non-numeric columns
numeric_cols <- sapply(df, function(col) all(!is.na(suppressWarnings(as.numeric(as.character(col))))))
# check if column header is missing and data conform to expectations. If so, process and return
if (any(!is.na(suppressWarnings(as.numeric(original_colnames))))) {
# Confirm exactly one numeric and one character-type column exist
if (sum(numeric_cols) == 1 && sum(!numeric_cols) == 1) {
new_colnames <- c("level", "variable")
new_colnames_ordered <- rep(NA, length(df))
new_colnames_ordered[numeric_cols] <- "level"
new_colnames_ordered[!numeric_cols] <- "variable"
# Move original column names to first row
df <- rbind(setNames(as.list(original_colnames), names(df)), df)
# Now assign the new column names
colnames(df) <- new_colnames_ordered
} else {
return("Unable to read knowledge file data. Please make sure file contains a header with the following column names: level, variable. 'variable' should contain the name of each variable used, and 'level' should be a numeric value to represent an estimated causal hierarchy (see readme file for a detailed description).")
}
} else if (sum(numeric_cols) == 1 && sum(!numeric_cols) == 1) {
colnames(df)[numeric_cols] <- "level"
colnames(df)[!numeric_cols] <- "variable"
} else {
return("Unable to read knowledge file data. Please make sure file contains a header with the following column names: level, variable. 'variable' should contain the name of each variable used, and 'level' should be a numeric value to represent an estimated causal hierarchy (see readme file for a detailed description).")
}
return(df)
}
# change color of nodes in graph
change_node_color <- function(dot_code, node, color) {
node <- escape_dot(node)
# Remove any accidental extra quotes from the color string
color <- trimws(gsub("['\"]", "", color))
node_definition <- paste0("\"", node, "\" [style=filled, fillcolor=\"", color, "\"];")
dot_code <- sub("digraph g \\{", paste0("digraph g {\n ", node_definition), dot_code)
dot_code <- gsub("\'", "\"", dot_code)
return(dot_code)
}
paint_nodes <- function(dot, nodes, col) {
nodes <- nodes[nzchar(nodes)]
for (n in nodes) {
dot <- change_node_color(dot, n, col)
}
dot
}
AIR_getGraph <- function(data, knowledge, graphtxt_buffer = NULL) {
headers_string <- "PD\tfrac_ind\tfrac_dep\tunif\t \tBIC\t \t#edges\tn_tests_ind\tn_tests_dep"
log_debug(headers_string)
r_df_to_tetrad <- function(df) {
require(rJava)
log_debug("r_df_to_tetrad(): START")
n_rows <- nrow(df)
n_cols <- ncol(df)
log_debug("Rows: {r}, Cols: {c}", r = n_rows, c = n_cols)
# ------------------ VARS LIST ------------------
log_debug("Constructing vars ArrayList...")
vars <- .jnew("java.util.ArrayList")
log_debug("vars class = {cls}", cls = .jclass(vars))
log_debug("Adding ContinuousVariables...")
for (name in names(df)) {
log_debug(" Creating variable for column '{nm}'", nm = name)
v <- .jnew("edu.cmu.tetrad.data.ContinuousVariable", as.character(name))
log_debug(" OK: created; class={cls}", cls = .jclass(v))
vars$add(v)
log_debug(" OK: added to list")
}
log_debug("Casting vars → java.util.List...")
vars_list <- .jcast(vars, "java.util.List")
log_debug("vars_list class = {cls}", cls = .jclass(vars_list))
# ------------------ DATA BOX ------------------
log_debug("Constructing DoubleDataBox...")
dbox <- .jnew(
"edu.cmu.tetrad.data.DoubleDataBox",
as.integer(n_rows),
as.integer(n_cols)
)
log_debug("dbox class = {cls}", cls = .jclass(dbox))
log_debug("Setting DoubleDataBox values...")
for (j in seq_len(n_cols)) {
col <- as.numeric(df[[j]])
log_debug(" Column {j}: length={len}", j = j, len = length(col))
for (i in seq_len(n_rows)) {
# Create a java.lang.Double
dbl <- .jnew("java.lang.Double", col[i])
dbox$set(
as.integer(i - 1L),
as.integer(j - 1L),
dbl
)
}
}
log_debug("Finished populating DoubleDataBox.")
log_debug("Casting dbox → DataBox...")
dbox_cast <- .jcast(dbox, "edu.cmu.tetrad.data.DataBox")
log_debug("dbox_cast class = {cls}", cls = .jclass(dbox_cast))
# ------------------ DATASET ------------------
log_debug("Constructing BoxDataSet...")
dataset <- .jnew(
"edu.cmu.tetrad.data.BoxDataSet",
dbox_cast,
vars_list
)
log_debug("dataset created; class = {cls}", cls = .jclass(dataset))
log_debug("Casting dataset → DataSet interface...")
dataset_cast <- .jcast(dataset, "edu.cmu.tetrad.data.DataSet")
log_debug("dataset_cast class = {cls}", cls = .jclass(dataset_cast))
log_debug("r_df_to_tetrad(): SUCCESS")
return(dataset_cast)
}
np_dataset_to_df <- function(j_np_dataset, orig_names = NULL) {
require(rJava)
log_debug("np_dataset_to_df(): START")
# Get the underlying Matrix: dataSet.getDoubleData()
j_mat <- .jcall(
j_np_dataset,
"Ledu/cmu/tetrad/util/Matrix;",
"getDoubleData"
)
log_debug("np_dataset_to_df(): got Matrix; class={cls}", cls = .jclass(j_mat))
n_rows <- .jcall(j_mat, "I", "getNumRows")
n_cols <- .jcall(j_mat, "I", "getNumColumns")
log_debug("np_dataset_to_df(): rows={r}, cols={c}", r = n_rows, c = n_cols)
# Pull values via Matrix.get(int row, int col)
mat <- matrix(NA_real_, n_rows, n_cols)
for (i in seq_len(n_rows)) {
for (j in seq_len(n_cols)) {
mat[i, j] <- .jcall(
j_mat,
"D",
"get",
as.integer(i - 1L),
as.integer(j - 1L)
)
}
}
df <- as.data.frame(mat)
if (!is.null(orig_names) && length(orig_names) == n_cols) {
colnames(df) <- orig_names
}
log_debug("np_dataset_to_df(): DONE; returning data.frame with names = {n}",
n = paste(colnames(df), collapse = ", "))
df
}
nonparanormal_transform <- function(j_dataset) {
j_dataset <- .jcast(j_dataset, "edu.cmu.tetrad.data.DataSet")
.jcall(
"edu/cmu/tetrad/data/DataTransforms",
returnSig = "Ledu/cmu/tetrad/data/DataSet;",
method = "getNonparanormalTransformed",
j_dataset,
sig = "(Ledu/cmu/tetrad/data/DataSet;)Ledu/cmu/tetrad/data/DataSet;"
)
}
# 1. Build Java dataset and NP transform
isbinary <- apply(data, MARGIN = 2, FUN = function(x) {length(unique(x))==2 })
log_debug("nvars: {ib}", ib = paste0(isbinary, collapse = ", "))
data_binary <- data[, isbinary, drop = FALSE]
data_continuous <- data[, !isbinary, drop = FALSE]
log_debug("Discovered {db} binary and {dc} continuous columns...", db = ncol(data_binary), dc = ncol(data_continuous))
j_dataset <- r_df_to_tetrad(data_continuous)
log_debug("Class after java transform: {cls}", cls = .jclass(j_dataset))
j_np_dataset <- nonparanormal_transform(j_dataset)
log_debug("Class after NP transform: {cls}", cls = .jclass(j_np_dataset))
# 2. Convert NP dataset back to an R data.frame
#np_df <- np_dataset_to_df(j_np_dataset, orig_names = names(data))
np_df <- np_dataset_to_df(j_np_dataset, orig_names = names(data_continuous))
np_df <- cbind(data_binary, np_df)
log_debug("After NP back to R: class={cls}", cls = paste(class(np_df), collapse = ", "))
# optional:
# log_debug(paste(capture.output(dplyr::glimpse(np_df)), collapse = "\n"))
MC_passing_cpdag_already_found <- FALSE
best_cpdag_seen_so_far <- NULL
best_cpdag_seen_so_far_num_edges <- Inf
best_cpdag_seen_so_far_params <- "<unset>"
cpdag_graph_when_PD_is_1 <- NULL
last_ts <- NULL
suppress_output <- function(expr) {
sink("/dev/null")
on.exit(sink(), add = TRUE)
force(expr)
}
for (i in seq(0, 15)) {
pd <- 0.5 + (i * 0.1)
tryCatch({
ts <- TetradSearch$new(np_df)
last_ts <- ts
# Validate and apply knowledge tiers
if (!is.null(knowledge) && nrow(knowledge) > 0) {
if (!all(c("level", "variable") %in% colnames(knowledge))) {
log_debug("Knowledge file is missing required columns 'level' and 'variable'; skipping tier assignment.")
} else {
# Add knowledge to specific tiers
for (j in seq_len(nrow(knowledge))) {
level <- knowledge$level[j]
variable <- knowledge$variable[j]
if (is.numeric(level) && is.character(variable)) {
tryCatch({
ts$add_to_tier(level, variable)
}, error = function(e) {
log_debug(sprintf("Failed to add variable '%s' to tier %s: %s",
as.character(variable), as.character(level), conditionMessage(e)))
})
} else {
log_debug(sprintf("Invalid knowledge row at index %d: level=%s, variable=%s",
j, deparse(level), deparse(variable)))
}
}
}
}
ts$use_sem_bic(penalty_discount = pd)
suppress_output(ts$run_boss())
g2 <- ts$get_java()
bic <- tryCatch(g2$getAttribute("BIC"), error = function(e) NA_real_)
num_edges <- tryCatch(g2$getNumEdges(), error = function(e) NA_integer_)
suppress_output(ts$use_fisher_z(use_for_mc = TRUE))
ret <- suppress_output(ts$markov_check(g2))
cpdag_graph_when_PD_is_1 <- g2
result_line <- tryCatch({
sprintf("%.1f\t%.4f \t%.4f \t%.4f \t%.2f \t%.0f \t%.0f \t\t%.0f", pd, ret$frac_dep_ind, ret$frac_dep_dep, ret$ad_ind, bic, num_edges, ret$num_tests_ind, ret$num_tests_dep)
}, error = function(e) {
"<incomplete>"
})
if (!is.null(ret) && is.list(ret) && !is.null(ret$ad_ind) && ret$ad_ind > 0.1) {
log_debug(result_line)
if (!MC_passing_cpdag_already_found || (num_edges < best_cpdag_seen_so_far_num_edges)) {
best_cpdag_seen_so_far <- g2
best_cpdag_seen_so_far_num_edges <- num_edges
best_cpdag_seen_so_far_params <- result_line
MC_passing_cpdag_already_found <- TRUE
}
}
# If PD==1.0 and still no valid CPDAG found, keep something usable
if (pd == 1.0 && is.null(best_cpdag_seen_so_far)) {
best_cpdag_seen_so_far <- g2
best_cpdag_seen_so_far_num_edges <- num_edges
best_cpdag_seen_so_far_params <- result_line
}
}, error = function(e) {
log_debug(sprintf("Failed iteration for PD=%.1f: %s", pd, conditionMessage(e)))
})
}
# Bail out early if absolutely nothing passed any threshold
if (!MC_passing_cpdag_already_found && is.null(cpdag_graph_when_PD_is_1)) {
stop(structure(
list(
message = "No valid graph found; TetradSearch may have failed",
call = match.call()
),
class = c("simpleError", "error", "condition")
))
}
log_debug("The best cpdag (the one with fewest edges among those for which unif > 0.1) has these attributes:")
log_debug(headers_string)
log_debug(best_cpdag_seen_so_far_params)
graph <- if (!is.null(best_cpdag_seen_so_far)) {
# A valid CPDAG passed Markov Check
best_cpdag_seen_so_far
} else {
# Nothing passed, but fallback to something rather than crashing
log_debug("Falling back to cpdag at PD=1.0, as no unif > 0.1 CPDAG was found")
cpdag_graph_when_PD_is_1
}
graph_str <- tryCatch(
graph_to_dot(graph)
)
if (!is.null(graphtxt_buffer)) {
if (is.null(graph_str) || !nzchar(graph_str)) {
log_debug("graph_str is NULL or empty, not updating graphtxt_buffer.")
graphtxt_buffer(NULL)
} else {
graphtxt_buffer(
tryCatch(
gsub("(?s)Graph Attributes:.*", "", graph_str, perl = TRUE),
error = function(e) {
log_debug(sprintf("Regex failed on graph_str: %s", conditionMessage(e)))
graph_str # fallback to raw string
}
)
)
}
}
return(list(graph, last_ts, MC_passing_cpdag_already_found, best_cpdag_seen_so_far))
}
AIR_getAdjSets <- function(ts, tv, ov, MC_passing_cpdag_already_found, best_cpdag_seen_so_far){
TREATMENT_NAME = tv
RESPONSE_NAME = ov
MAX_NUM_SETS = 3
MAX_DISTANCE_FROM_POINT = 4
MAX_PATH_LENGTH = 4
NEAR_TREATMENT = 1
NEAR_RESPONSE = 2
log_debug("Identification parameters:")
log_debug("maximum number of adjustment sets = {p}", p = MAX_NUM_SETS)
log_debug("maximum distance from target endpoint (TREATMENT or RESPONSE) = {p}", p = MAX_DISTANCE_FROM_POINT)
log_debug("maximum path length = {p}", p = MAX_PATH_LENGTH)
len_adj_sets_t <- 0
len_adj_sets_r <- 0
union_of_two_lists <- NULL
count_undirected_from_dot <- function(dot_text) {
lines <- strsplit(dot_text, "\n")[[1]]
undirected <- grep("arrowtail=none[^]]*arrowhead=none", lines, value = TRUE)
length(undirected)
}
undirected_edges <- count_undirected_from_dot(rv$dot)
log_debug("Number of undirected edges found: {ue}", ue = undirected_edges)
#if (MC_passing_cpdag_already_found == TRUE) {
log_debug("Searching for adjustment set(s) on the *** Treatment *** side:")
# Z1
adj_sets_treatment = ts$get_adjustment_sets(best_cpdag_seen_so_far, TREATMENT_NAME, RESPONSE_NAME,
MAX_NUM_SETS,
MAX_DISTANCE_FROM_POINT,
NEAR_TREATMENT,
MAX_PATH_LENGTH)
ts$print_adjustment_sets(adj_sets_treatment)