## ----include=FALSE, results = 'hide'------------------------------------------
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)

## ----setup, 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),
     # calculating age at the end of follow up
    age_eof = as.numeric(difftime(indiv_eof, fdato, units = "days")) / 365.25) %>%
  filter(str_detect(id, "pid_g", negate = T))  # remove the genetic liability of the proband

## ----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, status, age_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)

## -----------------------------------------------------------------------------
# thresholds: personalised, fixed upper and lower threshold
multi_thrs_fixed = prepare_thresholds_multi(
  .tbl = pheno, CIP_list = CIP_list, phen_names = all_outcomes, personal_thr = TRUE, lower_equal_upper = TRUE
)

## ----echo=FALSE---------------------------------------------------------------
paged_table(multi_thrs_fixed)

## -----------------------------------------------------------------------------
graph = prepare_graph(.tbl = family, 
                      icol = "id",
                      mcol = "momcol", 
                      fcol = "dadcol",
                      node_attributes = select(multi_thrs_fixed, id,
                                               contains("lower"), 
                                               contains("upper"),
                                               contains("K_i"),
                                               contains("K_pop")))

## -----------------------------------------------------------------------------
# Identify family members of degree n
family_graphs = get_family_graphs(pop_graph = graph,
                                  ndegree = 1,
                                  proband_vec = multi_thrs_fixed$id,
                                  fid = "fid",
                                  fam_graph_col = "fam_graph")
family_graphs %>% print(n = 4)

## -----------------------------------------------------------------------------
family_graphs$fam_graph[[1]]

## -----------------------------------------------------------------------------
PA_MT = estimate_liability(family_graphs = family_graphs,
                           h2 = h2_vec,
                           genetic_corrmat = corMat,
                           phen_names = all_outcomes,
                           full_corrmat = diag(Ntrait),
                           target_phenotype = "disorder_1")

Gibbs_MT = estimate_liability(family_graphs = family_graphs,
                              h2 = h2_vec,
                              genetic_corrmat = corMat,
                              phen_names = all_outcomes,
                              full_corrmat = diag(Ntrait),
                              method = "Gibbs")


## ----echo=FALSE---------------------------------------------------------------
paged_table(PA_MT)

## ----echo=FALSE---------------------------------------------------------------
paged_table(Gibbs_MT)

## -----------------------------------------------------------------------------
# thresholds: personalised, fixed upper and lower threshold
multi_thrs_mixture = prepare_thresholds_multi(
  .tbl = pheno, 
  CIP_list = CIP_list, 
  phen_names = all_outcomes, 
  personal_thr = FALSE, 
  lower_equal_upper = FALSE
)

# creating a graph for the family with mixture model thresholds
graph_mixture = prepare_graph(.tbl = family, 
                              icol = "id",
                              mcol = "momcol",
                              fcol = "dadcol",
                              node_attributes = select(multi_thrs_mixture, id,
                                                       contains("lower"), 
                                                       contains("upper"),
                                                       contains("K_i"),
                                                       contains("K_pop")))
# Identify family members of degree n
family_graphs_mixture = get_family_graphs(pop_graph = graph_mixture,
                                          ndegree = 1,
                                          proband_vec = multi_thrs_mixture$id,
                                          fid = "fid",
                                          fam_graph_col = "fam_graph_mixture")


PA_MT_mix = estimate_liability(family_graphs = family_graphs_mixture,
                               family_graphs_col = "fam_graph_mixture",
                               h2 = h2_vec,
                               genetic_corrmat = corMat,
                               phen_names = all_outcomes,
                               full_corrmat = diag(Ntrait),
                               target_phenotype = "disorder_1", 
                               useMixture = TRUE)

## ----echo=FALSE---------------------------------------------------------------
paged_table(PA_MT_mix)

