vis.InOutNodes <- function(root.node, edge.full.list, pvalue.full.list,
                           dict.combine,thr_p,thr_OR){
  n.root = length(root.node)
  if(n.root==1){
    edge.matrix = t(as.matrix(edge.full.list[root.node,]))
    pvalue.matrix = t(as.matrix(pvalue.full.list[root.node,]))
    rownames(edge.matrix) = rownames(edge.full.list)[root.node]
    rownames(pvalue.matrix) = rownames(pvalue.full.list)[root.node]
  }else{
    edge.matrix = edge.full.list[root.node,]
    pvalue.matrix = pvalue.full.list[root.node,]
  }
  edge.matrix[abs(log(edge.matrix[edge.matrix>0]))<thr_OR]  = 0
  edge.matrix[pvalue.matrix>thr_p|pvalue.matrix==0]  = 0
  edge.matrix.full = edge.full.list
  pvalue.matrix.full = pvalue.full.list
  which(colSums(edge.matrix) == NA)
  
  ### nodes
  nodes = data.frame(id = unique(c(rownames(edge.matrix),
                                   colnames(edge.matrix)[colSums(edge.matrix)>0])))
  nodes = na.omit(nodes)
  nodes$id_ances = nodes$id
  nodes$id = str_remove(nodes$id, "[a-zA-Z]+\\_")
  n.nonroot = nrow(nodes) - n.root
  nodes$id = as.character(nodes$id)
  
  title = dict.combine$Description[match(nodes$id,dict.combine$Variable)]
  title = str_remove(title, "^[A-Z]{3}: ")
  title[1:n.root] = dict.combine$Description[match(nodes$id_ances[1:n.root],dict.combine$uid)]
  
  label = dict.combine$Description_s[match(nodes$id,dict.combine$Variable)]
  label = str_remove(label, "^[A-Z]{3}: ")
  label[1:n.root] = dict.combine$Description[match(nodes$id_ances[1:n.root],dict.combine$uid)]
  
  
  nodes = cbind(nodes, data.frame(label = label,
                                  iscenter = c(rep(1,n.root),rep(0,n.nonroot)),
                                  ancestry = dict.combine$ancestry[match(nodes$id,dict.combine$Variable)],
                                  group = dict.combine$group[match(nodes$id,dict.combine$Variable)],
                                  type = dict.combine$type[match(nodes$id,dict.combine$Variable)],
                                  chromo = dict.combine$chromosome[match(nodes$id,dict.combine$Variable)],
                                  gene = dict.combine$gene[match(nodes$id,dict.combine$Variable)],
                                  phetype = dict.combine$phetype[match(nodes$id,dict.combine$Variable)],
                                  shape = c(rep("star",n.root),rep("square",n.nonroot)),
                                  mass = c(rep(5,n.root),rep(1,n.nonroot)),
                                  font.size = c(rep(50,n.root),rep(42,n.nonroot)),
                                  size =  c(rep(30,n.root),rep(20,n.nonroot)),
                                  font.background = c(rep("#FFFFF0",n.root),rep("#FFFFF0",n.nonroot)),
                                  borderWidth = c(rep(2,n.root),rep(1,n.nonroot)),
                                  borderWidthSelected = c(rep(3,n.root),rep(2,n.nonroot))))
  nodes$shape[nodes$phetype == "SNP"] = "triangle"
  nodes$group = as.character(nodes$group)
  nodes$group[1:n.root] = as.character(nodes$label[1:n.root])
  nodes$group[is.null(nodes$group)] = nodes$id[is.null(nodes$group)]
  nodes$group[is.na(nodes$group)] = nodes$id[is.na(nodes$group)]
  nodes$group[nodes$group=="null"] = nodes$id[nodes$group=="null"]
  nodes$gene_group = nodes$gene
  nodes$gene_group[is.na(nodes$gene_group)] = nodes$id[is.na(nodes$gene_group)]
  nodes$phe_group = nodes$phetype
  nodes$phe_group[nodes$phe_group=="SNP"] = nodes$id[nodes$phe_group=="SNP"]
  nodes$id = nodes$id_ances
  node.used = c()
  edges.dataframe = data.frame()
  for (i in 1:nrow(edge.matrix)) {
    edges = data.frame()
    from = to = rownames(edge.matrix)[i]
    newtofrom = colnames(edge.matrix)[which(edge.matrix[i,]!=0)]
    color.opa = c()
    if(length(newtofrom)!=0){
      i.loc = root.node[i]
      newtofrom.value = abs(log(edge.matrix.full[i.loc, newtofrom]))^(-1)
      #newtofrom.value = abs(log(edge.matrix.full[newtofrom,i.loc]))^3
      OR.value = edge.matrix.full[i.loc, newtofrom]
      newtofrom.p = pvalue.matrix.full[i.loc, newtofrom]
      rr = rank(newtofrom.value,ties.method = "random")
      newtofrom[rr] = newtofrom
      newtofrom.value = sort(newtofrom.value)
      newtofrom.p[rr] = newtofrom.p
      OR.value[rr] = OR.value
      length=abs(newtofrom.value)
      color.opa = c(color.opa, -log10(newtofrom.p))
      edges = rbind(edges, data.frame(to=as.character(newtofrom),
                                      from=as.character(rep(from,length(newtofrom))),
                                      edgetype="both directions",
                                      odds_ratio=OR.value,
                                      pvalue=newtofrom.p,
                                      length=length,
                                      hidden=FALSE,
                                      title= paste0(as.character(newtofrom),"<b> &harr; </b>",
                                                    as.character(rep(to,length(newtofrom))),
                                                    "<br>Odds ratio: ",signif(OR.value,3),
                                                    "<br>P value: ",newtofrom.p)))
      
    }
    node.used = c(node.used, rownames(edge.matrix)[i])
    p.limit = 2.2
    color.opa[color.opa<p.limit] = (color.opa[color.opa<p.limit])/p.limit
    color.opa[color.opa>=p.limit] = 1
    color.opa = sapply(color.opa,function(x) max(x,0.2))
    #plot(length.total,color.opa)
    if(is.na(color.opa[1])){
      color.opa = 1
    }
    if(nrow(edges)!=0){
      color.color.1 = paste0("rgba(220,20,60,", color.opa,")")  # OR>1 red
      color.color.2 = paste0("rgba(0,0,255,", color.opa,")")  # OR<1 blue 
      
      edges = cbind(edges, data.frame(color.color=color.color.1,
                                      color.opa = color.opa,
                                      smooth = TRUE,
                                      width=2.5,
                                      selectionWidth=3.5))
      edges$length = unlist(edges$length)
      edges$color.color[edges$odds_ratio<1]=color.color.2[edges$odds_ratio<1]
      edges.dataframe = rbind(edges.dataframe,edges)
    }
    edges_id_uni = unique(c(edges$from,edges$to))
    phe_uni = unique(dict.combine$phetype[match(edges_id_uni,dict.combine$Variable)])
    phe_uni = na.omit(phe_uni)
    phe_uni = setdiff(phe_uni,"SNP")
    for (j in 1:length(phe_uni)) {
      nodes_sub = nodes[nodes$phetype==phe_uni[j] & nodes$id %in% edges_id_uni,]
      if(nrow(nodes_sub)>=2){
        edges_sub = edges[1:(nrow(nodes_sub)-1),]
        edges_sub$from = nodes_sub$id[-1]
        edges_sub$to = nodes_sub$id[-nrow(nodes_sub)]
        edges_sub$color.color = "rgba(0,255,255,1)"
        edges_sub = edges_sub[!(edges_sub$from %in% to | edges_sub$to %in% to),]
        edges_sub$edgetype = "only display"
        edges_sub$length = 0.01
        edges_sub$hidden=TRUE
        edges_sub$title = NA
        edges_sub = edges_sub[!is.na(edges_sub$from), ]
        edges.dataframe = rbind(edges.dataframe,edges_sub)
      }
    }
  }
  edges = edges.dataframe
  
  # if centers are connected, bold + change color
  edges$color.highlight = edges$color.color
  
  type.names = unique(dict.combine$phetype)
  
  
  ##### code colors!!!!
  type.colors = c("#7FFF00",inlmisc::GetColors(9, scheme = "light"),
                  inlmisc::GetColors(9, scheme = "sunset"))
  
  type.colors.rgb = paste0("rgba(",apply(col2rgb(type.colors),2,function(x){
    paste0(x,collapse = ",")
  }), ",")
  
  nodes.colors = nodes.colors.select = nodes$id
  type.legend = list(1,1)
  type.legend[[1]] = list(label = "SNP",shape="box",color="rgb(127,255,0)",
                          physics = FALSE,size=10)
  #type.legend[[1]] = list(label = "Phecode",shape="box",color="rgb(135,206,250)",
  #                         physics = FALSE,size=10)
  type.legend[[2]] = list(label = "Cluster",shape="ellipse",color="rgb(255,99,71)",
                          physics = FALSE,size=10)
  
  ledges <- data.frame(color = c("rgb(0,0,255)","rgba(220,20,60)"),
                       label = c("OR<1", "OR>1"), 
                       width = 3, arrows = c("",""),
                       physics = FALSE,font.align = c("top","top"),font.size=10)  
  for (i in 1:length(type.names)) {
    nodes.colors[which(nodes$phetype==type.names[i])] = type.colors.rgb[i]
    nodes.colors.select[which(nodes$phetype==type.names[i])] = type.colors[i]
  }
  
  nodes$color.opa = sapply(1:length(nodes$id), function(i){
    if(!(nodes$id[i] %in% edges$from | nodes$id[i] %in% edges$to)){
      1
    }else{
      max(edges$color.opa[nodes$id[i]==edges$from],
          edges$color.opa[nodes$id[i]==edges$to])
    }
  })
  nodes$color.background = paste0(nodes.colors,nodes$color.opa,")")
  nodes$color.highlight.background = paste0(nodes.colors,"1)")
  #nodes$color.hover.background = paste0(nodes.colors,"1)")
  
  nodes$color.border = nodes$color.background
  nodes$color.highlight.border = nodes$color.highlight.background
  #nodes$color.hover.border = nodes$color.hover.background
  
  #nodes$color.background[1:n.root] = nodes$color.highlight.background[1:n.root] =
  #  nodes$color.hover.background[1:n.root] =  nodes$color.border[1:n.root] = "#FF0000"
  nodes$color.highlight.border[1:n.root] = "#FF0000"
  
  nodes$font.size = sapply(nodes$color.opa*35,function(x){max(min(x,32),10)})
  nodes$font.size[str_length(nodes$label)>40] = 
    nodes$font.size[str_length(nodes$label)>40]*40/
    str_length(nodes$label[str_length(nodes$label)>40])
  nodes$font.size[str_length(nodes$label)>40] = sapply(nodes$font.size[str_length(nodes$label)>40],
                                                       function(x){max(x,10)})
  nodes$font.size[1:n.root] = 50
  nodes$font.size = nodes$font.size / 1.2
  nodes$font.background[(n.root+1):nrow(nodes)] = nodes$color.background[(n.root+1):nrow(nodes)]
  nodes$shape[nodes$type=="phecode"&nodes$iscenter==1] = "triangle"
  nodes$font.color = "black"
  nodes$font.color[1:n.root] = "red"
  ### If cluster by both
  group.target = unique(nodes$group[1:n.root])
  group.other = na.omit(setdiff(unique(nodes$group),group.target))
  text.group.color = NA
  if(length(group.other)!=0){
    text.group.color = paste0("rgba(255,99,71,", sapply(group.other, function(group){
      max(nodes$color.opa[which(nodes$group==group)])}),")")
    
  }
  text.group.color = na.omit(unlist(text.group.color))
  
  
  ### If cluster by genes
  gene.target = unique(nodes$gene[1:n.root])
  gene_group.other = na.omit(setdiff(unique(nodes$gene_group),gene.target))
  text.gene_group.color = NA
  if(length(gene_group.other)!=0){
    text.gene_group.color = paste0("rgba(255,99,71,", sapply(gene_group.other, function(group){
      max(nodes$color.opa[which(nodes$gene_group==group)])}),")")
    
  }
  text.gene_group.color = na.omit(unlist(text.gene_group.color))
  
  
  ### If cluster by phetypes
  phe.target = unique(nodes$phe_group[1:n.root])
  phe_group.other = na.omit(setdiff(unique(nodes$phe_group),phe.target))
  text.phe_group.color = NA
  if(length(phe_group.other)!=0){
    text.phe_group.color = paste0("rgba(255,99,71,", sapply(phe_group.other, function(group){
      max(nodes$color.opa[which(nodes$phe_group==group)])}),")")
    
  }
  text.gene_group.color = na.omit(unlist(text.gene_group.color))
  
  
  nodes$title = NA
  nodes$title[which(nodes$type=='snpcode')] =
    paste0("<b>",title[which(nodes$type=='snpcode')],"</b>",
           "<br>Gene:", nodes$gene[which(nodes$type=='snpcode')],
           "<br>Chromosome:", nodes$chromo[which(nodes$type=='snpcode')])
  #nodes = rbind(nodes[((n.root+1):nrow(nodes)),],nodes[(1:n.root),])
  
  nodes$title[which(nodes$type=='phecode')] =
    paste0("<b>",title[which(nodes$type=='phecode')],"</b>",
           "<br>Phecode:", nodes$id[which(nodes$type=='phecode')],
           "<br>Phetype:", nodes$phetype[which(nodes$type=='phecode')])
  nodes[nodes$iscenter==0,] = nodes[nodes$iscenter==0,] %>% arrange(group)
  return(list(nodes, edges, list(type.legend,ledges), 
              `both_group`=list(group.target, group.other, text.group.color),
              `gene_group`=list(gene.target, gene_group.other, text.gene_group.color),
              `phe_group`=list(phe.target, phe_group.other, text.phe_group.color)))
}








## Generate circular plot using ggplot =======================================
circularPreData <- function(data){
  # Set a number of 'empty bar' to add at the end of each group
  n_group = length(unique(data$group))
  empty_bar=n_group - 1
  to_add = data.frame( matrix(NA, empty_bar*nlevels(data$group), ncol(data)) )
  colnames(to_add) = colnames(data)
  to_add$group=rep(levels(data$group), each=empty_bar)
  data=rbind(data, to_add)
  data=data %>% arrange(group, individual, source, value)
  data$id=seq(1, nrow(data))
  
  # Get the name and the y position of each label
  label_data=data
  number_of_bar=nrow(label_data)
  angle= 90 - 360 * (label_data$id-0.5) /number_of_bar     # I substract 0.5 because the letter must have the angle of the center of the bars. Not extreme right(1) or extreme left (0)
  label_data$hjust<-ifelse( angle < -90, 1, 0)
  label_data$angle<-ifelse(angle < -90, angle+180, angle)
  
  # prepare a data frame for base lines
  base_data=data %>%
    group_by(group) %>%
    summarize(start=min(id), end=max(id) - empty_bar) %>%
    rowwise() %>%
    mutate(title=mean(c(start, end)))
  
  
  # prepare a data frame for grid (scales)
  grid_data = base_data
  grid_data$end = grid_data$end[c( nrow(grid_data), 1:nrow(grid_data)-1)] + 1
  grid_data$start = grid_data$start - 1
  if(nrow(grid_data)>1){
    grid_data=grid_data[-1,]
  }else{
    grid_data$start = -1
  }
  return(list(`data` = data, `label_data` = label_data, 
              `grid_data` = grid_data, `base_data` = base_data))
}

circularStatic <- function(node_now, thr_pval=0.05, 
                           edge.full.list, pvalue.full.list, pvalue.bon.full.list, 
                           dict.combine){
  if(length(node_now) == 0){return()}
  node_now_name = dict.combine$Description[match(node_now,dict.combine$uid)]
  node_now_group = dict.combine$group[match(node_now,dict.combine$uid)]
  node_now_group[is.na(node_now_group)] = "Others"
  node_now_type = dict.combine$type[match(node_now,dict.combine$uid)]
  
  OR_lst = sapply(node_now, function(i){
    b = data.frame(`id` = colnames(edge.full.list),
                   `OR` = edge.full.list[match(i, rownames(edge.full.list)), ],
                   `pval` = pvalue.full.list[match(i, rownames(pvalue.full.list)), ],
                   `pval.bon` = pvalue.bon.full.list[match(i, rownames(pvalue.full.list)), ])
    b$OR[b$OR>10] = 10
    b$OR[b$OR==0] = NA
    # b = b[b$pval < thr_pval & b$OR != 0, ]
    return(b)
  }, simplify = FALSE)
  
  id.keep = sapply(1:length(OR_lst), function(i){
    b =  OR_lst[[i]]
    sig = b$id[b$pval.bon < thr_pval]
    return(sig)
  })
  id.keep = unique(unlist(id.keep))
  
  OR_lst = sapply(1:length(OR_lst), function(i){
    b = OR_lst[[i]]
    b = b[b$id %in% id.keep, ]
    return(b)
  }, simplify = FALSE)
  
  for(i in 1:length(OR_lst)){
    a = OR_lst[[i]]
    if(unique(node_now_type)=="phecode"){
      a$source_id = paste0(node_now[i]," ",
                           dict.combine$Description[match(node_now[i], dict.combine$uid)])
      
    }else{
      a$source_id = node_now[i]
    }
    if(i == 1){
      OR_df = a
    }else{
      id_rep = intersect(OR_df$id, a$id)
      OR_df = rbind(OR_df[OR_df$id %in% id_rep, ], 
                    a[a$id %in% id_rep, ])
    }
  }
  
  if(unique(dict.combine$type[match(OR_df$id, dict.combine$Variable)]) == "phecode"){
    desc = str_remove(dict.combine$Description[match(OR_df$id, dict.combine$Variable)],
                      "^[A-Z]{3}: ")
    desc = paste0(OR_df$id," ",desc)
  }else{
    desc = OR_df$id
  }
  data = data.frame(
    individual = OR_df$id,
    desc = desc,
    group = dict.combine$group[match(OR_df$id, dict.combine$Variable)],
    type = dict.combine$type[match(OR_df$id, dict.combine$Variable)],
    value = OR_df$OR,
    pval = OR_df$pval,
    source = OR_df$source_id
  )
  data$group[is.na(data$group)] = "others"
  
  data = data %>% arrange(type, group, value)
  data$value[data$value == 0] = NA
  
  data$value = data$value*100
  data$group = factor(data$group)
  
  circularData = circularPreData(data)
  data = circularData$data
  label_data = circularData$label_data
  label_data0 = label_data %>% group_by(individual) %>%
    summarise(id = mean(id), value = max(value), angle = max(angle),
              hjust = max(hjust))
  label_data1 = left_join(label_data, label_data0, by = "individual",
                          suffix = c(".old", ""))
  
  label_data1$value.old = label_data1$id.old = 
    label_data1$angle.old = label_data1$hjust.old = NULL
  label_data = label_data1
  label_data$angle[label_data$angle == 0] = 0.001
  grid_data = circularData$grid_data
  base_data = circularData$base_data
  data$col_bar = "not sig"
  data$col_bar[data$pval < thr_pval] = "sig" 
  data$value = sapply(data$value, function(i){min(i, 300)})
  
  print("+++++++++++++++++++++++++++++++++++++++++")
  readr::write_tsv(data, "circ_data.csv")
  readr::write_tsv(label_data, "circ_label_data.csv")
  readr::write_tsv(base_data, "circ_base_data.csv")
  print("+++++++++++++++++++++++++++++++++++++++++")
  
  if(length(node_now) > 1){
    # Make the plot
    p = ggplot(data, aes(x=id, y=value,alpha = 1-pval,
                   color=col_bar,fill = source)) +       # Note that id is a factor. If x is numeric, there is some space between the first bar
      geom_bar(stat="identity", size = 0.3,
               position = 'dodge') +
      # facet_grid(.~group, scales = 'free_x', space = 'free_x') +
      scale_color_manual(values = c("grey", "yellow"),
                        breaks = c("not sig", "sig")) +
      # Add a val=.8/.6/.4/.2 lines. I do it at the beginning to make sur barplots are OVER it.
      geom_abline(slope = 0, intercept = 50, col = "grey", size = 0.4, linetype = 2) +
      geom_abline(slope = 0, intercept = 100, col = "red", size = 0.6, linetype = 2) +
      geom_abline(slope = 0, intercept = 150, col = "grey", size = 0.4, linetype = 2) +
      geom_abline(slope = 0, intercept = 200, col = "grey", size = 0.4, linetype = 2) +
      # Add text showing the value of each .8/.6/.4/.2 lines
      annotate("text", x = rep(max(data$id),4),
               y = c(50, 100, 150, 200), label = c("0.5", "1", "1.5", "2") ,
               color=c("grey","black","grey","grey"), size=3 , angle=0, fontface="bold", hjust=1) +
      
      ylim(-50,max(na.omit(data$value))+50) +
      theme_minimal() +
      theme(
        legend.position="bottom",
        axis.text = element_blank(),
        axis.title = element_blank(),
        panel.grid = element_blank(),
        plot.margin = unit(rep(1,4), "cm")
      ) +
      coord_polar() +
      geom_text(data=label_data, aes(x=id, y=value+3, label=individual, hjust=hjust), 
                color="black", fontface="bold",alpha=0.6, size=2.5, angle= label_data$angle, inherit.aes = FALSE ) +
      #
      # Add base line information
      geom_segment(data=base_data, aes(x = start, y = -5, xend = end, yend = -5), 
                   colour = "black", alpha=0.8, size=0.6 , inherit.aes = FALSE ) + 
      geom_text(data=base_data, aes(x = title, y = -10, label=group), 
                colour = "black", alpha=0.8, size=2, fontface="bold", 
                inherit.aes = FALSE)
    
  }else{
    data = data[complete.cases(data), ]
    data$OR = data$value/100
    # data$sign[which(data$value < 1)] = "OR<1"
    data$value = data$value/100
    p = ggplot(data, aes(x=individual, y=value, fill = OR<1)) +       # Note that id is a factor. If x is numeric, there is some space between the first bar
      geom_bar(aes(x=individual, y=value, alpha = 1-pval,
                   fill = OR<1), stat="identity") +
      facet_wrap(.~group, scales = "free_x", nrow = 3) +
      # Add a val=.8/.6/.4/.2 lines. I do it at the beginning to make sur barplots are OVER it.
      geom_abline(slope = 0, intercept = 1, col = "black", size = 0.6, linetype = 1) +
      theme_minimal() +
      theme(
        axis.text = element_text(angle = 90, size = 6, hjust = 1),
        legend.position = "bottom",
        axis.title = element_blank(),
        panel.grid = element_blank(),
        plot.margin = unit(rep(1,4), "cm")
      ) 
    
  }
  p 
}


## pvalue ====
hcMulticomparison <- function(node_now, thr_pval=0.05, 
                           edge.full.list, pvalue.full.list, pvalue.bon.full.list,
                           dict.combine){
  if(length(node_now) == 0){return()}
  node_now_name = dict.combine$Description[match(node_now,dict.combine$uid)]
  node_now_group = dict.combine$group[match(node_now,dict.combine$uid)]
  node_now_group[is.na(node_now_group)] = "Others"
  node_now_type = dict.combine$type[match(node_now,dict.combine$uid)]
  
  OR_lst = sapply(node_now, function(i){
    b = data.frame(`id` = colnames(edge.full.list),
                   `OR` = edge.full.list[match(i, rownames(edge.full.list)), ],
                   `pval` = pvalue.full.list[match(i, rownames(pvalue.full.list)), ],
                   `pval.bon` = pvalue.bon.full.list[match(i, rownames(pvalue.full.list)), ])
    b$OR[b$OR>10] = 10
    b$OR[b$OR==0] = NA
    # b = b[b$pval < thr_pval & b$OR != 0, ]
    return(b)
  }, simplify = FALSE)
  
  id.keep = sapply(1:length(OR_lst), function(i){
    b =  OR_lst[[i]]
    sig = b$id[b$pval.bon < thr_pval]
    return(sig)
  })
  id.keep = unique(unlist(id.keep))
  
  OR_lst = sapply(1:length(OR_lst), function(i){
    b = OR_lst[[i]]
    b = b[b$id %in% id.keep, ]
    return(b)
  }, simplify = FALSE)
  
  for(i in 1:length(OR_lst)){
    a = OR_lst[[i]]
    if(unique(node_now_type)=="phecode"){
      a$source_id = paste0(node_now[i]," ",
                           dict.combine$Description[match(node_now[i], dict.combine$uid)])
      
    }else{
      a$source_id = node_now[i]
    }
    if(i == 1){
      OR_df = a
    }else{
      id_rep = intersect(OR_df$id, a$id)
      OR_df = rbind(OR_df[OR_df$id %in% id_rep, ], 
                    a[a$id %in% id_rep, ])
    }
  }
  
  if(unique(dict.combine$type[match(OR_df$id, dict.combine$Variable)]) == "phecode"){
    desc = str_remove(dict.combine$Description[match(OR_df$id, dict.combine$Variable)],
                      "^[A-Z]{3}:")
    # desc = paste0(OR_df$id," ",desc)
  }else{
    desc = OR_df$id
  }
  data = data.frame(
    individual = OR_df$id,
    desc = desc,
    group = dict.combine$group[match(OR_df$id, dict.combine$Variable)],
    type = dict.combine$type[match(OR_df$id, dict.combine$Variable)],
    value = OR_df$OR,
    pval = OR_df$pval,
    source = OR_df$source_id
  )
  data$group[is.na(data$group)] = "others"
  
  data = data %>% arrange(type, group, desc)
  data$value[data$value == 0] = NA
  
  
  data$OR = data$value
  data$P = -log10(data$pval)
  # data$individual = str_remove(data$individual, "^PheCode:")
  data$desc = dict.combine$Description[match(data$individual, dict.combine$Variable)]
  data$desc = str_remove(data$desc, "^[A-Za-z]+:")
  data_wide = pivot_wider(data, id_cols = c('individual', 'source', 'desc', 'group'),
                          values_from =  c('OR', 'P'),
                          names_from = 'source', names_sep = "_")
  
  ances_color = data.frame('ancestor' = c('ASN','AFR','EUR','HIS','PheWas'),
                           'color' = c('#6495ED', '#8B4513', '#FFDEAD',
                                       '#ADFF2F', '#9370DB'))
  # generate graph
  h = highchart() %>% 
    hc_xAxis(categories = data_wide$desc)
  target_source = unique(data$source)
  data_wide = as.data.frame(data_wide)
  for(i in 1:length(target_source)){
    # col.id = which(colnames(data_wide) == paste0("OR_", target_source[i]))
    p.id = which(colnames(data_wide) == paste0("P_", target_source[i]))
    # coll = ances_color$color[match(str_extract(target_source[i], '^[A-Za-z]+'),
    #                                ances_color$ancestor)]
    # coll = rep(coll, nrow(data_wide))
    # coll[data_wide[,p.id] < 0.05] = '#DC143C'
    h = h %>%  hc_add_series(name = target_source[i], type = "column",
                             data = signif(data_wide[,p.id], 3))
  }
  
  h = h %>%
    hc_chart(
      zoomType = "xy"
    ) %>%
    hc_title(text = "P-value",
             margin = 20, 
             align = "left",
             style = list(color = "steelblue")) %>% 
    hc_subtitle(text = "VA data",
                align = "left",
                style = list(color = "#2b908f", 
                             fontWeight = "bold")) %>% 
    hc_credits(enabled = TRUE, # add credits
               text = "Gapminder Data",
               href = "http://gapminder.com") %>% 
    hc_legend(align = "left", 
              verticalAlign = "top",
              layout = "vertical", 
              x = 0, 
              y = 100) %>%
    hc_tooltip(crosshairs = TRUE, 
               backgroundColor = "#FCFFC5",
               shared = TRUE, 
               borderWidth = 4) %>% 
    hc_yAxis(max = max(data$P)) %>%
    hc_exporting(enabled = TRUE)
  h
}



setTable <- function(node_now, thr_pval=0.05, 
                     edge.full.list, pvalue.full.list,pvalue.bon.full.list,
                     dict.combine){
  if(length(node_now) == 0){return()}
  node_now_name = dict.combine$Description[match(node_now,dict.combine$Variable)]
  node_now_group = dict.combine$group[match(node_now,dict.combine$Variable)]
  node_now_group[is.na(node_now_group)] = "Others"
  node_now_type = dict.combine$type[match(node_now,dict.combine$Variable)]
  
  OR_lst = sapply(node_now, function(i){
    b = data.frame(`id` = colnames(edge.full.list),
                   `OR` = edge.full.list[match(i, rownames(edge.full.list)), ],
                   `pval` = pvalue.full.list[match(i, rownames(pvalue.full.list)), ],
                   `pval.bon` = pvalue.bon.full.list[match(i, rownames(pvalue.full.list)), ])
    return(b)
  }, simplify = FALSE)
  
  id.keep = sapply(1:length(OR_lst), function(i){
    b =  OR_lst[[i]]
    sig = b$id[b$pval.bon < thr_pval]
    return(sig)
  })
  id.keep = unique(unlist(id.keep))
  
  OR_lst = sapply(1:length(OR_lst), function(i){
    b = OR_lst[[i]]
    b = b[b$id %in% id.keep, ]
    return(b)
  }, simplify = FALSE)
  
  
  for(i in 1:length(OR_lst)){
    a = OR_lst[[i]]
    a$pval.bon = NULL
    colnames(a)[2:3] = paste0(colnames(a)[2:3], "_", node_now[i])
    desc = str_remove(dict.combine$Description[match(a$id, dict.combine$Variable)],
                      "^[A-Z]{3}:")
    a$desc = desc
    a$group = dict.combine$group[match(a$id, dict.combine$Variable)]
    a$group[is.na(a$group)] = "others"
    if(i == 1){
      OR_df = a
      if(unique(dict.combine$type[match(OR_df$id, dict.combine$Variable)]) == "phecode"){
        OR_df = OR_df[,c(1,5,4,2,3)]
      }else{
        OR_df = OR_df[,c(1,4,2,3)]
      }
    }else{
      OR_df = full_join(OR_df, a)
    }
  }
 
  data = OR_df
  return(data)
}

