content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
---|---|
##' @importFrom utils packageDescription
.onAttach <- function(libname, pkgname) {
pkgVersion <- packageDescription(pkgname, fields="Version")
msg <- paste0(pkgname, " v ", pkgVersion, " ",
"welcome to use ",pkgname, "!\n")
citation <- paste0("If you use ", pkgname, " in published research, please acknowledgements:\n",
"We thank Dr.Jianming Zeng(University of Macau), and all the members of his bioinformatics team, biotrainee, for generously sharing their experience and codes.")
packageStartupMessage(paste0(msg, citation))
}
| /scratch/gouwar.j/cran-all/cranData/AnnoProbe/R/zzz.R |
#' Breaks up genbank sequences into their annotated components based on a set of search terms and writes each subsequence of interest to a FASTA for each accession number supplied.
#' @param Accessions A vector of INSDC GenBank accession numbers. Note that refseq numbers are not supported at the moment (i.e. prefixes like XM_ and NC_) will not work.
#' @param Terms A data frame of search terms. Search terms for animal mitogenomes, nuclear rRNA, chloroplast genomes, and plant mitogenomes are pre-made and can be loaded using the data()function. Additional terms can be addded using the MergeSearchTerms function.
#' @param Duplicates A vector of loci names that have more than one copy. Default is NULL
#' @param DuplicateInstances A numeric vector the length of Duplicates of the number of duplicates for each duplicated gene you wish to extract.Default is NULL
#' @param TranslateSeqs Logical as to whether or not the sequence should be translated to the corresponding peptide sequence. Default is FALSE. Note that this only makes sense to list as TRUE for protein coding sequences.
#' @param TranslateCode Numerical representing the GenBank translation code for which sequences should be translated under. Default is 1. For all options see ?seqinr::getTrans. Some possible useful ones are: 2. Vertebrate Mitochondrial, 5. Invertebrate Mitochondrial, and 11. bacterial+plantplastid
#' @param DuplicateSpecies Logical. As to whether there are duplicate individuals per species. If TRUE, adds the accession number to the fasta file
#' @param Prefix Character If a prefix is specified, all output FASTA files written will begin with the prefix. Default is NULL.
#' @param TidyAccessions Logical as to whether the accession table should have a single row per species. If numerous accessions for a species occur, they will be seperated by a comma in the accession table. Default=TRUE.
#' @details The AnnotationBust function takes a vector of accession numbers and a data frame of search terms and extracts subsequences from genomes or concatenated sequences.
#' This function requires a steady internet connection. It writes files in the FASTA format to the working directory and returns an accession table. Files append, so use different prefixes between runs, otherwise they will be added to the current files in the working directory if the names are the same. AnnoitationBustR comes with pre-made
#' search terms for metazoan mitogenomes, plant mitogenomes, chloroplast genomes, and rDNA that can be loaded using data(mtDNAterms), data(mtDNAtermsPlants),data(cpDNAterms), and data(rDNAterms) respectively.
#' Search terms can be completely made by the user as long as they follow a similar format with three columns. The first, Locus, should contain the name of the locus that will also be used to name the files. We recommend following
#' a similar naming convention to what we currently have in the pre-made data frames to ensure that files are named properly, characters like "-" or ".", and names starting with numbers should be avoided as it can cause errors with R.
#' The second column, Type, contains the type of subsequence it is, with options being CDS, rRNA, tRNA, misc_RNA, Intro, Exon, and D_Loop. The last column, Name, consists of a possible
#' name for the locus of interest as it might appear in an annotation. For numerous synonyms for the same locus, one should have each synonym as its own row.An additional fourth column is needed for extracting introns/exons.
#' This column, called IntronExonNumber should contain the number of the intron to extract. If extracting both introns/exons and non-intron/exon sequences the fourth column should be NA for non-intron/exon sequence types. See the examples below and the vignette for detailed examples on extracting intron and exons.
#' It is possible that some subsequences are not fully annotated on ACNUC and, therefore, are not extractable. These will return in the accession table as "type not fully Ann". It is also possible that the sequence has no annotations at all, for which it will return "No Ann. For".
#' If the function returns "Acc. Not Found", the accession number supplied could not be found on NCBI. If "Not On ACNUC GenBank" is returned, the accession is not available through AcNUC.
#' This may be due to ACNUC not being fully up to date. To see the last time ACNUC was updated, run seqinr::choosebank("genbank", infobank=T).
#'
#' For a more detailed walkthrough on using AnnotationBust you can access the vignette with vignette("AnnotationBustR).
#' @return Writes a fasta file(s) to the current working directory selected for each unique subsequence of interest in Terms containing all the accession numbers the subsequence was found in.
#' @return An accesion table of class data.frame.
#' @references Borstein, Samuel R., and Brian C. O'Meara. "AnnotationBustR: An R package to extract subsequences from GenBank annotations." PeerJ Preprints 5 (2017): e2920v1.
#' @examples
#' \dontrun{
#' #Create vector of three NCBI accessions of rDNA toget subsequences of and load rDNA terms.
#' ncbi.accessions<-c("FJ706295","FJ706343","FJ706292")
#' data(rDNAterms)#load rDNA search terms from AnnotationBustR
#' #Run AnnotationBustR and write files to working directory
#' my.sequences<-AnnotationBust(ncbi.accessions, rDNAterms, DuplicateSpecies=TRUE,
#' Prefix="Example1")
#' my.sequences#Return the accession table for each species.
#'
#' ###Example With matK CDS and trnK Introns/Exons##
#' #Subset out matK from cpDNAterms
#' cds.terms<-subset(cpDNAterms,cpDNAterms$Locus=="matK")
#' #Create a vecotr of NA so we can merge with the search terms for introns and exons
#' cds.terms<-cbind(cds.terms,(rep(NA,length(cds.terms$Locus))))
#' colnames(cds.terms)[4]<-"IntronExonNumber"
#'
#' #Prepare a search term table for the intron and exons to remove
#' #We can start with the cpDNAterms for trnK
#' IntronExon.terms<-subset(cpDNAterms,cpDNAterms$Locus=="trnK")
#' #As we want to go for two exons, we will want the synonyms repeated as we are doing and intron
#' #and an exon
#' IntronExon.terms<-rbind(IntronExon.terms,IntronExon.terms)#duplicate the terms
#' #rep the sequence type we want to extract
#' IntronExon.terms$Type<-rep(c("Intron","Intron","Exon","Exon"))
#' IntronExon.terms$Locus<-rep(c("trnK_Intron","trnK_Exon2"),each=2)
#' IntronExon.terms<-cbind(IntronExon.terms,rep(c(1,1,2,2)))#Add intron/exon number info
#' #change column name for number info for IntronExon name
#' colnames(IntronExon.terms)[4]<-"IntronExonNumber"
#' #We can then merge everything together with MergeSearchTerms terms
#' IntronExonExampleTerms<-MergeSearchTerms(IntronExon.terms,cds.terms)
#'
#' #Run AnnotationBust
#' IntronExon.example<-AnnotationBust(Accessions=c("KX687911.1", "KX687910.1"),
#' Terms=IntronExonExampleTerms, Prefix="DemoIntronExon")
#' }
#' @export
AnnotationBust<-function(Accessions, Terms, Duplicates= NULL,DuplicateInstances=NULL, TranslateSeqs=FALSE, TranslateCode=1, DuplicateSpecies=FALSE, Prefix=NULL, TidyAccessions=TRUE){
#seqinr::choosebank("genbank")
uni.locus<-unique(Terms$Locus)
uni.type<-unique(Terms$Type)
##Deal with duplicates in regards to writing output files##
if(is.null(Duplicates)==FALSE){
new.file.names<-character(length = 0)
dup.frame<-data.frame(Duplicates, DuplicateInstances)
singles<-uni.locus[uni.locus %in% dup.frame$Duplicates==FALSE]#get matching duplicates
doubles<-uni.locus[uni.locus %in% dup.frame$Duplicates==TRUE]#get matching duplicates
for (i in 1:length (doubles)){
sub.dups<-subset(dup.frame, dup.frame$Duplicates %in% doubles[i]==TRUE)#subset the duplicate genes
number.names<-paste0(sub.dups$Duplicates, 1:sub.dups$DuplicateInstances)#add duplicate numbers to names
new.file.names<-append(new.file.names, number.names)#append the new pasted file names
}
file.names<-c(as.vector(singles), new.file.names)#combo the names of single and dup loci
}else {file.names<-as.vector(uni.locus)}
Accession.Table<-data.frame(data.frame(matrix(NA, nrow = length(Accessions), ncol = 1+length(file.names))))#make empty accession table
colnames(Accession.Table)<-c("Species",file.names)#attach loci names as colnames
#Setup Prefix
if(is.null(Prefix)){
File.Prefix<-NULL
}else{File.Prefix<-paste0(Prefix,"_")}
for (subsequence.type.index in 1:length(uni.type)){#for each sequence type, get the stuff subset. Don't do d-loop as it has a seperate pathway to being captured
if (uni.type[subsequence.type.index]=="CDS"){
CDS.Search<-subset(Terms, Terms$Type=="CDS")
unique.CDS<-unique(CDS.Search$Locus)
}
if (uni.type[subsequence.type.index]=="tRNA"){
tRNA.Search<-subset(Terms, Terms$Type=="tRNA")
unique.tRNA<-unique(tRNA.Search$Locus)
}
if (uni.type[subsequence.type.index]=="rRNA"){
rRNA.Search<-subset(Terms, Terms$Type=="rRNA")
unique.rRNA<-unique(rRNA.Search$Locus)
}
if (uni.type[subsequence.type.index]=="misc_RNA"){
misc_RNA.Search<-subset(Terms, Terms$Type=="misc_RNA")
unique.misc_RNA<-unique(misc_RNA.Search$Locus)
}
if (uni.type[subsequence.type.index]=="Intron"){
Intron.Search<-subset(Terms, Terms$Type=="Intron")
unique.Intron<-unique(Intron.Search$Locus)
}
if (uni.type[subsequence.type.index]=="Exon"){
Exon.Search<-subset(Terms, Terms$Type=="Exon")
unique.Exon<-unique(Exon.Search$Locus)
}
if (uni.type[subsequence.type.index]=="misc_feature"){
misc_feature.Search<-subset(Terms, Terms$Type=="misc_feature")
unique.misc_feature<-unique(misc_feature.Search$Locus)
}
}
for (accession.index in 1:length(Accessions)){
try.test<-try(seqinr::choosebank("genbank", verbose = FALSE),silent = TRUE)
while(class(try.test)== "try-error"){
Sys.sleep(10)
try.test<-try(seqinr::choosebank("genbank", verbose = FALSE),silent = TRUE)
}
new.access<-strsplit(Accessions[accession.index],"\\.",perl=TRUE)[[1]][1]#split and decimal spot in accession number. seqinr won't take them with it
species.name<-try(attr(ape::read.GenBank(Accessions[accession.index]),"species"))#get the sequence names
if(class(species.name)=="try-error"){
Accession.Table[accession.index,1:length(colnames(Accession.Table))]<-paste(new.access,"Acc. Not Found",sep=" ")
next
}else{
print(paste("Working On Accession",new.access,species.name, sep=" "))
ifelse(DuplicateSpecies==TRUE, seq.name<-paste(species.name,new.access,sep = "_"), seq.name<-species.name)
Accession.Table$Species[accession.index]<-species.name
full.rec<-try(seqinr::query(paste0("AC=",new.access)))
if(grepl("unknown accession", full.rec[[1]][1])==TRUE){
Accession.Table[accession.index,2:length(colnames(Accession.Table))]<-paste(new.access,"Not On ACNUC GenBank",sep=" ")
next
}else{
while(class(full.rec)== "try-error"){
Sys.sleep(10)
try.test<-try(seqinr::choosebank("genbank", verbose = FALSE),silent = TRUE)
full.rec<-try(seqinr::query(paste0("AC=",new.access)))
}
}
full.annot<-seqinr::getAnnot(full.rec$req, nbl=20000)#read in the annotation
start.loci<-grep("FEATURES", full.annot[[1]])#find start of features
new.ann<-full.annot[[1]][-c(1:start.loci,length(full.annot[[1]]))]#cut just to the feature
new.ann<-gsub("D-loop","Dloop",new.ann)#kill wild character "-"
#Start parsing into a list to speed up. Only have to ping ACNUC one time this way
annotation.list <- list()
to.store <- c()
for (i in sequence(length(new.ann))) {
if(grepl(" [a-zA-Z_]\\w*. ", new.ann[i]) & i!=1) {
annotation.list[[length(annotation.list)+1]] <- to.store
to.store <- new.ann[i]
} else {
to.store <- append(to.store, new.ann[i])
}
}
annotation.list[[length(annotation.list)+1]] <- to.store
#check that annotation is multiple parts
check.ann<-annotation.list[-1]
if(length(check.ann)==1){
Accession.Table[accession.index,2:length(colnames(Accession.Table))]<-paste("No Ann. For",new.access,sep=" ")
next
}
#Now find loci for every loci type
for (loci.type.index in 1:length(uni.type)){
if (uni.type[loci.type.index]=="tRNA") {
rec<-seqinr::query(paste("SUB", paste0("AC=",new.access), "AND T=tRNA", sep=" "))#get the tRNA
current.annot<-annotation.list[grep("tRNA ",annotation.list)]#subset in the parsed annotation
if (!length(current.annot)==length(rec$req)){
bad.cols<-which(colnames(Accession.Table) %in% unique.tRNA)
Accession.Table[accession.index,bad.cols]<-paste("type not fully Ann.",new.access,sep=" ")
next
}
for (tRNA.term.index in 1:length(unique.tRNA)){
current.locus<-subset(tRNA.Search, tRNA.Search$Locus==unique.tRNA[tRNA.term.index])#subset the tRNA terms by the current locus
synonyms<-unique(current.locus$Name)#subset the Name column, which includes the synonyms
if (unique.tRNA[tRNA.term.index] %in% Duplicates ==TRUE){#if the locus is a duplicate
current.dup<-subset(dup.frame, dup.frame$Duplicates==as.character(unique.tRNA[tRNA.term.index]))
for (synonym.index in 1:length(synonyms)){
found.tRNA<-grep(paste0("\\b",synonyms[synonym.index],"\\b"), current.annot)
if (length(found.tRNA)>0){
max.instance<-min(c(length(found.tRNA),current.dup$DuplicateInstances))#to control number found and written, get lowest common number
for (dup.found.index in 1:max.instance){
found.seq<-seqinr::getSequence(rec$req[[found.tRNA[dup.found.index]]])#
seqinr::write.fasta(toupper(found.seq),names=seq.name, paste0(File.Prefix,unique.tRNA[tRNA.term.index],dup.found.index,".fasta"),open="a", nbchar = 60)
Accession.Table[accession.index,grep(paste0("\\b",unique.tRNA[tRNA.term.index],dup.found.index,"\\b"), colnames(Accession.Table))]<-new.access
}
break
}
}
}
else{for (synonym.index in 1:length(synonyms)){
found.tRNA<-grep(paste0("\\b",synonyms[synonym.index],"\\b"), current.annot)#search for the regular
if (length(found.tRNA)>0){
found.seq<-seqinr::getSequence(rec$req[found.tRNA[1]], as.string=FALSE)
seqinr::write.fasta(toupper(found.seq[[1]]),names=seq.name, paste0(File.Prefix,unique.tRNA[tRNA.term.index],".fasta"),open="a",nbchar = 60)
Accession.Table[accession.index,grep(paste0("\\b",unique.tRNA[tRNA.term.index],"\\b"), colnames(Accession.Table))]<-new.access
break}}
}
}
}
if (uni.type[loci.type.index]=="CDS") {
rec<-seqinr::query(paste("SUB", paste0("AC=",new.access), "AND T=CDS", sep=" "))#get the CDS
current.annot<-annotation.list[grep("CDS ",annotation.list)]#subset in the parsed annotation
if (!length(current.annot)==length(rec$req)){
bad.cols<-which(colnames(Accession.Table) %in% unique.CDS)
Accession.Table[accession.index,bad.cols]<-paste("type not fully Ann.",new.access,sep=" ")
next
}
for (CDS.term.index in 1:length(unique.CDS)){
current.locus<-subset(CDS.Search, CDS.Search$Locus==unique.CDS[CDS.term.index])#subset the CDS terms by the current locus
synonyms<-unique(current.locus$Name)#subset the Name column, which includes the synonyms
if (unique.CDS[CDS.term.index] %in% Duplicates ==TRUE){#if the locus is a duplicate
current.dup<-subset(dup.frame, dup.frame$Duplicates==as.character(unique.CDS[CDS.term.index]))
for (synonym.index in 1:length(synonyms)){
found.CDS<-grep(paste0("\\b",synonyms[synonym.index],"\\b"), current.annot)
if (length(found.CDS)>0){
max.instance<-min(c(length(found.CDS),current.dup$DuplicateInstances))#to control number found and written, get lowest common number
for (dup.found.index in 1:max.instance){
if (TranslateSeqs==TRUE){
found.seq<-seqinr::c2s(seqinr::getTrans(rec$req[[found.CDS[dup.found.index]]], numcode=TranslateCode))####Trans work?
}
else{found.seq<-seqinr::getSequence(rec$req[found.CDS[dup.found.index]], as.string=FALSE)}
seqinr::write.fasta(toupper(found.seq[[1]]),names=seq.name, paste0(File.Prefix,unique.CDS[CDS.term.index],dup.found.index,".fasta"),open="a",nbchar = 60)
Accession.Table[accession.index,grep(paste0("\\b",unique.CDS[CDS.term.index],dup.found.index,"\\b"), colnames(Accession.Table))]<-new.access
}
break
}
}
}
else{for (synonym.index in 1:length(synonyms)){
found.CDS<-grep(paste0("\\b",synonyms[synonym.index],"\\b"), current.annot)#search for the regular
if (length(found.CDS)>0){
ifelse(TranslateSeqs==TRUE, found.seq<-seqinr::c2s(seqinr::getTrans(rec$req[[found.CDS]],numcode=TranslateCode)),found.seq<-seqinr::getSequence(rec$req[found.CDS[1]], as.string=FALSE))
seqinr::write.fasta(toupper(found.seq[[1]]),names=seq.name, paste0(File.Prefix,unique.CDS[CDS.term.index],".fasta"),open="a",nbchar = 60)
Accession.Table[accession.index,grep(paste0("\\b",unique.CDS[CDS.term.index],"\\b"), colnames(Accession.Table))]<-new.access
break}}
}
}
}
if (uni.type[loci.type.index]=="rRNA") {
rec<-seqinr::query(paste("SUB", paste0("AC=",new.access), "AND T=rRNA", sep=" "))#get the rRNA
current.annot<-annotation.list[grep("rRNA ",annotation.list)]#subset in the parsed annotation
if (!length(current.annot)==length(rec$req)){
bad.cols<-which(colnames(Accession.Table) %in% unique.rRNA)
Accession.Table[accession.index,bad.cols]<-paste("type not fully Ann.",new.access,sep=" ")
next
}
for (rRNA.term.index in 1:length(unique.rRNA)){
current.locus<-subset(rRNA.Search, rRNA.Search$Locus==unique.rRNA[rRNA.term.index])#subset the rRNA terms by the current locus
synonyms<-unique(current.locus$Name)#subset the Name column, which includes the synonyms
if (unique.rRNA[rRNA.term.index] %in% Duplicates ==TRUE){#if the locus is a duplicate
current.dup<-subset(dup.frame, dup.frame$Duplicates==as.character(unique.rRNA[rRNA.term.index]))
for (synonym.index in 1:length(synonyms)){
found.rRNA<-grep(paste0("\\b",synonyms[synonym.index],"\\b"), current.annot)
if (length(found.rRNA)>0){
max.instance<-min(c(length(found.rRNA),current.dup$DuplicateInstances))#to control number found and written, get lowest common number
for (dup.found.index in 1:max.instance){
found.seq<-seqinr::getSequence(rec$req[[found.rRNA[dup.found.index]]])####Trans work?
seqinr::write.fasta(toupper(found.seq[[1]]),names=seq.name, paste0(File.Prefix,unique.rRNA[rRNA.term.index],dup.found.index,".fasta"),open="a",nbchar = 60)
Accession.Table[accession.index,grep(paste0("\\b",unique.rRNA[rRNA.term.index],dup.found.index,"\\b"), colnames(Accession.Table))]<-new.access
}
break
}
}
}
else{for (synonym.index in 1:length(synonyms)){
found.rRNA<-grep(paste0("\\b",synonyms[synonym.index],"\\b"), current.annot)#search for the regular
if (length(found.rRNA)>0){
found.seq<-seqinr::getSequence(rec$req[found.rRNA[1]], as.string=FALSE)
seqinr::write.fasta(toupper(found.seq[[1]]),names=seq.name, paste0(File.Prefix,unique.rRNA[rRNA.term.index],".fasta"),open="a",nbchar = 60)
Accession.Table[accession.index,grep(paste0("\\b",unique.rRNA[rRNA.term.index],"\\b"), colnames(Accession.Table))]<-new.access
break}}
}
}
}
if (uni.type[loci.type.index]=="misc_RNA") {
rec<-seqinr::query(paste("SUB", paste0("AC=",new.access), "AND T=misc_RNA", sep=" "))#get the misc_RNA
current.annot<-annotation.list[grep("misc_RNA ",annotation.list)]#subset in the parsed annotation
if (!length(current.annot)==length(rec$req)){
bad.cols<-which(colnames(Accession.Table) %in% unique.misc_RNA)
Accession.Table[accession.index,bad.cols]<-paste("type not fully Ann.",new.access,sep=" ")
next
}
for (misc_RNA.term.index in 1:length(unique.misc_RNA)){
current.locus<-subset(misc_RNA.Search, misc_RNA.Search$Locus==unique.misc_RNA[misc_RNA.term.index])#subset the misc_RNA terms by the current locus
synonyms<-unique(current.locus$Name)#subset the Name column, which includes the synonyms
if (unique.misc_RNA[misc_RNA.term.index] %in% Duplicates ==TRUE){#if the locus is a duplicate
current.dup<-subset(dup.frame, dup.frame$Duplicates==as.character(unique.misc_RNA[misc_RNA.term.index]))
for (synonym.index in 1:length(synonyms)){
found.misc_RNA<-grep(paste0("\\b",synonyms[synonym.index],"\\b"), current.annot)
if (length(found.misc_RNA)>0){
max.instance<-min(c(length(found.misc_RNA),current.dup$DuplicateInstances))#to control number found and written, get lowest common number
for (dup.found.index in 1:max.instance){
found.seq<-seqinr::getSequence(rec$req[[found.misc_RNA[dup.found.index]]])####Trans work?
seqinr::write.fasta(toupper(found.seq[[1]]),names=seq.name, paste0(File.Prefix,unique.misc_RNA[misc_RNA.term.index],dup.found.index,".fasta"),open="a",nbchar = 60)
Accession.Table[accession.index,grep(paste0("\\b",unique.misc_RNA[misc_RNA.term.index],dup.found.index,"\\b"), colnames(Accession.Table))]<-new.access
}
break
}
}
}
else{for (synonym.index in 1:length(synonyms)){
found.misc_RNA<-grep(paste0("\\b",synonyms[synonym.index],"\\b"), current.annot)#search for the regular
if (length(found.misc_RNA)>0){
found.seq<-(seqinr::getSequence(rec$req[found.misc_RNA[1]], as.string=FALSE))
seqinr::write.fasta(toupper(found.seq[[1]]),names=seq.name, paste0(File.Prefix,unique.misc_RNA[misc_RNA.term.index],".fasta"),open="a", nbchar = 60)
Accession.Table[accession.index,grep(paste0("\\b",unique.misc_RNA[misc_RNA.term.index],"\\b"), colnames(Accession.Table))]<-new.access
break}}
}
}
}
if (uni.type[loci.type.index]=="Intron") {
current.annot<-annotation.list[grep("intron ",annotation.list)]#subset in the parsed annotation
intron.find <- seqinr::query("intron.find",paste0("AC=",new.access), virtual = TRUE)
check.intron <- seqinr::extractseqs("intron.find", operation = "feature", feature = "intron")
if (length(check.intron)>0){
intron.fasta <- seqinr::read.fasta(textConnection(check.intron),as.string = FALSE,forceDNAtolower = FALSE)
if (!length(current.annot)==length(intron.fasta)){
bad.cols<-which(colnames(Accession.Table) %in% unique.Intron)
Accession.Table[accession.index,bad.cols]<-paste("type not fully Ann.",new.access,sep=" ")
next
}
for (Intron.term.index in 1:length(unique.Intron)){
current.locus<-subset(Intron.Search, Intron.Search$Locus==unique.Intron[Intron.term.index])#subset the Intron terms by the current locus
synonyms<-unique(current.locus$Name)#subset the Name column, which includes the synonyms
IntronNumber<-unique(current.locus$IntronExonNumber)
for (synonym.index in 1:length(synonyms)){
found.Intron<-grep(paste0("\\b",synonyms[synonym.index],"\\b"), current.annot)#Find introns for gene name
foundNumber<-grep(paste0("\\b", IntronNumber[synonym.index],"\\b"),current.annot[found.Intron])#find intron number that is to be extracted
ifelse(length(foundNumber)==0|length(found.Intron)==1,foundNumber<-found.Intron,foundNumber<-foundNumber)
if (length(foundNumber)>0){
seqinr::write.fasta(intron.fasta[foundNumber],names=seq.name, paste0(File.Prefix,unique.Intron[Intron.term.index],".fasta"),open="a",nbchar = 60)
Accession.Table[accession.index,grep(paste0("\\b",unique.Intron[Intron.term.index],"\\b"), colnames(Accession.Table))]<-new.access
break}
}
}
}
}
if (uni.type[loci.type.index]=="Exon") {
current.annot<-annotation.list[grep("exon ",annotation.list)]#subset in the parsed annotation
Exon.find <- seqinr::query("Exon.find",paste0("AC=",new.access), virtual = TRUE)
check.Exon <- seqinr::extractseqs("Exon.find", operation = "feature", feature = "Exon")
if (length(check.Exon)>0){
Exon.fasta <- seqinr::read.fasta(textConnection(check.Exon),as.string = FALSE,forceDNAtolower = FALSE)
if (!length(current.annot)==length(Exon.fasta)){
bad.cols<-which(colnames(Accession.Table) %in% unique.Exon)
Accession.Table[accession.index,bad.cols]<-paste("type not fully Ann.",new.access,sep=" ")
next
}
for (Exon.term.index in 1:length(unique.Exon)){
current.locus<-subset(Exon.Search, Exon.Search$Locus==unique.Exon[Exon.term.index])#subset the Exon terms by the current locus
synonyms<-unique(current.locus$Name)#subset the Name column, which includes the synonyms
ExonNumber<-unique(current.locus$IntronExonNumber)
for (synonym.index in 1:length(synonyms)){
found.Exon<-grep(paste0("\\b",synonyms[synonym.index],"\\b"), current.annot)#Find Exons for gene name
foundNumber<-grep(paste0("\\b", ExonNumber[synonym.index],"\\b"),current.annot[found.Exon])#find Exon number that is to be extracted
ifelse(length(foundNumber)==0|length(found.Exon)==1,foundNumber<-found.Exon,foundNumber<-foundNumber)
if (length(foundNumber)>0){
seqinr::write.fasta(Exon.fasta[foundNumber],names=seq.name, paste0(File.Prefix,unique.Exon[Exon.term.index],".fasta"),open="a",nbchar = 60)
Accession.Table[accession.index,grep(paste0("\\b",unique.Exon[Exon.term.index],"\\b"), colnames(Accession.Table))]<-new.access
break}
}
}
}
}
if (uni.type[loci.type.index]=="misc_feature") {
current.annot<-annotation.list[grep("misc_feature ",annotation.list)]#subset in the parsed annotation
misc_feature.find <- seqinr::query("misc_feature.find",paste0("AC=",new.access), virtual = TRUE)
check.misc_feature <- seqinr::extractseqs("misc_feature.find", operation = "feature", feature = "misc_feature")
if (length(check.misc_feature)>0){
misc_feature.fasta <- seqinr::read.fasta(textConnection(check.misc_feature),as.string = FALSE,forceDNAtolower = FALSE)
if (!length(current.annot)==length(misc_feature.fasta)){
bad.cols<-which(colnames(Accession.Table) %in% unique.misc_feature)
Accession.Table[accession.index,bad.cols]<-paste("type not fully Ann.",new.access,sep=" ")
next
}
for (misc_feature.term.index in 1:length(unique.misc_feature)){
current.locus<-subset(misc_feature.Search, misc_feature.Search$Locus==unique.misc_feature[misc_feature.term.index])#subset the misc_feature terms by the current locus
synonyms<-unique(current.locus$Name)#subset the Name column, which includes the synonyms
for (synonym.index in 1:length(synonyms)){
found.misc_feature<-grep(paste0("\\b",synonyms[synonym.index],"\\b"), current.annot)#Find Exons for gene name
if (length(found.misc_feature)>0){
seqinr::write.fasta(misc_feature.fasta[found.misc_feature],names=seq.name, paste0(File.Prefix,unique.misc_feature[misc_feature.term.index],".fasta"),open="a",nbchar = 60)
Accession.Table[accession.index,grep(paste0("\\b",unique.misc_feature[misc_feature.term.index],"\\b"), colnames(Accession.Table))]<-new.access
break}
}
}
}
}
if (uni.type[loci.type.index]=="D-loop") {
mito.loop <- seqinr::query("mito.loop",paste0("AC=",new.access), virtual = TRUE)
dloop <- seqinr::extractseqs("mito.loop", operation = "feature", feature = "D-loop")
if (length(dloop)>0){
dloop.fasta <- seqinr::read.fasta(textConnection(dloop),as.string = FALSE,forceDNAtolower = FALSE)
seqinr::write.fasta(dloop.fasta,file=paste0(File.Prefix,"D_loop.fasta"),names=seq.name, open="a")
Accession.Table[accession.index,grep(paste0("\\b","D_loop","\\b"), colnames(Accession.Table))]<-new.access
}
}
}
seqinr::closebank()
}
}
#Make Final Accession Table
if(TidyAccessions==TRUE){
UniqueSpecies<-unique(Accession.Table$Species)
Final.Accession.Table<-data.frame(data.frame(matrix(NA, nrow = length(UniqueSpecies), ncol = 1+length(file.names))))#make empty accession table
colnames(Final.Accession.Table)<-c("Species",file.names)#attach loci names as colnames
for (species.index in 1:length(UniqueSpecies)){
current.spec<-subset(Accession.Table,Accession.Table$Species==UniqueSpecies[species.index])
Final.Accession.Table[species.index,1]<-UniqueSpecies[species.index]
for (gene.index in 2:length(Accession.Table)){
current.loci<-current.spec[,gene.index]#The current column/loci
found.accessions<-subset(current.loci,!is.na(current.loci))#subset the ones that are present
numbers<-ifelse(length(found.accessions)==0, NA, paste(found.accessions, sep=",", collapse=","))#ifelse statemen, if not present, fill with NA
Final.Accession.Table[species.index,gene.index]<-numbers
Sort.Final.Accession.Table<-Final.Accession.Table[order(Final.Accession.Table$Species),]
}
rownames(Sort.Final.Accession.Table)<-1:nrow(Sort.Final.Accession.Table)
}
}else{
Final.Accession.Table<-Accession.Table
Sort.Final.Accession.Table<-Final.Accession.Table[order(Final.Accession.Table$Species),]
rownames(Sort.Final.Accession.Table)<-1:nrow(Sort.Final.Accession.Table)
}
Sort.Final.Accession.Table
}
seqinr_getSequence_loop <- function(x) {
seq_return <- NA
reps <- 0
while(is.na(seq_return[1])) {
reps <- reps + 1
try(seq_return <- seqinr::getSequence(x))
if(is.na(seq_return[1])) {
warning(paste0("Connection to the database failed; trying again in ", 10*reps, " seconds"), immediate.=TRUE)
Sys.sleep(10*reps)
}
}
return(seq_return)
}
| /scratch/gouwar.j/cran-all/cranData/AnnotationBustR/R/AnnotationBust.R |
#' Mitochondrial DNA Search Terms for Animals
#'
#' A data frame containing search terms for animal mitochondrial loci. Can be subset for loci of
#' interest. Columns are as follows and users should follow the column format if they wish to
#' add search terms using the MergeSearchTerms function:
#'
#' @format A data frame of of 253 rows and 3 columns
#' \itemize{
#' \item Locus: Locus name, FASTA files will be written with this name
#' \item Type: Type of subsequence, either CDS,tRNA,rRNA,misc_RNA, or D-loop
#' \item Name:Name of synonym for a locus to search for
#' }
#'
#' @seealso \code{\link{MergeSearchTerms}}
"mtDNAterms"
#' Mitochondrial DNA Search Terms for Plants
#'
#' A data frame containing search terms for plant mitochondrial loci. Can be subset for loci of
#' interest. Columns are as follows and users should follow the column format if they wish to
#' add search terms using the MergeSearchTerms function:
#'
#' @format A data frame of of 248 rows and 3 columns
#' \itemize{
#' \item Locus: Locus name, FASTA files will be written with this name
#' \item Type: Type of subsequence, either CDS,tRNA,rRNA,misc_RNA, or D-loop
#' \item Name:Name of synonym for a locus to search for
#' }
#'
#' @seealso \code{\link{MergeSearchTerms}}
"mtDNAtermsPlants"
#' Chloroplast DNA (cpDNA) Search Terms
#'
#' A data frame containing search terms for Chloroplast loci. Can be subset for loci of
#' interest. Columns are as follows and users should follow the column format if they wish to
#' add search terms using the MergeSearchTerms function:
#'
#' @format A data frame of of 364 rows and 3 columns
#' \itemize{
#' \item Locus: Locus name, FASTA files will be written with this name
#' \item Type: Type of subsequence, either CDS,tRNA,rRNA, or misc_RNA
#' \item Name:Name of synonym for a locus to search for
#' }
#'
#' @seealso \code{\link{MergeSearchTerms}}
"cpDNAterms"
#' Ribosomal DNA (rDNA) Search Terms
#'
#' A data frame containing search terms for ribosomal RNA loci. Can be subset for loci of
#' interest. Columns are as follows and users should follow the column format if they wish to
#' add search terms using the MergeSearchTerms function:
#'
#' @format A data frame of of 7 rows and 3 columns
#' \itemize{
#' \item Locus: Locus name, FASTA files will be written with this name
#' \item Type: Type of subsequence, either rRNA or misc_RNA
#' \item Name:Name of synonym for a locus to search for
#' }
#'
#' @seealso \code{\link{MergeSearchTerms}}
"rDNAterms" | /scratch/gouwar.j/cran-all/cranData/AnnotationBustR/R/DataDoc.R |
#' Find the longest sequence for each species from a list of GenBank accession numbers.
#' @param Accessions A vector of GenBank accession numbers.
#' @details For a set of GenBank accession numbers, this will return the longest sequence for in the set for species.
#' @return A list of genbank accessions numbers for the longest sequence for each taxon in a list of accession numbers.
#' @examples
#' #a vector of 4 genbank accessions, there are two for each species.
#' genbank.accessions<-c("KP978059.1","KP978060.1","JX516105.1","JX516111.1")
#' \dontrun{
#' #returns the longest sequence respectively for the two species.
#' long.seq.result<-FindLongestSeq(genbank.accessions)
#' }
#' @export
FindLongestSeq<-function(Accessions){
Accessions<-sapply(strsplit(as.character(Accessions),"\\.",perl = TRUE), `[`, 1)
raw.accessions<-ape::read.GenBank(Accessions)#get the seqs
seq.ids<-attr(raw.accessions, "species")#extract attribute-species name, from genbank takedown above
seq.data<-data.frame(cbind(attr(raw.accessions, "species"), names(raw.accessions),as.vector(summary(raw.accessions)[,1])),stringsAsFactors = FALSE)#data frame it
colnames(seq.data)<-c("Species","Accession","Length")#attribute column names
seq.data$Length<-as.numeric(seq.data$Length)#make the length of the sequence numeric
uni.taxa<-unique(seq.data$Species)#get unique taxa
long.seqs<-data.frame(matrix(nrow=length(uni.taxa), ncol=dim(seq.data)[2]))#empty data frame to store results
colnames(long.seqs)<-colnames(seq.data)
for (taxa.index in 1:length(uni.taxa)){
current.tax<-subset(seq.data,seq.data$Species==uni.taxa[taxa.index])
longest.seq<-subset(current.tax,current.tax$Length==sort(as.numeric(current.tax$Length),decreasing = TRUE)[1])[1,]#id and grab longest seq
long.seqs[taxa.index, ]<-longest.seq#append data frame with longest seq
}
long.seqs#return longest seqs
}
| /scratch/gouwar.j/cran-all/cranData/AnnotationBustR/R/FindLongestSeq.R |
#' Merging of two tables containing search terms to expand search term database for the AnnotationBust function.
#' @param ... the data frames of search terms you want to combine into a single data frame The Data frame(s) should have stringsAsFactors=FALSE listed if you want to sort them.
#' @param SortGenes Should the final data frame be sorted by gene name? Default is FALSE.
#' @return A new merged data frame with all the search terms combined from the lists supplied. If sort.gene=TRUE, genes will be sorted by name.
#' @description
#' This function merges two data frames with search terms. This allows users to easily add search terms to data frames (either their
#' own or ones included in this package using data() as GenBank annotations for the same genes may vary in gene name.
#' @examples
#' #load the list of search terms for mitochondrial genes
#' data(mtDNAterms)
#'
#' #Make a data.frame of new terms to add.
#' #This is a dummy example for a non-real annoation of COI, but lets pretend it is real.
#' add.name<-data.frame("COI","CDS", "CX1")
#'
#' # make the column names the same for combination.
#' colnames(add.name)<-colnames(mtDNAterms)
#'
#' #Run the merge search term function without sorting based on gene name.
#' new.terms<-MergeSearchTerms(add.name, mtDNAterms, SortGenes=FALSE)
#'
#' #Run the merge search term function with sorting based on gene name.
#' new.terms<-MergeSearchTerms(add.name, mtDNAterms, SortGenes=TRUE)
#'
#' #Merge search terms and create an additional column for introns and/or exons to
#' #In this example, add the trnK intron to the terms
#' #create empty IntornExonNumber column for non-intron/exons
#' cp.terms<-cbind(cpDNAterms,rep(NA,length(cpDNAterms$Name)))
#' colnames(cp.terms)[4]<-"IntronExonNumber"#Name the column IntronExonNumber
#' trnK.intron.terms<-subset(cpDNAterms,cpDNAterms$Locus=="trnK")#subset trnK
#' #Create a vector of 1's the same length as the number of rows for trnK
#' trnK.terms<-cbind(trnK.intron.terms,rep(1,length(trnK.intron.terms$Name)))
#' colnames(trnK.terms)[4]<-"IntronExonNumber"#Name the column IntronExonNumber
#' #Use MergeSearchTerms to merge the modified cpDNAterms and new intron terms
#' all.terms<-MergeSearchTerms(cp.terms,trnK.terms)
#' @export
MergeSearchTerms<-function(..., SortGenes=FALSE){
dots <- list(...)
check.names<-c("Locus","Type","Name","IntronExonNumber")
if(length(unique(sapply(lapply(dots, dim), "[", 2)))>1){
stop(paste("The input data frames are of different dimensions"))
}
for (i in sequence(length(dots))) {
working <- TRUE
if(class(dots[[i]])!="data.frame") {
stop(paste("The input object is the wrong format", sep=""))
#working <- FALSE
}
if(dim(dots[[i]])[2]!=3&&dim(dots[[i]])[2]!=4) {
stop(paste("The input object is the wrong dimensions", sep=""))
#working <- FALSE
}
if(length(grep(TRUE,colnames(dots[[i]])!=check.names[1:unique(sapply(lapply(dots, dim), "[", 2))])>0)) {
stop(paste("The columns for table",i, "do not have the proper names ('Locus','Type','Name' and if extracting introns/exons, the additional column 'IntronExonNumber')", sep=" "))
#working <- FALSE
}
}
new.terms <- rbind(...)
if(SortGenes==TRUE) {
new.terms <- new.terms[order(new.terms$Locus),]
}
row.names(new.terms)<-1:dim(new.terms)[[1]]
return(new.terms)
}
| /scratch/gouwar.j/cran-all/cranData/AnnotationBustR/R/MergeSearchTerms.R |
#' An R package to extract sub-sequences from GenBank annotations under different synonyms
#'
#' @description An R package to extract sub-sequences from GenBank annotations under different synonyms.
#'
#' @details
#' Package: AnnotationBustR
#'
#' Type: Package
#'
#' Title: An R package to extract sub-sequences from GenBank annotations under different synonyms
#'
#' Version: 1.1
#'
#' Date: 2017-8-15
#'
#' License: GPL (>= 2)
#'
#' This package allows users to quickly extract sub-sequences from GenBank accession numbers that may be annotated
#' under different synonyms. It writes these sub-sequences to FASTA files and creates a corresponding accession
#' table. The package comes with pre-made search terms with synonyms. A vignette going over the basic functions and
#' how to use them can be accessed with vignette("AnnotationBustR-vignette").
#'
#' @author Samuel Borstein, Brian O'Meara.
#' Maintainer: Samuel Borstein <[email protected]>
#'
#' @seealso \code{\link{AnnotationBust}},\code{\link{cpDNAterms}},\code{\link{FindLongestSeq}},\code{\link{MergeSearchTerms}},\code{\link{mtDNAterms}},\code{\link{rDNAterms}}
#'
#' @docType package
#' @name AnnotationBustR
#"_PACKAGE"
#> [1] "_PACKAGE"
NULL | /scratch/gouwar.j/cran-all/cranData/AnnotationBustR/R/pkgname.R |
## ---- out.width = "100%", echo=FALSE,fig.align='left',fig.cap= "Fig. 1: AnnotationBustR Workflow. Steps in orange occur outside the package while steps in blue are core parts of AnnotationBustR and steps in green represent optional steps"----
knitr::include_graphics("workflow.jpg")
## ---- out.width = "100%", echo=FALSE, fig.align='left',fig.cap= "Fig. 2: GenBank features annotation for accession G295784.1 that contains ATP8 and ATP6. The words highlighted in yellow would fall under the column of Type. Here they are both CDS. The type of sequence is always listed farthest to the left in the features table. Colors in blue indicate terms that would be placed in the Name column, here indicating that the two CDS in this example are ATP8, labeled as ATPase8 and ATP6 respectively."----
knitr::include_graphics("featuresMarked.jpg")
## ---- echo=FALSE--------------------------------------------------------------
ex.frame<-rbind(c("ATP8","CDS","ATPase8"),c("ATP6","CDS","ATPase6"))
colnames(ex.frame)<-c("Locus","Type","Name")
ex.frame<-as.data.frame(ex.frame)
print(ex.frame)
| /scratch/gouwar.j/cran-all/cranData/AnnotationBustR/inst/doc/AnnotationBustR-vignette.R |
---
title: "AnnotationBustR Tutorial"
author: "Samuel R. Borstein"
date: "`r format(Sys.time(), '%d %B, %Y')`"
output:
html_document:
keep_md: true
vignette: >
%\VignetteIndexEntry{AnnotationBustR Tutorial}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
# 1: Introduction
This is a tutorial for using the R package AnnotationBustR. AnnotationBustR reads in sequences from GenBank and allows you to quickly extract specific parts and write them to FASTA files given a set of search terms. This is useful as it allows users to quickly extract parts of concatenated or genomic sequences based on GenBank features and write them to FASTA files, even when feature annotations for homologous loci may vary (i.e. gene synonyms like COI, COX1, COXI all being used for cytochrome oxidase subunit 1).
In this tutorial we will cover the basics of how to use AnnotationBustR to extract parts of a GenBank sequences.This is considerably faster than extracting them manually and requires minimal effort by the user. While command line utilities like BLAST can also work, they require the buliding of databases to search against and can be computationally intensive and can have difficulties with highly complex sequences, like trans-spliced genes. They also require a far more complex query language to extract the subsequence and write it to a file. For example, it is possible to extract into FASTA files every subsequence from a mitochondrial genome (38 sequences, 13 CDS, 22 tRNA, 2rRNA, 1 D-loop) in 26-36 seconds, which is significantly faster than if you were to do it manually from the online GenBank features table. In this tutorial, we will discuss how to install AnnotationBustR, the basic AnnotationBustR pipeline, and how to use the functions that are included in AnnotationBustR.
# 2: Installation
## 2.1: Installation From CRAN
In order to install the stable CRAN version of the AnnotationBustR package:
```
install.packages("AnnotationBustR")
```
## 2.2: Installation of Development Version From GitHub
While we recommend use of the stable CRAN version of this package, we recommend using the package `devtools` to temporarily install the development version of the package from GitHub if for any reason you wish to use it :
```
#1. Install 'devtools' if you do not already have it installed:
install.packages("devtools")
#2. Load the 'devtools' package and temporarily install the development version of
#'AnnotationBustR' from GitHub:
library(devtools)
dev_mode(on=T)
install_github("sborstein/AnnotationBustR") # install the package from GitHub
library(AnnotationBustR)# load the package
#3. Leave developers mode after using the development version of 'AnnotationBustR' so it will not remain on
#your system permanently.
dev_mode(on=F)
```
# 3: Using AnnotationBustR
To load AnnotationBustR and all of its functions/data:
```
library(AnnotationBustR)
```
It is important to note that most of the functions within AnnotationBustR connect to sequence databases and require an internet connection.
##3.0: AnnotationBustR Work Flow
Before we begin a tutorial on how to use AnnotationBustR to extract sequences, lets first discuss the basic workflow of the functions in the package (Fig. 1). The orange box represents the step that occur outside of using AnnotationBustR. The only step you must do outside of AnnotationBustR is obtain a target list of accession numbers. This can be done either by downloading the accession numbers themselves from GenBank (https://www.ncbi.nlm.nih.gov/nuccore) or using R packages like `ape`, `seqinr` and `rentrez` to find accessions of interest in R. All boxes in blue in the graphic below represent steps that occur using AnnotationBustR. Boxes in green represent steps that are not mandatory, but may prove to be useful features of AnnotationBustR. In this tutorial, we will go through the steps in order, including the optional steps to show how to fully use the AnnotationBustR package.
```{r, out.width = "100%", echo=FALSE,fig.align='left',fig.cap= "Fig. 1: AnnotationBustR Workflow. Steps in orange occur outside the package while steps in blue are core parts of AnnotationBustR and steps in green represent optional steps"}
knitr::include_graphics("workflow.jpg")
```
For this tutorial we will be extracting loci from the mitochondrial genomes of a fish genus, *Barbonymus*. We'll start off by using the R package `reutils` to search for accessions to use in this tutorial. There are a variety of R packages that can be used to find accessions you may want to extract subsequences from (i.e. `seqinr`,`rentrez`,`reutils`) or you can perform a search on the NCBI Database website (https://www.ncbi.nlm.nih.gov/nuccore) and download a list of accession numbers that can then be read into R.
```
#install (if necessary) and load reutils
#install.packages("reutils")#install if necessary
library(reutils)
```
Lets pretend we wanted to search for the gene cytochrome B. We could perform a search using the following.
```
#search for cytochrome b Barbonymus sequences
demo.search <- esearch(term = "Barbonymus[orgn] and CYTB[title]", db = 'nuccore', usehistory = TRUE)#search
accessions<-efetch(demo.search, rettype = "acc",retmode = "text")#fetch accessions
accessions <- strsplit(content(accessions), "\n")[[1]]#split out accessions from other meta-data
```
We can see that this returned 51 sequences. Many of these are accessions for a single cytochrome b sequence. However, if we wanted to find complete mitochondrial genomes to extract sequences from, we could refine our search to find complete mitochondrial genomes.
```
#perform the search and retrieve accessions of complete mitochondrial genomes for Barbonymus
demo.search <- esearch(term = "Barbonymus[orgn] and complete genome[title]", db = 'nuccore')#search
accessions<-efetch(demo.search, rettype = "acc",retmode = "text")#fetch accessions
accessions <- strsplit(content(accessions), "\n")[[1]]#split out accessions from other meta-data
#Currently, ACNUC, which AnnotationBustR uses through the seqinr dependency, doesn't have access to refseq
#accessions, so remove them
accessions<-accessions[-grep("NC_",accessions)]
```
We can see that this returns six complete mitochondrial genome sequences on GenBank for *Barbonymus* species. We'll be using these accessions later in this tutorial.
One important note for using `reutils` for finding sequences is that if you are trying to retrieve over 500 accession numbers, you will get a warning that you need to write it to a file locally on the machine. In this case, you can use the folowing code below. As the file is local and not stored in R, you will need to read it back into R for use with AnnotationBustR. Luckily, this doesn't write meta-data to the file, so we don't have to run the line stripping the meta-data.
```
#Perform search given critera
demo.search.long <- esearch(term = "Pristimantis[orgn] and 12S[title]", db = 'nuccore', usehistory = TRUE)
#As more than 500 records, write the records to file in the current working directory
accessions.long<-efetch(demo.search.long, rettype = "acc",retmode = "text", outfile = "12S.txt")
#Read in file with records, you can now use these in AnnotationBustR
accessions.long.table <- read.table("12S.txt",header = FALSE,stringsAsFactors = FALSE)
accessions.long.accessions <- accessions.long.table$V1
```
## 3.1:(Optional Step) Finding the Longest Available
AnnotationBustR's `FindLongestSeq` function finds the longest available sequence for each species in a given set of GenBank accession numbers. All the user needs is to obtain a list of GenBank accession numbers they would like to input. The only function argument for `FindLongestSeq` is `Accessions`, which takes a vector of accession numbers as input. We can run the function below on the six Barbonymus accessions we found above by:
```
#Create a vector of GenBank nucleotide accession numbers. In order this contains accessions
my.longest.seqs<-FindLongestSeq(accessions)#Run the FindLongestSeq function
my.longest.seqs#returns the longest seqs found per species
```
In this case we can see that the function worked as it only returned accession AP011317.1 (16577 bp) for *Barbonymus schwanefeldii* which was longer than accessions KU498040.2, KU233186.2, KJ573467.1 (16570,16478, and 16576 bp respectively) as well as the single accessions for *Barbonymus altus* and *Barbonymus gonionnotus*. The table returns a three-column data frame with the species name, the corresponding accession number, and the length.
## 3.2: Load a Data Frame of Search Terms of Gene Synonyms to Search With:
AnnotationBustR works by searching through the annotation features table for a locus of interest using search terms for it (i.e. possible synonyms it may be listed under). These search terms are formatted to have three columns:
- Locus: The name of the locus and the name of the FASTA of the file for that locus to be written. It is important that you use names that will not confuse R, so don't start these with numbers or include other characters like "." or "-" that R uses for math.
- Type: The type of sequence to search for. Can be one of CDS, tRNA, rRNA, misc_RNA, D-Loop, or misc_feature.
- Name: A possible synonym that the locus could be listed under.
For extracting introns and exons, an additional fourth column is needed (which will be discussed in more detail later in the tutorial):
-IntronExonNumber: The number of the intron or exon to extract
Below (Figure 2) is an example of where these corresponding items would be in the GenBank features table:
```{r, out.width = "100%", echo=FALSE, fig.align='left',fig.cap= "Fig. 2: GenBank features annotation for accession G295784.1 that contains ATP8 and ATP6. The words highlighted in yellow would fall under the column of Type. Here they are both CDS. The type of sequence is always listed farthest to the left in the features table. Colors in blue indicate terms that would be placed in the Name column, here indicating that the two CDS in this example are ATP8, labeled as ATPase8 and ATP6 respectively."}
knitr::include_graphics("featuresMarked.jpg")
```
So, if we wanted to use AnnotationBustR to capture these and write them to a FASTA, we could set up a data frame that looks like the following.
```{r, echo=FALSE}
ex.frame<-rbind(c("ATP8","CDS","ATPase8"),c("ATP6","CDS","ATPase6"))
colnames(ex.frame)<-c("Locus","Type","Name")
ex.frame<-as.data.frame(ex.frame)
print(ex.frame)
```
While AnnotationBustR will work with any data frame formatted as discussed above, we have included in it pre-made search terms for animal and plant mitochondrial DNA (mtDNA), chloroplast DNA (cpDNA), and ribosomal DNA (rDNA). These can be loaded from AnnotationBustR using:
```
#Load in pre-made data frames of search terms
data(mtDNAterms)#loads the mitochondrial DNA search terms for metazoans
data(mtDNAtermsPlants)#loads the mitochondrial DNA search terms for plants
data(cpDNAterms)#loads the chloroplast DNA search terms
data(rDNAterms)#loads the ribosomal DNA search terms
```
These data frames can also easily be manipulated to select only the loci of interest. For instance, if we were only interested in tRNAs from mitochondrial genomes, we could easily subset out the tRNAs from the premade `mtDNAterms` object by:
```
data(mtDNAterms)#load the data frame of mitochondrial DNA terms
tRNA.terms<-mtDNAterms[mtDNAterms$Type=="tRNA",]#subset out the tRNAs into a new data frame
```
## 3.3:(Optional Step) Merge Search Terms If Neccessary
While we have tried to cover as many synonyms for genes in our pre-made data frames, it is likely that some synonyms may not be represented due to the vast array of synonyms a single gene may be listed under in the features table. To solve this we have included the function `MergeSearchTerms`.
For example, let's imagine that we found a completely new annotation for the gene cytochrome oxidase subunit 1 (COI) listed as CX1. The `MergeSearchTerms` function only has two arguments, `...`, which takes two or more objects of class `data.frame` and the logical `Sort.Genes`, which We could easily add this to other mitochondrial gene terms by:
```
#Add imaginary gene synonym for cytochrome oxidase subunit 1, CX1
add.name<-data.frame("COI","CDS", "CX1", stringsAsFactors = FALSE)
colnames(add.name)<-colnames(mtDNAterms)#make the columnames for this synonym those needed for AnnotationBustR
#Run the merge search term function without sorting based on gene name.
new.terms<-MergeSearchTerms(add.name, mtDNAterms, SortGenes=FALSE)
#Run the merge search term function with sorting based on gene name.
new.terms<-MergeSearchTerms(add.name, mtDNAterms, SortGenes=TRUE)
```
We will use this function again in a more realistic example later in this vignette.
## 3.4 Extract sequences with AnnotationBust
The main function of AnnotationBustR is `AnnotationBust`. This function extracts the sub-sequence(s) of interest from the accessions and writes them to FASTA files in the current working directory. In addition to writing sub-sequences to FASTA files, `AnnotationBust` also generates an accession table for all found sub-sequences written to FASTA files which can then be written to a csv file using base R `write.csv`. AnnotationBustR requires at least two arguments, a vector of accessions for `Accessions` and a data frame of search terms formatted as discussed in 3.2 and 3.3 for `Terms`.
Additional arguments include the ability to specify duplicate genes you wish to recover as a vector of gene names using the `Duplicates` argument and specifying the number of duplicate instances to extract using a numeric vector (which must be the same length as `Duplicates`) using the `DuplicateInstances` argument.
AnnotationBustR also has arguments to translate coding sequences into the corresponding peptide sequence setting the `TranslateSeqs` argument to TRUE. If `TranslateSeqs=TRUE`, users should also specify the GenBank translation code number corresponding to their sequences using the `TranslateCode` argument. A list of GenBank translaton codes for taxa is available here: https://www.ncbi.nlm.nih.gov/Taxonomy/Utils/wprintgc.cgi
An additional argument of `AnnotationBust` is `DuplicateSpecies` which when set to `DuplicateSpecies=TRUE` adds the accession number to the species name for the FASTA file. This can be useful for later analyses involving FASTA files as duplicate names in FASTA headers can pose problems with some programs. It is important to note that if users select `DuplicateSpecies=TRUE` that while FASTA file will contain species names with their respected accession number, the corresponding accession table will either have a single row per species containing all the accession numbers for each subsequence locus found for that species seperated by a comma or a seperate row for each accession number dependent on what the user chooses for the `TidyAccessions` argument (see description below).
The argument `Prefix`can either be `NULL` or a character vector of length 1. If Prefix is not `NULL` it will add the prefix specified to all FASTA files. If left as `Prefix=NULL` files names will just be the name of the locus.
The final argument `TidyAccessions` effects the format of the final accession table. If `TidyAccessions=TRUE`, all sequence for a single species will be collapsed into a single cell per locus and accessions will be seperated by commas. If `TidyAccessions=FALSE` it will leave each accession number in its own row in the accession table.
For the tutorial, we will use the accessions we created in examples 3.1 in the object `my.longest.accessions`. This is a vector that contains three accessions for mitogenomes of three species of *Barbonymus*. These accessions provide a good highlight as to the utility of this package.If we look at the annotations of these three accessions(https://www.ncbi.nlm.nih.gov/nuccore/AP011317.1, https://www.ncbi.nlm.nih.gov/nuccore/AP011181.1, https://www.ncbi.nlm.nih.gov/nuccore/AB238966.1), we can see that while AP011317 and AP011181 are annotated with similar nomenclature, AB238966 differs substantially (e.x. COI vs CO2, Cyt b vs Cb, etc.). For this example, we will use all the arguments of `AnnotationBust` to extract all 38 subsequences for the four accessions (22 tRNAs, 13 CDS, 2 rRNAs, and 1 D-loop). For this we will have to specify duplicates, in this case for tRNA-Leu and tRNA-Ser, which occur twice in vertebrate mitogenomes. We will translate the CDS using `TranslateSeqs` argument with `TranslateCode=2`, the code for vertebrate mitogenomes. Because we have a single accession for each species, we will specify `DuplicateSpecies=FALSE` and have out FASTA files output with the prefix "Demo" by specifying `Prefix="Demo"` and with `TiddyAccessions=TRUE`. This will create 38 FASTA files for all mitochondrial loci in the mitochondrial genome in the working director with the prefix "Demo".
```
#run AnnotationBust function for two duplicate tRNA genes occuring twice and translate CDS
my.seqs<-AnnotationBust(Accessions=my.longest.seqs$Accession, Terms=mtDNAterms,Duplicates=c("tRNA_Leu","tRNA_Ser"), DuplicateInstances=c(2,2), TranslateSeqs=TRUE, TranslateCode=2, DuplicateSpecies=TRUE, Prefix="Demo", TidyAccessions=TRUE)
#We can return the accession table and write it to a CSV file.
my.seqs#retutn the accession table
write.csv(my.seqs, file="AccessionTable.csv")#Write the accession table to a csv file
```
We can also use `AnnotationBustR` to extract introns from sequences. One limitation to this is that the introns must be annotated within the subsequence, which is lacking from some accessions (e.x. not all chloroplasts have introns annotated). As stated above, this requires the use of a fourth column in the search terms, labelled `IntronExonNumber`, which is used to find which number intron is to be extracted. For instance, lets imagine we want to extract the coding sequence matK and exon 2 and intron 1 of trnK from the chloroplast genomes KX687911.1 and KX687910.1 We could set up the search terms as follows using the current `cpDNAterms`:
```
#Subset out matK from cpDNAterms
cds.terms<-subset(cpDNAterms,cpDNAterms$Locus=="matK")
#Create a vecotr of NA so we can merge with the search terms for introns and exons
cds.terms<-cbind(cds.terms,(rep(NA,length(cds.terms$Locus))))
colnames(cds.terms)[4]<-"IntronExonNumber"
#Prepare a search term table for the intron and exons to remove
#We can start with the cpDNAterms for trnK
IntronExon.terms<-subset(cpDNAterms,cpDNAterms$Locus=="trnK")
#As we want to go for two exons, we will want the synonyms repeated as we are doing and intron and an exon
IntronExon.terms<-rbind(IntronExon.terms,IntronExon.terms)#duplicate the terms
IntronExon.terms$Type<-rep(c("Intron","Intron","Exon","Exon"))#rep the sequence type we want to extract
IntronExon.terms$Locus<-rep(c("trnK_Intron","trnK_Exon2"),each=2)
IntronExon.terms<-cbind(IntronExon.terms,rep(c(1,1,2,2)))#Add intron/exon number info
colnames(IntronExon.terms)[4]<-"IntronExonNumber"#change column name for number info for IntronExon name
#We can then merge everything together with MergeSearchTerms terms
IntronExonExampleTerms<-MergeSearchTerms(IntronExon.terms,cds.terms)
#Run AnnotationBust
IntronExon.example<-AnnotationBust(Accessions=c("KX687911.1", "KX687910.1"), Terms=IntronExonExampleTerms, Prefix="DemoIntronExon")
```
## 3.5 Troubleshooting
As `AnnotationBustR` is dependent on access to online databases, it is important that you make sure you have a reliable internet connection while using the package, especially for the `FindLongestSeq` and `AnnotationBust` functions. Additionally, as these functions require access to GenBank and ACNUC, if you have internet access yet are still having issues, check that these sites and there servers are not down or undergoing maintainence, which they do occasionally.
The `AnnotationBust` function may also provide the following warnings and report the following in the accessions table:
"Acc. # Not Found" = The supplied accession number does not seem to exist, check that it is correct.
"Acc. # Not On ACNUC GenBank" = Sometime ACNUC is behind a day or two from NCBI GenBank. To double check the date for the current version of the ACNUC database you can run the following code:
```
ACNUC.GB.Info<-seqinr::choosebank("genbank", infobank=T)
ACNUC.GB.INFO#return info on date
```
"type not fully Ann." = Indicates that the sequence is on GenBank, but is lacking necessary annotation information to fully extract all subsequences. They may be concatenated and not contain position information for each subsequence.
"Warning: In socketConnection(host = host, port = port, server = server, blocking = blocking, :pbil.univ-lyon1.fr:5558 cannot be opened" = There was an issue connecting to ACNUC. This is an error with the seqinr dependency indicating it is having issues connecting to the ACNUC server. This isn't usually common with a solid internet connection, but does occassionally occur when trying to connect to the ANCUC server for the first time during a session.
It is also important to note that refseq numbers are not supported at the moment (i.e. prefixes like XM_ and NC_). This is due to a limitation in our dependency `seqinr`, which only provides access to refseq viruses at present. We have been in contact with the maintainers of `seqinr` and look forward to implementing refseq accessability into AnotationBusR in the future.
## 4: Final Comments
Further information on the functions and their usage can be found in the helpfiles `help(package=AnnotationBustR)`. For any further issues and questions send an email with subject 'AnnotationBustR support' to [email protected] or post to the issues section on GitHub(https://github.com/sborstein/AnnotationBustR/issues).
| /scratch/gouwar.j/cran-all/cranData/AnnotationBustR/inst/doc/AnnotationBustR-vignette.Rmd |
---
title: "AnnotationBustR Tutorial"
author: "Samuel R. Borstein"
date: "`r format(Sys.time(), '%d %B, %Y')`"
output:
html_document:
keep_md: true
vignette: >
%\VignetteIndexEntry{AnnotationBustR Tutorial}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
# 1: Introduction
This is a tutorial for using the R package AnnotationBustR. AnnotationBustR reads in sequences from GenBank and allows you to quickly extract specific parts and write them to FASTA files given a set of search terms. This is useful as it allows users to quickly extract parts of concatenated or genomic sequences based on GenBank features and write them to FASTA files, even when feature annotations for homologous loci may vary (i.e. gene synonyms like COI, COX1, COXI all being used for cytochrome oxidase subunit 1).
In this tutorial we will cover the basics of how to use AnnotationBustR to extract parts of a GenBank sequences.This is considerably faster than extracting them manually and requires minimal effort by the user. While command line utilities like BLAST can also work, they require the buliding of databases to search against and can be computationally intensive and can have difficulties with highly complex sequences, like trans-spliced genes. They also require a far more complex query language to extract the subsequence and write it to a file. For example, it is possible to extract into FASTA files every subsequence from a mitochondrial genome (38 sequences, 13 CDS, 22 tRNA, 2rRNA, 1 D-loop) in 26-36 seconds, which is significantly faster than if you were to do it manually from the online GenBank features table. In this tutorial, we will discuss how to install AnnotationBustR, the basic AnnotationBustR pipeline, and how to use the functions that are included in AnnotationBustR.
# 2: Installation
## 2.1: Installation From CRAN
In order to install the stable CRAN version of the AnnotationBustR package:
```
install.packages("AnnotationBustR")
```
## 2.2: Installation of Development Version From GitHub
While we recommend use of the stable CRAN version of this package, we recommend using the package `devtools` to temporarily install the development version of the package from GitHub if for any reason you wish to use it :
```
#1. Install 'devtools' if you do not already have it installed:
install.packages("devtools")
#2. Load the 'devtools' package and temporarily install the development version of
#'AnnotationBustR' from GitHub:
library(devtools)
dev_mode(on=T)
install_github("sborstein/AnnotationBustR") # install the package from GitHub
library(AnnotationBustR)# load the package
#3. Leave developers mode after using the development version of 'AnnotationBustR' so it will not remain on
#your system permanently.
dev_mode(on=F)
```
# 3: Using AnnotationBustR
To load AnnotationBustR and all of its functions/data:
```
library(AnnotationBustR)
```
It is important to note that most of the functions within AnnotationBustR connect to sequence databases and require an internet connection.
##3.0: AnnotationBustR Work Flow
Before we begin a tutorial on how to use AnnotationBustR to extract sequences, lets first discuss the basic workflow of the functions in the package (Fig. 1). The orange box represents the step that occur outside of using AnnotationBustR. The only step you must do outside of AnnotationBustR is obtain a target list of accession numbers. This can be done either by downloading the accession numbers themselves from GenBank (https://www.ncbi.nlm.nih.gov/nuccore) or using R packages like `ape`, `seqinr` and `rentrez` to find accessions of interest in R. All boxes in blue in the graphic below represent steps that occur using AnnotationBustR. Boxes in green represent steps that are not mandatory, but may prove to be useful features of AnnotationBustR. In this tutorial, we will go through the steps in order, including the optional steps to show how to fully use the AnnotationBustR package.
```{r, out.width = "100%", echo=FALSE,fig.align='left',fig.cap= "Fig. 1: AnnotationBustR Workflow. Steps in orange occur outside the package while steps in blue are core parts of AnnotationBustR and steps in green represent optional steps"}
knitr::include_graphics("workflow.jpg")
```
For this tutorial we will be extracting loci from the mitochondrial genomes of a fish genus, *Barbonymus*. We'll start off by using the R package `reutils` to search for accessions to use in this tutorial. There are a variety of R packages that can be used to find accessions you may want to extract subsequences from (i.e. `seqinr`,`rentrez`,`reutils`) or you can perform a search on the NCBI Database website (https://www.ncbi.nlm.nih.gov/nuccore) and download a list of accession numbers that can then be read into R.
```
#install (if necessary) and load reutils
#install.packages("reutils")#install if necessary
library(reutils)
```
Lets pretend we wanted to search for the gene cytochrome B. We could perform a search using the following.
```
#search for cytochrome b Barbonymus sequences
demo.search <- esearch(term = "Barbonymus[orgn] and CYTB[title]", db = 'nuccore', usehistory = TRUE)#search
accessions<-efetch(demo.search, rettype = "acc",retmode = "text")#fetch accessions
accessions <- strsplit(content(accessions), "\n")[[1]]#split out accessions from other meta-data
```
We can see that this returned 51 sequences. Many of these are accessions for a single cytochrome b sequence. However, if we wanted to find complete mitochondrial genomes to extract sequences from, we could refine our search to find complete mitochondrial genomes.
```
#perform the search and retrieve accessions of complete mitochondrial genomes for Barbonymus
demo.search <- esearch(term = "Barbonymus[orgn] and complete genome[title]", db = 'nuccore')#search
accessions<-efetch(demo.search, rettype = "acc",retmode = "text")#fetch accessions
accessions <- strsplit(content(accessions), "\n")[[1]]#split out accessions from other meta-data
#Currently, ACNUC, which AnnotationBustR uses through the seqinr dependency, doesn't have access to refseq
#accessions, so remove them
accessions<-accessions[-grep("NC_",accessions)]
```
We can see that this returns six complete mitochondrial genome sequences on GenBank for *Barbonymus* species. We'll be using these accessions later in this tutorial.
One important note for using `reutils` for finding sequences is that if you are trying to retrieve over 500 accession numbers, you will get a warning that you need to write it to a file locally on the machine. In this case, you can use the folowing code below. As the file is local and not stored in R, you will need to read it back into R for use with AnnotationBustR. Luckily, this doesn't write meta-data to the file, so we don't have to run the line stripping the meta-data.
```
#Perform search given critera
demo.search.long <- esearch(term = "Pristimantis[orgn] and 12S[title]", db = 'nuccore', usehistory = TRUE)
#As more than 500 records, write the records to file in the current working directory
accessions.long<-efetch(demo.search.long, rettype = "acc",retmode = "text", outfile = "12S.txt")
#Read in file with records, you can now use these in AnnotationBustR
accessions.long.table <- read.table("12S.txt",header = FALSE,stringsAsFactors = FALSE)
accessions.long.accessions <- accessions.long.table$V1
```
## 3.1:(Optional Step) Finding the Longest Available
AnnotationBustR's `FindLongestSeq` function finds the longest available sequence for each species in a given set of GenBank accession numbers. All the user needs is to obtain a list of GenBank accession numbers they would like to input. The only function argument for `FindLongestSeq` is `Accessions`, which takes a vector of accession numbers as input. We can run the function below on the six Barbonymus accessions we found above by:
```
#Create a vector of GenBank nucleotide accession numbers. In order this contains accessions
my.longest.seqs<-FindLongestSeq(accessions)#Run the FindLongestSeq function
my.longest.seqs#returns the longest seqs found per species
```
In this case we can see that the function worked as it only returned accession AP011317.1 (16577 bp) for *Barbonymus schwanefeldii* which was longer than accessions KU498040.2, KU233186.2, KJ573467.1 (16570,16478, and 16576 bp respectively) as well as the single accessions for *Barbonymus altus* and *Barbonymus gonionnotus*. The table returns a three-column data frame with the species name, the corresponding accession number, and the length.
## 3.2: Load a Data Frame of Search Terms of Gene Synonyms to Search With:
AnnotationBustR works by searching through the annotation features table for a locus of interest using search terms for it (i.e. possible synonyms it may be listed under). These search terms are formatted to have three columns:
- Locus: The name of the locus and the name of the FASTA of the file for that locus to be written. It is important that you use names that will not confuse R, so don't start these with numbers or include other characters like "." or "-" that R uses for math.
- Type: The type of sequence to search for. Can be one of CDS, tRNA, rRNA, misc_RNA, D-Loop, or misc_feature.
- Name: A possible synonym that the locus could be listed under.
For extracting introns and exons, an additional fourth column is needed (which will be discussed in more detail later in the tutorial):
-IntronExonNumber: The number of the intron or exon to extract
Below (Figure 2) is an example of where these corresponding items would be in the GenBank features table:
```{r, out.width = "100%", echo=FALSE, fig.align='left',fig.cap= "Fig. 2: GenBank features annotation for accession G295784.1 that contains ATP8 and ATP6. The words highlighted in yellow would fall under the column of Type. Here they are both CDS. The type of sequence is always listed farthest to the left in the features table. Colors in blue indicate terms that would be placed in the Name column, here indicating that the two CDS in this example are ATP8, labeled as ATPase8 and ATP6 respectively."}
knitr::include_graphics("featuresMarked.jpg")
```
So, if we wanted to use AnnotationBustR to capture these and write them to a FASTA, we could set up a data frame that looks like the following.
```{r, echo=FALSE}
ex.frame<-rbind(c("ATP8","CDS","ATPase8"),c("ATP6","CDS","ATPase6"))
colnames(ex.frame)<-c("Locus","Type","Name")
ex.frame<-as.data.frame(ex.frame)
print(ex.frame)
```
While AnnotationBustR will work with any data frame formatted as discussed above, we have included in it pre-made search terms for animal and plant mitochondrial DNA (mtDNA), chloroplast DNA (cpDNA), and ribosomal DNA (rDNA). These can be loaded from AnnotationBustR using:
```
#Load in pre-made data frames of search terms
data(mtDNAterms)#loads the mitochondrial DNA search terms for metazoans
data(mtDNAtermsPlants)#loads the mitochondrial DNA search terms for plants
data(cpDNAterms)#loads the chloroplast DNA search terms
data(rDNAterms)#loads the ribosomal DNA search terms
```
These data frames can also easily be manipulated to select only the loci of interest. For instance, if we were only interested in tRNAs from mitochondrial genomes, we could easily subset out the tRNAs from the premade `mtDNAterms` object by:
```
data(mtDNAterms)#load the data frame of mitochondrial DNA terms
tRNA.terms<-mtDNAterms[mtDNAterms$Type=="tRNA",]#subset out the tRNAs into a new data frame
```
## 3.3:(Optional Step) Merge Search Terms If Neccessary
While we have tried to cover as many synonyms for genes in our pre-made data frames, it is likely that some synonyms may not be represented due to the vast array of synonyms a single gene may be listed under in the features table. To solve this we have included the function `MergeSearchTerms`.
For example, let's imagine that we found a completely new annotation for the gene cytochrome oxidase subunit 1 (COI) listed as CX1. The `MergeSearchTerms` function only has two arguments, `...`, which takes two or more objects of class `data.frame` and the logical `Sort.Genes`, which We could easily add this to other mitochondrial gene terms by:
```
#Add imaginary gene synonym for cytochrome oxidase subunit 1, CX1
add.name<-data.frame("COI","CDS", "CX1", stringsAsFactors = FALSE)
colnames(add.name)<-colnames(mtDNAterms)#make the columnames for this synonym those needed for AnnotationBustR
#Run the merge search term function without sorting based on gene name.
new.terms<-MergeSearchTerms(add.name, mtDNAterms, SortGenes=FALSE)
#Run the merge search term function with sorting based on gene name.
new.terms<-MergeSearchTerms(add.name, mtDNAterms, SortGenes=TRUE)
```
We will use this function again in a more realistic example later in this vignette.
## 3.4 Extract sequences with AnnotationBust
The main function of AnnotationBustR is `AnnotationBust`. This function extracts the sub-sequence(s) of interest from the accessions and writes them to FASTA files in the current working directory. In addition to writing sub-sequences to FASTA files, `AnnotationBust` also generates an accession table for all found sub-sequences written to FASTA files which can then be written to a csv file using base R `write.csv`. AnnotationBustR requires at least two arguments, a vector of accessions for `Accessions` and a data frame of search terms formatted as discussed in 3.2 and 3.3 for `Terms`.
Additional arguments include the ability to specify duplicate genes you wish to recover as a vector of gene names using the `Duplicates` argument and specifying the number of duplicate instances to extract using a numeric vector (which must be the same length as `Duplicates`) using the `DuplicateInstances` argument.
AnnotationBustR also has arguments to translate coding sequences into the corresponding peptide sequence setting the `TranslateSeqs` argument to TRUE. If `TranslateSeqs=TRUE`, users should also specify the GenBank translation code number corresponding to their sequences using the `TranslateCode` argument. A list of GenBank translaton codes for taxa is available here: https://www.ncbi.nlm.nih.gov/Taxonomy/Utils/wprintgc.cgi
An additional argument of `AnnotationBust` is `DuplicateSpecies` which when set to `DuplicateSpecies=TRUE` adds the accession number to the species name for the FASTA file. This can be useful for later analyses involving FASTA files as duplicate names in FASTA headers can pose problems with some programs. It is important to note that if users select `DuplicateSpecies=TRUE` that while FASTA file will contain species names with their respected accession number, the corresponding accession table will either have a single row per species containing all the accession numbers for each subsequence locus found for that species seperated by a comma or a seperate row for each accession number dependent on what the user chooses for the `TidyAccessions` argument (see description below).
The argument `Prefix`can either be `NULL` or a character vector of length 1. If Prefix is not `NULL` it will add the prefix specified to all FASTA files. If left as `Prefix=NULL` files names will just be the name of the locus.
The final argument `TidyAccessions` effects the format of the final accession table. If `TidyAccessions=TRUE`, all sequence for a single species will be collapsed into a single cell per locus and accessions will be seperated by commas. If `TidyAccessions=FALSE` it will leave each accession number in its own row in the accession table.
For the tutorial, we will use the accessions we created in examples 3.1 in the object `my.longest.accessions`. This is a vector that contains three accessions for mitogenomes of three species of *Barbonymus*. These accessions provide a good highlight as to the utility of this package.If we look at the annotations of these three accessions(https://www.ncbi.nlm.nih.gov/nuccore/AP011317.1, https://www.ncbi.nlm.nih.gov/nuccore/AP011181.1, https://www.ncbi.nlm.nih.gov/nuccore/AB238966.1), we can see that while AP011317 and AP011181 are annotated with similar nomenclature, AB238966 differs substantially (e.x. COI vs CO2, Cyt b vs Cb, etc.). For this example, we will use all the arguments of `AnnotationBust` to extract all 38 subsequences for the four accessions (22 tRNAs, 13 CDS, 2 rRNAs, and 1 D-loop). For this we will have to specify duplicates, in this case for tRNA-Leu and tRNA-Ser, which occur twice in vertebrate mitogenomes. We will translate the CDS using `TranslateSeqs` argument with `TranslateCode=2`, the code for vertebrate mitogenomes. Because we have a single accession for each species, we will specify `DuplicateSpecies=FALSE` and have out FASTA files output with the prefix "Demo" by specifying `Prefix="Demo"` and with `TiddyAccessions=TRUE`. This will create 38 FASTA files for all mitochondrial loci in the mitochondrial genome in the working director with the prefix "Demo".
```
#run AnnotationBust function for two duplicate tRNA genes occuring twice and translate CDS
my.seqs<-AnnotationBust(Accessions=my.longest.seqs$Accession, Terms=mtDNAterms,Duplicates=c("tRNA_Leu","tRNA_Ser"), DuplicateInstances=c(2,2), TranslateSeqs=TRUE, TranslateCode=2, DuplicateSpecies=TRUE, Prefix="Demo", TidyAccessions=TRUE)
#We can return the accession table and write it to a CSV file.
my.seqs#retutn the accession table
write.csv(my.seqs, file="AccessionTable.csv")#Write the accession table to a csv file
```
We can also use `AnnotationBustR` to extract introns from sequences. One limitation to this is that the introns must be annotated within the subsequence, which is lacking from some accessions (e.x. not all chloroplasts have introns annotated). As stated above, this requires the use of a fourth column in the search terms, labelled `IntronExonNumber`, which is used to find which number intron is to be extracted. For instance, lets imagine we want to extract the coding sequence matK and exon 2 and intron 1 of trnK from the chloroplast genomes KX687911.1 and KX687910.1 We could set up the search terms as follows using the current `cpDNAterms`:
```
#Subset out matK from cpDNAterms
cds.terms<-subset(cpDNAterms,cpDNAterms$Locus=="matK")
#Create a vecotr of NA so we can merge with the search terms for introns and exons
cds.terms<-cbind(cds.terms,(rep(NA,length(cds.terms$Locus))))
colnames(cds.terms)[4]<-"IntronExonNumber"
#Prepare a search term table for the intron and exons to remove
#We can start with the cpDNAterms for trnK
IntronExon.terms<-subset(cpDNAterms,cpDNAterms$Locus=="trnK")
#As we want to go for two exons, we will want the synonyms repeated as we are doing and intron and an exon
IntronExon.terms<-rbind(IntronExon.terms,IntronExon.terms)#duplicate the terms
IntronExon.terms$Type<-rep(c("Intron","Intron","Exon","Exon"))#rep the sequence type we want to extract
IntronExon.terms$Locus<-rep(c("trnK_Intron","trnK_Exon2"),each=2)
IntronExon.terms<-cbind(IntronExon.terms,rep(c(1,1,2,2)))#Add intron/exon number info
colnames(IntronExon.terms)[4]<-"IntronExonNumber"#change column name for number info for IntronExon name
#We can then merge everything together with MergeSearchTerms terms
IntronExonExampleTerms<-MergeSearchTerms(IntronExon.terms,cds.terms)
#Run AnnotationBust
IntronExon.example<-AnnotationBust(Accessions=c("KX687911.1", "KX687910.1"), Terms=IntronExonExampleTerms, Prefix="DemoIntronExon")
```
## 3.5 Troubleshooting
As `AnnotationBustR` is dependent on access to online databases, it is important that you make sure you have a reliable internet connection while using the package, especially for the `FindLongestSeq` and `AnnotationBust` functions. Additionally, as these functions require access to GenBank and ACNUC, if you have internet access yet are still having issues, check that these sites and there servers are not down or undergoing maintainence, which they do occasionally.
The `AnnotationBust` function may also provide the following warnings and report the following in the accessions table:
"Acc. # Not Found" = The supplied accession number does not seem to exist, check that it is correct.
"Acc. # Not On ACNUC GenBank" = Sometime ACNUC is behind a day or two from NCBI GenBank. To double check the date for the current version of the ACNUC database you can run the following code:
```
ACNUC.GB.Info<-seqinr::choosebank("genbank", infobank=T)
ACNUC.GB.INFO#return info on date
```
"type not fully Ann." = Indicates that the sequence is on GenBank, but is lacking necessary annotation information to fully extract all subsequences. They may be concatenated and not contain position information for each subsequence.
"Warning: In socketConnection(host = host, port = port, server = server, blocking = blocking, :pbil.univ-lyon1.fr:5558 cannot be opened" = There was an issue connecting to ACNUC. This is an error with the seqinr dependency indicating it is having issues connecting to the ACNUC server. This isn't usually common with a solid internet connection, but does occassionally occur when trying to connect to the ANCUC server for the first time during a session.
It is also important to note that refseq numbers are not supported at the moment (i.e. prefixes like XM_ and NC_). This is due to a limitation in our dependency `seqinr`, which only provides access to refseq viruses at present. We have been in contact with the maintainers of `seqinr` and look forward to implementing refseq accessability into AnotationBusR in the future.
## 4: Final Comments
Further information on the functions and their usage can be found in the helpfiles `help(package=AnnotationBustR)`. For any further issues and questions send an email with subject 'AnnotationBustR support' to [email protected] or post to the issues section on GitHub(https://github.com/sborstein/AnnotationBustR/issues).
| /scratch/gouwar.j/cran-all/cranData/AnnotationBustR/vignettes/AnnotationBustR-vignette.Rmd |
FV_post_artan=function(data,years=10){
sigma2=function(x){var(x) * (length(x) - 1)/length(x)}
U=1+data
u1=mean(U)
var=sigma2(U)
u2=sqrt(var+u1^2)
u_max=1+max(data)
u_min=1+min(data)
d=(u_min+u_max)/2
a=(u_max-u_min)/pi
b=tan(x=((u2-d)/a))-tan(x=((u1-d)/a))
c=tan(x=((u1-d)/a))-b
appo=rep(NA,years)
s=years-1
for(i in 0:s) {appo[i+1]=(a*atan(x=(b*i+c))+d)^i}
final_value=sum(appo)
return(final_value)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/FV_post_artan.R |
FV_post_beta_kmom=function(data,years=10){
nor=function(x){(x-min(x))/(max(x)-min(x))}
data2=nor(data)
app=EnvStats::ebeta(data2, method = "mme")
c=app$parameters[1]
d=app$parameters[2]
a=min(data)
b=max(data)
#print(paste("The shape parameters are equal to",round(c,3),"and",round(d,3)))
mean_beta=function(c,d){c/(c+d)}
media=mean_beta(c,d)
var_beta=function(c,d){c*d/((c+d)^2*(c+d+1))}
var_beta(c,d)
#print(paste("The mean of the standard beta distribution is equal to",round(mean_beta(app$parameters[1],app$parameters[2]),3)))
#print(paste("The variance of the standard beta distribution is equal to",round(var_beta(app$parameters[1],app$parameters[2]),3)))
n=years
fattoriale_crescente=function(n,f){n*factorial(x=n+f-1)/factorial(x=n)}
momento_beta=function(c,d,f){fattoriale_crescente(c,f)/fattoriale_crescente((c+d),f)}
momento_nn_normalizzato=function(n,a,b,c,d){
for(k in 0:n) { m=actuar::mbeta(n-k, c, d)
moment_nn_norm=sum(
choose(n,k)*(a^k)*((b-a)^(n-k))*m
) }
return(moment_nn_norm)}
sum_n_moments_non_norm_beta_pag_post=function(n,a,b,c,d){ app2=rep(NA,n)
for (i in 0:(n-1)) app2[i+1]=momento_nn_normalizzato(i,a,b,c,d)
app2[2:n]=app2[2:n]+1
return(sum(app2))}
sum_n_moments_non_norm_beta_pag_post(n,a,b,c,d)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/FV_post_beta_kmom.R |
FV_post_mood=function(data,years=10){
n=years
m=n+2
momenti=rep(NA,m)
U=1+data
u=mean(U)
for (i in 1:m) momenti[i]=moment(U,
central = FALSE, absolute = FALSE, order =i)
final_value=((momenti[n]-1)/(u-1))-
((momenti[n+1]-u*momenti[n])/((u-1)^2))+
((momenti[n]-1)/((u-1)^3))*
(momenti[2]-u^2)
return(final_value)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/FV_post_mood.R |
norm_mom = function(data, order) {
r = order
U = 1 + data
sigma2 = function(x) {
var(x) * (length(x) - 1) / length(x)
}
u = mean(U)
s = sqrt(sigma2(U))
f = function(x) {
(x ^ (r)) * (1 / (s * sqrt(2 * pi))) * exp(-((x - u) ^ 2) / (2 * (s) ^ 2))
}
mom = integrate(f, min(U), max(U))
return(mom$value)
}
FV_post_norm_kmom = function(data, years=10) {
app = rep(NA, years)
for (i in 1:years)
app[i] = norm_mom(data, i)
FV = sum(app[1:years - 1]) + 1
return(FV)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/FV_post_norm_kmom.R |
FV_post_quad=function(data,years=10){
n=years
u=mean(data)
u2=mean(data^2)
final_value=n+(n*(n-1)/2)*u+(n*(n-1)/4)*(1+(2*n-1)/3)*u2
return(final_value)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/FV_post_quad.R |
FV_pre_artan=function(data,years=10){
sigma2=function(x){var(x) * (length(x) - 1)/length(x)}
U=1+data
u1=mean(U)
var=sigma2(U)
u2=sqrt(var+u1^2)
u_min=1+min(data)
u_max=1+max(data)
d=(u_min+u_max)/2
a=(u_max-u_min)/pi
b=tan(x=((u2-d)/a))-tan(x=((u1-d)/a))
c=tan(x=((u1-d)/a))-b
appo=rep(NA,years)
for(i in 1:years) {appo[i]=(a*atan(x=(b*i+c))+d)^i}
final_value=sum(appo)
return(final_value)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/FV_pre_artan.R |
FV_pre_beta_kmom=function(data,years=10){
nor=function(x){(x-min(x))/(max(x)-min(x))}
data2=nor(data)
app=EnvStats::ebeta(data2, method = "mme")
c=app$parameters[1]
d=app$parameters[2]
a=min(data)
b=max(data)
#print(paste("The shape parameters are equal to",round(c,3),"and",round(d,3)))
mean_beta=function(c,d){c/(c+d)}
media=mean_beta(c,d)
var_beta=function(c,d){c*d/((c+d)^2*(c+d+1))}
var_beta(c,d)
#print(paste("The mean of the standard beta distribution is equal to",round(mean_beta(app$parameters[1],app$parameters[2]),3)))
#print(paste("The variance of the standard beta distribution is equal to",round(var_beta(app$parameters[1],app$parameters[2]),3)))
n=years
fattoriale_crescente=function(n,f){n*factorial(x=n+f-1)/factorial(x=n)}
momento_beta=function(c,d,f){fattoriale_crescente(c,f)/fattoriale_crescente((c+d),f)}
momento_nn_normalizzato=function(n,a,b,c,d){
for(k in 0:n) { m=actuar::mbeta(n-k, c, d)
moment_nn_norm=sum(
choose(n,k)*(a^k)*((b-a)^(n-k))*m
) }
return(moment_nn_norm)}
sum_n_moments_non_norm_beta_pag_anticip=function(n,a,b,c,d){
app=rep(NA,n)
for (i in 1:n) app[i]=(momento_nn_normalizzato(i,a,b,c,d)+1)
return(sum(app))}
sum_n_moments_non_norm_beta_pag_anticip(n,a,b,c,d)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/FV_pre_beta_kmom.R |
FV_pre_mood=function(data,years=10){
n=years
m=n+2
momenti=rep(NA,m)
U=1+data
u=mean(U)
for (i in 1:m) momenti[i]=moment(U,
central = FALSE, absolute = FALSE, order =i)
final_value=((momenti[n+1]-u)/(u-1))-
((momenti[n+2]-u*momenti[n+1]-momenti[2]+u^2)/
((u-1)^2))+
((momenti[n+1]-u)/((u-1)^3))*(momenti[2]-u^2)
return(final_value)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/FV_pre_mood.R |
FV_pre_norm_kmom = function(data, years=10) {
app = rep(NA, years)
for (i in 1:years)
app[i] = norm_mom(data, i)
FV = sum(app)
return(FV)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/FV_pre_norm_kmom.R |
FV_pre_quad=function(data,years=10){
n=years
u=mean(data)
u2=mean(data^2)
final_value=n+(n*(n+1)/2)*u+(n*(n+1)/4) *(1+(2*n-1)/3)*u2
return(final_value)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/FV_pre_quad.R |
PV_post_artan=function(data,years=10){
sigma2=function(x){var(x) * (length(x) - 1)/length(x)}
U=1+data
u1=mean(U)
var=sigma2(U)
u2=sqrt(var+u1^2)
u_max=1+max(data)
u_min=1+min(data)
d=(u_min+u_max)/2
a=(u_max-u_min)/pi
b=tan(x=((u2-d)/a))-tan(x=((u1-d)/a))
c=tan(x=((u1-d)/a))-b
appo=rep(NA,years)
s=years
for(i in 1:s) {appo[i]=(a*atan(x=(-b*i+c))+d)^-i}
present_value=sum(appo)
return(present_value)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/PV_post_artan.R |
PV_post_cubic=function(data,years=10){
#not on U but X
n=years
u=mean(data)
u2=mean(data^2)
u3=mean(data^3)
# qudratic approx PV=n-(n*(n+1)/2)*u+(n*(n+1)/4)*(1+(2*n+1)/3)*u2
PV=n-(n*(n+1)/2)*u+(n*(n+1)/4)*(1+(2*n+1)/3)*u2-(n*(n+1)*u3/6)*(1+(2*n+1)/2+n*(n+1)/4)
return(PV)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/PV_post_cubic.R |
PV_post_exact=function(data,years=10){
X=data
U=1+X
n=years
a=rep(NA,n)
for (i in 1:n) a[i]=moment(U, central = FALSE, absolute = FALSE, order =-i)
PV=sum(a)
return(PV)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/PV_post_exact.R |
PV_post_mood_nm=function(data,years=10){
n=years
U=1+data
u=mean(U)
u_2=moment(U,
central = FALSE,
absolute = FALSE,
order = 2)
u_n=moment(U,
central = FALSE,
absolute = FALSE,
order = -n)
u_n_1=moment(U,
central = FALSE,
absolute = FALSE,
order = -(n-1))
PV=(1-u_n)/(u-1)-(u_n_1-u_n*u)/(u-1)^2+(1-u_n)*(u_2-u^2)/(u-1)^3
return(PV)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/PV_post_mood_nm.R |
PV_post_mood_pm=function(data,years=10){
n=years
m=2*n+2
momenti=rep(NA,m)
U=1+data
u=mean(U)
for (i in 1:m) momenti[i]=moment(U,
central = FALSE, absolute = FALSE, order =i)
PV=((momenti[n]-1)/(momenti[n+1]-momenti[n]))-
((momenti[2*n+1]-momenti[n]*momenti[n+1]-momenti[2*n]+(momenti[n])^2)/((momenti[n+1]-momenti[n])^2))+
((momenti[n]-1)/((momenti[n+1]-momenti[n])^3))*
(momenti[2*n+2]-(momenti[n+1])^2+momenti[2*n]-(momenti[n])^2-2*((momenti[2*n+1])-momenti[n]*momenti[n+1]))
return(PV)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/PV_post_mood_pm.R |
PV_post_triang_3=function(data,years=10){
r=years
app=rep(NA,r)
for (i in 1:r) app[i]=triangular_moments_3_U(data,i)
somma_momenti=sum(app[3:r])+triangular_moments_dis_U(data,1)+triangular_moments_dis_U(data,2)
return(somma_momenti)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/PV_post_triang_3.R |
PV_post_triang_dis=function(data,years=10){
app=rep(NA,years)
for(i in 1:years) app[i]=triangular_moments_dis_U(data,i)
PV=sum(app)
return(PV)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/PV_post_triang_dis.R |
PV_pre_artan=function(data,years=10){
sigma2=function(x){var(x) * (length(x) - 1)/length(x)}
U=1+data
u1=mean(U)
var=sigma2(U)
u2=sqrt(var+u1^2)
u_max=1+max(data)
u_min=1+min(data)
d=(u_min+u_max)/2
a=(u_max-u_min)/pi
b=tan(x=((u2-d)/a))-tan(x=((u1-d)/a))
c=tan(x=((u1-d)/a))-b
appo=rep(NA,years)
s=years-1
for(i in 0:s) {appo[i+1]=(a*atan(x=(-b*i+c))+d)^-i}
present_value=sum(appo)
return(present_value)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/PV_pre_artan.R |
PV_pre_cubic=function(data,years=10){
#not on U but X
n=years
u=mean(data)
u2=mean(data^2)
u3=mean(data^3)
# qudratic approx PV=n-(n*(n-1)/2)*u+(n*(n-1)/4)*(1+(2*n-1)/3)*u2
PV=n-(n*(n-1)/2)*u+(n*(n-1)/4)*(1+(2*n-1)/3)*u2-(n*(n-1)*u3/6)*(1+(2*n-1)/2+n*(n-1)/4)
return(PV)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/PV_pre_cubic.R |
# from moments package
moment=function (x, order = 1, central = FALSE, absolute = FALSE, na.rm = FALSE)
{
if (is.matrix(x))
apply(x, 2, moment, order = order, central = central,
absolute = absolute, na.rm = na.rm)
else if (is.vector(x)) {
if (na.rm)
x = x[!is.na(x)]
if (central)
x = x - mean(x)
if (absolute)
x = abs(x)
sum(x^order)/length(x)
}
else if (is.data.frame(x))
sapply(x, moment, order = order, central = central, absolute = absolute,
na.rm = na.rm)
else moment(as.vector(x), order = order, central = central,
absolute = absolute, na.rm = na.rm)
}
PV_pre_exact=function(data,years=10){
X=data
U=1+X
n=years
a=rep(NA,n)
for (i in 1:n) a[i]=moment(U, central = FALSE, absolute = FALSE, order =-i)
PV=sum(a[1:n-1])+1
return(PV)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/PV_pre_exact.R |
PV_pre_mood_nm=function(data,years=10){
n=years
U=1+data
u=mean(U)
u_2=moment(U,
central = FALSE,
absolute = FALSE,
order = 2)
u_n=moment(U,
central = FALSE,
absolute = FALSE,
order = -n)
u_n_1=moment(U,
central = FALSE,
absolute = FALSE,
order = -(n-1))
u_n_2=moment(U,
central = FALSE,
absolute = FALSE,
order = -(n-2))
FV=(u-u_n_1)/(u-1)-(u_2-u^2-u_n_2+u*u_n_1)/(u-1)^2+(u-u_n_1)*(u_2-u^2)/(u-1)^3
return(FV)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/PV_pre_mood_nm.R |
PV_pre_mood_pm=function(data,years=10){
n=years
m=2*n+2
momenti=rep(NA,m)
U=1+data
u=mean(U)
for (i in 1:m) momenti[i]=moment(U,
central = FALSE, absolute = FALSE, order =i)
PV=((momenti[n+1]-u)/(momenti[n+1]-momenti[n]))-
((momenti[2*n+2]-(momenti[2*n+1])-momenti[n+2]+momenti[n+1]*(1-momenti[n+1]+u+momenti[n])-momenti[n]*u)/(momenti[n+1]-momenti[n])^2)+
((momenti[n+1]-u)/((momenti[n+1]-momenti[n])^3))*
(momenti[2*n+2]-(momenti[n+1])^2+momenti[2*n]-(momenti[n])^2-2*((momenti[2*n+1])-momenti[n]*momenti[n+1]))
return(PV)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/PV_pre_mood_pm.R |
PV_pre_triang_3=function(data,years=10){
r=years
app=rep(NA,r)
for (i in 1:r) app[i]=triangular_moments_3_U(data,i)
somma_momenti=1+sum(app[3:(r-1)])+triangular_moments_dis_U(data,1)+triangular_moments_dis_U(data,2)
return(somma_momenti)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/PV_pre_triang_3.R |
PV_pre_triang_dis=function(data,years=10){
app=rep(NA,years)
for(i in 1:years) app[i]=triangular_moments_dis_U(data,i)
PV=1+sum(app[1:years-1])
return(PV)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/PV_pre_triang_dis.R |
beta_parameters=function(data){
nor=function(x){(x-min(x))/(max(x)-min(x))}
data2=nor(data)
app=EnvStats::ebeta(data2, method = "mme")
c=app$parameters[1]
d=app$parameters[2]
a=min(data)
b=max(data)
print(paste("The shape parameters are equal to",round(c,3),"and",round(d,3)))
mean_beta=function(c,d){c/(c+d)}
media=mean_beta(c,d)
var_beta=function(c,d){c*d/((c+d)^2*(c+d+1))}
var_beta(c,d)
print(paste("The mean of the standard beta distribution is equal to",round(mean_beta(app$parameters[1],app$parameters[2]),3)))
print(paste("The variance of the standard beta distribution is equal to",round(var_beta(app$parameters[1],app$parameters[2]),3)))
# from the "stat" package
pl.beta <- function(a,b, asp = if(isLim) 1, ylim = if(isLim) c(0,1.1)) {
if(isLim <- a == 0 || b == 0 || a == Inf || b == Inf) {
eps <- 1e-10
x <- c(0, eps, (1:7)/16, 1/2+c(-eps,0,eps), (9:15)/16, 1-eps, 1)
} else {
x <- seq(0, 1, length = 1025)
}
fx <- cbind(dbeta(x, a,b), pbeta(x, a,b), qbeta(x, a,b))
f <- fx; f[fx == Inf] <- 1e100
matplot(x, f, ylab="", type="l", ylim=ylim, asp=asp,
main = sprintf("Beta Distribution", a,b))
abline(0,1, col="gray", lty=3)
abline(h = 0:1, col="gray", lty=3)
legend("top", paste0(c("d","p","q"), "beta(x, a,b)"),
col=1:3, lty=1:3, bty = "n")
invisible(cbind(x, fx))
}
par(mfrow=c(1, 3))
hist(data2,10, main="Histogram of Data",xlab="Interest Rates")
plot(density(data2), main="Kernel density estimation")
pl.beta(c,d)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/beta_parameters.R |
norm_test_jb=function(data){
x=data
sigma2=function(x){var(x) * (length(x) - 1)/length(x)}
a=tseries::jarque.bera.test(data)
m=mean(data)
n=sqrt(sigma2(data))
if (a$p.value>0.05) print(paste("Interest Rates are normally distributed with mean", round(m,5), "and standard deviation",round(n,5))) else print("Interest Rates are not normally distributed; you can try using the beta distribution")
#layout(matrix(c(1,1,2,3), 2, 2, byrow = TRUE))
par(mfrow=c(1,2))
hist(data,10)
curve(dnorm(x, mean=mean(data), sd=sd(data)), add=TRUE, col="red")
plot(density(data),col="green")
#boxplot(data,main="Box Plot")
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/norm_test_jb.R |
plot_FV_post_beta_kmom=function(data,years=10,lwd=1.5,lty=1){
appo=rep(NA,years)
for (i in 1:years) {
appo[i]=FV_post_beta_kmom(data,i)
}
appo[1]=1
anni=c(1:years)
plot(appo,type="b",col="red",lwd=lwd, lty=lty, xlim=c(0,years+1),ylim=c(min(appo),max(appo)),xlab="Time", ylab="Final Expexted Value",main="Final Expected Value (annuity-immediate)")
if (length(anni)<20) text(anni+0.2, appo, round(appo, 2), cex=0.7)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/plot_FV_post_beta_kmom.R |
plot_FV_post_norm_kmom=function(data,years=10,lwd=1.5,lty=1){
appo=rep(NA,years)
for (i in 1:years) {
appo[i]=FV_post_norm_kmom(data,i)
}
anni=c(1:years)
plot(appo,type="b",col="red",lwd=lwd, lty=lty, xlim=c(0,years+1),ylim=c(min(appo),max(appo)),xlab="Time", ylab="Final Expexted Value",main="Final Expected Value (annuity-immediate)")
if (length(anni)<20) text(anni+0.2, appo, round(appo, 2), cex=0.7)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/plot_FV_post_norm_kmom.R |
plot_FV_pre_beta_kmom=function(data,years=10,lwd=1.5,lty=1){
appo=rep(NA,years)
for (i in 1:years) {
appo[i]=FV_pre_beta_kmom(data,i)
}
anni=c(1:years)
plot(appo,type="b",col="red",lwd=lwd, lty=lty, xlim=c(0,years+1),ylim=c(min(appo),max(appo)),xlab="Time", ylab="Final Expexted Value",main="Final Expected Value (annuity-due)")
if (length(anni)<20) text(anni+0.2, appo, round(appo, 2), cex=0.7)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/plot_FV_pre_beta_kmom.R |
plot_FV_pre_norm_kmom=function(data,years=10,lwd=1.5,lty=1){
appo=rep(NA,years)
for (i in 1:years) {
appo[i]=FV_pre_norm_kmom(data,i)
}
anni=c(1:years)
plot(appo,type="b",col="red",lwd=lwd, lty=lty, xlim=c(0,years+1),ylim=c(min(appo),max(appo)),xlab="Time", ylab="Final Expexted Value",main="Final Expected Value (annuity-due)")
if (length(anni)<20) text(anni+0.2, appo, round(appo, 2), cex=0.7)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/plot_FV_pre_norm_kmom.R |
plot_FVs_post=function(data,years=10,lwd=1.5,lty1=1, lty2=2,lty3=3){
art=rep(NA,years)
lin=rep(NA,years)
moo=rep(NA,years)
for (i in 1:years) {
art[i]=FV_post_artan(data,i)
lin[i]=FV_post_quad(data,i)
moo[i]=FV_post_mood(data,i)
}
result=cbind(art,lin,moo)
result
plot(art,type="l",col="red",lwd=lwd, lty=lty1, xlim=c(0,years),ylim=c(0,max(result)),xlab="Time", ylab="Final Expexted Value",main="Final Expected Value (annuity-immediate)")
par(new=TRUE)
plot(lin,type="l",col="black",lwd=lwd, lty=lty2, xlim=c(0,years),ylim=c(0,max(result)),xlab="",ylab="")
par(new=TRUE)
plot(moo,type="l",col="green",lwd=lwd, lty=lty3, xlim=c(0,years),ylim=c(0,max(result)),xlab="",ylab="")
legend("topleft",c("Tetraparametric","Quadratic","Mood et al."), lwd=lwd, lty=c(lty1,lty2,lty3),
y.intersp = 0.65, col=c("red","black","green"), xjust = 1, merge = TRUE)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/plot_FVs_post.R |
plot_FVs_pre=function(data,years=10,lwd=1.5,lty1=1, lty2=2,lty3=3){
art=rep(NA,years)
lin=rep(NA,years)
moo=rep(NA,years)
for (i in 1:years) {
art[i]=FV_pre_artan(data,i)
lin[i]=FV_pre_quad(data,i)
moo[i]=FV_pre_mood(data,i)
}
result=cbind(art,lin,moo)
result
plot(art,type="l",col="red",lwd=lwd, lty=lty1,xlim=c(0,years),ylim=c(0,max(result)),xlab="Time", ylab="Final Expexted Value",main="Final Expected Value (annuity-immediate)")
par(new=TRUE)
plot(lin,type="l",col="black",lwd=lwd, lty=lty2,xlim=c(0,years),ylim=c(0,max(result)),xlab="",ylab="")
par(new=TRUE)
plot(moo,type="l",col="green",lwd=lwd, lty=lty3,xlim=c(0,years),ylim=c(0,max(result)),xlab="",ylab="")
legend("topleft",c("Tetraparametric","Quadratic","Mood et al."), lwd=lwd, lty=c(lty1,lty2,lty3),
y.intersp = 0.65, col=c("red","black","green"), xjust = 1, merge = TRUE)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/plot_FVs_pre.R |
plot_PVs_post=function(data,years=10,lwd=1.5,lty1=1, lty2=2,lty3=3,lty4=4,lty5=5,lty6=6){
art=rep(NA,years)
lin=rep(NA,years)
moo=rep(NA,years)
moo2=rep(NA,years)
ex=rep(NA,years)
tri=rep(NA,years)
for (i in 1:years) {
art[i]=PV_post_artan(data,i)
lin[i]=PV_post_cubic(data,i)
moo[i]=PV_post_mood_pm(data,i)
moo2[i]=PV_post_mood_nm(data,i)
ex[i]=PV_post_exact(data,i)
tri[i]=PV_post_triang_dis(data*100,i)
}
result=cbind(art,lin,moo,moo2,ex,tri)
result
plot(art,type="l",col="red", lwd=lwd, lty=lty1, xlim=c(0,years),ylim=c(0,max(result)),xlab="Time", ylab="Present Expexted Value",main="Present Expected Value (annuity-due)")
par(new=TRUE)
plot(lin,type="l",col="black", lwd=lwd, lty=lty2, xlim=c(0,years),ylim=c(0,max(result)),xlab="",ylab="")
par(new=TRUE)
plot(moo,type="l",col="green", lwd=lwd, lty=lty3, xlim=c(0,years),ylim=c(0,max(result)),xlab="",ylab="")
par(new=TRUE)
plot(moo2,type="l",col="green", lwd=lwd, lty=lty4, xlim=c(0,years),ylim=c(0,max(result)),xlab="",ylab="")
par(new=TRUE)
plot(ex,type="l",col="blue", lwd=lwd, lty=lty5, xlim=c(0,years),ylim=c(0,max(result)),xlab="",ylab="")
par(new=TRUE)
plot(tri,type="l",col="pink", lwd=lwd, lty=lty6, xlim=c(0,years),ylim=c(0,max(result)),xlab="",ylab="")
legend("topleft",c("Tetraparametric","Cubic","Mood PM","Mood NM","Exact","Triangular"), lwd=lwd, lty=c(lty1,lty2,lty3,lty4,lty5,lty6),
y.intersp = 0.65, col=c("red","black","green","green","blue","pink"), xjust = 1, merge = TRUE)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/plot_PVs_post.R |
plot_PVs_pre=function(data,years=10,lwd=1.5,lty1=1,lty2=2,lty3=3,lty4=4,lty5=5,lty6=6){
art=rep(NA,years)
lin=rep(NA,years)
moo=rep(NA,years)
moo2=rep(NA,years)
ex=rep(NA,years)
tri=rep(NA,years)
for (i in 1:years) {
art[i]=PV_pre_artan(data,i)
lin[i]=PV_pre_cubic(data,i)
moo[i]=PV_pre_mood_pm(data,i)
moo2[i]=PV_pre_mood_nm(data,i)
ex[i]=PV_pre_exact(data,i)
tri[i]=PV_pre_triang_dis(data*100,i)
}
result=cbind(art,lin,moo,moo2,ex,tri)
result
plot(art,type="l",col="red", lwd=lwd, lty=lty1, xlim=c(0,years),ylim=c(0,max(result)),xlab="Time", ylab="Present Expexted Value",main="Present Expected Value (annuity-due)")
par(new=TRUE)
plot(lin,type="l",col="black", lwd=lwd, lty=lty2, xlim=c(0,years),ylim=c(0,max(result)),xlab="",ylab="")
par(new=TRUE)
plot(moo,type="l",col="green", lwd=lwd, lty=lty3, xlim=c(0,years),ylim=c(0,max(result)),xlab="",ylab="")
par(new=TRUE)
plot(moo2,type="l",col="green", lwd=lwd, lty=lty4, xlim=c(0,years),ylim=c(0,max(result)),xlab="",ylab="")
par(new=TRUE)
plot(ex,type="l",col="blue", lwd=lwd, lty=lty5, xlim=c(0,years),ylim=c(0,max(result)),xlab="",ylab="")
par(new=TRUE)
plot(tri,type="l",col="pink", lwd=lwd, lty=lty6, xlim=c(0,years),ylim=c(0,max(result)),xlab="",ylab="")
legend("topleft",c("Tetraparametric","Cubic","Mood PM","Mood NM","Exact","Triangular"), lwd=lwd, lty=c(lty1,lty2,lty3,lty4,lty5,lty6),
y.intersp = 0.65, col=c("red","black","green","green","blue","pink"), xjust = 1, merge = TRUE)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/plot_PVs_pre.R |
triangular_moments_3=function(data,order){
x=data
r=order
# moda
Mode <- function(x, na.rm = FALSE) {
if (na.rm) {
x = x[!is.na(x)]
}
ux <- unique(x)
return(ux[which.max(tabulate(match(x, ux)))])
}
# vc triangolare
fCvM <-
fitdistrplus::fitdist(
data,
"triang",
method = "mge",
start = list(
min = min(data),
mode = Mode(data),
max = max(data)
),
gof = "CvM"
)
a=fCvM$estimate[1]
b=fCvM$estimate[3]
c=fCvM$estimate[2]
a=as.numeric(a)
b=as.numeric(b)
c=as.numeric(c)
mom=2*((b-c)/(a^(r-2))-(b-a)/(c^(r-2))+(c-a)/(b^(r-2)))/((r-1)*(r-2)*(b-a)*(c-a)*(b-c))
return(mom)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/triangular_moments_3.R |
triangular_moments_3_U=function(data,order){
r=order
# trovo la moda
Mode <- function(x, na.rm = FALSE) {
if (na.rm) {
x = x[!is.na(x)]
}
ux <- unique(x)
return(ux[which.max(tabulate(match(x, ux)))])
}
# fit della vc triangolare
fCvM <-
fitdistrplus::fitdist(
data,
"triang",
method = "mge",
start = list(
min = min(data),
mode = Mode(data),
max = max(data)
),
gof = "CvM"
)
# parametri della triangolare di U
param=c(fCvM$estimate[1], fCvM$estimate[3], fCvM$estimate[2])
a=1+param[1]/100
b=1+param[3]/100
c=1+param[2]/100
a=as.numeric(a)
b=as.numeric(b)
c=as.numeric(c)
mom=2*((b-c)/(a^(r-2))-(b-a)/(c^(r-2))+(c-a)/(b^(r-2)))/((r-1)*(r-2)*(b-a)*(c-a)*(b-c))
return(mom)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/triangular_moments_3_U.R |
triangular_moments_dis=function(data,order){
r=order
# trovo la moda
Mode <- function(x, na.rm = FALSE) {
if (na.rm) {
x = x[!is.na(x)]
}
ux <- unique(x)
return(ux[which.max(tabulate(match(x, ux)))])
}
# fit vc triangolare
fCvM <-
fitdistrplus::fitdist(
data,
"triang",
method = "mge",
start = list(
min = min(data),
mode = Mode(data),
max = max(data)
),
gof = "CvM"
)
# parametri della triangolare
a=fCvM$estimate[1]
b=fCvM$estimate[3]
c=fCvM$estimate[2]
a=as.numeric(a)
b=as.numeric(b)
c=as.numeric(c)
#split the triangular distribution into 2 pieces
f1=function(u){u^(-r)*2*(u-a)/((b-a)*(c-a))}
f2=function(u){u^(-r)*2*(b-u)/((b-a)*(b-c))}
#compute 2 approssimate integrals for each part
# from lower point to the mode c
i1=integrate(f1,a,c)
# from the mode c to the highest value
i2=integrate(f2,c,b)
# the moment is the sum of the integrals
mom=i1$value+i2$value
return(mom)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/triangular_moments_dis.R |
triangular_moments_dis_U=function(data,order){
r=order
# trovo la moda
Mode <- function(x, na.rm = FALSE) {
if (na.rm) {
x = x[!is.na(x)]
}
ux <- unique(x)
return(ux[which.max(tabulate(match(x, ux)))])
}
# fit della vc triangolare
fCvM <-
fitdistrplus::fitdist(
data,
"triang",
method = "mge",
start = list(
min = min(data),
mode = Mode(data),
max = max(data)
),
gof = "CvM"
)
# parametri della triangolare di U
param=c(fCvM$estimate[1], fCvM$estimate[3], fCvM$estimate[2])
a=1+param[1]/100
b=1+param[3]/100
c=1+param[2]/100
a=as.numeric(a)
b=as.numeric(b)
c=as.numeric(c)
#split the triangular distribution into 2 pieces
f1=function(u){u^(-r)*2*(u-a)/((b-a)*(c-a))}
f2=function(u){u^(-r)*2*(b-u)/((b-a)*(b-c))}
#compute 2 approssimate integrals for each part
# from lower point to the mode c
i1=integrate(f1,a,c)
# from the mode c to the highest value
i2=integrate(f2,c,b)
# the moment is the sum of the integrals
mom=i1$value+i2$value
return(mom)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/triangular_moments_dis_U.R |
triangular_parameters=function(data){
# trovo la moda
Mode <- function(x, na.rm = FALSE) {
if (na.rm) {
x = x[!is.na(x)]
}
ux <- unique(x)
return(ux[which.max(tabulate(match(x, ux)))])
}
# fit della vc triangolare
fCvM <-
fitdistrplus::fitdist(
data,
"triang",
method = "mge",
start = list(
min = min(data),
mode = Mode(data),
max = max(data)
),
gof = "CvM"
)
print(summary(fCvM))
plot(fCvM)
# parametri della triangolare
param=c(fCvM$estimate[1], fCvM$estimate[3], fCvM$estimate[2])
return(param)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/triangular_parameters.R |
triangular_parameters_U=function(data){
# trovo la moda
Mode <- function(x, na.rm = FALSE) {
if (na.rm) {
x = x[!is.na(x)]
}
ux <- unique(x)
return(ux[which.max(tabulate(match(x, ux)))])
}
# fit della vc triangolare
fCvM <-
fitdistrplus::fitdist(
data,
"triang",
method = "mge",
start = list(
min = min(data),
mode = Mode(data),
max = max(data)
),
gof = "CvM"
)
# parametri della triangolare di U
param=c(fCvM$estimate[1], fCvM$estimate[3], fCvM$estimate[2])
a=1+param[1]/100
b=1+param[3]/100
c=1+param[2]/100
return(c(a,b,c))
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/triangular_parameters_U.R |
variance_drv = function(data, years = 10) {
n = years
U = 1 + data
u = mean(U)
u2 = moment(U,
central = FALSE,
absolute = FALSE,
order = 2)
app1 = rep(NA, n - 1)
for (i in 1:(n - 1)) app1[i]=moment(U,
central = FALSE,
absolute = FALSE,
order = 2*i)
p1 = sum(app1)
app2 = matrix(NA, n,n)
# for (r in 1:nrow(app2)) for (s in 1:ncol(app2)) app2[r,s]=sum(r+s)
for (r in 1:nrow(app2)) for (s in 1:ncol(app2)) app2[r,s]=moment(U,
central = FALSE,
absolute = FALSE,
order = sum(r+s))
for (r in 1:nrow(app2)) for (s in 1:ncol(app2)) if (s<=r) app2[r,s]=0
app2[,n]=0
p2 = 2*sum(app2)
app3=rep(NA, n - 1)
for (i in 1:(n - 1)) app3[i]=moment(U,
central = FALSE,
absolute = FALSE,
order = i)
p3 =(sum(app3))^2
p4 =moment(U,
central = FALSE,
absolute = FALSE,
order = 2*n)
un=moment(U,
central = FALSE,
absolute = FALSE,
order = n)
p5=un^2
# vettore di appoggio per momenti da n+1 ad 2n-1
app6=rep(NA,(2*n)-(n+1))
# length(app6)
for (i in 1:length(app6)) app6[i]=moment(U,
central = FALSE,
absolute = FALSE,
order = n+i)
p6=2*sum(app6)
# vettore di appoggio per momenti da 1 ad n-1
app7=rep(NA,n-1)
for (i in 1:length(app7)) app7[i]=moment(U,
central = FALSE,
absolute = FALSE,
order = i)
p7=2*un*sum(app7)
var=p1+p2-p3+p4-p5+p6-p7
return(var)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/variance_drv.R |
variance_post_mood_nm=function(data,years=10){
n=years
U=1+data
u=mean(U)
u2=moment(U,
central = FALSE,
absolute = FALSE,
order = 2)
un=moment(U,
central = FALSE,
absolute = FALSE,
order = -n)
u2n=moment(U,
central = FALSE,
absolute = FALSE,
order = -2*n)
un1=moment(U,
central = FALSE,
absolute = FALSE,
order = -(n-1))
un2=moment(U,
central = FALSE,
absolute = FALSE,
order = -(n-2))
u2n1=moment(U,
central = FALSE,
absolute = FALSE,
order = -2*(n-1))
ex=1-un
ey=u-1
vx=u2n-un^2
vy=u2-u^2
covxy=-un1+un*u
var_nm=((ex/ey)^2)*((vx/(ex)^2)+(vy/(ey)^2)-(2*covxy/(ex*ey)))
return(var_nm)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/variance_post_mood_nm.R |
variance_post_mood_pm=function(data,years=10){
n=years
U=1+data
u=mean(U)
u2=moment(U,
central = FALSE,
absolute = FALSE,
order = 2)
un=moment(U,
central = FALSE,
absolute = FALSE,
order = n)
u2n=moment(U,
central = FALSE,
absolute = FALSE,
order = 2*n)
un1=moment(U,
central = FALSE,
absolute = FALSE,
order = (n+1))
un2=moment(U,
central = FALSE,
absolute = FALSE,
order = (n+2))
u2n1=moment(U,
central = FALSE,
absolute = FALSE,
order = 2*n+1)
u2n2=moment(U,
central = FALSE,
absolute = FALSE,
order = 2*n+2)
ex=un-1
ey=un1-un
vx=u2n-un^2
vy=u2n2-2*u2n1+u2n-(un1-un)^2
covxy=u2n1-un*un1-u2n+un^2
var_nm=((ex/ey)^2)*((vx/(ex)^2)+(vy/(ey)^2)-(2*covxy/(ex*ey)))
return(var_nm)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/variance_post_mood_pm.R |
variance_pre_mood_nm=function(data,years=10){
n=years
U=1+data
u=mean(U)
u2=moment(U,
central = FALSE,
absolute = FALSE,
order = 2)
un=moment(U,
central = FALSE,
absolute = FALSE,
order = -n)
u2n=moment(U,
central = FALSE,
absolute = FALSE,
order = -2*n)
un1=moment(U,
central = FALSE,
absolute = FALSE,
order = -(n-1))
un2=moment(U,
central = FALSE,
absolute = FALSE,
order = -(n-2))
u2n1=moment(U,
central = FALSE,
absolute = FALSE,
order = -2*(n-1))
ex=1-un1
ey=u-1
vx=u2-2*un2+u2n1-u^2+2*un1*u-un1^2
vy=u2-u^2
covxy=u2-u^2-un2+un1*u
var_nm=((ex/ey)^2)*((vx/(ex)^2)+(vy/(ey)^2)-(2*covxy/(ex*ey)))
return(var_nm)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/variance_pre_mood_nm.R |
variance_pre_mood_pm=function(data,years=10){
n=years
U=1+data
u=mean(U)
u2=moment(U,
central = FALSE,
absolute = FALSE,
order = 2)
un=moment(U,
central = FALSE,
absolute = FALSE,
order = n)
u2n=moment(U,
central = FALSE,
absolute = FALSE,
order = 2*n)
un1=moment(U,
central = FALSE,
absolute = FALSE,
order = (n-1))
un2=moment(U,
central = FALSE,
absolute = FALSE,
order = (n-2))
u2n1=moment(U,
central = FALSE,
absolute = FALSE,
order = 2*n-1)
u2n2=moment(U,
central = FALSE,
absolute = FALSE,
order = 2*n-2)
ex=un-1
ey=un-un1
vx=u2n-un^2
vy=u2n-2*u2n1+u2n2-(un-un1)^2
covxy=u2n-un^2-u2n1+un*un1
var_nm=((ex/ey)^2)*((vx/(ex)^2)+(vy/(ey)^2)-(2*covxy/(ex*ey)))
return(var_nm)
}
| /scratch/gouwar.j/cran-all/cranData/AnnuityRIR/R/variance_pre_mood_pm.R |
#' @title AntAngioCOOL
#' @description Machine learning based package to predict anti-angiogenic peptides using heterogeneous sequence descriptors.
#' @details AntAngioCOOL is a machine learning based package to predict anti-angiogenic peptides using heterogeneous sequence descriptors.
#' @details This package consists of three different predictors according to the obtained performances on independent test set: sensitive model, specific model and accurate model. These models have been build using the gold standard dataset that published by Ramaprasad et al. (Ettayapuram Ramaprasad et al., 2015).
#' @details Four different features have been used to encode peptides:
#' @details 1- Pseudo Amino Acid Composition (PseAAC) that has been used effectively in predicting cell penetrating peptides (Chen, Chu, Huang, Kong, & Cai, 2015). Despite the simple amino acid composition, PseAAC considers the sequence-order information of the peptide.
#' @details 2- K-mer composition that shows the fraction of all possible subsequences with length k in the given peptide. To compute k-mer composition features, reduced amino acid alphabet that proposed by Zahiri et al (Zahiri et al., 2014) has been exploited: the 20 alphabet of amino acids have been reduced to a new alphabet with size 8 according to 544 physicochemical and biochemical indices that extracted from AAIndex database (Kawashima et al., 2008) (C1={A, E}, C2={I, L, F, M, V}, C3={N, D, T, S}, C4={G}, C5={P}, C6={R, K, Q, H}, C7={Y, W}, C8={C}). We have computed k-mer composition for k=2,3,4 for each peptide.
#' @details 3- Physico-chemical profile : To compute these features, 544 different physico-chemical indices have been extracted from AAINDEX (Kawashima et al., 2008). To remove redundant indices, a subset of indices with correlation coefficient less than 0.8 and greater than -0.8 has been selected. This feature type for 5 amino acids of N- termini (5-NT) and C-termini (5-CT).
#' @details 4- Atomic profile : A 50-dimentional feature vector has been used to encode each peptide according to its atomic properties (frequency of five types of atoms: C, H, N, O, S). For details of atomic composition for each 20 natural amino acid see Kumar et al., 2015.
#' @details References
#' @details 1- Chen, L., Chu, C., Huang, T., Kong, X., & Cai, Y.-D. (2015). Prediction and analysis of cell-penetrating peptides using pseudo-amino acid composition and random forest models. Amino Acids, 47(7), 1485-93. http://doi.org/10.1007/s00726-015-1974-5
#' @details 2- Ettayapuram Ramaprasad, A. S., Singh, S., Gajendra P. S, R., Venkatesan, S., Brem, S., Cotran, R., . Stephens, R. (2015). AntiAngioPred: A Server for Prediction of Anti-Angiogenic Peptides. PLOS ONE, 10(9), e0136990. http://doi.org/10.1371/journal.pone.0136990
#' @details 3- Kawashima, S., Pokarowski, P., Pokarowska, M., Kolinski, A., Katayama, T., & Kanehisa, M. (2008). AAindex: amino acid index database, progress report 2008. Nucleic Acids Research, 36(Database issue), D202-5. http://doi.org/10.1093/nar/gkm998
#' @details 3- Kumar, R., Chaudhary, K., Singh Chauhan, J., Nagpal, G., Kumar, R., Sharma, M., & Raghava, G. P. S. (2015). An in silico platform for predicting, screening and designing of antihypertensive peptides. Scientific Reports, 5, 12512. http://doi.org/10.1038/srep12512
#' @details 4- Zahiri, J., Mohammad-Noori, M., Ebrahimpour, R., Saadat, S., Bozorgmehr, J. H., Goldberg, T., & Masoudi-Nejad, A. (2014). LocFuse: Human protein-protein interaction prediction via classifier fusion using protein localization information. Genomics, 104(6), 496-503.
#' @author Babak Khorsand
#' @import caret
#' @import rJava
#' @import RWeka
#' @import rpart
#' @importFrom stats predict
#' @export AntAngioCOOL
#' @param Input_Sequence A peptide sequence
#' @param Classifier 1 if you want to get the prediction from model with maximum Accuracy (according to the independent test reasults), 2 if maximum Sensivity is desired and 3 if maximum Specefity is desired.
#' @param SF if True then all 2343 selected features (out of 175062 features) that had been used for prediction will be returned.
#' @param AF if True then all 175062 extracted features will be returned.
#' @return If Predicted class (Anti-angiogenic/ Not anti-angiogenic) of the input peptide and a subset of descriptors upon request.
#' @examples
#' AntAngioCOOL("AAPFLECQGN",2,SF=TRUE)
AntAngioCOOL = function(Input_Sequence,Classifier=1,SF=FALSE,AF=FALSE)
{
Seq_Length = nchar(Input_Sequence)
if(Seq_Length<10)
{
stop("Input Sequence must have length more than 10")
}else
{
Onemer=Features[which(Features=="A"):which(Features=="V")]
Twomers=Features[which(Features=="AA"):which(Features=="VV")]
Threemers=Features[which(Features=="AAA"):which(Features=="VVV")]
Fourmers=Features[which(Features=="AAAA"):which(Features=="VVVV")]
# A,AA,AAA,AAAA ----
Seq_Num=1:Seq_Length
Sequence="z"
Sequence= sapply(Seq_Num,function(i) c(Sequence,substr(Input_Sequence,i,i)))
Sequence=Sequence[2,]
Twomer_Seq="AA"
Seq_Num=1:(Seq_Length-1)
Twomer_Seq=sapply(Seq_Num, function(i) c(Twomer_Seq,paste(Sequence[i],Sequence[i+1],sep="")))
Twomer_Seq=Twomer_Seq[2,1:(Seq_Length-1)]
Threemer_Seq="AAA"
Seq_Num=1:(Seq_Length-2)
Threemer_Seq=sapply(Seq_Num, function(i) c(Threemer_Seq,paste(Sequence[i],Sequence[i+1],Sequence[i+2],sep="")))
Threemer_Seq=Threemer_Seq[2,1:(Seq_Length-2)]
Fourmer_Seq="AAAA"
Seq_Num=1:(Seq_Length-3)
Fourmer_Seq=sapply(Seq_Num, function(i) c(Fourmer_Seq,paste(Sequence[i],Sequence[i+1],Sequence[i+2],Sequence[i+3],sep="")))
Fourmer_Seq=Fourmer_Seq[2,1:(Seq_Length-3)]
Onemer_Seq_table=table(Sequence)
Feature_Onemer=0
Feature_Onemer = sapply(Onemer, function(x) c(Feature_Onemer,ifelse(length(grep(x,Sequence))>0,(Onemer_Seq_table[x]/length(Onemer)),0)))
Feature_Onemer=Feature_Onemer[2,]
names(Feature_Onemer)=Onemer
Twomer_Seq_table=table(Twomer_Seq)
Feature_Twomers=0
Feature_Twomers = sapply(Twomers, function(x) c(Feature_Twomers,ifelse(length(grep(x,Twomer_Seq))>0,(Twomer_Seq_table[x]/length(Twomers)),0)))
Feature_Twomers=Feature_Twomers[2,]
names(Feature_Twomers)=Twomers
Threemer_Seq_table=table(Threemer_Seq)
Feature_Threemers=0
Feature_Threemers = sapply(Threemers, function(x) c(Feature_Threemers,ifelse(length(grep(x,Threemer_Seq))>0,(Threemer_Seq_table[x]/length(Threemers)),0)))
Feature_Threemers=Feature_Threemers[2,]
names(Feature_Threemers)=Threemers
Fourmer_Seq_table=table(Fourmer_Seq)
Feature_Fourmers=0
Feature_Fourmers = sapply(Fourmers, function(x) c(Feature_Fourmers,ifelse(length(grep(x,Fourmer_Seq))>0,(Fourmer_Seq_table[x]/length(Fourmers)),0)))
Feature_Fourmers=Feature_Fourmers[2,]
names(Feature_Fourmers)=Fourmers
Extracted_Features=c(Feature_Onemer,Feature_Twomers,Feature_Threemers,Feature_Fourmers)
# Amino8 ----
Amino8 = Input_Sequence
Amino8 = gsub("A","a",Amino8)
Amino8 = gsub("E","a",Amino8)
Amino8 = gsub("I","b",Amino8)
Amino8 = gsub("L","b",Amino8)
Amino8 = gsub("F","b",Amino8)
Amino8 = gsub("M","b",Amino8)
Amino8 = gsub("V","b",Amino8)
Amino8 = gsub("N","c",Amino8)
Amino8 = gsub("D","c",Amino8)
Amino8 = gsub("T","c",Amino8)
Amino8 = gsub("S","c",Amino8)
Amino8 = gsub("G","d",Amino8)
Amino8 = gsub("P","e",Amino8)
Amino8 = gsub("R","f",Amino8)
Amino8 = gsub("K","f",Amino8)
Amino8 = gsub("Q","f",Amino8)
Amino8 = gsub("H","f",Amino8)
Amino8 = gsub("Y","g",Amino8)
Amino8 = gsub("W","g",Amino8)
Amino8 = gsub("C","h",Amino8)
Onemer=Features[which(Features=="a"):which(Features=="h")]
Twomers=Features[which(Features=="aa"):which(Features=="hh")]
Threemers=Features[which(Features=="aaa"):which(Features=="hhh")]
Fourmers=Features[which(Features=="aaaa"):which(Features=="hhhh")]
# a,aa,aaa,aaaa ----
Seq_Num=1:Seq_Length
Sequence="z"
Sequence= sapply(Seq_Num,function(i) c(Sequence,substr(Input_Sequence,i,i)))
Sequence=Sequence[2,]
Twomer_Seq="AA"
Seq_Num=1:(Seq_Length-1)
Twomer_Seq=sapply(Seq_Num, function(i) c(Twomer_Seq,paste(Sequence[i],Sequence[i+1],sep="")))
Twomer_Seq=Twomer_Seq[2,1:(Seq_Length-1)]
Threemer_Seq="AAA"
Seq_Num=1:(Seq_Length-2)
Threemer_Seq=sapply(Seq_Num, function(i) c(Threemer_Seq,paste(Sequence[i],Sequence[i+1],Sequence[i+2],sep="")))
Threemer_Seq=Threemer_Seq[2,1:(Seq_Length-2)]
Fourmer_Seq="AAAA"
Seq_Num=1:(Seq_Length-3)
Fourmer_Seq=sapply(Seq_Num, function(i) c(Fourmer_Seq,paste(Sequence[i],Sequence[i+1],Sequence[i+2],Sequence[i+3],sep="")))
Fourmer_Seq=Fourmer_Seq[2,1:(Seq_Length-3)]
Onemer_Seq_table=table(Sequence)
Feature_Onemer=0
Feature_Onemer = sapply(Onemer, function(x) c(Feature_Onemer,ifelse(length(grep(x,Sequence))>0,(Onemer_Seq_table[x]/length(Onemer)),0)))
Feature_Onemer=Feature_Onemer[2,]
names(Feature_Onemer)=Onemer
Twomer_Seq_table=table(Twomer_Seq)
Feature_Twomers=0
Feature_Twomers = sapply(Twomers, function(x) c(Feature_Twomers,ifelse(length(grep(x,Twomer_Seq))>0,(Twomer_Seq_table[x]/length(Twomers)),0)))
Feature_Twomers=Feature_Twomers[2,]
names(Feature_Twomers)=Twomers
Threemer_Seq_table=table(Threemer_Seq)
Feature_Threemers=0
Feature_Threemers = sapply(Threemers, function(x) c(Feature_Threemers,ifelse(length(grep(x,Threemer_Seq))>0,(Threemer_Seq_table[x]/length(Threemers)),0)))
Feature_Threemers=Feature_Threemers[2,]
names(Feature_Threemers)=Threemers
Fourmer_Seq_table=table(Fourmer_Seq)
Feature_Fourmers=0
Feature_Fourmers = sapply(Fourmers, function(x) c(Feature_Fourmers,ifelse(length(grep(x,Fourmer_Seq))>0,(Fourmer_Seq_table[x]/length(Fourmers)),0)))
Feature_Fourmers=Feature_Fourmers[2,]
names(Feature_Fourmers)=Fourmers
Extracted_Features=c(Extracted_Features,Feature_Onemer,Feature_Twomers,Feature_Threemers,Feature_Fourmers)
# Atomic Profile ----
Seq_Num=1:Seq_Length
Sequence="z"
Sequence= sapply(Seq_Num,function(i) c(Sequence,substr(Input_Sequence,i,i)))
Sequence=Sequence[2,]
for (i in 1:5)
{
temp = Atomic_Profile[Atomic_Profile$AminoAcids==Sequence[i],2:9]
names(temp)=paste(names(temp),"_C",i,sep = "")
temp=sapply(temp, function(x) as.numeric(as.character(x)))
Extracted_Features=c(Extracted_Features,temp)
temp = Atomic_Profile[Atomic_Profile$AminoAcids==Sequence[(Seq_Length-5+i)],2:9]
names(temp)=paste(names(temp),"_N",i,sep = "")
temp=sapply(temp, function(x) as.numeric(as.character(x)))
Extracted_Features=c(Extracted_Features,temp)
}
# PhysicoChemical AAC ----
for (i in 1:5)
{
PhysicoChemical_AAC = AAIndex193_Table[Sequence[i]]
PhysicoChemical_AAC=PhysicoChemical_AAC[,1]
names(PhysicoChemical_AAC)=paste(AAIndex193_Table[[1]],"_C",i,sep = "")
PhysicoChemical_AAC
Extracted_Features=c(Extracted_Features,PhysicoChemical_AAC)
PhysicoChemical_AAC = AAIndex193_Table[Sequence[Seq_Length-5+i]]
PhysicoChemical_AAC=PhysicoChemical_AAC[,1]
names(PhysicoChemical_AAC)=paste(AAIndex193_Table[[1]],"_N",i,sep = "")
Extracted_Features=c(Extracted_Features,PhysicoChemical_AAC)
}
AllFeatures=Extracted_Features
Extracted_Features=Extracted_Features[-nzv]
Extracted_Features=data.frame(Extracted_Features,stringsAsFactors = F)
Extracted_Features[,1]=as.numeric(Extracted_Features[,1])
Extracted_Features=t(Extracted_Features)
Extracted_Features=predict(standardObj,Extracted_Features)
if (Classifier==2)
{
Result=predict(modelFit2,Extracted_Features)
Result=ifelse(Result==0,"Query peptide is NOT Anti-Angiogenic","Query peptide is Anti-Angiogenic")
}else if (Classifier==3)
{
Result=predict(modelFit3,Extracted_Features,type="prob")
Result=ifelse(Result[1,1]>Result[1,2],paste("Query peptide is NOT Anti-Angiogenic (Prediction Probability: ",round(Result[1,1],2),")",sep=""),paste("Query peptide is Anti-Angiogenic (Prediction Probability: ",round(Result[1,2],2),")",sep=""))
}else
{
Result=predict(modelFit1,Extracted_Features,type="prob")
Result=ifelse(Result[1,1]>Result[1,2],paste("Query peptide is NOT Anti-Angiogenic (Prediction Probability: ",round(Result[1,1],2),")",sep=""),paste("Query peptide is Anti-Angiogenic (Prediction Probability: ",round(Result[1,2],2),")",sep=""))
}
if (SF)
{
if (AF)
{
Result_List=list(Prediction_Result=Result,Selected_Features=Extracted_Features,All_Features=AllFeatures)
}else{
Result_List=list(Prediction_Result=Result,Selected_Features=Extracted_Features)
}
}else{
if (AF)
{
Result_List=list(Prediction_Result=Result,All_Features=AllFeatures)
}else{return(Result)}
}
return(Result_List)
}
}
| /scratch/gouwar.j/cran-all/cranData/AntAngioCOOL/R/AntAngiCOOL.R |
#######################################################################################
###############
############### AntMAN Package
###############
###############
#######################################################################################
# #' Sequentially Allocated Latent Structure Optimisation
# #'
# #' Heuristic partitioning to minimise the expected Binder loss function
# #' with respect to a given expected adjacency matrix.
# #'
# #' @param fit an \code{\link{AM_mcmc_output}} object.
# #' @param maxClusts Maximum number of clusters.
# #' The actual number of clusters searched may be lower.
# #' If set to 0L, the maximum is automatically limited by the number of items.
# #' @param Const_Binder Relative penalty in the Binder loss function
# #' for false-positives vis-a-vis false-negatives.
# #' Must be a real number in the interval \[0, 1\].
# #' @param batchSize Number of permutations scanned per thread.
# #' If set to 0L, the thread will continue to scan permutations until it times out
# #' (in which case \code{timeLimit} cannot be 0L).
# #' @param nScans Number of scans for each permutation.
# #' @param maxThreads Maximum number of threads to use.
# #' If set to 0L (default), the maximum number of threads
# #' will be determined by the runtime.
# #' Set to 1L for no parallelisation.
# #' The actual number of threads used may be lower than \code{maxThreads}.
# #' @param timeLimit Maximum computation time for each thread in milliseconds.
# #' The actual computational time may be higher,
# #' since the time limit is only checked at the end of each iteration.
# #' If set to 0L, the thread will never time out
# #' (in which case \code{batchSize} cannot be 0L).
# #' @return A list containing the following items:
# #' \itemize{
# #' \item \code{Labels} - the vector of partition labels.
# #' \item \code{BinderLoss} - the associated binder loss function.
# #' \item \code{NumClusts} - the number of clusters found.
# #' \item \code{NumPermutations} - the number of permutations actually scanned.
# #' \item \code{WallClockTime} - cumulative wall-clock time used by all threads in milliseconds.
# #' \item \code{TimeLimitReached} - whether the computation time limit was reached in any of the threads.
# #' \item \code{NumThreads} - actual number of threads used.
# #' }
# #'@export
# AM_binder <- function(fit, maxClusts=0L, Const_Binder = 0.5, batchSize = 1000L, nScans = 10L, maxThreads = 0L, timeLimit = 600000L) {
# eam = AM_coclustering(fit)
# if (!is.validAdjacencyMatrix(eam)){
# stop(paste("eam must be a symmetric matrix with values between 0 and 1, ",
# "and 1s on the diagonal."))
# }
# if (!is.finiteInteger(maxClusts) |
# maxClusts < 0) {
# stop("maxClusts must be a nonnegative integer. ")
# }
# if (!is.nonNegNumberLessThan1(Const_Binder)) {
# stop("Const_Binder must be a number between 0 and 1.")
# }
# if (!is.finiteInteger(batchSize) |
# batchSize < 0) {
# stop("batchSize must be a nonnegative integer.")
# }
# if (!is.finiteInteger(nScans) |
# nScans <= 0) {
# stop("nScans must be a positive integer.")
# }
# if (!is.finiteInteger(maxThreads) |
# maxThreads < 0) {
# stop("maxThreads must be a nonnegative integer.")
# }
# if (!is.finiteInteger(timeLimit) |
# timeLimit < 0) {
# stop("timeLimit must be a nonnegative integer.")
# }
# if (timeLimit == 0L & batchSize == 0L) {
# stop("batchSize and timeLimit cannot both be 0.")
# }
# temp = .salso(eam, maxClusts, Const_Binder, batchSize, nScans, maxThreads, timeLimit)
# temp[["Labels"]] <- as.integer(as.vector(temp[["Labels"]]))
# return (temp)
# }
# #' Compute the Binder loss function
# #'
# #' Compute the Binder loss function of a partitioning
# #' with respect to an expected adjacency matrix.
# #'
# #' @param eam Expected Adjacency Matrix, i.e.,
# #' the matrix whose entries \eqn{E_{ij}} is the posterior probability
# #' that items \eqn{i} and \eqn{j} are together.
# #' If the partitioning is already known, this is just the adjacency matrix.
# #' @param labels vector of partition labels. Must be integers.
# #' @param Const_Binder Relative penalty in the Binder loss function
# #' for false-positives vis-a-vis false-negatives.
# #' Must be a real number in the interval \[0, 1\].
# #' @return The value of the Binder loss function of the given partition labels
# #' with respect to the given pairwise allocation matrix.
# #'@export
# AM_compute_binder_loss <- function(eam, labels, Const_Binder = 0.5){
# if (!is.validAdjacencyMatrix(eam)){
# stop(paste("eam must be a symmetric matrix with values between 0 and 1, ",
# "and 1s on the diagonal."))
# }
# if (!all(is.finiteInteger(labels))) {
# stop("labels must be a vector of integers.")
# }
# if (length(labels) != ncol(eam)) {
# stop("Incompatible size of eam and labels.")
# }
# return (.computeBinderLoss(eam, labels, Const_Binder))
# }
# #' Binder distance of two partitions
# #'
# #' Compute the binder loss function of a partitioning
# #' with respect to the adjacency matrix of another partitioning.
# #' @param testLabels The vector of integer labels of the partitioning.
# #' @param refLabels The vector of partition labels to use to construct the adjacency matrix.
# #' @param Const_Binder Relative penalty in the Binder loss function
# #' for false-positives vis-a-vis false-negatives.
# #' Must be a real number in the interval \[0, 1\].
# #' @return The value of the Binder loss function of \code{testLabels}
# #' with respect to the adjacency matrix of \code{refLabels}.
# #'@export
# AM_compute_binder_distance <- function(testLabels, refLabels, Const_Binder) {
# if (!all(is.finiteInteger(testLabels))) {
# stop("labels must be a vector of integers.")
# }
# if (!all(is.finiteInteger(refLabels))) {
# stop("labels must be a vector of integers.")
# }
# if (!is.nonNegNumberLessThan1(Const_Binder)) {
# stop("Const_Binder must be a number between 0 and 1.")
# }
# return(computeBinderLoss(computeAdjacencyMatrix(refLabels), testLabels, Const_Binder))
# }
# is.validAdjacencyMatrix <- function(p) {
# return(all(is.nonNegNumberLessThan1(p)) &
# nrow(p) == ncol(p) &
# all(p == t(p)) &
# sum(diag(p)) == nrow(p))
# }
# is.finiteInteger <- function(x) {
# return (is.integer(x) & is.finite(x))
# }
# is.nonNegNumberLessThan1 <- function(x) {
# return (is.numeric(x) & is.finite(x) & x <= 1 & x >= 0)
# }
#' Sequentially Allocated Latent Structure Optimisation
#'
#' Heuristic partitioning to minimise the expected loss function
#' with respect to a given expected adjacency matrix. This function is built upon R-package salso's implementation of the
#' \code{salso} function. See salso \insertCite{salso}{AntMAN} for more details.
#'
#' @param eam a co-clustering/ clustering matrix. See salso for more information on which matrix to use.
#' @param loss the recommended loss functions to be used are the "binder" or "VI". However, other loss functions that are supported
#' can be found in the R-package salso's salso function.
#' @param maxNClusters Maximum number of clusters to be considered.
#' The actual number of clusters searched may be lower. Default is 0.
#' @param nRuns Number of runs to try. Default is 16.
#' @param maxZealousAttempts Maximum number of tries for zealous updates. Default is 10. See salso for more information.
#' The actual number of clusters searched may be lower.
#' @param nRuns Number of runs to try.
#' @param maxZealousAttempts Maximum number of tries for zealous updates. See salso for more information.
#' @param probSequentialAllocation The probability of using sequential allocation instead of random sampling via sample(1:K,ncol(x),TRUE),
#' where K is maxNClusters. Default is 0.5. See salso for more information.
#' argument.
#' @param nCores Number of CPU cores to engage. Default is 0.
#'@source David B. Dahl and Devin J. Johnson and Peter Müller (2021). salso: Search Algorithms and Loss Functions for Bayesian Clustering. R package version 0.2.15.
#'@return A numeric vector describing the estimated partition. The integer values represent the cluster labels of each item respectively.
#'@importFrom salso salso
#'@export
AM_salso = function(eam, loss, maxNClusters = 0, nRuns = 16, maxZealousAttempts = 10, probSequentialAllocation = 0.5, nCores = 0){
return(salso(eam, loss, maxNClusters, nRuns, maxZealousAttempts, probSequentialAllocation, nCores))
} | /scratch/gouwar.j/cran-all/cranData/AntMAN/R/AM_binder.R |
#######################################################################################
###############
############### AntMAN Package
###############
###############
#######################################################################################
#' Return the co-clustering matrix
#'
#'
#' Given an \code{\link{AM_mcmc_output}} object, this function returns the co-clustering matrix.
#'
#' The co-clustering matrix is produced by the simultaneous clustering of the rows and columns. Each entry denotes the (posterior) probability
#' that items \eqn{i} and \eqn{j} are together. This technique is also known as
#' bi-clustering and block clustering \insertCite{govaert2013co}{AntMAN}, and is useful for understanding the number of clusters in the dataset.
#'
#'@param fit an \code{\link{AM_mcmc_output}} object.
#'@return A numeric co-clustering matrix
#'@seealso \code{\link{AM_clustering}}
#'
#'@examples
#'\donttest{
#' fit = AM_demo_uvp_poi()$fit
#'ccm <- AM_coclustering(fit)
#'}
#'@export
AM_coclustering = function (fit) {
CI = as.matrix((AM_extract(fit, c("CI")))[["CI"]]);
n_save <- dim(CI)[1]
N <- dim(CI)[2]
c_out <- lapply(1:n_save, function(x){outer(CI[x,], CI[x,], "==")})
pij = Reduce("+", c_out)/n_save
#cast pij into matrix
pij = matrix(unlist(pij), ncol=N, nrow=N, byrow=F)
return(coclustering_probability = pij);
}
#' Return the clustering matrix
#'
#'
#' Given an \code{\link{AM_mcmc_output}} object, this function returns the clustering matrix.
#'
#' The clustering matrix is an M by n matrix. Each of the M rows represents a clustering of n items
#' using cluster labels. Items i and j are in the same cluster if fit\[m,i\] == fit\[m,j\] for the mth clustering.
#'@param fit an \code{\link{AM_mcmc_output}} object.
#'@return A numeric clustering matrix
#'@export
#'@seealso \code{\link{AM_coclustering}}
#'
#'@examples
#'\donttest{
#' fit = AM_demo_uvp_poi()$fit
#'ccm <- AM_clustering(fit)
#'}
AM_clustering = function (fit) {
CI = as.matrix((AM_extract(fit, c("CI")))[["CI"]]);
return(CI);
}
| /scratch/gouwar.j/cran-all/cranData/AntMAN/R/AM_coclustering.R |
#######################################################################################
###############
############### AntMAN Package
###############
###############
#######################################################################################
#' Returns an example of \code{\link{AM_mcmc_fit}} output produced by the multivariate bernoulli model
#'
#'
#' This function allows us to generate a sample output of fitting the multivariate Bernoulli model. No arguments are needed to be passed.
#' The purpose of this function is to serve as a demo for users to understand the model's output, without diving too deep into details. By default,
#' this demo generates a sample dataset of dimension 500x4, where the MCMC sampler is specified to run for 2000 iterations, with a burn-in of 1000, and a thinning interval of 10. All possible outputs
#' that can be produced by \code{\link{AM_mcmc_fit}} are returned (see return value below).
#'
#' @return A list containing the following items:
#' \itemize{
#' \item the vector (or matrix) containing the synthetic data used to fit the model.
#' \item the vector containing the final cluster assignment of each observation.
#' \item an \code{\link{AM_mcmc_output}} object, which is the typical output of \code{\link{AM_mcmc_fit}}.
#' }
#'
#' @keywords demo
#' @export
#'
#' @examples
#' \donttest{
#' mvb_output <- AM_demo_mvb_poi()
#' }
AM_demo_mvb_poi = function () {
d <- 4
k <- 3
TH <- matrix(nrow=k,ncol=d)
TH[1,] <- c(0.9,0.0,0.2,0.1)
TH[2,] <- c(0.0,0.9,0.1,0.2)
TH[3,] <- c(0.0,0.0,0.9,0.9)
demo_multivariate_binomial <- AM_sample_multibin(n=500,d,c(0.3,0.3,0.4),TH)
y_mvb <- demo_multivariate_binomial$y
ci_mvb <- demo_multivariate_binomial$ci
mixture_mvb_params = AM_mix_hyperparams_multiber (a0= c(1,1,1,1),b0= c(1,1,1,1))
mcmc_params = AM_mcmc_parameters(niter=2000, burnin=1000, thin=10, verbose=0, output=c("ALL"))
components_prior = AM_mix_components_prior_pois (init=3, a=1, b=1)
weights_prior = AM_mix_weights_prior_gamma(init=2, a=1, b=1)
fit <- AM_mcmc_fit(
y = y_mvb,
mix_kernel_hyperparams = mixture_mvb_params,
mix_components_prior =components_prior,
mix_weight_prior = weights_prior,
mcmc_parameters = mcmc_params)
return (list(input = y_mvb, clusters = ci_mvb, fit = fit))
}
#' Returns an example of \code{\link{AM_mcmc_fit}} output produced by the multivariate gaussian model
#'
#'
#'This function allows us to generate a sample output of fitting the multivariate Gaussian model. No arguments are needed to be passed.
#' The purpose of this function is to serve as a demo for users to understand the model's output, without diving too deep into details. By default,
#' this demo generates a sample dataset of dimension 500x2, where the MCMC sampler is specified to run for 2000 iterations, with a burn-in of 1000, and a thinning interval of 10. All possible outputs
#' that can be produced by \code{\link{AM_mcmc_fit}} are returned (see return value below).
#'
#' @return A list containing the following items:
#' \itemize{
#' \item the vector (or matrix) containing the synthetic data used to fit the model.
#' \item the vector containing the final cluster assignment of each observation.
#' \item an \code{\link{AM_mcmc_output}} object, which is the typical output of \code{\link{AM_mcmc_fit}}.
#' }
#'
#' @keywords demo
#' @export
#'
#' @examples
#' \donttest{
#' mvn_output <- AM_demo_mvn_poi()
#' }
AM_demo_mvn_poi = function () {
MU <- matrix(nrow=3,ncol=2)
MU[1,] <- c(0,0)
MU[2,] <- c(-3,-3)
MU[3,] <- c(4,4)
sig1 <- c(1,1)
rho1 <- 0
Sig1 <- matrix(c(sig1[1]^2,rho1*sig1[1]*sig1[2], rho1*sig1[1]*sig1[2],sig1[2]^2),byrow=TRUE,nrow=2)
sig2 <- c(1,1)
rho2 <- -0.7
Sig2 <- matrix(c(sig2[1]^2,rho2*sig2[1]*sig2[2], rho2*sig2[1]*sig2[2],sig2[2]^2),byrow=TRUE,nrow=2)
sig3 <- c(1,1)
rho3 <- -0.3
Sig3 <- matrix(c(sig3[1]^2,rho3*sig3[1]*sig3[2], rho3*sig3[1]*sig3[2],sig3[2]^2),byrow=TRUE,nrow=2)
SIG <- array(0,dim=c(3,2,2))
SIG[1,,] <- Sig1
SIG[2,,] <- Sig2
SIG[3,,] <- Sig3
demo_multivariate_normal <-AM_sample_multinorm(n = 500 ,d = 2,c(0.3,0.3,0.4),MU,SIG)
y_mvn <- demo_multivariate_normal$y
ci_mvn <- demo_multivariate_normal$ci
mixture_mvn_params = AM_mix_hyperparams_multinorm (mu0=c(0,0),ka0=1,nu0=4,Lam0=diag(2))
mcmc_params = AM_mcmc_parameters(niter=2000, burnin=1000, thin=10, verbose=0, output=c("ALL"))
components_prior = AM_mix_components_prior_pois (init=3, a=1, b=1)
weights_prior = AM_mix_weights_prior_gamma(init=2, a=1, b=1)
fit <- AM_mcmc_fit(
y = y_mvn,
mix_kernel_hyperparams = mixture_mvn_params,
mix_components_prior =components_prior,
mix_weight_prior = weights_prior,
mcmc_parameters = mcmc_params)
return (list(input = y_mvn, clusters = ci_mvn, fit = fit))
}
##' Returns an example of \code{\link{AM_mcmc_fit}} output produced by the univariate Gaussian model
#'
#'
#'This function allows us to generate a sample output of fitting the univariate gaussian model. No arguments are needed to be passed.
#' The purpose of this function is to serve as a demo for users to understand the model's output, without diving too deep into details. By default,
#' this demo generates a sample dataset of dimension 500x1, where the MCMC sampler is specified to run for 2000 iterations, with a burn-in of 1000, and a thinning interval of 10. All possible outputs
#' that can be produced by \code{\link{AM_mcmc_fit}} are returned (see return value below).
#'
#' @return A list containing the following items:
#' \itemize{
#' \item the vector (or matrix) containing the synthetic data used to fit the model.
#' \item the vector containing the final cluster assignment of each observation.
#' \item an \code{\link{AM_mcmc_output}} object, which is the typical output of \code{\link{AM_mcmc_fit}}.
#' }
#'
#' @keywords demo
#' @export
#'
#' @examples
#' \donttest{
#' mvn_output <- AM_demo_uvn_poi()
#' }
AM_demo_uvn_poi = function () {
demo_univariate_normal <-AM_sample_uninorm(n = 500, pro=c(0.2,0.5,0.3),mmu=c(-2.1,0,2.3),ssd=c(0.5,0.5,0.5))
y_uvn <- demo_univariate_normal$y
ci_uvn <- demo_univariate_normal$ci
##############################################################################
### PREPARE THE GIBBS for Normal mixture with poisson gamma priors
##############################################################################
mixture_uvn_params = AM_mix_hyperparams_uninorm (m0=0,k0=0.1,nu0=1,sig02=1.5)
mcmc_params = AM_mcmc_parameters(niter=2000, burnin=1000, thin=10, verbose=0, output=c("ALL"))
components_prior = AM_mix_components_prior_pois (init=3, a=1, b=1)
weights_prior = AM_mix_weights_prior_gamma(init=2, a=1, b=1)
fit <- AM_mcmc_fit(
y = y_uvn,
mix_kernel_hyperparams = mixture_uvn_params,
mix_components_prior =components_prior,
mix_weight_prior = weights_prior,
mcmc_parameters = mcmc_params)
return (list(input = y_uvn, clusters = ci_uvn, fit = fit))
}
##' Returns an example of \code{\link{AM_mcmc_fit}} output produced by the univariate Poisson model
#'
#'
#'This function allows us to generate a sample output of fitting the univariate poisson model. No arguments are needed to be passed.
#' The purpose of this function is to serve as a demo for users to understand the model's output, without diving too deep into details. By default,
#' this demo generates a sample dataset of dimension 500x1, where the MCMC sampler is specified to run for 2000 iterations, with a burn-in of 1000, and a thinning interval of 10. All possible outputs
#' that can be produced by \code{\link{AM_mcmc_fit}} are returned (see return value below).
#'
#' @return A list containing the following items:
#' \itemize{
#' \item the vector (or matrix) containing the synthetic data used to fit the model.
#' \item the vector containing the final cluster assignment of each observation.
#' \item an \code{\link{AM_mcmc_output}} object, which is the typical output of \code{\link{AM_mcmc_fit}}.
#' }
#'
#' @keywords demo
#' @export
#'
#' @examples
#' \donttest{
#' mvn_output <- AM_demo_uvn_poi()
#' }
AM_demo_uvp_poi = function () {
demo_univariate_poisson <-AM_sample_unipois(n = 500, pro=c(0.2,0.5,0.3))
y_uvp <- demo_univariate_poisson$y
ci_uvp <- demo_univariate_poisson$ci
mixture_uvn_params = AM_mix_hyperparams_unipois (alpha0=1, beta0=1)
mcmc_params = AM_mcmc_parameters(niter=2000, burnin=1000, thin=10, verbose=0, output=c("ALL"))
components_prior = AM_mix_components_prior_pois (init=3, a=1, b=1)
weights_prior = AM_mix_weights_prior_gamma(init=2, a=1, b=1)
fit <- AM_mcmc_fit(
y = y_uvp,
mix_kernel_hyperparams = mixture_uvn_params,
mix_components_prior =components_prior,
mix_weight_prior = weights_prior,
mcmc_parameters = mcmc_params)
return (list(input = y_uvp, clusters = ci_uvp, fit = fit))
}
| /scratch/gouwar.j/cran-all/cranData/AntMAN/R/AM_demo.R |
#######################################################################################
###############
############### AntMAN Package
###############
###############
#######################################################################################
#' compute the hyperparameters of an Normal-Inverse-Gamma distribution using an empirical Bayes approach
#'
#' This function computes the hyperparameters of a Normal Inverse-Gamma distribution using an empirical Bayes approach.
#' More information about how these hyperparameters are determined can be found here:
#' \emph{Bayes and empirical Bayes: do they merge?} \insertCite{petrone2012bayes}{AntMAN}.
#'
#'@param y The data y. If y is univariate, a vector is expected. Otherwise, y should be a matrix.
#'@param scEmu a positive value (default=1) such that marginally E(\eqn{\mu}) = \eqn{s^2}*scEmu, where \eqn{s^2} is the
#'sample variance.
#'@param scEsig2 a positive value (default=3) such that marginally E(\eqn{\sigma^2}) = \eqn{s^2}*scEsig2, where \eqn{s^2} is the
#'sample variance.
#'@param CVsig2 The coefficient of variation of \eqn{\sigma^2} (default=3).
#'
#'@return an object of class \code{\link{AM_mix_hyperparams}}, in which hyperparameters \code{m0}, \code{k0},
#' \code{nu0} and \code{sig02} are specified. To understand the usage of these hyperparameters, please refer to
#' \code{\link{AM_mix_hyperparams_uninorm}}.
#'@export
AM_emp_bayes_uninorm = function(y,scEmu=1,scEsig2=3,CVsig2=3){
n <- length(y) ### sample size
bary <- mean(y) ### sample mean
s2y <- var(y) ### sample variance
Emu <- bary
Vmu <- s2y*scEmu
Esig2 <- s2y/scEsig2
Vsig2 <- CVsig2^2*Esig2^2
m0 = Emu
nu0 = 2*(Esig2)^2/Vsig2+4
sig02 = Esig2*(nu0-2)/nu0
k0 = sig02/Vmu * nu0/(nu0-2)
return(AM_mix_hyperparams_uninorm(m0=m0,nu0=nu0,sig02=sig02,k0=k0))
}
| /scratch/gouwar.j/cran-all/cranData/AntMAN/R/AM_emp_bayes.R |
#######################################################################################
###############
############### AntMAN Package
###############
###############
#######################################################################################
## INTERNAL
generate_column_names = function(target, r) {
values = NULL;
if (length(r) == 1) {
values = append( values , sprintf ( "%s", target ) );
} else {
for (i in r) {
values = append( values , sprintf ( "%s_%d", target , i) );
}
}
return (values);
}
## INTERNAL
extract_target = function(fit, target, iterations = NULL, debug = FALSE){
result = NULL
mainpath = strsplit(target, "_")[[1]]
if (debug) message("path = ", paste(mainpath,collapse = " "), "\n");
if (length(mainpath) == 0) {
warning("ERROR Invalid variable name(too small)\n");
return (NULL);
}
variable_name = mainpath[1];
if (debug) message(" - variable_name = ", variable_name, "\n");
if (!is.element(variable_name , names(fit))) {
warning("ERROR Invalid variable name '",variable_name, "' has not been found)\n");
return (NULL);
}
# level 1 - get variable
variable = fit[[variable_name]];
if (debug) message(" - variable taken, class = ",class(variable),", length = ",length(variable),"\n");
explored_iterations = iterations
if (is.null(explored_iterations)) {
explored_iterations = c(1:length(variable));
}
for (iter in explored_iterations) {
path = mainpath[-1];
# level 2 - get iteration
values = variable[[iter]];
# level 3 - get named_index if list
if (is.numeric(values) || is.integer(values)) {
# path can only be a numerical index / we skip
if (debug) message(" - This is already numerical, we don't need to go down\n")
} else if (is.list(values)) {
# path is a list we can access an element
if (debug) message(" - This is a list:", paste(names(values), collapse = " "), "\n")
if (length(path) == 0) {
warning("ERROR Invalid variable name(too small)\n");
return (NULL);
}
subitem = path[1];
path = path[-1];
if (!is.element(subitem , names(values))) {
warning("ERROR: Cannot find subitem '",subitem,"' among [", paste(names(values), collapse=" "),"]\n")
return (NULL);
} else {
if (debug) message(" - We access subitem: ", subitem, "\n")
values = values[[subitem]];
}
} else {
warning("ERROR: UNSUPPORTED TYPE " ,class(values) ," \n");
return (NULL);
}
if (is.numeric(values) || is.integer(values)) {
if (debug) message(" - lower level can be handle\n");
} else {
warning("ERROR: UNSUPPORTED TYPE " ,class(values) ," \n");
return (NULL);
}
# now we have values a numerical value or array.
# we flatten it or we get what the index requires.
if (length(path) == 0) {
if (debug) message(" - We need to flatten\n");
# we flatten
} else {
# get the one element selected
if (debug) message(" - We get the index\n");
value_index = strtoi(path[1]);
if (debug) message(" - value_index = " , value_index , "\n");
values = values[value_index];
}
values = as.vector(unlist(values))
if (is.null(result)) {
result = data.frame(t(values))
names(result) <- generate_column_names(target,c(1:length(values)))
} else {
## We add missing column on the new row
if (ncol(result) > length(values)) {
values = c( values , rep(NA, ncol(result) - length(values)));
}
## We add missing column on the original dataframe
if ((ncol(result) < length(values))) {
while (ncol(result) < length(values)) { ## TODO : Please find more efficient!
result = cbind(result,c(NA))
}
names(result) <- generate_column_names(target,c(1:length(values)))
}
if (ncol(result) != length(values)) { ## SHOULD NEVER HAPPEND!
warning("ERROR: NUMBER of COLUMN CHANGED FROM " ,ncol(result) , " to ", length(values)," \n");
return (NULL);
} else {
result = rbind(result, values);
}
}
}
return (result)
}
#' Extract values within a \code{\link{AM_mcmc_output}} object
#'
#' Given an \code{\link{AM_mcmc_output}} object, as well as the target variable names,
#' AM_extract will return a list of the variables of interest.
#'
#' Due to the complexity of AntMAN outputs, \code{\link{AM_mcmc_output}} object can be difficult
#' to handle. The AM_extract function eases access of particular variables within the
#' \code{\link{AM_mcmc_output}} object. Variables of varying dimension are expected to result from the transdimensional moves. When considering such
#' variables, the extracted list would correspond to an nx1 list, where n refers to the number of extracted iterations. Each of these nx1 entries consists
#' of another list of dimension mx1, where m specifies the number of components inferred for that iteration.
#'
#'@param object an \code{\link{AM_mcmc_output}} object.
#'@param targets List of variables to extract (ie. K, M, mu).
#'@param iterations Can specify particular iterations to extracts, NULL for all.
#'@param debug Activate log to.
#'@return a list of variables specified in \code{targets}.
#'
#'@export
AM_extract = function(object, targets, iterations = NULL, debug = FALSE){
df = NULL;
for (target in targets) {
if (target == "CI") {
## CI Extractor
nrows = length(object$CI)
ncols = length(object$CI[[1]])
tmp = data.frame(t(array(as.numeric(unlist(object$CI)), dim=c(ncols,nrows))))
names(tmp) <- generate_column_names(target,c(1:ncols));
if (!is.null(iterations)) {
tmp = tmp[iterations,];
}
}
#TODO: working but not elegant
if (target == "mu" || target == "sig2" || target == "Sig" || target == "theta" || target == "W"){
tmp = as.matrix(object[[target]])
if (!is.null(iterations)){
tmp = as.matrix(tmp[iterations,])
}
}
else {
## Generic extractor (SLOW)
tmp = as.matrix(extract_target(object,target,iterations,debug));
}
if (is.null(tmp)) {
warning("ERROR: Invalid extraction target: ",target,", please make sure this was part of the outputs list in AM_mcmc_parameters.\n", sep="");
return (NULL);
}
if(is.null(df)) {
nrows = nrow(tmp)
df = list();
} else {
if (nrow(tmp) != nrows) {
warning("ERROR: Invalid extraction size, previously found ",nrow(df),"while with target '",target,"' we have ", nrow(tmp),"\n", sep="");
return (NULL);
}
}
df[[target]] = tmp;
}
return (df);
}
| /scratch/gouwar.j/cran-all/cranData/AntMAN/R/AM_extract.R |
#######################################################################################
###############
############### AntMAN Package
###############
###############
#######################################################################################
#' Given that the prior on M is a dirac delta, find the \eqn{\gamma} hyperparameter of the weights prior to match \eqn{E(K)=K*},
#' where \eqn{K*} is user-specified
#'
#' Once a fixed value of the number of components \eqn{M^*} is specified, this function adopts a \emph{bisection method} to find the value of \eqn{\gamma}
#' such that the induced distribution on the number of clusters is centered around a user specifed value \eqn{K^*}, i.e. the function uses
#' a bisection method to solve for \eqn{\gamma} \insertCite{argiento2019infinity}{AntMAN}. The user can provide a lower \eqn{\gamma_{l}} and
#' an upper \eqn{\gamma_{u}} bound for the possible values of \eqn{\gamma}. The default values are \eqn{\gamma_l= 10^{-3}} and \eqn{\gamma_{u}=10}.
#' A default value for the tolerance is \eqn{\epsilon=0.1}. Moreover, after a maximum number of iteration (default is 31), the function
#' stops warning that convergence has not been reached.
#'
#' @param n sample size.
#' @param Mstar number of components of the mixture.
#' @param Kstar mean number of clusters the user wants to specify.
#' @param gam_min lower bound of the interval in which \code{gamma} should lie (default 1e-4).
#' @param gam_max upper bound of the interval in which \code{gamma} should lie (default 10).
#' @param tolerance Level of tolerance for the method.
#'
#'
#' @return A value of \code{gamma} such that \eqn{E(K)=K^*}
#'
#' @keywords prior number of clusters
#'
#' @export
#'
#' @examples
#' n <- 82
#' Mstar <- 12
#' gam_de <- AM_find_gamma_Delta(n,Mstar,Kstar=6, gam_min=1e-4,gam_max=10, tolerance=0.1)
#' prior_K_de <- AM_prior_K_Delta(n,gam_de,Mstar)
#' prior_K_de\\%*\\%1:n
AM_find_gamma_Delta <- function (n,Mstar,Kstar=6, gam_min=0.0001,gam_max=10, tolerance=0.1) {
return(find_gamma_Delta(n,Mstar,Kstar, gam_min,gam_max, tolerance));
}
#' Given that the prior on M is a shifted Poisson, find the \eqn{\gamma} hyperparameter of the weights prior to match \eqn{E(K)=K^{*}}, where \eqn{K^{*}} is user-specified
#'
#' Once the prior on the number of mixture components M is assumed to be a Shifted Poisson of parameter \code{Lambda},
#' this function adopts a \emph{bisection method} to find the value of \eqn{\gamma} such that the induced distribution
#' on the number of clusters is centered around a user specifed value \eqn{K^{*}}, i.e. the function uses a bisection
#' method to solve for \eqn{\gamma} \insertCite{argiento2019infinity}{AntMAN}. The user can provide a lower \eqn{\gamma_{l}}
#' and an upper \eqn{\gamma_{u}} bound for the possible values of \eqn{\gamma}. The default values are \eqn{\gamma_l= 10^{-3}} and \eqn{\gamma_{u}=10}.
#' A defaault value for the tolerance is \eqn{\epsilon=0.1}. Moreover, after a maximum number of iteration (default is 31),
#'the function stops warning that convergence has not bee reached.
#'
#' @param n The sample size.
#' @param Lambda The parameter of the Shifted Poisson for the number of components of the mixture.
#' @param Kstar The mean number of clusters the user wants to specify.
#' @param gam_min The lower bound of the interval in which \code{gamma} should lie.
#' @param gam_max The upper bound of the interval in which \code{gamma} should lie.
#' @param tolerance Level of tolerance of the method.
#'
#'
#' @return A value of \code{gamma} such that \eqn{E(K)=K^{*}}
#'
#' @keywords prior number of clusters
#'
#' @export
#'
#' @examples
#' n <- 82
#' Lam <- 11
#' gam_po <- AM_find_gamma_Pois(n,Lam,Kstar=6, gam_min=0.0001,gam_max=10, tolerance=0.1)
#' prior_K_po <- AM_prior_K_Pois(n,gam_po,Lam)
#' prior_K_po\\%*\\%1:n
AM_find_gamma_Pois <- function (n,Lambda,Kstar=6, gam_min=0.0001,gam_max=10, tolerance=0.1) {
return (find_gamma_Pois(n,Lambda,Kstar, gam_min,gam_max, tolerance));
}
#' Given that the prior on M is a Negative Binomial, find the \eqn{\gamma} hyperparameter of the weights
#' prior to match \eqn{E(K)=K*}, where \eqn{K*} is user-specified
#'
#' Once the prior on the number of mixture components M is assumed to be a Negative Binomial with
#' parameter \code{r>0} and \code{0<p<1}, with mean is 1+ r*p/(1-p), this function adopts a \emph{bisection method}
#' to find the value of \code{gamma} such that the induced distribution on the number of clusters is centered around a
#' user specifed value \eqn{K^{*}}, i.e. the function uses a bisection method to solve for \eqn{\gamma} \insertCite{argiento2019infinity}{AntMAN}.
#' The user can provide a lower \eqn{\gamma_{l}} and an upper \eqn{\gamma_{u}} bound for the possible values of \eqn{\gamma}. The default values
#' are \eqn{\gamma_l= 10^{-3}} and \eqn{\gamma_{u}=10}. A defaault value for the tolerance is \eqn{\epsilon=0.1}. Moreover, after a
#' maximum number of iteration (default is 31), the function stops warning that convergence has not bee reached.
#'
#' @param n The sample size.
#' @param r The dispersion parameter \code{r} of the Negative Binomial.
#' @param p The probability of failure parameter \code{p} of the Negative Binomial.
#' @param Kstar The mean number of clusters the user wants to specify.
#' @param gam_min The lower bound of the interval in which \code{gamma} should lie.
#' @param gam_max The upper bound of the interval in which \code{gamma} should lie.
#' @param tolerance Level of tolerance of the method.
#'
#'
#' @return A value of \code{gamma} such that \eqn{E(K)=K^{*}}
#'
#' @keywords prior number of clusters
#'
#' @export
#'
#' @examples
#' n <- 82
#' r <- 1
#' p <- 0.8571
#' gam_nb= AM_find_gamma_NegBin(n,r,p,Kstar=6, gam_min=0.001,gam_max=10000, tolerance=0.1)
#' prior_K_nb= AM_prior_K_NegBin(n,gam_nb, r, p)
#' prior_K_nb\\%*\\%1:n
AM_find_gamma_NegBin <- function (n,r,p,Kstar=6, gam_min=0.001,gam_max=10000, tolerance=0.1){
return (find_gamma_NegBin(n,r,p,Kstar, gam_min,gam_max, tolerance));
}
| /scratch/gouwar.j/cran-all/cranData/AntMAN/R/AM_find_gamma.R |
#######################################################################################
###############
############### AntMAN Package
###############
###############
#######################################################################################
#' S3 class AM_mcmc_output
#' @description Output type of return values from \code{\link{AM_mcmc_fit}}.
#' @seealso \code{\link{AM_mcmc_fit}}
#' @name AM_mcmc_output
#' @return \code{\link{AM_mcmc_output}}
NULL
#' S3 class AM_mcmc_configuration
#' @description Output type of return values from \code{\link{AM_mcmc_parameters}}.
#' @seealso \code{\link{AM_mcmc_fit}}
#' @name AM_mcmc_configuration
#' @return \code{\link{AM_mcmc_configuration}}
NULL
#################################################################################
##### AM_mcmc_configuration function
#################################################################################
#' summary information of the AM_mcmc_configuration object
#'
#'
#'
#' Given an \code{\link{AM_mcmc_configuration}} object, this function prints the summary information
#' of the specified mcmc configuration.
#'
#'@param object an \code{\link{AM_mcmc_configuration}} object.
#'@param ... all additional parameters are ignored
#'
#'
#'@method summary AM_mcmc_configuration
#'@seealso \code{\link{AM_mcmc_parameters}}
#'@return NULL. Called for side effects.
#'@export
summary.AM_mcmc_configuration = function(object, ...){
cat("\n", "AM_mcmc_configuration\n", sep = "")
for (item in names(object)) {
cat(' -', item , ': ' , head(unlist(object[[item]], use.names=FALSE)), "\n")
}
}
#################################################################################
##### AM_mcmc_output function
#################################################################################
#' plot AM_mcmc_output
#'
#'
#' Given an \code{\link{AM_mcmc_output}} object, this function plots some useful information about the MCMC results
#' regarding \eqn{M} and \eqn{K}. Besides the PMFs, some of the diagnostic plots of the MCMC chain are visualised.
#'
#'@param x an \code{\link{AM_mcmc_output}} object.
#'@param ... all additional parameters are ignored.
#'@return NULL. Called for side effects.
#'
#'@method plot AM_mcmc_output
#'@importFrom graphics image
#'@importFrom grDevices gray.colors
#'@export
plot.AM_mcmc_output=function(x, ...){
print(AM_plot_pairs(x));readline(prompt="Press [enter] to continue")
print(AM_plot_pmf(x));readline(prompt="Press [enter] to continue")
print(AM_plot_traces(x));readline(prompt="Press [enter] to continue")
print(AM_plot_values(x));readline(prompt="Press [enter] to continue")
print(AM_plot_chaincor(x));
return(NULL)
}
#' Internal function that produces a string from a list of values
#'
#'@param x a list of values
#'
#'@importFrom utils head
#' @keywords internal
list_values = function (x) {
arguments = vector();
for (item in names(x)) {
arguments = append(arguments,sprintf("%s = %s",item, head(x[[item]]) )) ;
}
return (paste(arguments, collapse=", "));
}
#' summary information of the AM_mcmc_output object
#'
#'
#' Given an \code{\link{AM_mcmc_output}} object, this function prints the summary information
#' pertaining to the given model output.
#'
#'@param object a \code{\link{AM_mcmc_output}} object
#'@param ... all additional parameters are ignored
#'@return NULL. Called for side effects.
#'
#'
#'@method summary AM_mcmc_output
#'@seealso \code{\link{AM_mcmc_fit}}, \code{\link{AM_mcmc_refit}}
#'@export
summary.AM_mcmc_output=function(object,...){
cat("\n","Fitted model:","\n");
cat(" -mix_kernel_hyperparams(",list_values(attr(object,'mix_kernel_hyperparams')),")\n", sep = "");
cat(" -mix_components_prior(",list_values(attr(object,'mix_components_prior')),")\n", sep = "");
cat(" -mix_weight_prior(",list_values(attr(object,'mix_weight_prior')),")\n", sep = "");
cat(" -mcmc_parameters(",list_values(attr(object,'mcmc_parameters')),")\n", sep = "");
cat("\n - Summary of the MCMC output:\n\n");
cat(sprintf(" %10s%10s%10s%10s%10s%10s%10s%10s\n", "Name", "Mean", "StdDev", "2.5%","50%","97.5%", "ESS", "MCMC Err."));
invisible = c("CI","W","mu","Sig","sig2","theta","R","P")
# If fixed clustering
for (item in names(object)) {
if (!item %in% invisible) {
allcols = AM_extract(object,c(item))
for (subitem in names(allcols)) {
e = allcols[[subitem]]
emean = mean(e)
esd = sd(e)
elen = length(e)
neff = NA
if (anyNA(e) == FALSE) neff = IAM_mcmc_neff(e)
mcmcerror = NA
if (anyNA(e) == FALSE) mcmcerror = IAM_mcmc_error(e)
q = quantile(e,prob=c(0.025, 0.5,0.975), names=FALSE, na.rm=TRUE)
cat(sprintf(" %10s%10.2f%10.2f%10.2f%10.2f%10.2f%10.2f%10.2f\n", subitem, emean, esd, q[1], q[2], q[3], neff, mcmcerror));
}
}
}
}
## INTERNAL
# AM_reshape is an internal function for reshaping the fit output into the correct form
AM_reshape <- function(fit, y){
y_dim = dim(y)[2]
if (is.null(y_dim)){
y_dim = 1}
if (!is.null(fit$theta)){
theta_mat = as.matrix(fit$theta)
theta = apply(theta_mat, 1, function(x){
x_vec = as.numeric(unlist(x))
matrix(x_vec, ncol=y_dim, nrow=length(x_vec)/y_dim, byrow=F)})
fit$theta = theta
}
if (!is.null(fit$mu)){
mu = mapply(function(x, m){
mu_size = length(x)/m
mu_individual = split(x, ceiling(seq_along(x)/mu_size))
mu_combined = lapply(mu_individual, function(mu_vec){
matrix(unlist(mu_vec), nrow=y_dim, byrow=F)
})
}, fit$mu, fit$M)
fit$mu = mu
}
if (!is.null(fit$sig2)){
sig = mapply(function(x, m){
sig_size = length(x)/m
sig_individual = split(x, ceiling(seq_along(x)/sig_size))
sig_combined = lapply(sig_individual, function(sig_vec){
matrix(unlist(sig_vec), ncol=y_dim, nrow=y_dim, byrow=F)
})
}, fit$sig2, fit$M)
fit$sig2 = sig
}
if (!is.null(fit$Sig)){
sig = mapply(function(x, m){
sig_size = length(x)/m
sig_individual = split(x, ceiling(seq_along(x)/sig_size))
sig_combined = lapply(sig_individual, function(sig_vec){
matrix(unlist(sig_vec), ncol=y_dim, nrow=y_dim, byrow=F)
})
}, fit$Sig, fit$M)
fit$Sig = sig
}
return(fit)
}
#################################################################################
##### AM_mcmc_fit function
#################################################################################
#' Performs a Gibbs sampling
#'
#' The \code{AM_mcmc_fit} function performs a Gibbs sampling in order to estimate the mixture comprising the sample data \code{y}.
#' The mixture selected must be of a predefined type \code{mix_kernel_hyperparams} (defined with \code{AM_mix_hyperparams_*} functions, where star
#' \code{*} denotes the chosen kernel).
#' Additionally, a prior distribution on the number of mixture components
#' must be specified through \code{mix_components_prior}
#' (generated with \code{AM_mix_components_prior_*} functions, where \code{*} denotes the chosen prior). Similarly,
#' a prior on the weights of the mixture should be specified through \code{mix_weight_prior}
#' (defined with \code{AM_mix_weights_prior_*} functions). Finally, with \code{mcmc_parameters}, the user sets
#' the MCMC parameters for the Gibbs sampler (defined with \code{\link{AM_mcmc_parameters}} functions).
#'
#' If no initial clustering is specified (either as \code{init_K} or \code{init_clustering}),
#' then every observation is allocated to a different cluster.
#' If \code{init_K} is specified then AntMAN initialises the clustering through K-means.
#'
#' **Warning**: if the user does not specify init_K or initial_cluster, the first steps can be be time-consuming because of default setting of the initial clustering.
#'
#'
#'@param y input data, can be a vector or a matrix.
#'@param mix_kernel_hyperparams is a configuration list, defined by *_mix_hyperparams functions, where * denotes the chosen kernel.
#'See \code{\link{AM_mix_hyperparams_multiber}}, \code{\link{AM_mix_hyperparams_multinorm}}, \code{\link{AM_mix_hyperparams_uninorm}}, \code{\link{AM_mix_hyperparams_unipois}} for more details.
#'@param initial_clustering is a vector CI of initial cluster assignement. If no clustering is specified (either as \code{init_K} or \code{init_clustering}), then every observation is
#' assigned to its own cluster.
#'@param fixed_clustering if specified, this is the vector CI containing the cluster assignments. This will remain unchanged for every iteration.
#'@param init_K initial value for the number of cluster. When this is specified, AntMAN intitialises the clustering assign usng K-means.
#'@param mix_components_prior is a configuration list defined by AM_mix_components_prior_* functions, where * denotes the chosen prior.
#' See \code{\link{AM_mix_components_prior_dirac}},
#' \cr \code{\link{AM_mix_components_prior_negbin}}, \code{\link{AM_mix_components_prior_pois}} for more \cr
#' details.
#'@param mix_weight_prior is a configuration list defined by AM_weight_prior_* functions, where * denotes the chosen prior specification.
#' See \code{\link{AM_mix_weights_prior_gamma}} for more \cr details.
#'@param mcmc_parameters is a configuration list defined by AM_mcmc_parameters. See \code{\link{AM_mcmc_parameters}} for more details.
#'@return The return value is an \code{\link{AM_mcmc_output}} object.
#'@examples
#' \donttest{
#' AM_mcmc_fit( AM_sample_unipois()$y,
#' AM_mix_hyperparams_unipois (alpha0=2, beta0=0.2),
#' mcmc_parameters = AM_mcmc_parameters(niter=50, burnin=0, thin=1, verbose=0))
#' }
#'@useDynLib AntMAN
#'@export
AM_mcmc_fit <- function(
y,
mix_kernel_hyperparams,
initial_clustering = NULL,
init_K = NULL,
fixed_clustering = NULL,
mix_components_prior = AM_mix_components_prior_pois() ,
mix_weight_prior = AM_mix_weights_prior_gamma(),
mcmc_parameters = AM_mcmc_parameters() ) {
fixed_cluster = FALSE
if (is.null(fixed_clustering) & is.null(init_K) & !is.null(initial_clustering)) {
fixed_cluster = FALSE
# initial_clustering is set
} else if (!is.null(init_K) & is.null(initial_clustering)& is.null(fixed_clustering)) {
fixed_cluster = FALSE
initial_clustering <- kmeans(y, init_K)$cluster
# initial_clustering is set
} else if (is.null(init_K) & is.null(initial_clustering)& is.null(fixed_clustering)) {
fixed_cluster = FALSE
initial_clustering <- 0:(NROW(y)-1)
# initial_clustering is set
} else if (is.null(init_K) & is.null(initial_clustering)& !is.null(fixed_clustering)) {
fixed_cluster = TRUE
initial_clustering = fixed_clustering
}
else {
stop("Please provide only one of K_init or initial_clustering or fixed_clustering.")
}
fit_result = (structure(
IAM_mcmc_fit(y = y, mix_kernel_hyperparams = mix_kernel_hyperparams, initial_clustering = initial_clustering, fixed_clustering= fixed_cluster , mix_components_prior = mix_components_prior, mix_weight_prior = mix_weight_prior, mcmc_parameters = mcmc_parameters)
, class = "AM_mcmc_output",
mix_kernel_hyperparams = mix_kernel_hyperparams,
initial_clustering = initial_clustering,
init_K = init_K,
fixed_clustering = fixed_clustering,
mix_components_prior =mix_components_prior ,
mix_weight_prior = mix_weight_prior,
mcmc_parameters =mcmc_parameters));
fit_result = AM_reshape(fit_result, y)
return (fit_result)
}
#' Performs a Gibbs sampling reusing previous configuration
#'
#' Similar to \code{\link{AM_mcmc_fit}}, the \code{AM_mcmc_refit} function performs a Gibbs sampling in order to estimate
#' a mixture. However parameters will be reused from a previous result from \code{\link{AM_mcmc_fit}}.
#'
#' In practice this function will call AM_mcmc_fit(y, fixed_clustering = fixed_clustering, ...); with the same parameters as previously
#' specified.
#'
#'@param y input data, can be a vector or a matrix.
#'@param fit previous output from \code{\link{AM_mcmc_fit}} that is used to setup kernel and priors.
#'@param fixed_clustering is a vector CI of cluster assignment that will remain unchanged for every iterations.
#'@param mcmc_parameters is a configuration list defined by \code{\link{AM_mcmc_parameters}}.
#'@return The return value is an \code{\link{AM_mcmc_output}} object.
#'@examples
#' \donttest{
#' y = AM_sample_unipois()$y
#' fit = AM_mcmc_fit( y ,
#' AM_mix_hyperparams_unipois (alpha0=2, beta0=0.2),
#' mcmc_parameters = AM_mcmc_parameters(niter=20, burnin=0, thin=1, verbose=0))
#' eam = AM_coclustering(fit)
#' cluster = AM_salso(eam, "binder")
#' refit = AM_mcmc_refit(y , fit, cluster,
#' mcmc_parameters = AM_mcmc_parameters(niter=20, burnin=0, thin=1, verbose=0));
#' }
#'@export
AM_mcmc_refit <- function(
y, fit,
fixed_clustering,
mcmc_parameters = AM_mcmc_parameters() ) {
mcp = attr(fit,'mix_components_prior')
mwp = attr(fit,'mix_weight_prior')
mkh = attr(fit,'mix_kernel_hyperparams')
## TODO : check input data size
AM_mcmc_fit(y,
mix_kernel_hyperparams = mkh,
fixed_clustering = fixed_clustering,
mix_components_prior = mcp ,
mix_weight_prior = mwp,
mcmc_parameters = mcmc_parameters );
}
#################################################################################
##### AM_mcmc_parameters function
#################################################################################
#' MCMC Parameters
#'
#' This function generates an MCMC parameters list to be used as \code{mcmc_parameters} argument within \code{\link{AM_mcmc_fit}}.
#'
#'
#'
#'@param niter Total number of MCMC iterations to be carried out.
#'@param burnin Number of iterations to be considered as burn-in. Samples from this burn-in period are discarded.
#'@param thin Thinning rate. This argument specifies how often a draw from the posterior distribution is stored after
#' burnin, i.e. one every -th samples is saved. Therefore, the toral number of MCMC samples saved is
#' (\code{niter} -\code{burnin})/\code{thin}. If thin =1, then AntMAN stores every iteration.
#'@param verbose A value from 0 to 4, that specifies the desired level of verbosity (0:None, 1:Warnings, 2:Debug, 3:Extras).
#'@param output A list of parameters output to return.
#'@param output_dir Path to an output dir, where to store all the outputs.
#'@param parallel Some of the algorithms can be run in parallel using OpenMP. When set to True, this parameter triggers the parallelism.
#'@return An \code{\link{AM_mcmc_configuration}} Object. This is a list to be used as \code{mcmc_parameters} argument with \code{\link{AM_mcmc_fit}}.
#'@examples
#' AM_mcmc_parameters (niter=1000, burnin=10000, thin=50)
#' AM_mcmc_parameters (niter=1000, burnin=10000, thin=50, output=c("CI","W","TAU"))
#'@export
AM_mcmc_parameters <- function( niter=5000,
burnin=2500, ## niter / 2
thin=1,
verbose = 1,
output=c("CI","K"),
parallel=TRUE,
output_dir = NULL) {
return (structure(list(type="AM_MCMC_PARAMETERS",
niter=niter, burnin=burnin, thin=thin,
verbose=verbose, output=output, parallel=parallel,
output_dir=output_dir), class = "AM_mcmc_configuration") );
}
| /scratch/gouwar.j/cran-all/cranData/AntMAN/R/AM_mcmc.R |
#######################################################################################
###############
############### AntMAN Package
###############
###############
#######################################################################################
#' S3 class AM_mix_components_prior
#' @description Object returned by \code{AM_mix_components_prior_*}.
#' @seealso \code{\link{AM_mix_components_prior_dirac}},
#' \code{\link{AM_mix_components_prior_negbin}},
#' \code{\link{AM_mix_components_prior_pois}}
#' @name AM_mix_components_prior
#' @return \code{\link{AM_mix_components_prior}}
NULL
#' summary information of the AM_mix_components_prior object
#'
#'
#' Given an \code{\link{AM_mix_components_prior}} object, this function prints the summary information
#' of the specified prior on the number of components.
#'
#'@param object an \code{\link{AM_mix_components_prior}} object.
#'@param ... all additional parameters are ignored.
#'@return NULL. Called for side effects.
#'
#'@importFrom utils head
#'@seealso \code{\link{AM_mix_components_prior}}
#'@method summary AM_mix_components_prior
#'@export
summary.AM_mix_components_prior = function(object, ...){
cat("\n", "AM_mix_components_prior\n", sep = "")
for (item in names(object)) {
cat(' -', item , ': ' , head(object[[item]]), "\n")
}
}
#################################################################################
##### Prior on Number of Components Configuration functions
#################################################################################
#' Generate a configuration object that contains a Point mass prior
#'
#' Generate a configuration object that assigns a Point mass prior to the number of mixture components.
#' This is the simplest option and it requires users to specify a value \eqn{M^*}
#' such that \eqn{Pr(M=M^* =1}.
#'
#'@param Mstar Fixed value \eqn{M^*} for the number of components.
#'@return An \code{\link{AM_mix_components_prior}} object. This is a configuration list to be used as \code{mix_components_prior} argument for \code{\link{AM_mcmc_fit}}.
#'
#'@keywords prior
#'@seealso \code{\link{AM_mcmc_fit}}
#'@export
#'
#'@examples
#'
#' AM_mix_components_prior_dirac (Mstar=3)
AM_mix_components_prior_dirac <- function(Mstar) {
parameters = list(type = "AM_mix_components_prior_dirac", Mstar = Mstar);
return ( structure(
parameters,
class = "AM_mix_components_prior")
) ;
};
#' Generate a configuration object for a Shifted Negative Binomial prior on the number of mixture components
#'
#'
#' This generates a configuration object for a Shifted Negative Binomial prior on the number of mixture components such that
#' \deqn{q_M(m)=Pr(M=m) =\frac{\Gamma(r+m-1)}{(m-1)!\Gamma(r)} p^{m-1}(1-p)^r, \quad m=1,2,3,\ldots}
#' The hyperparameters \eqn{p\in (0,1)} (probability of success) and \eqn{r>0} (size) can either be fixed using \code{r} and \code{p}
#' or assigned appropriate prior distributions.
#' In the latter case, we assume \eqn{p \sim Beta(a_P,b_P)} and \eqn{r \sim Gamma(a_R,b_R)}. In AntMAN we assume the following
#' parametrization of the Gamma density:
#' \deqn{p(x\mid a,b )= \frac{b^a x^{a-1}}{\Gamma(a)} \exp\{ -bx \}, \quad x>0.}
#'
#'
#' If no arguments are provided, the default is \eqn{r = 1 , a_P = 1, b_P = 1}.
#'
#' Additionally, when init_R and init_P are not specified, there are default values:
#' \eqn{init_R = 1} and \eqn{init_P = 0.5}.
#'
#'@param a_R The shape parameter \eqn{a} of the \eqn{Gamma(a,b)} prior distribution for \eqn{r}.
#'@param b_R The rate parameter \eqn{b} of the \eqn{Gamma(a,b)} prior distribution for \eqn{r}.
#'@param init_R The initial value of \eqn{r}, when specifying \code{a_R} and \code{b_R}.
#'@param a_P The parameter \eqn{a} of the \eqn{Beta(a,b)} prior distribution for \eqn{p}.
#'@param b_P The parameter \eqn{b} of the \eqn{Beta(a,b)} prior distribution for \eqn{p}.
#'@param init_P The inivial value of \eqn{p}, when specifying \code{a_P} and \code{b_P}.
#'@param R It allows to fix \eqn{r} to a specific value.
#'@param P It allows to fix \eqn{p} to a specific value.
#'
#'@return An \code{\link{AM_mix_components_prior}} object. This is a configuration list to be used as \code{mix_components_prior} argument for \code{\link{AM_mcmc_fit}}.
#'
#'
#'@keywords prior
#'@seealso \code{\link{AM_mcmc_fit}}
#'@export
#'
#'@examples
#'
#' AM_mix_components_prior_negbin (R=1, P=1)
#' AM_mix_components_prior_negbin ()
AM_mix_components_prior_negbin <- function(a_R = NULL, b_R = NULL, a_P = NULL, b_P = NULL, R = NULL, P = NULL,
init_R = NULL, init_P = NULL) {
paradox_error_R = "Please note that you cannot specify a_R,b_R and R. R specifies a fixed value.";
paradox_error_P = "Please note that you cannot specify a_P,b_P and P. P specifies a fixed value.";
parameters = list(type = "AM_mix_components_prior_negbin");
if (!is.null(a_R) & !is.null(b_R) & !is.null(init_R) & is.null(R)) {parameters = c(parameters, list(a_R = a_R, b_R = b_R, init_R = init_R));}
else if (!is.null(a_R) & !is.null(b_R) & is.null(init_R) & is.null(R)) {parameters = c(parameters, list(a_R = a_R, b_R = b_R ));}
else if ( is.null(a_R) & is.null(b_R) & is.null(init_R) & !is.null(R)) {parameters = c(parameters, list(fixed_R = R));}
else if ( is.null(a_R) & is.null(b_R) & is.null(init_R) & is.null(R)) {parameters = c(parameters, list(fixed_R = 1));}
else {stop ( paradox_error_R );}
if (!is.null(a_P) & !is.null(b_P) & !is.null(init_P) & is.null(P)) {parameters = c(parameters, list(a_P = a_P, b_P = b_P, init_P = init_P));}
else if (!is.null(a_P) & !is.null(b_P) & is.null(init_P) & is.null(P)) {parameters = c(parameters, list(a_P = a_P, b_P = b_P ));}
else if ( is.null(a_P) & is.null(b_P) & is.null(init_P) & !is.null(P)) {parameters = c(parameters, list(fixed_P = P));}
else if ( is.null(a_P) & is.null(b_P) & is.null(init_P) & is.null(P)) {parameters = c(parameters, list(a_P = 1, b_P = 1));}
else {stop ( paradox_error_P );}
return ( structure(
parameters,
class = "AM_mix_components_prior")
) ;
};
#' Generate a configuration object for a Poisson prior on the number of mixture components
#'
#'
#' This function generates a configuration object for a Shifted Poisson prior on the number
#' of mixture components such that
#' \deqn{q_M(m)= Pr (M=m)= \frac{e^{-\Lambda}\Lambda^{m-1} }{(m-1)!} , \quad m=1,2,3,\ldots}
#' The hyperparameter \eqn{\Lambda} can either be fixed using \code{Lambda}
#' or assigned a \eqn{Gamma(a,b)} prior distribution with \code{a} and \code{b}.
#' In AntMAN we assume the following parametrization of the Gamma density:
#' \deqn{p(x\mid a,b )= \frac{b^a x^{a-1}}{\Gamma(a)} \exp\{ -bx \}, \quad x>0.}
#'
#' If no arguments are provided, the default is a prior distribution with \code{a = 1} and \code{b = 1}.
#'
#'@param a The shape parameter \code{a} of the \eqn{Gamma(a,b)} prior distribution.
#'@param b The rate parameter \code{b} of the \eqn{Gamma(a,b)} prior distribution.
#'@param init The initial value for \eqn{\Lambda}, when specifying \code{a} and \code{b}.
#'@param Lambda It allows to set the hyperparameter \eqn{\Lambda} to be assigned a fixed value.
#'
#'@return An \code{\link{AM_mix_components_prior}} object. This is a configuration list to be used as \code{mix_components_prior} argument for \code{\link{AM_mcmc_fit}}.
#'
#'@keywords prior
#'@seealso \code{\link{AM_mcmc_fit}}
#'@export
#'
#'@examples
#'
#' components_prior = AM_mix_components_prior_pois (init=3, a=1, b=1)
#'
AM_mix_components_prior_pois <- function(a=NULL, b=NULL, Lambda=NULL, init=NULL) {
paradox_error = "Please note that you cannot specify a,b,init and Lambda. Lambda specifies a fixed value.";
### Default value ###
parameters = list(type = "AM_mix_components_prior_pois", a = 1, b = 1);
if (!is.null(a) & !is.null(b)) {
parameters = list(type = "AM_mix_components_prior_pois", a = a, b = b);
if (!is.null(init)) {
parameters = list(type = "AM_mix_components_prior_pois", a = a, b = b, init = init)
};
if (!is.null(Lambda)) {
stop ( paradox_error );
};
} else if (!is.null(Lambda)) {
parameters = list(type = "AM_mix_components_prior_pois", Lambda = Lambda);
if (!is.null(a) | !is.null(b) | !is.null(init)) {
stop ( paradox_error );
}
} else {
if (!is.null(a) | !is.null(b) | !is.null(init)) {
stop ( paradox_error );
}
};
return ( structure(
parameters,
class = "AM_mix_components_prior")
) ;
};
| /scratch/gouwar.j/cran-all/cranData/AntMAN/R/AM_mix_components_prior.R |
#######################################################################################
###############
############### AntMAN Package
###############
###############
#######################################################################################
#' S3 class AM_mix_hyperparams
#' @description Object type returned by \code{AM_mix_hyperparams_*} commands.
#' @seealso \code{\link{AM_mix_hyperparams_unipois}}, \code{\link{AM_mix_hyperparams_uninorm}}, \code{\link{AM_mix_hyperparams_multiber}},
#' \code{\link{AM_mix_hyperparams_multinorm}}
#' @name AM_mix_hyperparams
#' @return \code{\link{AM_mix_hyperparams}}
NULL
#' summary information of the AM_mix_hyperparams object
#'
#'
#' Given an \code{\link{AM_mix_hyperparams}} object, this function prints the summary information
#' of the specified mixture hyperparameters.
#'
#'@param object an \code{\link{AM_mix_hyperparams}} object.
#'@param ... all additional parameters are ignored.
#'@return NULL. Called for side effects.
#'
#'@method summary AM_mix_hyperparams
#'@seealso \code{\link{AM_mix_hyperparams}}
#'@importFrom utils head
#'@export
summary.AM_mix_hyperparams = function(object, ...){
cat("\n", "AM_mix_hyperparams\n", sep = "")
for (item in names(object)) {
cat(' -', item , ': ' , head(object[[item]]), "\n")
}
}
#################################################################################
##### Mixture Kernel Hyperparameters.
#################################################################################
#'univariate Poisson mixture hyperparameters
#'
#' Generate a configuration object that specifies a univariate Poisson mixture kernel, where users can
#' specify the hyperparameters of the conjugate Gamma prior, i.e. the kernel is a \eqn{Poisson(\tau) }
#' and \eqn{\tau\sim Gamma(\alpha_0,\beta_0)}.
#' In AntMAN we assume the following
#' parametrization of the Gamma density:
#' \deqn{p(x\mid a,b )= \frac{b^a x^{a-1}}{\Gamma(a)} \exp\{ -bx \}, \quad x>0.}
#'
#' Note that by default, alpha0=1 and beta0=1.
#'
#'
#'
#'@param alpha0 The shape hyperparameter \eqn{\alpha_0}.
#'@param beta0 The rate hyperparameter \eqn{\beta_0}.
#'@return An \code{\link{AM_mix_hyperparams}} object. This is a configuration list to be used as \code{mix_kernel_hyperparams} argument for \code{\link{AM_mcmc_fit}}.
#'@examples
#' AM_mix_hyperparams_unipois (alpha0=2, beta0=0.2)
#'@export
AM_mix_hyperparams_unipois <- function(alpha0, beta0) {
parameters = list ( type = "AM_mix_hyperparams_unipois", alpha0 = alpha0, beta0 = beta0 );
return ( structure(
parameters,
class = "AM_mix_hyperparams")
) ;
}
#' univariate Normal mixture hyperparameters
#'
#' Generate a configuration object that specifies a univariate Normal mixture kernel, where users can specify the hyperparameters of the Normal-InverseGamma conjugate prior.
#' As such, the kernel is a Gaussian distribution with mean \eqn{\mu} and variance \eqn{\sigma^2}. The prior on \eqn{(\mu,\sigma^2)} the Normal-InverseGamma:
#' \deqn{\pi(\mu,\sigma^2\mid m_0,\kappa_0,\nu_0,\sigma^2_0) = \pi_{\mu}(\mu|\sigma^2,m_0,\kappa_0)\pi_{\sigma^2}(\sigma^2\mid \nu_0,\sigma^2_0),}
#' \deqn{\pi_{\mu}(\mu|\sigma^2,m_0,\kappa_0) =\frac{\sqrt{\kappa_0}}{\sqrt{2\pi\sigma^2},}
#' \exp^{-\frac{\kappa_0}{2\sigma^2}(\mu-m_0)^2 }, \qquad \mu\in\mathcal{R},}
#' \deqn{\pi_{\sigma^2}(\sigma^2\mid \nu_0,\sigma^2_0)= {\frac {\sigma_0^{2^{\nu_0 }}}{\Gamma (\nu_0 )}}(1/\sigma^2)^{\nu_0 +1}\exp \left(-\frac{\sigma_0^2}{\sigma^2}\right), \qquad \sigma^2>0.}
#'
#'
#'
#' \eqn{m_0} corresponds \code{m0},
#' \eqn{\kappa_0} corresponds \code{k0},
#' \eqn{\nu_0} corresponds \code{nu0}, and
#' \eqn{\sigma^2_0} corresponds \code{sig02}.
#'
#'If hyperparameters are not specified, the default is \code{m0=0}, \code{k0=1}, \code{nu0=3}, \code{sig02=1}.
#'
#'@param m0 The \eqn{m_0} hyperparameter.
#'@param k0 The \eqn{\kappa_0} hyperparameter.
#'@param nu0 The \eqn{\nu_0} hyperparameter.
#'@param sig02 The \eqn{\sigma^2_0} hyperparameter.
#'@return An \code{\link{AM_mix_hyperparams}} object. This is a configuration list to be used as \code{mix_kernel_hyperparams} argument for \code{\link{AM_mcmc_fit}}.
#'@examples
#'
#' #### This example ...
#'
#' data(galaxy)
#' y_uvn = galaxy
#' mixture_uvn_params = AM_mix_hyperparams_uninorm (m0=20.83146, k0=0.3333333,
#' nu0=4.222222, sig02=3.661027)
#'
#' mcmc_params = AM_mcmc_parameters(niter=2000, burnin=500, thin=10, verbose=0)
#' components_prior = AM_mix_components_prior_pois (init=3, a=1, b=1)
#' weights_prior = AM_mix_weights_prior_gamma(init=2, a=1, b=1)
#'
#' fit <- AM_mcmc_fit(
#' y = y_uvn,
#' mix_kernel_hyperparams = mixture_uvn_params,
#' mix_components_prior =components_prior,
#' mix_weight_prior = weights_prior,
#' mcmc_parameters = mcmc_params)
#'
#' summary (fit)
#' plot (fit)
#'
#'@export
AM_mix_hyperparams_uninorm <- function(m0, k0, nu0, sig02) {
parameters = list ( type = "AM_mix_hyperparams_uninorm", m0 = m0 , k0 = k0 , nu0 = nu0 , sig02 = sig02 );
return ( structure(
parameters,
class = "AM_mix_hyperparams")
) ;
}
#' multivariate Bernoulli mixture hyperparameters (Latent Class Analysis)
#'
#'
#' Generate a configuration object that defines the prior hyperparameters for a mixture of multivariate Bernoulli.
#' If the dimension of the data is P, then the prior is a product of P independent Beta distributions, Beta(\eqn{a_{0i},b_{0i}}). Therefore,
#' the vectors of hyperparameters, a0 and b0, are P-dimensional. Default is (a0= c(1,....,1),b0= c(1,....,1)).
#'
#'@param a0 The a0 hyperparameters.
#'@param b0 The b0 hyperparameters.
#'@return An \code{\link{AM_mix_hyperparams}} object. This is a configuration list to be used as \code{mix_kernel_hyperparams} argument for \code{\link{AM_mcmc_fit}}.
#'@examples
#' AM_mix_hyperparams_multiber (a0= c(1,1,1,1),b0= c(1,1,1,1))
#'@export
AM_mix_hyperparams_multiber <- function(a0, b0) {
parameters = list ( type = "AM_mix_hyperparams_multiber", a0 = a0 , b0 = b0 );
return ( structure(
parameters,
class = "AM_mix_hyperparams")
) ;
}
#' multivariate Normal mixture hyperparameters
#'
#'
#' Generate a configuration object that specifies a multivariate Normal mixture kernel, where users can specify the hyperparameters for the conjugate prior of the multivariate
#' Normal mixture. We assume that the data are d-dimensional vectors \eqn{\boldsymbol{y}_i}, where \eqn{\boldsymbol{y}_i} are i.i.d
#' Normal random variables with mean \eqn{\boldsymbol{\mu}} and covariance matrix \eqn{\boldsymbol{\Sigma}}.
#' The conjugate prior is
#' \deqn{\pi(\boldsymbol \mu, \boldsymbol \Sigma\mid\boldsymbol m_0,\kappa_0,\nu_0,\boldsymbol \Lambda_0)=
#' \pi_{\mu}(\boldsymbol \mu|\boldsymbol \Sigma,\boldsymbol m_0,\kappa_0)\pi_{\Sigma}(\boldsymbol \Sigma \mid \nu_0,\boldsymbol \Lambda_0),}
#' \deqn{ \pi_{\mu}(\boldsymbol \mu|\boldsymbol \Sigma,\boldsymbol m_0,\kappa_0) =
#' \frac{\sqrt{\kappa_0^d}}{\sqrt {(2\pi )^{d}|{\boldsymbol \Sigma }|}} \exp \left(-{\frac {\kappa_0}{2}}(\boldsymbol\mu -{\boldsymbol m_0 })^{\mathrm {T} }{\boldsymbol{\Sigma }}^{-1}(\boldsymbol\mu-{\boldsymbol m_0 })\right),
#' \qquad \boldsymbol \mu\in\mathcal{R}^d,}
#' \deqn{\pi_{\Sigma}(\boldsymbol \Sigma\mid \nu_0,\boldsymbol \Lambda_0)= {\frac {\left|{\boldsymbol \Lambda_0 }\right|^{\nu_0 /2}}{2^{\nu_0 d/2}\Gamma _{d}({\frac {\nu_0 }{2}})}}\left|\boldsymbol \Sigma \right|^{-(\nu_0 +d+1)/2}e^{-{\frac {1}{2}}\mathrm {tr} (\boldsymbol \Lambda_0 \boldsymbol \Sigma^{-1})}
#', \qquad \boldsymbol \Sigma^2>0,}
#' where \code{mu0} corresponds to \eqn{\boldsymbol m_0}, \code{ka0} corresponds to \eqn{\kappa_0},
#' \code{nu0} to \eqn{\nu_0}, and \code{Lam0} to \eqn{\Lambda_0}.
#'
#' Default is \code{(mu0=c(0,..,0)}, \code{ka0=1}, \code{nu0=Dim+2}, \code{Lam0=diag(Dim))} with \code{Dim} is the dimension of the data \code{y}.
#' We advise the user to set \eqn{\nu_0} equal to at least the dimension of the data, \code{Dim}, plus 2.
#'
#'@param mu0 The hyperparameter \eqn{\boldsymbol m_0}.
#'@param ka0 The hyperparameter \eqn{\kappa_0}.
#'@param nu0 The hyperparameter \eqn{\nu_0}.
#'@param Lam0 The hyperparameter \eqn{\Lambda_0}.
#'@return An \code{\link{AM_mix_hyperparams}} object. This is a configuration list to be used as \code{mix_kernel_hyperparams} argument for \code{\link{AM_mcmc_fit}}.
#'@examples
#' AM_mix_hyperparams_multinorm ()
#'@export
AM_mix_hyperparams_multinorm <- function(mu0 = NULL, ka0 = NULL, nu0 = NULL, Lam0 = NULL) {
parameters = list ( type = "AM_mix_hyperparams_multinorm", mu0 = mu0 , ka0 = ka0 , nu0 = nu0 , Lam0 = Lam0 );
return ( structure(
parameters,
class = "AM_mix_hyperparams")
) ;
}
| /scratch/gouwar.j/cran-all/cranData/AntMAN/R/AM_mix_hyperparams.R |
#######################################################################################
###############
############### AntMAN Package
###############
###############
#######################################################################################
#' S3 class AM_mix_weights_prior
#' @description Object type returned by \code{AM_mix_weights_prior_*} commands.
#' @seealso \code{\link{AM_mix_weights_prior_gamma}}
#' @name AM_mix_weights_prior
#' @return \code{\link{AM_mix_weights_prior}}
NULL
#################################################################################
##### Configuration functions for the prior on the mixture weights
#################################################################################
#' summary information of the AM_mix_weights_prior object
#'
#'
#' Given an \code{\link{AM_mix_weights_prior}} object, this function prints the summary information
#' of the specified mixture weights prior.
#'
#'@param object an \code{\link{AM_mix_weights_prior}} object.
#'@param ... all additional parameters are ignored.
#'@return NULL. Called for side effects.
#'
#'
#'@method summary AM_mix_weights_prior
#'@seealso \code{\link{AM_mix_weights_prior}}
#'@importFrom utils head
#'@export
summary.AM_mix_weights_prior = function(object, ...){
cat("\n", "AM_mix_weights_prior\n", sep = "")
for (item in names(object)) {
cat(' -', item , ': ' , head(object[[item]]), "\n")
}
}
#' specify a prior on the hyperparameter \eqn{\gamma} for the Dirichlet mixture weights prior
#'
#'
#' Generate a configuration object to specify a prior on the hyperparameter \eqn{\gamma} for the Dirichlet prior on the
#' mixture weights.
#' We assume \eqn{\gamma \sim Gamma(a,b)}. Alternatively, we can fix \eqn{\gamma} to a specific value.
#' Default is \eqn{\gamma=1/N}, where N is the number of observations.
#'In AntMAN we assume the following
#' parametrization of the Gamma density:
#' \deqn{p(x\mid a,b )= \frac{b^a x^{a-1}}{\Gamma(a)} \exp\{ -bx \}, \quad x>0.}
#'
#'@param a The shape parameter a of the Gamma prior.
#'@param b The rate parameter b of the Gamma prior.
#'@param init The init value for \eqn{\gamma}, when we assume \eqn{\gamma} random.
#'@param gamma It allows to fix \eqn{\gamma} to a specific value.
#'
#'@return A \code{\link{AM_mix_weights_prior}} object. This is a configuration list to be used as \code{mix_weight_prior} argument for \code{\link{AM_mcmc_fit}}.
#'
#'@examples
#' AM_mix_weights_prior_gamma (a=1, b=1)
#' AM_mix_weights_prior_gamma (a=1, b=1, init=1)
#' AM_mix_weights_prior_gamma (gamma = 3)
#' AM_mix_weights_prior_gamma ()
#'@export
#'@keywords prior
AM_mix_weights_prior_gamma <- function(a = NULL, b = NULL, gamma = NULL, init = NULL) {
paradox_error = "Please note that you cannot specify a,b,init and gamma. gamma specifies a fixed value.";
parameters = list(type = "AM_mix_weights_prior_gamma");
if (!is.null(a) & !is.null(b)) {
parameters = list(type = "AM_mix_weights_prior_gamma", a = a, b = b);
if (!is.null(init)) {
parameters = list(type = "AM_mix_weights_prior_gamma", a = a, b = b, init = init)
};
if (!is.null(gamma)) {
stop ( paradox_error );
};
} else if (!is.null(gamma)) {
parameters = list(type = "AM_mix_weights_prior_gamma", gamma = gamma);
if (!is.null(a) | !is.null(b) | !is.null(init)) {
stop ( paradox_error );
}
} else {
if (!is.null(a) | !is.null(b) | !is.null(init)) {
stop ( paradox_error );
}
};
return ( structure(
parameters,
class = "AM_mix_weights_prior")
) ;
};
| /scratch/gouwar.j/cran-all/cranData/AntMAN/R/AM_mix_weights_prior.R |
#######################################################################################
###############
############### AntMAN Package
###############
###############
#######################################################################################
# density_discrete_variables is internal
#
density_discrete_variables <- function(Par, color=rgb(0.4, 0.8, 1, alpha=0.7), single_maxy=TRUE, title, ...){
rows <- dim(Par)[2]
fun <- function(xx){
return(table(xx)/length(xx))
}
tables <- lapply(Par,fun)
#cat("maxy is",maxy,"\n")
if(single_maxy){
maxy=rep(0,rows)
for(r in 1:rows){
maxy[r]=as.numeric(max(tables[[r]]))
}
# print("ciao")
}else{
maxy <- rep(max(unlist(tables)),rows)
}
oldpar <- par(no.readonly = TRUE)
on.exit(par(oldpar))
par(mfrow=c(rows,1))
for(r in 1:rows){
plot(tables[[r]],lwd=8,col=color,ylim=c(0,maxy[r]),xlab=names(tables)[r],ylab="p.m.f.", main=title,...)
}
}
#' Plot \code{\link{AM_mcmc_output}} scatterplot matrix
#'
#' visualise a matrix of plots describing the MCMC results. This function is built upon GGally's plotting function ggpairs \insertCite{GGally}{AntMAN}.
#'
#'@param x an \code{\link{AM_mcmc_output}} object, produced by calling \code{\link{AM_mcmc_fit}}.
#'@param tags A list of variables to consider for plotting. This function only produces meaningful plots for variables that have fixed dimension across the draws. If not specified, plots pertaining to M and K will be produced.
#'@param title Title for the plot.
#'@return Same as ggpairs function, a ggmatrix object that if called, will print.
#'@importFrom graphics image
#'@importFrom GGally ggpairs
#'@importFrom grDevices gray.colors
#'@export
AM_plot_pairs=function(x,tags = NULL,title = "MCMC Results"){
targets = tags
if (is.null(targets)) {
if (!is.null(x$M)) {targets = c(targets,"M")}
if (!is.null(x$K)) {targets = c(targets,"K")}
}
message("Plotting pairs from ",paste(targets,collapse=","));
if (length(targets) > 0) {
df = data.frame(AM_extract(x,targets))
ggpairs(df, title = title, upper = list(continuous = "points"),) + ggplot2::labs(title=title)
}
}
#' Plot the density of variables from \code{\link{AM_mcmc_output}} object
#'
#'
#' Given an \code{\link{AM_mcmc_output}} object, AM_plot_density plots the posterior density of the specified variables of interest. AM_plot_density makes use
#' of bayesplot's plotting function mcmc_areas \insertCite{bayesplot}{AntMAN}.
#'
#'
#'@param x An \code{\link{AM_mcmc_output}} fit object, produced by calling \code{\link{AM_mcmc_fit}}.
#'@param tags A list of variables to consider. This function only produces meaningful plots for variables that have fixed dimension across the draws.
#'@param title Title for the plot.
#'@return a ggplot object visualising the posterior density of the specified variables.
#'@importFrom bayesplot mcmc_areas color_scheme_set
#'@export
AM_plot_density=function(x,tags = NULL,title = "MCMC Results"){
targets = tags
if (is.null(targets)) {
stop('Please supplement arguments to tags. tags cannot be NULL.')
}
message("Plotting density from ",paste(targets,collapse=","));
if (length(targets) > 0) {
df = data.frame(AM_extract(x,targets))
color_scheme_set("brightblue")
mcmc_areas(df)+ ggplot2::labs(title=title)
}
}
#' Plot the probability mass function of variables from \code{\link{AM_mcmc_output}} object
#'
#'
#' Given an \code{\link{AM_mcmc_output}} object, AM_plot_pmf plots the posterior probability mass function of the specified variables.
#'
#'@param x An \code{\link{AM_mcmc_output}} object, produced by calling \code{\link{AM_mcmc_fit}}.
#'@param tags A list of variables to consider. If not specified, the pmf of both M and K will be plotted.
#'@param title Title for the plot.
#'@return No return value. Called for side effects.
#'@importFrom grDevices rgb
#'@export
AM_plot_pmf=function(x,tags = NULL,title = "MCMC Results"){
targets = tags
if (is.null(targets)) {
if (!is.null(x$M)) {targets = c(targets,"M")}
if (!is.null(x$K)) {targets = c(targets,"K")}
}
message("Plotting pmf for ",paste(targets,collapse=","));
if (length(targets) > 0) {
df = data.frame(AM_extract(x,targets))
density_discrete_variables(df, single_maxy=TRUE, title = title)
}
}
#' Plot traces of variables from an \code{\link{AM_mcmc_output}} object
#'
#'
#' Given an \code{\link{AM_mcmc_output}} object, \code{\link{AM_plot_traces}} visualises the traceplots of the specified variables involved in the MCMC inference.
#' AM_plot_traces is built upon bayesplot's mcmc_trace \insertCite{bayesplot}{AntMAN}.
#'
#'@param x An \code{\link{AM_mcmc_output}} fit object, produced by calling \code{\link{AM_mcmc_fit}}.
#'@param tags A list of variables to consider. This function only produces meaningful plots for variables that have fixed dimension across the draws. If not specified, plots pertaining to M and K will be produced.
#'@param title Title for the plot
#'@return No return value. Called for side effects.
#'@importFrom bayesplot mcmc_trace color_scheme_set
#'@export
AM_plot_traces=function(x,tags = NULL,title = "MCMC Results"){
targets = tags
if (is.null(targets)) {
if (!is.null(x$M)) {targets = c(targets,"M")}
if (!is.null(x$K)) {targets = c(targets,"K")}
}
message("Plotting traces from ",paste(targets,collapse=","));
if (length(targets) > 0) {
df = data.frame(AM_extract(x,targets))
color_scheme_set("brightblue")
mcmc_trace(df)+ ggplot2::labs(title=title)
}
}
#' Plot posterior interval estimates obtained from MCMC draws
#'
#' Given an object of class \code{\link{AM_mcmc_fit}}, AM_plot_values visualises the interval estimates of the specified variables involved in the MCMC inference.
#' AM_plot_values is built upon bayesplot's mcmc_intervals \insertCite{bayesplot}{AntMAN}.
#'
#'@param x An \code{\link{AM_mcmc_output}} fit object, produced by calling \code{\link{AM_mcmc_fit}}.
#'@param tags A list of variables to consider. This function only produces meaningful plots for variables that have fixed dimension across the draws. If not specified, plots pertaining to M and K will be produced.
#'@param title Title for the plot.
#'@return No return value. Called for side effects.
#'@importFrom bayesplot mcmc_intervals color_scheme_set
#'@export
AM_plot_values=function(x,tags = NULL,title = "MCMC Results"){
targets = tags
if (is.null(targets)) {
if (!is.null(x$M)) {targets = c(targets,"M")}
if (!is.null(x$K)) {targets = c(targets,"K")}
}
message("Plotting values from ",paste(targets,collapse=","));
if (length(targets) > 0) {
df = data.frame(AM_extract(x,targets))
color_scheme_set("brightblue")
mcmc_intervals(df)+ ggplot2::labs(title=title)
}
}
#' Plot the Similarity Matrix
#'
#'
#' Given an \code{\link{AM_mcmc_output}} object, this function will produce an image of the Similarity Matrix.
#'
#'@param x An \code{\link{AM_mcmc_output}} fit object, produced by calling \code{AM_mcmc_fit}.
#'@param loss Loss function to minimise. Specify either "VI" or "binder". If not specified, the default loss
#' to minimise is "binder".
#'@param ... All additional parameters wil lbe pass to the image command.
#'@return No return value. Called for side effects.
#'@importFrom graphics title
#'@export
AM_plot_similarity_matrix = function(x, loss, ...){
CCM = AM_coclustering(x)
CM = AM_clustering(x)
if (loss == 'VI'){
eam = CM
}
else{
eam = CCM
}
hatc = AM_salso(eam, loss, 'maxZealousAttempts'=0, 'probSequentialAllocation'=1)
par(mar=c(5,5,5,5))
image(CCM[sort(hatc), sort(hatc)], axes=FALSE)
axis(side=1, at=seq(0,1,length.out=ncol(CCM)), labels=sort(hatc), las=2)
axis(side=2, at=seq(0,1,length.out=ncol(CCM)), labels=sort(hatc), las=2)
title(main = "Ordered Similarity Matrix", cex.main=0.7)
}
# AM_plot_similarity_matrix=function(x, loss, ...){
# sorted = TRUE
# arguments <- list(...)
# if ("sorted" %in% names(arguments)) {
# sorted = arguments[[sorted]]
# }
# if (!is.null(x$CI)) {
# message("Plotting Similarity Matrix");
# pij = AM_clustering(x)
# clustering = AM_salso(pij, loss=loss)
# # binder_result = AM_binder(x)
# # clustering = binder_result[["Labels"]]
# # pij = AM_coclustering(x)
# if (sorted) {
# new_indexes = order(clustering, decreasing = TRUE)
# pij = pij[new_indexes,new_indexes];
# }
# image(pij,main="Similarity matrix")
# } else {
# warning("CI has not been generated. Cannot plot the similarity matrix.")
# }
# }
#' Plot the Autocorrelation function
#'
#'
#'
#' Given an \code{\link{AM_mcmc_output}} object, this function produces the autocorrelation function bars describing the MCMC results. AM_plot_chaincor makes use of bayesplot’s
#' plotting function mcmc_acf_bar \insertCite{bayesplot}{AntMAN}.
#'
#'@param x An \code{\link{AM_mcmc_output}} object, produced by calling \code{\link{AM_mcmc_fit}}.
#'@param tags A list of variables to consider. This function only produces meaningful plots for variables that have fixed dimension across the draws. If not specified, plots pertaining to M and K will be produced.
#'This function is built upon bayesplot's \code{mcmc_acf_bar}.
#'@param lags An integer specifying the number of lags to plot. If no value is specified, the default number of lags shown is half the total number of iterations.
#'@param title Title for the plot.
#'
#'@return A ggplot object.
#'@importFrom bayesplot mcmc_acf_bar
#'@export
AM_plot_chaincor=function(x, tags = NULL, lags = NULL, title = "MCMC Results"){
targets = tags
if (is.null(targets)) {
if (!is.null(x$M)) {targets = c(targets,"M")}
if (!is.null(x$K)) {targets = c(targets,"K")}
# if (!is.null(x$MNA)) {targets = c(targets,"MNA")}
# if (!is.null(x$H) && (length(x$H) > 0) && (length(x$H[[1]]) > 0)) {targets = c(targets,paste0("H_",names(x$H[[1]])))}
# if (!is.null(x$Q) && (length(x$Q) > 0) && (length(x$Q[[1]]) > 0)) {targets = c(targets,paste0("Q_",names(x$Q[[1]])))}
}
message("Plotting Autocorrelation from ",paste(targets,collapse=","))
if (length(targets) > 0) {
df = data.frame(AM_extract(x,targets))
if (is.null(lags)) {
lags = floor(dim(df)[1]/2)
}
color_scheme_set("brightblue")
mcmc_acf_bar(df, lags = lags)+ ggplot2::labs(title=title)
}
}
#' Visualise the cluster frequency plot for the multivariate bernoulli model
#'
#'
#' Given an \code{\link{AM_mcmc_output}} object, and the data the model was fit on, this function will produce a cluster frequency plot for the multivariate bernoulli model.
#'
#'@param fit An \code{\link{AM_mcmc_output}} fit object, produced by calling \code{AM_mcmc_fit}.
#'@param y A matrix containing the y observations which produced fit.
#'@param x_lim_param A vector with two elements describing the plot's x_axis scale, e.g. c(0.8, 7.2).
#'@param y_lim_param A vector with two elements describing the plot's y_axis scale, e.g. c(0, 1).
#'
#'@return No return value. Called for side effects.
#'@importFrom grDevices n2mfrow
#'@importFrom graphics axis
#'@export
AM_plot_mvb_cluster_frequency = function(fit, y, x_lim_param= c(0.8, 7.2), y_lim_param = c(0,1)){
eam = AM_clustering(fit)
result = AM_salso(eam, "binder")
hatc = result
hatk = length(unique(hatc))
ci = t(do.call(cbind,fit$CI)) +1
# obtain dim of y
y_dim = dim(y)[2]
G = length(fit$K)
n = length(hatc)
thetapost <- array(0,dim=c(G,n,y_dim))
for(g in 1:G){
thetapost[g,,] =fit$theta[[g]][ci[g,],]
}
thetahat <- apply(thetapost,c(2,3),mean)
# obtain col names (if any)
col_names = colnames(y)
oldpar <- par(no.readonly = TRUE)
on.exit(par(oldpar))
par(mfrow=rev(n2mfrow(hatk)))
for(j in 1:hatk){
plot(1:y_dim,apply(thetahat[hatc==j,],2, mean),type="h",xaxt="n",
xlim = x_lim_param, ylim= y_lim_param ,col=j, lwd=2, xlab = "",
ylab = expression(hat(theta)), main=paste("Group", j))
lines((1:y_dim)+0.1, apply(y[hatc==j,],2,mean), type="h",xaxt="n",
xlim = x_lim_param, ylim = y_lim_param, col=j, lwd=2, ylab="",lty=2)
axis(1, at=1:y_dim, labels = col_names)
}
}
| /scratch/gouwar.j/cran-all/cranData/AntMAN/R/AM_plot.R |
#######################################################################################
###############
############### AntMAN Package
###############
###############
#######################################################################################
#' S3 class AM_prior
#' @description Object type returned by \code{AM_prior_*} commands.
#' @seealso \code{\link{AM_prior_K_Delta}}, \code{\link{AM_prior_K_Pois}}, \code{\link{AM_prior_K_NegBin}}
#' @name AM_prior
#' @return \code{\link{AM_prior}}
NULL
#' plot AM_prior
#'
#'
#' plot the prior on the number of clusters for a given \code{\link{AM_prior}} object.
#'
#'@param x an \code{\link{AM_prior}} object. See \code{\link{AM_prior_K_Delta}}, \code{\link{AM_prior_K_NegBin}},
#' \code{\link{AM_prior_K_Pois}} for more details.
#'@param ... all additional parameters are ignored.
#'@return NULL. Called for side effects.
#'
#'@method plot AM_prior
#'@importFrom graphics image
#'@importFrom graphics par
#'@importFrom grDevices gray.colors
#'@export
plot.AM_prior=function(x,...){
oldpar <- par(no.readonly = TRUE)
on.exit(par(oldpar))
n = length(x)
par(mar=c(3,3,1.5,0.5)+0.1)
par(mgp=c(2, 1.0, 0))
title = sprintf("Prior on the number of clusters,\nn=%d with %s", n, attr(x,'type'))
plot(1:n, x, type = "n", bty = "l", xlab = "k",
ylab = expression(paste("P(",K[n],"=k)")),
main = title,
xlim=c(.5,20),cex.main=0.8)
lines(1:n,x,type="h",lwd=3)
#legend(x="topright",legend=c("INFORMATION"),col=c(1,2,3),lty=1,lwd=2,cex=1.5)
}
#' summary information of the AM_prior object
#'
#'
#' Given an \code{\link{AM_prior}} object, this function prints the summary information of the specified prior on the number of clusters.
#'
#'@param object an \code{\link{AM_prior}} object. See \code{\link{AM_prior_K_Delta}}, \code{\link{AM_prior_K_NegBin}},
#' \code{\link{AM_prior_K_Pois}} for more details.
#'@param ... all additional parameters are ignored.
#'@return NULL. Called for side effects.
#'
#'@method summary AM_prior
#'@seealso \code{\link{AM_prior}}
#'@export
summary.AM_prior = function(object, ...){
quantiles = c(0.025, 0.25, 0.5, 0.75, 0.975)
cat("\n", "AM_Prior = ", attr(object,'type'), "\n", sep = "")
cat(" - n = ", attr(object,'n'), "\n", sep = "")
cat(" - mean = ", mean(object, na.rm = TRUE), "\n", sep = "")
cat(" - var = ", var(object, na.rm = TRUE), "\n", sep = "")
cat(" - Quantiles:\n\n")
print(quantile(object, quantiles), ...)
cat("\n")
}
#' Computes the prior number of clusters
#'
#'
#' This function computes the prior on the number of clusters, i.e. occupied components of the mixture for a Finite Dirichlet process when the prior on the component-weights of the mixture is a
#' Dirichlet with parameter \code{gamma} (i.e. when unnormalized weights are distributed as Gamma(\eqn{\gamma},1)). This function can be used when the prior on the number of
#' components is Shifted Poisson of parameter \code{Lambda}. See \insertCite{argiento2019infinity}{AntMAN} for more details.
#'
#' There are no default values.
#'
#' @param n The sample size.
#' @param Lambda The \code{Lambda} parameter of the Poisson.
#' @param gamma The \code{gamma} parameter of the Dirichlet distribution.
#'
#' @return an \code{\link{AM_prior}} object, that is a vector of length n, reporting the values of the prior on the number of clusters induced by the prior on \code{M} and \code{w}, i.e. \code{p^*_k} for \code{k=1,...,n}. See \insertCite{argiento2019infinity}{AntMAN} for more details.
#'
#' @keywords prior number of clusters
#'
#' @export
#'
#' @examples
#' n <- 82
#' Lambda <- 10
#' gam_po <- 0.1550195
#' prior_K_po <- AM_prior_K_Pois(n,gam_po,Lambda)
#' plot(prior_K_po)
AM_prior_K_Pois <- function (n,gamma,Lambda) {
res = (prior_K_Pois(n,gamma,Lambda));
return ( structure(
res,
type = sprintf("%s(Gamma=%f,Lambda=%f)","Poisson", gamma,Lambda) ,
n = n,
gamma = gamma,
Lambda = Lambda,
class = "AM_prior")
) ;
}
#' computes the prior number of clusters
#'
#'
#' This function computes the prior on the number of clusters, i.e. occupied component of the mixture for a Finite Dirichlet process when the
#' prior on the component-weights of the mixture is a Dirichlet with parameter \code{gamma} (i.e. when unnormalized weights are distributed as
#' Gamma(\eqn{\gamma},1)). This function can be used when the prior on the number of components is Negative Binomial with parameter \eqn{r>0} and
#' \eqn{0<p<1}, with mean \eqn{mu =1+ r*p/(1-p)}. See \insertCite{argiento2019infinity}{AntMAN} for more details.
#'
#' There are no default values.
#'
#' @param n The sample size.
#' @param r The dispersion parameter \code{r} of the Negative Binomial.
#' @param p The probability of failure parameter \code{p} of the Negative Binomial.
#' @param gamma The \code{gamma} parameter of the Dirichlet distribution.
#'
#' @return an \code{\link{AM_prior}} object, that is a vector of length n, reporting the values \code{V(n,k)} for \code{k=1,...,n}.
#'
#' @keywords prior number of cluster
#'
#' @export
#'
#' @examples
#' n <- 50
#' gamma <- 1
#' r <- 0.1
#' p <- 0.91
#' gam_nb <- 0.2381641
#' prior_K_nb <- AM_prior_K_NegBin(n,gam_nb,r,p)
#' plot(prior_K_nb)
AM_prior_K_NegBin <- function (n,gamma, r, p){
res = (prior_K_NegBin(n,gamma, r, p));
return ( structure(
res,
type = sprintf("%s(Gamma=%f,r=%f,p=%f)","NegBin", gamma,r,p) ,
n = n,
gamma = gamma,
r = r,
p = p,
class = "AM_prior")
) ;
}
#' Computes the prior on the number of clusters
#'
#'
#' This function computes the prior on the number of clusters, i.e. occupied components of the mixture for a Finite Dirichlet process
#' when the prior on the component-weights of the mixture is a Dirichlet with parameter \code{gamma} (i.e. when unnormalised weights
#' are distributed as Gamma(\eqn{\gamma},1)). This function can be used when the number of components is fixed to \eqn{M^*}, i.e.
#' a Dirac prior assigning mass only to \eqn{M^*} is assumed. See \insertCite{argiento2019infinity}{AntMAN} There are no default values.
#'
#' @param n The sample size.
#' @param Mstar The number of component of the mixture.
#' @param gamma The \code{gamma} parameter of the Dirichlet distribution.
#'
#' @return an \code{\link{AM_prior}} object, that is a vector of length n, reporting the values \code{V(n,k)} for \code{k=1,...,n}.
#'
#' @keywords prior number of cluster
#'
#' @export
#'
#' @examples
#' n <- 82
#' gam_de <- 0.1743555
#' Mstar <- 12
#' prior_K_de <- AM_prior_K_Delta(n,gam_de, Mstar)
#' plot(prior_K_de)
AM_prior_K_Delta <- function (n,gamma,Mstar){
res = prior_K_Delta(n,gamma,Mstar);
return ( structure(
res,
type = sprintf("%s(Gamma=%f,Mstar=%d)","Delta", gamma,Mstar) ,
n = n,
gamma = gamma,
Mstar = Mstar,
class = "AM_prior")
) ;
}
| /scratch/gouwar.j/cran-all/cranData/AntMAN/R/AM_prior.R |
#######################################################################################
###############
############### AntMAN Package
###############
###############
#######################################################################################
library(mvtnorm)
#' AM_sample_uninorm
#'
#' @keywords internal
#' @export
AM_sample_uninorm <- function(n,pro,mmu,ssd){
if(length(mmu)!=length(pro)){stop()}
if(length(ssd)!=length(pro)){stop()}
y <- vector(length=n)
ci <- vector(length=n)
for(i in 1:n){
u <- runif(1)
if(u<pro[1]){
ci[i] <- 0
y[i] <- rnorm(1,mean=mmu[1],sd=ssd)
}
else{
if(u<(pro[1]+pro[2])){
ci[i] <- 1
y[i] <- rnorm(1,mean=mmu[2],sd=ssd[2])
}
else{
ci[i] <- 2
y[i] <- rnorm(1,mean=mmu[3],sd=ssd[3])
}
}
}
return(list(y=y,ci=ci))
}
#' AM_sample_unipois
#'
#'
#' @keywords internal
#' @export
AM_sample_unipois <- function(n=1000,pro=c(0.2,0.5,0.3),mth=c(5,25,50)){
if(length(mth)!=length(pro)){stop()}
y <- vector(length=n)
ci <- vector(length=n)
for(i in 1:n){
u <- runif(1)
if(u<pro[1]){
ci[i] <- 0
y[i] <- rpois(1,lambda=mth[1])
}
else{
if(u<(pro[1]+pro[2])){
ci[i] <- 1
y[i] <- rpois(1,lambda=mth[2])
}
else{
ci[i] <- 2
y[i] <- rpois(1,lambda=mth[3])
}
}
}
return(list(y=y,ci=ci))
}
# #' AM_sample_unibin
# #'
# #'
# #' @keywords internal
# #' @export
# AM_sample_unibin <- function(n,mb, pro,mth){
# if(length(mth)!=length(pro)){stop()}
# y <- vector(length=n)
# ci <- vector(length=n)
# for(i in 1:n){
# u <- runif(1)
# if(u<pro[1]){
# ci[i] <- 0
# y[i] <- rbinom(1, size=mb, prob=mth[1])
# }
# else{
# if(u<(pro[1]+pro[2])){
# ci[i] <- 1
# y[i] <- rbinom(1, size=mb, prob=mth[2])
# }
# else{
# ci[i] <- 2
# y[i] <- rbinom(1, size=mb, prob=mth[3])
# }
# }
# }
# return(list(y=y,ci=ci))
# }
# #' AM_sample_multibin
# #'
# #'
# #' @keywords internal
# #' @export
# AM_sample_multibin <- function(n,d,pro,TH){
# y <- matrix(nrow=n,ncol=d)
# ci <- vector(length=n)
# for(i in 1:n){
# u <- runif(1)
# if(u<pro[1]){
# ci[i] <- 0
# y[i,] <-rbinom(d, rep(1,d), TH[1,])
# }
# else{
# if(u<(pro[1]+pro[2])){
# ci[i] <- 1
# y[i,] <-rbinom(d, rep(1,d), TH[2,])
# }
# else{
# ci[i] <- 2
# y[i,] <-rbinom(d, rep(1,d), TH[3,])
# }
# }
# }
# return(list(y=y,ci=ci))
# }
#' AM_sample_multinorm
#'
#' @keywords internal
#' @importFrom mvtnorm rmvnorm
#' @export
AM_sample_multinorm <- function(n,d,pro,MU,SIG){
if(dim(SIG)[1]!=length(pro)){stop()}
y <- matrix(nrow=n,ncol=d)
ci <- vector(length=n)
for(i in 1:n){
u <- runif(1)
if(u<pro[1]){
ci[i] <- 0
y[i,] <-rmvnorm(1, mean = MU[1,], sigma = SIG[1,,])
}
else{
if(u<(pro[1]+pro[2])){
ci[i] <- 1
y[i,] <- rmvnorm(1, mean = MU[2,], sigma = SIG[2,,])
}
else{
ci[i] <- 2
y[i,] <- rmvnorm(1, mean = MU[3,], sigma = SIG[3,,])
}
}
}
return(list(y=y,ci=ci))
}
#' AM_sample_multibin
#'
#'
#' @keywords internal
#' @export
AM_sample_multibin <- function(n,d,pro,TH){
y <- matrix(nrow=n,ncol=d)
ci <- vector(length=n)
for(i in 1:n){
u <- runif(1)
if(u<pro[1]){
ci[i] <- 0
y[i,] <-rbinom(d, rep(1,d), TH[1,])
}
else{
if(u<(pro[1]+pro[2])){
ci[i] <- 1
y[i,] <-rbinom(d, rep(1,d), TH[2,])
}
else{
ci[i] <- 2
y[i,] <-rbinom(d, rep(1,d), TH[3,])
}
}
}
return(list(y=y,ci=ci))
}
| /scratch/gouwar.j/cran-all/cranData/AntMAN/R/AM_sample.R |
#######################################################################################
###############
############### AntMAN Package
###############
###############
#######################################################################################
#################################################################################
##### Datasets Definition
#################################################################################
#' Usage frequency of the word "said" in the Brown corpus
#'
#'@format A list with 500 observations on the frequency of said in different texts.
#'
#'@source https://www.kaggle.com/nltkdata/brown-corpus
#'@references Francis, W., and Kucera, H. (1982) Frequency Analysis of English Usage, Houghton Mifflin Company, Boston.
#'@examples
#' data(said)
#'@keywords datasets
#'@docType data
"said"
#' Galaxy velocities dataset
#'
#' This data set considers the physical information of velocities (10^3 km/second) for
#' 82 galaxies reported by Roeder (1990). These are drawn from six well-separated
#' conic sections of the Corona Borealis region.
#'
#'@format A data frame with X rows and Y variables.
#'
#'@format A numeric vector giving the speed of galaxies (1000*(km/second))
#'@examples
#' data(galaxy)
#'@source Roeder, K. (1990). Density estimation with confidence sets exemplified by superclusters and voids in the galaxies, Journal of the American Statistical Association, 85: 617-624.
#'@keywords datasets
#'@docType data
"galaxy"
#' Carcinoma dataset
#'
#'
#' The carcinoma data from Agresti (2002, 542) consist of seven dichotomous variables representing
#' the ratings by seven pathologists of 118 slides on the presence or absence of carcinoma.
#' The purpose of studying this data is to model "interobserver agreement" by examining how
#' subjects might be divided into groups depending upon the consistency of their diagnoses.
#'
#'@format A data frame with 118 rows and 7 variables (from A to G).
#'
#'@references Agresti A (2002). Categorical Data Analysis. John Wiley & Sons, Hoboken.
#'
#'@examples
#' data(carcinoma)
#'
#'@keywords datasets
#'@docType data
"carcinoma"
#' Teen Brain Images from the National Institutes of Health, U.S.
#'
#' Picture of brain activities from a teenager consuming drugs.
#'
#'@format A list that contains \code{dim} a (W:width,H:height) pair, and \code{pic} a data frame (W*H pixels image in RGB format).
#'
#'@source https://www.flickr.com/photos/nida-nih/29741916012
#'@references Crowley TJ, Dalwani MS, Mikulich-Gilbertson SK, Young SE, Sakai JT, Raymond KM, et al. (2015) Adolescents' Neural Processing of Risky Decisions: Effects of Sex and Behavioral Disinhibition. PLoS ONE 10(7): e0132322. doi:10.1371/journal.pone.0132322
#'
#'@examples
#' data(brain)
#'
#'@keywords datasets
#'@docType data
"brain"
| /scratch/gouwar.j/cran-all/cranData/AntMAN/R/AntMANDatasets.R |
#######################################################################################
###############
############### AntMAN Package
###############
###############
#######################################################################################
#################################################################################
##### Package Definition
#################################################################################
#' AntMAN: A package for fitting finite Bayesian Mixture models with a random number of components
#'
#'@description AntMAN: Anthology of Mixture ANalysis tools
#' AntMan is an R package fitting Finite Bayesian Mixture models with a random number of components.
#' The MCMC algorithm behind AntMAN is based on point processes and offers a more computationally
#' efficient alternative to the Reversible Jump.
#' Different mixture kernels can be specified: univariate Gaussian, multivariate Gaussian, univariate Poisson,
#' and multivariate Bernoulli (Latent Class Analysis). For the parameters characterising the mixture kernel, we specify
#' conjugate priors, with possibly user specified hyper-parameters.
#' We allow for different choices on the prior on the number of components:
#' Shifted Poisson, Negative Binomial, and Point Masses (i.e. mixtures with fixed number of components).
#'
#'
#'@section Package Philosophy:
#'
#' The main function of the AntMAN package is \code{\link{AM_mcmc_fit}}. AntMAN performs a Gibbs sampling in order to fit,
#' in a Bayesian framework, a mixture model of a predefined type \code{mix_kernel_hyperparams} given a sample \code{y}.
#' Additionally AntMAN allows the user to specify a prior on the number of components \code{mix_components_prior} and on the weights \code{mix_weight_prior} of the mixture.
#' MCMC parameters \code{mcmc_parameters} need to be given as argument for the Gibbs sampler (number of interations, burn-in, ...).
#' Initial values for the number of clusters (\code{init_K}) or a specific clustering allocation (\code{init_clustering}) can also be user-specified.
#' Otherwise, by default, we initialise each element of the sample \code{y} to a different cluster allocation. This choice can be computationally inefficient.
#'
#'
#' For example, in order to identify clusters over a population of patients given a set of medical assumptions:
#'
#'```
#' mcmc = AM_mcmc_parameters(niter=20000)
#' mix = AM_mix_hyperparams_multiber ()
#' fit = AM_mcmc_fit (mix, mcmc)
#' summary (fit)
#'```
#'
#' In this example \code{AM_mix_hyperparams_multiber} is one of the possible mixtures to use.
#'
#' AntMAN currently support four different mixtures :
#'
#' ```
#' AM_mix_hyperparams_unipois(alpha0, beta0)
#' AM_mix_hyperparams_uninorm(m0, k0, nu0, sig02)
#' AM_mix_hyperparams_multiber(a0, b0)
#' AM_mix_hyperparams_multinorm(mu0, ka0, nu0, Lam0)
#' ```
#'
#' Additionally, three types of kernels on the prior number of components are available:
#'
#' ```
#' AM_mix_components_prior_pois()
#' AM_mix_components_prior_negbin()
#' AM_mix_components_prior_dirac()
#' ```
#'
#' For example, in the context of image segmentation, if we know that there are 10 colours present, a prior dirac can be used :
#'
#' ```
#' mcmc = AM_mcmc_parameters(niter=20000)
#' mix = AM_mix_hyperparams_multinorm ()
#' prior_component = AM_mix_components_prior_dirac(10) # 10 colours present
#' fit = AM_mcmc_fit (mix, prior_component, mcmc)
#' summary (fit)
#' ```
#'
#'@importFrom Rcpp evalCpp
#'@importFrom stats kmeans rbinom rnorm rpois runif sd acf density quantile var
#'@importFrom graphics plot hist rasterImage abline layout legend lines
#'@importFrom salso dlso
#'@docType package
#'@name AntMAN
NULL
| /scratch/gouwar.j/cran-all/cranData/AntMAN/R/AntMANPackage.R |
#######################################################################################
###############
############### AntMAN Package
###############
###############
#######################################################################################
## This function produce nice representation of the posterior chain
## of univariate hyperparameter
univariate_plot <- function(chain, main_trace="Trace plot", main_auto="Autocorrelation",main_hist="Histogram",col_hist="gray",col_dens="blue",col_quant="red",nclass="fd",lag_acf=30){
### A nice plot to synthesize our analysis on the parameter theta!
### Please try to understand the code
#x11()
if(length(unique(chain))==1){
warning("The chain is constant")
stop();
}
## Representation of the posterior chain of theta
#Divide the plot device in three sub-graph regions
#two square on the upper and a rectangle on the bottom
layout(matrix(c(1,2,3,3),2,2,byrow=TRUE))
#trace-plot of the posterior chain
plot(chain,type="l",main=main_trace)
# autocorrelation plot
acf(chain,main=main_auto,lag.max=lag_acf)
#Histogram
hist(chain,nclass=nclass,freq=FALSE,main=main_hist,col=col_hist)
## Overlap the kernel-density
lines(density(chain),col=col_dens,lwd=2)
## Posterior credible interval of beta0
## quantile(chain,prob=c(0.05,0.5,0.95))
## We Display the posterior credible interval on the graph
abline(v=quantile(chain,prob=c(0.05)),col=col_quant,lty=2,lwd=2)
abline(v=quantile(chain,prob=c(0.5)),col=col_quant,lty=1,lwd=2)
abline(v=quantile(chain,prob=c(0.95)),col=col_quant,lty=2,lwd=2)
## Add the legend to the plot
legend("topright",legend=c("posterior median", "95% Credible bounds","kernel density smoother"),lwd=c(2,2,2), col=c(col_quant,col_quant,col_dens),lty=c(1,2,1))
layout(matrix(c(1,1,1,1),1,1,byrow=TRUE))
}
| /scratch/gouwar.j/cran-all/cranData/AntMAN/R/INTERNAL_functions_antman_uninorm.R |
#######################################################################################
###############
############### AntMAN Package
###############
###############
#######################################################################################
#################################################################################
##### Raffaele Functions
#################################################################################
#' Compute the logarithm of the absolute value of the generalized Sriling number of second Kind (mi pare) See charambeloides, using a recursive formula Devo vedere la formula
#'
#' There are no default values.
#'
#' @param n The sample size
#' @param gamma A positive real number \code{gamma}
#'
#' @return A vector of length n, reporting the values \code{C(gamma,n,k)} for \code{k=1,...,n}
#'
#' @keywords internal
#'
IAM_compute_stirling_ricor_abs <- function (n,gamma) {
return(compute_stirling_ricor_abs(n,gamma));
}
#' Compute stirling ricor log
#'
#' There are no default values.
#'
#' @param n The sample size
#' @param gamma A positive real number \code{gamma}
#'
#' @return A vector of length n, reporting the values ... for \code{k=1,...,n}
#'
#' @keywords internal
IAM_compute_stirling_ricor_log<- function (n,gamma) {
return(compute_stirling_ricor_log(n,gamma));
}
#' Compute the value V(n,k), needed to caclulate the eppf of a Finite Dirichlet process when the prior on the component-weigts of the mixture is a Dirichlet with parameter \code{gamma} (i.e. when unnormailized weights are distributed as Gamma(\eqn{\gamma},1) ) when the prior on the number of componet is Shifted Poisson of parameter \code{Lambda}. See Section 9.1.1 of the Paper Argiento de Iorio 2019.
#'
#' There are no default values.
#'
#' @param n The sample size
#' @param Lambda The \code{Lambda} parameter of the Poisson
#' @param gamma The \code{gamma} parameter of the Dirichlet
#'
#' @return A vector of length n, reporting the values \code{V(n,k)} for \code{k=1,...,n}
#'
#' @keywords internal
#'
IAM_VnkPoisson <- function (n,Lambda,gamma) {
return(VnkPoisson(n,Lambda,gamma));
}
#' Compute the value V(n,k), needed to caclulate the eppf of a Finite Dirichlet process when the prior on the component-weigts of the mixture is a Dirichlet with parameter \code{gamma} (i.e. when unnormailized weights are distributed as Gamma(\eqn{\gamma},1) ) when the prior on the number of componet is Negative Binomial with parameter \code{r} and \code{p}with mean is mu =1+ r*p/(1-p) TODO: CHECK THIS FORMULA!!!. See Section 9.1.1 of the Paper Argiento de Iorio 2019 for more details
#'
#' There are no default values.
#'
#' @param n The sample size
#' @param r The dispersion parameter \code{r} of Negative Binomial
#' @param p The probability of failure parameter \code{p} of Negative Binomial
#' @param gam The \code{gamma} parameter of the Dirichlet
#'
#' @return A vector of length n, reporting the values \code{V(n,k)} for \code{k=1,...,n}
#'
#' @keywords internal
#'
IAM_VnkNegBin <- function (n,r,p,gam) {
return(VnkNegBin(n,r,p,gam));
}
#' Compute the value V(n,k), needed to caclulate the eppf of a Finite Dirichlet process when the prior on the component-weigts
#' of the mixture is a Dirichlet with parameter \code{gamma} (i.e. when unnormailized weights are distributed as Gamma(\eqn{\gamma},1) )
#' when the number of component are fixed to \code{M^*}, i.e. a Dirac prior assigning mass only to \code{M^*} is assumed.
#' See Section 9.1.1 of the Paper Argiento de Iorio 2019 for more details.
#'
#' There are no default values.
#'
#' @param n The sample size
#' @param Mstar The number of component of the mixture
#' @param gamma The \code{gamma} parameter of the Dirichlet
#'
#' @return A vector of length n, reporting the values \code{V(n,k)} for \code{k=1,...,n}
#'
#' @keywords internal
#'
IAM_VnkDelta <- function (n,Mstar,gamma) {
return(VnkDelta(n,Mstar,gamma));
}
#' IAM_mcmc_neff MCMC Parameters
#'
#' TBD
#'
#'@keywords internal
#'@param unichain
#'@return Effective Sample Size
IAM_mcmc_neff <- function(unichain){ # Using 11.5 of Bayesian Data Analysis
# Dunson Ventari Rubin Section 11.5
# Whit rho estimated using the acf function of R
G <- length(unichain)
rho=acf(unichain,lag.max=G, plot=FALSE)$acf
differenza <- rho[1:(G-1)]+rho[2:(G)]
wh_neg=which(differenza<0)
if (length(wh_neg) == 0) {
return (NaN);
}
TT=min(wh_neg)
if( TT%%2!=1){TT= TT+1}
denom=1+2*sum(rho[2:(TT)])
return(G/denom)
}
#' Internal function used to compute the MCMC Error as a batch mean.
#'
#'@keywords internal
#'@param X is a chain
#'@return the MCMC Error (sqrt(sigma2) / sqrt(N))
IAM_mcmc_error <- function(X){
N <- length(X)
b = max(1, round(sqrt(N)))
a = ceiling(N/b)
m = matrix(c(X,rep(0,a*b - N)) , nrow = a, ncol=b)
count_matrix = matrix(c(rep(1,N),rep(0,a*b - N)), nrow = a, ncol=b)
count_row = rowSums(count_matrix)
Yks = rowSums(m) / count_row # NA
mu = mean(X)
sigma2 = (b / (a - 1)) * sum((Yks - mu)**2) # NA
return ( sqrt(sigma2) / sqrt(N) ) ; # NA
}
| /scratch/gouwar.j/cran-all/cranData/AntMAN/R/INTERNAL_utilities.R |
# Generated by using Rcpp::compileAttributes() -> do not edit by hand
# Generator token: 10BE3573-1514-4C36-9D1C-5A225CD40393
IAM_mcmc_fit <- function(y, mix_kernel_hyperparams, initial_clustering, fixed_clustering, mix_components_prior, mix_weight_prior, mcmc_parameters) {
.Call('_AntMAN_IAM_mcmc_fit', PACKAGE = 'AntMAN', y, mix_kernel_hyperparams, initial_clustering, fixed_clustering, mix_components_prior, mix_weight_prior, mcmc_parameters)
}
compute_stirling <- function(n, gamma) {
.Call('_AntMAN_compute_stirling', PACKAGE = 'AntMAN', n, gamma)
}
compute_stirling_ricor <- function(n, gamma) {
.Call('_AntMAN_compute_stirling_ricor', PACKAGE = 'AntMAN', n, gamma)
}
compute_stirling_ricor_abs <- function(n, gamma) {
.Call('_AntMAN_compute_stirling_ricor_abs', PACKAGE = 'AntMAN', n, gamma)
}
compute_stirling_ricor_log <- function(n, gamma) {
.Call('_AntMAN_compute_stirling_ricor_log', PACKAGE = 'AntMAN', n, gamma)
}
VnkPoisson <- function(n, Lambda, gamma) {
.Call('_AntMAN_VnkPoisson', PACKAGE = 'AntMAN', n, Lambda, gamma)
}
VnkNegBin <- function(n, r, p, gamma) {
.Call('_AntMAN_VnkNegBin', PACKAGE = 'AntMAN', n, r, p, gamma)
}
VnkDelta <- function(n, Mstar, gamma) {
.Call('_AntMAN_VnkDelta', PACKAGE = 'AntMAN', n, Mstar, gamma)
}
prior_K_Pois <- function(n, gamma, Lambda) {
.Call('_AntMAN_prior_K_Pois', PACKAGE = 'AntMAN', n, gamma, Lambda)
}
prior_K_NegBin <- function(n, gamma, r, p) {
.Call('_AntMAN_prior_K_NegBin', PACKAGE = 'AntMAN', n, gamma, r, p)
}
prior_K_Delta <- function(n, gamma, Mstar) {
.Call('_AntMAN_prior_K_Delta', PACKAGE = 'AntMAN', n, gamma, Mstar)
}
find_gamma_Pois <- function(n, Lambda, Kstar, gam_min, gam_max, tolerance, max_iter = 30L) {
.Call('_AntMAN_find_gamma_Pois', PACKAGE = 'AntMAN', n, Lambda, Kstar, gam_min, gam_max, tolerance, max_iter)
}
find_gamma_NegBin <- function(n, r, p, Kstar, gam_min, gam_max, tolerance, max_iter = 30L) {
.Call('_AntMAN_find_gamma_NegBin', PACKAGE = 'AntMAN', n, r, p, Kstar, gam_min, gam_max, tolerance, max_iter)
}
find_gamma_Delta <- function(n, Mstar, Kstar, gam_min, gam_max, tolerance, max_iter = 30L) {
.Call('_AntMAN_find_gamma_Delta', PACKAGE = 'AntMAN', n, Mstar, Kstar, gam_min, gam_max, tolerance, max_iter)
}
| /scratch/gouwar.j/cran-all/cranData/AntMAN/R/RcppExports.R |
binary_to_table <- function(data, relative = FALSE) {
### data: matrix of binary data, + one column for the group indicator
### relative: boolean, indicates whether the last rows of the table contain
### absolute frequencies (i.e., number of individuals with each trait)
### or relative frequencies (i.e., proportions).
### Converts this data frame into a table of group sample sizes and frequencies.
## 1. Set some constants:
colnames(data)[1] <- "Group"
groupnames <- levels(data$Group)
## 2. Compute the observed sample size per group and trait
mateff <- aggregate(
x = data[, -1],
by = list(data$Group),
FUN = function(x) sum(!is.na(x))
)
## 3. Compute the observed frequency per group and trait
matfreq <- aggregate(
x = data[, -1],
by = list(data$Group),
FUN = sum,
na.rm = TRUE
)
## 4. Combine results in a matrix:
mat <- as.matrix(rbind(mateff[, -1], matfreq[, -1]))
rownames(mat) <- c(paste("N", groupnames, sep = "_"),
paste("Freq", groupnames, sep = "_"))
###########################
## 4. Return the results ##
###########################
if (relative == FALSE) {
return(mat)
} else {
return(table_relfreq(mat))
}
}
| /scratch/gouwar.j/cran-all/cranData/AnthropMMD/R/binary_to_table.R |
compute_omd <- function(data, formule, OMDvalue = 0) {
### tab: the data in 'table of frequencies' format
### formule: string, "Anscombe" or "Freeman"
### OMDvalue: OMD (overall measure of divergence) threshold for a trait to be kept
### Compute the overall measure of divergence for each trait.
### output -> list with 4 components
##################################################
## 1. Define some useful constants and matrices ##
##################################################
nb_groups <- nrow(data) / 2 # number of groups in the data
## part of the data corresponding to the sample sizes:
mat_size <- data[1:nb_groups, ]
## part of the data corresponding to the relative frequencies:
mat_freq <- data[seq(from = nb_groups + 1, to = 2 * nb_groups, by = 1), ]
## angular transformation of relative frequencies:
for (i in seq_len(nrow(mat_freq))) {
for (j in seq_len(ncol(mat_freq))) {
mat_freq[i, j] <- theta(n = mat_size[i, j],
p = mat_freq[i, j],
choice = formule)
}
}
########################
## 2. Compute the OMD ##
########################
## Initialize an empty matrix:
omd_matrix <- matrix(NA, nrow = ncol(mat_size), ncol = 1)
rownames(omd_matrix) <- colnames(mat_size)
## This will contain, for each trait, the MD between each pair of groups:
temp_matrix <- matrix(0, nrow = nb_groups, ncol = nb_groups)
## (reminder: OMD = sum of MD's)
for (i in seq_len(ncol(mat_size))) { # For each trait,
for (j in seq_len(nb_groups)) { # and for each pair of groups,
for (k in seq_len(nb_groups)) {
if (j > k) { # (strict) upper part of the matrix
temp_matrix[j, k] <- compute_md(nA = mat_size[j, i],
pA = mat_freq[j, i],
nB = mat_size[k, i],
pB = mat_freq[k, i])
}
}
}
omd_matrix[i, 1] <- sum(temp_matrix) # OMD of trait number "i"
}
## At this stage, omd_matrix = OMD values for each trait,
## sorted in the original order of traits in the data
###########################
## 3. Return the results ##
###########################
## # OMD values sorted by decreasing order:
omd_matrix_sorted <- as.matrix(omd_matrix[order(omd_matrix[, 1], decreasing = TRUE), ])
## OMD values, sorted and *greater than a given threshold*:
omd_matrix_sorted_pos <- as.matrix(omd_matrix_sorted[omd_matrix_sorted[,1] > OMDvalue, ])
## OMD values, in the original order and *greater than a given threshold*:
omd_matrix_pos <- as.matrix(omd_matrix[omd_matrix[,1] > OMDvalue, ])
return(list("Matrix" = omd_matrix,
"Pos" = omd_matrix_pos,
"Sorted" = omd_matrix_sorted,
"SortedPos" = omd_matrix_sorted_pos))
}
| /scratch/gouwar.j/cran-all/cranData/AnthropMMD/R/compute_omd.R |
fisherTestTab <- function(tab) {
### tab: data in 'table' format
### output -> a list with two components
### Check whether each trait in 'tab' exhibits a significant difference
### at Fisher's exact test for at least one pair of groups.
###########################
## 1. Set some constants ##
###########################
nb_groups <- nrow(tab) / 2 # number of groups
nb_traits <- ncol(tab) # number of traits
group_names <- extract_groups(tab, type = "table")
## Initialize an empty matrix:
res <- matrix(NA, ncol = nb_traits,
nrow = nb_groups * (nb_groups - 1) / 2)
colnames(res) <- colnames(tab)
rownames(res) <- seq_len(nrow(res)) # avoid an error in subsequent commands
#############################
## 2. Fisher's exact tests ##
#############################
for (j in seq_len(nb_traits)) { # For each trait,
counter <- 1
for (k in 1:(nb_groups - 1)) { # and each pair of groups,
for (l in seq(from = k + 1, to = nb_groups, by = 1)) {
rownames(res)[counter] <- paste(group_names[k], group_names[l], sep = " - ")
pres_group1 <- round(tab[k, j] * tab[(k + nb_groups), j])
pres_group2 <- round(tab[l, j] * tab[(l + nb_groups), j])
abs_group1 <- round(tab[k, j] * (1 - tab[(k + nb_groups), j]))
abs_group2 <- round(tab[l, j] * (1 - tab[(l + nb_groups), j]))
## Build the confusion matrix:
mat <- matrix(c(pres_group1, pres_group2, abs_group1, abs_group2),
ncol = 2)
## and run Fisher's exact test:
res[counter, j] <- fisher.test(mat)$p.value
counter <- counter + 1
}
}
}
###########################
## 3. Return the results ##
###########################
is_informative <- apply(res, MARGIN = 2, FUN = function(x) return(ifelse(any(x <= 0.05), TRUE, FALSE)))
return(list(informative = tab[, is_informative], pval = res))
}
| /scratch/gouwar.j/cran-all/cranData/AnthropMMD/R/fisherTestTab.R |
mmd <- function(data, angular = c("Anscombe", "Freeman"), correct = TRUE,
all.results = TRUE) {
### data: table of group sample sizes and frequencies,
### such as returned by the function table_relfreq
### angular: choice of a formula for angular transformation
### correct: boolean; whether to apply the correction for small samples
### all.results: boolean; if FALSE, only the symmetrical MMD matrix is computed
angular <- match.arg(angular) # avoid a warning if no arg is given
##################################################
## 1. Define some useful constants and matrices ##
##################################################
ngroups <- nrow(data) / 2
ntraits <- ncol(data)
## portion of the data corresponding to the sample sizes:
matsize <- data[1:ngroups, ]
groupnames <- rownames(matsize)
## portion of the data corresponding to the relative frequencies:
matfreq <- data[-c(1:ngroups), ]
## angular transformation of relative frequencies:
for (j in 1:ntraits) {
matfreq[, j] <- mapply(
n = matsize[, j],
p = matfreq[, j],
FUN = theta,
MoreArgs = list(choice = angular)
)
}
#######################################
## 2. Initialize some empty matrices ##
#######################################
## MMD matrix (symmetrical):
mmd_sym <- matrix(NA, nrow = ngroups, ncol = ngroups)
## the rows and columns of mmd_sym are labeled according to group names:
colnames(mmd_sym) <- substr(groupnames, 3, nchar(groupnames))
rownames(mmd_sym) <- colnames(mmd_sym)
## Other matrices:
pval_matrix <- sd_matrix <- signif_matrix <- mmd_sym
#############################
## 3. Fill in the matrices ##
#############################
for (i in 1:ngroups) {
for (j in 1:ngroups) { # For each pair of groups (i, j)...
mmd_vect <- sd_vect <- rep(NA, ntraits)
sum_pval <- 0
for (k in 1:ntraits) { # and for each trait k,
## Compute the measure of divergence on trait k:
mmd_vect[k] <- compute_md(nA = matsize[i, k],
pA = matfreq[i, k],
nB = matsize[j, k],
pB = matfreq[j, k],
correct = correct)
if (all.results) {
## Compute the SD for this trait:
sd_vect[k] <- sd_mmd(nA = matsize[i, k], nB = matsize[j, k])
## Intermediate result for computing the p-value:
sum_pval <- sum_pval + ((matfreq[i, k] - matfreq[j, k])^2 / (1 / (matsize[i, k] + 0.5) + 1 / (matsize[j, k] + 0.5)))
}
}
## The MMD is the mean of those MD values:
mmd_sym[i, j] <- max(mean(mmd_vect), 0) # replace by 0 if negative
if (all.results & (i != j)) { # avoid NaN when comparing a group to itself
## The associated SD is as follows:
sd_matrix[i, j] <- sqrt(2 * sum(sd_vect)) / ntraits
## The associated p-value:
pval_matrix[i, j] <- pchisq(sum_pval, df = ntraits,
lower.tail = FALSE)
## And finally the significance ('*' or 'NS'):
signif_matrix[i, j] <- ifelse(pval_matrix[i, j] < 0.05, "*", "NS")
}
}
}
diag(mmd_sym) <- 0 # distance between a group and itself must be null
#################################################
## 4. Prepare the matrices for elegant display ##
#################################################
mmd_matrix <- mix_matrices(m = mmd_sym, n = sd_matrix, diag_value = 0)
if (all.results) {
pval_matrix <- mix_matrices(m = mmd_sym, n = pval_matrix, diag_value = NA)
signif_matrix <- mix_matrices(m = round(mmd_sym, 3), n = signif_matrix,
diag_value = NA)
}
###########################
## 5. Return the results ##
###########################
list_results <- list(MMDMatrix = round(mmd_matrix, 6),
MMDSym = round(mmd_sym, 6),
MMDSignif = signif_matrix,
MMDpval = round(pval_matrix, 4))
class(list_results) <- "anthropmmd_result"
return(list_results)
}
| /scratch/gouwar.j/cran-all/cranData/AnthropMMD/R/mmd.R |
mmd_resample <- function(dat, B = 100) {
### dat: dataset *in raw binary data* format
### B: numeric value; number of bootstrap replicates
## Define some useful constants:
ntraits <- ncol(dat) - 1 # (the 1st column is the group indicator)
colnames(dat)[1] <- "Group"
ngroups <- nlevels(dat$Group)
groupnames <- levels(dat$Group)
sampsizes <- as.numeric(table(dat$Group)) # ns by group
###################################
## 1. Initialize empty matrices ###
###################################
matfreq <- matrix(NA,
nrow = ngroups * (B + 1),
ncol = ntraits)
colnames(matfreq) <- colnames(dat[, -1])
rownames(matfreq) <- c(
groupnames,
paste0(rep(groupnames, times = B),
"_boot",
rep(1:B, each = ngroups))
)
matsizes <- matfreq
##############################
## 2. Fill in the matrices ###
##############################
## One row per bootstrap replicate,
## one column per trait.
## 2.1. For the original data:
origtable <- binary_to_table(dat, relative = TRUE)
matfreq[1:ngroups, ] <- tail(origtable, ngroups)
matsizes[1:ngroups, ] <- head(origtable, ngroups)
## 2.2. For the bootstrap samples:
for (b in 1:B) {
starsample <- dat |>
group_by(.data$Group) |> ## .data prefix avoids a NOTE in R CMD check
sample_n(n(), replace = TRUE) |>
as.data.frame()
startable <- binary_to_table(starsample, relative = TRUE)
matfreq[(b*ngroups+1):((b+1)*ngroups), ] <- tail(startable, ngroups)
matsizes[(b*ngroups+1):((b+1)*ngroups), ] <- head(startable, ngroups)
}
###################
## Return result ##
###################
rownames(matsizes) <- paste0("N_", rownames(matfreq))
rownames(matfreq) <- paste0("Freq_", rownames(matfreq))
return(list(matfreq = matfreq, matsizes = matsizes))
}
mmd_boot <- function(data, angular = c("Anscombe", "Freeman"), B = 100, ...) {
### data: dataset *in raw binary data* format
### B: numeric value; number of bootstrap replicates
### ...: arguments for traits selection, passed to select_traits()
angular <- match.arg(angular)
########################
## 1. Trait selection ##
########################
selected_traits <- data |>
binary_to_table(relative = TRUE) |>
select_traits(...) |>
getElement(name = "filtered") |>
colnames()
if (is.null(selected_traits) | length(selected_traits) < 2) {
stop("Not enough traits available -- change strategy of traits selection.")
}
data <- data.frame(
Group = data[, 1],
data[, selected_traits]
)
###############################
## 2. Resample in each group ##
###############################
resamp <- mmd_resample(data, B = B)
if (any(resamp$matsizes == 0)) {
warning("The resampling process resulted in empty groups for some traits. Try to choose a higher value of k in mmd_boot().")
}
###################
## 3. MMD matrix ##
###################
mmdmat <- mmd(
data = rbind(resamp$matsizes, resamp$matfreq),
angular = angular,
correct = FALSE,
all.results = FALSE
)$MMDSym
######################
## 4. Return result ##
######################
class(mmdmat) <- "anthropmmd_boot"
return(mmdmat)
}
| /scratch/gouwar.j/cran-all/cranData/AnthropMMD/R/mmd_boot.R |
plot.anthropmmd_boot <- function(
x,
method = c("classical", "interval", "ratio", "ordinal"),
level = 0.95,
pch = 16,
gof = FALSE,
xlab = NA,
ylab = NA,
main = "MDS plot of original and bootstrapped samples",
...
) {
### x: an object of class "anthropmmd_boot"
## Check input:
stopifnot(class(x) == "anthropmmd_boot")
method <- match.arg(method)
############
## 1. MDS ##
############
## Compute MDS coordinates:
mdsboot <- compute_mds(data = x, dim = 2, gof = gof, method = method)
coor <- as.data.frame(mdsboot$coor) # MDS coordinates
colnames(coor) <- c("x", "y")
## Dataframe of MDS coordinates:
coor$Group <- gsub(
x = rownames(coor),
pattern = "([[:graph:] ]*)(_boot[0-9]*)$",
replacement = "\\1"
) |> factor()
coor$Type <- ifelse(
grepl(pattern = "_boot[0-9]*", x = rownames(coor)),
yes = "boot",
no = "original"
) |> factor()
#########################
## 2. Display MDS plot ##
#########################
if (gof) {
goflegend <- paste0(mdsboot$legend_gof, mdsboot$gof_value)
} else {
goflegend <- NULL
}
plot(x = coor$x, y = coor$y,
pch = pch, xlab = xlab, ylab = ylab,
col = coor$Group,
xlim = c(1.2 * min(coor$x), max(coor$x)),
ylim = c(min(coor$y), 1.2 * max(coor$y)),
cex = ifelse(coor$Type == "original", 2.2, 0.8),
main = main,
sub = goflegend,
...)
legend("topleft", col = 1:nlevels(coor$Group),
legend = levels(coor$Group), pch = pch)
## Compute KDE2d for each group (using only bootstrapped data):
coor <- coor[coor$Type == "boot", ]
for (g in 1:nlevels(coor$Group)) {
temp <- subset(coor, coor$Group == levels(coor$Group)[g])
kd <- MASS::kde2d(
x = temp$x,
y = temp$y,
n = 100,
lims = 1.1 * c(min(coor$x), max(coor$x), min(coor$y), max(coor$y))
)
contour(kd, levels = c(0.95), col = g, add = TRUE,
xlim = c(min(coor$x), max(coor$x)),
ylim = c(min(coor$y), max(coor$y)))
}
}
| /scratch/gouwar.j/cran-all/cranData/AnthropMMD/R/plot.anthropmmd_boot.R |
plot.anthropmmd_result <- function(x,
method = c("classical", "interval", "ratio", "ordinal"),
axes = FALSE, gof = FALSE,
dim = 2, asp = TRUE,
xlim = NULL, ...) {
### x: an object of class "anthropmmd_result"
### method: type of MDS. "classical" for cmdscale, or one of SMACOF methods
### axes: boolean, display axes on plot or not
### gof: boolean, display goodness of fit value on plot or not
### dim: *maximal* dimension for the calculation of MDS coordinates. /!\ In fine, the solution can be computed on 2 axes only even if dim=3.
### asp: boolean, TRUE passes "asp=1" to plot function.
### ...: possibly other parameters passed to plot()
## Check input:
stopifnot(class(x) == "anthropmmd_result")
## Pass to main plotting function:
plot_mmd(data = x$MMDSym,
method = method,
axes = axes,
gof = gof,
dim = dim,
asp = asp,
xlim = NULL)
}
| /scratch/gouwar.j/cran-all/cranData/AnthropMMD/R/plot.anthropmmd_result.R |
compute_mds <- function(data, dim = 2, gof = FALSE,
method = c("classical", "interval", "ratio", "ordinal")) {
### Helper function that only *computes* the mds solution.
## Will be redefined below iff gof=TRUE:
legend_gof <- gof_value <- rho_value <- NULL
## Compute MDS solution:
if (method == "classical") {
## Option A. Classical metric MDS
res_mds <- cmdscale(data, k = dim, eig = TRUE) # *list* of MDS results
coor <- res_mds$points # MDS coordinates
var_by_dim <- apply(coor, MARGIN = 2, FUN = sd) # sd along each axis
legend_plot <- "Classical multidimensional scaling of MMD values"
if (gof == TRUE) {
legend_gof <- "Eigenvalue-based GoF="
gof_value <- round(res_mds$GOF[1], 3)
rho_value <- mds_rho(mmd = data, coor = coor)
}
} else {
## Option B: MDS via SMACOF package
res_mds <- smacof::smacofSym(as.dist(data),
type = method) # *list* of MDS results
coor <- res_mds$conf # MDS coordinates
var_by_dim <- apply(coor, MARGIN = 2, FUN = sd) # sd along each axis
legend_plot <- paste0("Multidimensional scaling of MMD values (",
method, " type)")
if (gof == TRUE) {
legend_gof <- "Stress="
gof_value <- round(res_mds$stress, 3)
rho_value <- mds_rho(mmd = data, coor = coor)
}
}
## Return result:
return(list(res_mds = res_mds, coor = coor, var_by_dim = var_by_dim,
legend_plot = legend_plot, legend_gof = legend_gof,
gof_value = gof_value, rho_value = rho_value))
}
plot_mds2d <- function(data, coor, axes, legend_plot, asp_value, xlim,
gof, legend_gof, gof_value, rho_value) {
### data: original data submitted to plot.anthropmmd_result()
### coor: mds coordinates
if (ncol(coor) >= 2 && any(data > 0)) { # OK, the plot can be displayed
plot(x = coor[, 1], y = coor[, 2], pch = 16, xlab = "", ylab = "",
axes = axes, main = legend_plot, asp = asp_value, xlim = xlim,
ylim = c(1.1 * min(coor[, 2]), 1.15 * max(coor[, 2])))
plotrix::thigmophobe.labels(x = coor[, 1], y = coor[, 2],
labels = rownames(coor))
if (gof == TRUE) { # if the user wants the GOF to be displayed
legend("topleft", legend = c(paste0("Spearman's rho=", rho_value),
paste0(legend_gof, gof_value)))
}
} else if (ncol(coor) >= 2 && all(data == 0)) {
## if the input matrix is filled only with zeroes -> error:
plot(x = 0, y = 0, xlab = "", ylab = "", axes = FALSE,
xlim = c(-2, 2), ylim = c(-2, 2), pch = "")
text(x = 0, y = 0.5,
labels = "The MMD matrix contains only zeroes.",
col = "black")
text(x = 0, y = -0.5, labels = "Impossible to get a MDS plot.",
col = "black")
} else { # ncol(coor)<2, so that MDS cannot be computed
plot(x = 0, y = 0, xlab = "", ylab = "", axes = FALSE,
xlim = c(-2, 2), ylim = c(-2, 2), pch = "")
text(x = 0, y = 0, col = "black",
labels = "The representation could not be computed since there is only one positive eigenvalue.")
}
}
plot_mmd <- function(data,
method = c("classical", "interval", "ratio", "ordinal"),
axes = FALSE, gof = FALSE, dim = 2, asp = TRUE,
xlim = NULL) {
### data: symmetrical matrix of MMD values
### method: type of MDS. "classical" for cmdscale, or one of SMACOF methods
### axes: boolean, display axes on plot or not
### gof: boolean, display goodness of fit value on plot or not
### dim: *maximal* dimension for the calculation of MDS coordinates.
### /!\ In fine, the solution may be computed on 2 axes only even if dim=3.
### asp: boolean, TRUE passes "asp=1" to plot function.
########################################
### 1. Verify and set some arguments ###
########################################
## 'translate' asp parameter as required by plot function:
asp_value <- ifelse(asp == TRUE, 1, NA)
method <- match.arg(method) # avoid a warning if no arg is given
if (! dim %in% c(2, 3)) {
stop("Incorrect value for dim parameter: please choose 2 or 3.")
}
#############################################################
### 2. Compute the MDS according to user-defined criteria ###
#############################################################
## MDS solution:
sol <- compute_mds(data = data, method = method, gof = gof, dim = dim)
## Set the limits for the x-axis on 2D plot, if no arg is given:
if (is.null(xlim)) {
border_value <- max(abs(min(sol$coor[, 1])), abs(max(sol$coor[, 1])))
xlim <- c(-1.17 * border_value, 1.17 * border_value)
}
###########################
### 3. Display MDS plot ###
###########################
## 3.1. MDS 2D
## (if the user wanted a 2D plot, or if a 3D plot could not be computed)
if ((dim == 2) | (dim == 3 & ncol(sol$coor) < 3) | (dim == 3 & ncol(sol$coor) >= 3 & min(sol$var_by_dim) < 2e-16)) {
plot_mds2d(data = data, coor = sol$coor, axes = axes,
legend_plot = sol$legend_plot, asp_value = asp_value,
xlim = xlim, gof = gof, legend_gof = sol$legend_gof,
gof_value = sol$gof_value, rho_value = sol$rho_value)
} else { # dim=3 & ncol(coor)>=3 & sufficient variability on third axis: a 3D graph is possible
## 3.2. MDS 3D:
graphe <- scatterplot3d::scatterplot3d(
x = sol$coor[, 1],
y = sol$coor[, 2],
z = sol$coor[, 3],
axis = axes,
pch = 16,
highlight.3d = TRUE,
type = "h",
main = sol$legend_plot,
asp = asp_value,
xlab = "",
ylab = "",
zlab = "")
coord_labels <- graphe$xyz.convert(x = sol$coor[, 1],
y = sol$coor[, 2],
z = sol$coor[, 3])
text(x = coord_labels$x, y = coord_labels$y,
pos = 3, labels = rownames(sol$coor))
if (gof == TRUE) { # if the user wants the GOF to be displayed
legend("topleft",
legend = c(paste0("Spearman's rho=", sol$rho_value),
paste0(sol$legend_gof, sol$gof_value)))
}
}
}
| /scratch/gouwar.j/cran-all/cranData/AnthropMMD/R/plot_mmd.R |
select_traits <- function(tab, k = 10,
strategy = c("none", "excludeNPT", "excludeQNPT", "excludeNOMD", "keepFisher"),
OMDvalue = NULL, groups = NULL,
angular = c("Anscombe", "Freeman")) {
### tab: table of sample sizes and frequencies
### k: numeric value, required minimal number of individuals per group
### strategy: scheme of exclusion of non-polymorphic traits
### groups: a factor or character vector, indicating the groups to be included
### angular: angular transformation to be used in MMD formula
strategy <- match.arg(strategy) # avoid a warning if the user gives no arg
angular <- match.arg(angular) # idem
###############################################################
## 1. Select a subset of the dataset according to the groups ##
###############################################################
nb_groups <- nrow(tab) / 2 # *initial* number of groups, before subsetting
if (is.null(groups)) { # if the user specified nothing, keep all groups
etiquettes <- rownames(tab)[1:nb_groups]
groups <- factor(substr(etiquettes, 3, nchar(etiquettes)))
}
## A boolean indicating whether each group sould be included:
take_group <- substr(rownames(tab), 3, nchar(rownames(tab))) %in% as.character(groups)
## Perform subsetting in data to keep only those groups:
take_group[(nrow(tab) / 2 + 1):nrow(tab)] <- take_group[1:(nrow(tab) / 2)]
tab <- tab[take_group, ]
## *Final* number of groups after subsetting:
nb_groups <- nrow(tab) / 2
###########################################################################
## 2. Filter data to keep only the traits with >=k individuals per group ##
###########################################################################
sel <- rep(NA, ncol(tab)) # initialize an empty boolean
for (j in seq_len(ncol(tab))) { # For each trait...
## if there are more than 'k' individuals per group for this trait,
if (all(tab[1:nb_groups, j] >= k) == TRUE) {
sel[j] <- TRUE # then keep this trait,
} else {
sel[j] <- FALSE # else discard it.
}
}
## If at least 2 traits meet this criterion, filter the dataset:
if (sum(sel) > 1) {
tab <- tab[, sel]
} else {
## else stop here (a MMD does not make sense if there is only one trait)
return()
}
######################################################################
## 3. Addtional step to discard the traits with too few variability ##
######################################################################
omd <- compute_omd(data = tab, formule = angular, OMDvalue = OMDvalue)
## 3.1. If scheme of exclusion = exclude non-polymorphic traits:
if (strategy == "excludeNPT") {
polym <- rep(NA, ncol(tab))
for (j in seq_len(ncol(tab))) {
polym[j] <- ifelse(all(tab[(nb_groups+1):nrow(tab), j] == 0) | all(tab[(nb_groups+1):nrow(tab), j] == 1), FALSE, TRUE)
## (this is TRUE iff the trait has two levels)
}
tab <- tab[, polym] # keep polymorphic traits only
tab_display <- omd$Sorted[rownames(omd$Sorted) %in% colnames(tab), ]
}
## 3.2. If scheme of exclusion = "quasi-non-polymorphic" traits:
else if (strategy == "excludeQNPT") {
avirer <- rep(NA, ncol(tab))
for (j in seq_len(ncol(tab))) {
tabprov <- round(tab[1:nb_groups, j] * tab[(nb_groups + 1):nrow(tab), j], 1)
tabprov <- abs(tab[1:nb_groups, j] - tabprov)
avirer[j] <- ifelse(sum(tabprov) <= 1 | sum(tabprov) >= (sum(tab[1:nb_groups, j])-1), FALSE, TRUE)
}
tab <- tab[, avirer]
tab_display <- omd$Sorted[rownames(omd$Sorted) %in% colnames(tab), ]
}
## 3.3. If scheme of exclusion = weak contribution to MMD:
else if (strategy == "excludeNOMD") {
tab <- tab[, rownames(omd$Pos)]
tab_display <- omd$SortedPos
}
## 3.4. If scheme of exclusionis based on Fisher's exact tests:
else if (strategy=="keepFisher") {
tab <- fisherTestTab(tab)$informative
tab_display <- omd$Sorted[rownames(omd$Sorted) %in% colnames(tab), ]
}
## If scheme of exclusion = "none", then no filtering at all:
else {
tab_display <- omd$Sorted
}
###########################
## 4. Return the results ##
###########################
tab_display <- as.matrix(tab_display)
colnames(tab_display) <- "Overall MD"
return(list("filtered" = tab, "OMD" = tab_display))
}
| /scratch/gouwar.j/cran-all/cranData/AnthropMMD/R/select_traits.R |
server <- shinyServer(function(input, output, session) {
myenvg = new.env() # package environement, will contain the dataset (seen as a global variable)
#################################################
### 1. Read the dataset imported through the UI #
#################################################
observeEvent(input$loadData, {
if (! is.null(input$file$name)) { # check that the user has indeed loaded a file!
if (input$typeData == "raw") { # this dataset is a binary dataset
dat <- read.table(
file = input$file$datapath,
header = input$colNamesRaw,
sep = input$fieldSepRaw,
na.strings = input$charNA,
stringsAsFactors = TRUE # useful for R >= 4.0.0
)
if (input$rowNames) { # if the dataset includes row names, then remove them (they are useless in the MMD workflow)
dat[, 1] <- NULL
}
if (ncol(dat) > 2) {
## make sure that the first column (group indicator) will be recognized as a factor,
## even if the labels are numeric ('1', '2', etc.):
dat[, 1] <- factor(dat[, 1])
} else {
showModal(modalDialog(title = "Error", "Invalid file or invalid settings: less than two columns could be found in the data file. Please check the field separator.", easyClose = TRUE))
}
} else if (input$typeData == "table") { # this dataset is already a table of frequencies
dat <- read.table(
file = input$file$datapath,
header = input$colNamesTable,
row.names = 1,
sep = input$fieldSepTable
)
}
if (valid_data_mmd(dat, type = input$typeData)) { # quick checks: is it a valid data file?
groups <- extract_groups(dat, type = input$typeData) # retrieve the groups from the data file
updateSelectizeInput(session, "selectGroups", choices = groups, selected = groups, server = TRUE) # update the UI widget displaying the list of groups...
updateNumericInput(session, "MDSdim", value = 2, min = 2, max = ifelse(length(groups)>3,3,2)) # ... and maximal admissible dimension for the MDS
output$text_title_summary <- renderText("Number of individuals and relative frequencies for each active variable within each group")
output$text_table_MMD <- renderText("MMD values (upper triangular part) and associated SD values (lower triangular part)") # render titles of all tables (passed to UI)
output$text_table_OMD <- renderText("Overall measure of divergence for each variable, sorted in decreasing order of discriminatory power")
output$text_table_MMDSym <- renderText("Symmetrical matrix of MMD values")
output$text_table_MMDSignif <- renderText("MMD values (upper triangular part) and their significance (indicated by a * in the lower part; 'NS'='non significant')")
if (input$typeData == "raw") { # this dataset is already a table of sample sizes and frequencies
dat <- binary_to_table(dat, relative = FALSE) # turn it into relative frequencies
}
dat <- table_relfreq(dat)
assign("dat", dat, envir = myenvg) # put the data into the package's global environment
} else { # this is not a valid data file!
showModal(modalDialog(title = "Error", "Invalid file. Please check the field separator, and make sure that there are at least two individuals in each group. Please read the help page of 'StartMMD' for detailed information.", easyClose = TRUE))
}
} else { # the user provided no data file before clicking on 'Load' button
showModal(modalDialog(title = "Error", "Please select a file on your computer.", easyClose = TRUE))
}
})
#####################
### 2. MMD analysis #
#####################
dat <- reactive({ # reactive expression that will return ('in real time') the filtered dataset, according to user-defined criteria
if (input$loadData > 0 & exists("dat", envir = myenvg) & length(input$selectGroups) > 1) { # if a valid data file has been loaded, we return this:
select_traits(get("dat", envir = myenvg), k = as.numeric(input$minNbInd),
strategy = as.character(input$exclusionStrategy), groups = as.character(input$selectGroups),
angular = as.character(input$formuleMMD), OMDvalue = input$OMDvalue)
} else { # either no data file, or invalid data file
return() # display nothing (avoid unexplicit red error messages in the UI)
}
}) # 'dat' is computed once, but will be reused multiple times below (avoid useless re-computations)
resultatsMMD <- reactive({ # reactive expression that will return MMD results computed on 'dat'
if (input$loadData > 0 & exists("dat", envir = myenvg) & length(input$selectGroups) > 1) { # if a valid data file has been loaded:
if (ncol(dat()$filtered) > 1) { # we check that there are at least two remaining traits after applying the user-defined criteria for filtering
mmd(dat()$filtered, angular = input$formuleMMD)
} else {
return()
}
} else {
return()
}
})
temp <- reactive({ # similar to dat(), except that we do not filter according to 'k' (the number of individuals), only according to the traits
if (input$loadData > 0 & exists("dat", envir = myenvg) & length(input$selectGroups) > 1) { # if a valid data file has been loaded:
tempo <- select_traits(get("dat", envir = myenvg), k = 1,
strategy = as.character(input$exclusionStrategy), groups = as.character(input$selectGroups),
angular = as.character(input$formuleMMD), OMDvalue = input$OMDvalue)
if (ncol(as.data.frame(tempo$filtered)) < 2) {
showModal(modalDialog(title = "Error", "With the current settings for trait selection, there is less than two traits suitable for the analysis. Consequently, the MMD will not be calculated. Please change the strategy for trait selection, or exclude some groups (with very few individuals) from the analysis.", easyClose = FALSE))
return()
} else {
return(tempo)
}
} else { # either no data file, or invalid data file
return() # display nothing (avoid unexplicit red error messages in the UI)
}
})
## Update slider bar:
calcNbMaxReglette <- reactive({ # computes dynamically the upper bound of the slider bar according to the select groups (this bound may change if the select groups change as well)
if (input$loadData > 0 & exists("dat", envir = myenvg) & length(input$selectGroups) > 1) { # if a valid data file has been loaded:
max3(temp()$filtered)
} else {
return(15) # the default value is set to 100 if no data file has been loaded
}
})
output$regletteNbMinInd <- renderUI({
sliderInput("minNbInd", label = "Only retain the traits with this minimal number of individuals per group",
value = min(c(10, calcNbMaxReglette())), min = 1, max = calcNbMaxReglette())
}) # by default, the slider bar ranges from 1 to 15, and then it adapts dynamically to the active groups
## ##############################
## 2.1. Fill in the 'Summary' tab
## 2.1.1. Summary (summary of filtered dataset):
output$tableResume <- renderTable(dat()$filtered, rownames = TRUE, digits = 3)
## Reminder: this output is rendered only once the data file has been loaded (thanks to the reactive expression dat())
output$button_download_summary <- renderUI({ # this button is rendered and displayed only once the data have been loaded
if (input$loadData > 0 & exists("dat", envir = myenvg) & length(input$selectGroups) > 1) {
downloadButton("download_summary", "Download this table [CSV file]")
} else {
return()
}
})
output$download_summary <- downloadHandler(filename = 'summary_active_groups.csv', content = function(file) {
write.csv(dat()$filtered, file)
}) # the function triggered by the download button
## 2.1.2. Table of p-values for Fisher's exact test
output$text_title_pvalFisher <- reactive({ # render and display the title of the table of p-values for Fisher's test (passed to UI)
if (input$loadData > 0 & exists("dat", envir = myenvg) & length(input$selectGroups) > 1 & input$exclusionStrategy == "keepFisher") {
return("p-values of Fisher's exact tests for pairwise comparisons of frequencies")
} else {
return("")
}
})
tablePvaleurs <- reactive({ # compute table of p-values for Fisher's exact test (if the radio button "Fisher exact test" is selected in the UI)
if (input$loadData > 0 & exists("dat", envir = myenvg) & length(input$selectGroups) > 1 & input$exclusionStrategy == "keepFisher") {
dataTemp <- select_traits(get("dat", envir = myenvg), k = as.numeric(input$minNbInd),
strategy = "none", groups = as.character(input$selectGroups),
angular = as.character(input$formuleMMD), OMDvalue = input$OMDvalue)$filtered
return(fisherTestTab(dataTemp)$pval)
} else {
return()
}
})
output$tablePval <- renderTable(tablePvaleurs(), rownames = TRUE, digits = 3) # display table of p-values for Fisher's exact test (passed to UI)
output$button_download_tablePval <- renderUI({ # this button is rendered and displayed only once the data have been loaded
if (input$loadData > 0 & exists("dat", envir = myenvg) & length(input$selectGroups) > 1 & input$exclusionStrategy == "keepFisher") {
downloadButton("download_pval", "Download this table [CSV file]")
} else {
return()
}
})
output$download_pval <- downloadHandler(filename = 'pairwise_fisher_tests_pvalues.csv', content = function(file) {
dataTemp <- select_traits(get("dat", envir = myenvg), k = as.numeric(input$minNbInd),
strategy = "none", groups = as.character(input$selectGroups),
angular = as.character(input$formuleMMD), OMDvalue = input$OMDvalue)$filtered
write.csv(fisherTestTab(dataTemp)$pval, file)
}) # the function triggered by the download button
## ######################################################
## 2.2. Fill in the tab of MMD results (various matrices)
## 2.2.1. Matrix of MMD and SD:
output$tableMMD <- renderTable(resultatsMMD()$MMDMatrix, rownames = TRUE, digits = 3)
output$button_download_tableMMD <- renderUI({ # this button is rendered and displayed only once the data have been loaded
if (input$loadData>0 & exists("dat", envir = myenvg) & length(input$selectGroups) > 1) {
downloadButton("download_tableMMD", "Download this table [CSV file]")
} else {
return()
}
})
output$download_tableMMD <- downloadHandler(filename = 'MMD_SD_matrix.csv', content = function(file) {
write.csv(resultatsMMD()$MMDMatrix, file)
}) # the function triggered by the download button
## 2.2.2. Matrix of 'OMD' values:
output$tableOMD <- renderTable(dat()$OMD, rownames = TRUE, digits = 3)
output$button_download_tableOMD <- renderUI({ # this button is rendered and displayed only once the data have been loaded
if (input$loadData > 0 & exists("dat", envir = myenvg) & length(input$selectGroups) > 1) {
downloadButton("download_tableOMD", "Download this table [CSV file]")
} else {
return()
}
})
output$download_tableOMD <- downloadHandler(filename='Overall_MD_matrix.csv', content=function(file) {
write.csv(dat()$OMD, file)
}) # the function triggered by the download button
## 2.2.3. Symmetrical matrix of MMD values:
output$tableMMDSym <- renderTable(resultatsMMD()$MMDSym, rownames = TRUE, digits = 3)
output$button_download_tableMMDSym <- renderUI({ # this button is rendered and displayed only once the data have been loaded
if (input$loadData > 0 & exists("dat", envir = myenvg) & length(input$selectGroups) > 1) {
downloadButton("download_tableMMDSym", "Download this table [CSV file]")
} else {
return()
}
})
output$download_tableMMDSym <- downloadHandler(filename = 'MMD_Sym_matrix.csv', content = function(file) {
write.csv(resultatsMMD()$MMDSym, file)
}) # the function triggered by the download button
## 2.2.4. Matrix of MMD significance:
output$tableMMDSignif <- renderTable(resultatsMMD()$MMDSignif, rownames = TRUE, digits = 3)
output$button_download_tableMMDSignif <- renderUI({ # this button is rendered and displayed only once the data have been loaded
if (input$loadData > 0 & exists("dat", envir = myenvg) & length(input$selectGroups) > 1) {
downloadButton("download_tableMMDSignif", "Download this table [CSV file]")
} else {
return()
}
})
output$download_tableMMDSignif <- downloadHandler(filename = 'MMD_Signif_matrix.csv', content = function(file) {
write.csv(resultatsMMD()$MMDSignif, file)
}) # the function triggered by the download button
## #################################################################################
## 2.3. Fill in the tab 'MDS plot', *only if there are at least three active groups*
observeEvent(input$helpMDS, { # help button for MDS info
showModal(modalDialog(
title = "Graphical options for MDS plots",
h4("Axes and scales"),
div("Making all axes use the same scale is strongly recommended in all cases: cf. I. Borg, P. Groenen and P. Mair (2013),",
span(em("Applied Multidimensional Scaling,")),
"Springer, chap. 7, p. 79. For a 3D-plot, since the third axis carries generally only a very small percentage of the total variability, you might want to uncheck this option to better visualize the distances along the third axis. In this case, the axes scales must be displayed on the plot, otherwise the plot would be misleading."),
h4("Goodness of fit values"),
p("For classical metric MDS, a common statistic is given: the sum of the eigenvalues of the first two axes, divided by the sum of all eigenvalues. It indicates the fraction of the total variance of the data represented in the MDS plot. This statistic comes from the '$GOF' value returned by the function 'cmdscale' (which is the basic R function for PCoA)."),
p("For SMACOF methods, the statistic given is the '$stress' value returned by the function smacofSym (from the R package smacof). It indicates the final stress-1 value. A value very close to 0 corresponds to a perfect fit."),
p("For both approaches, a 'rho' value is also given, which is the Spearman's correlation coefficient between real dissimilarities (i.e., MMD values) and distances observed on the MDS plot: cf. G. Dzemyda, O. Kurasova, and J. Zilinskas (2013),",
span(em("Multidimensional Data Visualization,")),
"Springer, chap. 2, p. 39-40. A value very close to 1 indicates a perfect fit."),
easyClose = TRUE,
size = "l"
))
})
observeEvent(input$selectGroups, # update maximal admissible dimension for the MDS plot according to the selected groups
updateNumericInput(session, "MDSdim", min = 2, max = ifelse(length(input$selectGroups)>3,3,2))
)
output$plotMDS <- renderPlot({
if (input$loadData > 0 & exists("dat", envir = myenvg) & length(input$selectGroups) > 2) { # if a valid dataset has been loaded, with at least 3 active groups
plot_mmd(data = resultatsMMD()$MMDSym, method = input$methodMDS, axes = input$axesMDSplot, gof = input$checkboxGOFstats,
dim = input$MDSdim, asp = input$aspMDSplot)
} else { # either no data file, or invalid data file
return() # display nothing
}
})
output$button_download_plotMDS <- renderUI({ # this button is rendered and displayed only once the data have been loaded
## Display the button only if the MDS can be computed. So, we check it is the case:
if (input$loadData > 0 & exists("dat", envir = myenvg) & length(input$selectGroups) > 2 ) {
mmdval <- resultatsMMD()$MMDSym
mmdtoy <- mmdval
diag(mmdtoy) <- rep(1, nrow(mmdtoy))
if (input$methodMDS == "classical") {
coor <- cmdscale(mmdval, k = 2)
} else if (input$methodMDS != "classical" & all(mmdtoy > 0)) {
coor <- smacofSym(as.dist(mmdval), type = input$methodMDS)$conf
} else {
return()
}
if (ncol(coor) == 2 & any(mmdval > 0)) {
downloadButton("download_plotMDS", "Download this plot [PNG file]")
} else {
return()
}
} else {
return()
}
})
output$download_plotMDS <- downloadHandler(filename = 'MDS_plot.png', content = function(file) { # the function triggered by the download button
png(file, width = 800, height = 800)
par(cex = 1.16)
plot_mmd(data = resultatsMMD()$MMDSym, method = input$methodMDS, axes = input$axesMDSplot,
gof = input$checkboxGOFstats, dim = input$MDSdim, asp = input$aspMDSplot)
dev.off()
}) # the function triggered by the download button
## ############################################################################
## 2.4. Fill in the tab 'CAH', *only if there are at least three active groups*
output$plotCAH <- renderPlot({
if (input$loadData > 0 & exists("dat", envir = myenvg) & length(input$selectGroups) > 2) { # if a valid dataset has been loaded, with at least 3 active groups
if (any(resultatsMMD()$MMDSym > 0)) {
distances <- as.dist(resultatsMMD()$MMDSym)
plot(hclust(distances, method = input$methodCAH), main = "Hierarchical clustering", xlab = "")
} else {
plot(x = 0, y = 0, xlab = "", ylab = "", axes = FALSE, xlim = c(-2,2), ylim = c(-2,2), pch = "")
text(x = 0, y = 0.5, labels = "The MMD matrix contains only zeroes.", col = "black")
}
} else { # either no data file, or invalid data file
return() # display nothing
}
})
output$button_download_plotCAH <- renderUI({ # this button is rendered and displayed only once the data have been loaded
if (input$loadData > 0 & exists("dat", envir = myenvg) & length(input$selectGroups) > 2 ) {
if (any(resultatsMMD()$MMDSym > 0)) {
downloadButton("download_plotCAH", "Download this plot [PNG file]")
} else {
return()
}
} else {
return()
}
})
output$download_plotCAH <- downloadHandler(filename = 'Hierarchical_clustering_MMD.png', content = function(file) {
distances <- as.dist(resultatsMMD()$MMDSym)
png(file, width = 900, height = 900)
par(cex = 1.16)
plot(hclust(distances, method = input$methodCAH), main = "Hierarchical clustering", xlab = "")
dev.off()
}) # the function triggered by the download button
})
| /scratch/gouwar.j/cran-all/cranData/AnthropMMD/R/server.R |
theta <- function(n, p, choice = c("Anscombe", "Freeman")) {
### Function for angular transformation
### n: sample size
### p: relative frequency for the given trait
### choice: variant of angular transformation to be used
choice <- match.arg(choice)
if (choice == "Anscombe") {
return(asin((n/(n+3/4)) * (1-2*p)))
} else { # Freeman-Tukey
return(0.5 * ( asin(1-(2*p*n/(n+1))) + asin(1-(2*((p*n)+1)/(n+1))) ))
}
}
sd_mmd <- function(nA, nB) {
### nA & nB: sample sizes in the groups A et B
return((1 / (nA + 0.5) + 1 / (nB + 0.5))^2)
}
compute_md <- function(nA, pA, nB, pB, correct = TRUE) {
### Computes the measure of divergence for one given trait
### nA & nB: sample sizes in the groups A et B
### pA & pB: *transformed* trait frequencies in the groups A et B
### correct: boolean; correction for small sample sizes.
if (correct) {
return((pA - pB)^2 - sqrt(sd_mmd(nA, nB)))
} else {
return((pA - pB)^2)
}
}
mds_rho <- function(mmd, coor) {
### Computes the rho values displayed on MDS plots
### mmd: symmetrical matrix of MMD values
### coor: MDS coordinates
## 1. Compute all pairwise distances:
mds_distances <- dist(coor[, 1:ncol(coor)],
diag = FALSE,
upper = FALSE)
mmd_distances <- as.dist(mmd, diag = FALSE, upper = FALSE)
## 2. Compute Spearman correlation between "real" (MMD) distances,
## and the distances post-MDS, not taking into account the null diagonal:
rho <- cor(x = as.vector(mmd_distances), y = as.vector(mds_distances),
method = "spearman")
## 3. Return Spearman's coef:
return(round(rho, 3))
}
max3 <- function(dat) {
### dat: table of sample sizes and frequencies,
### such as returned by 'binary_to_table'
### Returns the maximal value admissible for the slider bar in the UI
### (i.e., the maximal value that can be set for the required number of individuals in each group)
## for each trait, the minimal sample size reached among all groups:
mins <- apply(dat[1:(nrow(dat)/2), ],
MARGIN = 2, FUN = min)
## return the second greatest value
## (so that at least *two* traits can be used in further analyses):
return(as.numeric(sort(mins, decreasing = TRUE)[2]))
}
extract_groups <- function(tab, type) {
### Function extracting the group names from the data
### tab: dataframe loaded through the UI
### type: string ('raw' or 'table')
### output -> vector of strings
if (type == "raw") {
## raw binary data:
return(levels(tab[, 1]))
} else if (type == "table") {
## table of n's and frequencies:
nb_grps <- nrow(tab) / 2 # number of groups
noms <- rownames(tab)[1:nb_grps] # should be 'N_Group1', 'N_Group2', ...
return(substr(noms, 3, nchar(noms))) # thus discard the 'N_' everywhere
}
}
mix_matrices <- function(m, n, diag_value = 0) {
### m, n: (square) matrices, same dimension
### diag_value: a number
### Return a matrix composed as follows: upper-diagonal part of m,
### lower-diagonal part of n, and diagonal equal to diag.
res <- m # result matrix
## Replace lower part by those of n:
res[lower.tri(res)] <- n[lower.tri(n)]
## Fill diagonal with diag_value:
diag(res) <- diag_value
## Return result:
return(res)
}
| /scratch/gouwar.j/cran-all/cranData/AnthropMMD/R/small_utils.R |
start_mmd <- function() {
## Define the UI and server files for the app:
app <- shiny::shinyApp(ui = ui, server = server)
## Define a folder that contains a CSS sheet:
shiny::addResourcePath(prefix = "style", directoryPath = system.file("css", package = "AnthropMMD"))
## Run the app:
shiny::runApp(app)
}
StartMMD <- function() {
.Deprecated("start_mmd")
start_mmd()
}
| /scratch/gouwar.j/cran-all/cranData/AnthropMMD/R/start_mmd.R |
table_relfreq <- function(tab) {
### tab: table of sample sizes and raw frequencies,
### such as returned by `binary_to_table()'
### Converts the `N/2' last rows of tab into relative frequencies.
## Useful constant:
n <- nrow(tab)
## Indices of last N/2 rows:
last_rows <- seq(from = n / 2 + 1, to = n, by = 1)
## Indices of first N/2 rows:
first_rows <- seq_len(n / 2)
## Convert raw frequencies into relative frequencies:
tab[last_rows, ] <- tab[last_rows, ] / tab[first_rows, ]
## Return result:
return(tab)
}
| /scratch/gouwar.j/cran-all/cranData/AnthropMMD/R/table_relfreq.R |
ui <- shinyUI(fluidPage(theme = "style/kappa.css", # prefix 'style' to locate the CSS file: cf. StartMMD.R
titlePanel("AnthropMMD \u2014 A GUI for Smith's Mean Measure of Divergence"),
tags$style(type = "text/css", "
.irs-bar {width: 100%; background: #0098B6;}
.irs-bar-edge {background: #0098B6;}
.irs-single {color:white; background:#0098B6; font-weight: bold;}
"),
tags$style(HTML("
.btn-help.btn {
display: inline-block;
padding: 7px 12px;
font-size: 1em;
margin: 0 0 0 0;
vertical-align: middle;
color: gray;
font-weight: bold;
background-color: white;
border-color: gray;
}
.btn-help.btn:hover {
color: white;
background-color: #0098B6;
}
.btn-help.active {
color: white;
background-color: #0098B6;
border-color: #0098B6;
}
"
)),
sidebarLayout(
###################################################################
### 1. Define widgets in the left panel (various analysis settings)
sidebarPanel(
## 1.1. Widgets allowing to choose the type of dataset:
fileInput("file",
label = h3("1. Data import"),
accept = c(".csv", ".txt")),
radioButtons("typeData",
label = strong("Type of dataset"),
choices = list("Raw binary dataset" = "raw",
"Table of n's and absolute frequencies for each group" = "table")),
## 1.2. Widgets to specify some details about the data file:
## The following panel will be displayed for a "raw dataset" only:
conditionalPanel(condition = "input.typeData == 'raw'",
fluidRow( # create a grid of widgets with 2 columns of equal widths
column(6,
checkboxInput("colNamesRaw",
label = "Variable names in first row",
value = TRUE),
selectInput("fieldSepRaw",
label = "Field separator",
choices = list("Semicolon (;)" = ";",
"Comma (,)" = ",",
"Tabulation" = "\t",
"Space" = " "))
),
column(6,
checkboxInput("rowNames",
label = "Row names in first column",
value = TRUE),
textInput("charNA",
label = "Indicator for missing values",
value = "")
)
)
),
## The following panel will be displayed for a "table of n's and frequencies" only:
conditionalPanel(condition = "input.typeData == 'table'",
fluidRow(
column(6,
selectInput("fieldSepTable",
label = "Field separator",
choices = list("Semicolon (;)" = ";",
"Comma (,)" = ",",
"Tabulation" = "\t",
"Space" = " ")
)
),
column(6,
checkboxInput("colNamesTable",
label = "Variable names in first line",
value = TRUE)
)
),
helpText("No missing values allowed here. Row names are mandatory.")
),
## Action button to load the data (server.R is waiting a mouse click here to begin)
actionButton("loadData", "Load dataset", icon=icon("file-upload")),
## Blank lines (vertical spacing):
br(),
br(),
## 1.3. Various analysis settings:
h3("2. Analysis settings"),
## Select the active groups:
selectizeInput("selectGroups",
label = h4("Selection of active groups"),
choices = NULL,
multiple = TRUE),
## Select MMD formula:
radioButtons("formuleMMD",
label = h4("Formula"),
choices = list("Use Anscombe formula" = "Anscombe",
"Use Freeman and Tukey formula" = "Freeman"),
inline = TRUE,
selected = "Anscombe"),
## Strategy for trait selection:
h4("Trait selection"),
fluidRow(
column(6,
radioButtons("exclusionStrategy",
label = "Exclusion strategy",
choices = list("None" = "none",
"Exclude nonpolymorphic traits" = "excludeNPT",
"Exclude quasi-nonpolymorphic traits" = "excludeQNPT",
"Use Fisher's exact test (may be slow)" = "keepFisher",
"Exclude traits with overall MD lower than..." = "excludeNOMD")
),
## The following panel will be displayed only if the button "overall MD" is active:
conditionalPanel(condition = "input.exclusionStrategy == 'excludeNOMD'",
numericInput("OMDvalue",
label = NULL,
value = 0,
step = 0.05,
min = 0)
)
),
column(6,
## Display the slider for the minimum number of individuals:
uiOutput("regletteNbMinInd")
)
)
),
##########################################
### 2. Main panel (to display the results)
mainPanel(
tabsetPanel(
## 2.1. First tab, displaying the selected subset of the dataset:
tabPanel("Summary",
br(),
strong(textOutput("text_title_summary")), # this element is processed in server.R only after loading the file
br(),
div(style = "overflow:auto; width:100%;", tableOutput("tableResume")), # the "div" allows to put this element into a proper frame with a scrollbar
uiOutput("button_download_summary"), # the download button is processed in server.R, and displayed, only once everything is OK.
br(),
strong(textOutput("text_title_pvalFisher")),
br(),
br(),
div(style = "overflow:auto; width:100%;", tableOutput("tablePval")),
uiOutput("button_download_tablePval")
),
## 2.2. Tab of MMD matrices:
tabPanel("MMD Statistics",
fluidRow( # make a 2x2 grid to display the four matrices of results
column(6,
br(),
strong(textOutput("text_table_MMDSym")), # this element is processed in server.R only after loading the file
br(),
div(style = "overflow:auto; width:100%;", tableOutput("tableMMDSym")),
uiOutput("button_download_tableMMDSym"),
br(),
br(),
strong(textOutput("text_table_OMD")), # this element is processed in server.R only after loading the file
br(),
div(style = "overflow:auto; height:210px; width:50%;", tableOutput("tableOMD")),
uiOutput("button_download_tableOMD")
),
column(6,
br(),
strong(textOutput("text_table_MMD")), # this element is processed in server.R only after loading the file
br(),
div(style = "overflow:auto; width:100%;", tableOutput("tableMMD")),
uiOutput("button_download_tableMMD"),
br(),
br(),
strong(textOutput("text_table_MMDSignif")), # this element is processed in server.R only after loading the file
br(),
div(style = "overflow:auto; width:100%;", tableOutput("tableMMDSignif")),
uiOutput("button_download_tableMMDSignif")
)
)
),
## 2.3. Tab of MDS plot:
tabPanel("MDS plot",
helpText("A 2D multidimensional scaling plot (MDS) can be displayed below if and only if there are at least three active groups. For a 3D MDS plot, at least four groups are needed, and the first three eigenvalue found during the MDS calculation must be positive (so that you will not necessarily get a 3D plot even if you allow the maximum dimension of the space to be 3)."),
br(),
fluidRow(
column(6,
numericInput("MDSdim",
label = "Maximum dimension of the space",
value = 2,
step = 1,
min = 2,
max = 3),
selectInput("methodMDS",
label = "MDS method",
choices = list("Classical metric MDS (a.k.a. PCoA)" = "classical",
"SMACOF, interval type" = "interval",
"SMACOF, ratio type" = "ratio",
"SMACOF, ordinal (nonmetric) MDS" = "ordinal"),
selected = "MMDS",
multiple = FALSE)
),
column(6,
strong("Graph options"),
checkboxInput("aspMDSplot",
label = "Make all axes use the same scale",
value = TRUE),
checkboxInput("axesMDSplot",
label = "Display axes on the MDS plot",
value = TRUE),
p(checkboxInput("checkboxGOFstats",
label = "Display goodness of fit statistics on the MDS plot",
value = FALSE),
actionButton("helpMDS",
label = "Help",
class = "btn-help",
icon = icon("info-circle"))
)
)
),
br(),
plotOutput("plotMDS", width = "80%"),
br(),
uiOutput("button_download_plotMDS") # the download button is processed in server.R, and displayed, only once everything is OK.
),
## 2.4. Hierarchical clustering tab:
tabPanel("Hierarchical clustering",
helpText("A hierarchical clustering using Ward's method is displayed below if and only if there are at least three active groups."),
br(),
selectInput("methodCAH",
label = "Agglomeration method",
choices = list("Ward's method (squared distances)" = "ward.D2",
"Single linkage" = "single",
"Complete linkage" = "complete",
"Average linkage (UPGMA)" = "average"),
selected = "ward.D2",
multiple = FALSE),
br(),
plotOutput("plotCAH", width = "80%"),
br(),
uiOutput("button_download_plotCAH") # the download button is processed in server.R, and displayed, only once everything is OK.
)
)
)
)
))
| /scratch/gouwar.j/cran-all/cranData/AnthropMMD/R/ui.R |
valid_data_mmd <- function(tab, type) {
### tab : dataframe loaded through the UI
### type : 'raw' or 'table', indicating the type of data submitted
### Output -> boolean. Check whether "tab" is suitable for AnthropMMD.
## For both types (raw or table), a dataframe with only 1 column is invalid
## (probably due to a wrong field separator):
if (ncol(tab) <= 1) {
warning("Only one column read in the data file. Please check the field separator.")
return(FALSE)
} else {
if (type == "raw") { # for raw (i.e., binary) files
## Condition 1: all groups must include at least 2 individuals
if (min(table(tab[, 1])) < 2) {
warning("All groups must include at least 2 individuals. Please remove at least one of your groups.")
return(FALSE)
}
tab[, 1] <- NULL # Then, the group identifier can be removed
## Condition 2: invalid data if at least one column has more
## than 2 levels (thus, other levels than '0' and '1'):
for (j in seq_len(ncol(tab))) {
tab[, j] <- factor(tab[, j])
}
nb_levels <- apply(tab, MARGIN = 2,
FUN = function(x) return(nlevels(factor(x))))
if (max(nb_levels) > 2) {
warning("At least one of your columns does not contain only zeroes and ones. Please check your data.")
return(FALSE)
}
## Condition 3: are there only zeroes and ones?
ok01 <- rep(NA, ncol(tab))
for (j in seq_len(ncol(tab))) {
ok01[j] <- all(levels(tab[, j]) %in% c("0", "1"))
}
if (all(ok01)) { # all factors have only 0s and 1s
return(TRUE)
} else {
warning("At least one of your columns does not contain only zeroes and ones. Please check your data.")
return(FALSE)
}
} else if (type == "table") { # For 'tables'
nb_grps <- nrow(tab) / 2 # number of groups
noms <- rownames(tab)[1:nb_grps] # should be something like 'N_Group1', 'N_Group2', ...
if (all(substr(noms, 1, 2) == "N_") & all(apply(tab, MARGIN = 2, FUN = mode) == "numeric")) {
return(TRUE)
} else {
warning("If there are k groups in your data file, the first k lines should be something like 'N_Group1', 'N_Group2', ..., with a mandatory 'N_' prefix.")
return(FALSE)
}
}
}
}
| /scratch/gouwar.j/cran-all/cranData/AnthropMMD/R/valid_data_mmd.R |
## ----include = FALSE----------------------------------------------------------
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
options(digits = 3)
## ----include=FALSE------------------------------------------------------------
library(AnthropMMD)
## ----eval=FALSE, include=TRUE-------------------------------------------------
# start_mmd()
## ----rows.print=8-------------------------------------------------------------
data(toyMMD)
head(toyMMD)
## -----------------------------------------------------------------------------
str(toyMMD)
## -----------------------------------------------------------------------------
tab <- binary_to_table(toyMMD, relative = TRUE)
tab
## -----------------------------------------------------------------------------
data(absolute_freqs)
print(absolute_freqs)
## -----------------------------------------------------------------------------
tab <- table_relfreq(absolute_freqs)
print(tab)
## -----------------------------------------------------------------------------
tab_selected <- select_traits(tab, k = 10, strategy = "keepFisher")
tab_selected$filtered
## -----------------------------------------------------------------------------
mmd.result <- mmd(tab_selected$filtered, angular = "Anscombe")
mmd.result
## -----------------------------------------------------------------------------
par(cex = 0.8)
plot(x = mmd.result, method = "interval",
gof = TRUE, axes = TRUE, xlim = c(-1.2, 0.75))
## -----------------------------------------------------------------------------
library(cluster)
par(cex = 0.8)
plot(agnes(mmd.result$MMDSym), which.plots = 2, main = "Dendrogram of MMD dissimilarities")
## -----------------------------------------------------------------------------
## Load the example data once again:
data(toyMMD)
## Compute MMD among bootstrapped samples:
set.seed(2023) # set seed for reproducibility
resboot <- mmd_boot(
data = toyMMD,
B = 50, # number of bootstrap samples
angular = "Anscombe",
strategy = "keepFisher", # strategy for trait selection
k = 10 # minimal number of observations required per trait
)
## -----------------------------------------------------------------------------
## MDS plot for bootstrapped samples:
plot(
x = resboot,
method = "interval", # algorithm used for MDS computation
level = 0.95, # confidence level for the contour lines
gof = TRUE # display goodness of fit statistic
)
| /scratch/gouwar.j/cran-all/cranData/AnthropMMD/inst/doc/intro_AnthropMMD.R |
---
title: "An overview of AnthropMMD"
author: "Frédéric Santos, <frederic.santos[at]u-bordeaux.fr>"
output:
rmarkdown::html_vignette:
number_sections: true
toc: true
fig_width: 5
fig_height: 5
vignette: >
%\VignetteIndexEntry{An overview of AnthropMMD}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
bibliography: biblio.bib
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
options(digits = 3)
```
```{r include=FALSE}
library(AnthropMMD)
```
# Graphical user interface
`AnthropMMD` was primarily designed as an R-Shiny application [@Santos18], that can be launched with the following instruction:
```{r eval=FALSE, include=TRUE}
start_mmd()
```
Starting with the version 3.0.0, it can also be used from the command line, to make it convenient in a context of reproducible research.
# Using `AnthropMMD` from the command line
## Data formatting
The MMD is a dissimilarity measure among groups of individuals described by binary (presence-absence) traits [@Sjovold73; @Sjovold77; @Harris04]. The MMD formula only requires to know the sample sizes and relative trait frequencies within each group: providing the raw individual data is not mandatory.
Usually, the user will have recorded the data in one of the the two following formats.
### Raw binary data
Most of the time, the data will be formatted as a classical dataframe with $n$ rows (one per individual) and $p+1$ columns (the first column must be a group indicator; the $p$ other columns correspond to the $p$ binary traits observed). Each trait has two possible values: $1$ if present, $0$ if absent (missing values are allowed). Rownames are optional but colnames (i.e., `header`s) are mandatory.
An artificial dataset, `toyMMD`, is available in the package to give an example of such a format:
```{r rows.print=8}
data(toyMMD)
head(toyMMD)
```
It is not necessary for the `Trait`s to be manually converted as factors prior to the analysis. `toyMMD` includes nine traits with many missing values, and the individuals belong to five groups:
```{r}
str(toyMMD)
```
If the data were recorded as a raw binary dataset, they **must** be converted into a table of relative frequencies prior to the MMD analysis. The R function `binary_to_table()` with the argument `relative = TRUE` can perform this operation:
```{r}
tab <- binary_to_table(toyMMD, relative = TRUE)
tab
```
### Tables of sample sizes and absolute frequencies
Sometimes, in particular if the data were extracted from research articles rather than true exprimentation, the user will only know the sample sizes and absolute trait frequencies in each group. As previously stated, those data are perfectly sufficient to compute MMD values. Here is an example of such a table:
```{r}
data(absolute_freqs)
print(absolute_freqs)
```
If there are $k$ groups in the data, the first $k$ rows (whose names must start with an `N_` prefix, followed by the group labels) indicates the sample sizes of each trait in each group, and the last $k$ rows indicates the *absolute* trait frequencies. Such a table can be directly imported by the user, but **must** be converted to *relative* trait frequencies prior to the analysis, for instance by using the function `table_relfreq()`:
```{r}
tab <- table_relfreq(absolute_freqs)
print(tab)
```
### Important remark
Due to rounding issues, it is clearly not advised for the user to submit directly a table of relative frequencies. If the absolute frequencies do not perfectly sum up to 1 for each trait, an error will be triggered.
A table of relative frequencies is the starting point of all subsequent analyses, but it should be *computed* from the data loaded in R; it should not be loaded itself.
A quick summary:
* if you load a raw binary dataframe, convert it to a table of relative frequencies with the function `binary_to_table(relative = TRUE)` as shown above;
* if you load a table of absolute frequencies, convert it to a table of relative frequencies with the function `table_relfreq()`.
## Trait selection
`AnthropMMD` proposes a built-in feature for trait selection, in order to discard the traits that could be observed on too few individuals, or that do not show enough variability among groups. The function `select_traits()` allows such a selection according to several strategies [@Harris04; @Santos18].
For instance, with the following instruction, we can discard the traits that could be observed on at least 10 individuals *per group*, and that exhibit no significant variability in frequencies among groups according to Fisher's exact tests:
```{r}
tab_selected <- select_traits(tab, k = 10, strategy = "keepFisher")
tab_selected$filtered
```
`Trait1` (which could be observed on only 8 individuals in Group B), `Trait5` and `Trait8` (whose variation in frequencies was not significant among groups) were removed from the data.
## Compute the mean measure of divergence
Once the trait selection has been performed, the MMD can be computed with the `mmd()` function. With the following instruction, the MMD is computed using Anscombe's angular transformation of trait frequencies:
```{r}
mmd.result <- mmd(tab_selected$filtered, angular = "Anscombe")
mmd.result
```
* The first component, `$MMDMatrix`, follows the presentation adopted in most research articles [@Donlon00]: the true MMD values are indicated above the diagonal, and their standard deviations are indicated below the diagonal.
* A MMD value can be considered as significant if it is greater than twice its standard deviation. Significant MMD values are indicated by a `*` in the component `$MMDSignif`.
* The component `$MMDSym` is a symmetrical matrix of MMD values, with a null diagonal. This matrix of dissimilarities can be used to perform a multidimensional scaling or a hierarchical clustering to visualize the distances among the groups.
* Finally, p-values for non-nullity of each MMD value are given (in the lower triangular part of the matrix returned) by the component `$MMDpval`. Theoretical details for this test of significance can be found in @Souza77.
## Graphical representations of MMD
### Multidimensional scaling
Although `mmd.result$MMDSym` can perfectly be passed to your favourite function to produce a MDS plot, `AnthropMMD` also proposes a built-in generic function for such a graphical representation: `plot()`.
The MDS can be computed using the classical `stats::cmdscale()` function (and the produces a metric MDS), or several variants of MDS algorithms implemented in the R package `smacof`.
For instance, we plot here the MDS coordinates computed with one variant of SMACOF algorithms:
```{r}
par(cex = 0.8)
plot(x = mmd.result, method = "interval",
gof = TRUE, axes = TRUE, xlim = c(-1.2, 0.75))
```
The argument `gof = TRUE` displays goodness of fits statistics for the MDS configurations directly on the plot.
### Hierarchical clustering
`AnthropMMD` does not propose a built-in function for hierarchical clustering, but such a plot can easily be obtained with the usual R functions.
```{r}
library(cluster)
par(cex = 0.8)
plot(agnes(mmd.result$MMDSym), which.plots = 2, main = "Dendrogram of MMD dissimilarities")
```
# Alternative: analysis using bootstrapped samples
Starting with `AnthropMMD 4.0.0`, a bootstrap method introduced by Daniel Fidalgo and co-workers [@Fidalgo2021; @Fidalgo2022] is now available. Please note that:
* this method is only available when the input data is a "raw binary dataset", as described earlier in this vignette (see Section 2.1.1);
* this method requires longer computations than the standard MMD, so that it is not available through the graphical user interface.
Let's start again from the dataset `toyMMD`. The first step is to perform the resampling and the MMD computations using the separate function `mmd_boot()`. @Fidalgo2022 suggest a value of `B = 100` bootstrap experiments, it is thus the default value for the corresponding argument in this function. Below, for this simple example, we will use a value of `B = 50`. Be careful: the computation time (in the current implementation) will grow quite fast for high values of `B`.
Note that `mmd_boot()` takes care itself of the trait selection. All arguments usually submitted to `select_traits()` can also be passed to `mmd_boot()`; see example below.
```{r}
## Load the example data once again:
data(toyMMD)
## Compute MMD among bootstrapped samples:
set.seed(2023) # set seed for reproducibility
resboot <- mmd_boot(
data = toyMMD,
B = 50, # number of bootstrap samples
angular = "Anscombe",
strategy = "keepFisher", # strategy for trait selection
k = 10 # minimal number of observations required per trait
)
```
Now you can simply `plot()` the result of your computations, and set various parameters to customize your plot:
```{r}
## MDS plot for bootstrapped samples:
plot(
x = resboot,
method = "interval", # algorithm used for MDS computation
level = 0.95, # confidence level for the contour lines
gof = TRUE # display goodness of fit statistic
)
```
This plot displays the contour lines of a 2D kernel density estimation, as in Figure 3 from @Fidalgo2022.
# References
| /scratch/gouwar.j/cran-all/cranData/AnthropMMD/inst/doc/intro_AnthropMMD.Rmd |
---
title: "An overview of AnthropMMD"
author: "Frédéric Santos, <frederic.santos[at]u-bordeaux.fr>"
output:
rmarkdown::html_vignette:
number_sections: true
toc: true
fig_width: 5
fig_height: 5
vignette: >
%\VignetteIndexEntry{An overview of AnthropMMD}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
bibliography: biblio.bib
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
options(digits = 3)
```
```{r include=FALSE}
library(AnthropMMD)
```
# Graphical user interface
`AnthropMMD` was primarily designed as an R-Shiny application [@Santos18], that can be launched with the following instruction:
```{r eval=FALSE, include=TRUE}
start_mmd()
```
Starting with the version 3.0.0, it can also be used from the command line, to make it convenient in a context of reproducible research.
# Using `AnthropMMD` from the command line
## Data formatting
The MMD is a dissimilarity measure among groups of individuals described by binary (presence-absence) traits [@Sjovold73; @Sjovold77; @Harris04]. The MMD formula only requires to know the sample sizes and relative trait frequencies within each group: providing the raw individual data is not mandatory.
Usually, the user will have recorded the data in one of the the two following formats.
### Raw binary data
Most of the time, the data will be formatted as a classical dataframe with $n$ rows (one per individual) and $p+1$ columns (the first column must be a group indicator; the $p$ other columns correspond to the $p$ binary traits observed). Each trait has two possible values: $1$ if present, $0$ if absent (missing values are allowed). Rownames are optional but colnames (i.e., `header`s) are mandatory.
An artificial dataset, `toyMMD`, is available in the package to give an example of such a format:
```{r rows.print=8}
data(toyMMD)
head(toyMMD)
```
It is not necessary for the `Trait`s to be manually converted as factors prior to the analysis. `toyMMD` includes nine traits with many missing values, and the individuals belong to five groups:
```{r}
str(toyMMD)
```
If the data were recorded as a raw binary dataset, they **must** be converted into a table of relative frequencies prior to the MMD analysis. The R function `binary_to_table()` with the argument `relative = TRUE` can perform this operation:
```{r}
tab <- binary_to_table(toyMMD, relative = TRUE)
tab
```
### Tables of sample sizes and absolute frequencies
Sometimes, in particular if the data were extracted from research articles rather than true exprimentation, the user will only know the sample sizes and absolute trait frequencies in each group. As previously stated, those data are perfectly sufficient to compute MMD values. Here is an example of such a table:
```{r}
data(absolute_freqs)
print(absolute_freqs)
```
If there are $k$ groups in the data, the first $k$ rows (whose names must start with an `N_` prefix, followed by the group labels) indicates the sample sizes of each trait in each group, and the last $k$ rows indicates the *absolute* trait frequencies. Such a table can be directly imported by the user, but **must** be converted to *relative* trait frequencies prior to the analysis, for instance by using the function `table_relfreq()`:
```{r}
tab <- table_relfreq(absolute_freqs)
print(tab)
```
### Important remark
Due to rounding issues, it is clearly not advised for the user to submit directly a table of relative frequencies. If the absolute frequencies do not perfectly sum up to 1 for each trait, an error will be triggered.
A table of relative frequencies is the starting point of all subsequent analyses, but it should be *computed* from the data loaded in R; it should not be loaded itself.
A quick summary:
* if you load a raw binary dataframe, convert it to a table of relative frequencies with the function `binary_to_table(relative = TRUE)` as shown above;
* if you load a table of absolute frequencies, convert it to a table of relative frequencies with the function `table_relfreq()`.
## Trait selection
`AnthropMMD` proposes a built-in feature for trait selection, in order to discard the traits that could be observed on too few individuals, or that do not show enough variability among groups. The function `select_traits()` allows such a selection according to several strategies [@Harris04; @Santos18].
For instance, with the following instruction, we can discard the traits that could be observed on at least 10 individuals *per group*, and that exhibit no significant variability in frequencies among groups according to Fisher's exact tests:
```{r}
tab_selected <- select_traits(tab, k = 10, strategy = "keepFisher")
tab_selected$filtered
```
`Trait1` (which could be observed on only 8 individuals in Group B), `Trait5` and `Trait8` (whose variation in frequencies was not significant among groups) were removed from the data.
## Compute the mean measure of divergence
Once the trait selection has been performed, the MMD can be computed with the `mmd()` function. With the following instruction, the MMD is computed using Anscombe's angular transformation of trait frequencies:
```{r}
mmd.result <- mmd(tab_selected$filtered, angular = "Anscombe")
mmd.result
```
* The first component, `$MMDMatrix`, follows the presentation adopted in most research articles [@Donlon00]: the true MMD values are indicated above the diagonal, and their standard deviations are indicated below the diagonal.
* A MMD value can be considered as significant if it is greater than twice its standard deviation. Significant MMD values are indicated by a `*` in the component `$MMDSignif`.
* The component `$MMDSym` is a symmetrical matrix of MMD values, with a null diagonal. This matrix of dissimilarities can be used to perform a multidimensional scaling or a hierarchical clustering to visualize the distances among the groups.
* Finally, p-values for non-nullity of each MMD value are given (in the lower triangular part of the matrix returned) by the component `$MMDpval`. Theoretical details for this test of significance can be found in @Souza77.
## Graphical representations of MMD
### Multidimensional scaling
Although `mmd.result$MMDSym` can perfectly be passed to your favourite function to produce a MDS plot, `AnthropMMD` also proposes a built-in generic function for such a graphical representation: `plot()`.
The MDS can be computed using the classical `stats::cmdscale()` function (and the produces a metric MDS), or several variants of MDS algorithms implemented in the R package `smacof`.
For instance, we plot here the MDS coordinates computed with one variant of SMACOF algorithms:
```{r}
par(cex = 0.8)
plot(x = mmd.result, method = "interval",
gof = TRUE, axes = TRUE, xlim = c(-1.2, 0.75))
```
The argument `gof = TRUE` displays goodness of fits statistics for the MDS configurations directly on the plot.
### Hierarchical clustering
`AnthropMMD` does not propose a built-in function for hierarchical clustering, but such a plot can easily be obtained with the usual R functions.
```{r}
library(cluster)
par(cex = 0.8)
plot(agnes(mmd.result$MMDSym), which.plots = 2, main = "Dendrogram of MMD dissimilarities")
```
# Alternative: analysis using bootstrapped samples
Starting with `AnthropMMD 4.0.0`, a bootstrap method introduced by Daniel Fidalgo and co-workers [@Fidalgo2021; @Fidalgo2022] is now available. Please note that:
* this method is only available when the input data is a "raw binary dataset", as described earlier in this vignette (see Section 2.1.1);
* this method requires longer computations than the standard MMD, so that it is not available through the graphical user interface.
Let's start again from the dataset `toyMMD`. The first step is to perform the resampling and the MMD computations using the separate function `mmd_boot()`. @Fidalgo2022 suggest a value of `B = 100` bootstrap experiments, it is thus the default value for the corresponding argument in this function. Below, for this simple example, we will use a value of `B = 50`. Be careful: the computation time (in the current implementation) will grow quite fast for high values of `B`.
Note that `mmd_boot()` takes care itself of the trait selection. All arguments usually submitted to `select_traits()` can also be passed to `mmd_boot()`; see example below.
```{r}
## Load the example data once again:
data(toyMMD)
## Compute MMD among bootstrapped samples:
set.seed(2023) # set seed for reproducibility
resboot <- mmd_boot(
data = toyMMD,
B = 50, # number of bootstrap samples
angular = "Anscombe",
strategy = "keepFisher", # strategy for trait selection
k = 10 # minimal number of observations required per trait
)
```
Now you can simply `plot()` the result of your computations, and set various parameters to customize your plot:
```{r}
## MDS plot for bootstrapped samples:
plot(
x = resboot,
method = "interval", # algorithm used for MDS computation
level = 0.95, # confidence level for the contour lines
gof = TRUE # display goodness of fit statistic
)
```
This plot displays the contour lines of a 2D kernel density estimation, as in Figure 3 from @Fidalgo2022.
# References
| /scratch/gouwar.j/cran-all/cranData/AnthropMMD/vignettes/intro_AnthropMMD.Rmd |
#Helper function to calculate the approximated convex hull.
ahull <- function(zs) {
a <- rbind(archetypes::parameters(zs), archetypes::parameters(zs)[1,])
xc <- a[,1]; xm <- mean(xc)
yc <- a[,2]; ym <- mean(yc)
real <- xc - xm
imag <- yc - ym
angle <- atan2(imag, real)
index <- order(angle)
return(a[c(index, index[1]),])
}
#No standardize.
no.scalefn <- function(x, ...){
return(x)
}
no.rescalefn <- function(x, zs, ...){
if ( is.null(zs) )
return(matrix(NA, nrow = 0, ncol = 0))
return(zs)
}
#Helper functions to calculate archetypoids.
swap <- function(vect_arch_ini, rss_arch_ini, huge=200, numArchoid, x_gvv, n){
vect_arch_end <- vect_arch_ini
rss <- rss_arch_ini
for(l in 1 : numArchoid){
rss1 <- c()
setpossibles <- setdiff(1:n,vect_arch_ini)
for(i in setpossibles){
zs <- x_gvv[,c(i,vect_arch_ini[-l])]
zs <- as.matrix(zs)
alphas <- matrix(0, nrow = numArchoid, ncol = n)
for (j in 1 : n){
alphas[, j] = coef(nnls(zs, x_gvv[,j]))
}
resid <- zs %*% alphas - x_gvv
rss1[i] <- max(svd(resid)$d) / n
if(rss1[i] < rss){
rss <- rss1[i]
vect_arch_end = c(i,vect_arch_ini[-l])
}
}
}
if(numArchoid==1){
result <- swap2_k1(vect_arch_end, vect_arch_ini, rss, huge, numArchoid, x_gvv, n)
}else{
result <- swap2(vect_arch_end, vect_arch_ini, rss, huge, numArchoid, x_gvv, n)
}
return(result)
}
swap2 <- function(vect_arch_end, vect_arch_ini, rss, huge=200, numArchoid, x_gvv, n){
vect_arch_ini_aux <- vect_arch_ini
vect_arch_end_aux <- vect_arch_end
rss_aux <- rss
vect_arch_end2 <- c()
while(any(sort(vect_arch_end_aux) != sort(vect_arch_ini_aux))){ #this loop is executed while both vectors are
#different in at least one element. Since we have not found an R function that says whether two vectors are
#equal, we have done the following: first, we have ordered them (because both vectors may be the same, although
#their elements are in a different order, for example, c(1,2,3) and c(3,1,2)). Then, we have checked if any
#element does not match with the element that is placed in the same position in the other vector.
se <- setdiff(vect_arch_end_aux,vect_arch_ini_aux) #this function looks for the distinct element between the
#initial vector (in the first iteration, the initial vector is either the nearest or which vector, while in the
#second iteration, the initial vector is the final vector returned by the swap step and so on and so forth)
#and the final vector (the final vector in the first iteration is that one returned by the swap step but in the
#following iterations, it is the vector returned by the swap2 function).
se1 <- setdiff(vect_arch_end_aux,se) #the elements different from the distinct one of the former setdiff
#function.
for(l in 1 : length(se1)){
rss1 <- c()
comp <- c(se,se1[-l]) #vector made up of the distinct element with the no distincts without one.
setpossibles <- setdiff(1:n,vect_arch_end_aux)
for(i in setpossibles){
zs <- x_gvv[,c(i,comp)]
zs <- as.matrix(zs)
alphas <- matrix(0, nrow = numArchoid, ncol = n)
for (j in 1 : n){
alphas[, j] = coef(nnls(zs, x_gvv[,j]))
}
resid <- zs %*% alphas - x_gvv
rss1[i] <- max(svd(resid)$d) / n
if(rss1[i] < rss_aux){
rss_aux <- rss1[i]
vect_arch_end2 <- c(i,comp)
}
}
}
if(is.null(vect_arch_end2)){ #if vect_arch_end2 is NULL, this means that any vector improves the final vector
#of the swap function (called vect_arch_end_aux). Therefore, the vect_arch_end_aux that it is going to be
#returned is just the vect_arch_end_aux that it is the final vector of the first swap. If we don't add this
#condition, the function displays an error because it might happen that the vect_arch_end returned by the
#swap function already is the best vector (this happens with the nba2d database) and therefore the swap2
#function is not going to be able to improve it.
vect_arch_end_aux <- vect_arch_end_aux
vect_arch_ini_aux <- vect_arch_end_aux #In addition, we also have to fix the initial vector as the final
#vector in order to the while loop stops.
}else{
vect_arch_ini_aux <- vect_arch_end_aux #the initial vector of the following iteration must be the final
#vector of the previous iteration to compare it with the final vector returned by the swap2 in the next
#iteration.
vect_arch_end_aux <- vect_arch_end2 #final vector returned by the swap2 function.
}
}
#Actual alpha coefficients for the optimal vector of archetypoids:
zs <- x_gvv[,vect_arch_end_aux]
zs <- as.matrix(zs)
alphas_def <- matrix(0, nrow = numArchoid, ncol = n)
for (j in 1 : n){
alphas_def[, j] = coef(nnls(zs, x_gvv[,j]))
}
return(list(cases=vect_arch_end_aux, rss=rss_aux, archet_ini=vect_arch_ini, alphas=alphas_def))
}
swap2_k1 <- function(vect_arch_end, vect_arch_ini, rss, huge=200, numArchoid, x_gvv, n){
vect_arch_ini_aux <- vect_arch_ini
vect_arch_end_aux <- vect_arch_end
rss_aux <- rss
vect_arch_end2 <- c()
while(vect_arch_end_aux != vect_arch_ini_aux){
rss1 <- c()
setpossibles <- setdiff(1:n,vect_arch_end_aux)
for(i in setpossibles){
zs <- x_gvv[,i]
zs <- as.matrix(zs)
alphas <- matrix(0, nrow = numArchoid, ncol = n)
for (j in 1 : n){
alphas[, j] = coef(nnls(zs, x_gvv[,j]))
}
resid <- zs %*% alphas - x_gvv
rss1[i] <- max(svd(resid)$d) / n
if(rss1[i] < rss_aux){
rss_aux <- rss1[i]
vect_arch_end2 = i
}
}
if(is.null(vect_arch_end2)){
vect_arch_end_aux <- vect_arch_end_aux
vect_arch_ini_aux <- vect_arch_end_aux
}else{
vect_arch_ini_aux <- vect_arch_end_aux
vect_arch_end_aux <- vect_arch_end2
}
}
#Actual alpha coefficients for the optimal vector of archetypoids:
zs <- x_gvv[,vect_arch_end_aux]
zs <- as.matrix(zs)
alphas_def <- matrix(0, nrow = numArchoid, ncol = n)
for (j in 1 : n){
alphas_def[, j] = coef(nnls(zs, x_gvv[,j]))
}
return(list(cases=vect_arch_end_aux, rss=rss_aux, archet_ini=vect_arch_ini, alphas=alphas_def))
}
| /scratch/gouwar.j/cran-all/cranData/Anthropometry/R/Anthropometry-internalArchetypoids.R |
#All these functions are common to the HIPAM_{MO} and HIPAM_{IMO} algorithms.
initialize.tree <- function(x, maxsplit, orness, type, ah=c(23,28,20,25,25), verbose, ...){
if(type == "MO"){
x.ps <- getBestPamsamMO(x, maxsplit, orness, type, ah, verbose, ...)
}else{
x.ps <- getBestPamsamIMO(x, maxsplit, orness, type, ah, verbose, ...)
}
n.clust <- length(unique(x.ps$clustering))
list(clustering = x.ps$clustering, asw = x.ps$asw, n.levels = 1, medoids = x.ps$medoids, active =
rep(TRUE,n.clust), development = matrix(1:n.clust), n.clust = n.clust, metric = "McCulloch")
}
ext.dist <- function(x, maxsplit, orness, ah, verbose){
num.variables <- dim(x)[2]
w <- weightsMixtureUB(orness, num.variables)
num.personas <- dim(x)[1]
datosm <- as.matrix(x)
datost <- aperm(datosm, c(2,1))
dim(datost) <- c(1, num.personas * num.variables)
rm(datosm)
bh <- (apply(as.matrix(log(x)), 2, range)[2,] - apply(as.matrix(log(x)), 2, range)[1,]) / ((maxsplit - 1) * 8)
if(any(bh==0)){
bh[which(bh == 0)]=0.0000000001
}
bl <- -3 * bh
ah <- ah
al <- 3 * ah
DIST <- getDistMatrix(datost, num.personas, num.variables, w, bl, bh, al, ah, verbose)
if( is.null(dimnames(x)[1]) ) dimnames(DIST) <- NULL
return(DIST)
}
pamsam <- function(x, k = k, type = type, DIST, maxclust = 50, further.maxclust = 20, exhaustive = FALSE,
max.check = 20, total.check = 100, maxsplit = maxsplit, orness = orness,
ah, verbose){
if(type == "MO"){
#Calculate DIST:
DIST <- ext.dist(x, maxsplit = k, orness = orness, ah, verbose)
}else{
DIST <- DIST
}
#Initial clustering:
init.clust <- initial.clustering(x, k, DIST = DIST, maxclust, exhaustive)
if(!is.na(k)){
clustering <- init.clust$clustering
medoids <- init.clust$medoids
asw.profile <- init.clust$asw.profile
sesw.profile <- init.clust$sesw.profile
asw <- asw.profile
sesw <- sesw.profile
furth.info <- NULL
}else{
k <- init.clust$num.of.clusters
asw.profile <- init.clust$asw.profile
sesw.profile <- init.clust$sesw.profile
asw <- asw.profile[k]
sesw <- sesw.profile[k]
medoids <- init.clust$medoids
clustering <- init.clust$clustering
#Further partitioning, ordering and collapsing:
furth.clust <- further.clustering(x, k, DIST = DIST, medoids, clustering, asw, sesw, max.check, total.check,
maxclust = further.maxclust, exhaustive, maxsplit = maxsplit,
orness = orness, ah = ah, verbose)
medoids <- furth.clust$medoids
clustering <- furth.clust$clustering
k <- furth.clust$num.of.clusters
asw <- furth.clust$asw
furth.info <- list(k.development = furth.clust$k.info, asw.development = furth.clust$asw.info,
sesw.development = furth.clust$sesw.info, total.checks = furth.clust$total.checks)
}
if( !is.null(dimnames(x)[[1]]) ) names(clustering) <- dimnames(x)[[1]]
#OUTPUT:
list(medoids = medoids, clustering = clustering, asw = asw, num.of.clusters = k, info = furth.info,
profiles = list(asw.profile = asw.profile, sesw.profile = sesw.profile), metric = "McCulloch" )
}
#INITIAL CLUSTERING#
#Search function for finding the best clustering of x using PAM or CLARA. Uses a grid or exhaustive search up
#to maxclust unless k is given.
initial.clustering <- function(x, k, DIST, maxclust, exhaustive){
n.obj <- nrow(x)
DIST.init <- full2dist(DIST)
x.clust <- cluster.search(x, k, DIST = DIST.init, maxclust, exhaustive)
list(medoids = x.clust$medoids, clustering = x.clust$clustering,asw.profile = x.clust$asw.profile,
sesw.profile = x.clust$sesw.profile, num.of.clusters = x.clust$num.of.clusters)
}
cluster.search <- function(x, k, DIST = NULL, maxclust = 50, exhaustive){
n.obj <- nrow(x)
#Start:
if(n.obj <= 2 | !is.na(k)) { #When k is given or < 3 objects.
if(n.obj <= 2) {
x.medoids <- x
k <- n.obj
x.clustering <- 1:k
asw.profile <- NA
sesw.profile <- NA
names(asw.profile) <- list( k )
names(sesw.profile) <- list( k )
}else{
x.clust <- pam(DIST, k, diss=TRUE)
asw.profile <- x.clust$silinfo$avg.width
sesw.profile <- NA
names(asw.profile) <- list( k )
names(sesw.profile) <- list( k )
maxclust <- k
}
}else{ #Estimate k using average silhouette width:
maxclust <- min( maxclust, n.obj - 1 )
if(maxclust > 12 & exhaustive == FALSE){
gp <- sqrt(maxclust)
gpr <- round(gp)
gl <- floor(gp)
gst <- floor( ((gpr - 2) + (maxclust - gpr * gl)) / 2 + 2 )
grid <- seq(gst, by = gpr, length = gl)
gridout <- c(1, grid, maxclust + 1)
}else {
grid <- 2:maxclust
gpr <- 1
}
aswmax <- -1
k <- 1
asw.profile <- rep(-1,maxclust)
sesw.profile <- rep(NA,maxclust)
for(i in grid){
clusti <- pam(DIST, i, diss=TRUE)
asw.profile[i] <- clusti$silinfo$avg.width
if(asw.profile[i] > aswmax) {
aswmax <- asw.profile[i]
k <- i
x.clust <- clusti
}
}
if(gpr > 1){
kpos <- match(k,gridout)
grid2 <- c((gridout[kpos - 1] + 1) : (k - 1), (k + 1) : (gridout[kpos + 1] - 1))
for(i in grid2) {
clusti <- pam(DIST, i, diss=TRUE)
asw.profile[i] <- clusti$silinfo$avg.width
if(asw.profile[i] > aswmax){
aswmax <- asw.profile[i]
k <- i
x.clust <- clusti
}
}
}
}
#Check that k is a possible value:
if(n.obj > 2) {
if( !is.element(k,2:maxclust) ) {
stop("Number of clusters found is wrong")
}
x.medoids <- x[x.clust$medoids,]
x.clustering <- x.clust$clustering
}
list(medoids = x.medoids, clustering = x.clustering,asw.profile = asw.profile, sesw.profile = NA,
num.of.clusters = k)
}
##########
#ASW CALC#
#Calculates the average silhouette width of the data given a specific clustering. Note that asw.calc needs
#to be fed the appropriate medoids.
asw.calc <- function(x, k, clustering, DIST = NULL){
n.obj <- nrow(x)
if(is.matrix(DIST) && (ncol(DIST)==n.obj & nrow(DIST)==n.obj)){
col.size <- n.obj
sil.mem <- clustering
ind <- rep( clustering, col.size ) + rep( k * (0:(col.size-1)), each=n.obj )
sumdists <- matrix(tapply(DIST,ind,sum),ncol=col.size)
}
identif <- matrix(0,k,col.size)
identif[cbind(sil.mem,1:col.size)] <- 1
clus.sizes <- tabulate(clustering)
denominators <- matrix(rep(clus.sizes, col.size), ncol=col.size) - identif
sil.widths <- sumdists / denominators
ai <- sil.widths[identif == 1]
bi <- apply( matrix(sil.widths[identif == 0] , nrow = k - 1), 2, min)
si <- (bi - ai) / apply(cbind(bi,ai),1,max)
si[!is.finite(si)] <- 0
#[gives 0 as value of a(i) when only 1 in cluster].
asw <- mean(si)
sesw <- sqrt( var(si) / col.size )
list(asw = asw, sesw = sesw)
}
#####################
#FURTHER CLUSTERING#
#Further partitioning and collapsing; uses initial.clustering.
further.clustering <- function(x, k, DIST, medoids, clustering, asw, sesw, max.check, total.check, maxclust,
exhaustive, maxsplit, orness, ah, verbose){
n.obj <- nrow(x)
itc <- 0
isc <- 0
clust.perm <- sample(k)
k.info <- k
asw.info <- asw
sesw.info <- sesw
prev.groups <- NULL
prev.groups.index <- NULL
while(isc < k & itc <= total.check){
itc <- itc + 1
isc <- isc + 1
clust.i <- clust.perm[isc]
if(runif(1) < 0.5) {
poss.clust <- partition.cluster(x, k, DIST = DIST, clust.i, medoids, clustering, maxclust, exhaustive)
if(poss.clust$asw <= asw) {
poss.clust <- collapse.cluster(x, k, DIST = DIST, clust.i, medoids, clustering, asw, sesw, maxclust,
exhaustive, maxsplit, orness, ah, verbose)
}
}else{
poss.clust <- collapse.cluster(x, k, DIST = DIST, clust.i, medoids, clustering, asw, sesw, maxclust,
exhaustive, maxsplit, orness, ah, verbose)
if(poss.clust$asw <= asw) {
poss.clust <- partition.cluster(x, k, DIST = DIST, clust.i, medoids, clustering, maxclust, exhaustive)
}
}
if(poss.clust$asw > asw) {
k <- poss.clust$num.of.clusters
asw <- poss.clust$asw
sesw <- poss.clust$sesw
medoids <- poss.clust$medoids
clustering <- poss.clust$clustering
k.info <- c(k.info, k)
asw.info <- c(asw.info, asw)
sesw.info <- c(sesw.info, sesw)
isc <- 0
clust.perm <- sample(k)
}
}
list(medoids = medoids, clustering = clustering, num.of.clusters = k, asw = asw, sesw = sesw, k.info = k.info,
asw.info = asw.info, sesw.info = sesw.info, total.checks = itc)
}
#PARTITION CLUSTER#
partition.cluster <- function(x, k, DIST = NULL, j, medoids, clustering, maxclust, exhaustive){
if(length(clustering[clustering==j]) >= 1){
#Partitioning:
if(is.null(DIST)) {
DIST.part <- NULL
}else{
DIST.part <- full2dist( DIST[clustering==j,clustering==j] )
}
clust.obj <- cluster.search(x[clustering==j,], k = NA, DIST = DIST.part, maxclust = maxclust, exhaustive)
kj <- clust.obj$num.of.clusters
medoids.j <- clust.obj$medoids
#Ordering:
clustering[clustering > j] <- clustering[clustering>j] + kj - 1
clustering[clustering == j] <- j + clust.obj$clustering - 1
if(j == 1) medoids <- rbind(medoids.j, medoids[(j+1):k,])
if(j > 1 & j < k) medoids <- rbind(medoids[1:(j-1),], medoids.j, medoids[(j+1):k,])
if(j == k) medoids <- rbind(medoids[1:(j-1),], medoids.j)
k <- k + kj - 1
asw.obj <- asw.calc(x, k, clustering, DIST)
asw <- asw.obj$asw
sesw <- asw.obj$sesw
}
list(medoids = medoids, clustering = clustering,asw = asw, sesw = sesw, num.of.clusters = k)
}
##################
#COLLAPSE CLUSTER#
collapse.cluster <- function(x, k, DIST, j, medoids, clustering, asw, sesw, maxclust, exhaustive, maxsplit,
orness, ah,verbose){
if(k > 2){
DIST.medoids <- ext.dist(medoids, maxsplit, orness = orness, ah, verbose)
cluster.weights <- 1/(DIST.medoids[j,-j] + .001)
cluster.weights <- cluster.weights/sum(cluster.weights)
chosen.order <- sample((1:k)[-j], prob = cluster.weights)
}
n.check <- min(k-1,3)
ip <- 0
while(k > 2 & ip < n.check){
ip <- ip + 1
change1 <- j
change2 <- chosen.order[ip]
coll.step <- collapse.step(x, k, DIST, change1, change2, medoids, clustering, asw, sesw)
if(coll.step$asw > asw) {
medoids <- coll.step$medoids
clustering <- coll.step$clustering
asw <- coll.step$asw
sesw <- coll.step$sesw
k <- coll.step$num.of.clusters
ip <- n.check + 1
}
}
list(medoids = medoids, clustering = clustering,num.of.clusters = k, asw = asw, sesw = sesw)
}
#COLLAPSE STEP#
collapse.step <- function(x, k, DIST, change1, change2, medoids, clustering, asw, sesw){
ch.low <- min(change1,change2)
ch.high <- max(change1,change2)
if(ch.high != ch.low){
poss.clustering <- clustering
poss.clustering[poss.clustering == ch.high] <- ch.low
poss.clustering[poss.clustering > ch.high] <- poss.clustering[poss.clustering > ch.high] - 1
poss.medoids <- medoids
poss.medoids <- medoids[-ch.high,]
x.mm <- x[poss.clustering==ch.low,]
DIST.mm <- DIST[poss.clustering == ch.low, poss.clustering == ch.low]
pos.mm <- pam(full2dist(DIST.mm), k=1)$medoids
poss.medoids[ch.low,] <- x.mm[pos.mm,]
if(!is.null(dimnames(medoids))) dimnames(medoids)[[1]][ch.low] <- pos.mm
k.poss <- k - 1
asw.poss.obj <- asw.calc(x, k=k.poss, poss.clustering, DIST)
asw.poss <- asw.poss.obj$asw
sesw.poss <- asw.poss.obj$sesw
if(asw.poss >= asw){
asw <- asw.poss
sesw <- sesw.poss
clustering <- poss.clustering
k <- k.poss
medoids <- poss.medoids
}
}else{
}
list(medoids = medoids, clustering = clustering,num.of.clusters = k, asw = asw, sesw = sesw)
}
hipam.local <- function(tree, x, asw.tol, maxsplit, local.const, orness, type, ah, verbose,...){
#Iterative procedure to keep splitting branches as long as there are active branches.
active <- tree$active
while(sum(active) > 0){
choose.among <- (1:length(active))[active]
if(length(choose.among) == 1){
whch.brnch <- choose.among
}else {
whch.brnch <- sample(choose.among, 1)
}
if(type == "MO"){
proposal <- checkBranchLocalMO(tree, x, whch.brnch, maxsplit, asw.tol, local.const,
orness, type, ah, verbose, ...)
}else{
proposal <- checkBranchLocalIMO(tree, x, whch.brnch, maxsplit, asw.tol, local.const,
orness, type, ah, verbose, ...)
}
proposed.tree <- proposal$tree
if(proposal$reject){
tree$active[whch.brnch] <- FALSE
}else{
tree <- proposed.tree
}
active <- tree$active
}
tree
}
update.tree.local <- function(object, xi.ps, which.x, i){
tree <- object
#Number of clusters before the update:
maxclust <- max(tree$clustering)
#Update clustering:
tree$clustering[which.x] <- maxclust + xi.ps$clustering
#Update number of clusters:
new.clust <- xi.ps$num.of.clusters
tree$n.clust <- tree$n.clust + new.clust - 1
clust <- tree$clustering
#Update medoids:
tree$medoids <- rbind(tree$medoids, xi.ps$medoids)
#Update active status:
tree$active[i] <- FALSE
new.activities <- rep(TRUE, new.clust)
for (j in 1:new.clust){
if (sum(xi.ps$clustering==j) <= 2){
new.activities[j] <- FALSE
}
}
tree$active <- c(tree$active,new.activities)
#Update the development matrix:
dmat<- tree$development
nr <- nrow(dmat)
nc <- ncol(dmat)
whch.row <- sum((1:nr) * apply((dmat==i), 1, sum, na.rm = TRUE))
whch.col <- sum((1:nc) * apply((dmat==i), 2, sum, na.rm = TRUE))
dmat<-dmat[c(1:whch.row,rep(whch.row,new.clust-2),whch.row:nr),]
if (nc==whch.col){
dmat <- cbind(dmat,NA)
tree$n.levels <- tree$n.levels + 1
}
for (j in 1:new.clust){
dmat[whch.row + j - 1, whch.col + 1] <- maxclust + j
}
tree$development <- dmat
tree
}
full2dist <- function(fullm, method = "unspecified"){
distm <- fullm[lower.tri(fullm)] #?lower.tri: Returns a matrix of logicals the same size of a given
#matrix with entries.
#TRUE in the lower or upper triangle.
attr(distm , "Size") <- nrow(fullm)
attr(distm , "Labels") <- dimnames(fullm)[[1]]
attr(distm , "Diag") <- FALSE
attr(distm , "UPPER") <- FALSE
attr(distm, "method") <- method
attr(distm , "class") <- "dist"
attr(distm , "call") <- match.call()
class(distm) <- "dist"
return(distm)
}
| /scratch/gouwar.j/cran-all/cranData/Anthropometry/R/Anthropometry-internalHipamAnthropom.R |
make.circle.discovery <- function(cn, diam, diam.y = NA, col = "darkgrey"){
if (is.na(diam.y)){
diam.y<-diam
}
phi <- seq(0,2 * pi,length = 1000)
complex.circle <- complex(modulus = 1,argument = phi)
polygon(x = cn[1] + diam * Re(complex.circle) / 2, y = cn[2] + diam.y * Im(complex.circle) / 2, border = col)
}
make.arrow.circle <- function(x, y, diam, diam.y = NA, lwd = 1, code = 2){
if (is.na(diam.y)){
diam.y <- diam
}
xy.factor <- c(diam,diam.y)
x <- x / xy.factor
y <- y / xy.factor
diam <- 1
if (x[1] > y[1]){
#Calculate the skip vector v:
alpha <- atan((x[2] - y[2])/ (x[1] - y[1]))
v <- c(cos(alpha) * diam / 2, sin(alpha) * diam / 2)
}
if (x[1] == y[1]){
if (x[2] > y[2]){
v <- c(0, diam / 2)
} else {
v <- c(0, -diam / 2)
}
}
if (x[1] <y[1]){
#Calculate the skip vector v:
alpha <- atan((x[2] - y[2]) / (y[1] - x[1]))
v <- c(-cos(alpha) * diam / 2, sin(alpha) * diam / 2)
}
if (sum((x-y)^2)<=diam^2){
x.new <- x + v
y.new <- y + v
} else {
x.new <- x - v
y.new <- y + v
}
x.new <- x.new * xy.factor
y.new <- y.new * xy.factor
arrows(x.new[1], x.new[2], y.new[1], y.new[2], lwd = lwd, length = 0.1, angle = 20, code = code)
}
| /scratch/gouwar.j/cran-all/cranData/Anthropometry/R/Anthropometry-internalPlotTree.R |
#assign("last.warning", NULL, envir = baseenv())
is.empty <- function(x, mode=NULL){
if (is.null(mode)) mode <- class(x)
identical(vector(mode,1),c(x,vector(class(x),1)))
}
rowweight <- function(X,a){ #Product function.
xm <- X * a
return(xm)
}
Distvec <- function(Xmatr,y){ #L1 distance from y to all data points.
Dv <- apply(Xmatr,1,l1norm,b=y)
return(Dv)
}
l1norm <- function(a,b){ #L1 distance from a to b.
l1 <- sqrt(sum((a-b)^2))
return(l1)
}
unitvec <- function(a,b){ #Unit vector from a to b.
l1 <- sqrt(sum((a-b)^2))
if (l1 > 10^(-10)){
uv <- (b-a)/l1
}
if (l1 < 10^(-10)){
uv <- matrix(0,1,length(a))
}
return(uv)
}
initW2 <- function(Xmatr,Nvec){ #Initial y for Weiszfeld algorithm.
#Xmatr = cell data matrix, Nmat = multiplicities.
dimX <- dim(Xmatr)
mm <- apply(Xmatr,2,mean)
ystart <- mm
return(ystart)
}
Weisziteradj <- function(Xmatr,Nvec,ystart,B){ #Iterates the Weiszfeld step B times # starting value ystart.
y <- ystart
for(k in (1:B)){
W <- Weiszfeldadj(Xmatr,Nvec,y)
y <- W$y
}
DDy <- W$DDy
return(list(y=y,DDy=DDy))
}
Weiszfeldadj <- function(Xmatr,Nvec,ystart){
#Xmatr distinct data matrix, Nvec vector of multiplicities, ystart is the starting point.
#Also gives data depth of new y.
l <- rbind(Xmatr,ystart)
y <- ystart
lcorr <- cor(t(l))
diag(lcorr) <- 0
uc <- upper.tri(lcorr)
lcorr[uc==0] <- 0
lcorr[abs(lcorr-1) < 10^(-10)] <- 1
lcorr[abs(lcorr-1) > 10^(-10)] <- 0
ccl <- apply(lcorr,1,sum) #Default for y weight.
ny <- 0
if (max(ccl)==1){ #y is in the set of observations.
cpp <-ccl[1:(length(ccl)-1)]
ny <- Nvec[cpp==1]
}
dvec <- Distvec(Xmatr,y) #Distance from Xmatr elements to y.
dind <- seq(1,length(dvec))
dinds <- dind[abs(dvec) > 10^(-10)]
wvec <- matrix(0,1,dim(Xmatr)[1])
wvec[dinds] <- (Nvec[dinds] / dvec[dinds])
wvec <- wvec / sum(wvec)
Ttilde <- apply(apply(Xmatr,2,rowweight,a=wvec),2,sum)
unitvecs <- t(apply(Xmatr,1,unitvec,b=y))
wunitvecs <- apply(unitvecs,2,rowweight,a=Nvec)
ry <- sqrt(sum(apply(wunitvecs,2,sum)^2))
ynew <- Ttilde * max(0,(1-ny/ry)) + y * min(1,ny/ry)
unitvecs <- t(apply(Xmatr,1,unitvec,b=ynew))
ebar <- sqrt(sum(apply(apply(unitvecs,2,rowweight,a=Nvec/sum(Nvec)),2,sum)^2))
l <- rbind(ynew,Xmatr)
lcorr <- cor(t(l))
diag(lcorr) <- 0
uc<-upper.tri(lcorr)
lcorr[uc==0] <- 0
lcorr[abs(lcorr-1) < 10^(-10)] <- 1
lcorr[abs(lcorr-1) > 10^(-10)] <- 0
ccl <- apply(lcorr,1,sum)
ny<-0
if(max(ccl)==1){
ny<-Nvec[ccl==1]
}
if(ny==0){
DDy <- 1 - ebar
}
if(ny>0) {
DDy <- 1 - max(0,(ebar-ny/sum(Nvec)))
#DDy <- 1 - ebar
}
y<-ynew
return(list(y=y,DDy=DDy))
}
##TO RUN THE PROGRAM##
#yr <- initW2(Xmatr,Nvecr)
#W <- Weisziteradj(Xmatr,Nvecr,yr,B) #Usually enough to run B=5, can check by DDy to see that it is equal to 1.
#Y <- W$Y #This is the multivariate median.
#Computing depth of an observations with respect to a cluster.
DDapply <- function(Xv,Xmat) { #Computes the depths of a vector of observations Xv with respect to
#a cloud of observations Xmat.
Nvec <- rep(1,dim(Xmat)[1])
dd <- DDfcnadj(Xmat,Nvec,Xv)
return(dd)
}
DDfcnadj <- function(Xmatr,Nvec,y){ #Computes the data depth of point y in cloud Xmatr.
aux <- apply(Xmatr,1,unitvec,b=y)
#if(class(aux) == "list"){
# unitvecs <- t(matrix(unlist(aux),dim(Xmatr)[1],dim(Xmatr)[2]))
#}else{
# unitvecs <- t(aux)
#}
if(inherits(aux, "list")){
unitvecs <- t(matrix(unlist(aux),dim(Xmatr)[1],dim(Xmatr)[2]))
}else{
unitvecs <- t(aux)
}
#unitvec<-function(a,b){ #Unit vector from a to b.
#l1<-sqrt(sum((a-b)^2))
#if (l1 > 10^(-10)){ #10^(-10)
# uv <- (b-a)/l1
#}
# if (l1 < 10^(-10)){
# uv <- matrix(0,1,length(a))
# }
# return(uv)
#}
gvv = matrix(as.numeric(unitvecs), dim(unitvecs)[1], dim(unitvecs)[2])
a <- Nvec/sum(Nvec)
ebar <- sqrt( sum ( apply( rowweight(gvv,a) ,2,sum )^2))
#rowweight<-function(X,a){ #Product function
# xm<-X*a
# return(xm)
#}
l <- rbind(y,Xmatr)
lcorr <- cor(t(l))
diag(lcorr) <- 0
uc <- upper.tri(lcorr)
lcorr[uc==0] <- 0
lcorr[abs(lcorr-1) < 10^(-10)] <- 1
lcorr[abs(lcorr-1) > 10^(-10)] <- 0
ccl <- apply(lcorr,1,sum)
ny <- 0
if(max(ccl)==1){
ny <- sum(Nvec[ccl==1])
}
if(ny == 0){
DDy <- 1-ebar
}
if(ny > 0){
DDy <- 1-max(0,(ebar-ny/sum(Nvec)))
#DDy <- 1-ebar
}
return(DDy)
}
DDapplyloo <- function(Xv,Xmat){
dl <- apply(Xmat,1,l1norm,b=Xv)
Xmatu <- Xmat[dl>0,]
Nvec <- rep(1,dim(Xmatu)[1])
dd <- DDfcnadj(Xmatu,Nvec,Xv)
return(dd)
}
##TO RUN##
#x is a vector, X is a group of data,N is the vector of multiplicities.
#Dx <- apply(x,1,DDapply,Xmat=X,Nvec=N) #Depth of a single observation x.
#Dx <- DDfcnadj(Xmat,Nvec,x)
DDcalc2 <- function(DDi,NN,K,Km,norm=1){
n <- NN[1,]
nvec <- matrix(0,K,1)
ovec <- matrix(0,length(n),1)
svec <- matrix(0,length(n),1)
indvec <- seq(1,length(n))
normvec <- matrix(0,K,1)
for(kz in (1:K)){
nvec[kz] <- length(n[n==kz])
Vin <- DDi[n==kz,kz]
normvec[kz] <- mean(Vin)
}
if(norm==0){
normvec <- normvec/normvec
}
DDb <- matrix(0,length(n),1)
DDw <- DDb
DD <- DDb
Vt <- 0
VZD <- DDi
for(ml in (1:length(n))){
if(ml==1){
Vt <- DDi[ml,c(NN[2:Km,ml])] / normvec[c(NN[2:Km,ml])]
VZD[ml,] <- DDi[ml,] / normvec[c(NN[,ml])]
}
if(ml>1){
Vt <- c(Vt,DDi[ml,c(NN[2:Km,ml])] / normvec[c(NN[2:Km,ml])])
VZD[ml,] <- DDi[ml,] / normvec[c(NN[,ml])]
}
}
TT <- Vt[rev(sort.list(Vt))[length(NN[1,])+1]] #VZD2<-VZD #VZD[VZD<-0
for(kt in (1:length(n))){
Nv <- NN[2:Km,kt]
Vv <- sum(VZD[kt,Nv])
DDw[kt] <- DDi[kt,NN[1,kt]] / normvec[NN[1,kt]]
DDb[kt] <- VZD[kt,NN[2,kt]] / normvec[c(NN[2,kt])]
ti <- DDi[kt,NN[1,kt]] / normvec[NN[1,kt]]
DD[kt] <- (ti-Vv)
}
return(list(DDw=DDw,DD=DD))
}
pamsil <- function(X,pc,K) { #Silwidth calculation.
sil <- matrix(0,length(pc),1)
Kvec <- seq(min(pc):max(pc))
Nuvec <- pc
ccl <- rep(0,length(pc))
clvec <- matrix(0,length(pc),K)
clvec[,1] <- pc
clvec2 <- clvec
indvec <- seq(1:length(Nuvec))
for(kt in (1:length(pc))){
kk <- Nuvec[kt]
kc <- setdiff(indvec,kt)
Nt <- Nuvec[kc]
ai <- mean(Distvec(X[kc[Nt==kk],],X[kt,]))
Ks <- setdiff(Kvec,kk)
for(kz in (1:length(Ks))){
if(kz==1){
bi <- mean(Distvec(X[Nuvec==Ks[kz],],X[kt,]))
ccl[kt] <- Ks[kz]
clvec2[kt,2] <- bi
clvec[kt,2] <- Ks[kz]
}
if(kz>1){
nnd <- mean(Distvec(X[Nuvec==Ks[kz],],X[kt,]))
if(bi>nnd){
ccl[kt] <- Ks[kz]
}
bi <- min(bi,nnd)
clvec2[kt,kz+1] <- nnd
clvec[kt,kz+1] <- Ks[kz]
}
}
sili <- (bi-ai) / max(bi,ai)
sil[kt] <- sili
}
clvec <- clvec[,2:K]
clvec2 <- clvec2[,2:K]
if(K>2){
Sm <- apply(clvec2,1,sort.list)
clvec3 <- clvec
for(kk in (1:length(Nuvec))){
clvec3[kk,] <- clvec[kk,Sm[,kk]]
}
clvec <- clvec3
}
return(list(sil=sil,ccl=ccl,clvec=clvec))
}
NNDDVQA1 <- function(X,pcc,lambda,norm){
#X is the data matrix.
#pcc particion actual.
#MM is the matrix of multivariate medians.
#T is current temperature.
K <- dim(pcc$med)[1]
Km <- 2
Kmat <- matrix(0,dim(X)[1],K)
for(kk in (1:K)){
Kmat[,kk]<-apply(X,1,l1norm,b=pcc$med[kk,])
}
Smat <- apply(Kmat,1,sort.list)
Kmat <- apply(Kmat,1,sort)
NNuse <- Smat
Nvec <- rep(1,dim(X)[1])
DDi <- matrix(0,dim(X)[1],K)
for(kz in (1:K)){
for(ky in (1:dim(X)[1])){
Xmatr <- X[NNuse[1,] == kz,]
Nvecr <- Nvec[NNuse[1,] == kz]
DDi[ky,kz] <- DDfcnadj(Xmatr,Nvecr,X[ky,])
}
}
DD <- DDcalc2(DDi,NNuse,K,Km,norm)
pcc <- pamsil(X,NNuse[1,],K)
Kmata <- pcc$sil * (1 - lambda) + lambda * DD$DD
NN <- NNuse
NN[2:K,] <- t(pcc$clvec)
Nuvec <- NNuse[1,]
Kmatb <- 0
prs <- 0
stopnow <- 0
return(list(NN=NN,DDi=DDi,DD=DD,pcc=pcc,Kmata=Kmata,Nuvec=Nuvec,Kmatb=Kmatb,prs=prs,stopnow=stopnow))
}
NNDDVQE <- function(X,MM,prT,lambda,NNold,Km,Th,Trimm,kl,NNold_old,verbose){
#X is the data matrix.
#MM is the matrix of multivariate medians.
#Th is current temperature.
change <- c()
iter_while <- 0
improv <- c()
norm <- 0
K <- dim(MM)[1]
if(K <= 3){
Km <- 2
}
aux <- sort(NNold$Kmata)
tri <- Trimm*(dim(X)[1])
if(tri < 1){
tri1 <- ceiling(tri)
}else{
tri1 <- round(tri)
}
phi <- aux[abs(tri1)]
trimm <- which(NNold$Kmata <= phi)
if(verbose){
cat("Trimmed women: ")
print(trimm)
cat("\n")
}
X <- X[-trimm,]
sil <- as.matrix(NNold$pcc$sil[-trimm,])
ccl <- NNold$pcc$ccl[-trimm]
clvec <- as.matrix(NNold$pcc$clvec[-trimm,])
pcc_aux <- list(sil=sil,ccl=ccl,clvec=clvec)
pcc <- pcc_aux
NNuse <- NNold$NN[,-trimm]
NNuse[2:K,] <- t(pcc$clvec)
Nvec <- rep(1,dim(X)[1])
DDi <- NNold$DDi[-trimm,]
DDw <- as.matrix(NNold$DD$DDw[-trimm,])
DD <- as.matrix(NNold$DD$DD[-trimm,])
DD <- list(DDw=DDw,DD=DD)
Kmata <- pcc$sil * (1 - lambda) + lambda * DD$DD
if((kl-1) == 0){
if(verbose){
cat("Initial value of the partition:")
print(mean(Kmata))
cat("\n")
}
}else{
if(verbose){
cat("Initial value of the partition:")
print(NNold$Cost)
cat("\n")
}
}
Th <- as.numeric(quantile(Kmata,0.25))
Kmat0 <- Kmata
Kmatb <- Kmata
Kmatb[Kmata > Th] <- 1
Kmatb[Kmata <= Th] <- 0
NNnew <- NNuse
NNusea <- NNuse
indvec <- seq(1,dim(X)[1])
Iuse <- indvec[Kmatb==0] #Elements that can be moved.
Iuse <- setdiff(Iuse,trimm)
if(verbose){
cat("Set S of observations that can be relocated:")
print(Iuse)
cat("\n")
}
ct <- 0
nostop <- 0
nb <- min(50,length(Iuse))
if(verbose){
cat("While loop starts: \n")
}
while(length(Iuse)>0 & nostop<=nb){
iter_while <- iter_while + 1
if(length(Iuse)==1){
iuse <- Iuse
if(verbose){
cat("Random subset E of S:")
print(iuse)
}
}
if(length(Iuse)>1){
E <- round(runif(1,min=1,max=min(10,length(Iuse))))
iuse <- sample(Iuse,E)
if(verbose){
cat("Random subset E of S:")
print(iuse)
}
}
for(zz in (1:length(iuse))){
NNusea[1,iuse[zz]] <- NNuse[2,iuse[zz]]
NNusea[2,iuse[zz]] <- NNuse[1,iuse[zz]]
}
DDia <- DDi-DDi
for(kz in (1:K)){
Xmatr <- X[NNusea[1,]==kz,]
Nvecr <- Nvec[NNusea[1,]==kz]
DDia[,kz] <- apply(X,1,DDapply,Xmat=Xmatr)
}
DDa <- DDcalc2(DDia,NNusea,K,Km,norm)
pcca <- pamsil(X,NNusea[1,],K)
if(verbose){
cat("Candidate partition:")
print(table(NNusea[1,]))
cat("\n")
}
Kmataa <- pcca$sil * (1 - lambda) + lambda * DDa$DD #Value of new partition.
if((kl-1) == 0){
Del <- mean(Kmataa) - mean(Kmata)
}else{
Del <- mean(Kmataa) - NNold$Cost
}
if(Del == "NaN"){
stop("This partition cannot be evaluated \n")
break
}
if((kl-1) == 0){
if(verbose){
cat("Value of the previous partition C(I_1^{K}):")
print(mean(Kmata))
}
}else{
if(verbose){
cat("Value of the previous partition C(I_1^{K}):")
print(NNold$Cost)
}
}
if(verbose){
cat("Value of the new partition C(tilde{I}_1^{K}):")
print(mean(Kmataa))
cat("Current Delta value:")
print(Del)
cat("\n")
}
#Stopping criterion:
if(Del > 0){
if((Del / mean(Kmataa)) < 0.01){
if(verbose){
cat("STOPPING CRITERION FULFILLED")
cat("\n")
}
change[iter_while] <- 0
break
}
}
pru <- runif(1)
if(prT>0){
PRT <- exp(Del/prT)
if(verbose){
cat("Probability of mis-allocation:")
print(PRT)
cat("\n")
}
}
if(prT==0){
PRT <- 0
if(verbose){
cat("Probability of mis-allocation:")
print(PRT)
cat("\n")
}
}
if(Del>0 | (Del<=0 & pru==PRT)){
NNuse <- NNusea
Kmata <- Kmataa
if(verbose){
cat("The partition is accepted.\n")
cat("New value of the partition:")
print(mean(Kmata))
cat("Partition:\n")
print(table(NNuse[1,]))
}
NNold$Cost <- mean(Kmata)
if(verbose){
cat("\n")
}
improv[kl] <- kl - 1
change[iter_while] <- 1
}else{
NNold$Cost <- NNold$Cost
if(verbose){
cat("The partition is rejected.\n")
cat("Current value of the partition:")
print(NNold$Cost)
cat("\n")
}
change[iter_while] <- 0
}
nostop <- nostop+1
}
if(verbose){
cat("While loop ends: \n")
}
if(max(change) == 1){
if(ct==0){
stopnow <- 1
}
if(ct>0){
stopnow <- 0
}
prs <- ct/length(NNuse[1,])
NNnew <- NNuse
NN <- NNnew
Nuvec <- NNnew[1,]
DDia <- matrix(0,nrow=dim(X)[1],ncol=K)
for(kz in (1:K)){
Xmatr <- X[NNuse[1,]==kz,]
Nvecr <- Nvec[NNuse[1,]==kz]
DDia[,kz]<-apply(X,1,DDapply,Xmat=Xmatr)
}
DDa <- DDcalc2(DDia,NNuse,K,Km,norm)
pcc <- pamsil(X,NNuse[1,],K)
return(list(Iuse=Iuse,ct=ct,NN=NN,DDi=DDia,DD=DDa,pcc=pcc,Kmata=Kmata,Kmat0=Kmat0,Nuvec=Nuvec,Kmatb=Kmatb,
prs=prs,stopnow=stopnow,Cost=NNold$Cost,trimmed=trimm,improv=improv))
}else if(max(change) == 0 | is.null(change)){
NNold_old <- NNold_old
if((kl-1) == 0){
NNold_old$Cost <- mean(Kmata)
}else{
NNold_old$Cost <- NNold$Cost
}
NNold_old$ct <- ct
NNold_old$trimmed <- trimm
NNold_old$improv <- improv
return(NNold_old)
}
}
NNDDVQEstart <- function(X,MM,prT,lambda,NNold,Km,Th,Trimm,kl,NNold_old,verbose){
#X is the data matrix.
#MM is the matrix of multivariate medians.
#Th is current temperature.
change <- c()
iter_while <- 0
improv <- c()
norm <- 0
K <- dim(MM)[1]
if(K < 3){
Km <- 2
}
aux <- sort(NNold$Kmata)
tri <- Trimm*(dim(X)[1])
if(tri < 1){
tri1 <- ceiling(tri)
}else{
tri1 <- round(tri)
}
phi <- aux[abs(tri1)]
trimm <- which(NNold$Kmata <= phi)
if(verbose){
cat("Trimmed women: ")
print(trimm)
cat("\n")
}
X <- X[-trimm,]
sil <- as.matrix(NNold$pcc$sil[-trimm,])
ccl <- NNold$pcc$ccl[-trimm]
clvec <- as.matrix(NNold$pcc$clvec[-trimm,])
pcc_aux <- list(sil=sil,ccl=ccl,clvec=clvec)
pcc <- pcc_aux
NNuse <- NNold$NN[,-trimm]
NNuse[2:K,] <- t(pcc$clvec)
Nvec <- rep(1,dim(X)[1])
DDi <- NNold$DDi[-trimm,]
DDw <- as.matrix(NNold$DD$DDw[-trimm,])
DD <- as.matrix(NNold$DD$DD[-trimm,])
DD <- list(DDw=DDw,DD=DD)
Kmata <- pcc$sil * (1 - lambda) + lambda * DD$DD
if((kl-1) == 0){
if(verbose){
cat("Initial value of the partition:")
print(mean(Kmata))
cat("\n")
}
}else{
if(verbose){
cat("Initial value of the partition:")
print(NNold$Cost)
cat("\n")
}
}
Th <- as.numeric(quantile(Kmata,0.25))
Kmat0 <- Kmata
Kmatb <- Kmata
Kmatb[Kmata > Th] <- 1
Kmatb[Kmata <= Th] <- 0
NNnew <- NNuse
NNusea <- NNuse
indvec <- seq(1,dim(X)[1])
Iuse <- indvec[Kmatb==0] #Elements that can be moved.
Iuse <- setdiff(Iuse,trimm)
if(verbose){
cat("Set S of observations that can be relocated:")
print(Iuse)
cat("\n")
}
ct <- 0
fir <- 0
nostop <- 0
nb <- min(50,length(Iuse))
if(verbose){
cat("While loop starts:\n")
}
while(length(Iuse)>0 & nostop<=nb){
iter_while <- iter_while + 1
if(length(Iuse)==1){
iuse <- Iuse
if(verbose){
cat("Random subset E of S:")
print(iuse)
}
}
if(length(Iuse)>1){
E <- round(runif(1,min=1,max=min(5,length(Iuse))))
iuse <- sample(Iuse,E)
if(verbose){
cat("Random subset E of S:")
print(iuse)
}
}
for(zz in (1:length(iuse))){
NNusea[1,iuse[zz]] <- NNuse[2,iuse[zz]]
NNusea[2,iuse[zz]] <- NNuse[1,iuse[zz]]
}
DDia <- DDi-DDi
for(kz in (1:K)){
Xmatr <- X[NNusea[1,]==kz,]
Nvecr <- Nvec[NNusea[1,]==kz]
DDia[,kz]<-apply(X,1,DDapply,Xmat=Xmatr)
}
DDa <- DDcalc2(DDia,NNusea,K,Km,norm)
pcca <- pamsil(X,NNusea[1,],K)
if(verbose){
cat("Candidate partition:")
print(table(NNusea[1,]))
cat("\n")
}
Kmataa <- pcca$sil * (1 - lambda) + lambda * DDa$DD
if((kl-1) == 0){
Del <- mean(Kmataa) - mean(Kmata)
}else{
Del <- mean(Kmataa) - NNold$Cost
}
if(Del == "NaN"){
stop("This partition cannot be evaluated \n")
break
}
if((kl-1) == 0){
if(verbose){
cat("Value of the previous partition C(I_1^{K}):")
print(mean(Kmata))
}
}else{
if(verbose){
cat("Value of the previous partition C(I_1^{K}):")
print(NNold$Cost)
}
}
if(verbose){
cat("Value of the new partition C(tilde{I}_1^{K}):")
print(mean(Kmataa))
cat("Current Delta value:")
print(Del)
cat("\n")
}
#Stopping criterion:
if(Del > 0){
if((Del / mean(Kmataa)) < 0.01){
if(verbose){
cat("STOPPING CRITERION FULFILLED")
cat("\n")
}
change[iter_while] <- 0
break
}
}
pru <- runif(1)
if(fir==0 & prT>0){
prT <- -abs(Th)/log(prT)
T0 <- prT
PRT <- exp(Del/prT)
fir <- 1
if(verbose){
cat("Probability of mis-allocation:")
print(PRT)
cat("\n")
}
}
if(fir!=0 & prT>0){
PRT <- exp(Del/prT)
if(verbose){
cat("Probability of mis-allocation:")
print(PRT)
cat("\n")
}
}
if(prT==0){
PRT <- 0
if(verbose){
cat("Probability of mis-allocation:")
print(PRT)
cat("\n")
}
}
if(fir==0){
PRT <- -abs(Del)/log(prT)
if(verbose){
cat("Probability of mis-allocation:")
print(PRT)
cat("\n")
}
T0 <- prT
fir <- 1
}
if(verbose){
cat("Probability of mis-allocation:")
print(PRT)
cat("\n")
}
if(Del>0 | (Del<=0 & pru==PRT)){
NNuse <- NNusea
Kmata <- Kmataa
if(verbose){
cat("The partition is accepted.\n")
cat("New value of the partition:")
print(mean(Kmata))
cat("Partition:\n")
print(table(NNuse[1,]))
}
NNold$Cost <- mean(Kmata)
if(verbose){
cat("\n")
}
improv[kl] <- kl - 1
change[iter_while] <- 1
}else{
NNold$Cost <- NNold$Cost
if(verbose){
cat("The partition is rejected.\n")
cat("Current value of the partition:")
print(NNold$Cost)
cat("\n")
}
change[iter_while] <- 0
}
nostop <- nostop+1
}
if(verbose){
cat("While loop ends: \n")
}
if(max(change) == 1){
if(ct==0){
stopnow <- 1
}
if(ct>0){
stopnow <- 0
}
prs <- ct/length(NNuse[1,])
NNnew <- NNuse
NN <- NNnew
Nuvec <- NNnew[1,]
DDia <- matrix(0,nrow=dim(X)[1],ncol=K)
for(kz in (1:K)){
Xmatr <- X[NNuse[1,]==kz,]
Nvecr <- Nvec[NNuse[1,]==kz]
DDia[,kz]<-apply(X,1,DDapply,Xmat=Xmatr)
}
DDa <- DDcalc2(DDia,NNuse,K,Km,norm)
pcc <- pamsil(X,NNuse[1,],K)
return(list(Iuse=Iuse,ct=ct,NN=NN,DDi=DDia,DD=DDa,pcc=pcc,Kmata=Kmata,Kmat0=Kmat0,Nuvec=Nuvec,Kmatb=Kmatb,
prs=prs,stopnow=stopnow,Cost=NNold$Cost,trimmed=trimm,improv=improv,T0=T0))
}else if(max(change) == 0 | is.null(change)){
NNold_old <- NNold_old
if((kl-1) == 0){
NNold_old$Cost <- mean(Kmata)
}else{
NNold_old$Cost <- NNold$Cost
}
NNold_old$ct <- ct
NNold_old$trimmed <- trimm
NNold_old$improv <- improv
NNold_old$T0 <- T0
return(NNold_old)
}
}
| /scratch/gouwar.j/cran-all/cranData/Anthropometry/R/Anthropometry-internalTDDclust.R |
CCbiclustAnthropo <- function(data,waistVariable,waistCirc,lowerVar,nsizes,nBic,diffRanges,percDisac,dir){
n <- c()
dims <- list() ; res <- list() ; wr <- list() ; mat <- list() ; tab_acc <- list() ;
ColBics <- list() ; delta <- list() ; disac <- list()
setwd(dir)
for (i in 1 : (nsizes-1)){
da_size <- data[(waistVariable >= waistCirc[i]) & (waistVariable < waistCirc[i + 1]), ]
n[i] <- dim(da_size)[1]
da_size2 <- da_size[,lowerVar]
da_size3 <- da_size2 / 10
diff_ranges <- apply(da_size3, 2, range)[2,] - apply(da_size3, 2, range)[1,]
selectedCols <- which(diff_ranges >= diffRanges[[i]][1] & diff_ranges <= diffRanges[[i]][2])
da_size4 <- as.matrix(da_size3[,selectedCols])
dims[[i]] <- dim(da_size4)
delta[[i]] <- 1
disac[[i]] <- nrow(da_size4)
while (disac[[i]] > ceiling(percDisac * nrow(da_size4))){
res[[i]] <- biclust(da_size4, method = BCCC(), delta = delta[[i]], alpha = 1.5, number = nBic[i])
wr[[i]] <- writeclust(res[[i]], row = TRUE, noC = res[[i]]@Number)
disac[[i]] <- sum(wr[[i]] == 0)
if(disac[[i]] > ceiling(percDisac * nrow(da_size4))){
delta[[i]] = delta[[i]] + 1
}
}
if(res[[i]]@Number == 0){
mat[[i]] <- NA
}else{
mat[[i]] <- sapply(1 : res[[i]]@Number, overlapBiclustersByRows, res[[i]])
acc <- c()
for(j in 1:nrow(mat[[i]])){
acc[j] <- length(which(mat[[i]][j,] == 0))
}
tab_acc[[i]] <- list(table(acc), nBic[i], dims[[i]][1], disac[[i]])
rm(acc)
tab_acc[[i]] <- list(table(acc), nBic[i], dims[[i]][1])
rm(acc)
fils <- res[[i]]@RowxNumber
cols <- res[[i]]@NumberxCol
fun1 <- function(x){
list(rownames(da_size4[fils[, x], ]), colnames(da_size4[, cols[x,]]))
}
nom_var <- paste("list.bicl", i, sep = ".")
assign(nom_var, lapply(1:length(fils[1, ]), fun1))
lista <- get(paste("list.bicl.", i, sep = ""))
save(lista, file = paste("list.bicl", i, "RData", sep = "."))
filsBic <- list()
colsBic <- list()
for(j in 1:res[[i]]@Number){
filsBic[[j]] <- biclusternumber(res[[i]], number = 1:res[[i]]@Number)[[j]][1]
colsBic[[j]] <- biclusternumber(res[[i]], number = 1:res[[i]]@Number)[[j]][2]
}
tab <- table(unlist(colsBic))
dimnames_tab <- attr(tab, "dimnames")
dimnames_tab2 <- as.numeric(unlist(dimnames_tab))
ColBics[[i]] <- colnames(da_size2)[dimnames_tab2[tab == nBic[i]]]
}
}
return(list(res=res,dims=dims,delta=delta,disac=disac,mat=mat,tab_acc=tab_acc,ColBics=ColBics))
} | /scratch/gouwar.j/cran-all/cranData/Anthropometry/R/CCbiclustAnthropo.R |
HartiganShapes <- function(array3D,numClust,algSteps=10,niter=10,stopCr=0.0001,simul,initLl,initials,
verbose){
#,computCost
time_iter <- list()
comp_time <- c()
list_ic1 <- list()
list_ic1_step <- list()
vect_all_rate <- c()
ll <- 1 : numClust
dist <- matrix(0, dim(array3D)[3], numClust)
if(verbose){
print(Sys.time())
}
time_ini <- Sys.time()
#Initialize the objective function by a large enough value:
vopt <- 1e+08
#Ramdon restarts:
for(iter in 1 : niter){
wss_step <- list()
if(verbose){
cat("New iteration")
print(iter)
cat("Optimal value with which this iteration starts:")
print(vopt)
}
#STEP 1: For each point I, find its two closest centers, IC1(I) and IC2(I). Assign the point to IC1(I):
meanshapes <- 0 ; mean_sh <- list()
ic1 <- c() ; ic2 <- c() ; dt <- c() ; nc <- c() #number of points in each cluster.
an1 <- c() ; an2 <- c() ; itran <- c() ; ncp <- c()
indx <- c() ; d <- c() ; live <- c() ; wss <- c()
n <- dim(array3D)[3]
initials_hart <- list()
if(initLl){
initials_hart[[iter]] <- initials[[iter]]
}else{
initials_hart[[iter]] <- sample(1:n, numClust, replace = FALSE)
}
if(verbose){
cat("Initial values of this iteration:")
print(initials_hart[[iter]])
}
meanshapes <- array3D[,,initials_hart[[iter]]]
#meanshapes_aux <- array3D[, , initials[[iter]]]
#if(computCost){
#time_ini_dist <- Sys.time()
#dist_aux = riemdist(array3D[,,1], y = meanshapes[,,1])
#time_end_dist <- Sys.time()
#cat("Computational cost of the Procrustes distance:")
#print(time_end_dist - time_ini_dist)
#}
for(i in 1 : n){
ic1[i] = 1
ic2[i] = 2
for(il in 1 : 2){
dt[il] = (riemdist(array3D[,,i], meanshapes[,,il]))^2
}
if(dt[2] < dt[1]){
ic1[i] = 2
ic2[i] = 1
temp = dt[1]
dt[1] = dt[2]
dt[2] = temp
}
if(simul == FALSE){
for(l in 3 : numClust){
db = (riemdist(array3D[,,i], meanshapes[,,l]))^2
if(db < dt[2]){
if(dt[1] <= db){
dt[2] = db
ic2[i] = l
}else{
dt[2] = dt[1]
ic2[i] = ic1[i]
dt[1] = db
ic1[i] = l
}
}
}
}
}
#if(computCost){
#time_ini_mean <- Sys.time()
#meanshapes_aux[,,1] = procGPA(array3D[, , ic1 == 1], distances = TRUE, pcaoutput = TRUE)$mshape
#time_end_mean <- Sys.time()
#cat("Computational cost of the Procrustes mean:")
#print(time_end_mean - time_ini_mean)
#}
#STEP 2: Update the cluster centres to be the averages of points contained within them.
#Check to see if there is any empty cluster at this stage:
for(l in 1 : numClust){
nc[l] <- table(ic1)[l]
#print("Loop numClust")
#print(nc[l])
if(nc[l] <= 3){ # nc[l] == 0
#stop("At least one cluster is empty or has a very few elements after the initial assignment.
# A better set of initial cluster centers is needed.")
#break
return(cat("At least one cluster is empty or has a very few elements after the initial assignment.
A better set of initial cluster centers is needed. No solution provided."))
}
}
#print("Loop checked successfully")
for(l in 1 : numClust){
aa = nc[l]
#print("This is array3D")
#print(array3D)
#print("This is ic1")
#print(ic1)
#print("This is l")
#print(l)
x <- array3D[, , ic1 == l]
#print("This is x")
#print(dim(x))
if (length(dim(x)) != 3) {
#stop("Please ensure that array3D has 3 dimensions.")
#break
return(cat("Please ensure that array3D has 3 dimensions.")) # This is not actually needed
# anymore because the previous return already stops the execution since there are some
# very small clusters.
}else{
meanshapes[,,l] = shapes::procGPA(x, distances = TRUE, pcaoutput = TRUE)$mshape
}
#Initialize AN1, AN2, ITRAN and NCP.
#AN1(L) = NC(L) / (NC(L) - 1)
#AN2(L) = NC(L) / (NC(L) + 1)
#ITRAN(L) = 1 if cluster L is updated in the quick-transfer stage,
# = 0 otherwise
#In the optimal-transfer stage, NCP(L) stores the step at which cluster L is last updated.
#In the quick-transfer stage, NCP(L) stores the step at which cluster L is last updated plus M:
an2[l] = aa / (aa + 1)
if(1 < aa){
an1[l] = aa / (aa - 1)
}else{
an1[l] = Inf
}
itran[l] = 1
ncp[l] = -1
}
indx <- 0
d[1:n] = 0
live[1:numClust] = 0
for(step in 1 : algSteps){
#In this stage, there is only one pass through the data. Each point is re-allocated, if necessary, to the
#cluster that will induce the maximum reduction in within-cluster sum of squares:
lis <- optraShapes(array3D,n,meanshapes,numClust,ic1,ic2,nc,an1,an2,ncp,d,itran,live,indx)
meanshapes <- lis[[1]] ; ic1 <- lis[[2]] ; ic2 <- lis[[3]] ; nc <- lis[[4]] ; an1 <- lis[[5]] ; an2 <- lis[[6]] ; ncp <- lis[[7]]
d <- lis[[8]] ; itran <- lis[[9]] ; live <- lis[[10]] ; indx <- lis[[11]]
#Each point is tested in turn to see if it should be re-allocated to the cluster to which it is most likely
#to be transferred, IC2(I), from its present cluster, IC1(I). Loop through the data until no further change
#is to take place:
lis1 <- qtranShapes(array3D,n,meanshapes,ic1,ic2,nc,an1,an2,ncp,d,itran,indx)
meanshapes <- lis1[[1]] ; ic1 <- lis1[[2]] ; ic2 <- lis1[[3]] ; nc <- lis1[[4]] ; an1 <- lis1[[5]] ; an2 <- lis1[[6]] ; ncp <- lis1[[7]]
d <- lis1[[8]] ; itran <- lis1[[9]] ; indx <- lis1[[10]] ; icoun <- lis1[[11]]
mean_sh[[step]] <- meanshapes
#NCP has to be set to 0 before entering OPTRA:
for( l in 1 : numClust ){
ncp[l] = 0
}
#Compute the within-cluster sum of squares for each cluster:
wss <- vector("list", numClust)
for(num_cl in 1 : numClust){
wss[[num_cl]] <- 0
array3D_cl <- array(0, dim = c(n, 3, table(ic1)[num_cl])) #table(ic1)[num_cl] is the number of observations that
#belong to each cluster.
array3D_cl <- array3D[,,ic1 == num_cl]
distances <- c()
for(num_mujs_cl in 1:table(ic1)[num_cl]){
distances[num_mujs_cl] <- riemdist(array3D_cl[,,num_mujs_cl], meanshapes[,,num_cl])^2
}
wss[[num_cl]] <- sum(distances) / n
}
#Total within-cluster sum of squares:
wss_step[[step]] <- sum(unlist(wss))
list_ic1_step[[step]] <- ic1
if(verbose){
paste(cat("Clustering of the Nstep", step, ":\n"))
print(table(list_ic1_step[[step]]))
}
if(verbose){
if(iter <= 10){
paste(cat("Objective function of the Nstep", step))
print(wss_step[[step]])
}
}
if(step > 1){
aux <- wss_step[[step]]
aux1 <- wss_step[[step-1]]
if( ((aux1 - aux) / aux1) < stopCr ){
break
}
}
}#The algSteps loop ends here.
#Calculus of the objective function (the total within-cluster sum of squares):
wss1 <- vector("list", numClust)
for(num_cl in 1 : numClust){
wss1[[num_cl]] <- 0
array3D_cl1 <- array(0, dim = c(n, 3, table(ic1)[num_cl]))
array3D_cl1 <- array3D[,,ic1 == num_cl]
distances1 <- c()
for(num_mujs_cl in 1:table(ic1)[num_cl]){
distances1[num_mujs_cl] <- riemdist(array3D_cl1[,,num_mujs_cl], meanshapes[,,num_cl])^2
}
wss1[[num_cl]] <- sum(distances1) / n
}
#Total within-cluster sum of squares:
wss_step1 <- 0
wss_step1 <- sum(unlist(wss1))
#Change the optimal value and the optimal centers (copt) if a reduction in the objective function happens:
if(wss_step1 > min(unlist(wss_step))){
if(min(unlist(wss_step)) < vopt){
vopt <- min(unlist(wss_step))
if(verbose){
#Improvements in the objective functions are printed:
cat("optimal")
print(vopt)
}
optim_wss <- which.min(unlist(wss_step))
copt <- mean_sh[[optim_wss]] #optimal centers.
ic1_opt <- list_ic1_step[[optim_wss]]
}
}else if(wss_step1 < vopt){
vopt <- wss_step1
if(verbose){
#Improvements in the objective functions are printed:
cat("optimal")
print(vopt)
}
optim_wss <- which.min(unlist(wss_step))
copt <- mean_sh[[optim_wss]] #optimal centers.
ic1_opt <- list_ic1_step[[optim_wss]]
}
time_iter[[iter]] <- Sys.time()
if(iter == 1){
comp_time[1] <- difftime(time_iter[[iter]], time_ini, units = "mins")
if(verbose){
cat("Computational time of this iteration: \n")
print(time_iter[[iter]] - time_ini)
}
}else{
comp_time[iter] <- difftime(time_iter[[iter]], time_iter[[iter-1]], units = "mins")
if(verbose){
cat("Computational time of this iteration: \n")
print(time_iter[[iter]] - time_iter[[iter - 1]])
}
}
if(verbose){
cat("Optimal clustering of this iteration: \n")
}
optim_wss <- which.min(unlist(wss_step))
list_ic1[[iter]] <- list_ic1_step[[optim_wss]]
if(verbose){
print(table(list_ic1[[iter]]))
}
if(simul){
#Allocation rate:
as1 <- table(list_ic1[[iter]][1:(n/2)])
as2 <- table(list_ic1[[iter]][seq(n/2 + 1,n)])
if( max(as1) != n/2 & max(as2) != n/2 ){
suma <- min(as1) + min(as2)
all_rate <- 1 - suma / n
}else if( (max(as1) == n/2 & max(as2) != n/2) || (max(as1) != n/2 & max(as2) == n/2) ){
minim <- min(min(as1),min(as2))
all_rate <- 1 - minim / n
}else if( max(as1) == n/2 & max(as2) == n/2 ){
all_rate <- 1
}
vect_all_rate[iter] <- all_rate
if(verbose){
cat("Optimal allocation rate in this iteration:")
print(all_rate)
}
}
}#The niter loop ends here.
if(simul){
dimnames(copt) <- NULL
return(list(ic1=ic1_opt,cases=copt,vopt=vopt,compTime=comp_time,
AllRate=vect_all_rate))
}else{
return(list(ic1=ic1_opt,cases=copt,vopt=vopt))
}
}
| /scratch/gouwar.j/cran-all/cranData/Anthropometry/R/HartiganShapes.R |
LloydShapes <- function(array3D,numClust,algSteps=10,niter=10,stopCr=0.0001,simul,verbose){
#,computCost
time_iter <- list() #List to save the real time in which each iteration ends.
comp_time <- c() #List to save the computational time of each iteration.
list_asig_step <- list() #List to save the clustering obtained in each Nstep.
list_asig <- list() #List to save the optimal clustering obtained among all the Nstep of each iteration.
vect_all_rate <- c() #List to save the optimal allocation rate of each iteration.
initials <- list() #List to save the random initial values used by this Lloyd algorithm. Thus,
#the Hartigan algorithm can be executed with these same values.
ll <- 1 : numClust
dist <- matrix(0, dim(array3D)[3], numClust)
if(verbose){
print(Sys.time())
}
time_ini <- Sys.time()
#Initialize the objective function by a large enough value:
vopt <- 1e+08
#Random restarts:
for(iter in 1 : niter){
obj <- list() #List to save the objective function (without dividing between n) of each Nstep.
meanshapes <- 0 ; meanshapes_aux <- 0 ; asig <- 0
mean_sh <- list()
n <- dim(array3D)[3]
if(verbose){
cat("New iteration:")
print(iter)
cat("Optimal value with which this iteration starts:")
print(vopt)
}
#Randomly choose the numClust initial centers:
initials[[iter]] <- sample(1:n, numClust, replace = FALSE)
if(verbose){
cat("Initial values of this iteration:")
print(initials[[iter]])
}
meanshapes <- array3D[, , initials[[iter]]]
meanshapes_aux <- array3D[, , initials[[iter]]]
#if(computCost){
#time_ini_dist <- Sys.time()
#dist_aux = riemdist(array3D[,,1], y = meanshapes[,,1])
#time_end_dist <- Sys.time()
#cat("Computational cost of the Procrustes distance:")
#print(time_end_dist - time_ini_dist)
#}
for(step in 1 : algSteps){
for(h in 1 : numClust){
dist[,h] = apply(array3D[,,1:n], 3, riemdist, y = meanshapes[,,h])
}
asig = max.col(-dist)
#if(computCost){
#time_ini_mean <- Sys.time()
#meanshapes_aux[,,1] = procGPA(array3D[, , asig == 1], distances = TRUE, pcaoutput = TRUE)$mshape
#time_end_mean <- Sys.time()
#cat("Computational cost of the Procrustes mean:")
#print(time_end_mean - time_ini_mean)
#}
for(h in 1 : numClust){
if(table(asig == h)[2] == 1){
meanshapes[,,h] = array3D[, , asig == h]
mean_sh[[step]] <- meanshapes
}else{
meanshapes[,,h] = procGPA(array3D[, , asig == h], distances = TRUE, pcaoutput = TRUE)$mshape
mean_sh[[step]] <- meanshapes
}
}
obj[[step]] <- c(0)
for (l in 1 : n){
obj[[step]] <- obj[[step]] + dist[l,asig[l]]^2
}
obj[[step]] <- obj[[step]] / n
list_asig_step[[step]] <- asig
if(verbose){
paste(cat("Clustering of the Nstep", step, ":\n"))
print(table(list_asig_step[[step]]))
}
if(verbose){
if(iter <= 10){
paste(cat("Objective function of the Nstep", step))
print(obj[[step]])
}
}
if(step > 1){
aux <- obj[[step]]
aux1 <- obj[[step-1]]
if( ((aux1 - aux) / aux1) < stopCr ){
break
}
}
}#The algSteps loop ends here.
#Calculus of the objective function (the total within-cluster sum of squares):
obj1 <- 0
for(l in 1 : n){
obj1 <- obj1 + dist[l,asig[l]]^2
}
obj1 <- obj1 / n
#Change the optimal value and the optimal centers (copt) if a reduction in the objective function happens:
if( obj1 > min(unlist(obj)) ){
if( min(unlist(obj)) < vopt ){
vopt <- min(unlist(obj))
if(verbose){
#Improvements in the objective functions are printed:
cat("optimal")
print(vopt)
}
optim_obj <- which.min(unlist(obj))
copt <- mean_sh[[optim_obj]] #optimal centers.
asig_opt <- list_asig_step[[optim_obj]] #to save the optimal clustering.
}
}else if(obj1 < vopt){
vopt <- obj1
if(verbose){
#Improvements in the objective functions are printed:
cat("optimal")
print(vopt)
}
optim_obj <- which.min(unlist(obj))
copt <- mean_sh[[optim_obj]] #optimal centers.
asig_opt <- list_asig_step[[optim_obj]]
}
time_iter[[iter]] <- Sys.time()
if(iter == 1){
comp_time[1] <- difftime(time_iter[[iter]], time_ini, units = "mins")
if(verbose){
cat("Computational time of this iteration: \n")
print(time_iter[[iter]] - time_ini)
}
}else{
comp_time[iter] <- difftime(time_iter[[iter]], time_iter[[iter-1]], units = "mins")
if(verbose){
cat("Computational time of this iteration: \n")
print(time_iter[[iter]] - time_iter[[iter - 1]])
}
}
if(verbose){
#In order to display the optimal clustering related to the optimal objective function, we have to find
#the step in which the optimal was obtained. This is provided by (which.min(unlist(obj))).
cat("Optimal clustering of this iteration: \n")
}
optim_obj <- which.min(unlist(obj))
list_asig[[iter]] <- list_asig_step[[optim_obj]]
if(verbose){
print(table(list_asig[[iter]]))
}
if(simul){
#Allocation rate:
as1 <- table(list_asig[[iter]][1:(n/2)])
as2 <- table(list_asig[[iter]][seq(n/2 + 1,n)])
if( max(as1) != n/2 & max(as2) != n/2 ){
suma <- min(as1) + min(as2)
all_rate <- 1 - suma / n
}else if( (max(as1) == n/2 & max(as2) != n/2) || (max(as1) != n/2 & max(as2) == n/2) ){
minim <- min(min(as1),min(as2))
all_rate <- 1 - minim / n
}else if( max(as1) == n/2 & max(as2) == n/2 ){
all_rate <- 1
}
vect_all_rate[iter] <- all_rate
if(verbose){
cat("Optimal allocation rate in this iteration:")
print(all_rate)
}
}
}#The niter loop ends here.
if(simul){
dimnames(copt) <- NULL
return(list(asig=asig_opt,cases=copt,vopt=vopt,compTime=comp_time,
AllRate=vect_all_rate,initials=initials))
}else{
return(list(asig=asig_opt,cases=copt,vopt=vopt,initials=initials))
}
}
| /scratch/gouwar.j/cran-all/cranData/Anthropometry/R/LloydShapes.R |
TDDclust <- function(data,numClust,lambda,Th,niter,T0,simAnn,alpha,data1,verbose=TRUE){
B <- 5 ;
Km <- 2 ;
norm <- 0 ;
acc <- c()
improv_kl <- list() ;
indiv_trimmed <- list() ;
NN1_aux <- list()
if(verbose){
cat("Step (1): \n Initial partition with PAM:")
}
pcc <- pam(data,numClust)
if(verbose){
print(table(pcc$clustering))
cat("Medoids:")
print(rownames(data[pcc$id.med,]))
}
Y <- pcc$med
prs <- 0
move <- 0
if(verbose){
cat("Step (2): \n")
}
NN <- NNDDVQA1(data,pcc,lambda,norm)
NNa <- NN
NNold_old <- NN
Cost <- NNa$Kmata
if(verbose){
cat("Objective function value for this partition:")
print(mean(Cost))
}
Ls <- sum(NN$Kmata)
qa <- 0
if(niter > 1){#niter - number of iterations, default 5
if(verbose){
cat("Iteration for niter")
print(niter)
}
kl <- 0
while(kl < (niter-1)){
if(verbose){
cat("Iteration for kl:")
print(kl)
}
kl <- kl + 1
if(niter<=5 & kl>=(niter-5)){
if(verbose){
cat("\n")
cat("Steps (3),(4),(5),(6) (for niter <= 5 | kl>=(niter-5)) NNDDVQE: \n")
}
NN <- NNDDVQE(data,Y,0,lambda,NN,Km,Th,alpha,kl,NNold_old,verbose)
if(sum(table(NN$NN[1,])) == dim(data)[1]){
if(verbose){
cat("The optimal partition is provided by PAM")
}
Y <- as.integer(rownames(Y))
return(list(NN=NN$NN,cases=Y,Cost=NN$Cost,discarded="None",klBest=0))
}
}
if(niter>5 & kl!=0){
if(verbose){
cat("\n")
cat("Steps (3),(4),(5),(6) (for niter > 5 & kl!=0) NNDDVQEstart: \n")
}
NN <- NNDDVQEstart(data,Y,T0,lambda,NN,Km,Th,alpha,kl,NNold_old,verbose)
if(sum(table(NN$NN[1,])) == dim(data)[1]){
if(verbose){
cat("The optimal partition is provided by PAM")
}
Y <- as.integer(rownames(Y))
return(list(NN=NN$NN,cases=Y,Cost=NN$Cost,discarded="None",klBest=0))
}
T0 <-NN$T0 * simAnn
Th <- Th * simAnn
}
aux1 <- list() ; Kmata_aux <- list() ; pcc_aux1 <- list()
aux_mat <- list() ; DDi_aux <- list() ; DD_aux <- list()
NNold_old <- NN
if(verbose){
cat("Optimal partition when finishing the kl iteration: \n")
print(table(NNold_old$Nuvec))
cat("\n")
}
NN1_aux[[kl]] <- NN
NNN <- NN
if(length(NN$Nuvec) < dim(data1)[1]){
indiv_trimmed[[kl]] <- NN$trimmed
improv_kl[[kl]] <- NN$improv
for(trimm in NN$trimmed){
for(nu in 1:numClust){
aux1[[nu]] <- append(NN$Nuvec,nu,trimm-1)
pcc_aux1[[nu]] <- pamsil(data1,aux1[[nu]],numClust)
DDi_aux[[nu]] <- matrix(0,dim(data1)[1],numClust)
Nvec <- rep(1,dim(data1)[1])
for(kz in (1:numClust)){
for(ky in (1:dim(data1)[1])){
Xmatr <- data1[aux1[[nu]] == kz,]
Nvecr <- Nvec[aux1[[nu]] == kz]
DDi_aux[[nu]][ky,kz] <- DDfcnadj(Xmatr,Nvecr,data1[ky,])
}
}
num <- sample((1:numClust)[-nu],1)
aux2 <- append(NN$NN[2,],num,trimm-1)
aux3 <- append(NN$NN[3,],(1:numClust)[-c(nu,num)],trimm-1)
aux_mat[[nu]] <- as.matrix(rbind(aux1[[nu]],aux2,aux3))
DD_aux[[nu]] <- DDcalc2(DDi_aux[[nu]],aux_mat[[nu]],numClust,Km,norm)
Kmata_aux[[nu]] <- pcc_aux1[[nu]]$sil * (1 - lambda) + lambda * DD_aux[[nu]]$DD
acc[nu] <- Kmata_aux[[nu]][trimm,]
nu_max <- which.max(acc)
}
NN$Kmata <- Kmata_aux[[nu_max]]
NN$pcc <- pcc_aux1[[nu_max]]
NN$NN <- aux_mat[[nu_max]]
NN$DDi <- DDi_aux[[nu_max]]
NN$DD <- DD_aux[[nu_max]]
NN$Nuvec <- aux1[[nu_max]]
}
}
move <- c(move,NN$ct)
prs <- c(prs,NN$prs)
Ls <- c(Ls,sum(NN$Kmata))
NN$Cost <- NN1_aux[[kl]]$Cost
if(verbose){
cat("Cost of the partition when finishing the kl iteration: \n")
print(NN$Cost)
cat("\n")
}
data=data1
Nvec <- rep(1,dim(data)[1])
for (kk in (1:numClust)){
Xmatr <- data[NN$Nuvec==kk,]
Nvecr <- Nvec[NN$Nuvec==kk]
yr <- initW2(Xmatr,Nvecr) # Initial y for Weiszfeld algorithm
W <- Weisziteradj(Xmatr,Nvecr,yr,B)
Y[kk,] <- W$y
}
rm(W,Nvecr,Xmatr,yr)
if(verbose){
cat("Deepest women: (modified Weiszfeld algorithm)\n")
print(rownames(Y))
cat("\n")
}
}
ma <- max(unlist(improv_kl),na.rm=TRUE)
indiv_trimmed1 <- indiv_trimmed[[ma+1]]
NN1_aux1 <- NN1_aux[[ma+1]]
data <- data[-NN1_aux1$trimmed,]
Nvec <- rep(1,dim(data)[1])
ntt <- matrix(0,numClust,1)
if(NN1_aux1$ct==0 & T0==0){
qa <- qa + 1
if(qa > 5){
kl <- niter + 1
}
}
if(NN1_aux1$ct==0 & T0>0 & kl>=5){
T0 <- 0
}
if(NN1_aux1$stopnow==1 & T0<.001){
kl <- niter + 1
}
for(kk in (1:numClust)){
Xmatr <- data[NN1_aux1$Nuvec==kk,]
Nvecr <- Nvec[NN1_aux1$Nuvec==kk]
yr <- initW2(Xmatr,Nvecr)
W <- Weisziteradj(Xmatr,Nvecr,yr,B)
Y[kk,] <- W$y
}
NNa <- NN1_aux1
DD <- NNa$DD$DD
Cost <- NNa$Cost
NN <- NNa$NN
}
Y <- as.integer(rownames(Y))
return(list(NN=NN,cases=Y,DD=DD,Cost=Cost,discarded=indiv_trimmed1,klBest=ma))
}
| /scratch/gouwar.j/cran-all/cranData/Anthropometry/R/TDDclust.R |
anthrCases <- function(resMethod, nsizes){
UseMethod("anthrCases")
}
anthrCases.default <- function(resMethod, nsizes){
cases <- resMethod$cases
#class(cases) <- "anthrCases"
structure(cases, class = c("anthrCases", "list"))
return(cases)
}
anthrCases.trimowa <- function(resMethod, nsizes){
if (nsizes == 1){
cases <- c()
cases <- resMethod$cases
}else{
cases <- list()
for (i in 1 : nsizes){
cases[[i]] <- resMethod[[i]]$cases
}
}
#class(cases) <- "anthrCases"
structure(cases, class = c("anthrCases", "list"))
return(cases)
}
anthrCases.hipamAnthropom <- function(resMethod, nsizes){
cases <- list()
for (i in 1 : nsizes){
aux <- table(resMethod[[i]]$clustering)
aux <- as.numeric(aux)
auxBig <- which(aux > 2)
#length(unique(rownames(resMethod[[i]]$cases))) must match with length(attr(table(resMethod[[i]]$clustering), "names"))
cases[[i]] <- rownames(unique(resMethod[[i]]$cases))[auxBig]
}
#class(cases) <- "anthrCases"
structure(cases, class = c("anthrCases", "list"))
return(cases)
}
| /scratch/gouwar.j/cran-all/cranData/Anthropometry/R/anthrCases.R |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.