
## com8a of september 2023, for stk4011 story with Oslo boys and girls
#  and for Nils-Emil story, with lots of quantiles 

#  looking at boys and girls oslo 2001-2008 again: 
#  how similar are the distributions of 
#  (y - \mu_b)/\sigma_b and (y - \mu_g)/\sigma_g ? 

#  here: looking at quantiles Q_b(q) and Q_g(q) 

yyB <- scan("birthweight-boys") / 1000 # in kg, and sorted  
nnB <- length(yyB) # 548, from 1.275 to 5.140  
iiB <- 1:nnB 

yyG <- scan("birthweight-girls") / 1000 # in kg, and sorted  
nnG <- length(yyG) # 480, from 0.600 to 5.420 
iiG <- 1:nnG 

mean(yyB) # 3.669
mean(yyG) # 3.493 
dhat <- mean(yyB) - mean(yyG) # 0.176 kg bigger at birth  

nevner <- sqrt( sd(yyB)^2/nnB + sd(yyG)^2/nnG )
ttest <- (mean(yyB) - mean(yyG))/nevner # 4.96, superbig, so boys > girls 

Ftest <- var(yyB) / var(yyG) # 1.042, close to 1 
pf(Ftest,nnB-1,nnG-1) # 

# qval <- seq(0.10,0.90,by=0.001)
qval <- seq(0.05,0.95,by=0.001)
QBval <- quantile(yyB,qval)
QGval <- quantile(yyG,qval)

matplot(qval, cbind(QBval,QGval),type="l")

## kappa(q) = sqrt( q(1-q) )/f(Q(q)) :

## need density estimates for fB and fG, computed at quantiles: 
## this part can also be done via "density" in R 

hB <- 1.059*sd(yyB) / nnB^(1/5)
hG <- 1.059*sd(yyB) / nnB^(1/5)

fhatBval <- 0*qval
fhatGval <- 0*qval 

for (j in 1:length(qval))
{
auxB <- hB^(-1)*dnorm(hB^(-1)*(yyB - QBval[j]))
fhatBval[j] <- mean(auxB)
# 
auxG <- hG^(-1)*dnorm(hG^(-1)*(yyG - QGval[j]))
fhatGval[j] <- mean(auxG) 
}

# densities, but via quantiles: f(F^(-1)(q))

matplot(qval,cbind(fhatBval,fhatGval),type="l")

kappaBval <- sqrt(qval*(1-qval)) / fhatBval
kappaGval <- sqrt(qval*(1-qval)) / fhatGval

matplot(qval,cbind(kappaBval,kappaGval),type="l")

## now i'm ready for confidence bands around
#  (i) differences and (ii) ratios

# zpoint <- qnorm(0.995) # if i go for 99 percent band 
zpoint <- qnorm(0.975) # if i go for 95 percent band 

## story 1: 

focus1val <- QBval - QGval
upper1val <- focus1val + zpoint*sqrt(kappaBval^2/nnB + kappaGval^2/nnG)
lower1val <- focus1val - zpoint*sqrt(kappaBval^2/nnB + kappaGval^2/nnG)

## cool figure 1: making boysgirls_fig31.pdf  

par(bty="l")
par(cex.lab=1.4142)

matplot(qval, 1000*cbind(focus1val,lower1val,upper1val), type="l",
   lty=c(1,2,2),lwd=3,col=c(1,2,2),
   xlab="quantile", ylab="quantile difference in gram")

matlines(qval, 1000*dhat+0*qval, type="l",lwd=3,lty=3,col=4)

## story 2: making boysgirls_fig32.pdf  

focus2val <- QBval/QGval
hei11 <- (1/QBval)^2*kappaBval^2/nnB + (1/QGval)^2*kappaGval^2/nnG
upper2val <- focus2val + zpoint*focus2val*sqrt(hei11)
lower2val <- focus2val - zpoint*focus2val*sqrt(hei11)

## cool figure 2: 

par(bty="l")
par(cex.lab=1.4142)

matplot(qval, cbind(focus2val,lower2val,upper2val), type="l",
   lty=c(1,2,2),lwd=3,col=c(1,2,2),
   xlab="quantile", ylab="quantile quotient with 0.95 band")
