code
stringlengths 1
13.8M
|
---|
plotfplsr <- function(x, xlab1 = x$ypred$xname, ylab1 = "Basis function", xlab2 = "Time", ylab2 = "Coefficient", mean.lab = "Mean", interaction.title = "Interaction")
{
scores = x$T
order = dim(scores)[2]
pred = x$P
resp = x$Q
par(mfrow = c(3, (order + 1)))
plot(x$y1, x$meanX$y, type = "l", xlab = xlab1, ylab = mean.lab, main = "Predictor")
for(i in 1:order)
{
plot(x$y1, pred[,i], type = "l", xlab = xlab1, ylab = paste(ylab1, i, sep = " "))
}
plot(x$y1, x$meanY$y, type = "l", xlab = xlab1, ylab = mean.lab, main = "Response")
for(i in 1:order)
{
plot(x$y1, resp[,i], type = "l", xlab = xlab1, ylab = paste(ylab1, i, sep = " "))
}
plot(x$y1, resp[,1], type = "n", xlab = "", ylab = "", xaxt = "n", yaxt = "n", bty = "n")
for(i in 1:order)
{
plot(x$x1, scores[,i], type = "l", xlab = xlab2, ylab = paste(ylab2, i, sep = " "))
}
} |
SurveyQ<-function(data, Longitude=NULL, Latitude=NULL, cell=60, Areas=NULL,
variables = c("Slope","Completeness","Ratio"), completeness=c(50,90),
slope=c(0.02,0.3), ratio=c(3,15), shape=NULL, shapenames=NULL, admAreas=TRUE,
Area="World", minLon, maxLon, minLat, maxLat, main=NULL, PLOTP=NULL, PLOTB=NULL,
POINTS=NULL, XLAB=NULL, YLAB=NULL, XLIM=NULL, YLIM=NULL,
palette=c("blue","green","red"), COLOR=c("red","green","blue"), colm="black", labels=TRUE,
sizelabels=1, LEGENDP=NULL, LEGENDM=NULL, file="Polar coordinates.csv",
na="NA", dec=",", row.names=FALSE, jpg=FALSE, filejpg="Map.jpg"){
if(missing(Latitude) & missing(Longitude) & missing(Areas)){
stop("It is necessary to specify the arguments Latitude and Longitude, if the file 'Estimators' was obtained with the function KnowB, or the argument Areas
if the file 'Estimators' was obtained with the function KnowBPolygon")
}
"%ni%" <- Negate( "%in%" )
TE<- function(datosL=datosL, dim=dim, COLOR=NULL,sizelabels=1){
h<-0
for(z in 1:dim[1]){
if(h==6) h<-1 else h<-h+1
c<-plotrix::draw.circle(datosL[z,2], datosL[z,3], rangeX*1/100, nv = 6, border = "transparent", col = "transparent")
datosL[z,2]<-c$x[h]
datosL[z,3]<-c$y[h]
text(x = datosL[z,2] , y = datosL[z,3] , labels = datosL[z,1] , col = COLOR, cex=sizelabels)
}
}
Bubbles<-function(data, varY, varX, varColor=NULL, palette= "cm.colors",
digitsC=0, ncolor=10, transparency=1, PLOTB=NULL, POINTS=NULL, COLEGEND=NULL, XLAB=NULL,
YLAB=NULL, XLIM=NULL, YLIM=NULL, LEGENDS=NULL){
datos<-data
datosT<-data.frame(subset(datos, select=varX), subset(datos, select=varY))
if(!is.null(varColor)){
datosT<-data.frame(datosT, subset(datos, select=varColor))
}
datos<-na.exclude(datosT)
par(font.lab=2, mar=c(4.5,4.5,3,5),cex.lab=1.5)
if(!is.null(XLAB)) xlab<-XLAB else xlab<-varX
if(!is.null(YLAB)) ylab<-YLAB else ylab<-varY
if(!is.null(XLIM)){
minsx<-XLIM[1]
maxsx<-XLIM[2]
}
else{
minsx<-min(datos[,varX])
maxsx<-max(datos[,varX])
XLIM<-c(minsx,maxsx)
}
if(!is.null(YLIM)){
minsy<-YLIM[1]
maxsy<-YLIM[2]
}
else{
minsy<-min(datos[,varY])
maxsy<-max(datos[,varY])
YLIM<-c(minsy,maxsy)
}
if(!is.null(varColor)){
maxC<-max(datos[,varColor])
minC<-min(datos[,varColor])
matriz<-matrix(c(maxC,minC, 1, ncolor),nrow = 2 , ncol = 2)
regC<-lm(matriz[,2]~matriz[,1])
}
if(palette== "heat.colors"){
rampa<-heat.colors(n=ncolor, alpha=transparency)
}
if(palette== "terrain.colors"){
rampa<-terrain.colors(n=ncolor, alpha=transparency)
}
if(palette== "gray.colors"){
rampa<-gray.colors(n=ncolor, alpha=transparency)
}
if(palette== "topo.colors"){
rampa<-topo.colors(n=ncolor, alpha=transparency)
}
if(palette== "cm.colors"){
rampa<-cm.colors(n=ncolor, alpha=transparency)
}
if(palette!= "heat.colors" & palette!= "topo.colors" & palette!= "gray.colors" & palette!= "cm.colors" & palette!= "terrain.colors"){
ramp <- colorRamp(palette)
rampa<-rgb(ramp(seq(0, 1, length = ncolor)), maxColorValue = 255)
}
cex<-1
if(!is.null(varColor)){
color<-round(regC$coefficients[1]+regC$coefficients[2]*datos[1,varColor])
pch<-16
}
else{
rampa<-"black"
pch<-1
color<-1
}
if(!is.null(PLOTB)){
scatterplotexe<-paste("plot(","x=datos[1,varX],", "y=datos[1,varY],", toString(x=PLOTB), ")")
eval(parse(text=scatterplotexe))
}
else{
scatterplotexe<-paste("plot(","x=datos[1,varX],", "y=datos[1,varY],","cex=cex,", "col=rampa[color],",
"xlim=XLIM,","ylim=YLIM,", "xlab=xlab,","ylab=ylab,", "pch=pch", ")")
eval(parse(text=scatterplotexe))
}
dimS<-dim(datos)
for(zz in 2:dimS[1]){
cex=1
if(!is.null(varColor)){
color<-round(regC$coefficients[1]+regC$coefficients[2]*datos[zz,varColor])
}
if(!is.null(POINTS)){
scatterplotexe<-paste("points(","x=datos[zz,varX],", "y=datos[zz,varY],", toString(x=POINTS), ")")
eval(parse(text=scatterplotexe))
}
else{
scatterplotexe<-paste("points(","x=datos[zz,varX],", "y=datos[zz,varY],","cex=cex,", "col=rampa[color],",
"xlim=XLIM,","ylim=YLIM,", "pch=pch", ")")
eval(parse(text=scatterplotexe))
}
}
ranX<-abs(XLIM[2]-XLIM[1])
ranY<-abs(YLIM[2]-YLIM[1])
x1<-XLIM[2]+ranX*8/100
x2<-XLIM[2]+ranX*12/100
if(palette== "heat.colors"){
rampa<-heat.colors(n=100, alpha=transparency)
}
if(palette== "terrain.colors"){
rampa<-terrain.colors(n=100, alpha=transparency)
}
if(palette== "gray.colors"){
rampa<-gray.colors(n=100, alpha=transparency)
}
if(palette== "topo.colors"){
rampa<-topo.colors(n=100, alpha=transparency)
}
if(palette== "cm.colors"){
rampa<-cm.colors(n=100, alpha=transparency)
}
if(palette!= "heat.colors" & palette!= "topo.colors" & palette!= "gray.colors" & palette!= "cm.colors" & palette!= "terrain.colors"){
ramp <- colorRamp(palette)
rampa<-rgb(ramp(seq(0, 1, length = 100)), maxColorValue = 255)
}
if(!is.null(varColor)){
int<-as.numeric(format((maxC-minC)/ncolor, digits=digitsC))
maxC<-as.numeric(format(maxC,digits=digitsC))
minC<-as.numeric(format(minC,digits=digitsC))
color<-minC
valor<-minC
for(zz in 1:ncolor){
valor<-valor+int
color<-append(color,valor)
}
y1<-YLIM[1]-YLIM[1]*3/100
y2<-YLIM[2]+YLIM[2]*1.5/100
if(!is.null(COLEGEND)){
scatterplotexe<-paste("plotrix::color.legend(","xl=x1,", "yb=y1,", "xr=x2,", "yt=y2,", toString(x=COLEGEND), ")")
eval(parse(text=scatterplotexe))
}
else{
scatterplotexe<-paste("plotrix::color.legend(","xl=x1,", "yb=y1,", "xr=x2,", "yt=y2,",
"legend=color,","gradient='y',", "align='rb',", "cex=1,", "rect.col=rev(rampa)", ")")
eval(parse(text=scatterplotexe))
}
}
}
adareas<-function(data, Area="World", minLon, maxLon, minLat, maxLat,
colbg="
exclude = NULL, colexc = NULL, colfexc="black", colscale=rev(heat.colors(100)),
legend.pos="y", breaks=10, xl=0, xr=0, yb=0, yt=0, asp, lab = NULL, xlab = "Longitude",
ylab = "Latitude", main=NULL, cex.main = 1.2, cex.lab = 1, cex.axis = 0.9, cex.legend=0.9,
family = "sans", font.main = 2, font.lab = 1, font.axis = 1, lwdP=0.6, lwdC=0.1,
trans=c(1,1), log=c(0,0), ndigits=0, ini=NULL, end=NULL, jpg=FALSE, filejpg="Map.jpg"){
if(class(data)=="data.frame"){
data<-as.matrix(data)
}
if(class(data)=="RasterLayer"){
if(round(raster::xmin(data))==-180 & round(raster::ymin(data))==-90 & round(raster::xmax(data))==180 & round(raster::ymax(data))==90){
m1<-raster::as.matrix(data)
dimm<-dim(m1)
long<-seq(from=(-180+360/dimm[2]), to = 180 , by = 360/dimm[2])
m1<-rbind(long,m1)
lat<-seq(from=(90-180/dimm[1]), to = -90 , by = -180/dimm[1])
lat<-c(0,lat)
data<-cbind(lat,m1, deparse.level=0)
}
else{
reso<-raster::res(data)
r1<-raster::raster(xmn=-180, xmx=180, ymn=-90, ymx=90, resolution=reso)
data<-raster::resample(data,r1)
m1<-raster::as.matrix(data)
dimm<-dim(m1)
long<-seq(from=(raster::xmin(data)+(raster::xmax(data)-raster::xmin(data))/dimm[2]), to = raster::xmax(data) , by = (raster::xmax(data)-raster::xmin(data))/dimm[2])
m1<-rbind(long,m1)
lat<-seq(from=(raster::ymax(data)+(raster::ymin(data)-raster::ymax(data))/dimm[1]), to = raster::ymin(data) , by = (raster::ymin(data)-raster::ymax(data))/dimm[1])
lat<-c(0,lat)
data<-cbind(lat,m1, deparse.level=0)
}
}
if(exists("adworld")==FALSE){
adworld<-1
stop("It is necessary to load data(adworld)")
}
if(Area!="World" & exists("adworld1")==FALSE){
stop("It is necessary to use RWizard and replace data(adworld) by @_Build_AdWorld_, for using administative areas")
}
if(Area!="World" & exists("adworld2")==FALSE){
stop("It is necessary to use RWizard and replace data(adworld) by @_Build_AdWorld_, for using administative areas")
}
if(exists("adworld1")==FALSE){
adworld1<-1
}
if(exists("adworld2")==FALSE){
adworld2<-1
}
varscale<-data
if(!is.null(end)){
datos1<-replace(data, data>=end, end)
datos1[1,]<-varscale[1,]
datos1[,1]<-varscale[,1]
varscale<-datos1
rm(datos1)
codlegend<-paste(">",end)
}
d<-length(Area)
AA<-Area[1]
if (AA=="World"){
datos1<-adworld[2:5,]
}
else{
datos1<-rbind(adworld1,adworld2)
}
datos1<-na.exclude(datos1)
if (AA=="World"){
if (missing(minLat)) minLat<--90 else minLat<-minLat
if (missing(maxLat)) maxLat<-90 else maxLat<-maxLat
if (missing(minLon)) minLon<--180 else minLon<-minLon
if (missing(maxLon)) maxLon<-180 else maxLon<-maxLon
}
else{
if (missing(maxLon)){
if(max(datos1$Lon)<0) maxLon<-(max(datos1$Lon)-max(datos1$Lon)*inc) else maxLon<-(max(datos1$Lon)+max(datos1$Lon)*inc)
}
else {
maxLon<-maxLon
}
if (missing(minLon)){
if(min(datos1$Lon)<0) minLon<-(min(datos1$Lon)+min(datos1$Lon)*inc) else minLon<-(min(datos1$Lon)-min(datos1$Lon)*inc)
}
else {
minLon<-minLon
}
if (missing(maxLat)){
if(max(datos1$Lat)<0) maxLat<-(max(datos1$Lat)-max(datos1$Lat)*inc) else maxLat<-(max(datos1$Lat)+max(datos1$Lat)*inc)
}
else {
maxLat<-maxLat
}
if (missing(minLat)){
if(min(datos1$Lat)<0) minLat<-(min(datos1$Lat)+min(datos1$Lat)*inc) else minLat<-(min(datos1$Lat)-min(datos1$Lat)*inc)
}
else {
minLat<-minLat
}
}
Lon<-as.numeric(varscale[1,-1])
varLon<-as.numeric(varscale[1,-1])
a<-length(Lon)
for (i in 1:a){
if(i==1) varLon[i]<-((-180+Lon[i])/2) else varLon[i]<-((Lon[i-1]+Lon[i])/2)
}
Lat<-as.numeric(varscale[-1,1])
varLat<-as.numeric(varscale[-1,1])
a<-length(Lat)
for (i in 1:a){
if(i==1) varLat[i]<-((90+Lat[i])/2) else varLat[i]<-((Lat[i-1]+Lat[i])/2)
}
varLat<-(-varLat)
firstrow<-varscale[1,]
ajuste<-varscale[varscale[,1]<=maxLat&varscale[,1]>=minLat,]
ifelse(firstrow==ajuste[1,], yes=ajuste<-ajuste, no=ajuste<-rbind(firstrow,ajuste))
ajuste<-ajuste[,ajuste[1,]<=maxLon&ajuste[1,]>=minLon]
ajuste<-ajuste[-1,-1]
ajuste<-as.matrix(ajuste)
if(trans[1]==0){
ajuste<-replace(ajuste, ajuste==-9999,NA)
ajuste<-ajuste/trans[2]
ajuste<-replace(ajuste, is.na(ajuste),-9999)
}
else{
ajuste<-replace(ajuste, ajuste==-9999,NA)
ajuste<-ajuste*trans[2]
ajuste<-replace(ajuste, is.na(ajuste),-9999)
}
if(log[1]==0){
ajuste<-ajuste
}
else{
ajuste<-replace(ajuste, ajuste==-9999,NA)
ajuste<-log(ajuste+log[2])
ajuste<-replace(ajuste, is.na(ajuste),-9999)
}
ajuste<- ajuste[nrow(ajuste):1,]
varscale<-varscale[-1,-1]
varscale<-as.matrix(varscale)
if(trans[1]==0){
varscale<-replace(varscale, varscale==-9999,NA)
varscale<-varscale/trans[2]
varscale<-replace(varscale, is.na(varscale),-9999)
}
else{
varscale<-replace(varscale, varscale==-9999,NA)
varscale<-varscale*trans[2]
varscale<-replace(varscale, is.na(varscale),-9999)
}
if(log[1]==0){
varscale<-varscale
}
else{
varscale<-replace(varscale, varscale==-9999,NA)
varscale<-log(varscale+log[2])
varscale<-replace(varscale, is.na(varscale),-9999)
}
varscale<- varscale[nrow(varscale):1,]
varscale<-t(varscale)
if (maxLon>=180) maxLon<-180 else maxLon<-maxLon
if (minLon<=-180) minLon<--180 else minLon<-minLon
if (maxLat>=90) maxLat<-90 else maxLat<-maxLat
if (minLat<=-90) minLat<--90 else minLat<-minLat
if (missing(Area)) Area="World" else Area=Area
if (missing(colbg)) colbg="transparent" else colbg=colbg
if (missing(colcon)) colcon="transparent" else colcon=colcon
if (missing(colf)) colf="black" else colf=colf
if (missing(colfexc)) colfexc="black" else colfexc=colfexc
if (missing(varscale)) varscale=NULL else varscale=varscale
color<-rev(heat.colors(100))
if (missing(colscale)) colscale<-color else colscale=colscale
legend.max=max(ajuste)
if(legend.max<=10){
legend.min=(if(min(ajuste[!ajuste==-9999])==0) min(ajuste[!ajuste==-9999])+(max(ajuste)/(length(colscale)-1)) else min(ajuste[!ajuste==-9999]))
}
else{
legend.min=min(ajuste[!ajuste==-9999])
}
if(legend.min<0) legend.min<-legend.min+legend.min*0.1/100 else legend.min<-legend.min-legend.min*0.1/100
if(legend.max<0) legend.max<-legend.max-legend.max*0.1/100 else legend.max<-legend.max+legend.max*0.1/100
Lati<-(maxLat+minLat)/2
if (pro==TRUE) aspe=(1/cos(Lati*pi/180)) else aspe=1
if (missing(asp)) asp=aspe else asp=asp
x<-0
y<-0
rm(datos1)
if(jpg==TRUE) jpeg(filename = filejpg, width = 8000, height = 4000, units = "px", pointsize = 14, quality = 1200, bg = "white", res = 600) else hhjhk<-1
squishplot <- function(xlim,ylim,asp=1){
if(length(xlim) < 2) stop('xlim must be a vector of length 2')
if(length(ylim) < 2) stop('ylim must be a vector of length 2')
tmp <- par(c('plt','pin','xaxs','yaxs'))
if( tmp$xaxs == 'i' ){
xlim <- range(xlim)
} else {
tmp.r <- diff(range(xlim))
xlim <- range(xlim) + c(-1,1)*0.04*tmp.r
}
if( tmp$yaxs == 'i' ){
ylim <- range(ylim)
} else {
tmp.r <- diff(range(ylim))
ylim <- range(ylim) + c(-1,1)*0.04*tmp.r
}
tmp2 <- (ylim[2]-ylim[1])/(xlim[2]-xlim[1])
tmp.y <- tmp$pin[1] * tmp2 * asp
if(tmp.y < tmp$pin[2]){
par(pin=c(tmp$pin[1], tmp.y))
par(plt=c(tmp$plt[1:2], par('plt')[3:4]))
} else {
tmp.x <- tmp$pin[2]/tmp2/asp
par(pin=c(tmp.x, tmp$pin[2]))
par(plt=c(par('plt')[1:2], tmp$plt[3:4]))
}
return(invisible(tmp['plt']))
}
if (missing(ini)){
if(min(varscale[!varscale==-9999])==0) ini<-0 else ini<-legend.min
}
else{
ini<-ini
}
par(lwd=lwdP,fg="black",family=family)
tmp<-squishplot(xlim=c(minLon,maxLon), ylim=c(minLat,maxLat), asp=aspe)
if(!is.null(end)){
legend.max<-end
}
legend.freq1=abs((legend.max-ini)/(length(colscale)-1))
legend.freq=abs((legend.max-ini)/(breaks-1))
if(missing(legend.pos)){
if((maxLon-minLon)>260 & (maxLon-minLon)/(maxLat-minLat)>2.265) legend.pos="x" else legend.pos=legend.pos
}
if (legend.pos=="y") par(oma=c(0,0,0,1)) else par(oma=c(0,0,2,0))
image(varLon, varLat,varscale,xlim=c(minLon,maxLon),ylim=c(minLat,maxLat), axes=F, xaxs="i", yaxs="i", xlab="",ylab="", col=colscale, breaks=c(ini,seq(ini,legend.max,by=legend.freq1)))
par(new=T,lwd=lwdP)
plot(x,y,xlim=c(minLon,maxLon),ylim=c(minLat,maxLat),xlab=xlab, main="", axes=TRUE,
ylab = ylab, cex.lab=cex.lab, type="n",bty="l",
font.lab=font.lab, font.axis=font.axis,lab=lab,yaxs="i",xaxs="i",yaxt="n",xaxt="n")
mtext(text=main,side=3, line=0.3, cex=cex.main, font=font.main)
axis(side=1,xlim=c(minLon,maxLon),lwd=lwdP, cex.axis=cex.axis)
axis(side=2,ylim=c(minLat,maxLat),lwd=lwdP, cex.axis=cex.axis)
if (colbg=="
if (legend.pos=="y"){
if (xl==0){
x1<-(maxLon-minLon)*(-0.00106495)+0.747382095+maxLon
x2<-(maxLon-minLon)*(-0.003194851)+2.060146284+maxLon
}
else{
x1<-xl
x2<-xr
}
if(legend.max<=10){
sequ<-(seq(ini,legend.max,by=legend.freq))
sequ<-round(sequ, digits=ndigits)
}
else{
if(ini==0){
legend.freq=abs((legend.max-ini)/(breaks-1))
sequ<-(seq(ini,legend.max,by=legend.freq))
sequ<-round(sequ, digits=ndigits)
}
else{
sequ<-(seq(ini,legend.max,by=legend.freq))
sequ<-round(sequ, digits=ndigits)
}
}
if(!is.null(end)){
lensequ<-length(sequ)
sequ[lensequ]<-codlegend
}
plotrix::color.legend(xl=x1, yb=minLat, xr= x2,
yt=maxLat, sequ, gradient="y", align="rb", cex=cex.legend, rect.col=colscale[-1])
}
else{
if (yb==0){
if(!is.null(main)){
y1<-maxLat+(maxLat-minLat)*(0.101851852)-1.333333333
y2<-maxLat+(maxLat-minLat)*(0.157407407)-1.333333333
}
else{
y1<-maxLat+(maxLat-minLat)*(0.027777778)
y2<-maxLat+(maxLat-minLat)*(0.083333333)
}
}
else{
y1<-yb
y2<-yt
}
if(legend.max<=10){
sequ<-(seq(ini,legend.max,by=legend.freq))
sequ<-round(sequ, digits=ndigits)
}
else{
sequ<-(seq(ini,legend.max,by=legend.freq))
sequ<-round(sequ, digits=ndigits)
}
if(!is.null(end)){
lensequ<-length(sequ)
sequ[lensequ]<-codlegend
}
plotrix::color.legend(xl=minLon, yb=y1, xr=maxLon, yt=y2, sequ,
gradient="x", align="lt", cex=cex.legend, rect.col=colscale[-1])
}
if (AA=="World") {
polygon(adworld$Lon,adworld$Lat,col=colcon, border=colf)
if(!is.null(exclude)){
polygon(adworld2$Lon,adworld2$Lat,col=colexc, border=colfexc)
}
}
else {
polygon(adworld1$Lon,adworld1$Lat,col=colcon, border=colf)
polygon(adworld2$Lon,adworld2$Lat,col=colexc, border=colfexc)
}
par(tmp)
if(jpg==TRUE) dev.off() else hhjk<-1
}
n<-length(variables)
var<-variables
if(!is.null(Areas)){
datosT<-data.frame(subset(data, select=Areas), subset(data, select=var))
datos<-na.exclude(datosT)
selection<-datos[,-1]
}
if(!is.null(Longitude)){
datosT<-data.frame(subset(data, select=Longitude), subset(data, select=Latitude), subset(data, select=var))
datos<-na.exclude(datosT)
selection<-datos[,c(-1,-2)]
}
var<-colnames(selection)
datosE<-selection
for (z in 1:3){
matrixE<-matrix(c(-1, 1, min(selection[,z],na.rm=TRUE),max(selection[,z],na.rm=TRUE)), nrow = 2 , ncol = 2)
reg<-lm(matrixE[,1]~matrixE[,2])
datosC<-reg$coefficients[1]+selection[,z]*reg$coefficients[2]
datosE<-cbind(datosE,datosC)
}
datosE<-datosE[,-c(1:3)]
colnames(datosE)<-colnames(selection)
selection<-datosE
angle<-pi/3
datosX<-selection[,1]
h<-0
for (z in 1:3){
h<-h+1
datosC<- ifelse(selection[,z] <=0, abs(selection[,z])*cos(angle*h+pi), abs(selection[,z])*cos(angle*h))
datosX<-data.frame(datosX,datosC)
}
datosX<-datosX[,-1]
XX<-apply(datosX,1,sum)
RX<-(max(XX)-min(XX))
datosY<-selection[,1]
h<-0
for (z in 1:3){
h<-h+1
datosC<- ifelse(selection[,z] <=0, abs(selection[,z])*sin(angle*h+pi), abs(selection[,z])*sin(angle*h))
datosY<-cbind(datosY,datosC)
}
datosY<-datosY[,-1]
YY<-apply(datosY,1,sum)
RY<-(max(YY)-min(YY))
datosF<-data.frame(XX,YY)
if(!is.null(Areas)){
datosF<-data.frame(datos[,1], datosF)
colnames(datosF)<-c("Area", "X","Y")
}
if(!is.null(Longitude)){
datosF<-data.frame(datos[,c(1,2)], datosF)
colnames(datosF)<-c("Longitude","Latitude", "X","Y")
}
if(dec=="."){
write.csv(x=datosF,file = file, fileEncoding = "", row.names=row.names,na=na)
}
else{
write.csv2(x = datosF,file = file, fileEncoding = "", row.names=row.names,na=na)
}
if(dec=="."){
datosF<-read.csv(file=file ,header=TRUE)
}
else{
datosF<-read.csv2(file=file ,header=TRUE)
}
if(!is.null(XLAB)) xlab<-XLAB else xlab<-"POLAR COORDINATES X"
if(!is.null(YLAB)){
ylab<-YLAB
}
else{
ylab<-"POLAR COORDINATES Y"
}
if(is.null(Longitude)){
xx=datosF[,2]
yy=datosF[,3]
}
else{
xx=datosF[,3]
yy=datosF[,4]
}
if(is.null(XLIM)){
XLIM<-c(min(xx),max(xx))
}
if(is.null(YLIM)){
YLIM<-c(min(yy),max(yy))
}
rangeX<-abs(XLIM[2]-XLIM[1])
dev.new()
par(font.lab=2, mar=c(5,5,3,2),cex.lab=1.5)
if(!is.null(PLOTP)){
plotexe<-paste("plot(","x=xx,", "y=yy,", toString(x=PLOTP), ")")
eval(parse(text=plotexe))
}
else{
plotexe<-paste("plot(","x=xx,", "y=yy,", "xlab=xlab,","ylab=ylab,","xlim=XLIM,","ylim=YLIM,", "cex=0",")")
eval(parse(text=plotexe))
}
if(!is.null(Areas)){
datosT<-cbind(datosF,datos)
datosL<-subset(datosT,datosT[,variables[1]]<slope[1] & datosT[,variables[2]]>completeness[2] & datosT[,variables[3]]>ratio[2])
datosL<-datosL[,c(1,2,3)]
datosL<-datosL[order(datosL[,2]),]
dim<-dim(datosL)
eti<-rep("Good",dim[1])
datosL<-cbind(datosL,eti)
names(datosL)<-c("Area","X","Y","Survey")
ldata<-datosL
if(dim[1]>0){
if(labels==FALSE | !is.null(Longitude)) {
points(x = datosL[,2] , y = datosL[,3], pch=16, col=COLOR[1],cex=sizelabels)
}
else{
TE(datosL=datosL, dim=dim, COLOR=COLOR[1],sizelabels=sizelabels)
}
}
datosL<-subset(datosT,datosT[,variables[1]]>slope[2] & datosT[,variables[2]]<completeness[1] & datosT[,variables[3]]<ratio[1])
datosL<-datosL[,c(1,2,3)]
datosL<-datosL[order(datosL[,2]),]
dim<-dim(datosL)
eti<-rep("Poor",dim[1])
datosP<-cbind(datosL,eti)
names(datosP)<-c("Area","X","Y","Survey")
if(dim[1]>0){
if(labels==FALSE | !is.null(Longitude)) {
points(x = datosP[,2] , y = datosP[,3], pch=16, col=COLOR[3],cex=sizelabels)
}
else{
TE(datosL=datosP, dim=dim, COLOR=COLOR[3],sizelabels=sizelabels)
}
}
datosL<-subset(datosT,(datosT[,variables[1]]>=slope[1] & datosT[,variables[1]]<=slope[2]) | (datosT[,variables[2]]>=completeness[1] & datosT[,variables[2]]<=completeness[2] ) | (datosT[,variables[3]]>=ratio[1] & datosT[,variables[3]]<=ratio[2]))
datosL<-datosL[,c(1,2,3)]
datosL<-datosL[order(datosL[,2]),]
dim<-dim(datosL)
eti<-rep("Fair",dim[1])
datosFF<-cbind(datosL,eti)
names(datosFF)<-c("Area","X","Y","Survey")
if(dim[1]>0){
if(labels==FALSE | !is.null(Longitude)) {
points(x = datosFF[,2] , y = datosFF[,3], pch=16, col=COLOR[2],cex=sizelabels)
}
else{
TE(datosL=datosFF, dim=dim, COLOR=COLOR[2],sizelabels=sizelabels)
}
}
ldata<-rbind(ldata,datosFF, datosP)
if(!is.null(LEGENDP)){
legendexe<-paste("legend(",toString(x=LEGENDP), ")")
eval(parse(text=legendexe))
}
else{
legendexe<-paste("legend(","x='bottomleft',", "legend=c('High quality survey','Fair quality survey','Poor quality survey'),", "pch=15,", "col=COLOR,", "bty='n'", ")")
eval(parse(text=legendexe))
}
dim<-dim(ldata)
valor<-rep(1, dim[1])
ldata<-cbind(ldata,valor)
names(ldata)<-c("Area","X","Y","Survey","Survey2")
ldata$Survey2[which(ldata$Survey=="Good")]<-3
ldata$Survey2[which(ldata$Survey=="Fair")]<-2
ldata$Survey2[which(ldata$Survey=="Poor")]<-1
ldata[,"Survey2"]<-as.numeric(ldata[,"Survey"])
catcol<-as.character(unique(ldata[,4]))
if(any(catcol=="Good")==TRUE) vp1="" else vp1=COLOR[1]
if(any(catcol=="Fair")==TRUE) vp2="" else vp2=COLOR[2]
if(any(catcol=="Poor")==TRUE) vp3="" else vp3=COLOR[3]
COLORF<-COLOR[ COLOR %ni% c(vp1,vp2,vp3)]
datosT<-ldata
if(!is.null(shape)){
if(class(shape)=="list"){
data<-shape[[1]]
lsh<-length(shape)
if(lsh>1){
ss<-seq(2,lsh)
hh<-as.character(shape[ss])
shapeT<-eval(parse(text=paste("subset(data,",noquote(shapenames), " %in% hh)", sep="")))
}
}
else{
shapeT<-shape
if(class(shapeT)=="character"){
shapeT<-eval(parse(text=paste(".GlobalEnv$", shapeT, sep="")))
}
}
AreasT<-data.frame(eval(parse(text=paste("shapeT$",noquote(shapenames),sep=""))))
names(AreasT)<-"Area"
datosT<-merge(AreasT,ldata, sort=FALSE)
}
if(jpg==TRUE){
jpeg(filename = filejpg, width = 8000, height = 4000, units = "px", pointsize = 14, quality = 1200, bg = "white", res = 600)
}
else{
dev.new()
}
KnowBR::MapPolygon(data=datosT, polygonname="Area", Area=Area, var="Survey2", colscale=COLORF, jpg=FALSE, xl=500, xr=500, shape=shape, shapenames=shapenames,
minLon=minLon, maxLon=maxLon,minLat=minLat, maxLat=maxLat, admAreas=admAreas, main=main, colm=colm)
if(!is.null(LEGENDM)){
legendexe<-paste("legend(",toString(x=LEGENDM), ")")
eval(parse(text=legendexe))
}
else{
legendexe<-paste("legend(","x='bottomleft',", "legend=c('High quality survey','Fair quality survey','Poor quality survey'),", "pch=15,", "col=COLOR,", "bty='n'", ")")
eval(parse(text=legendexe))
}
if(jpg==TRUE){
dev.off()
}
ldata<-ldata[,-5]
}
if(!is.null(Longitude)){
datosT<-cbind(datosF,datos)
datosL<-subset(datosT,datosT[,variables[1]]<slope[1] & datosT[,variables[2]]>completeness[2] & datosT[,variables[3]]>ratio[2])
datosL<-datosL[,c(1,2,3,4)]
dim<-dim(datosL)
eti<-rep("Good",dim[1])
datosL<-cbind(datosL,eti)
names(datosL)<-c("Longitude","Latitude","X","Y","Survey")
ldata<-datosL
points(x = datosL[,3] , y = datosL[,4], pch=16, col=COLOR[1],cex=sizelabels)
datosL<-subset(datosT,datosT[,variables[1]]>slope[2] & datosT[,variables[2]]<completeness[1] & datosT[,variables[3]]<ratio[1])
datosL<-datosL[,c(1,2,3,4)]
dim<-dim(datosL)
eti<-rep("Poor",dim[1])
datosP<-cbind(datosL,eti)
names(datosP)<-c("Longitude","Latitude","X","Y","Survey")
points(x = datosP[,3] , y = datosP[,4], pch=16, col=COLOR[3],cex=sizelabels)
datosL<-subset(datosT,(datosT[,variables[1]]>=slope[1] & datosT[,variables[1]]<=slope[2]) | (datosT[,variables[2]]>=completeness[1] & datosT[,variables[2]]<=completeness[2] ) | (datosT[,variables[3]]>=ratio[1] & datosT[,variables[3]]<=ratio[2]))
datosL<-datosL[,c(1,2,3,4)]
dim<-dim(datosL)
eti<-rep("Fair",dim[1])
datosFF<-cbind(datosL,eti)
names(datosFF)<-c("Longitude","Latitude","X","Y","Survey")
ldata<-rbind(ldata,datosFF, datosP)
points(x = datosFF[,3] , y = datosFF[,4], pch=16, col=COLOR[2],cex=sizelabels)
if(!is.null(LEGENDP)){
legendexe<-paste("legend(",toString(x=LEGENDP), ")")
eval(parse(text=legendexe))
}
else{
legendexe<-paste("legend(","x='bottomleft',", "legend=c('High quality survey','Fair quality survey','Poor quality survey'),", "pch=15,", "col=COLOR,", "bty='n'", ")")
eval(parse(text=legendexe))
}
dim<-dim(ldata)
valor<-rep(1, dim[1])
ldata<-cbind(ldata,valor)
names(ldata)<-c("Longitude","Latitude","X","Y","Survey","Survey2")
ldata$Survey2[which(ldata$Survey=="Good")]<-3
ldata$Survey2[which(ldata$Survey=="Fair")]<-2
ldata$Survey2[which(ldata$Survey=="Poor")]<-1
ldata[,"Survey2"]<-as.numeric(ldata[,"Survey"])
catcol<-as.character(unique(ldata[,5]))
if(any(catcol=="Good")==TRUE) vp1="" else vp1=COLOR[1]
if(any(catcol=="Fair")==TRUE) vp2="" else vp2=COLOR[2]
if(any(catcol=="Poor")==TRUE) vp3="" else vp3=COLOR[3]
COLORF<-COLOR[ COLOR %ni% c(vp1,vp2,vp3)]
if(jpg==TRUE){
jpeg(filename = filejpg, width = 8000, height = 4000, units = "px", pointsize = 14, quality = 1200, bg = "white", res = 600)
}
else{
dev.new()
}
f<-cell/60
ff<-180/f
cc<-ff*2
matriz<-matrix(-9999, nrow=ff, ncol=cc)
col<-c(0,seq(from=-180+f, to=180, by=f))
row<-c(seq(from=-90, to=90-f, by=f))
names(matriz)<-NULL
matriz<-cbind(row,matriz)
matriz<-rbind(col,matriz)
colnames(matriz)<-NULL
le<-length(ldata[,1])
x<-matriz[1,-1]
y<-matriz[-1,1]
for(z in 1:le){
vx<-findInterval(ldata[z,1], x)
vy<-findInterval(ldata[z,2], y)
matriz[vy+1,vx+2]<-ldata[z,6]
}
matriz <- matriz[ nrow(matriz):2, ]
matriz<-rbind(col,matriz)
adareas(data=matriz, Area=Area, jpg=FALSE, minLon=minLon, maxLon=maxLon,minLat=minLat, maxLat=maxLat, colcon="transparent",
xl=500, xr=500, colscale=append("transparent",COLORF))
rm(matriz)
if(!is.null(LEGENDM)){
legendexe<-paste("legend(",toString(x=LEGENDM), ")")
eval(parse(text=legendexe))
}
else{
legendexe<-paste("legend(","x='bottomleft',", "legend=c('High quality survey','Fair quality survey','Poor quality survey'),", "pch=15,", "col=COLOR,", "bty='n'", ")")
eval(parse(text=legendexe))
}
if(jpg==TRUE){
dev.off()
}
ldata<-ldata[,-6]
}
if(dec=="."){
write.csv(x=ldata,file = file, fileEncoding = "", row.names=row.names,na=na)
}
else{
write.csv2(x = ldata,file = file, fileEncoding = "", row.names=row.names,na=na)
}
dev.new()
LRatio<-log(data[,variables[3]])
data<-cbind(data,LRatio)
Bubbles(data = data , varY = variables[2] , varX = "LRatio" , XLAB="log Ratio",varColor = variables[1] , digitsC = 1, PLOTB=PLOTB, palette=palette,
POINTS=POINTS)
} |
ml_psineglog <-
function(param,dat,mlmax=1e+15,fixed=FALSE,...)
{
loglik = mlmax
lik = NULL
x = dat[,1]
y = dat[,2]
if(fixed) param[1]=0
lik = try(dbgpd(x, y, model = "psineglog",mar1 = param[1:3],mar2 = param[4:6],dep = param[7],asy=param[8], p=param[9]),
silent=TRUE)
if(!is.null(lik)){
if(is.null(attr(lik,"class"))){
loglik = -sum(log(lik))
if(min(1+param[3]*(x-param[1])/param[2])<0) loglik=mlmax
if(min(1+param[6]*(y-param[4])/param[5])<0) loglik=mlmax
}}
loglik
} |
insertvec<-function(v, ind, val)
{
sects = list()
isects = length(ind)+1
JIND = c(0, ind, length(v))
for(k in 1:isects)
{
J1 = JIND[k]+1
J2 = JIND[k+1]
sects[[k]] = v[J1:J2]
}
w = sects[[1]]
for(k in 2:(isects))
{
w = c(w, val, sects[[k]])
}
return(w)
} |
replaceLibrary <- function(lib, value) {
envs <- c(
as.environment("package:base"),
.BaseNamespaceEnv
)
for (env in envs) {
do.call("unlockBinding", list(lib, env))
assign(lib, value, envir = env)
do.call("lockBinding", list(lib, env))
}
}
hideLibrary <- function(lib) {
replaceLibrary(lib, character())
}
restoreLibrary <- function(lib) {
cachedLib <- if (lib == ".Library")
getenv("R_PACKRAT_SYSTEM_LIBRARY")
else if (lib == ".Library.site")
getenv("R_PACKRAT_SITE_LIBRARY")
if (is.null(cachedLib)) {
warning("packrat did not properly save the library state; cannot restore")
return(invisible(NULL))
}
replaceLibrary(lib, cachedLib)
}
hideSiteLibraries <- function() {
hideLibrary(".Library.site")
}
restoreSiteLibraries <- function() {
restoreLibrary(".Library.site")
} |
test_that("delete_MCAR() calls check_delete_args_MCAR()", {
expect_error(
delete_MCAR(df_XY_100, 0.1, p_overall = "A"),
"p_overall must be logical of length 1"
)
})
test_that("delete_MCAR() creates MCAR", {
set.seed(123454)
df_MCAR <- delete_MCAR(df_XY_100, 0.1)
expect_equal(count_NA(df_MCAR), c(X = 10, Y = 10))
df_MCAR <- delete_MCAR(df_XY_100, 1)
expect_equal(count_NA(df_MCAR), c(X = 100, Y = 100))
df_MCAR <- delete_MCAR(df_XY_100, 0)
expect_equal(count_NA(df_MCAR), c(X = 0, Y = 0))
df_MCAR <- delete_MCAR(df_XY_100, 0.2, cols_mis = 2)
expect_equal(count_NA(df_MCAR), c(X = 0, Y = 20))
df_MCAR <- delete_MCAR(df_XY_100, 0.2, cols_mis = "X")
expect_equal(count_NA(df_MCAR), c(X = 20, Y = 0))
df_MCAR <- delete_MCAR(df_XY_100, p = 0.5, stochastic = TRUE)
expect_true(anyNA(df_MCAR))
df_MCAR <- delete_MCAR(df_XY_100, p = 1, stochastic = TRUE)
expect_equal(count_NA(df_MCAR), c(X = 100, Y = 100))
df_MCAR <- delete_MCAR(df_XY_100, p = 0, stochastic = TRUE)
expect_equal(count_NA(df_MCAR), c(X = 0, Y = 0))
N <- 1000
res <- 0
for (i in seq_len(N)) {
res <- res + sum(count_NA(delete_MCAR(df_XY_100, p = 0.2, stochastic = TRUE)))
}
expect_true(
res / prod(dim(df_XY_100), N) < 0.3 &
res / prod(dim(df_XY_100), N) > 0.1
)
df_MCAR <- delete_MCAR(df_XY_100, p = 0.2, p_overall = TRUE)
expect_equal(sum(count_NA(df_MCAR)), 40)
df_MCAR <- delete_MCAR(df_XY_100, p = 1, p_overall = TRUE)
expect_equal(sum(count_NA(df_MCAR)), 200)
df_MCAR <- delete_MCAR(df_XY_100, p = 0, p_overall = TRUE)
expect_equal(sum(count_NA(df_MCAR)), 0)
})
test_that("delete_MCAR() works with matrices", {
set.seed(123454)
ds_m_MCAR <- delete_MCAR(matrix_100_2, p = 0.4)
expect_equal(count_NA(ds_m_MCAR), c(40, 40))
ds_m_MCAR <- delete_MCAR(matrix_100_2, p = 0.4, cols_mis = 2)
expect_equal(count_NA(ds_m_MCAR), c(0, 40))
ds_m_MCAR <- delete_MCAR(matrix_20_10, p = c(0.1, 0.2, 0.3), cols_mis = 2:4)
expect_equal(count_NA(ds_m_MCAR), c(0, 2, 4, 6, rep(0, 6)))
})
test_that("delete_MCAR() works with tibbles", {
set.seed(123454)
tbl_MCAR <- delete_MCAR(tbl_XY_100, p = 0.4)
expect_equal(count_NA(tbl_MCAR), c(X = 40, Y = 40))
tbl_MCAR <- delete_MCAR(tbl_XY_100, p = 0.4, cols_mis = 2)
expect_equal(count_NA(tbl_MCAR), c(X = 0, Y = 40))
tbl_MCAR <- delete_MCAR(tbl_XYZ_100, p = c(0.1, 0.2, 0.3), cols_mis = 1:3)
expect_equal(count_NA(tbl_MCAR), c(X = 10, Y = 20, Z = 30))
}) |
plot.Intervals_full <- function(
x, y = NULL,
axes = TRUE,
xlab = "", ylab = "",
xlim = NULL, ylim = NULL,
col = "black", lwd = 1,
cex = 1,
use_points = TRUE,
use_names = TRUE,
names_cex = 1,
...
)
{
if ( any( is.na( x ) ) ) x <- x[ !is.na(x), ]
if ( is.null(xlim) )
xlim <- range( [email protected] )
else
x <- x[ x[,2] >= xlim[1] & x[,1] <= xlim[2], ]
if ( is.null(y) )
y <- .Call( "_plot_overlap", [email protected], closed(x), is( x, "Intervals_full" ) )
if ( is.null(ylim) )
ylim <- c( 0, max( y ) )
plot(
0, 0,
type = "n",
xlim = xlim, ylim = ylim,
axes = FALSE,
xlab = xlab, ylab = ylab,
...
)
segments(
pmax( x[,1], par("usr")[1] ), y,
pmin( x[,2], par("usr")[2] ), y,
col = col,
lwd = lwd
)
if ( use_points ) {
adjust <- ( x[,1] == x[,2] ) & !closed(x)[,1]
closed(x)[ adjust, 2 ] <- FALSE
points(
[email protected], rep( y, 2 ),
pch = 21, cex = cex,
col = col, bg = ifelse( closed(x), col, "white" )
)
}
if ( use_names && !is.null( rownames(x) ) ) {
mids <- ( x[,1] + x[,2] ) / 2
text(
mids, y,
rownames( x ),
pos = 3, offset = .5,
cex = names_cex,
xpd = NA
)
}
if ( axes )
axis( 1 )
}
plot.Intervals <- function( x, y = NULL, ... ) {
plot( as( x, "Intervals_full" ), y, ... )
}
setMethod( "plot", c( "Intervals", "missing" ), function( x, y, ... ) plot.Intervals( x, ... ) )
setMethod( "plot", c( "Intervals", "ANY" ), function( x, y, ... ) plot.Intervals( x, y, ... ) )
setMethod( "plot", c( "Intervals_full", "missing" ), function( x, y, ... ) plot.Intervals_full( x, ... ) )
setMethod( "plot", c( "Intervals_full", "ANY" ), function( x, y, ... ) plot.Intervals_full( x, y, ... ) ) |
IBM_greenLight_criterion <- function(estim.obj, sample1, sample2, comp.dist = NULL, comp.param = NULL, min_size = NULL, alpha = 0.05)
{
if (is.null(min_size)) {
min_sample_size <- min(length(sample1), length(sample2))
} else {
min_sample_size <- min_size
}
length.support <- length(estim.obj[["integ.supp"]])
z <- estim.obj[["integ.supp"]][round(floor(length.support/2))]
varCov_estim <- IBM_estimVarCov_gaussVect(x = z, y = z, estim.obj = estim.obj, fixed.p1 = estim.obj[["p.X.fixed"]], known.p = NULL,
sample1 = sample1, sample2 = sample2, min_size = min_size,
comp.dist = comp.dist, comp.param = comp.param)
if (length(estim.obj[["prop.estim"]]) == 2) {
inf_bound.p1 <- estim.obj[["prop.estim"]][1] - sqrt(varCov_estim[1,1]/min_sample_size) * stats::qnorm(p=(1-alpha/4), mean=0, sd=1)
sup_bound.p1 <- estim.obj[["prop.estim"]][1] + sqrt(varCov_estim[1,1]/min_sample_size) * stats::qnorm(p=(1-alpha/4), mean=0, sd=1)
conf_interval.p1 <- c(inf_bound.p1, sup_bound.p1)
inf_bound.p2 <- estim.obj[["prop.estim"]][2] - sqrt(varCov_estim[2,2]/min_sample_size) * stats::qnorm(p=(1-alpha/4), mean=0, sd=1)
sup_bound.p2 <- estim.obj[["prop.estim"]][2] + sqrt(varCov_estim[2,2]/min_sample_size) * stats::qnorm(p=(1-alpha/4), mean=0, sd=1)
conf_interval.p2 <- c(inf_bound.p2, sup_bound.p2)
green_light_crit <- max(conf_interval.p1[1],conf_interval.p2[1]) <= 1
} else {
inf_bound.p <- estim.obj[["prop.estim"]][1] - sqrt(varCov_estim[1,1]/min_sample_size) * stats::qnorm(p=(1-alpha/4), mean=0, sd=1)
sup_bound.p <- estim.obj[["prop.estim"]][1] + sqrt(varCov_estim[1,1]/min_sample_size) * stats::qnorm(p=(1-alpha/4), mean=0, sd=1)
conf_interval.p2 <- c(inf_bound.p, sup_bound.p)
conf_interval.p1 <- NULL
green_light_crit <- conf_interval.p2[1] <= 1
}
return( list(green_light = green_light_crit, conf_interval_p1 = conf_interval.p1, conf_interval_p2 = conf_interval.p2) )
} |
source("ESEUR_config.r")
library("plyr")
pal_col=rainbow(2)
full_price=function(df)
{
df=df[order(df$Date), ]
lines(df$Date, df$Full.Price, col=df$col[1])
}
cc_cpp=read.csv(paste0(ESEUR_dir, "economics/upgrade-languages.csv.xz"), as.is=TRUE)
cc_cpp$OS=(cc_cpp$OS == "Windows")
cc_cpp=subset(cc_cpp, !is.na(Full.Price))
cc_cpp$Date=as.Date(paste0("01-", cc_cpp$Date), format="%d-%b-%y")
cc=subset(cc_cpp, Cpp == 0)
no_Watcom=subset(cc_cpp, Firm != "Watcom")
Vis_Cpp=subset(cc_cpp, Product == "Visual C++")
Bor_Cpp=subset(cc_cpp, Product == "C++")
plot(jitter(no_Watcom$Full.Price), no_Watcom$OS, col=point_col, yaxt="n",
xlab="Full retail price ($)", ylab="OS")
axis(side=2, at=c(0, 1), label=c("MS-DOS", "Windows"))
sl=glm(OS ~ Full.Price, data=no_Watcom)
lines(no_Watcom$Full.Price, predict(sl), col=pal_col[1])
b_sl=glm(OS ~ Full.Price, data=no_Watcom, family=binomial)
x_vals=min(no_Watcom$Full.Price):max(no_Watcom$Full.Price)
lines(x_vals, predict(b_sl, newdata=data.frame(Full.Price=x_vals), type="response"), col=pal_col[2])
prod_b_sl=glm(OS ~ Full.Price:Cpp, data=no_Watcom, family=binomial)
summary(prod_b_sl)
lines(x_vals, predict(prod_b_sl, newdata=data.frame(Full.Price=x_vals, Cpp=1), type="response"), col=pal_col[2]) |
invent15 <- stats::ts(c(143, 152, 161, 139, 137, 174, 142, 141, 162, 180,
164, 171, 206, 193, 207, 218, 229, 225, 204, 227, 223, 242, 239,
266),f=12,s=1) |
elman <- function(x, ...) UseMethod("elman")
elman.default <- function(x, y, size=c(5), maxit=100,
initFunc="JE_Weights", initFuncParams=c(1.0, -1.0, 0.3, 1.0, 0.5),
learnFunc="JE_BP", learnFuncParams=c(0.2),
updateFunc="JE_Order", updateFuncParams=c(0.0),
shufflePatterns=FALSE, linOut=TRUE, outContext=FALSE, inputsTest=NULL, targetsTest=NULL, ...) {
x <- as.matrix(x)
y <- as.matrix(y)
checkInput(x,y)
nInputs <- dim(x)[2L]
nOutputs <- dim(y)[2L]
snns <- rsnnsObjectFactory(subclass=c("elman"), nInputs=nInputs, maxit=maxit,
initFunc=initFunc, initFuncParams=initFuncParams,
learnFunc=learnFunc, learnFuncParams=learnFuncParams,
updateFunc=updateFunc,
updateFuncParams=updateFuncParams,
shufflePatterns=shufflePatterns, computeIterativeError=TRUE)
snns$archParams <- list(size=size)
snns$snnsObject$setUnitDefaults(1,0,1,0,1,"Act_Logistic","Out_Identity")
snns$snnsObject$elman_createNet(c(nInputs, size, nOutputs), seq(1,1,length=(length(size)+2)), outContext)
if(linOut) {
outputActFunc <- "Act_Identity"
} else {
outputActFunc <- "Act_Logistic"
}
snns$snnsObject$setTTypeUnitsActFunc("UNIT_INPUT", "Act_Identity")
snns$snnsObject$setTTypeUnitsActFunc("UNIT_OUTPUT", outputActFunc)
snns <- train(snns, inputsTrain=x, targetsTrain=y, inputsTest=inputsTest, targetsTest=targetsTest)
snns
} |
rga.environment <- new.env()
assign("kMaxPages", 100, envir = rga.environment)
assign("kMaxDefaultRows", 10000, envir = rga.environment) |
expected <- eval(parse(text="c(TRUE, TRUE, TRUE)"));
test(id=0, code={
argv <- eval(parse(text="list(c(\"a\", \"b\", \"c\"))"));
do.call(`nzchar`, argv);
}, o=expected); |
context("Calc longterm mean")
test_that("`calc_longterm_mean()` works", {
skip_on_cran()
skip_on_ci()
data <- calc_longterm_mean(station_number = "08NM116", start_year = 1980)
expect_true(is.data.frame(data) &
ncol(data) == 2 &
all(c("LTMAD") %in% colnames(data)))
})
test_that("outputs data for two stations", {
skip_on_cran()
skip_on_ci()
data <- calc_longterm_mean(station_number = c("08NM116","08HB048"), start_year = 1980)
expect_true(length(unique(data$STATION_NUMBER)) &
ncol(data) == 2 &
all(c("LTMAD") %in% colnames(data)))
})
test_that("percent mad is added correctly", {
skip_on_cran()
skip_on_ci()
data <- calc_longterm_mean(station_number = "08NM116", start_year = 1980,
percent_MAD = 25)
expect_true(length(unique(data$STATION_NUMBER)) &
ncol(data) == 3 &
all(c("LTMAD","25%MAD") %in% colnames(data)))
})
test_that("it is calculated correctly", {
skip_on_cran()
skip_on_ci()
flow_data <- add_date_variables(station_number = "08NM116")
flow_data <- dplyr::filter(flow_data, WaterYear %in% 1980:1990)
longterm_mean <- round(mean(flow_data$Value),5)
ptile_mean <- round(longterm_mean * .25,5)
data <- calc_longterm_mean(data = flow_data,
start_year = 1980, end_year = 1990,
percent_MAD = 25)
expect_true(longterm_mean == round(data[[1,2]],5))
expect_true(ptile_mean == round(data[[1,3]],5))
}) |
get_collection <- function(x, ...) {
UseMethod("get_collection", x)
}
get_collection.default <- function(x, ...) {
get_network_by_id(x, force_collection = TRUE, ...)
}
get_collection.mgSearchDatasets <- function(x, ...) {
net_ids <- unique(unlist(purrr::map(x$networks, "id")))
get_collection.default(net_ids, ...)
}
get_collection.mgSearchNetworks <- function(x, ...) {
get_collection.default(x$id, ...)
}
get_collection.mgSearchReferences <- function(x, ...) {
net_ids <- unique(unlist(purrr::map(x$networks, "id")))
get_collection.default(net_ids, ...)
}
get_collection.mgSearchNodes <- function(x, ...) {
net_ids <- unique(x$network_id)
get_collection.default(net_ids, ...)
}
get_collection.mgSearchTaxonomy <- function(x, ...) {
net_ids <- unique(x$network_id)
get_collection.default(net_ids, ...)
}
get_collection.mgSearchInteractions <- function(x, ...) {
net_ids <- unique(x$network_id)
get_collection.default(net_ids, ...)
} |
morphomapAlignment<-function(mesh,set,side=c("left","right"),
param1=4,iter1=2000,iter2=2000,
iter3=2000,from1=180,to1=360,
from2=-5,to2=5,from3=-5,to3=5,
tol=0.5){
morphomapAlOne<-function(mesh,set,iter,from,to,tol){
pos_1<-aro.clo.points(t(mesh$vb)[,-4],set)$position
set_1<-t(mesh$vb)[pos_1, -4]
sur_2 <- morphomapAlMesh(rbind(set_1[2, ], colMeans(set_1[c(1,2),]),set_1[1,]),mesh)
set_2<-t(sur_2$mesh$vb)[pos_1, -4]
sur_2<-sur_2$mesh
degrees <- seq(from, to, length = iter)
radians <- (degrees * pi)/180
for (i in 1:length(degrees)) {
set_3_t <- rotaxis3d(set_2, set_2[2,], c(500,0,0), radians[i])
diff_align_z <- (set_3_t[3, 3] - set_3_t[4, 3])
if (abs(diff_align_z) <= tol) {
break
}
}
sur_3 <- rotaxis3d(sur_2, set_2[2,], c(500,0,0), radians[i])
set_3 <- t(sur_3$vb)[pos_1, -4]
if((set_3[3,3] >0 & set_3[4,3] >0)==TRUE){
sur_3 <- rotaxis3d(sur_3, set_3[2,], c(500,0,0), (180 * pi)/180)
set_3 <- t(sur_3$vb)[pos_1, -4]
}
dist_1_z<-colMeans(set_3[c(3,4),])[3]
dist_2_z<-set_3[1,3]
sur_4<-sur_3
sur_4$vb[3,]<-sur_4$vb[3,]+abs(dist_1_z)
set_4 <- t(sur_4$vb)[pos_1, -4]
out<-list("sur"=sur_4,"coo"=set_4)
}
morphomapLanDia<-function(sur,side=c("left","right"),param1=4){
sur<-morphomapSegm(sur)$external
xaxis<-as.vector(range(sur$vb[1,]))
seqs<-seq(xaxis[1],xaxis[2],length.out = 20)[c(4,15)]
p1 <- c(seqs[1], 0, 0)
p2 <- c(seqs[1], 100, 0)
p3 <- c(seqs[1], 0, 100)
normal <- crossProduct(p2 - p1, p3 - p1)
zeroPro <- points2plane(rep(0,3),p1,normal)
sig <- sign(crossprod(-zeroPro,normal))
d <- sig*norm(zeroPro,"2")
sect_t1<-meshPlaneIntersect(sur, p1, p2, p3)
sect_t2 <- morphomapSort(sect_t1[,c(2,3)])
sect_tp<-cbind(sect_t1[,1],sect_t2)
points_1<-morphomapRegradius(sect_tp[,c(2,3)],n = 4,center=colMeans(sect_tp[,c(2,3)]))
p1 <- c(seqs[2], 0, 0)
p2 <- c(seqs[2], 100, 0)
p3 <- c(seqs[2], 0, 100)
normal <- crossProduct(p2 - p1, p3 - p1)
zeroPro <- points2plane(rep(0,3),p1,normal)
sig <- sign(crossprod(-zeroPro,normal))
d <- sig*norm(zeroPro,"2")
sect_t1<-meshPlaneIntersect(sur, p1, p2, p3)
sect_t2 <- morphomapSort(sect_t1[,c(2,3)])
sect_td<-cbind(sect_t1[,1],sect_t2)
points_2<-morphomapRegradius(sect_td[,c(2,3)],n = 4,center=colMeans(sect_td[,c(2,3)]))
if(side=="right"){
sets<-rbind(sect_td[points_2[c(1,2)],],
sect_tp[points_1[c(1)],])
}
if(side=="left"){
sets<-rbind(sect_td[points_2[c(3,2)],],
sect_tp[points_1[c(3)],])
}
return(sets)
}
morphomapAlMesh<-function(set,mesh){
eucl<-dist(set,method="euclidean")
newP1<-c(0,0,0)
newP2<-c(eucl[1],0,0)
newP3<-c(((eucl[1]^2)+(eucl[2]^2)-(eucl[3]^2))/(2*eucl[1]), sqrt((eucl[2]^2)-(((eucl[1]^2)+(eucl[2]^2)- (eucl[3]^2))/(2*eucl[1]))^2), 0)
newP3[which(is.na(newP3))]<-0
tar<-rbind(newP1,newP2,newP3)
rot_mesh<-rotmesh.onto(mesh,as.matrix(set),as.matrix(tar))
return(rot_mesh)
}
morphomapAlTwo<-function(mesh,set,iter,from,to,
tol, iter2, from2,
to2){
pos<-aro.clo.points(vert2points(mesh),set)$position
set_2<-set
for(j in 1:iter2){
if((j>=2)==TRUE){from<-from2}
if((j>=2)==TRUE){to<-to2}
if((j>=2)==TRUE){tol<-tol}
degrees <- seq(from, to, length = iter)
degrees<-c(0,degrees)
radians <- (degrees * pi)/180
for (i in 1:length(degrees)) {
set_2_t <- rotaxis3d(set_2, set_2[2,], c(0,500,500), radians[i])
diff_align_z <- set_2_t[2,3]-set_2_t[5, 3]
if (abs(diff_align_z) <= tol) {
break
}
}
sur_3<-rotaxis3d(mesh, set_2[2,], c(0,500,500), radians[i])
set_3<-t(sur_3$vb)[pos, -4]
sur_4<-sur_3
set_4<-t(sur_4$vb)[pos, -4]
degrees <- seq(from, to, length = iter)
degrees<-c(0,degrees)
radians <- (degrees * pi)/180
for (i in 1:length(degrees)) {
set_4_t <- rotaxis3d(set_4, set_4[2,], c(0,0,500), radians[i])
diff_align_z <- set_4_t[2,2]-set_4_t[6, 2]
if (abs(diff_align_z) <= tol) {
break
}
}
sur_5<-rotaxis3d(sur_4, set_4[2,], c(0,0,500), radians[i])
set_5<-t(sur_5$vb)[pos, -4]
degrees <- seq(from, to, length = iter)
degrees<-c(0,degrees)
radians <- (degrees * pi)/180
for (i in 1:length(degrees)) {
set_5_t <- rotaxis3d(set_5, set_5[2,], c(0,500,0), radians[i])
diff_align_z <- set_5_t[5,3]-set_5_t[7,3]
if (abs(diff_align_z) <= 0.05) {
break
}
}
sur_6<-rotaxis3d(sur_5, set_5[2,], c(0,500,0), radians[i])
set_6<-t(sur_6$vb)[pos, -4]
degrees <- seq(from, to, length = iter)
degrees<-c(0,degrees)
radians <- (degrees * pi)/180
for (i in 1:length(degrees)) {
set_6_t <- rotaxis3d(set_6, set_6[2,], c(500,0,0), radians[i])
diff_align_z <- set_6_t[6,2]-set_6_t[2,2]
if (abs(diff_align_z) <= 0.05) {
break
}
}
sur_7<-rotaxis3d(sur_6, set_6[2,], c(500,0,0), radians[i])
set_7<-t(sur_7$vb)[pos, -4]
sur_8<-sur_7
sur_8$vb[1,]<-sur_7$vb[1,]-set_7[2,1]
sur_8$vb[2,]<-sur_7$vb[2,]-set_7[2,2]
sur_8$vb[3,]<-sur_7$vb[3,]-set_7[2,3]
set_8<-t(sur_8$vb)[pos, -4]
sur_9<-sur_8
sur_9$vb[1,]<-sur_8$vb[1,]-mean(c(set_8[9,1],set_8[10,1]))
set_9<-t(sur_9$vb)[pos,-4]
ax1<-(abs(set_9[3,3]-set_9[4,3]))
ax2<-(abs(set_9[7,3]-set_9[5,3]))
ax3<-(abs(set_9[2,2]-set_9[6,2]))
if((ax1<=tol & ax2 <= tol &ax3<= tol)==TRUE){
break
}
if((ax1<=tol & ax2 <= tol &ax3<= tol)==FALSE){
mesh<-sur_9
set_2<-set_9
}
}
mech_lengh<-set_9[8,1]-mean(c(set_9[c(9,10),1]))
sur_9<-rotaxis3d(sur_9,c(0,0,0),c(0,500,0),(-90 * pi)/180)
sur_9 <- rotaxis3d(sur_9, c(0,0,0), c(0,0,500), (270 * pi)/180)
set_9 <- t(sur_9$vb)[pos, -4]
out<-list("sur"=sur_9,"coo"=set_9,"mech_length"=mech_lengh)
return(out)
}
set0<-set
set1<-morphomapAlOne(mesh,set0[c(1,4,2,3),],iter=iter1,from=from1,to=to1,tol=tol)
set2<-morphomapLanDia(set1$sur,side,param1=param1)
posold<-aro.clo.points(vert2points(mesh),set0[c(1,4,2,3),])$position
set_new<-vert2points(set1$sur)[posold,]
posold1<-aro.clo.points(vert2points(mesh),set0[c(5:7),])$position
set_new1<-vert2points(set1$sur)[posold1,]
set_new1<-rbind(set2,set_new1)
setf<-morphomapAlTwo(set1$sur,set=rbind(set_new,set_new1),
iter=iter2,from=from2,to=to2,tol=tol,iter2=iter3,
from2=from3,to2=to3)
out<-list("sur"=setf$sur,"mech_length"=setf$mech_length)
return(out)
} |
f_lta_nstarts <- function(S, counts, D, nstarts, tol, maxiter, pdGH)
{
out <- f_lta(S, counts, D, tol, maxiter, pdGH)
if(nstarts > 1){
for(i in 2:nstarts){
out1 <- f_lta(S, counts, D, tol, maxiter, pdGH)
if(out1$LL > out$LL) out <- out1
}
}
out
} |
erho.bw.p <-
function(p,c1)
return(chi.int.p(p,2,c1)/2-chi.int.p(p,4,c1)/(2*c1^2)+
2*chi.int(p,4,c1)/(2*c1^3)+chi.int.p(p,6,c1)/(6*c1^4)-
4*chi.int(p,6,c1)/(6*c1^5)+c1^2*chi.int2.p(p,0,c1)/6
+2*c1*chi.int2(p,0,c1)/6) |
samp.dist.snap<-function(parent = NULL, parent2 = NULL, biv.parent = NULL, stat = mean,stat2 = NULL, stat3 = NULL, stat4 = NULL, s.size=c(1,3,6,10,20,50), s.size2 = NULL, R=1000,
func = NULL, xlab = expression(bar(x)),show.SE = TRUE, fits = NULL, show.fits = TRUE, xlim = NULL, ylim = NULL,...){
old.par <- par(no.readonly = TRUE)
if(!is.null(s.size2)&(length(s.size)!=length(s.size2))) stop("length of s.size must equal length of size2")
L <- length(s.size)
if(L>12) {stop("L must be <= 12")} else
if(L==1) {par(mfrow=c(1,1),mar=c(5,4,1,1.5))} else
if(L==2) {par(mfrow=c(2,1),mar=c(5,4,1,1.5))} else
if(L==3) {par(mfrow=c(1,3),mar=c(5,4,1.5))} else
if(L==4) {par(mfrow=c(2,2),mar=c(5,4,1,1.5))} else
if(L==5|L==6) {par(mfrow=c(3,2),mar=c(5,4,2,1.5))} else
if(L==7|L==8|L==9) {par(mfrow=c(3,3),mar=c(5,4,2,1.0))}else
if(L==10|L==11|L==12) {par(mfrow=c(4,3),mar=c(5,4,2,1.0))}
if(L>12)stop("s.size vectors must have length <= 12", call. = FALSE)
for(i in 1:L){
if(is.null(xlim)&is.null(ylim)){
samp.dist(parent = parent, parent2 = parent2, biv.parent = biv.parent, stat = stat, stat2 = stat2, stat3 = stat3, stat4 = stat4, s.size = s.size[i],
s.size2 = s.size2[i], func = func, R = R, xlab = xlab, show.SE = show.SE, anim = FALSE, ...)}
if(!is.null(xlim)&is.null(ylim)){
samp.dist(parent = parent, parent2 = parent2, biv.parent = biv.parent, stat = stat, stat2 = stat2, stat3 = stat3, stat4 = stat4, s.size = s.size[i],
s.size2 = s.size2[i], func = func, R = R, xlab = xlab, show.SE = show.SE, anim = FALSE, xlim = xlim, ...)}
if(!is.null(xlim)&!is.null(ylim)){
samp.dist(parent = parent, parent2 = parent2, biv.parent = biv.parent, stat = stat, stat2 = stat2, stat3 = stat3, stat4 = stat4, s.size = s.size[i],
s.size2 = s.size2[i], func = func, R = R, xlab = xlab, show.SE = show.SE, anim = FALSE, xlim = xlim, ylim = ylim,...)}
if(show.fits == TRUE){
if(!is.null(fits))fits(s.size[i], s.size2[i])}
}
on.exit(par(old.par))
}
samp.dist.snap.tck1<-function(statc = "mean"){
local({
have_ttk <- as.character(tcl("info", "tclversion")) >= "8.5"
if(have_ttk) {
tkbutton <- ttkbutton
tkcheckbutton <- ttkcheckbutton
tkentry <- ttkentry
tkframe <- ttkframe
tklabel <- ttklabel
tkradiobutton <- ttkradiobutton
}
tclServiceMode(FALSE)
dialog.sd <- function(){
tt <- tktoplevel()
tkwm.title(tt,"Sampling distributions")
biv.parent.entry <- tkentry(tt, textvariable=Biv.parent, width = 16)
parent.entry1 <- tkentry(tt, textvariable=Parent1, width = 16)
parent.entry2 <- tkentry(tt, textvariable=Parent2, width = 16)
s.size.entry<-tkentry(tt, textvariable=SS, width = 16)
s.size.entry2<-tkentry(tt, textvariable=SS2, width = 16)
stat.entry1<-tkentry(tt, textvariable=Stat1, width = 16)
stat.entry2<-tkentry(tt, textvariable=Stat2, width = 16)
stat.entry3<-tkentry(tt, textvariable=Stat3, width = 16)
stat.entry4<-tkentry(tt, textvariable=Stat4, width = 16)
func.entry<-tkentry(tt, textvariable=Func, width = 16)
R.entry<-tkentry(tt, textvariable=Rep, width = 16)
x.entry<-tkentry(tt, textvariable=Xlab, width = 16)
fits.entry <- tkentry(tt, textvariable=fits, width = 16)
x.lim.entry<-tkentry(tt, textvariable=xlim, width = 16)
y.lim.entry<-tkentry(tt, textvariable=ylim, width = 16)
done <- tclVar(0)
show.SE<-tclVar(1)
show.fits <- tclVar(1)
reset <- function()
{
tclvalue(Biv.parent)<-"NULL"
tclvalue(Parent1)<-"NULL"
tclvalue(Parent2)<-"NULL"
tclvalue(SS)<-"0"
tclvalue(SS2)<-"0"
tclvalue(Stat1)<-"NULL"
tclvalue(Stat2)<-"NULL"
tclvalue(Stat3)<-"NULL"
tclvalue(Stat4)<-"NULL"
tclvalue(Func)<-"NULL"
tclvalue(Rep)<-"NULL"
tclvalue(Xlab)<-"NULL"
tclvalue(xlim)<-"NULL"
tclvalue(ylim)<-"NULL"
tclvalue(fits)<-"NULL"
}
reset.but <- tkbutton(tt, text="Reset", command=reset)
submit.but <- tkbutton(tt, text="Submit",command=function()tclvalue(done)<-1)
tw <- function(){
tkdestroy(tt)
samp.dist.snap.tck2(statc = statc)
}
add.button <- tkbutton(tt, text="Add 2nd sample",command=tw)
build <- function()
{
parent <-parse(text=tclvalue(Parent1))[[1]]
s.size <-parse(text=tclvalue(SS))[[1]]
stat <-parse(text=tclvalue(Stat1))[[1]]
R <-tclvalue(Rep)
x<-parse(text=tclvalue(Xlab))[[1]]
R <-tclvalue(Rep)
se <- as.logical(tclObj(show.SE))
xlim<-parse(text=tclvalue(xlim))[[1]]
ylim<-parse(text=tclvalue(ylim))[[1]]
fits <- parse(text=tclvalue(fits))[[1]]
show.fits <- as.logical(tclObj(show.fits))
substitute(samp.dist.snap(parent = parent, s.size = s.size, stat = stat, R = as.numeric(R), xlab = x,show.SE = se, xlim = xlim, ylim = ylim, fits = fits, show.fits = show.fits))
}
se.cbut <- tkcheckbutton(tt, text="Show SE", variable=show.SE)
fits.cbut <- tkcheckbutton(tt, text="Show fits", variable=show.fits)
tkgrid(tklabel(tt,text="Sampling distribution snapshots"), columnspan = 2)
tkgrid(tklabel(tt,text=""))
tkgrid(tklabel(tt,text="Parent",font=c("Helvetica","9","bold"), width = 12),parent.entry1)
tkgrid(tklabel(tt,text="Sample sizes ",font=c("Helvetica","9","bold"), width = 12),s.size.entry)
tkgrid(tklabel(tt,text="Stat",font=c("Helvetica","9","bold"), width = 12),stat.entry1)
tkgrid(tklabel(tt,text="Iterations", width = 12), R.entry)
tkgrid(tklabel(tt,text="X-axis label", width = 12), x.entry)
tkgrid(tklabel(tt,text="Xlim", width = 12), x.lim.entry)
tkgrid(tklabel(tt,text="Ylim", width = 12), y.lim.entry)
tkgrid(tklabel(tt,text=""), columnspan = 2)
tkgrid(se.cbut, sticky = "w")
tkgrid(fits.cbut,sticky="w")
tkgrid(tklabel(tt,text="Fit(s)"), fits.entry, sticky = "w")
tkgrid(tklabel(tt,text=""), columnspan = 2)
tkgrid(add.button, columnspan = 2)
tkgrid(submit.but, reset.but)
tkbind(tt, "<Destroy>", function()tclvalue(done)<-2)
tkwait.variable(done)
if(tclvalue(done)=="2") stop("aborted")
tkdestroy(tt)
cmd <- build()
eval.parent(cmd)
tclServiceMode(TRUE)
}
if(statc == "mean"){
Biv.parent<-tclVar("NULL")
Parent1<-tclVar("expression(rexp(s.size))")
Parent2<-tclVar("NULL")
SS<-tclVar("c(1,3,7,10,20,50)")
SS2<-tclVar("NULL")
Stat1<-tclVar("mean")
Stat2<-tclVar("NULL")
Stat3<-tclVar("NULL")
Stat4<-tclVar("NULL")
Func<-tclVar("NULL")
Rep<-tclVar("10000")
Xlab<- tclVar("expression(bar(x))")
ylim <- tclVar("NULL")
xlim <- tclVar("NULL")
fits <- tclVar("NULL")
}
if(statc == "median"){
Biv.parent<-tclVar("NULL")
Parent1<-tclVar("expression(rexp(s.size))")
Parent2<-tclVar("NULL")
SS<-tclVar("c(1,3,7,10,20,50)")
SS2<-tclVar("NULL")
Stat1<-tclVar("median")
Stat2<-tclVar("NULL")
Stat3<-tclVar("NULL")
Stat4<-tclVar("NULL")
Func<-tclVar("NULL")
Rep<-tclVar("1000")
Xlab<- tclVar("expression(Median)")
ylim <- tclVar("NULL")
xlim <- tclVar("NULL")
fits <- tclVar("NULL")
}
if(statc == "trimmed mean"){
Biv.parent<-tclVar("NULL")
Parent1<-tclVar("expression(rexp(s.size))")
Parent2<-tclVar("NULL")
SS<-tclVar("c(7,10,20,50)")
SS2<-tclVar("NULL")
tr.mean <- function(x)mean(x,trim = 0.2)
Stat1<-tclVar("tr.mean")
Stat2<-tclVar("NULL")
Stat3<-tclVar("NULL")
Stat4<-tclVar("NULL")
Func<-tclVar("NULL")
Rep<-tclVar("1000")
Xlab<- tclVar("expression(Trimmed.mean)")
ylim <- tclVar("NULL")
xlim <- tclVar("NULL")
fits <- tclVar("NULL")}
if(statc == "Winsorized mean"){
Biv.parent<-tclVar("NULL")
Parent1<-tclVar("expression(rexp(s.size))")
Parent2<-tclVar("NULL")
SS<-tclVar("c(7,10,20,50)")
SS2<-tclVar("NULL")
win.mean <- function(x)mean(win(x))
Stat1<-tclVar("win.mean")
Stat2<-tclVar("NULL")
Stat3<-tclVar("NULL")
Stat4<-tclVar("NULL")
Func<-tclVar("NULL")
Rep<-tclVar("1000")
Xlab<- tclVar("expression(Winsorized.mean)")
ylim <- tclVar("NULL")
xlim <- tclVar("NULL")
fits <- tclVar("NULL")}
if(statc == "Huber estimator"){
Biv.parent<-tclVar("NULL")
Parent1<-tclVar("expression(rexp(s.size))")
Parent2<-tclVar("NULL")
SS<-tclVar("c(7,10,20,50)")
SS2<-tclVar("NULL")
Stat1<-tclVar("huber.mu")
Stat2<-tclVar("NULL")
Stat3<-tclVar("NULL")
Stat4<-tclVar("NULL")
Func<-tclVar("NULL")
Rep<-tclVar("1000")
Xlab<- tclVar("expression(Huber.estimator)")
ylim <- tclVar("NULL")
xlim <- tclVar("NULL")
fits <- tclVar("NULL")}
if(statc == "H-L estimator"){
Biv.parent<-tclVar("NULL")
Parent1<-tclVar("expression(rexp(s.size))")
Parent2<-tclVar("NULL")
SS<-tclVar("c(7,10,20,50)")
SS2<-tclVar("NULL")
Stat1<-tclVar("HL.mean")
Stat2<-tclVar("NULL")
Stat3<-tclVar("NULL")
Stat4<-tclVar("NULL")
Func<-tclVar("NULL")
Rep<-tclVar("1000")
Xlab<- tclVar("expression(H-L.estimator)")
ylim <- tclVar("NULL")
xlim <- tclVar("NULL")
fits <- tclVar("NULL")}
if(statc == "sd"){
Biv.parent<-tclVar("NULL")
Parent1<-tclVar("expression(rnorm(s.size))")
Parent2<-tclVar("NULL")
SS<-tclVar("c(3,7,10,20)")
SS2<-tclVar("NULL")
Stat1<-tclVar("sd")
Stat2<-tclVar("NULL")
Stat3<-tclVar("NULL")
Stat4<-tclVar("NULL")
Func<-tclVar("NULL")
Rep<-tclVar("1000")
Xlab<- tclVar("expression(S)")
ylim <- tclVar("NULL")
xlim <- tclVar("NULL")
fits <- tclVar("NULL")
}
if(statc == "var"){
Biv.parent<-tclVar("NULL")
Parent1<-tclVar("expression(rnorm(s.size))")
Parent2<-tclVar("NULL")
SS<-tclVar("c(3,7,10,20)")
SS2<-tclVar("NULL")
Stat1<-tclVar("var")
Stat2<-tclVar("NULL")
Stat3<-tclVar("NULL")
Stat4<-tclVar("NULL")
Func<-tclVar("NULL")
Rep<-tclVar("1000")
Xlab<- tclVar("expression(S^2)")
ylim <- tclVar("NULL")
xlim <- tclVar("NULL")
fits <- tclVar("NULL")
}
if(statc == "MAD"){
Biv.parent<-tclVar("NULL")
Parent1<-tclVar("expression(rnorm(s.size))")
Parent2<-tclVar("NULL")
SS<-tclVar("c(7,10,20,50)")
SS2<-tclVar("NULL")
Stat1<-tclVar("mad")
Stat2<-tclVar("NULL")
Stat3<-tclVar("NULL")
Stat4<-tclVar("NULL")
Func<-tclVar("NULL")
Rep<-tclVar("1000")
Xlab<- tclVar("expression(MAD)")
ylim <- tclVar("NULL")
xlim <- tclVar("NULL")
fits <- tclVar("NULL")
}
if(statc == "IQR"){
Biv.parent<-tclVar("NULL")
Parent1<-tclVar("expression(rnorm(s.size))")
Parent2<-tclVar("NULL")
SS<-tclVar("c(7,10,20,50)")
SS2<-tclVar("NULL")
Stat1<-tclVar("IQR")
Stat2<-tclVar("NULL")
Stat3<-tclVar("NULL")
Stat4<-tclVar("NULL")
Func<-tclVar("NULL")
Rep<-tclVar("1000")
Xlab<- tclVar("expression(IQR)")
ylim <- tclVar("NULL")
xlim <- tclVar("NULL")
fits <- tclVar("NULL")
}
dialog.sd()
})
}
samp.dist.snap.tck2<-function (statc = "mean")
{
local({
have_ttk <- as.character(tcl("info", "tclversion")) >=
"8.5"
if (have_ttk) {
tkbutton <- ttkbutton
tkcheckbutton <- ttkcheckbutton
tkentry <- ttkentry
tkframe <- ttkframe
tklabel <- ttklabel
tkradiobutton <- ttkradiobutton
}
tclServiceMode(FALSE)
dialog.sd <- function() {
tt <- tktoplevel()
tkwm.title(tt, "Sampling distributions")
biv.parent.entry <- tkentry(tt, textvariable = Biv.parent,
width = 16)
parent.entry1 <- tkentry(tt, textvariable = Parent1,
width = 16)
parent.entry2 <- tkentry(tt, textvariable = Parent2,
width = 16)
s.size.entry <- tkentry(tt, textvariable = SS, width = 16)
s.size.entry2 <- tkentry(tt, textvariable = SS2,
width = 16)
stat.entry1 <- tkentry(tt, textvariable = Stat1,
width = 16)
stat.entry2 <- tkentry(tt, textvariable = Stat2,
width = 16)
stat.entry3 <- tkentry(tt, textvariable = Stat3,
width = 16)
stat.entry4 <- tkentry(tt, textvariable = Stat4,
width = 16)
func.entry <- tkentry(tt, textvariable = Func, width = 16)
R.entry <- tkentry(tt, textvariable = Rep, width = 16)
x.entry <- tkentry(tt, textvariable = Xlab, width = 16)
fits.entry <- tkentry(tt, textvariable = fits, width = 16)
x.lim.entry <- tkentry(tt, textvariable = xlim, width = 16)
y.lim.entry <- tkentry(tt, textvariable = ylim, width = 16)
done <- tclVar(0)
show.SE <- tclVar(1)
show.fits <- tclVar(1)
reset <- function() {
tclvalue(Biv.parent) <- "NULL"
tclvalue(Parent1) <- "NULL"
tclvalue(Parent2) <- "NULL"
tclvalue(SS) <- "0"
tclvalue(SS2) <- "0"
tclvalue(Stat1) <- "NULL"
tclvalue(Stat2) <- "NULL"
tclvalue(Stat3) <- "NULL"
tclvalue(Stat4) <- "NULL"
tclvalue(Func) <- "NULL"
tclvalue(Rep) <- "NULL"
tclvalue(Xlab) <- "NULL"
tclvalue(xlim) <- "NULL"
tclvalue(ylim) <- "NULL"
tclvalue(fits) <- "NULL"
}
reset.but <- tkbutton(tt, text = "Reset", command = reset)
submit.but <- tkbutton(tt, text = "Submit", command = function() tclvalue(done) <- 1)
build <- function() {
biv.parent <- parse(text = tclvalue(Biv.parent))[[1]]
parent <- parse(text = tclvalue(Parent1))[[1]]
parent2 <- parse(text = tclvalue(Parent2))[[1]]
s.size <- parse(text = tclvalue(SS))[[1]]
stat <- parse(text = tclvalue(Stat1))[[1]]
s.size2 <- parse(text = tclvalue(SS2))[[1]]
stat2 <- parse(text = tclvalue(Stat2))[[1]]
stat3 <- parse(text = tclvalue(Stat3))[[1]]
stat4 <- parse(text = tclvalue(Stat4))[[1]]
R <- tclvalue(Rep)
x <- parse(text = tclvalue(Xlab))[[1]]
func <- parse(text = tclvalue(Func))[[1]]
se <- as.logical(tclObj(show.SE))
xlim <- parse(text = tclvalue(xlim))[[1]]
ylim <- parse(text = tclvalue(ylim))[[1]]
fits <- parse(text = tclvalue(fits))[[1]]
show.fits <- as.logical(tclObj(show.fits))
substitute(samp.dist.snap(parent = parent, parent2 = parent2,
biv.parent = biv.parent, s.size = s.size, s.size2 = s.size2,
stat = stat, func = func, stat2 = stat2, stat3 = stat3,
stat4 = stat4, R = as.numeric(R), xlab = x,
show.SE = se, xlim = xlim, ylim = ylim, show.fits = show.fits,
fits = fits))
}
se.cbut <- tkcheckbutton(tt, text = "Show SE", variable = show.SE)
fits.cbut <- tkcheckbutton(tt, text = "Show fits",
variable = show.fits)
tkgrid(tklabel(tt, text = "Sampling distribution snapshots"),
columnspan = 4)
tkgrid(tklabel(tt, text = ""))
tkgrid(tklabel(tt, text = ""), tklabel(tt, text = "Bivariate parent"),
biv.parent.entry)
tkgrid(tklabel(tt, text = "Parent 1", font = c("Helvetica",
"9", "bold")), parent.entry1, tklabel(tt, text = "Parent 2"),
parent.entry2)
tkgrid(tklabel(tt, text = "Sample sizes ", font = c("Helvetica",
"9", "bold")), s.size.entry, tklabel(tt, text = "Sample sizes 2"),
s.size.entry2)
tkgrid(tklabel(tt, text = "Stat", font = c("Helvetica",
"9", "bold")), stat.entry1, tklabel(tt, text = "Stat 2"),
stat.entry2)
tkgrid(tklabel(tt, text = "Stat 3"), stat.entry3,
tklabel(tt, text = "Stat 4"), stat.entry4)
tkgrid(tklabel(tt, text = ""))
tkgrid(tklabel(tt, text = ""), tklabel(tt, text = "Iterations"),
R.entry)
tkgrid(tklabel(tt, text = ""), tklabel(tt, text = "Function"),
func.entry)
tkgrid(tklabel(tt, text = ""), tklabel(tt, text = "X-axis label"),
x.entry)
tkgrid(tklabel(tt, text = ""), tklabel(tt, text = "Xlim"),
x.lim.entry)
tkgrid(tklabel(tt, text = ""), tklabel(tt, text = "Ylim"),
y.lim.entry)
tkgrid(tklabel(tt, text = ""))
tkgrid(se.cbut)
tkgrid(fits.cbut, tklabel(tt, text = "Fit(s)"), fits.entry)
tkgrid(tklabel(tt, text = ""))
tkgrid(tklabel(tt, text = ""), submit.but, reset.but)
tkgrid(tklabel(tt, text = ""))
tkbind(tt, "<Destroy>", function() tclvalue(done) <- 2)
tkwait.variable(done)
if (tclvalue(done) == "2")
stop("aborted")
tkdestroy(tt)
cmd <- build()
eval.parent(cmd)
tclServiceMode(TRUE)
}
if (statc == "custom") {
Biv.parent <- tclVar("NULL")
Parent1 <- tclVar("NULL")
Parent2 <- tclVar("NULL")
SS <- tclVar("NULL")
SS2 <- tclVar("NULL")
Stat1 <- tclVar("mean")
Stat2 <- tclVar("NULL")
Stat3 <- tclVar("NULL")
Stat4 <- tclVar("NULL")
Func <- tclVar("NULL")
Rep <- tclVar("NULL")
Xlab <- tclVar("NULL")
ylim <- tclVar("NULL")
xlim <- tclVar("NULL")
fits <- tclVar("NULL")
}
if (statc == "mean") {
Biv.parent <- tclVar("NULL")
Parent1 <- tclVar("expression(rexp(s.size))")
Parent2 <- tclVar("NULL")
SS <- tclVar("c(1,3,7,10,20,50)")
SS2 <- tclVar("NULL")
Stat1 <- tclVar("mean")
Stat2 <- tclVar("NULL")
Stat3 <- tclVar("NULL")
Stat4 <- tclVar("NULL")
Func <- tclVar("NULL")
Rep <- tclVar("10000")
Xlab <- tclVar("expression(bar(x))")
ylim <- tclVar("NULL")
xlim <- tclVar("NULL")
fits <- tclVar("NULL")
}
if (statc == "median") {
Biv.parent <- tclVar("NULL")
Parent1 <- tclVar("expression(rexp(s.size))")
Parent2 <- tclVar("NULL")
SS <- tclVar("c(1,3,7,10,20,50)")
SS2 <- tclVar("NULL")
Stat1 <- tclVar("median")
Stat2 <- tclVar("NULL")
Stat3 <- tclVar("NULL")
Stat4 <- tclVar("NULL")
Func <- tclVar("NULL")
Rep <- tclVar("10000")
Xlab <- tclVar("expression(Median)")
ylim <- tclVar("NULL")
xlim <- tclVar("NULL")
fits <- tclVar("NULL")
}
if (statc == "trimmed mean") {
Biv.parent <- tclVar("NULL")
Parent1 <- tclVar("expression(rexp(s.size))")
Parent2 <- tclVar("NULL")
SS <- tclVar("c(7,10,20,50)")
SS2 <- tclVar("NULL")
tr.mean <- function(x) mean(x, trim = 0.2)
Stat1 <- tclVar("tr.mean")
Stat2 <- tclVar("NULL")
Stat3 <- tclVar("NULL")
Stat4 <- tclVar("NULL")
Func <- tclVar("NULL")
Rep <- tclVar("1000")
Xlab <- tclVar("expression(Trimmed.mean)")
ylim <- tclVar("NULL")
xlim <- tclVar("NULL")
fits <- tclVar("NULL")
}
if (statc == "Winsorized mean") {
Biv.parent <- tclVar("NULL")
Parent1 <- tclVar("expression(rexp(s.size))")
Parent2 <- tclVar("NULL")
SS <- tclVar(("c(7,10,20,50)"))
SS2 <- tclVar("NULL")
win.mean <- function(x) mean(win(x))
Stat1 <- tclVar("win.mean")
Stat2 <- tclVar("NULL")
Stat3 <- tclVar("NULL")
Stat4 <- tclVar("NULL")
Func <- tclVar("NULL")
Rep <- tclVar("1000")
Xlab <- tclVar("expression(Winsorized.mean)")
ylim <- tclVar("NULL")
xlim <- tclVar("NULL")
fits <- tclVar("NULL")
}
if (statc == "Huberestimator") {
Biv.parent <- tclVar("NULL")
Parent1 <- tclVar("expression(rexp(s.size))")
Parent2 <- tclVar("NULL")
SS <- tclVar(("c(7,10,20,50)"))
SS2 <- tclVar("NULL")
Stat1 <- tclVar("huber.mu")
Stat2 <- tclVar("NULL")
Stat3 <- tclVar("NULL")
Stat4 <- tclVar("NULL")
Func <- tclVar("NULL")
Rep <- tclVar("1000")
Xlab <- tclVar("expression(Huber.estimator)")
ylim <- tclVar("NULL")
xlim <- tclVar("NULL")
fits <- tclVar("NULL")
}
if (statc == "H-L estimator") {
Biv.parent <- tclVar("NULL")
Parent1 <- tclVar("expression(rexp(s.size))")
Parent2 <- tclVar("NULL")
SS <- tclVar(("c(7,10,20,50)"))
SS2 <- tclVar("NULL")
Stat1 <- tclVar("HL.mean")
Stat2 <- tclVar("NULL")
Stat3 <- tclVar("NULL")
Stat4 <- tclVar("NULL")
Func <- tclVar("NULL")
Rep <- tclVar("1000")
Xlab <- tclVar("expression(H-L.estimator)")
ylim <- tclVar("NULL")
xlim <- tclVar("NULL")
fits <- tclVar("NULL")
}
if (statc == "sd") {
Biv.parent <- tclVar("NULL")
Parent1 <- tclVar("expression(rnorm(s.size))")
Parent2 <- tclVar("NULL")
SS <- tclVar("c(3,7,10,20)")
SS2 <- tclVar("NULL")
Stat1 <- tclVar("sd")
Stat2 <- tclVar("NULL")
Stat3 <- tclVar("NULL")
Stat4 <- tclVar("NULL")
Func <- tclVar("NULL")
Rep <- tclVar("1000")
Xlab <- tclVar("expression(S)")
ylim <- tclVar("NULL")
xlim <- tclVar("NULL")
fits <- tclVar("NULL")
}
if (statc == "var") {
Biv.parent <- tclVar("NULL")
Parent1 <- tclVar("expression(rnorm(s.size))")
Parent2 <- tclVar("NULL")
SS <- tclVar("c(3,7,10,20)")
SS2 <- tclVar("NULL")
Stat1 <- tclVar("var")
Stat2 <- tclVar("NULL")
Stat3 <- tclVar("NULL")
Stat4 <- tclVar("NULL")
Func <- tclVar("NULL")
Rep <- tclVar("1000")
Xlab <- tclVar("expression(S^2)")
ylim <- tclVar("NULL")
xlim <- tclVar("NULL")
fits <- tclVar("NULL")
}
if (statc == "MAD") {
Biv.parent <- tclVar("NULL")
Parent1 <- tclVar("expression(rnorm(s.size))")
Parent2 <- tclVar("NULL")
SS <- tclVar(("c(7,10,20,50)"))
SS2 <- tclVar("NULL")
Stat1 <- tclVar("mad")
Stat2 <- tclVar("NULL")
Stat3 <- tclVar("NULL")
Stat4 <- tclVar("NULL")
Func <- tclVar("NULL")
Rep <- tclVar("1000")
Xlab <- tclVar("expression(MAD)")
ylim <- tclVar("NULL")
xlim <- tclVar("NULL")
fits <- tclVar("NULL")
}
if (statc == "IQR") {
Biv.parent <- tclVar("NULL")
Parent1 <- tclVar("expression(rnorm(s.size))")
Parent2 <- tclVar("NULL")
SS <- tclVar("c(7,10,20,50)")
SS2 <- tclVar("NULL")
Stat1 <- tclVar("IQR")
Stat2 <- tclVar("NULL")
Stat3 <- tclVar("NULL")
Stat4 <- tclVar("NULL")
Func <- tclVar("NULL")
Rep <- tclVar("1000")
Xlab <- tclVar("expression(IQR)")
ylim <- tclVar("NULL")
xlim <- tclVar("NULL")
fits <- tclVar("NULL")
}
if (statc == "(n-1)S^2/sigma^2") {
Biv.parent <- tclVar("NULL")
Parent1 <- tclVar("expression(rnorm(s.size))")
Parent2 <- tclVar("NULL")
SS <- tclVar("c(3,7,10,20)")
SS2 <- tclVar("NULL")
Stat1 <- tclVar("var")
Stat2 <- tclVar("NULL")
Stat3 <- tclVar("NULL")
Stat4 <- tclVar("NULL")
Func <- tclVar("function(s.dist, s.dist2, s.size, s.size2, sigma.sq = 1)((s.size - 1) * s.dist)/sigma.sq")
Rep <- tclVar("10000")
Xlab <- tclVar("expression((n - 1)*S^2/sigma^2)")
ylim <- tclVar("NULL")
xlim <- tclVar("c(0,40)")
x <- NULL
suppressWarnings(rm(x))
fits <- tclVar("function(s.size, s.size2)curve(dchisq(x, s.size - 1),from = 0, to = 40, add = TRUE, lwd = 2, col = gray(.3))")
}
if (statc == "F*") {
Biv.parent <- tclVar("NULL")
Parent1 <- tclVar("expression(rnorm(s.size))")
Parent2 <- tclVar("expression(rnorm(s.size2))")
SS <- tclVar("c(5,7,12,20)")
SS2 <- tclVar("c(7,5,10,15)")
Stat1 <- tclVar("var")
Stat2 <- tclVar("var")
Stat3 <- tclVar("NULL")
Stat4 <- tclVar("NULL")
Func <- tclVar("function(s.dist, s.dist2, s.size, s.size2) s.dist/s.dist2")
Rep <- tclVar("2000")
Xlab <- tclVar("expression(F.star)")
ylim <- tclVar("c(0, 0.8)")
xlim <- tclVar("c(0,20)")
x <- NULL
suppressWarnings(rm(x))
fits <- tclVar("function(s.size, s.size2)curve(df(x, s.size - 1, s.size2 - 1),from = 0, to = 20, add = TRUE, col = gray(.3), lwd = 2)")
}
if (statc == "t* (1 sample)") {
Biv.parent <- tclVar("NULL")
Parent1 <- tclVar("expression(rnorm(s.size))")
Parent2 <- tclVar("NULL")
SS <- tclVar("c(3,7,10,20)")
SS2 <- tclVar("NULL")
Stat1 <- tclVar("mean")
Stat2 <- tclVar("NULL")
Stat3 <- tclVar("var")
Stat4 <- tclVar("NULL")
Func <- tclVar("function(s.dist, s.dist3, s.size, s.size2)s.dist/sqrt(s.dist3/s.size)")
Rep <- tclVar("10000")
Xlab <- tclVar("expression(t.star)")
ylim <- tclVar("c(0, 0.5)")
xlim <- tclVar("c(-5, 5)")
x <- NULL
suppressWarnings(rm(x))
fits <- tclVar("function(s.size, s.size2)({curve(dnorm(x),from = -10, to = 10, add = TRUE, lty = 2, lwd = 2, col = gray(.3)); curve(dt(x, s.size-1),from = -10,to = 10, add = TRUE, lty = 1, lwd = 2, col = gray(.6))})")
}
if (statc == "t* (2 sample)") {
Biv.parent <- tclVar("NULL")
Parent1 <- tclVar("expression(rnorm(s.size))")
Parent2 <- tclVar("expression(rnorm(s.size))")
SS <- tclVar("c(3,7,10,20)")
SS2 <- tclVar("c(5,8,10,30)")
Stat1 <- tclVar("mean")
Stat2 <- tclVar("mean")
Stat3 <- tclVar("var")
Stat4 <- tclVar("var")
Func <- tclVar("function(s.dist1, s.dist2, s.dist3, s.dist4, s.size = 6, s.size2 = s.size2)({MSE<-(((s.size - 1) * s.dist3) + ((s.size2 - 1) * s.dist4))/((s.size + s.size2) - 2);(s.dist1 - s.dist2)/(sqrt(MSE) * sqrt((1/s.size) + (1/s.size2)))})")
Rep <- tclVar("10000")
Xlab <- tclVar("expression(t.star)")
ylim <- tclVar("c(0, 0.5)")
xlim <- tclVar("c(-5, 5)")
x <- NULL
suppressWarnings(rm(x))
fits <- tclVar("function(s.size, s.size2)({curve(dnorm(x),from = -10, to = 10, add = TRUE, lty = 2, lwd = 2, col = gray(.3)); curve(dt(x, (s.size + s.size2) - 2),from = -10,to = 10, add = TRUE, lty = 1, lwd = 2, col = gray(.6))})")
}
if (statc == "Pearson correlation") {
Biv.parent <- tclVar("expression(rmvnorm(s.size, c(0,0), sigma = matrix(nrow=2,ncol=2, data =c(1,0,0,1))))")
Parent1 <- tclVar("NULL")
Parent2 <- tclVar("NULL")
SS <- tclVar("c(3,5,7,10,20,50)")
SS2 <- tclVar("NULL")
Stat1 <- tclVar("NULL")
Stat2 <- tclVar("NULL")
Stat3 <- tclVar("NULL")
Stat4 <- tclVar("NULL")
Func <- tclVar("cor")
Rep <- tclVar("2000")
Xlab <- tclVar("expression(r)")
ylim <- tclVar("NULL")
xlim <- tclVar("NULL")
fits <- tclVar("NULL")
}
if (statc == "covariance") {
Biv.parent <- tclVar("expression(rmvnorm(s.size, c(0,0), sigma = matrix(nrow=2,ncol=2, data =c(1,0,0,1))))")
Parent1 <- tclVar("NULL")
Parent2 <- tclVar("NULL")
SS <- tclVar("c(3,5,7,10,20,50)")
SS2 <- tclVar("NULL")
Stat1 <- tclVar("NULL")
Stat2 <- tclVar("NULL")
Stat3 <- tclVar("NULL")
Stat4 <- tclVar("NULL")
Func <- tclVar("cov")
Rep <- tclVar("2000")
Xlab <- tclVar("expression(Covariance)")
ylim <- tclVar("NULL")
xlim <- tclVar("NULL")
fits <- tclVar("NULL")
}
dialog.sd()
})
} |
data(nuclearplants)
( fm1 <- fullmatch(pr ~ t1 + t2, data = nuclearplants) )
summary(fm1)
( fm2 <- fullmatch(pr ~ t1 + t2, min.controls = .5, max.controls = 4, data = nuclearplants) )
summary(fm2)
( fm3 <- fullmatch(pr ~ t1 + t2, omit.fraction = .5, data = nuclearplants) )
summary(fm3)
( fm4 <- fullmatch(pr ~ t1 + t2, max.controls = 1, data=nuclearplants) )
summary(fm4)
optmatch_restrictions(fm4)
ppty <- glm(pr ~ . - (pr + cost), family = binomial(), data = nuclearplants)
mhd <- match_on(pr ~ t1 + t2, data = nuclearplants) + caliper(match_on(ppty), width = 1)
( fm5 <- fullmatch(mhd, data = nuclearplants) )
summary(fm5)
if (require(RItools)) summary(fm5,ppty)
cbind(nuclearplants, matches = fm5)
m1 <- fullmatch(pr ~ t1 + t2, data=nuclearplants,
within=exactMatch(pr ~ pt, data=nuclearplants))
m2 <- fullmatch(pr ~ t1 + t2 + strata(pt), data=nuclearplants)
m3 <- fullmatch(glm(pr ~ t1 + t2, data=nuclearplants, family=binomial),
data=nuclearplants,
within=exactMatch(pr ~ pt, data=nuclearplants))
m4 <- fullmatch(glm(pr ~ t1 + t2 + pt, data=nuclearplants,
family=binomial),
data=nuclearplants,
within=exactMatch(pr ~ pt, data=nuclearplants))
m5 <- fullmatch(glm(pr ~ t1 + t2 + strata(pt), data=nuclearplants,
family=binomial), data=nuclearplants) |
escalc <- function(measure, ai, bi, ci, di, n1i, n2i, x1i, x2i, t1i, t2i, m1i, m2i, sd1i, sd2i, xi, mi, ri, ti, sdi, r2i, ni, yi, vi, sei,
data, slab, subset, include, add=1/2, to="only0", drop00=FALSE, vtype="LS", var.names=c("yi","vi"), add.measure=FALSE, append=TRUE, replace=TRUE, digits, ...) {
mstyle <- .get.mstyle("crayon" %in% .packages())
if (missing(measure) && missing(yi))
stop(mstyle$stop("Must specify an effect size or outcome measure via the 'measure' argument."))
if (!missing(yi) && missing(measure))
measure <- "GEN"
if (!is.character(measure))
stop(mstyle$stop("The 'measure' argument must be a character string."))
if (!is.element(measure, c("RR","OR","PETO","RD","AS","PHI","YUQ","YUY","RTET",
"PBIT","OR2D","OR2DN","OR2DL",
"MPRD","MPRR","MPOR","MPORC","MPPETO",
"IRR","IRD","IRSD",
"MD","SMD","SMDH","ROM",
"CVR","VR",
"RPB","RBIS","D2OR","D2ORN","D2ORL",
"COR","UCOR","ZCOR",
"PCOR","ZPCOR","SPCOR",
"PR","PLN","PLO","PAS","PFT",
"IR","IRLN","IRS","IRFT",
"MN","MNLN","CVLN","SDLN","SMD1",
"MC","SMCC","SMCR","SMCRH","ROMC","CVRC","VRC",
"ARAW","AHW","ABT",
"GEN")))
stop(mstyle$stop("Unknown 'measure' specified."))
if (!is.element(to, c("all","only0","if0all","none")))
stop(mstyle$stop("Unknown 'to' argument specified."))
if (any(!is.element(vtype, c("UB","LS","LS2","HO","ST","CS","AV","AVHO")), na.rm=TRUE))
stop(mstyle$stop("Unknown 'vtype' argument specified."))
if (add.measure) {
if (length(var.names) == 2L)
var.names <- c(var.names, "measure")
if (length(var.names) != 3L)
stop(mstyle$stop("Argument 'var.names' must be of length 2 or 3."))
if (any(var.names != make.names(var.names, unique=TRUE))) {
var.names <- make.names(var.names, unique=TRUE)
warning(mstyle$warning(paste0("Argument 'var.names' does not contain syntactically valid variable names.\n Variable names adjusted to: var.names = c('", var.names[1], "', '", var.names[2], "', '", var.names[3], "').")))
}
} else {
if (length(var.names) == 3L)
var.names <- var.names[1:2]
if (length(var.names) != 2L)
stop(mstyle$stop("Argument 'var.names' must be of length 2."))
if (any(var.names != make.names(var.names, unique=TRUE))) {
var.names <- make.names(var.names, unique=TRUE)
warning(mstyle$warning(paste0("Argument 'var.names' does not contain syntactically valid variable names.\n Variable names adjusted to: var.names = c('", var.names[1], "', '", var.names[2], "').")))
}
}
if (hasArg(formula) || hasArg(weights))
stop(mstyle$stop("The 'formula interface' to escalc() has been deprecated."))
ddd <- list(...)
.chkdots(ddd, c("onlyo1", "addyi", "addvi"))
onlyo1 <- ifelse(is.null(ddd$onlyo1), FALSE, ddd$onlyo1)
addyi <- ifelse(is.null(ddd$addyi), TRUE, ddd$addyi)
addvi <- ifelse(is.null(ddd$addvi), TRUE, ddd$addvi)
if (missing(digits)) {
digits <- .set.digits(dmiss=TRUE)
} else {
digits <- .set.digits(digits, dmiss=FALSE)
}
if (missing(data))
data <- NULL
has.data <- !is.null(data)
if (is.null(data)) {
data <- sys.frame(sys.parent())
} else {
if (!is.data.frame(data))
data <- data.frame(data)
}
mf <- match.call()
mf.slab <- mf[[match("slab", names(mf))]]
mf.subset <- mf[[match("subset", names(mf))]]
mf.include <- mf[[match("include", names(mf))]]
slab <- eval(mf.slab, data, enclos=sys.frame(sys.parent()))
subset <- eval(mf.subset, data, enclos=sys.frame(sys.parent()))
include <- eval(mf.include, data, enclos=sys.frame(sys.parent()))
mf.yi <- mf[[match("yi", names(mf))]]
yi <- eval(mf.yi, data, enclos=sys.frame(sys.parent()))
addval <- mf[[match("add", names(mf))]]
if (is.element(measure, c("AS","PHI","RTET","IRSD","PAS","PFT","IRS","IRFT")) && is.null(addval))
add <- 0
if (is.null(yi)) {
if (is.element(measure, c("RR","OR","RD","AS","PETO","PHI","YUQ","YUY","RTET","PBIT","OR2D","OR2DN","OR2DL","MPRD","MPRR","MPOR","MPORC","MPPETO"))) {
mf.ai <- mf[[match("ai", names(mf))]]
if (any("~" %in% as.character(mf.ai)))
stop(mstyle$stop("The 'formula interface' to escalc() has been deprecated."))
mf.bi <- mf[[match("bi", names(mf))]]
mf.ci <- mf[[match("ci", names(mf))]]
mf.di <- mf[[match("di", names(mf))]]
mf.n1i <- mf[[match("n1i", names(mf))]]
mf.n2i <- mf[[match("n2i", names(mf))]]
ai <- eval(mf.ai, data, enclos=sys.frame(sys.parent()))
bi <- eval(mf.bi, data, enclos=sys.frame(sys.parent()))
ci <- eval(mf.ci, data, enclos=sys.frame(sys.parent()))
di <- eval(mf.di, data, enclos=sys.frame(sys.parent()))
n1i <- eval(mf.n1i, data, enclos=sys.frame(sys.parent()))
n2i <- eval(mf.n2i, data, enclos=sys.frame(sys.parent()))
if (is.null(bi)) bi <- n1i - ai
if (is.null(di)) di <- n2i - ci
k.all <- length(ai)
if (length(ai)==0L || length(bi)==0L || length(ci)==0L || length(di)==0L)
stop(mstyle$stop("Cannot compute outcomes. Check that all of the required \n information is specified via the appropriate arguments."))
if (!all(k.all == c(length(ai),length(bi),length(ci),length(di))))
stop(mstyle$stop("Supplied data vectors are not all of the same length."))
if (!is.null(subset)) {
subset <- .setnafalse(subset, k=k.all)
ai <- ai[subset]
bi <- bi[subset]
ci <- ci[subset]
di <- di[subset]
}
n1i <- ai + bi
n2i <- ci + di
if (any(c(ai > n1i, ci > n2i), na.rm=TRUE))
stop(mstyle$stop("One or more event counts are larger than the corresponding group sizes."))
if (any(c(ai, bi, ci, di) < 0, na.rm=TRUE))
stop(mstyle$stop("One or more counts are negative."))
if (any(c(n1i < 0, n2i < 0), na.rm=TRUE))
stop(mstyle$stop("One or more group sizes are < 0."))
ni.u <- ai + bi + ci + di
k <- length(ai)
if (drop00) {
id00 <- c(ai == 0L & ci == 0L) | c(bi == 0L & di == 0L)
id00[is.na(id00)] <- FALSE
ai[id00] <- NA
bi[id00] <- NA
ci[id00] <- NA
di[id00] <- NA
}
ai.u <- ai
bi.u <- bi
ci.u <- ci
di.u <- di
n1i.u <- ai + bi
n2i.u <- ci + di
if (to == "all") {
ai <- ai + add
ci <- ci + add
if (!onlyo1) {
bi <- bi + add
di <- di + add
}
}
if (to == "only0" || to == "if0all") {
id0 <- c(ai == 0L | ci == 0L | bi == 0L | di == 0L)
id0[is.na(id0)] <- FALSE
}
if (to == "only0") {
ai[id0] <- ai[id0] + add
ci[id0] <- ci[id0] + add
if (!onlyo1) {
bi[id0] <- bi[id0] + add
di[id0] <- di[id0] + add
}
}
if (to == "if0all") {
if (any(id0)) {
ai <- ai + add
ci <- ci + add
if (!onlyo1) {
bi <- bi + add
di <- di + add
}
}
}
n1i <- ai + bi
n2i <- ci + di
ni <- n1i + n2i
p1i.u <- ai.u/n1i.u
p2i.u <- ci.u/n2i.u
p1i <- ai/n1i
p2i <- ci/n2i
if (measure == "RR") {
if (addyi) {
yi <- log(p1i) - log(p2i)
} else {
yi <- log(p1i.u) - log(p2i.u)
}
if (addvi) {
vi <- 1/ai - 1/n1i + 1/ci - 1/n2i
} else {
vi <- 1/ai.u - 1/n1i.u + 1/ci.u - 1/n2i.u
}
}
if (is.element(measure, c("OR","OR2D","OR2DN","OR2DL"))) {
if (addyi) {
yi <- log(p1i/(1-p1i)) - log(p2i/(1-p2i))
} else {
yi <- log(p1i.u/(1-p1i.u)) - log(p2i.u/(1-p2i.u))
}
if (addvi) {
vi <- 1/ai + 1/bi + 1/ci + 1/di
} else {
vi <- 1/ai.u + 1/bi.u + 1/ci.u + 1/di.u
}
}
if (measure == "RD") {
if (addyi) {
yi <- p1i - p2i
} else {
yi <- p1i.u - p2i.u
}
if (length(vtype) == 1L)
vtype <- rep(vtype, k)
vi <- rep(NA_real_, k)
if (addvi) {
mnwp1i <- .wmean(p1i, n1i, na.rm=TRUE)
mnwp2i <- .wmean(p2i, n2i, na.rm=TRUE)
} else {
mnwp1i.u <- .wmean(p1i.u, n1i.u, na.rm=TRUE)
mnwp2i.u <- .wmean(p2i.u, n2i.u, na.rm=TRUE)
}
if (!all(is.element(vtype, c("UB","LS","AV"))))
stop(mstyle$stop("For this outcome measure, 'vtype' must be either 'UB', 'LS', or 'AV'."))
for (i in seq_len(k)) {
if (vtype[i] == "UB") {
if (addvi) {
vi[i] <- p1i[i]*(1-p1i[i])/(n1i[i]-1) + p2i[i]*(1-p2i[i])/(n2i[i]-1)
} else {
vi[i] <- p1i.u[i]*(1-p1i.u[i])/(n1i.u[i]-1) + p2i.u[i]*(1-p2i.u[i])/(n2i.u[i]-1)
}
}
if (vtype[i] == "LS") {
if (addvi) {
vi[i] <- p1i[i]*(1-p1i[i])/n1i[i] + p2i[i]*(1-p2i[i])/n2i[i]
} else {
vi[i] <- p1i.u[i]*(1-p1i.u[i])/n1i.u[i] + p2i.u[i]*(1-p2i.u[i])/n2i.u[i]
}
}
if (vtype[i] == "AV") {
if (addvi) {
vi[i] <- mnwp1i*(1-mnwp1i)/n1i[i] + mnwp2i*(1-mnwp2i)/n2i[i]
} else {
vi[i] <- mnwp1i.u*(1-mnwp1i.u)/n1i.u[i] + mnwp2i.u*(1-mnwp2i.u)/n2i.u[i]
}
}
}
}
if (measure == "PETO") {
xt <- ai + ci
yt <- bi + di
Ei <- xt * n1i / ni
Vi <- xt * yt * (n1i/ni) * (n2i/ni) / (ni - 1)
yi <- (ai - Ei) / Vi
vi <- 1/Vi
}
if (measure == "AS") {
yi <- asin(sqrt(p1i)) - asin(sqrt(p2i))
vi <- 1/(4*n1i) + 1/(4*n2i)
}
if (measure == "PHI") {
yi <- (ai*di - bi*ci)/sqrt((ai+bi)*(ci+di)*(ai+ci)*(bi+di))
if (length(vtype) == 1L)
vtype <- rep(vtype, k)
vi <- rep(NA_real_, k)
q1i <- 1 - p1i
q2i <- 1 - p2i
pi1. <- (ai+bi)/ni
pi2. <- (ci+di)/ni
pi.1 <- (ai+ci)/ni
pi.2 <- (bi+di)/ni
if (!all(is.element(vtype, c("ST","LS","CS"))))
stop(mstyle$stop("For this outcome measure, 'vtype' must be either 'ST', 'LS', or 'CS'."))
for (i in seq_len(k)) {
if (vtype[i] == "ST") {
vi[i] <- ((n1i[i]+n2i[i])^2*(4*n1i[i]^3*p1i[i]^2*p2i[i]*q1i[i]^2*q2i[i] + 4*n2i[i]^3*p1i[i]*p2i[i]^2*q1i[i]*q2i[i]^2 + n1i[i]*n2i[i]^2*p2i[i]*q2i[i]*(p2i[i]*q1i[i] + p1i[i]*q2i[i])*(p2i[i]*q1i[i] + p1i[i]*(4*q1i[i] + q2i[i])) + n1i[i]^2*n2i[i]*p1i[i]*q1i[i]*(p2i[i]*q1i[i] + p1i[i]*q2i[i])*(p1i[i]*q2i[i] + p2i[i]*(q1i[i] + 4*q2i[i]))))/(4*(ai[i]+ci[i])^3*(bi[i]+di[i])^3)
}
if (vtype[i] == "LS" || vtype[i] == "CS") {
vi[i] <- 1/ni[i] * (1 - yi[i]^2 + yi[i]*(1+1/2*yi[i]^2) * (pi1.[i]-pi2.[i])*(pi.1[i]-pi.2[i]) / sqrt(pi1.[i]*pi2.[i]*pi.1[i]*pi.2[i]) - 3/4 * yi[i]^2 * ((pi1.[i]-pi2.[i])^2/(pi1.[i]*pi2.[i]) + (pi.1[i]-pi.2[i])^2/(pi.1[i]*pi.2[i])))
}
}
}
if (measure == "YUQ") {
yi <- (ai/bi)/(ci/di)
yi <- (yi-1)/(yi+1)
vi <- 1/4 * (1-yi^2)^2 * (1/ai + 1/bi + 1/ci + 1/di)
}
if (measure == "YUY") {
yi <- (ai/bi)/(ci/di)
yi <- (sqrt(yi)-1)/(sqrt(yi)+1)
vi <- 1/16 * (1-yi^2)^2 * (1/ai + 1/bi + 1/ci + 1/di)
}
if (measure == "RTET") {
yi <- rep(NA_real_, k)
vi <- rep(NA_real_, k)
for (i in seq_len(k)) {
if (is.na(ai[i]) || is.na(bi[i]) || is.na(ci[i]) || is.na(di[i]))
next
res <- .rtet(ai[i], bi[i], ci[i], di[i], maxcor=.9999)
yi[i] <- res$yi
vi[i] <- res$vi
}
}
if (measure == "PBIT") {
z1i <- qnorm(p1i)
z2i <- qnorm(p2i)
yi <- z1i - z2i
vi <- 2*pi*p1i*(1-p1i)*exp(z1i^2)/n1i + 2*pi*p2i*(1-p2i)*exp(z2i^2)/n2i
}
if (is.element(measure, c("OR2D","OR2DL"))) {
yi <- sqrt(3) / pi * yi
vi <- 3 / pi^2 * vi
}
if (measure == "OR2DN") {
yi <- yi / 1.65
vi <- vi / 1.65^2
}
if (is.element(measure, c("MPRD","MPRR","MPOR"))) {
pi12 <- bi/ni
pi21 <- ci/ni
pi1. <- (ai+bi)/ni
pi.1 <- (ai+ci)/ni
}
if (measure == "MPRD") {
yi <- pi1. - pi.1
vi <- pi12*(1-pi12)/ni + 2*pi12*pi21/ni + pi21*(1-pi21)/ni
}
if (measure == "MPRR") {
yi <- log(pi1.) - log(pi.1)
vi <- (pi12 + pi21) / (ni * pi1. * pi.1)
}
if (measure == "MPOR") {
yi <- log(pi1./(1-pi1.)) - log(pi.1/(1-pi.1))
vi <- (pi12*(1-pi12) + pi21*(1-pi21) + 2*pi12*pi21) / (ni * pi1.*(1-pi1.) * pi.1*(1-pi.1))
}
if (measure == "MPORC") {
yi <- log(bi) - log(ci)
vi <- 1/bi + 1/ci
}
if (measure == "MPPETO") {
Ei <- (bi + ci) / 2
Vi <- (bi + ci) / 4
yi <- (bi - Ei) / Vi
vi <- 1/Vi
}
}
if (is.element(measure, c("IRR","IRD","IRSD"))) {
mf.x1i <- mf[[match("x1i", names(mf))]]
mf.x2i <- mf[[match("x2i", names(mf))]]
mf.t1i <- mf[[match("t1i", names(mf))]]
mf.t2i <- mf[[match("t2i", names(mf))]]
x1i <- eval(mf.x1i, data, enclos=sys.frame(sys.parent()))
x2i <- eval(mf.x2i, data, enclos=sys.frame(sys.parent()))
t1i <- eval(mf.t1i, data, enclos=sys.frame(sys.parent()))
t2i <- eval(mf.t2i, data, enclos=sys.frame(sys.parent()))
k.all <- length(x1i)
if (length(x1i)==0L || length(x2i)==0L || length(t1i)==0L || length(t2i)==0L)
stop(mstyle$stop("Cannot compute outcomes. Check that all of the required \n information is specified via the appropriate arguments."))
if (!all(k.all == c(length(x1i),length(x2i),length(t1i),length(t2i))))
stop(mstyle$stop("Supplied data vectors are not all of the same length."))
if (!is.null(subset)) {
subset <- .setnafalse(subset, k=k.all)
x1i <- x1i[subset]
x2i <- x2i[subset]
t1i <- t1i[subset]
t2i <- t2i[subset]
}
if (any(c(x1i, x2i) < 0, na.rm=TRUE))
stop(mstyle$stop("One or more counts are negative."))
if (any(c(t1i, t2i) <= 0, na.rm=TRUE))
stop(mstyle$stop("One or more person-times are <= 0."))
ni.u <- t1i + t2i
k <- length(x1i)
if (drop00) {
id00 <- c(x1i == 0L & x2i == 0L)
id00[is.na(id00)] <- FALSE
x1i[id00] <- NA
x2i[id00] <- NA
}
x1i.u <- x1i
x2i.u <- x2i
if (to == "all") {
x1i <- x1i + add
x2i <- x2i + add
}
if (to == "only0" || to == "if0all") {
id0 <- c(x1i == 0L | x2i == 0L)
id0[is.na(id0)] <- FALSE
}
if (to == "only0") {
x1i[id0] <- x1i[id0] + add
x2i[id0] <- x2i[id0] + add
}
if (to == "if0all") {
if (any(id0)) {
x1i <- x1i + add
x2i <- x2i + add
}
}
ir1i.u <- x1i.u/t1i
ir2i.u <- x2i.u/t2i
ir1i <- x1i/t1i
ir2i <- x2i/t2i
if (measure == "IRR") {
if (addyi) {
yi <- log(ir1i) - log(ir2i)
} else {
yi <- log(ir1i.u) - log(ir2i.u)
}
if (addvi) {
vi <- 1/x1i + 1/x2i
} else {
vi <- 1/x1i.u + 1/x2i.u
}
}
if (measure == "IRD") {
if (addyi) {
yi <- ir1i - ir2i
} else {
yi <- ir1i.u - ir2i.u
}
if (addvi) {
vi <- ir1i/t1i + ir2i/t2i
} else {
vi <- ir1i.u/t1i + ir2i.u/t2i
}
}
if (measure == "IRSD") {
if (addyi) {
yi <- sqrt(ir1i) - sqrt(ir2i)
} else {
yi <- sqrt(ir1i.u) - sqrt(ir2i.u)
}
vi <- 1/(4*t1i) + 1/(4*t2i)
}
}
if (is.element(measure, c("MD","SMD","SMDH","ROM","RPB","RBIS","D2OR","D2ORN","D2ORL","CVR","VR"))) {
mf.m1i <- mf[[match("m1i", names(mf))]]
mf.m2i <- mf[[match("m2i", names(mf))]]
mf.sd1i <- mf[[match("sd1i", names(mf))]]
mf.sd2i <- mf[[match("sd2i", names(mf))]]
mf.n1i <- mf[[match("n1i", names(mf))]]
mf.n2i <- mf[[match("n2i", names(mf))]]
m1i <- eval(mf.m1i, data, enclos=sys.frame(sys.parent()))
m2i <- eval(mf.m2i, data, enclos=sys.frame(sys.parent()))
sd1i <- eval(mf.sd1i, data, enclos=sys.frame(sys.parent()))
sd2i <- eval(mf.sd2i, data, enclos=sys.frame(sys.parent()))
n1i <- eval(mf.n1i, data, enclos=sys.frame(sys.parent()))
n2i <- eval(mf.n2i, data, enclos=sys.frame(sys.parent()))
k.all <- length(n1i)
if (is.element(measure, c("MD","SMD","SMDH","ROM","RPB","RBIS","D2OR","D2ORN","D2ORL","CVR"))) {
if (length(m1i)==0L || length(m2i)==0L || length(sd1i)==0L || length(sd2i)==0L || length(n1i)==0L || length(n2i)==0L)
stop(mstyle$stop("Cannot compute outcomes. Check that all of the required \n information is specified via the appropriate arguments."))
if (!all(k.all == c(length(m1i),length(m2i),length(sd1i),length(sd2i),length(n1i),length(n2i))))
stop(mstyle$stop("Supplied data vectors are not all of the same length."))
}
if (is.element(measure, c("VR"))) {
if (length(sd1i)==0L || length(sd2i)==0L || length(n1i)==0L || length(n2i)==0L)
stop(mstyle$stop("Cannot compute outcomes. Check that all of the required \n information is specified via the appropriate arguments."))
if (!all(k.all == c(length(sd1i),length(sd2i),length(n1i),length(n2i))))
stop(mstyle$stop("Supplied data vectors are not all of the same length."))
}
if (!is.null(subset)) {
subset <- .setnafalse(subset, k=k.all)
m1i <- m1i[subset]
m2i <- m2i[subset]
sd1i <- sd1i[subset]
sd2i <- sd2i[subset]
n1i <- n1i[subset]
n2i <- n2i[subset]
}
if (any(c(sd1i, sd2i) < 0, na.rm=TRUE))
stop(mstyle$stop("One or more standard deviations are negative."))
if (any(c(n1i, n2i) < 1, na.rm=TRUE))
stop(mstyle$stop("One or more sample sizes are < 1."))
ni.u <- n1i + n2i
k <- length(n1i)
ni <- ni.u
mi <- ni - 2
sdpi <- sqrt(((n1i-1)*sd1i^2 + (n2i-1)*sd2i^2)/mi)
di <- (m1i - m2i) / sdpi
if (measure == "MD") {
yi <- m1i - m2i
if (length(vtype) == 1L)
vtype <- rep(vtype, k)
vi <- rep(NA_real_, k)
if (!all(is.element(vtype, c("UB","LS","HO"))))
stop(mstyle$stop("For this outcome measure, 'vtype' must be either 'UB', 'LS', or 'HO'."))
for (i in seq_len(k)) {
if (vtype[i] == "UB" || vtype[i] == "LS")
vi[i] <- sd1i[i]^2/n1i[i] + sd2i[i]^2/n2i[i]
if (vtype[i] == "HO")
vi[i] <- sdpi[i]^2 * (1/n1i[i] + 1/n2i[i])
}
}
if (measure == "SMD") {
cmi <- .cmicalc(mi)
yi <- cmi * di
if (length(vtype) == 1L)
vtype <- rep(vtype, k)
vi <- rep(NA_real_, k)
mnwyi <- .wmean(yi, ni, na.rm=TRUE)
if (!all(is.element(vtype, c("UB","LS","LS2","AV"))))
stop(mstyle$stop("For this outcome measure, 'vtype' must be either 'UB', 'LS', 'LS2', or 'AV'."))
for (i in seq_len(k)) {
if (vtype[i] == "UB")
vi[i] <- 1/n1i[i] + 1/n2i[i] + (1 - (mi[i]-2)/(mi[i]*cmi[i]^2)) * yi[i]^2
if (vtype[i] == "LS")
vi[i] <- 1/n1i[i] + 1/n2i[i] + yi[i]^2/(2*ni[i])
if (vtype[i] == "AV")
vi[i] <- 1/n1i[i] + 1/n2i[i] + mnwyi^2/(2*ni[i])
if (vtype[i] == "LS2")
vi[i] <- cmi[i]^2 * (1/n1i[i] + 1/n2i[i] + di[i]^2/(2*ni[i]))
}
}
if (measure == "SMDH") {
cmi <- .cmicalc(mi)
si <- sqrt((sd1i^2 + sd2i^2)/2)
yi <- cmi * (m1i - m2i) / si
vi <- yi^2 * (sd1i^4 / (n1i-1) + sd2i^4 / (n2i-1)) / (2*(sd1i^2 + sd2i^2)^2) + (sd1i^2 / (n1i-1) + sd2i^2 / (n2i-1)) / ((sd1i^2 + sd2i^2)/2)
vi <- cmi^2 * vi
}
if (measure == "ROM") {
yi <- log(m1i/m2i)
if (length(vtype) == 1L)
vtype <- rep(vtype, k)
vi <- rep(NA_real_, k)
mn1wcvi <- .wmean(sd1i/m1i, n1i, na.rm=TRUE)
mn2wcvi <- .wmean(sd2i/m2i, n2i, na.rm=TRUE)
not.na <- !(is.na(n1i) | is.na(n2i) | is.na(sd1i/m1i) | is.na(sd2i/m2i))
mnwcvi <- (sum(n1i[not.na]*(sd1i/m1i)[not.na]) + sum(n2i[not.na]*(sd2i/m2i)[not.na])) / sum((n1i+n2i)[not.na])
if (!all(is.element(vtype, c("LS","HO","AV","AVHO"))))
stop(mstyle$stop("For this outcome measure, 'vtype' must be either 'LS', 'HO', 'AV', or 'AVHO'."))
for (i in seq_len(k)) {
if (vtype[i] == "LS")
vi[i] <- sd1i[i]^2/(n1i[i]*m1i[i]^2) + sd2i[i]^2/(n2i[i]*m2i[i]^2)
if (vtype[i] == "HO")
vi[i] <- sdpi[i]^2/(n1i[i]*m1i[i]^2) + sdpi[i]^2/(n2i[i]*m2i[i]^2)
if (vtype[i] == "AV")
vi[i] <- mn1wcvi^2/n1i[i] + mn2wcvi^2/n2i[i]
if (vtype[i] == "AVHO")
vi[i] <- mnwcvi^2 * (1/n1i[i] + 1/n2i[i])
}
}
if (is.element(measure, c("RPB","RBIS"))) {
hi <- mi/n1i + mi/n2i
yi <- di / sqrt(di^2 + hi)
if (measure == "RPB") {
if (length(vtype) == 1L)
vtype <- rep(vtype, k)
vi <- rep(NA_real_, k)
if (!all(is.element(vtype, c("ST","LS","CS"))))
stop(mstyle$stop("For this outcome measure, 'vtype' must be either 'ST', 'LS', or 'CS'."))
for (i in seq_len(k)) {
if (vtype[i] == "ST" || vtype[i] == "LS")
vi[i] <- hi[i]^2 / (hi[i] + di[i]^2)^3 * (1/n1i[i] + 1/n2i[i] + di[i]^2/(2*ni[i]))
if (vtype[i] == "CS")
vi[i] <- (1-yi[i]^2)^2 * (ni[i]*yi[i]^2 / (4*n1i[i]*n2i[i]) + (2-3*yi[i]^2)/(2*ni[i]))
}
}
}
if (measure == "RBIS") {
p1i <- n1i / ni
p2i <- n2i / ni
zi <- qnorm(p1i, lower.tail=FALSE)
fzi <- dnorm(zi)
yi <- sqrt(p1i*p2i) / fzi * yi
yi.t <- ifelse(abs(yi) > 1, sign(yi), yi)
vi <- 1/(ni-1) * (p1i*p2i/fzi^2 - (3/2 + (1 - p1i*zi/fzi)*(1 + p2i*zi/fzi)) * yi.t^2 + yi.t^4)
}
if (is.element(measure, c("D2OR","D2ORL"))) {
yi <- pi / sqrt(3) * di
vi <- pi^2 / 3 * (1/n1i + 1/n2i + di^2/(2*ni))
}
if (measure == "D2ORN") {
yi <- 1.65 * di
vi <- 1.65^2 * (1/n1i + 1/n2i + di^2/(2*ni))
}
if (measure == "CVR") {
yi <- log(sd1i/m1i) + 1/(2*(n1i-1)) - log(sd2i/m2i) - 1/(2*(n2i-1))
vi <- 1/(2*(n1i-1)) + sd1i^2/(n1i*m1i^2) + 1/(2*(n2i-1)) + sd2i^2/(n2i*m2i^2)
}
if (measure == "VR") {
yi <- log(sd1i/sd2i) + 1/(2*(n1i-1)) - 1/(2*(n2i-1))
vi <- 1/(2*(n1i-1)) + 1/(2*(n2i-1))
}
}
if (is.element(measure, c("COR","UCOR","ZCOR"))) {
mf.ri <- mf[[match("ri", names(mf))]]
mf.ni <- mf[[match("ni", names(mf))]]
ri <- eval(mf.ri, data, enclos=sys.frame(sys.parent()))
ni <- eval(mf.ni, data, enclos=sys.frame(sys.parent()))
k.all <- length(ri)
if (length(ri)==0L || length(ni)==0L)
stop(mstyle$stop("Cannot compute outcomes. Check that all of the required \n information is specified via the appropriate arguments."))
if (length(ri) != length(ni))
stop(mstyle$stop("Supplied data vectors are not of the same length."))
if (!is.null(subset)) {
subset <- .setnafalse(subset, k=k.all)
ri <- ri[subset]
ni <- ni[subset]
}
if (any(abs(ri) > 1, na.rm=TRUE))
stop(mstyle$stop("One or more correlations are > 1 or < -1."))
if (any(ni < 1, na.rm=TRUE))
stop(mstyle$stop("One or more sample sizes are < 1."))
if (measure != "UCOR" && vtype == "UB")
stop(mstyle$stop("Use of vtype='UB' only permitted when measure='UCOR'."))
if (measure == "UCOR" && any(ni <= 4, na.rm=TRUE))
warning(mstyle$warning("Cannot compute the bias-corrected correlation coefficient when ni <= 4."), call.=FALSE)
if (measure == "ZCOR" && any(ni <= 3, na.rm=TRUE))
warning(mstyle$warning("Cannot estimate the sampling variance when ni <= 3."), call.=FALSE)
ni.u <- ni
k <- length(ri)
if (measure == "COR")
yi <- ri
if (measure == "UCOR") {
yi <- ri * .Fcalc(1/2, 1/2, (ni-2)/2, 1-ri^2)
}
if (is.element(measure, c("COR","UCOR"))) {
if (length(vtype) == 1L)
vtype <- rep(vtype, k)
vi <- rep(NA_real_, k)
mnwyi <- .wmean(yi, ni, na.rm=TRUE)
if (!all(is.element(vtype, c("UB","LS","AV"))))
stop(mstyle$stop("For this outcome measure, 'vtype' must be either 'UB', 'LS', or 'AV'."))
for (i in seq_len(k)) {
if (vtype[i] == "UB") {
vi[i] <- yi[i]^2 - (1 - (ni[i]-3)/(ni[i]-2) * (1-ri[i]^2) * .Fcalc(1, 1, ni[i]/2, 1-ri[i]^2))
}
if (vtype[i] == "LS")
vi[i] <- (1-yi[i]^2)^2/(ni[i]-1)
if (vtype[i] == "AV")
vi[i] <- (1-mnwyi^2)^2/(ni[i]-1)
}
}
if (measure == "ZCOR") {
yi <- 1/2 * log((1+ri)/(1-ri))
vi <- 1/(ni-3)
}
vi[ni <= 3] <- NA
}
if (is.element(measure, c("PCOR","ZPCOR","SPCOR"))) {
mf.ti <- mf[[match("ti", names(mf))]]
mf.r2i <- mf[[match("r2i", names(mf))]]
mf.mi <- mf[[match("mi", names(mf))]]
mf.ni <- mf[[match("ni", names(mf))]]
ti <- eval(mf.ti, data, enclos=sys.frame(sys.parent()))
r2i <- eval(mf.r2i, data, enclos=sys.frame(sys.parent()))
mi <- eval(mf.mi, data, enclos=sys.frame(sys.parent()))
ni <- eval(mf.ni, data, enclos=sys.frame(sys.parent()))
k.all <- length(ti)
if (measure=="PCOR" && (length(ti)==0L || length(ni)==0L || length(mi)==0L))
stop(mstyle$stop("Cannot compute outcomes. Check that all of the required \n information is specified via the appropriate arguments."))
if (measure=="SPCOR" && (length(ti)==0L || length(ni)==0L || length(mi)==0L || length(r2i)==0L))
stop(mstyle$stop("Cannot compute outcomes. Check that all of the required \n information is specified via the appropriate arguments."))
if (measure=="PCOR" && !all(k.all == c(length(ni),length(mi))))
stop(mstyle$stop("Supplied data vectors are not all of the same length."))
if (measure=="SPCOR" && !all(k.all == c(length(ni),length(mi),length(r2i))))
stop(mstyle$stop("Supplied data vectors are not all of the same length."))
if (!is.null(subset)) {
subset <- .setnafalse(subset, k=k.all)
ti <- ti[subset]
r2i <- r2i[subset]
mi <- mi[subset]
ni <- ni[subset]
}
if (measure=="SPCOR" && any(r2i > 1 | r2i < 0, na.rm=TRUE))
stop(mstyle$stop("One or more R^2 values are > 1 or < 0."))
if (any(ni < 1, na.rm=TRUE))
stop(mstyle$stop("One or more sample sizes are < 1."))
if (any(mi < 0, na.rm=TRUE))
stop(mstyle$stop("One or more mi values are negative."))
if (any(ni - mi - 1 < 1, na.rm=TRUE))
stop(mstyle$stop("One or more dfs are < 1."))
ni.u <- ni
k <- length(ti)
if (measure == "PCOR") {
yi <- ti / sqrt(ti^2 + (ni - mi - 1))
if (length(vtype) == 1L)
vtype <- rep(vtype, k)
vi <- rep(NA_real_, k)
mnwyi <- .wmean(yi, ni, na.rm=TRUE)
if (!all(is.element(vtype, c("LS","AV"))))
stop(mstyle$stop("For this outcome measure, 'vtype' must be either 'LS' or 'AV'."))
for (i in seq_len(k)) {
if (vtype[i] == "LS")
vi[i] <- (1 - yi[i]^2)^2 / (ni[i] - mi[i] - 1)
if (vtype[i] == "AV")
vi[i] <- (1 - mnwyi^2)^2 / (ni[i] - mi[i] - 1)
}
}
if (measure == "ZPCOR") {
yi <- ti / sqrt(ti^2 + (ni - mi - 1))
yi <- 1/2 * log((1+yi)/(1-yi))
vi <- 1/(ni-mi-1)
}
if (measure == "SPCOR") {
yi <- ti * sqrt(1 - r2i) / sqrt(ni - mi - 1)
if (length(vtype) == 1L)
vtype <- rep(vtype, k)
vi <- rep(NA_real_, k)
mnwyi <- .wmean(yi, ni, na.rm=TRUE)
if (!all(is.element(vtype, c("LS","AV"))))
stop(mstyle$stop("For this outcome measure, 'vtype' must be either 'LS' or 'AV'."))
for (i in seq_len(k)) {
if (vtype[i] == "LS")
vi[i] <- (r2i[i]^2 - 2*r2i[i] + (r2i[i] - yi[i]^2) + 1 - (r2i[i] - yi[i]^2)^2) / ni[i]
if (vtype[i] == "AV")
vi[i] <- (r2i[i]^2 - 2*r2i[i] + (r2i[i] - mnwyi^2) + 1 - (r2i[i] - mnwyi^2)^2) / ni[i]
}
}
}
if (is.element(measure, c("PR","PLN","PLO","PAS","PFT"))) {
mf.xi <- mf[[match("xi", names(mf))]]
mf.mi <- mf[[match("mi", names(mf))]]
mf.ni <- mf[[match("ni", names(mf))]]
xi <- eval(mf.xi, data, enclos=sys.frame(sys.parent()))
mi <- eval(mf.mi, data, enclos=sys.frame(sys.parent()))
ni <- eval(mf.ni, data, enclos=sys.frame(sys.parent()))
if (is.null(mi)) mi <- ni - xi
k.all <- length(xi)
if (length(xi)==0L || length(mi)==0L)
stop(mstyle$stop("Cannot compute outcomes. Check that all of the required \n information is specified via the appropriate arguments."))
if (length(xi) != length(mi))
stop(mstyle$stop("Supplied data vectors are not all of the same length."))
if (!is.null(subset)) {
subset <- .setnafalse(subset, k=k.all)
xi <- xi[subset]
mi <- mi[subset]
}
ni <- xi + mi
if (any(xi > ni, na.rm=TRUE))
stop(mstyle$stop("One or more event counts are larger than the corresponding group sizes."))
if (any(c(xi, mi) < 0, na.rm=TRUE))
stop(mstyle$stop("One or more counts are negative."))
if (any(ni < 1, na.rm=TRUE))
stop(mstyle$stop("One or more group sizes are < 1."))
ni.u <- ni
k <- length(xi)
xi.u <- xi
mi.u <- mi
k <- length(xi)
if (to == "all") {
xi <- xi + add
mi <- mi + add
}
if (to == "only0" || to == "if0all") {
id0 <- c(xi == 0L | mi == 0L)
id0[is.na(id0)] <- FALSE
}
if (to == "only0") {
xi[id0] <- xi[id0] + add
mi[id0] <- mi[id0] + add
}
if (to == "if0all") {
if (any(id0)) {
xi <- xi + add
mi <- mi + add
}
}
ni <- xi + mi
pri.u <- xi.u/ni.u
pri <- xi/ni
if (measure == "PR") {
if (addyi) {
yi <- pri
} else {
yi <- pri.u
}
if (length(vtype) == 1L)
vtype <- rep(vtype, k)
vi <- rep(NA_real_, k)
if (addvi) {
mnwpri <- .wmean(pri, ni, na.rm=TRUE)
} else {
mnwpri.u <- .wmean(pri.u, ni.u, na.rm=TRUE)
}
if (!all(is.element(vtype, c("UB","LS","AV"))))
stop(mstyle$stop("For this outcome measure, 'vtype' must be either 'UB', 'LS', or 'AV'."))
for (i in seq_len(k)) {
if (vtype[i] == "UB") {
if (addvi) {
vi[i] <- pri[i]*(1-pri[i])/(ni[i]-1)
} else {
vi[i] <- pri.u[i]*(1-pri.u[i])/(ni.u[i]-1)
}
}
if (vtype[i] == "LS") {
if (addvi) {
vi[i] <- pri[i]*(1-pri[i])/ni[i]
} else {
vi[i] <- pri.u[i]*(1-pri.u[i])/ni.u[i]
}
}
if (vtype[i] == "AV") {
if (addvi) {
vi[i] <- mnwpri*(1-mnwpri)/ni[i]
} else {
vi[i] <- mnwpri.u*(1-mnwpri.u)/ni.u[i]
}
}
}
}
if (measure == "PLN") {
if (addyi) {
yi <- log(pri)
} else {
yi <- log(pri.u)
}
if (length(vtype) == 1L)
vtype <- rep(vtype, k)
vi <- rep(NA_real_, k)
if (addvi) {
mnwpri <- .wmean(pri, ni, na.rm=TRUE)
} else {
mnwpri.u <- .wmean(pri.u, ni.u, na.rm=TRUE)
}
if (!all(is.element(vtype, c("LS","AV"))))
stop(mstyle$stop("For this outcome measure, 'vtype' must be either 'LS' or 'AV'."))
for (i in seq_len(k)) {
if (vtype[i] == "LS") {
if (addvi) {
vi[i] <- 1/xi[i] - 1/ni[i]
} else {
vi[i] <- 1/xi.u[i] - 1/ni.u[i]
}
}
if (vtype[i] == "AV") {
if (addvi) {
vi[i] <- 1/(mnwpri*ni[i]) - 1/ni[i]
} else {
vi[i] <- 1/(mnwpri.u*ni.u[i]) - 1/ni.u[i]
}
}
}
}
if (measure == "PLO") {
if (addyi) {
yi <- log(pri/(1-pri))
} else {
yi <- log(pri.u/(1-pri.u))
}
if (length(vtype) == 1L)
vtype <- rep(vtype, k)
vi <- rep(NA_real_, k)
if (addvi) {
mnwpri <- .wmean(pri, ni, na.rm=TRUE)
} else {
mnwpri.u <- .wmean(pri.u, ni.u, na.rm=TRUE)
}
if (!all(is.element(vtype, c("LS","AV"))))
stop(mstyle$stop("For this outcome measure, 'vtype' must be either 'LS' or 'AV'."))
for (i in seq_len(k)) {
if (vtype[i] == "LS") {
if (addvi) {
vi[i] <- 1/xi[i] + 1/mi[i]
} else {
vi[i] <- 1/xi.u[i] + 1/mi.u[i]
}
}
if (vtype[i] == "AV") {
if (addvi) {
vi[i] <- 1/(mnwpri*ni[i]) + 1/((1-mnwpri)*ni[i])
} else {
vi[i] <- 1/(mnwpri.u*ni.u[i]) + 1/((1-mnwpri.u)*ni.u[i])
}
}
}
}
if (measure == "PAS") {
yi <- asin(sqrt(pri))
vi <- 1/(4*ni)
}
if (measure == "PFT") {
yi <- 1/2*(asin(sqrt(xi/(ni+1))) + asin(sqrt((xi+1)/(ni+1))))
vi <- 1/(4*ni + 2)
}
}
if (is.element(measure, c("IR","IRLN","IRS","IRFT"))) {
mf.xi <- mf[[match("xi", names(mf))]]
mf.ti <- mf[[match("ti", names(mf))]]
xi <- eval(mf.xi, data, enclos=sys.frame(sys.parent()))
ti <- eval(mf.ti, data, enclos=sys.frame(sys.parent()))
k.all <- length(xi)
if (length(xi)==0L || length(ti)==0L)
stop(mstyle$stop("Cannot compute outcomes. Check that all of the required \n information is specified via the appropriate arguments."))
if (length(xi) != length(ti))
stop(mstyle$stop("Supplied data vectors are not all of the same length."))
if (!is.null(subset)) {
subset <- .setnafalse(subset, k=k.all)
xi <- xi[subset]
ti <- ti[subset]
}
if (any(xi < 0, na.rm=TRUE))
stop(mstyle$stop("One or more counts are negative."))
if (any(ti <= 0, na.rm=TRUE))
stop(mstyle$stop("One or more person-times are <= 0."))
ni.u <- ti
k <- length(xi)
xi.u <- xi
if (to == "all") {
xi <- xi + add
}
if (to == "only0" || to == "if0all") {
id0 <- c(xi == 0L)
id0[is.na(id0)] <- FALSE
}
if (to == "only0") {
xi[id0] <- xi[id0] + add
}
if (to == "if0all") {
if (any(id0)) {
xi <- xi + add
}
}
iri.u <- xi.u/ti
iri <- xi/ti
if (measure == "IR") {
if (addyi) {
yi <- iri
} else {
yi <- iri.u
}
if (addvi) {
vi <- iri/ti
} else {
vi <- iri.u/ti
}
}
if (measure == "IRLN") {
if (addyi) {
yi <- log(iri)
} else {
yi <- log(iri.u)
}
if (addvi) {
vi <- 1/xi
} else {
vi <- 1/xi.u
}
}
if (measure == "IRS") {
if (addyi) {
yi <- sqrt(iri)
} else {
yi <- sqrt(iri.u)
}
vi <- 1/(4*ti)
}
if (measure == "IRFT") {
yi <- 1/2*(sqrt(iri) + sqrt(iri+1/ti))
vi <- 1/(4*ti)
}
}
if (is.element(measure, c("MN","MNLN","CVLN","SDLN","SMD1"))) {
mf.mi <- mf[[match("mi", names(mf))]]
mf.sdi <- mf[[match("sdi", names(mf))]]
mf.ni <- mf[[match("ni", names(mf))]]
mi <- eval(mf.mi, data, enclos=sys.frame(sys.parent()))
sdi <- eval(mf.sdi, data, enclos=sys.frame(sys.parent()))
ni <- eval(mf.ni, data, enclos=sys.frame(sys.parent()))
k.all <- length(ni)
if (is.element(measure, c("MN","MNLN","CVLN","SMD1"))) {
if (length(mi)==0L || length(sdi)==0L || length(ni)==0L)
stop(mstyle$stop("Cannot compute outcomes. Check that all of the required \n information is specified via the appropriate arguments."))
if (!all(k.all == c(length(mi),length(sdi),length(ni))))
stop(mstyle$stop("Supplied data vectors are not all of the same length."))
}
if (is.element(measure, c("SDLN"))) {
if (length(sdi)==0L || length(ni)==0L)
stop(mstyle$stop("Cannot compute outcomes. Check that all of the required \n information is specified via the appropriate arguments."))
if (length(sdi) != length(ni))
stop(mstyle$stop("Supplied data vectors are not all of the same length."))
}
if (!is.null(subset)) {
subset <- .setnafalse(subset, k=k.all)
mi <- mi[subset]
sdi <- sdi[subset]
ni <- ni[subset]
}
if (any(sdi < 0, na.rm=TRUE))
stop(mstyle$stop("One or more standard deviations are negative."))
if (any(ni < 1, na.rm=TRUE))
stop(mstyle$stop("One or more sample sizes are < 1."))
if (is.element(measure, c("MNLN","CVLN")) && any(mi < 0, na.rm=TRUE))
stop(mstyle$stop("One or more means are negative."))
ni.u <- ni
k <- length(ni)
if (measure == "MN") {
yi <- mi
vi <- sdi^2/ni
}
if (measure == "MNLN") {
yi <- log(mi)
vi <- sdi^2/(ni*mi^2)
}
if (measure == "CVLN") {
yi <- log(sdi/mi) + 1/(2*(ni-1))
vi <- 1/(2*(ni-1)) + sdi^2/(ni*mi^2)
}
if (measure == "SDLN") {
yi <- log(sdi) + 1/(2*(ni-1))
vi <- 1/(2*(ni-1))
}
if (measure == "SMD1") {
cmi <- .cmicalc(ni-1)
yi <- cmi * mi / sdi
vi <- 1/ni + yi^2/(2*ni)
}
}
if (is.element(measure, c("MC","SMCC","SMCR","SMCRH","ROMC","CVRC","VRC"))) {
mf.m1i <- mf[[match("m1i", names(mf))]]
mf.m2i <- mf[[match("m2i", names(mf))]]
mf.sd1i <- mf[[match("sd1i", names(mf))]]
mf.sd2i <- mf[[match("sd2i", names(mf))]]
mf.ni <- mf[[match("ni", names(mf))]]
mf.ri <- mf[[match("ri", names(mf))]]
m1i <- eval(mf.m1i, data, enclos=sys.frame(sys.parent()))
m2i <- eval(mf.m2i, data, enclos=sys.frame(sys.parent()))
sd1i <- eval(mf.sd1i, data, enclos=sys.frame(sys.parent()))
sd2i <- eval(mf.sd2i, data, enclos=sys.frame(sys.parent()))
ni <- eval(mf.ni, data, enclos=sys.frame(sys.parent()))
ri <- eval(mf.ri, data, enclos=sys.frame(sys.parent()))
k.all <- length(ni)
if (is.element(measure, c("MC","SMCC","SMCRH","ROMC","CVRC"))) {
if (length(m1i)==0L || length(m2i)==0L || length(sd1i)==0L || length(sd2i)==0L || length(ni)==0L || length(ri)==0L)
stop(mstyle$stop("Cannot compute outcomes. Check that all of the required \n information is specified via the appropriate arguments."))
if (!all(k.all == c(length(m1i),length(m2i),length(sd1i),length(sd2i),length(ni),length(ri))))
stop(mstyle$stop("Supplied data vectors are not all of the same length."))
}
if (is.element(measure, c("SMCR"))) {
if (length(m1i)==0L || length(m2i)==0L || length(sd1i)==0L || length(ni)==0L || length(ri)==0L)
stop(mstyle$stop("Cannot compute outcomes. Check that all of the required \n information is specified via the appropriate arguments."))
if (!all(k.all == c(length(m1i),length(m2i),length(sd1i),length(ni),length(ri))))
stop(mstyle$stop("Supplied data vectors are not all of the same length."))
}
if (is.element(measure, c("VRC"))) {
if (length(sd1i)==0L || length(sd2i)==0L || length(ni)==0L || length(ri)==0L)
stop(mstyle$stop("Cannot compute outcomes. Check that all of the required \n information is specified via the appropriate arguments."))
if (!all(k.all == c(length(sd1i),length(sd2i),length(ni),length(ri))))
stop(mstyle$stop("Supplied data vectors are not all of the same length."))
}
if (!is.null(subset)) {
subset <- .setnafalse(subset, k=k.all)
m1i <- m1i[subset]
m2i <- m2i[subset]
sd1i <- sd1i[subset]
sd2i <- sd2i[subset]
ni <- ni[subset]
ri <- ri[subset]
}
if (is.element(measure, c("MC","SMCC","SMCRH","ROMC","CVRC","VRC"))) {
if (any(c(sd1i, sd2i) < 0, na.rm=TRUE))
stop(mstyle$stop("One or more standard deviations are negative."))
}
if (is.element(measure, c("SMCR"))) {
if (any(sd1i < 0, na.rm=TRUE))
stop(mstyle$stop("One or more standard deviations are negative."))
}
if (any(abs(ri) > 1, na.rm=TRUE))
stop(mstyle$stop("One or more correlations are > 1 or < -1."))
if (any(ni < 1, na.rm=TRUE))
stop(mstyle$stop("One or more sample sizes are < 1."))
ni.u <- ni
k <- length(ni)
ni <- ni.u
mi <- ni - 1
if (measure == "MC") {
yi <- m1i - m2i
vi <- (sd1i^2 + sd2i^2 - 2*ri*sd1i*sd2i) / ni
}
if (measure == "SMCC") {
cmi <- .cmicalc(mi)
sddi <- sqrt(sd1i^2 + sd2i^2 - 2*ri*sd1i*sd2i)
di <- (m1i - m2i) / sddi
yi <- cmi * di
if (length(vtype) == 1L)
vtype <- rep(vtype, k)
vi <- rep(NA_real_, k)
if (!all(is.element(vtype, c("LS","LS2"))))
stop(mstyle$stop("For this outcome measure, 'vtype' must be either ''LS' or 'LS2'."))
for (i in seq_len(k)) {
if (vtype[i] == "LS")
vi[i] <- 1/ni[i] + yi[i]^2 / (2*ni[i])
if (vtype[i] == "LS2")
vi[i] <- cmi[i]^2 * (1/ni[i] + di[i]^2 / (2*ni[i]))
}
}
if (measure == "SMCR") {
cmi <- .cmicalc(mi)
di <- (m1i - m2i) / sd1i
yi <- cmi * di
if (length(vtype) == 1L)
vtype <- rep(vtype, k)
vi <- rep(NA_real_, k)
if (!all(is.element(vtype, c("LS","LS2"))))
stop(mstyle$stop("For this outcome measure, 'vtype' must be either ''LS' or 'LS2'."))
for (i in seq_len(k)) {
if (vtype[i] == "LS")
vi[i] <- 2*(1-ri[i])/ni[i] + yi[i]^2 / (2*ni[i])
if (vtype[i] == "LS2")
vi[i] <- cmi[i]^2 * (2*(1-ri[i])/ni[i] + di[i]^2 / (2*ni[i]))
}
}
if (measure == "SMCRH") {
cmi <- .cmicalc(mi)
vardi <- sd1i^2 + sd2i^2 - 2*ri*sd1i*sd2i
yi <- cmi * (m1i - m2i) / sd1i
vi <- vardi/(sd1i^2*(ni-1)) + yi^2 / (2*(ni-1))
vi <- cmi^2 * vi
}
if (measure == "ROMC") {
yi <- log(m1i/m2i)
vi <- sd1i^2/(ni*m1i^2) + sd2i^2/(ni*m2i^2) - 2*ri*sd1i*sd2i/(m1i*m2i*ni)
}
if (measure == "CVRC") {
yi <- log(sd1i/m1i) - log(sd2i/m2i)
vi <- (1-ri^2)/(ni-1) + (m1i^2*sd2i^2 + m2i^2*sd1i^2 - 2*m1i*m2i*ri*sd1i*sd2i) / (m1i^2*m2i^2*ni)
}
if (measure == "VRC") {
yi <- log(sd1i/sd2i)
vi <- (1-ri^2)/(ni-1)
}
}
if (is.element(measure, c("ARAW","AHW","ABT"))) {
mf.ai <- mf[[match("ai", names(mf))]]
mf.mi <- mf[[match("mi", names(mf))]]
mf.ni <- mf[[match("ni", names(mf))]]
ai <- eval(mf.ai, data, enclos=sys.frame(sys.parent()))
mi <- eval(mf.mi, data, enclos=sys.frame(sys.parent()))
ni <- eval(mf.ni, data, enclos=sys.frame(sys.parent()))
k.all <- length(ai)
if (length(ai)==0L || length(mi)==0L || length(ni)==0L)
stop(mstyle$stop("Cannot compute outcomes. Check that all of the required \n information is specified via the appropriate arguments."))
if (!all(k.all == c(length(ai),length(mi),length(ni))))
stop(mstyle$stop("Supplied data vectors are not all of the same length."))
if (!is.null(subset)) {
subset <- .setnafalse(subset, k=k.all)
ai <- ai[subset]
mi <- mi[subset]
ni <- ni[subset]
}
if (any(ai > 1, na.rm=TRUE))
stop(mstyle$stop("One or more alpha values are > 1."))
if (any(mi < 2, na.rm=TRUE))
stop(mstyle$stop("One or more mi values are < 2."))
if (any(ni < 1, na.rm=TRUE))
stop(mstyle$stop("One or more sample sizes are < 1."))
ni.u <- ni
k <- length(ai)
if (measure == "ARAW") {
yi <- ai
vi <- 2*mi*(1-ai)^2 / ((mi-1)*(ni-2))
}
if (measure == "AHW") {
yi <- 1 - (1-ai)^(1/3)
vi <- 18*mi*(ni-1)*(1-ai)^(2/3) / ((mi-1)*(9*ni-11)^2)
}
if (measure == "ABT") {
yi <- -log(1-ai)
vi <- 2*mi / ((mi-1)*(ni-2))
}
}
} else {
mf.vi <- mf[[match("vi", names(mf))]]
mf.sei <- mf[[match("sei", names(mf))]]
mf.ni <- mf[[match("ni", names(mf))]]
vi <- eval(mf.vi, data, enclos=sys.frame(sys.parent()))
sei <- eval(mf.sei, data, enclos=sys.frame(sys.parent()))
ni <- eval(mf.ni, data, enclos=sys.frame(sys.parent()))
k.all <- length(yi)
if (is.null(vi)) {
if (is.null(sei)) {
stop(mstyle$stop("Must specify 'vi' or 'sei' argument."))
} else {
vi <- sei^2
}
}
if (length(yi) != length(vi))
stop(mstyle$stop("Supplied data vectors are not of the same length."))
if (!is.null(ni) && (length(yi) != length(ni)))
stop(mstyle$stop("Supplied data vectors are not of the same length."))
if (!is.null(subset)) {
subset <- .setnafalse(subset, k=k.all)
yi <- yi[subset]
vi <- vi[subset]
ni <- ni[subset]
}
ni.u <- ni
k <- length(yi)
}
yi <- as.vector(yi)
vi <- as.vector(vi)
is.inf <- is.infinite(yi) | is.infinite(vi)
if (any(is.inf)) {
warning(mstyle$warning("Some 'yi' and/or 'vi' values equal to +-Inf. Recoded to NAs."), call.=FALSE)
yi[is.inf] <- NA
vi[is.inf] <- NA
}
is.NaN <- is.nan(yi) | is.nan(vi)
if (any(is.NaN)) {
yi[is.NaN] <- NA
vi[is.NaN] <- NA
}
vi[vi < 0] <- NA
if (!is.null(slab)) {
if (length(slab) != k.all)
stop(mstyle$stop("Study labels not of same length as data."))
if (is.factor(slab))
slab <- as.character(slab)
if (!is.null(subset))
slab <- slab[subset]
if (anyNA(slab))
stop(mstyle$stop("NAs in study labels."))
if (anyDuplicated(slab))
slab <- .make.unique(slab)
}
if (is.null(include))
include <- rep(TRUE, k.all)
if (is.null(subset))
subset <- rep(TRUE, k.all)
if (!is.null(include))
include <- .setnafalse(include, arg="include", k=k.all)
include <- include[subset]
if (has.data && any(!subset))
data <- data[subset,,drop=FALSE]
if (has.data && append) {
dat <- data.frame(data)
if (replace || !is.element(var.names[1], names(dat))) {
yi.replace <- rep(TRUE, k)
} else {
yi.replace <- is.na(dat[[var.names[1]]])
}
if (replace || !is.element(var.names[2], names(dat))) {
vi.replace <- rep(TRUE, k)
} else {
vi.replace <- is.na(dat[[var.names[2]]])
}
if (replace || !is.element(var.names[3], names(dat))) {
measure.replace <- rep(TRUE, k)
} else {
measure.replace <- is.na(dat[[var.names[3]]]) | dat[[var.names[3]]] == ""
}
dat[[var.names[1]]][include & yi.replace] <- yi[include & yi.replace]
dat[[var.names[2]]][include & vi.replace] <- vi[include & vi.replace]
if (add.measure)
dat[[var.names[3]]][!is.na(yi) & include & measure.replace] <- measure
if (!is.null(ni.u))
attributes(dat[[var.names[1]]])$ni[include & yi.replace] <- ni.u[include & yi.replace]
} else {
dat <- data.frame(yi=rep(NA_real_, k), vi=rep(NA_real_, k))
dat$yi[include] <- yi[include]
dat$vi[include] <- vi[include]
if (add.measure)
dat$measure[!is.na(yi) & include] <- measure
attributes(dat$yi)$ni[include] <- ni.u[include]
if (add.measure) {
names(dat) <- var.names
} else {
names(dat) <- var.names[1:2]
}
}
if (add.measure)
dat[[var.names[3]]][is.na(dat[[var.names[3]]])] <- ""
attr(dat[[var.names[1]]], "slab") <- slab
attr(dat[[var.names[1]]], "measure") <- measure
attr(dat, "digits") <- digits
attr(dat, "yi.names") <- unique(c(var.names[1], attr(data, "yi.names")))
attr(dat, "vi.names") <- unique(c(var.names[2], attr(data, "vi.names")))
attr(dat, "sei.names") <- attr(data, "sei.names")
attr(dat, "zi.names") <- attr(data, "zi.names")
attr(dat, "pval.names") <- attr(data, "pval.names")
attr(dat, "ci.lb.names") <- attr(data, "ci.lb.names")
attr(dat, "ci.ub.names") <- attr(data, "ci.ub.names")
attr(dat, "yi.names") <- attr(dat, "yi.names")[attr(dat, "yi.names") %in% colnames(dat)]
attr(dat, "vi.names") <- attr(dat, "vi.names")[attr(dat, "vi.names") %in% colnames(dat)]
class(dat) <- c("escalc", "data.frame")
return(dat)
} |
calc_pI <- function(seq) {
pI <- pI(seq)
as.data.frame(pI)
} |
`putBack` <-
function(n,blocklist,blockvalues){
x<-rep(0,n);nb<-length(blockvalues)
for (i in 1:nb) {
x[blocklist[i,1]:blocklist[i,2]]<-blockvalues[i]}
return(x)
} |
colourMatch <- function(colour,
colourList=getOption("roloc.colourList"),
colourMetric=getOption("roloc.colourMetric"),
...) {
if (!inherits(colourList, "colourList"))
stop("Invalid colourList")
if (is.numeric(colour)) {
colour <- col2char(colour)
}
colourRGB <- hex2RGB(col2hex(colour))
colourDist <- colourMetric(colourRGB, colourList$colours, ...)
missing <- is.na(colourDist)
unknown <- !missing & colourDist == Inf
match <- list(colour=colour, colourList=colourList,
colourDist=colourDist)
class(match) <- "colourMatch"
match
}
colorMatch <- colourMatch |
context("slpCOVIS")
load("../data/test_slpcovis.RData")
set.seed(7)
out <- slpCOVIS(st, tr, crx = TRUE, respt = FALSE, rgive = TRUE,
xtdo = FALSE)
test_that("slpCOVIS reproduces an arbitrarily chosen short simulation.", {
expect_equal(out$foutmat, testres$foutmat)
}) |
c( 1, 16 , 333 , 33 , 1) |
source("incl/start.R")
library("listenv")
message("*** multicore() - terminating workers ...")
if (supportsMulticore() && availableCores("multicore") >= 2L) {
plan(multicore, workers = 2L)
x %<-% tools::pskill(pid = Sys.getpid())
res <- tryCatch(y <- x, error = identity)
print(res)
stopifnot(inherits(res, "FutureError"))
}
message("*** multicore() - terminating workers ... DONE")
source("incl/end.R") |
view <- function(x,
method = "viewer",
file = "",
append = FALSE,
report.title = NA,
table.classes = NA,
bootstrap.css = st_options("bootstrap.css"),
custom.css = st_options("custom.css"),
silent = FALSE,
footnote = st_options("footnote"),
max.tbl.height = Inf,
collapse = 0,
escape.pipe = st_options("escape.pipe"),
...) {
if (grepl("\\.r?md$", file, ignore.case = TRUE, perl = TRUE) &&
method != "pander") {
message("Switching method to 'pander'")
method <- "pander"
} else if (grepl("\\.html$", file, ignore.case = TRUE, perl = TRUE) &&
method == "pander") {
message("Switching method to 'browser'")
method <- "browser"
}
if (inherits(x, "summarytools") &&
(isTRUE(attr(x, "st_type") %in%
c("freq", "ctable", "descr", "dfSummary")))) {
print.summarytools(x,
method = method,
file = file,
append = append,
report.title = report.title,
table.classes = table.classes,
bootstrap.css = bootstrap.css,
custom.css = custom.css,
silent = silent,
footnote = footnote,
max.tbl.height = max.tbl.height,
collapse = collapse,
escape.pipe = escape.pipe,
...)
} else if (inherits(x = x, what = c("stby","by")) &&
attr(x[[1]], "st_type") == "descr" &&
length(attr(x[[1]], "data_info")$by_var) == 1 &&
((!attr(x[[1]], "data_info")$transposed && dim(x[[1]])[2] == 1) ||
(attr(x[[1]], "data_info")$transposed && dim(x[[1]])[1] == 1))) {
if (attr(x[[1]], "data_info")$transposed) {
xx <- do.call(rbind, x)
} else {
xx <- do.call(cbind, x)
class(xx) <- class(x[[1]])
colnames(xx) <- names(x)
}
attr(xx, "st_type") <- "descr"
attr(xx, "date") <- attr(x[[1]], "date")
attr(xx, "fn_call") <- attr(x[[1]], "fn_call")
attr(xx, "stats") <- attr(x[[1]], "stats")
attr(xx, "data_info") <- attr(x[[1]], "data_info")
attr(xx, "data_info")$by_var_special <-
sub("^.*\\$(.+)", "\\1", attr(x[[1]], "data_info")$by_var)
attr(xx, "data_info")$Group <- NULL
attr(xx, "data_info")$by_first <- NULL
attr(xx, "data_info")$by_last <- NULL
attr(xx, "data_info")$N.Obs <- attr(x[[1]], "data_info")$N.Obs
attr(xx, "data_info") <- attr(xx,"data_info")[!is.na(attr(xx, "data_info"))]
attr(xx, "format_info") <- attr(x[[1]], "format_info")
attr(xx, "user_fmt") <- attr(x[[1]], "user_fmt")
attr(xx, "lang") <- attr(x[[1]], "lang")
print.summarytools(xx,
method = method,
file = file,
append = append,
report.title = report.title,
table.classes = table.classes,
bootstrap.css = bootstrap.css,
custom.css = custom.css,
silent = silent,
footnote = footnote,
collapse = collapse,
escape.pipe = escape.pipe,
...)
} else if (inherits(x = x, what = c("stby", "by")) &&
attr(x[[1]], "st_type") %in%
c("freq", "ctable", "descr", "dfSummary")) {
if (grepl("\\.html$", file, ignore.case = TRUE, perl = TRUE) &&
!grepl(pattern = tempdir(), x = file, fixed = TRUE) &&
method == "pander") {
method <- "browser"
message("Switching method to 'browser'")
}
null_ind <- which(vapply(x, is.null, TRUE))
if (length(null_ind) > 0) {
x <- x[-null_ind]
}
if (method %in% c("viewer", "browser")) {
file <- ifelse(file == "", paste0(tempfile(),".html"), file)
footnote_safe <- footnote
for (i in seq_along(x)) {
if (grepl(tempdir(), file, fixed = TRUE) && i == length(x)) {
open.doc <- TRUE
} else {
open.doc <- FALSE
}
if (i == length(x)) {
footnote <- footnote_safe
} else {
footnote <- NA
}
if (i == 1) {
if (isTRUE(append) && !is.na(custom.css)) {
stop("Can't append existing html file with new custom.css")
}
if (isTRUE(append) && !is.na(report.title)) {
stop("Can't append existing html file with new report.title")
}
print.summarytools(x[[i]],
method = method,
file = file,
append = append,
report.title = report.title,
table.classes = table.classes,
bootstrap.css = bootstrap.css,
custom.css = custom.css,
silent = silent,
footnote = footnote,
collapse = collapse,
escape.pipe = escape.pipe,
open.doc = open.doc,
...)
} else if (i < length(x)) {
print.summarytools(x[[i]],
method = method,
file = file,
append = TRUE,
table.classes = table.classes,
silent = TRUE,
footnote = footnote,
collapse = collapse,
escape.pipe = escape.pipe,
group.only = TRUE,
open.doc = open.doc,
...)
} else {
print.summarytools(x[[i]],
method = method,
file = file,
append = TRUE,
escape.pipe = escape.pipe,
table.classes = table.classes,
silent = silent,
footnote = footnote,
collapse = collapse,
group.only = TRUE,
open.doc = open.doc,
...)
}
}
} else if (method == "render") {
for (i in seq_along(x)) {
if (i == 1) {
html_content <-
list(print.summarytools(x[[i]],
method = method,
table.classes = table.classes,
bootstrap.css = bootstrap.css,
custom.css = custom.css,
silent = silent,
footnote = NA,
collapse = collapse,
...))
} else if (i < length(x)) {
html_content[[i]] <-
print.summarytools(x[[i]],
method = method,
table.classes = table.classes,
silent = silent,
footnote = NA,
collapse = collapse,
group.only = TRUE,
...)
} else {
html_content[[i]] <-
print.summarytools(x[[i]],
method = method,
table.classes = table.classes,
silent = silent,
footnote = footnote,
collapse = collapse,
group.only = TRUE,
...)
}
}
return(tagList(html_content))
} else if (method == "pander") {
for (i in seq_along(x)) {
if (i == 1) {
print.summarytools(x[[1]],
method = "pander",
silent = silent,
file = file,
append = append,
group.only = FALSE,
escape.pipe = escape.pipe,
...)
} else {
print.summarytools(x[[i]],
method = "pander",
silent = silent,
file = file,
append = ifelse(file == "", FALSE, TRUE),
group.only = TRUE,
escape.pipe = escape.pipe,
...)
}
}
}
} else if (inherits(x = x, what = "list") &&
inherits(x[[1]], "summarytools") &&
attr(x[[1]], "st_type") == "freq") {
if ("ignored" %in% names(attributes(x))) {
message("Variable(s) ignored: ",
paste(attr(x, "ignored"), collapse = ", "))
}
if (method %in% c("viewer", "browser")) {
file <- ifelse(file == "", paste0(tempfile(),".html"), file)
if (grepl(tempdir(), file, fixed = TRUE)) {
open.doc <- TRUE
} else {
open.doc <- FALSE
}
for (i in seq_along(x)) {
if (i == 1) {
print.summarytools(x[[1]],
method = method,
file = file,
silent = silent,
footnote = NA,
collapse = collapse,
append = FALSE,
var.only = FALSE,
report.title = report.title,
escape.pipe = escape.pipe,
table.classes = table.classes,
bootstrap.css = bootstrap.css,
custom.css = custom.css,
...)
} else if (i < length(x)) {
print.summarytools(x[[i]],
method = method,
file = file,
append = TRUE,
var.only = TRUE,
silent = TRUE,
footnote = NA,
collapse = collapse,
escape.pipe = escape.pipe,
table.classes = table.classes,
...)
} else {
print.summarytools(x[[i]],
method = method,
file = file,
append = TRUE,
var.only = TRUE,
silent = silent,
footnote = footnote,
collapse = collapse,
escape.pipe = escape.pipe,
table.classes = table.classes,
open.doc = open.doc,
...)
}
}
} else if (method == "render") {
for (i in seq_along(x)) {
if (i == 1) {
html_content <-
list(print.summarytools(x[[i]],
method = method,
silent = TRUE,
footnote = NA,
collapse = collapse,
table.classes = table.classes,
bootstrap.css = bootstrap.css,
custom.css = custom.css,
var.only = FALSE,
...))
} else if (i < length(x)) {
html_content[[i]] <-
print.summarytools(x[[i]],
method = method,
var.only = TRUE,
silent = TRUE,
footnote = NA,
collapse = collapse,
table.classes = table.classes,
bootstrap.css = FALSE,
var.only = TRUE,
...)
} else {
html_content[[i]] <-
print.summarytools(x[[i]],
method = method,
var.only = TRUE,
silent = silent,
footnote = footnote,
collapse = collapse,
table.classes = table.classes,
bootstrap.css = FALSE,
var.only = TRUE,
...)
}
}
return(tagList(html_content))
} else if (method == "pander") {
var.only <- "headings" %in% names(list(...)) &&
!isTRUE(list(...)$headings)
for (i in seq_along(x)) {
if (i == 1) {
print.summarytools(x[[1]],
method = "pander",
file = file,
silent = silent,
append = append,
escape.pipe = escape.pipe,
var.only = var.only,
...)
} else {
print.summarytools(x[[i]],
method = "pander",
file = file,
silent = silent,
append = ifelse(file == "", FALSE, TRUE),
var.only = TRUE,
escape.pipe = escape.pipe,
...)
}
}
}
} else {
message(
paste(
"x must either be a summarytools object created with freq(), descr(),",
"or a list of summarytools objects created using by()"
)
)
}
}
stview <- view |
Xs <- mwTensor::toyModel("coupled_Complex_Hard")
Xs[[3]] <- Xs[[3]] + array(rbinom(20*23*24,1000,0.1), dim=c(20,23,24))
A1 <- mwTensor:::.randMat(5, 15)
A2 <- mwTensor:::.randMat(5, 20)
A3 <- mwTensor:::.randMat(5, 25)
A4 <- mwTensor:::.randMat(5, 30)
A5 <- mwTensor:::.randMat(5, 15)
A6 <- mwTensor:::.randMat(5, 21)
A7 <- mwTensor:::.randMat(5, 22)
A8 <- mwTensor:::.randMat(5, 20)
A9 <- mwTensor:::.randMat(5, 23)
A10 <- mwTensor:::.randMat(5, 24)
A11 <- mwTensor:::.randMat(5, 25)
A12 <- mwTensor:::.randMat(5, 25)
A13 <- mwTensor:::.randMat(5, 26)
A14 <- mwTensor:::.randMat(5, 30)
A15 <- mwTensor:::.randMat(5, 27)
A16 <- mwTensor:::.randMat(5, 28)
A17 <- mwTensor:::.randMat(5, 21)
A18 <- mwTensor:::.randMat(5, 11)
A19 <- mwTensor:::.randMat(5, 22)
A20 <- mwTensor:::.randMat(5, 12)
A21 <- mwTensor:::.randMat(5, 23)
A22 <- mwTensor:::.randMat(5, 13)
A23 <- mwTensor:::.randMat(5, 24)
A24 <- mwTensor:::.randMat(5, 14)
A25 <- mwTensor:::.randMat(5, 25)
A26 <- mwTensor:::.randMat(5, 15)
A27 <- mwTensor:::.randMat(5, 26)
A28 <- mwTensor:::.randMat(5, 16)
A29 <- mwTensor:::.randMat(5, 27)
A30 <- mwTensor:::.randMat(5, 17)
A31 <- mwTensor:::.randMat(5, 28)
A32 <- mwTensor:::.randMat(5, 18)
params <- new("CoupledMWCAParams",
Xs=Xs,
mask=list(X1=NULL, X2=NULL, X3=NULL, X4=NULL, X5=NULL, X6=NULL,
X7=NULL, X8=NULL, X9=NULL, X10=NULL, X11=NULL,
X12=NULL, X13=NULL),
weights=list(X1=1, X2=1, X3=1, X4=1, X5=1, X6=1,
X7=1, X8=1, X9=1, X10=1, X11=1,
X12=1, X13=1),
common_model=list(X1=list(I1="A1", I2="A2", I3="A3", I4="A4"),
X2=list(I5="A5", I6="A6", I7="A7"),
X3=list(I8="A8", I9="A9", I10="A10"),
X4=list(I11="A11", I12="A12", I13="A13"),
X5=list(I14="A14", I15="A15", I16="A16"),
X6=list(I17="A17", I18="A18"),
X7=list(I19="A19", I20="A20"),
X8=list(I21="A21", I22="A22"),
X9=list(I23="A23", I24="A24"),
X10=list(I25="A25", I126="A26"),
X11=list(I27="A27", I28="A28"),
X12=list(I29="A29", I30="A30"),
X13=list(I31="A31", I32="A32")),
common_initial=list(A1=A1, A2=A2, A3=A3, A4=A4, A5=A5,
A6=A6, A7=A7, A8=A8, A9=A9, A10=A10,
A11=A11, A12=A12, A13=A13, A14=A14, A15=A15,
A16=A16, A17=A17, A18=A18, A19=A19, A20=A20,
A21=A21, A22=A22, A23=A23, A24=A24, A25=A25,
A26=A26, A27=A27, A28=A28, A29=A29, A30=A30,
A31=A31, A32=A32),
common_algorithms=list(A1="myNMF", A2="myNMF", A3="myNMF", A4="myNMF", A5="myNMF",
A6="myNMF", A7="myNMF", A8="myNMF", A9="myNMF", A10="myNMF",
A11="myNMF", A12="myNMF", A13="myNMF", A14="myNMF", A15="myNMF",
A16="myNMF", A17="myNMF", A18="myNMF", A19="myNMF", A20="myNMF",
A21="myNMF", A22="myNMF", A23="myNMF", A24="myNMF", A25="myNMF",
A26="myNMF", A27="myNMF", A28="myNMF", A29="myNMF", A30="myNMF",
A31="myNMF", A32="myNMF"),
common_iteration=list(A1=20, A2=20, A3=20, A4=20, A5=20,
A6=20, A7=20, A8=20, A9=20, A10=20,
A11=20, A12=20, A13=20, A14=20, A15=20,
A16=20, A17=20, A18=20, A19=20, A20=20,
A21=20, A22=20, A23=20, A24=20, A25=20,
A26=20, A27=20, A28=20, A29=20, A30=20,
A31=20, A32=20),
common_decomp=list(A1=TRUE, A2=TRUE, A3=TRUE, A4=TRUE, A5=TRUE,
A6=TRUE, A7=TRUE, A8=TRUE, A9=TRUE, A10=TRUE,
A11=TRUE, A12=TRUE, A13=TRUE, A14=TRUE, A15=TRUE,
A16=TRUE, A17=TRUE, A18=TRUE, A19=TRUE, A20=TRUE,
A21=TRUE, A22=TRUE, A23=TRUE, A24=TRUE, A25=TRUE,
A26=TRUE, A27=TRUE, A28=TRUE, A29=TRUE, A30=TRUE,
A31=TRUE, A32=TRUE),
common_fix=list(A1=FALSE, A2=FALSE, A3=FALSE, A4=FALSE, A5=FALSE,
A6=FALSE, A7=FALSE, A8=FALSE, A9=FALSE, A10=FALSE,
A11=FALSE, A12=FALSE, A13=FALSE, A14=FALSE, A15=FALSE,
A16=FALSE, A17=FALSE, A18=FALSE, A19=FALSE, A20=FALSE,
A21=FALSE, A22=FALSE, A23=FALSE, A24=FALSE, A25=FALSE,
A26=FALSE, A27=FALSE, A28=FALSE, A29=FALSE, A30=FALSE,
A31=FALSE, A32=FALSE),
common_dims=list(A1=5, A2=5, A3=5, A4=5, A5=5,
A6=5, A7=5, A8=5, A9=5, A10=5,
A11=5, A12=5, A13=5, A14=5, A15=5,
A16=5, A17=5, A18=5, A19=5, A20=5,
A21=5, A22=5, A23=5, A24=5, A25=5,
A26=5, A27=5, A28=5, A29=5, A30=5,
A31=5, A32=5),
common_transpose=list(A1=FALSE, A2=FALSE, A3=FALSE, A4=FALSE, A5=FALSE,
A6=FALSE, A7=FALSE, A8=FALSE, A9=FALSE, A10=FALSE,
A11=FALSE, A12=FALSE, A13=FALSE, A14=FALSE, A15=FALSE,
A16=FALSE, A17=FALSE, A18=FALSE, A19=FALSE, A20=FALSE,
A21=FALSE, A22=FALSE, A23=FALSE, A24=FALSE, A25=FALSE,
A26=FALSE, A27=FALSE, A28=FALSE, A29=FALSE, A30=FALSE,
A31=FALSE, A32=FALSE),
common_coretype="Tucker",
specific=FALSE,
thr=1e-10,
viz=TRUE,
verbose=TRUE)
out <- CoupledMWCA(params)
expect_equal(is(out), "CoupledMWCAResult")
rec <- mwTensor:::.recTensors(out@common_cores, out@common_factors,
out@common_model)
expect_equal(length(rec), 13) |
mergeReport <- function(INFO, Daily, Sample = NA, surfaces=NA, verbose = TRUE, interactive=NULL){
if(!is.null(interactive)) {
warning("The argument 'interactive' is deprecated. Please use 'verbose' instead")
verbose <- interactive
}
if (verbose & all(!is.na(Sample))){
dataOverview(Daily, Sample)
}
if(exists("Daily") && !all(is.na(Daily)) && !("Q" %in% names(Daily))){
message("Please double check that the Daily dataframe is correctly defined.")
}
if(exists("INFO") && !any(c("param.units", "shortName", "paramShortName", "constitAbbrev", "drainSqKm") %in% names(INFO))){
message("Please double check that the INFO dataframe is correctly defined.")
}
if(all(!is.na(surfaces))){
if(!isTRUE(dim(surfaces)[3] == 3 && dim(surfaces)[1] == 14)){
message("Please double check that the surfaces matrix is correctly defined.")
}
}
if(!all(is.na(Sample))){
if(!all((c("ConcLow","ConcHigh","Uncen","ConcAve") %in% names(Sample)))){
message("Please double check that the Sample dataframe is correctly defined.")
}
if(!all(is.na(Daily))){
if(all(c("Q","LogQ") %in% names(Sample))){
if(all(c("yHat","SE","ConcHat") %in% names(Sample))){
message("Merging new flow data will require modelEstimation to be rerun.")
}
Sample <- Sample[,!(names(Sample) %in% c("Q","LogQ"))]
}
Sample <- merge(Daily[,c("Date","Q","LogQ")],Sample,by = "Date",all.y = TRUE)
if(any(is.na(Sample$Q))){
message("Some Sample dates do not have corresponding flow data. Not all EGRET functions will work correctly.")
}
}
eList <- as.egret(INFO, Daily, Sample, surfaces)
} else {
eList <- as.egret(INFO, Daily, Sample = NA, surfaces = NA)
}
return(eList)
} |
foo = list(A = c(1, 2, 3, 4, 5), B = c(3, 4, 5, 6, 7),
C = c(5, 6, 7, 8, 9), D = c(7, 8, 9, 10, 11))
test_that("encrihment_test: p-value", {
expect_equal(class(enrichment_test(Venn(foo), "A", "B")), "list")
expect_equal(class(enrichment_test(Venn(foo), 1, 2)), "list")
expect_equal(class(enrichment_test(Venn(foo), 1, 2, univ = 1:1000)), "list")
}
)
test_that("enrichment_test: error", {
expect_error(enrichment_test(Venn(foo), 1, 2, n = 100))
}
) |
G3DHFun<-function(df,model,G3DHtext2){
data<-sapply(df,as.character)
dP1<-data[-1,which(data[1,]=="P1")];P1<-as.numeric(dP1[which(is.na(as.numeric(dP1))==FALSE)]);df11<-as.data.frame(P1)
dP2<-data[-1,which(data[1,]=="P2")];P2<-as.numeric(dP2[which(is.na(as.numeric(dP2))==FALSE)]);df21<-as.data.frame(P2)
dDH<-data[-1,which(data[1,]=="DH")];DH<-as.numeric(dDH[which(is.na(as.numeric(dDH))==FALSE)]);df31<-as.data.frame(DH)
G3DHcolname <- c("Model","Log_Max_likelihood_Value","AIC","mean[P1]","mean[P2]","Var(P1 & P2)","mean[1]","mean[2]","mean[3]","mean[4]","mean[5]","mean[6]","mean[7]","mean[8]","mean[9]","mean[10]",
"mean[11]","mean[12]","mean[13]","mean[14]","mean[15]","mean[16]","Var(Residual+Polygene)","Proportion[1]","Proportion[2]","Proportion[3]","Proportion[4]","Proportion[5]",
"Proportion[6]","Proportion[7]","Proportion[8]","Proportion[9]","Proportion[10]","Proportion[11]","Proportion[12]","Proportion[13]","Proportion[14]","Proportion[15]","Proportion[16]",
"m(m1)","m2","m3","d(da)","db","dc","dd","iab(i*)","iac","iad","ibc","ibd","icd","iabc","[d]","Major-Gene Var","Heritability(Major-Gene)(%)","Polygenes Var","Heritability(Polygenes-Var)(%)",
"U1 square-P1","P(U1 square-P1)","U2 square-P1","P(U2 square-P1)","U3 square-P1","P(U3 square-P1)","nW square-P1","P(nW square-P1)","Dn-P1","P(Dn-P1)","U1 square-P2","P(U1 square-P2)","U2 square-P2","P(U2 square-P2)","U3 square-P2","P(U3 square-P2)","nW square-P2","P(nW square-P2)","Dn-P2","P(Dn-P2)",
"U1 square-DH","P(U1 square-DH)","U2 square-DH","P(U2 square-DH)","U3 square-DH","P(U3 square-DH)","nW square-DH","P(nW square-DH)","Dn-DH","P(Dn-DH)")
G3DHModelFun<-list(NA)
G3DHModelFun[[1]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
mi <- as.matrix(1); mix_pi <-1.0; meanA<-mean(dataDH); sigma <-2.0*sigma0; sigmaA <-sigma_dh/2
abc <-logL(n_samP1,1,mix_pi,mean11,sigma,dataP1)+logL(n_samP2,1,mix_pi,mean12,sigma,dataP2)+logL(n_samDH,1,mix_pi,meanA,sigmaA,dataDH)
AIC <- -2.0*abc+2.0*2.0
dataP1<-sort(dataP1)
bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,1)
gg <- (dataDH - meanA)/sqrt(as.vector(sigmaA))
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,1] <- bmw*mix_pi
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("0MG",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(t(meanA),4)," "," "," "," "," "," "," "," "," "," "," "," "," "," "," ",round(sigmaA,4),round(t(mix_pi),4),
" "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," "," ",round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[2]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<-2 ; mi <- as.matrix(c(0.5,0.5)); meanA<-mean(dataDH); sigma <- 2.0*sigma0;
sigmaA <- matrix((sigma_dh/2),d2,1)
a1 <- sqrt(sigma_dh/n_samDH)
if(mean11<mean12){a1=-a1}
meanA <- as.matrix(c((meanA+1.5*a1),(meanA-1.5*a1)))
iteration <- 0; stopa <- 1000
WW <- matrix(0,d2,n_samDH); swx <- matrix(0,d2,1)
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanA,sqrt(sigmaA),mi)))
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(dataDH,meanA[i],sqrt(sigmaA[i]))/dmixnorm(dataDH,meanA,sqrt(sigmaA),mi) }
mix_pi <- as.matrix(rowSums(WW)/n_samDH)
sumwx <- WW%*%dataDH
n0 <- n_samDH*mix_pi
n0[n0<0.000001] <- 0.000001
mean11<-(sum(dataP1)+sumwx[1]*m_fam)/(n_samP1+n0[1]*m_fam)
mean12<-(sum(dataP2)+sumwx[2]*m_fam)/(n_samP2+n0[2]*m_fam)
meanA <- as.matrix(c(mean11,mean12))
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
for(i in 1:d2) { swx[i] <- WW[i,]%*%(dataDH-meanA[i])^2 }
sigma<-(ss1+ss2+sum(swx)*m_fam)/(n_samP1+n_samP2+n_samDH)
sigmaA<-matrix((sigma/m_fam),d2,1)
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanA,sqrt(sigmaA),mix_pi)))
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) {stopa <- -stopa}
}
abc <- L1
AIC <- -2*abc + 2*3
aa<- matrix(c(1,1,1,-1),2,2)
b_line1 <- meanA
B1 <- solve(aa,b_line1)
jj <- sigma_dh - sigmaA[1]
if(jj < 0) {jj <- 0}
ll <- jj/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
for(i in 1:d2){
gg <- (dataDH - meanA[i])/sqrt(sigmaA[i])
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,i] <- bmw*mix_pi[i]
}
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("1MG-A",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(t(meanA),4)," "," "," "," "," "," "," "," "," "," "," "," "," "," ",round(sigmaA[1],4),round(t(mix_pi),4),
" "," "," "," "," "," "," "," "," "," "," "," "," "," ",round(B1[1],4)," "," ",round(B1[2],4)," "," "," "," "," "," "," "," "," "," "," ",round(jj,4),round(ll*100,4)," "," ",round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[3]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<-4 ; mi <- as.matrix(c(0.25,0.25,0.25,0.25))
meanB<-mean(dataDH); sigmaB <- matrix((sigma_dh/2),d2,1); sigma <- sigma0
a1 <- sqrt(sigma_dh/n_samDH)
if(mean11<mean12){a1=-a1}
meanB <- as.matrix(c((meanB+3*a1),(meanB+a1),(meanB-a1),(meanB-3*a1)))
iteration <- 0; stopa <- 1000
WW <- matrix(0,d2,n_samDH); swx <- matrix(0,d2,1)
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanB,sqrt(sigmaB),mi)))
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(dataDH,meanB[i],sqrt(sigmaB[i]))/dmixnorm(dataDH,meanB,sqrt(sigmaB),mi) }
mix_pi <- as.matrix(rowSums(WW)/n_samDH)
sumwx <- WW%*%dataDH
n0 <- n_samDH*mix_pi
n0[n0<0.000001] <- 0.000001
mean11<-(sum(dataP1)+sumwx[1]*m_fam)/(n_samP1+n0[1]*m_fam)
mean12<-(sum(dataP2)+sumwx[4]*m_fam)/(n_samP2+n0[4]*m_fam)
meanB <- as.matrix(c(mean11,sumwx[2]/n0[2],sumwx[3]/n0[3],mean12))
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
for(i in 1:d2) { swx[i] <- WW[i,]%*%(dataDH-meanB[i])^2 }
sigma<-(ss1+ss2+sum(swx)*m_fam)/(n_samP1+n_samP2+n_samDH)
sigmaB<-matrix((sigma/m_fam),d2,1)
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanB,sqrt(sigmaB),mix_pi)))
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) {stopa <- -stopa}
}
abc <- L1
AIC <- -2*abc + 2*5
aa<- matrix(c(1,1,1,1, 1,1,-1,-1, 1,-1,1,-1, 1,-1,-1,1),4,4)
b_line1 <- meanB
B1 <- solve(aa,b_line1)
jj <- sigma_dh - sigmaB[1]
if(jj < 0) {jj <- 0}
ll <- jj/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
for(i in 1:d2){
gg <- (dataDH - meanB[i])/sqrt(sigmaB[i])
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,i] <- bmw*mix_pi[i]
}
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("2MG-AI",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(t(meanB),4)," "," "," "," "," "," "," "," "," "," "," "," ",round(sigmaB[1],4),round(t(mix_pi),4),
" "," "," "," "," "," "," "," "," "," "," "," ",round(B1[1],4)," "," ",round(B1[2],4),round(B1[3],4)," "," ",round(B1[4],4)," "," "," "," "," "," "," ",round(jj,4),round(ll*100,4)," "," ",round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[4]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<-4 ; mi <- as.matrix(c(0.25,0.25,0.25,0.25))
meanB<-mean(dataDH); sigmaB <- matrix((sigma_dh/2),d2,1); sigma <- sigma0
a1 <- sqrt(sigma_dh/n_samDH)
if(mean11<mean12){a1=-a1}
meanB <- as.matrix(c((meanB+3*a1),(meanB+a1),(meanB-a1),(meanB-3*a1)))
iteration <- 0; stopa <- 1000
WW <- matrix(0,d2,n_samDH); swx <- matrix(0,d2,1)
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanB,sqrt(sigmaB),mi)))
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(dataDH,meanB[i],sqrt(sigmaB[i]))/dmixnorm(dataDH,meanB,sqrt(sigmaB),mi) }
mix_pi <- as.matrix(rowSums(WW)/n_samDH)
sumwx <- WW%*%dataDH
n0 <- n_samDH*mix_pi
n0[n0<0.000001] <- 0.000001
s0<-matrix(0,4,1)
s0[1]<-sum(dataP1)+m_fam*sumwx[1]; s0[2]<-n_samP1+m_fam*n0[1]
s0[3]<-sum(dataP2)+m_fam*sumwx[4]; s0[4]<-n_samP2+m_fam*n0[4]
rr<-(s0[1]/s0[2]+s0[3]/s0[4]-sumwx[2]/n0[2]-sumwx[3]/n0[3])/(sigma/s0[2]+sigma/s0[4]+sigmaB[2]/n0[2]+sigmaB[3]/n0[3])
mean11<-(s0[1]-rr*sigma)/s0[2]
mean12<-(s0[3]-rr*sigma)/s0[4]
meanB <- as.matrix(c(mean11,(sumwx[2]+sigmaB[2]*rr)/n0[2],(sumwx[3]+sigmaB[3]*rr)/n0[3],mean12))
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
for(i in 1:d2) { swx[i] <- WW[i,]%*%(dataDH-meanB[i])^2 }
sigma<-(ss1+ss2+sum(swx)*m_fam)/(n_samP1+n_samP2+n_samDH)
sigmaB<-matrix((sigma/m_fam),d2,1)
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanB,sqrt(sigmaB),mix_pi)))
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) {stopa <- -stopa}
}
abc <- L1
AIC <- -2*abc + 2*4
aa<- matrix(c(1,1,1,1, 1,1,-1,-1, 1,-1,1,-1),4,3)
b_line1 <- meanB
B1 <- solve(t(aa)%*%aa)%*%(t(aa)%*%b_line1)
jj <- sigma_dh - sigmaB[1]
if(jj < 0) {jj <- 0}
ll <- jj/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
for(i in 1:d2){
gg <- (dataDH - meanB[i])/sqrt(sigmaB[i])
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,i] <- bmw*mix_pi[i]
}
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("2MG-A",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(t(meanB),4)," "," "," "," "," "," "," "," "," "," "," "," ",round(sigmaB[1],4),round(t(mix_pi),4),
" "," "," "," "," "," "," "," "," "," "," "," ",round(B1[1],4)," "," ",round(B1[2],4),round(B1[3],4)," "," "," "," "," "," "," "," "," "," ",round(jj,4),round(ll*100,4)," "," ",round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[5]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<-3
mi <- as.matrix(c(0.25,0.5,0.25))
meanB<-mean(dataDH)
sigmaB <- matrix((sigma_dh/2),d2,1)
sigma <- sigma0
a1 <- sqrt(sigma_dh/n_samDH)
if(mean11<mean12){a1=-a1}
meanB <- as.matrix(c((meanB+2.5*a1),meanB,(meanB-2.5*a1)))
iteration <- 0; stopa <- 1000
WW <- matrix(0,d2,n_samDH); swx <- matrix(0,d2,1)
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanB,sqrt(sigmaB),mi)))
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(dataDH,meanB[i],sqrt(sigmaB[i]))/dmixnorm(dataDH,meanB,sqrt(sigmaB),mi) }
mix_pi <- as.matrix(rowSums(WW)/n_samDH)
sumwx <- WW%*%dataDH
n0 <- n_samDH*mix_pi
n0[n0<0.000001] <- 0.000001
s0<-matrix(0,4,1)
s0[1]<-sum(dataP1)+m_fam*sumwx[1];s0[2]=n_samP1+m_fam*n0[1]
s0[3]<-sum(dataP2)+m_fam*sumwx[3];s0[4]=n_samP2+m_fam*n0[3]
rr<-(s0[1]/s0[2]-2.0*sumwx[2]/n0[2]+s0[3]/s0[4])/(sigma/s0[2]+sigma/s0[4]+4*sigmaB[2]/n0[2])
mean11<-(s0[1]-rr*sigma)/s0[2]
mean12<-(s0[3]-rr*sigma)/s0[4]
meanB <- as.matrix(c(mean11,(sumwx[2]+2*sigmaB[2]*rr)/n0[2],mean12))
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
for(i in 1:d2) { swx[i] <- WW[i,]%*%(dataDH-meanB[i])^2 }
sigma<-(ss1+ss2+sum(swx)*m_fam)/(n_samP1+n_samP2+n_samDH)
sigmaB<-matrix((sigma/m_fam),d2,1)
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanB,sqrt(sigmaB),mix_pi)))
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) {stopa <- -stopa}
}
abc <- L1
AIC <- -2*abc + 2*3
aa<- matrix(c(1,1,1,2,0,-2),3,2)
b_line1 <- meanB
B1 <- solve(t(aa)%*%aa)%*%(t(aa)%*%b_line1)
jj <- sigma_dh - sigmaB[1]
if(jj < 0) {jj <- 0}
ll <- jj/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
for(i in 1:d2){
gg <- (dataDH - meanB[i])/sqrt(sigmaB[i])
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,i] <- bmw*mix_pi[i]
}
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("2MG-EA",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(t(meanB),4)," "," "," "," "," "," "," "," "," "," "," "," "," ",round(sigmaB[1],4),round(t(mix_pi),4),
" "," "," "," "," "," "," "," "," "," "," "," "," ",round(B1[1],4)," "," ",round(B1[2],4),round(B1[2],4)," "," "," "," "," "," "," "," "," "," ",round(jj,4),round(ll*100,4)," "," ",round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[6]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<-3
mi <- as.matrix(c(0.5,0.25,0.25))
meanB<-mean(dataDH)
sigmaB <- matrix((sigma_dh/2),d2,1)
sigma <- sigma0
a1 <- sqrt(sigma_dh/n_samDH)
if(mean11<mean12){a1=-a1}
meanB <- as.matrix(c((meanB+2*a1),meanB,(meanB-2*a1)))
iteration <- 0; stopa <- 1000
WW <- matrix(0,d2,n_samDH); swx <- matrix(0,d2,1)
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanB,sqrt(sigmaB),mi)))
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(dataDH,meanB[i],sqrt(sigmaB[i]))/dmixnorm(dataDH,meanB,sqrt(sigmaB),mi) }
mix_pi <- as.matrix(rowSums(WW)/n_samDH)
sumwx <- WW%*%dataDH
n0 <- n_samDH*mix_pi
n0[n0<0.000001] <- 0.000001
mean11<-(sum(dataP1)+m_fam*sumwx[1])/(n_samP1+m_fam*n0[1])
mean12<-(sum(dataP2)+m_fam*sumwx[3])/(n_samP2+m_fam*n0[3])
meanB <- as.matrix(c(mean11,sumwx[2]/n0[2],mean12))
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
for(i in 1:d2) { swx[i] <- WW[i,]%*%(dataDH-meanB[i])^2 }
sigma<-(ss1+ss2+sum(swx)*m_fam)/(n_samP1+n_samP2+n_samDH)
sigmaB<-matrix((sigma/m_fam),d2,1)
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanB,sqrt(sigmaB),mix_pi)))
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) {stopa <- -stopa}
}
abc <- L1
AIC <- -2*abc + 2*4
aa<- matrix(c(1,1,1, 1,-1,-1, 0,1,-1),3,3)
b_line1 <- meanB
B1 <- solve(aa,b_line1)
jj <- sigma_dh - sigmaB[1]
if(jj < 0) {jj <- 0}
ll <- jj/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
for(i in 1:d2){
gg <- (dataDH - meanB[i])/sqrt(sigmaB[i])
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,i] <- bmw*mix_pi[i]
}
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("2MG-ED",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(t(meanB),4)," "," "," "," "," "," "," "," "," "," "," "," "," ",round(sigmaB[1],4),round(t(mix_pi),4),
" "," "," "," "," "," "," "," "," "," "," "," "," ",round(B1[1],4)," "," ",round(B1[2],4),round(B1[3],4)," "," "," "," "," "," "," "," "," "," ",round(jj,4),round(ll*100,4)," "," ",round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[7]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<-3
mi <- as.matrix(c(0.25,0.25,0.5))
meanB<-mean(dataDH)
sigmaB <- matrix((sigma_dh/2),d2,1)
sigma <- sigma0
a1 <- sqrt(sigma_dh/n_samDH)
if(mean11<mean12){a1=-a1}
meanB <- as.matrix(c((meanB+2*a1),meanB,(meanB-2*a1)))
iteration <- 0; stopa <- 1000
WW <- matrix(0,d2,n_samDH); swx <- matrix(0,d2,1)
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanB,sqrt(sigmaB),mi)))
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(dataDH,meanB[i],sqrt(sigmaB[i]))/dmixnorm(dataDH,meanB,sqrt(sigmaB),mi) }
mix_pi <- as.matrix(rowSums(WW)/n_samDH)
sumwx <- WW%*%dataDH
n0 <- n_samDH*mix_pi
n0[n0<0.000001] <- 0.000001
mean11<-(sum(dataP1)+m_fam*sumwx[1])/(n_samP1+m_fam*n0[1])
mean12<-(sum(dataP2)+m_fam*sumwx[3])/(n_samP2+m_fam*n0[3])
meanB <- as.matrix(c(mean11,sumwx[2]/n0[2],mean12))
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
for(i in 1:d2) { swx[i] <- WW[i,]%*%(dataDH-meanB[i])^2 }
sigma<-(ss1+ss2+sum(swx)*m_fam)/(n_samP1+n_samP2+n_samDH)
sigmaB<-matrix((sigma/m_fam),d2,1)
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanB,sqrt(sigmaB),mix_pi)))
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) {stopa <- -stopa}
}
abc <- L1
AIC <- -2*abc + 2*4
aa<- matrix(c(1,1,1, 1,1,-1, 1,-1,0),3,3)
b_line1 <- meanB
B1 <- solve(aa,b_line1)
jj <- sigma_dh - sigmaB[1]
if(jj < 0) {jj <- 0}
ll <- jj/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
for(i in 1:d2){
gg <- (dataDH - meanB[i])/sqrt(sigmaB[i])
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,i] <- bmw*mix_pi[i]
}
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("2MG-ER",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(t(meanB),4)," "," "," "," "," "," "," "," "," "," "," "," "," ",round(sigmaB[1],4),round(t(mix_pi),4),
" "," "," "," "," "," "," "," "," "," "," "," "," ",round(B1[1],4)," "," ",round(B1[2],4),round(B1[3],4)," "," "," "," "," "," "," "," "," "," ",round(jj,4),round(ll*100,4)," "," ",round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[8]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<-3
mi <- as.matrix(c(0.25,0.5,0.25))
meanB<-mean(dataDH)
sigmaB <- matrix((sigma_dh/2),d2,1)
sigma <- sigma0
a1 <- sqrt(sigma_dh/n_samDH)
if(mean11<mean12){a1=-a1}
meanB <- as.matrix(c((meanB+2*a1),meanB,(meanB-2*a1)))
iteration <- 0; stopa <- 1000
WW <- matrix(0,d2,n_samDH); swx <- matrix(0,d2,1)
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanB,sqrt(sigmaB),mi)))
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(dataDH,meanB[i],sqrt(sigmaB[i]))/dmixnorm(dataDH,meanB,sqrt(sigmaB),mi) }
mix_pi <- as.matrix(rowSums(WW)/n_samDH)
sumwx <- WW%*%dataDH
n0 <- n_samDH*mix_pi
n0[n0<0.000001] <- 0.000001
mean11<-(sum(dataP1)+m_fam*sumwx[1])/(n_samP1+m_fam*n0[1])
mean12<-(sum(dataP2)+m_fam*sumwx[3])/(n_samP2+m_fam*n0[3])
meanB <- as.matrix(c(mean11,sumwx[2]/n0[2],mean12))
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
for(i in 1:d2) { swx[i] <- WW[i,]%*%(dataDH-meanB[i])^2 }
sigma<-(ss1+ss2+sum(swx)*m_fam)/(n_samP1+n_samP2+n_samDH)
sigmaB<-matrix((sigma/m_fam),d2,1)
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanB,sqrt(sigmaB),mix_pi)))
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) {stopa <- -stopa}
}
abc <- L1
AIC <- -2*abc + 2*4
aa<- matrix(c(1,1,1, 2,0,-2, 1,-1,1),3,3)
b_line1 <- meanB
B1 <- solve(aa,b_line1)
jj <- sigma_dh - sigmaB[1]
if(jj < 0) {jj <- 0}
ll <- jj/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
for(i in 1:d2){
gg <- (dataDH - meanB[i])/sqrt(sigmaB[i])
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,i] <- bmw*mix_pi[i]
}
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("2MG-AE",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(t(meanB),4)," "," "," "," "," "," "," "," "," "," "," "," "," ",round(sigmaB[1],4),round(t(mix_pi),4),
" "," "," "," "," "," "," "," "," "," "," "," "," ",round(B1[1],4)," "," ",round(B1[2],4)," "," "," ",round(B1[3],4)," "," "," "," "," "," "," ",round(jj,4),round(ll*100,4)," "," ",round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[9]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<-2
mi <- as.matrix(c(0.25,0.75))
meanB<-mean(dataDH)
sigmaB <- matrix((sigma_dh/2),d2,1)
sigma <- sigma0
a1 <- sqrt(sigma_dh/n_samDH)
if(mean11<mean12){a1=-a1}
meanB <- as.matrix(c((meanB+2*a1),(meanB-2*a1)))
iteration <- 0; stopa <- 1000
WW <- matrix(0,d2,n_samDH); swx <- matrix(0,d2,1)
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanB,sqrt(sigmaB),mi)))
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(dataDH,meanB[i],sqrt(sigmaB[i]))/dmixnorm(dataDH,meanB,sqrt(sigmaB),mi) }
mix_pi <- as.matrix(rowSums(WW)/n_samDH)
sumwx <- WW%*%dataDH
n0 <- n_samDH*mix_pi
n0[n0<0.000001] <- 0.000001
mean11<-(sum(dataP1)+m_fam*sumwx[1])/(n_samP1+m_fam*n0[1])
mean12<-(sum(dataP2)+m_fam*sumwx[2])/(n_samP2+m_fam*n0[2])
meanB <- as.matrix(c(mean11,mean12))
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
for(i in 1:d2) { swx[i] <- WW[i,]%*%(dataDH-meanB[i])^2 }
sigma<-(ss1+ss2+sum(swx)*m_fam)/(n_samP1+n_samP2+n_samDH)
sigmaB<-matrix((sigma/m_fam),d2,1)
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanB,sqrt(sigmaB),mix_pi)))
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) {stopa <- -stopa}
}
abc <- L1
AIC <- -2*abc + 2*3
aa<- matrix(c(1,1,1,-1),2,2)
b_line1 <- meanB
B1 <- solve(aa,b_line1)
jj <- sigma_dh - sigmaB[1]
if(jj < 0) {jj <- 0}
ll <- jj/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
for(i in 1:d2){
gg <- (dataDH - meanB[i])/sqrt(sigmaB[i])
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,i] <- bmw*mix_pi[i]
}
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("2MG-CE",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(t(meanB),4)," "," "," "," "," "," "," "," "," "," "," "," "," "," ",round(sigmaB[1],4),round(t(mix_pi),4),
" "," "," "," "," "," "," "," "," "," "," "," "," "," ",round(B1[1],4)," "," "," "," "," "," ",round(B1[2],4)," "," "," "," "," "," "," ",round(jj,4),round(ll*100,4)," "," ",round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[10]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<-2
mi <- as.matrix(c(0.75,0.25))
meanB<-mean(dataDH)
sigmaB <- matrix((sigma_dh/2),d2,1)
sigma <- sigma0
a1 <- sqrt(sigma_dh/n_samDH)
if(mean11<mean12){a1=-a1}
meanB <- as.matrix(c((meanB+2*a1),(meanB-2*a1)))
iteration <- 0; stopa <- 1000
WW <- matrix(0,d2,n_samDH); swx <- matrix(0,d2,1)
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanB,sqrt(sigmaB),mi)))
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(dataDH,meanB[i],sqrt(sigmaB[i]))/dmixnorm(dataDH,meanB,sqrt(sigmaB),mi) }
mix_pi <- as.matrix(rowSums(WW)/n_samDH)
sumwx <- WW%*%dataDH
n0 <- n_samDH*mix_pi
n0[n0<0.000001] <- 0.000001
mean11<-(sum(dataP1)+m_fam*sumwx[1])/(n_samP1+m_fam*n0[1])
mean12<-(sum(dataP2)+m_fam*sumwx[2])/(n_samP2+m_fam*n0[2])
meanB <- as.matrix(c(mean11,mean12))
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
for(i in 1:d2) { swx[i] <- WW[i,]%*%(dataDH-meanB[i])^2 }
sigma<-(ss1+ss2+sum(swx)*m_fam)/(n_samP1+n_samP2+n_samDH)
sigmaB<-matrix((sigma/m_fam),d2,1)
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanB,sqrt(sigmaB),mix_pi)))
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) {stopa <- -stopa}
}
abc <- L1
AIC <- -2*abc + 2*3
aa<- matrix(c(1,1,1,-1),2,2)
b_line1 <- meanB
B1 <- solve(aa,b_line1)
jj <- sigma_dh - sigmaB[1]
if(jj < 0) {jj <- 0}
ll <- jj/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
for(i in 1:d2){
gg <- (dataDH - meanB[i])/sqrt(sigmaB[i])
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,i] <- bmw*mix_pi[i]
}
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("2MG-DE",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(t(meanB),4)," "," "," "," "," "," "," "," "," "," "," "," "," "," ",round(sigmaB[1],4),round(t(mix_pi),4),
" "," "," "," "," "," "," "," "," "," "," "," "," "," ",round(B1[1],4)," "," "," "," "," "," ",round(B1[2],4)," "," "," "," "," "," "," ",round(jj,4),round(ll*100,4)," "," ",round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[11]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<-2
mi <- as.matrix(c(0.75,0.25))
meanB<-mean(dataDH)
sigmaB <- matrix((sigma_dh/2),d2,1)
sigma <- sigma0
a1 <- sqrt(sigma_dh/n_samDH)
if(mean11<mean12){a1=-a1}
meanB <- as.matrix(c((meanB+2*a1),(meanB-2*a1)))
iteration <- 0; stopa <- 1000
WW <- matrix(0,d2,n_samDH); swx <- matrix(0,d2,1)
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanB,sqrt(sigmaB),mi)))
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(dataDH,meanB[i],sqrt(sigmaB[i]))/dmixnorm(dataDH,meanB,sqrt(sigmaB),mi) }
mix_pi <- as.matrix(rowSums(WW)/n_samDH)
sumwx <- WW%*%dataDH
n0 <- n_samDH*mix_pi
n0[n0<0.000001] <- 0.000001
mean11<-(sum(dataP1)+sum(dataP2)+m_fam*sumwx[1])/(n_samP1+n_samP2+m_fam*n0[1])
mean12<- mean11
meanB <- as.matrix(c(mean11,sumwx[2]/n0[2]))
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
for(i in 1:d2) { swx[i] <- WW[i,]%*%(dataDH-meanB[i])^2 }
sigma<-(ss1+ss2+sum(swx)*m_fam)/(n_samP1+n_samP2+n_samDH)
sigmaB<-matrix((sigma/m_fam),d2,1)
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanB,sqrt(sigmaB),mix_pi)))
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) {stopa <- -stopa}
}
abc <- L1
AIC <- -2*abc + 2*3
aa<- matrix(c(1,1,-1,1),2,2)
b_line1 <- meanB
B1 <- solve(aa,b_line1)
jj <- sigma_dh - sigmaB[1]
if(jj < 0) {jj <- 0}
ll <- jj/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
for(i in 1:d2){
gg <- (dataDH - meanB[i])/sqrt(sigmaB[i])
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,i] <- bmw*mix_pi[i]
}
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("2MG-IE",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(t(meanB),4)," "," "," "," "," "," "," "," "," "," "," "," "," "," ",round(sigmaB[1],4),round(t(mix_pi),4),
" "," "," "," "," "," "," "," "," "," "," "," "," "," ",round(B1[1],4)," "," "," "," "," "," ",round(B1[2],4)," "," "," "," "," "," "," ",round(jj,4),round(ll*100,4)," "," ",round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[12]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<- 1;mi <- as.matrix(1)
sigma <- 2*sigma0
meanC<- mean(dataDH)
sigmaC <- sigma_dh/2
mix_pi<-1.0
iteration <- 0; stopa <- 1000
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+logL(n_samDH,1,1,meanC,sigmaC,dataDH)
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
swx<- sum((dataDH-meanC)^2)
s0<-matrix(0,2,1)
s0[1]<-(ss1+ss2);s0[2]<-swx*m_fam
s1<-sigmaC - sigma/m_fam
if (s1<0.0){ s1<- 0.0 }
abc2<- sigma ; ss1<- 0 ;abc3<-1000
while(abc3>0.0001 && ss1<1000 ){
abc1<- (sigma/m_fam)/(sigma/m_fam+s1)
sigma<- (s0[1]+abc1*abc1*s0[2])/(n_samP1+n_samP2+abc1*n_samDH)
abc3<- abs(abc2-sigma)
abc2<- sigma;ss1<-ss1+1.0
}
sigmaC <-s1+ sigma/m_fam
s1<- swx/n_samDH-sigma/m_fam;
if (s1<0.0) { s1<- 0.0 }
sigmaC<- s1+sigma/m_fam
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+logL(n_samDH,1,1,meanC,sigmaC,dataDH)
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) { stopa <- -stopa }
}
abc <- L1
AIC <- -2*abc + 2*5
ma1<- mean11
ma2<- mean12
ma3<- meanC
B1 <- as.matrix(c(ma1,ma2,ma3))
mm <- sigma_dh-sigma
if (mm<0) {mm<- 0}
nnn<- mm/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
gg <- (dataDH - meanC)/sqrt(as.vector(sigmaC))
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,1] <- bmw*mix_pi
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("PG-AI",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(meanC,4)," "," "," "," "," "," "," "," "," "," "," "," "," "," "," ",round(sigmaC[1],4),round(mix_pi[1],4),
" "," "," "," "," "," "," "," "," "," "," "," "," "," "," ",round(B1[1],4),round(B1[2],4),round(B1[3],4)," "," "," "," "," "," "," "," "," "," "," "," "," "," ",round(mm,4),round(nnn*100,4),round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[13]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<- 1;mi <- as.matrix(1)
sigma <- 2*sigma0
meanC<- mean(dataDH)
sigmaC <- sigma_dh/2
iteration <- 0; stopa <- 1000
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+logL(n_samDH,1,1,meanC,sigmaC,dataDH)
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
mix_pi<-1.0
rr<-(sum(dataP1)/n_samP1+sum(dataP2)/n_samP2-2.0*sum(dataDH)/n_samDH)/(sigma/n_samP1+sigma/n_samP2+4.0*sigmaC/n_samDH)
mean11<- (sum(dataP1)-rr*sigma)/n_samP1
mean12<- (sum(dataP2)-rr*sigma)/n_samP2
meanC <- (sum(dataDH)+2.0*rr*sigmaC)/n_samDH
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
swx<- sum((dataDH-meanC)^2)
s0<-matrix(0,2,1)
s0[1]<-(ss1+ss2);s0[2]<-swx*m_fam
s1<-sigmaC -sigma/m_fam
if (s1<0.0){ s1<- 0.0 }
abc2<- sigma; ss1<- 0.0; abc3<-1000; n_iter<- 0
while(abc3>0.0001){
n_iter<- n_iter+1
abc1<- (sigma/m_fam)/(sigma/m_fam+s1)
sigma<- (s0[1]+abc1*abc1*s0[2])/(n_samP1+n_samP2+abc1*n_samDH)
abc3<- abs(abc2-sigma)
abc2<- sigma;ss1<- ss1+1.0
if (n_iter>20) break
}
sigmaC <- s1+sigma/m_fam
s1<- swx/n_samDH-sigma/m_fam
sigmaC <- s1+ sigma/m_fam
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+logL(n_samDH,1,1,meanC,sigmaC,dataDH)
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) {stopa <- -stopa}
}
abc <- L1
AIC <- -2*abc + 2*4
aa<- matrix(c(1,1,1, 1,-1,0),3,2)
b_line1 <- as.matrix(c(mean11,mean12,meanC))
B1 <- solve(t(aa)%*%aa)%*%(t(aa)%*%b_line1)
mm <- sigma_dh - sigma
if(mm < 0) {mm <- 0}
nnn <- mm/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
gg <- (dataDH - meanC)/sqrt(as.vector(sigmaC))
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,1] <- bmw*mix_pi
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("PG-A",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(meanC,4)," "," "," "," "," "," "," "," "," "," "," "," "," "," "," ",round(sigmaC[1],4),round(mix_pi[1],4),
" "," "," "," "," "," "," "," "," "," "," "," "," "," "," ",round(B1[1],4)," "," "," "," "," "," "," "," "," "," "," "," "," ",round(B1[2],4)," "," ",round(mm,4),round(nnn*100,4),round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[14]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<- 2
mi <- as.matrix(c(0.5,0.5))
sigma <- 2*sigma0
meanD<- mean(dataDH)
sigmaD <- matrix((sigma_dh/2),d2,1)
a1 <- sqrt(sigma_dh/n_samDH)
if(mean11<mean12){a1=-a1}
meanD <- as.matrix(c((meanD+3*a1/2),(meanD-3*a1/2)))
iteration <- 0; stopa <- 1000
WW <- matrix(0,d2,n_samDH); swx <- matrix(0,d2,1)
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanD,sqrt(sigmaD),mi)))
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(dataDH,meanD[i],sqrt(sigmaD[i]))/dmixnorm(dataDH,meanD,sqrt(sigmaD),mi) }
mix_pi <- as.matrix(rowSums(WW)/n_samDH)
sumwx <- WW%*%dataDH
n0 <- n_samDH*mix_pi
n0[n0<0.000001] <- 0.000001
mean11<- sum(dataP1)/n_samP1
mean12<- sum(dataP2)/n_samP2
meanD <- sumwx/n0
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
for(i in 1:d2) { swx[i] <- WW[i,]%*%(dataDH-meanD[i])^2 }
s0<-matrix(0,2,1)
s0[1]<- ss1+ss2
s0[2]<- sum(swx)*m_fam
s1<- sigmaD[1]-sigma/m_fam
if (s1<0.0){s1<- 0.000001}
abc2<- sigma
abc3<-1000; n_iter<- 0
while(abc3>0.0001){
n_iter<- n_iter+1
abc1<- (sigma/m_fam)/(sigma/m_fam+s1)
sigma<- (s0[1]+abc1*abc1*s0[2])/(n_samP1+n_samP2+abc1*n_samDH)
abc3<- abs(abc2-sigma)
abc2<- sigma
if (n_iter>20) break
}
if (sigma<0.1*sigma0){ sigma<- 0.1*sigma0 }
sigmaD[1]<- s1+sigma/m_fam
s1<- sum(swx)/n_samDH-sigma/m_fam
if (s1<0.0){ s1<- 0.000001 }
sigmaD<- matrix((s1+sigma/m_fam),d2,1)
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanD,sqrt(sigmaD),mix_pi)))
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) {stopa <- -stopa}
}
abc <- L1
AIC <- -2*abc + 2*6
aa<- matrix(c(1,0,0,0, 0,1,0,0, 0,0,1,1, 1,-1,1,-1),4,4)
b_line1 <- as.matrix(c(mean11,mean12,meanD))
B1 <- solve(aa,b_line1)
jj <- sigma_dh - sigmaD[1]
if(jj < 0) {jj <- 0}
ll <- jj/sigma_dh
mm<- sigmaD[1]-sigma
if (mm<0) {mm<- 0}
nnn<- mm/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
for(i in 1:d2){
gg <- (dataDH - meanD[i])/sqrt(sigmaD[i])
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,i] <- bmw*mix_pi[i]
}
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("MX1-A-AI",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(t(meanD),4)," "," "," "," "," "," "," "," "," "," "," "," "," "," ",round(sigmaD[1],4),round(t(mix_pi),4),
" "," "," "," "," "," "," "," "," "," "," "," "," "," ",round(B1[1],4),round(B1[2],4),round(B1[3],4),round(B1[3],4)," "," "," "," "," "," "," "," "," "," "," ",round(jj,4),round(ll*100,4),round(mm,4),round(nnn*100,4),round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[15]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<- 2
mi <- as.matrix(c(0.5,0.5))
sigma <- 2*sigma0
meanD<- mean(dataDH)
sigmaD <- matrix((sigma_dh/2),d2,1)
a1 <- sqrt(sigma_dh/n_samDH)
if(mean11<mean12){a1=-a1}
meanD <- as.matrix(c((meanD+3*a1/2),(meanD-3*a1/2)))
iteration <- 0; stopa <- 1000
WW <- matrix(0,d2,n_samDH); swx <- matrix(0,d2,1)
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanD,sqrt(sigmaD),mi)))
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(dataDH,meanD[i],sqrt(sigmaD[i]))/dmixnorm(dataDH,meanD,sqrt(sigmaD),mi) }
mix_pi <- as.matrix(rowSums(WW)/n_samDH)
sumwx <- WW%*%dataDH
n0 <- n_samDH*mix_pi
n0[n0<0.000001] <- 0.000001
rr<- (sum(dataP1)/n_samP1+sum(dataP2)/n_samP2-sumwx[1]/n0[1]-sumwx[2]/n0[2])/(sigma/n_samP1+sigma/n_samP2+sigmaD[1]/n0[1]+sigmaD[1]/n0[2])
mean11<- (sum(dataP1)-rr*sigma)/n_samP1
mean12<- (sum(dataP2)-rr*sigma)/n_samP2
meanD <- (sumwx+rr*sigmaD[1])/n0
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
for(i in 1:d2) { swx[i] <- WW[i,]%*%(dataDH-meanD[i])^2 }
s0<-matrix(0,2,1)
s0[1]<- ss1+ss2
s0[2]<- sum(swx)*m_fam
s1<- sigmaD[1]-sigma/m_fam
if (s1<0.0){s1<- 0.000001}
abc2<- sigma
abc3<-1000; n_iter<- 0
while(abc3>0.0001){
n_iter<- n_iter+1
abc1<- (sigma/m_fam)/(sigma/m_fam+s1)
sigma<- (s0[1]+abc1*abc1*s0[2])/(n_samP1+n_samP2+abc1*n_samDH)
abc3<- abs(abc2-sigma)
abc2<- sigma
if (n_iter>20) break
}
if (sigma<0.1*sigma0){ sigma<- 0.1*sigma0 }
sigmaD[1]<- s1+sigma/m_fam
s1<- sum(swx)/n_samDH-sigma/m_fam
if (s1<0.0){ s1<- 0 }
sigmaD<- matrix((s1+sigma/m_fam),d2,1)
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanD,sqrt(sigmaD),mix_pi)))
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) {stopa <- -stopa}
}
abc <- L1
AIC <- -2*abc + 2*5
aa<- matrix(c(1,1,1,1, 1,-1,1,-1, 1,-1,0,0),4,3)
b_line1 <- as.matrix(c(mean11,mean12,meanD))
B1 <- solve(t(aa)%*%aa)%*%(t(aa)%*%b_line1)
jj <- sigma_dh - sigmaD[1]
if(jj < 0) {jj <- 0}
ll <- jj/sigma_dh
mm<- sigmaD[1]-sigma
if (mm<0) {mm<- 0}
nnn<- mm/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
for(i in 1:d2){
gg <- (dataDH - meanD[i])/sqrt(sigmaD[i])
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,i] <- bmw*mix_pi[i]
}
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("MX1-A-A",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(t(meanD),4)," "," "," "," "," "," "," "," "," "," "," "," "," "," ",round(sigmaD[1],4),round(t(mix_pi),4),
" "," "," "," "," "," "," "," "," "," "," "," "," "," ",round(B1[1],4)," "," ",round(B1[2],4)," "," "," "," "," "," "," "," "," "," ",round(B1[3],4),round(jj,4),round(ll*100,4),round(mm,4),round(nnn*100,4),round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[16]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<-4
mi <- as.matrix(c(0.25,0.25,0.25,0.25))
meanE<-mean(dataDH)
sigmaE <- matrix((sigma_dh/2*1.2222101),d2,1)
sigma <- sigma0
a1 <- sqrt(sigma_dh/n_samDH)
if(mean11<mean12){a1=-a1}
meanE <- as.matrix(c((meanE+3*a1),(meanE+1.5*a1),(meanE-1.5*a1),(meanE-3*a1)))
iteration <- 0; stopa <- 1000
WW <- matrix(0,d2,n_samDH); swx <- matrix(0,d2,1)
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanE,sqrt(sigmaE),mi)))
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(dataDH,meanE[i],sqrt(sigmaE[i]))/dmixnorm(dataDH,meanE,sqrt(sigmaE),mi) }
mix_pi <- as.matrix(rowSums(WW)/n_samDH)
sumwx <- WW%*%dataDH
n0 <- n_samDH*mix_pi
n0[n0<0.000001] <- 0.000001
mean11<- sum(dataP1)/n_samP1
mean12<- sum(dataP2)/n_samP2
meanE <- sumwx/n0
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
for(i in 1:d2) { swx[i] <- WW[i,]%*%(dataDH-meanE[i])^2 }
s0<-matrix(0,2,1)
s0[1]<- ss1+ss2
s0[2]<- sum(swx)*m_fam
s1<- sigmaE[1]-sigma/m_fam
if (s1<0.0){s1<- 0.000001}
abc2<- sigma; abc3<-1000; n_iter<- 0
while(abc3>0.0001){
n_iter<- n_iter+1
abc1<- (sigma/m_fam)/(sigma/m_fam+s1)
sigma<- (s0[1]+abc1*abc1*s0[2])/(n_samP1+n_samP2+abc1*n_samDH)
abc3<- abs(abc2-sigma)
abc2<- sigma
if (n_iter>20) break
}
if (sigma<0.1*sigma0){ sigma<- 0.1*sigma0 }
sigmaE[1]<- s1+sigma/m_fam
s1<- sum(swx)/n_samDH-sigma/m_fam
if (s1<0.0){ s1<- 0.000001 }
sigmaE<- matrix((s1+sigma/m_fam),d2,1)
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanE,sqrt(sigmaE),mix_pi)))
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) {stopa <- -stopa}
}
abc <- L1
AIC <- -2*abc + 2*8
aa<- matrix(c(1,0,0,0,0,0, 0,1,0,0,0,0, 0,0,1,1,1,1, 1,-1,1,1,-1,-1, 1,-1,1,-1,1,-1, 1,1,1,-1,-1,1),6,6)
b_line1 <- as.matrix(c(mean11,mean12,meanE))
B1 <- solve(aa,b_line1)
jj <- sigma_dh - sigmaE[1]
if(jj < 0) {jj <- 0}
ll <- jj/sigma_dh
mm<- sigmaE[1]-sigma[1]
if(mm<0){mm<-0}
nnn<- mm/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
for(i in 1:d2){
gg <- (dataDH - meanE[i])/sqrt(sigmaE[i])
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,i] <- bmw*mix_pi[i]
}
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("MX2-AI-AI",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(t(meanE),4)," "," "," "," "," "," "," "," "," "," "," "," ",round(sigmaE[1],4),round(t(mix_pi),4),
" "," "," "," "," "," "," "," "," "," "," "," ",round(B1[1],4),round(B1[2],4),round(B1[3],4),round(B1[4],4),round(B1[5],4)," "," ",round(B1[6],4)," "," "," "," "," "," "," ",round(jj,4),round(ll*100,4),round(mm,4),round(nnn*100,4),round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[17]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<-4
mi <- as.matrix(c(0.25,0.25,0.25,0.25))
meanE<-mean(dataDH)
sigmaE <- matrix((sigma_dh/2*1.2222101),d2,1)
sigma <- sigma0
a1 <- sqrt(sigma_dh/n_samDH)
if(mean11<mean12){a1=-a1}
meanE <- as.matrix(c((meanE+3*a1),(meanE+1.5*a1),(meanE-1.5*a1),(meanE-3*a1)))
iteration <- 0; stopa <- 1000
WW <- matrix(0,d2,n_samDH); swx <- matrix(0,d2,1)
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanE,sqrt(sigmaE),mi)))
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(dataDH,meanE[i],sqrt(sigmaE[i]))/dmixnorm(dataDH,meanE,sqrt(sigmaE),mi) }
mix_pi <- as.matrix(rowSums(WW)/n_samDH)
sumwx <- WW%*%dataDH
n0 <- n_samDH*mix_pi
n0[n0<0.000001] <- 0.000001
rr<-(sum(dataP1)/n_samP1+sum(dataP2)/n_samP2-sumwx[1]/n0[1]-sumwx[4]/n0[4])/(sigma/n_samP1+sigma/n_samP2+sigmaE[1]/n0[1]+sigmaE[4]/n0[4])
mean11<- (sum(dataP1)-rr*sigma)/n_samP1
mean12<- (sum(dataP2)-rr*sigma)/n_samP2
meanE[1]<- (sumwx[1]+rr*sigmaE[1])/n0[1]
meanE[2]<- sumwx[2]/n0[2]
meanE[3]<- sumwx[3]/n0[3]
meanE[4]<- (sumwx[4]+rr*sigmaE[4])/n0[4]
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
for(i in 1:d2) { swx[i] <- WW[i,]%*%(dataDH-meanE[i])^2 }
s0<-matrix(0,2,1)
s0[1]<- ss1+ss2
s0[2]<- sum(swx)*m_fam
s1<- sigmaE[1]-sigma/m_fam
if (s1<0.0){s1<- 0.000001}
abc2<- sigma
abc3<-1000; n_iter<- 0
while(abc3>0.0001){
n_iter<- n_iter+1
abc1<- (sigma/m_fam)/(sigma/m_fam+s1)
sigma<- (s0[1]+abc1*abc1*s0[2])/(n_samP1+n_samP2+abc1*n_samDH)
abc3<- abs(abc2-sigma)
abc2<- sigma
if (n_iter>20) break
}
if (sigma<0.1*sigma0){ sigma<- 0.1*sigma0 }
sigmaE[1]<- s1+sigma/m_fam
s1<- sum(swx)/n_samDH-sigma/m_fam
if (s1<0.0){ s1<- 0.000001 }
sigmaE<- matrix((s1+sigma/m_fam),d2,1)
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanE,sqrt(sigmaE),mix_pi)))
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) {stopa <- -stopa}
}
abc <- L1
AIC <- -2*abc + 2*7
aa<- matrix(c(1,1,1,1,1,1, 1,-1,1,1,-1,-1, 1,-1,1,-1,1,-1, 1,-1,0,0,0,0, 1,1,1,-1,-1,1),6,5)
b_line1 <- as.matrix(c(mean11,mean12,meanE))
B1 <- solve(t(aa)%*%aa)%*%(t(aa)%*%b_line1)
jj <- sigma_dh - sigmaE[1]
if(jj < 0) {jj <- 0}
ll <- jj/sigma_dh
mm<- sigmaE[1]-sigma[1]
if(mm<0){mm<-0}
nnn<- mm/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
for(i in 1:d2){
gg <- (dataDH - meanE[i])/sqrt(sigmaE[i])
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,i] <- bmw*mix_pi[i]
}
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("MX2-AI-A",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(t(meanE),4)," "," "," "," "," "," "," "," "," "," "," "," ",round(sigmaE[1],4),round(t(mix_pi),4),
" "," "," "," "," "," "," "," "," "," "," "," ",round(B1[1],4)," "," ",round(B1[2],4),round(B1[3],4)," "," ",round(B1[4],4)," "," "," "," "," "," ",round(B1[5],4),round(jj,4),round(ll*100,4),round(mm,4),round(nnn*100,4),round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[18]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<-4
mi <- as.matrix(c(0.25,0.25,0.25,0.25))
meanE<-mean(dataDH)
sigmaE <- matrix((sigma_dh/2*1.2222101),d2,1)
sigma <- sigma0
a1 <- sqrt(sigma_dh)
if(mean11<mean12){a1=-a1}
meanE <- as.matrix(c((meanE+3*a1),(meanE+1.5*a1),(meanE-1.5*a1),(meanE-3*a1)))
iteration <- 0; stopa <- 1000
WW <- matrix(0,d2,n_samDH); swx <- matrix(0,d2,1)
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanE,sqrt(sigmaE),mi)))
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(dataDH,meanE[i],sqrt(sigmaE[i]))/dmixnorm(dataDH,meanE,sqrt(sigmaE),mi) }
mix_pi <- as.matrix(rowSums(WW)/n_samDH)
sumwx <- WW%*%dataDH
n0 <- n_samDH*mix_pi
n0[n0<0.000001] <- 0.000001
s0<- matrix(0,6,1)
s0[1]<- sum(dataP1)/n_samP1+sum(dataP2)/n_samP2-sumwx[1]/n0[1]-sumwx[4]/n0[4]
s0[2]<- sumwx[1]/n0[1]-sumwx[2]/n0[2]-sumwx[3]/n0[3]+sumwx[4]/n0[4]
s0[3]<- sigma/n_samP1+sigma/n_samP2+sigmaE[1]/n0[1]+sigmaE[4]/n0[4]
s0[4]<- -sigmaE[1]/n0[1]-sigmaE[4]/n0[4]
s0[5]<- sigmaE[1]/n0[1]+sigmaE[2]/n0[2]+sigmaE[3]/n0[3]+sigmaE[4]/n0[4]
s0[6]<- s0[3]*s0[5]-s0[4]*s0[4]
rr<- matrix(0,2,1)
rr[1]<- (s0[1]*s0[5]-s0[2]*s0[4])/s0[6]
rr[2]<- (s0[2]*s0[3]-s0[1]*s0[4])/s0[6]
mean11<- (sum(dataP1)-rr[1]*sigma)/n_samP1
mean12<- (sum(dataP2)-rr[1]*sigma)/n_samP2
meanE[1]<- (sumwx[1]+sigmaE[1]*(rr[1]-rr[2]))/n0[1]
meanE[2]<- (sumwx[2]+sigmaE[2]*rr[2])/n0[2]
meanE[3]<- (sumwx[3]+sigmaE[3]*rr[2])/n0[3]
meanE[4]<- (sumwx[4]+sigmaE[4]*(rr[1]-rr[2]))/n0[4]
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
for(i in 1:d2) { swx[i] <- WW[i,]%*%(dataDH-meanE[i])^2 }
s0E<-matrix(0,2,1)
s0E[1]<- ss1+ss2
s0E[2]<- sum(swx)*m_fam
s1<- sigmaE[1]-sigma/m_fam
if (s1<0.0){s1<- 0.000001 }
abc2<- sigma
abc3<-1000; n_iter<- 0
while(abc3>0.0001){
n_iter<- n_iter+1
abc1<- (sigma/m_fam)/(sigma/m_fam+s1)
sigma<- (s0E[1]+abc1*abc1*s0E[2])/(n_samP1+n_samP2+abc1*n_samDH)
abc3<- abs(abc2-sigma)
abc2<- sigma
if (n_iter>20) break
}
if (sigma<0.1*sigma0){ sigma<- 0.1*sigma0 }
sigmaE[1]<- s1+sigma/m_fam
s1<- sum(swx)/n_samDH-sigma/m_fam
if (s1<0.0){ s1<- 0.000001 }
sigmaE<- matrix((s1+sigma/m_fam),d2,1)
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanE,sqrt(sigmaE),mix_pi)))
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) {stopa <- -stopa}
}
abc <- L1
AIC <- -2*abc + 2*6
aa<- matrix(c(1,1,1,1,1,1, 1,-1,1,1,-1,-1, 1,-1,1,-1,1,-1, 1,-1,0,0,0,0),6,4)
b_line1 <- as.matrix(c(mean11,mean12,meanE))
B1 <- solve(t(aa)%*%aa)%*%(t(aa)%*%b_line1)
jj <- sigma_dh - sigmaE[1]
if(jj < 0) {jj <- 0}
ll <- jj/sigma_dh
mm<- sigmaE[1]-sigma[1]
if(mm<0){mm<-0}
nnn<- mm/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
for(i in 1:d2){
gg <- (dataDH - meanE[i])/sqrt(sigmaE[i])
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,i] <- bmw*mix_pi[i]
}
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("MX2-A-A",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(t(meanE),4)," "," "," "," "," "," "," "," "," "," "," "," ",round(sigmaE[1],4),round(t(mix_pi),4),
" "," "," "," "," "," "," "," "," "," "," "," ",round(B1[1],4)," "," ",round(B1[2],4),round(B1[3],4)," "," "," "," "," "," "," "," "," ",round(B1[4],4),round(jj,4),round(ll*100,4),round(mm,4),round(nnn*100,4),round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[19]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<-3
mi <- as.matrix(c(0.25,0.5,0.25))
meanE<-mean(dataDH)
sigmaE <- matrix((sigma_dh/2*1.2222101),d2,1)
sigma <- sigma0
a1 <- sqrt(sigma_dh)
if(mean11<mean12){a1=-a1}
meanE <- as.matrix(c(114,100,86))
iteration <- 0; stopa <- 1000
WW <- matrix(0,d2,n_samDH); swx <- matrix(0,d2,1)
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanE,sqrt(sigmaE),mi)))
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(dataDH,meanE[i],sqrt(sigmaE[i]))/dmixnorm(dataDH,meanE,sqrt(sigmaE),mi) }
mix_pi <- as.matrix(rowSums(WW)/n_samDH)
sumwx <- WW%*%dataDH
n0 <- n_samDH*mix_pi
n0[n0<0.000001] <- 0.000001
s0<- matrix(0,6,1)
s0[1]<- sum(dataP1)/n_samP1+sum(dataP2)/n_samP2-2*sumwx[2]/n0[2]
s0[2]<- sumwx[1]/n0[1]-2*sumwx[2]/n0[2]+sumwx[3]/n0[3]
s0[3]<- sigma/n_samP1+sigma/n_samP2+4*sigmaE[2]/n0[2]
s0[4]<- 4*sigmaE[2]/n0[2]
s0[5]<- sigmaE[1]/n0[1]+4*sigmaE[2]/n0[2]+sigmaE[3]/n0[3]
s0[6]<- s0[3]*s0[5]-s0[4]*s0[4]
rr<- matrix(0,2,1)
rr[1]<- (s0[1]*s0[5]-s0[2]*s0[4])/s0[6]
rr[2]<- (s0[2]*s0[3]-s0[1]*s0[4])/s0[6]
mean11<- (sum(dataP1)-rr[1]*sigma)/n_samP1
mean12<- (sum(dataP2)-rr[1]*sigma)/n_samP2
meanE[1]<- (sumwx[1]-sigmaE[1]*rr[2])/n0[1]
meanE[2]<- (sumwx[2]+sigmaE[2]*(2.0*rr[1]+2.0*rr[2]))/n0[2]
meanE[3]<- (sumwx[3]-sigmaE[3]*rr[2])/n0[3]
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
for(i in 1:d2) { swx[i] <- WW[i,]%*%(dataDH-meanE[i])^2 }
s0E<-matrix(0,2,1)
s0E[1]<- ss1+ss2
s0E[2]<- sum(swx)*m_fam
s1<- sigmaE[1]-sigma/m_fam
if (s1<0.0){s1<- 0.000001}
abc2<- sigma
abc3<-1000; n_iter<- 0
while(abc3>0.0001){
n_iter<- n_iter+1
abc1<- (sigma/m_fam)/(sigma/m_fam+s1)
sigma<- (s0E[1]+abc1*abc1*s0E[2])/(n_samP1+n_samP2+abc1*n_samDH)
abc3<- abs(abc2-sigma)
abc2<- sigma
if (n_iter>20) break
}
if (sigma<0.1*sigma0){ sigma<- 0.1*sigma0 }
sigmaE[1]<- s1+sigma/m_fam
s1<- sum(swx)/n_samDH-sigma/m_fam
if (s1<0.0){ s1<- 0.000001 }
sigmaE<- matrix((s1+sigma/m_fam),d2,1)
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanE,sqrt(sigmaE),mix_pi)))
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) {stopa <- -stopa}
}
abc <- L1
AIC <- -2*abc + 2*5
aa<- matrix(c(1,1,1,1,1, 2,-2,2,0,-2, 1,1,0,0,0),5,3)
b_line1 <- as.matrix(c(mean11,mean12,meanE))
B1 <- solve(t(aa)%*%aa)%*%(t(aa)%*%b_line1)
jj <- sigma_dh - sigmaE[1]
if(jj < 0) {jj <- 0}
ll <- jj/sigma_dh
mm<- sigmaE[1]-sigma[1]
if(mm<0){mm<-0}
nnn<- mm/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
for(i in 1:d2){
gg <- (dataDH - meanE[i])/sqrt(sigmaE[i])
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,i] <- bmw*mix_pi[i]
}
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("MX2-EA-A",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(t(meanE),4)," "," "," "," "," "," "," "," "," "," "," "," "," ",round(sigmaE[1],4),round(t(mix_pi),4),
" "," "," "," "," "," "," "," "," "," "," "," "," ",round(B1[1],4)," "," ",round(B1[2],4),round(B1[2],4)," "," "," "," "," "," "," "," "," ",round(B1[3],4),round(jj,4),round(ll*100,4),round(mm,4),round(nnn*100,4),round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[20]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<-3
mi <- as.matrix(c(0.5,0.25,0.25))
meanE<-mean(dataDH)
sigmaE <- matrix((sigma_dh/2*1.2222101),d2,1)
sigma <- sigma0
a1 <- sqrt(sigma_dh/n_samDH)
if(mean11<mean12){a1=-a1}
meanE <- as.matrix(c((meanE+2*a1),meanE,(meanE-2*a1)))
iteration <- 0; stopa <- 1000
WW <- matrix(0,d2,n_samDH); swx <- matrix(0,d2,1)
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanE,sqrt(sigmaE),mi)))
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(dataDH,meanE[i],sqrt(sigmaE[i]))/dmixnorm(dataDH,meanE,sqrt(sigmaE),mi) }
mix_pi <- as.matrix(rowSums(WW)/n_samDH)
sumwx <- WW%*%dataDH
n0 <- n_samDH*mix_pi
n0[n0<0.000001] <- 0.000001
rr<- (sum(dataP1)/n_samP1+sum(dataP2)/n_samP2-sumwx[1]/n0[1]-sumwx[3]/n0[3])/(sigma/n_samP1+sigma/n_samP2+sigmaE[1]/n0[1]+sigmaE[3]/n0[3])
mean11<- (sum(dataP1)-rr[1]*sigma)/n_samP1
mean12<- (sum(dataP2)-rr[1]*sigma)/n_samP2
meanE[1]<- (sumwx[1]+sigmaE[1]*rr)/n0[1]
meanE[2]<- sumwx[2]/n0[2]
meanE[3]<- (sumwx[3]+sigmaE[3]*rr)/n0[3]
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
for(i in 1:d2) { swx[i] <- WW[i,]%*%(dataDH-meanE[i])^2 }
s0E<-matrix(0,2,1)
s0E[1]<- ss1+ss2
s0E[2]<- sum(swx)*m_fam
s1<- sigmaE[1]-sigma/m_fam
if (s1<0.0){s1<- 0.000001}
abc2<- sigma
abc3<-1000; n_iter<- 0
while(abc3>0.0001){
n_iter<- n_iter+1
abc1<- (sigma/m_fam)/(sigma/m_fam+s1)
sigma<- (s0E[1]+abc1*abc1*s0E[2])/(n_samP1+n_samP2+abc1*n_samDH)
abc3<- abs(abc2-sigma)
abc2<- sigma
if (n_iter>20) break
}
if (sigma<0.1*sigma0){ sigma<- 0.1*sigma0 }
sigmaE[1]<- s1+sigma/m_fam
s1<- sum(swx)/n_samDH-sigma/m_fam
if (s1<0.0){ s1<- 0.000001 }
sigmaE<- matrix((s1+sigma/m_fam),d2,1)
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanE,sqrt(sigmaE),mix_pi)))
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) {stopa <- -stopa}
}
abc <- L1
AIC <- -2*abc + 2*6
aa<- matrix(c(1,1,1,1,1, 1,-1,1,-1,-1, 0,-1,0,1,-1, 1,-1,0,0,0),5,4)
b_line1 <- as.matrix(c(mean11,mean12,meanE))
B1 <- solve(t(aa)%*%aa)%*%(t(aa)%*%b_line1)
jj <- sigma_dh - sigmaE[1]
if(jj < 0) {jj <- 0}
ll <- jj/sigma_dh
mm<- sigmaE[1]-sigma[1]
if(mm<0){mm<-0}
nnn<- mm/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
for(i in 1:d2){
gg <- (dataDH - meanE[i])/sqrt(sigmaE[i])
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,i] <- bmw*mix_pi[i]
}
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("MX2-ED-A",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(t(meanE),4)," "," "," "," "," "," "," "," "," "," "," "," "," ",round(sigmaE[1],4),round(t(mix_pi),4),
" "," "," "," "," "," "," "," "," "," "," "," "," ",round(B1[1],4)," "," ",round(B1[2],4),round(B1[3],4)," "," "," "," "," "," "," "," "," ",round(B1[4],4),round(jj,4),round(ll*100,4),round(mm,4),round(nnn*100,4),round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[21]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<-3
mi <- as.matrix(c(0.25,0.25,0.5))
meanE<-mean(dataDH)
sigmaE <- matrix((sigma_dh/2*1.2222101),d2,1)
sigma <- sigma0
a1 <- sqrt(sigma_dh/n_samDH)
if(mean11<mean12){a1=-a1}
meanE <- as.matrix(c((meanE+2*a1),meanE,(meanE-2*a1)))
iteration <- 0; stopa <- 1000
WW <- matrix(0,d2,n_samDH); swx <- matrix(0,d2,1)
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanE,sqrt(sigmaE),mi)))
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(dataDH,meanE[i],sqrt(sigmaE[i]))/dmixnorm(dataDH,meanE,sqrt(sigmaE),mi) }
mix_pi <- as.matrix(rowSums(WW)/n_samDH)
sumwx <- WW%*%dataDH
n0 <- n_samDH*mix_pi
n0[n0<0.000001] <- 0.000001
rr<- (sum(dataP1)/n_samP1+sum(dataP2)/n_samP2-sumwx[1]/n0[1]-sumwx[3]/n0[3])/(sigma/n_samP1+sigma/n_samP2+sigmaE[1]/n0[1]+sigmaE[3]/n0[3])
mean11<- (sum(dataP1)-rr[1]*sigma)/n_samP1
mean12<- (sum(dataP2)-rr[1]*sigma)/n_samP2
meanE[1]<- (sumwx[1]+sigmaE[1]*rr)/n0[1]
meanE[2]<- sumwx[2]/n0[2]
meanE[3]<- (sumwx[3]+sigmaE[3]*rr)/n0[3]
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
for(i in 1:d2) { swx[i] <- WW[i,]%*%(dataDH-meanE[i])^2 }
s0E<-matrix(0,2,1)
s0E[1]<- ss1+ss2
s0E[2]<- sum(swx)*m_fam
s1<- sigmaE[1]-sigma/m_fam
if (s1<0.0){s1<- 0.000001}
abc2<- sigma
abc3<-1000; n_iter<- 0
while(abc3>0.0001){
n_iter<- n_iter+1
abc1<- (sigma/m_fam)/(sigma/m_fam+s1)
sigma<- (s0E[1]+abc1*abc1*s0E[2])/(n_samP1+n_samP2+abc1*n_samDH)
abc3<- abs(abc2-sigma)
abc2<- sigma
if (n_iter>20) break
}
if (sigma<0.1*sigma0){ sigma<- 0.1*sigma0 }
sigmaE[1]<- s1+sigma/m_fam
s1<- sum(swx)/n_samDH-sigma/m_fam
if (s1<0.0){ s1<- 0.000001 }
sigmaE<- matrix((s1+sigma/m_fam),d2,1)
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanE,sqrt(sigmaE),mix_pi)))
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) {stopa <- -stopa}
}
abc <- L1
AIC <- -2*abc + 2*6
aa<- matrix(c(1,1,1,1,1, 1,-1,1,1,-1, 1,0,1,-1,0, 1,-1,0,0,0),5,4)
b_line1 <- as.matrix(c(mean11,mean12,meanE))
B1 <- solve(t(aa)%*%aa)%*%(t(aa)%*%b_line1)
jj <- sigma_dh - sigmaE[1]
if(jj < 0) {jj <- 0}
ll <- jj/sigma_dh
mm<- sigmaE[1]-sigma[1]
if(mm<0){mm<-0}
nnn<- mm/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
for(i in 1:d2){
gg <- (dataDH - meanE[i])/sqrt(sigmaE[i])
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,i] <- bmw*mix_pi[i]
}
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("MX2-ER-A",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(t(meanE),4)," "," "," "," "," "," "," "," "," "," "," "," "," ",round(sigmaE[1],4),round(t(mix_pi),4),
" "," "," "," "," "," "," "," "," "," "," "," "," ",round(B1[1],4)," "," ",round(B1[2],4),round(B1[3],4)," "," "," "," "," "," "," "," "," ",round(B1[4],4),round(jj,4),round(ll*100,4),round(mm,4),round(nnn*100,4),round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[22]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<-3
mi <- as.matrix(c(0.25,0.5,0.25))
meanE<-mean(dataDH)
sigmaE <- matrix((sigma_dh/2*1.2222101),d2,1)
sigma <- sigma0
a1 <- sqrt(sigma_dh/n_samDH)
if(mean11<mean12){a1=-a1}
meanE <- as.matrix(c((meanE+2*a1),meanE,(meanE-2*a1)))
iteration <- 0; stopa <- 1000
WW <- matrix(0,d2,n_samDH); swx <- matrix(0,d2,1)
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanE,sqrt(sigmaE),mi)))
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(dataDH,meanE[i],sqrt(sigmaE[i]))/dmixnorm(dataDH,meanE,sqrt(sigmaE),mi) }
mix_pi <- as.matrix(rowSums(WW)/n_samDH)
sumwx <- WW%*%dataDH
n0 <- n_samDH*mix_pi
n0[n0<0.000001] <- 0.000001
rr<- (sum(dataP1)/n_samP1+sum(dataP2)/n_samP2-sumwx[1]/n0[1]-sumwx[3]/n0[3])/(sigma/n_samP1+sigma/n_samP2+sigmaE[1]/n0[1]+sigmaE[3]/n0[3])
mean11<- (sum(dataP1)-rr*sigma)/n_samP1
mean12<- (sum(dataP2)-rr*sigma)/n_samP2
meanE[1]<- (sumwx[1]+sigmaE[1]*rr)/n0[1]
meanE[2]<- sumwx[2]/n0[2]
meanE[3]<- (sumwx[3]+sigmaE[1]*rr)/n0[3]
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
for(i in 1:d2) { swx[i] <- WW[i,]%*%(dataDH-meanE[i])^2 }
s0E<-matrix(0,2,1)
s0E[1]<- ss1+ss2
s0E[2]<- sum(swx)*m_fam
s1<- sigmaE[1]-sigma/m_fam
if (s1<0.0){s1<- 0.000001}
abc2<- sigma
abc3<-1000; n_iter<- 0
while(abc3>0.0001){
n_iter<- n_iter+1
abc1<- (sigma/m_fam)/(sigma/m_fam+s1)
sigma<- (s0E[1]+abc1*abc1*s0E[2])/(n_samP1+n_samP2+abc1*n_samDH)
abc3<- abs(abc2-sigma)
abc2<- sigma
if (n_iter>20) break
}
if (sigma<0.1*sigma0){ sigma<- 0.1*sigma0 }
sigmaE[1]<- s1+sigma/m_fam
s1<- sum(swx)/n_samDH-sigma/m_fam
if (s1<0.0){ s1<- 0.000001 }
sigmaE<- matrix((s1+sigma/m_fam),d2,1)
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanE,sqrt(sigmaE),mix_pi)))
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) {stopa <- -stopa}
}
abc <- L1
AIC <- -2*abc + 2*6
aa<- matrix(c(1,1,1,1,1, 2,-2,2,0,-2, 1,1,1,-1,1, 1,-1,0,0,0),5,4)
b_line1 <- as.matrix(c(mean11,mean12,meanE))
B1 <- solve(t(aa)%*%aa)%*%(t(aa)%*%b_line1)
jj <- sigma_dh - sigmaE[1]
if(jj < 0) {jj <- 0}
ll <- jj/sigma_dh
mm<- sigmaE[1]-sigma[1]
if(mm<0){mm<-0}
nnn<- mm/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
for(i in 1:d2){
gg <- (dataDH - meanE[i])/sqrt(sigmaE[i])
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,i] <- bmw*mix_pi[i]
}
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("MX2-AE-A",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(t(meanE),4)," "," "," "," "," "," "," "," "," "," "," "," "," ",round(sigmaE[1],4),round(t(mix_pi),4),
" "," "," "," "," "," "," "," "," "," "," "," "," ",round(B1[1],4)," "," ",round(B1[2],4)," "," "," ",round(B1[3],4)," "," "," "," "," "," ",round(B1[4],4),round(jj,4),round(ll*100,4),round(mm,4),round(nnn*100,4),round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[23]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<-2
mi <- as.matrix(c(0.25,0.75))
meanE<-mean(dataDH)
sigmaE <- matrix((sigma_dh/2*1.2222101),d2,1)
sigma <- sigma0
a1 <- sqrt(sigma_dh/n_samDH)
if(mean11<mean12){a1=-a1}
meanE <- as.matrix(c((meanE+1.5*a1),(meanE-1.5*a1)))
iteration <- 0; stopa <- 1000
WW <- matrix(0,d2,n_samDH); swx <- matrix(0,d2,1)
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanE,sqrt(sigmaE),mi)))
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(dataDH,meanE[i],sqrt(sigmaE[i]))/dmixnorm(dataDH,meanE,sqrt(sigmaE),mi) }
mix_pi <- as.matrix(rowSums(WW)/n_samDH)
sumwx <- WW%*%dataDH
n0 <- n_samDH*mix_pi
n0[n0<0.000001] <- 0.000001
rr<- (sum(dataP1)/n_samP1+sum(dataP2)/n_samP2-2*sumwx[1]/n0[1])/(sigma/n_samP1+sigma/n_samP2+sigmaE[1]/n0[1])
mean11<- (sum(dataP1)-rr*sigma)/n_samP1
mean12<- (sum(dataP2)-rr*sigma)/n_samP2
meanE[1]<- (sumwx[1]+sigmaE[1]*rr)/n0[1]
meanE[2]<- (sumwx[2]+sigmaE[2]*rr)/n0[2]
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
for(i in 1:d2) { swx[i] <- WW[i,]%*%(dataDH-meanE[i])^2 }
s0E<-matrix(0,2,1)
s0E[1]<- ss1+ss2
s0E[2]<- sum(swx)*m_fam
s1<- sigmaE[1]-sigma/m_fam
if (s1<0.0){s1<- 0.000001}
abc2<- sigma
abc3<-1000; n_iter<- 0
while(abc3>0.0001){
n_iter<- n_iter+1
abc1<- (sigma/m_fam)/(sigma/m_fam+s1)
sigma<- (s0E[1]+abc1*abc1*s0E[2])/(n_samP1+n_samP2+abc1*n_samDH)
abc3<- abs(abc2-sigma)
abc2<- sigma
if (n_iter>20) break
}
if (sigma<0.1*sigma0){ sigma<- 0.1*sigma0 }
sigmaE[1]<- s1+sigma/m_fam
s1<- sum(swx)/n_samDH-sigma/m_fam
if (s1<0.0){ s1<- 0.000001 }
sigmaE<- matrix((s1+sigma/m_fam),d2,1)
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanE,sqrt(sigmaE),mix_pi)))
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) {stopa <- -stopa}
}
abc <- L1
AIC <- -2*abc + 2*5
aa<- matrix(c(1,1,1,1, 1,1,1,-1, 1,-1,0,0),4,3)
b_line1 <- as.matrix(c(mean11,mean12,meanE))
B1 <- solve(t(aa)%*%aa)%*%(t(aa)%*%b_line1)
jj <- sigma_dh - sigmaE[1]
if(jj < 0) {jj <- 0}
ll <- jj/sigma_dh
mm<- sigmaE[1]-sigma[1]
if(mm<0){mm<-0}
nnn<- mm/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
for(i in 1:d2){
gg <- (dataDH - meanE[i])/sqrt(sigmaE[i])
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,i] <- bmw*mix_pi[i]
}
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("MX2-CE-A",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(t(meanE),4)," "," "," "," "," "," "," "," "," "," "," "," "," "," ",round(sigmaE[1],4),round(t(mix_pi),4),
" "," "," "," "," "," "," "," "," "," "," "," "," "," ",round(B1[1],4)," "," "," "," "," "," ",round(B1[2],4)," "," "," "," "," "," ",round(B1[3],4),round(jj,4),round(ll*100,4),round(mm,4),round(nnn*100,4),round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[24]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<-2
mi <- as.matrix(c(0.75,0.25))
meanE<-mean(dataDH)
sigmaE <- matrix((sigma_dh/2*1.2222101),d2,1)
sigma <- sigma0
a1 <- sqrt(sigma_dh/n_samDH)
if(mean11<mean12){a1=-a1}
meanE <- as.matrix(c((meanE+2*a1),(meanE-2*a1)))
iteration <- 0; stopa <- 1000
WW <- matrix(0,d2,n_samDH); swx <- matrix(0,d2,1)
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanE,sqrt(sigmaE),mi)))
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(dataDH,meanE[i],sqrt(sigmaE[i]))/dmixnorm(dataDH,meanE,sqrt(sigmaE),mi) }
mix_pi <- as.matrix(rowSums(WW)/n_samDH)
sumwx <- WW%*%dataDH
n0 <- n_samDH*mix_pi
n0[n0<0.000001] <- 0.000001
rr<- (sum(dataP1)/n_samP1+sum(dataP2)/n_samP2-sumwx[1]/n0[1]-sumwx[2]/n0[2])/(sigma/n_samP1+sigma/n_samP2+sigmaE[1]/n0[1]+sigmaE[2]/n0[2])
mean11<- (sum(dataP1)-rr*sigma)/n_samP1
mean12<- (sum(dataP2)-rr*sigma)/n_samP2
meanE[1]<- (sumwx[1]+sigmaE[1]*rr)/n0[1]
meanE[2]<- (sumwx[2]+sigmaE[2]*rr)/n0[2]
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
for(i in 1:d2) { swx[i] <- WW[i,]%*%(dataDH-meanE[i])^2 }
s0E<-matrix(0,2,1)
s0E[1]<- ss1+ss2
s0E[2]<- sum(swx)*m_fam
s1<- sigmaE[1]-sigma/m_fam
if (s1<0.0){s1<- 0.000001}
abc2<- sigma
abc3<-1000; n_iter<- 0
while(abc3>0.0001){
n_iter<- n_iter+1
abc1<- (sigma/m_fam)/(sigma/m_fam+s1)
sigma<- (s0E[1]+abc1*abc1*s0E[2])/(n_samP1+n_samP2+abc1*n_samDH)
abc3<- abs(abc2-sigma)
abc2<- sigma
if (n_iter>20) break
}
if (sigma<0.1*sigma0){ sigma<- 0.1*sigma0 }
sigmaE[1]<- s1+sigma/m_fam
s1<- sum(swx)/n_samDH-sigma/m_fam
if (s1<0.0){ s1<- 0.000001 }
sigmaE<- matrix((s1+sigma/m_fam),d2,1)
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanE,sqrt(sigmaE),mix_pi)))
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) {stopa <- -stopa}
}
abc <- L1
AIC <- -2*abc + 2*5
aa<- matrix(c(1,1,1,1, 1,1,1,-1, 1,-1,0,0),4,3)
b_line1 <- as.matrix(c(mean11,mean12,meanE))
B1 <- solve(t(aa)%*%aa)%*%(t(aa)%*%b_line1)
jj <- sigma_dh - sigmaE[1]
if(jj < 0) {jj <- 0}
ll <- jj/sigma_dh
mm<- sigmaE[1]-sigma[1]
if(mm<0){mm<-0}
nnn<- mm/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
for(i in 1:d2){
gg <- (dataDH - meanE[i])/sqrt(sigmaE[i])
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,i] <- bmw*mix_pi[i]
}
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("MX2-DE-A",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(t(meanE),4)," "," "," "," "," "," "," "," "," "," "," "," "," "," ",round(sigmaE[1],4),round(t(mix_pi),4),
" "," "," "," "," "," "," "," "," "," "," "," "," "," ",round(B1[1],4)," "," "," "," "," "," ",round(B1[2],4)," "," "," "," "," "," ",round(B1[3],4),round(jj,4),round(ll*100,4),round(mm,4),round(nnn*100,4),round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[25]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<-2
mi <- as.matrix(c(0.75,0.25))
meanE<-mean(dataDH)
sigmaE <- matrix((sigma_dh/2*1.2222101),d2,1)
sigma <- sigma0
a1 <- sqrt(sigma_dh/n_samDH)
if(mean11<mean12){a1=-a1}
meanE <- as.matrix(c((meanE+2*a1),(meanE-2*a1)))
iteration <- 0; stopa <- 1000
WW <- matrix(0,d2,n_samDH); swx <- matrix(0,d2,1)
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanE,sqrt(sigmaE),mi)))
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(dataDH,meanE[i],sqrt(sigmaE[i]))/dmixnorm(dataDH,meanE,sqrt(sigmaE),mi) }
mix_pi <- as.matrix(rowSums(WW)/n_samDH)
sumwx <- WW%*%dataDH
n0 <- n_samDH*mix_pi
n0[n0<0.000001] <- 0.000001
rr<-(sum(dataP1)/n_samP1+sum(dataP2)/n_samP2-2.0*sumwx[2]/n0[2])/(sigma/n_samP1+sigma/n_samP2+4.0*sigmaE[2]/n0[2])
mean11<- (sum(dataP1)-rr*sigma)/n_samP1
mean12<- (sum(dataP2)-rr*sigma)/n_samP2
meanE[1]<- sumwx[1]/n0[1]
meanE[2]<- (sumwx[2]+2.0*rr*sigmaE[2])/n0[2]
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
for(i in 1:d2) { swx[i] <- WW[i,]%*%(dataDH-meanE[i])^2 }
s0E<-matrix(0,2,1)
s0E[1]<- ss1+ss2
s0E[2]<- sum(swx)*m_fam
s1<- sigmaE[1]-sigma/m_fam
if (s1<0.0){s1<- 0.000001}
abc2<- sigma
abc3<-1000; n_iter<- 0
while(abc3>0.0001){
n_iter<- n_iter+1
abc1<- (sigma/m_fam)/(sigma/m_fam+s1)
sigma<- (s0E[1]+abc1*abc1*s0E[2])/(n_samP1+n_samP2+abc1*n_samDH)
abc3<- abs(abc2-sigma)
abc2<- sigma
if (n_iter>20) break
}
if (sigma<0.1*sigma0){ sigma<- 0.1*sigma0 }
sigmaE[1]<- s1+sigma/m_fam
s1<- sum(swx)/n_samDH-sigma/m_fam
if (s1<0.0){ s1<- 0.000001 }
sigmaE<- matrix((s1+sigma/m_fam),d2,1)
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanE,sqrt(sigmaE),mix_pi)))
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) {stopa <- -stopa}
}
abc <- L1
AIC <- -2*abc + 2*5
aa<- matrix(c(1,1,1,1, 1,1,-1,1, 1,-1,0,0),4,3)
b_line1 <- as.matrix(c(mean11,mean12,meanE))
B1 <- solve(t(aa)%*%aa)%*%(t(aa)%*%b_line1)
jj <- sigma_dh - sigmaE[1]
if(jj < 0) {jj <- 0}
ll <- jj/sigma_dh
mm<- sigmaE[1]-sigma[1]
if(mm<0){mm<-0}
nnn<- mm/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
for(i in 1:d2){
gg <- (dataDH - meanE[i])/sqrt(sigmaE[i])
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,i] <- bmw*mix_pi[i]
}
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("MX2-IE-A",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(t(meanE),4)," "," "," "," "," "," "," "," "," "," "," "," "," "," ",round(sigmaE[1],4),round(t(mix_pi),4),
" "," "," "," "," "," "," "," "," "," "," "," "," "," ",round(B1[1],4)," "," "," "," "," "," ",round(B1[2],4)," "," "," "," "," "," ",round(B1[3],4),round(jj,4),round(ll*100,4),round(mm,4),round(nnn*100,4),round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[26]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<-8
mi <- as.matrix(c(0.125,0.125,0.125,0.125,0.125,0.125,0.125,0.125))
meanF<-mean(dataDH)
sigmaF <- matrix((sigma_dh/(2*1.2222101)),d2,1)
sigma <- sigma0
a1 <- sqrt(sigma_dh/n_samDH)
if(mean11<mean12){a1=-a1}
meanF <- as.matrix(c((meanF+3*a1),(meanF+2.1*a1),(meanF+1.2*a1),(meanF+0.3*a1),(meanF+1.5*a1),(meanF+0.5*a1),(meanF-1.5*a1),(meanF-2.5*a1)))
iteration <- 0; stopa <- 1000
WW <- matrix(0,d2,n_samDH); swx <- matrix(0,d2,1)
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanF,sqrt(sigmaF),mi)))
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(dataDH,meanF[i],sqrt(sigmaF[i]))/dmixnorm(dataDH,meanF,sqrt(sigmaF),mi) }
mix_pi <- as.matrix(rowSums(WW)/n_samDH)
sumwx <- WW%*%dataDH
n0 <- n_samDH*mix_pi
n0[n0<0.000001] <- 0.000001
meanF<- sumwx/n0
meanF[1]<- (sum(dataP1)+m_fam*sumwx[1])/(n_samP1+m_fam*n0[1])
meanF[8]<- (sum(dataP2)+m_fam*sumwx[8])/(n_samP2+m_fam*n0[8])
mean11<- meanF[1]
mean12<- meanF[8]
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
for(i in 1:d2) { swx[i] <- WW[i,]%*%(dataDH-meanF[i])^2 }
s0F<-matrix(0,2,1)
s0F[1]<- ss1+ss2
s0F[2]<- sum(swx)*m_fam
s1<- sigmaF[1]-sigma/m_fam
if (s1<0.0){s1<- 0.000001}
abc2<- sigma
abc3<-1000; n_iter<- 0
while(abc3>0.0001){
n_iter<- n_iter+1
sigma<- (s0F[1]+s0F[2])/(n_samP1+n_samP2+n_samDH)
abc3<- abs(abc2-sigma)
abc2<- sigma
if (n_iter>20) break
}
if (sigma<0.1*sigma0){ sigma<- 0.1*sigma0 }
sigmaF<- matrix((sigma/m_fam),d2,1)
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanF,sqrt(sigmaF),mix_pi)))
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) {stopa <- -stopa}
}
abc <- L1
AIC <- -2*abc + 2*9
aa<- matrix(c(1,1,1,1,1,1,1,1, 1,1,-1,-1,1,1,-1,-1, 1,-1,1,-1,1,-1,1,-1, 1,1,1,1,-1,-1,-1,-1,
1,-1,-1,1,1,-1,-1,1, 1,1,-1,-1,-1,-1,1,1, 1,-1,1,-1,-1,1,-1,1, 1,-1,-1,1,-1,1,1,-1 ),8,8)
b_line1 <- meanF
B1 <- ginv(t(aa)%*%aa)%*%(t(aa)%*%b_line1)
jj <- sigma_dh - sigmaF[1]
if(jj < 0) {jj <- 0}
ll <- jj/sigma_dh
mm<- sigmaF[1]-sigma[1]
if(mm<0){mm<-0}
nnn<- mm/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
for(i in 1:d2){
gg <- (dataDH - meanF[i])/sqrt(sigmaF[i])
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,i] <- bmw*mix_pi[i]
}
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("3MG-AI",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(t(meanF),4)," "," "," "," "," "," "," "," ",round(sigmaF[1],4),round(t(mix_pi),4),
" "," "," "," "," "," "," "," ",round(B1[1],4)," "," ",round(B1[2],4),round(B1[3],4),round(B1[4],4)," ",round(B1[5],4),round(B1[6],4)," ",round(B1[7],4)," "," ",round(B1[8],4)," ",
round(jj,4),round(ll*100,4)," "," ",round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[27]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<-8
mi <- as.matrix(c(0.125,0.125,0.125,0.125,0.125,0.125,0.125,0.125))
meanF<-mean(dataDH)
sigmaF <- matrix((sigma_dh/(2*1.2222101)),d2,1)
sigma <- sigma0
a1 <- sqrt(sigma_dh/n_samDH)
if(mean11<mean12){a1=-a1}
meanF <- as.matrix(c((meanF+3*a1),(meanF+2.1*a1),(meanF+1.2*a1),(meanF+0.3*a1),(meanF+1.5*a1),(meanF+0.5*a1),(meanF-1.5*a1),(meanF-2.5*a1)))
iteration <- 0; stopa <- 1000
WW <- matrix(0,d2,n_samDH); swx <- matrix(0,d2,1)
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanF,sqrt(sigmaF),mi)))
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(dataDH,meanF[i],sqrt(sigmaF[i]))/dmixnorm(dataDH,meanF,sqrt(sigmaF),mi) }
mix_pi <- as.matrix(rowSums(WW)/n_samDH)
sumwx <- WW%*%dataDH
n0 <- n_samDH*mix_pi
n0[n0<0.000001] <- 0.000001
hh<- matrix(0,4,4)
hh[1,1]<- sigma*(1.0/(n_samP1+m_fam*n0[1])+1.0/(n_samP2+m_fam*n0[2]))+sigmaF[3]*(1.0/n0[3]+1.0/n0[6])
hh[1,2]<- 0
hh[1,3]<- sigma/(n_samP1+m_fam*n0[1])-sigmaF[6]/n0[6]
hh[1,4]<- -sigmaF[3]/n0[3]+sigma/(n_samP2+m_fam*n0[8])
hh[2,2]<- sigmaF[2]*(1.0/n0[2]+1.0/n0[4]+1.0/n0[5]+1.0/n0[7])
hh[2,3]<- sigmaF[2]*(-1.0/n0[2]+1.0/n0[5])
hh[2,4]<- sigmaF[4]*(1.0/n0[4]-1.0/n0[7])
hh[3,3]<- sigma/(n_samP1+m_fam*n0[1])+sigmaF[2]*(1.0/n0[2]+1.0/n0[5]+1.0/n0[6])
hh[3,4]<- 0
hh[4,4]<- sigma/(n_samP2+m_fam*n0[8])+sigmaF[3]*(1.0/n0[3]+1.0/n0[4]+1.0/n0[7])
for(i in 2:4){
for(j in 1:(i-1)){
hh[i,j]<- hh[j,i]
}
}
b_line<- matrix(0,4,1)
b_line[1]<-(sum(dataP1)+m_fam*sumwx[1])/(n_samP1+m_fam*n0[1])+(sum(dataP2)+m_fam*n0[8])/(n_samP2+m_fam*n0[8])-sumwx[3]/n0[3]-sumwx[6]/n0[6]
b_line[2]<-sumwx[2]/n0[2]-sumwx[4]/n0[4]-sumwx[5]/n0[5]+sumwx[7]/n0[7]
b_line[3]<-(sum(dataP1)+m_fam*sumwx[1])/(n_samP1+m_fam*n0[1])-sumwx[2]/n0[2]-sumwx[5]/n0[5]+sumwx[6]/n0[6]
b_line[4]<-(sum(dataP2)+m_fam*sumwx[8])/(n_samP2+m_fam*n0[8])+sumwx[3]/n0[3]-sumwx[4]/n0[4]-sumwx[7]/n0[7]
B <- solve(hh,b_line)
meanF[1]<- (sum(dataP1)+m_fam*sumwx[1]-(B[1]+B[3])*sigma)/(n_samP1+m_fam*n0[1])
meanF[2]<- (sumwx[2]+(-B[2]+B[3])*sigmaF[2])/n0[2]
meanF[3]<- (sumwx[3]+(B[1]-B[4])*sigmaF[3])/n0[3]
meanF[4]<- (sumwx[4]+(B[2]+B[4])*sigmaF[4])/n0[4]
meanF[5]<- (sumwx[5]+(B[2]+B[3])*sigmaF[5])/n0[5]
meanF[6]<- (sumwx[6]+(B[1]-B[3])*sigmaF[6])/n0[6]
meanF[7]<- (sumwx[7]+(-B[2]+B[4])*sigmaF[7])/n0[7]
meanF[8]<- (sum(dataP2)+m_fam*sumwx[8]-(B[1]+B[4])*sigma)/(n_samP2+m_fam*n0[8])
mean11<- meanF[1]
mean12<- meanF[8]
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
for(i in 1:d2) { swx[i] <- WW[i,]%*%(dataDH-meanF[i])^2 }
s0F<-matrix(0,2,1)
s0F[1]<- ss1+ss2
s0F[2]<- sum(swx)*m_fam
s1<- sigmaF[1]-sigma/m_fam
if (s1<0.0){s1<- 0.000001}
abc2<- sigma
abc3<-1000; n_iter<- 0
while(abc3>0.0001){
n_iter<- n_iter+1
sigma<- (s0F[1]+s0F[2])/(n_samP1+n_samP2+n_samDH)
abc3<- abs(abc2-sigma)
abc2<- sigma
if (n_iter>20) break
}
if (sigma<0.1*sigma0){ sigma<- 0.1*sigma0 }
sigmaF<- matrix((sigma/m_fam),d2,1)
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanF,sqrt(sigmaF),mix_pi)))
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) {stopa <- -stopa}
}
abc <- L1
AIC <- -2*abc + 2*5
aa<- matrix(c(1,1,1,1,1,1,1,1, 1,1,-1,-1,1,1,-1,-1, 1,-1,1,-1,1,-1,1,-1, 1,1,1,1,-1,-1,-1,-1),8,4)
b_line1 <- meanF
B1 <- ginv(t(aa)%*%aa)%*%(t(aa)%*%b_line1)
jj <- sigma_dh - sigmaF[1]
if(jj < 0) {jj <- 0}
ll <- jj/sigma_dh
mm<- sigmaF[1]-sigma[1]
if(mm<0){mm<-0}
nnn<- mm/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
for(i in 1:d2){
gg <- (dataDH - meanF[i])/sqrt(sigmaF[i])
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,i] <- bmw*mix_pi[i]
}
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("3MG-A",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(t(meanF),4)," "," "," "," "," "," "," "," ",round(sigmaF[1],4),round(t(mix_pi),4),
" "," "," "," "," "," "," "," ",round(B1[1],4)," "," ",round(B1[2],4),round(B1[3],4),round(B1[4],4)," "," "," "," "," "," "," "," "," ",
round(jj,4),round(ll*100,4)," "," ",round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[28]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<-4
mi <- as.matrix(c(0.125,0.375,0.375,0.125))
meanF<-mean(dataDH)
sigmaF <- matrix((sigma_dh/(2*1.2222101)),d2,1)
sigma <- sigma0
a1 <- sqrt(sigma_dh/n_samDH)
if(mean11<mean12){a1=-a1}
meanF <- as.matrix(c((meanF+3*a1),(meanF+a1),(meanF-a1),(meanF-3*a1)))
iteration <- 0; stopa <- 1000
WW <- matrix(0,d2,n_samDH); swx <- matrix(0,d2,1)
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanF,sqrt(sigmaF),mi)))
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(dataDH,meanF[i],sqrt(sigmaF[i]))/dmixnorm(dataDH,meanF,sqrt(sigmaF),mi) }
mix_pi <- as.matrix(rowSums(WW)/n_samDH)
sumwx <- WW%*%dataDH
n0 <- n_samDH*mix_pi
n0[n0<0.000001] <- 0.000001
aa1<- sigma*(1.0/n_samP1+1.0/n_samP2)+sigmaF[2]/n0[2]+sigmaF[3]/n0[3]
aa2<- sigma*(1.0/n_samP1-1.0/n_samP2)+3.0*sigmaF[2]/n0[2]-3.0*sigmaF[3]/n0[3]
aa3<- sigma*(1.0/n_samP1+1.0/n_samP2)+9.0*(sigmaF[2]/n0[2]+sigmaF[3]/n0[3])
aa4<- sum(dataP1)/n_samP1+sum(dataP2)/n_samP2-sumwx[2]/n0[2]-sumwx[3]/n0[3]
aa5<- sum(dataP1)/n_samP1-sum(dataP2)/n_samP2-3.0*sumwx[2]/n0[2]+3.0*sumwx[3]/n0[3]
aa6<- aa1*aa3-aa2*aa2
rr<- matrix(0,2,1)
rr[1]<- (aa3*aa4-aa2*aa5)/aa6
rr[2]<- (aa1*aa5-aa2*aa4)/aa6
meanF[1]<- (sum(dataP1)+m_fam*sumwx[1]-(rr[1]+rr[2])*sigma)/(n_samP1+m_fam*n0[1])
meanF[2]<- (sumwx[2]+(rr[1]+3.0*rr[2])*sigmaF[2])/n0[2]
meanF[3]<- (sumwx[3]+(rr[1]-3.0*rr[2])*sigmaF[3])/n0[3]
meanF[4]<- (sum(dataP2)+m_fam*sumwx[4]-(rr[1]-rr[2])*sigma)/(n_samP2+m_fam*n0[4])
mean11<- meanF[1]
mean12<- meanF[4]
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
for(i in 1:d2) { swx[i] <- WW[i,]%*%(dataDH-meanF[i])^2 }
s0F<-matrix(0,2,1)
s0F[1]<- ss1+ss2
s0F[2]<- sum(swx)*m_fam
s1<- sigmaF[1]-sigma/m_fam
if (s1<0.0){s1<- 0.000001}
abc2<- sigma
abc3<-1000; n_iter<- 0
while(abc3>0.0001){
n_iter<- n_iter+1
sigma<- (s0F[1]+s0F[2])/(n_samP1+n_samP2+n_samDH)
abc3<- abs(abc2-sigma)
abc2<- sigma
if (n_iter>20) break
}
if (sigma<0.1*sigma0){ sigma<- 0.1*sigma0 }
sigmaF<- matrix((sigma/m_fam),d2,1)
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanF,sqrt(sigmaF),mix_pi)))
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) {stopa <- -stopa}
}
abc <- L1
AIC <- -2*abc + 2*3
aa<- matrix(c(1,1,1,1, 3,1,-1,-3),4,2)
b_line1 <- meanF
B1 <- ginv(t(aa)%*%aa)%*%(t(aa)%*%b_line1)
jj <- sigma_dh - sigmaF[1]
if(jj < 0) {jj <- 0}
ll <- jj/sigma_dh
mm<- sigmaF[1]-sigma[1]
if(mm<0){mm<-0}
nnn<- mm/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
for(i in 1:d2){
gg <- (dataDH - meanF[i])/sqrt(sigmaF[i])
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,i] <- bmw*mix_pi[i]
}
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("3MG-CEA",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(t(meanF),4)," "," "," "," "," "," "," "," "," "," "," "," ",round(sigmaF[1],4),round(t(mix_pi),4),
" "," "," "," "," "," "," "," "," "," "," "," ",round(B1[1],4)," "," ",round(B1[2],4),round(B1[2],4),round(B1[2],4)," "," "," "," "," "," "," "," "," ",
round(jj,4),round(ll*100,4)," "," ",round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[29]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<-6
mi <- as.matrix(c(0.125,0.125,0.25,0.25,0.125,0.125))
meanF<-mean(dataDH)
sigmaF <- matrix((sigma_dh/(2*1.2222101)),d2,1)
sigma <- sigma0
a1 <- sqrt(sigma_dh)
if(mean11<mean12){a1=-a1}
meanF <- as.matrix(c((meanF+3*a1),(meanF+2*a1),(meanF+a1),(meanF-a1),(meanF-2*a1),(meanF-3*a1)))
iteration <- 0; stopa <- 1000
WW <- matrix(0,d2,n_samDH); swx <- matrix(0,d2,1)
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanF,sqrt(sigmaF),mi)))
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(dataDH,meanF[i],sqrt(sigmaF[i]))/dmixnorm(dataDH,meanF,sqrt(sigmaF),mi) }
mix_pi <- as.matrix(rowSums(WW)/n_samDH)
sumwx <- WW%*%dataDH
n0 <- n_samDH*mix_pi
n0[n0<0.000001] <- 0.000001
hh<- matrix(0,3,3)
hh[1,1]<- sigma*(1.0/(n_samP1+m_fam*n0[1])+1.0/(n_samP2+m_fam*n0[6]))+sigmaF[2]*(1.0/n0[2]+1.0/n0[5])
hh[1,2]<- sigma/(n_samP1+m_fam*n0[1])+sigmaF[2]/n0[2]
hh[1,3]<- sigma/(n_samP1+m_fam*n0[1])-sigmaF[5]/n0[5]
hh[2,2]<- sigma/(n_samP1+m_fam*n0[1])+sigmaF[2]*(1.0/n0[2]+1.0/n0[3]+1.0/n0[4])
hh[2,3]<- sigma/(n_samP1+m_fam*n0[1])+2.0*sigmaF[3]/n0[3]
hh[3,3]<- sigma/(n_samP1+m_fam*n0[1])+4.0*sigmaF[3]/n0[3]+sigmaF[5]/n0[5]
for(i in 2:3){
for(j in 1:(i-1)){
hh[i,j]<- hh[j,i]
}
}
b_line<- matrix(0,3,1)
b_line[1]<-(sum(dataP1)+m_fam*sumwx[1])/(n_samP1+m_fam*n0[1])+(sum(dataP2)+m_fam*sumwx[6])/(n_samP2+m_fam*n0[6])-sumwx[2]/n0[2]-sumwx[5]/n0[5]
b_line[2]<-(sum(dataP1)+m_fam*sumwx[1])/(n_samP1+m_fam*n0[1])-sumwx[2]/n0[2]-sumwx[3]/n0[3]+sumwx[4]/n0[4]
b_line[3]<-(sum(dataP1)+m_fam*sumwx[1])/(n_samP1+m_fam*n0[1])-2*sumwx[3]/n0[3]+sumwx[5]/n0[5]
B <- solve(hh,b_line)
meanF[1]<- (sum(dataP1)+m_fam*sumwx[1]-(B[1]+B[2]+B[3])*sigma)/(n_samP1+m_fam*n0[1])
meanF[2]<- (sumwx[2]+(B[1]+B[2])*sigmaF[2])/n0[2]
meanF[3]<- (sumwx[3]+(B[2]+2.0*B[3])*sigmaF[3])/n0[3]
meanF[4]<- (sumwx[4]-B[2]*sigmaF[4])/n0[4]
meanF[5]<- (sumwx[5]+(B[1]-B[3])*sigmaF[5])/n0[5]
meanF[6]<- (sum(dataP2)+m_fam*sumwx[6]-B[1]*sigma)/(n_samP2+m_fam*n0[6])
mean11<- meanF[1]
mean12<- meanF[6]
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
for(i in 1:d2) { swx[i] <- WW[i,]%*%(dataDH-meanF[i])^2 }
s0F<-matrix(0,2,1)
s0F[1]<- ss1+ss2
s0F[2]<- sum(swx)*m_fam
s1<- sigmaF[1]-sigma/m_fam
if (s1<0.0){s1<- 0.000001}
abc2<- sigma
abc3<-1000; n_iter<- 0
while(abc3>0.0001){
n_iter<- n_iter+1
sigma<- (s0F[1]+s0F[2])/(n_samP1+n_samP2+n_samDH)
abc3<- abs(abc2-sigma)
abc2<- sigma
if (n_iter>20) break
}
if (sigma<0.1*sigma0){ sigma<- 0.1*sigma0 }
sigmaF<- matrix((sigma/m_fam),d2,1)
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanF,sqrt(sigmaF),mix_pi)))
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) {stopa <- -stopa}
}
abc <- L1
AIC <- -2*abc + 2*4
aa<- matrix(c(1,1,1,1,1,1, 2,2,0,0,-2,-2, 1,-1,1,-1,1,-1),6,3)
b_line1 <- meanF
B1 <- ginv(t(aa)%*%aa)%*%(t(aa)%*%b_line1)
jj <- sigma_dh - sigmaF[1]
if(jj < 0) {jj <- 0}
ll <- jj/sigma_dh
mm<- sigmaF[1]-sigma[1]
if(mm<0){mm<-0}
nnn<- mm/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
for(i in 1:d2){
gg <- (dataDH - meanF[i])/sqrt(sigmaF[i])
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,i] <- bmw*mix_pi[i]
}
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("3MG-PEA",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(t(meanF),4)," "," "," "," "," "," "," "," "," "," ",round(sigmaF[1],4),round(t(mix_pi),4),
" "," "," "," "," "," "," "," "," "," ",round(B1[1],4)," "," ",round(B1[2],4),round(B1[2],4),round(B1[3],4)," "," "," "," "," "," "," "," "," ",
round(jj,4),round(ll*100,4)," "," ",round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[30]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<-8
mi <- as.matrix(c(0.125,0.125,0.125,0.125,0.125,0.125,0.125,0.125))
meanG<-mean(dataDH)
sigmaG <- matrix((sigma_dh/(2*1.2222101)),d2,1)
sigma <- sigma0
a1 <- sqrt(sigma_dh/n_samDH)
if(mean11<mean12){a1=-a1}
meanG <- as.matrix(c((meanG+3*a1),(meanG+2.1*a1),(meanG+1.2*a1),(meanG+0.3*a1),(meanG+1.5*a1),(meanG+0.5*a1),(meanG-1.5*a1),(meanG-2.5*a1)))
iteration <- 0; stopa <- 1000
WW <- matrix(0,d2,n_samDH); swx <- matrix(0,d2,1)
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanG,sqrt(sigmaG),mi)))
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(dataDH,meanG[i],sqrt(sigmaG[i]))/dmixnorm(dataDH,meanG,sqrt(sigmaG),mi) }
mix_pi <- as.matrix(rowSums(WW)/n_samDH)
sumwx <- WW%*%dataDH
n0 <- n_samDH*mix_pi
n0[n0<0.000001] <- 0.000001
mean11<- sum(dataP1)/n_samP1
mean12<- sum(dataP2)/n_samP2
meanG<- sumwx/n0
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
for(i in 1:d2) { swx[i] <- WW[i,]%*%(dataDH-meanG[i])^2 }
s0G<-matrix(0,2,1)
s0G[1]<- ss1+ss2
s0G[2]<- sum(swx)*m_fam
s1<- sigmaG[1]-sigma/m_fam
if (s1<0.0){s1<- 0.000001}
abc2<- sigma
abc3<-1000; n_iter<- 0
while(abc3>0.0001){
n_iter<- n_iter+1
abc1<- (sigma/m_fam)/(sigma/m_fam+s1)
sigma<- (s0G[1]+abc1*abc1*s0G[2])/(n_samP1+n_samP2+abc1*n_samDH)
abc3<- abs(abc2-sigma)
abc2<- sigma
if (n_iter>20) break
}
if (sigma<0.1*sigma0){ sigma<- 0.1*sigma0 }
sigmaG[1]<- s1+sigma/m_fam
s1<- sum(swx)/n_samDH-sigma/m_fam
if (s1<0.0){ s1<- 0.000001 }
sigmaG<- matrix((s1+sigma/m_fam),d2,1)
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanG,sqrt(sigmaG),mix_pi)))
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) {stopa <- -stopa}
}
abc <- L1
AIC <- -2*abc + 2*12
aa<- matrix(c(1,0,0,0,0,0,0,0,0,0, 0,1,0,0,0,0,0,0,0,0, 0,0,1,1,1,1,1,1,1,1, 1,-1,1,1,-1,-1,1,1,-1,-1, 1,-1,1,-1,1,-1,1,-1,1,-1,
1,-1,1,1,1,1,-1,-1,-1,-1, 1,1,1,-1,-1,1,1,-1,-1,1, 1,1,1,1,-1,-1,-1,-1,1,1, 1,1,1,-1,1,-1,-1,1,-1,1, 1,-1,1,-1,-1,1,-1,1,1,-1 ),10,10)
b_line1 <- matrix(c(mean11,mean12,meanG))
B1 <- ginv(t(aa)%*%aa)%*%(t(aa)%*%b_line1)
jj <- sigma_dh - sigmaG[1]
if(jj < 0) {jj <- 0}
ll <- jj/sigma_dh
mm<- sigmaG[1]-sigma[1]
if(mm<0){mm<-0}
nnn<- mm/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
for(i in 1:d2){
gg <- (dataDH - meanG[i])/sqrt(sigmaG[i])
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,i] <- bmw*mix_pi[i]
}
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("MX3-AI-AI",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(t(meanG),4)," "," "," "," "," "," "," "," ",round(sigmaG[1],4),round(t(mix_pi),4),
" "," "," "," "," "," "," "," ",round(B1[1],4),round(B1[2],4),round(B1[3],4),round(B1[4],4),round(B1[5],4),round(B1[6],4)," ",round(B1[7],4),round(B1[8],4)," ",round(B1[9],4)," "," ",round(B1[10],4)," ",
round(jj,4),round(ll*100,4),round(mm,4),round(nnn*100,4),round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[31]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<-8
mi <- as.matrix(c(0.125,0.125,0.125,0.125,0.125,0.125,0.125,0.125))
meanG<-mean(dataDH)
sigmaG <- matrix((sigma_dh/(2*1.2222101)),d2,1)
sigma <- sigma0
a1 <- sqrt(sigma_dh)
if(mean11<mean12){a1=-a1}
meanG <- as.matrix(c((meanG+3*a1),(meanG+2.1*a1),(meanG+1.2*a1),(meanG+0.3*a1),(meanG+1.5*a1),(meanG+0.5*a1),(meanG-1.5*a1),(meanG-2.5*a1)))
iteration <- 0; stopa <- 1000
WW <- matrix(0,d2,n_samDH); swx <- matrix(0,d2,1)
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanG,sqrt(sigmaG),mi)))
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(dataDH,meanG[i],sqrt(sigmaG[i]))/dmixnorm(dataDH,meanG,sqrt(sigmaG),mi) }
mix_pi <- as.matrix(rowSums(WW)/n_samDH)
sumwx <- WW%*%dataDH
n0 <- n_samDH*mix_pi
n0[n0<0.000001] <- 0.000001
aa1<- sum(dataP1)/n_samP1+sum(dataP2)/n_samP2-sumwx[1]/n0[1]-sumwx[8]/n0[8]
aa2<- sigma*(1.0/n_samP1+1.0/n_samP2)+sigmaG[1]/n0[1]+sigmaG[8]/n0[8]
rr<- aa1/aa2
mean11<- (sum(dataP1)-rr*sigma)/n_samP1
mean12<- (sum(dataP2)-rr*sigma)/n_samP2
meanG<- sumwx/n0
meanG[1]<-(sumwx[1]+rr*sigmaG[1])/n0[1]
meanG[8]<-(sumwx[8]+rr*sigmaG[8])/n0[8]
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
for(i in 1:d2) { swx[i] <- WW[i,]%*%(dataDH-meanG[i])^2 }
s0G<-matrix(0,2,1)
s0G[1]<- ss1+ss2
s0G[2]<- sum(swx)*m_fam
s1<- sigmaG[1]-sigma/m_fam
if (s1<0.0){s1<- 0.000001}
abc2<- sigma; abc3<-1000; n_iter<- 0
while(abc3>0.0001){
n_iter<- n_iter+1
abc1<- (sigma/m_fam)/(sigma/m_fam+s1)
sigma<- (s0G[1]+abc1*abc1*s0G[2])/(n_samP1+n_samP2+abc1*n_samDH)
abc3<- abs(abc2-sigma)
abc2<- sigma
if (n_iter>20) break
}
if (sigma<0.1*sigma0){ sigma<- 0.1*sigma0 }
sigmaG[1]<- s1+sigma/m_fam
s1<- sum(swx)/n_samDH-sigma/m_fam
if (s1<0.0){ s1<- 0.000001 }
sigmaG<- matrix((s1+sigma/m_fam),d2,1)
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanG,sqrt(sigmaG),mix_pi)))
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) {stopa <- -stopa}
}
abc <- L1
AIC <- -2*abc + 2*11
aa<- matrix(c(1,1,1,1,1,1,1,1,1,1, 1,-1,1,1,-1,-1,1,1,-1,-1, 1,-1,1,-1,1,-1,1,-1,1,-1, 1,-1,1,1,1,1,-1,-1,-1,-1, 1,1,1,-1,-1,1,1,-1,-1,1,
1,1,1,1,-1,-1,-1,-1,1,1, 1,1,1,-1,1,-1,-1,1,-1,1, 1,-1,1,-1,-1,1,-1,1,1,-1, 1,-1,0,0,0,0,0,0,0,0),10,9)
b_line1 <- matrix(c(mean11,mean12,meanG))
B1 <- ginv(t(aa)%*%aa)%*%(t(aa)%*%b_line1)
jj <- sigma_dh - sigmaG[1]
if(jj < 0) {jj <- 0}
ll <- jj/sigma_dh
mm<- sigmaG[1]-sigma[1]
if(mm<0){mm<-0}
nnn<- mm/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
for(i in 1:d2){
gg <- (dataDH - meanG[i])/sqrt(sigmaG[i])
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,i] <- bmw*mix_pi[i]
}
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("MX3-AI-A",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(t(meanG),4)," "," "," "," "," "," "," "," ",round(sigmaG[1],4),round(t(mix_pi),4),
" "," "," "," "," "," "," "," ",round(B1[1],4)," "," ",round(B1[2],4),round(B1[3],4),round(B1[4],4)," ",round(B1[5],4),round(B1[6],4)," ",round(B1[7],4)," "," ",round(B1[8],4),round(B1[9],4),
round(jj,4),round(ll*100,4),round(mm,4),round(nnn*100,4),round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[32]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<-8
mi <- as.matrix(c(0.125,0.125,0.125,0.125,0.125,0.125,0.125,0.125))
meanG<-mean(dataDH)
sigmaG <- matrix((sigma_dh/(2*1.2222101)),d2,1)
sigma <- sigma0
a1 <- sqrt(sigma_dh)
if(mean11<mean12){a1=-a1}
meanG <- as.matrix(c((meanG+3*a1),(meanG+2.1*a1),(meanG+1.2*a1),(meanG+0.3*a1),(meanG+1.5*a1),(meanG+0.5*a1),(meanG-1.5*a1),(meanG-2.5*a1)))
iteration <- 0; stopa <- 1000
WW <- matrix(0,d2,n_samDH); swx <- matrix(0,d2,1)
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanG,sqrt(sigmaG),mi)))
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(dataDH,meanG[i],sqrt(sigmaG[i]))/dmixnorm(dataDH,meanG,sqrt(sigmaG),mi) }
mix_pi <- as.matrix(rowSums(WW)/n_samDH)
sumwx <- WW%*%dataDH
n0 <- n_samDH*mix_pi
n0[n0<0.000001] <- 0.000001
hh<-matrix(0,5,5)
hh[1,1]<- sigma*(1.0/n_samP1+1.0/n_samP2)+sigmaG[1]*(1.0/n0[1]+1.0/n0[8])
hh[1,2]<- -sigmaG[1]*(1.0/n0[1]+1.0/n0[8])
hh[1,3]<- 0
hh[1,4]<- -sigmaG[1]/n0[1]
hh[1,5]<- -sigmaG[8]/n0[8]
hh[2,2]<- sigmaG[1]*(1.0/n0[1]+1.0/n0[3]+1.0/n0[6]+1.0/n0[8])
hh[2,3]<- 0
hh[2,4]<- sigmaG[1]*(1.0/n0[1]-1.0/n0[6])
hh[2,5]<- sigmaG[1]*(-1.0/n0[3]+1.0/n0[8])
hh[3,3]<- sigmaG[2]*(1.0/n0[2]+1.0/n0[4]+1.0/n0[5]+1.0/n0[7])
hh[3,4]<- sigmaG[2]*(-1.0/n0[2]+1.0/n0[5])
hh[3,5]<- sigmaG[4]*(1.0/n0[4]-1.0/n0[7])
hh[4,4]<- sigmaG[1]*(1.0/n0[1]+1.0/n0[2]+1.0/n0[5]+1.0/n0[6])
hh[4,5]<- 0
hh[5,5]<- sigmaG[3]*(1.0/n0[3]+1.0/n0[4]+1.0/n0[7]+1.0/n0[8])
for(i in 2:5){
for(j in 1:(i-1)){
hh[i,j]<- hh[j,i]
}
}
b_line<-matrix(0,5,1)
b_line[1]<- sum(dataP1)/n_samP1+sum(dataP2)/n_samP2-sumwx[1]/n0[1]-sumwx[8]/n0[8]
b_line[2]<- sumwx[1]/n0[1]-sumwx[3]/n0[3]-sumwx[6]/n0[6]+sumwx[8]/n0[8]
b_line[3]<- sumwx[2]/n0[2]-sumwx[4]/n0[4]-sumwx[5]/n0[5]+sumwx[7]/n0[7]
b_line[4]<- sumwx[1]/n0[1]-sumwx[2]/n0[2]-sumwx[5]/n0[5]+sumwx[6]/n0[6]
b_line[5]<- sumwx[3]/n0[3]-sumwx[4]/n0[4]-sumwx[7]/n0[7]+sumwx[8]/n0[8]
B <- solve(hh,b_line)
mean11<- (sum(dataP1)-B[1]*sigma)/n_samP1
mean12<- (sum(dataP2)-B[1]*sigma)/n_samP2
meanG[1]<- (sumwx[1]+(B[1]-B[2]-B[4])*sigmaG[1])/n0[1]
meanG[2]<- (sumwx[2]+(-B[3]+B[4])*sigmaG[2])/n0[2]
meanG[3]<- (sumwx[3]+(B[2]-B[5])*sigmaG[3])/n0[3]
meanG[4]<- (sumwx[4]+(B[3]+B[5])*sigmaG[4])/n0[4]
meanG[5]<- (sumwx[5]+(B[3]+B[4])*sigmaG[5])/n0[5]
meanG[6]<- (sumwx[6]+(B[2]-B[4])*sigmaG[6])/n0[6]
meanG[7]<- (sumwx[7]-(B[3]-B[5])*sigmaG[7])/n0[7]
meanG[8]<- (sumwx[8]+(B[1]-B[2]-B[5])*sigmaG[8])/n0[8]
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
for(i in 1:d2) { swx[i] <- WW[i,]%*%(dataDH-meanG[i])^2 }
s0G<-matrix(0,2,1)
s0G[1]<- ss1+ss2
s0G[2]<- sum(swx)*m_fam
s1<- sigmaG[1]-sigma/m_fam
if (s1<0.0){s1<- 0.000001}
abc2<- sigma
abc3<-1000; n_iter<- 0
while(abc3>0.0001){
n_iter<- n_iter+1
abc1<- (sigma/m_fam)/(sigma/m_fam+s1)
sigma<- (s0G[1]+abc1*abc1*s0G[2])/(n_samP1+n_samP2+n_samDH)
abc3<- abs(abc2-sigma)
abc2<- sigma
if (n_iter>20) break
}
if (sigma<0.1*sigma0){ sigma<- 0.1*sigma0 }
sigmaG[1]<- s1+sigma/m_fam
s1<- sum(swx)/n_samDH-sigma/m_fam
if (s1<0.0){ s1<- 0.000001 }
sigmaG<- matrix((s1+sigma/m_fam),d2,1)
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanG,sqrt(sigmaG),mix_pi)))
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) {stopa <- -stopa}
}
abc <- L1
AIC <- -2*abc + 2*6
aa<- matrix(c(1,1,1,1,1,1,1,1,1,1, 1,-1,1,1,-1,-1,1,1,-1,-1, 1,-1,1,-1,1,-1,1,-1,1,-1,
1,-1,1,1,1,1,-1,-1,-1,-1, 1,-1,0,0,0,0,0,0,0,0),10,5)
b_line1 <- matrix(c(mean11,mean12,meanG))
B1 <- ginv(t(aa)%*%aa)%*%(t(aa)%*%b_line1)
jj <- sigma_dh - sigmaG[1]
if(jj < 0) {jj <- 0}
ll <- jj/sigma_dh
mm<- sigmaG[1]-sigma[1]
if(mm<0){mm<-0}
nnn<- mm/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
for(i in 1:d2){
gg <- (dataDH - meanG[i])/sqrt(sigmaG[i])
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,i] <- bmw*mix_pi[i]
}
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("MX3-A-A",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(t(meanG),4)," "," "," "," "," "," "," "," ",round(sigmaG[1],4),round(t(mix_pi),4),
" "," "," "," "," "," "," "," ",round(B1[1],4)," "," ",round(B1[2],4),round(B1[3],4),round(B1[4],4)," "," "," "," "," "," "," "," ",round(B1[5],4),
round(jj,4),round(ll*100,4),round(mm,4),round(nnn*100,4),round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[33]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<-4
mi <- as.matrix(c(0.125,0.375,0.375,0.125))
meanG<-mean(dataDH)
sigmaG <- matrix((sigma_dh/(2*1.2222101)),d2,1)
sigma <- sigma0
a1 <- sqrt(sigma_dh)
if(mean11<mean12){a1=-a1}
meanG <- as.matrix(c((meanG+3*a1),(meanG+a1),(meanG-a1),(meanG-3*a1)))
iteration <- 0; stopa <- 1000
WW <- matrix(0,d2,n_samDH); swx <- matrix(0,d2,1)
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanG,sqrt(sigmaG),mi)))
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(dataDH,meanG[i],sqrt(sigmaG[i]))/dmixnorm(dataDH,meanG,sqrt(sigmaG),mi) }
mix_pi <- as.matrix(rowSums(WW)/n_samDH)
sumwx <- WW%*%dataDH
n0 <- n_samDH*mix_pi
n0[n0<0.000001] <- 0.000001
hh<-matrix(0,3,3)
hh[1,1]<- sigma*(1.0/n_samP1+1.0/n_samP2)+sigmaG[1]*(1.0/n0[1]+1.0/n0[4])
hh[1,2]<- -sigmaG[1]*(1.0/n0[1]+1.0/n0[4])
hh[1,3]<- -sigmaG[1]*(1.0/n0[1]-1.0/n0[4])
hh[2,2]<- sigmaG[1]*(1.0/n0[1]+1.0/n0[2]+1.0/n0[3]+1.0/n0[4])
hh[2,3]<- sigmaG[1]*(1.0/n0[1]+3.0/n0[2]-3.0/n0[3]-1.0/n0[4])
hh[3,3]<- sigmaG[1]*(1.0/n0[1]+9.0/n0[2]+9.0/n0[3]+1.0/n0[4])
for(i in 2:3){
for(j in 1:(i-1)){
hh[i,j]<- hh[j,i]
}
}
b_line<-matrix(0,3,1)
b_line[1]<- sum(dataP1)/n_samP1+sum(dataP2)/n_samP2-sumwx[1]/n0[1]-sumwx[4]/n0[4]
b_line[2]<- sumwx[1]/n0[1]-sumwx[2]/n0[2]-sumwx[3]/n0[3]+sumwx[4]/n0[4]
b_line[3]<- sumwx[1]/n0[1]-3.0*sumwx[2]/n0[2]+3.0*sumwx[3]/n0[3]-sumwx[4]/n0[4]
B <- solve(hh,b_line)
mean11<- (sum(dataP1)-B[1]*sigma)/n_samP1
mean12<- (sum(dataP2)-B[1]*sigma)/n_samP2
meanG[1]<-(sumwx[1]+(B[1]-B[2]-B[3])*sigmaG[1])/n0[1]
meanG[2]<-(sumwx[2]+(B[2]+3.0*B[3])*sigmaG[2])/n0[2]
meanG[3]<-(sumwx[3]+(B[2]-3.0*B[3])*sigmaG[3])/n0[3]
meanG[4]<-(sumwx[4]+(B[1]-B[2]+B[3])*sigmaG[4])/n0[4]
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
for(i in 1:d2) { swx[i] <- WW[i,]%*%(dataDH-meanG[i])^2 }
s0G<-matrix(0,2,1)
s0G[1]<- ss1+ss2
s0G[2]<- sum(swx)*m_fam
s1<- sigmaG[1]-sigma/m_fam
if (s1<0.0){s1<- 0.000001}
abc2<- sigma
abc3<-1000; n_iter<- 0
while(abc3>0.0001){
n_iter<- n_iter+1
abc1<- (sigma/m_fam)/(sigma/m_fam+s1)
sigma<- (s0G[1]+abc1*abc1*s0G[2])/(n_samP1+n_samP2+abc1*n_samDH)
abc3<- abs(abc2-sigma)
abc2<- sigma
if (n_iter>20) break
}
if (sigma<0.1*sigma0){ sigma<- 0.1*sigma0 }
sigmaG[1]<- s1+sigma/m_fam
s1<- sum(swx)/n_samDH-sigma/m_fam
if (s1<0.0){ s1<- 0.000001 }
sigmaG<- matrix((s1+sigma/m_fam),d2,1)
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanG,sqrt(sigmaG),mix_pi)))
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) {stopa <- -stopa}
}
abc <- L1
AIC <- -2*abc + 2*5
aa<- matrix(c(1,1,1,1,1,1,3,-3,3,1,-1,-3, 1,-1,0,0,0,0),6,3)
b_line1 <- matrix(c(mean11,mean12,meanG))
B1 <- ginv(t(aa)%*%aa)%*%(t(aa)%*%b_line1)
jj <- sigma_dh - sigmaG[1]
if(jj < 0) {jj <- 0}
ll <- jj/sigma_dh
mm<- sigmaG[1]-sigma[1]
if(mm<0){mm<-0}
nnn<- mm/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
for(i in 1:d2){
gg <- (dataDH - meanG[i])/sqrt(sigmaG[i])
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,i] <- bmw*mix_pi[i]
}
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("MX3-CEA-A",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(t(meanG),4)," "," "," "," "," "," "," "," "," "," "," "," ",round(sigmaG[1],4),round(t(mix_pi),4),
" "," "," "," "," "," "," "," "," "," "," "," ",round(B1[1],4)," "," ",round(B1[2],4),round(B1[2],4),round(B1[2],4)," "," "," "," "," "," "," "," ",round(B1[3],4),
round(jj,4),round(ll*100,4),round(mm,4),round(nnn*100,4),round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[34]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<- 6
mi <- as.matrix(c(0.125,0.125,0.25,0.25,0.125,0.125))
meanG<-mean(dataDH)
sigmaG <- matrix((sigma_dh/(2*1.2222101)),d2,1)
sigma <- sigma0
a1 <- sqrt(sigma_dh/n_samDH)
if(mean11<mean12){a1=-a1}
meanG <- as.matrix(c((meanG+3*a1),(meanG+2*a1),(meanG+a1),(meanG-a1),(meanG-2*a1),(meanG-3*a1)))
iteration <- 0; stopa <- 1000
WW <- matrix(0,d2,n_samDH); swx <- matrix(0,d2,1)
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanG,sqrt(sigmaG),mi)))
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(dataDH,meanG[i],sqrt(sigmaG[i]))/dmixnorm(dataDH,meanG,sqrt(sigmaG),mi) }
mix_pi <- as.matrix(rowSums(WW)/n_samDH)
sumwx <- WW%*%dataDH
n0 <- n_samDH*mix_pi
n0[n0<0.000001] <- 0.000001
hh<-matrix(0,4,4)
hh[1,1]<- sigma*(1.0/n_samP1+1.0/n_samP2)+sigmaG[1]*(1.0/n0[1]+1.0/n0[6])
hh[1,2]<- -sigmaG[1]*(1.0/n0[1]+1.0/n0[6])
hh[1,3]<- -sigmaG[1]/n0[1]
hh[1,4]<- -sigmaG[1]/n0[1]
hh[2,2]<- sigmaG[1]*(1.0/n0[1]+1.0/n0[2]+1.0/n0[5]+1.0/n0[6])
hh[2,3]<- sigmaG[1]*(1.0/n0[1]+1.0/n0[2])
hh[2,4]<- sigmaG[1]*(1.0/n0[1]-1.0/n0[5])
hh[3,3]<- sigmaG[1]*(1.0/n0[1]+1.0/n0[2]+1.0/n0[3]+1.0/n0[4])
hh[3,4]<- sigmaG[1]*(1.0/n0[1]+2.0/n0[3])
hh[4,4]<- sigmaG[1]*(1.0/n0[1]+4.0/n0[3]+1.0/n0[5])
for(i in 2:4){
for(j in 1:(i-1)){
hh[i,j]<- hh[j,i]
}
}
b_line<-matrix(0,4,1)
b_line[1]<- sum(dataP1)/n_samP1+sum(dataP2)/n_samP2-sumwx[1]/n0[1]-sumwx[6]/n0[6]
b_line[2]<- sumwx[1]/n0[1]-sumwx[2]/n0[2]-sumwx[5]/n0[5]+sumwx[6]/n0[6]
b_line[3]<- sumwx[1]/n0[1]-sumwx[2]/n0[2]-sumwx[3]/n0[3]+sumwx[4]/n0[4]
b_line[4]<- sumwx[1]/n0[1]-2.0*sumwx[3]/n0[3]+sumwx[5]/n0[5]
B <- solve(hh,b_line)
mean11<- (sum(dataP1)-B[1]*sigma)/n_samP1
mean12<- (sum(dataP2)-B[1]*sigma)/n_samP2
meanG[1]<-(sumwx[1]-(-B[1]+B[2]+B[3]+B[4])*sigmaG[1])/n0[1]
meanG[2]<-(sumwx[2]+(B[2]+B[3])*sigmaG[2])/n0[2]
meanG[3]<-(sumwx[3]+(B[3]+2.0*B[4])*sigmaG[3])/n0[3]
meanG[4]<-(sumwx[4]-B[3]*sigmaG[4])/n0[4]
meanG[5]<-(sumwx[5]+(B[2]-B[4])*sigmaG[5])/n0[5]
meanG[6]<-(sumwx[6]+(B[1]-B[2])*sigmaG[6])/n0[6]
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
for(i in 1:d2) { swx[i] <- WW[i,]%*%(dataDH-meanG[i])^2 }
s0G<-matrix(0,2,1)
s0G[1]<- ss1+ss2
s0G[2]<- sum(swx)*m_fam
s1<- sigmaG[1]-sigma/m_fam
if (s1<0.0){s1<- 0.000001}
abc2<- sigma
abc3<-1000; n_iter<- 0
while(abc3>0.0001){
n_iter<- n_iter+1
abc1<- (sigma/m_fam)/(sigma/m_fam+s1)
sigma<- (s0G[1]+abc1*abc1*s0G[2])/(n_samP1+n_samP2+n_samDH)
abc3<- abs(abc2-sigma)
abc2<- sigma
if (n_iter>20) break
}
if (sigma<0.1*sigma0){ sigma<- 0.1*sigma0 }
sigmaG[1]<- s1+sigma/m_fam
s1<- sum(swx)/n_samDH-sigma/m_fam
if (s1<0.0){ s1<- 0.000001 }
sigmaG<- matrix((s1+sigma/m_fam),d2,1)
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanG,sqrt(sigmaG),mix_pi)))
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) {stopa <- -stopa}
}
abc <- L1
AIC <- -2*abc + 2*6
aa<- matrix(c(1,1,1,1,1,1,1,1, 2,-2,2,2,0,0,-2,-2, 1,-1,1,-1,1,-1,1,-1, 1,-1,0,0,0,0,0,0),8,4)
b_line1 <- matrix(c(mean11,mean12,meanG))
B1 <- ginv(t(aa)%*%aa)%*%(t(aa)%*%b_line1)
jj <- sigma_dh - sigmaG[1]
if(jj < 0) {jj <- 0}
ll <- jj/sigma_dh
mm<- sigmaG[1]-sigma[1]
if(mm<0){mm<-0}
nnn<- mm/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
for(i in 1:d2){
gg <- (dataDH - meanG[i])/sqrt(sigmaG[i])
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,i] <- bmw*mix_pi[i]
}
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("MX3-PEA-A",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(t(meanG),4)," "," "," "," "," "," "," "," "," "," ",round(sigmaG[1],4),round(t(mix_pi),4),
" "," "," "," "," "," "," "," "," "," ",round(B1[1],4)," "," ",round(B1[2],4),round(B1[3],4),","," "," "," "," "," "," "," "," ",round(B1[4],4),
round(jj,4),round(ll*100,4),round(mm,4),round(nnn*100,4),round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[35]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<-16
mi <- as.matrix(c(0.0625,0.0625,0.0625,0.0625,0.0625,0.0625,0.0625,0.0625,0.0625,0.0625,0.0625,0.0625,0.0625,0.0625,0.0625,0.0625))
meanH<-mean(dataDH)
sigmaH <- matrix((sigma_dh/(2*1.2222101)),d2,1)
sigma <- sigma0
a1 <- sqrt(sigma_dh)
if(mean11<mean12){a1=-a1}
meanH <- as.matrix(c(222,146,114,138,114,78,50,54,152,96,76,100,84,68,72,56))
iteration <- 0; stopa <- 1000
WW <- matrix(0,d2,n_samDH); swx <- matrix(0,d2,1)
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanH,sqrt(sigmaH),mi)))
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(dataDH,meanH[i],sqrt(sigmaH[i]))/dmixnorm(dataDH,meanH,sqrt(sigmaH),mi) }
mix_pi <- as.matrix(rowSums(WW)/n_samDH)
sumwx <- WW%*%dataDH
n0 <- n_samDH*mix_pi
n0[n0<0.000001] <- 0.000001
s0<-matrix(0,4,1)
s0[1]<- sigma;s0[2]<- n_samP1+m_fam*n0[1]
s0[3]<- sigma;s0[4]<- n_samP2+m_fam*n0[16]
hh<-matrix(0,5,5)
hh[1,1]<- s0[1]/s0[2]+sigmaH[2]/n0[2]+sigmaH[3]/n0[3]+sigmaH[4]/n0[4]+sigmaH[9]/n0[9]+sigmaH[10]/n0[10]+sigmaH[11]/n0[11]+sigmaH[12]/n0[12]
hh[1,2]<- s0[1]/s0[2]+sigmaH[2]/n0[2]+sigmaH[3]/n0[3]+sigmaH[4]/n0[4]
hh[1,3]<- s0[1]/s0[2]+sigmaH[2]/n0[2]+sigmaH[3]/n0[3]+sigmaH[4]/n0[4]
hh[1,4]<- -(s0[1]/s0[2]+sigmaH[2]/n0[2]+sigmaH[9]/n0[9]+sigmaH[10]/n0[10])
hh[1,5]<- sigmaH[2]/n0[2]+sigmaH[3]/n0[3]+sigmaH[10]/n0[10]+sigmaH[11]/n0[11]
hh[2,2]<- s0[1]/s0[2]+sigmaH[2]/n0[2]+sigmaH[3]/n0[3]+sigmaH[4]/n0[4]+sigmaH[13]/n0[13]+sigmaH[14]/n0[14]+sigmaH[15]/n0[15]+s0[3]/s0[4]
hh[2,3]<- s0[1]/s0[2]+sigmaH[2]/n0[2]+sigmaH[3]/n0[3]+sigmaH[4]/n0[4]
hh[2,4]<- -(s0[1]/s0[2]+sigmaH[2]/n0[2]-sigmaH[13]/n0[13]-sigmaH[14]/n0[14])
hh[2,5]<- sigmaH[2]/n0[2]+sigmaH[3]/n0[3]+sigmaH[13]/n0[13]+s0[3]/s0[4]
hh[3,3]<- s0[1]/s0[2]+sigmaH[2]/n0[2]+sigmaH[3]/n0[3]+sigmaH[4]/n0[4]+sigmaH[5]/n0[5]+sigmaH[6]/n0[6]+sigmaH[7]/n0[7]+sigmaH[8]/n0[8]
hh[3,4]<- -(s0[1]/s0[2]+sigmaH[2]/n0[2]+sigmaH[5]/n0[5]+sigmaH[6]/n0[6])
hh[3,5]<- sigmaH[2]/n0[2]+sigmaH[3]/n0[3]-sigmaH[5]/n0[5]-sigmaH[8]/n0[8]
hh[4,4]<- s0[1]/s0[2]+sigmaH[2]/n0[2]+sigmaH[5]/n0[5]+sigmaH[6]/n0[6]+sigmaH[9]/n0[9]+sigmaH[10]/n0[10]+sigmaH[13]/n0[13]+sigmaH[14]/n0[14]
hh[4,5]<- -sigmaH[2]/n0[2]+sigmaH[5]/n0[5]-sigmaH[10]/n0[10]+sigmaH[13]/n0[13]
hh[5,5]<- sigmaH[2]/n0[2]+sigmaH[3]/n0[3]+sigmaH[5]/n0[5]+sigmaH[8]/n0[8]+sigmaH[10]/n0[10]+sigmaH[11]/n0[11]+sigmaH[13]/n0[13]+s0[3]/s0[4]
for(i in 2:5){
for(j in 1:(i-1)){
hh[i,j]<- hh[j,i]
}
}
b_line<-matrix(0,5,1)
b_line[1]<- -(sum(dataP1)+m_fam*sumwx[1])/(n_samP1+m_fam*n0[1])+sumwx[2]/n0[2]-sumwx[3]/n0[3]+sumwx[4]/n0[4]+sumwx[9]/n0[9]-sumwx[10]/n0[10]+sumwx[11]/n0[11]-sumwx[12]/n0[12]
b_line[2]<- -(sum(dataP1)+m_fam*sumwx[1])/(n_samP1+m_fam*n0[1])+sumwx[2]/n0[2]-sumwx[3]/n0[3]+sumwx[4]/n0[4]+sumwx[13]/n0[13]-sumwx[14]/n0[14]+sumwx[15]/n0[15]-(sum(dataP2)+m_fam*sumwx[16])/(n_samP2+m_fam*n0[16])
b_line[3]<- -(sum(dataP1)+m_fam*sumwx[1])/(n_samP1+m_fam*n0[1])+sumwx[2]/n0[2]-sumwx[3]/n0[3]+sumwx[4]/n0[4]+sumwx[5]/n0[5]-sumwx[6]/n0[6]+sumwx[7]/n0[7]-sumwx[8]/n0[8]
b_line[4]<- (sum(dataP1)+m_fam*sumwx[1])/(n_samP1+m_fam*n0[1])-sumwx[2]/n0[2]-sumwx[5]/n0[5]+(sum(dataP2)+m_fam*sumwx[16])/(n_samP2+m_fam*n0[16])-sumwx[9]/n0[9]+sumwx[10]/n0[10]+sumwx[13]/n0[13]-sumwx[14]/n0[14];
b_line[5]<- sumwx[2]/n0[2]-sumwx[3]/n0[3]-sumwx[5]/n0[5]+sumwx[8]/n0[8]-sumwx[10]/n0[10]+sumwx[11]/n0[11]+sumwx[13]/n0[13]-(sum(dataP2)+m_fam*sumwx[16])/(n_samP2+m_fam*n0[16])
B <- solve(hh,b_line)
meanH[1]<-(sum(dataP1)+m_fam*sumwx[1]+(B[1]+B[2]+B[3]-B[4])*sigma)/(n_samP1+m_fam*n0[1])
meanH[2]<-(sumwx[2]-(B[1]+B[2]+B[3]-B[4]+B[5])*sigmaH[2])/n0[2]
meanH[3]<-(sumwx[3]+(B[1]+B[2]+B[3]+B[5])*sigmaH[3])/n0[3]
meanH[4]<-(sumwx[4]-(B[1]+B[2]+B[3])*sigmaH[4])/n0[4]
meanH[5]<-(sumwx[5]+(-B[3]+B[4]+B[5])*sigmaH[5])/n0[5]
meanH[6]<-(sumwx[6]+(B[3]-B[4])*sigmaH[6])/n0[6]
meanH[7]<-(sumwx[7]+(-B[3])*sigmaH[7])/n0[7]
meanH[8]<-(sumwx[8]+(B[3]-B[5])*sigmaH[8])/n0[8]
meanH[9]<-(sumwx[9]-(B[1]-B[4])*sigmaH[9])/n0[9]
meanH[10]<-(sumwx[10]+(B[1]-B[4]+B[5])*sigmaH[10])/n0[10]
meanH[11]<-(sumwx[11]-(B[1]+B[5])*sigmaH[11])/n0[11]
meanH[12]<-(sumwx[12]+B[1]*sigmaH[12])/n0[12]
meanH[13]<-(sumwx[13]-(B[2]+B[4]+B[5])*sigmaH[13])/n0[13]
meanH[14]<-(sumwx[14]+(B[2]+B[4])*sigmaH[14])/n0[14]
meanH[15]<-(sumwx[15]-B[2]*sigmaH[15])/n0[15]
meanH[16]<-(sum(dataP2)+m_fam*sumwx[16]+(B[2]+B[5])*sigma)/(n_samP2+m_fam*n0[16])
mean11<- meanH[1]
mean12<- meanH[16]
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
for(i in 1:d2) { swx[i] <- WW[i,]%*%(dataDH-meanH[i])^2 }
s0H<-matrix(0,2,1)
s0H[1]<- ss1+ss2
s0H[2]<- sum(swx)*m_fam
s1<- sigmaH[1]-sigma/m_fam
if (s1<0.0){s1<- 0.000001}
abc2<- sigma
abc3<-1000; n_iter<- 0
while(abc3>0.0001){
n_iter<- n_iter+1
sigma<- (s0H[1]+s0H[2])/(n_samP1+n_samP2+n_samDH)
abc3<- abs(abc2-sigma)
abc2<- sigma
if (n_iter>20) break
}
if (sigma<0.1*sigma0){ sigma<- 0.1*sigma0 }
sigmaH<-matrix((sigma/m_fam),d2,1)
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanH,sqrt(sigmaH),mix_pi)))
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) {stopa <- -stopa}
}
abc <- L1
AIC <- -2*abc + 2*11
aa<- matrix(c(1,1,1,1,1,1,1,1,1,1,1,1,1,1,1,1, 1,1,1,1,1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1, 1,1,1,1,-1,-1,-1,-1,1,1,1,1,-1,-1,-1,-1,
1,1,-1,-1,1,1,-1,-1,1,1,-1,-1,1,1,-1,-1, 1,-1,-1,1,1,-1,-1,1,1,-1,-1,1,1,-1,-1,1, 1,1,1,1,-1,-1,-1,-1,-1,-1,-1,-1,1,1,1,1,
1,1,-1,-1,1,1,-1,-1,-1,-1,1,1,-1,-1,1,1, 1,-1,-1,1,1,-1,-1,1,-1,1,1,-1,-1,1,1,-1, 1,1,-1,-1,-1,-1,1,1,1,1,-1,-1,-1,-1,1,1,
1,-1,1,1,-1,1,1,-1,1,-1,-1,1,-1,1,1,-1, 1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1,1,-1),16,11)
b_line1 <- meanH
B1 <- ginv(t(aa)%*%aa)%*%(t(aa)%*%b_line1)
jj <- sigma_dh - sigmaH[1]
if(jj < 0) {jj <- 0}
ll <- jj/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
for(i in 1:d2){
gg <- (dataDH - meanH[i])/sqrt(sigmaH[i])
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,i] <- bmw*mix_pi[i]
}
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("4MG-AI",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(t(meanH),4),round(sigmaH[1],4),round(t(mix_pi),4),
round(B1[1],4)," "," ",round(B1[2],4),round(B1[3],4),round(B1[4],4),round(B1[5],4),round(B1[6],4),round(B1[7],4),round(B1[8],4),round(B1[9],4),round(B1[10],4),round(B1[11],4)," "," ",
round(jj,4),round(ll*100,4)," "," ",round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[36]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<-5
mi <- as.matrix(c(0.0625,0.25,0.375,0.25,0.0625))
meanH<-mean(dataDH)
sigmaH <- matrix((sigma_dh/(2*1.2222101)),d2,1)
sigma <- sigma0
a1 <- sqrt(sigma_dh/n_samDH)
if(mean11<mean12){a1=-a1}
meanH <- as.matrix(c((meanH+3*a1),(meanH+2*a1),meanH,(meanH-2*a1),(meanH-3*a1)))
iteration <- 0; stopa <- 1000
WW <- matrix(0,d2,n_samDH); swx <- matrix(0,d2,1)
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanH,sqrt(sigmaH),mi)))
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(dataDH,meanH[i],sqrt(sigmaH[i]))/dmixnorm(dataDH,meanH,sqrt(sigmaH),mi) }
mix_pi <- as.matrix(rowSums(WW)/n_samDH)
sumwx <- WW%*%dataDH
n0 <- n_samDH*mix_pi
n0[n0<0.000001] <- 0.000001
s0<-matrix(0,4,1)
s0[1]<- sigma;s0[2]<- n_samP1+m_fam*n0[1]
s0[3]<- sigma;s0[4]<- n_samP2+m_fam*n0[5]
hh<-matrix(0,3,3)
hh[1,1]<- s0[1]/s0[2]+4.0*sigmaH[2]/n0[2]+sigmaH[3]/n0[3]
hh[1,2]<- 2.0*s0[1]/s0[2]+6.0*sigmaH[2]/n0[2]
hh[1,3]<- s0[1]/s0[2]+2.0*sigmaH[2]/n0[2]
hh[2,2]<- 4.0*s0[1]/s0[2]+9.0*sigmaH[2]/n0[2]+sigmaH[4]/n0[4]
hh[2,3]<- 2.0*s0[1]/s0[2]+3.0*sigmaH[2]/n0[2]-sigmaH[4]/n0[4]
hh[3,3]<- s0[1]/s0[2]+sigmaH[2]/n0[2]+sigmaH[4]/n0[4]+s0[3]/s0[4]
for(i in 2:3){
for(j in 1:(i-1)){
hh[i,j]<- hh[j,i]
}
}
b_line<-matrix(0,3,1)
b_line[1]<- -(sum(dataP1)+m_fam*sumwx[1])/(n_samP1+m_fam*n0[1])+2*sumwx[2]/n0[2]-sumwx[3]/n0[3]
b_line[2]<- -2*(sum(dataP1)+m_fam*sumwx[1])/(n_samP1+m_fam*n0[1])+3*sumwx[2]/n0[2]-sumwx[4]/n0[4]
b_line[3]<- -(sum(dataP1)+m_fam*sumwx[1])/(n_samP1+m_fam*n0[1])+sumwx[2]/n0[2]+sumwx[4]/n0[4]-(sum(dataP2)+m_fam*sumwx[5])/(n_samP2+m_fam*n0[5])
B <- solve(hh,b_line)
meanH[1]<-(sum(dataP1)+m_fam*sumwx[1]+(B[1]+2*B[2]+B[3])*sigma)/(n_samP1+m_fam*n0[1])
meanH[2]<-(sumwx[2]+(-2*B[1]-3*B[2]-B[3])*sigmaH[2])/n0[2]
meanH[3]<-(sumwx[3]+B[1]*sigmaH[3])/n0[3]
meanH[4]<-(sumwx[4]+(B[2]-B[3])*sigmaH[4])/n0[4]
meanH[5]<-(sum(dataP2)+m_fam*sumwx[5]+B[3]*sigma)/(n_samP2+m_fam*n0[5])
mean11<- meanH[1]
mean12<- meanH[5]
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
for(i in 1:d2) { swx[i] <- WW[i,]%*%(dataDH-meanH[i])^2 }
s0H<-matrix(0,2,1)
s0H[1]<- ss1+ss2
s0H[2]<- sum(swx)*m_fam
s1<- sigmaH[1]-sigma/m_fam
if (s1<0.0){s1<- 0.000001}
abc2<- sigma
abc3<-1000; n_iter<- 0
while(abc3>0.0001){
n_iter<- n_iter+1
sigma<- (s0H[1]+s0H[2])/(n_samP1+n_samP2+n_samDH)
abc3<- abs(abc2-sigma)
abc2<- sigma
if (n_iter>20) break
}
if (sigma<0.1*sigma0){ sigma<- 0.1*sigma0 }
sigmaH<-matrix((sigma/m_fam),d2,1)
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanH,sqrt(sigmaH),mix_pi)))
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) {stopa <- -stopa}
}
abc <- L1
AIC <- -2*abc + 2*3
aa<- matrix(c(1,1,1,1,1, 4,2,0,-2,-4),5,2)
b_line1 <- meanH
B1 <- ginv(t(aa)%*%aa)%*%(t(aa)%*%b_line1)
jj <- sigma_dh - sigmaH[1]
if(jj < 0) {jj <- 0}
ll <- jj/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
for(i in 1:d2){
gg <- (dataDH - meanH[i])/sqrt(sigmaH[i])
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,i] <- bmw*mix_pi[i]
}
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("4MG-CEA",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(t(meanH),4)," "," "," "," "," "," "," "," "," "," "," ",round(sigmaH[1],4),round(t(mix_pi),4),
" "," "," "," "," "," "," "," "," "," "," ",round(B1[1],4)," "," ",round(B1[2],4),round(B1[2],4),round(B1[2],4),round(B1[2],4)," "," "," "," "," "," "," "," ",
round(jj,4),round(ll*100,4)," "," ",round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[37]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<-9
mi <- as.matrix(c(0.0625,0.0625,0.125,0.125,0.25,0.125,0.125,0.0625,0.0625))
meanH<-mean(dataDH)
sigmaH <- matrix((sigma_dh/(2*1.2222101)),d2,1)
sigma <- sigma0
a1 <- sqrt(sigma_dh/n_samDH)
if(mean11<mean12){a1=-a1}
meanH <- as.matrix(c((meanH+3*a1),(meanH+2.5*a1),(meanH+2*a1),(meanH+1.5*a1),(meanH+a1),
(meanH-1.5*a1),(meanH-2*a1),(meanH-2.5*a1),(meanH-3*a1)))
iteration <- 0; stopa <- 1000
WW <- matrix(0,d2,n_samDH); swx <- matrix(0,d2,1)
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanH,sqrt(sigmaH),mi)))
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(dataDH,meanH[i],sqrt(sigmaH[i]))/dmixnorm(dataDH,meanH,sqrt(sigmaH),mi) }
mix_pi <- as.matrix(rowSums(WW)/n_samDH)
sumwx <- WW%*%dataDH
n0 <- n_samDH*mix_pi
n0[n0<0.000001] <- 0.000001
s0<-matrix(0,4,1)
s0[1]<- sigma;s0[2]<- n_samP1+m_fam*n0[1]
s0[3]<- sigma;s0[4]<- n_samP2+m_fam*n0[9]
hh<-matrix(0,6,6)
hh[1,1]<- s0[1]/s0[2]+sigmaH[2]/n0[2]+sigmaH[4]/n0[4]+sigmaH[6]/n0[6]
hh[1,2]<- s0[1]/s0[2]
hh[1,3]<- 0
hh[1,4]<- sigmaH[4]/n0[4]-sigmaH[6]/n0[6]
hh[1,5]<- -(s0[1]/s0[2]+sigmaH[4]/n0[4])
hh[1,6]<- -(s0[1]/s0[2]+2.0*sigmaH[4]/n0[4])
hh[2,2]<- s0[1]/s0[2]+sigmaH[3]/n0[3]+sigmaH[7]/n0[7]+sigmaH[8]/n0[8]
hh[2,3]<- 2.0*sigmaH[7]/n0[7]+sigmaH[8]/n0[8]
hh[2,4]<- 0
hh[2,5]<- -(s0[1]/s0[2]+sigmaH[3]/n0[3])
hh[2,6]<- -(s0[1]/s0[2]+2.0*sigmaH[7]/n0[7])
hh[3,3]<- 4.0*sigmaH[7]/n0[7]+sigmaH[8]/n0[8]+s0[3]/s0[4]
hh[3,4]<- hh[3,5]<- 0
hh[3,6]<- -(4.0*sigmaH[7]/n0[7]+s0[3]/s0[4])
hh[4,4]<- sigmaH[4]/n0[4]+4.0*sigmaH[5]/n0[5]+sigmaH[6]/n0[6]
hh[4,5]<- -(sigmaH[4]/n0[4]+2.0*sigmaH[5]/n0[5])
hh[4,6]<- -2.0*sigmaH[4]/n0[4]
hh[5,5]<- s0[1]/s0[2]+sigmaH[3]/n0[3]+sigmaH[4]/n0[4]+sigmaH[5]/n0[5]
hh[5,6]<- s0[1]/s0[2]+2.0*sigmaH[4]/n0[4]
hh[6,6]<- s0[1]/s0[2]+4.0*sigmaH[4]/n0[4]+4.0*sigmaH[7]/n0[7]+s0[3]/s0[4]
for(i in 2:6){
for(j in 1:(i-1)){
hh[i,j]<- hh[j,i]
}
}
b_line<-matrix(0,6,1)
b_line[1]<- (sum(dataP1)+m_fam*sumwx[1])/(n_samP1+m_fam*n0[1])-sumwx[2]/n0[2]-sumwx[4]/n0[4]+sumwx[6]/n0[6]
b_line[2]<- (sum(dataP1)+m_fam*sumwx[1])/(n_samP1+m_fam*n0[1])-sumwx[3]/n0[3]+sumwx[7]/n0[7]-sumwx[8]/n0[8]
b_line[3]<- 2.0*sumwx[7]/n0[7]-sumwx[8]/n0[8]-(sum(dataP2)+m_fam*sumwx[9])/(n_samP2+m_fam*n0[9])
b_line[4]<- -sumwx[4]/n0[4]+2.0*sumwx[5]/n0[5]-sumwx[6]/n0[6]
b_line[5]<- -(sum(dataP1)+m_fam*sumwx[1])/(n_samP1+m_fam*n0[1])+sumwx[3]/n0[3]+sumwx[4]/n0[4]-sumwx[5]/n0[5]
b_line[6]<- -(sum(dataP1)+m_fam*sumwx[1])/(n_samP1+m_fam*n0[1])+2.0*sumwx[4]/n0[4]+(sum(dataP2)+m_fam*sumwx[9])/(n_samP2+m_fam*n0[9])-2.0*sumwx[7]/n0[7]
B <- solve(hh,b_line)
meanH[1]<-(sum(dataP1)+m_fam*sumwx[1]-(B[1]+B[2]-B[5]-B[6])*sigma)/(n_samP1+m_fam*n0[1])
meanH[2]<-(sumwx[2]+B[1]*sigmaH[2])/n0[2]
meanH[3]<-(sumwx[3]+(B[2]-B[5])*sigmaH[3])/n0[3]
meanH[4]<-(sumwx[4]+(B[1]+B[4]-B[5]-2.0*B[6])*sigmaH[4])/n0[4]
meanH[5]<-(sumwx[5]+(-2.0*B[4]+B[5])*sigmaH[5])/n0[5]
meanH[6]<-(sumwx[6]-(B[1]-B[4])*sigmaH[6])/n0[6]
meanH[7]<-(sumwx[7]-(B[2]+2.0*B[3]-2.0*B[6])*sigmaH[7])/n0[7]
meanH[8]<-(sumwx[8]+(B[2]+B[3])*sigmaH[8])/n0[8]
meanH[9]<-(sum(dataP2)+m_fam*sumwx[9]+(B[3]-B[6])*sigma)/(n_samP2+m_fam*n0[9])
mean11<- meanH[1]
mean12<- meanH[9]
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
for(i in 1:d2) { swx[i] <- WW[i,]%*%(dataDH-meanH[i])^2 }
s0H<-matrix(0,2,1)
s0H[1]<- ss1+ss2
s0H[2]<- sum(swx)*m_fam
s1<- sigmaH[1]-sigma/m_fam
if (s1<0.0){s1<- 0.000001}
abc2<- sigma
abc3<-1000; n_iter<- 0
while(abc3>0.0001){
n_iter<- n_iter+1
sigma<- (s0H[1]+s0H[2])/(n_samP1+n_samP2+n_samDH)
abc3<- abs(abc2-sigma)
abc2<- sigma
if (n_iter>20) break
}
if (sigma<0.1*sigma0){ sigma<- 0.1*sigma0 }
sigmaH<-matrix((sigma/m_fam),d2,1)
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanH,sqrt(sigmaH),mix_pi)))
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) {stopa <- -stopa}
}
abc <- L1
AIC <- -2*abc + 2*4
aa<- matrix(c(1,1,1,1,1,1,1,1,1, 2,2,2,0,0,0,-2,-2,-2, 2,-2,0,2,0,-2,0,2,-2),9,3)
b_line1 <- meanH
B1 <- ginv(t(aa)%*%aa)%*%(t(aa)%*%b_line1)
jj <- sigma_dh - sigmaH[1]
if(jj < 0) {jj <- 0}
ll <- jj/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
for(i in 1:d2){
gg <- (dataDH - meanH[i])/sqrt(sigmaH[i])
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,i] <- bmw*mix_pi[i]
}
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("4MG-EEA",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(t(meanH),4)," "," "," "," "," "," "," ",round(sigmaH[1],4),round(t(mix_pi),4),
" "," "," "," "," "," "," ",round(B1[1],4)," "," ",round(B1[2],4),round(B1[2],4),round(B1[3],4),round(B1[3],4)," "," "," "," "," "," "," "," ",
round(jj,4),round(ll*100,4)," "," ",round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
G3DHModelFun[[38]] <- function(K1,logL,df11,df21,df31,G3DHtext2){
dataP1 <- as.matrix(as.numeric(df11[,1]));dataP2 <- as.matrix(as.numeric(df21[,1]));dataDH <- as.matrix(as.numeric(df31[,1]))
n_samP1<-dim(dataP1)[1]; n_samP2<-dim(dataP2)[1];n_samDH<-dim(dataDH)[1]
mean11<-mean(dataP1);mean12<-mean(dataP2)
sigmaP1<- as.numeric(var(dataP1)); sigmaP2<- as.numeric(var(dataP2))
ss1<-(n_samP1-1)*sigmaP1; ss2<-(n_samP2-1)*sigmaP2
sigma0<-(ss1+ss2)/(n_samP1+n_samP2-2);sigma_dh<-as.numeric(var(dataDH))
m_esp<- 0.0001 ;m_fam<- as.numeric(G3DHtext2)
d2<-8
mi <- as.matrix(c(0.0625,0.0625,0.1875,0.1875,0.1875,0.1875,0.0625,0.0625))
meanH<-mean(dataDH)
sigmaH <- matrix((sigma_dh/(2*1.2222101)),d2,1)
sigma <- sigma0
a1 <- sqrt(sigma_dh/n_samDH)
if(mean11<mean12){a1=-a1}
meanH <- as.matrix(c((meanH+3*a1),(meanH+2.5*a1),(meanH+2*a1),(meanH+1.5*a1),
(meanH-1.5*a1),(meanH-2*a1),(meanH-2.5*a1),(meanH-3*a1)))
iteration <- 0; stopa <- 1000
WW <- matrix(0,d2,n_samDH); swx <- matrix(0,d2,1)
L0 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanH,sqrt(sigmaH),mi)))
while(stopa > m_esp && iteration<=1000){
iteration <- iteration + 1
for(i in 1:d2) { WW[i,] <- mi[i]*dnorm(dataDH,meanH[i],sqrt(sigmaH[i]))/dmixnorm(dataDH,meanH,sqrt(sigmaH),mi) }
mix_pi <- as.matrix(rowSums(WW)/n_samDH)
sumwx <- WW%*%dataDH
n0 <- n_samDH*mix_pi
n0[n0<0.000001] <- 0.000001
s0<-matrix(0,4,1)
s0[1]<- sigma;s0[2]<- n_samP1+m_fam*n0[1]
s0[3]<- sigma;s0[4]<- n_samP2+m_fam*n0[8]
hh<-matrix(0,5,5)
hh[1,1]<- 4.0*s0[1]/s0[2]+9.0*sigmaH[4]/n0[4]+s0[3]/s0[4]
hh[1,2]<- -(2.0*s0[1]/s0[2]+3.0*sigmaH[4]/n0[4])
hh[1,3]<- 0
hh[1,4]<- -2.0*s0[1]/s0[2]
hh[1,5]<- 0
hh[2,2]<- s0[1]/s0[2]+sigmaH[4]/n0[4]+sigmaH[2]/n0[2]+sigmaH[3]/n0[3]
hh[2,3]<- (sigmaH[2]/n0[2]+2.0*sigmaH[3]/n0[3])
hh[2,4]<- s0[1]/s0[2]+sigmaH[2]/n0[2]
hh[2,5]<- 2.0*sigmaH[2]/n0[2]+3.0*sigmaH[3]/n0[3]
hh[3,3]<- sigmaH[2]/n0[2]+4.0*sigmaH[3]/n0[3]+sigmaH[5]/n0[5]
hh[3,4]<- sigmaH[2]/n0[2]-sigmaH[5]/n0[5]
hh[3,5]<- 2.0*sigmaH[2]/n0[2]+6.0*sigmaH[3]/n0[3]
hh[4,4]<- s0[1]/s0[2]+sigmaH[2]/n0[2]+sigmaH[5]/n0[5]+sigmaH[6]/n0[6]
hh[4,5]<- 2.0*sigmaH[2]/n0[2]
hh[5,5]<- 4.0*sigmaH[2]/n0[2]+9.0*sigmaH[3]/n0[3]+sigmaH[7]/n0[7]
for(i in 2:5){
for(j in 1:(i-1)){
hh[i,j]<- hh[j,i]
}
}
b_line<-matrix(0,5,1)
b_line[1]<- -2.0*(sum(dataP1)+m_fam*sumwx[1])/(n_samP1+m_fam*n0[1])+3.0*sumwx[4]/n0[4]-(sum(dataP2)+m_fam*sumwx[8])/(n_samP2+m_fam*n0[8])
b_line[2]<- (sum(dataP1)+m_fam*sumwx[1])/(n_samP1+m_fam*n0[1])-sumwx[2]/n0[2]+sumwx[3]/n0[3]-sumwx[4]/n0[4]
b_line[3]<- -sumwx[2]/n0[2]+2.0*sumwx[3]/n0[3]-sumwx[5]/n0[5]
b_line[4]<- (sum(dataP1)+m_fam*sumwx[1])/(n_samP1+m_fam*n0[1])-sumwx[2]/n0[2]+sumwx[5]/n0[5]-sumwx[6]/n0[6]
b_line[5]<- -2.0*sumwx[2]/n0[2]+3.0*sumwx[3]/n0[3]-sumwx[7]/n0[7]
B <- solve(hh,b_line)
meanH[1]<-(sum(dataP1)+m_fam*sumwx[1]+(2.0*B[1]-B[2]-B[4])*sigma)/(n_samP1+m_fam*n0[1])
meanH[2]<-(sumwx[2]+(B[2]+B[3]+B[4]+2.0*B[5])*sigmaH[2])/n0[2]
meanH[3]<-(sumwx[3]-(B[2]+2.0*B[3]+3.0*B[5])*sigmaH[3])/n0[3]
meanH[4]<-(sumwx[4]+(-3.0*B[1]+B[2])*sigmaH[4])/n0[4]
meanH[5]<-(sumwx[5]+(B[3]-B[4])*sigmaH[5])/n0[5]
meanH[6]<-(sumwx[6]+B[4]*sigmaH[6])/n0[6]
meanH[7]<-(sumwx[7]+B[5]*sigmaH[7])/n0[7]
meanH[8]<-(sum(dataP2)+m_fam*sumwx[8]+B[1]*sigma)/(n_samP2+m_fam*n0[8])
mean11<- meanH[1]
mean12<- meanH[8]
ss1<- sum((dataP1-mean11)^2)
ss2<- sum((dataP2-mean12)^2)
for(i in 1:d2) { swx[i] <- WW[i,]%*%(dataDH-meanH[i])^2 }
s0H<-matrix(0,2,1)
s0H[1]<- ss1+ss2
s0H[2]<- sum(swx)*m_fam
s1<- sigmaH[1]-sigma/m_fam
if (s1<0.0){s1<- 0.000001}
abc2<- sigma
abc3<-1000; n_iter<- 0
while(abc3>0.0001){
n_iter<- n_iter+1
sigma<- (s0H[1]+s0H[2])/(n_samP1+n_samP2+n_samDH)
abc3<- abs(abc2-sigma)
abc2<- sigma
if (n_iter>20) break
}
if (sigma<0.1*sigma0){ sigma<- 0.1*sigma0 }
sigmaH<-matrix((sigma/m_fam),d2,1)
L1 <- logL(n_samP1,1,1,mean11,sigma,dataP1)+logL(n_samP2,1,1,mean12,sigma,dataP2)+sum(log(dmixnorm(dataDH,meanH,sqrt(sigmaH),mix_pi)))
stopa <- L1 - L0
L0 <- L1
if(stopa < 0) {stopa <- -stopa}
}
abc <- L1
AIC <- -2*abc + 2*4
aa<- matrix(c(1,1,1,1,1,1,1,1, 3,3,1,1,-1,-1,-3,-3, 1,-1,-1,1,-1,1,-1,1),8,3)
b_line1 <- meanH
B1 <- ginv(t(aa)%*%aa)%*%(t(aa)%*%b_line1)
jj <- sigma_dh - sigmaH[1]
if(jj < 0) {jj <- 0}
ll <- jj/sigma_dh
dataP1<-sort(dataP1);bmw_P1 <- matrix(0,n_samP1,1); bmwsl_P1 <- matrix(0,n_samP1,1)
gg_P1 <- (dataP1 - mean11)/sqrt(as.vector(sigma))
bmw_P1[which(gg_P1>=0)] <- pnorm(gg_P1[gg_P1>=0])
bmw_P1[which(gg_P1<0)] <- 1 - pnorm(abs(gg_P1[gg_P1<0]))
bmwsl_P1[,1] <- bmw_P1
P2_P1 <- rowSums(bmwsl_P1)
nn<-dim(as.matrix(unique(P2_P1)))[1]
if(nn<n_samP1){P2_P1<-P2_P1+runif(n_samP1)/1e4}
dd_P1 <- as.matrix(c(sum(P2_P1),sum(P2_P1^2),sum((P2_P1-0.5)^2)))
WW2_P1 <- 1/(12*n_samP1) + sum((P2_P1 - (as.matrix(c(1:n_samP1)) - 0.5)/n_samP1)^2)
u_P1 <- as.matrix(c(12*n_samP1*((dd_P1[1]/n_samP1-0.5)^2),((45*n_samP1)/4)*((dd_P1[2]/n_samP1-1/3)^2),180*n_samP1*((dd_P1[3]/n_samP1-1/12)^2)))
D_P1 <- as.numeric(ks.test(P2_P1,"punif")[[1]][1])
tt_P1 <- as.matrix(c((1 - pchisq(u_P1[1],1)),(1 - pchisq(u_P1[2],1)),(1 - pchisq(u_P1[3],1)),K1(WW2_P1),(1-pkolm(D_P1,n_samP1))))
dataP2<-sort(dataP2);bmw_P2 <- matrix(0,n_samP2,1); bmwsl_P2 <- matrix(0,n_samP2,1)
gg_P2 <- (dataP2 - mean12)/sqrt(as.vector(sigma))
bmw_P2[which(gg_P2>=0)] <- pnorm(gg_P2[gg_P2>=0])
bmw_P2[which(gg_P2<0)] <- 1 - pnorm(abs(gg_P2[gg_P2<0]))
bmwsl_P2[,1] <- bmw_P2
P2_P2 <- rowSums(bmwsl_P2)
nn<-dim(as.matrix(unique(P2_P2)))[1]
if(nn<n_samP2){P2_P2<-P2_P2+runif(n_samP2)/1e4}
dd_P2 <- as.matrix(c(sum(P2_P2),sum(P2_P2^2),sum((P2_P2-0.5)^2)))
WW2_P2 <- 1/(12*n_samP2) + sum((P2_P2 - (as.matrix(c(1:n_samP2)) - 0.5)/n_samP2)^2)
u_P2 <- as.matrix(c(12*n_samP2*((dd_P2[1]/n_samP2-0.5)^2),((45*n_samP2)/4)*((dd_P2[2]/n_samP2-1/3)^2),180*n_samP2*((dd_P2[3]/n_samP2-1/12)^2)))
D_P2 <- as.numeric(ks.test(P2_P2,"punif")[[1]][1])
tt_P2 <- as.matrix(c((1 - pchisq(u_P2[1],1)),(1 - pchisq(u_P2[2],1)),(1 - pchisq(u_P2[3],1)),K1(WW2_P2),(1-pkolm(D_P2,n_samP2))))
dataDH<-sort(dataDH);bmw <- matrix(0,n_samDH,1); bmwsl <- matrix(0,n_samDH,d2)
for(i in 1:d2){
gg <- (dataDH - meanH[i])/sqrt(sigmaH[i])
bmw[which(gg>=0)] <- pnorm(gg[gg>=0])
bmw[which(gg<0)] <- 1 - pnorm(abs(gg[gg<0]))
bmwsl[,i] <- bmw*mix_pi[i]
}
P2 <- rowSums(bmwsl)
nn<-dim(as.matrix(unique(P2)))[1]
if(nn<n_samDH){P2<-P2+runif(n_samDH)/1e4}
dd <- as.matrix(c(sum(P2),sum(P2^2),sum((P2-0.5)^2)))
WW2 <- 1/(12*n_samDH) + sum((P2 - (as.matrix(c(1:n_samDH)) - 0.5)/n_samDH)^2)
u <- as.matrix(c(12*n_samDH*((dd[1]/n_samDH-0.5)^2),((45*n_samDH)/4)*((dd[2]/n_samDH-1/3)^2),180*n_samDH*((dd[3]/n_samDH-1/12)^2)))
D <- as.numeric(ks.test(P2,"punif")[[1]][1])
tt <- as.matrix(c((1 - pchisq(u[1],1)),(1 - pchisq(u[2],1)),(1 - pchisq(u[3],1)),K1(WW2),(1-pkolm(D,n_samDH))))
tt_P1[which(tt_P1>=10e-4)]<-round(tt_P1[which(tt_P1>=10e-4)],4);tt_P1[which(tt_P1<10e-4)]<-format(tt_P1[which(tt_P1<10e-4)],scientific=TRUE,digit=4)
tt_P2[which(tt_P2>=10e-4)]<-round(tt_P2[which(tt_P2>=10e-4)],4);tt_P2[which(tt_P2<10e-4)]<-format(tt_P2[which(tt_P2<10e-4)],scientific=TRUE,digit=4)
tt[which(tt>=10e-4)]<-round(tt[which(tt>=10e-4)],4);tt[which(tt<10e-4)]<-format(tt[which(tt<10e-4)],scientific=TRUE,digit=4)
output <- data.frame("4MG-EEEA",round(abc,4),round(AIC,4),round(mean11,4),round(mean12,4),round(sigma,4),round(t(meanH),4)," "," "," "," "," "," "," "," ",round(sigmaH[1],4),round(t(mix_pi),4),
" "," "," "," "," "," "," "," ",round(B1[1],4)," "," ",round(B1[2],4),round(B1[2],4),round(B1[2],4),round(B1[3],4)," "," "," "," "," "," "," "," ",
round(jj,4),round(ll*100,4)," "," ",round(u_P1[1],4),tt_P1[1],round(u_P1[2],4),
tt_P1[2],round(u_P1[3],4),tt_P1[3],round(WW2_P1,4),tt_P1[4],round(D_P1,4),tt_P1[5],round(u_P2[1],4),tt_P2[1],round(u_P2[2],4),
tt_P2[2],round(u_P2[3],4),tt_P2[3],round(WW2_P2,4),tt_P2[4],round(D_P2,4),tt_P2[5],round(u[1],4),tt[1],round(u[2],4),
tt[2],round(u[3],4),tt[3],round(WW2,4),tt[4],round(D,4),tt[5])
output<-as.matrix(output)
OUTPUT<-list(output,mi)
return(OUTPUT)
}
K1G3DH <- function(x){
V0 <- 0
for(j in 0:2)
{I1 <- 0;I2 <- 0
for(k in 0:8)
{I1 <- I1 + (((4*j+1)^2/(32*x))^(-0.25+2*k))/(gamma(k+1)*gamma(0.75+k))
I2 <- I2 + ((4*j+1)^2/(32*x))^(0.25+2*k)/(gamma(k+1)*gamma(1.25+k))}
V0 <- V0 + (gamma(j+0.5)*sqrt(4*j+1)/(gamma(0.5)*gamma(j+1)))*exp(-(4*j+1)^2/(16*x))*(I1-I2)}
V <- (1/sqrt(2*x))*V0
return (1-V)
}
logLG3DH <- function(nm,nng,mi,mn,s,d1) { sum2 <- sum(log(dmixnorm(d1,mn,sqrt(s),mi)));return (sum2) }
if(model=="All models"){
cl.cores <- detectCores()
if(cl.cores<=2){
cl.cores<-1
}else if(cl.cores>2){
if(cl.cores>10){
cl.cores<-10
}else {
cl.cores <- detectCores()-1
}
}
cl <- makeCluster(cl.cores)
registerDoParallel(cl)
i<-NULL
allresult=foreach(i=1:38,.combine = 'rbind')%dopar%{
requireNamespace("KScorrect")
requireNamespace("kolmim")
requireNamespace("MASS")
G3DHModelFun[[i]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2)[[1]]
}
stopCluster(cl)
mi<-NULL
}else{
allresultq<-switch(model,"0MG"=G3DHModelFun[[1]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2),"1MG-A"=G3DHModelFun[[2]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2),"2MG-AI"=G3DHModelFun[[3]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2),
"2MG-A"=G3DHModelFun[[4]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2),"2MG-EA"=G3DHModelFun[[5]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2),"2MG-ED"=G3DHModelFun[[6]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2),
"2MG-ER"=G3DHModelFun[[7]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2),"2MG-AE"=G3DHModelFun[[8]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2),"2MG-CE"=G3DHModelFun[[9]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2),
"2MG-DE"=G3DHModelFun[[10]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2),"PG-AI"=G3DHModelFun[[12]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2),
"PG-A"=G3DHModelFun[[13]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2),"MX1-A-AI"=G3DHModelFun[[14]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2),"MX1-A-A"=G3DHModelFun[[15]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2),
"MX2-AI-AI"=G3DHModelFun[[16]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2),"MX2-AI-A"=G3DHModelFun[[17]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2),"MX2-A-A"=G3DHModelFun[[18]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2),
"MX2-EA-A"=G3DHModelFun[[19]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2),"MX2-ED-A"=G3DHModelFun[[20]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2),"MX2-ER-A"=G3DHModelFun[[21]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2),
"MX2-AE-A"=G3DHModelFun[[22]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2),"MX2-CE-A"=G3DHModelFun[[23]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2),"MX2-DE-A"=G3DHModelFun[[24]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2),
"MX2-IE-A"=G3DHModelFun[[25]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2),"3MG-AI"=G3DHModelFun[[26]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2),"3MG-A"=G3DHModelFun[[27]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2),
"3MG-CEA"=G3DHModelFun[[28]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2),"3MG-PEA"=G3DHModelFun[[29]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2),"MX3-AI-AI"=G3DHModelFun[[30]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2),
"MX3-AI-A"=G3DHModelFun[[31]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2),"MX3-A-A"=G3DHModelFun[[32]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2),"MX3-CEA-A"=G3DHModelFun[[33]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2),
"MX3-PEA-A"=G3DHModelFun[[34]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2),"4MG-AI"=G3DHModelFun[[35]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2),"4MG-CEA"=G3DHModelFun[[36]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2),
"4MG-EEA"=G3DHModelFun[[37]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2),"4MG-EEEA"=G3DHModelFun[[38]](K1G3DH,logLG3DH,df11,df21,df31,G3DHtext2))
allresult<-allresultq[[1]]
if(model=="0MG"||model=="PG-A"||model=="PG-AI"){
mi<-NULL
}else{
mi<-allresultq[[2]]
}
}
colnames(allresult) <- G3DHcolname
out<-list(allresult,mi)
return(out)
} |
getT <- function(countsTable, sizeFactors = NULL, q.vec = NULL,
numPart = 1, propForSigma = c(0, 1), verbose = TRUE, shrinkTarget = NULL,
shrinkQuantile = NULL, shrinkVar = FALSE, eSlope = 0.05,
disp = NULL, dispXX = NULL, normalize = FALSE, lwd1 = 4.5,
cexlab1 = 1.2) {
if (!is.null(countsTable)) {
counts = as.matrix(countsTable)
}
if (is.null(countsTable) & is.null(disp)) {
stop("at least provide the initial dispersion estimates.")
}
if (is.null(sizeFactors) & !is.null(countsTable)) {
sizeFactors = getNormFactor(countsTable)
}
if (is.null(eSlope)) {
eSlope = 0.002
} else {
if (length(eSlope) > 1 & verbose)
print("Note: only the first value in eSlope is used for tests.")
}
allAdjDisp = list()
if (is.null(disp) & !is.null(countsTable)) {
normc = as.matrix(t(t(counts) / sizeFactors))
normc.m = rowMeans(normc)
normc.v = rowVars(as.matrix(t(t(counts) / sqrt(sizeFactors))))
s_st = mean(1 / sizeFactors)
disp = (normc.v - normc.m) / (normc.m)^2
normc.m[normc.m <= 0] = 1
log.normc.m = log(normc.m)
} else if (!is.null(dispXX)) {
normc.m = dispXX
normc.m[normc.m <= 0] = 1
log.normc.m = log(normc.m)
} else {
normc.m = NULL
log.normc.m = NULL
}
if (shrinkVar & is.null(disp)) {
disp = normc.v
if (verbose)
print("Shrinkage estimates on variance are used.")
} else {
if (verbose)
print("Shrinkage estimates on dispersion are used for the tests.")
}
disp[is.na(disp)] = 0
disp[disp <= 0] = 0
if (numPart == 1) {
disp.m = mean(disp)
asd.mle = round(mean((disp - disp.m)^2, na.rm = T), 4)
rg.xx = quantile(disp[is.finite(disp)], prob = c(0.05, 0.995))
xx = seq(rg.xx[1], rg.xx[2], length.out = 200)
asd = rep(0, length(xx))
for (i in 1:length(xx)) {
allAdjDisp[[i]] = equalSpace(disp, log.normc.m, 1,
propForSigma = propForSigma, shrinkTarget = xx[i],
vb = FALSE)
allAdjDisp[[i]] = pmax(1e-08, allAdjDisp[[i]])
names(allAdjDisp[[i]]) = 1:length(disp)
asd[i] = mean((allAdjDisp[[i]] - disp)^2, na.rm = T)
}
diff.q = diff.asd = rep(0, length(asd))
maxASD = max(asd, na.rm = T)
maxASD.pnt = which(asd == maxASD)
for (i in 1:length(asd)) {
diff.asd[i] = maxASD - asd[i]
diff.q[i] = xx[maxASD.pnt] - xx[i]
}
numAdjPoints = 6
len.asd = length(asd) - numAdjPoints + 1
slope1 = rep(1, len.asd)
if (normalize) {
xx1 = xx / sd(xx)
yy1 = asd / sd(asd)
eSlope = eSlope * 5
} else {
xx1 = xx
yy1 = asd
}
for (i in 1:len.asd) {
slope1.xx = xx1[i:(i + numAdjPoints - 1)]
slope1.yy = yy1[i:(i + numAdjPoints - 1)]
slope1[i] = cov(slope1.xx, slope1.yy) / var(slope1.xx)
}
maxSlope1 = max(abs(slope1))
maxSlope1.pnt = which(abs(slope1) == maxSlope1)
sub.slope1 = abs(slope1)[maxSlope1.pnt:len.asd]
sub.diff.asd = diff.asd[maxSlope1.pnt:length(diff.asd)]
pred.diff = matrix(NA, nrow = length(sub.diff.asd), ncol = numAdjPoints)
for (i in 1:length(sub.diff.asd)) {
for (j in 1:numAdjPoints) {
if (i - j >= 0) {
pred.diff[i, j] = sub.diff.asd[i] / sub.slope1[i - j + 1]
}
}
}
max.pred = max(pred.diff, na.rm = T)
max.rowInd = which(apply(pred.diff, 1, max, na.rm = T) == max.pred)
temp.max.pnt = max.rowInd + maxSlope1.pnt - 1 - ceiling(numAdjPoints/2)
max.pnt = rep(0, length(eSlope))
for (k in 1:length(eSlope)) {
max.pnt[k] = temp.max.pnt[1]
while (-slope1[max.pnt[k] - ceiling(numAdjPoints/2)] <
eSlope[k] & slope1[max.pnt[k] - ceiling(numAdjPoints/2)] < 0) {
max.pnt[k] = max.pnt[k] - 1
}
}
if (!is.null(shrinkQuantile)) {
max.pnt = 1
q.vec = shrinkQuantile
adjDisp1 = equalSpace(disp, log.normc.m, numPart,
propForSigma = propForSigma, shrinkQuantile = q.vec[1],
vb = FALSE)
adjDisp1 = pmax(1e-08, adjDisp1)
names(adjDisp1) = 1:length(disp)
asd.target = mean((adjDisp1 - disp)^2, na.rm = T)
target = round(quantile(disp, prob = q.vec[1]), 3)
}
if (!is.null(shrinkTarget)) {
max.pnt = 1
disp.tm = c(disp[!is.na(disp)], shrinkTarget[1])
q.vec = round(rank(disp.tm)[disp.tm == shrinkTarget[1]] / length(disp[!is.na(disp)]), 3)
adjDisp1 = equalSpace(disp, log.normc.m, numPart,
propForSigma = propForSigma, shrinkQuantile = q.vec[1],
vb = FALSE)
adjDisp1 = pmax(1e-08, adjDisp1)
names(adjDisp1) = 1:length(disp)
asd.target = mean((adjDisp1 - disp)^2, na.rm = T)
target = shrinkTarget[1]
}
if (is.null(shrinkQuantile) & is.null(shrinkTarget)) {
target = asd.target = q.vec = rep(0, length(eSlope))
for (k in 1:length(eSlope)) {
target[k] = xx[max.pnt[k]][1]
asd.target[k] = asd[max.pnt[k]]
disp.tm = c(disp[!is.na(disp)], target[k])
q.vec[k] = round(rank(disp.tm)[disp.tm == target[k]] / length(disp[!is.na(disp)]), 3)
}
}
if (verbose) {
if (!is.null(shrinkQuantile) | !is.null(shrinkTarget)) {
print(paste("The selected shrink target is",
target[1]))
print(paste("The selected shrink quantile is",
q.vec[1]))
}
else {
print(paste("The shrink target is", target[1]))
print(paste("The shrink quantile is", q.vec[1]))
}
}
return(list(q = q.vec[1], target = target[1]))
} else if (numPart > 1) {
if (is.null(log.normc.m)) {
stop("Error in getT: log.normc.m can not be NULL.")
}
out = getTgroup(y = disp, x = log.normc.m, numPart = numPart,
verbose = verbose, eSlope = eSlope,
lwd1 = lwd1, cexlab1 = cexlab1)
return(out)
} else {
stop("Error: numPart must be a non-negative integer.")
}
}
getAdjustDisp <- function(obs, propForSigma = c(0.5, 1), shrinkTarget = NULL,
shrinkQuantile = NULL, verbose = TRUE){
obs[is.na(obs)] = 0
if (is.null(shrinkTarget)) {
upBound = quantile(obs, prob = shrinkQuantile, na.rm = T)
if (verbose) {
print(paste("shrink toward ", shrinkTarget, " (",
shrinkQuantile, "th quantile).", sep = ""))
}
} else {
upBound = shrinkTarget
if (verbose) {
print(paste("shrink toward ", shrinkTarget, ".", sep = ""))
}
}
if (is.null(propForSigma)) {
subobs = obs[obs >= upBound & obs <= quantile(obs, prob = 0.999)]
S.mat = var(subobs, na.rm = T)
} else if (length(propForSigma) == 2) {
subobs = obs
rg = quantile(subobs[is.finite(subobs)], na.rm = T, prob = propForSigma)
subobs = subobs[subobs >= rg[1] & subobs <= rg[2]]
S.mat = var(subobs[is.finite(subobs)], na.rm = T)
} else if (length(propForSigma) == 1 & is.numeric(propForSigma)) {
S.mat = propForSigma
} else if (is.na(propForSigma)) {
subobs = obs[is.finite(obs)]
S.mat = var(subobs[is.finite(subobs)], na.rm = T)
} else {
stop(paste("if don't know the empirical value on the variance of",
"dispersion, please set it as NULL."))
}
cmp = data.frame(mean = mean(obs, na.rm = T), sigmasq.part = S.mat)
mean.mat = rep(upBound, length(obs))
dif.mat = obs - mean.mat
dif2.mat = sum(dif.mat^2)
deta = 1 - ((length(obs) - 2) * S.mat / (dif2.mat))
jsDiff = pmax(0, deta) * dif.mat
jsest = jsDiff + mean.mat
return(list(adj = jsest, cmp = cmp))
}
getNormFactor <- function (countsTable1){
countsTable1.log = log(countsTable1)
row.mean1.log = rowMeans(countsTable1.log)
geo.dev1.log = countsTable1.log - row.mean1.log
apply(geo.dev1.log, 2, function(x) {
exp(median(x[is.finite(x)]))
})
}
rowVars <- function (x){
apply(x, 1, var, na.rm = T)
}
equalSpace <- function (y, x = NULL, numcls = 1, propForSigma = c(0, 1), shrinkTarget = NULL,
shrinkQuantile = 0.975, vb = TRUE){
if (numcls == 1 | is.null(x))
return(getAdjustDisp(y, propForSigma = propForSigma,
shrinkTarget, shrinkQuantile, verbose = vb)$adj)
if (!is.null(shrinkTarget) & length(shrinkTarget) != numcls) {
print(paste("Warning: the number of shrink targes is unequal to the",
"number of pre-decied groups. Only the first target is used."))
shrinkTarget = shrinkTarget[1]
numcls = 1
}
if (sum(is.na(x)) > 0)
print("The NA values in the dependent variable were ignored.")
if (length(y) != length(x))
stop(paste("Error: check the input of equalSpace. y and x have",
"unequal lengths in equalSpace function."))
rgx = range(x[x > -Inf])
cut = seq(from = rgx[1], to = rgx[2], length = numcls + 1)
cls = rep(1, length(y))
cls[x <= cut[2]] = 1
cls[x > cut[numcls]] = numcls
for (i in 2:(numcls - 1)) {
cls[x > cut[i] & x <= cut[i + 1]] = i
}
sizes = tapply(rep(1, length(cls)), cls, sum)
js = y
mean.y = mean(y)
for (i in 1:length(sizes)) {
if (sizes[i] > 2) {
x.sub = x[cls == i]
if (!is.null(shrinkTarget)) {
mixr = getAdjustDisp(y[cls == i], propForSigma = propForSigma,
shrinkTarget[i], shrinkQuantile, verbose = vb)
} else {
mixr = getAdjustDisp(y[cls == i], propForSigma = propForSigma,
shrinkTarget = NULL, shrinkQuantile = shrinkQuantile,
verbose = vb)
}
js[cls == i] = mixr$adj
} else {
js[cls == i] = mean.y
}
}
return(js)
}
getTgroup <- function (y, x, numPart = 10, plotASD = FALSE, verbose = FALSE,
eSlope = 0.05, lwd1 = 4.5, cexlab1 = 1.2){
rgx = range(x[is.finite(x)])
cut = seq(from = rgx[1], to = rgx[2], length = numPart + 1)
cls = rep(1, length(y))
cls[x <= cut[2]] = 1
cls[x > cut[numPart]] = numPart
for (i in 2:(numPart - 1)) {
cls[x > cut[i] & x <= cut[i + 1]] = i
}
sizes = tapply(rep(1, length(cls)), cls, sum)
qall.vec = targetall = rep(1, numPart)
for (gp in 1:numPart) {
allAdjy = list()
y1 = y[cls == gp]
x1 = x[cls == gp]
y.m = mean(y1)
asd.mle = round(mean((y1 - y.m)^2, na.rm = T), 4)
rg.xx = quantile(y[is.finite(y1)], prob = c(0.05, 0.995))
xx = seq(rg.xx[1], rg.xx[2], length.out = 200)
asd = rep(0, length(xx))
for (i in 1:length(xx)) {
allAdjy[[i]] = equalSpace(y = y1, x = x1, numcls = 1,
shrinkTarget = xx[i], vb = FALSE)
allAdjy[[i]] = pmax(1e-08, allAdjy[[i]])
names(allAdjy[[i]]) = 1:length(y1)
asd[i] = mean((allAdjy[[i]] - y1)^2, na.rm = T)
}
diff.q = diff.asd = rep(0, length(asd))
maxASD = max(asd, na.rm = T)
maxASD.pnt = which(asd == maxASD)
maxASD.pnt = max(maxASD.pnt)
for (i in 1:length(asd)) {
diff.asd[i] = maxASD - asd[i]
diff.q[i] = xx[maxASD.pnt] - xx[i]
}
numAdjPoints = 6
len.asd = length(asd) - numAdjPoints + 1
slope1 = rep(1, len.asd)
xx1 = xx
y11 = asd
for (i in 1:len.asd) {
slope1.xx = xx1[i:(i + numAdjPoints - 1)]
slope1.y1 = y11[i:(i + numAdjPoints - 1)]
slope1[i] = cov(slope1.xx, slope1.y1) / var(slope1.xx)
}
maxSlope1 = max(abs(slope1))
maxSlope1.pnt = which(abs(slope1) == maxSlope1)
sub.slope1 = abs(slope1)[maxSlope1.pnt:len.asd]
sub.diff.asd = diff.asd[maxSlope1.pnt:length(diff.asd)]
pred.diff = matrix(NA, nrow = length(sub.diff.asd), ncol = numAdjPoints)
for (i in 1:length(sub.diff.asd)) {
for (j in 1:numAdjPoints) {
if (i - j >= 0) {
pred.diff[i, j] = sub.diff.asd[i] / sub.slope1[i - j + 1]
}
}
}
max.pred = max(pred.diff, na.rm = T)
max.rowInd = which(apply(pred.diff, 1, max, na.rm = T) == max.pred)
temp.max.pnt = max.rowInd + maxSlope1.pnt - 1 - ceiling(numAdjPoints / 2)
max.pnt = rep(0, length(eSlope))
for (k in 1:length(eSlope)) {
max.pnt[k] = temp.max.pnt[1]
tm1 = -slope1[max.pnt[k] - ceiling(numAdjPoints/2)]
tm2 = -tm1
while (!is.na(tm1) & tm1[1] < eSlope[k] & tm2[1] < 0) {
max.pnt[k] = max.pnt[k] - 1
tm1 = -slope1[max.pnt[k] - ceiling(numAdjPoints/2)]
tm2 = -tm1
if (length(tm1) == 0)
break
}
}
target = asd.target = q.vec = rep(0, length(eSlope))
for (k in 1:length(eSlope)) {
target[k] = xx[max.pnt[k]][1]
asd.target[k] = asd[max.pnt[k]][1]
y.tm = c(y1[!is.na(y1)], target[k])
q.vec[k] = round(rank(y.tm)[y.tm == target[k]]/length(y1[!is.na(y1)]), 3)
}
if (verbose) {
print(paste("In group", gp, "the average of the values on",
"X-axis for", sizes[gp], "genes is", mean(x1, na.rm = T)))
print(paste("shrinkTarget ", target[1], " and shrinkQuantile ",
q.vec[1], ".", sep = ""))
}
qall.vec[gp] = q.vec[1]
targetall[gp] = target[1]
}
return(list(q = qall.vec, target = targetall))
} |
checkArg = function(x, cl, s4 = FALSE, len, min.len, max.len, choices, subset, lower = NA, upper = NA, na.ok = TRUE, formals) {
s = deparse(substitute(x))
if (missing(x))
stop("Argument ", s, " must not be missing!")
cl2 = class(x)[1]
len2 = length(x)
matchEl = function(x, xs) any(sapply(xs, function(y) identical(y, x)))
if (!missing(choices)) {
if (!matchEl(x, choices))
stop("Argument ", s, " must be any of: ", collapse(choices), "!")
} else if (!missing(subset)) {
if (!all(sapply(x, matchEl, xs = subset)))
stop("Argument ", s, " must be subset of: ", collapse(subset), "!")
} else if (!missing(formals)) {
if (!is.function(x))
stop("Argument ", s, " must be of class ", "function", " not: ", cl2, "!")
fs = names(formals(x))
if (length(fs) < length(formals) || !all(formals == fs[seq_along(formals)]))
stop("Argument function must have first formal args: ", paste(formals, collapse = ","), "!")
} else {
mycheck = function(x, cc)
if(identical(cc, "numeric"))
is.numeric(x)
else if(identical(cc, "integer"))
is.integer(x)
else if(identical(cc, "vector"))
is.vector(x)
else if (!s4)
inherits(x, cc)
else if (s4)
is(x, cc)
if (!any(sapply(cl, mycheck, x = x)))
stop("Argument ", s, " must be of class ", collapse(cl, " OR "), ", not: ", cl2, "!")
if (!missing(len) && len2 != len)
stop("Argument ", s, " must be of length ", len, " not: ", len2, "!")
if (!missing(min.len) && len2 < min.len)
stop("Argument ", s, " must be at least of length ", min.len, " not: ", len2, "!")
if (!missing(max.len) && len2 > max.len)
stop("Argument ", s, " must be at most of length ", max.len, " not: ", len2, "!")
if (!na.ok && any(is.na(x)))
stop("Argument ", s, " must not contain any NAs!")
if (is.numeric(x) && !is.na(lower) && ((is.na(x) && !na.ok) || (!is.na(x) && any(x < lower))))
stop("Argument ", s, " must be greater than or equal ", lower, "!")
if (is.numeric(x) && !is.na(upper) && ((is.na(x) && !na.ok) || (!is.na(x) && any(x > upper))))
stop("Argument ", s, " must be less than or equal ", upper, "!")
}
} |
cgamm = function(formula, nsim = 0, family = gaussian(), cpar = 1.2, data = NULL, weights = NULL, sc_x = FALSE, sc_y = FALSE, bisect = TRUE, reml = TRUE) {
cl <- match.call()
mf <- match.call(expand.dots = FALSE)
m <- match(c("formula", "data"), names(mf), 0L)
mf <- mf[c(1L, m)]
mf[[1]] <- quote(lme4::lFormula)
mf <- eval(mf, parent.frame(1L))$fr
ynm <- names(mf)[1]
mt <- attr(mf, "terms")
y <- model.response(mf, "any")
shapes1 <- NULL; shapes2 <- NULL
xmat <- NULL; xnms <- NULL
tr <- NULL; pl <- NULL; umb <- NULL
tree.delta <- NULL; umbrella.delta <- NULL
tid1 <- NULL; tid2 <- NULL; tpos2 <- 0
uid1 <- NULL; uid2 <- NULL; upos2 <- 0
nums <- NULL; ks <- list(); sps <- NULL; xid <- 1
zmat <- NULL; zid <- NULL; zid0 <- NULL; zid1 <- NULL; zid2 <- NULL; znms <- NULL; is_param <- NULL; is_fac <- NULL; vals <- NULL; st <- 1; ed <- 1
ztb <- list(); iztb <- 1
nc <- ncol(mf)
id <- mf[,nc]
szs <- unname(table(id))
for (i in 2:(nc-1)) {
if (is.numeric(attributes(mf[,i])$shape)) {
shapes1 <- c(shapes1, attributes(mf[,i])$shape)
xmat <- cbind(xmat, mf[,i])
xnms <- c(xnms, attributes(mf[,i])$nm)
nums <- c(nums, attributes(mf[,i])$numknots)
sps <- c(sps, attributes(mf[,i])$space)
ks[[xid]] <- attributes(mf[,i])$knots
xid <- xid + 1
}
if (is.character(attributes(mf[,i])$shape)) {
shapes2 <- c(shapes2, attributes(mf[,i])$shape)
if (attributes(mf[,i])$shape == "tree") {
pl <- c(pl, attributes(mf[,i])$pl)
treei <- tree.fun(mf[,i], attributes(mf[,i])$pl)
tree.delta <- rbind(tree.delta, treei)
tpos1 <- tpos2 + 1
tpos2 <- tpos2 + nrow(treei)
tid1 <- c(tid1, tpos1)
tid2 <- c(tid2, tpos2)
tr <- cbind(tr, mf[,i])
}
if (attributes(mf[,i])$shape == "umbrella") {
umbi <- umbrella.fun(mf[,i])
umbrella.delta <- rbind(umbrella.delta, umbi)
upos1 <- upos2 + 1
upos2 <- upos2 + nrow(umbi)
uid1 <- c(uid1, upos1)
uid2 <- c(uid2, upos2)
umb <- cbind(umb, mf[,i])
}
}
if (is.null(attributes(mf[,i])$shape)) {
if (!is.null(names(mf)[i])) {
znms <- c(znms, names(mf)[i])
}
if (!is.matrix(mf[,i])) {
zid <- c(zid, i)
is_param <- c(is_param, TRUE)
if (is.factor(mf[,i])) {
is_fac <- c(is_fac, TRUE)
ch_char <- suppressWarnings(is.na(as.numeric(levels(mf[, i]))))
if (any(ch_char)) {
vals <- c(vals, unique(levels(mf[, i]))[-1])
} else {
vals <- c(vals, as.numeric(levels(mf[, i]))[-1])
}
nlvs <- length(attributes(mf[,i])$levels)
ed <- st + nlvs - 2
zid1 <- c(zid1, st)
zid2 <- c(zid2, ed)
st <- st + nlvs - 1
zmat0 <- model.matrix(~ mf[, i])[, -1, drop = FALSE]
zmat <- cbind(zmat, zmat0)
ztb[[iztb]] <- mf[,i]
iztb <- iztb + 1
} else {
is_fac <- c(is_fac, FALSE)
zmat <- cbind(zmat, mf[, i])
ztb[[iztb]] <- mf[,i]
iztb <- iztb + 1
ed <- st
zid1 <- c(zid1, st)
zid2 <- c(zid2, ed)
st <- st + 1
vals <- c(vals, "")
}
} else {
is_param <- c(is_param, FALSE)
is_fac <- c(is_fac, FALSE)
zmat0 <- mf[, i]
mat_cols <- ncol(zmat0)
mat_rm <- NULL
for (irm in 1:mat_cols) {
if (all(round(diff(zmat0[, irm]), 8) == 0)) {
mat_rm <- c(mat_rm, irm)
}
}
if (!is.null(mat_rm)) {
zmat0 <- zmat0[, -mat_rm, drop = FALSE]
}
zmat <- cbind(zmat, zmat0)
ztb[[iztb]] <- mf[,i]
iztb <- iztb + 1
vals <- c(vals, 1)
zid <- c(zid, i)
nlvs <- ncol(zmat0) + 1
ed <- st + nlvs - 2
zid1 <- c(zid1, st)
zid2 <- c(zid2, ed)
st <- st + nlvs - 1
}
}
}
dimnames(zmat)[[2]] <- NULL
wt.iter = FALSE
if (is.null(shapes1) & is.null(shapes2)) {
nsim <- 0
}
xmat0 <- xmat; shapes0 <- shapes1; nums0 <- nums; ks0 <- ks; sps0 <- sps; xnms0 <- xnms; idx_s <- NULL; idx <- NULL
if (any(shapes1 == 17)) {
kshapes <- length(shapes1)
obs <- 1:kshapes
idx_s <- obs[which(shapes1 == 17)]; idx <- obs[which(shapes1 != 17)]
xmat0[ ,1:length(idx_s)] <- xmat[ ,idx_s]
shapes0[1:length(idx_s)] <- shapes1[idx_s]
nums0[1:length(idx_s)] <- nums[idx_s]
sps0[1:length(idx_s)] <- sps[idx_s]
ks0[1:length(idx_s)] <- ks[idx_s]
xnms0[1:length(idx_s)] <- xnms[idx_s]
if (length(idx) > 0) {
xmat0[ ,(1 + length(idx_s)):kshapes] <- xmat[ ,idx]
shapes0[(1 + length(idx_s)):kshapes] <- shapes1[idx]
nums0[(1 + length(idx_s)):kshapes] <- nums[idx]
sps0[(1 + length(idx_s)):kshapes] <- sps[idx]
ks0[(1 + length(idx_s)):kshapes] <- ks[idx]
xnms0[(1 +length(idx_s)):kshapes] <- xnms[idx]
}
}
shapes <- c(shapes1, shapes2)
ans <- cgamm.fit(y = y, xmat = xmat0, zmat = zmat, id = id, shapes = shapes0, numknots = nums0, knots = ks0, space = sps0, nsim = nsim, family = family, cpar = cpar, wt.iter = wt.iter, umbrella.delta = umbrella.delta, tree.delta = tree.delta, weights = weights, sc_x = sc_x, sc_y = sc_y, idx_s = idx_s, idx = idx, bisect = bisect, reml = reml)
rslt <- list(muhat = ans$muhat, coefs = ans$coefs, bh = ans$bh, zcoefs = ans$zcoefs, pvals.beta = ans$pvals.beta, se.beta = ans$se.beta, vcoefs = ans$vcoefs, ahat = ans$ahat, sig2hat = ans$sig2hat, siga2hat = ans$siga2hat, thhat = ans$thhat, bigmat = ans$bigmat, gtil=ans$gtil, dd2=ans$dd2, id = id, szs = szs, shapes = shapes0, numknots = ans$numknots, knots = ans$knots, space = sps0, d0 = ans$np, xmat_add = xmat, xmat0 = ans$xmat2, knots0 = ans$knots2, numknots0 = ans$numknots2, sps0 = ans$sps2, ms0 = ans$ms2, etacomps = ans$etacomps, xnms_add = xnms, xid1 = ans$xid1, xid2 = ans$xid2, ynm = ynm, y = y, znms = znms, zmat = zmat, ztb = ztb, zid = zid, zid1 = zid1, zid2 = zid2, vals = vals, family = family, is_fac = is_fac, is_param = is_param, tms = mt, capm = ans$capm, capms = ans$capms, capk = ans$capk, capt = ans$capt, capu = ans$capu, mod.lmer = ans$mod.lmer, pv.siga2 = ans$pv.siga2, ci.siga2 = ans$ci.siga2, ci.siga2.bi = ans$ci.siga2.bi, ci.th = ans$ci.th, ci.rho = ans$ci.rho, ci.sig2 = ans$ci.sig2, ones = ans$ones, resid_df_obs = ans$resid_df_obs, edf = ans$edf)
rslt$call <- cl
class(rslt) <- c("cgamm", "cgam")
return (rslt)
}
cgamm.fit = function(y, xmat, zmat, id, shapes, numknots, knots, space, nsim, family = gaussian(), cpar = 1.2, wt.iter = FALSE, umbrella.delta = NULL, tree.delta = NULL, weights = NULL, sc_x = FALSE, sc_y = FALSE, idx_s = NULL, idx = NULL, bisect = FALSE, modlmer = FALSE, reml = TRUE) {
cicfamily = CicFamily(family)
llh.fun = cicfamily$llh.fun
linkfun = cicfamily$linkfun
etahat.fun = cicfamily$etahat.fun
gr.fun = cicfamily$gr.fun
wt.fun = cicfamily$wt.fun
zvec.fun = cicfamily$zvec.fun
muhat.fun = cicfamily$muhat.fun
ysim.fun = cicfamily$ysim.fun
deriv.fun = cicfamily$deriv.fun
dev.fun = cicfamily$dev.fun
n = length(y)
szs = unname(table(id))
ncl = length(szs)
balanced = FALSE
if (length(unique(szs)) == 1) {balanced = TRUE}
ycl = f_ecl(y, ncl, szs)
sm = 1e-7
capl = length(xmat) / n
if (capl < 1) {capl = 0}
if (round(capl, 8) != round(capl, 1)) {stop ("Incompatible dimensions for xmat!")}
if (capl > 0 & sc_x) {
for (i in 1:capl) {xmat[,i] = (xmat[,i] - min(xmat[,i])) / (max(xmat[,i]) - min(xmat[,i]))}
}
if (sc_y) {
sc = sd(y)
y = y / sc
}
capk = length(zmat) / n
if (capk < 1) {capk = 0}
if (round(capk, 8) != round(capk, 1)) {stop ("Incompatible dimensions for zmat!")}
capls = sum(shapes == 17)
delta = NULL
varlist = NULL
xid1 = NULL; xid2 = NULL; xpos2 = 0
knotsuse = list(); numknotsuse = NULL
mslst = list()
capm = 0
capms = 0
if (capl > 0) {
del1_ans = makedelta(xmat[, 1], shapes[1], numknots[1], knots[[1]], space = space[1])
del1 = del1_ans$amat
knotsuse[[1]] = del1_ans$knots
mslst[[1]] = del1_ans$ms
numknotsuse = c(numknotsuse, length(del1_ans$knots))
m1 = length(del1) / n
if (shapes[1] == 17) {capms = capms + m1}
var1 = 1:m1*0 + 1
xpos1 = xpos2 + 1
xpos2 = xpos2 + m1
xid1 = c(xid1, xpos1)
xid2 = c(xid2, xpos2)
if (capl == 1) {
delta = del1
varlist = var1
} else {
for (i in 2:capl) {
del2_ans = makedelta(xmat[,i], shapes[i], numknots[i], knots[[i]], space = space[i])
del2 = del2_ans$amat
knotsuse[[i]] = del2_ans$knots
mslst[[i]] = del2_ans$ms
numknotsuse = c(numknotsuse, length(del2_ans$knots))
m2 = length(del2) / n
if (shapes[i] == 17) {capms = capms + m2}
xpos1 = xpos2 + 1
xpos2 = xpos2 + m2
xid1 = c(xid1, xpos1)
xid2 = c(xid2, xpos2)
delta = rbind(del1, del2)
varlist = 1:(m1 + m2)*0
varlist[1:m1] = var1
varlist[(m1 + 1):(m1 + m2)] = (1:m2)*0 + i
var1 = varlist
m1 = m1 + m2
del1 = delta
}
}
xvec = NULL
if (sum(shapes > 2 & shapes < 5 | shapes > 10 & shapes < 13) > 0 & capk > 0) {
xvec = t(xmat[, shapes > 2 & shapes < 5 | shapes > 10 & shapes < 13])
bigmat = rbind(1:n*0 + 1, t(zmat), xvec, delta)
np = 1 + capk + sum(shapes > 2 & shapes < 5 | shapes > 10 & shapes < 13) + capms
} else if (sum(shapes > 2 & shapes < 5 | shapes > 10 & shapes < 13) > 0 & capk == 0) {
xvec = t(xmat[, shapes > 2 & shapes < 5 | shapes > 10 & shapes < 13])
bigmat = rbind(1:n*0 + 1, xvec, delta)
np = 1 + sum(shapes > 2 & shapes < 5 | shapes > 10 & shapes < 13) + capms
} else if (sum(shapes > 2 & shapes < 5 | shapes > 10 & shapes < 13) == 0 & capk > 0) {
bigmat = rbind(1:n*0 + 1, t(zmat), delta)
np = 1 + capk + capms
} else if (sum(shapes > 2 & shapes < 5 | shapes > 10 & shapes < 13) == 0 & capk == 0) {
bigmat = rbind(1:n*0 + 1, delta)
np = 1 + capms
} else {
print ("error in capk, shapes!")
}
capm = length(delta) / n - capms
}
if (!is.null(umbrella.delta)) {
bigmat = rbind(bigmat, umbrella.delta)
capu = length(umbrella.delta) / n
} else {capu = 0}
if (!is.null(tree.delta)) {
bigmat = rbind(bigmat, tree.delta)
capt = length(tree.delta) / n
} else {capt = 0}
if (!is.null(umbrella.delta) | !is.null(tree.delta))
delta_ut = rbind(umbrella.delta, tree.delta)
if (!wt.iter) {
if (is.null(weights)) {
weights = 1:n*0 + 1
}
wt = weights
zvec = wt^(1/2) * y
gmat = t(bigmat)
for (i in 1:n) {gmat[i,] = bigmat[,i] * sqrt(wt[i])}
if (any(shapes != 17)) {
dsend = gmat[, (np + 1):(np + capm + capu + capt), drop = FALSE]
zsend = gmat[, 1:np, drop = FALSE]
ans = coneB(zvec, dsend, zsend)
edf = ans$df
face = ans$face
bh = coef(ans)
if (any(round(bh[1:np],6) < 0)) {
pos = (1:np)[which(round(bh[1:np],6) < 0)]
face = unique(c(pos, face))
}
} else {
bh = solve(crossprod(gmat), t(gmat)) %*% zvec
edf = nrow(bigmat)
face = 1:edf
}
xtx = xtx2 = NULL
dd = t(bigmat[face, ,drop = FALSE])
xms = ones = list()
st = 1
ed = 0
for (icl in 1:ncl) {
sz = szs[icl]
ed = ed + sz
xms[[icl]] = dd[st:ed, ,drop=F]
onevec = 1:sz*0+1
onemat = onevec%*%t(onevec)
ones[[icl]] = onemat
st = ed + 1
}
muhat = t(bigmat) %*% bh
oldmu = muhat
diff = 10
nrep = 0
while (diff > 1e-7 & nrep < 10) {
nrep = nrep + 1
evec = y - muhat
ecl = f_ecl(evec, ncl, szs)
mod.lmer = NULL
if (!balanced) {
if (modlmer) {
mod.lmer = lmer(evec~-1+(1|id), REML=reml)
thhat = summary(mod.lmer)$optinfo$val^2
} else {
if (reml) {
ansi = try(ansi0<-uniroot(fth2rm, c(1e-10, 1e+3), szs=szs, ycl=ecl, N=n, xcl=xms, p=edf, type='ub', xtx=xtx, xtx2=xtx2, xmat_face=dd, ones=ones), silent=TRUE)
} else {
ansi = try(ansi0<-uniroot(fth2, c(1e-10, 1e+3), szs=szs, ycl=ecl, N=n), silent=TRUE)
}
if (class(ansi) == "try-error") {
thhat = 0
} else {
thhat = ansi$root
}
}
type = "ub"
} else {
if (modlmer) {
mod.lmer = lmer(evec~-1+(1|id), REML=reml)
thhat = summary(mod.lmer)$optinfo$val^2
} else {
if (reml) {
ansi = try(ansi0<-uniroot(fth2rm, c(1e-10, 1e+3), szs=szs, ycl=ecl, N=n, xcl=xms, p=edf, type='b', xtx=xtx, xtx2=xtx2, xmat_face=dd, ones=ones), silent=TRUE)
} else {
ansi = try(ansi0<-uniroot(fth2, c(1e-10, 1e+3), szs=szs, ycl=ecl, N=n), silent=TRUE)
}
if (class(ansi) == "try-error") {
thhat = 0
} else {
thhat = ansi$root
}
}
type = "b"
}
ytil = NULL
gtil = NULL
st = 1
ed = 0
if (balanced) {
oneMat = ones[[1]]
sz = szs[1]
} else {
sz = max(szs)
pos = which(szs == sz)[1]
oneMat = ones[[pos]]
}
vi = diag(sz) + oneMat*thhat
covi = vi
umat = t(chol(covi))
uinv = solve(umat)
uinv0 = uinv
for (icl in 1:ncl) {
sz = szs[icl]
if (!balanced) {
uinv = uinv0[1:sz, 1:sz, drop=FALSE]
}
yi = ycl[[icl]]
ytil = c(ytil, uinv %*% as.matrix(yi, ncol=1))
ed = ed + sz
gtil = rbind(gtil, uinv %*% gmat[st:ed, ,drop=F])
st = ed + 1
}
if (any(shapes != 17)) {
dsend = gtil[, (np + 1):(np + capm + capu + capt), drop = FALSE]
zsend = gtil[, 1:np, drop = FALSE]
ans = coneB(ytil, dsend, vmat = zsend, face=face)
edf = ans$df
face = ans$face
bh = coef(ans)
if (any(round(bh[1:np],6) < 0)) {
pos = (1:np)[which(round(bh[1:np],6) < 0)]
face = unique(c(pos, face))
}
} else {
bh = solve(crossprod(gtil), t(gtil)) %*% ytil
edf = nrow(bigmat)
face = 1:edf
}
muhat = t(bigmat) %*% bh
diff = mean((oldmu - muhat)^2)
oldmu = muhat
dd = t(bigmat[face, ,drop = FALSE])
dd2 = gtil[,face,drop=FALSE]
if (reml) {
xms = list()
st = 1
ed = 0
for (icl in 1:ncl) {
sz = szs[icl]
ed = ed + sz
xms[[icl]] = dd[st:ed, ,drop=F]
st = ed + 1
}
}
}
ebars = sapply(ecl, mean)
sig2hat = fsig(thhat, szs, ecl, ncl, N=n, edf=edf, D=nrow(bigmat), type=type)
siga2hat = sig2hat * thhat
ahat = ebars*szs*thhat/(1+szs*thhat)
}
onevw = NULL; zmatw = NULL; xvecw = NULL; dusew = NULL
st = 1
ed = 0
dd_nv = dd[,-c(1:np),drop=FALSE]
for (icl in 1:ncl) {
sz = szs[icl]
onevi = 1:sz*0+1
if (!balanced) {
uinv = uinv0[1:sz, 1:sz, drop=FALSE]
}
ed = ed + sz
onevw = rbind(onevw, uinv %*% onevi)
if (!is.null(xvec)) {
xvecw = rbind(xvecw, uinv %*% xvec[st:ed, ,drop=F])
}
if (capk > 0) {
zmatw = rbind(zmatw, uinv %*% zmat[st:ed, ,drop=F])
}
if (!is.null(dd_nv)) {
dusew = rbind(dusew, uinv %*% dd_nv[st:ed, ,drop=F])
}
st = ed + 1
}
df_obs = sum(abs(bh) > 0)
pv.siga2 = ranef.test(ecl, szs, n, ncl)
ci1 = NULL
ci1 = ranef.ci(ecl, szs, n, ncl, level = 0.95)
ci.siga2 = ci1
ci.th = ci.rho = ci.siga2.bi = NULL
if (bisect) {
ci2 = ranef.cith(thhat, sig2hat, siga2hat, ahat, ecl, szs, n, ncl, level = 0.95, xms=xms, p=edf, reml=reml)
ci.th = ci2$ci.th
ci.rho = ci2$ci.rho
cia = ranef.cisiga(sig2hat, siga2hat, ahat, ecl, szs, n, ncl, level = 0.95, xms=xms, p=edf, reml=reml)
ci.siga2.bi = cia$ci.siga2
}
ci.sig2 = ranef.cisig2(ecl, n, ncl, level = 0.95)
coefskeep = bh
thvecs = NULL
if (capl > 0) {
dcoefs = coefskeep[(np - capms + 1):(np + capm)]
thvecs = matrix(nrow = capl, ncol = n)
ncon = 1
for (i in 1:capl) {
thvecs[i,] = t(delta[varlist == i,]) %*% dcoefs[varlist == i]
if (shapes[i] > 2 & shapes[i] < 5 | shapes[i] > 10 & shapes[i] < 13) {
ncon = ncon + 1
thvecs[i,] = thvecs[i,] + vcoefs[capk + ncon] * xmat[,i]
}
}
}
if (length(idx_s) > 0) {
thvecs0 = thvecs
thvecs0[idx_s,] = thvecs[1:length(idx_s), ]
if (length(idx) > 0) {
thvecs0[idx,] = thvecs[(1+length(idx_s)):capl, ]
}
thvecs = thvecs0
}
thvecs_ut = NULL
if (capu + capt > 0) {
thvecs_ut = t(delta_ut) %*% coefskeep[(np + 1 + capm):(np + capm + capu + capt)]
}
if (!is.null(thvecs_ut)) {
thvecs = rbind(thvecs, t(thvecs_ut))
}
ncl = length(szs)
bhmt = matrix(rep(bh[-1], each = ncl), nrow = ncl)
coefs = cbind(ahat - bh[1], bhmt)
colnames(coefs) = c("(Intercept)", paste("edge", 1:ncol(bhmt)))
se.beta = 1:(capk + 1)*0
tstat = 1:(capk + 1)*0
pvals.beta = 1:(capk + 1)*0
zcoefs = bh[1:(1+capk)]
imat = diag(n)
pj = 0
if (ncol(dusew) >= 1) {
if (sum(shapes > 2 & shapes < 5 | shapes > 10 & shapes < 13) > 0) {
pm = cbind(xvecw , dusew)
} else {
pm = dusew
}
pj = pm %*% solve(crossprod(pm), t(pm))
}
se2 = solve(t(cbind(onevw, zmatw)) %*% (imat - pj) %*% cbind(onevw, zmatw))*sig2hat
se.beta = sqrt(as.vector(diag(se2)))
tstat = zcoefs / se.beta
if (n<=200){cpar=1.5}
if ((n - cpar * df_obs) <= 0) {
pvals.beta=2 * (1 - pt(abs(tstat), df_obs))
warning ('Effective degrees of freedom is close to the number of observations! Inference about parametric covariates is not reliable!')
} else {
pvals.beta=2 * (1 - pt(abs(tstat), n - cpar * df_obs))
}
if (capl > 0) {
xcoefs = bh[(capk + 2):np]
} else {xcoefs = NULL}
if (np > 0) {
vcoefs = bh[1:np]
} else {vcoefs = NULL}
knotsuse2 = knotsuse
numknotsuse2 = numknotsuse
mslst2 = mslst
xmat2 = xmat
if (length(idx_s) > 0) {
knotsuse0 = knotsuse
numknotsuse0 = numknotsuse
mslst0 = mslst
knotsuse0[idx_s] = knotsuse[1:length(idx_s)]
numknotsuse0[idx_s] = numknotsuse[1:length(idx_s)]
mslst0[idx_s] = mslst[1:length(idx_s)]
if (length(idx) > 0) {
knotsuse0[idx] = knotsuse[(1+length(idx_s)):capl]
numknotsuse0[idx] = numknotsuse[(1+length(idx_s)):capl]
mslst0[idx] = mslst[(1+length(idx_s)):capl]
}
knotsuse = knotsuse0
numknotsuse = numknotsuse0
mslst = mslst0
}
rslt = list(muhat = muhat, coefs = coefs, bh = bh, zcoefs = zcoefs, pvals.beta = pvals.beta, se.beta = se.beta, vcoefs = vcoefs, ahat = ahat, sig2hat = sig2hat, siga2hat = siga2hat, thhat = thhat, bigmat = bigmat, gtil=gtil, dd2=dd2, np = np, knots = knotsuse, knots2 = knotsuse2, numknots = numknotsuse, numknots2 = numknotsuse2, ms = mslst, ms2 = mslst2, xmat2 = xmat2, xid1 = xid1, xid2 = xid2, capm = capm, capms = capms, capk = capk, capt = capt, capu = capu, etacomps = thvecs, mod.lmer = mod.lmer, pv.siga2 = pv.siga2, ci.siga2 = ci.siga2, ci.siga2.bi = ci.siga2.bi, ci.th = ci.th, ci.rho = ci.rho, ci.sig2 = ci.sig2, ones = ones, resid_df_obs = n - cpar * df_obs, edf = df_obs)
return (rslt)
}
fth = function(ycl, ncl, N) {
ni = N/ncl
ybar = sapply(ycl, mean)
y = unlist(ycl)
num = ni^2*sum(ybar^2) - sum(y^2)
den = ni*sum(y^2) - ni^2*sum(ybar^2)
return (num/den)
}
fth2 = function(th, szs, ycl, N) {
ybar = sapply(ycl, mean)
y = unlist(ycl)
num = sum(szs^2*ybar^2/(1+szs*th)^2)
den = sum(y^2) - sum(th*szs^2*ybar^2/(1+szs*th))
obj = N/2*num/den - 1/2*sum(szs/(1+szs*th))
return (obj)
}
fth2rm = function(th, szs, ycl, N, xcl, p=2, type='b', xtx=NULL, xtx2=NULL, xmat_face=NULL, ones=NULL) {
ybar = sapply(ycl, mean)
y = unlist(ycl)
num = sum(szs^2*ybar^2/(1+szs*th)^2)
den = sum(y^2) - sum(th*szs^2*ybar^2/(1+szs*th))
ncl = length(ycl)
hmat = matrix(0, p, p)
xtils = list()
ones2 = list()
for(icl in 1:ncl){
ni = szs[icl]
xi = xcl[[icl]]
xm = xi
onemat = ones[[icl]]
ones2[[icl]] = onemat/(1+ni*th)^2
rinv = diag(ni) - th/(1+ni*th)*onemat
hmat = hmat + t(xm) %*% rinv %*% xm
}
lmat = chol(hmat)
hinv = chol2inv(lmat)
tr = 0
for (icl in 1:ncl) {
ni = szs[icl]
xi = xcl[[icl]]
onevec = 1:ni*0+1
xtil = t(onevec)%*%xi
tr = tr + sum(diag(hinv %*% crossprod(xtil)/(1+ni*th)^2))
}
rml = 1/2*tr
obj = (N-p)/2*num/den - 1/2*sum(szs/(1+szs*th)) + rml
return (obj)
}
fsig = function(thhat, szs, ycl, ncl, N, edf, D, type='b') {
ybars = sapply(ycl, mean)
d = min(1.5*edf, D)
if (type == 'b') {
sz = N/ncl
sig2hat = (sum(unlist(ycl)^2) - sz^2*thhat/(1+sz*thhat) * sum(ybars^2))/(N-d-1)
} else {
sig2hat = (sum(unlist(ycl)^2) - sum(thhat*szs^2*ybars^2/(1 + szs*thhat)))/(N-d-1)
}
return (sig2hat)
}
f_ecl = function(evec, ncl, sz) {
ecl = list()
st = 1
ed = 0
for (icl in 1:ncl) {
if (length(sz) > 1) {
szi = sz[icl]
} else {szi = sz}
ed = ed + szi
ecl[[icl]] = evec[st:ed]
st = ed + 1
}
return (ecl)
}
ranef.test = function(ecl, szs, N, ncl) {
evec = unlist(ecl)
ebars = sapply(ecl, mean)
sse = 0
ssb = 0
ebar = mean(evec)
for(icl in 1:ncl) {
sz = szs[icl]
eibar = ebars[[icl]]
ei = ecl[[icl]]
ssei = sum((ei - eibar)^2)
sse = sse + ssei
ssbi = sz*(eibar - ebar)^2
ssb = ssb + ssbi
}
mse = sse/(N-ncl)
msb = ssb/(ncl-1)
fstat = msb/mse
pv = 1-pf(fstat, df1=ncl-1, df2=N-ncl)
return (pv)
}
ranef.ci = function(ecl, szs, N, ncl, level = 0.95) {
evec = unlist(ecl)
ebars = sapply(ecl, mean)
sse = 0
ssb = 0
ebar = mean(evec)
for(icl in 1:ncl) {
sz = szs[icl]
eibar = ebars[[icl]]
ei = ecl[[icl]]
ssei = sum((ei - eibar)^2)
sse = sse + ssei
ssbi = sz*(eibar - ebar)^2
ssb = ssb + ssbi
}
mse = sse/(N-ncl)
msb = ssb/(ncl-1)
sz2 = 1/(ncl-1)*(N - sum(szs^2)/N)
siga2hat = (msb-mse)/sz2
dfsiga = (sz2*siga2hat)**2/(msb**2/(ncl-1)+mse**2/(N-ncl))
alpha = 1-level
lwr = dfsiga*siga2hat/qchisq(1-alpha/2, df=dfsiga)
upp = dfsiga*siga2hat/qchisq(alpha/2, df=dfsiga)
ci = c(lwr, upp)
return (ci)
}
ranef.cith = function(thhat, sig2hat, siga2hat, ahat, ecl, szs, N, ncl, level = 0.95, xms, p, reml=TRUE) {
N = sum(szs)
evec = unlist(ecl)
thval = fmin(thhat, ncl, ecl, N, xms, p, reml=reml)
ebars = sapply(ecl, mean)
ans = try(ans0<-uniroot(fn2, ncl=ncl, ycl=ecl, N=N, thval=thval, xms=xms, p=p, reml=reml, interval=c(1e-10, thhat^1), tol=.Machine$double.eps),silent=TRUE)
if (class(ans) == 'try-error') {
lwr = 0
} else {lwr = ans$root}
ans2 = try(ans20<-uniroot(fn2, ncl=ncl, ycl=ecl, N=N, thval=thval, xms=xms, p=p, reml=reml, interval=c(thhat^1, 1e+4), tol=.Machine$double.eps),silent=TRUE)
if (class(ans2) == 'try-error') {
upp = 1e+4
} else {upp = ans2$root}
ci = c(lwr, upp)
ci2 = c(lwr/(1+lwr), upp/(1+upp))
ans = list(ci.th = ci, ci.rho = ci2)
return (ans)
}
ranef.cisiga = function(sig2hat, siga2hat, ahat, ecl, szs, N, ncl, level = 0.95, xms, p, reml=TRUE) {
N = sum(szs)
evec = unlist(ecl)
thval = fmin2(siga2=siga2hat, sig2hat, ncl, ecl, N, xms, p, reml=reml)
ebars = sapply(ecl, mean)
ans = try(ans0<-uniroot(fn2a, sig2hat=sig2hat, ncl=ncl, ycl=ecl, N=N, thval=thval, xms=xms, p=p, reml=reml, interval=c(1e-10, siga2hat^1), tol=.Machine$double.eps),silent=TRUE)
if (class(ans) == 'try-error') {
lwr = 0
} else {lwr = ans$root}
ans2 = try(ans20<-uniroot(fn2a, sig2hat=sig2hat, ncl=ncl, ycl=ecl, N=N, thval=thval, xms=xms, p=p, reml=reml, interval=c(siga2hat^1, 1e+4), tol=.Machine$double.eps),silent=TRUE)
if (class(ans2) == 'try-error') {
upp = 1e+4
} else {upp = ans2$root}
ci = c(lwr, upp)
ans = list(ci.siga2 = ci)
return (ans)
}
ranef.cisig2 = function(ecl, N, ncl, level = 0.95) {
evec = unlist(ecl)
ebars = sapply(ecl, mean)
sse = 0
ebar = mean(evec)
for(icl in 1:ncl) {
eibar = ebars[[icl]]
ei = ecl[[icl]]
ssei = sum((ei - eibar)^2)
sse = sse + ssei
}
alpha = 1-level
lwr = sse/qchisq(1-alpha/2, df=N-ncl)
upp = sse/qchisq(alpha/2, df=N-ncl)
ci = c(lwr, upp)
return (ci)
}
fmin = function(theta, ncl, ycl, N, xms=NULL, p=2, reml=TRUE) {
if (reml) {
acc1 = acc2 = acc3 = 0
hmat = matrix(0, p, p)
for (i in 1:ncl) {
yi = ycl[[i]]
ni = length(yi)
one = matrix(rep(1, ni), ncol=1)
onemat = tcrossprod(one)
viinv = diag(ni) - theta / (1+ni*theta) * onemat
detvi = (1+ni*theta)
acc1 = acc1 + t(yi) %*% viinv %*% yi
acc2 = acc2 + log(detvi)
xm = xms[[i]]
rinv = diag(ni) - theta/(1+ni*theta)*onemat
hmat = hmat + t(xm) %*% rinv %*% xm
}
obj = (N-p)/2 * log(acc1) + 1/2 * acc2 + 1/2 * log(det(hmat))
} else {
acc1 = acc2 = 0
for (i in 1:ncl) {
yi = ycl[[i]]
ni = length(yi)
one = matrix(rep(1, ni), ncol=1)
onemat = tcrossprod(one)
viinv = diag(ni) - theta / (1+ni*theta) * onemat
detvi = (1+ni*theta)
acc1 = acc1 + t(yi) %*% viinv %*% yi
acc2 = acc2 + log(detvi)
}
obj = N/2 * log(acc1) + 1/2 * acc2
}
return (obj)
}
fn2 = function(x, ncl, ycl, N, thval, level=0.95, xms=NULL, p=2, reml=TRUE) {
thval2 = -thval
cts = thval2 - 1/2*qchisq(level, df=1)
obj = -fmin(x, ncl, ycl, N, xms, p, reml) - cts[1]
return (obj)
}
fmin2 = function(siga2, sig2hat, ncl, ycl, N, xms=NULL, p=2, reml=TRUE) {
if (reml) {
acc1 = acc2 = acc3 = 0
hmat = matrix(0, p, p)
for (i in 1:ncl) {
yi = ycl[[i]]
ni = length(yi)
one = matrix(rep(1, ni), ncol=1)
onemat = tcrossprod(one)
viinv = diag(ni) - siga2 / (sig2hat+ni*siga2) * onemat
detvi = (1+ni*siga2/sig2hat)
acc1 = acc1 + t(yi) %*% viinv %*% yi
acc2 = acc2 + log(detvi)
xm = xms[[i]]
rinv = diag(ni) - siga2/(sig2hat+ni*siga2)*onemat
hmat = hmat + t(xm) %*% rinv %*% xm
}
obj = (N-p)/2 * log(acc1) + 1/2 * acc2 + 1/2 * log(det(hmat))
} else {
acc1 = acc2 = 0
for (i in 1:ncl) {
yi = ycl[[i]]
ni = length(yi)
one = matrix(rep(1, ni), ncol=1)
onemat = tcrossprod(one)
viinv = diag(ni) - siga2 / (sig2hat+ni*siga2) * onemat
detvi = (1+ni*siga2/sig2hat)
acc1 = acc1 + t(yi) %*% viinv %*% yi
acc2 = acc2 + log(detvi)
}
obj = N/2 * log(acc1) + 1/2 * acc2
}
return (obj)
}
fn2a = function(siga2, sig2hat, ncl, ycl, N, thval, level=0.95, xms=NULL, p=2, reml=TRUE) {
thval2 = -thval
cts = thval2 - 1/2*qchisq(level, df=1)
obj = -fmin2(siga2, sig2hat, ncl, ycl, N, xms, p, reml) - cts[1]
return (obj)
}
coef.cgamm <- function(object,...) {
ans <- object$coefs
ans
}
ranef.cgamm <- function(object,...) {
ans <- object$ahat
ans
}
fixef.cgamm <- function(object,...) {
ans <- object$bh
ans
}
predict.cgamm = function(object, newData, interval = c("none", "confidence", "prediction"), type = c("response", "link"), level = 0.95, n.mix = 500, var.f = NULL,...) {
family = object$family
cicfamily = CicFamily(family)
muhat.fun = cicfamily$muhat.fun
if (!inherits(object, "cgamm")) {
warning("calling predict.cgamm(<fake-cgam-object>) ...")
}
if (missing(newData) || is.null(newData)) {
muhat = object$muhat
ahat = object$ahat
ans = list(fix_effect = muhat, random_effect = ahat)
return (ans)
}
if (!is.data.frame(newData)) {
stop ("newData must be a data frame!")
}
prior.w = object$prior.w
y = object$y
muhat = object$muhat
shapes = object$shapes
np = object$d0; capm = object$capm; capk = object$capk; capt = object$capt; capu = object$capu
xid10 = object$xid1; xid20 = object$xid2;
xmat0 = object$xmat0; knots0 = object$knots0; numknots0 = object$numknots0; sps0 = object$sps0; ms0 = object$ms0
zmat = object$zmat; umb = object$umb; tr = object$tr
ztb = object$ztb; zid1 = object$zid1; zid2 = object$zid2; iz = 1
bigmat = object$bigmat; umbrella.delta = object$umbrella.delta; tree.delta = object$tree.delta
coefs = object$bh; zcoefs = object$zcoefs; vcoefs = object$vcoefs; xcoefs0 = object$xcoefs; ucoefs = object$ucoefs; tcoefs = object$tcoefs
tt = object$tms
Terms = delete.response(tt)
lbs = attributes(object$tms)$term.labels
idlb = rev(lbs)[1]
group = object$id
if (!any(names(newData) %in% lbs)){
newData[[idlb]] = rep(1, nrow(newData))
m = model.frame(Terms, newData)
group_new = NULL
if (interval == "prediction") {
stop ("Group information is missing for the newData!")
}
} else {
m = model.frame(Terms, newData)
nmsm = names(m)
group_new = m[,which(nmsm%in%idlb)]
}
nmsm = names(m)
rm_id = which(nmsm%in%idlb)
newdata = m[, -rm_id, drop=F]
newx0 = NULL; newxv = NULL; newx = NULL; newx_s = NULL; newu = NULL; newt = NULL; newz = NULL; newv = NULL
rn = nrow(newdata)
newetahat = 0; newmuhat = 0
newxbasis = NULL; newx_sbasis = NULL; newubasis = NULL; newtbasis = NULL; newbigmat = NULL
my_line = function(xp = NULL, y, x, end, start) {
slope = NULL
intercept = NULL
yp = NULL
slope = (y[end] - y[start]) / (x[end] - x[start])
intercept = y[end] - slope * x[end]
yp = intercept + slope * xp
ans = new.env()
ans$slope = slope
ans$intercept = intercept
ans$yp = yp
ans
}
for (i in 1:ncol(newdata)) {
if (is.null(attributes(newdata[,i])$shape)) {
if (is.factor(newdata[,i])) {
lvli = levels(newdata[,i])
ztbi = levels(ztb[[iz]])
newdatai = NULL
if (!any(lvli %in% ztbi)) {
stop ("new factor level must be among factor levels in the fit!")
} else {
id1 = which(ztbi %in% lvli)
klvls = length(ztbi)
if (klvls > 1) {
newimat = matrix(0, nrow = rn, ncol = klvls-1)
for (i1 in 1:rn) {
if (newdata[i1,i] != ztbi[1]) {
id_col = which(ztbi %in% newdata[i1,i]) - 1
newimat[i1,id_col] = 1
}
}
newdatai = newimat
}
}
} else {
newdatai = newdata[,i]
}
newz = cbind(newz, newdatai)
iz = iz + 1
}
if (is.numeric(attributes(newdata[,i])$shape)) {
newx0 = cbind(newx0, newdata[,i])
if ((attributes(newdata[,i])$shape > 2 & attributes(newdata[,i])$shape < 5) | (attributes(newdata[,i])$shape > 10 & attributes(newdata[,i])$shape < 13)) {
newxv = cbind(newxv, newdata[,i])
}
}
if (is.character(attributes(newdata[,i])$shape)) {
if (attributes(newdata[,i])$shape == "tree") {
newt = cbind(newt, newdata[,i])
}
if (attributes(newdata[,i])$shape == "umbrella") {
newu = cbind(newu, newdata[,i])
}
}
}
if (!is.null(shapes)) {
if (any(shapes == 17)) {
kshapes <- length(shapes)
obs <- 1:kshapes
idx_s <- obs[which(shapes == 17)]; idx <- obs[which(shapes != 17)]
newx1 <- newx0
shapes0 <- 1:kshapes*0
newx1[,1:length(idx_s)] <- newx0[,idx_s]
shapes0[1:length(idx_s)] <- shapes[idx_s]
if (length(idx) > 0) {
newx1[,(1 + length(idx_s)):kshapes] <- newx0[,idx]
shapes0[(1 + length(idx_s)):kshapes] <- shapes[idx]
}
newx0 <- newx1; shapes <- shapes0
}
xmat = xmat_s = NULL
newx = newx_s = NULL
knots = NULL
ms_x = ms = NULL
sh_x = sh = NULL
if (all(shapes < 9)) {
newx = newx0
xid1 = xid10; xid2 = xid20
xmat = xmat0
sh_x = shapes
ms_x = ms0
} else if (all(shapes > 8)) {
newx_s = newx0
xid1_s = xid10; xid2_s = xid20
xmat_s = xmat0
numknots = numknots0
knots = knots0
sps = sps0
sh = shapes
ms = ms0
} else if (any(shapes > 8) & any(shapes < 9)) {
newx = newx0[, shapes < 9, drop = FALSE]
xmat = xmat0[, shapes < 9, drop = FALSE]
sh_x = shapes[shapes < 9]
ms_x = ms0[shapes < 9]
xid1 = xid10[shapes < 9]; xid2 = xid20[shapes < 9]
newx_s = newx0[, shapes > 8, drop = FALSE]
xmat_s = xmat0[, shapes > 8, drop = FALSE]
sh = shapes[shapes > 8]
ms = ms0[shapes > 8]
xid1_s = xid10[shapes > 8]; xid2_s = xid20[shapes > 8]
numknots = numknots0[shapes > 8]
knots = knots0[shapes > 8]
sps = sps0[shapes > 8]
}
}
if (!is.null(shapes)) {
vcoefs = vcoefs[1:(1 + capk + sum(shapes > 2 & shapes < 5 | shapes > 10 & shapes < 13))]
} else {vcoefs = vcoefs[1:(1 + capk)]}
if (capk > 0) {
vcoefs_nz = vcoefs[-c(2:(1 + capk))]
} else {vcoefs_nz = vcoefs}
newv = cbind(1:rn*0 + 1, newz, newxv)
newv_nz = cbind(1:rn*0 + 1, newxv)
n = ncol(bigmat)
nc = ncol(xmat0)
spl = splpr = NULL
m_acc = 0
object$ms0 -> ms0
object$shapes -> shapes
for (i in 1:nc) {
msi = ms0[[i]]
shpi = shapes[i]
ki = knots0[[i]]
xi = xmat0[,i]
xipr = newx0[,i]
if (any(xipr > max(xi)) | any(xipr < min(xi))) {
stop ("No extrapolation is allowed in cgamm prediction!")
}
deli = makedelta(xi, shpi, knots = ki)
spli = deli$amat
if (shpi >= 9) {
dpri = makedelta(xipr, shpi, knots = ki, suppre = TRUE, interp = TRUE)
splpri = dpri$amat
if (shpi > 10 & shpi < 13) {
xs = sort(xi)
ord = order(xi)
obs = 1:n
nr = nrow(splpri)
ms2 = matrix(0, nrow = nr, ncol = rn)
for (i1 in 1:rn) {
for (i2 in 1:nr) {
ms2[i2, i1] = my_line(xp = xipr[i1], y = msi[i2, ][ord], x = xs, end = n, start = 1)$yp
}
}
splpri = splpri - ms2
} else {
splpri = splpri - msi
}
} else {splpri = pred_del(xi, shpi, xipr, msi)}
mi = dim(spli)[1]
m_acc = m_acc + mi
spl = rbind(spl, spli)
splpr = rbind(splpr, splpri)
}
xmatpr = cbind(newv, t(splpr))
muhatpr = xmatpr %*% coefs[1:ncol(xmatpr), ,drop=FALSE]
if ("none" %in% interval) {
ans = list(fit = muhatpr)
} else if (interval == "confidence" | interval == "prediction") {
ones = object$ones
capk = object$capk
p = 1 + capk + sum(shapes > 2 & shapes < 5 | shapes > 10 & shapes < 13)
if (family$family == "gaussian") {
sig2hat = object$sig2hat
siga2hat = object$siga2hat
thhat = object$thhat
szs = object$szs
ahat = object$ahat
muhat = object$muhat
balanced = FALSE
if (length(unique(szs)) == 1) {
balanced = TRUE
}
ncl = length(szs)
edges = t(bigmat)
nd = ncol(edges)
if (is.null(var.f)) {
face = NULL
nloop = n.mix
nsec = 2^m_acc
if (balanced) {
oneMat = ones[[1]]
sz = szs[1]
} else {
sz = max(szs)
pos = which(szs == sz)[1]
oneMat = ones[[pos]]
}
wi = 1*(diag(sz) + thhat*oneMat)
covi = wi
umat = t(chol(covi))
uinv0 = uinv = solve(umat)
if (round(thhat,6) != 0) {
sector = NULL
times = NULL
df = NULL
for(iloop in 1:nloop){
ysim = NULL
etil = NULL
st = 1
ed = 0
for (icl in 1:ncl) {
sz = szs[icl]
ed = ed + sz
mui = muhat[st:ed]
if (!balanced) {
uinv = uinv0[1:sz, 1:sz, drop=FALSE]
}
ysi = uinv %*% (rnorm(1, sd = siga2hat^.5) + as.matrix(mui, ncol=1) + rnorm(sz, sd=sig2hat^.5))
ysim = c(ysim, ysi)
emati = edges[st:ed, ,drop=F]
etil = rbind(etil, uinv %*% emati)
st = ed + 1
}
dsend = etil[, -(1:np)]
zsend = etil[, 1:np]
ans = coneB(ysim, dsend, vmat = zsend, face = NULL)
cf = round(ans$coefs[(np+1):(m_acc+np)],10)
sec = 1:m_acc*0
sec[cf > 0] = 1
sector = rbind(sector, sec)
r = makebin(sec) + 1
if (iloop == 1) {
df = rbind(df, c(r, 1))
} else {
if (r %in% df[,1]) {
ps = which(df[,1] %in% r)
df[ps,2] = df[ps,2] + 1
} else {
df = rbind(df, c(r, 1))
}
}
}
sm_id = which((df[,2]/nloop) < 1e-3)
if (any(sm_id)) {
df = df[-sm_id, ,drop=FALSE]
}
} else {
prior.w = 1:n*0 + 1
sector = NULL
times = NULL
df = NULL
for (iloop in 1:nloop) {
ysim = muhat + rnorm(n)*sig2hat^.5
ysim = ysim * sqrt(prior.w)
dsend = edges[, (np+1):(m_acc+np)]
zsend = edges[, 1:np]
ans = coneB(ysim, dsend, zsend, face = NULL)
cf = round(ans$coefs[(np+1):(m_acc+np)], 10)
sec = 1:m_acc*0
sec[cf > 0] = 1
sector = rbind(sector, sec)
r = makebin(sec) + 1
if (iloop == 1) {
df = rbind(df, c(r, 1))
} else {
if (r %in% df[,1]) {
ps = which(df[,1] %in% r)
df[ps,2] = df[ps,2] + 1
} else {
df = rbind(df, c(r, 1))
}
}
}
sm_id = which((df[,2]/nloop) < 1e-3)
if (any(sm_id)) {
df = df[-sm_id, ,drop=FALSE]
}
}
ns = nrow(df)
bsec = df
bsec[,2] = bsec[,2] / sum(bsec[,2])
ord = order(bsec[,1])
bsec = bsec[ord,,drop=FALSE]
nv = np
zmat = zsend
spl = t(dsend)
obs = 1:m_acc;oobs = 1:(m_acc+nv)
acov = matrix(0, nrow = m_acc+nv, ncol = m_acc+nv)
for (is in 1:ns) {
if (bsec[is,2] > 0) {
jvec = getbin(bsec[is,1], m_acc)
if (sum(jvec) == 1) {
smat = cbind(zmat, t(spl[which(jvec==1),,drop=F]))
} else if (sum(jvec) == 0) {
smat = zmat
} else {
smat = cbind(zmat, t(spl[which(jvec==1),,drop=F]))
}
acov1 = bsec[is,2]*solve(t(smat)%*%smat)
acov2 = matrix(0,nrow=m_acc+nv,ncol=m_acc+nv)
jobs = 1:(m_acc+nv)>0
jm = 1:m_acc>0
jm[obs[jvec==0]] = FALSE
jobs[(nv+1):(m_acc+nv)] = jm
nobs = oobs[jobs==TRUE]
for (i in 1:sum(jobs)) {
acov2[nobs[i],jobs] = acov1[i,]
}
acov = acov+acov2
}
}
acov = acov*sig2hat
}
mult = qnorm((1 - level)/2, lower.tail=FALSE)
if (interval == "confidence") {
if (is.null(var.f)) {
var.f = diag(xmatpr%*%acov%*%t(xmatpr))
}
hl = mult*sqrt(var.f)
}
if (interval == "prediction") {
bh = object$bh
dd = t(bigmat[abs(bh)>0, ,drop=FALSE])
nnew = nrow(xmatpr)
vp1 = rep(sig2hat, nnew)
if (is.null(var.f)){
var.f = diag(xmatpr%*%acov%*%t(xmatpr))
}
vp2 = var.f
imat2 = diag(ncl)
gm = siga2hat*imat2
rinvlst = ones = list()
if (balanced) {
pos = 1
} else {
pos = min(which(szs == max(szs)))
}
n1=szs[pos]
one1=rep(1,n1)
onem1=tcrossprod(one1)
im1=diag(n1)
rinv1=im1-thhat/(1+n1*thhat)*onem1
rinv0=rinv1
for(i in 1:ncl){
if (balanced) {
rinvlst[[i]] = rinv1
ones[[i]] = one1
} else {
ni = szs[i]
onevec = rep(1, ni)
onemat = onem1[1:ni,1:ni]
imatn = im1[1:ni,1:ni]
rinv = imatn-thhat/(1+ni*thhat)*onemat
rinvlst[[i]] = rinv
ones[[i]] = onevec
}
}
rinv = as.matrix(bdiag(rinvlst))
onem = as.matrix(bdiag(ones))
mult1 = t(dd)%*%rinv
pw = dd%*%solve(mult1%*%dd)%*%mult1
vp30 = gm-siga2hat*thhat*t(onem)%*%rinv%*%(diag(n)-pw)%*%onem
vp3 = diag(vp30)
lwr = upp = fitpr = var.pred = rep(0, nnew)
ugr = unique(group)
ugr_new = unique(group_new)
ncl_new = length(ugr_new)
for(i in 1:ncl_new){
gri = ugr_new[i]
gr_id = which(group_new%in%gri)
szi = length(gr_id)
oneveci = matrix(rep(1, szi), ncol=1)
evi = matrix(rep(0, ncl), nrow=1);evi[i]=1
face = which(abs(bh)>0)
pwpr = (xmatpr[gr_id, face])%*%solve(mult1%*%dd)%*%mult1
vp40 = -siga2hat*pwpr%*%onem
vp4i = diag(vp40%*%t(evi)%*%t(oneveci))
pos_cl = which(ugr%in%gri)
var.predi = rep(sig2hat, szi) + vp2[gr_id] + rep(vp3[pos_cl], szi) + 2*vp4i
var.pred[gr_id] = var.predi
lwr[gr_id] = muhatpr[gr_id] + ahat[pos_cl] - mult*sqrt(var.predi)
upp[gr_id] = muhatpr[gr_id] + ahat[pos_cl] + mult*sqrt(var.predi)
fitpr[gr_id] = muhatpr[gr_id] + ahat[pos_cl]
}
}
if (interval == "confidence") {
ans = list(fit = muhatpr, lower = muhatpr - hl, upper = muhatpr + hl, var.f=var.f)
}
if (interval == "prediction") {
ans = list(fit = fitpr, lower = lwr, upper = upp, var.f=var.f, var.pred=var.pred)
}
}
}
class(ans) = "cgamp"
return (ans)
}
makebin = function(x){
k = length(x)
r = 0
for(i in 1:k){r = r + x[k-i+1]*2^(i-1)}
r
}
getvars = function(num){
i = num
digits = 0
power = 0
while(digits == 0){
if(i<2^power){digits = power}
power = power+1
}
binry = 1:digits*0
if(num>0){binry[1] = 1}
i = i-2^(digits-1)
power = digits-2
for(p in power:0){
if(i >= 2^p){
i = i-2^p
binry[digits-p] = 1
}
}
binry
}
getbin = function(num, capl){
br = getvars(num-1)
digits = length(br)
binrep = 1:capl*0
binrep[(capl-digits+1):capl] = br
binrep
}
pred_del = function(x, sh, xp, ms) {
n = length(xp)
xu = sort(unique(x))
n1 = length(xu)
sigma = NULL
my_line = function(xp = NULL, y, x, end, start) {
slope = NULL
intercept = NULL
yp = NULL
slope = (y[end] - y[start]) / (x[end] - x[start])
intercept = y[end] - slope * x[end]
yp = intercept + slope * xp
ans = new.env()
ans$slope = slope
ans$intercept = intercept
ans$yp = yp
ans
}
if (sh < 3) {
sigma = matrix(0, nrow = n1 - 1, ncol = n)
for (i in 1: (n1 - 1)) {
sigma[i, xp > xu[i]] = 1
}
if (sh == 2) {sigma = -sigma}
for (i in 1:(n1 - 1)) {sigma[i, ] = sigma[i, ] - ms[i]}
}
if (sh == 3 | sh == 4) {
sigma = matrix(0, nrow = n1 - 2, ncol = n)
for (i in 1: (n1 - 2)) {
sigma[i, xp > xu[i+1]] = xp[xp > xu[i+1]] - xu[i+1]
}
if (sh == 4) {sigma = -sigma}
xs = sort(x)
ord = order(x)
nx = length(x)
obs = 1:nx
m = nrow(ms)
ms0 = matrix(0, nrow = m, ncol = n)
for (i1 in 1:n) {
for (i2 in 1:m) {
ms0[i2, i1] = my_line(xp = xp[i1], y = ms[i2, ][ord], x = xs, end = nx, start = 1)$yp
}
}
sigma = sigma - ms0
}
if (sh > 4 & sh < 9) {
sigma = matrix(0, nrow = n1 - 1, ncol = n)
if (sh == 5) {
for (i in 1:(n1 - 1)) {
sigma[i, xp > xu[i]] = (xp[xp > xu[i]] - xu[i]) / (max(x) - xu[i])
}
for (i in 1:(n1 - 1)) {sigma[i,] = sigma[i,] - ms[i]}
} else if (sh == 6) {
for (i in 1:(n1 - 1)) {
sigma[i, xp < xu[i + 1]] = (xp[xp < xu[i + 1]] - xu[i + 1]) / (min(x) - xu[i + 1])
}
for (i in 1:(n1 - 1)) {sigma[i,] = sigma[i,] - ms[i]}
} else if (sh == 7) {
for (i in 1:(n1 - 1)) {
sigma[i, xp < xu[i + 1]] = (xp[xp < xu[i + 1]] - xu[i + 1]) / (min(x) - xu[i + 1])
}
for (i in 1:(n1 - 1)) {sigma[i,] = -sigma[i,] + ms[i]}
} else if (sh == 8) {
for (i in 1:(n1 - 1)) {
sigma[i, xp > xu[i]] = (xp[xp > xu[i]] - xu[i]) / (max(x) - xu[i])
}
for (i in 1:(n1 - 1)) {sigma[i,] = -sigma[i,] + ms[i]}
}
}
return (sigma)
}
summary.cgamm <- function(object,...) {
if (!is.null(object$zcoefs)) {
family <- object$family
resid_df_obs <- object$resid_df_obs
coefs <- object$zcoefs
se <- object$se.beta
tval <- coefs / se
pvalbeta <- object$pvals.beta
n <- length(coefs)
zid <- object$zid
zid1 <- object$zid1
zid2 <- object$zid2
tms <- object$tms
is_param <- object$is_param
is_fac <- object$is_fac
vals <- object$vals
rslt1 <- data.frame("Estimate" = round(coefs, 4), "StdErr" = round(se, 4), "t.value" = round(tval, 4), "p.value" = round(pvalbeta, 4))
rownames(rslt1)[1] <- "(Intercept)"
if (n > 1) {
lzid <- length(zid1)
for (i in 1:lzid) {
pos1 <- zid1[i]; pos2 <- zid2[i];
for (j in pos1:pos2) {
if (!is_param[i]) {
rownames(rslt1)[j + 1] <- paste(attributes(tms)$term.labels[zid[i] - 1], rownames(rslt1)[j + 1], sep = "")
} else {
rownames(rslt1)[j + 1] <- paste(attributes(tms)$term.labels[zid[i] - 1], vals[j], sep = "")
}
}
}
}
rslt1 <- as.matrix(rslt1)
ans <- list(call = object$call, coefficients = rslt1, zcoefs = coefs, resid_df_obs = resid_df_obs, family = family)
class(ans) <- "summary.cgamm"
ans
} else {
ans <- list(zcoefs = object$zcoefs)
class(ans) <- "summary.cgamm"
ans
}
}
print.summary.cgamm <- function(x,...) {
if (!is.null(x$zcoefs)) {
cat("Call:\n")
print(x$call)
cat("\n")
cat("Coefficients:")
cat("\n")
printCoefmat(x$coefficients, P.values = TRUE, has.Pvalue = TRUE)
} else {
print ("No linear predictor is defined")
}
}
plotpersp <- function(object,...) {
UseMethod("plotpersp", object)
}
plotpersp.cgamp = function(object, x1=NULL, x2=NULL, x1nm=NULL, x2nm=NULL, data=NULL, up = TRUE, main=NULL, cex.main=.8, xlab = NULL, ylab = NULL, zlab = NULL, zlim = NULL, th = NULL, ltheta = NULL, ticktype = "detailed",...) {
if (!inherits(object, "cgamp")) {
warning("calling plotpersp(<fake-cgam-prediction-object>) ...")
}
t_col = function(color, percent = 50, name = NULL) {
rgb.val <- col2rgb(color)
t.col <- rgb(rgb.val[1], rgb.val[2], rgb.val[3],
maxColorValue = 255,
alpha = (100-percent)*255/100,
names = name)
invisible(t.col)
}
if (up) {
mycol = t_col("green", perc = 90, name = "lt.green")
} else {
mycol = t_col("pink", perc = 80, name = "lt.pink")
}
acov = object$acov
mult = object$mult
obj = object$object
xnms = obj$xnms_add
xmat = obj$xmat_add
bigmat = obj$bigmat
if (is.null(x1nm) | is.null(x2nm)) {
if (length(xnms) >= 2) {
x1nm = xnms[1]
x2nm = xnms[2]
x1id = 1
x2id = 2
x1 = xmat[, 1]
x2 = xmat[, 2]
} else {stop ("Number of non-parametric predictors must >= 2!")}
}
ynm = obj$ynm
kts = obj$knots
np = obj$d0
knms = length(xnms)
obs = 1:knms
if (!is.null(data)) {
if (!is.data.frame(data)) {
stop ("User need to make the data argument a data frame with names for each variable!")
}
datnms <- names(data)
if (!any(datnms == x1nm) | !any(datnms == x2nm)) {
stop ("Check the accuracy of the names of x1 and x2!")
}
x1 <- data[ ,which(datnms == x1nm)]
x2 <- data[ ,which(datnms == x2nm)]
if (length(x1) != nrow(xmat)) {
warning ("Number of observations in the data set is not the same as the number of elements in x1!")
}
x1id <- obs[xnms == x1nm]
if (length(x2) != nrow(xmat)) {
warning ("Number of observations in the data set is not the same as the number of elements in x2!")
}
x2id <- obs[xnms == x2nm]
} else {
if (all(xnms != x1nm)) {
if (length(x1) != nrow(xmat)) {
stop ("Number of observations in the data set is not the same as the number of elements in x1!")
}
bool <- apply(xmat, 2, function(x) all(x1 == x))
if (any(bool)) {
x1id <- obs[bool]
x1nm <- xnms[bool]
} else {
stop (paste(paste("'", x1nm, "'", sep = ''), "is not a predictor defined in the cgam fit!"))
}
} else {
x1id <- obs[xnms == x1nm]
}
if (all(xnms != x2nm)) {
if (length(x2) != nrow(xmat)) {
stop ("Number of observations in the data set is not the same as the number of elements in x2!")
}
bool <- apply(xmat, 2, function(x) all(x2 == x))
if (any(bool)) {
x2id <- obs[bool]
x2nm <- xnms[bool]
} else {
stop (paste(paste("'", x2nm, "'", sep = ''), "is not a predictor defined in the cgam fit!"))
}
} else {
x2id <- obs[xnms == x2nm]
}
}
xm0 = object$newx0
xm = xm0[,c(x1id,x2id)]
thvs_upp = object$thvs_upp
thvs_lwr = object$thvs_lwr
mins = min(thvs_lwr)+obj$coefs[1]
maxs = max(thvs_upp)+obj$coefs[1]
if (is.null(zlim)) {
zlim = c(mins-(maxs-mins)/2.2, maxs+(maxs-mins)/2.2)
}
res = plotpersp.cgam(obj, x1=x1, x2=x2, x1nm=x1nm, x2nm=x2nm, zlim=zlim, col='white', xlab=xlab, ylab=ylab, zlab=zlab, th=th, ltheta=ltheta, ticktype=ticktype)
ngrid = res$ngrid
x_grid = ngrid
y_grid = ngrid
x1g = 0:x_grid / x_grid * .95 * (max(xm[,1]) - min(xm[,1])) + min(xm[,1]) + .025 * (max(xm[,1]) - min(xm[,1]))
n1 = length(x1g)
x2g = 0:y_grid / y_grid * .95 * (max(xm[,2]) - min(xm[,2])) + min(xm[,2]) + .025 * (max(xm[,2]) - min(xm[,2]))
n2 = length(x2g)
xgmat = matrix(nrow = n1, ncol = n2)
eta0 = obj$coefs[1]
if (up) {
thvecs = thvs_upp
} else {
thvecs = thvs_lwr
}
for (i2 in 1:n2) {
for (i1 in 1:n1) {
x1a = max(xm[xm[,1] <= x1g[i1], 1])
x1b = min(xm[xm[,1] > x1g[i1], 1])
v1a = min(thvecs[x1id, xm[,1] == x1a])
v1b = min(thvecs[x1id, xm[,1] == x1b])
alp = (x1g[i1] - x1a) / (x1b - x1a)
th1add = (1 - alp) * v1a + alp * v1b
x2a = max(xm[xm[,2] <= x2g[i2],2])
x2b =min(xm[xm[,2] > x2g[i2],2])
v2a = min(thvecs[x2id, xm[,2] == x2a])
v2b = min(thvecs[x2id, xm[,2] == x2b])
alp = (x2g[i2] - x2a) / (x2b - x2a)
th2add = (1 - alp) * v2a + alp * v2b
xgmat[i1,i2] = eta0 + th1add + th2add
}
}
z_add = res$z_add
x3_add = res$x3_add
xgmat = xgmat + z_add + x3_add
fml = obj$family$family
if (up) {
if (is.null(main)) {
main = "Cgam Surface with Upper 95% Confidence Surface"
}
}
if (!up) {
if (is.null(main)) {
main = "Cgam Surface with Lower 95% Confidence Surface"
}
}
par(new = TRUE)
persp(x1g, x2g, xgmat, zlim = res$zlim, xlab = "", ylab = "", zlab = "", theta = res$theta, ltheta = res$ltheta, cex.axis = res$cex.axis, main = main, cex.main = cex.main, ticktype = res$ticktype, col=mycol, box=FALSE, axes=FALSE)
par(new=FALSE)
} |
library(testthat)
context("PCMParam")
library(PCMBase)
if(PCMBaseIsADevRelease()) {
list2env(PCMBaseTestObjects, globalenv())
set.seed(1, kind = "Mersenne-Twister", normal.kind = "Inversion")
k <- PCMNumTraits(model.ab.123)
R <- PCMNumRegimes(model.ab.123)
randVecs1 <- PCMParamRandomVecParams(o = model.ab.123, k = k, R = R, n = 10)
test_that("randVecs1 is 10-row matrix",
expect_true(is.matrix(randVecs1) && nrow(randVecs1) == 10L))
randVecs2 <- PCMParamRandomVecParams(
o = model.ab.123, k = k, R = R, n = 10)
test_that("randVecs2 is 10-row matrix",
expect_true(is.matrix(randVecs2) && nrow(randVecs2) == 10L))
randVecs3 <- PCMParamRandomVecParams(
o = model.ab.123, k = k, R = R, n = 10)
test_that("randVecs3 is 10-row matrix",
expect_true(is.matrix(randVecs3) && nrow(randVecs3) == 10L))
randVecs4 <- PCMParamRandomVecParams(
o = model.ab.123, k = k, R = R, n = 1)
test_that("randVecs4 is 1-row matrix", {
expect_true(is.matrix(randVecs4))
expect_equal(nrow(randVecs4), 1L)
})
randVecs5 <- PCMParamRandomVecParams(
o = model.ab.123, k = k, R = R, n = 0)
test_that("randVecs5 is 0-row matrix", {
expect_true(is.matrix(randVecs5))
expect_equal(nrow(randVecs5), 0L)
})
} |
prodlimMulti <- function(response,size.strata,N,NU,cotype,force.multistate){
is.event <- response[,"status"]!=0
if (force.multistate==TRUE){
to <- response[,"status"]
from <- rep(0,length(to))
}
else{
to <- response[,"event"]
from <- response[,"from"]
}
state.names <- unique(c(from, to[response[,"status"]!=0]))
ns <- length(state.names)
cens <- FALSE
if(length(to[is.event])>0) cens <- TRUE
from <- as.integer(factor(from,levels=state.names)) - 1
from <- as.numeric(from)
to[is.event] <- as.integer(factor(to[is.event], levels=state.names)) - 1
to[!is.event] <- ns
to <- as.numeric(to)
states <- sort(unique(c(from, to[is.event])))
tra <- unique(cbind(from[is.event], to[is.event]))
sorted <- order(tra[,1],tra[,2])
tra <- matrix(tra[sorted,], ncol=2)
tra <- cbind(0:(length(tra[,1])-1),tra)
colnames(tra) <- c("row","from", "to")
ntra <- nrow(tra)
trow <- match(paste(from,to), paste(tra[,"from"],tra[,"to"]), nomatch=0) - 1
cens.in <- sort(unique(from[!is.event]))
nci <- length(cens.in)
cpos <- match(paste(from,to), paste(cens.in, ns), nomatch = 0) - 1
if( cotype > 1 ) {
nr.start <- size.strata
}
else{nr.start <- length(from[from==0])}
fit <- .C("prodlim_multistates",
as.integer(N),
as.integer(ns),
as.integer(length(is.event)),
as.integer(size.strata),
as.integer(ntra),
as.integer(tra[,"from"]),
as.integer(tra[,"to"]),
as.integer(trow),
as.integer(nci),
as.integer(cens.in),
as.integer(cpos),
as.double(response[,"time"]),
as.integer(response[,"status"]),
as.integer(nr.start),
time=double(N),
hazard=double(N*ns*ns),
prob=double(N*ns*ns),
nevent=integer(N*ns*ns),
ncens=integer(N*ns),
nrisk=integer(N*ns),
first.strata=integer(NU),
ntimes.strata=integer(NU),
PACKAGE="prodlim")
tra[,"from"] <- state.names[tra[,"from"]+1]
tra[,"to"] <- state.names[tra[,"to"]+1]
cens.in <- state.names[cens.in+1]
NT <- sum(fit$ntimes.strata)
res <- list("time"=fit$time[1:NT],"hazard"=fit$hazard[1:(NT*ns*ns)],"prob"=fit$prob[1:(NT*ns*ns)],"nevent"=fit$nevent[1:(NT*ns*ns)],"ncens"=fit$ncens[1:(NT*ns)],"nrisk"=nrisk <- fit$nrisk[1:(NT*ns)],"first.strata"=fit$first.strata,"size.strata"=fit$ntimes.strata,"uniquetrans"=tra,"cens.in"=cens.in,"states"=states,"state.names"=state.names,"model"="multi.states")
res
} |
test_that("Coefficient digits work correctly", {
model_simple <- lm(mpg ~ cyl + disp, data = mtcars)
expect_snapshot_output(
extract_eq(model_simple, use_coefs = TRUE, coef_digits = 4)
)
expect_snapshot_output(
extract_eq(model_simple, use_coefs = TRUE, fix_signs = FALSE)
)
})
test_that("Wrapping works correctly", {
model_big <- lm(mpg ~ ., data = mtcars)
expect_snapshot_output(
extract_eq(model_big, wrap = TRUE, terms_per_line = 4)
)
expect_snapshot_output(
extract_eq(model_big, wrap = TRUE, terms_per_line = 2)
)
tex_end <- capture.output(extract_eq(model_big,
wrap = TRUE,
operator_location = "end"
))
expect_match(tex_end[3], "\\+ \\\\\\\\$",
label = "wrapped equation line ends with +"
)
expect_match(tex_end[4], "\\+ \\\\\\\\$",
label = "other wrapped equation line ends with +"
)
tex_start <- capture.output(extract_eq(model_big,
wrap = TRUE,
operator_location = "start"
))
expect_match(tex_start[3], "\\)\\\\\\\\$",
label = "wrapped equation line doesn't end with +"
)
expect_match(tex_start[4], "&\\\\quad \\+ ",
label = "wrapped equation line starts with +"
)
expect_match(tex_start[5], "&\\\\quad \\+ ",
label = "other wrapped equation line starts with +"
)
tex_align <- capture.output(extract_eq(model_big,
wrap = TRUE,
align_env = "align"
))
expect_equal(tex_align[2], "\\begin{align}",
label = "different align environment used"
)
}) |
context("test-ls_fun_args")
test_that("extract function args", {
args <- ls_fun_args(quote(library(tidycode)))
expect_equal(unlist(args), list(quote(tidycode)))
args <- ls_fun_args(quote(lm(mpg ~ cyl, mtcars)))
expect_equal(args[[1]], list(quote(mpg ~ cyl), quote(mtcars)))
expect_equal(args[[2]], list(quote(mpg), quote(cyl)))
}) |
NULL
setGeneric("oracle", function(catObj, theta, responses, approx = FALSE, parallel = FALSE) standardGeneric("oracle"))
setMethod(f = "oracle", signature = "Cat", definition = function(catObj, theta, responses, approx = FALSE, parallel = FALSE){
n <- catObj@lengthThreshold
if(length(theta) != nrow(responses)){
stop("Need a corresponding theta value for each answer profile.")
}
if(ncol(responses) != length(catObj@answers)){
stop("Response profiles are not compatible with Cat object.")
}
ncombos <- choose(ncol(responses), n)
if(ncombos > 1000000){
stop("Too many combinations result from choose(nrow(responses), n).")
}
if(n > 5){
warning("Asking n>5 questions will provide estimate likely arbitrarily close to truth.")
}
combo_mat <- t(combn(1:ncol(responses), n))
if(approx & nrow(combo_mat) > 1000){
combo_mat <- combo_mat[sample(x = 1:nrow(combo_mat), size = 1000, replace = FALSE), ]
}
find_truth <- function(ind_theta, ind_ans, combo_mat, cat){
combo_profiles <- adply(.data = combo_mat,
.margins = 1,
.id = NULL,
.parallel = parallel,
.fun = function(indices, catObj, ans){
catObj@answers[indices] <- unlist(ans[indices])
theta_est <- estimateTheta(catObj)
return(data.frame(theta = ind_theta, theta_est = theta_est, ans[indices]))
},
catObj = cat,
ans = ind_ans)
return_row <- which.min(abs(combo_profiles$theta_est - ind_theta))
return(combo_profiles[return_row, ])
}
out <- adply(.data = 1:nrow(responses),
.margins = 1,
.id = NULL,
.parallel = parallel,
.fun = function(x) find_truth(ind_theta = theta[x], ind_ans = responses[x,], combo_mat = combo_mat, cat = catObj))
return(out)
}) |
bayesfactor_parameters <- function(posterior,
prior = NULL,
direction = "two-sided",
null = 0,
verbose = TRUE,
...) {
UseMethod("bayesfactor_parameters")
}
bayesfactor_pointnull <- function(posterior,
prior = NULL,
direction = "two-sided",
null = 0,
verbose = TRUE,
...) {
if (length(null) > 1) {
message("'null' is a range - computing a ROPE based Bayes factor.")
}
bayesfactor_parameters(
posterior = posterior,
prior = prior,
direction = direction,
null = null,
verbose = verbose,
...
)
}
bayesfactor_rope <- function(posterior,
prior = NULL,
direction = "two-sided",
null = rope_range(posterior),
verbose = TRUE,
...) {
if (length(null) < 2) {
message("'null' is a point - computing a Savage-Dickey (point null) Bayes factor.")
}
bayesfactor_parameters(
posterior = posterior,
prior = prior,
direction = direction,
null = null,
verbose = verbose,
...
)
}
bf_parameters <- bayesfactor_parameters
bf_pointnull <- bayesfactor_pointnull
bf_rope <- bayesfactor_rope
bayesfactor_parameters.numeric <- function(posterior, prior = NULL, direction = "two-sided", null = 0, verbose = TRUE, ...) {
if (is.null(prior)) {
prior <- posterior
if (verbose) {
warning(
"Prior not specified! ",
"Please specify a prior (in the form 'prior = distribution_normal(1000, 0, 1)')",
" to get meaningful results."
)
}
}
prior <- data.frame(X = prior)
posterior <- data.frame(X = posterior)
sdbf <- bayesfactor_parameters.data.frame(
posterior = posterior, prior = prior,
direction = direction, null = null,
verbose = verbose, ...
)
sdbf$Parameter <- NULL
sdbf
}
bayesfactor_parameters.stanreg <- function(posterior,
prior = NULL,
direction = "two-sided",
null = 0,
verbose = TRUE,
effects = c("fixed", "random", "all"),
component = c("conditional", "location", "smooth_terms", "sigma", "zi", "zero_inflated", "all"),
parameters = NULL,
...) {
cleaned_parameters <- insight::clean_parameters(posterior)
effects <- match.arg(effects)
component <- match.arg(component)
samps <- .clean_priors_and_posteriors(posterior, prior,
verbose = verbose,
effects = effects, component = component,
parameters = parameters
)
temp <- bayesfactor_parameters.data.frame(
posterior = samps$posterior, prior = samps$prior,
direction = direction, null = null,
verbose = verbose, ...
)
bf_val <- .prepare_output(temp, cleaned_parameters, inherits(posterior, "stanmvreg"))
class(bf_val) <- class(temp)
attr(bf_val, "clean_parameters") <- cleaned_parameters
attr(bf_val, "hypothesis") <- attr(temp, "hypothesis")
attr(bf_val, "direction") <- attr(temp, "direction")
attr(bf_val, "plot_data") <- attr(temp, "plot_data")
bf_val
}
bayesfactor_parameters.brmsfit <- bayesfactor_parameters.stanreg
bayesfactor_parameters.blavaan <- function(posterior,
prior = NULL,
direction = "two-sided",
null = 0,
verbose = TRUE,
...) {
cleaned_parameters <- insight::clean_parameters(posterior)
samps <- .clean_priors_and_posteriors(posterior, prior,
verbose = verbose
)
temp <- bayesfactor_parameters.data.frame(
posterior = samps$posterior, prior = samps$prior,
direction = direction, null = null,
verbose = verbose, ...
)
bf_val <- .prepare_output(temp, cleaned_parameters)
class(bf_val) <- class(temp)
attr(bf_val, "clean_parameters") <- cleaned_parameters
attr(bf_val, "hypothesis") <- attr(temp, "hypothesis")
attr(bf_val, "direction") <- attr(temp, "direction")
attr(bf_val, "plot_data") <- attr(temp, "plot_data")
bf_val
}
bayesfactor_parameters.emmGrid <- function(posterior,
prior = NULL,
direction = "two-sided",
null = 0,
verbose = TRUE,
...) {
samps <- .clean_priors_and_posteriors(posterior, prior,
verbose = verbose
)
bayesfactor_parameters.data.frame(
posterior = samps$posterior, prior = samps$prior,
direction = direction, null = null,
verbose = verbose, ...
)
}
bayesfactor_parameters.emm_list <- bayesfactor_parameters.emmGrid
bayesfactor_parameters.data.frame <- function(posterior,
prior = NULL,
direction = "two-sided",
null = 0,
verbose = TRUE,
...) {
direction <- .get_direction(direction)
if (is.null(prior)) {
prior <- posterior
warning(
"Prior not specified! ",
"Please specify priors (with column order matching 'posterior')",
" to get meaningful results."
)
}
if (verbose && length(null) == 1L && (nrow(posterior) < 4e4 || nrow(prior) < 4e4)) {
warning(
"Bayes factors might not be precise.\n",
"For precise Bayes factors, sampling at least 40,000 posterior samples is recommended.",
call. = FALSE
)
}
sdbf <- numeric(ncol(posterior))
for (par in seq_along(posterior)) {
sdbf[par] <- .bayesfactor_parameters(
posterior[[par]],
prior[[par]],
direction = direction,
null = null,
...
)
}
bf_val <- data.frame(
Parameter = colnames(posterior),
log_BF = log(sdbf),
stringsAsFactors = FALSE
)
class(bf_val) <- unique(c(
"bayesfactor_parameters",
"see_bayesfactor_parameters",
class(bf_val)
))
attr(bf_val, "hypothesis") <- null
attr(bf_val, "direction") <- direction
attr(bf_val, "plot_data") <- .make_BF_plot_data(posterior, prior, direction, null, ...)
bf_val
}
.bayesfactor_parameters <- function(posterior,
prior,
direction = 0,
null = 0,
...) {
stopifnot(length(null) %in% c(1, 2))
if (isTRUE(all.equal(posterior, prior))) {
return(1)
}
insight::check_if_installed("logspline")
if (length(null) == 1) {
relative_density <- function(samples) {
f_samples <- .logspline(samples, ...)
d_samples <- logspline::dlogspline(null, f_samples)
if (direction < 0) {
norm_samples <- logspline::plogspline(null, f_samples)
} else if (direction > 0) {
norm_samples <- 1 - logspline::plogspline(null, f_samples)
} else {
norm_samples <- 1
}
d_samples / norm_samples
}
return(relative_density(prior) /
relative_density(posterior))
} else if (length(null) == 2) {
null <- sort(null)
null[is.infinite(null)] <- 1.797693e+308 * sign(null[is.infinite(null)])
f_prior <- .logspline(prior, ...)
f_posterior <- .logspline(posterior, ...)
h0_prior <- diff(logspline::plogspline(null, f_prior))
h0_post <- diff(logspline::plogspline(null, f_posterior))
BF_null_full <- h0_post / h0_prior
if (direction < 0) {
h1_prior <- logspline::plogspline(min(null), f_prior)
h1_post <- logspline::plogspline(min(null), f_posterior)
} else if (direction > 0) {
h1_prior <- 1 - logspline::plogspline(max(null), f_prior)
h1_post <- 1 - logspline::plogspline(max(null), f_posterior)
} else {
h1_prior <- 1 - h0_prior
h1_post <- 1 - h0_post
}
BF_alt_full <- h1_post / h1_prior
return(BF_alt_full / BF_null_full)
}
}
bayesfactor_parameters.bayesfactor_models <- function(...) {
stop(
"Oh no, 'bayesfactor_parameters()' does not know how to deal with multiple models :(\n",
"You might want to use 'bayesfactor_inclusion()' here to test specific terms across models."
)
}
bayesfactor_parameters.sim <- function(...) {
stop(
"Bayes factors are based on the shift from a prior to a posterior. ",
"Since simulated draws are not based on any priors, computing Bayes factors does not make sense :(\n",
"You might want to try `rope`, `ci`, `pd` or `pmap` for posterior-based inference."
)
}
bayesfactor_parameters.sim.merMod <- bayesfactor_parameters.sim |
if (requireNamespace("lintr", quietly = TRUE)) {
test_that("Package Style", {
lintr::expect_lint_free()
})
} |
library(testthat)
credential <- retrieve_credential_testing()
test_that("One Shot: Bad Uri -Not HTTPS", {
expected_message_411 <- "<!DOCTYPE HTML PUBLIC \"-//W3C//DTD HTML 4.01//EN\"\"http://www.w3.org/TR/html4/strict.dtd\">\n<HTML><HEAD><TITLE>Length Required</TITLE>\n<META HTTP-EQUIV=\"Content-Type\" Content=\"text/html; charset=us-ascii\"></HEAD>\n<BODY><h2>Length Required</h2>\n<hr><p>HTTP Error 411. The request must be chunked or have a content length.</p>\n</BODY></HTML>\n"
expected_message_501 <- "<?xml version=\"1.0\" encoding=\"UTF-8\" ?><hash><error>The requested method is not implemented.</error></hash>"
expect_message(
returned_object <-
redcap_read_oneshot(
redcap_uri = "http://bbmc.ouhsc.edu/redcap/api/",
token = credential$token
)
)
expect_equal(returned_object$data, expected=data.frame(), label="An empty data.frame should be returned.")
expect_true(returned_object$status_code %in% c(411L, 501L))
expect_true(returned_object$raw_text %in% c(expected_message_411, expected_message_501))
expect_equal(returned_object$records_collapsed, "")
expect_equal(returned_object$fields_collapsed, "")
expect_false(returned_object$success)
})
test_that("One Shot: Bad Uri -wrong address", {
expected_message <- "<!DOCTYPE html PUBLIC \"-//W3C//DTD XHTML 1.0 Strict//EN\" \"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd\">\n<html xmlns=\"http://www.w3.org/1999/xhtml\">\n<head>\n<meta http-equiv=\"Content-Type\" content=\"text/html; charset=iso-8859-1\"/>\n<title>404 - File or directory not found.</title>\n<style type=\"text/css\">\n<!--\nbody{margin:0;font-size:.7em;font-family:Verdana, Arial, Helvetica, sans-serif;background:
expect_message(
returned_object <-
redcap_read_oneshot(
redcap_uri = "https://bbmc.ouhsc.edu/redcap/apiFFFFFFFFFFFFFF/",
token = credential$token
)
)
expect_equal(returned_object$data, expected=data.frame(), label="An empty data.frame should be returned.")
expect_equal(returned_object$status_code, expected=404L)
expect_equal(returned_object$raw_text, expected=expected_message)
expect_equal(returned_object$records_collapsed, "")
expect_equal(returned_object$fields_collapsed, "")
expect_false(returned_object$success)
})
test_that("Batch: Bad Uri -Not HTTPS", {
expected_outcome_message <- "The initial call failed with the code: (411|501)."
expect_message(
returned_object <-
redcap_read(
redcap_uri = "http://bbmc.ouhsc.edu/redcap/api/",
token = credential$token
)
)
expect_equal(returned_object$data, expected=data.frame(), label="An empty data.frame should be returned.")
expect_true(returned_object$status_code %in% c(411L, 501L))
expect_equal(returned_object$records_collapsed, "failed in initial batch call")
expect_equal(returned_object$fields_collapsed, "failed in initial batch call")
expect_match(returned_object$outcome_messages, expected_outcome_message)
expect_false(returned_object$success)
})
test_that("Batch: Bad Uri -wrong address", {
expected_outcome_message <- "The initial call failed with the code: 404."
expect_message(
returned_object <-
redcap_read(
redcap_uri = "https://bbmc.ouhsc.edu/redcap/apiFFFFFFFFFFFFFF/",
token = credential$token
)
)
expect_equal(returned_object$data, expected=data.frame(), label="An empty data.frame should be returned.")
expect_equal(returned_object$status_code, expected=404L)
expect_equal(returned_object$records_collapsed, "failed in initial batch call")
expect_equal(returned_object$fields_collapsed, "failed in initial batch call")
expect_equal(returned_object$outcome_messages, expected_outcome_message)
expect_false(returned_object$success)
})
test_that("hashed record -warn", {
expected_warning <- "^It appears that the REDCap record IDs have been hashed.+"
expect_warning(
REDCapR:::warn_hash_record_id(),
expected_warning
)
})
test_that("guess_max deprecated -warn", {
expected_outcome_message <- "The `guess_max` parameter in `REDCapR::redcap_read\\(\\)` is deprecated\\."
expect_warning(
regexp = expected_outcome_message,
returned_object <- redcap_read(
redcap_uri = credential$redcap_uri,
token = credential$token,
guess_max = 100
)
)
})
rm(credential) |
furrr_test_that("future_pmap() matches pmap() for simple cases", {
expect_identical(
future_pmap(list(1:3, 4:6, 7:9), ~.x + .y + ..3),
pmap(list(1:3, 4:6, 7:9), ~.x + .y + ..3)
)
})
furrr_test_that("names of `.x` are retained", {
x <- c(a = 1, b = 2)
y <- c(c = 1, d = 2)
expect_named(future_pmap(list(x, y), ~1), c("a", "b"))
})
furrr_test_that("named empty input makes named empty output", {
x <- set_names(list(), character())
expect_named(future_pmap(list(x, x), ~.x), character())
})
furrr_test_that("future_pmap_dbl() works", {
x <- c(1, 2, 3)
y <- c(4, 5, 6)
expect_identical(
future_pmap_dbl(list(x, y), ~.x + .y),
pmap_dbl(list(x, y), ~.x + .y)
)
})
furrr_test_that("future_pmap_int() works", {
x <- c(1L, 2L, 3L)
y <- c(4L, 5L, 6L)
expect_identical(
future_pmap_int(list(x, y), ~.x + .y),
pmap_int(list(x, y), ~.x + .y)
)
})
furrr_test_that("future_pmap_lgl() works", {
x <- c(TRUE, FALSE, TRUE)
y <- c(FALSE, TRUE, TRUE)
expect_identical(
future_pmap_lgl(list(x, y), ~.x || .y),
pmap_lgl(list(x, y), ~.x || .y)
)
})
furrr_test_that("future_pmap_chr() works", {
x <- c("a", "b", "c")
y <- c("d", "e", "f")
expect_identical(
future_pmap_chr(list(x, y), ~.y),
pmap_chr(list(x, y), ~.y)
)
})
furrr_test_that("future_pmap_raw() works", {
x <- c("a", "b", "c")
y <- as.raw(1:3)
expect_identical(
future_pmap_raw(list(x, y), ~.y),
pmap_raw(list(x, y), ~.y)
)
})
furrr_test_that("names of `.x` are retained", {
x <- c(a = 1, b = 2)
y <- c(c = 1, d = 2)
expect_named(future_pmap_dbl(list(x, y), ~1), c("a", "b"))
})
furrr_test_that("future_pmap_dfr() works", {
x <- c("a", "b", "c")
y <- c("d", "e", "f")
expect_identical(
future_pmap_dfr(list(x, y), ~data.frame(x = .x, y = .y)),
pmap_dfr(list(x, y), ~data.frame(x = .x, y = .y))
)
})
furrr_test_that("future_pmap_dfc() works", {
x <- c("a", "b", "c")
y <- c("d", "e", "f")
expect_identical(
future_pmap_dfc(list(x, y), ~as.data.frame(set_names(list(.x), .y))),
pmap_dfc(list(x, y), ~as.data.frame(set_names(list(.x), .y)))
)
})
furrr_test_that("future_pmap() works with completely empty list", {
expect_identical(future_pmap(list(), identity), list())
expect_identical(future_pmap_dbl(list(), identity), double())
})
furrr_test_that("future_pmap() works with size zero input", {
expect_identical(future_pmap(list(list(), list()), identity), list())
})
furrr_test_that("atomic variants work with size zero input", {
expect_identical(future_pmap_chr(list(list(), list()), identity), character())
expect_identical(future_pmap_dbl(list(list(), list()), identity), double())
expect_identical(future_pmap_int(list(list(), list()), identity), integer())
expect_identical(future_pmap_lgl(list(list(), list()), identity), logical())
expect_identical(future_pmap_raw(list(list(), list()), identity), raw())
})
furrr_test_that("size one recycling works", {
expect_identical(
future_pmap(list(1, 1:2), ~c(.x, .y)),
list(c(1, 1), c(1, 2))
)
expect_identical(
future_pmap(list(1:2, 1), ~c(.x, .y)),
list(c(1, 1), c(2, 1))
)
expect_identical(
future_pmap(list(integer(), 1), ~c(.x, .y)),
list()
)
expect_identical(
future_pmap(list(1, integer()), ~c(.x, .y)),
list()
)
})
furrr_test_that("generally can't recycle to size zero", {
expect_error(
future_pmap(list(1:2, integer()), ~c(.x, .y)),
"Can't recycle"
)
expect_error(
future_pmap(list(integer(), 1:2), ~c(.x, .y)),
"Can't recycle"
)
})
furrr_test_that("named arguments can be passed through", {
vec_mean <- function(.x, .y, na.rm = FALSE) {
mean(c(.x,.y), na.rm = na.rm)
}
x <- list(c(NA, 1), 1:2)
expect_identical(
future_pmap(x, vec_mean, na.rm = TRUE),
list(1, 1.5)
)
})
furrr_test_that("arguments can be matched by name", {
x <- list(x = c(1, 2), y = c(3, 5))
fn <- function(y, x) {y - x}
expect_identical(future_pmap_dbl(x, fn), c(2, 3))
})
furrr_test_that("unused components can be absorbed", {
x <- list(c(1, 2), c(3, 5))
fn1 <- function(x) {x}
fn2 <- function(x, ...) {x}
expect_error(future_pmap_dbl(x, fn1))
expect_identical(future_pmap_dbl(x, fn2), c(1, 2))
})
furrr_test_that("globals in `.x` and `.y` are found (
fn1 <- function(x) sum(x, na.rm = TRUE)
fn2 <- function(x) sum(x, na.rm = FALSE)
x <- list(c(1, 2, NA), c(2, 3, 4))
fns1 <- map(x, ~ purrr::partial(fn1, x = .x))
fns2 <- map(x, ~ purrr::partial(fn2, x = .x))
expect_identical(
future_pmap(list(fns1, fns2), ~c(.x(), .y())),
list(c(3, NA), c(9, 9))
)
})
test_that("globals in `.l` are only exported to workers that use them", {
plan(multisession, workers = 2)
on.exit(plan(sequential), add = TRUE)
my_wrapper1 <- local({
my_mean1 <- function(x) mean(x, na.rm = TRUE)
function(x) {
my_mean1(x)
exists("my_mean1")
}
})
my_wrapper2 <- local({
my_mean2 <- function(x) mean(x, na.rm = FALSE)
function(x) {
my_mean2(x)
exists("my_mean1")
}
})
x <- list(my_wrapper1, my_wrapper2)
expect_identical(
future_pmap_lgl(list(x), .f = ~.x(c(1, NA))),
c(TRUE, FALSE)
)
}) |
NULL
NULL
cluspred <- function(y, x, u = NULL,
K = 2, model.reg = "mean", tau = 0.5,
simultaneous=TRUE, np=TRUE,
nbinit = 20, nbCPU = 1, tol = 0.01,
band = (length(y)**(-1/5)), seed=134) {
checkinputs(y, x, u, K, model.reg, tau, simultaneous, np, nbinit, nbCPU, tol, band, seed)
set.seed(seed)
if (!np){
if (!(model.reg%in%c("mean", "quantile"))) stop("model.red must be mean or quantile for the parametric approach")
}
if (simultaneous){
if (np){
return(Singleblock_algo_NP(y, x, u, model.reg, nbinit, K, tau, nbCPU, tol, band))
}else{
return(Singleblock_algo_Param(y, x, u, model.reg, nbinit, K, tau, nbCPU, tol))
}
}else{
return(TwostepsAlgo(y, x, u, np, model.reg, nbinit, K, tau,nbCPU, tol, band))
}
} |
ArchiveGribGrab <- function(abbrev, model.date, model.run, preds, local.dir = NULL, file.names = NULL,
tidy = FALSE, verbose = TRUE, download.method = NULL, file.type = "grib2") {
if(is.null(local.dir)) {
local.dir <- getwd()
}
if(!is.null(file.names)) {
if(length(file.names) != length(preds)) {
stop("The length of the \"file.names\" argument is not the same as the length of the \"preds\" argument.
Each file downloaded from NOMADS needs its own file name.")
}
}
if(tidy) {
unlink(list.files(local.dir, pattern = "*\\.grb[2]?$", full.names = TRUE))
}
model.date <- as.numeric(strsplit(as.character(model.date), split = "")[[1]])
if(length(model.date) != 8) {
stop("MODEL.DATE should be in YYYYMMDD format!")
}
if(file.type == "grib1") {
suffix <- ".grb"
} else if (file.type == "grib2") {
suffix <- ".grb2"
} else {
stop(paste0("Did not recognize file type \"", file.type, "\""))
}
model.url <- NOMADSArchiveList(abbrev)$url
download.url <- paste0(model.url, paste(model.date[1:6], collapse = ""), "/", paste(model.date, collapse = ""), "/")
grib.info <- NULL
for(k in 1:length(preds)) {
if(is.null(file.names)) {
file.part <- paste0(paste(model.date, collapse = ""), "_",
sprintf("%02.f", as.numeric(model.run)),
"00_", sprintf("%03.f", as.numeric(preds[k])), suffix)
file.name <- file.part
} else {
file.name <- file.names[k]
}
link.list <- unique(LinkExtractor(download.url))
if(!any(grepl(file.part, link.list))) {
warning(paste("The requested data file ending in", file.part, "does not appear to be in the archive.
Try opening", download.url, "in a web browser to verify that it's missing."))
next
}
grb.urls <- stringr::str_replace(
stringr::str_extract(
paste0(download.url, link.list[grepl(file.part, link.list)]),
paste0("^.*", file.part, ">")),
">", "")
if(length(grb.urls) > 1) {
warning("Two files were found: ", paste(link.list[grepl(paste0(".*", file.part, "$"), link.list)], collapse = " "), ". Both will be downloaded.")
c <- 1
} else {
c <- ""
}
use.curl <- FALSE
file.names <- NULL
for(grb.url in grb.urls) {
file.name.tmp <- paste0(c, file.name)
if(is.null(download.method) & !use.curl) {
download.file(grb.url, paste(local.dir,file.name.tmp, sep = "/"), mode = "wb", quiet = !verbose)
}
if(!is.null(download.method) & !use.curl) {
download.file(grb.url, paste(local.dir,file.name.tmp, sep = "/"), download.method, mode = "wb", quiet = !verbose)
}
file.names <- append(file.names, paste(normalizePath(local.dir), file.name.tmp, sep = "/"))
print(file.names)
if(c != "") {
c <- c + 1
}
}
grib.info[[k]] <- list(file.name = file.names, url = grb.urls)
}
return(grib.info)
}
CheckNOMADSArchive <- function(abbrev, model.date = NULL) {
model.url <- NOMADSArchiveList(abbrev=abbrev)$url
model.list <- c()
if(is.null(model.date)) {
month.list <- grep("\\d{6}/", LinkExtractor(model.url), value = TRUE)
for(month in month.list) {
month.url <- paste0(model.url, month)
if(RCurl::url.exists(month.url)) {
date.list <- grep("\\d{8}/", LinkExtractor(month.url), value = TRUE)
for(day in date.list) {
day.url <- paste0(model.url, month, day)
if(RCurl::url.exists(day.url)) {
model.list <- append(model.list, grep("grb\\d?$", LinkExtractor(day.url), value = TRUE))
}
}
}
}
} else {
model.date <- as.numeric(strsplit(as.character(model.date), split = "")[[1]])
check.url <- paste0(model.url, paste(model.date[1:6], collapse = ""), "/", paste(model.date, collapse = ""), "/")
if(RCurl::url.exists(check.url)) {
model.list <- append(
model.list,
stringr::str_replace(
unlist(stringr::str_extract_all(LinkExtractor(check.url),
"^.*grb\\d?>")), ">", "")
)
}
}
model.list <- as.vector(model.list)
available.models <- list(
date = stringr::str_extract(model.list, "\\d{8}"),
model.run = stringr::str_replace_all(stringr::str_extract(model.list, "_\\d{4}_"), "_", ""),
pred = stringr::str_replace(stringr::str_replace(stringr::str_extract(model.list, "_\\d{3}\\."), "\\.", ""), "_", ""),
file.name = model.list)
if(length(available.models$date) == 0) {
warning("No products are available for that model and date. Sorry!")
}
invisible(available.models)
} |
summary.mmsbm <- function(object, ...){
summ <- list("Number of Dyads" = nrow(object$dyadic.data),
"Number of Blocks" = ncol(object$BlockModel),
"Percent of Observations in Each Block" = rowMeans(object$MixedMembership),
"Blockmodel Matrix" = exp(object$BlockModel) / (1 + exp(object$BlockModel)),
"Monadic Coefficients" = object$MonadCoef)
if(length(object$DyadCoef)){
summ$`Dyadic Coefficients` <- object$DyadCoef
}
if(object$n_states > 1){
summ$`Markov State Probabilities` <- rowMeans(object$Kappa)
}
if(object$forms$hessian){
if("vcov_dyad" %in% names(object)){
summ$`Dyadic Coefficients` <- cbind(object$DyadCoef,
sqrt(diag(object$vcov_dyad)))
colnames(summ$`Dyadic Coefficients`) <- c("Coefficient", "Std. Error")
}
mse <- sqrt(diag(object$vcov_monad))
summ$`Monadic Coefficients` <- cbind(c(summ$`Monadic Coefficients`),
mse)
colnames(summ$`Monadic Coefficients`) <- c("Coefficient", "Std. Error")
rownames(summ$`Monadic Coefficients`) <- rownames(object$vcov_monad)
}
print(summ)
} |
source("ESEUR_config.r")
library("boot")
sd_diff=function(est, indices)
{
t=est[indices]
return(sd(t[1:num_A_est])-sd(t[(num_A_est+1):total_est]))
}
est=read.csv(paste0(ESEUR_dir, "group-compare/simula_04.csv.xz"), as.is=TRUE)
A_est=subset(est, Group =="A")$Estimate
B_est=subset(est, Group !="A")$Estimate
num_A_est=length(A_est)
num_B_est=length(B_est)
total_est=num_A_est+num_B_est
AB_sd_diff=abs(sd(A_est)-sd(B_est))
bid_boot=boot(c(A_est, B_est), sd_diff, R = 4999)
plot(density(bid_boot$t),
main="", ylab="Density\n")
mean(bid_boot$t)
sd(bid_boot$t)
length(bid_boot$t[abs(bid_boot$t) >= AB_sd_diff]) |
test_that("plot runs without warning",{
curve <- function(t){
rbind(t*cos(13*t), t*sin(13*t))
}
set.seed(18)
data_curves <- lapply(1:4, function(i){
m <- sample(10:15, 1)
delta <- abs(rnorm(m, mean = 1, sd = 0.05))
t <- cumsum(delta)/sum(delta)
data.frame(t(curve(t)) + 0.07*t*matrix(cumsum(rnorm(2*length(delta))),
ncol = 2))
})
knots <- seq(0,1, length = 11)
smooth_elastic_mean <- compute_elastic_mean(data_curves, knots = knots)
expect_warning(plot(smooth_elastic_mean), regexp = NA)
})
test_that("plot gives error if more than two dim",{
data_curve1 <- data.frame(x1 = sin(1:7/4*pi), x2 = cos(1:7/4*pi),
x3 = -sin(1:7/4*pi))
data_curve2 <- data_curve <- data.frame(x1 = sin(1:15/8*pi), x2 = cos(1:15/8*pi),
x3 = 1:15/8*pi)
data_curves <- list(data_curve1, data_curve2)
knots <- seq(0,1, length = 11)
elastic_mean <- compute_elastic_mean(data_curves, knots = knots, type = "polygon")
expect_error(plot(elastic_mean), "Plotting option only for functions and planar curves!")
}) |
predicted <- function(fitted_model) {
Z <- rstan::extract(fitted_model$model, "Z", permuted = FALSE)
x <- rstan::extract(fitted_model$model, "x", permuted = FALSE)
Zperm <- rstan::extract(fitted_model$model, "Z", permuted = TRUE)
xperm <- rstan::extract(fitted_model$model, "x", permuted = TRUE)
n_ts <- dim(Zperm$Z)[2]
n_y <- dim(xperm$x)[3]
n_chains <- dim(Z)[2]
n_trends <- dim(xperm$x)[2]
n_mcmc <- dim(x)[1]
pred <- array(0, c(n_mcmc, n_chains, n_y, n_ts))
for (i in 1:n_mcmc) {
for (chain in 1:n_chains) {
x_i <- t(matrix(x[i, chain, ], nrow = n_trends, ncol = n_y))
Z_i <- t(matrix(Z[i, chain, ], nrow = n_ts, ncol = n_trends))
pred[i, chain, , ] <- x_i %*% Z_i
}
}
return(pred)
} |
geom_node_tile <- function(mapping = NULL, data = NULL, position = 'identity',
show.legend = NA, ...) {
mapping <- aes_intersect(mapping, aes(
x = x, y = y, width = width, height = height
))
layer(
data = data, mapping = mapping, stat = StatFilter, geom = GeomNodeTile,
position = position, show.legend = show.legend, inherit.aes = FALSE,
params = list(na.rm = FALSE, ...)
)
}
GeomNodeTile <- ggproto('GeomNodeTile', GeomTile,
default_aes = aes(
fill = NA, colour = 'black', size = 0.5, linetype = 1,
alpha = NA, width = 1, height = 1
),
required_aes = c('x', 'y')
) |
vital_status <- function(wide_df, status_var = "p_status", life_var_new = "p_alive", check = TRUE,
as_labelled_factor = FALSE){
if(!is.data.frame(wide_df) & data.table::is.data.table(wide_df)){
rlang::inform("You are using a dplyr based function on a raw data.table; the data.table has been converted to a data.frame to let this function run more efficiently.")
wide_df <- as.data.frame(wide_df)
}
status_var <- rlang::enquo(status_var)
life_var_new <- rlang::enquo(life_var_new)
defined_vars <- c(rlang::as_name(status_var))
not_found <- defined_vars[!(defined_vars %in% colnames(wide_df))]
if(length(not_found) > 0) {
rlang::abort(paste0("The following variables defined are not found in the provided dataframe: ", not_found, ". Please run pat_status function beforehand."))
}
lifevar_label <- paste("Patient Vital Status at end of follow-up", attr(wide_df[[rlang::eval_tidy(status_var)]], "label", exact = T) %>%
stringr::str_sub(-10))
if(is.factor(wide_df[[rlang::eval_tidy(status_var)]])){
changed_status_var <- TRUE
wide_df <- wide_df %>%
dplyr::mutate(
status_var_orig = .data[[!!status_var]],
!!status_var := sjlabelled::as_numeric(.data[[!!status_var]],
keep.labels=FALSE, use.labels = TRUE))
} else{
changed_status_var <- FALSE
}
wide_df <- wide_df %>%
dplyr::mutate(!!life_var_new := dplyr::case_when(
.data[[!!status_var]] == 1 ~ 10,
.data[[!!status_var]] == 2 ~ 10,
.data[[!!status_var]] == 3 ~ 11,
.data[[!!status_var]] == 4 ~ 11,
TRUE ~ as.numeric(.data[[!!status_var]])))
if(changed_status_var == TRUE){
wide_df <- wide_df %>%
dplyr::mutate(
!!status_var := .data$status_var_orig
) %>%
dplyr::select(-status_var_orig)
}
wide_df <- wide_df %>%
sjlabelled::var_labels(!!life_var_new := !!lifevar_label) %>%
sjlabelled::val_labels(!!life_var_new := c("Patient alive" = 10,
"Patient dead" = 11,
"NA - patient not born before end of FU" = 97,
"NA - patient did not develop cancer before end of FU" = 98,
"NA - patient date of death is missing" = 99),
force.labels = TRUE)
if(as_labelled_factor == TRUE){
wide_df <- wide_df %>%
dplyr::mutate(!!life_var_new := sjlabelled::as_label(.data[[!!life_var_new]], keep.labels=TRUE))
}
if(check == TRUE){
check_tab <- wide_df %>%
dplyr::count(.data[[!!status_var]], .data[[!!life_var_new]])
print(check_tab)
}
return(wide_df)
} |
f_abbreviation <- function (x, length = 5, ...) {
abbreviate(x, minlength = length, named = FALSE, ...)
}
ff_abbreviation <- functionize(f_abbreviation) |
getBins <- function (model = NULL, obs = NULL, pred = NULL, id = NULL,
bin.method, n.bins = 10, fixed.bin.size = FALSE, min.bin.size = 15,
min.prob.interval = 0.1, quantile.type = 7, simplif = FALSE, verbosity = 2) {
if (!is.null(model)) {
if (!is.null(obs) && verbosity > 0)
message("Argument 'obs' ignored in favour of 'model'.")
if (!is.null(pred) && verbosity > 0)
message("Argument 'pred' ignored in favour of 'model'.")
obspred <- mod2obspred(model)
obs <- obspred[ , "obs"]
pred <- obspred[ , "pred"]
}
stopifnot(length(obs) == length(pred),
!(NA %in% obs),
!(NA %in% pred),
obs %in% c(0, 1),
is.null(id) | length(id) == length(pred),
n.bins >= 2,
min.bin.size >= 0,
min.prob.interval > 0,
min.prob.interval < 1)
if (!(bin.method %in% modEvAmethods("getBins")))
stop("Invalid bin.method; type modEvAmethods('getBins') for available options.")
N <- length(obs)
bin.method0 <- bin.method
if (bin.method == "round.prob" ) {
if (verbosity > 1) message("Arguments n.bins, fixed.bin.size and min.bin.size are ignored by this bin.method.")
prob.bin <- round(pred, digits = nchar(min.prob.interval) - 2)
}
else if (bin.method == "prob.bins") {
if (verbosity > 1) message("Arguments n.bins, fixed.bin.size and min.bin.size are ignored by this bin.method.")
bin.cuts <- seq(from = min(0, min(pred)), to = max(1, max(pred)), by = min.prob.interval)
prob.bin <- findInterval(pred, bin.cuts)
}
else if (bin.method == "size.bins") {
if (verbosity > 1) message("Arguments n.bins and min.prob.interval are ignored by this bin.method.")
bin.method <- "n.bins"
n.bins <- floor(N / min.bin.size)
fixed.bin.size <- TRUE
}
if (bin.method == "n.bins") {
if (verbosity > 1 && bin.method0 != "size.bins") message("Arguments min.bin.size and min.prob.interval are ignored by this bin.method.")
if (fixed.bin.size) {
prob.bin <- cut(seq_along(pred), n.bins)
} else {
prob.bin <- cut(pred, n.bins)
}
}
else if (bin.method == "quantiles") {
if (verbosity > 1) message("Arguments fixed.bin.size, min.bin.size and min.prob.interval are ignored by this bin.method.")
cutpoints <- quantile(pred, probs = (0:n.bins)/n.bins, type = quantile.type)
prob.bin <- findInterval(pred, cutpoints, rightmost.closed = TRUE)
}
prob.bins <- sort(unique(prob.bin))
bins.table <- t(as.data.frame(unclass(table(obs, prob.bin))))
bins.table <- data.frame(rowSums(bins.table), bins.table[, c(2, 1)])
colnames(bins.table) <- c("N", "N.pres", "N.abs")
bins.table$prevalence <- with(bins.table, N.pres/N)
bins.table$mean.prob <- tapply(pred, prob.bin, mean)
bins.table$median.prob <- tapply(pred, prob.bin, median)
bins.table$difference <- with(bins.table, mean.prob - prevalence)
bins.table$max.poss.diff <- ifelse(bins.table$mean.prob < 0.5,
1 - bins.table$mean.prob,
bins.table$mean.prob)
bins.table$adj.diff <- with(bins.table, abs(difference - max.poss.diff))
bins.table$overpred <- apply(bins.table[, c("prevalence", "mean.prob")],
MARGIN = 1, max)
bins.table$underpred <- apply(bins.table[, c("prevalence", "mean.prob")],
MARGIN = 1, min)
bins.table <- bins.table[bins.table$N > 0, ]
if (min(as.data.frame(bins.table)$N) < 15)
if (verbosity > 0) warning("There is at least one bin with less than 15 values, for which comparisons may not be meaningful; consider using a bin.method that allows defining a minimum bin size")
n.bins <- nrow(bins.table)
list(prob.bin = prob.bin, bins.table = bins.table, N = N, n.bins = n.bins)
} |
check_nodes <- function(x, nms, check_calls = F, depth = NA,
stop_pred = NULL) {
depth = depth - 1
if (!is.na(depth) && depth < 0)
return(NULL)
if (check_calls) {
if (is_call(x) && call_name(x) %in% nms)
withRestarts(
signal("Reserved symbol found", .subclass="passer", val=deparse(x)),
get_back_to_work = function() NULL)
} else {
if (is_symbol(x) && deparse(x) %in% nms)
withRestarts(
signal("Reserved symbol found", .subclass="passer", val=deparse(x)),
get_back_to_work = function() NULL)
}
if (is_call(x) && !(call_name(x) %in% c("::", ":::"))) {
if (is.null(stop_pred) || !as_mapper(stop_pred)(x))
call_args(x) %>%
map(~check_nodes(., nms=nms, check_calls=check_calls,
depth=depth, stop_pred=stop_pred))
}
}
find_used_symbols <- function(x, nms, check_calls = F, depth = NA,
stop_pred = NULL) {
expr <- enexpr(x)
symbol_list <- NULL
handler <- function(cond) {
symbol_list <<- append(symbol_list, cond$val)
invokeRestart("get_back_to_work")
}
withCallingHandlers(
check_nodes(expr, nms=nms, check_calls=check_calls,
depth=depth, stop_pred=stop_pred),
passer = handler
)
return(unique(symbol_list))
}
get_used_specials <- function(qs, names_to_check, ...) {
qs %>%
keep(~quo_is_call(.) | quo_is_symbol(.)) %>%
map(function(q) {
l <- find_used_symbols(!!get_expr(q), names_to_check, ...)
if (!is.null(l))
env_has(env = get_env(q), nms=l, inherit = T) %>%
keep(~.==T) %>% names()
}) %>%
unlist() %>%
unique()
}
check_for_calls <- function(qs, names_to_check, message, ...) {
l <- qs %>%
keep(~quo_is_call(.) | quo_is_symbol(.)) %>%
map(function(q)
find_used_symbols(!!get_expr(q), names_to_check, check_calls = T, ...)) %>%
unlist()
if (length(l) > 0) warning(paste0(message, "`", l[[1]], "`"),
immediate. = TRUE, call. = FALSE)
invisible(NULL)
}
warn_of_specials <- function(x) {
if (length(x) > 0) {
agreement <- ""
verb <- "have"
if (length(x) == 1) {
agreement <- "s"
verb <- "has"
}
warning("`", paste(x, collapse = "`, `"),
"` ", verb, " special meaning as catchr input, but seem", agreement, " to already be defined elsewhere. These previous definitions may be masked when determining condition behavior. (To turn these warnings off, use `catchr_default_opts(warn_about_terms=FALSE)`.)",
immediate. = TRUE, call. = FALSE)
}
}
approx_arg_name <- function(x, len = 25) {
v <- get_expr(enquo(x)) %>% expr_deparse(width = 999) %>% paste(collapse = "")
add_ellipses(v, len)
}
has_handler_args <- function(fn) {
args <- Map(is_missing, fn_fmls(args(fn)))
needed <- args %>% keep(~.) %>% length()
supplied <- args %>% keep(~!.) %>% length()
has_dots <- "..." %in% fn_fmls_names(args(fn))
return(needed == 1 || (needed == 0 && supplied > 0) || has_dots)
}
classify_el <- function(el, nono_words) {
el_expr <- approx_arg_name(!!el)
if (is_function(el) && !has_handler_args(el))
abort(paste0(el_expr, " must take at least one argument to be in a catchr plan"), fn = el)
else if (is_string(el) && !(el %in% nono_words))
abort(paste0(el_expr, " is not one of catchr's special reserved terms"), string = el)
else if (!is_string(el) && !is_function(el))
abort(paste0(el_expr, " must be a string, unquoted expression, or function, but is type '", typeof(el), "'"), arg=el)
}
classify_arg <- function(arg, nono_words) {
arg_expr <- approx_arg_name(!!arg)
if (length(arg) > 1 || is_list(arg)) {
if (!is_list(arg) && !is_bare_character(arg))
abort(paste0("Input `", arg_expr, "` has an invalid type: '", typeof(arg), "'"), val=arg)
walk(arg, ~classify_el(., nono_words))
} else
classify_el(arg, nono_words)
invisible(arg)
}
make_catchr_mask <- function(nms = special_terms) {
as_list(nms) %>%
set_names(nms) %>%
as_data_mask()
}
clean_input <- function(qs, spec_names = NULL) {
if (is.null(spec_names))
spec_names <- special_terms
mask <- make_catchr_mask(spec_names)
res <- qs %>%
map(~eval_tidy(., data = mask)) %>%
map(~classify_arg(., spec_names)) %>%
add_back_arg_pos(qs)
env_unbind(parent.env(mask), env_names(parent.env(mask)))
res
}
check_and_clean_input <- function(..., spec_names) {
akw <- args_and_kwargs(...)
if (getOption("catchr.warn_about_terms", FALSE))
warn_of_specials(get_used_specials(akw$kwargs, spec_names))
check_for_calls(akw$kwargs, c("user_exit", "user_display"), "`user_exit/user_display` is being called in the input to a plan at a very shallow level, possibly meaning that it is not in a function. Remember that these functions need to be IN a function or passed in AS a function, not a call. The call in question: ", depth=2, stop_pred = ~call_name(.)=="function")
kwargs <- clean_input(akw$kwargs, spec_names)
args <- unnamed_args_to_strings(akw$args)
check_for_duplicates(args, names(kwargs))
walk(args, function(arg)
if (arg %in% names(kwargs))
abort(paste0("'", arg, "' is both an unnamed and named argument")))
return(list(args = args, kwargs = kwargs))
}
check_for_duplicates <- function(l, ...) {
l <- append(l, list(...))
dupes <- l[duplicated(l)] %>% unique()
if (length(dupes) > 0)
abort(paste0("Conditions cannot have multiple plans: ",
paste0("'", dupes, "'", collapse = ",")))
NULL
}
unnamed_args_to_strings <- function(x) {
x %>%
map(get_expr) %>%
walk(~if (!is_string(.) && !is_symbol(.))
abort("Unnamed args must be unquoted names or strings", arg=.)) %>%
as.character() %>%
add_back_arg_pos(x)
} |
if(!dev.interactive(TRUE)) pdf("smooth.spline-test.pdf")
y18 <- c(1:3, 5, 4, 7:3, 2*(2:5), rep(10, 4))
(b.64 <- grepl("^x86.64", Sys.info()[["machine"]]) &&
.Machine$sizeof.pointer > 4)
(Lb.64 <- b.64 && Sys.info()[["sysname"]] == "Linux" && .Machine$sizeof.pointer == 8)
(s2. <- smooth.spline(y18, cv = TRUE,
control = list(trace=TRUE, tol = 1e-6,
low = if(b.64) -3 else -2)))
plot(y18)
xx <- seq(1,length(y18), len=201)
lines(predict(s2., xx), col = 4)
mtext(deparse(s2.$call,200), side= 1, line= -1, cex= 0.8, col= 4)
(sdf8 <- smooth.spline(y18, df = 8, control=list(trace=TRUE)))
sdf8$df - 8
(sdf8. <- smooth.spline(y18, df = 8, control=list(tol = 1e-8)))
ss50 <- try(smooth.spline(y18, spar = 50))
e <- try(smooth.spline(y18, spar = -9))
if(Lb.64) inherits(e, "try-error") else "not Linux 64-bit"
b.64 || inherits(ss50, "try-error")
e10 <- c(-20, -10, -7, -4:4, 7, 10)
(lams <- setNames(10^e10, paste0("lambda = 10^", e10)))
lamExp <- as.expression(lapply(e10, function(E)
substitute(lambda == 10^e, list(e = E))))
sspl <- lapply(lams, function(LAM) try(smooth.spline(y18, lambda = LAM)))
sspl
ok <- vapply(sspl, class, "") == "smooth.spline"
stopifnot(ok[e10 <= 7])
ssok <- sspl[ok]
ssGet <- function(ch) t(sapply(ssok, `[` , ch))
ssGet1 <- function(ch) sapply(ssok, `[[`, ch)
stopifnot(all.equal(ssGet1("crit"), ssGet1("cv.crit"), tol = 1e-10))
ssGet(c("lambda", "df", "crit", "pen.crit"))
plot(y18); lines(predict(s2., xx), lwd = 5, col = adjustcolor(4, 1/4))
invisible(lapply(seq_along(ssok), function(i) lines(predict(ssok[[i]], xx), col=i)))
i18 <- 1:18
abline(lm(y18 ~ i18), col = adjustcolor('tomato',1/2), lwd = 5, lty = 3)
legend("topleft", lamExp[ok], ncol = 2, bty = "n", col = seq_along(ssok), lty=1)
s2 <- smooth.spline(y18, cv = TRUE, keep.stuff=TRUE)
s2.7 <- smooth.spline(y18, cv = TRUE, keep.stuff=TRUE, nknots = 7)
s2.11 <- smooth.spline(y18, cv = TRUE, keep.stuff=TRUE, nknots = 11)
plot(y18)
lines(predict(s2, xx), lwd = 5, col = adjustcolor(4, 1/4))
lines(predict(s2.7, xx), lwd = 3, col = adjustcolor("red", 1/4))
lines(predict(s2.11, xx), lwd = 2, col = adjustcolor("forestgreen", 1/4))
if(!requireNamespace("Matrix", quietly = TRUE) && !interactive())
q("no")
if(Lb.64 && interactive())
stopifnot(inherits(e, "try-error"))
rbind("s-9_err" = inherits(e, "try-error"),
"s+50_err"= inherits(ss50, "try-error"))
aux2Mat <- function(auxM) {
stopifnot(is.list(auxM),
identical(vapply(auxM, class, ""),
setNames(rep("numeric", 4), c("XWy", "XWX", "Sigma", "R"))))
nk <- length(XWy <- auxM[["XWy"]])
list(XWy = XWy,
XWX = Matrix::bandSparse(nk, k= 0:3, diagonals= matrix(auxM[[ "XWX" ]], nk,4), symmetric=TRUE),
Sigma= Matrix::bandSparse(nk, k= 0:3, diagonals= matrix(auxM[["Sigma"]], nk,4), symmetric=TRUE))
}
chkB <- function(smspl, tol = 1e-10) {
stopifnot(inherits(smspl, "smooth.spline"))
if(!is.list(smspl$auxM))
stop("need result of smooth.spline(., keep.stuff = TRUE)")
lM <- aux2Mat(smspl$auxM)
beta.hat <- solve(lM$XWX + smspl$lambda * lM$Sigma, lM$XWy)
all.equal(as.vector(beta.hat),
smspl$fit$coef, tolerance = tol)
}
stopifnot(chkB(s2))
stopifnot(chkB(s2.7))
stopifnot(chkB(s2.11))
lM <- aux2Mat(s2$auxM)
A <- lM$XWX + s2$lambda * lM$Sigma
R <- Matrix::chol(A)
c. <- s2$fit$coef
stopifnot(all.equal(c., as.vector( solve(A, lM$XWy))) )
pen <- as.vector(c. %*% lM$Sigma %*% c.)
c(unscaled.penalty = pen,
scaled.penalty = s2$lambda * pen)
Sigma.tit <- quote(list(Sigma == Omega, "where"~~ Omega[list(j,k)] ==
integral({B[j]*second}(t)~{B[k]*second}(t)~dt)))
Matrix::image(lM$XWX, main = quote({X*minute}*W*X))
Matrix::image(lM$Sigma, main = Sigma.tit)
Matrix::image(A, main = quote({X*minute}*W*X + lambda*Sigma))
Matrix::image(R, main = quote(R == chol({X*minute}*W*X + lambda*Sigma)))
s2.7.k <- smooth.spline(y18, cv = TRUE, keep.stuff=TRUE,
all.knots = s2.7$fit$knot[3+ 1:7])
ii <- names(s2.7) != "call"
stopifnot( all.equal(s2.7 [ii],
s2.7.k[ii]))
s2.9f <- smooth.spline(y18, cv = TRUE, keep.stuff=TRUE,
all.knots = seq(0, 1, length.out = 9))
lines(predict(s2.9f, xx), lwd = 2, lty=3, col = adjustcolor("tomato", 1/2))
s2.7f <- smooth.spline(y18, cv = TRUE, keep.stuff=TRUE,
all.knots = c(-1,1,3,5,7,9,12)/10)
if(FALSE) {
s2.5f <- smooth.spline(y18, cv = TRUE, keep.stuff=TRUE, control=list(trace=TRUE),
all.knots = c(1,3,5,7,9)/10)
lines(predict(s2.5f, xx), lwd = 2, lty=3, col = adjustcolor("brown", 1/2))
}
dScaledKnots <- function(smsp, drop.ends=TRUE) {
stopifnot(inherits(smsp, "smooth.spline"))
sf <- smsp$fit
nk <- length(kk <- sf$knot)
stopifnot((nk <- length(kk <- sf$knot)) >= 7)
if(drop.ends) kk <- kk[4:(nk-3)]
sf$min + sf$range * kk
}
pLines <- function(ss) {
abline(v = dScaledKnots(ss), lty=3, col=adjustcolor("black", 1/2))
abline(h = 0, v = range(ss$x), lty=4, lwd = 1.5, col="skyblue4")
}
xe <- seq(-5, 25, length=256)
plot(y18, xlim=range(xe), ylim = c(-4,10)+.5, xlab="x")
lines(predict(s2.7f, xe), col=2, lwd = 2)
pLines(s2.7f)
str(m2 <- predict(s2.7f, x=xe, deriv=2))
plot(m2, type="l", col=2, lwd = 2,
main = "m''(x) -- for m(.) := smooth.spl(*, all.knots=c(..))",
sub = "(knots shown as vertical dotted lines)")
pLines(s2.7f)
m1 <- predict(s2.7f, x=xe, deriv = 1)
plot(m1, type="l", col=2, lwd = 2,
main = "m'(x) -- for m(.) := smooth.spl(*, all.knots=c(..))",
sub = "(knots shown as vertical dotted lines)")
pLines(s2.7f) |
context("Just testing PSTNPds functionality")
test_that("Check whether length of PSTNPds vector is correct",{
pstFunc<-as.vector(PSTNPds(seqs="ATAAACG",pos = c("ATAAGCG","ATCCCCG"),neg = c("AAAACCG","CGCCACT")))
expect_equal(length(pstFunc),5)
}) |
expected <- eval(parse(text="\"ts\""));
test(id=0, code={
argv <- eval(parse(text="list(structure(1:5, .Tsp = c(1, 5, 1), class = \"ts\"))"));
do.call(`oldClass`, argv);
}, o=expected); |
NULL
interpret_d <- function(...) {
.Deprecated("interpret_cohens_d")
interpret_cohens_d(...)
}
interpret_g <- function(...) {
.Deprecated("interpret_hedges_g")
interpret_hedges_g(...)
}
interpret_delta <- function(...) {
.Deprecated("interpret_glass_delta")
interpret_glass_delta(...)
}
interpret_parameters <- function(...) {
.Deprecated("interpret_r")
interpret_r(...)
} |
targets::tar_test("tar_git_status_targets() up-to-date targets", {
skip_os_git()
git_setup_init()
expect_equal(nrow(tar_git_status_targets(callr_function = NULL)), 0L)
})
targets::tar_test("tar_git_status_targets() outdated targets", {
skip_os_git()
git_setup_init()
targets::tar_invalidate(everything())
expect_gt(nrow(tar_git_status_targets(callr_function = NULL)), 0L)
}) |
context("ColorProvider works")
test_that("ColorProvider works", {
aa <- ColorProvider$new()
expect_is(aa, "ColorProvider")
expect_is(aa, "R6")
expect_is(aa$locale, "character")
expect_equal(aa$locale, "en_US")
expect_is(aa$all_colors, "list")
expect_equal(aa$all_colors$AliceBlue, "
expect_is(aa$safe_colors, "character")
expect_is(aa$bothify, "function")
expect_is(aa$color_name, "function")
expect_is(aa$color_name(), "character")
expect_is(aa$hex_color(), "character")
expect_is(aa$safe_color_name(), "character")
expect_error(aa$check_locale("en_asdf"))
})
test_that("ColorProvider locale support works", {
skip_on_cran()
skip_on_travis()
test_locale <- function(loc) {
bb <- ColorProvider$new(locale = loc)
expect_is(bb$locale, "character")
expect_equal(bb$locale, loc)
expect_is(bb$color_name(), "character")
expect_true(all(bb$color_name() %in% names(bb$all_colors)))
expect_is(bb$safe_color_name(), "character")
expect_true(all(bb$safe_color_name() %in% bb$safe_colors))
}
locales <- c("en_US", "uk_UA")
for (loc in locales) {
test_locale(loc)
}
})
context("ch color functions work")
test_that("ch color functions error for incorrect input", {
expect_error(ch_color_name(-1))
expect_error(ch_color_name(-99, "uk_UA"))
expect_error(ch_color_name(locale = "ch_AR"))
expect_error(ch_safe_color_name(-1))
expect_error(ch_safe_color_name(-99, "uk_UA"))
expect_error(ch_safe_color_name(locale = "ch_AR"))
expect_error(ch_hex_color(-99))
expect_error(ch_safe_hex_color(-1))
expect_error(ch_rgb_color(-99))
expect_error(ch_rgb_css_color(-1))
})
test_that("ch_color_name works", {
expect_is(ch_color_name(), "character")
expect_is(ch_color_name(7), "character")
expect_equal(length(ch_color_name()), 1)
expect_equal(length(ch_color_name(12)), 12)
expect_true(all(ch_color_name() %in% names(ColorProvider$new()$all_colors)))
expect_true(all(ch_color_name(7) %in% names(ColorProvider$new()$all_colors)))
})
test_that("ch_safe_color_name works", {
expect_is(ch_safe_color_name(), "character")
expect_is(ch_safe_color_name(5), "character")
expect_equal(length(ch_safe_color_name()), 1)
expect_equal(length(ch_safe_color_name(7)), 7)
expect_true(all(ch_safe_color_name() %in% ColorProvider$new()$safe_colors))
expect_true(all(ch_safe_color_name(7) %in% ColorProvider$new()$safe_colors))
})
test_that("ch_hex_color works", {
expect_is(ch_hex_color(), "character")
expect_is(ch_hex_color(7), "character")
expect_equal(length(ch_hex_color()), 1)
expect_equal(length(ch_hex_color(12)), 12)
hex_regex <- "^
expect_match(ch_hex_color(), hex_regex, ignore.case = TRUE)
expect_match(ch_hex_color(12), hex_regex, ignore.case = TRUE)
expect_true(all(nchar(ch_hex_color()) == 7))
expect_true(all(nchar(ch_hex_color(12)) == 7))
})
test_that("ch_safe_hex_color works", {
expect_is(ch_safe_hex_color(), "character")
expect_is(ch_safe_hex_color(7), "character")
expect_equal(length(ch_safe_hex_color()), 1)
expect_equal(length(ch_safe_hex_color(12)), 12)
safe_hex_regex <- "^
expect_match(ch_safe_hex_color(), safe_hex_regex, ignore.case = TRUE)
expect_match(ch_safe_hex_color(12), safe_hex_regex, ignore.case = TRUE)
expect_true(all(nchar(ch_safe_hex_color()) == 7))
expect_true(all(nchar(ch_safe_hex_color(12)) == 7))
})
between_0_255 <- function(x) all(0 <= x & x <= 255)
test_that("ch_rgb_color works", {
expect_is(ch_rgb_color(), "list")
expect_is(ch_rgb_color(7), "list")
expect_equal(length(ch_rgb_color()), 1)
expect_equal(length(ch_rgb_color(7)), 7)
expect_equal(vapply(ch_rgb_color(), length, integer(1)), rep(3, 1))
expect_equal(vapply(ch_rgb_color(7), length, integer(1)), rep(3, 7))
expect_true(all(vapply(ch_rgb_color(), between_0_255, logical(1))))
expect_true(all(vapply(ch_rgb_color(7), between_0_255, logical(1))))
})
test_that("ch_rgb_css_color works", {
expect_is(ch_rgb_css_color(), "character")
expect_is(ch_rgb_css_color(7), "character")
expect_equal(length(ch_rgb_css_color()), 1)
expect_equal(length(ch_rgb_css_color(7)), 7)
rgb_regex <- "^rgb\\((\\d+), (\\d+), (\\d+)\\)$"
res <- ch_rgb_css_color()
expect_match(res, rgb_regex)
expect_true(between_0_255(as.integer(gsub(rgb_regex, "\\1", res))))
expect_true(between_0_255(as.integer(gsub(rgb_regex, "\\2", res))))
expect_true(between_0_255(as.integer(gsub(rgb_regex, "\\3", res))))
res7 <- ch_rgb_css_color(7)
expect_match(res7, rgb_regex)
expect_true(between_0_255(as.integer(gsub(rgb_regex, "\\1", res7))))
expect_true(between_0_255(as.integer(gsub(rgb_regex, "\\2", res7))))
expect_true(between_0_255(as.integer(gsub(rgb_regex, "\\3", res7))))
}) |
test_that("extract single, contiguous submatrix", {
for (i in 1:n_datasets) {
Mat <- r_mats[[i]]
on_disc_mat <- cov_odms[[i]]@ondisc_matrix
for (j in 1:n_reps) {
col_idxs_range <- sample(x = 1:ncol(Mat), size = 2, replace = FALSE) %>% sort()
col_idxs <- col_idxs_range[1]:col_idxs_range[2]
row_idxs_range <- sample(x = 1:nrow(Mat), size = 2, replace = FALSE) %>% sort()
row_idxs <- row_idxs_range[1]:row_idxs_range[2]
compare_Mat_on_disc_extract(Mat = Mat, on_disc_mat = on_disc_mat, col_idxs = col_idxs, row_idxs = row_idxs)
col_idxs <- sample(col_idxs)
row_idxs <- sample(row_idxs)
compare_Mat_on_disc_extract(Mat = Mat, on_disc_mat = on_disc_mat, col_idxs = col_idxs, row_idxs = row_idxs)
}
}
})
test_that("extract multiple, contiguous submatrices", {
for (i in 1:n_datasets) {
Mat <- r_mats[[i]]
on_disc_mat <- cov_odms[[i]]@ondisc_matrix
if (nrow(Mat) >= 6 && ncol(Mat) >= 6) {
for (j in 1:n_reps) {
col_idxs_range <- sample(x = 1:ncol(Mat), size = 6, replace = FALSE) %>% sort()
col_idxs <- c(col_idxs_range[1]:col_idxs_range[2], col_idxs_range[3]:col_idxs_range[4], col_idxs_range[5]:col_idxs_range[6])
row_idxs_range <- sample(x = 1:nrow(Mat), size = 6, replace = FALSE) %>% sort()
row_idxs <- c(row_idxs_range[1]:row_idxs_range[2], row_idxs_range[3]:row_idxs_range[4], row_idxs_range[5]:row_idxs_range[6])
compare_Mat_on_disc_extract(Mat = Mat, on_disc_mat = on_disc_mat, col_idxs = col_idxs, row_idxs = row_idxs)
col_idxs <- sample(col_idxs)
row_idxs <- sample(row_idxs)
compare_Mat_on_disc_extract(Mat = Mat, on_disc_mat = on_disc_mat, col_idxs = col_idxs, row_idxs = row_idxs)
}
}
}
})
test_that("Extract arbitrary submatrices", {
for (i in 1:n_datasets) {
Mat <- r_mats[[i]]
on_disc_mat <- cov_odms[[i]]@ondisc_matrix
for (j in 1:n_reps) {
subset_size_col <- sample(1:(ceiling(ncol(Mat)/30)), 1)
subset_size_row <- sample(1:(ceiling(nrow(Mat)/30)), 1)
col_idxs <- sample(x = 1:ncol(Mat), size = subset_size_col)
row_idxs <- sample(x = 1:nrow(Mat), size = subset_size_row)
compare_Mat_on_disc_extract(Mat = Mat, on_disc_mat = on_disc_mat, col_idxs = col_idxs, row_idxs = row_idxs)
}
}
})
test_that("Illegal subsets and extracts", {
for (i in 1:n_datasets) {
on_disc_mat <- cov_odms[[i]]@ondisc_matrix
expect_error(on_disc_mat[,ncol(on_disc_mat) + 10])
expect_error(on_disc_mat[nrow(on_disc_mat) + 10,])
expect_error(on_disc_mat[[,]])
}
})
test_that("Test correct dimensions after subset", {
for (i in 1:n_datasets) {
Mat <- r_mats[[i]]
on_disc_mat <- cov_odms[[i]]@ondisc_matrix
subset_size_col <- sample(1:(ceiling(ncol(Mat)/30)), 1)
subset_size_row <- sample(1:(ceiling(nrow(Mat)/30)), 1)
col_idxs <- sample(x = 1:ncol(Mat), size = subset_size_col)
row_idxs <- sample(x = 1:nrow(Mat), size = subset_size_row)
t1 <- on_disc_mat[,col_idxs]
t2 <- Mat[,col_idxs,drop=FALSE]
expect_equal(dim(t1), dim(t2))
t1 <- on_disc_mat[,-col_idxs]
t2 <- Mat[,-col_idxs,drop=FALSE]
expect_equal(dim(t1), dim(t2))
t1 <- on_disc_mat[row_idxs,]
t2 <- Mat[row_idxs,,drop=FALSE]
expect_equal(dim(t1), dim(t2))
t1 <- on_disc_mat[-row_idxs,]
t2 <- Mat[-row_idxs,,drop=FALSE]
expect_equal(dim(t1), dim(t2))
t1 <- Mat[row_idxs, col_idxs,drop=FALSE]
t2 <- on_disc_mat[row_idxs, col_idxs]
expect_equal(dim(t1), dim(t2))
t1 <- Mat[-row_idxs, -col_idxs,drop=FALSE]
t2 <- on_disc_mat[-row_idxs, -col_idxs]
expect_equal(dim(t1), dim(t2))
}
})
test_that("Extract arbitrary submatrices after subset", {
for (i in 1:n_datasets) {
Mat <- r_mats[[i]]
on_disc_mat <- cov_odms[[i]]@ondisc_matrix
for (j in 1:n_reps) {
subset_size_col <- sample(1:(ceiling(ncol(Mat)/10)), 1)
subset_size_row <- sample(1:(ceiling(nrow(Mat)/10)), 1)
col_idxs <- sample(x = 1:ncol(Mat), size = subset_size_col)
row_idxs <- sample(x = 1:nrow(Mat), size = subset_size_row)
Mat_row_sub <- Mat[row_idxs,,drop=FALSE]
Mat_col_sub <- Mat[,col_idxs,drop=FALSE]
Mat_sub <- Mat[row_idxs, col_idxs,drop=FALSE]
on_disc_mat_row_sub <- on_disc_mat[row_idxs,]
on_disc_mat_col_sub <- on_disc_mat[,col_idxs]
on_disc_mat_sub <- on_disc_mat[row_idxs, col_idxs]
col_idxs_sub <- sample(x = 1:ncol(Mat_sub), size = sample(1:ncol(Mat_sub), 1))
row_idxs_sub <- sample(x = 1:nrow(Mat_sub), size = sample(1:nrow(Mat_sub), 1))
compare_Mat_on_disc_extract(Mat = Mat_row_sub, on_disc_mat = on_disc_mat_row_sub, col_idxs = col_idxs, row_idxs = row_idxs_sub)
compare_Mat_on_disc_extract(Mat = Mat_col_sub, on_disc_mat = on_disc_mat_col_sub, col_idxs = col_idxs_sub, row_idxs = row_idxs)
compare_Mat_on_disc_extract(Mat = Mat_sub, on_disc_mat = on_disc_mat_sub, col_idxs = col_idxs_sub, row_idxs = row_idxs_sub)
}
}
})
test_that("Subset/extract corner cases", {
for (i in 1:n_datasets) {
Mat <- r_mats[[i]]
on_disc_mat <- cov_odms[[i]]@ondisc_matrix
on_dist_mat_sub <- on_disc_mat[]
expect_identical(on_disc_mat, on_dist_mat_sub)
zero_rows <- which(Matrix::rowSums(Mat) == 0)
if (length(zero_rows) >= 1) {
idx <- zero_rows[1]
zero_extract <- as.numeric(on_disc_mat[[idx,]])
expect_equal(zero_extract, rep(0, ncol(Mat)))
}
}
}) |
allstats<-function(file.name, river.name=NULL, file.type="txt",
date.col=3, discharge.col=4, skipped.rows=28) {
cat("Starting file ", file.name, ".\n")
if (file.type=="txt") {
file<-read.table(file.name, skip=skipped.rows, sep="\t",header=F)
}
if (file.type=="csv") {
file<-read.csv(file.name, skip=skipped.rows)
}
if (file.type!="csv" & file.type!="txt") stop ("Unrecognized file type.
Use txt or csv.")
k<-c(date.col, discharge.col)
file<-file[,k]
colnames(file)<-c("date", "discharge")
n.file<-dim(file)[1]
max.nas<-n.file*.35
x<-asStreamflow(file, river.name, max.na=max.nas)
signal.stats<-fourierAnalysis(x)
hflow.stats<-sigmaHighFlows(signal.stats$signal, resid.column=10)
lflow.stats<-sigmaLowFlows(signal.stats$signal, resid.column=10)
logpearson.stats<-lp3Events(x)
ann.extremes<-annualExtremes(x)
annual.stats<-annualnoise(ann.extremes$annual.max$ldis.corrupt)
sigma.hf<-as.numeric(hflow.stats$sigma.hfb)
sigma.lf<-as.numeric(lflow.stats$sigma.lfb)
q2<-as.numeric(logpearson.stats[[1]])
q10<-as.numeric(logpearson.stats[[2]])
l2<-as.numeric(logpearson.stats[[3]])
l10<-as.numeric(logpearson.stats[[4]])
a.rms<-as.numeric(signal.stats$rms[[1]])
n.rms<-as.numeric(signal.stats$rms[[2]])
snr<-as.numeric(signal.stats$rms[[4]])
theta.d<--1*as.numeric(coefficients(signal.stats$logps.regression)[2])
name<-as.character(x$name)
theta.a<--1*as.numeric(annual.stats$reg.stats[2])
cat("File", file.name, " successful.\n")
out<-as.data.frame(cbind(a.rms,n.rms,
snr, theta.d, theta.a,sigma.hf,
sigma.lf,q2, q10, l2, l10))
row.names(out)<-name
return(out)
}
parameters.list<-function(x, names=NULL, file.type="txt", date.col=3,
dis.col=4,skipped.rows=28) {
n.files<-length(x)
files<-x
if( !is.null(names)) name.vec<-names
if (is.null(names)) name.vec<-as.character(1:n.files)
all.out<-NULL
filetype<-file.type
datecol<-date.col
discol<-dis.col
skipped<-skipped.rows
for (i in 1:n.files) {
output<-tryCatch(allstats(files[i], name.vec[i], file.type=filetype, date.col=datecol,
discharge.col=discol,skipped.rows=skipped),
error=function(ex){
cat("Error in file ", files[i])
print(ex)
return(rep(NA,11))})
all.out<-rbind(all.out, output)
}
all.out<-as.data.frame(all.out)
return(all.out)
} |
.xyvBuf <- function(object, xy, buffer, fun=NULL, na.rm=TRUE, layer, nl, cellnumbers=FALSE, small=FALSE, onlycells=FALSE) {
buffer <- abs(buffer)
if (length(buffer == 1)) {
buffer <- rep(buffer, times=nrow(xy))
} else if (length(buffer) != nrow(xy) | ! is.vector(buffer) ) {
stop('buffer should be a single value or a vector of length==nrow(xy)')
}
buffer[is.na(buffer)] <- 0
if (onlycells) {
cellnumbers <- TRUE
fun <- NULL
small <- TRUE
object <- raster(object)
} else if (! is.null(fun)) {
cellnumbers <- FALSE
}
cv <- list()
obj <- raster(object)
if (couldBeLonLat(obj)) {
bufy <- buffer / 111319.5
ymx <- pmin(90, xy[,2] + bufy)
ymn <- pmax(-90, xy[,2] - bufy)
bufx1 <- buffer / pointDistance(cbind(0, ymx), cbind(1, ymx), lonlat=TRUE)
bufx2 <- buffer / pointDistance(cbind(0, ymn), cbind(1, ymn), lonlat=TRUE)
bufx <- pmax(bufx1, bufx2)
cn <- colFromX(obj, xy[,1]-bufx)
cx <- colFromX(obj, xy[,1]+bufx)
cn[is.na(cn) & (xy[,1]-bufx <= xmin(obj) & xy[,1]+bufx >= xmin(obj))] <- 1
cx[is.na(cx) & (xy[,1]-bufx <= xmax(obj) & xy[,1]+bufx > xmax(obj))] <- ncol(obj)
rn <- rowFromY(obj, xy[,2]+bufy)
rx <- rowFromY(obj, xy[,2]-bufy)
rn[is.na(rn) & (xy[,2]-bufy <= ymax(obj) & xy[,2]+bufy >= ymax(obj))] <- 1
rx[is.na(rx) & (xy[,2]-bufy <= ymin(obj) & xy[,2]+bufy >= ymin(obj))] <- nrow(obj)
for (i in 1:nrow(xy)) {
s <- sum(rn[i], rx[i], cn[i], cx[i])
if (is.na(s)) {
cv[[i]] <- NA
} else {
if (onlycells) {
value <- i
} else {
value <- getValuesBlock(object, rn[i], rx[i]-rn[i]+1, cn[i], cx[i]-cn[i]+1)
}
cell <- cellFromRowColCombine(obj, rn[i]:rx[i], cn[i]:cx[i])
coords <- xyFromCell(obj, cell)
if (cellnumbers) {
pd <- cbind(pointDistance(xy[i,], coords, lonlat=TRUE), cell, value)
} else {
pd <- cbind(pointDistance(xy[i,], coords, lonlat=TRUE), value)
}
if (nrow(pd) > 1) {
v <- pd[pd[,1] <= buffer[i], -1]
if (NROW(v) == 0) {
cv[[i]] <- pd[which.min(pd[,1]), -1]
} else {
cv[[i]] <- v
}
} else {
cv[[i]] <- pd[,-1]
}
}
}
} else {
cn <- colFromX(obj, xy[,1]-buffer)
cx <- colFromX(obj, xy[,1]+buffer)
cn[is.na(cn) & (xy[,1]-buffer <= xmin(obj) & xy[,1]+buffer >= xmin(obj))] <- 1
cx[is.na(cx) & (xy[,1]-buffer <= xmax(obj) & xy[,1]+buffer > xmax(obj))] <- ncol(obj)
rn <- rowFromY(obj, xy[,2]+buffer)
rx <- rowFromY(obj, xy[,2]-buffer)
rn[is.na(rn) & (xy[,2]-buffer <= ymax(obj) & xy[,2]+buffer >= ymax(obj))] <- 1
rx[is.na(rx) & (xy[,2]-buffer <= ymin(obj) & xy[,2]+buffer >= ymin(obj))] <- nrow(obj)
if (.doCluster()) {
cl <- getCluster()
on.exit( returnCluster() )
nodes <- min(nrow(xy), length(cl))
message('Using cluster with ', nodes, ' nodes')
utils::flush.console()
parallel::clusterExport(cl, c('object', 'obj', 'cellnumbers'), envir=environment())
clFun2 <- function(i, xy, rn, rx, cn, cx) {
s <- sum(rn, rx, cn, cx)
if (is.na(s)) {
return(NA)
} else {
if (onlycells) {
value <- i
} else {
value <- getValuesBlock(object, rn, rx-rn+1, cn, cx-cn+1)
}
cell <- cellFromRowColCombine(obj, rn:rx, cn:cx)
coords <- xyFromCell(obj, cell)
if (cellnumbers) {
pd <- cbind(pointDistance(xy, coords, lonlat=TRUE), cell, value)
} else {
pd <- cbind(pointDistance(xy, coords, lonlat=TRUE), value)
}
if (nrow(pd) > 1) {
pd <- pd[pd[,1] <= buffer[i], -1]
} else {
pd <- pd[,-1]
}
return(pd)
}
}
.sendCall <- eval( parse( text="parallel:::sendCall") )
for (i in 1:nodes) {
.sendCall(cl[[i]], clFun2, list(i, xy[i, ,drop=FALSE], rn[i], rx[i], cn[i], cx[i]), tag=i)
}
for (i in 1:nrow(xy)) {
d <- .recvOneData(cl)
if (! d$value$success) {
print(d)
stop('cluster error')
} else {
cv[[i]] <- d$value$value
}
ni <- nodes + i
if (ni <= nrow(xy)) {
.sendCall(cl[[d$node]], clFun2, list(ni, xy[i, ,drop=FALSE], rn[i], rx[i], cn[i], cx[i]), tag=i)
}
}
} else {
for (i in 1:nrow(xy)) {
s <- sum(rn[i], rx[i], cn[i], cx[i])
if (is.na(s)) {
cv[[i]] <- NA
} else {
if (onlycells) {
value <- i
} else {
value <- getValuesBlock(object, rn[i], rx[i]-rn[i]+1, cn[i], cx[i]-cn[i]+1)
}
cell <- cellFromRowColCombine(obj, rn[i]:rx[i], cn[i]:cx[i])
coords <- xyFromCell(obj, cell)
if (cellnumbers) {
pd <- cbind(pointDistance(xy[i,], coords, lonlat=FALSE), cell, value)
} else {
pd <- cbind(pointDistance(xy[i,], coords, lonlat=FALSE), value)
}
if (nrow(pd) > 1) {
cv[[i]] <- pd[pd[,1] <= buffer[i], -1]
} else {
cv[[i]] <- pd[,-1]
}
}
}
}
}
if (small) {
i <- sapply(cv, function(x) length(x)==0)
if (any(i)) {
i <- which(i)
if (onlycells) {
vv <- cbind(cellFromXY(object, xy[i, ,drop=FALSE]), NA)
} else {
vv <- extract(object, xy[i, ,drop=FALSE], na.rm=na.rm, layer=layer, nl=nl, cellnumbers=cellnumbers)
}
if (NCOL(vv) > 1) {
for (j in 1:length(i)) {
cv[[ i[j] ]] <- vv[j, ]
}
} else {
for (j in 1:length(i)) {
cv[[ i[j] ]] <- vv[j]
}
}
}
}
nls <- nlayers(object)
nms <- names(object)
if (nls > 1) {
if (layer > 1 | nl < nls) {
lyrs <- layer:(layer+nl-1)
nms <- nms[ lyrs ]
cv <- lapply(cv, function(x) x[, lyrs ])
}
}
if (! is.null(fun)) {
fun <- match.fun(fun)
if (na.rm) {
fun2 <- function(x){
x <- stats::na.omit(x)
if (length(x) > 0) { return(fun(x))
} else { return(NA)
}
}
} else {
fun2 <- fun
}
if (nl == 1) {
cv <- unlist(lapply(cv, fun2), use.names = FALSE)
} else {
np <- length(cv)
cv <- lapply(cv, function(x) {
if (!is.matrix(x)) { x <- t(matrix(x)) }
apply(x, 2, fun2)}
)
cv <- matrix(unlist(cv, use.names = FALSE), nrow=np, byrow=TRUE)
colnames(cv) <- nms
}
}
return(cv)
}
|
NULL
setClass(
Class="CompositeModel",
representation=representation(
variable.independency = "logical",
component.independency = "logical"
),
contains=c("Model"),
prototype=prototype(
variable.independency = logical(0),
component.independency = logical(0)
),
validity=function(object){
vcf<-c("Heterogeneous_pk_E_L_B",
"Heterogeneous_pk_E_Lk_B",
"Heterogeneous_pk_E_L_Bk",
"Heterogeneous_pk_E_Lk_Bk")
vce<-c("Heterogeneous_p_E_L_B",
"Heterogeneous_p_E_Lk_B",
"Heterogeneous_p_E_L_Bk",
"Heterogeneous_p_E_Lk_Bk")
f<-c("Heterogeneous_pk_Ekj_L_B",
"Heterogeneous_pk_Ekj_Lk_B",
"Heterogeneous_pk_Ekj_L_Bk",
"Heterogeneous_pk_Ekj_Lk_Bk",
"Heterogeneous_pk_Ekjh_L_B",
"Heterogeneous_pk_Ekjh_Lk_B",
"Heterogeneous_pk_Ekjh_L_Bk",
"Heterogeneous_pk_Ekjh_Lk_Bk")
e<-c("Heterogeneous_p_Ekj_L_B",
"Heterogeneous_p_Ekj_Lk_B",
"Heterogeneous_p_Ekj_L_Bk",
"Heterogeneous_p_Ekj_Lk_Bk",
"Heterogeneous_p_Ekjh_L_B",
"Heterogeneous_p_Ekjh_Lk_B",
"Heterogeneous_p_Ekjh_L_Bk",
"Heterogeneous_p_Ekjh_Lk_Bk")
cf<-c("Heterogeneous_pk_Ej_L_B",
"Heterogeneous_pk_Ej_Lk_B",
"Heterogeneous_pk_Ej_L_Bk",
"Heterogeneous_pk_Ej_Lk_Bk")
ce<-c("Heterogeneous_p_Ej_L_B",
"Heterogeneous_p_Ej_Lk_B",
"Heterogeneous_p_Ej_L_Bk",
"Heterogeneous_p_Ej_Lk_Bk")
vf<-c("Heterogeneous_pk_Ek_L_B",
"Heterogeneous_pk_Ek_Lk_B",
"Heterogeneous_pk_Ek_L_Bk",
"Heterogeneous_pk_Ek_Lk_Bk")
ve<-c("Heterogeneous_p_Ek_L_B",
"Heterogeneous_p_Ek_Lk_B",
"Heterogeneous_p_Ek_L_Bk",
"Heterogeneous_p_Ek_Lk_Bk")
all.free<-c(vcf,f,cf,vf)
all.equal<-c(vce,e,ce,ve)
variable.free<-c(vcf,vf)
variable.equal<-c(vce,ve)
variable<-c(variable.free,variable.equal)
component.free<-c(vcf,cf)
component.equal<-c(vce,ce)
component<-c(component.free,component.equal)
all=c(all.free,all.equal)
if ( sum(object@listModels %in% all) != length(object@listModels) )
stop("At least one model is not a valid model. See ?mixmodCompositeModel for the list of all composite models.")
if ( [email protected] & [email protected] )
stop("equal.proportions and free.porportions cannot be both as FALSE !")
if ( [email protected] & (sum(object@listModels %in% all.free)>0) )
stop("At least one model has a free proportions but free.proportions is set as FALSE. See ?mixmodCompositeModel for the list of models with equal proportions.")
if ( [email protected] & (sum(object@listModels %in% all.equal)>0) )
stop("At least one model has an equal proportions but equal.proportions is set as FALSE. See ?mixmodCompositeModel for the list of models with free proportions.")
if ( length([email protected]) ){
if ( [email protected] & sum(object@listModels %in% variable) != length(object@listModels) )
stop("At least one model is not independent of the variable j. See ?mixmodCompositeModel for the list of all composite models.")
}
if ( length([email protected]) ){
if ( [email protected] & sum(object@listModels %in% component) != length(object@listModels) )
stop("At least one model is not independent of the variable j. See ?mixmodCompositeModel for the list of all composite models.")
}
}
)
setMethod(
f="initialize",
signature=c("CompositeModel"),
definition=function(.Object, listModels, free.proportions, equal.proportions, variable.independency, component.independency){
vcf<-c("Heterogeneous_pk_E_L_B",
"Heterogeneous_pk_E_Lk_B",
"Heterogeneous_pk_E_L_Bk",
"Heterogeneous_pk_E_Lk_Bk")
vce<-c("Heterogeneous_p_E_L_B",
"Heterogeneous_p_E_Lk_B",
"Heterogeneous_p_E_L_Bk",
"Heterogeneous_p_E_Lk_Bk")
f<-c("Heterogeneous_pk_Ekj_L_B",
"Heterogeneous_pk_Ekj_Lk_B",
"Heterogeneous_pk_Ekj_L_Bk",
"Heterogeneous_pk_Ekj_Lk_Bk",
"Heterogeneous_pk_Ekjh_L_B",
"Heterogeneous_pk_Ekjh_Lk_B",
"Heterogeneous_pk_Ekjh_L_Bk",
"Heterogeneous_pk_Ekjh_Lk_Bk")
e<-c("Heterogeneous_p_Ekj_L_B",
"Heterogeneous_p_Ekj_Lk_B",
"Heterogeneous_p_Ekj_L_Bk",
"Heterogeneous_p_Ekj_Lk_Bk",
"Heterogeneous_p_Ekjh_L_B",
"Heterogeneous_p_Ekjh_Lk_B",
"Heterogeneous_p_Ekjh_L_Bk",
"Heterogeneous_p_Ekjh_Lk_Bk")
cf<-c("Heterogeneous_pk_Ej_L_B",
"Heterogeneous_pk_Ej_Lk_B",
"Heterogeneous_pk_Ej_L_Bk",
"Heterogeneous_pk_Ej_Lk_Bk")
ce<-c("Heterogeneous_p_Ej_L_B",
"Heterogeneous_p_Ej_Lk_B",
"Heterogeneous_p_Ej_L_Bk",
"Heterogeneous_p_Ej_Lk_Bk")
vf<-c("Heterogeneous_pk_Ek_L_B",
"Heterogeneous_pk_Ek_Lk_B",
"Heterogeneous_pk_Ek_L_Bk",
"Heterogeneous_pk_Ek_Lk_Bk")
ve<-c("Heterogeneous_p_Ek_L_B",
"Heterogeneous_p_Ek_Lk_B",
"Heterogeneous_p_Ek_L_Bk",
"Heterogeneous_p_Ek_Lk_Bk")
all.free<-c(vcf,f,cf,vf)
all.equal<-c(vce,e,ce,ve)
variable.free<-c(vcf,vf)
variable.equal<-c(vce,ve)
variable<-c(variable.free,variable.equal)
component.free<-c(vcf,cf)
component.equal<-c(vce,ce)
component<-c(component.free,component.equal)
if ( !missing(listModels) ){
.Object@listModels <- listModels
if ( missing(free.proportions) ){
if ( sum(listModels %in% all.free) ){ [email protected]<-TRUE }
else{ [email protected]<-FALSE }
}
else{ [email protected]<-free.proportions }
if ( missing(equal.proportions) ){
if ( sum(listModels %in% all.equal) ){ [email protected]<-TRUE }
else{ [email protected]<-FALSE }
}
else{ [email protected]<-equal.proportions }
if ( missing(variable.independency) ){
if ( sum(listModels %in% variable) == length(listModels) ){ [email protected]<-TRUE }
}
else{ [email protected]<-variable.independency }
if ( missing(component.independency) ){
if ( sum(listModels %in% component) == length(listModels) ){ [email protected]<-TRUE }
}
else{ [email protected]<-component.independency }
}
else{
if ( missing(free.proportions) ){ [email protected]<-TRUE }
else{ [email protected]<-free.proportions }
if ( missing(equal.proportions) ){ [email protected]<-TRUE }
else{ [email protected]<-equal.proportions }
list<-character(0)
if ( !missing(variable.independency) & !missing(component.independency)){
if ( variable.independency & component.independency){
if ( [email protected] ){ list<-c(list,vcf) }
if ( [email protected] ){ list<-c(list,vce) }
}else if ( !variable.independency & !component.independency){
if ( [email protected] ){ list<-c(list,f) }
if ( [email protected] ){ list<-c(list,e) }
}else if ( !variable.independency & component.independency){
if ( [email protected] ){ list<-c(list,cf) }
if ( [email protected] ){ list<-c(list,ce) }
}else if ( variable.independency & !component.independency){
if ( [email protected] ){ list<-c(list,vf) }
if ( [email protected] ){ list<-c(list,ve) }
}
[email protected] <- component.independency
[email protected] <- variable.independency
}
else if ( !missing(component.independency) ){
if ( component.independency ){
if ( [email protected] ){ list<-c(list,component.free) }
if ( [email protected] ){ list<-c(list,component.equal) }
}else{
if ( [email protected] ){ list<-c(list,f,vf) }
if ( [email protected] ){ list<-c(list,e,ve) }
}
[email protected]<-component.independency
[email protected] <- logical(0)
}
else if ( !missing(variable.independency) ){
if ( variable.independency ){
if ( [email protected] ){ list<-c(list,variable.free) }
if ( [email protected] ){ list<-c(list,variable.equal) }
}else{
if ( [email protected] ){ list<-c(list,f,cf) }
if ( [email protected] ){ list<-c(list,e,ce) }
}
[email protected] <- logical(0)
[email protected] <- variable.independency
}
else{
if ( [email protected] ){ list<-c(list,all.free) }
if ( [email protected] ){ list<-c(list,all.equal) }
[email protected] <- logical(0)
[email protected] <- logical(0)
}
.Object@listModels<-list
}
validObject(.Object)
return(.Object)
}
)
mixmodCompositeModel<- function(listModels=NULL, free.proportions=TRUE, equal.proportions=TRUE, variable.independency=NULL, component.independency=NULL ){
if ( !is.null(listModels) ){
new("CompositeModel", listModels=listModels)
}
else{
if ( !is.null(variable.independency) & !is.null(component.independency) ){
new("CompositeModel", free.proportions=free.proportions, equal.proportions=equal.proportions, variable.independency=variable.independency, component.independency=component.independency)
}
else if ( !is.null(variable.independency) & is.null(component.independency) ){
new("CompositeModel", free.proportions=free.proportions, equal.proportions=equal.proportions, variable.independency=variable.independency)
}
else if ( is.null(variable.independency) & !is.null(component.independency) ){
new("CompositeModel", free.proportions=free.proportions, equal.proportions=equal.proportions, component.independency=component.independency)
}
else{
new("CompositeModel", free.proportions=free.proportions, equal.proportions=equal.proportions)
}
}
}
composeModelName <- function (g_modelname,m_modelname) {
gaussianmodel = mixmodGaussianModel(listModels = g_modelname)
multinomialmodel = mixmodMultinomialModel(listModels = m_modelname)
if(gaussianmodel["free.proportions"]!=multinomialmodel["free.proportions"] & gaussianmodel["equal.proportions"]!=multinomialmodel["equal.proportions"])
stop("Proportions should either be free or equal for both the models.")
if(gaussianmodel["family"]!="diagonal")
stop("In heterogeneous case, Gaussian model can only belong diagonal family.")
if(gaussianmodel["free.proportions"])
return(paste("Heterogeneous_",substr(m_modelname,8,nchar(m_modelname)),substr(g_modelname,12,nchar(g_modelname)),sep=""))
else
return(paste("Heterogeneous_",substr(m_modelname,8,nchar(m_modelname)),substr(g_modelname,11,nchar(g_modelname)),sep=""))
}
setMethod(
f="[",
signature(x = "CompositeModel"),
definition=function(x,i,j,drop){
if ( missing(j) ){
switch(EXPR=i,
"listModels"={return(x@listModels)},
"free.proportions"={return([email protected])},
"equal.proportions"={return([email protected])},
"variable.independency"={return([email protected])},
"component.independency"={return([email protected])},
stop("This attribute doesn't exist !")
)
}else{
switch(EXPR=i,
"listModels"={return(x@listModels[j])},
stop("This attribute doesn't exist !")
)
}
}
)
setReplaceMethod(
f="[",
signature(x = "CompositeModel"),
definition=function(x,i,j,value){
if ( missing(j) ){
switch(EXPR=i,
"listModels"={x@listModels<-value},
"free.proportions"={[email protected]<-value},
"equal.proportions"={[email protected]<-value},
"variable.independency"={[email protected]<-value},
"component.independency"={[email protected]<-value},
stop("This attribute doesn't exist !")
)
}else{
switch(EXPR=i,
"listModels"={x@listModels[j]<-value},
stop("This attribute doesn't exist !")
)
}
validObject(x)
return(x)
}
) |
get_problem_matrix <- function(linOps, id_to_col = integer(0), constr_offsets = integer(0)) {
cvxCanon <- CVXcanon$new()
lin_vec <- CVXcanon.LinOpVector$new()
id_to_col_C <- id_to_col
storage.mode(id_to_col_C) <- "integer"
tmp <- R6List$new()
for (lin in linOps) {
tree <- build_lin_op_tree(lin, tmp)
tmp$append(tree)
lin_vec$push_back(tree)
}
if (typeof(constr_offsets) != "integer") {
stop("get_problem_matrix: expecting integer vector for constr_offsets")
}
if (length(constr_offsets) == 0)
problemData <- cvxCanon$build_matrix(lin_vec, id_to_col_C)
else {
constr_offsets_C <- constr_offsets
storage.mode(constr_offsets_C) <- "integer"
problemData <- cvxCanon$build_matrix(lin_vec, id_to_col_C, constr_offsets_C)
}
list(V = problemData$getV(), I = problemData$getI(), J = problemData$getJ(),
const_vec = matrix(problemData$getConstVec(), ncol = 1))
}
format_matrix <- function(matrix, format='dense') {
if(is.bigq(matrix) || is.bigz(matrix)) {
matdbl <- matrix(sapply(matrix, as.double))
dim(matdbl) <- dim(matrix)
matrix <- matdbl
}
if (format == 'dense') {
as.matrix(matrix)
} else if (format == 'sparse') {
Matrix::Matrix(matrix, sparse = TRUE)
} else if (format == 'scalar') {
as.matrix(matrix)
} else {
stop(sprintf("format_matrix: format %s unknown", format))
}
}
set_matrix_data <- function(linC, linR) {
if (is.list(linR$data) && linR$data$class == "LinOp") {
if (linR$data$type == 'sparse_const') {
linC$sparse_data <- format_matrix(linR$data$data, 'sparse')
} else if (linR$data$type == 'dense_const') {
linC$dense_data <- format_matrix(linR$data$data)
} else {
stop(sprintf("set_matrix_data: data.type %s unknown", linR$data$type))
}
} else {
if (linR$type == 'sparse_const') {
linC$sparse_data <- format_matrix(linR$data, 'sparse')
} else {
linC$dense_data <- format_matrix(linR$data)
}
}
}
set_slice_data <- function(linC, linR) {
for (i in seq.int(length(linR$data) - 1L)) {
sl <- linR$data[[i]]
linC$slice_push_back(sl - 1)
}
}
build_lin_op_tree <- function(root_linR, tmp, verbose = FALSE) {
Q <- Deque$new()
root_linC <- CVXcanon.LinOp$new()
Q$append(list(linR = root_linR, linC = root_linC))
while(Q$length() > 0) {
node <- Q$popleft()
linR <- node$linR
linC <- node$linC
for(argR in linR$args) {
tree <- CVXcanon.LinOp$new()
tmp$append(tree)
Q$append(list(linR = argR, linC = tree))
linC$args_push_back(tree)
}
linC$type <- toupper(linR$type)
linC$size_push_back(as.integer(linR$dim[1]))
linC$size_push_back(as.integer(linR$dim[2]))
if(!is.null(linR$data)) {
if (length(linR$data) == 3L && linR$data[[3L]] == 'key') {
set_slice_data(linC, linR)
} else if(is.numeric(linR$data) || is.integer(linR$data))
linC$dense_data <- format_matrix(linR$data, 'scalar')
else if(linR$data$class == 'LinOp' && linR$data$type == 'scalar_const')
linC$dense_data <- format_matrix(linR$data$data, 'scalar')
else
set_matrix_data(linC, linR)
}
}
root_linC
} |
rm(list=ls())
setwd("C:/Users/Tom/Documents/Kaggle/Santander")
library(data.table)
library(bit64)
library(xgboost)
library(stringr)
submissionDate <- "06-12-2016"
loadFile <- "xgboost weighted stacked 1, linear increase jun15 times6 back 11-0 no zeroing, exponential normalisation joint"
submissionFile <- "xgboost weighted stacked 1, linear increase jun15 times6 back 11-0 no zeroing, exponential normalisation joint"
targetDate <- "12-11-2016"
trainModelsFolder <- "trainFixedLag5TrainAll"
trainAll <- grepl("TrainAll", trainModelsFolder)
testFeaturesFolder <- "testFixedLag5"
loadPredictions <- FALSE
loadBaseModelPredictions <- TRUE
savePredictions <- TRUE
saveBaseModelPredictions <- TRUE
savePredictionsBeforeNormalisation <- TRUE
dropFoldModels <- FALSE
foldRelativeWeight <- 0.8
normalizeProdProbs <- TRUE
normalizeMode <- c("additive", "linear", "exponential")[3]
additiveNormalizeProds <- NULL
fractionPosFlankUsers <- 0.035
expectedCountPerPosFlank <- 1.25
marginalNormalisation <- c("linear", "exponential")[2]
weightSum <- 1
predictSubset <- FALSE
predictionsFolder <- "Predictions"
zeroTargets <- NULL
source("Common/exponentialNormaliser.R")
source("Common/getModelWeights.R")
dateTargetWeights <- readRDS(file.path(getwd(), "Model weights", targetDate,
"model weights second.rds"))
predictionsPath <- file.path(getwd(), "Submission", submissionDate,
predictionsFolder)
dir.create(predictionsPath, showWarnings = FALSE)
if(saveBaseModelPredictions && !loadBaseModelPredictions){
baseModelPredictionsPath <- file.path(predictionsPath, submissionFile)
dir.create(baseModelPredictionsPath, showWarnings = FALSE)
} else{
if(loadBaseModelPredictions){
baseModelPredictionsPath <- file.path(predictionsPath, loadFile)
}
}
if(loadPredictions){
rawPredictionsPath <- file.path(predictionsPath,
paste0("prevNorm", loadFile, ".rds"))
} else{
rawPredictionsPath <- file.path(predictionsPath,
paste0("prevNorm", submissionFile, ".rds"))
}
posFlankClientsFn <- file.path(getwd(), "Feature engineering", targetDate,
"positive flank clients.rds")
posFlankClients <- readRDS(posFlankClientsFn)
modelsBasePath <- file.path(getwd(), "Second level learners", "Models",
targetDate, trainModelsFolder)
modelGroups <- list.dirs(modelsBasePath)[-1]
modelGroups <- modelGroups[!grepl("Manual tuning", modelGroups)]
modelGroups <- modelGroups[!grepl("no fold BU", modelGroups)]
nbModelGroups <- length(modelGroups)
baseModelInfo <- NULL
baseModels <- list()
for(i in 1:nbModelGroups){
modelGroup <- modelGroups[i]
slashPositions <- gregexpr("\\/", modelGroup)[[1]]
modelGroupExtension <- substring(modelGroup,
1 + slashPositions[length(slashPositions)])
modelGroupFiles <- list.files(modelGroup)
modelGroupFiles <- modelGroupFiles[!grepl("no fold BU", modelGroupFiles)]
if(dropFoldModels){
modelGroupFiles <- modelGroupFiles[!grepl("Fold", modelGroupFiles)]
}
nbModels <- length(modelGroupFiles)
monthsBack <- suppressWarnings(
as.numeric(substring(gsub("Lag.*$", "", modelGroupExtension), 5)))
lag <- suppressWarnings(as.numeric(gsub("^.*Lag", "", modelGroupExtension)))
if(nbModels>0){
for(j in 1:nbModels){
modelGroupFile <- modelGroupFiles[j]
modelInfo <- readRDS(file.path(modelGroup, modelGroupFile))
targetProduct <- modelInfo$targetVar
relativeWeight <- getModelWeights(monthsBack, targetProduct,
dateTargetWeights)
isFold <- grepl("Fold", modelGroupFile)
prodMonthFiles <- modelGroupFiles[grepl(targetProduct, modelGroupFiles)]
nbFoldsProd <- sum(grepl("Fold", prodMonthFiles))
prodMonthFiles <- modelGroupFiles[grepl(targetProduct, modelGroupFiles)]
nbFoldsProd <- sum(grepl("Fold", prodMonthFiles))
foldBaseWeight <- foldRelativeWeight * 4 / nbFoldsProd
if(!is.finite(foldBaseWeight)){
foldBaseWeight <- 0
}
productMonthSum <- 1 + nbFoldsProd*foldBaseWeight
if(isFold){
foldModelWeight <- foldBaseWeight/productMonthSum
} else{
foldModelWeight <- 1/productMonthSum
}
baseModelInfo <- rbind(baseModelInfo,
data.table(
modelGroupExtension = modelGroupExtension,
targetProduct = targetProduct,
monthsBack = monthsBack,
modelLag = lag,
relativeWeight = relativeWeight * foldModelWeight)
)
baseModels <- c(baseModels, list(modelInfo))
}
}
}
baseModelInfo[, modelId := 1:nrow(baseModelInfo)]
if(all(is.na(baseModelInfo$modelLag))){
nbGroups <- length(unique(baseModelInfo$modelGroupExtension))
baseModelInfo <- baseModelInfo[order(targetProduct), ]
baseModelInfo$modelLag <- 5
baseModelInfo$relativeWeight <- 1
monthsBackLags <- rep(defaultTestLag, nbGroups)
nbMarginalLags <- length(monthsBackLags)
nbConditionalLags <- 1
} else{
monthsBackLags <- rev(sort(unique(baseModelInfo$modelLag)))
nbMarginalLags <- length(monthsBackLags)
nbConditionalLags <- length(monthsBackLags)
}
uniqueBaseModels <- sort(unique(baseModelInfo$targetProduct))
for(i in 1:length(uniqueBaseModels)){
productIds <- baseModelInfo$targetProduct==uniqueBaseModels[i]
productWeightSum <- baseModelInfo[productIds, sum(relativeWeight)]
normalizeWeightRatio <- weightSum/productWeightSum
baseModelInfo[productIds, relativeWeight := relativeWeight*
normalizeWeightRatio]
}
baseModelInfo <- baseModelInfo[order(monthsBack), ]
baseModelNames <- unique(baseModelInfo[monthsBack==0, targetProduct])
testDataLag <- readRDS(file.path(getwd(), "Second level learners",
"Features", targetDate, testFeaturesFolder,
"Lag5.rds"))
if(predictSubset){
predictSubsetIds <- sort(sample(1:nrow(testDataLag), predictSubsetCount))
testDataLag <- testDataLag[predictSubsetIds]
}
testDataPosFlank <- testDataLag$ncodpers %in% posFlankClients
trainFn <- "trainFixedLag5/Back11Lag5.rds"
colOrderData <- readRDS(file.path(getwd(), "Second level learners",
"Features", targetDate, trainFn))
targetCols <- grep("^ind_.*_ult1$", names(colOrderData), value=TRUE)
rm(colOrderData)
gc()
nbBaseModels <- length(targetCols)
countContributions <- readRDS(file.path(getwd(), "Feature engineering",
targetDate,
"monthlyRelativeProductCounts.rds"))
if(!trainAll){
posFlankModelInfo <- baseModelInfo[targetProduct=="hasNewProduct"]
newProdPredictions <- rep(0, nrow(testDataLag))
if(nrow(posFlankModelInfo) != nbMarginalLags) browser()
for(i in 1:nbMarginalLags){
cat("Generating new product predictions for lag", i, "of", nbMarginalLags,
"\n")
lag <- posFlankModelInfo[i, modelLag]
weight <- posFlankModelInfo[i, relativeWeight]
newProdModel <- baseModels[[posFlankModelInfo[i, modelId]]]
testDataLag <- readRDS(file.path(getwd(), "Feature engineering", targetDate,
testFeaturesFolder,
paste0("Lag", lag, " features.rds")))
if(predictSubset){
testDataLag <- testDataLag[predictSubsetIds]
}
predictorData <- testDataLag[, newProdModel$predictors, with=FALSE]
predictorDataM <- data.matrix(predictorData)
rm(predictorData)
gc()
newProdPredictionsLag <- predict(newProdModel$model, predictorDataM)
newProdPredictions <- newProdPredictions + newProdPredictionsLag*weight
}
newProdPredictions <- newProdPredictions/weightSum
meanGroupPredsMayFlag <-
c(mean(newProdPredictions[testDataLag$hasMay15Data==0]),
mean(newProdPredictions[testDataLag$hasMay15Data==1]))
meanGroupPredsPosFlank <- c(mean(newProdPredictions[!testDataPosFlank]),
mean(newProdPredictions[testDataPosFlank]))
expectedPosFlanks <- sum(newProdPredictions)
leaderboardPosFlanks <- fractionPosFlankUsers*nrow(testDataLag)
normalisedProbRatio <- leaderboardPosFlanks/expectedPosFlanks
cat("Expected/leaderboard positive flank ratio",
round(1/normalisedProbRatio, 2), "\n")
if(marginalNormalisation == "linear"){
newProdPredictions <- newProdPredictions * normalisedProbRatio
} else{
newProdPredictions <- probExponentNormaliser(newProdPredictions,
normalisedProbRatio)
}
} else{
newProdPredictions <- rep(1, nrow(testDataLag))
}
if(loadPredictions && file.exists(rawPredictionsPath)){
allPredictions <- readRDS(rawPredictionsPath)
} else{
allPredictions <- NULL
for(lagId in 1:nbConditionalLags){
cat("\nGenerating positive flank predictions for lag", lagId, "of",
nbConditionalLags, "@", as.character(Sys.time()), "\n\n")
lag <- monthsBackLags[lagId]
testDataLag <- readRDS(file.path(getwd(), "Second level learners",
"Features", targetDate, testFeaturesFolder,
paste0("Lag", lag, ".rds")))
if(predictSubset){
testDataLag <- testDataLag[predictSubsetIds]
}
for(i in 1:nbBaseModels){
targetVar <- targetCols[i]
targetModelIds <- baseModelInfo[targetProduct==targetVar &
modelLag==lag, modelId]
cat("Generating test predictions for model", i, "of", nbBaseModels, "\n")
if(exists("baseModelPredictionsPath")){
baseModelPredPath <- file.path(baseModelPredictionsPath,
paste0(targetVar, " Lag ", lag, ".rds"))
} else{
baseModelPredPath <- ""
}
foldWeights <- baseModelInfo[modelId %in% targetModelIds,
relativeWeight]
weight <- sum(foldWeights)
if(loadBaseModelPredictions && file.exists(baseModelPredPath)){
predictionsDT <- readRDS(baseModelPredPath)
} else{
if(targetVar %in% zeroTargets || weight <= 0){
predictions <- rep(0, nrow(testDataLag))
} else{
nbTargetModelFolds <- length(targetModelIds)
foldPredictions <- rep(0, nrow(testDataLag))
alreadyOwned <- is.na(testDataLag[[paste0(targetVar, "Lag1")]]) |
testDataLag[[paste0(targetVar, "Lag1")]] == 1
predictorData <-
testDataLag[!alreadyOwned,
baseModels[[targetModelIds[1]]]$predictors, with=FALSE]
predictorDataM <- data.matrix(predictorData)
rm(predictorData)
gc()
for(fold in 1:nbTargetModelFolds){
targetModelId <- targetModelIds[fold]
targetModel <- baseModels[[targetModelId]]
weightFold <- foldWeights[fold]
if(targetModel$targetVar != targetVar) browser()
predictionsPrevNotOwnedFold <- predict(targetModel$model,
predictorDataM)
foldPredictions[!alreadyOwned] <- foldPredictions[!alreadyOwned] +
predictionsPrevNotOwnedFold*weightFold
}
predictions <- foldPredictions/weight
predictions[alreadyOwned] <- 0
}
predictionsDT <- data.table(ncodpers = testDataLag$ncodpers,
predictions = predictions,
product = targetVar)
}
predictionsDT[, weightedPrediction :=
predictionsDT$predictions*weight]
if(targetVar %in% allPredictions$product){
allPredictions[product==targetVar, weightedPrediction:=
weightedPrediction +
predictionsDT$weightedPrediction]
} else{
allPredictions <- rbind(allPredictions, predictionsDT)
}
if(saveBaseModelPredictions && !loadBaseModelPredictions){
predictionsDT[, weightedPrediction:=NULL]
saveRDS(predictionsDT, baseModelPredPath)
}
}
}
allPredictions[, prediction := weightedPrediction / weightSum]
allPredictions[, weightedPrediction := NULL]
allPredictions[, predictions := NULL]
if(savePredictionsBeforeNormalisation){
saveRDS(allPredictions, file=rawPredictionsPath)
}
}
probMultipliers <- rep(NA, nbBaseModels)
if(normalizeProdProbs){
for(i in 1:nbBaseModels){
cat("Normalizing product predictions", i, "of", nbBaseModels, "\n")
targetVar <- targetCols[i]
alreadyOwned <- is.na(testDataLag[[paste0(targetVar, "Lag1")]]) |
testDataLag[[paste0(targetVar, "Lag1")]] == 1
predictions <- allPredictions[product==targetVar, prediction]
predictionsPrevNotOwned <- predictions[!alreadyOwned]
if(suppressWarnings(max(predictions[alreadyOwned]))>0) browser()
predictedPosFlankCount <- sum(predictionsPrevNotOwned *
newProdPredictions[!alreadyOwned])
probMultiplier <- nrow(testDataLag) * fractionPosFlankUsers *
expectedCountPerPosFlank * countContributions[17, i] /
predictedPosFlankCount
probMultipliers[i] <- probMultiplier
if(is.finite(probMultiplier)){
if(normalizeMode == "additive" || targetVar %in% additiveNormalizeProds){
predictions[!alreadyOwned] <- predictions[!alreadyOwned] +
(probMultiplier-1)*mean(predictions[!alreadyOwned])
} else{
if(normalizeMode == "linear"){
predictions[!alreadyOwned] <- predictions[!alreadyOwned] *
probMultiplier
} else{
predictions[!alreadyOwned] <- probExponentNormaliser(
predictions[!alreadyOwned], probMultiplier,
weights=newProdPredictions[!alreadyOwned])
}
}
allPredictions[product==targetVar, prediction:=predictions]
}
}
}
setkey(allPredictions, ncodpers)
allPredictions[,order_predict := match(1:length(prediction),
order(-prediction)), by=ncodpers]
allPredictions <- allPredictions[order(ncodpers, -prediction), ]
orderCount <- allPredictions[, .N, .(ncodpers, order_predict)]
if(max(orderCount$N)>1) browser()
hist(allPredictions[order_predict==1, prediction])
topPredictions <- allPredictions[order_predict==1, .N, product]
topPredictions <- topPredictions[order(-N)]
topPredictionsPosFlanks <- allPredictions[order_predict==1 &
ncodpers %in% posFlankClients,
.N, product]
topPredictionsPosFlanks <- topPredictionsPosFlanks[order(-N)]
productRankDelaFin <- allPredictions[product=="ind_dela_fin_ult1", .N,
order_predict]
productRankDelaFin <- productRankDelaFin[order(order_predict),]
productRankDecoFin <- allPredictions[product=="ind_deco_fin_ult1", .N,
order_predict]
productRankDecoFin <- productRankDecoFin[order(order_predict),]
productRankTjcrFin <- allPredictions[product=="ind_tjcr_fin_ult1", .N,
order_predict]
productRankTjcrFin <- productRankTjcrFin[order(order_predict),]
productRankRecaFin <- allPredictions[product=="ind_reca_fin_ult1", .N,
order_predict]
productRankRecaFin <- productRankRecaFin[order(order_predict),]
allPredictions[, totalProb := prediction * rep(newProdPredictions,
each = nbBaseModels)]
meanProductProbs <- allPredictions[, .(meanCondProb = mean(prediction),
meanProb = mean(totalProb),
totalProb = sum(totalProb)), product]
meanProductProbs <- meanProductProbs[order(-meanProb), ]
productString <- paste(allPredictions[order_predict==1, product],
allPredictions[order_predict==2, product],
allPredictions[order_predict==3, product],
allPredictions[order_predict==4, product],
allPredictions[order_predict==5, product],
allPredictions[order_predict==6, product],
allPredictions[order_predict==7, product])
if(length(productString) != nrow(testDataLag)) browser()
submission <- data.frame(ncodpers = testDataLag$ncodpers,
added_products = productString)
paddedSubmission <- fread("Data/sample_submission.csv")
paddedSubmission[, added_products := ""]
matchIds <- match(submission$ncodpers, paddedSubmission$ncodpers)
paddedSubmission[matchIds, added_products := submission$added_products]
write.csv(paddedSubmission, file.path(getwd(), "Submission", submissionDate,
paste0(submissionFile, ".csv")),
row.names = FALSE)
if(savePredictions){
saveRDS(allPredictions, file=file.path(predictionsPath,
paste0(submissionFile, ".rds")))
}
cat("Submission file created successfully!\n",
nrow(submission)," records were predicted (",
round(nrow(submission)/nrow(paddedSubmission)*100,2), "%)\n", sep="") |
expected <- eval(parse(text="FALSE"));
test(id=0, code={
argv <- eval(parse(text="list(FALSE, FALSE)"));
.Internal(qsort(argv[[1]], argv[[2]]));
}, o=expected); |
makeModelFile <-function(model,
filename, mergedTree, S,
hyperprior,
corString=NULL,
predString=NULL,
parString="",
groupMatT1=NULL,
fixedPar=NULL
){
treeNames <- as.character(sort(unique(mergedTree$Tree)))
NOT=length(treeNames)
count=1
ncatPerTree <- as.vector(by(mergedTree$Category, mergedTree$Tree, length))
cat(ifelse(model=="traitMPT",
"
"
"data{\nfor(s in 1:S){\n zeros[s] <- 0\n}\n}\n\n",
"model{\n\n",
"for (n in 1: subjs){\n\n
file=filename)
for(i in 1:NOT){
for(j in 1:ncatPerTree[i]){
cat(treeNames[i],"[n,",j,"] <- ",mergedTree$Equation[count],
"\n",sep="",file=filename,append=T)
count=count+1
}
cat("\n",file=filename,append=T)
}
cat("\n
for(i in 1:NOT){
cat("response.",treeNames[i],"[n,1:",ncatPerTree[i],"] ~ dmulti(",
treeNames[i],"[n,1:",ncatPerTree[i],"],items.",treeNames[i],
"[n])\n",sep="",file=filename,append=T)
}
cat("}\n",file=filename,append=T)
hyperprior <- switch(model,
"betaMPT" = makeBetaHyperprior(S =S ,
alpha = hyperprior$alpha,
beta = hyperprior$beta),
"traitMPT" = makeTraitHyperprior(S = S,
predString = predString,
mu = hyperprior$mu,
xi = hyperprior$xi,
wishart = !anyNA(hyperprior$V))
)
cat("\n\n
hyperprior, file=filename, append=TRUE)
if(! is.null(fixedPar)){
S.fixed <- length(unique(fixedPar$theta))
cat("\nfor(i in 1:", S.fixed,"){\n",
" thetaFE[i] ~ dunif(0,1)\n}\n", file=filename, append=TRUE)
}
if( !is.null(corString)){
cat(corString, file=filename, append=T)
}
cat(parString, file=filename, append = TRUE)
cat("}\n",file=filename,append=T)
}
makeBetaHyperprior <- function(S, alpha = "dunif(1,5000)", beta = "dunif(1,5000)"){
if(!inherits(alpha, "character") || !length(alpha) %in% c(1,S)){
stop("Hyperprior for 'alpha' must be a character vector of length 1
if the same prior should be used for all MPT parameters (default)
or a vector of the same length as the number of parameters (=", S, "; to
check the order see ?readEQN).")
}
if(!inherits(beta, "character") || !length(beta) %in% c(1,S)){
stop("Hyperprior for 'beta' must be a character vector of length 1
if the same prior should be used for all MPT parameters (default)
or a vector of the same length as the number of parameters (=", S, "; to
check the order see ?readEQN).")
}
modelString <- paste0("
for(s in 1:S){
for(n in 1:subjs) {
theta[s,n] ~ dbeta(alph[s], bet[s])
}
}
for(s in 1:S){
mean[s] <- alph[s]/(alph[s]+bet[s])
sd[s] <- sqrt(alph[s]*bet[s]/(pow(alph[s]+bet[s],2)*(alph[s]+bet[s]+1)))
}\n\n")
for(s in 1:S){
if(alpha[s] == "zero" | beta[s] == "zero"){
modelString <- paste0(modelString,
"alph[", s, "] ~ dunif(.01,5000)\n",
"bet[", s, "] ~ dunif(.01,5000)\n",
"zeros[",s,"] ~ dpois(phi[",s,"])\n",
"phi[",s,"] <- -log(1/pow(alph[",s,"]+bet[",s,"],5/2))\n")
}else{
modelString <- paste0(modelString,
"alph[", s, "] ~ ", alpha[s], "\n",
"bet[", s, "] ~ ", beta[s], "\n")
}
}
modelString <- paste0(modelString, "\n")
return(modelString)
}
makeTraitHyperprior <- function(S, predString, mu = "dnorm(0,1)",
xi = "dunif(0,100)", wishart = TRUE){
if(!inherits(mu, "character") || !length(mu) %in% c(1,S)){
stop("Hyperprior for 'mu' must be a character vector of length 1
if the same prior should be used for all MPT parameters (default)
or a vector of the same length as the number of parameters (=", S, "; to
check the order see ?readEQN).")
}
if(!inherits(xi, "character") || !length(xi) %in% c(1,S)){
stop("Hyperprior for 'xi' must be a character vector of length 1
if the same prior should be used for all MPT parameters (default)
or a vector of the same length as the number of parameters (=", S, "; to
check the order see ?readEQN).")
}
if (wishart){
modelString <- paste0(predString, "
for(i in 1:subjs) {
delta.part.raw[1:S,i] ~ dmnorm(zeros,T.prec.part[1:S,1:S])
}
",
ifelse(S > 1,"
T.prec.part[1:S,1:S] ~ dwish(V, df)",
"
T.prec.part[1,1] ~ dchisq(df)"),
"
Sigma.raw[1:S,1:S] <- inverse(T.prec.part[,])
for(s in 1:S){
mean[s] <- phi(mu[s])
for(q in 1:S){
Sigma[s,q] <- Sigma.raw[q,s]*xi[s]*xi[q]
}
}
for(s in 1:S){
for(q in 1:S){
rho[s,q] <- Sigma[s,q]/sqrt(Sigma[s,s]*Sigma[q,q])
}
sigma[s] <- sqrt(Sigma[s,s])
}")
} else {
modelString <- paste0(predString, "
for(s in 1:S) {
for(i in 1:subjs) {
delta.part.raw[s,i] ~ dnorm(0,tau[s])
}
mean[s] <- phi(mu[s])
tau[s] ~ dgamma(.5, df / 2)
sigma[s] <- abs(xi[s]) / sqrt(tau[s])
for(s2 in 1:S){
rho[s,s2] <- -99
}
}")
}
paste0(modelString, "\n\n",
paste0("\nmu[", 1:S, "] ~ ", mu, collapse = ""),
paste0("\nxi[", 1:S, "] ~ ", xi, collapse = ""),"\n\n")
} |
tm_wordcloud <- function(data,
stopwords = NULL,
seed = 100,
keep = 100,
return = "plot",
...){
set.seed(seed)
clean_data <-
suppressMessages(tm_clean(
data = data,
token = "words",
stopwords = stopwords
))
plot_data <-
clean_data %>%
count(word, name = "freq") %>%
arrange(desc(freq))
if(nrow(plot_data) < keep){
keep <- nrow(plot_data)
}
plot_data <- plot_data %>% slice(1:keep)
if(return == "plot"){
output <-
plot_data %>%
ggplot(aes(label = word, size = freq)) +
ggwordcloud::geom_text_wordcloud(rm_outside = TRUE, ...) +
scale_size_area(max_size = 15) +
theme_minimal()
return(output)
} else if (return == "table"){
return(plot_data)
} else {
stop("Please enter a valid input for `return`.")
}
} |
make.timedep.dataset = function(dat, X, d, baseline.ageyrs, t.1, t.2=NULL) {
stopifnot(t.1<t.2)
dat[[baseline.ageyrs]]=round(dat[[baseline.ageyrs]],3)
dat$tstart = 0
dat$tstop = dat[[X]]
if (is.null(t.2)) breaks=c(0,t.1,100) else breaks=c(0,t.1,t.2,100)
dat$.timedep.agegrp=cut(dat[[baseline.ageyrs]], breaks=breaks, right=FALSE)
dat$.baseline.agegrp=dat$.timedep.agegrp
.levels=levels(dat$.timedep.agegrp)
age.at.X=dat[[baseline.ageyrs]] + dat[[X]]
subset.2 = dat[[baseline.ageyrs]] < t.1 & age.at.X>=t.1
dat.young = subset(dat, subset.2)
dat.young.cpy=dat.young
if (nrow(dat.young)>0) {
dat.young[[d]]=0
dat.young$tstop=(t.1 - 1e-4) - dat.young[[baseline.ageyrs]]
dat.young.cpy$tstart=dat.young$tstop
dat.young.cpy$.timedep.agegrp=.levels[2]
dat.young.cpy$.timedep.agegrp=factor(dat.young.cpy$.timedep.agegrp, levels=.levels)
}
if (is.null(t.2)) {
out=rbind(
subset(dat, !subset.2),
dat.young, dat.young.cpy
)
} else {
subset.1 = dat[[baseline.ageyrs]]<t.2 & dat[[baseline.ageyrs]]>=t.1 & age.at.X>=t.2
dat.middle = subset(dat, subset.1)
dat.middle.cpy=dat.middle
if(nrow(dat.middle)>0) {
dat.middle[[d]]=0
dat.middle$tstop=(t.2 - 1e-4) - dat.middle[[baseline.ageyrs]]
dat.middle.cpy$tstart=dat.middle$tstop
dat.middle.cpy$.timedep.agegrp=.levels[3]
dat.middle.cpy$.timedep.agegrp=factor(dat.middle.cpy$.timedep.agegrp, levels=.levels)
}
out=rbind(
subset(dat, !(subset.1 | subset.2)),
dat.middle, dat.middle.cpy,
dat.young, dat.young.cpy
)
}
} |
context("legendre()")
test_that("basic", {
expect_equal(
legendre(3),
structure(
list(
c("x" = 1, "coef" = -1.5),
c("x" = 3, "coef" = 2.5)
),
"class" = c("legendre", "mpoly"),
"legendre" = list(
"degree" = 3,
"indeterminate" = "x",
"normalized" = FALSE
)
)
)
})
test_that("basic", {
expect_equal(
legendre(3, indeterminate = "t"),
structure(
list(
c("t" = 1, "coef" = -1.5),
c("t" = 3, "coef" = 2.5)
),
"class" = c("legendre", "mpoly"),
"legendre" = list(
"degree" = 3,
"indeterminate" = "t",
"normalized" = FALSE
)
)
)
})
test_that("normalized", {
expect_equal(
legendre(3, normalized = TRUE),
structure(
list(
c("x" = 1, "coef" = -2.806243),
c("x" = 3, "coef" = 4.677072)
),
"class" = c("legendre", "mpoly"),
"legendre" = list(
"degree" = 3,
"indeterminate" = "x",
"normalized" = TRUE
)
),
tolerance = 1e-5
)
})
test_that("vectorized", {
expect_equal(
legendre(0:2),
structure(
list(
structure(
list(
c("coef" = 1)
),
"class" = c("legendre", "mpoly"),
"legendre" = list(
"degree" = 0,
"indeterminate" = "x",
"normalized" = FALSE
)
),
structure(
list(
c("x" = 1, "coef" = 1)
),
"class" = c("legendre", "mpoly"),
"legendre" = list(
"degree" = 1,
"indeterminate" = "x",
"normalized" = FALSE
)
),
structure(
list(
c("coef" = -.5),
c("x" = 2, "coef" = 1.5)
),
"class" = c("legendre", "mpoly"),
"legendre" = list(
"degree" = 2,
"indeterminate" = "x",
"normalized" = FALSE
)
)
),
class = "mpolyList"
)
)
}) |
"colombian" |
get_unemployment <- function(by=NULL) {
params <- list(subject="unemp")
if (!is.null(by)) params <- make_params(params, by, c("g", "r", "a", "e"))
res <- epi_query(params)
if (is.null(res)) return(data.frame())
cols <- stringi::stri_trans_tolower(res$columns$name)
cols <- stringi::stri_replace_all_regex(cols, "[\\('\\)]", "")
cols <- stringi::stri_replace_all_regex(cols, "[[:space:]" %s+%
rawToChar(as.raw(c(0xe2, 0x80, 0x93))) %s+% "-]+",
"_")
out <- setNames(as_data_frame(res$data), cols)
out <- dplyr::mutate_all(out, "clean_cols")
out <- suppressMessages(readr::type_convert(out))
show_citation(res)
out
}
get_unemployment_by_state <- function(by=NULL) {
params <- list(subject="unempstate")
if (!is.null(by)) params <- make_params(params, by, c("r"))
res <- epi_query(params)
if (is.null(res)) return(data.frame())
cols <- stringi::stri_trans_tolower(res$columns$name)
cols <- stringi::stri_replace_all_regex(cols, "[\\('\\)]", "")
cols <- stringi::stri_replace_all_regex(cols, "[[:space:]" %s+%
rawToChar(as.raw(c(0xe2, 0x80, 0x93))) %s+% "-]+",
"_")
out <- setNames(as_data_frame(res$data), cols)
out <- dplyr::mutate_all(out, "clean_cols")
out <- suppressMessages(readr::type_convert(out))
out <- tidyr::gather(out, region, value, -date)
show_citation(res)
out
}
get_long_term_unemployment <- function(by=NULL) {
params <- list(subject="ltunemp")
if (!is.null(by)) params <- make_params(params, by, c("g", "r", "a", "e"))
res <- epi_query(params)
if (is.null(res)) return(data.frame())
cols <- stringi::stri_trans_tolower(res$columns$name)
cols <- stringi::stri_replace_all_regex(cols, "[\\('\\)]", "")
cols <- stringi::stri_replace_all_regex(cols, "[[:space:]" %s+%
rawToChar(as.raw(c(0xe2, 0x80, 0x93))) %s+% "-]+",
"_")
out <- setNames(as_data_frame(res$data), cols)
out <- dplyr::mutate_all(out, "clean_cols")
out <- suppressMessages(readr::type_convert(out))
show_citation(res)
out
}
get_underemployment <- function(by=NULL) {
params <- list(subject="underemp")
if (!is.null(by)) params <- make_params(params, by, c("g", "r", "a", "e"))
res <- epi_query(params)
if (is.null(res)) return(data.frame())
cols <- stringi::stri_trans_tolower(res$columns$name)
cols <- stringi::stri_replace_all_regex(cols, "[\\('\\)]", "")
cols <- stringi::stri_replace_all_regex(cols, "[[:space:]" %s+%
rawToChar(as.raw(c(0xe2, 0x80, 0x93))) %s+% "-]+",
"_")
out <- setNames(as_data_frame(res$data), cols)
out <- dplyr::mutate_all(out, "clean_cols")
out <- suppressMessages(readr::type_convert(out))
show_citation(res)
out
}
get_labor_force_participation_rate <- function(by=NULL) {
params <- list(subject="lfpr")
if (!is.null(by)) params <- make_params(params, by, c("g", "r", "a", "e"))
res <- epi_query(params)
if (is.null(res)) return(data.frame())
cols <- stringi::stri_trans_tolower(res$columns$name)
cols <- stringi::stri_replace_all_regex(cols, "[\\('\\)]", "")
cols <- stringi::stri_replace_all_regex(cols, "[[:space:]" %s+%
rawToChar(as.raw(c(0xe2, 0x80, 0x93))) %s+% "-]+",
"_")
out <- setNames(as_data_frame(res$data), cols)
out <- dplyr::mutate_all(out, "clean_cols")
out <- suppressMessages(readr::type_convert(out))
show_citation(res)
out
}
get_employment_to_population_ratio <- function(by=NULL) {
params <- list(subject="epop")
if (!is.null(by)) params <- make_params(params, by, c("g", "r", "a", "e"))
res <- epi_query(params)
if (is.null(res)) return(data.frame())
cols <- stringi::stri_trans_tolower(res$columns$name)
cols <- stringi::stri_replace_all_regex(cols, "[\\('\\)]", "")
cols <- stringi::stri_replace_all_regex(cols, "[[:space:]" %s+%
rawToChar(as.raw(c(0xe2, 0x80, 0x93))) %s+% "-]+",
"_")
out <- setNames(as_data_frame(res$data), cols)
out <- dplyr::mutate_all(out, "clean_cols")
out <- suppressMessages(readr::type_convert(out))
show_citation(res)
out
} |
cal_MASE <- function(training, test, forecast){
m <- stats::frequency(training)
q_t <- abs(test-forecast)/mean(abs(diff(training, lag=m)))
return(mean(q_t))
} |
findit <- function(lims=list(), objective="CV", niter=NULL, iprotein=NULL, plot.it=TRUE,
T=25, P="Psat", res=NULL, labcex=0.6, loga2=NULL,
loga.balance=0, rat=NULL, balance=NULL, normalize=FALSE) {
nd <- length(lims)
if(!is.null(iprotein)) pl <- protein.length(iprotein)
if(is.null(res)) res <- c(128,64,16,8,6,4,4)[nd]
if(is.null(niter)) niter <- c(4,6,6,8,12,12,12)[nd]
if(is.null(rat)) {
rat <- 0.95
if(res > 4) rat <- 0.9
if(res > 8) rat <- 0.8
if(res > 16) rat <- 0.7
}
basis <- get("thermo", CHNOSZ)$basis
if("pH" %in% names(lims)) {
iH <- match("H+",rownames(basis))
if(length(iH) > 0) {
rownames(basis)[iH] <- "pH"
basis$logact[iH] <- -basis$logact[iH]
} else(stop("pH is a requested variable but H+ is not in the basis"))
}
limfun <- function(lim,curr,i) {
if(i==1) mylims <- lim
else {
message(paste("optimal:",round(curr,4),"",""), appendLF=FALSE)
range <- range(lim)
int <- abs(diff(range)) * rat^(i-1)
mylims <- c(curr-int/2, curr+int/2)
if(any(mylims < min(range))) mylims <- mylims + (min(range) - min(mylims))
if(any(mylims > max(range))) mylims <- mylims - (max(mylims) - max(range))
if(diff(lim) < 0) mylims <- rev(mylims)
}
message(paste("new limits:",round(mylims[1],4),round(mylims[2],4)))
return(mylims)
}
teststat <- numeric()
out <- vector("list",length(lims))
names(out) <- names(lims)
lolim <- out
hilim <- out
outlims <- lims
for(i in 1:niter) {
message(paste("\n
aargs <- list()
for(j in 1:length(lims)) {
if(names(lims)[j] %in% rownames(basis)) {
ibasis <- match(names(lims)[j],rownames(basis))
message(paste("
lim <- lims[[j]]
curr <- basis$logact[ibasis]
myarg <- list(c(limfun(lim,curr,i),res))
names(myarg) <- rownames(basis)[ibasis]
aargs <- c(aargs,myarg)
} else if(names(lims[j]) %in% c("T","P")) {
message(paste("
if(names(lims[j])=="T") {
lim <- lims$T
curr <- T
} else {
lim <- lims$P
curr <- P
}
myarg <- list(c(limfun(lim,curr,i),res))
names(myarg) <- names(lims[j])
aargs <- c(aargs,myarg)
} else warning(paste("findit: ignoring",names(lims[j]),"which is not a basis species, T or P"))
}
if(!"T" %in% names(lims)) aargs <- c(aargs,list(T=T))
if(!"P" %in% names(lims)) aargs <- c(aargs,list(P=P))
if(!is.null(iprotein)) {
aargs <- c(aargs,list(iprotein=iprotein))
}
a <- do.call(affinity,aargs)
e <- equilibrate(a, balance=balance, loga.balance=loga.balance, normalize=normalize)
dd <- revisit(e, objective, loga2=loga2, plot.it=FALSE)$H
iopt <- optimal.index(dd, objective)[1,, drop=FALSE]
teststat <- c(teststat,dd[iopt])
for(j in 1:length(lims)) {
mylims <- aargs[[j]]
myinc <- seq(mylims[1],mylims[2],length.out=mylims[3])
myval <- myinc[iopt[j]]
if(names(lims)[j] %in% rownames(basis)) {
ibasis <- match(names(lims)[j],rownames(basis))
basis$logact[ibasis] <- myval
basis(rownames(basis)[ibasis],myval)
} else if(names(lims)[j]=="T") {
T <- myval
} else if(names(lims)[j]=="P") {
P <- myval
}
out[[j]] <- c(out[[j]],myval)
lolim[[j]] <- c(lolim[[j]],mylims[1])
hilim[[j]] <- c(hilim[[j]],mylims[2])
outlims[[j]] <- mylims
}
if(plot.it) {
if(nd==1) {
if(i==1) revisit(e,objective,loga2,xlim=lims[[1]])
abline(v=outlims[[1]][1:2])
lines(myinc,dd)
points(myval,dd[iopt])
} else if(nd==2) {
if(i==1) revisit(e,objective,loga2,xlim=lims[[1]],ylim=lims[[2]],labcex=labcex)
else {
ol1 <- outlims[[1]]
ol2 <- outlims[[2]]
rect(ol1[1],ol2[1],ol1[2],ol2[2],border=par("fg"),col="white")
revisit(e,objective,loga2,xlim=lims[[1]],ylim=lims[[2]],add=TRUE,labcex=labcex)
}
text(out[[1]],out[[2]])
points(out[[1]],out[[2]],cex=2)
} else {
if(i==1) add <- FALSE else add <- TRUE
if(i > 1) {
ol1 <- outlims[[1]]
ol2 <- outlims[[2]]
rect(ol1[1],ol2[1],ol1[2],ol2[2],border=par("fg"),col="white")
}
for(j in 3:nd) {
for(k in 1:length(e$loga.equil)) e$loga.equil[[k]] <- slice(e$loga.equil[[k]],3,iopt[j])
}
revisit(e,objective,loga2,xlim=lims[[1]],ylim=lims[[2]],add=add,labcex=labcex)
text(out[[1]],out[[2]])
points(out[[1]],out[[2]],cex=2)
}
}
}
teststat <- list(teststat)
names(teststat) <- objective
value <- c(out,teststat)
out <- list(value=value,lolim=lolim,hilim=hilim)
class(out) <- "findit"
return(out)
}
plot_findit <- function(x,which=NULL,mar=c(3.5,5,2,2),xlab="iteration",...) {
l <- length(x$value)
if(is.null(which)) which <- 1:l
l <- length(which)
opar <- par(mfrow=c(l,1),mar=mar)
for(i in which) {
niter <- length(x$value[[i]])
ylab <- names(x$value)[i]
if(ylab %in% c(rownames(get("thermo", CHNOSZ)$basis),"T","P","pH","Eh")) ylab <- axis.label(ylab)
plot(1:niter,x$value[[i]],xlab=xlab,ylab=ylab,...)
lines(1:niter,x$value[[i]])
if(i!=length(x$value)) {
lines(1:niter,x$lolim[[i]],lty=2)
lines(1:niter,x$hilim[[i]],lty=2)
}
}
par(opar)
} |
f.polygons.preCKrige <- function(
newdata,
neighbours,
model,
pwidth,
pheight,
napp = 1
)
{
if( class( newdata ) == "SpatialPolygons" )
{
data = as.data.frame( matrix( ncol = 0, nrow = 0 ) )
}
if( class( newdata ) == "SpatialPolygonsDataFrame" )
{
data = newdata@data
}
class(model) <- "list"
model.me.free <- model[unlist(lapply(1:length(model), function(i,m){m[[i]]$model != "mev"},m = model))]
newdata.polygons = SpatialPolygons( newdata@polygons )
if( missing( neighbours ) )
{
neighbours <- lapply( as.list( 1:length(newdata@polygons) ), function( x ){ return( integer(0) ) } )
}
stopifnot( is.list(neighbours) )
pixgrid<- f.pixelgrid(
polygons = newdata.polygons,
neighbours = neighbours,
pixel.x.width = pwidth,
pixel.y.width = pheight
)
pixcm <- f.pixelcovmat(
pixgrid = pixgrid,
model = model.me.free
)
t.n.poly <- as.list( 1:length( newdata.polygons@polygons ) )
for( i in 1:napp ){
pc.tmp <- f.pixconfig(
polygons = newdata.polygons,
neighbours = neighbours,
pixgrid = pixgrid,
n = napp
)
if( i == 1 )
{
pixconfig = pc.tmp
}
else
{
t2 <- proc.time()[3]
pixconfig <- lapply( pixconfig,
function( pc, pc.tmp )
{
pc$pixcenter <- cbind( pc$pixcenter,
pc.tmp[[ pc$posindex[1] ]]$pixcenter )
pc$pix.in.poly <- cbind( pc$pix.in.poly, pc.tmp[[ pc$posindex[1] ]]$pix.in.poly )
pc$sa.polygons <- c(pc$sa.polygons,
pc.tmp[[ pc$posindex[1] ]]$sa.polygons)
return(pc)
},
pc.tmp= pc.tmp
)
}
rm( pc.tmp )
}
cm.list <- f.polygoncovmat(
pixconfig = pixconfig,
pixcm = pixcm,
model = model.me.free,
n = napp
)
return( new( "preCKrigePolygons",
covmat = cm.list$mean.bb.cov.mat,
se.covmat = cm.list$var.mean.bb.cov.mat,
pixconfig = pixconfig,
pixcovmat = pixcm,
model = model,
data = data,
polygons = newdata@polygons
)
)
rm( pixcm, pixgrid, newdata.polygons, pixconfig, cm.list)
} |
context("Checking PFT lookup")
con <- check_db_test()
teardown(
db.close(con)
)
test_that("query.pft_species finds species for a PFT", {
one_sp <- query.pft_species(pft = "salix-miyabeana", modeltype = NULL, con)
expect_is(one_sp, "data.frame")
expect_equal(nrow(one_sp), 1)
expect_equivalent(as.numeric(one_sp$id), 2871)
expect_equivalent(one_sp$scientificname, "Salix miyabeana")
multi_sp <- query.pft_species(pft = "salix", modeltype = NULL, con)
expect_is(multi_sp, "data.frame")
expect_gt(nrow(multi_sp), 10)
expect_equal(length(multi_sp$id), length(unique(multi_sp$id)))
expect_equal(unique(multi_sp$genus), "Salix")
})
test_that("specifying modeltype removes duplicates from ambiguous query", {
soil_null <- query.pft_species(pft = "soil", modeltype = NULL, con)
soil_ed <- query.pft_species(pft = "soil", modeltype = "ED2", con)
expect_lt(nrow(soil_ed), nrow(soil_null))
expect_true(all(soil_ed$id %in% soil_null$id))
})
test_that("nonexistant PFTs and modeltypes return empty dataframes", {
expect_length(query.pft_species("soil", "NOTAMODEL", con)$id, 0)
expect_length(query.pft_species("NOTAPFT", NULL, con)$id, 0)
})
test_that("query.pft_cultivars finds cultivars for a PFT", {
skip("Disabled until Travis bety contains Pavi_alamo and Pavi_all (
one_cv <- query.pft_cultivars(pft = "Pavi_alamo", modeltype = NULL, con)
expect_is(one_cv, "data.frame")
expect_equal(nrow(one_cv), 1)
expect_equal(one_cv$id, 3)
expect_equal(one_cv$specie_id, 938)
expect_equal(one_cv$scientificname, "Panicum virgatum")
multi_cv <- query.pft_cultivars(pft = "Pavi_all", modeltype = NULL, con)
expect_is(multi_cv, "data.frame")
expect_gt(nrow(multi_cv), 90)
expect_equal(length(multi_cv$id), length(unique(multi_cv$id)))
expect_true(one_cv$id %in% multi_cv$id)
})
test_that("query.pft_species and query.pft_cultivars do not find each other's PFTs", {
expect_equal(nrow(query.pft_species("Pavi_alamo", NULL, con)), 0)
expect_equal(nrow(query.pft_cultivars("soil", NULL, con)), 0)
}) |
pb.hybrid.binary <- function(n00, n01, n10, n11, data, methods, iter.resam = 1000, theo.pval = TRUE){
if(!missing(data)){
n00 <- eval(substitute(n00), data, parent.frame())
n01 <- eval(substitute(n01), data, parent.frame())
n10 <- eval(substitute(n10), data, parent.frame())
n11 <- eval(substitute(n11), data, parent.frame())
}
if(missing(methods)){
methods <- c("rank", "reg", "reg.het", "skew", "skew.het", "inv.sqrt.n", "trimfill",
"n", "inv.n", "as.rank", "as.reg", "as.reg.het", "smoothed", "smoothed.het", "score", "count")
}
if(!all(is.element(methods, c("rank", "reg", "reg.het", "skew", "skew.het", "inv.sqrt.n", "trimfill",
"n", "inv.n", "as.rank", "as.reg", "as.reg.het", "smoothed", "smoothed.het", "score", "count")))){
stop("incorrect input for methods.")
}
pval.rank <- pval.reg <- pval.reg.het <- pval.skew <- pval.skew.het <- pval.inv.sqrt.n <- pval.trimfill <-
pval.n <- pval.inv.n <- pval.as.rank <- pval.as.reg <- pval.as.reg.het <-
pval.smoothed <- pval.smoothed.het <- pval.score <- pval.count <- NA
pval.rank.theo <- pval.reg.theo <- pval.reg.het.theo <- pval.skew.theo <- pval.skew.het.theo <- pval.inv.sqrt.n.theo <- pval.trimfill.theo <-
pval.n.theo <- pval.inv.n.theo <- pval.as.rank.theo <- pval.as.reg.theo <- pval.as.reg.het.theo <-
pval.smoothed.theo <- pval.smoothed.het.theo <- pval.score.theo <- pval.count.theo <- NA
n00.ori <- n00
n01.ori <- n01
n10.ori <- n10
n11.ori <- n11
counts <- check.counts(n00, n01, n10, n11)
n00 <- counts$n00
n01 <- counts$n01
n10 <- counts$n10
n11 <- counts$n11
y <- log(n11/n10*n00/n01)
s2 <- 1/n00 + 1/n01 + 1/n10 + 1/n11
n <- n00 + n01 + n10 + n11
pi0 <- n01/(n00 + n01)
n0Sum <- n00 + n01
n1Sum <- n10 + n11
if(is.element("rank", methods)){
rank <- pb.rank(y, s2)
stat.rank <- rank$stat
if(theo.pval) pval.rank.theo <- rank$pval
}
if(is.element("reg", methods)){
reg <- pb.reg(y, s2)
stat.reg <- reg$stat
if(theo.pval) pval.reg.theo <- reg$pval
}
if(is.element("reg.het", methods)){
reg.het <- pb.reg.het(y, s2)
stat.reg.het <- reg.het$stat
if(theo.pval) pval.reg.het.theo <- reg.het$pval
}
if(is.element("skew", methods)){
skew <- pb.skew(y, s2)
stat.skew <- skew$stat
if(theo.pval) pval.skew.theo <- skew$pval
}
if(is.element("skew.het", methods)){
skew.het <- pb.skew.het(y, s2)
stat.skew.het <- skew.het$stat
if(theo.pval) pval.skew.het.theo <- skew.het$pval
}
if(is.element("inv.sqrt.n", methods)){
inv.sqrt.n <- pb.inv.sqrt.n(y, s2, n)
stat.inv.sqrt.n <- inv.sqrt.n$stat
if(theo.pval) pval.inv.sqrt.n.theo <- inv.sqrt.n$pval
}
if(is.element("trimfill", methods)){
options(warn = -1)
rma <- rma(yi = y, vi = s2, method = "DL")
trimfill <- pb.trimfill(rma, estimator = "R0")
stat.trimfill <- trimfill$k0
if(theo.pval) pval.trimfill.theo <- trimfill$pval
options(warn = 0)
}
if(is.element("n", methods)){
pbn <- pb.n(y = y, n00 = n00, n01 = n01, n10 = n10, n11 = n11)
stat.n <- pbn$stat
if(theo.pval) pval.n.theo <- pbn$pval
}
if(is.element("inv.n", methods)){
inv.n <- pb.inv.n(y = y, n00 = n00, n01 = n01, n10 = n10, n11 = n11)
stat.inv.n <- inv.n$stat
if(theo.pval) pval.inv.n.theo <- inv.n$pval
}
if(is.element("as.rank", methods)){
as.rank <- pb.as.rank(n00 = n00, n01 = n01, n10 = n10, n11 = n11)
stat.as.rank <- as.rank$stat
if(theo.pval) pval.as.rank.theo <- as.rank$pval
}
if(is.element("as.reg", methods)){
as.reg <- pb.as.reg(n00 = n00, n01 = n01, n10 = n10, n11 = n11)
stat.as.reg <- as.reg$stat
if(theo.pval) pval.as.reg.theo <- as.reg$pval
}
if(is.element("as.reg.het", methods)){
as.reg.het <- pb.as.reg.het(n00 = n00, n01 = n01, n10 = n10, n11 = n11)
stat.as.reg.het <- as.reg.het$stat
if(theo.pval) pval.as.reg.het.theo <- as.reg.het$pval
}
if(is.element("smoothed", methods)){
smoothed <- pb.smoothed(y = y, n00 = n00, n01 = n01, n10 = n10, n11 = n11)
stat.smoothed <- smoothed$stat
if(theo.pval) pval.smoothed.theo <- smoothed$pval
}
if(is.element("smoothed.het", methods)){
smoothed.het <- pb.smoothed.het(y = y, n00 = n00, n01 = n01, n10 = n10, n11 = n11)
stat.smoothed.het <- smoothed.het$stat
if(theo.pval) pval.smoothed.het.theo <- smoothed.het$pval
}
if(is.element("score", methods)){
score <- pb.score(n00 = n00, n01 = n01, n10 = n10, n11 = n11)
stat.score <- score$stat
if(theo.pval) pval.score.theo <- score$pval
}
if(is.element("count", methods)){
count <- pb.count(n00 = n00.ori, n01 = n01.ori, n10 = n10.ori, n11 = n11.ori)
stat.count <- count$stat
if(theo.pval) pval.count.theo <- count$pval
}
N <- length(y)
w <- 1/s2
theta.hat <- sum(w*y)/sum(w)
Q <- sum(w*(y - theta.hat)^2)
tau2.hat <- (Q - N + 1)/(sum(w) - sum(w^2)/sum(w))
tau2.hat <- max(c(0, tau2.hat))
w <- 1/(s2 + tau2.hat)
theta.hat <- sum(w*y)/sum(w)
if(all(is.na(n))) n <- rep(NA, N)
stat.rank.resam <- stat.reg.resam <- stat.reg.het.resam <- stat.skew.resam <- stat.skew.het.resam <-
stat.inv.sqrt.n.resam <- stat.trimfill.resam <-
stat.n.resam <- stat.inv.n.resam <- stat.as.rank.resam <- stat.as.reg.resam <- stat.as.reg.het.resam <-
stat.smoothed.resam <- stat.smoothed.het.resam <- stat.score.resam <- stat.count.resam <- stat.hybrid.resam <- stat.hybrid.theo.resam <- rep(NA, iter.resam)
pval.rank.theo.resam <- pval.reg.theo.resam <- pval.reg.het.theo.resam <- pval.skew.theo.resam <- pval.skew.het.theo.resam <- pval.inv.sqrt.n.theo.resam <- pval.trimfill.theo.resam <-
pval.n.theo.resam <- pval.inv.n.theo.resam <- pval.as.rank.theo.resam <- pval.as.reg.theo.resam <- pval.as.reg.het.theo.resam <-
pval.smoothed.theo.resam <- pval.smoothed.het.theo.resam <- pval.score.theo.resam <- pval.count.theo.resam <- rep(NA, iter.resam)
for(i in 1:iter.resam){
idx <- sample(1:N, replace = TRUE)
n0Sum.resam <- n0Sum[idx]
n1Sum.resam <- n1Sum[idx]
pi0.resam <- pi0[idx]
s2.resam <- s2[idx]
theta.resam <- rnorm(n = N, mean = theta.hat, sd = sqrt(s2.resam + tau2.hat))
n00.resam <- n01.resam <- n10.resam <- n11.resam <- rep(NA, N)
for(j in 1:N){
counts.resam <- find.counts(n0. = n0Sum.resam[j], n1. = n1Sum.resam[j], lor = theta.resam[j], lor.var = s2.resam[j], p0.ori = pi0.resam[j])
n00.resam[j] <- counts.resam$n00
n01.resam[j] <- counts.resam$n01
n10.resam[j] <- counts.resam$n10
n11.resam[j] <- counts.resam$n11
}
n00.ori.resam <- n00.resam
n00.ori.resam <- round(n00.ori.resam)
n01.ori.resam <- n01.resam
n01.ori.resam <- round(n01.ori.resam)
n10.ori.resam <- n10.resam
n10.ori.resam <- round(n10.ori.resam)
n11.ori.resam <- n11.resam
n11.ori.resam <- round(n11.ori.resam)
counts.resam <- check.counts(n00.resam, n01.resam, n10.resam, n11.resam)
n00.resam <- counts.resam$n00
n01.resam <- counts.resam$n01
n10.resam <- counts.resam$n10
n11.resam <- counts.resam$n11
y.resam <- log(n11.resam/n10.resam*n00.resam/n01.resam)
s2.resam <- 1/n00.resam + 1/n01.resam + 1/n10.resam + 1/n11.resam
n.resam <- n00.resam + n01.resam + n10.resam + n11.resam
if(is.element("rank", methods)){
rank.resam <- pb.rank(y.resam, s2.resam)
stat.rank.resam[i] <- rank.resam$stat
if(theo.pval) pval.rank.theo.resam[i] <- rank.resam$pval
}
if(is.element("reg", methods)){
reg.resam <- pb.reg(y.resam, s2.resam)
stat.reg.resam[i] <- reg.resam$stat
if(theo.pval) pval.reg.theo.resam[i] <- reg.resam$pval
}
if(is.element("reg.het", methods)){
reg.het.resam <- pb.reg.het(y.resam, s2.resam)
stat.reg.het.resam[i] <- reg.het.resam$stat
if(theo.pval) pval.reg.het.theo.resam[i] <- reg.het.resam$pval
}
if(is.element("skew", methods)){
skew.resam <- pb.skew(y.resam, s2.resam)
stat.skew.resam[i] <- skew.resam$stat
if(theo.pval) pval.skew.theo.resam[i] <- skew.resam$pval
}
if(is.element("skew.het", methods)){
skew.het.resam <- pb.skew.het(y.resam, s2.resam)
stat.skew.het.resam[i] <- skew.het.resam$stat
if(theo.pval) pval.skew.het.theo.resam[i] <- skew.het.resam$pval
}
if(is.element("inv.sqrt.n", methods)){
inv.sqrt.n.resam <- pb.inv.sqrt.n(y.resam, s2.resam, n.resam)
stat.inv.sqrt.n.resam[i] <- inv.sqrt.n.resam$stat
if(theo.pval) pval.inv.sqrt.n.theo.resam[i] <- inv.sqrt.n.resam$pval
}
if(is.element("trimfill", methods)){
options(warn = -1)
rma.resam <- rma(yi = y.resam, vi = s2.resam, method = "DL")
trimfill.resam <- pb.trimfill(rma.resam, estimator = "R0")
stat.trimfill.resam[i] <- trimfill.resam$k0
if(theo.pval) pval.trimfill.theo.resam[i] <- trimfill.resam$pval
options(warn = 0)
}
if(is.element("n", methods)){
pbn.resam <- pb.n(y = y.resam, n00 = n00.resam, n01 = n01.resam, n10 = n10.resam, n11 = n11.resam)
stat.n.resam[i] <- pbn.resam$stat
if(theo.pval) pval.n.theo.resam[i] <- pbn.resam$pval
}
if(is.element("inv.n", methods)){
inv.n.resam <- pb.inv.n(y = y.resam, n00 = n00.resam, n01 = n01.resam, n10 = n10.resam, n11 = n11.resam)
stat.inv.n.resam[i] <- inv.n.resam$stat
if(theo.pval) pval.inv.n.theo.resam[i] <- inv.n.resam$pval
}
if(is.element("as.rank", methods)){
as.rank.resam <- pb.as.rank(n00 = n00.resam, n01 = n01.resam, n10 = n10.resam, n11 = n11.resam)
stat.as.rank.resam[i] <- as.rank.resam$stat
if(theo.pval) pval.as.rank.theo.resam[i] <- as.rank.resam$pval
}
if(is.element("as.reg", methods)){
as.reg.resam <- pb.as.reg(n00 = n00.resam, n01 = n01.resam, n10 = n10.resam, n11 = n11.resam)
stat.as.reg.resam[i] <- as.reg.resam$stat
if(theo.pval) pval.as.reg.theo.resam[i] <- as.reg.resam$pval
}
if(is.element("as.reg.het", methods)){
as.reg.het.resam <- pb.as.reg.het(n00 = n00.resam, n01 = n01.resam, n10 = n10.resam, n11 = n11.resam)
stat.as.reg.het.resam[i] <- as.reg.het.resam$stat
if(theo.pval) pval.as.reg.het.theo.resam[i] <- as.reg.het.resam$pval
}
if(is.element("smoothed", methods)){
smoothed.resam <- pb.smoothed(y = y.resam, n00 = n00.resam, n01 = n01.resam, n10 = n10.resam, n11 = n11.resam)
stat.smoothed.resam[i] <- smoothed.resam$stat
if(theo.pval) pval.smoothed.theo.resam[i] <- smoothed.resam$pval
}
if(is.element("smoothed.het", methods)){
smoothed.het.resam <- pb.smoothed.het(y = y.resam, n00 = n00.resam, n01 = n01.resam, n10 = n10.resam, n11 = n11.resam)
stat.smoothed.het.resam[i] <- smoothed.het.resam$stat
if(theo.pval) pval.smoothed.het.theo.resam[i] <- smoothed.het.resam$pval
}
if(is.element("score", methods)){
score.resam <- pb.score(n00 = n00.resam, n01 = n01.resam, n10 = n10.resam, n11 = n11.resam)
stat.score.resam[i] <- score.resam$stat
if(theo.pval) pval.score.theo.resam[i] <- score.resam$pval
}
if(is.element("count", methods)){
count.resam <- pb.count(n00 = n00.ori.resam, n01 = n01.ori.resam, n10 = n10.ori.resam, n11 = n11.ori.resam)
stat.count.resam[i] <- count.resam$stat
if(theo.pval) pval.count.theo.resam[i] <- count.resam$pval
}
}
if(is.element("rank", methods)) pval.rank <- (sum(abs(stat.rank.resam) >= abs(stat.rank)) + 1)/(iter.resam + 1)
if(is.element("reg", methods)) pval.reg <- (sum(abs(stat.reg.resam) >= abs(stat.reg)) + 1)/(iter.resam + 1)
if(is.element("reg.het", methods)) pval.reg.het <- (sum(abs(stat.reg.het.resam) >= abs(stat.reg.het)) + 1)/(iter.resam + 1)
if(is.element("skew", methods)) pval.skew <- (sum(abs(stat.skew.resam) >= abs(stat.skew)) + 1)/(iter.resam + 1)
if(is.element("skew.het", methods)) pval.skew.het <- (sum(abs(stat.skew.het.resam) >= abs(stat.skew.het)) + 1)/(iter.resam + 1)
if(is.element("inv.sqrt.n", methods)) pval.inv.sqrt.n <- (sum(abs(stat.inv.sqrt.n.resam) >= abs(stat.inv.sqrt.n)) + 1)/(iter.resam + 1)
if(is.element("trimfill", methods)) pval.trimfill <- (sum(abs(stat.trimfill.resam) >= abs(stat.trimfill)) + 1)/(iter.resam + 1)
if(is.element("n", methods)) pval.n <- (sum(abs(stat.n.resam) >= abs(stat.n)) + 1)/(iter.resam + 1)
if(is.element("inv.n", methods)) pval.inv.n <- (sum(abs(stat.inv.n.resam) >= abs(stat.inv.n)) + 1)/(iter.resam + 1)
if(is.element("as.rank", methods)) pval.as.rank <- (sum(abs(stat.as.rank.resam) >= abs(stat.as.rank)) + 1)/(iter.resam + 1)
if(is.element("as.reg", methods)) pval.as.reg <- (sum(abs(stat.as.reg.resam) >= abs(stat.as.reg)) + 1)/(iter.resam + 1)
if(is.element("as.reg.het", methods)) pval.as.reg.het <- (sum(abs(stat.as.reg.het.resam) >= abs(stat.as.reg.het)) + 1)/(iter.resam + 1)
if(is.element("smoothed", methods)) pval.smoothed <- (sum(abs(stat.smoothed.resam) >= abs(stat.smoothed)) + 1)/(iter.resam + 1)
if(is.element("smoothed.het", methods)) pval.smoothed.het <- (sum(abs(stat.smoothed.het.resam) >= abs(stat.smoothed.het)) + 1)/(iter.resam + 1)
if(is.element("score", methods)) pval.score <- (sum(abs(stat.score.resam) >= abs(stat.score)) + 1)/(iter.resam + 1)
if(is.element("count", methods)) pval.count <- (sum(abs(stat.count.resam) >= abs(stat.count)) + 1)/(iter.resam + 1)
if(length(methods) == 1){
if(!theo.pval) out <- get(paste0("pval.", methods))
if(theo.pval){
out <- list(get(paste0("pval.", methods)), get(paste0("pval.", methods, ".theo")))
names(out) <- c(paste0("pval.", methods), paste0("pval.", methods, ".theo"))
}
}
if(length(methods) > 1){
stat.hybrid <- min(c(pval.rank, pval.reg, pval.reg.het, pval.skew, pval.skew.het, pval.inv.sqrt.n, pval.trimfill,
pval.n, pval.inv.n, pval.as.rank, pval.as.reg, pval.as.reg.het, pval.smoothed, pval.smoothed.het, pval.score, pval.count), na.rm = TRUE)
if(theo.pval) stat.hybrid.theo <- min(c(pval.rank.theo, pval.reg.theo, pval.reg.het.theo, pval.skew.theo, pval.skew.het.theo, pval.inv.sqrt.n.theo, pval.trimfill.theo,
pval.n.theo, pval.inv.n.theo, pval.as.rank.theo, pval.as.reg.theo, pval.as.reg.het.theo, pval.smoothed.theo, pval.smoothed.het.theo, pval.score.theo, pval.count.theo), na.rm = TRUE)
pval.rank.resam <- pval.reg.resam <- pval.reg.het.resam <- pval.skew.resam <- pval.skew.het.resam <-
pval.inv.sqrt.n.resam <- pval.trimfill.resam <-
pval.n.resam <- pval.inv.n.resam <- pval.as.rank.resam <- pval.as.reg.resam <- pval.as.reg.het.resam <-
pval.smoothed.resam <- pval.smoothed.het.resam <- pval.score.resam <- pval.count.resam <- rep(NA, iter.resam)
for(i in 1:iter.resam){
if(theo.pval) stat.hybrid.theo.resam[i] <- min(c(pval.rank.theo.resam[i], pval.reg.theo.resam[i], pval.reg.het.theo.resam[i], pval.skew.theo.resam[i], pval.skew.het.theo.resam[i], pval.inv.sqrt.n.theo.resam[i], pval.trimfill.theo.resam[i],
pval.n.theo.resam[i], pval.inv.n.theo.resam[i], pval.as.rank.theo.resam[i], pval.as.reg.theo.resam[i], pval.as.reg.het.theo.resam[i], pval.smoothed.theo.resam[i], pval.smoothed.het.theo.resam[i], pval.score.theo.resam[i], pval.count.theo.resam[i]), na.rm = TRUE)
if(is.element("rank", methods)) pval.rank.resam[i] <- (sum(abs(stat.rank.resam[-i]) >= abs(stat.rank.resam[i])) + 1)/iter.resam
if(is.element("reg", methods)) pval.reg.resam[i] <- (sum(abs(stat.reg.resam[-i]) >= abs(stat.reg.resam[i])) + 1)/iter.resam
if(is.element("reg.het", methods)) pval.reg.het.resam[i] <- (sum(abs(stat.reg.het.resam[-i]) >= abs(stat.reg.het.resam[i])) + 1)/iter.resam
if(is.element("skew", methods)) pval.skew.resam[i] <- (sum(abs(stat.skew.resam[-i]) >= abs(stat.skew.resam[i])) + 1)/iter.resam
if(is.element("skew.het", methods)) pval.skew.het.resam[i] <- (sum(abs(stat.skew.het.resam[-i]) >= abs(stat.skew.het.resam[i])) + 1)/iter.resam
if(is.element("inv.sqrt.n", methods)) pval.inv.sqrt.n.resam[i] <- (sum(abs(stat.inv.sqrt.n.resam[-i]) >= abs(stat.inv.sqrt.n.resam[i])) + 1)/iter.resam
if(is.element("trimfill", methods)) pval.trimfill.resam[i] <- (sum(abs(stat.trimfill.resam[-i]) >= abs(stat.trimfill.resam[i])) + 1)/iter.resam
if(is.element("n", methods)) pval.n.resam[i] <- (sum(abs(stat.n.resam[-i]) >= abs(stat.n.resam[i])) + 1)/iter.resam
if(is.element("inv.n", methods)) pval.inv.n.resam[i] <- (sum(abs(stat.inv.n.resam[-i]) >= abs(stat.inv.n.resam[i])) + 1)/iter.resam
if(is.element("as.rank", methods)) pval.as.rank.resam[i] <- (sum(abs(stat.as.rank.resam[-i]) >= abs(stat.as.rank.resam[i])) + 1)/iter.resam
if(is.element("as.reg", methods)) pval.as.reg.resam[i] <- (sum(abs(stat.as.reg.resam[-i]) >= abs(stat.as.reg.resam[i])) + 1)/iter.resam
if(is.element("as.reg.het", methods)) pval.as.reg.het.resam[i] <- (sum(abs(stat.as.reg.het.resam[-i]) >= abs(stat.as.reg.het.resam[i])) + 1)/iter.resam
if(is.element("smoothed", methods)) pval.smoothed.resam[i] <- (sum(abs(stat.smoothed.resam[-i]) >= abs(stat.smoothed.resam[i])) + 1)/iter.resam
if(is.element("smoothed.het", methods)) pval.smoothed.het.resam[i] <- (sum(abs(stat.smoothed.het.resam[-i]) >= abs(stat.smoothed.het.resam[i])) + 1)/iter.resam
if(is.element("score", methods)) pval.score.resam[i] <- (sum(abs(stat.score.resam[-i]) >= abs(stat.score.resam[i])) + 1)/iter.resam
if(is.element("count", methods)) pval.count.resam[i] <- (sum(abs(stat.count.resam[-i]) >= abs(stat.count.resam[i])) + 1)/iter.resam
stat.hybrid.resam[i] <- min(c(pval.rank.resam[i], pval.reg.resam[i], pval.reg.het.resam[i], pval.skew.resam[i], pval.skew.het.resam[i], pval.inv.sqrt.n.resam[i], pval.trimfill.resam[i],
pval.n.resam[i], pval.inv.n.resam[i], pval.as.rank.resam[i], pval.as.reg.resam[i], pval.as.reg.het.resam[i], pval.smoothed.resam[i], pval.smoothed.het.resam[i], pval.score.resam[i], pval.count.resam[i]), na.rm = TRUE)
}
pval.hybrid <- (sum(stat.hybrid.resam <= stat.hybrid) + 1)/(iter.resam + 1)
if(!theo.pval){
out <- list(pval.rank = pval.rank, pval.reg = pval.reg, pval.reg.het = pval.reg.het, pval.skew = pval.skew, pval.skew.het = pval.skew.het,
pval.inv.sqrt.n = pval.inv.sqrt.n, pval.trimfill = pval.trimfill,
pval.n = pval.n, pval.inv.n = pval.inv.n, pval.as.rank = pval.as.rank, pval.as.reg = pval.as.reg, pval.as.reg.het = pval.as.reg.het,
pval.smoothed = pval.smoothed, pval.smoothed.het = pval.smoothed.het, pval.score = pval.score, pval.count = pval.count,
pval.hybrid = pval.hybrid)
}
if(theo.pval){
pval.hybrid.theo <- (sum(stat.hybrid.theo.resam <= stat.hybrid.theo) + 1)/(iter.resam + 1)
out <- list(pval.rank = pval.rank, pval.rank.theo = pval.rank.theo, pval.reg = pval.reg, pval.reg.theo = pval.reg.theo, pval.reg.het = pval.reg.het, pval.reg.het.theo = pval.reg.het.theo, pval.skew = pval.skew, pval.skew.theo = pval.skew.theo, pval.skew.het = pval.skew.het, pval.skew.het.theo = pval.skew.het.theo,
pval.inv.sqrt.n = pval.inv.sqrt.n, pval.inv.sqrt.n.theo = pval.inv.sqrt.n.theo, pval.trimfill = pval.trimfill, pval.trimfill.theo = pval.trimfill.theo,
pval.n = pval.n, pval.n.theo = pval.n.theo, pval.inv.n = pval.inv.n, pval.inv.n.theo = pval.inv.n.theo, pval.as.rank = pval.as.rank, pval.as.rank.theo = pval.as.rank.theo, pval.as.reg = pval.as.reg, pval.as.reg.theo = pval.as.reg.theo, pval.as.reg.het = pval.as.reg.het, pval.as.reg.het.theo = pval.as.reg.het.theo,
pval.smoothed = pval.smoothed, pval.smoothed.theo = pval.smoothed.theo, pval.smoothed.het = pval.smoothed.het, pval.smoothed.het.theo = pval.smoothed.het.theo, pval.score = pval.score, pval.score.theo = pval.score.theo, pval.count = pval.count, pval.count.theo = pval.count.theo,
pval.hybrid = pval.hybrid, pval.hybrid.theo = pval.hybrid.theo)
}
na.test <- which(is.na(out))
if(length(na.test) > 0) out <- out[-na.test]
}
return(out)
} |
logtpdfL = function(logDetGamma, mahalx, alpha, L){
y = lgamma(alpha+L/2) - lgamma(alpha) - (L/2)*log(2*pi) - logDetGamma - (alpha+L/2)*(log(mahalx/2 + 1));
return(y)} |
heatmapCol <- function(data, col, lim, na.rm = TRUE){
nrcol <- length(col)
data.range <- range(data, na.rm = na.rm)
if(diff(data.range) == 0)
stop("data has range 0")
if(lim <= 0)
stop("lim has to be positive")
if(lim > min(abs(data.range))){
warning("specified bound 'lim' is out of data range\n
hence 'min(abs(range(data)))' is used")
lim <- min(abs(data.range))
}
nrcol <- length(col)
reps1 <- ceiling(nrcol*(-lim-data.range[1])/(2*lim))
reps2 <- ceiling(nrcol*(data.range[2]-lim)/(2*lim))
col1 <- c(rep(col[1], reps1), col, rep(col[nrcol], reps2))
return(col1)
} |
testthat::skip_if_not(requireNamespace("maptools"))
library(maptools)
library(testthat)
library(spbabel)
data(wrld_simpl)
data("mpoint1")
polytab <- spbabel::sptable(wrld_simpl)
polynames <- c("object_", "branch_", "island_", "order_", "x_", "y_")
polytypes <- setNames(c("integer", "integer", "logical", "integer", "numeric", "numeric"), polynames)
linetab <- spbabel::sptable(as(wrld_simpl, "SpatialLinesDataFrame"))
linenames <- c("object_", "branch_", "order_", "x_", "y_")
linetypes <- setNames(c("integer", "integer", "integer", "numeric", "numeric"), linenames)
spts <- as(as(wrld_simpl, "SpatialLinesDataFrame"), "SpatialPointsDataFrame")
pointtab <- spbabel::sptable(spts)
pointnames <- c("object_", "x_", "y_")
pointtypes <- setNames(c("integer", "numeric", "numeric"), pointnames)
multitab <- spbabel::sptable(mpoint1)
multinames <- c("branch_", "object_", "x_", "y_")
multitypes <- setNames(c("integer", "integer", "numeric", "numeric"), multinames)
context("safety catch in case the column order changes")
test_that("sptable names is the same", {
expect_equal(names(polytab), polynames)
expect_equal(names(linetab), linenames)
})
context("sptable")
test_that("sptable structure is sound", {
expect_equal(sort(names(polytab)), sort(polynames))
expect_equal(sapply(polytab, class)[polynames], polytypes)
expect_equal(sort(names(linetab)), sort(linenames))
expect_equal(sapply(linetab, class)[linenames], linetypes)
})
context("points")
test_that("sptable points structure is sound", {
expect_true(all(pointnames %in% names(pointtab)))
expect_equal(sapply(pointtab, class)[pointnames], pointtypes)
expect_equal(sort(names(multitab)), sort(multinames))
expect_equal(sapply(multitab, class)[multinames], multitypes)
})
context("holes")
test_that("hole checking", {
expect_that(sptable(sp(holey)), is_a("tbl_df"))
}) |
lava.options <- function(...) {
dots <- list(...)
newopt <- curopt <- get("options",envir=lava.env)
if (length(dots)==0)
return(curopt[order(names(curopt))])
if (length(dots)==1 && is.list(dots[[1]]) && is.null(names(dots))) {
dots <- dots[[1]]
}
idx <- which(names(dots)!="")
newopt[names(dots)[idx]] <- dots[idx]
assign("options",newopt,envir=lava.env)
invisible(curopt)
}
gethook <- function(hook="estimate.hooks",...) {
get(hook,envir=lava.env)
}
addhook <- function(x,hook="estimate.hooks",...) {
newhooks <- unique(c(gethook(hook),x))
assign(hook,newhooks,envir=lava.env)
invisible(newhooks)
}
versioncheck <- function(pkg="lava",geq,sep=".",...) {
xyz <- tryCatch(
char2num(strsplit(as.character(packageVersion(pkg)),sep,fixed=TRUE)[[1]]),
error=function(x) NULL)
if (is.null(xyz)) return(FALSE)
if (missing(geq)) return(xyz)
for (i in seq(min(length(xyz),length(geq)))) {
if (xyz[i]>geq[i]) return(TRUE)
if (xyz[i]<geq[i]) return(FALSE)
}
if (length(xyz)>=length(geq)) return(TRUE)
return(FALSE)
}
lava.env <- new.env()
assign("init.hooks",c(),envir=lava.env)
assign("remove.hooks",c(),envir=lava.env)
assign("estimate.hooks",c(),envir=lava.env)
assign("color.hooks",c(),envir=lava.env)
assign("sim.hooks",c(),envir=lava.env)
assign("post.hooks",c(),envir=lava.env)
assign("print.hooks",c(),envir=lava.env)
assign("plot.post.hooks",c(),envir=lava.env)
assign("plot.hooks",c(),envir=lava.env)
assign("options", list(
trace=0,
tol=1e-6,
gamma=1,
backtrack="wolfe",
ngamma=0,
iter.max=300,
eval.max=250,
constrain=FALSE,
allow.negative.variance=FALSE,
progressbarstyle=3,
itol=1e-16,
cluster.index=versioncheck("mets",c(0,2,7)),
tobit=versioncheck("lava.tobit",c(0,5)),
Dmethod="simple",
messages=ifelse(interactive(), 1, 0),
parallel=TRUE,
param="relative",
sparse=FALSE,
test=TRUE,
coef.names=FALSE,
constrain=TRUE,
graph.proc="beautify",
regex=FALSE,
min.weight=1e-3,
exogenous=TRUE,
plot.engine="Rgraphviz",
node.color=c(exogenous="lightblue",endogenous="orange",
latent="yellowgreen",transform="lightgray"),
edgecolor=FALSE,
layout="dot",
symbols=c("~","~~"),
devel=FALSE,
debug=FALSE), envir=lava.env) |
create_probs <- function(input.obj = NULL,
global_error = NULL,
genotypes_errors = NULL,
genotypes_probs = NULL){
if(!(is(input.obj,"onemap") | is(input.obj,"sequence"))){
stop("input.obj should be of class onemap or sequence")
}
if(is(input.obj, "sequence")) {
seq.obj <- input.obj
input.obj <- input.obj$data.name
flag <- TRUE
} else {
flag <- FALSE
}
if(input.obj$n.mar == 0){
warning("It is a empty onemap object. Nothing will be done.")
return(input.obj)
}
if(all(is.null(c(global_error, genotypes_errors, genotypes_probs)))){
global_error <- 10^-5
}
crosstype <- class(input.obj)[2]
probs <- melt(t(input.obj$geno))
probs$type <- rep(input.obj$segr.type.num, input.obj$n.ind)
if(!is.null(global_error) | !is.null(genotypes_errors)){
if(!is.null(global_error)) {
error <- rep(global_error, length(probs$value))
} else {
if(!all(colnames(input.obj$geno)%in%colnames(genotypes_errors))){
stop("Not all markers in onemap object have corresponding genotype errors in matrix")
}
if(!all(colnames(genotypes_errors)%in%colnames(input.obj$geno))){
stop("There are more markers in errors matrix than in onemap object")
}
if(!all(rownames(input.obj$geno)%in%rownames(genotypes_errors))){
stop("Not all individuals in onemap object have corresponding genotype errors in matrix")
}
if(!all(rownames(input.obj$geno)%in%rownames(genotypes_errors))){
stop("There are more individuals in errors matrix than in onemap object")
}
error <- melt(t(genotypes_errors))
error <- error$value
}
if(crosstype == "outcross" | crosstype == "f2"){
prob <- matrix(NA, nrow=length(probs$value), ncol = 4)
idx <- which(probs$value == 0)
prob[idx,] <- 1
idx <- which(is.na(error))
prob[idx,] <- 1
idx <- which(probs$value == 1 & probs$type == 1)
prob[idx,] <- c(1-error[idx], rep(error[idx]/3,3))
idx <- which(probs$value == 2 & probs$type == 1)
prob[idx,] <- c(error[idx]/3, 1-error[idx], rep(error[idx]/3,2))
idx <- which(probs$value == 3 & probs$type == 1)
prob[idx,] <- c(rep(error[idx]/3,2), 1-error[idx], error[idx]/3)
idx <- which(probs$value == 4 & probs$type == 1)
prob[idx,] <- c(rep(error[idx]/3,3), 1-error[idx])
idx <- which(probs$value == 1 & probs$type == 2)
prob[idx,] <- c(rep(1-error[idx],2), rep(error[idx],2))
idx <- which(probs$value == 2 & probs$type == 2)
prob[idx,] <- c(rep(error[idx]/3,2), 1-error[idx], error[idx]/3)
idx <- which(probs$value == 3 & probs$type == 2)
prob[idx,] <- c(rep(error[idx]/3,3), 1-error[idx])
idx <- which(probs$value == 1 & probs$type == 3)
prob[idx,] <- c(1-error[idx], error[idx], 1-error[idx], error[idx])
idx <- which(probs$value == 2 & probs$type == 3)
prob[idx,] <- c(error[idx]/3, 1-error[idx], rep(error[idx]/3,2))
idx <- which(probs$value == 3 & probs$type == 3)
prob[idx,] <- c(rep(error[idx]/3,3), 1-error[idx])
idx <- which(probs$value == 1 & probs$type == 4)
prob[idx,] <- c(1-error[idx], rep(error[idx]/3,3))
idx <- which(probs$value == 2 & probs$type == 4)
prob[idx,] <- c(error[idx], rep(1-error[idx],2), error[idx])
idx <- which(probs$value == 3 & probs$type == 4)
prob[idx,] <- c(rep(error[idx]/3,3), 1-error[idx])
idx <- which(probs$value == 1 & probs$type == 5)
prob[idx,] <- c(rep((1-error[idx])/3,3), error[idx])
idx <- which(probs$value == 2 & probs$type == 5)
prob[idx,] <- c(rep(error[idx]/3,3), 1-error[idx])
idx <- which(probs$value == 1 & probs$type == 6)
prob[idx,] <- c(rep(1-error[idx],2), rep(error[idx],2))
idx <- which(probs$value == 2 & probs$type == 6)
prob[idx,] <- c(rep(error[idx],2), rep(1-error[idx],2))
idx <- which(probs$value == 3 & probs$type == 6)
prob[idx,] <- 1
idx <- which(probs$value == 1 & probs$type == 7)
prob[idx,] <- c(1-error[idx], error[idx], 1-error[idx], error[idx])
idx <- which(probs$value == 2 & probs$type == 7)
prob[idx,] <- c(error[idx], 1-error[idx], error[idx], 1-error[idx])
idx <- which(probs$value == 3 & probs$type == 7)
prob[idx,] <- 1
} else if(crosstype == "backcross" | crosstype == "riself" | crosstype == "risib"){
prob <- matrix(NA, nrow=length(probs$value), ncol = 2)
idx <- which(probs$value == 0)
prob[idx,] <- 1
idx <- which(probs$value == 1)
prob[idx,] <- c(1- error[idx], error[idx])
idx <- which(probs$value == 2)
prob[idx,] <- c(error[idx], 1-error[idx])
idx <- which(probs$value == 3)
prob[idx,] <- c(error[idx], 1-error[idx])
}
}
if(!is.null(genotypes_probs)){
if(crosstype == "outcross" | crosstype == "f2"){
prob.temp <- matrix(NA, nrow=length(probs$value), ncol = 3)
prob.temp[,2] <- genotypes_probs[,2]
het.idx <- which(probs$value == 2)
hom1.idx <- which(probs$value == 1)
if(length(hom1.idx) > 1){
sub <- genotypes_probs[hom1.idx,-2]
} else {
sub <- t(as.matrix(genotypes_probs[hom1.idx,-2]))
}
for_het <- table(apply(sub,1, which.max))
for_het <- as.numeric(which.max(for_het))
if(for_het == 2){
prob.temp[het.idx,3] <- genotypes_probs[het.idx,1]
prob.temp[het.idx,1] <- genotypes_probs[het.idx,3]
} else {
prob.temp[het.idx,1] <- genotypes_probs[het.idx,1]
prob.temp[het.idx,3] <- genotypes_probs[het.idx,3]
}
hom1.idx.prob <- which(apply(sub,1, which.max) == 1)
prob.temp[hom1.idx[hom1.idx.prob],1] <- genotypes_probs[hom1.idx[hom1.idx.prob], 1]
prob.temp[hom1.idx[hom1.idx.prob],3] <- genotypes_probs[hom1.idx[hom1.idx.prob], 3]
hom1.idx.prob <- which(apply(sub,1, which.max) == 2)
prob.temp[hom1.idx[hom1.idx.prob],1] <- genotypes_probs[hom1.idx[hom1.idx.prob], 3]
prob.temp[hom1.idx[hom1.idx.prob],3] <- genotypes_probs[hom1.idx[hom1.idx.prob], 1]
hom3.idx <- which(probs$value == 3)
if(length(hom3.idx) > 1){
sub <- genotypes_probs[hom3.idx,-2]
} else {
sub <- t(as.matrix(genotypes_probs[hom3.idx,-2]))
}
hom3.idx.prob <- which(apply(sub,1, which.max) == 1)
prob.temp[hom3.idx[hom3.idx.prob],3] <- genotypes_probs[hom3.idx[hom3.idx.prob], 1]
prob.temp[hom3.idx[hom3.idx.prob],1] <- genotypes_probs[hom3.idx[hom3.idx.prob], 3]
hom3.idx.prob <- which(apply(sub,1, which.max) == 2)
prob.temp[hom3.idx[hom3.idx.prob],3] <- genotypes_probs[hom3.idx[hom3.idx.prob], 3]
prob.temp[hom3.idx[hom3.idx.prob],1] <- genotypes_probs[hom3.idx[hom3.idx.prob], 1]
prob <- matrix(NA, nrow=length(probs$value), ncol = 4)
idx <- which(probs$type == 4)
prob[idx,] <- cbind(prob.temp[idx,1], prob.temp[idx,2], prob.temp[idx,2], prob.temp[idx,3])
idx <- which(probs$type == 6)
prob[idx,] <- cbind(prob.temp[idx,1], prob.temp[idx,1], prob.temp[idx,2], prob.temp[idx,2])
idx <- which(probs$type == 7)
prob[idx,] <- cbind(prob.temp[idx,1], prob.temp[idx,2], prob.temp[idx,1], prob.temp[idx,2])
idx <- which(probs$value == 0)
prob[idx,] <- 1
} else {
prob.temp <- matrix(NA, nrow=length(probs$value), ncol = 3)
prob.temp[,2] <- genotypes_probs[,2]
het.idx <- which(probs$value == 2)
hom1.idx <- which(probs$value == 1)
if(length(hom1.idx) > 1){
sub <- genotypes_probs[hom1.idx,-2]
} else {
sub <- t(as.matrix(genotypes_probs[hom1.idx,-2]))
}
hom1.idx.prob <- unique(apply(genotypes_probs[hom1.idx,],1, which.max))
prob.temp[hom1.idx,1] <- genotypes_probs[hom1.idx, hom1.idx.prob]
if(hom1.idx.prob == 3){
prob.temp[hom1.idx,3] <- genotypes_probs[hom1.idx, 1]
prob.temp[het.idx,3] <- genotypes_probs[het.idx,1]
prob.temp[het.idx,1] <- genotypes_probs[het.idx,3]
} else {
prob.temp[hom1.idx,3] <- genotypes_probs[hom1.idx, 3]
prob.temp[het.idx,1] <- genotypes_probs[het.idx,1]
prob.temp[het.idx,3] <- genotypes_probs[het.idx,3]
}
hom3.idx <- which(probs$value == 3)
if(length(hom3.idx) > 1){
sub <- genotypes_probs[hom3.idx,-2]
} else {
sub <- t(as.matrix(genotypes_probs[hom3.idx,-2]))
}
hom3.idx.prob <- unique(apply(genotypes_probs[hom3.idx,],1, which.max))
prob.temp[hom3.idx,3] <- genotypes_probs[hom3.idx, hom3.idx.prob]
if(hom3.idx.prob == 3){
prob.temp[hom3.idx,1] <- genotypes_probs[hom3.idx, 1]
} else {
prob.temp[hom3.idx,1] <- genotypes_probs[hom3.idx, 3]
}
if(crosstype == "backcross" | crosstype == "riself" | crosstype == "risib") {
prob <- matrix(NA, nrow=length(probs$value), ncol = 2)
idx <- which(probs$value == 1)
prob[idx,] <- cbind(prob.temp[idx,1], prob.temp[idx,2])
idx <- which(probs$value == 2)
prob[idx,] <- cbind(prob.temp[idx,1], prob.temp[idx,2])
idx <- which(probs$value == 3)
prob[idx,] <- cbind(prob.temp[idx,1], prob.temp[idx,3])
idx <- which(probs$value == 0)
prob[idx,] <- 1
}
}
}
rownames(prob) <- paste0(probs$Var1, "_", probs$Var2)
input.obj$error<- t(apply(prob, 1, function(x) if(all(is.na(x))) rep(1, 4) else x))
if(flag) {
seq.obj$data.name <- input.obj
seq.obj$twopt$data.name <- input.obj
input.obj <- seq.obj
}
return(input.obj)
} |
create_hn_api_response <- function(response) {
parsed_content <- parse_json(response)
structure(
list(
content = parsed_content,
path = response$url,
response = response
),
class = "hn_api_response"
)
}
is_hn_api_response <- function(x) {
inherits(x, "hn_api_response")
}
get_content <- function(x) {
assert(is_hn_api_response(x))
x$content
}
validate_hn_api_response <- function(hn_api_response) {
assert(!httr::http_error(hn_api_response$response),
sprintf("The request resulted with an error [%s]\n%s\n<%s>",
hn_api_response$response$status_code,
hn_api_response$content,
hn_api_response$path))
if (is.null(hn_api_response$content)) {
warning(
sprintf("The content of the response is empty!\n<%s>", hn_api_response$path)
)
}
}
print.hn_api_response <- function(x, ...) {
cat(sprintf("---HN API RESPONSE [%s][%s]---", x$path, x$response$status_code))
utils::str(x$content)
} |
ICESAcoustic <- function(AcousticData){
ICESAcousticData <- lapply(
AcousticData,
AcousticDataToICESAcousticOne
)
return(ICESAcousticData)
}
AcousticDataToICESAcousticOne <- function(AcousticDataOne){
if(AcousticDataOne$metadata$useXsd=='icesAcoustic'){
ICESAcousticDataOne <- AcousticData_ICESToICESAcousticOne(AcousticDataOne)
}
else{
stop('StoX: only ices acoustic format is allowed')
}
return(ICESAcousticDataOne)
}
AcousticData_ICESToICESAcousticOne <- function(AcousticData_ICESOne){
ICESAcousticDataOne <- data.table::copy(AcousticData_ICESOne)
ICESAcousticDataOne$Data$EchoType<-NULL
independentTables <- c("Instrument", "Calibration", "DataAcquisition", "DataProcessing")
hierarchicalTables <- c("Cruise", "Log", "Sample", "Data")
tablesToKeep <- c(independentTables, hierarchicalTables)
ICESAcousticDataOne$Cruise$Survey <- utils::tail(ICESAcousticDataOne$Survey$Code, 1)
if(length(ICESAcousticDataOne$vocabulary)) {
vocabulary <- findVariablesMathcinigVocabulary(
vocabulary = ICESAcousticDataOne$vocabulary,
data = ICESAcousticDataOne[tablesToKeep]
)
vocabulary <- unique(vocabulary)
ICESAcousticDataOne[tablesToKeep] <- translateVariables(
data = ICESAcousticDataOne[tablesToKeep],
Translation = vocabulary,
translate.keys = TRUE,
warnMissingTranslation = FALSE
)
}
compareICES('https://acoustic.ices.dk/Services/Schema/XML/AC_TransducerLocation.xml',unique(ICESAcousticDataOne$Instrument$TransducerLocation))
compareICES('https://acoustic.ices.dk/Services/Schema/XML/AC_TransducerBeamType.xml',unique(ICESAcousticDataOne$Instrument$TransducerBeamType))
compareICES('https://acoustic.ices.dk/Services/Schema/XML/AC_AcquisitionMethod.xml',unique(ICESAcousticDataOne$Calibration$AcquisitionMethod))
compareICES('https://acoustic.ices.dk/Services/Schema/XML/AC_ProcessingMethod.xml',unique(ICESAcousticDataOne$Calibration$ProcessingMethod))
compareICES('https://acoustic.ices.dk/Services/Schema/XML/AC_DataAcquisitionSoftwareName.xml',unique(ICESAcousticDataOne$DataAcquisition$SoftwareName))
compareICES('https://acoustic.ices.dk/Services/Schema/XML/AC_StoredDataFormat.xml',unique(ICESAcousticDataOne$DataAcquisition$StoredDataFormat))
compareICES('https://acoustic.ices.dk/Services/Schema/XML/AC_DataAcquisitionSoftwareName.xml',unique(ICESAcousticDataOne$DataAcquisition$SoftwareName))
compareICES('https://acoustic.ices.dk/Services/Schema/XML/AC_DataProcessingSoftwareName.xml',unique(ICESAcousticDataOne$DataProcessing$SoftwareName))
compareICES('https://acoustic.ices.dk/Services/Schema/XML/AC_TriwaveCorrection.xml',unique(ICESAcousticDataOne$DataProcessing$TriwaveCorrection))
compareICES('https://acoustic.ices.dk/Services/Schema/XML/AC_OnAxisGainUnit.xml',unique(ICESAcousticDataOne$DataProcessing$OnAxisGainUnit))
compareICES('https://acoustic.ices.dk/Services/Schema/XML/ISO_3166.xml',unique(ICESAcousticDataOne$Cruise$Country))
compareICES('https://acoustic.ices.dk/Services/Schema/XML/SHIPC.xml',unique(ICESAcousticDataOne$Cruise$Platform))
compareICES('https://acoustic.ices.dk/Services/Schema/XML/EDMO.xml',unique(ICESAcousticDataOne$Cruise$Organisation))
compareICES('https://acoustic.ices.dk/Services/Schema/XML/AC_Survey.xml',unique(ICESAcousticDataOne$Survey$Code))
compareICES('https://acoustic.ices.dk/Services/Schema/XML/AC_LogOrigin.xml',unique(ICESAcousticDataOne$Log$Origin))
compareICES('https://acoustic.ices.dk/Services/Schema/XML/AC_LogValidity.xml',unique(ICESAcousticDataOne$Log$Validity))
compareICES('https://acoustic.ices.dk/Services/Schema/XML/AC_PingAxisIntervalType.xml',unique(ICESAcousticDataOne$Sample$PingAxisIntervalType))
compareICES('https://acoustic.ices.dk/Services/Schema/XML/AC_PingAxisIntervalUnit.xml',unique(ICESAcousticDataOne$Sample$PingAxisIntervalUnit))
compareICES('https://acoustic.ices.dk/Services/Schema/XML/AC_PingAxisIntervalOrigin.xml',unique(ICESAcousticDataOne$Sample$PingAxisIntervalOrigin))
compareICES('https://acoustic.ices.dk/Services/Schema/XML/AC_SaCategory.xml',unique(ICESAcousticDataOne$Data$SaCategory))
compareICES('https://acoustic.ices.dk/Services/Schema/XML/AC_AcousticDataType.xml',unique(ICESAcousticDataOne$Data$Type))
compareICES('https://acoustic.ices.dk/Services/Schema/XML/AC_DataUnit.xml',unique(ICESAcousticDataOne$Data$Unit))
independentTablesColumnNames <- lapply(ICESAcousticDataOne[independentTables], names)
independentTablesNewColumnNames <- mapply(paste0, independentTables, independentTablesColumnNames)
mapply(
data.table::setnames,
ICESAcousticDataOne[independentTables],
old = independentTablesColumnNames,
new = independentTablesNewColumnNames
)
renameToTableNameFirst(
ICESAcousticDataOne,
tableNames = hierarchicalTables,
setToID = independentTables,
formatType = "Acoustic"
)
hierarchicalTablesSansCruise <- setdiff(hierarchicalTables, "Cruise")
LogSampleData <- RstoxData::mergeDataTables(ICESAcousticDataOne[hierarchicalTablesSansCruise], output.only.last = TRUE, all = TRUE)
LogSampleData <- unique(LogSampleData)
ICESAcousticDataOne <- c(
ICESAcousticDataOne[c("Instrument", "Calibration", "DataAcquisition", "DataProcessing", "Cruise")],
list(Data = LogSampleData)
)
ICESAcousticDataOne <- lapply(ICESAcousticDataOne, moveIDsLast)
return(ICESAcousticDataOne)
}
WriteICESAcoustic <- function(ICESAcousticData){
WriteICESAcousticData <- lapply(
ICESAcousticData,
WriteICESAcousticOne
)
return(WriteICESAcousticData)
}
WriteICESAcousticOne <- function(ICESAcousticDataOne){
ICESAcousticCSVDataOne <- convertToHeaderRecordMatrix(ICESAcousticDataOne)
ICESAcousticCSVDataOne <- expandWidth(ICESAcousticCSVDataOne)
ICESAcousticCSVDataOne <- do.call(rbind, ICESAcousticCSVDataOne)
return(ICESAcousticCSVDataOne)
}
convertToHeaderRecordMatrix <- function(ICESData) {
lapply(names(ICESData), createHeaderRecordMatrix, ICESData = ICESData)
}
createHeaderRecordMatrix <- function(ICESDataTableName, ICESData) {
thisTable <- ICESData[[ICESDataTableName]]
header <- c(
ICESDataTableName,
"Header",
names(thisTable)
)
record <- cbind(
ICESDataTableName,
"Record",
as.matrix(thisTable)
)
unname(rbind(header, record))
}
convertToRecordTypeMatrix <- function(ICESData) {
lapply(names(ICESData), createRecordTypeMatrix, ICESData = ICESData)
}
createRecordTypeMatrix <- function(ICESDataTableName, ICESData) {
thisTable <- ICESData[[ICESDataTableName]]
header <- c(
"RecordType",
names(thisTable)
)
record <- cbind(
ICESDataTableName,
trimws(as.matrix(thisTable))
)
unname(rbind(header, record))
}
moveIDsLast <- function(x) {
endsWithID <- endsWith(names(x), "ID")
data.table::setcolorder(x, c(names(x)[!endsWithID], names(x)[endsWithID]))
}
expandWidth <- function(x, na = NA) {
ncols <- sapply(x, ncol)
nrows <- sapply(x, nrow)
dims <- cbind(nrows, max(ncols) - ncols)
dimsList <- split(dims, seq_along(x))
NAArrays <- mapply(array, dim = dimsList, SIMPLIFY = FALSE, MoreArgs = list(data = na))
mapply(cbind, x, NAArrays, SIMPLIFY = FALSE)
}
ICESBiotic <- function(
BioticData,
SurveyName = character(),
Country = character(),
Organisation = integer(),
AllowRemoveSpecies = TRUE
) {
ICESBioticData <- lapply(
BioticData,
BioticDataToICESBioticOne,
SurveyName = SurveyName,
Country = Country,
Organisation = Organisation,
AllowRemoveSpecies = AllowRemoveSpecies
)
return(ICESBioticData)
}
BioticDataToICESBioticOne <- function(
BioticDataOne,
SurveyName = character(),
Country = character(),
Organisation = integer(),
AllowRemoveSpecies = TRUE
) {
if(BioticDataOne$metadata$useXsd %in% "icesBiotic") {
ICESBioticDataOne <- BioticData_ICESToICESBioticOne(BioticDataOne)
}
else if(BioticDataOne$metadata$useXsd %in% c("nmdbioticv3", "nmdbioticv3.1")) {
ICESBioticDataOne <- BioticData_NMDToICESBioticOne(
BioticDataOne,
SurveyName = SurveyName,
Country = Country,
Organisation = Organisation,
AllowRemoveSpecies = AllowRemoveSpecies
)
}
else {
warning("StoX: Only NMD Biotic version 3 and 3.1 data can be converted to ICESBiotic (was ", BioticDataOne$metadata$useXsd, " for the file ", BioticDataOne$metadata$file, ". NA returned.")
return(NULL)
}
hierarchicalTables <- c("Cruise", "Haul", "Catch", "Biology")
ICESBioticDataOne <- ICESBioticDataOne[hierarchicalTables]
renameToTableNameFirst(
ICESBioticDataOne,
tableNames = hierarchicalTables,
formatType = "Biotic"
)
ICESBioticDataOne <- lapply(ICESBioticDataOne, moveIDsLast)
return(ICESBioticDataOne)
}
BioticData_ICESToICESBioticOne <- function(BioticData_ICESOne) {
BioticDataOne <- data.table::copy(BioticData_ICESOne)
BioticDataOne$Cruise$Survey <- utils::tail(BioticDataOne$Survey$Code, 1)
tablesToTranslate <- c("Cruise", "Haul", "Catch", "Biology")
if(length(BioticDataOne$vocabulary)) {
vocabulary <- findVariablesMathcinigVocabulary(
vocabulary = BioticDataOne$vocabulary,
data = BioticDataOne[tablesToTranslate]
)
vocabulary <- unique(vocabulary)
BioticDataOne[tablesToTranslate] <- translateVariables(
data = BioticDataOne[tablesToTranslate],
Translation = vocabulary,
translate.keys = TRUE,
warnMissingTranslation = FALSE
)
}
return(BioticDataOne)
}
BioticData_NMDToICESBioticOne <- function(
BioticData_NMDOne,
SurveyName = character(),
Country = character(),
Organisation = integer(),
AllowRemoveSpecies = TRUE
) {
cruiseRaw <- BioticData_NMDOne$mission
if(!all(length(SurveyName), length(Country), length(Organisation))) {
stop("All of SurveyName, Country and Organisation must be given.")
}
Cruise <- cruiseRaw[, .(
Survey = ..SurveyName,
Country = ..Country,
Organisation = ..Organisation,
Platform = getICESShipCode(platformname),
StartDate = gsub("Z", "", missionstartdate),
EndDate = gsub("Z", "", missionstopdate),
LocalID = cruise
)]
haulRaw <- merge(cruiseRaw, BioticData_NMDOne$fishstation)
Haul <- haulRaw[, .(
LocalID = cruise,
Gear = gear,
Number = serialnumber,
StationName = station,
StartTime = ifelse(is.na(stationstartdate) | is.na(stationstarttime), NA, gsub("Z", " ", paste0(stationstartdate, substr(stationstarttime, 1, 5)))),
Duration = getTimeDiff(stationstartdate, stationstarttime, stationstopdate, stationstoptime),
Validity = getHaulValiditySimple(gearcondition, samplequality),
StartLatitude = latitudestart,
StartLongitude = longitudestart,
StopLatitude = latitudeend,
StopLongitude = longitudeend,
StatisticalRectangle = getICESrect(latitudestart, longitudestart),
MinTrawlDepth = ifelse(is.na(fishingdepthmin), fishingdepthmax, fishingdepthmin),
MaxTrawlDepth = fishingdepthmax,
BottomDepth = ifelse(bottomdepthstop > fishingdepthmax, bottomdepthstop, NA),
Distance = getDistanceMeter(latitudestart, longitudestart, latitudeend, longitudeend),
Netopening = verticaltrawlopening,
CodendMesh = NA,
SweepLength = sweeplength,
GearExceptions = NA,
DoorType = trawldoortype,
WarpLength = round(wirelength),
WarpDiameter = round(wirediameter),
WarpDensity = round(wiredensity),
DoorSurface = trawldoorarea,
DoorWeight = round(trawldoorweight),
DoorSpread = trawldoorspread,
WingSpread = wingspread,
Buoyancy = NA,
KiteArea = NA,
GroundRopeWeight = NA,
Rigging = NA,
Tickler = NA,
HydrographicStationID = NA,
TowDirection = round(direction),
SpeedGround = NA,
SpeedWater = gearflow,
WindDirection = winddirection,
WindSpeed = round(windspeed),
SwellDirection = NA,
SwellHeight = NA,
LogDistance = logstart,
Stratum = NA
)]
catchRaw <- merge(BioticData_NMDOne$catchsample, haulRaw, by = intersect(names(BioticData_NMDOne$catchsample), names(haulRaw)))
catchRaw <- catchRaw[!is.na(aphia)]
Catch <- catchRaw[, .(
LocalID = cruise,
Gear = gear,
Number = serialnumber,
SpeciesCode = aphia,
SpeciesCategory = catchpartnumber,
DataType = "R",
SpeciesValidity = ifelse(is.na(catchproducttype), 0, catchproducttype),
SpeciesCategoryNumber = catchcount,
WeightUnit = "kg",
SpeciesCategoryWeight = catchweight,
SpeciesSex = NA,
SubsampledNumber = lengthsamplecount,
SubsamplingFactor = catchcount / lengthsamplecount,
SubsampleWeight = lengthsampleweight,
LengthCode = NA,
LengthClass = NA,
LengthType = lengthmeasurement,
NumberAtLength = lengthsamplecount,
WeightAtLength = NA
)]
Catch[is.na(SpeciesCategoryNumber) & is.na(SpeciesCategoryWeight) & !is.na(SubsampledNumber), SpeciesCategoryNumber := SubsampledNumber]
Catch[is.na(SpeciesCategoryNumber) & is.na(SpeciesCategoryWeight) & !is.na(SubsampleWeight), SpeciesCategoryWeight := SubsampleWeight]
Catch[!is.na(SpeciesCategoryWeight) & is.na(SubsampleWeight), SubsampleWeight := 0]
indRaw <- BioticData_NMDOne$individual
indRaw[is.na(preferredagereading), preferredagereading := 1]
baseAge <- intersect(names(indRaw), names(BioticData_NMDOne$agedetermination))
indRaw <- merge(indRaw, BioticData_NMDOne$agedetermination, by.x=c(baseAge, "preferredagereading"), by.y= c(baseAge, "agedeterminationid"), all.x = TRUE)
indRaw <- merge(catchRaw, indRaw, by = intersect(names(catchRaw), names(indRaw)))
indRaw[is.na(age), agingstructure := NA_character_]
Biology <- indRaw[, .(
LocalID = cruise,
Gear = gear,
Number = serialnumber,
SpeciesCode = aphia,
SpeciesCategory = catchpartnumber,
StockCode = NA,
FishID = specimenid,
LengthCode = getLengthCodeICES(lengthresolution),
LengthClass = scaleLengthUsingLengthCode(length, getLengthCodeICES(lengthresolution), inputUnit = "m"),
WeightUnit = 'kg',
IndividualWeight = individualweight,
IndividualSex = sex,
IndividualMaturity = specialstage,
MaturityScale = NA,
IndividualAge = age,
AgePlusGroup = NA,
AgeSource = agingstructure,
GeneticSamplingFlag = NA,
StomachSamplingFlag = NA,
ParasiteSamplingFlag = NA,
IndividualVertebraeCount = NA
)]
if(AllowRemoveSpecies) {
xmlRaw <- read_xml("https://acoustic.ices.dk/Services/Schema/XML/SpecWoRMS.xml")
validCodes <- xml_text(xml_find_all(xmlRaw, "//Code//Key"))
notPresentInCatch <- unique(setdiff(Catch$SpeciesCode, validCodes))
notPresentInBiology <- unique(setdiff(Biology$SpeciesCode, validCodes))
if(length(notPresentInCatch)) {
warning("StoX: The following species are not listed in https://acoustic.ices.dk/Services/Schema/XML/SpecWoRMS.xml were automatically removed from table Catch (set AllowRemoveSpecies = FALSE to prevent this):\n", paste(notPresentInCatch, collapse = ", "))
}
if(length(notPresentInBiology)) {
warning("StoX: The following species are not listed in https://acoustic.ices.dk/Services/Schema/XML/SpecWoRMS.xml were automatically removed from table Biology (set AllowRemoveSpecies = FALSE to prevent this):\n", paste(notPresentInBiology, collapse = ", "))
}
Catch <- Catch[SpeciesCode %in% validCodes, ]
Biology <- Biology[SpeciesCode %in% validCodes, ]
} else {
message("AllowRemoveSpecies is set to FALSE. Will only give warning for records with species that is not accepted by the ICES system.")
compareICES("https://acoustic.ices.dk/Services/Schema/XML/SpecWoRMS.xml", unique(Catch$SpeciesCode))
}
ICESBioticCSV <- list(
Cruise = Cruise,
Haul = Haul,
Catch = Catch,
Biology = Biology
)
return(ICESBioticCSV)
}
WriteICESBiotic <- function(ICESBioticData){
WriteICESBioticData <- lapply(
ICESBioticData,
WriteICESBioticOne
)
return(WriteICESBioticData)
}
WriteICESBioticOne <- function(ICESBioticDataOne){
ICESBioticCSVDataOne <- convertToHeaderRecordMatrix(ICESBioticDataOne)
ICESBioticCSVDataOne <- expandWidth(ICESBioticCSVDataOne)
ICESBioticCSVDataOne <- do.call(rbind, ICESBioticCSVDataOne)
return(ICESBioticCSVDataOne)
}
renameToTableNameFirst <- function(data, tableNames, setToID = NULL, formatType = c("Biotic", "Acoustic")) {
formatType <- match.arg(formatType)
columnName <- lapply(data[tableNames], names)
tableName = rep(tableNames, lengths(columnName))
columnName <- unlist(columnName)
areTableNames <- columnName %in% setToID
newColumnName <- character(length(columnName))
newColumnName[areTableNames] <- paste0(columnName[areTableNames], "ID")
newColumnName[!areTableNames] <- paste0(tableName[!areTableNames], columnName[!areTableNames])
conversionTable <- data.table::data.table(
tableName = tableName,
columnName = columnName,
newColumnName = newColumnName
)
ICESKeys <- getRstoxDataDefinitions(paste0("ICES", formatType, "Keys"))
ICESKeys <- unique(unlist(ICESKeys[!names(ICESKeys) %in% tail(tableNames, 1)]))
conversionTable <- conversionTable[!(duplicated(columnName) & columnName %in% ICESKeys), ]
conversionTable <- subset(conversionTable, tableName != columnName)
conversionTableList <- split(conversionTable, by = "tableName")
keys <- conversionTable[columnName %in% ICESKeys, ]
conversionTableList <- lapply(conversionTableList, rbind, keys)
conversionTableList <- lapply(conversionTableList, unique)
mapply(
data.table::setnames,
data[tableNames],
old = lapply(conversionTableList, "[[", "columnName"),
new = lapply(conversionTableList, "[[", "newColumnName"),
skip_absent = TRUE
)
}
ICESDatras <- function(
BioticData
) {
ICESDatrasData <- lapply(
BioticData,
ICESDatrasOne
)
ICESDatrasData <- ICESDatrasData[lengths(ICESDatrasData) > 0]
return(ICESDatrasData)
}
ICESDatrasOne <- function(
BioticDataOne
) {
if(!(BioticDataOne$metadata$useXsd %in% c("nmdbioticv3", "nmdbioticv3.1"))) {
warning("StoX: Currently, only NMD Biotic version 3 and 3.1 data can be written by ICESDatras")
return(matrix(1, 0, 0))
}
'%ni%' <- Negate('%in%')
finalHH <- merge(BioticDataOne$mission, BioticDataOne$fishstation)
finalHH[, `:=`(
"Quarter" = getQuarter(stationstartdate),
"Country" = getTSCountryByIOC(nation),
"Ship" = getICESShipCode(platformname),
"Gear" = "GOV",
"SweepLngt" = getGOVSweepByEquipment(gear),
"GearEx" = getGearEx(getGOVSweepByEquipment(gear), startyear, serialnumber, bottomdepthstart),
"DoorType" = "P",
"StNo" = serialnumber,
"HaulNo" = station,
"Year" = getYear(stationstartdate),
"Month" = getMonth(stationstartdate),
"Day" = getDay(stationstartdate),
"TimeShot" = getTimeShot(stationstarttime),
"DepthStratum" = NA,
"HaulDur" = as.numeric(getTimeDiff(stationstartdate, stationstarttime, stationstopdate, stationstoptime)),
"DayNight" = getDayNight(stationstartdate, stationstarttime, latitudestart, longitudestart),
"ShootLat" = roundDrop0(latitudestart, digits = 4),
"ShootLong" = roundDrop0(longitudestart, digits = 4),
"HaulLat" = roundDrop0(latitudeend, digits = 4),
"HaulLong" = roundDrop0(longitudeend, digits = 4),
"StatRec" = getICESrect(latitudestart, longitudestart),
"Depth" = roundDrop0(bottomdepthstart),
"HaulVal" = getHaulVal(gearcondition, samplequality),
"HydroStNo" = NA,
"StdSpecRecCode" = 1,
"BycSpecRecCode" = 1,
"DataType" = "R",
"Netopening"= roundDrop0(verticaltrawlopening, digits = 1),
"Rigging" = NA,
"Tickler" = NA,
"Distance" = roundDrop0(getDistanceMeter(latitudestart, longitudestart, latitudeend, longitudeend)),
"Warplngt" = roundDrop0(wirelength),
"Warpdia" = NA,
"WarpDen" = NA,
"DoorSurface" = 4.5,
"DoorWgt" = 1075,
"DoorSpread" = ifelse(!is.na(trawldoorspread), roundDrop0(trawldoorspread, digits = 1), NA),
"WingSpread" = NA,
"Buoyancy" = NA,
"KiteDim" = 0.8,
"WgtGroundRope" = NA,
"TowDir" = ifelse(!is.na(direction), roundDrop0(direction), NA),
"GroundSpeed" = roundDrop0(gearflow, digits = 1),
"SpeedWater" = NA,
"SurCurDir" = NA,
"SurCurSpeed" = NA,
"BotCurDir" = NA,
"BotCurSpeed" = NA,
"WindDir" = NA,
"WindSpeed" = NA,
"SwellDir" = NA,
"SwellHeight" = NA,
"SurTemp" = NA,
"BotTemp" = NA,
"SurSal" = NA,
"BotSal" = NA,
"ThermoCline" = NA,
"ThClineDepth" = NA,
"CodendMesh" = NA ,
"SecchiDepth" = NA,
"Turbidity" = NA,
"TidePhase" = NA,
"TideSpeed" = NA,
"PelSampType" = NA,
"MinTrawlDepth" = NA,
"MaxTrawlDepth" = NA
)]
HHraw <- data.table::copy(finalHH[, c(
"Quarter", "Country", "Ship", "Gear",
"SweepLngt", "GearEx", "DoorType", "StNo", "HaulNo", "Year", "Month", "Day",
"TimeShot", "DepthStratum", "HaulDur", "DayNight", "ShootLat", "ShootLong", "HaulLat", "HaulLong",
"StatRec", "Depth", "HaulVal", "HydroStNo", "StdSpecRecCode", "BycSpecRecCode", "DataType", "Netopening",
"Rigging", "Tickler", "Distance", "Warplngt", "Warpdia", "WarpDen", "DoorSurface", "DoorWgt",
"DoorSpread", "WingSpread", "Buoyancy", "KiteDim", "WgtGroundRope", "TowDir", "GroundSpeed",
"SpeedWater", "SurCurDir", "SurCurSpeed", "BotCurDir", "BotCurSpeed", "WindDir", "WindSpeed",
"SwellDir", "SwellHeight", "SurTemp", "BotTemp", "SurSal", "BotSal", "ThermoCline", "ThClineDepth",
"CodendMesh", "SecchiDepth", "Turbidity", "TidePhase", "TideSpeed", "PelSampType", "MinTrawlDepth", "MaxTrawlDepth")]
)
mergedHL <- merge(BioticDataOne$catchsample, finalHH, by=intersect(names(BioticDataOne$catchsample), names(finalHH)))
groupCA <- c("missiontype", "startyear", "platform", "missionnumber", "serialnumber", "aphia", "sex")
groupHL <- c(groupCA, "catchpartnumber")
mergedHL <- mergedHL[!is.na(aphia)]
getSpecVal <- function(HaulVal, catchcount, lengthsamplecount, catchweight){
temp <- as.data.table(cbind(hv=HaulVal, cc=catchcount, lsc=lengthsamplecount, cw=catchweight))
temp[, res := "0"]
temp[!is.na(cc) & !is.na(lsc) & !is.na(cw), res:="1"]
temp[!is.na(cc) & is.na(lsc) & is.na(cw), res:="4"]
temp[ is.na(cc) & is.na(lsc) & !is.na(cw), res:="6"]
temp[!is.na(cc) & is.na(lsc) & !is.na(cw), res:="7"]
temp[ is.na(cc) & is.na(lsc) & is.na(cw), res:="5"]
temp[!is.na(cc) & !is.na(lsc) & is.na(cw), res:="0"]
temp[hv == "I", res:="0"]
return(temp$res)
}
mergedHL[, SpecVal := getSpecVal(HaulVal, catchcount, lengthsamplecount, catchweight)]
mergedHL[,`:=`( isHerringOrSprat = ifelse(aphia %in% c("126417", "126425"), TRUE, FALSE),
isCrustacean = ifelse(aphia %in% c("107275", "107276", "107369", "107253", "107703", "107704", "107350", "107254", "107205", "140712", "140687", "140658"), TRUE, FALSE))]
mergedHL[,lngtCode := "1"]
mergedHL[is.na(sampletype), lngtCode := NA]
mergedHL[isCrustacean == TRUE, lngtCode := "."]
mergedHL[isHerringOrSprat == TRUE, lngtCode := "0"]
mergedHL[,`:=`(lenInterval = ifelse(lngtCode=="0", 5, 1), reportInMM = ifelse(lngtCode %ni% c("1", NA), TRUE, FALSE))]
mergedHL[is.na(lenInterval), lenInterval := 1]
mergedHL[!is.na(catchweight), catCatchWgt := ceiling(catchweight * 1000)]
mergedHL[!is.na(lengthsampleweight), subWeight := ceiling(lengthsampleweight * 1000)]
mergedHL[, sampleFac := catchweight / lengthsampleweight]
mergedHL <- merge(mergedHL, BioticDataOne$individual, by = intersect(names(mergedHL), names(BioticDataOne$individual)), all.x = TRUE)
mergedHL[, N := sum(!is.na(specimenid)), by = groupHL]
mergedHL[N == 0, `:=`(lngtClass = as.integer(NA), sex = as.character(NA))]
mergedHL[, length := length * 100]
mergedHL[length < 1, `:=`(lngtCode = ".", lenInterval = 1, reportInMM = TRUE)]
mergedHL[reportInMM == TRUE, length := length * 10]
mergedHL[, sex := ifelse(is.na(sex), as.character(NA), ifelse(sex == "1", "F", "M"))]
for(interval in unique(mergedHL$lenInterval)) {
intVec <- seq(0, max(mergedHL$length, na.rm = T), by = interval)
mergedHL[lenInterval == interval, lngtClass := intVec[findInterval(length, intVec)]]
}
mergedHL[!is.na(length), lsCountTot := 1]
finalHL <- mergedHL[, .(N, lsCountTot = sum(lsCountTot)), by = c(
groupHL,
"lngtClass", "Quarter", "Country", "Ship", "Gear", "SweepLngt", "GearEx", "DoorType", "HaulNo", "SpecVal", "catCatchWgt", "sampleFac", "subWeight", "lngtCode", "stationtype", "lengthmeasurement"
)
]
finalHL <- finalHL[!duplicated(finalHL)]
finalHL[,`:=`(noMeas = sum(lsCountTot)), by = groupHL]
finalHL[,`:=`(totalNo = noMeas * sampleFac, subFactor = sampleFac)]
HLraw <- data.table::copy(finalHL[, .(
"Quarter" = Quarter,
"Country" = Country,
"Ship" = Ship,
"Gear" = Gear,
"SweepLngt" = SweepLngt,
"GearEx" = GearEx,
"DoorType" = DoorType,
"StNo" = serialnumber,
"HaulNo" = HaulNo,
"Year" = startyear,
"SpecCodeType" = "W",
"SpecCode" = aphia,
"SpecVal" = SpecVal,
"Sex" = sex,
"TotalNo" = roundDrop0(totalNo, digits = 2),
"CatIdentifier" = catchpartnumber,
"NoMeas" = noMeas,
"SubFactor" = roundDrop0(subFactor, 4),
"SubWgt" = roundDrop0(subWeight),
"CatCatchWgt" = roundDrop0(catCatchWgt),
"LngtCode" = lngtCode,
"LngtClass" = lngtClass,
"HLNoAtLngt" = roundDrop0(lsCountTot, 2),
"DevStage" = NA,
"LenMeasType" = convLenMeasType(lengthmeasurement)
)]
)
mergedHL[is.na(preferredagereading), preferredagereading := 1]
baseAge <- intersect(names(mergedHL), names(BioticDataOne$agedetermination))
mergedCA <- merge(mergedHL, BioticDataOne$agedetermination, by.x=c(baseAge, "preferredagereading"), by.y= c(baseAge, "agedeterminationid"), all.x = TRUE)
mergedCA <- mergedCA[!is.na(specimenid)]
mergedCA[, maturity:=getDATRASMaturity(Quarter, aphia, specialstage, maturationstage)]
mergedCA[!is.na(individualweight), `:=`(nWithWeight =.N, totWeight = sum(individualweight)), by = c(groupCA, "lngtClass", "maturity", "age")]
finalCA <- mergedCA[, .(nInd =.N), by = c(
groupCA,
"lngtClass", "maturity", "age", "Quarter", "Country", "Ship", "Gear", "SweepLngt", "GearEx", "DoorType", "HaulNo", "SpecVal", "StatRec", "lngtCode", "stationtype", "nWithWeight", "totWeight", "specimenid", "tissuesample", "stomach", "agingstructure", "readability", "parasite")]
finalCA[!is.na(nWithWeight), meanW := totWeight / nWithWeight]
CAraw <- data.table::copy(finalCA[,
.(
"Quarter" = Quarter,
"Country" = Country,
"Ship" = Ship,
"Gear" = Gear,
"SweepLngt" = SweepLngt,
"GearEx" = GearEx,
"DoorType" = DoorType,
"StNo" = serialnumber,
"HaulNo" = HaulNo,
"Year" = startyear,
"SpecCodeType" = "W",
"SpecCode" = aphia,
"AreaType" = "0",
"AreaCode" = StatRec,
"LngtCode" = lngtCode,
"LngtClass" = lngtClass,
"Sex" = sex,
"Maturity" = maturity,
"PlusGr" = as.character(NA),
"AgeRings" = ifelse(!is.na(age), age, NA),
"CANoAtLngt" = nInd,
"IndWgt" = ifelse(!is.na(meanW), roundDrop0(meanW * 1000, 1), NA),
"MaturityScale" = "M6",
"FishID" = specimenid,
"GenSamp" = ifelse(!is.na(tissuesample), "Y", "N"),
"StomSamp" = ifelse(!is.na(stomach), "Y", "N"),
"AgeSource" = convAgeSource(agingstructure),
"AgePrepMet" = NA,
"OtGrading" = ifelse(readability %in% as.character(c(1:4)), readability, NA),
"ParSamp" = ifelse(!is.na(parasite), "Y", "N")
)]
)
hh <- HHraw
hl <- HLraw
ca <- CAraw
dupl <- stats::aggregate(catchcategory ~ aphia + serialnumber, BioticDataOne$catchsample, FUN = function(x) length(unique(x)))
dupl <- dupl[dupl$catchcategory > 1, ]
if(nrow(dupl)) {
found <- stats::aggregate(CatCatchWgt ~ StNo + SpecCode + Sex + CatIdentifier, hl[(hl$SpecCode %in% dupl$aphia & hl$StNo %in% dupl$serialnumber),], FUN = function(x) length(unique(x)))
found <- found[found$CatCatchWgt > 1, ]
for(iz in seq_len(nrow(found))) {
tmpHL <- hl[hl$StNo==found[iz, "StNo"] & hl$SpecCode==found[iz, "SpecCode"] & hl$Sex==found[iz, "Sex"] & hl$CatIdentifier==found[iz, "CatIdentifier"], ]
combinedCatCatchWgt <- tmpHL
hl[hl$StNo==found[iz, "StNo"] & hl$SpecCode==found[iz, "SpecCode"] & hl$Sex==found[iz, "Sex"] & hl$CatIdentifier==found[iz, "CatIdentifier"], "CatCatchWgt"] <- roundDrop0(mean(tmpHL$CatCatchWgt))
hl[hl$StNo==found[iz, "StNo"] & hl$SpecCode==found[iz, "SpecCode"] & hl$Sex==found[iz, "Sex"] & hl$CatIdentifier==found[iz, "CatIdentifier"], "SubWgt"] <- roundDrop0(mean(tmpHL$SubWgt))
hl[hl$StNo==found[iz, "StNo"] & hl$SpecCode==found[iz, "SpecCode"] & hl$Sex==found[iz, "Sex"] & hl$CatIdentifier==found[iz, "CatIdentifier"], "TotalNo"] <- sum(unique(tmpHL$TotalNo))
hl[hl$StNo==found[iz, "StNo"] & hl$SpecCode==found[iz, "SpecCode"] & hl$Sex==found[iz, "Sex"] & hl$CatIdentifier==found[iz, "CatIdentifier"], "NoMeas"] <- sum(tmpHL$HLNoAtLngt)
hl[hl$StNo==found[iz, "StNo"] & hl$SpecCode==found[iz, "SpecCode"] & hl$Sex==found[iz, "Sex"] & hl$CatIdentifier==found[iz, "CatIdentifier"], "SubFactor"] <- sum(unique(tmpHL$TotalNo))/sum(tmpHL$HLNoAtLngt)
}
}
tmp <- stats::aggregate(SpecVal ~ SpecCode + StNo, hl, FUN = function(x) length(unique(x)))
tmp <- tmp[tmp$SpecVal>1, ]
for( rownum in seq_len(nrow(tmp)) ) {
tmpSpecs <- hl[(hl$StNo==tmp$StNo[rownum] & hl$SpecCode==tmp$SpecCode[rownum]),]$SpecVal
if(any(tmpSpecs == 1))
hl <- hl[!(hl$StNo==tmp$StNo[rownum] & hl$SpecCode==tmp$SpecCode[rownum] & hl$SpecVal!=1),]
else
hl[(hl$StNo==tmp$StNo[rownum] & hl$SpecCode==tmp$SpecCode[rownum]), c("SpecVal")] <- min(tmpSpecs)
}
hl[hl$SpecVal==0, c("Sex", "TotalNo", "CatIdentifier", "NoMeas", "SubFactor", "SubWgt", "CatCatchWgt", "LngtCode", "LngtClass", "HLNoAtLngt")] <- NA
hl[hl$SpecVal==4, c("NoMeas", "SubWgt", "CatCatchWgt", "LngtCode", "LngtClass", "HLNoAtLngt")] <- NA
hl[hl$SpecVal==4, c("SubFactor")] <- 1
hl[hl$SpecVal==5, c("TotalNo", "NoMeas", "SubWgt", "CatCatchWgt", "LngtCode", "LngtClass", "HLNoAtLngt")] <- NA
hl[hl$SpecVal==5, c("SubFactor")] <- 1
hl[hl$SpecVal==6, c("TotalNo", "NoMeas", "LngtCode", "LngtClass", "HLNoAtLngt")] <- NA
hl[hl$SpecVal==7, c("NoMeas", "LngtCode", "LngtClass", "HLNoAtLngt")] <- NA
hl[hl$SpecVal==10, c("CatCatchWgt")] <- NA
hl <- hl[!duplicated(hl),]
hl <- hl[hl$StNo %in% hh$StNo,]
ca <- ca[ca$StNo %in% hh$StNo,]
ca <- ca[!ca$StNo %in% hh$StNo[hh$HaulVal=='I'],]
hl <- hl[!hl$SpecCode %in% c(230,558,830,883,1302,1839,100635,100706,100930,103929,106048,106087,106204,106733,106791,
106854,106928,107044,107218,107230,107240,107273,107292,107318,107330,107346,107397,107398,107551,
107616,107643,111374,111597,111604,116986,117302,117809,117815,117890,123117,123867,123920,123970,
123987,124319,124418,124913,124929,124934,125128,125131,125134,129196,129229,130464,130867,132072,
132480,135144,135302,137704,137732,138223,138239,138760,138899,139004,139488,140299,140627,141753,
144129,150642,178639,181228,23986719494,21263,100817,100982,106738,107160,107232,107277,107322,
107323,107327,107387,107531,107552,107564,107649,107651,111367,123080,123083,123084,123776,123813,
124043,124154,124160,124287,124535,125166,125333,128517,129840,138802,138878,138920,140467,140717,
143755,145541,145546,145548,532031,589677,1762,123082,149),]
ca <- ca[!ca$SpecCode %in% c(230,558,830,883,1302,1839,100635,100706,100930,103929,106048,106087,106204,106733,106791,
106854,106928,107044,107218,107230,107240,107273,107292,107318,107330,107346,107397,107398,107551,
107616,107643,111374,111597,111604,116986,117302,117809,117815,117890,123117,123867,123920,123970,
123987,124319,124418,124913,124929,124934,125128,125131,125134,129196,129229,130464,130867,132072,
132480,135144,135302,137704,137732,138223,138239,138760,138899,139004,139488,140299,140627,141753,
144129,150642,178639,181228,23986719494,21263,100817,100982,106738,107160,107232,107277,107322,
107323,107327,107387,107531,107552,107564,107649,107651,111367,123080,123083,123084,123776,123813,
124043,124154,124160,124287,124535,125166,125333,128517,129840,138802,138878,138920,140467,140717,
143755,145541,145546,145548,532031,589677,1762,123082,149),]
hl <- hl[!hl$SpecCode %in% c(443,938,1131,1292,1337,1360,19494,22988,100751,100757,100790,101054,103484,104062,
106122,106669,107011,107052,107148,107239,107388,107563,110690,110911,110956,111411,117136,
117258,123260,123276,123321,123335,123574,123593 ,123851,123922,123985,124085,125158,125269,
128506,130467,130987,131779,134591,137683,141872,146142 ,149864,445590,510534,105,175,927,1107,
1135,1267,100793),]
hl <- hl[!hl$SpecCode %in% c(105,175,927,1107,1135,1267,100793,103443,103692,106057,106835,106903,107558,110908,111361,
117940,122348,123160,123426,124257,125027,125284,131495,135294,135301,135306,138992,140528,140687,
167882,178527,239867,291396,106763,137656,117225,100653,125125,100698,131774,134366,123386,117228,
117994,138923,123127,137701,123320,131629 ,152391,1363,214,103543,106994,103450,129400,140143,
146420,141905,22496,988,103717,107163,982,985,123622,102145,1082,10216,103483),]
ca <- ca[!ca$SpecCode %in% c(443,938,1131,1292,1337,1360,19494,22988,100751,100757,100790,101054,103484,104062,
106122,106669,107011,107052,107148,107239,107388,107563,110690,110911,110956,111411,117136,
117258,123260,123276,123321,123335,123574,123593 ,123851,123922,123985,124085,125158,125269,
128506,130467,130987,131779,134591,137683,141872,146142 ,149864,445590,510534,105,175,927,1107,
1135,1267,100793),]
ca <- ca[!ca$SpecCode %in% c(105,175,927,1107,1135,1267,100793,103443,103692,106057,106835,106903,107558,110908,111361,
117940,122348,123160,123426,124257,125027,125284,131495,135294,135301,135306,138992,140528,140687,
167882,178527,239867,291396,106763,137656,117225,100653,125125,100698,131774,134366,123386,117228,
117994,138923,123127,137701,123320,131629 ,152391,1363,214,103543,106994,103450,129400,140143,
146420,141905,22496,988,103717,107163,982,985,123622,102145,1082,10216,103483),]
hl <- hl[!hl$SpecCode %in% c(NA, 101,106769,106782,107010,107726,122478,123506,12437,124951,128539,129402,196221,205077,124373, 123187, 124710),]
ca <- ca[!ca$SpecCode %in% c(NA, 101,106769,106782,107010,107726,122478,123506,12437,124951,128539,129402,196221,205077,124373, 123187, 124710),]
benthosSpecCodes <- c(104,956,966,1128,1296,1367,1608,11707,100782,100839,100854,103439,103732,104040,105865,106041,106673,106702,106789,106834,107152,
107205,107264,110749,110916,110993,111152,111355,111365,117093,117195,118445,122626,123204,123255,123613,124147,124151,124324,124670,
128490,128503,129563,130057,134691,136025,137710,138018,138068,138477,138631,138749,138938,140166,140173,140480,140625,141904,141929,
149854,152997,532035,816800)
hl <- hl[!hl$SpecCode %in% benthosSpecCodes,]
ca <- ca[!ca$SpecCode %in% benthosSpecCodes,]
if (nrow(ca) > 0) {
testca <- unique(data.table::data.table(StNo=ca$StNo, SpecCode=ca$SpecCode, ca=TRUE))
testhl <- unique(data.table::data.table(StNo=hl$StNo, SpecCode=hl$SpecCode, hl=TRUE))
tt <- merge(testca, testhl, by = c("StNo","SpecCode"), all=TRUE)
missingHL <- tt[is.na(tt$hl),]
for(idxHL in seq_len(nrow(missingHL))) {
r <- missingHL[idxHL,]
tmp <- hl[hl$StNo==r$StNo,][1,]
tmp$SpecCode <- r$SpecCode
tmp$SpecVal <- 4
tmp$TotalNo <- c(hh$HaulDur[hh$StNo==r$StNo])
tmp$CatCatchWgt <- NA
hl <- rbind(hl,tmp)
}
}
ca[ which((ca$SpecCode==127023 | ca$SpecCode==126417) & ca$AgeRings >= 15), c("PlusGr", "AgeRings")] <- list("+", 15)
hl <- hl[order(hl$StNo),]
ICESDatrasData <- list(HH = hh, HL = hl, CA = ca)
return(ICESDatrasData)
}
WriteICESDatras <- function(ICESDatrasData){
WriteICESDatrasData <- lapply(
ICESDatrasData,
WriteICESDatrasOne,
na = "-9"
)
return(WriteICESDatrasData)
}
WriteICESDatrasOne <- function(ICESDatrasDataOne, na = "-9"){
ICESDatrasCSVDataOne <- convertToRecordTypeMatrix(ICESDatrasDataOne)
if(length(na)) {
ICESDatrasCSVDataOne <- lapply(ICESDatrasCSVDataOne, function(x) {x[is.na(x)] <- na; x})
}
ICESDatrasCSVDataOne <- lapply(ICESDatrasCSVDataOne, apply, 1, paste, collapse = ",")
ICESDatrasCSVDataOne <- unlist(ICESDatrasCSVDataOne)
return(ICESDatrasCSVDataOne)
}
getTSCountryByIOC <- function(nation) {
cnvTbl <- c("58" = "NO")
x <- cnvTbl[as.character(nation)]
x[is.null(x)] <- NA
return(x)
}
getGearEx <- function(sweep, year, serialnumber, depth) {
temp <- as.data.table(cbind(sweep, year, serialnumber, depth))
temp[, res:= "S"]
temp[year == 2011 & serialnumber > 24362 & depth >= 70 | year == 2012
| year == 2011 & serialnumber >= 24135 & depth >= 70, res:="ST"]
return (temp$res)
}
getYear <- function(stationstartdate) {
format(as.Date(stationstartdate, format="%Y-%m-%dZ"), "%Y")
}
getMonth <- function(stationstartdate) {
format(as.Date(stationstartdate, format="%Y-%m-%dZ"), "%m")
}
getDay <- function(stationstartdate) {
format(as.Date(stationstartdate, format="%Y-%m-%dZ"), "%d")
}
getTimeShot <- function(stationstarttime) {
timeshot <- function(y) {
if(length(y) == 3) {
return(paste0(y[1], y[2]))
} else {
return(NA)
}
}
x <- strsplit(stationstarttime, ":")
return(unlist(lapply(x, timeshot)))
}
getQuarter <- function(stationstartdate) {
x <- format(as.Date(stationstartdate, format="%Y-%m-%dZ"), "%m")
return(floor((as.numeric(x) - 1) / 3 + 1))
}
getDayNight <- function(stationstartdate, stationstarttime, latitudestart, longitudestart, UTCoff = 0) {
deg2rad <- function(val) {
return(val * (pi / 180))
}
rad2deg <- function(val) {
return(val * (180 / pi))
}
datetime0 <- as.POSIXct("1990-12-30", tz = "UTC")
uniqueDates <- unique(stationstartdate)
nDaysA = as.numeric(difftime(uniqueDates, datetime0, units = "days"))
nTimes = 24*3600
tArray = seq(0, 1, length = nTimes)
ssTab <- list()
for(idx in seq_len(length(nDaysA))) {
nDays <- nDaysA[idx]
lat <- latitudestart[idx]
lng <- longitudestart[idx]
localdate <- as.POSIXct(uniqueDates[idx], tz = "UTC")
E = tArray
F = nDays + 2415018.5 + E - UTCoff / 24
G = (F - 2451545) / 36525
I = (280.46646 + G * (36000.76983 + G * 0.0003032)) %% 360
J = 357.52911 + G * (35999.05029 - 0.0001537 * G)
K = 0.016708634 - G * (0.000042037 + 0.0000001267 * G)
L = sin(deg2rad(J)) * (1.914602 - G * (0.004817 + 0.000014 * G))+sin(deg2rad(2 * J)) * (0.019993 - 0.000101*G) + sin(deg2rad(3 * J)) * 0.000289
M = I + L
P = M - 0.00569 - 0.00478 * sin(deg2rad(125.04 - 1934.136 * G))
Q = 23 + (26 + ((21.448 - G * (46.815 + G * (0.00059 - G * 0.001813)))) / 60) / 60
R = Q + 0.00256 * cos(deg2rad(125.04 - 1934.136 * G))
T = rad2deg(asin(sin(deg2rad(R)) * sin(deg2rad(P))))
U = tan(deg2rad(R/2)) * tan(deg2rad(R/2))
V = 4 * rad2deg(U * sin(2 * deg2rad(I))-2 * K * sin(deg2rad(J)) + 4 * K * U * sin(deg2rad(J)) * cos(2*deg2rad(I)) - 0.5 * U * U * sin(4 * deg2rad(I)) - 1.25 * K * K * sin(2 * deg2rad(J)))
AB = (E * 1440 + V + 4 *lng - 60 * UTCoff) %% 1440
AC = ifelse (AB/4 < 0, AB/4 + 180, AB/4 - 180)
AD = rad2deg(acos(sin(deg2rad(lat)) * sin(deg2rad(T)) + cos(deg2rad(lat)) * cos(deg2rad(T)) * cos(deg2rad(AC))))
WArg <- cos(deg2rad(90.833)) / (cos(deg2rad(lat)) * cos(deg2rad(T))) - tan(deg2rad(lat)) * tan(deg2rad(T))
if(any(WArg < -1)) {
WArg[WArg < -1] <- -1
}
if(any(WArg > 1)) {
WArg[WArg > 1] <- 1
}
W = rad2deg(acos(WArg))
X = (720 - 4 * lng - V + UTCoff * 60) * 60
sunrise = which.min(abs(X - round(W * 4 * 60) - nTimes * tArray))
sunset = which.min(abs(X+round(W*4*60) - nTimes*tArray))
sunrisetime = localdate + sunrise
sunsettime = localdate + sunset
ssTab[[uniqueDates[idx]]] <- list(sunrise = sunrisetime, sunset = sunsettime)
}
getDN <- function(x, ssTab) {
y <- ssTab[[format(x, "%Y-%m-%dZ")]]
if(x < y$sunrise || x >= y$sunset) {
return("N")
} else {
return("D")
}
}
datetime <- as.POSIXct(gsub("Z", " ", paste0(stationstartdate, stationstarttime)), tz = "UTC")
return(unlist(lapply(datetime, getDN, ssTab)))
}
convLenMeasType <- function(LenMeasType) {
ct <- c(
"B" = 5,
"C" = 6,
"E" = 1,
"F" = 8,
"G" = 4,
"H" = 3,
"J" = 2,
"L" = 7,
"S" = 9
)
return(ct[LenMeasType])
}
convAgeSource <- function(AgeSource) {
if(!all(AgeSource %in% c("1", "2", "7"))) {
warning("The conversion from agingstructure to AgeSource may be wrong for other values than 1, 2 and 7. Please noify the developers of StoX.")
}
ct <- c("1" = "scale",
"2" = "otolith",
"4" = "df-spine",
"6" = "spine",
"7" = "vertebra",
"8" = "caudal-thorn")
return(ct[AgeSource])
}
roundDrop0 <- function(x, digits = 0) {
notNA <- !is.na(x)
x[notNA] <- formatC(x[notNA], digits = digits, format = "f", drop0trailing = TRUE)
return(x)
} |
OipTsSdEwma <- function(data, n.train, threshold, l = 3, m = 5,
to.next.iteration = list(last.res = NULL, to.check = NULL, last.m = NULL)) {
if (!is.numeric(data) | (sum(is.na(data)) > 0)) {
stop("data argument must be a numeric vector and without NA values.")
}
if (!is.numeric(n.train) | n.train <= 0) {
stop("n.train argument must be a positive numeric value.")
}
if (!is.numeric(threshold) | threshold <= 0 | threshold > 1) {
stop("threshold argument must be a numeric value in (0,1] range.")
}
if (!is.numeric(l)) {
stop("l argument must be a numeric value.")
}
if (!is.numeric(m)) {
stop("m argument must be a numeric value and smaller than all dataset
length.")
}
if (!is.null(to.next.iteration) & !is.list(to.next.iteration)) {
stop("to.next.iteration argument must be NULL or a list with las execution
result.")
}
ApplyKolmogorovTest <- function(part1, part2) {
res.test <- suppressWarnings(stats::ks.test(part1, part2, exact = NULL))
return(ifelse(res.test$p.value > 0.05, 0, 1))
}
OnePointTssdEwma <- function(data, n.train, threshold, l, m, to.next.iteration) {
result <- OipSdEwma(data, n.train, threshold, l, to.next.iteration$last.res)
if (is.null(to.next.iteration)) {
last.m <- NULL
to.check <- list()
} else {
last.m <- to.next.iteration$last.m
to.check <- to.next.iteration$to.check
}
last.m.values <- ifelse(is.null(last.m), 0, length(last.m))
result$result$i <- result$last.res[1,"i"]
if (last.m.values < m) {
last.m <- c(last.m, data)
to.check <- NULL
last.data.checked <- NULL
} else {
last.m <- last.m[-1]
last.m <- c(last.m, data)
to.check.len <- length(to.check)
if (result$result$is.anomaly) {
to.check[[to.check.len + 1]] <- list(index = result$result$i,
check.in = result$result$i + m,
last.m = last.m)
}
if (to.check.len >= 1) {
if (to.check[[1]]$check.in == result$result$i) {
is.anomaly <- ApplyKolmogorovTest(to.check[[1]]$last.m, last.m)
last.data.checked <- data.frame(i = to.check[[1]]$index, is.anomaly = is.anomaly)
to.check <- to.check[-1]
} else {
last.data.checked <- NULL
}
} else {
last.data.checked <- NULL
}
}
to.next.iteration <- list(last.res = result$last.res, to.check = to.check, last.m = last.m)
return(list(result = result$result, last.data.checked = last.data.checked,
to.next.iteration = to.next.iteration))
}
if (length(data) == 1) {
return(OnePointTssdEwma(data, n.train, threshold, l, m, to.next.iteration))
} else {
n <- length(data)
last.res <- list()
last.res$result <- NULL
last.res$to.next.iteration <- to.next.iteration
res <- NULL
last.data.checked <- NULL
for (i in 1:n) {
last.res <- OnePointTssdEwma(data = data[i], n.train, threshold, l, m,
last.res$to.next.iteration)
res <- rbind(res, last.res$result)
if (!is.null(last.res$last.data.checked)) {
last.data.checked <- rbind(last.data.checked, last.res$last.data.checked)
}
}
if (!is.null(last.data.checked)) {
res[res$i %in% last.data.checked$i, "is.anomaly"] <- last.data.checked$is.anomaly
last.data.checked <- last.data.checked[!(last.data.checked$i %in% res$i),]
if (nrow(last.data.checked) == 0) last.res[2] <- list(NULL)
else last.res$last.data.checked <- last.data.checked
}
last.res$result <- res
return(last.res)
}
} |
globalVariables(c("Partidos","Desproporcionalidad","Comunidad"))
AgregadosIndi <- function(Ano=0,Mes="",RutaDescarga="",Auto=TRUE,datos=""){
out <- tryCatch(
{
if(Auto==TRUE){
if(Ano == 0) stop("It must be provided a year in 'Ano'")
if(Mes=="") stop("It must be provided a month with a two-character format in 'Mes'")
if(RutaDescarga=="") stop("A download path must be provided in 'RutaDescarga'")
}else{
if(class(datos) != "data.frame") stop("It must be provided a data.frame in parameter 'datos'")
if(ncol(datos) != 3) stop("The data.frame provided in parameter 'datos' must contain 3 columns")
}
if(Auto){
data <- suppressMessages(Agregado_Prov_MIR(Ano,Mes,Tipo="Congreso",RutaDescarga, Borrar=TRUE))
start_idx <- which(substr(colnames(data),1,2)=="V_")[1]
data[,start_idx:ncol(data)]<-apply(data[,start_idx:ncol(data)],2,as.integer)
data <-data[1:52,start_idx:ncol(data)]
data2<- as.data.frame(t(colSums(data)))
idx_votos <- substr(colnames(data2),1,2)=="V_"
data3 <- t(data2[,idx_votos])
data4 <- t(data2[,!idx_votos])
data5 <- data.frame(Partidos=substr(rownames(data3),3,nchar(rownames(data3))),
Votos=data3,Escanos=data4,stringsAsFactors = FALSE)
data5[,c(2,3)] <- apply(data5[,c(2,3)],2,as.integer)
}else{
data5 <-datos
colnames(data5)<-c("Partidos","Votos","Escanos")
}
data5$Porc_votos <- round(data5$Votos/sum(data5$Votos),4)*100
data5$Porc_escanos <- round(data5$Escanos/sum(data5$Escanos),4)*100
data5$Acum_porc_votos <- cumsum(data5$Porc_votos)
data5$Acum_porc_escanos <- cumsum(data5$Porc_escanos)
data5$Desproporcionalidad <- round(data5$Porc_escanos - data5$Porc_votos,2)
p<-ggplot(data5,aes(x=Partidos,y=Desproporcionalidad))+
geom_bar(stat='identity') +
coord_flip() +
scale_x_discrete(limits=rev(data5$Partidos))+
geom_hline(yintercept = 0, color="blue") +
geom_text(aes(x = Partidos,y = max(Desproporcionalidad) + 0.1,
label = Desproporcionalidad),size=2.5)
idx_sainte_lag <- Sainte_Lague(data5$Votos,data5$Escanos)
idx_rae <- Rae(data5$Votos,data5$Escanos)
idx_rae_corr <- Rae_corregido(data5$Votos,data5$Escanos,correc=0.5)
idx_loos_hanb <- Loos_Hanby(data5$Votos,data5$Escanos)
idx_Gallagher <- Gallagher(data5$Votos,data5$Escanos)
idx_L_max <-L_max(data5$Votos,data5$Escanos)
idx_Cox_Shugart <- Cox_Shugart(data5$Votos,data5$Escanos)
idx_Cox_Shugart_corr <- Cox_Shugart_correg(data5$Votos,data5$Escanos)
idx_L_Tukey <- L_Tukey(data5$Votos,data5$Escanos)
despr_res=data.frame(SL=idx_sainte_lag)
despr_res$R<-idx_rae
despr_res$Rco <- idx_rae_corr
despr_res$LH <- idx_loos_hanb
despr_res$Gcm <- idx_Gallagher
despr_res$Lmax <- idx_L_max
despr_res$CS <- idx_Cox_Shugart
despr_res$CS_correg <- idx_Cox_Shugart_corr
despr_res$LT <- idx_L_Tukey
idx_F <- fragmentacion_rae(data5$Votos,data5$Escanos)
idx_N <- nep(data5$Votos,data5$Escanos)
idx_Hiper <-hiper(data5$Votos,data5$Escanos)
idx_NP <-nepMolinar(data5$Votos,data5$Escanos)
idx_Con <- concentracion(data5$Votos,data5$Escanos)
idx_Comp <- competitividad(data5$Votos,data5$Escanos)
dimension <- data.frame(F_electoral=as.numeric(idx_F[1]),
F_parlamen=as.numeric(idx_F[2]))
dimension$N_electoral <- as.numeric(idx_N[1])
dimension$N_parlamen <- as.numeric(idx_N[2])
dimension$Hiper_electoral <- as.numeric(idx_Hiper[1])
dimension$Hiper_parlamen <- as.numeric(idx_Hiper[2])
dimension$NP_electoral <- as.numeric(idx_NP[1])
dimension$NP_parlamen <- as.numeric(idx_NP[2])
dimension$Con_electoral <- as.numeric(idx_Con[1])
dimension$Con_parlamen <- as.numeric(idx_Con[2])
dimension$Comp_electoral <- as.numeric(idx_Comp[1])
dimension$Comp_parlamen <- as.numeric(idx_Comp[2])
res <- list(dat=data5,grafico=p,In_despro= despr_res,In_dimen=dimension)
return(res)
},
warning = function(cond){
message("A warning has been generated, the path may not exist or cannot be written to")
message("The warning message is the following:")
message(cond)
return(NULL)
},
error= function(cond){
message("The path provided may not exist or cannot be written to")
message("The error message is the following:")
message(cond)
return(NA)
}
)
return(out)
}
DesAgregadosIndi <- function(Ano=0,Mes="",RutaDescarga="",Auto=TRUE,datos_v="",datos_d=""){
out <- tryCatch(
{
if(Auto==TRUE){
if(Ano == 0) stop("It must be provided a year in 'Ano'")
if(Mes=="") stop("It must be provided a month with a two-character format in 'Mes'")
if(RutaDescarga=="") stop("A download path must be provided in 'RutaDescarga'")
}else{
if(datos_v=="") stop("A data.frame must be provided with voting data in parameter 'datos_v'")
if(datos_d=="") stop("A data.frame must be provided with seat data in parameter 'datos_d'")
if(class(datos_v) != "data.frame") stop("It must be provided a data.frame containing the votes in parameter 'datos_v'")
if(class(datos_d) != "data.frame") stop("It must be provided a data.frame containing the seats in parameter 'datos_d'")
}
if(Auto){
data <- suppressMessages(Agregado_Prov_MIR(Ano,Mes,Tipo="Congreso",RutaDescarga, Borrar=TRUE))
iden <- data[1:50,1:3]
start_idx <- which(substr(colnames(data),1,2)=="V_")[1]
data22 <- data[1:50,start_idx:ncol(data)]
idx_votos <- substr(colnames(data22),1,2)=="V_"
data33 <- data22[,idx_votos]
data33 <- cbind(iden,data33)
data44 <- data22[,!idx_votos]
data44 <- cbind(iden,data44)
}else{
data33 <- datos_v
data44 <- datos_d
}
res_prov <-list()
for(h in 1:nrow(data33)){
cprov <- data33[h,2]
d1<-colnames(data33[4:ncol(data33)])
d1 <- substr(d1,3,nchar(d1))
d2<-t(data33[h,4:ncol(data33)])
d3 <- t(data44[h,4:ncol(data33)])
data5 <-data.frame(Partidos=d1,Votos=d2,Escanos=d3,stringsAsFactors = FALSE)
colnames(data5) <- c("Partidos","Votos","Escanos")
data5[,c(2,3)] <- apply(data5[,c(2,3)],2,as.integer)
votos <- data5[,2]>0
data5 <-data5[votos,]
r <- AgregadosIndi(Ano=0,Mes="",RutaDescarga="",Auto = FALSE,datos=data5)
res_prov[[cprov]]<- r
}
res_CCAA <- list()
data333 <- data33[,-c(2,3)]
colnames(data333)[1]<-"Comunidad"
data333[,2:ncol(data333)] <-apply(data333[,2:ncol(data333)],2,as.integer)
data333 <-data333 %>% group_by(Comunidad) %>% summarise_all(funs(sum))
data444 <- data44[,-c(2,3)]
colnames(data444)[1]<-"Comunidad"
data444[,2:ncol(data444)] <-apply(data444[,2:ncol(data444)],2,as.integer)
data444 <-data444 %>% group_by(Comunidad) %>% summarise_all(funs(sum))
for(h in 1:nrow(data333)){
d1<-colnames(data333[2:ncol(data333)])
d1 <- substr(d1,3,nchar(d1))
d2<-t(data333[h,2:ncol(data333)])
d3 <- t(data444[h,2:ncol(data444)])
data5 <-data.frame(Partidos=d1,Votos=d2,Escanos=d3,stringsAsFactors = FALSE)
colnames(data5) <- c("Partidos","Votos","Escanos")
votos <- data5[,2]>0
data5 <-data5[votos,]
r <- AgregadosIndi(Ano=0,Mes="",RutaDescarga="",Auto = FALSE,datos=data5)
res_CCAA[[as.character(h)]]<- r
}
res_total <- list(CCAA=res_CCAA,PROV= res_prov)
return(res_total)
},
warning = function(cond){
message("A warning has been generated, the path may not exist or cannot be written to")
message("The warning message is the following:")
message(cond)
return(NULL)
},
error= function(cond){
message("The path provided may not exist or cannot be written to")
message("The error message is the following:")
message(cond)
return(NA)
}
)
return(out)
} |
NULL
dapc <- function(.data, .f, ...) UseMethod("dapc")
dapc.default <- function(.data, .f, ...) {
assert_that(is_vector(.data))
if (is_lang(.f)) {
e <- call_env()
.f <- eval(.f, envir = e)[[2]]
.data[] <- lapply(.data, function(.x) {
eval(.f, list(.x = .x), e)
})
} else {
.data[] <- lapply(.data, .f, ...)
}
.data
}
dapr <- function(.data, .f, ...) UseMethod("dapr")
dapr.default <- function(.data, .f, ...) {
assert_that(is_vector(.data))
if (is_lang(.f)) {
e <- call_env()
.f <- eval(.f, envir = e)[[2]]
.data[seq_len(nrow(.data)), ] <- t(apply(.data, 1,
function(.x) eval(.f, list(.x = .x), e)
))
} else {
.data[seq_len(nrow(.data)), ] <- t(apply(.data, 1, .f, ...))
}
.data
}
dapc_if <- function(.data, .predicate, .f, ...) UseMethod("dapc_if")
dapc_if.default <- function(.data, .predicate, .f, ...) {
assert_that(is_vector(.data))
if (is.logical(.predicate)) {
lg <- .predicate
} else if (is_lang(.predicate)) {
e <- call_env()
.predicate <- eval(.predicate, envir = e)[[2]]
lg <- vapply(.data,
function(.x) eval(.predicate, list(.x = .x), e),
FUN.VALUE = logical(1))
} else {
lg <- vapply(.data, .predicate,
FUN.VALUE = logical(1))
}
assert_that(is.logical(lg))
if (is_lang(.f)) {
e <- call_env()
.f <- eval(.f, envir = e)[[2]]
.data[lg] <- lapply(.data[lg],
function(.x) eval(.f, list(.x = .x), e)
)
} else {
.data[lg] <- lapply(.data[lg], .f, ...)
}
.data
}
dapr_if <- function(.data, .predicate, .f, ...) UseMethod("dapr_if")
dapr_if.default <- function(.data, .predicate, .f, ...) {
assert_that(is_vector(.data))
if (is.logical(.predicate)) {
lg <- .predicate
} else if (is_lang(.predicate)) {
e <- call_env()
.predicate <- eval(.predicate, envir = e)[[2]]
lg <- unlist(apply(.data, 1,
function(.x) eval(.predicate, list(.x = .x), e)
))
} else {
lg <- vapply(.data, .predicate,
FUN.VALUE = logical(1))
}
assert_that(is.logical(lg))
if (sum(lg) == 0) return(.data)
if (is_lang(.f)) {
e <- call_env()
.f <- eval(.f, envir = e)[[2]]
.data[lg, ] <- t(apply(.data[lg, ], 1,
function(.x) eval(.f, list(.x = .x), e)
))
} else {
.data[lg, ] <- t(apply(.data[lg, ], 1, .f, ...))
}
.data
} |
"asafellow" |
getDistancePointers <- function(dist.fcts,
prefabDists = c("sumofsquares", "euclidean",
"manhattan", "tanimoto")) {
dist.ptrs <- vector(length(dist.fcts), mode = "list")
if (prefab.idx <- dist.fcts %in% prefabDists) {
dist.ptrs[prefab.idx] <-
CreateStdDistancePointers(factor(dist.fcts[prefab.idx],
levels = prefabDists))
}
if (rest.idx <- !prefab.idx) {
if (!exists(dist.fcts)) {
stop(paste("Cannot find (custom) distance function: ", dist.fcts, sep=""))
}
dist.ptrs[[1]] <- eval(call(dist.fcts))
}
dist.ptrs
} |
node_status <- function(.dag, as_factor = TRUE, ...) {
.tdy_dag <- if_not_tidy_daggity(.dag, ...)
.exposures <- dagitty::exposures(.tdy_dag$dag)
.outcomes <- dagitty::outcomes(.tdy_dag$dag)
.latents <- dagitty::latents(.tdy_dag$dag)
.tdy_dag$data <- dplyr::mutate(.tdy_dag$data,
status = ifelse(name %in% .exposures, "exposure",
ifelse(name %in% .outcomes, "outcome",
ifelse(name %in% .latents, "latent",
NA))))
if (as_factor) .tdy_dag$data$status <- factor(.tdy_dag$data$status, exclude = NA)
.tdy_dag
}
ggdag_status <- function(.tdy_dag, ..., edge_type = "link_arc", node_size = 16, text_size = 3.88,
label_size = text_size,
text_col = "white", label_col = text_col,
node = TRUE, stylized = FALSE, text = TRUE,
use_labels = NULL) {
edge_function <- edge_type_switch(edge_type)
p <- if_not_tidy_daggity(.tdy_dag) %>%
node_status(...) %>%
ggplot2::ggplot(ggplot2::aes(x = x, y = y, xend = xend, yend = yend, color = status)) +
edge_function() +
scale_adjusted() +
breaks(c("exposure", "outcome", "latent"))
if (node) {
if (stylized) {
p <- p + geom_dag_node(size = node_size)
} else {
p <- p + geom_dag_point(size = node_size)
}
}
if (text) p <- p + geom_dag_text(col = text_col, size = text_size)
if (!is.null(use_labels)) p <- p +
geom_dag_label_repel(ggplot2::aes_string(label = use_labels,
fill = "status"), size = text_size,
col = label_col, show.legend = FALSE)
p
} |
plotBP <- function(ts, breaks, bp.y, ...) {
plot(ts, ...)
ylons <- mean(ts, na.rm = TRUE)
if (missing(bp.y)) bp.y <- quantile(ts, .005)
colors <- palette()[1:length(breaks)]
abline(v = breaks[2, ], col = colors, lty=2)
text(breaks[2, ], y = bp.y, labels = names(breaks),
col = colors)
for (a in 1:length(breaks)) arrows(breaks[1, a], ylons,
breaks[3, a], ylons, code = 3, angle = 90, length = 0.1,
lwd = 2, col = colors[a])
} |
extractDIC <- function(fit,...){
UseMethod("extractDIC")
}
extractDIC.merMod <- function(fit,...){
is_REML <- isREML(fit)
llik <- logLik(fit, REML=is_REML)
dev <- deviance(refitML(fit))
n <- getME(fit, "devcomp")$dims["n"]
Dhat <- -2 * (llik)
pD <- dev - Dhat
DIC <- dev + pD[[1]]
names(DIC) <- "DIC"
return(DIC)
} |
library(PopED)
ff <- function(model_switch,xt,parameters,poped.db){
with(as.list(parameters),{
y=xt
MS <- model_switch
N = floor(xt/TAU)+1
CONC=(DOSE*Favail/V)*(KA/(KA - CL/V)) *
(exp(-CL/V * (xt - (N - 1) * TAU)) * (1 - exp(-N * CL/V * TAU))/(1 - exp(-CL/V * TAU)) -
exp(-KA * (xt - (N - 1) * TAU)) * (1 - exp(-N * KA * TAU))/(1 - exp(-KA * TAU)))
EFF = E0*(1 - CONC*IMAX/(IC50 + CONC))
y[MS==1] = CONC[MS==1]
y[MS==2] = EFF[MS==2]
return(list( y= y,poped.db=poped.db))
})
}
sfg <- function(x,a,bpop,b,bocc){
parameters=c( V=bpop[1]*exp(b[1]),
KA=bpop[2]*exp(b[2]),
CL=bpop[3]*exp(b[3]),
Favail=bpop[4],
DOSE=a[1],
TAU = a[2],
E0=bpop[5]*exp(b[4]),
IMAX=bpop[6],
IC50=bpop[7])
return( parameters )
}
feps <- function(model_switch,xt,parameters,epsi,poped.db){
returnArgs <- ff(model_switch,xt,parameters,poped.db)
y <- returnArgs[[1]]
poped.db <- returnArgs[[2]]
MS <- model_switch
pk.dv <- y*(1+epsi[,1])+epsi[,2]
pd.dv <- y*(1+epsi[,3])+epsi[,4]
y[MS==1] = pk.dv[MS==1]
y[MS==2] = pd.dv[MS==2]
return(list( y= y,poped.db =poped.db ))
}
bpop_vals <- c(V=72.8,KA=0.25,CL=3.75,Favail=0.9,E0=1120,IMAX=0.807,IC50=0.0993)
bpop_vals_ed <- cbind(zeros(7,1),bpop_vals,zeros(7,1))
bpop_vals_ed["IC50",1] <- 1
bpop_vals_ed["IC50",3] <- (bpop_vals_ed["IC50",2]*0.1)^2
bpop_vals_ed
poped.db <- create.poped.database(ff_fun="ff",
fError_fun="feps",
fg_fun="sfg",
groupsize=20,
m=3,
bpop=bpop_vals_ed,
notfixed_bpop=c(1,1,1,0,1,1,1),
d=c(V=0.09,KA=0.09,CL=0.25^2,E0=0.09),
sigma=c(0.04,5e-6,0.09,100),
notfixed_sigma=c(0,0,0,0),
xt=c( 1,2,8,240,240,1,2,8,240,240),
minxt=c(0,0,0,240,240,0,0,0,240,240),
maxxt=c(10,10,10,248,248,10,10,10,248,248),
discrete_xt = list(0:248),
G_xt=c(1,2,3,4,5,1,2,3,4,5),
bUseGrouped_xt=1,
model_switch=c(1,1,1,1,1,2,2,2,2,2),
a=list(c(DOSE=20,TAU=24),c(DOSE=40, TAU=24),c(DOSE=0, TAU=24)),
maxa=c(DOSE=200,TAU=40),
mina=c(DOSE=0,TAU=2),
ourzero=0)
tic(); output <- evaluate.e.ofv.fim(poped.db,ED_samp_size=20); toc()
output$E_ofv
output$E_fim
output <- poped_optim(poped.db, opt_xt = T, parallel = T,
d_switch=F,ED_samp_size=20,
method = c("LS"))
summary(output)
get_rse(output$FIM,output$poped.db)
plot_model_prediction(output$poped.db,facet_scales="free") |
print.list.rma <- function(x, digits=x$digits, ...) {
mstyle <- .get.mstyle("crayon" %in% .packages())
.chkclass(class(x), must="list.rma")
digits <- .get.digits(digits=digits, xdigits=x$digits, dmiss=FALSE)
attr(x, "class") <- NULL
x$cr.lb <- NULL
x$cr.ub <- NULL
slab.pos <- which(names(x) == "slab")
out <- x[seq_len(slab.pos-1)]
out <- data.frame(out, row.names=x$slab, stringsAsFactors=FALSE)
if (nrow(out) == 0L)
stop(mstyle$stop("All values are NA."), call.=FALSE)
if (exists("select", where=x, inherits=FALSE))
out <- out[x$select,]
if (nrow(out) == 0L) {
message(mstyle$message("No values to print."))
return(invisible())
}
transf.true <- 0
if (exists("transf", where=x, inherits=FALSE) && x$transf) {
transf.true <- 1
out$se <- NULL
}
if (exists("method", where=x, inherits=FALSE)) {
min.pos <- slab.pos - is.element("tau2.level", names(x)) - is.element("gamma2.level", names(x)) - is.element("X", names(x)) - is.element("Z", names(x)) - transf.true
} else {
min.pos <- slab.pos - transf.true
}
sav <- out[,seq_len(min.pos-1)]
for (i in seq_len(min.pos-1)) {
if (inherits(out[,i], c("integer","logical","factor","character"))) {
out[,i] <- out[,i]
} else {
if (names(out)[i] %in% c("pred", "resid"))
out[,i] <- .fcf(out[,i], digits[["est"]])
if (names(out)[i] %in% c("se"))
out[,i] <- .fcf(out[,i], digits[["se"]])
if (names(out)[i] %in% c("ci.lb", "ci.ub", "cr.lb", "cr.ub", "pi.lb", "pi.ub"))
out[,i] <- .fcf(out[,i], digits[["ci"]])
if (names(out)[i] %in% c("zval", "Q", "z", "X2"))
out[,i] <- .fcf(out[,i], digits[["test"]])
if (names(out)[i] %in% c("pval", "Qp"))
out[,i] <- .fcf(out[,i], digits[["pval"]])
if (names(out)[i] %in% c("I2", "H2"))
out[,i] <- .fcf(out[,i], digits[["het"]])
if (names(out)[i] %in% c("tau2"))
out[,i] <- .fcf(out[,i], digits[["var"]])
if (!is.character(out[,i]))
out[,i] <- .fcf(out[,i], digits[["est"]])
}
}
.space()
tmp <- capture.output(print(out, quote=FALSE, right=TRUE))
.print.table(tmp, mstyle)
if (is.null(attr(x, ".rmspace"))) .space()
invisible(sav)
} |
spadimo <- function(data, weights, obs,
control = list(scaleFun = Qn,
nlatent = 1,
etas = NULL,
csqcritv = 0.975,
stopearly = FALSE,
trace = FALSE,
plot = TRUE))
{
if (missing(data)) {
stop("Argument 'data' is missing, with no default.")
}
if (missing(weights)) {
stop("Argument 'weights' is missing, with no default.")
}
if (missing(obs)) {
stop("Argument 'obs' is missing, with no default.")
}
if (missing(control)) {
control <- list(scaleFun = Qn,
nlatent = 1,
etas = NULL,
csqcritv = 0.975,
stopearly = FALSE,
trace = FALSE,
plot = TRUE)
}
starttimer <- proc.time()
obs <- as.integer(obs)
x <- as.matrix(data)
n <- nrow(x)
p <- ncol(x)
w <- weights
if (is.null(control$scaleFun)) {
control$scaleFun <- Qn
}
if (is.null(control$nlatent)) {
control$nlatent <- 1
}
if (is.null(control$etas)) {
if (n > p) {
control$etas <- seq(0.9, 0.1, -0.05)
} else if (n <= p) {
control$etas <- seq(0.6, 0.1, -0.05)
}
}
if (is.null(control$csqcritv)) {
control$csqcritv <- 0.975
}
if (is.null(control$stopearly)) {
control$stopearly <- FALSE
}
if (is.null(control$trace)) {
control$trace <- FALSE
}
if (is.null(control$plot)) {
control$plot <- TRUE
}
etas <- sort(control$etas, decreasing = TRUE)
stopcrit <- FALSE
a.list <- list()
outlvars.list <- list()
robLoc <- apply(x, 2, weighted.mean, w)
robScale <- apply(x, 2, control$scaleFun)
if (any(robScale < .Machine$double.eps)) {
stop("The following variables have 0 scale:\n ",
paste(names(which(robScale < .Machine$double.eps)), collapse = ", "))
}
z <- scale(x, center = robLoc, scale = robScale)
outlyingness.before <- NA
PCA.outlflag.before <- NA
if (n > p) {
Sigmaw <- (t(z) %*% diag(w) %*% z) / (sum(w)-1)
outlyingness.before <- sqrt(t(z[obs, ]) %*% chol2inv(chol(Sigmaw)) %*% z[obs, ])
if (control$trace) printer(type = 1, n = n, p = p, control = control, outlyingness.before = outlyingness.before)
} else if (n <= p) {
set.seed(2017)
PCA.outlflag.before <- !(PcaHubert(z, alpha = 0.75, k = 0, kmax = 10, maxdir = 250, scale = FALSE)@flag[obs])
if (control$trace) printer(type = 1, n = n, p = p, PCA.outlflag.before = PCA.outlflag.before)
}
for (i in 1:length(etas)) {
reg <- spadimo.exs(Z = z,
w = w,
obs = obs,
nlatent = control$nlatent,
eta = etas[i])
outlvars <- reg$outlvars
a.list[[i]] <- reg$a
outlvars.list[[i]] <- outlvars
if (control$trace) printer(type = 2, etas = etas, i = i, reg = reg)
if (length(outlvars) == p) {
if (stopcrit == FALSE) {
stopcrit <- TRUE
outlvars.crit <- outlvars
eta.crit <- reg$eta
a.crit <- reg$a
outlyingness.after.crit <- NA
PCA.outlflag.after.crit <- NA
}
warning('All variables were flagged!', call. = FALSE)
break
}
z.reduced <- as.matrix(z[,-outlvars])
df <- p - length(outlvars)
csqcrit.after <- qchisq(control$csqcritv, df)
outlyingness.after <- 0
PCA.outlflag.after <- FALSE
if (n > p) {
Sigmaw <- (t(z.reduced) %*% diag(w) %*% z.reduced) / (sum(w)-1)
outlyingness.after <- sqrt(t(z.reduced[obs, ]) %*% chol2inv(chol(Sigmaw)) %*% z.reduced[obs, ])
if (control$trace) printer(type = 3, n = n, p = p, control = control, outlyingness.after = outlyingness.after, csqcrit.after = csqcrit.after, df = df)
} else if (n <= p) {
set.seed(2017)
PCA.outlflag.after <- !(PcaHubert(z.reduced, alpha = 0.75, k = 0, kmax = 10, maxdir = 250, scale = FALSE)@flag[obs])
if (control$trace) printer(type = 3, n = n, p = p, PCA.outlflag.after = PCA.outlflag.after)
}
if (n > p & outlyingness.after^2 < csqcrit.after & stopcrit == FALSE) {
stopcrit <- TRUE
outlvars.crit <- outlvars
eta.crit <- reg$eta
a.crit <- reg$a
outlyingness.after.crit <- outlyingness.after
PCA.outlflag.after.crit <- NA
if (control$stopearly) break
} else if (n <= p & PCA.outlflag.after == FALSE & stopcrit == FALSE) {
stopcrit <- TRUE
outlvars.crit <- outlvars
eta.crit <- reg$eta
a.crit <- reg$a
outlyingness.after.crit <- NA
PCA.outlflag.after.crit <- PCA.outlflag.after
if (control$stopearly) break
} else if (i == length(etas) & stopcrit == FALSE) {
warning('Algorithm did not converge; reduced case remains outlying.', call. = FALSE)
outlvars.crit <- outlvars
eta.crit <- reg$eta
a.crit <- reg$a
outlyingness.after.crit <- NA
PCA.outlflag.after.crit <- PCA.outlflag.after
}
}
endtimer <- proc.time() - starttimer
if (control$trace) printer(type = 4, endtimer = endtimer)
if (control$plot) printer(type = 5, n = n, p = p, x = x, i = i, obs = obs, control = control, etas = etas, eta.crit = eta.crit,
outlvars.crit = outlvars.crit, rownamesData = rownames(data), colnamesData = colnames(data),
a.list = a.list, outlvars.list = outlvars.list)
return(list(outlvars = outlvars.crit,
outlvarslist = outlvars.list,
a = a.crit,
alist = a.list,
eta = eta.crit,
o.before = ifelse(n > p, as.numeric(outlyingness.before), PCA.outlflag.before),
o.after = ifelse(n > p, as.numeric(outlyingness.after.crit), PCA.outlflag.after.crit),
time = round(endtimer[3], 4),
control = control))
}
spadimo.exs <- function(Z, w, obs, nlatent, eta) {
z <- as.matrix(Z)
n <- nrow(z)
p <- ncol(z)
if (w[obs] == 0) w[obs] <- 1e-10
zw <- sqrt(w) * z
yw <- rep(0, n)
yw[obs] <- 1
if (nlatent == 1) {
a <- t(zw) %*% yw
a <- a/norm(a, 'F')
wnn2 <- data.frame(outlvars = abs(a) - eta*max(abs(a)), oldorder = 1:p)
a <- wnn2$outlvars*sign(a)
wnn2 <- wnn2[order(wnn2$outlvars, decreasing = TRUE), ]
outlvars <- wnn2$oldorder[which(wnn2$outlvars >= 0)]
names(outlvars) <- colnames(Z)[outlvars]
a[setdiff(1:p, outlvars)] <- 0
a <- a/norm(a, 'F')
} else {
a <- snipls_nc(yw ~ zw - 1, data = cbind.data.frame(yw, zw), eta = eta, a = nlatent, print = FALSE)$coefficients
a <- a/norm(a, 'F')
wnn2 <- data.frame(outlvars = abs(a), oldorder = 1:p)
wnn2 <- wnn2[order(wnn2$outlvars, decreasing = TRUE), ]
outlvars <- wnn2$oldorder[which(wnn2$outlvars > 0)]
names(outlvars) <- colnames(Z)[outlvars]
}
return(list(outlvars = outlvars,
a = a,
eta = eta,
nlatent = nlatent))
}
snipls_nc <- function(formula, data, eta, a, print = FALSE){
Z <- model.frame(formula, data = data)
Xh <- as.matrix(Z[, 2:ncol(Z)])
X0 <- Xh
yh <- as.vector(Z[, 1])
my <- 0
y0 <- yh
Tpls <- NULL
W <- NULL
P <- NULL
C <- NULL
B <- NULL
bh <- 0
Xev <- matrix(0, nrow = 1, ncol = a)
Yev <- matrix(0, nrow = 1, ncol = a)
oldgoodies <- NULL
vars <- vector('list', 2*a)
for(i in 1:a){
wh <- t(Xh)%*%yh
wh <- wh/norm(wh, 'F')
goodies <- abs(wh) - eta*max(abs(wh))[1]
wh <- goodies*sign(wh)
goodies <- which((goodies >= 0))
goodies <- union(oldgoodies, goodies)
oldgoodies <- goodies
wh[setdiff(1:ncol(X0), goodies)] <- 0
th <- Xh%*%wh
nth <- norm(th, 'F')
ch <- t(yh)%*%th/(nth^2)
ph <- t(Xh)%*%th/(nth^2)
ph[setdiff(1:ncol(X0), goodies)] <- 0
yh <- yh - th * as.numeric(ch)
Xh <- Xh - th%*%t(ph)
W <- cbind(W, wh)
P <- cbind(P, ph)
C <- rbind(C, ch)
Tpls <- cbind(Tpls, th)
Xev[i] <- (nth^2*norm(ph, 'F')^2)/sum(X0^2)*100
Yev[i] <- sum(nth^2*as.numeric(ch^2))/sum(y0^2)*100
if (print) {
cat('Variables retained for ', i, ' latent variable(s):', '\n', colnames(X0)[goodies], '.\n')
}
vars[[2*(i-1)+1]] <- colnames(X0)[goodies]
vars[[2*i]] <- goodies
}
if (length(goodies) > 0) {
R <- W %*% solve(t(P)%*%W)
B <- R%*%C
} else {
B <- matrix(0, nrow = ncol(Xh), ncol = 1)
R <- B
Tpls <- matrix(0, nrow = nrow(Xh), ncol = a)
}
yp <- X0%*%B + my
if (any(is.nan(Tpls))) {
stop('NaN generated in Tpls')
}
if (length(vars[[2*a]]) == 0) {
stop('No variables have been retained in Sparse PRM model!')
}
return(list(W = W, loadings = P, C = C, scores = Tpls, coefficients = B, Xev = Xev, Yev = Yev, Vars = vars, fitted.values = yp, R = R))
}
printer <- function(type,
x = NULL,
n = NULL,
p = NULL,
i = NULL,
df = NULL,
obs = NULL,
reg = NULL,
etas = NULL,
a.list = NULL,
control = NULL,
endtimer = NULL,
eta.crit = NULL,
rownamesData = NULL,
colnamesData = NULL,
csqcrit.after = NULL,
outlvars.crit = NULL,
outlvars.list = NULL,
outlyingness.after = NULL,
PCA.outlflag.after = NULL,
outlyingness.before = NULL,
PCA.outlflag.before = NULL,
nOutliers = NULL,
nOutliers.crit = NULL)
{
if (type == 1) {
if (n > p) {
cat(paste0('\n --------------------------------------------------------------------------',
'\n squared outlyingness of original case = ', round(outlyingness.before^2, 4),
'\n qchisq(', control$csqcritv, ', df = ', p, ') = ', round(qchisq(control$csqcritv, p), 4)))
} else if (n <= p) {
cat(paste('\n --------------------------------------------------------------------------',
'\n orignal case outlying according to ROBPCA :', PCA.outlflag.before))
}
}
if (type == 2) {
cat(paste0('\n\n --------------------------------------------------------------------------',
'\n eta = ', etas[i], ' (SNIPLS, nlatent = ', reg$nlatent, ')',
'\n ', length(reg$outlvars), ' variables retained: ', '\n'))
print(reg$outlvars)
}
if (type == 3) {
if (n > p) {
cat(paste0('\n squared outlyingness of reduced case = ', round(outlyingness.after^2, 4),
'\n qchisq(' , control$csqcritv, ', df = ', df, ') = ', round(csqcrit.after, 4)))
} else if (n <= p) {
cat(paste('\n reduced case outlying according to ROBPCA :', PCA.outlflag.after))
}
}
if (type == 4) {
cat(paste('\n\n computation time:', round(endtimer[3], 4), 'sec.\n'))
}
if (type == 5) {
if (i > 1) {
heatmap <- matrix(0, nrow = i, ncol = p)
cellnotes.a <- matrix(0, nrow = i, ncol = p)
cellnotes.obs <- matrix(0, nrow = i, ncol = p)
for (j in 1:i) {
heatmap[j, which(a.list[[j]] > 0)] <- 1
heatmap[j, which(a.list[[j]] < 0)] <- -1
if (p <= 50) {
cellnotes.a[j, ] <- round(a.list[[j]], 2)
cellnotes.obs[j, ] <- round(x[obs, ], 2)
} else {
cellnotes.a[j, ] <- rep(NA, p)
cellnotes.obs[j, ] <- rep(NA, p)
}
}
rownames(heatmap) <- round(etas[1:i], 2)
if (is.null(colnamesData)) {
colnames(heatmap) <- 1:p
} else {
colnames(heatmap) <- colnamesData
}
Color <- c()
if(-1 %in% c(heatmap)) {
Color <- c(Color, 'blue')
}
if (0 %in% c(heatmap)) {
Color <- c(Color, 'lightgray')
}
if (1 %in% c(heatmap)) {
Color <- c(Color, 'red')
}
if (p <= 50) {
heatmap.2(heatmap,
scale = 'none',
col = Color,
cellnote = cellnotes.a,
notecol = ifelse(as.vector(t(heatmap[i:1, ])) != 0, 'white', 'black'),
xlab = 'sparse direction of maximal outlyingness',
ylab = expression(eta),
notecex = 1.0,
Rowv = FALSE,
Colv = FALSE,
dendrogram = 'none',
density.info = 'none',
trace = 'none',
key = FALSE,
margins = c(5, 4.5),
lhei = c(0.5, 12),
lwid = c(0.5, 10),
colsep = 1:p,
rowsep = 1:i,
sepcolor = 'white',
sepwidth = c(0.01, 0.01))
}
if (p <= 500) {
heatmap.2(heatmap,
scale = 'none',
col = Color,
cellnote = cellnotes.obs,
notecol = ifelse(as.vector(t(heatmap[i:1, ])) != 0, 'white', 'black'),
xlab = 'case',
ylab = expression(eta),
notecex = 0.8,
Rowv = FALSE,
Colv = FALSE,
dendrogram = 'none',
density.info = 'none',
trace = 'none',
key = FALSE,
margins = c(5, 4.5),
lhei = c(0.5, 12),
lwid = c(0.5, 10),
colsep = 1:p,
rowsep = 1:i,
sepcolor = 'white',
sepwidth = c(0.01, 0.01))
}
screeplot <- ggplot(data = data.frame(etas = etas[1:i], nOutliers = sapply(outlvars.list, length)), aes(x = etas, y = nOutliers)) +
geom_point(size = 3.5) +
geom_line() +
geom_point(data = data.frame(eta.crit = eta.crit, nOutliers.crit = length(outlvars.crit)), aes(x = eta.crit, y = nOutliers.crit),
shape = 18, size = 7, col = 'red') +
labs(x = expression(eta),
y = 'No. flagged variables') +
theme(plot.title = element_text(size = 15),
text = element_text(size = 20),
axis.title = element_text(size = 15)) +
ggtitle(substitute(paste(eta, ' = ', eta.crit, ' , ', nflags, ' variables flagged'),
list(eta.crit = eta.crit, nflags = length(outlvars.crit))))
plot(screeplot)
}
}
} |
plot.gensvm.grid <- function(x, ...)
{
if (is.null(x$best.estimator)) {
cat("Error: Can't plot, the best.estimator element is NULL\n")
return(invisible(NULL))
}
fit <- x$best.estimator
return(plot(fit, ...))
} |
startNLR <- function(Data, group, model, match = "zscore", parameterization = "alternative",
simplify = FALSE) {
if (missing(model)) {
stop("'model' is missing.",
call. = FALSE
)
} else {
if (!all(model %in% c(
"Rasch", "1PL", "2PL",
"3PLcg", "3PLdg", "3PLc", "3PL", "3PLd",
"4PLcgdg", "4PLcgd", "4PLd", "4PLcdg", "4PLc", "4PL"
))) {
stop("Invalid value for 'model'.",
call. = FALSE
)
}
}
Data <- as.data.frame(Data)
if (length(model) == 1) {
model <- rep(model, ncol(Data))
} else {
if (length(model) != ncol(Data)) {
stop("Invalid length of 'model'. Model needs to be specified for each item or
by single string.", call. = FALSE)
}
}
if (length(parameterization) == 1) {
parameterization <- rep(parameterization, ncol(Data))
} else {
if (length(parameterization) != ncol(Data)) {
stop("Invalid length of 'parameterization'. Parameterization for initial values needs to be specified
for each item or by single string.", call. = FALSE)
}
}
startNLR_line <- function(match, DATA) {
covar <- match
breaks <- unique(quantile(covar, (0:3) / 3, na.rm = TRUE))
lb <- length(breaks) - 1
Q3 <- cut(covar, breaks, include.lowest = TRUE)
levels(Q3) <- LETTERS[1:lb]
x <- cbind(
mean(covar[Q3 == LETTERS[1]], na.rm = TRUE),
colMeans(data.frame(DATA[Q3 == LETTERS[1], ]), na.rm = TRUE)
)
y <- cbind(
mean(covar[Q3 == LETTERS[lb]], na.rm = TRUE),
colMeans(data.frame(DATA[Q3 == LETTERS[lb], ]), na.rm = TRUE)
)
u1 <- y[, 1] - x[, 1]
u2 <- y[, 2] - x[, 2]
q <- -(-u1 * y[, 2] + u2 * y[, 1]) / u1
k <- u2 / u1
results <- as.data.frame(cbind(k, q))
return(results)
}
if (match[1] == "zscore") {
MATCH <- scale(apply(Data, 1, sum))
} else {
if (match[1] == "score") {
MATCH <- as.numeric(apply(Data, 1, sum))
} else {
if (length(match) == dim(Data)[1]) {
MATCH <- match
} else {
stop("Invalid value for 'match'. Possible values are 'score', 'zscore', or vector of
the same length as number of observations in 'Data'.", call. = FALSE)
}
}
}
M_R <- mean(MATCH[group == 0], na.rm = TRUE)
M_F <- mean(MATCH[group == 1], na.rm = TRUE)
SD_R <- sd(MATCH[group == 0], na.rm = TRUE)
SD_F <- sd(MATCH[group == 1], na.rm = TRUE)
MATCH <- scale(MATCH)
line <- startNLR_line(MATCH, DATA = Data)
data_R <- data.frame(Data[group == 0, ])
data_F <- data.frame(Data[group == 1, ])
line_R <- startNLR_line(MATCH[group == 0], DATA = data_R)
line_F <- startNLR_line(MATCH[group == 1], DATA = data_F)
a_R <- a_F <- b_R <- b_F <- c_R <- c_F <- d_R <- d_F <- c()
c <- sapply(
1:ncol(Data),
function(i) {
if (model[i] %in% c("Rasch", "1PL", "2PL", "3PLdg", "3PLd")) {
c_R[i] <- c_F[i] <- 0
} else {
if (grepl("cg", model[i])) {
c_R[i] <- c_F[i] <- checkInterval(line$k * (-4) + line$q, c(0, 0.99))[i]
} else {
c_R[i] <- checkInterval(line_R$k * (-4) + line_R$q, c(0, 0.99))[i]
c_F[i] <- checkInterval(line_F$k * (-4) + line_F$q, c(0, 0.99))[i]
}
}
return(c(c_R[i], c_F[i]))
}
)
c_R <- t(c)[, 1]
c_F <- t(c)[, 2]
d <- sapply(
1:ncol(Data),
function(i) {
if (model[i] %in% c("Rasch", "1PL", "2PL", "3PLcg", "3PLc", "3PL")) {
d_R[i] <- d_F[i] <- 1
} else {
if (grepl("dg", model[i])) {
d_R[i] <- d_F[i] <- checkInterval(line$k * 4 + line$q, c(0.01, 1))[i]
} else {
d_R[i] <- checkInterval(line_R$k * 4 + line_R$q, c(0.01, 1))[i]
d_F[i] <- checkInterval(line_F$k * 4 + line_F$q, c(0.01, 1))[i]
}
}
return(c(d_R[i], d_F[i]))
}
)
d_R <- t(d)[, 1]
d_F <- t(d)[, 2]
a <- sapply(
1:ncol(Data),
function(i) {
if (model[i] == "Rasch") {
a_R[i] <- a_F[i] <- 1
} else {
if (model[i] == "1PL") {
a_R[i] <- a_F[i] <- (4 * line$k / (d_R - c_R))[i]
} else {
a_R[i] <- (4 * line_R$k / (d_R - c_R))[i]
a_F[i] <- (4 * line_F$k / (d_F - c_F))[i]
}
}
return(c(a_R[i], a_F[i]))
}
)
a_R <- t(a)[, 1]
a_F <- t(a)[, 2]
b_R <- ((d_R + c_R) / 2 - line_R$q) / line_R$k
b_F <- ((d_F + c_F) / 2 - line_F$q) / line_F$k
a_R <- a_R / SD_R
a_F <- a_F / SD_F
b_R <- b_R * SD_R + M_R
b_F <- b_F * SD_F + M_F
if (length(unique(parameterization)) == 1 & simplify) {
results <- switch(unique(parameterization),
classic = data.frame(
"a" = a_R, "b" = b_R, "c" = c_R, "d" = d_R,
"aDif" = a_F - a_R, "bDif" = b_F - b_R, "cDif" = c_F - c_R, "dDif" = d_F - d_R
),
alternative = data.frame(
"a" = a_R, "b" = b_R, "cR" = c_R, "dR" = d_R,
"aDif" = a_F - a_R, "bDif" = b_F - b_R, "cF" = c_F, "dF" = d_F
),
logistic = data.frame(
"b1" = a_R, "b0" = -a_R * b_R, "c" = c_R, "d" = d_R,
"b3" = a_F - a_R, "b2" = -a_R * b_R + a_F * b_F, "cDif" = c_F - c_R, "dDif" = d_F - d_R
)
)
} else {
results <- lapply(1:ncol(Data), function(i) {
switch(parameterization[i],
classic = data.frame(
"a" = a_R, "b" = b_R, "c" = c_R, "d" = d_R,
"aDif" = a_F - a_R, "bDif" = b_F - b_R, "cDif" = c_F - c_R, "dDif" = d_F - d_R
)[i, ],
alternative = data.frame(
"a" = a_R, "b" = b_R, "cR" = c_R, "dR" = d_R,
"aDif" = a_F - a_R, "bDif" = b_F - b_R, "cF" = c_F, "dF" = d_F
)[i, ],
logistic = data.frame(
"b1" = a_R, "b0" = -a_R * b_R, "c" = c_R, "d" = d_R,
"b3" = a_F - a_R, "b2" = -a_R * b_R + a_F * b_F, "cDif" = c_F - c_R, "dDif" = d_F - d_R
)[i, ]
)
})
}
return(results)
} |
ParameterSet <- R6::R6Class("ParameterSet",
public = list(
initialize = function(prms = list(), tag_properties = NULL) {
.ParameterSet__initialize(self, private, prms, tag_properties)
},
print = function(sort = TRUE) .ParameterSet__print(self, private, sort),
get_values = function(id = NULL, tags = NULL, transform = TRUE,
inc_null = TRUE, simplify = TRUE) {
.ParameterSet__get_values(self, private, id, tags, transform, inc_null,
simplify)
},
add_dep = function(id, on, cnd) {
.ParameterSet__add_dep(self, private, id, on, cnd)
},
rep = function(times, prefix) {
.ParameterSet__rep(self, private, times, prefix)
},
extract = function(id = NULL, tags = NULL, prefix = NULL) {
.ParameterSet__extract(self, private, id, tags, prefix)
},
remove = function(id = NULL, prefix = NULL) {
.ParameterSet__remove(self, private, id, prefix)
},
getParameterValue = function(id, ...) {
warning("Deprecated. In the future please use $values/$get_values(). Will be removed in 0.3.0.")
self$get_values(id)
},
setParameterValue = function(..., lst = list(...)) {
warning("Deprecated. In the future please use $values. Will be removed in 0.3.0.")
self$values <- unique_nlist(c(lst, self$values))
},
set_values = function(..., lst = list(...)) {
self$values <- unique_nlist(c(lst, self$values))
invisible(self)
},
parameters = function(...) {
warning("Deprecated. In the future please use $print/as.data.table(). Will be removed in 0.3.0.")
self
},
transform = function(x = self$values) {
.ParameterSet__transform(self, private, x)
}
),
active = list(
tags = function() private$.tags,
ids = function() private$.id,
length = function() length(self$ids),
deps = function() private$.deps,
supports = function() .ParameterSet__supports(self, private),
tag_properties = function(x) {
.ParameterSet__tag_properties(self, private, x)
},
values = function(x) .ParameterSet__values(self, private, x),
trafo = function(x) .ParameterSet__trafo(self, private, x)
),
private = list(
.id = NULL,
.isupports = NULL,
.supports = NULL,
.value = NULL,
.tags = NULL,
.tag_properties = NULL,
.trafo = NULL,
.deps = NULL,
.immutable = NULL,
.update_support = function(..., lst = list(...)) {
.ParameterSet__.update_support(self, private, lst)
},
.prefix = function(prefix) {
.ParameterSet__.prefix(self, private, prefix)
},
.unprefix = function(prefix) {
.ParameterSet__.unprefix(self, private, prefix)
},
deep_clone = function(name, value) {
switch(name,
".deps" = {
if (!is.null(value)) {
data.table::copy(value)
}
},
value
)
}
)
)
pset <- function(..., prms = list(...), tag_properties = NULL, deps = NULL,
trafo = NULL) {
ps <- ParameterSet$new(prms, tag_properties)
if (!is.null(deps)) {
checkmate::assert_list(deps)
lapply(deps, function(x) {
cnd <- if (checkmate::test_list(x$cond)) x$cond[[1]] else x$cond
ps$add_dep(x$id, x$on, cnd)
})
}
ps$trafo <- trafo
ps
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.