Why Neuro-Symbolic Statistical Interfaces?
When building Shiny applications for open-ended statistical workflows—such as Monte Carlo simulations, multilevel power analysis, or missing-data studies—you normally face an uncomfortable choice:
- Expose every parameter statically, resulting in a cluttered 300-control cockpit where simple analyses drown in irrelevant options.
- Restrict the app to fixed templates, locking out researchers as soon as they need a random slope, MAR attrition, or a parameter sweep.
- Let an LLM emit and execute raw R code, sacrificing reproducibility, statistical guardrails, and security.
specshiny breaks this trade-off with a four-stage
neuro-symbolic pipeline:
-
Natural Language -> Typed Specification IR
(
spec_ir): A pluggable translator compiles English study descriptions into a declarative, schema-validated JSON/YAML Intermediate Representation—never executing raw model output. - Schema & Statistical Sanity Guardrails: Pure-R validation checks positive variances, ICC bounds, random-slope identifiability, positive-definite correlation matrices, missingness rates, and parameter-grid limits.
-
Dynamic Minimal UI Synthesis:
spec_to_controls()andbslibShiny modules render only the controls active in the current specification, bidirectionally synced with conversational edits and live change diffs. -
Deterministic Code & Report Compilation:
Audited templates compile any validated
spec_irinto readable, standalone R scripts and Quarto reports with zeroeval(parse())of untrusted strings.
1. Compiling Natural Language to a Verified Specification
Start offline with the deterministic rule-based translator
(translator_rule()):
library(specshiny)
prompt <- paste(
"2-level multilevel power simulation with 60 schools, 25 students per school,",
"ICC 0.2, treatment effect 0.35, random slope for x1, 15% MAR missingness,",
"500 replications"
)
tr <- nl_to_spec(prompt)
tr$spec
#>
#> ── spec_ir v1.2.0 [valid] ──
#>
#> Title: 2-Level School Linear Power Simulation (Random Slopes, MAR Missingness)
#> Design: power_analysis | Estimator: lmer
#> Hierarchy: 2-level (60 schools x 25 students = 1500 total; ICC = 0.2)
#> Outcome: y (gaussian, link = identity)
#> Predictors: treatment [L1, binary, beta=0.35], x1 [L1, normal, beta=0.2]
#> Random Slopes: x1 (sd=0.2)
#> Missingness: MAR (15% on outcome)
#> Simulation: 500 reps | alpha = 0.05 | seed = 2026 | grid: noneEvery inferred default is documented transparently in
defaults_rationale:
tr$spec$defaults_rationale
#> $outcome.family
#> [1] "Outcome distribution was not specified; defaulted to Gaussian (continuous outcome with identity link)."
#>
#> $outcome.residual_sd
#> [1] "Residual SD was not specified; defaulted to 1.0 so effect sizes are interpretable in SD units."
#>
#> $predictors.treatment.level
#> [1] "Treatment assignment level was not stated; defaulted to level-1 (within-cluster randomization)."
#>
#> $effects.fixed.x1
#> [1] "Fixed effect for covariate 'x1' was not specified; defaulted to 0.20."
#>
#> $effects.random.slopes.x1.sd
#> [1] "Random slope SD for 'x1' was not specified; defaulted to 0.20."
#>
#> $effects.random.corr_matrix
#> [1] "Random-effects correlation was not specified; defaulted to 0 (uncorrelated intercept and slope)."
#>
#> $missingness.auxiliary
#> [1] "Selected 'x1' as the observed auxiliary predictor driving MAR missingness."
#>
#> $missingness.strength
#> [1] "Defaulted MAR log-odds slope to 1.0 (moderate dependence on auxiliary variable)."
#>
#> $simulation.alpha
#> [1] "Significance level alpha was not specified; defaulted to 0.05 (two-sided)."
#>
#> $simulation.seed
#> [1] "Random seed was not specified; set deterministic seed 2026 for reproducibility."
#>
#> $estimator.engine
#> [1] "Selected 'lmer' estimator matching the 2-level gaussian model specification."And underspecified design choices are surfaced as structured
clarifications rather than hidden silently:
lapply(tr$clarifications, function(cl) {
sprintf("[%s] %s (default: %s)", cl$id, cl$question, cl$current_default)
})
#> [[1]]
#> [1] "[treatment_level] Is 'treatment' randomized within schools (level 1) or at the school level (level 2)? (default: 1)"
#>
#> [[2]]
#> [1] "[slope_sd_x1] What random slope standard deviation (SD) should be used for 'x1'? (default: 0.2)"2. Answering Clarifications & Iterative Refinement
Clarifications can be answered programmatically (or via the Shiny
composer UI) using answer_clarifications():
clarified <- answer_clarifications(
tr,
answers = list(treatment_level = 2L, slope_sd_x1 = 0.25)
)
clarified$diff
#>
#> ── spec_diff (2 changes across 2 sections)
#> • predictors.treatment.level: 1 -> 2
#> • effects.random.slopes.x1.sd: 0.2 -> 0.25Next, refine the study conversationally with
refine_spec() and inspect the structured semantic diff:
refined <- refine_spec(
clarified$spec,
"increase clusters to 80 and sweep ICC across 0.1, 0.2, 0.3"
)
refined$diff
#>
#> ── spec_diff (2 changes across 2 sections)
#> • hierarchy.n_clusters: 60 -> 80
#> ✔ simulation.parameter_grid.icc: added (c(0.1, 0.2, 0.3))3. Statistical Sanity Guardrails
Before any specification can drive UI rendering or code generation,
validate_spec_ir() verifies both schema structure and
statistical identifiability. For instance, attempting to put a random
slope on a cluster-constant level-2 predictor or supplying a
non-positive-definite random effects correlation matrix is immediately
caught:
bad_spec <- refined$spec
# Level-2 treatment cannot have a random slope across clusters:
bad_spec$effects$random$slopes <- list(list(predictor = "treatment", sd = 0.2))
# Non-positive-definite correlation matrix (eigenvalue = 0):
bad_spec$effects$random$corr_matrix <- matrix(c(1, 1, 1, 1), nrow = 2, ncol = 2)
val <- validate_spec_ir(bad_spec, strict = FALSE)
val$valid
#> [1] FALSE
val$errors[, c("path", "code", "category")]
#> path code
#> 1 effects.random.slopes[1].predictor random_slope_level2_unidentifiable
#> 2 effects.random.corr_matrix corr_matrix_not_positive_definite
#> category
#> 1 statistical
#> 2 statistical4. Minimal Dynamic UI Synthesis
Compare the synthesized UI surface of a simple single-level linear regression against our complex 2-level multilevel power design:
simple_spec <- nl_to_spec(
"Single-level Monte Carlo simulation with 200 observations, x1 effect 0.4, 250 reps"
)$spec
d_simple <- spec_to_controls(simple_spec)
d_mlm <- spec_to_controls(refined$spec)
cat("Single-level active controls:", d_simple$control_count, "\n")
#> Single-level active controls: 12
cat(" IDs:", paste(d_simple$control_ids, collapse = ", "), "\n\n")
#> IDs: n_obs, outcome_family, residual_sd, error_dist, pred_beta_x1, pred_sd_x1, pred_centering_x1, effects_intercept, missing_mechanism, n_reps, alpha, seed
cat("Multilevel + MAR + Grid active controls:", d_mlm$control_count, "\n")
#> Multilevel + MAR + Grid active controls: 26
cat(" IDs:", paste(d_mlm$control_ids, collapse = ", "), "\n")
#> IDs: n_clusters, cluster_size, cluster_size_dist, icc, outcome_family, residual_sd, error_dist, pred_beta_treatment, pred_prob_treatment, pred_centering_treatment, pred_beta_x1, pred_sd_x1, pred_centering_x1, effects_intercept, focal_predictor, slope_sd_x1, corr_1_2, missing_mechanism, missing_rate, missing_auxiliary, missing_strength, n_reps, alpha, seed, estimator_reml, grid_iccNotice that d_simple never shows
n_clusters, icc, slope_sd_*,
missing_rate, or estimator_reml. Complexity
appears only when the study design requires it.
5. Deterministic R Script & Quarto Report Compilation
Any validated spec_ir compiles deterministically into a
standalone R script and a reproducible Quarto .qmd
report:
# Compile a fast 1-level example and execute the generated script in isolation
fast_spec <- new_spec_ir(
design_type = "power_analysis",
title = "Quick Power Verification",
hierarchy = list(levels = 1L, n_obs = 120L),
predictors = list(spec_predictor("trt", level = 1L, distribution = "binary", prob = 0.5, role = "treatment")),
effects = list(intercept = 0, fixed = list(trt = 0.5), focal_predictor = "trt"),
simulation = list(n_reps = 15L, seed = 2026L)
)
script_code <- compile_r_script(fast_spec)
cat(substr(script_code, 1, 700), "...\n")
#> # =============================================================================
#> # Quick Power Verification
#> # Generated deterministically by specshiny (AST-verified; zero eval/parse)
#> # IR Schema Version : 1.2.0
#> # Design Type : power_analysis (1-level, gaussian / identity link)
#> # Model Formula : y ~ trt
#> # Estimator Engine : lm
#> # =============================================================================
#>
#> # --- 1. Simulation Configuration ---
#> cfg <- list(
#> title = "Quick Power Verification",
#> design_type = "power_analysis",
#> levels = 1L,
#> n_obs = 120L,
#> residual_sd = 1,
#> error_dist = "normal",
#> intercept = 0,
#> focal_predictor = "trt",
#> fixed = list(trt = ...We can execute the generated standalone script in a clean environment to verify it runs end-to-end:
tmp_r <- tempfile(fileext = ".R")
compile_r_script(fast_spec, file = tmp_r)
sim_env <- new.env(parent = globalenv())
invisible(capture.output(sys.source(tmp_r, envir = sim_env)))
unlink(tmp_r)
sim_env$results$summary
#> cell_id n_reps n_converged true_effect mean_est bias emp_se mean_se rmse
#> 1 1 15 15 0.5 0.4399 -0.0601 0.1939 0.1844 0.1967
#> power coverage
#> 1 0.6667 0.9333And generating a full Quarto report (including LaTeX equations, audit table of defaults, YAML IR, and simulation chunks) takes one line:
qmd_doc <- compile_quarto_report(refined$spec)
cat(substr(qmd_doc, 1, 650), "...\n")
#> ---
#> title: "2-Level School Linear Power Simulation (Random Slopes, MAR Missingness)"
#> subtitle: "Reproducible Statistical Simulation Report (specshiny IR v1.2.0)"
#> format: html
#> execute:
#> echo: true
#> warning: false
#> message: false
#> eval: true
#> ---
#>
#> ## 1. Study Design Overview
#>
#> > **Originating Prompt:** 2-level multilevel power simulation with 60 schools, 25 students per school, ICC 0.2, treatment effect 0.35, random slope for x1, 15% MAR missingness, 500 replications
#>
#> | Component | Specification |
#> | :--- | :--- |
#> | **Design Type** | `power_analysis` |
#> | **Data Hierarchy** | 2-level (80 schools x 25 students; total N = 2000; ICC = 0.2) |
#> | **O ...6. Saving & Sharing Specifications
Specifications round-trip losslessly to YAML or JSON files:
tmp_yaml <- tempfile(fileext = ".yaml")
write_spec_ir(refined$spec, tmp_yaml)
reloaded <- read_spec_ir(tmp_yaml)
unlink(tmp_yaml)
diff_spec_ir(refined$spec, reloaded)$has_changes
#> [1] FALSE