library(vegan)
library(ROBITools)
library(ProcMod)

litere_col_clean <- readRDS("litere_col_clean.rds")
litere_col_clean <- metabarcoding.data(reads = litere_col_clean$reads,
                                       motus = litere_col_clean$motus,
                                       samples = litere_col_clean$samp)

litere_bac_clean <- readRDS("litere_bac_clean.rds")
litere_bac_clean <- metabarcoding.data(reads = litere_bac_clean$reads,
                                       motus = litere_bac_clean$motus,
                                       samples = litere_bac_clean$samp)




litere_ins_clean <- readRDS("litere_ins_clean.rds")
litere_ins_clean <- metabarcoding.data(reads = litere_ins_clean$reads,
                                       motus = litere_ins_clean$motus,
                                       samples = litere_ins_clean$samp)

litere_euk_clean <- readRDS("litere_euk_clean.rds")
litere_euk_clean <- metabarcoding.data(reads = litere_euk_clean$reads,
                                       motus = litere_euk_clean$motus,
                                       samples = litere_euk_clean$samp)


# Remove rare motus

litere_col_norare <- litere_col_clean[,apply(decostand(litere_col_clean$reads,method = "total"),MARGIN = 2,max) >= 0.001]
litere_euk_norare <- litere_euk_clean[,apply(decostand(litere_euk_clean$reads,method = "total"),MARGIN = 2,max) >= 0.001]
litere_ins_norare <- litere_ins_clean[,apply(decostand(litere_ins_clean$reads,method = "total"),MARGIN = 2,max) >= 0.001]
litere_bac_norare <- litere_bac_clean[,apply(decostand(litere_bac_clean$reads,method = "total"),MARGIN = 2,max) >= 0.001]


litere_euk_classes <- lapply(levels(litere_euk_norare$motus$class_name),
                             function(x) litere_euk_norare[,which(litere_euk_norare$motus$class_name == x)])
names(litere_euk_classes)=levels(litere_euk_norare$motus$class_name)

litere_euk_classes <- litere_euk_classes[! sapply(litere_euk_classes, is.numeric)]
litere_euk_classes.diverse = litere_euk_classes[sapply(litere_euk_classes,ncol) >=30]

litere_euk_dist <- lapply(litere_euk_classes.diverse,
                          function(metabar)
                            vegdist(decostand(metabar@reads,"hellinger"),"euclidean"))

litere_euk_dist <- as.procmod.frame(litere_euk_dist)

litere_euk_cor <- corls(litere_euk_dist)
ilitere_euk_cor <- solve(litere_euk_cor)
litere_euk_cor.partial = ilitere_euk_cor/sqrt(diag(ilitere_euk_cor) %*% t(diag(ilitere_euk_cor)))

plot(hclust(as.dist(1- ilitere_euk_cor.partial^2)))
