## ----setup, include=FALSE-----------------------------------------------------
knitr::opts_chunk$set(echo = TRUE)

## ----results = 'hide',warning = FALSE, message = FALSE------------------------
library(LTFGRS)
library(dplyr)
library(lubridate)
library(rmarkdown)
library(stringr)

## -----------------------------------------------------------------------------
set.seed(555)
Ntrait = 3 # number of traits to consider
h2_vec = rep(0.5, Ntrait) # heritability
corMat = matrix(0.3, nrow = Ntrait, ncol = Ntrait) # genetic correlation matrix
diag(corMat) = 1
K = .3 # population prevalence
all_outcomes = paste0("disorder_", c("1", "2", "3")) # disorder names

## -----------------------------------------------------------------------------
# assuming we have been provided a CIP object of the following style:
CIP = expand.grid(list(age = 1:100,
                       birth_year = 1900:2024,
                       sex = 0:1)) %>%
  group_by(sex, birth_year) %>%
  mutate(cip = (1:n() - 1)/n() * K) %>%
  ungroup() %>% 
  print(n = 10)

## -----------------------------------------------------------------------------
# creating dummy CIP list for multiple traits
CIP_list = lapply(1:Ntrait, function(i) {
  CIP
})

## -----------------------------------------------------------------------------
# hand curated trio information, taken from LTFHPlus vignette:
# https://emilmip.github.io/LTFHPlus/articles/FromTrioToFamilies.html
family = tribble(
  ~id, ~momcol, ~dadcol,
  "pid", "mom", "dad",
  "sib", "mom", "dad",
  "mhs", "mom", "dad2",
  "phs", "mom2", "dad",
  "mom", "mgm", "mgf",
  "dad", "pgm", "pgf",
  "dad2", "pgm2", "pgf2",
  "paunt", "pgm", "pgf",
  "pacousin", "paunt", "pauntH",
  "hspaunt", "pgm", "newpgf",
  "hspacousin", "hspaunt", "hspauntH",
  "puncle", "pgm", "pgf",
  "pucousin", "puncleW", "puncle",
  "maunt", "mgm", "mgf",
  "macousin", "maunt", "mauntH",
  "hsmuncle", "newmgm", "mgf",
  "hsmucousin", "hsmuncleW", "hsmuncle"
)

## -----------------------------------------------------------------------------

# creating a graph for the family
graph = prepare_graph(.tbl = family, icol = "id", mcol = "momcol", fcol = "dadcol")
# calculating the kinship matrix based on the graph
cov_mat_obj = graph_based_covariance_construction_multi(
  fid = "fam",
  pid = "pid",
  cur_proband_id = "pid",
  cur_family_graph = graph,
  h2_vec = h2_vec,
  genetic_corrmat = corMat,
  useMixture = FALSE,
  phen_names = c("1", "2", "3"),
  add_ind = TRUE)

# creating a phenotype for the family
liabs = MASS::mvrnorm(n = 1, mu = rep(0, nrow(cov_mat_obj$cov)), Sigma = cov_mat_obj$cov)

## -----------------------------------------------------------------------------
pheno = tibble(
  id = names(liabs),
  status = liabs > qnorm(K, lower.tail = F),
  # no consideration for generation etc in sex, fdato or birth_year:
  sex = rep(sample(0:1, size = length(liabs)/Ntrait, replace = TRUE), Ntrait),
  fdato = rep(dmy(paste0(sample(1:28, length(liabs)/Ntrait, replace = T), "/", sample(1:12, length(liabs)/Ntrait, replace = T), "/", sample(1940:2000, length(liabs)/Ntrait, replace = T))), Ntrait),
  birth_year = year(fdato),
  # age of onset only after fdato
  disorder = purrr::map2_chr(.x = status, .y = birth_year,
                         ~ if(.x) paste0(sample(1:28, 1), "/", sample(1:12, 1), "/", sample((.y + 1):2010, 1)) else NA),
  # end of follow up assigned here
  indiv_eof = dmy("31/12/2010")) %>% # blanket time stop, meant to simulate end of registers
  mutate(
    # converting to date format
    disorder = dmy(disorder),
    # eof either blanket time stop or event date
    indiv_eof = pmin(indiv_eof, disorder, na.rm = T)) %>% 
  filter(str_detect(id, "pid_g", negate = T)) %>%   # remove the genetic liability of the proband
  # status is not required here. Only used it to generate the age of diagnosis.
  select(-contains("status"))

## ----echo=FALSE---------------------------------------------------------------
paged_table(pheno)

## -----------------------------------------------------------------------------
pheno %>% filter(str_detect(id, "pid"))

## -----------------------------------------------------------------------------
# helper function - from: https://stackoverflow.com/questions/7963898/extracting-the-last-n-characters-from-a-string-in-r
substrRight <- function(x, n){
  substr(x, nchar(x)-n+1, nchar(x))
}
pheno = pheno %>%
  mutate(trait = substrRight(id, 1),
         id = substr(id, 1, nchar(id) - 2)) %>%
  tidyr::pivot_wider(names_from = trait,
                     values_from = c(disorder, indiv_eof),
                     names_glue = "{.value}_{trait}")
# sorting out names, such that they follow the required pattern with suffix ending in one of the disorder names:
colnames(pheno)[-(1:7)] = str_replace_all(colnames(pheno)[-(1:7)], 
                                          c("_1" = "_disorder_1", 
                                            "_2" = "_disorder_2", 
                                            "_3" = "_disorder_3"))

## ----echo=FALSE---------------------------------------------------------------
paged_table(pheno)

## -----------------------------------------------------------------------------
graph = prepare_graph(.tbl = family, 
                      icol = "id",
                      mcol = "momcol", 
                      fcol = "dadcol")

## -----------------------------------------------------------------------------
# Identify family members of degree n
family_graphs = get_family_graphs(pop_graph = graph,
                                  ndegree = 1,
                                  proband_vec = pheno$id,
                                  fid = "fid",
                                  fam_graph_col = "fam_graph")
family_graphs %>% print(n = 4)

## -----------------------------------------------------------------------------
# calculate family specific thresholds

info = familywise_censoring_multi(
  family_graphs = family_graphs,
  tbl = pheno %>% rename(pid = id),
  start = "fdato",
  end_base = "indiv_eof",
  phen_names = all_outcomes,
  target_outcome = "disorder_1",
  status_col_base = "status",
  aod_col_base = "aod",
  age_eof_col_base = "age_eof",
  fam_graph_col = "fam_graph",
  fid = "fid",
  pid = "pid",
  simplify = TRUE # simplifies output by removing all columns not specific to an outcome.
)

## ----echo=FALSE---------------------------------------------------------------
paged_table(info)

## -----------------------------------------------------------------------------
# thresholds: personalised, fixed upper and lower threshold
multi_thrs = prepare_thresholds_multi(
  .tbl = info,
  CIP_list = CIP_list, 
  phen_names = all_outcomes, 
  personal_thr = TRUE, 
  lower_equal_upper = TRUE
)


## ----echo=FALSE---------------------------------------------------------------
paged_table(multi_thrs)

## -----------------------------------------------------------------------------
# attach family specific thresholds
ltfgrs_input = familywise_attach_attributes(
  family_graphs = family_graphs,
  fam_attr = multi_thrs,
  fam_graph_col = "fam_graph",
  attached_fam_graph_col = "masked_fam_graph",
  cols_to_attach = str_subset(colnames(multi_thrs), "lower|upper|K_i|K_pop"),
  proband_cols_to_censor = str_subset(colnames(multi_thrs), "lower|upper|K_i|K_pop"))
ltfgrs_input %>% print(n = 4)

## -----------------------------------------------------------------------------
ltfgrs_input$masked_fam_graph[[1]]

## -----------------------------------------------------------------------------
ltfgrs_pa = estimate_liability(family_graphs = ltfgrs_input,
                                h2 = h2_vec,
                               genetic_corrmat = corMat,
                               full_corrmat = diag(Ntrait),
                               phen_names = all_outcomes,
                               fid = "fid",
                               pid = "pid",
                               family_graphs_col = "masked_fam_graph",
                               method = "PA", # <- METHOD
                               target_phenotype = "disorder_1",
                               useMixture = F)

## ----echo=FALSE---------------------------------------------------------------
paged_table(ltfgrs_pa)

## -----------------------------------------------------------------------------
ltfgrs_gibbs = estimate_liability(family_graphs = ltfgrs_input,
                                  h2 = h2_vec,
                                  genetic_corrmat = corMat,
                                  full_corrmat = diag(Ntrait),
                                  phen_names = all_outcomes,
                                  fid = "fid",
                                  pid = "pid",
                                  family_graphs_col = "masked_fam_graph",
                                  method = "Gibbs", # <- METHOD
                                  useMixture = F)

## ----echo=FALSE---------------------------------------------------------------
paged_table(ltfgrs_gibbs)

## ----message=FALSE, warning=FALSE---------------------------------------------
# creating a graph for the family with mixture model thresholds
graph_mixture = prepare_graph(.tbl = family, 
                              icol = "id",
                              mcol = "momcol",
                              fcol = "dadcol")

# Identify family members of degree n
family_graphs_mixture = get_family_graphs(pop_graph = graph_mixture,
                                          ndegree = 1,
                                          proband_vec = pheno$id,
                                          fid = "fid",
                                          fam_graph_col = "fam_graph")


info_mixture = familywise_censoring_multi(
  family_graphs = family_graphs_mixture,
  tbl = pheno %>% rename(pid = id),
  start = "fdato",
  end_base = "indiv_eof",
  phen_names = all_outcomes,
  target_outcome = "disorder_1",
  status_col_base = "status",
  aod_col_base = "aod",
  age_eof_col_base = "age_eof",
  fam_graph_col = "fam_graph",
  fid = "fid",
  pid = "pid",
  simplify = TRUE # simplifies output by removing all columns not specific to an outcome.
)


# thresholds: personalised, fixed upper and lower threshold
multi_thrs_mixture = prepare_thresholds_multi(
  .tbl = info_mixture, 
  CIP_list = CIP_list, 
  phen_names = all_outcomes, 
  personal_thr = FALSE, #<--
  lower_equal_upper = FALSE #<---
)


# attaching familywise censored thresholds to family graphs
ltfgrs_input = familywise_attach_attributes(
  family_graphs = family_graphs_mixture,
  fam_attr = multi_thrs_mixture,
  fam_graph_col = "fam_graph",
  attached_fam_graph_col = "masked_fam_graph_mixture",
  cols_to_attach = str_subset(colnames(multi_thrs), "lower|upper|K_i|K_pop"), #<-- includes K_i and K_pop
  proband_cols_to_censor = str_subset(colnames(multi_thrs), "lower|upper|K_i|K_pop")) #<--


PA_MT_mix = estimate_liability(family_graphs = ltfgrs_input,
                               family_graphs_col = "masked_fam_graph_mixture",
                               h2 = h2_vec,
                               genetic_corrmat = corMat,
                               phen_names = all_outcomes,
                               full_corrmat = diag(Ntrait),
                               target_phenotype = "disorder_1", 
                               useMixture = TRUE)#<-- using mixture model

## ----echo=FALSE---------------------------------------------------------------
paged_table(PA_MT_mix)

