##############################################################################
#============================================================================
#  Framework to find microbial signatures of Pulmonary Exacerbation in CF
#============================================================================
#
# R codes to find shifts in relative abundance of keystone taxa that
# correspond to changes in patient health.
#
# Manuscript: Microbiome Networks and Change-Point Analysis Reveal Key
# Community Changes Associated with Cystic Fibrosis Pulmonary Exacerbations
#
# Journal: npj Biofilms and Microbiomes
#
# Author: Mehdi Layeghifard et al.
#
# Date: November/2018
#
# Functions needed to run the main code.
# 
##### Disclaimer
# This code is supplied without any warranty or guaranteed support whatsoever. 
# Authors are not responsible for its use, misuse, or functionality.
#
#============================================================================
#    Contact: Mehdi Layeghifard (mehdi.layeghifard@utoronto.ca)
#============================================================================
##############################################################################


##########
## Function to find hubs
find_hubs <- function(net, hub_metric="pagerank") {
    if (hub_metric == "pagerank") {
        hubs <- names(head(sort(page_rank(net)$vector, decreasing=T), top))
    } else if (hub_metric == "hubscore") {
        hubs <- names(head(sort(hub_score(net)$vector, decreasing=T), top))
    }
    return(hubs)
}


##########
## Function to convert CP to segments
cpt_conv <- function(cpt, len) {
    vec <- as.vector(matrix(0, nrow=len))
    j <- 1
    for (i in 1:length(cpt@cpts)) {
        vec[j:cpt@cpts[i]] <- i
        j <- cpt@cpts[i] + 1
    }
    return(vec)
}


##########
## Function to compare CP vectors
cp_comp <- function(MB, cs_vec) {
    res <- array(0, dim=c(3, dim(MB)[1]))
    colnames(res) <- rownames(MB)
    for (i in 1:dim(MB)[1]) {
        cpt <- cpt.meanvar(MB[i,], method="PELT")
        
        cp_vec <- as.vector(matrix(0, nrow=dim(MBr)[2]))
        j <- 1
        for (i in 1:length(cpt@cpts)) {
            cp_vec[j:cpt@cpts[i]] <- i
            j <- cpt@cpts[i] + 1
        }
        
        ccf_status <- ccf(cp_vec, cs_vec, lag.max = 1, type="covariance", plot=F)
        res[, i] <- ccf_status$acf
    }
    return(res)
}


##########
## Function to run wilcox test
wilcoxtest <- function (x, top) {
    num_samples <- dim(x)[2] / 3
    step <- num_samples - 1
    y <- seq(1 , dim(x)[2] , dim(x)[2] / 3)
    wtmat <- array(0, dim=c(top, 3))
    for (i in 1:top) {
        wt1 <- wilcox.test(x[i,y[1]:(y[1]+step)],x[i,y[2]:(y[2]+step)])
        wt2 <- wilcox.test(x[i,y[1]:(y[1]+step)],x[i,y[3]:(y[3]+step)])
        wt3 <- wilcox.test(x[i,y[2]:(y[2]+step)],x[i,y[3]:(y[3]+step)])
        wtmat[i, 1] <- wt1$p.value
        wtmat[i, 2] <- wt2$p.value
        wtmat[i, 3] <- wt3$p.value
    }
    rownames(wtmat) <- paste0("Top.", c(1:top))
    colnames(wtmat) <- c("Abundane-Prevalence", "Abundance-Hub", "Prevalence-Hub")
    return(wtmat)
}
