# ============================================================================== # 04_brms_laterality_analysis.R # Repeating the 07_Trans_Neuro_Meta Trick on Iain McGilchrist's Hemisphere Theory # Engine: Stan NUTS via brms + cmdstanr | Joint mi(Age_z) | ROPE [-0.1, 0.1] # ============================================================================== library(brms) library(dplyr) library(bayesplot) library(ggplot2) library(jsonlite) setwd("C:/Users/Vivian/Desktop/R Projects/09_McGilchrist_Hemisphere_Meta") source("cybernetic_laterality_verbs.R") set.seed(42) cat("1. Loading and auditing verified empirical laterality dataset (k = 28, J = 14 papers)...\n") data <- read.csv("mcgilchrist_empirical_data.csv", stringsAsFactors = FALSE) |> audit_cybernetic_loop_closure() # Set LeftBrain_RightBrain_Typology as reference intercept so Intercept directly tests # McGilchrist's global bi-hemispheric mode / typology claim after confound marginalization! data$cognitive_domain <- relevel( factor(data$cognitive_domain), ref = "LeftBrain_RightBrain_Typology" ) cat(sprintf( "Loaded %d empirical effects | Missing Age_z rows for joint Stan mi(): %d (%.1f%%)\n", nrow(data), sum(is.na(data$Age_z)), 100 * mean(is.na(data$Age_z)) )) # 2. Compute N-Dimensional Hypervolume Regime Overlap (Pipeable Gestalt Verb!) hv_res <- compute_regime_hypervolume_overlap(data) cat("Hypervolume Jaccard Overlap (Clamped/GSR vs. Naturalistic):", round(hv_res$overlap$jaccard[1], 4), "\n") # 3. Exact Structural Isomorphism with 07_Trans_Neuro_Meta # Joint Multivariate Stan Model: # - Marginalizes handedness_controlled (motor/Broca wiring efficiency) # - Marginalizes gsr_applied (Murphy 2009 whole-body autonomic erasure artifact) # - Marginalizes open_loop_clamped (<200ms tachistoscopic / head-fixed cross-cueing block) # - Jointly imputes missing Age_z inside NUTS via brms::mi(Age_z) # - Partitions variance across (1 | study_id) + (1 | paradigm_class) + (1 | cognitive_domain) meta_formula <- bf( yi | se(sei) ~ 0 + Intercept + cognitive_domain + handedness_controlled + gsr_applied + open_loop_clamped + mi(Age_z) + (1 | study_id) + (1 | paradigm_class) ) + bf(Age_z | mi() ~ 1) + set_rescor(FALSE) prior_array <- c( prior(normal(0, 0.5), class = "b", resp = "yi"), prior(student_t(3, 0, 1), class = "sd", resp = "yi", lb = 0) ) cat("4. Compiling & sampling Stan NUTS model via cmdstanr (4 chains x 4000 iter)...\n") fit <- brm( formula = meta_formula, data = data, prior = prior_array, sample_prior = "yes", chains = 4, cores = 4, iter = 4000, warmup = 2000, seed = 42, backend = "cmdstanr", control = list(adapt_delta = 0.99, max_treedepth = 12), refresh = 500 ) # 5. Save Full Posterior Summary & ROPE Tests post_summary <- summary(fit) capture.output(post_summary, file = "posterior_summary.txt") h_typology <- hypothesis(fit, "yi_Intercept > 0", rope = c(-0.1, 0.1)) h_coupling <- hypothesis(fit, "yi_Intercept + yi_cognitive_domainCross_Domain_Coupling > 0", rope = c(-0.1, 0.1)) h_global <- hypothesis(fit, "yi_Intercept + yi_cognitive_domainGlobal_Contextual_RH > 0", rope = c(-0.1, 0.1)) h_clamp <- hypothesis(fit, "yi_open_loop_clamped > 0", rope = c(-0.1, 0.1)) h_gsr <- hypothesis(fit, "yi_gsr_applied > 0", rope = c(-0.1, 0.1)) capture.output( cat("=== 1. Global Left/Right Typology (Baseline Marginalized Mode) ===\n"), print(h_typology), cat("\n=== 2. Cross-Domain LH-RH Complementary Coupling ===\n"), print(h_coupling), cat("\n=== 3. Global/Contextual RH Attention Mode ===\n"), print(h_global), cat("\n=== 4. Open-Loop Tachistoscopic Clamping Confound ===\n"), print(h_clamp), cat("\n=== 5. Global Signal Regression (GSR) Confound ===\n"), print(h_gsr), file = "rope_tests.txt" ) # 6. Extract Posterior Draws & Variance Decomposition via Pipeable Verb post_draws <- as_draws_df(fit) decomp_df <- decompose_unmodeled_variance(post_draws) calc_metric <- function(vec) { pd <- max(mean(vec > 0), mean(vec < 0)) list( mean = round(mean(vec), 4), median = round(median(vec), 4), sd = round(sd(vec), 4), ci95_low = round(unname(quantile(vec, 0.025)), 4), ci95_high = round(unname(quantile(vec, 0.975)), 4), rope_pct = round(100 * mean(vec >= -0.1 & vec <= 0.1), 2), bayes_p = round(2 * (1 - pd), 4) ) } metrics_payload <- list( n_effects = nrow(data), n_studies = length(unique(data$study_id)), total_participants_sum = sum(data$n_total), pct_missing_age_imputed = round(100 * mean(is.na(data$Age_z)), 1), hypervolume_jaccard = round(hv_res$overlap$jaccard[1], 4), typology_mode = calc_metric(decomp_df$b_typology), cross_domain_coupling = calc_metric(decomp_df$b_cross_coupling), global_contextual_rh = calc_metric(decomp_df$b_global_rh), local_detail_lh = calc_metric(post_draws$b_yi_Intercept + post_draws$b_yi_cognitive_domainLocal_Detail_LH), unified_splitbrain = calc_metric(post_draws$b_yi_Intercept + post_draws$b_yi_cognitive_domainUnified_CrossField_Control), handedness_confound = calc_metric(post_draws$b_yi_handedness_controlled), gsr_confound = calc_metric(post_draws$b_yi_gsr_applied), open_loop_clamp_confound = calc_metric(post_draws$b_yi_open_loop_clamped), mi_age_slope = calc_metric(post_draws$bsp_yi_miAge_z), sd_study = calc_metric(decomp_df$sd_study), sd_paradigm = calc_metric(decomp_df$sd_paradigm), sd_unmodeled_total = calc_metric(decomp_df$sd_unmodeled_total), median_uvr_ratio = round(median(decomp_df$uvr_ratio), 2) ) write_json(metrics_payload, "mcgilchrist_metrics.json", pretty = TRUE, auto_unbox = TRUE) # 7. Generate Publication-Grade Dark-Mode Catppuccin Posterior Plot plot_df <- tibble::tibble( `Global Left/Right Typology` = decomp_df$b_typology, `LH-RH Cross-Domain Coupling` = decomp_df$b_cross_coupling, `RH Broad/Contextual Mode` = decomp_df$b_global_rh, `Open-Loop Lab Clamp Shift` = post_draws$b_yi_open_loop_clamped, `GSR Preprocessing Shift` = post_draws$b_yi_gsr_applied, `Unmodeled Study+Paradigm SD` = decomp_df$sd_unmodeled_total ) color_scheme_set("purple") p1 <- mcmc_areas( plot_df, prob = 0.89, prob_outer = 0.95, point_est = "median" ) + ggplot2::geom_vline(xintercept = c(-0.1, 0.1), linetype = "dashed", color = "#ed8796", linewidth = 1.0) + ggplot2::geom_vline(xintercept = 0, linetype = "solid", color = "#a5adcb", linewidth = 0.5) + ggplot2::labs( title = "McGilchrist Hemisphere Meta-Audit: Posterior Densities vs. Unmodeled Variance", subtitle = "Stan NUTS (8,000 draws) | Marginalizing Handedness, GSR, Open-Loop Clamping & Joint mi(Age_z) | ROPE [-0.1, 0.1]" ) + ggplot2::theme_minimal(base_size = 13) + ggplot2::theme( plot.background = ggplot2::element_rect(fill = "#181926", color = "#363a4f"), panel.background = ggplot2::element_rect(fill = "#181926", color = NA), panel.grid.major = ggplot2::element_line(color = "#24273a"), panel.grid.minor = ggplot2::element_blank(), text = ggplot2::element_text(color = "#cad3f5"), axis.text = ggplot2::element_text(color = "#cad3f5", face = "bold"), plot.title = ggplot2::element_text(color = "#f5bde6", face = "bold", size = 14), plot.subtitle = ggplot2::element_text(color = "#eed49f", size = 10.5) ) ggsave("mcgilchrist_posterior_densities.png", plot = p1, width = 10, height = 6.2, dpi = 160) file.copy("mcgilchrist_posterior_densities.png", "C:/Users/Vivian/Desktop/bulletin_board/mcgilchrist_posterior_densities.png", overwrite = TRUE) cat("7. Analysis complete! Metrics JSON & Posterior PNG saved.\n")