## R function to read .sfs file readBjoint <- function(file=NULL,nind=10,nsites=10){ ff <- gzfile(file,"rb") m<-matrix(readBin(ff,double(),(2*nind+1)*nsites),ncol=(2*nind+1),byrow=TRUE) close(ff) return(m) } ##normalizer norm <- function(x) x/sum(x) ##we have 2 function to estimate the SFS from the .sfs file ##bfgs using the unconstraint 2*nChr+1 (doesn't work well, in the ccode we are shifting to dim-1 space) ##em algorithm ##pick random start in constraint space pick <- function(nchr) return(0.01/(1+0:(nchr-1))) ## go from full to dim-1 space swap <- function(x){ tmp <- 1+sum(x) return(c(1/tmp,x/tmp)) } ## unconstraind bfgs myOptim <- function(ind=12,theLikes=dat){ like2 <- function(x){ if(length(x)!=ncol(theLikes)) stop("Dimension mismatch") res <- exp(theLikes) %*% x res <- sum(log(res)) return(-res) } neg_fn <- function(x,calcLike=T){ return(like2(swap(x))) } ti <- system.time(opt <- optim(pick(ind*2),neg_fn,method="L-BFGS-B",lower=rep(0.0000001,ind*2),upper=rep(10,ind*2))) return(list(time=ti,opt=opt,ml=swap(opt$par))) } ## em old myOptim2 <- function(start,nIter=10,tol=0.1,theLikes){ ind<-ncol(theLikes) if(missing(start)) start<-norm(rep(1,ind)) x<-start like<--Inf for(i in 1:nIter){ post<-t(t(exp(theLikes))*x) norma<-rowSums(post) likeNew<-sum(log(norma)) pp<-post/norma x<-colSums(pp)/nrow(theLikes) if((likeNew-like)