Spaces:
Running
Running
Update app.R
Browse files
app.R
CHANGED
|
@@ -1,4 +1,4 @@
|
|
| 1 |
-
# setwd('~/Dropbox/ImageSeq/')
|
| 2 |
|
| 3 |
options(error = NULL)
|
| 4 |
library(shiny)
|
|
@@ -7,16 +7,48 @@ library(fields) # For image.plot in heatMap
|
|
| 7 |
library(akima) # For interpolation
|
| 8 |
|
| 9 |
# Load the data from sm.csv
|
| 10 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 11 |
|
| 12 |
# Define function to convert to numeric
|
| 13 |
f2n <- function(x) as.numeric(as.character(x))
|
| 14 |
|
| 15 |
# Compute MaxImageDimsLeft and MaxImageDimsRight from MaxImageDims
|
| 16 |
-
|
| 17 |
-
sm$
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 18 |
|
| 19 |
-
#
|
|
|
|
|
|
|
|
|
|
|
|
|
| 20 |
heatMap <- function(x, y, z,
|
| 21 |
main = "",
|
| 22 |
N, yaxt = NULL,
|
|
@@ -34,8 +66,8 @@ heatMap <- function(x, y, z,
|
|
| 34 |
col_vline = "black",
|
| 35 |
hline = NULL,
|
| 36 |
col_hline = "black",
|
| 37 |
-
cex.lab =
|
| 38 |
-
cex.main =
|
| 39 |
myCol = NULL,
|
| 40 |
includeMarginals = FALSE,
|
| 41 |
marginalJitterSD_x = 0.01,
|
|
@@ -43,13 +75,48 @@ heatMap <- function(x, y, z,
|
|
| 43 |
openBrowser = FALSE,
|
| 44 |
optimal_point = NULL) {
|
| 45 |
if (openBrowser) { browser() }
|
| 46 |
-
|
| 47 |
-
|
| 48 |
-
|
| 49 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 50 |
if (is.null(xlim)) { xlim = range(s_$x, finite = TRUE) }
|
| 51 |
if (is.null(ylim)) { ylim = range(s_$y, finite = TRUE) }
|
|
|
|
|
|
|
|
|
|
|
|
|
| 52 |
imageFxn <- if (add.legend) fields::image.plot else graphics::image
|
|
|
|
| 53 |
if (!grepl(useLog, pattern = "z")) {
|
| 54 |
imageFxn(s_, xlab = xlab, ylab = ylab, log = useLog, cex.lab = cex.lab, main = main,
|
| 55 |
cex.main = cex.main, col = myCol, xlim = xlim, ylim = ylim,
|
|
@@ -57,32 +124,47 @@ heatMap <- function(x, y, z,
|
|
| 57 |
zlim = zlim, legend.only = legend.only)
|
| 58 |
} else {
|
| 59 |
useLog <- gsub(useLog, pattern = "z", replace = "")
|
| 60 |
-
|
| 61 |
-
|
| 62 |
-
|
| 63 |
-
|
| 64 |
-
|
| 65 |
-
|
| 66 |
-
|
| 67 |
-
|
| 68 |
-
|
| 69 |
-
|
| 70 |
-
|
| 71 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 72 |
}
|
| 73 |
-
if (!is.null(vline)) { abline(v = vline, lwd =
|
| 74 |
-
if (!is.null(hline)) { abline(h = hline, lwd =
|
| 75 |
|
| 76 |
if (includeMarginals) {
|
| 77 |
-
points(x + rnorm(length(y), sd = marginalJitterSD_x * sd(x)),
|
| 78 |
-
rep(ylim[1] *
|
| 79 |
-
|
| 80 |
-
|
|
|
|
|
|
|
| 81 |
}
|
| 82 |
|
| 83 |
-
# Add green star at optimal point if provided
|
| 84 |
-
if (!is.null(optimal_point)) {
|
| 85 |
-
points(optimal_point$x, optimal_point$y, pch = 8, col = "green", cex =
|
| 86 |
}
|
| 87 |
}
|
| 88 |
|
|
@@ -98,9 +180,9 @@ metric_choices <- c(
|
|
| 98 |
"Mean AUTOC RATE Ratio with PC" = "AUTOC_rate_std_ratio_mean_pc",
|
| 99 |
"Mean AUTOC RATE with PC" = "AUTOC_rate_mean_pc",
|
| 100 |
"Mean SD of AUTOC RATE with PC" = "AUTOC_rate_std_mean_pc",
|
| 101 |
-
"Mean Variable Importance (
|
| 102 |
-
"Mean Variable Importance (
|
| 103 |
-
"Mean
|
| 104 |
"Mean RMSE" = "RMSE"
|
| 105 |
)
|
| 106 |
|
|
@@ -111,70 +193,65 @@ getMetricLabel <- function(metric_value) {
|
|
| 111 |
# This returns, e.g., "Mean AUTOC RATE" if metric_value == "AUTOC_rate_mean".
|
| 112 |
# If it doesn't find a match, return the code itself.
|
| 113 |
lbl <- names(metric_choices)[which(metric_choices == metric_value)]
|
| 114 |
-
if (length(lbl) == 0) return(metric_value)
|
| 115 |
lbl
|
| 116 |
}
|
| 117 |
|
| 118 |
# UI Definition
|
| 119 |
ui <- fluidPage(
|
|
|
|
|
|
|
| 120 |
tags$head(
|
| 121 |
-
#
|
| 122 |
-
tags$meta(name = "viewport",
|
| 123 |
-
content = "width=device-width, initial-scale=1"),
|
| 124 |
-
|
| 125 |
-
# Tiny CSS tweaks that only activate below 576 px
|
| 126 |
tags$style(HTML("
|
| 127 |
-
|
| 128 |
-
|
| 129 |
-
|
| 130 |
-
|
| 131 |
-
|
| 132 |
-
|
| 133 |
-
|
| 134 |
-
|
| 135 |
-
|
| 136 |
-
|
| 137 |
-
|
| 138 |
-
|
|
|
|
| 139 |
),
|
| 140 |
|
| 141 |
-
titlePanel("Multiscale Representations Explorer"),
|
| 142 |
-
|
| 143 |
tags$p(
|
| 144 |
-
style = "text-align: left; margin-top: -10px;",
|
| 145 |
tags$a(
|
| 146 |
href = "https://planetarycausalinference.org/",
|
| 147 |
target = "_blank",
|
| 148 |
title = "PlanetaryCausalInference.org",
|
| 149 |
-
style = "color: #337ab7; text-decoration: none;",
|
| 150 |
"PlanetaryCausalInference.org ",
|
| 151 |
icon("external-link", style = "font-size: 12px;")
|
| 152 |
)
|
| 153 |
),
|
| 154 |
|
| 155 |
-
# ----
|
| 156 |
-
# We wrap it in tags$div(...) and tags$script(HTML(...)) so it is recognized
|
| 157 |
-
# by Shiny. You can adjust the styling or placement as needed.
|
| 158 |
tags$div(
|
| 159 |
-
style = "text-align: left;
|
| 160 |
HTML('
|
| 161 |
-
|
| 162 |
style="
|
| 163 |
display: inline-flex;
|
| 164 |
align-items: center;
|
| 165 |
justify-content: center;
|
| 166 |
-
gap: 8px;
|
| 167 |
padding: 5px 10px;
|
| 168 |
-
font-size:
|
| 169 |
font-weight: normal;
|
| 170 |
-
color: #
|
| 171 |
-
background-color: #
|
| 172 |
-
border: 1px solid #
|
| 173 |
-
border-radius:
|
| 174 |
cursor: pointer;
|
| 175 |
-
box-shadow: 0
|
| 176 |
">
|
| 177 |
-
<svg width="
|
| 178 |
stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
| 179 |
<circle cx="18" cy="5" r="3"></circle>
|
| 180 |
<circle cx="6" cy="12" r="3"></circle>
|
|
@@ -185,247 +262,383 @@ ui <- fluidPage(
|
|
| 185 |
<strong>Share</strong>
|
| 186 |
</button>
|
| 187 |
'),
|
| 188 |
-
# Insert the JS as well
|
| 189 |
tags$script(
|
| 190 |
HTML("
|
| 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 |
-
# ---- End:
|
| 250 |
|
| 251 |
|
| 252 |
sidebarLayout(
|
| 253 |
sidebarPanel(
|
| 254 |
-
|
|
|
|
| 255 |
choices = unique(sm$application),
|
| 256 |
selected = unique(sm$application)[1]),
|
| 257 |
-
selectInput("model", "Model",
|
| 258 |
choices = unique(sm$optimizeImageRep),
|
| 259 |
selected = "clip-rsicd"),
|
| 260 |
|
| 261 |
########################################################################
|
| 262 |
# Use our named vector 'metric_choices' directly in selectInput
|
| 263 |
########################################################################
|
| 264 |
-
selectInput("metric", "Metric",
|
| 265 |
choices = metric_choices,
|
| 266 |
selected = "AUTOC_rate_std_ratio_mean"),
|
| 267 |
|
| 268 |
-
checkboxInput("compareToBest", "Compare to best single scale", value = FALSE)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 269 |
),
|
| 270 |
mainPanel(
|
| 271 |
-
|
| 272 |
-
div
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 273 |
)
|
| 274 |
)
|
| 275 |
)
|
| 276 |
|
| 277 |
# Server Definition
|
| 278 |
-
server <- function(input, output) {
|
| 279 |
# Function to determine whether to maximize or minimize the metric
|
| 280 |
-
get_better_direction <- function(
|
| 281 |
-
#
|
| 282 |
-
if (grepl(
|
|
|
|
|
|
|
|
|
|
|
|
|
| 283 |
}
|
| 284 |
|
| 285 |
# Reactive data processing
|
| 286 |
filteredData <- reactive({
|
|
|
|
|
|
|
| 287 |
df <- sm %>%
|
| 288 |
filter(application == input$application,
|
| 289 |
optimizeImageRep == input$model) %>%
|
| 290 |
-
|
| 291 |
-
|
| 292 |
-
|
| 293 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 294 |
df
|
| 295 |
})
|
| 296 |
|
| 297 |
-
# Reactive expression to compute
|
| 298 |
-
|
| 299 |
data <- filteredData()
|
| 300 |
-
|
| 301 |
|
| 302 |
# Group data
|
| 303 |
grouped_data <- data %>%
|
| 304 |
group_by(MaxImageDimsLeft, MaxImageDimsRight) %>%
|
| 305 |
summarise(
|
| 306 |
-
mean_metric = mean(
|
| 307 |
-
se_metric = sd(
|
| 308 |
n = n(),
|
| 309 |
.groups = "drop"
|
| 310 |
-
)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 311 |
|
| 312 |
better_dir <- get_better_direction(input$metric)
|
|
|
|
|
|
|
| 313 |
single_scale_data <- grouped_data %>% filter(MaxImageDimsLeft == MaxImageDimsRight)
|
| 314 |
best_single_scale_metric <- if (nrow(single_scale_data) > 0) {
|
| 315 |
-
if (better_dir == "max")
|
| 316 |
-
|
| 317 |
-
} else NA
|
| 318 |
-
|
| 319 |
-
grouped_data <- grouped_data %>%
|
| 320 |
-
mutate(improvement = if (better_dir == "max") {
|
| 321 |
-
mean_metric - best_single_scale_metric
|
| 322 |
} else {
|
| 323 |
-
|
| 324 |
-
}
|
| 325 |
-
|
| 326 |
-
|
| 327 |
-
z_to_interpolate <- if (input$compareToBest) grouped_data$improvement else grouped_data$mean_metric
|
| 328 |
-
x <- grouped_data$MaxImageDimsLeft
|
| 329 |
-
y <- grouped_data$MaxImageDimsRight
|
| 330 |
-
|
| 331 |
-
# Check if interpolation is possible
|
| 332 |
-
if (length(unique(x)) < 2 || length(unique(y)) < 2 || nrow(grouped_data) < 3) {
|
| 333 |
-
return(NULL)
|
| 334 |
}
|
| 335 |
|
| 336 |
-
#
|
| 337 |
-
|
| 338 |
-
|
| 339 |
-
|
| 340 |
-
|
| 341 |
-
|
| 342 |
-
|
| 343 |
-
|
| 344 |
-
)
|
| 345 |
-
|
| 346 |
-
# Find optimal point from interpolated grid
|
| 347 |
-
max_idx <- if (input$compareToBest || better_dir == "max") {
|
| 348 |
-
which.max(s_$z)
|
| 349 |
} else {
|
| 350 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
| 351 |
}
|
| 352 |
-
row_col <- arrayInd(max_idx, .dim = dim(s_$z))
|
| 353 |
-
optimal_x <- s_$x[row_col[1,1]]
|
| 354 |
-
optimal_y <- s_$y[row_col[1,2]]
|
| 355 |
-
optimal_z <- s_$z[row_col[1,1], row_col[1,2]]
|
| 356 |
|
| 357 |
list(
|
| 358 |
-
|
| 359 |
-
|
|
|
|
| 360 |
)
|
| 361 |
})
|
| 362 |
|
| 363 |
-
|
| 364 |
-
|
| 365 |
-
{
|
| 366 |
-
|
| 367 |
-
|
| 368 |
-
|
| 369 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 370 |
return(NULL)
|
| 371 |
}
|
| 372 |
|
| 373 |
-
|
| 374 |
-
|
| 375 |
-
|
| 376 |
-
|
| 377 |
-
|
| 378 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 379 |
)
|
|
|
|
|
|
|
|
|
|
|
|
|
| 380 |
|
| 381 |
-
|
| 382 |
-
|
| 383 |
-
|
| 384 |
-
|
| 385 |
-
else min(single_scale_data$mean_metric, na.rm = TRUE)
|
| 386 |
-
} else NA
|
| 387 |
|
| 388 |
-
|
| 389 |
-
|
| 390 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 391 |
} else {
|
| 392 |
-
|
| 393 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 394 |
|
| 395 |
-
|
| 396 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 397 |
|
| 398 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 399 |
z <- grouped_data$improvement
|
| 400 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 401 |
} else {
|
| 402 |
z <- grouped_data$mean_metric
|
| 403 |
-
main_title <- paste(input$application, "-",
|
|
|
|
|
|
|
|
|
|
|
|
|
| 404 |
}
|
| 405 |
|
| 406 |
x <- grouped_data$MaxImageDimsLeft
|
| 407 |
y <- grouped_data$MaxImageDimsRight
|
| 408 |
-
zlim <- range(z, na.rm = TRUE)
|
| 409 |
|
| 410 |
-
|
| 411 |
-
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 412 |
heatMap(
|
| 413 |
-
x =
|
| 414 |
-
y =
|
| 415 |
-
z =
|
| 416 |
-
N = 50,
|
| 417 |
main = main_title,
|
| 418 |
-
xlab = "Image Dimension 1",
|
| 419 |
-
ylab = "Image Dimension 2",
|
| 420 |
-
useLog = "xy",
|
| 421 |
myCol = customPalette,
|
| 422 |
-
cex.lab = 1.
|
| 423 |
-
|
| 424 |
-
|
|
|
|
|
|
|
|
|
|
| 425 |
)
|
| 426 |
-
|
|
|
|
| 427 |
|
| 428 |
-
# Contextual Note Output
|
| 429 |
output$contextNote <- renderText({
|
| 430 |
SharedContextText <- c(
|
| 431 |
"The Peru RCT involves a multifaceted graduation program treatment to reduce poverty outcomes.",
|
|
@@ -473,6 +686,7 @@ server <- function(input, output) {
|
|
| 473 |
)
|
| 474 |
}
|
| 475 |
})
|
|
|
|
| 476 |
}
|
| 477 |
|
| 478 |
# Run the Shiny App
|
|
|
|
| 1 |
+
# setwd('~/Dropbox/ImageSeq/') # Set your working directory if needed
|
| 2 |
|
| 3 |
options(error = NULL)
|
| 4 |
library(shiny)
|
|
|
|
| 7 |
library(akima) # For interpolation
|
| 8 |
|
| 9 |
# Load the data from sm.csv
|
| 10 |
+
# Ensure 'sm.csv' is in the same directory as the app.R file or provide the full path.
|
| 11 |
+
# Add error handling for file loading
|
| 12 |
+
sm <- tryCatch({
|
| 13 |
+
read.csv("sm.csv")
|
| 14 |
+
}, error = function(e) {
|
| 15 |
+
stop("Error loading sm.csv: ", e$message, "\nPlease ensure 'sm.csv' is in the application directory.")
|
| 16 |
+
})
|
| 17 |
+
|
| 18 |
|
| 19 |
# Define function to convert to numeric
|
| 20 |
f2n <- function(x) as.numeric(as.character(x))
|
| 21 |
|
| 22 |
# Compute MaxImageDimsLeft and MaxImageDimsRight from MaxImageDims
|
| 23 |
+
# Handle potential errors if split doesn't work as expected
|
| 24 |
+
sm$MaxImageDimsLeft <- tryCatch({
|
| 25 |
+
unlist(lapply(strsplit(as.character(sm$MaxImageDims), split = "_"), function(x) sort(f2n(x))[1]))
|
| 26 |
+
}, error = function(e) {
|
| 27 |
+
warning("Could not parse MaxImageDimsLeft from MaxImageDims. Check format (e.g., '64_128').")
|
| 28 |
+
NA # Assign NA or a default value
|
| 29 |
+
})
|
| 30 |
+
|
| 31 |
+
sm$MaxImageDimsRight <- tryCatch({
|
| 32 |
+
unlist(lapply(strsplit(as.character(sm$MaxImageDims), split = "_"), function(x) sort(f2n(x))[2]))
|
| 33 |
+
}, error = function(e) {
|
| 34 |
+
warning("Could not parse MaxImageDimsRight from MaxImageDims. Check format (e.g., '64_128').")
|
| 35 |
+
NA # Assign NA or a default value
|
| 36 |
+
})
|
| 37 |
+
|
| 38 |
+
# Handle cases where parsing might have failed or where Right dim might be missing for single scale
|
| 39 |
+
sm <- sm %>%
|
| 40 |
+
mutate(
|
| 41 |
+
MaxImageDimsLeft = f2n(MaxImageDimsLeft), # Ensure numeric
|
| 42 |
+
MaxImageDimsRight = f2n(MaxImageDimsRight), # Ensure numeric
|
| 43 |
+
# If Right is NA after parsing (or originally missing), assume it's the same as Left (single scale)
|
| 44 |
+
MaxImageDimsRight = ifelse(is.na(MaxImageDimsRight), MaxImageDimsLeft, MaxImageDimsRight)
|
| 45 |
+
)
|
| 46 |
|
| 47 |
+
# Remove rows where essential dimensions couldn't be determined
|
| 48 |
+
sm <- sm %>% filter(!is.na(MaxImageDimsLeft) & !is.na(MaxImageDimsRight))
|
| 49 |
+
|
| 50 |
+
|
| 51 |
+
# Heatmap function (no significant changes needed here, aesthetics controlled in server)
|
| 52 |
heatMap <- function(x, y, z,
|
| 53 |
main = "",
|
| 54 |
N, yaxt = NULL,
|
|
|
|
| 66 |
col_vline = "black",
|
| 67 |
hline = NULL,
|
| 68 |
col_hline = "black",
|
| 69 |
+
cex.lab = 1.3, # Default adjusted slightly
|
| 70 |
+
cex.main = 1.5, # Default adjusted slightly
|
| 71 |
myCol = NULL,
|
| 72 |
includeMarginals = FALSE,
|
| 73 |
marginalJitterSD_x = 0.01,
|
|
|
|
| 75 |
openBrowser = FALSE,
|
| 76 |
optimal_point = NULL) {
|
| 77 |
if (openBrowser) { browser() }
|
| 78 |
+
|
| 79 |
+
# Ensure finite values for interpolation range finding
|
| 80 |
+
finite_x <- x[is.finite(x)]
|
| 81 |
+
finite_y <- y[is.finite(y)]
|
| 82 |
+
if(length(finite_x) == 0 || length(finite_y) == 0) {
|
| 83 |
+
warning("Insufficient finite x or y data for interpolation range.")
|
| 84 |
+
return(NULL) # Cannot proceed
|
| 85 |
+
}
|
| 86 |
+
min_x <- min(finite_x, na.rm = TRUE)
|
| 87 |
+
max_x <- max(finite_x, na.rm = TRUE)
|
| 88 |
+
min_y <- min(finite_y, na.rm = TRUE)
|
| 89 |
+
max_y <- max(finite_y, na.rm = TRUE)
|
| 90 |
+
|
| 91 |
+
# Ensure xo and yo sequences are valid
|
| 92 |
+
if (min_x == max_x) { max_x <- min_x + 1e-6 } # Avoid zero range
|
| 93 |
+
if (min_y == max_y) { max_y <- min_y + 1e-6 } # Avoid zero range
|
| 94 |
+
|
| 95 |
+
xo_seq <- seq(min_x, max_x, length = N)
|
| 96 |
+
yo_seq <- seq(min_y, max_y, length = N)
|
| 97 |
+
|
| 98 |
+
# Perform interpolation
|
| 99 |
+
s_ <- tryCatch({
|
| 100 |
+
akima::interp(x = x, y = y, z = z,
|
| 101 |
+
xo = xo_seq,
|
| 102 |
+
yo = yo_seq,
|
| 103 |
+
duplicate = "mean",
|
| 104 |
+
linear = TRUE) # Use linear interpolation by default
|
| 105 |
+
}, error = function(e) {
|
| 106 |
+
warning("Akima interpolation failed: ", e$message)
|
| 107 |
+
return(NULL) # Return NULL if interp fails
|
| 108 |
+
})
|
| 109 |
+
|
| 110 |
+
if (is.null(s_)) return(NULL) # Exit if interpolation failed
|
| 111 |
+
|
| 112 |
if (is.null(xlim)) { xlim = range(s_$x, finite = TRUE) }
|
| 113 |
if (is.null(ylim)) { ylim = range(s_$y, finite = TRUE) }
|
| 114 |
+
|
| 115 |
+
# Default color palette if none provided
|
| 116 |
+
if (is.null(myCol)) { myCol = hcl.colors(50, palette = "YlOrRd", rev = TRUE) }
|
| 117 |
+
|
| 118 |
imageFxn <- if (add.legend) fields::image.plot else graphics::image
|
| 119 |
+
|
| 120 |
if (!grepl(useLog, pattern = "z")) {
|
| 121 |
imageFxn(s_, xlab = xlab, ylab = ylab, log = useLog, cex.lab = cex.lab, main = main,
|
| 122 |
cex.main = cex.main, col = myCol, xlim = xlim, ylim = ylim,
|
|
|
|
| 124 |
zlim = zlim, legend.only = legend.only)
|
| 125 |
} else {
|
| 126 |
useLog <- gsub(useLog, pattern = "z", replace = "")
|
| 127 |
+
z_finite <- s_$z[is.finite(s_$z)]
|
| 128 |
+
if (length(z_finite) == 0 || all(z_finite <= 0)) {
|
| 129 |
+
warning("Cannot compute log scale for z: All finite values are non-positive.")
|
| 130 |
+
# Fallback to non-log scale or plot without z-log
|
| 131 |
+
imageFxn(s_, xlab = xlab, ylab = ylab, log = useLog, cex.lab = cex.lab, main = paste(main, "(z-log failed)"),
|
| 132 |
+
cex.main = cex.main, col = myCol, xlim = xlim, ylim = ylim,
|
| 133 |
+
legend.width = legend.width, horizontal = horizontal, yaxt = yaxt,
|
| 134 |
+
zlim = zlim, legend.only = legend.only)
|
| 135 |
+
|
| 136 |
+
} else {
|
| 137 |
+
zTicks <- pretty(range(log(z_finite[z_finite > 0]), na.rm = TRUE), n = 5) # Use pretty for nice log ticks
|
| 138 |
+
zTickLabels <- signif(exp(zTicks), 2) # Nicer labels
|
| 139 |
+
# ep_ <- min(z_finite[z_finite > 0], na.rm=TRUE) * 0.1 # Small positive value based on data
|
| 140 |
+
ep_ <- 1e-9 # Or a small fixed epsilon
|
| 141 |
+
|
| 142 |
+
s_$z[s_$z <= ep_] <- ep_ # Replace non-positive with epsilon for log
|
| 143 |
+
|
| 144 |
+
imageFxn(s_$x, s_$y, log(s_$z), yaxt = yaxt,
|
| 145 |
+
axis.args = list(at = zTicks, labels = zTickLabels),
|
| 146 |
+
main = main, cex.main = cex.main, xlab = xlab, ylab = ylab,
|
| 147 |
+
log = useLog, cex.lab = cex.lab, xlim = xlim, ylim = ylim,
|
| 148 |
+
horizontal = horizontal, col = myCol, legend.width = legend.width,
|
| 149 |
+
zlim = if(!is.null(zlim)) log(zlim) else NULL, # Apply log to zlim if provided
|
| 150 |
+
legend.only = legend.only)
|
| 151 |
+
}
|
| 152 |
}
|
| 153 |
+
if (!is.null(vline)) { abline(v = vline, lwd = 3, col = col_vline, lty = 2) } # Thinner, dashed line
|
| 154 |
+
if (!is.null(hline)) { abline(h = hline, lwd = 3, col = col_hline, lty = 2) } # Thinner, dashed line
|
| 155 |
|
| 156 |
if (includeMarginals) {
|
| 157 |
+
points(x + rnorm(length(y), sd = marginalJitterSD_x * sd(x, na.rm = TRUE)), # Added na.rm
|
| 158 |
+
rep(ylim[1] + 0.02 * diff(ylim), length(y)), # Adjust position slightly off bottom
|
| 159 |
+
pch = "|", col = "darkgray")
|
| 160 |
+
points(rep(xlim[1] + 0.02 * diff(xlim), length(x)), # Adjust position slightly off left
|
| 161 |
+
y + rnorm(length(y), sd = sd(y, na.rm = TRUE) * marginalJitterSD_y), # Added na.rm
|
| 162 |
+
pch = "-", col = "darkgray")
|
| 163 |
}
|
| 164 |
|
| 165 |
+
# Add green star at optimal point if provided and valid
|
| 166 |
+
if (!is.null(optimal_point) && is.finite(optimal_point$x) && is.finite(optimal_point$y)) {
|
| 167 |
+
points(optimal_point$x, optimal_point$y, pch = 8, col = "green", cex = 2.5, lwd = 3) # Slightly smaller star
|
| 168 |
}
|
| 169 |
}
|
| 170 |
|
|
|
|
| 180 |
"Mean AUTOC RATE Ratio with PC" = "AUTOC_rate_std_ratio_mean_pc",
|
| 181 |
"Mean AUTOC RATE with PC" = "AUTOC_rate_mean_pc",
|
| 182 |
"Mean SD of AUTOC RATE with PC" = "AUTOC_rate_std_mean_pc",
|
| 183 |
+
"Mean Variable Importance (Img 1)" = "MeanVImportHalf1", # Shorter label
|
| 184 |
+
"Mean Variable Importance (Img 2)" = "MeanVImportHalf2", # Shorter label
|
| 185 |
+
"Mean Frac Top k Feats (Img 1)" = "FracTopkHalf1", # Shorter label
|
| 186 |
"Mean RMSE" = "RMSE"
|
| 187 |
)
|
| 188 |
|
|
|
|
| 193 |
# This returns, e.g., "Mean AUTOC RATE" if metric_value == "AUTOC_rate_mean".
|
| 194 |
# If it doesn't find a match, return the code itself.
|
| 195 |
lbl <- names(metric_choices)[which(metric_choices == metric_value)]
|
| 196 |
+
if (length(lbl) == 0 || is.na(lbl)) return(metric_value) # Handle NA/no match
|
| 197 |
lbl
|
| 198 |
}
|
| 199 |
|
| 200 |
# UI Definition
|
| 201 |
ui <- fluidPage(
|
| 202 |
+
titlePanel("Multiscale Representations Explorer"),
|
| 203 |
+
|
| 204 |
tags$head(
|
| 205 |
+
# Add some basic CSS for better spacing/responsiveness if needed
|
|
|
|
|
|
|
|
|
|
|
|
|
| 206 |
tags$style(HTML("
|
| 207 |
+
.shiny-plot-output { /* Ensure plot output behaves well */
|
| 208 |
+
margin: auto; /* Center if container allows */
|
| 209 |
+
}
|
| 210 |
+
.control-label { /* Ensure labels are readable */
|
| 211 |
+
font-weight: bold;
|
| 212 |
+
}
|
| 213 |
+
#contextNote { /* Style for the context note */
|
| 214 |
+
margin-top: 15px;
|
| 215 |
+
font-size: 0.9em; /* Slightly smaller font */
|
| 216 |
+
line-height: 1.6; /* Better readability */
|
| 217 |
+
}
|
| 218 |
+
#share-button { margin-bottom: 15px; } /* Add space below share button */
|
| 219 |
+
"))
|
| 220 |
),
|
| 221 |
|
|
|
|
|
|
|
| 222 |
tags$p(
|
| 223 |
+
style = "text-align: left; margin-top: -10px; margin-bottom: 10px;", # Added margin-bottom
|
| 224 |
tags$a(
|
| 225 |
href = "https://planetarycausalinference.org/",
|
| 226 |
target = "_blank",
|
| 227 |
title = "PlanetaryCausalInference.org",
|
| 228 |
+
style = "color: #337ab7; text-decoration: none; font-weight: bold;", # Make link bold
|
| 229 |
"PlanetaryCausalInference.org ",
|
| 230 |
icon("external-link", style = "font-size: 12px;")
|
| 231 |
)
|
| 232 |
),
|
| 233 |
|
| 234 |
+
# ---- Share button HTML + JS ----
|
|
|
|
|
|
|
| 235 |
tags$div(
|
| 236 |
+
style = "text-align: left;", # Removed fixed margin
|
| 237 |
HTML('
|
| 238 |
+
<button id="share-button"
|
| 239 |
style="
|
| 240 |
display: inline-flex;
|
| 241 |
align-items: center;
|
| 242 |
justify-content: center;
|
| 243 |
+
gap: 8px;
|
| 244 |
padding: 5px 10px;
|
| 245 |
+
font-size: 14px; /* Slightly smaller font */
|
| 246 |
font-weight: normal;
|
| 247 |
+
color: #333; /* Darker text */
|
| 248 |
+
background-color: #f8f9fa; /* Lighter background */
|
| 249 |
+
border: 1px solid #ccc; /* Lighter border */
|
| 250 |
+
border-radius: 4px; /* Smaller radius */
|
| 251 |
cursor: pointer;
|
| 252 |
+
box-shadow: 0 1px 1px rgba(0,0,0,0.05); /* Softer shadow */
|
| 253 |
">
|
| 254 |
+
<svg width="16" height="16" viewBox="0 0 24 24" fill="none" stroke="currentColor"
|
| 255 |
stroke-width="2" stroke-linecap="round" stroke-linejoin="round">
|
| 256 |
<circle cx="18" cy="5" r="3"></circle>
|
| 257 |
<circle cx="6" cy="12" r="3"></circle>
|
|
|
|
| 262 |
<strong>Share</strong>
|
| 263 |
</button>
|
| 264 |
'),
|
|
|
|
| 265 |
tags$script(
|
| 266 |
HTML("
|
| 267 |
+
(function() {
|
| 268 |
+
const shareBtn = document.getElementById('share-button');
|
| 269 |
+
if (!shareBtn) return; // Exit if button not found
|
| 270 |
+
|
| 271 |
+
function showCopyNotification() {
|
| 272 |
+
const notification = document.createElement('div');
|
| 273 |
+
notification.innerText = 'Link copied!'; /* Shorter message */
|
| 274 |
+
notification.style.position = 'fixed';
|
| 275 |
+
notification.style.bottom = '15px'; /* Adjust position */
|
| 276 |
+
notification.style.left = '50%'; /* Center horizontally */
|
| 277 |
+
notification.style.transform = 'translateX(-50%)'; /* Correct centering */
|
| 278 |
+
notification.style.backgroundColor = 'rgba(0, 0, 0, 0.75)';
|
| 279 |
+
notification.style.color = '#fff';
|
| 280 |
+
notification.style.padding = '8px 15px'; /* Adjust padding */
|
| 281 |
+
notification.style.borderRadius = '4px';
|
| 282 |
+
notification.style.fontSize = '14px'; /* Match button font */
|
| 283 |
+
notification.style.zIndex = '10000'; /* Ensure visibility */
|
| 284 |
+
notification.style.boxShadow = '0 2px 5px rgba(0,0,0,0.2)'; /* Add shadow */
|
| 285 |
+
document.body.appendChild(notification);
|
| 286 |
+
setTimeout(() => { notification.remove(); }, 1500); /* Shorter duration */
|
| 287 |
+
}
|
| 288 |
+
|
| 289 |
+
shareBtn.addEventListener('click', function() {
|
| 290 |
+
const currentURL = window.location.href;
|
| 291 |
+
const pageTitle = document.title || 'Multiscale Explorer';
|
| 292 |
+
|
| 293 |
+
if (navigator.share) {
|
| 294 |
+
navigator.share({
|
| 295 |
+
title: pageTitle,
|
| 296 |
+
text: 'Check out this multiscale analysis:', /* Add context */
|
| 297 |
+
url: currentURL
|
| 298 |
+
})
|
| 299 |
+
.catch((error) => {
|
| 300 |
+
// If user cancels share, don't log error unless it's a real failure
|
| 301 |
+
if (error.name !== 'AbortError') {
|
| 302 |
+
console.log('Sharing failed', error);
|
| 303 |
+
}
|
| 304 |
+
});
|
| 305 |
+
} else if (navigator.clipboard && navigator.clipboard.writeText) {
|
| 306 |
+
navigator.clipboard.writeText(currentURL).then(() => {
|
| 307 |
+
showCopyNotification();
|
| 308 |
+
}, (err) => {
|
| 309 |
+
console.error('Could not copy text: ', err);
|
| 310 |
+
// Fallback alert if clipboard fails unexpectedly
|
| 311 |
+
alert('Failed to copy link. Please copy manually:\\n' + currentURL);
|
| 312 |
+
});
|
| 313 |
+
} else {
|
| 314 |
+
// Basic fallback for very old browsers
|
| 315 |
+
try {
|
| 316 |
+
const textArea = document.createElement('textarea');
|
| 317 |
+
textArea.value = currentURL;
|
| 318 |
+
textArea.style.position = 'fixed'; // Prevent scrolling
|
| 319 |
+
textArea.style.opacity = '0'; // Hide element
|
| 320 |
+
document.body.appendChild(textArea);
|
| 321 |
+
textArea.select();
|
| 322 |
+
document.execCommand('copy');
|
| 323 |
+
showCopyNotification();
|
| 324 |
+
document.body.removeChild(textArea);
|
| 325 |
+
} catch (err) {
|
| 326 |
+
alert('Sharing not supported. Please copy this link manually:\\n' + currentURL);
|
| 327 |
+
}
|
| 328 |
+
}
|
| 329 |
+
});
|
| 330 |
+
})();
|
| 331 |
+
")
|
| 332 |
)
|
| 333 |
),
|
| 334 |
+
# ---- End: Share button snippet ----
|
| 335 |
|
| 336 |
|
| 337 |
sidebarLayout(
|
| 338 |
sidebarPanel(
|
| 339 |
+
width = 3, # Explicitly set sidebar width (adjust as needed 1-12)
|
| 340 |
+
selectInput("application", "Application:", # Colon for clarity
|
| 341 |
choices = unique(sm$application),
|
| 342 |
selected = unique(sm$application)[1]),
|
| 343 |
+
selectInput("model", "Model:",
|
| 344 |
choices = unique(sm$optimizeImageRep),
|
| 345 |
selected = "clip-rsicd"),
|
| 346 |
|
| 347 |
########################################################################
|
| 348 |
# Use our named vector 'metric_choices' directly in selectInput
|
| 349 |
########################################################################
|
| 350 |
+
selectInput("metric", "Metric:",
|
| 351 |
choices = metric_choices,
|
| 352 |
selected = "AUTOC_rate_std_ratio_mean"),
|
| 353 |
|
| 354 |
+
checkboxInput("compareToBest", "Compare to best single scale?", value = FALSE), # Question format
|
| 355 |
+
|
| 356 |
+
# Add some explanation directly in the sidebar
|
| 357 |
+
tags$hr(), # Horizontal line separator
|
| 358 |
+
tags$p(tags$small("Adjust parameters to explore how multiscale image representations impact model performance or heterogeneity discovery across different applications."))
|
| 359 |
),
|
| 360 |
mainPanel(
|
| 361 |
+
width = 9, # Explicitly set main panel width (should sum to 12 with sidebar)
|
| 362 |
+
# Wrap plot in a div for potential future styling/sizing control
|
| 363 |
+
div(
|
| 364 |
+
# *** ADJUSTED PLOT OUTPUT ***
|
| 365 |
+
plotOutput("heatmapPlot", height = "500px", width = "100%")
|
| 366 |
+
),
|
| 367 |
+
# Use uiOutput for potentially HTML content in the note
|
| 368 |
+
uiOutput("contextNote")
|
| 369 |
)
|
| 370 |
)
|
| 371 |
)
|
| 372 |
|
| 373 |
# Server Definition
|
| 374 |
+
server <- function(input, output, session) { # Add session argument
|
| 375 |
# Function to determine whether to maximize or minimize the metric
|
| 376 |
+
get_better_direction <- function(metric_value) {
|
| 377 |
+
# Assuming lower SD and lower RMSE are better
|
| 378 |
+
if (grepl("std_mean|RMSE", metric_value, ignore.case = TRUE)) {
|
| 379 |
+
"min"
|
| 380 |
+
} else {
|
| 381 |
+
"max" # Assume higher is better for others (RATE, Ratio, VImport, FracTopk)
|
| 382 |
+
}
|
| 383 |
}
|
| 384 |
|
| 385 |
# Reactive data processing
|
| 386 |
filteredData <- reactive({
|
| 387 |
+
req(input$application, input$model) # Ensure inputs are available
|
| 388 |
+
|
| 389 |
df <- sm %>%
|
| 390 |
filter(application == input$application,
|
| 391 |
optimizeImageRep == input$model) %>%
|
| 392 |
+
# Ensure dimensions are numeric before filtering/grouping
|
| 393 |
+
mutate(
|
| 394 |
+
MaxImageDimsLeft = as.numeric(MaxImageDimsLeft),
|
| 395 |
+
MaxImageDimsRight = as.numeric(MaxImageDimsRight),
|
| 396 |
+
metric_value = as.numeric(get(input$metric)) # Get chosen metric value
|
| 397 |
+
) %>%
|
| 398 |
+
filter(is.finite(MaxImageDimsLeft) & is.finite(MaxImageDimsRight) & is.finite(metric_value)) # Keep only valid rows
|
| 399 |
+
|
| 400 |
+
# Check if data exists after filtering
|
| 401 |
+
if (nrow(df) == 0) {
|
| 402 |
+
warning("No valid data found for the selected Application/Model/Metric combination.")
|
| 403 |
+
return(NULL)
|
| 404 |
+
}
|
| 405 |
df
|
| 406 |
})
|
| 407 |
|
| 408 |
+
# Reactive expression to compute grouped/summarized data and best single scale
|
| 409 |
+
summaryData <- reactive({
|
| 410 |
data <- filteredData()
|
| 411 |
+
req(data) # Require filtered data
|
| 412 |
|
| 413 |
# Group data
|
| 414 |
grouped_data <- data %>%
|
| 415 |
group_by(MaxImageDimsLeft, MaxImageDimsRight) %>%
|
| 416 |
summarise(
|
| 417 |
+
mean_metric = mean(metric_value, na.rm = TRUE),
|
| 418 |
+
se_metric = sd(metric_value, na.rm = TRUE) / sqrt(n()),
|
| 419 |
n = n(),
|
| 420 |
.groups = "drop"
|
| 421 |
+
) %>%
|
| 422 |
+
filter(is.finite(mean_metric)) # Ensure mean is valid after aggregation
|
| 423 |
+
|
| 424 |
+
if (nrow(grouped_data) < 3) {
|
| 425 |
+
warning("Less than 3 unique dimension pairs after grouping. Cannot interpolate.")
|
| 426 |
+
return(NULL) # Not enough data points for reliable interpolation
|
| 427 |
+
}
|
| 428 |
+
|
| 429 |
+
# Check variability in dimensions needed for interpolation
|
| 430 |
+
if (length(unique(grouped_data$MaxImageDimsLeft)) < 2 || length(unique(grouped_data$MaxImageDimsRight)) < 2) {
|
| 431 |
+
warning("Insufficient variability in one or both image dimensions for interpolation.")
|
| 432 |
+
return(NULL)
|
| 433 |
+
}
|
| 434 |
+
|
| 435 |
|
| 436 |
better_dir <- get_better_direction(input$metric)
|
| 437 |
+
|
| 438 |
+
# Calculate best single scale metric *from the summarized data*
|
| 439 |
single_scale_data <- grouped_data %>% filter(MaxImageDimsLeft == MaxImageDimsRight)
|
| 440 |
best_single_scale_metric <- if (nrow(single_scale_data) > 0) {
|
| 441 |
+
if (better_dir == "max") {
|
| 442 |
+
max(single_scale_data$mean_metric, na.rm = TRUE)
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 443 |
} else {
|
| 444 |
+
min(single_scale_data$mean_metric, na.rm = TRUE)
|
| 445 |
+
}
|
| 446 |
+
} else {
|
| 447 |
+
NA # No single scale data available for comparison
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 448 |
}
|
| 449 |
|
| 450 |
+
# Calculate improvement only if best_single_scale_metric is valid
|
| 451 |
+
if (is.finite(best_single_scale_metric)) {
|
| 452 |
+
grouped_data <- grouped_data %>%
|
| 453 |
+
mutate(improvement = if (better_dir == "max") {
|
| 454 |
+
mean_metric - best_single_scale_metric
|
| 455 |
+
} else {
|
| 456 |
+
best_single_scale_metric - mean_metric
|
| 457 |
+
})
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
|
| 458 |
} else {
|
| 459 |
+
# If no valid single-scale baseline, improvement cannot be calculated
|
| 460 |
+
grouped_data <- grouped_data %>% mutate(improvement = NA_real_)
|
| 461 |
+
# Optionally disable the checkbox if comparison isn't possible
|
| 462 |
+
# updateCheckboxInput(session, "compareToBest", value = FALSE, label = "Compare to best single scale (N/A)")
|
| 463 |
+
# shinyjs::disable("compareToBest") # Requires shinyjs package
|
| 464 |
}
|
|
|
|
|
|
|
|
|
|
|
|
|
| 465 |
|
| 466 |
list(
|
| 467 |
+
grouped_data = grouped_data,
|
| 468 |
+
best_single_scale_metric = best_single_scale_metric,
|
| 469 |
+
better_dir = better_dir
|
| 470 |
)
|
| 471 |
})
|
| 472 |
|
| 473 |
+
|
| 474 |
+
# Reactive expression for interpolation (depends on summaryData)
|
| 475 |
+
interpolatedData <- reactive({
|
| 476 |
+
sumData <- summaryData()
|
| 477 |
+
req(sumData) # Requires valid summary data
|
| 478 |
+
|
| 479 |
+
grouped_data <- sumData$grouped_data
|
| 480 |
+
better_dir <- sumData$better_dir
|
| 481 |
+
|
| 482 |
+
# Determine which z-value to interpolate based on user choice and availability
|
| 483 |
+
use_improvement <- input$compareToBest && "improvement" %in% names(grouped_data) && any(is.finite(grouped_data$improvement))
|
| 484 |
+
z_to_interpolate <- if (use_improvement) {
|
| 485 |
+
grouped_data$improvement
|
| 486 |
+
} else {
|
| 487 |
+
grouped_data$mean_metric
|
| 488 |
+
}
|
| 489 |
+
|
| 490 |
+
# Filter out rows where the chosen z value is not finite
|
| 491 |
+
valid_rows <- is.finite(grouped_data$MaxImageDimsLeft) &
|
| 492 |
+
is.finite(grouped_data$MaxImageDimsRight) &
|
| 493 |
+
is.finite(z_to_interpolate)
|
| 494 |
+
|
| 495 |
+
if (sum(valid_rows) < 3) {
|
| 496 |
+
warning("Less than 3 valid points remaining for interpolation after filtering non-finite z-values.")
|
| 497 |
return(NULL)
|
| 498 |
}
|
| 499 |
|
| 500 |
+
x <- grouped_data$MaxImageDimsLeft[valid_rows]
|
| 501 |
+
y <- grouped_data$MaxImageDimsRight[valid_rows]
|
| 502 |
+
z <- z_to_interpolate[valid_rows]
|
| 503 |
+
|
| 504 |
+
# Double-check dimension variability again with filtered data
|
| 505 |
+
if (length(unique(x)) < 2 || length(unique(y)) < 2) {
|
| 506 |
+
warning("Insufficient dimension variability after filtering for interpolation.")
|
| 507 |
+
return(NULL)
|
| 508 |
+
}
|
| 509 |
+
|
| 510 |
+
# Perform interpolation
|
| 511 |
+
s_ <- tryCatch({
|
| 512 |
+
akima::interp(
|
| 513 |
+
x = x,
|
| 514 |
+
y = y,
|
| 515 |
+
z = z,
|
| 516 |
+
xo = seq(min(x, na.rm=TRUE), max(x, na.rm=TRUE), length = 50),
|
| 517 |
+
yo = seq(min(y, na.rm=TRUE), max(y, na.rm=TRUE), length = 50),
|
| 518 |
+
duplicate = "mean",
|
| 519 |
+
linear = TRUE # Ensure linear is explicitly set if default changes
|
| 520 |
)
|
| 521 |
+
}, error = function(e){
|
| 522 |
+
warning("Interpolation failed: ", e$message)
|
| 523 |
+
return(NULL)
|
| 524 |
+
})
|
| 525 |
|
| 526 |
+
if (is.null(s_) || !is.matrix(s_$z) || all(!is.finite(s_$z))) {
|
| 527 |
+
warning("Interpolation result is invalid or contains no finite values.")
|
| 528 |
+
return(NULL) # Interpolation failed or yielded no usable results
|
| 529 |
+
}
|
|
|
|
|
|
|
| 530 |
|
| 531 |
+
# Find optimal point from the *interpolated* grid (s_$z)
|
| 532 |
+
optimal_z_value <- NA
|
| 533 |
+
optimal_x <- NA
|
| 534 |
+
optimal_y <- NA
|
| 535 |
+
|
| 536 |
+
if(any(is.finite(s_$z))) { # Proceed only if there are finite values in the grid
|
| 537 |
+
# Determine optimization direction for the *interpolated* z-value
|
| 538 |
+
# If we interpolated 'improvement', we always maximize it.
|
| 539 |
+
# Otherwise, use the original metric's direction.
|
| 540 |
+
interp_better_dir <- if(use_improvement) "max" else better_dir
|
| 541 |
+
|
| 542 |
+
if (interp_better_dir == "max") {
|
| 543 |
+
max_idx <- which.max(s_$z)
|
| 544 |
+
optimal_z_value <- max(s_$z, na.rm = TRUE)
|
| 545 |
} else {
|
| 546 |
+
max_idx <- which.min(s_$z) # Index of the minimum
|
| 547 |
+
optimal_z_value <- min(s_$z, na.rm = TRUE)
|
| 548 |
+
}
|
| 549 |
+
# Convert linear index to row/column
|
| 550 |
+
row_col <- arrayInd(max_idx, .dim = dim(s_$z))
|
| 551 |
+
optimal_x <- s_$x[row_col[1, 1]]
|
| 552 |
+
optimal_y <- s_$y[row_col[1, 2]]
|
| 553 |
+
} else {
|
| 554 |
+
warning("No finite values in the interpolated grid to find optimum.")
|
| 555 |
+
}
|
| 556 |
|
| 557 |
+
list(
|
| 558 |
+
s_ = s_,
|
| 559 |
+
optimal_point = list(x = optimal_x, y = optimal_y, z = optimal_z_value),
|
| 560 |
+
interpolated_metric_name = if(use_improvement) "Improvement" else getMetricLabel(input$metric)
|
| 561 |
+
)
|
| 562 |
+
})
|
| 563 |
+
|
| 564 |
+
|
| 565 |
+
# Heatmap Output
|
| 566 |
+
output$heatmapPlot <- renderPlot({
|
| 567 |
+
sumData <- summaryData()
|
| 568 |
+
interpData <- interpolatedData()
|
| 569 |
|
| 570 |
+
# Use req() for cleaner checking of reactive results
|
| 571 |
+
req(sumData, interpData, cancelOutput = TRUE) # Ensure both summary and interpolation are valid
|
| 572 |
+
|
| 573 |
+
grouped_data <- sumData$grouped_data
|
| 574 |
+
optimal_point <- interpData$optimal_point
|
| 575 |
+
|
| 576 |
+
# Determine z values and title based on checkbox and data availability
|
| 577 |
+
use_improvement <- input$compareToBest && "improvement" %in% names(grouped_data) && any(is.finite(grouped_data$improvement))
|
| 578 |
+
|
| 579 |
+
if (use_improvement) {
|
| 580 |
z <- grouped_data$improvement
|
| 581 |
+
# Check if improvement calculation was possible
|
| 582 |
+
if (all(is.na(z))) {
|
| 583 |
+
plot.new()
|
| 584 |
+
title(main = "Cannot Compute Improvement", sub = "No valid single-scale baseline found.", col.main = "red")
|
| 585 |
+
return()
|
| 586 |
+
}
|
| 587 |
+
main_title <- paste(input$application, "-", getMetricLabel(input$metric), "\nImprovement Over Best Single Scale")
|
| 588 |
+
plot_zlim <- range(interpData$s_$z, na.rm = TRUE) # Use range of interpolated improvement
|
| 589 |
} else {
|
| 590 |
z <- grouped_data$mean_metric
|
| 591 |
+
main_title <- paste(input$application, "-", getMetricLabel(input$metric))
|
| 592 |
+
plot_zlim <- range(interpData$s_$z, na.rm = TRUE) # Use range of interpolated metric
|
| 593 |
+
if (input$compareToBest) { # Add note if checkbox is ticked but comparison N/A
|
| 594 |
+
main_title <- paste0(main_title, "\n(Comparison to single scale not available)")
|
| 595 |
+
}
|
| 596 |
}
|
| 597 |
|
| 598 |
x <- grouped_data$MaxImageDimsLeft
|
| 599 |
y <- grouped_data$MaxImageDimsRight
|
|
|
|
| 600 |
|
| 601 |
+
# Filter data for plotting to match data used for interpolation
|
| 602 |
+
valid_rows <- is.finite(x) & is.finite(y) & is.finite(z)
|
| 603 |
+
if(sum(valid_rows) == 0) {
|
| 604 |
+
plot.new()
|
| 605 |
+
text(0.5, 0.5, "No valid data to plot.", cex = 1.5)
|
| 606 |
+
return()
|
| 607 |
+
}
|
| 608 |
+
x_plot <- x[valid_rows]
|
| 609 |
+
y_plot <- y[valid_rows]
|
| 610 |
+
z_plot <- z[valid_rows]
|
| 611 |
+
|
| 612 |
+
|
| 613 |
+
# *** ADJUSTED MARGINS AND COLORS ***
|
| 614 |
+
par(mar=c(5, 5, 4, 2) + 0.1) # Adjusted margins (bottom, left, top, right)
|
| 615 |
+
# *** USING HCL COLORS ***
|
| 616 |
+
customPalette <- hcl.colors(50, palette = "YlOrRd", rev = TRUE) # Or "Viridis", "Plasma" etc.
|
| 617 |
+
|
| 618 |
+
# Call heatMap using the raw (but filtered) data points
|
| 619 |
+
# The interpolation result (interpData$s_) is implicitly used by heatMap via akima::interp
|
| 620 |
+
# We pass the *original* x, y, z used for interpolation to heatMap
|
| 621 |
heatMap(
|
| 622 |
+
x = x_plot,
|
| 623 |
+
y = y_plot,
|
| 624 |
+
z = z_plot, # Pass the original data used for interpolation
|
| 625 |
+
N = 50, # Interpolation grid size used within heatMap
|
| 626 |
main = main_title,
|
| 627 |
+
xlab = "Image Dimension 1 (log scale)", # Clarify log scale
|
| 628 |
+
ylab = "Image Dimension 2 (log scale)", # Clarify log scale
|
| 629 |
+
useLog = "xy", # Keep log scale for axes
|
| 630 |
myCol = customPalette,
|
| 631 |
+
cex.lab = 1.3, # Slightly reduced label size
|
| 632 |
+
cex.main = 1.5, # Slightly reduced main title size
|
| 633 |
+
zlim = plot_zlim, # Use zlim from the *interpolated* data for consistent coloring
|
| 634 |
+
optimal_point = optimal_point, # Pass the calculated optimal point
|
| 635 |
+
add.legend = TRUE,
|
| 636 |
+
legend.width = 1.5 # Slightly wider legend
|
| 637 |
)
|
| 638 |
+
|
| 639 |
+
}, res = 96) # Adjust resolution if needed
|
| 640 |
|
| 641 |
+
# Contextual Note Output (using renderUI for HTML)
|
| 642 |
output$contextNote <- renderText({
|
| 643 |
SharedContextText <- c(
|
| 644 |
"The Peru RCT involves a multifaceted graduation program treatment to reduce poverty outcomes.",
|
|
|
|
| 686 |
)
|
| 687 |
}
|
| 688 |
})
|
| 689 |
+
|
| 690 |
}
|
| 691 |
|
| 692 |
# Run the Shiny App
|