## Author Qi Li (qli8@nd.edu)
## When use adaptive Lasso network inference method, please cite the follow paper.
## Krämer, N., Schäfer, J., & Boulesteix, A. L. (2009). Regularized estimation of large-scale gene association networks using graphical Gaussian models. BMC bioinformatics, 10(1), 384.

## R version >= 3.6.2

## adaptive lasso ###

## check if a package is installed or not ##
is.installed <- function(mypkg){
  is.element(mypkg, installed.packages()[,1])
} 

if (!is.installed("glmnet")){
  install.packages("glmnet")
}

if (!is.installed("parcor")){
  install.packages("parcor")
}

library(parcor)

## Process the network ##
data <- read.table("./examples/expression-data/Hu_data_renamed_nocontrol.txt", header = TRUE)
gene <- data[['newID']]

ncol <- dim(data)[2]
data <- data[,2:ncol]
data <- t(data)
data <- as.matrix(data)

Net <- adalasso.net(data)
NetMat <- Net$pcor.adalasso

### output as adjacency matrix ###

rownames(NetMat) <- colnames(NetMat) <- gene
list <- data.frame(matrix(ncol = 3, nrow = 0))
names(list)<-c("node1","node2", "weight")
for (i in 1:nrow(NetMat)){
  for (j in 1:ncol(NetMat)){
    if (NetMat[i, j] != 0){
      tmp<-data.frame(gene[i], gene[j], NetMat[i,j])
      names(tmp)<-c("node1","node2", "weight")
      list = rbind(list, tmp)
    }
  }
}

write.table(list, file = "./network-output/AdaLasso.txt", sep = " \t", quot= FALSE, row.names = FALSE, col.names = FALSE)
