library(tidyverse)
library(brms)
library(arrow)
library(INLA)
library(inlabru)
library(janitor)
library(gtsummary)

mr <- read_parquet('Data/mr.parquet') |>
  rename_with(str_trim) |>
  mutate(
    性别 = factor(str_trim(性别)),
    分组 = case_when(组别 == 'MMR' ~ 1, 组别 == 'MR' ~ 0),
    sex = ifelse(性别 == "男", 1, 0)
  )

mr_brm <- brm(组别 ~ 月龄, family = bernoulli(), data = mr)
summary(mr_brm)

model_age <- bru(
  分组 ~ 月龄,
  family = "binomial",
  data = mr,
  options = list(
    control.compute = list(dic = TRUE, waic = TRUE, config = TRUE),
    control.predictor = list(compute = TRUE)
  )
)

model_age <- inla(
  分组 ~ 月龄,
  family = "binomial",
  data = mr,
  control.compute = list(
    dic = TRUE,
    waic = TRUE,
    config = TRUE,
    cpo = TRUE,
    return.marginals.predictor = TRUE
  )
)

summary(model_age)

model_sex <- bru(
  分组 ~ sex,
  family = "binomial",
  data = mr,
  options = list(
    control.compute = list(dic = TRUE, waic = TRUE, config = TRUE),
    control.predictor = list(compute = TRUE)
  )
)

summary(model_sex)

model_jian <- bru(
  分组 ~ 间隔,
  family = "binomial",
  data = mr,
  options = list(
    control.compute = list(dic = TRUE, waic = TRUE, config = TRUE),
    control.predictor = list(compute = TRUE)
  )
)

summary(model_jian)

table_one <- mr |>
  select(组别, 性别, 月龄, 间隔) |>
  tbl_summary(
    by = 组别,
    statistic = list(
      all_continuous() ~ "{mean} ({sd})",
      all_categorical() ~ "{n} ({p}%)"
    ),
    digits = list(
      all_continuous() ~ 2,
      all_categorical() ~ 2
    ),
    label = list(
      性别 ~ "性别",
      月龄 ~ "月龄（月）",
      间隔 ~ "间隔 (天)"
    )
  ) |>
  add_p() |> # 添加p值
  add_overall() |> # 添加总体列
  modify_header(label ~ "**变量**") |>
  modify_spanning_header(c("stat_1", "stat_2") ~ "**组别**") |>
  bold_labels()

table_one |>
  gtsummary::as_tibble() %>%
  writexl::write_xlsx("Data/tableone.xlsx")

mr_long_numeric <- mr |>
  pivot_longer(
    cols = matches("(免前|免后).*(IgG|IgM)"),
    names_to = "变量名",
    values_to = "抗体值"
  ) |>
  mutate(
    时间点 = if_else(str_detect(变量名, "免前"), "免前", "免后"),
    指标 = str_remove(变量名, "免前|免后") |> str_trim(),
    时间点 = factor(时间点, levels = c("免前", "免后"))
  ) |>
  select(-变量名)

# 日期型数据
mr_long_date <- mr |>
  pivot_longer(
    cols = matches("(免前|免后).*日期"),
    names_to = "变量名",
    values_to = "采血日期"
  ) |>
  mutate(
    时间点 = if_else(str_detect(变量名, "免前"), "免前", "免后"),
    时间点 = factor(时间点, levels = c("免前", "免后"))
  ) |>
  select(-变量名) |>
  distinct(组别, 性别, 月龄, 时间点, .keep_all = TRUE)

# 合并
mr_long <- mr_long_numeric |>
  left_join(
    mr_long_date |> select(组别, 性别, 月龄, 时间点, 采血日期),
    by = c("组别", "性别", "月龄", "时间点")
  ) |>
  select(-c('免前采血日期', '免后采血日期')) |>
  mutate(免疫 = ifelse(时间点 == "免后", 1, 0))


##免前
mr_long |>
  filter(时间点 == '免前' & 指标 == '风疹-IgG' & 抗体值 > 0) |>
  mutate(log_antibody = log(抗体值)) -> jzq

formula <- log_antibody ~ 组别
model <- inla(
  formula,
  family = "gaussian",
  data = jzq,
  control.compute = list(
    dic = TRUE,
    waic = TRUE,
    cpo = TRUE,
    config = TRUE
  ),
  control.predictor = list(compute = TRUE),
)

summary(model)

# 1. 检查拟合诊断
plot(model$cpo$pit) # 检查CPO值
# 2. 后验预测检查
model$summary.fitted.values
# 3. 组间差异的后验概率
# P(MR组 < 对照组)
inla.pmarginal(0, model$marginals.fixed$组别MR)

#计算GMC
jzq |>
  group_by(组别) |>
  summarise(gmc = exp(mean(log(抗体值), na.rm = T)))

jzq |>
  group_by(组别) |>
  summarise(
    n = n(),
    log_mean = mean(log(抗体值)),
    log_sd = sd(log(抗体值)),
    log_se = log_sd / sqrt(n),

    # GMC
    gmc = exp(log_mean),

    # 95% CI (对数尺度)
    log_lower = log_mean - 1.96 * log_se,
    log_upper = log_mean + 1.96 * log_se,

    # 95% CI (原尺度)
    lower_95 = exp(log_lower),
    upper_95 = exp(log_upper),

    # 格式化
    CI_95 = sprintf("(%.2f, %.2f)", lower_95, upper_95),
    gmc = sprintf("%.2f", gmc)
  ) |>
  select(组别, n, gmc, lower_95, upper_95, CI_95)


mean(mr$`免后麻疹-IgG`, na.rm = T)
var(mr$`免后麻疹-IgG`, na.rm = T)
min(mr$`免后麻疹-IgG`, na.rm = T)

##麻疹抗体
data_measles <- mr_long |>
  filter(指标 == '麻疹-IgG') |>
  mutate(组别 = factor(组别), 时间点 = factor(时间点))

formula <- 抗体值 ~ 组别 +
  时间点 + # 固定效应
  f(月龄, model = "rw1") + # 月龄随机效应
  f(间隔, model = "rw1") + # 间隔随机效应
  f(编码, model = "iid") + # 个体随机效应
  f(性别, model = 'rw1') # 性别随机效应

model <- inla(
  formula,
  family = "gamma",
  data = data_measles,
  control.compute = list(
    dic = TRUE,
    waic = TRUE,
    cpo = TRUE,
    config = TRUE
  ),
  control.predictor = list(compute = TRUE, link = 1),
  control.inla = list(strategy = "adaptive")
)

summary(model)

##风疹抗体
data_rubella <- mr_long |>
  filter(指标 == '风疹-IgG') |>
  mutate(组别 = factor(组别), 时间点 = factor(时间点))

formula <- 抗体值 ~ 组别 +
  时间点 + # 固定效应
  f(月龄, model = "rw1") + # 月龄随机效应
  f(间隔, model = "rw1") + # 间隔随机效应
  f(编码, model = "iid") + # 个体随机效应
  f(性别, model = 'rw1') # 性别随机效应

model <- inla(
  formula,
  family = "gamma",
  data = data_rubella,
  control.compute = list(
    dic = TRUE,
    waic = TRUE,
    cpo = TRUE,
    config = TRUE
  ),
  control.predictor = list(compute = TRUE, link = 1),
  control.inla = list(strategy = "adaptive")
)

summary(model)


##腮腺炎抗体
data_mumps <- mr_long |>
  filter(指标 == '腮腺炎-IgG') |>
  mutate(组别 = factor(组别), 时间点 = factor(时间点))

formula <- 抗体值 ~ 组别 +
  时间点 + # 固定效应
  f(月龄, model = "rw1") + # 月龄随机效应
  f(间隔, model = "rw1") + # 间隔随机效应
  f(编码, model = "iid") + # 个体随机效应
  f(性别, model = 'rw1') # 性别随机效应

model <- inla(
  formula,
  family = "gamma",
  data = data_mumps,
  control.compute = list(
    dic = TRUE,
    waic = TRUE,
    cpo = TRUE,
    config = TRUE
  ),
  control.predictor = list(compute = TRUE, link = 1),
  control.inla = list(strategy = "adaptive")
)

summary(model)


#修改
##麻疹抗体
data_measles <- mr_long |>
  filter(指标 == '麻疹-IgG') |>
  mutate(组别 = factor(组别), 时间点 = factor(时间点))

formula <- 抗体值 ~ 组别 + 时间点 + 月龄 + 间隔 + 性别 + f(编码, model = "iid") # 个体随机效应

model <- inla(
  formula,
  family = "gamma",
  data = data_measles,
  control.compute = list(
    dic = TRUE,
    waic = TRUE,
    cpo = TRUE,
    config = TRUE
  ),
  control.predictor = list(compute = TRUE, link = 1),
  control.inla = list(strategy = "adaptive")
)

summary(model)
