content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
---|---|
#######################################################################################
# local functions
######################################################################################
lnK <- function(A, B, C, D, E, T)
{
lnK <- A + (B/T) + C*log(T) + D*T + E*T^2
}
logK <- function(A, B, C, D, E, T)
{
logK <- A + (B/T) + C*log10(T) + D*T + E*T^2
}
Sterms <- function(S)
{
sqrtS <- sqrt(S)
Sterms <- list(S^2, sqrtS, S*sqrtS)
}
Iterms <- function(S)
{
I <- I(S)
sqrtI <- sqrt(I)
Iterms <- list(I, I^2, sqrtI, I*sqrtI)
}
deltaPlnK <- function(T, p, coeff)
{
t <- T + PhysChemConst$absZero
t2 <- t^2
deltaV <- coeff[[1]] + coeff[[2]]*t + coeff[[3]]*t2
deltaK <- (coeff[[4]] + coeff[[5]]*t + coeff[[6]]*t2)/1000 #the 1000 is correction from Lewis1998
deltaPlnK <- -(deltaV/(PhysChemConst$R*T))*p + (0.5*(deltaK/(PhysChemConst$R*T)))*(p^2)
}
splitS_K_CO2 <- function(T)
{
res <- c()
for (te in T)
{
lnK1 <- function(T,S)
{
Sterms <- Sterms(S)
A <- 2.83655 - 0.20760841*Sterms[[2]] + 0.08468345*S - 0.00654208*Sterms[[3]]
B <- -2307.1266 - 4.0484*Sterms[[2]]
C <- -1.5529413
lnK1 <- lnK(A, B, C, 0, 0, T)
}
lnK2 <- function(T,S)
{
Sterms <- Sterms(S)
A <- 290.9097 - 228.39774*Sterms[[2]] + 54.20871*S - 3.969101*Sterms[[3]] - 0.00258768*Sterms[[1]]
B <- -14554.21 + 9714.36839*Sterms[[2]] - 2310.48919*S + 170.22169*Sterms[[3]]
C <- -45.0575 + 34.485796*Sterms[[2]] - 8.19515*S + 0.60367*Sterms[[3]]
lnK2 <- lnK(A, B, C, 0, 0, T)
}
res <- c(res, uniroot(function(x) lnK1(te,x)-lnK2(te,x), c(3,7))$root)
}
return(res)
}
splitS_K_HCO3 <- function(T)
{
res <- c()
for (te in T)
{
lnK1 <- function(T,S)
{
Sterms <- Sterms(S)
A <- -9.226508 - 0.106901773*Sterms[[2]] + 0.1130822*S - 0.00846934*Sterms[[3]]
B <- -3351.6106 - 23.9722*Sterms[[2]]
C <- -0.2005743
lnK1 <- lnK(A, B, C, 0, 0, T)
}
lnK2 <- function(T,S)
{
Sterms <- Sterms(S)
A <- 207.6548 - 167.69908*Sterms[[2]] + 39.75854*S - 2.892532*Sterms[[3]] - 0.00613142*Sterms[[1]]
B <- -11843.79 + 6551.35253*Sterms[[2]] - 1566.13883*S + 116.270079*Sterms[[3]]
C <- -33.6485 + 25.928788*Sterms[[2]] - 6.171951*S + 0.45788501*Sterms[[3]]
lnK2 <- lnK(A, B, C, 0, 0, T)
}
res <- c(res, uniroot(function(x) lnK1(te,x)-lnK2(te,x), c(3,7))$root)
}
return(res)
}
att <- function(K)
{
attr(K, "unit") <- "mol/kg-soln"
attr(K, "pH scale") <- "free"
att <- K
}
######################################################################################
######################################################################################
# Henry's constants
######################################################################################
K0_CO2 <- function(S, t)
{
T <- T(t)
A <- 0.023517*S - 167.81077
B <- 9345.17
C <- 23.3585
D <- -2.3656e-4*S
E <- 4.7036e-7*S
K0_CO2 <- exp(lnK(A, B, C, D, E, T))
attr(K0_CO2, "unit") <- "mol/(kg-soln*atm)"
return (K0_CO2)
}
K0_O2 <- function(S, t)
{
T <- T(t)
A <- -846.9978 - 0.037362*S
B <- 25559.07
C <- 146.4813
D <- -0.22204 + 0.00016504*S
E <- -2.0564e-7*S
K0_O2 <- exp(lnK(A, B, C, D, E, T))
K0_O2 <- K0_O2 * PhysChemConst$uMolToMol
attr(K0_O2, "unit") <- "mol/(kg-soln*atm)"
return(K0_O2)
}
######################################################################################
######################################################################################
# ion product of water
######################################################################################
K_W <- function(S, t, p=0, SumH2SO4=NULL, SumHF=NULL, khf="dickson", khso4="dickson")
{
T <- T(t)
Sterms <- Sterms(S)
A <- 148.9652 - 5.977*Sterms[[2]] - 0.01615*S
B <- -13847.26 + 118.67*Sterms[[2]]
C <- -23.6521 + 1.0495*Sterms[[2]]
D <- 0
E <- 0
K_W <- exp(lnK(A, B, C, D, E, T) +
log(scaleconvert(S, t, p=0, SumH2SO4, SumHF, khf, khso4)$tot2sws) +
deltaPlnK(T, p, DeltaPcoeffs$K_W) +
log(scaleconvert(S, t, p, SumH2SO4, SumHF, khf, khso4)$sws2free))
attr(K_W, "unit") <- "(mol/kg-soln)^2"
attr(K_W, "pH scale") <- "free"
return(K_W)
}
######################################################################################
######################################################################################
# acid dissociation constants
######################################################################################
K_HSO4 <- function(S, t, p=0, khso4="dickson")
{
if (khso4 == "khoo")
{
return(K_HSO4_khoo(S=S, t=t, p=p))
}
else
{
T <- T(t)
Iterms <- Iterms(S)
A <- 324.57*Iterms[[3]] - 771.54*Iterms[[1]] + 141.328
B <- 35474*Iterms[[1]] + 1776*Iterms[[2]] - 13856*Iterms[[3]] - 2698*Iterms[[4]] - 4276.1
C <- 114.723*Iterms[[1]] - 47.986*Iterms[[3]] - 23.093
D <- 0
E <- 0
K_HSO4 <- exp(lnK(A, B, C, D, E, T) + deltaPlnK(T, p, DeltaPcoeffs$K_HSO4) + log(molal2molin(S)))
return (eval(att(K_HSO4)))
}
}
K_HSO4_khoo <- function(S, t, p=0)
{
T <- T(t)
A <- 6.3451 + 0.5208*sqrt(I(S))
B <- -647.59
C <- 0
D <- -0.019085
E <- 0
K_HSO4_khoo <- exp(lnK(A, B, C, D, E, T) + deltaPlnK(T, p, DeltaPcoeffs$K_HSO4) + log(molal2molin(S)))
return (eval(att(K_HSO4_khoo)))
}
K_HF <- function(S, t, p=0, SumH2SO4=NULL, SumHF=NULL, khf="dickson", khso4="dickson")
{
if (khf == "perez")
{
return(K_HF_perez(S=S, t=t, p=p, SumH2SO4=SumH2SO4, SumHF=SumHF, khso4=khso4))
}
else
{
T <- T(t)
A <- 1.525 * sqrt(I(S)) - 12.641
B <- 1590.2
C <- 0
D <- 0
E <- 0
K_HF <- exp(lnK(A, B, C, D, E, T) + deltaPlnK(T, p, DeltaPcoeffs$K_HF) + log(molal2molin(S)))
return(eval(att(K_HF)))
}
}
K_HF_perez <- function(S, t, p=0, SumH2SO4=NULL, SumHF=NULL, khso4="dickson")
{
T <- T(t)
A <- -9.68 + 0.111 * sqrt(S)
B <- 874
C <- 0
D <- 0
E <- 0
# To convert from the total to the free scale, only K_HSO4 is needed. That's why we do not need to call "scaleconvert" with
# the option khf="perez" here. Otherwise the cat would also bite its own tail
K_HF_perez <- exp(lnK(A, B, C, D, E, T) + deltaPlnK(T, p, DeltaPcoeffs$K_HF) +
log(scaleconvert(S, t, p=0, SumH2SO4, SumHF, khso4=khso4)$tot2free)) # CODE of CO2Sys matlab version:
# one can assume that the pressure corrections for K_HF and K_HSO4 given in Millero 1995 are
# valid for constants on the FREE pH scale only, that's why we convert the constant
# first from the total to the free scale WITHOUT pressure corrected conversion factors
# and then pressure correct (summands are switched here). If one would now want to
# convert this obtained constant to another scale, it would need to be done WITH
# pressure corrected conversion factors (as implemented in "convert")
return(eval(att(K_HF_perez)))
}
K_CO2 <- function(S, t, p=0, SumH2SO4=NULL, SumHF=NULL, k1k2="lueker", khf="dickson", khso4="dickson")
{
if (k1k2 == "lueker")
{
return(K_CO2_lueker(S=S, t=t, p=p, SumH2SO4=SumH2SO4, SumHF=SumHF, khf=khf, khso4=khso4))
}
else if (k1k2 == "millero")
{
return(K_CO2_millero(S=S, t=t, p=p, SumH2SO4=SumH2SO4, SumHF=SumHF, khf=khf, khso4=khso4))
}
else # Roy1993
{
T <- T(t)
splitS <- splitS_K_CO2(T)
K_CO2 <- c()
for (s in 1:length(S))
{
Sterms <- Sterms(S[[s]])
for (te in 1:length(t))
{
if (S[[s]] > splitS[[te]])
{
A <- 2.83655 - 0.20760841*Sterms[[2]] + 0.08468345*S[[s]] - 0.00654208*Sterms[[3]]
B <- -2307.1266 - 4.0484*Sterms[[2]]
C <- -1.5529413
D <- 0
E <- 0
}
else
{
A <- 290.9097 - 228.39774*Sterms[[2]] + 54.20871*S[[s]] - 3.969101*Sterms[[3]] - 0.00258768*Sterms[[1]]
B <- -14554.21 + 9714.36839*Sterms[[2]] - 2310.48919*S[[s]] + 170.22169*Sterms[[3]]
C <- -45.0575 + 34.485796*Sterms[[2]] - 8.19515*S[[s]] + 0.60367*Sterms[[3]]
D <- 0
E <- 0
}
}
K_CO2 <- c(K_CO2, exp(lnK(A, B, C, D, E, T) +
log(scaleconvert(S[[s]], t, p=0, SumH2SO4[[s]], SumHF[[s]], khf=khf, khso4=khso4)$tot2sws) + #Lewis2008: first convert to SWS with not pressure corrected conversion
deltaPlnK(T, p, DeltaPcoeffs$K_CO2) + # then pressure correct (inferred from Millero1995: valid on SWS)
log(scaleconvert(S[[s]], t, p, SumH2SO4[[s]], SumHF[[s]], khf=khf, khso4=khso4)$sws2free) + # then convert to destiny scale with pressure corrected conversion
log(molal2molin(S[[s]]))))
}
return(eval(att(K_CO2)))
}
}
K_CO2_lueker <- function(S, t, p=0, SumH2SO4=NULL, SumHF=NULL, khf="dickson", khso4="dickson") # Lueker2000
{
T <- T(t)
Sterms <- Sterms(S)
A <- 61.2172 + 0.011555*S - 0.0001152*Sterms[[1]]
B <- -3633.86
C <- -9.67770
D <- 0
E <- 0
K_CO2_lueker <- 10^(lnK(A, B, C, D, E, T)) * exp(log(scaleconvert(S, t, p=0, SumH2SO4, SumHF, khf=khf, khso4=khso4)$tot2sws) +
deltaPlnK(T, p, DeltaPcoeffs$K_CO2) +
log(scaleconvert(S, t, p, SumH2SO4, SumHF, khf=khf, khso4=khso4)$sws2free))
return(eval(att(K_CO2_lueker)))
}
K_CO2_millero <- function(S, t, p=0, SumH2SO4=NULL, SumHF=NULL, khf="dickson", khso4="dickson") # Millero2006
{
T <- T(t)
Sterms <- Sterms(S)
A <- 126.34048 - 0.0331*S + 0.0000533*Sterms[[1]] - 13.4191*Sterms[[2]]
B <- -6320.813 + 6.103*S + 530.123*Sterms[[2]]
C <- -19.568224 + 2.06950*Sterms[[2]]
D <- 0
E <- 0
K_CO2_millero <- 10^(lnK(A, B, C, D, E, T)) * exp(deltaPlnK(T, p, DeltaPcoeffs$K_CO2) + log(scaleconvert(S, t, p, SumH2SO4, SumHF, khf=khf, khso4=khso4)$sws2free))
return(eval(att(K_CO2_millero)))
}
K_HCO3 <- function(S, t, p=0, SumH2SO4=NULL, SumHF=NULL, k1k2="lueker", khf="dickson", khso4="dickson")
{
if (k1k2 == "lueker")
{
return(K_HCO3_lueker(S=S, t=t, p=p, SumH2SO4=SumH2SO4, SumHF=SumHF, khf=khf, khso4=khso4))
}
else if (k1k2 == "millero")
{
return(K_HCO3_millero(S=S, t=t, p=p, SumH2SO4=SumH2SO4, SumHF=SumHF, khf=khf, khso4=khso4))
}
else # Roy1993
{
T <- T(t)
splitS <- splitS_K_HCO3(T)
K_HCO3 <- c()
for (s in 1:length(S))
{
Sterms <- Sterms(S[[s]])
for (te in 1:length(t))
{
if (S[[s]] > splitS[[te]])
{
A <- -9.226508 - 0.106901773*Sterms[[2]] + 0.1130822*S[[s]] - 0.00846934*Sterms[[3]]
B <- -3351.6106 - 23.9722*Sterms[[2]]
C <- -0.2005743
D <- 0
E <- 0
}
else
{
A <- 207.6548 - 167.69908*Sterms[[2]] + 39.75854*S[[s]] - 2.892532*Sterms[[3]] - 0.00613142*Sterms[[1]]
B <- -11843.79 + 6551.35253*Sterms[[2]] - 1566.13883*S[[s]] + 116.270079*Sterms[[3]]
C <- -33.6485 + 25.928788*Sterms[[2]] - 6.171951*S[[s]] + 0.45788501*Sterms[[3]]
D <- 0
E <- 0
}
}
K_HCO3 <- c(K_HCO3, exp(lnK(A, B, C, D, E, T) +
log(scaleconvert(S[[s]], t, p=0, SumH2SO4[[s]], SumHF[[s]], khf=khf, khso4=khso4)$tot2sws) +
deltaPlnK(T, p, DeltaPcoeffs$K_HCO3) +
log(scaleconvert(S[[s]], t, p, SumH2SO4[[s]], SumHF[[s]], khf=khf, khso4=khso4)$sws2free) +
log(molal2molin(S[[s]]))))
}
return(eval(att(K_HCO3)))
}
}
K_HCO3_lueker <- function(S, t, p=0, SumH2SO4=NULL, SumHF=NULL, khf="dickson", khso4="dickson") # Lueker2000
{
T <- T(t)
Sterms <- Sterms(S)
A <- -25.9290 + 0.01781*S -0.0001122*Sterms[[1]]
B <- -471.78
C <- 3.16967
D <- 0
E <- 0
K_HCO3_lueker <- 10^(lnK(A, B, C, D, E, T)) * exp(log(scaleconvert(S, t, p=0, SumH2SO4, SumHF, khf=khf, khso4=khso4)$tot2sws) +
deltaPlnK(T, p, DeltaPcoeffs$K_HCO3) +
log(scaleconvert(S, t, p, SumH2SO4, SumHF, khf=khf, khso4=khso4)$sws2free))
return(eval(att(K_HCO3_lueker)))
}
K_HCO3_millero <- function(S, t, p=0, SumH2SO4=NULL, SumHF=NULL, khf="dickson", khso4="dickson") # Millero2006
{
T <- T(t)
Sterms <- Sterms(S)
A <- 90.18333 - 0.1248*S + 0.0003687*Sterms[[1]] - 21.0894*Sterms[[2]]
B <- -5143.692 + 20.051*S + 772.483*Sterms[[2]]
C <- -14.613358 + 3.3336*Sterms[[2]]
D <- 0
E <- 0
K_HCO3_millero <- 10^(lnK(A, B, C, D, E, T)) * exp(deltaPlnK(T, p, DeltaPcoeffs$K_HCO3) + log(scaleconvert(S, t, p, SumH2SO4, SumHF, khf=khf, khso4=khso4)$sws2free))
return(eval(att(K_HCO3_millero)))
}
K_BOH3 <- function(S, t, p=0, SumH2SO4=NULL, SumHF=NULL, khf="dickson", khso4="dickson")
{
T <- T(t)
Sterms <- Sterms(S)
A <- 148.0248 + 137.1942*Sterms[[2]] + 1.62142*S
B <- -8966.90 - 2890.53*Sterms[[2]] - 77.942*S + 1.728*Sterms[[3]] - 0.0996*Sterms[[1]]
C <- -24.4344 - 25.085*Sterms[[2]] - 0.2474*S
D <- 0.053105*Sterms[[2]]
E <- 0
K_BOH3 <- exp(lnK(A, B, C, D, E, T) +
log(scaleconvert(S, t, p=0, SumH2SO4, SumHF, khf=khf, khso4=khso4)$tot2sws) +
deltaPlnK(T, p, DeltaPcoeffs$K_BOH3) +
log(scaleconvert(S, t, p, SumH2SO4, SumHF, khf=khf, khso4=khso4)$sws2free))
return(eval(att(K_BOH3)))
}
K_NH4 <- function(S, t, p=0, SumH2SO4=NULL, SumHF=NULL, khf="dickson", khso4="dickson")
{
T <- T(t)
Sterms <- Sterms(S)
A <- -0.25444 + 0.46532*Sterms[[2]] - 0.01992*S
B <- -6285.33 - 123.7184*Sterms[[2]] + 3.17556*S
C <- 0
D <- 0.0001635
E <- 0
K_NH4 <- exp(lnK(A, B, C, D, E, T) + deltaPlnK(T, p, DeltaPcoeffs$K_NH4) + log(scaleconvert(S, t, p, SumH2SO4, SumHF, khf=khf, khso4=khso4)$sws2free))
return(eval(att(K_NH4)))
}
K_H2S <- function(S, t, p=0, SumH2SO4=NULL, SumHF=NULL, khf="dickson", khso4="dickson")
{
T <- T(t)
Sterms <- Sterms(S)
A <- 225.838 + 0.3449*Sterms[[2]] - 0.0274*S
B <- -13275.3
C <- -34.6435
D <- 0
E <- 0
K_H2S <- exp(lnK(A, B, C, D, E, T) +
log(scaleconvert(S, t, p=0, SumH2SO4, SumHF, khf=khf, khso4=khso4)$tot2sws) +
deltaPlnK(T, p, DeltaPcoeffs$K_H2S) +
log(scaleconvert(S, t, p, SumH2SO4, SumHF, khf=khf, khso4=khso4)$sws2free))
return(eval(att(K_H2S)))
}
K_H3PO4 <- function(S, t, p=0, SumH2SO4=NULL, SumHF=NULL, khf="dickson", khso4="dickson")
{
T <- T(t)
Sterms <- Sterms(S)
A <- 115.525 + 0.69171*Sterms[[2]] - 0.01844*S
B <- -4576.752 - 106.736*Sterms[[2]] - 0.65643*S
C <- -18.453
D <- 0
E <- 0
K_H3PO4 <- exp(lnK(A, B, C, D, E, T) +
log(scaleconvert(S, t, p=0, SumH2SO4, SumHF, khf=khf, khso4=khso4)$tot2sws) +
deltaPlnK(T, p, DeltaPcoeffs$K_H3PO4) +
log(scaleconvert(S, t, p, SumH2SO4, SumHF, khf=khf, khso4=khso4)$sws2free))
return(eval(att(K_H3PO4)))
}
K_H2PO4 <- function(S, t, p=0, SumH2SO4=NULL, SumHF=NULL, khf="dickson", khso4="dickson")
{
T <- T(t)
Sterms <- Sterms(S)
A <- 172.0883 + 1.3566*Sterms[[2]] - 0.05778*S
B <- -8814.715 - 160.340*Sterms[[2]] + 0.37335*S
C <- -27.927
D <- 0
E <- 0
K_H2PO4 <- exp(lnK(A, B, C, D, E, T) +
log(scaleconvert(S, t, p=0, SumH2SO4, SumHF, khf=khf, khso4=khso4)$tot2sws) +
deltaPlnK(T, p, DeltaPcoeffs$K_H2PO4) +
log(scaleconvert(S, t, p, SumH2SO4, SumHF, khf=khf, khso4=khso4)$sws2free))
return(eval(att(K_H2PO4)))
}
K_HPO4 <- function(S, t, p=0, SumH2SO4=NULL, SumHF=NULL, khf="dickson", khso4="dickson")
{
T <- T(t)
Sterms <- Sterms(S)
A <- -18.141 + 2.81197*Sterms[[2]] - 0.09984*S
B <- -3070.75 + 17.27039*Sterms[[2]] - 44.99486*S
C <- 0
D <- 0
E <- 0
K_HPO4 <- exp(lnK(A, B, C, D, E, T) +
log(scaleconvert(S, t, p=0, SumH2SO4, SumHF, khf=khf, khso4=khso4)$tot2sws) +
deltaPlnK(T, p, DeltaPcoeffs$K_HPO4) +
log(scaleconvert(S, t, p, SumH2SO4, SumHF, khf=khf, khso4=khso4)$sws2free))
return(eval(att(K_HPO4)))
}
K_SiOH4 <- function(S, t, p=0, SumH2SO4=NULL, SumHF=NULL, khf="dickson", khso4="dickson")
{
T <- T(t)
Iterms <- Iterms(S)
A <- 117.385 + 3.5913*Iterms[[3]] - 1.5998*Iterms[[1]] + 0.07871*Iterms[[2]]
B <- -8904.2 - 458.79*Iterms[[3]] + 188.74*Iterms[[1]] - 12.1652*Iterms[[2]]
C <- -19.334
D <- 0
E <- 0
K_SiOH4 <- exp(lnK(A, B, C, D, E, T) +
log(scaleconvert(S, t, p=0, SumH2SO4, SumHF, khf=khf, khso4=khso4)$tot2sws) +
deltaPlnK(T, p, DeltaPcoeffs$K_SiOH4) +
log(scaleconvert(S, t, p, SumH2SO4, SumHF, khf=khf, khso4=khso4)$sws2free) +
log(molal2molin(S)))
return(eval(att(K_SiOH4)))
}
K_SiOOH3 <- function(S, t, p=0, SumH2SO4=NULL, SumHF=NULL, khf="dickson", khso4="dickson")
{
T <- T(t)
A <- 8.9613
B <- -4465.18
C <- 0
D <- -0.021952
E <- 0
T <- T(t)
K_SiOOH3 <- 10^(lnK(A, B, C, D, E, T)) * exp(log(scaleconvert(S, t, p = 0, SumH2SO4, SumHF, khf = khf, khso4 = khso4)$tot2sws) +
deltaPlnK(T, p, DeltaPcoeffs$K_SiOOH3) +
log(scaleconvert(S, t, p, SumH2SO4, SumHF, khf = khf, khso4 = khso4)$sws2free))
return(eval(att(K_SiOOH3)))
}
######################################################################################
######################################################################################
# solubility products
######################################################################################
Ksp_calcite <- function(S, t, p=0)
{
T <- T(t)
Sterms <- Sterms(S)
A <- -171.9065 - 0.77712*Sterms[[2]] - 0.07711*S + 0.0041249*Sterms[[3]]
B <- 2839.319 + 178.34*Sterms[[2]]
C <- 71.595
D <- -0.077993 + 0.0028426*Sterms[[2]]
E <- 0
Ksp_calcite <- 10^(logK(A, B, C, D, E, T)) * exp(deltaPlnK(T, p, DeltaPcoeffs$Ksp_calcite))
attr(Ksp_calcite, "unit") <- "(mol/kg-soln)^2"
return(Ksp_calcite)
}
Ksp_aragonite <- function(S, t, p=0)
{
T <- T(t)
Sterms <- Sterms(S)
A <- -171.945 - 0.068393*Sterms[[2]] - 0.10018*S + 0.0059415*Sterms[[3]]
B <- 2903.293 + 88.135*Sterms[[2]]
C <- 71.595
D <- -0.077993 + 0.0017276*Sterms[[2]]
E <- 0
Ksp_aragonite <- 10^(logK(A, B, C, D, E, T)) * exp(deltaPlnK(T, p, DeltaPcoeffs$Ksp_aragonite))
attr(Ksp_aragonite, "unit") <- "(mol/kg-soln)^2"
return(Ksp_aragonite)
}
| /scratch/gouwar.j/cran-all/cranData/AquaEnv/R/aquaenv_private_Kfunctions.R |
##################################################
# operations on objects of type AQUAENV
###################################################
# PRIVATE function:
# converts all elements of a special unit or pH scale in an object of class aquaenv
convert.aquaenv <- function(aquaenv, # object of class aquaenv
from, # the unit which needs to be converted (as a string; must be a perfect match)
to, # the unit to which the conversion should go
factor, # the conversion factor to be applied: can either be a number (e.g. 1000 to convert from mol to mmol), or any of the conversion factors given in an object of class aquaenv
convattr="unit", # which attribute should be converted? can either be "unit" or "pH scale"
...)
{
for (x in names(aquaenv))
{
if (!is.null(attr(aquaenv[[x]], convattr)))
{
if (attr(aquaenv[[x]], convattr) == from)
{
aquaenv[[x]] <- aquaenv[[x]] * factor
attr(aquaenv[[x]], convattr) <- to
}
}
}
return(aquaenv) # object of class aquaenv whith the converted elements
}
# PRIVATE function:
# returns the (maximal) length of the elements in an object of class aquaenv (i.e. > 1 if one of the input variables was a vector)
length.aquaenv <- function(x, # object of class aquaenv
...)
{
for (e in x)
{
if (length(e) > 1)
{
return(length(e)) # the maximal length of the elements in the object of class aquaenv
}
}
return(1) # the maximal length of the elements in the object of class aquaenv
}
# PRIVATE function:
# adds an element to an object of class aquaenv
c.aquaenv <- function(aquaenv, # object of class aquaenv
x, # a vector of the form c(value, name) representing the element to be inserted into the object of class aquaenv
...)
{
aquaenv[[x[[2]]]] <- x[[1]]
return(aquaenv) # object of class aquaenv with the added element
}
# PRIVATE function:
# merges the elements of two objects of class aquaenv: element names are taken from the first argument, the elements of which are also first in the merged object
merge.aquaenv <- function(x, # object of class aquaenv: this is where the element names are taken from
y, # object of class aquaenv: must contain at leas all the element (names) as x, extra elements are ignored
...)
{
nam <- names(x)
for (n in nam)
{
unit <- attr(x[[n]], "unit")
x[[n]] <- c(x[[n]], y[[n]])
attr(x[[n]], "unit") <- unit
}
return(x) # object of class aquaenv with merged elements
}
# PRIVATE function:
# clones an object of class aquaenv: it is possible to supply a new value for either TA or pH; the switches speciation, skeleton, revelle, and dsa are obtained from the object to be cloned
cloneaquaenv <- function(aquaenv, # object of class aquaenv
TA=NULL, # optional new value for TA
pH=NULL, # optional new value for pH
k_co2=NULL, # used for TA fitting: give a K_CO2 and NOT calculate it from T and S: i.e. K_CO2 can be fitted in the routine as well
k1k2="roy", # either "roy" (default, Roy1993a) or "lueker" (Lueker2000, calculated with seacarb) for K\_CO2 and K\_HCO3
khf="dickson", # either "dickson" (default, Dickson1979a) or "perez" (Perez1987a, calculated with seacarb) for K\_HF}
khso4="dickson") # either 'dickson" (default, Dickson1990) or "khoo" (Khoo1977) for K\_HSO4
{
if (is.null(TA) && is.null(pH))
{
pH <- aquaenv$pH
}
res <- aquaenv(S=aquaenv$S, t=aquaenv$t, p=aquaenv$p, SumCO2=aquaenv$SumCO2, SumNH4=aquaenv$SumNH4, SumH2S=aquaenv$SumH2S,SumH3PO4=aquaenv$SumH3PO4,
SumSiOH4=aquaenv$SumSiOH4, SumHNO3=aquaenv$SumHNO3, SumHNO2=aquaenv$SumHNO2, SumBOH3=aquaenv$SumBOH3, SumH2SO4=aquaenv$SumH2SO4,
SumHF=aquaenv$SumHF, pH=pH, TA=TA,
speciation=(!is.null(aquaenv$HCO3)), skeleton=(is.null(aquaenv$Na)), revelle=(!is.null(aquaenv$revelle)), dsa=(!is.null(aquaenv$dTAdH)), k1k2=k1k2, khf=khf, khso4=khso4)
if (!is.null(k_co2))
{
res$K_CO2 <- rep(k_co2,length(res))
attr(res$K_CO2, "unit") <- "mol/kg-soln"
attr(res$K_CO2, "pH scale") <- "free"
}
return(res) # cloned object of class aquaenv
}
# PRIVATE function:
# creates an object of class aquaenv from a data frame (e.g. as supplied from the numerical solver of a dynamic model)
from.data.frame <- function(df) # data frame
{
temp <- as.list(df)
class(temp) <- "aquaenv"
return(temp) # object of class aquaenv
}
#########################################################
# CONVERSION functions
#########################################################
# PRIVATE function:
# converts either the pH scale of a pH value, the pH scale of a dissociation constant (K*), or the unit of a concentration value
convert.standard <- function(x, # the object to be converted (pH value, K* value, or concentration value)
vartype, # the type of x, either "pHscale", "KHscale", or "conc"
what, # the type of conversion to be done, for pH scales one of "free2tot", "free2sws", "free2nbs", ... (any combination of "free", "tot", "sws", and "nbs"); for concentrations one of "molar2molal", "molar2molin", ... (any combination of "molar" (mol/l), "molal" (mol/kg-H2O), and "molin" (mol/kg-solution))
S, # salinity (in practical salinity units: no unit)
t, # temperature in degrees centigrade
p=0, # gauge pressure (total pressure minus atmospheric pressure) in bars
SumH2SO4=NULL, # total sulfate concentration in mol/kg-solution; if not supplied this is calculated from S
SumHF=NULL, # total fluoride concentration in mol/kg-solution; if not supplied this is calculated from S
khf="dickson", # either "dickson" (default, Dickson1979a) or "perez" (Perez1987a) for K\_HF
khso4="dickson") # either 'dickson" (default, Dickson1990) or "khoo" (Khoo1977) for K\_HSO4
{
result <- (switch
(vartype,
pHscale = switch
(what,
free2tot = x - log10(scaleconvert(S, t, p, SumH2SO4, SumHF, khf, khso4)$free2tot),
free2sws = x - log10(scaleconvert(S, t, p, SumH2SO4, SumHF, khf, khso4)$free2sws),
free2nbs = x - log10(scaleconvert(S, t, p, SumH2SO4, SumHF, khf, khso4)$free2nbs),
tot2free = x - log10(scaleconvert(S, t, p, SumH2SO4, SumHF, khf, khso4)$tot2free),
tot2sws = x - log10(scaleconvert(S, t, p, SumH2SO4, SumHF, khf, khso4)$tot2sws),
tot2nbs = x - log10(scaleconvert(S, t, p, SumH2SO4, SumHF, khf, khso4)$tot2nbs),
sws2free = x - log10(scaleconvert(S, t, p, SumH2SO4, SumHF, khf, khso4)$sws2free),
sws2tot = x - log10(scaleconvert(S, t, p, SumH2SO4, SumHF, khf, khso4)$sws2tot),
sws2nbs = x - log10(scaleconvert(S, t, p, SumH2SO4, SumHF, khf, khso4)$sws2nbs),
nbs2free = x - log10(scaleconvert(S, t, p, SumH2SO4, SumHF, khf, khso4)$nbs2free),
nbs2tot = x - log10(scaleconvert(S, t, p, SumH2SO4, SumHF, khf, khso4)$nbs2tot),
nbs2sws = x - log10(scaleconvert(S, t, p, SumH2SO4, SumHF, khf, khso4)$nbs2sws)
),
KHscale = switch
(what,
free2tot = x * scaleconvert(S, t, p, SumH2SO4, SumHF, khf, khso4)$free2tot,
free2sws = x * scaleconvert(S, t, p, SumH2SO4, SumHF, khf, khso4)$free2sws,
free2nbs = x * scaleconvert(S, t, p, SumH2SO4, SumHF, khf, khso4)$free2nbs,
tot2free = x * scaleconvert(S, t, p, SumH2SO4, SumHF, khf, khso4)$tot2free,
tot2sws = x * scaleconvert(S, t, p, SumH2SO4, SumHF, khf, khso4)$tot2sws,
tot2nbs = x * scaleconvert(S, t, p, SumH2SO4, SumHF, khf, khso4)$tot2nbs,
sws2free = x * scaleconvert(S, t, p, SumH2SO4, SumHF, khf, khso4)$sws2free,
sws2tot = x * scaleconvert(S, t, p, SumH2SO4, SumHF, khf, khso4)$sws2tot,
sws2nbs = x * scaleconvert(S, t, p, SumH2SO4, SumHF, khf, khso4)$sws2nbs,
nbs2free = x * scaleconvert(S, t, p, SumH2SO4, SumHF, khf, khso4)$nbs2free,
nbs2tot = x * scaleconvert(S, t, p, SumH2SO4, SumHF, khf, khso4)$nbs2tot,
nbs2sws = x * scaleconvert(S, t, p, SumH2SO4, SumHF, khf, khso4)$nbs2sws
),
conc = switch
(what,
molar2molal = x * (1/((seadensity(S,t)/1e3)* molal2molin(S))),
molar2molin = x * (1/((seadensity(S,t))/1e3)) ,
molal2molar = x * (molal2molin(S) * (seadensity(S,t))/1e3) ,
molal2molin = x * (molal2molin(S)) ,
molin2molar = x * (seadensity(S,t)/1e3) ,
molin2molal = x * (1/molal2molin(S))
)
)
)
if ((what == "tot2free") || (what == "sws2free") || (what == "nbs2free"))
{
attr(result, "pH scale") <- "free"
}
else if ((what == "free2tot") || (what == "sws2tot") || (what == "nbs2tot"))
{
attr(result, "pH scale") <- "tot"
}
else if ((what == "free2nbs") || (what == "sws2nbs") || (what == "tot2nbs"))
{
attr(result, "pH scale") <- "nbs"
}
else if ((what == "molar2molal") || (what == "molin2molal"))
{
attr(result, "unit") <- "mol/kg-H2O"
}
else if ((what == "molal2molin") || (what == "molar2molin"))
{
attr(result, "unit") <- "mol/kg-soln"
}
else if ((what == "molal2molar") || (what == "molin2molar"))
{
attr(result, "unit") <- "mol/l-soln"
}
return(result) # converted pH, K*, or concentration value, attributed with the new unit/pH scale
}
# PUBLIC function:
# calculates the depth (in m) from the gauge pressure p (or the total pressure P) and the latitude (in degrees: -90 to 90) and the atmospheric pressure (in bar)
# references Fofonoff1983
watdepth <- function(P=Pa, p=pmax(0, P-Pa), lat=0, Pa=1.013253)
{
gravity <- function(lat)
{
X <- sin(lat * pi/180)
X <- X * X
grav = 9.780318 * (1 + (0.0052788 + 2.36e-05 * X) * X)
return(grav)
}
P <- p * 10
denom = gravity(lat) + 1.092e-06 * P
nom = (9.72659 + (-2.2512e-05 + (2.279e-10 - 1.82e-15 * P) *
P) * P) * P
return(nom/denom)
}
# PUBLIC function:
# calculates the gauge pressure from the depth (in m) and the latitude (in degrees: -90 to 90) and the atmospheric pressure (in bar)
# references Fofonoff1983
gauge_p <- function(d, lat=0, Pa=1.01325)
{
gauge_p <- c()
for (de in d)
{
if (de==0)
{
gauge_p <- c(gauge_p,0)
}
else
{
xx <- function(x)
{
return(de - watdepth(P=x+Pa, lat=lat))
}
gauge_p <- c(gauge_p, (uniroot(f=xx, interval=c(0,1300), tol=Technicals$uniroottol, maxiter=Technicals$maxiter)$root))
}
}
return(gauge_p)
}
# PRIVATE function:
# calculates the ionic strength I as a function of salinity S
# references: DOE1994, Zeebe2001, Roy1993b (the carbonic acid paper)
I <- function(S) # salinity S in practical salinity units (i.e. no unit)
{
return(19.924*S/(1000-1.005*S)) # ionic strength in mol/kg-solution (molinity)
}
# PRIVATE function:
# calculates chlorinity Cl from salinity S
# references: DOE1994, Zeebe2001
Cl <- function(S) # salinity S in practical salinity units (i.e. no unit)
{
return(S/1.80655) # chlorinity Cl in permil
}
# PRIVATE function:
# calculates concentrations of constituents of natural seawater from a given salinity S
# reference: DOE1994
seaconc <- function(spec, # constituent of seawater (chemical species) of which the concentration should be calculated. can be any name of the vectors ConcRelCl and MeanMolecularMass: "Cl", "SO4", "Br", "F", "Na", "Mg", "Ca", "K", "Sr", "B", "S"
S) # salinity S in practical salinity units (i.e. no unit)
{
return( # concentration of the constituent of seawater speciefied in spec in mol/kg-solution (molinity): this is determined by the data in ConcRelCl and MeanMolecularMass
ConcRelCl[[spec]]/MeanMolecularMass[[spec]]*Cl(S))
}
# PRIVATE function:
# calculates the conversion factor converting from molality (mol/kg-H2O) to molinity (mol/kg-solution) from salinity S
# reference: Roy1993b (the carbonic acid paper), DOE1994
molal2molin <- function(S) # salinity S in practical salinity units (i.e. no unit)
{
return(1-0.001005*S) # the conversion factor from molality (mol/kg-H2O) to molinity (mol/kg-solution)
}
# PRIVATE function:
# calculates the temperature in Kelvin from the temperature in degrees centigrade
T <- function(t) # temperature in degrees centigrade
{
return(t - PhysChemConst$absZero) # temperature in Kelvin
}
# PRIVATE function:
# provides pH scale conversion factors (caution: the activity coefficient for H+ (needed for NBS scale conversions) is calculated with the Davies equation (Zeebe2001) which is only accurate up to ionic strengthes of I = 0.5)
# references: Dickson1984, DOE1994, Zeebe2001
scaleconvert <- function(S, # salinity S in practical salinity units (i.e. no unit)
t, # temperature in degrees centigrade
p=0, # gauge pressure (total pressure minus atmospheric pressure) in bars
SumH2SO4=NULL, # total sulfate concentration in mol/kg-solution; if not supplied this is calculated from S
SumHF=NULL, # total fluoride concentration in mol/kg-solution; if not supplied this is calculated from S
khf="dickson", # either "dickson" (Dickson1979a) or "perez" (Perez1987a) for K_HF
khso4="dickson") # either 'dickson" (default, Dickson1990) or "khoo" (Khoo1977) for K\_HSO4
{
if (is.null(SumH2SO4))
{
SumH2SO4 = seaconc("SO4", S)
}
if (is.null(SumHF))
{
SumHF = seaconc("F", S)
}
K_HSO4 <- K_HSO4(S, t, p, khso4=khso4)
K_HF <- K_HF(S, t, p, SumH2SO4, SumHF, khf=khf)
FreeToTot <- (1 + (SumH2SO4/K_HSO4))
FreeToSWS <- (1 + (SumH2SO4/K_HSO4) + (SumHF/K_HF))
attributes(FreeToTot) <- NULL
attributes(FreeToSWS) <- NULL
#davies equation: only valid up to I=0.5
SQRTI <- sqrt(I(S))
eT <- PhysChemConst$e*T(t)
A <- 1.82e6/(eT*sqrt(eT))
gamma_H <- 10^-((A*((SQRTI/(1+SQRTI)) - 0.2*I(S))))
NBSToFree <- 1/(gamma_H*FreeToSWS) * molal2molin(S) #Lewis1998, Perez1984: pH_NBS = -log10(gamma_H (H + HSO4 + HF)) with concs being molal
#i.e.: the NBS scale is related to the SEAWATER scale via gamma_H not the free scale
# (since, if you measure with NBS buffers in seawater, you do not get the activity of the proton alone
# but of the proton plus HSO4 and HF)
##################
#Lewis1998: NBS scale is based on mol/kg-H2O (molality) and all other scales (incl free) on mol/kg-soln (molinity)
return(list( # list of conversion factors "free2tot", "free2sws", etc.
free2tot = FreeToTot,
free2sws = FreeToSWS,
free2nbs = 1/NBSToFree,
tot2free = 1/FreeToTot,
tot2sws = 1/FreeToTot * FreeToSWS,
tot2nbs = 1/FreeToTot * 1/NBSToFree,
sws2free = 1/FreeToSWS,
sws2tot = 1/FreeToSWS * FreeToTot,
sws2nbs = 1/FreeToSWS * 1/NBSToFree,
nbs2free = NBSToFree,
nbs2tot = NBSToFree * FreeToTot,
nbs2sws = NBSToFree * FreeToSWS
))
}
# PRIVATE function:
# calculates seawater density (in kg/m3) from temperature (in degrees centigrade) and salinity
# references: Millero1981, DOE1994
seadensity <- function(S, # salinity S in practical salinity units (i.e. no unit)
t) # temperature in degrees centigrade
{
t2 <- t^2
t3 <- t2 * t
t4 <- t3 * t
t5 <- t4 * t
A <- 8.24493e-1 - 4.0899e-3*t + 7.6438e-5*t2 - 8.2467e-7*t3 + 5.3875e-9*t4
B <- -5.72466e-3 + 1.0227e-4*t - 1.6546e-6*t2
C <- 4.8314e-4
densityWater <- 999.842594 + 6.793952e-2*t - 9.095290e-3*t2 + 1.001685e-4*t3 - 1.120083e-6*t4 + 6.536332e-9*t5
return(densityWater + A*S + B*S*sqrt(S) + C*S^2) # seawater density in kg/m
}
################################################################
# input / output (IO) functions
################################################################
# PRIVATE function:
# basic wrapper for the R plot function for plotting objects of class aquaenv; no return value, just side-effect
basicplot <- function(aquaenv, # object of class aquaenv
xval, # x-value: the independent variable describing a change in elements of an object of class aquaenv
type="l", # standard plot parameter; default: plot lines
mgp=c(1.8, 0.5, 0), # standard plot parameter; default: axis title on line 1.8, axis labels on line 0.5, axis on line 0
mar=c(3,3,0.5,0.5), # standard plot parameter; default: margin of 3 lines bottom and left and 0.5 lines top and right
oma=c(0,0,0,0), # standard plot parameter; default: no outer margin
size=c(15,13), # the size of the plot device; default: 15 (width) by 13 (height) inches
mfrow=c(11,10), # standard plot parameter; default: 11 columns and 10 rows of plots
device="x11", # the device to plot on; default: "x11" (can also be "eps" or "pdf")
filename="aquaenv", # filename to be used if "eps" or "pdf" is selected for device
newdevice, # flag: if TRUE, new plot device is opened
setpar, # flag: if TRUE parameters are set with the function par
ylab=NULL, # y axis label: if given, it overrides the names from an aquaenv object
...)
{
if (newdevice)
{
opendevice(device, size, filename)
}
if (setpar)
{
par(mfrow=mfrow, mar=mar, oma=oma, mgp=mgp)
}
aquaenv <- as.data.frame(aquaenv)
for (i in 1:length(aquaenv))
{
if(is.null(ylab))
{
ylab_ <- names(aquaenv)[[i]]
}
else
{
ylab_ <- ylab
}
plot(xval, aquaenv[[i]], ylab=ylab_, type=type, ...)
}
}
# PRIVATE function:
# opens a device for plotting; no return value, just side-effect
opendevice <- function(device, # either "x11", "eps", or "pdf"
size, # size of the plot device in the form c(width, height)
filename) # filename to use if "eps" or "pdf" is used
{
if (device == "x11")
{
dev.new(width=size[[1]], height=size[[2]])
}
else if (device == "eps")
{
postscript(width=size[[1]], height=size[[2]], file=paste(filename, ".eps", sep=""), paper="special")
}
else if (device == "pdf")
{
pdf(width=size[[1]], height=size[[2]], file=paste(filename, ".pdf", sep=""), paper="special")
}
}
# PRIVATE function:
# plots all elements of an object of class aquaenv; no return value, just side-effect
plotall <- function(aquaenv, # object of class aquaenv
xval, # x-value: the independent variable describing a change in elements of an object of class aquaenv
...)
{
basicplot(aquaenv, xval=xval, ...)
}
# PRIVATE function:
# plots just the elements of an object of class aquaenv given in what; no return value, just side-effect
selectplot <- function(aquaenv, # object of class aquaenv
xval, # x-value: the independent variable describing a change in elements of an object of class aquaenv
what, # vector of names of elements of aquaenv that should be plotted
mfrow=c(1,1), # standard plot parameter; default: just one plot
size=c(7,7), # the size of the plot device; default: 7 (width) by 7 (height) inches
...)
{
aquaenvnew <- aquaenv[what]
class(aquaenvnew) <- "aquaenv"
basicplot(aquaenvnew, xval=xval, mfrow=mfrow, size=size, ...)
}
# PRIVATE function:
# creates a bjerrumplot from the elements of an object of class aquaenv given in what; no return value, just side-effect
bjerrumplot <- function(aquaenv, # object of class aquaenv
what, # vector of names of elements of aquaenv that should be plotted; if not specified: what <- c("CO2", "HCO3", "CO3", "BOH3", "BOH4", "OH", "H3PO4", "H2PO4", "HPO4", "PO4", "SiOH4", "SiOOH3", "SiO2OH2", "H2S", "HS", "S2min", "NH4", "NH3", "H2SO4", "HSO4", "SO4", "HF", "F", "HNO3", "NO3", "HNO2", "NO2")
log=FALSE, # should the plot be on a logarithmic y axis?
palette=NULL, # a vector of colors to use in the plot (either numbers or names given in colors())
device="x11", # the device to plot on; default: "x11" (can also be "eps" or "pdf")
filename="aquaenv", # filename to be used if "eps" or "pdf" is selected for device
size=c(12,10), # the size of the plot device; default: 12 (width) by 10 (height) inches
ylim=NULL, # standard plot parameter; if not supplied it will be calculated by range() of the elements to plot
lwd=2, # standard plot parameter; width of the lines in the plot
xlab="free scale pH", # x axis label
mgp=c(1.8, 0.5, 0), # standard plot parameter; default: axis title on line 1.8, axis labels on line 0.5, axis on line 0
mar=c(3,3,0.5,0.5), # standard plot parameter; default: margin of 3 lines bottom and left and 0.5 lines top and right
oma=c(0,0,0,0), # standard plot parameter; default: no outer margin
legendposition="bottomleft", # position of the legend
legendinset=0.05, # standard legend parameter inset
legendlwd=4, # standard legend parameter lwd: line width of lines in legend
bg="white", # standard legend parameter: default background color: white
newdevice, # flag: if TRUE, new plot device is opened
setpar, # flag: if TRUE parameters are set with the function par
...)
{
if (is.null(what))
{
what <- c("CO2", "HCO3", "CO3", "BOH3", "BOH4", "OH", "H3PO4", "H2PO4", "HPO4", "PO4", "SiOH4", "SiOOH3", "SiO2OH2",
"H2S", "HS", "S2min", "NH4", "NH3", "H2SO4", "HSO4", "SO4", "HF", "F", "HNO3", "NO3", "HNO2", "NO2")
}
bjerrumvarslist <- aquaenv[what]
class(bjerrumvarslist) <- "aquaenv"
bjerrumvars <- as.data.frame(bjerrumvarslist)
if (newdevice)
{
opendevice(device, size, filename)
}
if(setpar)
{
par(mar=mar, mgp=mgp, oma=oma)
}
if (is.null(palette))
{
palette <- 1:length(what)
}
if (log)
{
if (is.null(ylim))
{
ylim <- range(log10(bjerrumvars))
}
yvals <- log10(bjerrumvars)
ylab <- paste("log10([X]/(",attr(bjerrumvarslist[[1]], "unit"),"))", sep="")
}
else
{
if (is.null(ylim))
{
ylim <- range(bjerrumvars)
}
yvals <- bjerrumvars
ylab <- attr(bjerrumvarslist[[1]], "unit")
}
for (i in 1:length(bjerrumvars))
{
plot(aquaenv$pH, yvals[[i]], type="l", ylab=ylab, xlab=xlab, ylim=ylim, col=palette[[i]], lwd=lwd, ...)
par(new=TRUE)
}
par(new=FALSE)
legend(legendposition, inset=legendinset, legend=names(bjerrumvarslist), col=palette, bg=bg, lwd=legendlwd, ...)
}
# PRIVATE function:
# creates a cumulative plot from the elements of an object of class aquaenv given in what; no return value, just side-effect
cumulativeplot <- function(aquaenv, # object of class aquaenv
xval, # x-value: the independent variable describing a change in elements of an object of class aquaenv
what, # vector of names of elements of aquaenv that should be plotted
total=TRUE, # should the sum of all elements specified in what be plotted as well?
palette=NULL, # a vector of colors to use in the plot (either numbers or names given in colors())
device="x11", # the device to plot on; default: "x11" (can also be "eps" or "pdf")
filename="aquaenv",# filename to be used if "eps" or "pdf" is selected for device
size=c(12,10), # the size of the plot device; default: 12 (width) by 10 (height) inches
ylim=NULL, # standard plot parameter; if not supplied it will be calculated by an adaptation of range() of the elements to plot
lwd=2, # standard plot parameter; width of the lines in the plot
mgp=c(1.8, 0.5, 0),# standard plot parameter; default: axis title on line 1.8, axis labels on line 0.5, axis on line 0
mar=c(3,3,0.5,0.5),# standard plot parameter; default: margin of 3 lines bottom and left and 0.5 lines top and right
oma=c(0,0,0,0), # standard plot parameter; default: no outer margin
legendposition="bottomleft", # position of the legend
legendinset=0.05, # standard legend parameter inset
legendlwd=4, # standard legend parameter lwd: line width of lines in legend
bg="white", # standard legend parameter: default background color: white
y.intersp=1.2, # standard legend parameter; default: 1.2 lines space between the lines in the legend
newdevice, # flag: if TRUE, new plot device is opened
setpar, # flag: if TRUE parameters are set with the function par
...)
{
if (is.null(what))
{
what=names(aquaenv)
}
cumulativevarslist <- aquaenv[what]
class(cumulativevarslist) <- "aquaenv"
cumulativevars <- as.data.frame(cumulativevarslist)
if (is.null(ylim))
{
ylim <- c(0,0)
for (var in cumulativevars)
{
ylim <- ylim + range(c(var,0))
}
}
if (is.null(palette))
{
palette <- 1:length(names(cumulativevars))
}
if (newdevice)
{
opendevice(device, size, filename)
}
if (setpar)
{
par(mar=mar, mgp=mgp, oma=oma)
}
plot(xval, rep(0,length(xval)), type="l", ylim=ylim, col="white", ...)
sumfuncpos <- rep(0,length(xval))
for (x in 1:(length(cumulativevars)))
{
yval <- (cumulativevars[[x]])
yval[yval<=0] <- 0
newsumfuncpos <- sumfuncpos + yval
if (!(identical(yval, rep(0,length(yval)))))
{
polygon(c(xval,rev(xval)), c(newsumfuncpos, rev(sumfuncpos)), col=palette[[x]], border=NA)
}
sumfuncpos <- newsumfuncpos
}
sumfuncneg <- rep(0,length(xval))
for (x in 1:(length(cumulativevars)))
{
yval <- (cumulativevars[[x]])
yval[yval>=0] <- 0
newsumfuncneg <- sumfuncneg + yval
if (!(identical(yval, rep(0,length(yval)))))
{
polygon(c(xval,rev(xval)), c(newsumfuncneg, rev(sumfuncneg)), col=palette[[x]], border=NA)
}
sumfuncneg <- newsumfuncneg
}
if (total)
{
par(new=TRUE)
plot(xval, apply(cumulativevars, 1, sum), col="gray", type="l", ylim=ylim, xlab="", ylab="", lwd=lwd)
}
legend(legendposition, legend=names(cumulativevars), col=palette, inset=legendinset, y.intersp=y.intersp, bg=bg, lwd=legendlwd)
}
| /scratch/gouwar.j/cran-all/cranData/AquaEnv/R/aquaenv_private_auxilaryfunctions.R |
# concentrations of species of an univalent acid
HAuni <- function(Sum,K,H)
{
H/(H + K)*Sum
}
Auni <- function(Sum,K,H)
{
K/(H + K)*Sum
}
# concentrations of species of a bivalent acid
H2Abi <- function(Sum, K1, K2, H)
{
(H^2/(H^2+K1*H+K1*K2))*Sum
}
HAbi <- function(Sum, K1, K2, H)
{
(K1*H/(H^2+K1*H+K1*K2))*Sum
}
Abi <- function(Sum, K1, K2, H)
{
(K1*K2/(H^2+K1*H+K1*K2))*Sum
}
# concentrations of species of a trivalent acid
H3Atri <- function(Sum, K1, K2, K3, H)
{
(H^3/(H^3 + H^2*K1 + H*K1*K2 + K1*K2*K3))*Sum
}
H2Atri <- function(Sum, K1, K2, K3, H)
{
(K1*H^2/(H^3 + H^2*K1 + H*K1*K2 + K1*K2*K3))*Sum
}
HAtri <- function(Sum, K1, K2, K3, H)
{
(K1*K2*H/(H^3 + H^2*K1 + H*K1*K2 + K1*K2*K3))*Sum
}
Atri <- function(Sum, K1, K2, K3, H)
{
(K1*K2*K3/(H^3 + H^2*K1 + H*K1*K2 + K1*K2*K3))*Sum
}
# PRIVATE function:
# calculates [TA] from an object of class aquanenv and a given [H+]
calcTA <- function(aquaenv, # object of class aquaenv
H) # given [H+] in mol/kg-solution
{
with (aquaenv,
{
HCO3 <- HAbi (SumCO2, K_CO2, K_HCO3, H)
CO3 <- Abi (SumCO2, K_CO2, K_HCO3, H)
return(HCO3 + 2*CO3 + calcTAMinor(aquaenv, H)) # the calculated [TA]
})
}
# PRIVATE function:
# calculates minor contributions to [TA] from an object of class aquanenv and a given [H+]
calcTAMinor <- function(aquaenv, # object of class aquaenv
H) # given [H+] in mol/kg-solution
{
with (aquaenv,
{
BOH4 <- Auni (SumBOH3, K_BOH3, H)
OH <- K_W / H
HPO4 <- HAtri (SumH3PO4, K_H3PO4, K_H2PO4, K_HPO4, H)
PO4 <- Atri (SumH3PO4, K_H3PO4, K_H2PO4, K_HPO4, H)
SiOOH3 <- HAbi (SumSiOH4, K_SiOH4, K_SiOOH3, H)
HS <- HAbi (SumH2S, K_H2S, K_HS, H)
S2min <- Abi (SumH2S, K_H2S, K_HS, H)
NH3 <- Auni (SumNH4, K_NH4, H)
HSO4 <- HAbi (SumH2SO4, K_H2SO4, K_HSO4, H)
HF <- HAuni (SumHF, K_HF, H)
H3PO4 <- H3Atri(SumH3PO4, K_H3PO4, K_H2PO4, K_HPO4, H)
return(BOH4 + OH + HPO4 + 2*PO4 + SiOOH3 + HS + 2*S2min + NH3 - H - HSO4 - HF - H3PO4) # calculated minor contributions to [TA]
})
}
# PRIVATE function:
# calculates [H+] from an object of class aquanenv and a given [TA]: first according to Follows2006, if no solution is found after Technicals$maxiter iterations, uniroot is applied
calcH_TA <- function(aquaenv, # object of class aquaenv
TA) # given [TA] in mol/kg-solution
{
H <- c()
aquaenv[["TA"]] <- TA
for (z in 1:length(aquaenv))
{
aquaenvtemp <- as.list(as.data.frame(aquaenv)[z,])
with (aquaenvtemp,
{
Htemp <- Technicals$Hstart; i <- 1
while ((abs(calcTA(aquaenvtemp, Htemp) - aquaenvtemp$TA) > Technicals$Haccur) && (i <= Technicals$maxiter))
{
a <- TA - calcTAMinor(aquaenvtemp, Htemp)
b <- K_CO2*(a-SumCO2)
c <- K_CO2*K_HCO3*(a-2*SumCO2)
Htemp <- (-b + sqrt(b^2 - (4*a*c)))/(2*a); i <- i + 1
if (Htemp<0) {break}
}
if ((Htemp < 0) || (i > Technicals$maxiter))
{
Htemp <- uniroot(function(x){calcTA(aquaenvtemp, x) - aquaenvtemp$TA},
Technicals$unirootinterval, tol=Technicals$uniroottol, maxiter=Technicals$maxiter)$root
}
H <<- c(H, Htemp)
})
}
return(H) # calculated [H+] in mol/kg-solution
}
# PRIVATE function:
# calculates [H+] from an object of class aquanenv and a given [CO2]: by analytically solving the resulting quadratic equation
calcH_CO2 <- function(aquaenv, # object of class aquaenv
CO2) # given [CO2] in mol/kg-solution
{
H <- c()
aquaenv[["CO2"]] <- CO2
for (x in 1:length(aquaenv))
{
aquaenvtemp <- as.list(as.data.frame(aquaenv)[x,])
with (aquaenvtemp,
{
a <- CO2 - SumCO2
b <- K_CO2*CO2
c <- K_CO2*K_HCO3*CO2
H <<- c(H, ((-b-sqrt(b^2 - 4*a*c))/(2*a)))
})
}
return(H) # calculated [H+] in mol/kg-solution
}
# PRIVATE function:
# calculates [SumCO2] from an object of class aquanenv, a given pH, and a given [CO2]: by analytically solving the resulting equation
calcSumCO2_pH_CO2 <- function(aquaenv, # object of class aquaenv
pH, # given pH on the free proton scale
CO2) # given [CO2] in mol/kg-solution
{
SumCO2 <- c()
aquaenv[["pH"]] <- pH
aquaenv[["CO2"]] <- CO2
for (x in 1:length(aquaenv))
{
aquaenvtemp <- as.list(as.data.frame(aquaenv)[x,])
with (aquaenvtemp,
{
H <- 10^{-pH}
denom <- H^2/(H^2 + H*K_CO2 + K_CO2*K_HCO3)
SumCO2 <<- c(SumCO2, (CO2/denom))
})
}
return(SumCO2) # calculated [SumCO2] in mol/kg-solution
}
# PRIVATE function:
# calculates [SumCO2] from an object of class aquanenv, a given pH, and a given [TA]: by analytically solving the resulting quadratic equation
calcSumCO2_pH_TA <- function(aquaenv, # object of class aquaenv
pH, # given pH on the free proton scale
TA) # given [TA] in mol/kg-solution
{
SumCO2 <- c()
aquaenv[["pH"]] <- pH
aquaenv[["TA"]] <- TA
for (x in 1:length(aquaenv))
{
aquaenvtemp <- as.list(as.data.frame(aquaenv)[x,])
with (aquaenvtemp,
{
H <- 10^{-pH}
c2 <- (H*K_CO2) /(H^2 + H*K_CO2 + K_CO2*K_HCO3)
c3 <- (K_CO2*K_HCO3)/(H^2 + H*K_CO2 + K_CO2*K_HCO3)
numer <- TA - calcTAMinor(aquaenvtemp, H)
denom <- c2 + 2*c3
SumCO2 <<- c(SumCO2, (numer/denom))
})
}
return(SumCO2) # calculated [SumCO2] in mol/kg-solution
}
# PRIVATE function:
# calculates [SumCO2] from an object of class aquanenv, a given [TA], and a given [CO2]: by analytically solving the resulting quadratic equation
calcSumCO2_TA_CO2 <- function(aquaenv, # object of class aquaenv
TA, # given [TA] in mol/kg-solution
CO2) # given [CO2] in mol/kg-solution
{
SumCO2 <- c()
aquaenv[["TA"]] <- TA
aquaenv[["CO2"]] <- CO2
for (i in 1:length(aquaenv))
{
aquaenvtemp <- as.list(as.data.frame(aquaenv)[i,])
with (aquaenvtemp,
{
f <- function(x)
{
c1 <- (x^2) /(x^2 + x*K_CO2 + K_CO2*K_HCO3)
c2 <- (x*K_CO2) /(x^2 + x*K_CO2 + K_CO2*K_HCO3)
c3 <- (K_CO2*K_HCO3)/(x^2 + x*K_CO2 + K_CO2*K_HCO3)
return(TA - ((c2+2*c3)*(CO2/c1) + calcTAMinor(aquaenvtemp, x)))
}
H <- uniroot(f, Technicals$unirootinterval, tol=Technicals$uniroottol, maxiter=Technicals$maxiter)$root
attr(aquaenvtemp, "class") <- "aquaenv"
SumCO2 <<- c(SumCO2, calcSumCO2_pH_TA(aquaenvtemp, -log10(H), TA))
})
}
return(SumCO2) # calculated [SumCO2] in mol/kg-solution
}
| /scratch/gouwar.j/cran-all/cranData/AquaEnv/R/aquaenv_private_pHTAfunctions.R |
# function:
# creates an object of class aquaenv which contains a titration simulation
titration <- function(aquaenv, # an object of type aquaenv: minimal definition, contains all information about the system: T, S, d, total concentrations of nutrients etc (Note that it is possible to give values for SumBOH4, SumHSO4, and SumHF in the sample other than the ones calculated from salinity)
mass_sample, # the mass of the sample solution in kg
mass_titrant, # the total mass of the added titrant solution in kg
conc_titrant, # the concentration of the titrant solution in mol/kg-soln
S_titrant=NULL, # the salinity of the titrant solution, if not supplied it is assumed that the titrant solution has the same salinity as the sample solution
steps, # the amount of steps the mass of titrant is added in
type="HCl", # the type of titrant: either "HCl" or "NaOH"
seawater_titrant=FALSE, # is the titrant based on natural seawater? (does it contain SumBOH4, SumHSO4, and SumHF in the same proportions as seawater, i.e., correlated to S?); Note that you can only assume a seawater based titrant (i.e. SumBOH4, SumHSO4, and SumHF ~ S) or a water based titrant (i.e. SumBOH4, SumHSO4, and SumHF = 0). It is not possible to give values for SumBOH4, SumHSO4, and SumHF of the titrant.
k_w=NULL, # a fixed K_W can be specified
k_co2=NULL, # a fixed K_CO2 can be specified: used for TA fitting: give a K_CO2 and NOT calculate it from T and S: i.e. K_CO2 can be fitted in the routine as well
k_hco3=NULL, # a fixed K_HCO3 can be specified
k_boh3=NULL, # a fixed K_BOH3 can be specified
k_hso4=NULL, # a fixed K_HSO4 can be specified
k_hf=NULL, # a fixed K_HF can be specified
k1k2="lueker", # either "lueker" (default, Lueker2000) or "roy" (Roy1993a) or for K\_CO2 and K\_HCO3
khf="dickson") # either "dickson" (default, Dickson1979a) or "perez" (Perez1987a, calculated with seacarb) for K\_HF}
{
concstep <- function(conc, oldmass, newmass)
{
return((conc*oldmass)/(newmass))
}
if (is.null(S_titrant))
{
S_titrant <- aquaenv$S
}
directionTAchange <- switch(type, HCl = -1, NaOH = +1)
TAmolchangeperstep <- (conc_titrant*mass_titrant)/steps
masschangeperstep <- mass_titrant/steps
aquaenv[["mass"]] <- mass_sample
for (i in 1:steps)
{
with(aquaenv,
{
i <- length(mass)
newmass <- mass[[i]] + masschangeperstep
SumCO2 <- concstep(SumCO2[[i]], mass[[i]], newmass)
SumNH4 <- concstep(SumNH4[[i]], mass[[i]], newmass)
SumH2S <- concstep(SumH2S[[i]], mass[[i]], newmass)
SumH3PO4 <- concstep(SumH3PO4[[i]], mass[[i]], newmass)
SumSiOH4 <- concstep(SumSiOH4[[i]], mass[[i]], newmass)
SumHNO3 <- concstep(SumHNO3[[i]], mass[[i]], newmass)
SumHNO2 <- concstep(SumHNO2[[i]], mass[[i]], newmass)
if (seawater_titrant)
{
SumBOH3 <- (SumBOH3[[i]]*mass[[i]] + seaconc("B", S_titrant)*masschangeperstep)/newmass
SumH2SO4 <- (SumH2SO4[[i]]*mass[[i]] + seaconc("SO4", S_titrant)*masschangeperstep)/newmass
SumHF <- (SumHF[[i]]*mass[[i]] + seaconc("F", S_titrant)*masschangeperstep)/newmass
}
else
{
SumBOH3 <- concstep(SumBOH3[[i]], mass[[i]], newmass)
SumH2SO4 <- concstep(SumH2SO4[[i]], mass[[i]], newmass)
SumHF <- concstep(SumHF[[i]], mass[[i]], newmass)
}
S <- (S[[i]]*mass[[i]] + S_titrant*masschangeperstep)/newmass
TA <- (TA[[i]]*mass[[i]] + (directionTAchange * TAmolchangeperstep))/newmass
aquaenvtemp <- aquaenv(S=S, t=t[[i]], p=p[[i]], SumCO2=SumCO2, SumNH4=SumNH4, SumH2S=SumH2S, SumH3PO4=SumH3PO4, SumSiOH4=SumSiOH4, SumHNO3=SumHNO3, SumHNO2=SumHNO2,
SumBOH3=SumBOH3, SumH2SO4=SumH2SO4, SumHF=SumHF, TA=TA,
speciation=(!is.null(aquaenv$HCO3)), skeleton=(is.null(aquaenv$Na)), revelle=(!is.null(aquaenv$revelle)), dsa=(!is.null(aquaenv$dTAdH)),
k_w=k_w, k_co2=k_co2, k_hco3=k_hco3, k_boh3=k_boh3, k_hso4=k_hso4, k_hf=k_hf, k1k2=k1k2, khf=khf)
aquaenvtemp[["mass"]] <- newmass
aquaenv <<- merge(aquaenv, aquaenvtemp)
})
}
aquaenv[["delta_conc_titrant"]] <- ((0:steps)*TAmolchangeperstep)/aquaenv[["mass"]] ; attr(aquaenv[["delta_conc_titrant"]], "unit") <- "mol/kg-soln"
aquaenv[["delta_mass_titrant"]] <- (0:steps)*masschangeperstep ; attr(aquaenv[["delta_mass_titrant"]], "unit") <- "kg"
aquaenv[["delta_moles_titrant"]] <- (0:steps)*TAmolchangeperstep ; attr(aquaenv[["delta_moles_titrant"]], "unit") <- "mol"
return(aquaenv) # object of class aquaenv which contains a titration simulation
}
# PUBLIC function:
# calculates [TA] and [SumCO2] from a titration curve using an optimization procedure (nls.lm from R package minpack.lm)
TAfit <- function(ae, # an object of type aquaenv: minimal definition, contains all information about the system: T, S, d, total concentrations of nutrients etc
titcurve, # a table containing the titration curve: basically a series of tuples of added titrant solution mass and pH values (pH on free proton scale) or E values in V
conc_titrant, # concentration of the titrant solution in mol/kg-soln
mass_sample, # the mass of the sample solution in kg
S_titrant=NULL, # the salinity of the titrant solution, if not supplied it is assumed that the titrant solution has the same salinity as the sample solution
TASumCO2guess=0.0025, # a first guess for [TA] and [SumCO2] to be used as initial values for the optimization procedure
E0guess=0.4, # first guess for E0 in V
type="HCl", # the type of titrant: either "HCl" or "NaOH"
Evals=FALSE, # are the supplied datapoints pH or E (V) values?
electrode_polarity="pos", # either "pos" or "neg": how is the polarity of the Electrode: E = E0 -(RT/F)ln(H^+) ("pos") or -E = E0 -(RT/F)ln(H^+) ("neg")
K_CO2fit=FALSE, # should K_CO2 be fitted as well?
equalspaced=TRUE, # are the mass values of titcurve equally spaced?
seawater_titrant=FALSE, # is the titrant based on natural seawater? (does it contain SumBOH4, SumHSO4, and SumHF in the same proportions as seawater, i.e., correlated to S?); Note that you can only assume a seawater based titrant (i.e. SumBOH4, SumHSO4, and SumHF ~ S) or a water based titrant (i.e. SumBOH4, SumHSO4, and SumHF = 0). It is not possible to give values for SumBOH4, SumHSO4, and SumHF of the titrant.
pHscale="free", # either "free", "total", "sws" or "nbs": if the titration curve contains pH data: on which scale is it measured?
debug=FALSE, # debug mode: the last simulated titration tit, the converted pH profile calc, and the nls.lm output out are made global variables for investigation and plotting
k_w=NULL, # a fixed K_W can be specified
k_co2=NULL, # a fixed K_CO2 can be specified
k_hco3=NULL, # a fixed K_HCO3 can be specified
k_boh3=NULL, # a fixed K_BOH3 can be specified
k_hso4=NULL, # a fixed K_HSO4 can be specified
k_hf=NULL, # a fixed K_HF can be specified
nlscontrol=nls.lm.control(),# nls.lm.control() can be specified
verbose=FALSE, # verbose mode: show the traject of the fitting in a plot
k1k2="roy", # either "roy" (default, Roy1993a) or "lueker" (Lueker2000, calculated with seacarb) for K\_CO2 and K\_HCO3
khf="dickson", # either "dickson" (default, Dickson1979a) or "perez" (Perez1987a, calculated with seacarb) for K\_HF}
datxbegin=0, # at what x value (amount of titrant added) does the supplied curve start? (i.e. is the complete curve supplied or just a part?)
SumCO2Zero=FALSE) # should SumCO2==0 ?
{
residuals <- function(state)
{
if (K_CO2fit) {if (Evals){k_co2 <- state[[4]]/1e4} else {k_co2 <- state[[3]]/1e4}} # devide by 1e4 since the parameter was scaled to obtain parameters in the same range
if (SumCO2Zero) {state[[1]] <- 0} # should SumCO2==0?
tit <- titration(aquaenv(S=ae$S, t=ae$t, p=ae$p,
SumCO2=state[[1]], SumNH4=ae$SumNH4, SumH2S=ae$SumH2S, SumH3PO4=ae$SumH3PO4, SumSiOH4=ae$SumSiOH4, SumHNO3=ae$SumHNO3, SumHNO2=ae$SumHNO2,
SumBOH3=ae$SumBOH3, SumH2SO4=ae$SumH2SO4, SumHF=ae$SumHF,
TA=state[[2]], speciation=FALSE, skeleton=TRUE,
k_w=k_w, k_co2=k_co2, k_hco3=k_hco3, k_boh3=k_boh3, k_hso4=k_hso4, k_hf=k_hf, k1k2=k1k2, khf=khf),
mass_sample=mass_sample, mass_titrant=titcurve[,1][[length(titcurve[,1])]], conc_titrant=conc_titrant,
S_titrant=S_titrant, steps=steps, type=type, seawater_titrant=seawater_titrant,
k_w=k_w, k_co2=k_co2, k_hco3=k_hco3, k_boh3=k_boh3, k_hso4=k_hso4, k_hf=k_hf, k1k2=k1k2, khf=khf)
calc <- tit$pH
if (Evals)
{
# The Nernst equation relates E to TOTAL [H+] (DOE1994, p.7, ch.4, sop.3, Dickson2007)
calc <- convert(calc, "pHscale", "free2tot", S=tit$S, t=tit$t, p=tit$p, SumH2SO4=tit$SumH2SO4, SumHF=tit$SumHF, khf=khf)
# electrode polarity: E = E0 -(RT/F)ln([H+]) ("pos") or -E = E0 -(RT/F)ln([H+]) ("neg")
if (electrode_polarity=="pos")
{
pol <- 1
}
else
{
pol <- -1
}
#Nernst Equation: E = E0 -(RT/F)ln([H+]); 83.14510 (bar*cm3)/(mol*K) = 8.314510 J/(mol*K): division by 10
calc <- pol*(state[[3]]*1e2 - (((PhysChemConst$R/10)*ae$T)/PhysChemConst$F)*log(10^(-calc)))
ylab <- "E/V"
}
else if (!(pHscale=="free"))
{
calc <- convert(calc, "pHscale", paste("free2", pHscale, sep=""), S=tit$S, t=tit$t, p=tit$p, SumH2SO4=tit$SumH2SO4, SumHF=tit$SumHF, khf=khf) #conversion done here not on data before call, since S changes along the titration!
ylab <- paste("pH (", pHscale, " scale)", sep="")
}
else
{
ylab <- paste("pH (", pHscale, " scale)", sep="")
}
if (!equalspaced)
{
# to cope with not equally spaced delta values for the masses (i.e. per step of the titration, NOT the same amount of titrant has been added),
# we fit a function through our calculated pH curve (NOT the data)
calcfun <- approxfun(tit$delta_mass_titrant[(stepsbeforecurve+1):(steps+1)], calc[(stepsbeforecurve+1):(steps+1)], rule=2)
residuals <- titcurve[,2]-calcfun(titcurve[,1])
}
else
{
residuals <- (titcurve[,2]-calc[(stepsbeforecurve+1):(steps+1)])
}
if (debug) # debug mode: make some variables global
{
tit <<- tit
calc <<- calc
}
if (verbose) # show the traject of the fitting procedure in a plot
{
ylim=range(titcurve[,2], calc)
xlim=range(tit$delta_mass_titrant, titcurve[,1])
plot(titcurve[,1], titcurve[,2], xlim=xlim, ylim=ylim, type="l", xlab="delta mass titrant", ylab=ylab)
par(new=TRUE)
plot(tit$delta_mass_titrant, calc, xlim=xlim, ylim=ylim, type="l", col="red", xlab="", ylab="")
}
return(residuals)
}
# deal with just partially supplied curves
stepsbeforecurve <- 0
steps <- (length(titcurve[,1])-1)
if (!(datxbegin==0))
{
stepsbeforecurve <- (titcurve[,1][[1]] / ((titcurve[,1][[length(titcurve[,1])]] - titcurve[,1][[1]])/(length(titcurve[,1])-1)))
steps <- stepsbeforecurve + (length(titcurve[,1])-1)
}
if (Evals && K_CO2fit)
{
out <- nls.lm(fn=residuals, par=c(TASumCO2guess, TASumCO2guess, E0guess/1e2, ae$K_CO2*1e4), control=nlscontrol) #multiply K_CO2 with 1e4 to bring the variables to fit into the same order of magnitude
result <- list(out$par[[2]], out$par[[1]], out$par[[3]]*1e2, out$par[[4]]/1e4, out$deviance) #same thing for E0 but the other way round and with 1e2
attr(result[[3]], "unit") <- "V"
attr(result[[4]], "unit") <- "mol/kg-soln"
attr(result[[4]], "pH scale") <- "free"
names(result) <- c("TA", "SumCO2", "E0", "K_CO2", "sumofsquares")
}
else if (Evals)
{
out <- nls.lm(fn=residuals, par=c(TASumCO2guess, TASumCO2guess, E0guess/1e2), control=nlscontrol)
result <- list(out$par[[2]], out$par[[1]], out$par[[3]]*1e2, out$deviance)
attr(result[[3]], "unit") <- "V"
names(result) <- c("TA", "SumCO2", "E0", "sumofsquares")
}
else if (K_CO2fit)
{
out <- nls.lm(fn=residuals, par=c(TASumCO2guess, TASumCO2guess, ae$K_CO2*1e4), control=nlscontrol) #multiply K_CO2 with 1e4 to bring the variables to fit into the same order of magnitude
result <- list(out$par[[2]], out$par[[1]], out$par[[3]]/1e4, out$deviance)
attr(result[[3]], "unit") <- "mol/kg-soln"
attr(result[[3]], "pH scale") <- "free"
names(result) <- c("TA", "SumCO2", "K_CO2", "sumofsquares")
}
else
{
out <- nls.lm(fn=residuals, par=c(TASumCO2guess, TASumCO2guess), control=nlscontrol)
result <- list(out$par[[2]], out$par[[1]], out$deviance)
names(result) <- c("TA","SumCO2","sumofsquares")
}
if (SumCO2Zero) {result[[2]] <- 0} # should SumCO2==0?
attr(result[[1]], "unit") <- "mol/kg-soln"
attr(result[[2]], "unit") <- "mol/kg-soln"
if (debug) # debug mode: make some variables global
{
out <<- out
}
return(result) # a list of up to five values ([TA] in mol/kg-solution, [SumCO2] in mol/kg-solution, E0 in V, K_CO2 in mol/kg-solution and on free scale, sum of the squared residuals)
}
| /scratch/gouwar.j/cran-all/cranData/AquaEnv/R/aquaenv_public_applications.R |
# a list of physical-chemical constants used in AquaEnv
PhysChemConst <- list(
R = 83.14472, # (bar*cm3)/(mol*K) the gas constant (corrected after Lewis1998, in Millero1995: R = 83.131; digits extended after DOE1994, Dickson2007)
F = 96485.3399, # C/mol the Faraday constant (charge per mol of electrons) (N_A*e-) (Dickson2007)
uMolToMol = 1e-6, # conversion factor from umol to mol
absZero = -273.15, # absolute zero in degrees centigrade
e = 79, # relative dielectric constanf of seawater (Zeebe2001)
K_HNO2 = 1.584893e-3, # dissociation constant of HNO2: mol/l, NBS pH scale, hybrid constant (Riordan2005)
K_HNO3 = 23.44, # dissociation constant of HNO3: assumed on mol/kg-soln and free pH scale, stoichiometric constant (Soetaert pers. comm.)
K_H2SO4 = 100, # dissociation constant of H2SO4: assumed on mol/kg-soln and free pH scale, stoichiometric constant (Atkins1996)
K_HS = 1.1e-12 # dissociation constant of HHS: assumed on mol/kg-soln and free pH scale, stoichiometric constant (Atkins1996)
)
# a list of technical constants used in AquaEnv
Technicals <- list(
Haccur = 1e-12, # accuracy for iterative (Follows2006) pH calculations (max. deviation in [H+])
Hstart = 1e-8, # start [H+] for an iterative pH calculation
maxiter = 100, # maximum number of iterations for iterative (Follows2006) pH calculation method as well as for the application of the standard R function uniroot
unirootinterval = c(1e-18, 1), # the interval (in terms of [H+]) for pH calculation using the standard R function uniroot
uniroottol = 1e-20, # the interval (in terms of [H+]) for pH calculation using the standard R function uniroot
epsilon_fraction = 0.1, # fraction of disturbance for the numerical calculation of derivatives of TA with respect to changes in the dissociation constants
revelle_fraction = 1e-5 # fraction of disturbance for the numerical calculation of the revelle factor
)
# coefficients for the pressure correction of dissociation constants and solubility products (Millero1995 WITH CORRECTIONS BY Lewis1998 (CO2Sys)!!!!!!)
DeltaPcoeffs <- data.frame(
K_HSO4 = c(-18.03, 0.0466, 0.3160e-3,- 4.53, 0.0900,0),
K_HF = c( -9.78,-0.0090,-0.9420e-3,- 3.91, 0.0540,0),
K_CO2 = c(-25.50, 0.1271, 0.0000e-3,- 3.08, 0.0877,0),
K_HCO3 = c(-15.82,-0.0219, 0.0000e-3, 1.13,-0.1475,0),
K_W = c(-25.60, 0.2324,-3.6246e-3,- 5.13, 0.0794,0),
K_BOH3 = c(-29.48, 0.1622, 2.6080e-3,- 2.84, 0.0000,0),
K_NH4 = c(-26.43, 0.0889,-0.9050e-3,- 5.03, 0.0814,0),
K_H2S = c(-14.80, 0.0020,-0.4000e-3, 2.89, 0.0540,0),
K_H3PO4 = c(-14.51, 0.1211,-0.3210e-3,- 2.67, 0.0427,0),
K_H2PO4 = c(-23.12, 0.1758,-2.6470e-3,- 5.15, 0.0900,0),
K_HPO4 = c(-26.57, 0.2020,-3.0420e-3,- 4.08, 0.0714,0),
K_SiOH4 = c(-29.48, 0.1622, 2.6080e-3,- 2.84, 0.0000,0), # same as K_BOH3
K_SiOOH3 = c(-29.48, 0.1622, 2.6080e-3,- 2.84, 0.0000,0), # same as K_BOH3
Ksp_calcite = c(-48.76, 0.5304, 0.0000e-3,-11.76, 0.3692,0),
Ksp_aragonite = c(-45.96, 0.5304, 0.0000e-3,-11.76, 0.3692,0)
)
# mean molecular mass of key chemical species in seawater in g/mol (DOE1994, Dickson2007)
MeanMolecularMass <- data.frame(
Cl = 35.453,
SO4 = (32.065+4*(15.999)),
Br = 79.904,
F = 18.998,
Na = 22.990,
Mg = 24.3050,
Ca = 40.078,
K = 39.098,
Sr = 87.62,
B = 10.811
)
# concentrations of key chemical species in seawater, relative with respect to chlorinity (DOE1994)
ConcRelCl <- data.frame(
Cl = 0.99889,
SO4 = 0.1400,
Br = 0.003473,
F = 0.000067,
Na = 0.55661,
Mg = 0.06626,
Ca = 0.02127,
K = 0.0206,
Sr = 0.00041,
B = 0.000232
)
| /scratch/gouwar.j/cran-all/cranData/AquaEnv/R/aquaenv_public_constants.R |
###########################################################################
# Preparing variables for the constructor of the class aquaenv: conversions
###########################################################################
convert <- function(x, ...)
{
if ((!is.null(attr(x, "class"))) && (attr(x, "class") == "aquaenv"))
{
return(convert.aquaenv(x, ...))
}
else
{
return(convert.standard(x, ...))
}
}
#########################################################################
# The class aquaenv: constructor, plotting and conversion to a data frame
#########################################################################
aquaenv <- function(S, t, p=pmax((P-Pa), gauge_p(d, lat, Pa)), P=Pa, Pa=1.01325, d=0, lat=0,
SumCO2=0, SumNH4=0, SumH2S=0, SumH3PO4=0, SumSiOH4=0, SumHNO3=0, SumHNO2=0,
SumBOH3=NULL, SumH2SO4=NULL, SumHF=NULL,
TA=NULL, pH=NULL, fCO2=NULL, CO2=NULL,
speciation=TRUE,
dsa=FALSE,
ae=NULL,
from.data.frame=FALSE,
SumH2SO4_Koffset=0,
SumHF_Koffset=0,
revelle=FALSE,
skeleton=FALSE,
k_w=NULL,
k_co2=NULL,
k_hco3=NULL,
k_boh3=NULL,
k_hso4=NULL,
k_hf=NULL,
k1k2="lueker",
khf="dickson",
khso4="dickson",
fCO2atm=0.000400,
fO2atm=0.20946)
{
if (from.data.frame)
{
return (from.data.frame(ae))
}
else if (!is.null(ae))
{
return (cloneaquaenv(ae, TA=TA, pH=pH, k_co2=k_co2, k1k2=k1k2, khf=khf, khso4=khso4))
}
else
{
aquaenv <- list()
attr(aquaenv, "class") <- "aquaenv"
aquaenv[["S"]] <- S ; attr(aquaenv[["S"]], "unit") <- "p2su"
aquaenv[["t"]] <- t ; attr(aquaenv[["t"]], "unit") <- "deg C"
aquaenv[["p"]] <- p ; attr(aquaenv[["p"]], "unit") <- "bar"
aquaenv[["T"]] <- T(t) ; attr(aquaenv[["T"]], "unit") <- "deg K"
aquaenv[["Cl"]] <- Cl(S) ; attr(aquaenv[["Cl"]], "unit") <- "permil"
aquaenv[["I"]] <- I(S) ; attr(aquaenv[["I"]], "unit") <- "mol/kg-H2O"
aquaenv[["P"]] <- p+Pa ; attr(aquaenv[["P"]], "unit") <- "bar"
aquaenv[["Pa"]] <- Pa ; attr(aquaenv[["Pa"]], "unit") <- "bar"
aquaenv[["d"]] <- round(watdepth(P=p+Pa, lat=lat),2) ; attr(aquaenv[["d"]], "unit") <- "m"
aquaenv[["density"]] <- seadensity(S=S, t=t) ; attr(aquaenv[["density"]], "unit") <- "kg/m3"
aquaenv[["SumCO2"]] <- SumCO2
aquaenv[["SumNH4"]] <- SumNH4 ; attr(aquaenv[["SumNH4"]], "unit") <- "mol/kg-soln"
aquaenv[["SumH2S"]] <- SumH2S ; attr(aquaenv[["SumH2S"]], "unit") <- "mol/kg-soln"
aquaenv[["SumHNO3"]] <- SumHNO3 ; attr(aquaenv[["SumHNO3"]], "unit") <- "mol/kg-soln"
aquaenv[["SumHNO2"]] <- SumHNO2 ; attr(aquaenv[["SumHNO2"]], "unit") <- "mol/kg-soln"
aquaenv[["SumH3PO4"]] <- SumH3PO4 ; attr(aquaenv[["SumH3PO4"]], "unit") <- "mol/kg-soln"
aquaenv[["SumSiOH4"]] <- SumSiOH4 ; attr(aquaenv[["SumSiOH4"]], "unit") <- "mol/kg-soln"
if (is.null(SumBOH3))
{
SumBOH3 = seaconc("B", S)
}
else if (length(S)>1)
{
SumBOH3 = rep(SumBOH3, length(S))
}
aquaenv[["SumBOH3"]] <- SumBOH3 ; attr(aquaenv[["SumBOH3"]], "unit") <- "mol/kg-soln"
if (is.null(SumH2SO4))
{
SumH2SO4 = seaconc("SO4", S)
}
else if (length(S)>1)
{
SumH2SO4 = rep(SumH2SO4, length(S))
}
aquaenv[["SumH2SO4"]] <- SumH2SO4 ; attr(aquaenv[["SumH2SO4"]], "unit") <- "mol/kg-soln"
if (is.null(SumHF))
{
SumHF = seaconc("F", S)
}
else if (length(S)>1)
{
SumHF = rep(SumHF, length(S))
}
aquaenv[["SumHF"]] <- SumHF ; attr(aquaenv[["SumHF"]], "unit") <- "mol/kg-soln"
if(!skeleton)
{
aquaenv[["Br"]] <- seaconc("Br", S) ; attr(aquaenv[["Br"]], "unit") <- "mol/kg-soln"
aquaenv[["ClConc"]] <- seaconc("Cl", S) ; attr(aquaenv[["ClConc"]], "unit") <- "mol/kg-soln"
aquaenv[["Na"]] <- seaconc("Na", S) ; attr(aquaenv[["Na"]], "unit") <- "mol/kg-soln"
aquaenv[["Mg"]] <- seaconc("Mg", S) ; attr(aquaenv[["Mg"]], "unit") <- "mol/kg-soln"
aquaenv[["Ca"]] <- seaconc("Ca", S) ; attr(aquaenv[["Ca"]], "unit") <- "mol/kg-soln"
aquaenv[["K"]] <- seaconc("K", S) ; attr(aquaenv[["K"]], "unit") <- "mol/kg-soln"
aquaenv[["Sr"]] <- seaconc("Sr", S) ; attr(aquaenv[["Sr"]], "unit") <- "mol/kg-soln"
aquaenv[["molal2molin"]] <- molal2molin(S) ; attr(aquaenv[["molal2molin"]], "unit") <- "(mol/kg-soln)/(mol/kg-H2O)"
scaleconvs <- scaleconvert(S, t, p, SumH2SO4, SumHF, khf=khf, khso4=khso4)
aquaenv[["free2tot"]] <- scaleconvs$free2tot ; attr(aquaenv[["free2tot"]], "pH scale") <- "free -> tot"
aquaenv[["free2sws"]] <- scaleconvs$free2sws ; attr(aquaenv[["free2sws"]], "pH scale") <- "free -> sws"
aquaenv[["tot2free"]] <- scaleconvs$tot2free ; attr(aquaenv[["tot2free"]], "pH scale") <- "total -> free"
aquaenv[["tot2sws"]] <- scaleconvs$tot2sws ; attr(aquaenv[["tot2sws"]], "pH scale") <- "total -> sws"
aquaenv[["sws2free"]] <- scaleconvs$sws2free ; attr(aquaenv[["sws2free"]], "pH scale") <- "sws -> free"
aquaenv[["sws2tot"]] <- scaleconvs$sws2tot ; attr(aquaenv[["sws2tot"]], "pH scale") <- "sws -> total"
aquaenv[["K0_CO2"]] <- K0_CO2 (S, t)
aquaenv[["K0_O2"]] <- K0_O2 (S, t)
aquaenv[["fCO2atm"]] <- fCO2atm ; attr(aquaenv[["fCO2atm"]], "unit") <- "atm"
aquaenv[["fO2atm"]] <- fO2atm ; attr(aquaenv[["fO2atm"]], "unit") <- "atm"
aquaenv[["CO2_sat"]] <- aquaenv[["fCO2atm"]] * aquaenv[["K0_CO2"]] ; attr(aquaenv[["CO2_sat"]], "unit") <- "mol/kg-soln"
aquaenv[["O2_sat"]] <- aquaenv[["fO2atm"]] * aquaenv[["K0_O2"]] ; attr(aquaenv[["O2_sat"]], "unit") <- "mol/kg-soln"
}
len <- max(length(t), length(S), length(p))
if (is.null(k_w))
{
aquaenv[["K_W"]] <- K_W(S, t, p, SumH2SO4 + SumH2SO4_Koffset, SumHF + SumHF_Koffset, khf=khf, khso4=khso4)
}
else
{
aquaenv[["K_W"]] <- eval(att(rep(k_w,len)))
}
if (is.null(k_hso4))
{
aquaenv[["K_HSO4"]] <- K_HSO4(S, t, p, khso4)
}
else
{
aquaenv[["K_HSO4"]] <- eval(att(rep(k_hso4,len)))
}
if (is.null(k_hf))
{
aquaenv[["K_HF"]] <- K_HF(S, t, p, SumH2SO4=(SumH2SO4 + SumH2SO4_Koffset), SumHF=(SumHF + SumHF_Koffset), khf=khf, khso4=khso4)
}
else
{
aquaenv[["K_HF"]] <- eval(att(rep(k_hf,len)))
}
if (is.null(k_co2))
{
aquaenv[["K_CO2"]] <- K_CO2 (S, t, p, SumH2SO4 + SumH2SO4_Koffset, SumHF + SumHF_Koffset, k1k2=k1k2, khf=khf, khso4=khso4)
}
else
{
aquaenv[["K_CO2"]] <- eval(att(rep(k_co2,len)))
}
if (is.null(k_hco3))
{
aquaenv[["K_HCO3"]] <- K_HCO3(S, t, p, SumH2SO4 + SumH2SO4_Koffset, SumHF + SumHF_Koffset, k1k2=k1k2, khf=khf, khso4=khso4)
}
else
{
aquaenv[["K_HCO3"]] <- eval(att(rep(k_hco3,len)))
}
if (is.null(k_boh3))
{
aquaenv[["K_BOH3"]] <- K_BOH3(S, t, p, SumH2SO4 + SumH2SO4_Koffset, SumHF + SumHF_Koffset, khf=khf, khso4=khso4)
}
else
{
aquaenv[["K_BOH3"]] <- eval(att(rep(k_boh3,len)))
}
aquaenv[["K_NH4"]] <- K_NH4 (S, t, p, SumH2SO4 + SumH2SO4_Koffset, SumHF + SumHF_Koffset, khf=khf, khso4=khso4)
aquaenv[["K_H2S"]] <- K_H2S (S, t, p, SumH2SO4 + SumH2SO4_Koffset, SumHF + SumHF_Koffset, khf=khf, khso4=khso4)
aquaenv[["K_H3PO4"]] <- K_H3PO4 (S, t, p, SumH2SO4 + SumH2SO4_Koffset, SumHF + SumHF_Koffset, khf=khf, khso4=khso4)
aquaenv[["K_H2PO4"]] <- K_H2PO4 (S, t, p, SumH2SO4 + SumH2SO4_Koffset, SumHF + SumHF_Koffset, khf=khf, khso4=khso4)
aquaenv[["K_HPO4"]] <- K_HPO4 (S, t, p, SumH2SO4 + SumH2SO4_Koffset, SumHF + SumHF_Koffset, khf=khf, khso4=khso4)
aquaenv[["K_SiOH4"]] <- K_SiOH4 (S, t, p, SumH2SO4 + SumH2SO4_Koffset, SumHF + SumHF_Koffset, khf=khf, khso4=khso4)
aquaenv[["K_SiOOH3"]] <- K_SiOOH3(S, t, p, SumH2SO4 + SumH2SO4_Koffset, SumHF + SumHF_Koffset, khf=khf, khso4=khso4)
aquaenv[["K_HNO2"]] <- PhysChemConst$K_HNO2 ; attr(aquaenv[["K_HNO2"]], "unit") <- "mol/kg-soln; mol/kg-H2O; mol/l"
aquaenv[["K_HNO3"]] <- PhysChemConst$K_HNO3 ; attr(aquaenv[["K_HNO3"]], "unit") <- "mol/kg-soln; mol/kg-H2O; mol/l"
aquaenv[["K_H2SO4"]] <- PhysChemConst$K_H2SO4 ; attr(aquaenv[["K_H2SO4"]], "unit") <- "mol/kg-soln; mol/kg-H2O; mol/l"
aquaenv[["K_HS"]] <- PhysChemConst$K_HS ; attr(aquaenv[["K_HS"]], "unit") <- "mol/kg-soln; mol/kg-H2O; mol/l"
if (!skeleton)
{
aquaenv[["Ksp_calcite"]] <- Ksp_calcite(S, t, p)
aquaenv[["Ksp_aragonite"]] <- Ksp_aragonite(S, t, p)
}
if (!(is.null(TA) && is.null(pH) && is.null(fCO2) && is.null(CO2)))
{
if (is.null(SumCO2))
{
if (!is.null(pH))
{
if (!is.null(fCO2))
{
CO2 <- aquaenv[["K0_CO2"]] * fCO2
SumCO2 <- calcSumCO2_pH_CO2(aquaenv, pH, CO2)
TA <- calcTA(c(aquaenv, list(SumCO2, "SumCO2")), 10^(-pH))
}
else if (!is.null(CO2))
{
SumCO2 <- calcSumCO2_pH_CO2(aquaenv, pH, CO2)
fCO2 <- CO2 / aquaenv[["K0_CO2"]]
TA <- calcTA(c(aquaenv, list(SumCO2, "SumCO2")), 10^(-pH))
}
else if (!is.null(TA))
{
SumCO2 <- calcSumCO2_pH_TA(aquaenv, pH, TA)
CO2 <- H2Abi(SumCO2, aquaenv[["K_CO2"]], aquaenv[["K_HCO3"]], 10^(-pH))
fCO2 <- CO2 / aquaenv[["K0_CO2"]]
}
else
{
print(paste("Error! Underdetermined system!"))
print("To calculate [SumCO2], please enter one pair of: (pH/CO2), (pH,fCO2), (TA,pH), (TA/CO2), (TA/fCO2)")
return(NULL)
}
}
else if (!is.null(TA))
{
if (!is.null(fCO2))
{
CO2 <- aquaenv[["K0_CO2"]] * fCO2
SumCO2 <- calcSumCO2_TA_CO2(aquaenv, TA, CO2)
pH <- -log10(calcH_TA(c(aquaenv, list(SumCO2, "SumCO2")), TA))
}
else if (!is.null(CO2))
{
SumCO2 <- calcSumCO2_TA_CO2(aquaenv, TA, CO2)
fCO2 <- CO2 / aquaenv[["K0_CO2"]]
pH <- -log10(calcH_TA(c(aquaenv, list(SumCO2, "SumCO2")), TA))
}
else
{
print(paste("Error! Underdetermined system!"))
print("To calculate [SumCO2], please enter one pair of: (pH/CO2), (pH,fCO2), (TA,pH), (TA/CO2), (TA/fCO2)")
return(NULL)
}
}
else
{
print(paste("Error! Underdetermined system!"))
print("To calculate [SumCO2], please enter one pair of: (pH/CO2), (pH,fCO2), (TA,pH), (TA/CO2), (TA/fCO2)")
return(NULL)
}
}
else
{
if (is.null(fCO2) && is.null(CO2) && !is.null(pH) && !is.null(TA))
{
TAcalc <- calcTA(aquaenv, 10^(-pH))
print(paste("Error! Overdetermined system: entered TA:", TA, ", calculated TA:", TAcalc))
print("Please enter only one of: pH, TA, CO2, or fCO2.")
return(NULL)
}
if ((!is.null(pH) || !is.null(TA)) && (is.null(fCO2) && is.null(CO2)))
{
if (!is.null(pH))
{
H <- 10^(-pH)
TA <- calcTA(aquaenv, H)
attributes(TA) <- NULL
}
else
{
pH <- -log10(calcH_TA(aquaenv, TA))
}
CO2 <- H2Abi(SumCO2, aquaenv[["K_CO2"]], aquaenv[["K_HCO3"]], 10^(-pH))
attributes(CO2) <- NULL
fCO2 <- CO2 / aquaenv[["K0_CO2"]]
attributes(fCO2) <- NULL
}
else if (!is.null(fCO2) && !is.null(CO2) && is.null(pH) && is.null(TA))
{
fCO2calc <- CO2 / aquaenv[["K0_CO2"]]
print(paste("Error! Overdetermined system: entered fCO2:", fCO2, ", calculated fCO2:", fCO2calc))
print("Please enter only one of: pH, TA, CO2, or fCO2.")
return(NULL)
}
else if ((!is.null(fCO2) || !is.null(CO2)) && (is.null(pH) && is.null(TA)))
{
if(!is.null(fCO2))
{
CO2 <- aquaenv[["K0_CO2"]] * fCO2
attributes(CO2) <- NULL
}
else
{
fCO2 <- CO2 / aquaenv[["K0_CO2"]]
attributes(fCO2) <- NULL
}
H <- calcH_CO2(aquaenv, CO2)
TA <- calcTA(aquaenv, H)
pH <- -log10(H)
}
else if ((!is.null(fCO2) || !is.null(CO2)) && !is.null(pH) && is.null(TA))
{
if (!is.null(fCO2))
{
CO2 <- aquaenv[["K0_CO2"]] * fCO2
}
pHcalc <- -log10(calcH_CO2(aquaenv, CO2))
print(paste("Error! Overdetermined system: entered pH:", pH, ", calculated pH:", pHcalc))
print("Please enter only one of: pH, TA, CO2, or fCO2.")
return(NULL)
}
else if ((!is.null(fCO2) || !is.null(CO2)) && is.null(pH) && !is.null(TA))
{
if (!is.null(fCO2))
{
CO2 <- aquaenv[["K0_CO2"]] * fCO2
}
H <- calcH_CO2(aquaenv, CO2)
TAcalc <- calcTA(aquaenv, H)
print(paste("Error! Overdetermined system: entered TA:", TA, ", calculated TA:", TAcalc))
print("Please enter only one of: pH, TA, CO2, or fCO2.")
return(NULL)
}
}
aquaenv[["TA"]] <- TA ; attr(aquaenv[["TA"]], "unit") <- "mol/kg-soln"
aquaenv[["pH"]] <- pH ; attr(aquaenv[["pH"]], "pH scale") <- "free"
aquaenv[["SumCO2"]] <- SumCO2 ; attr(aquaenv[["SumCO2"]], "unit") <- "mol/kg-soln"
aquaenv[["fCO2"]] <- fCO2 ; attr(aquaenv[["fCO2"]], "unit") <- "atm"
aquaenv[["CO2"]] <- CO2 ; attr(aquaenv[["CO2"]], "unit") <- "mol/kg-soln"
if (speciation)
{
H <- 10^(-pH)
with (aquaenv,
{
aquaenv[["HCO3"]] <<- HAbi (SumCO2, K_CO2, K_HCO3, H) ; attr(aquaenv[["HCO3"]], "unit") <<- "mol/kg-soln"
aquaenv[["CO3"]] <<- Abi (SumCO2, K_CO2, K_HCO3, H) ; attr(aquaenv[["CO3"]], "unit") <<- "mol/kg-soln"
aquaenv[["BOH3"]] <<- HAuni (SumBOH3, K_BOH3, H) ; attr(aquaenv[["BOH3"]], "unit") <<- "mol/kg-soln"
aquaenv[["BOH4"]] <<- Auni (SumBOH3, K_BOH3, H) ; attr(aquaenv[["BOH4"]], "unit") <<- "mol/kg-soln"
aquaenv[["OH"]] <<- K_W / H ; attr(aquaenv[["OH"]], "unit") <<- "mol/kg-soln"
aquaenv[["H3PO4"]] <<- H3Atri(SumH3PO4, K_H3PO4, K_H2PO4, K_HPO4, H) ; attr(aquaenv[["H3PO4"]], "unit") <<- "mol/kg-soln"
aquaenv[["H2PO4"]] <<- H2Atri(SumH3PO4, K_H3PO4, K_H2PO4, K_HPO4, H) ; attr(aquaenv[["H2PO4"]], "unit") <<- "mol/kg-soln"
aquaenv[["HPO4"]] <<- HAtri (SumH3PO4, K_H3PO4, K_H2PO4, K_HPO4, H) ; attr(aquaenv[["HPO4"]], "unit") <<- "mol/kg-soln"
aquaenv[["PO4"]] <<- Atri (SumH3PO4, K_H3PO4, K_H2PO4, K_HPO4, H) ; attr(aquaenv[["PO4"]], "unit") <<- "mol/kg-soln"
aquaenv[["SiOH4"]] <<- H2Abi (SumSiOH4, K_SiOH4, K_SiOOH3, H) ; attr(aquaenv[["SiOH4"]], "unit") <<- "mol/kg-soln"
aquaenv[["SiOOH3"]] <<- HAbi (SumSiOH4, K_SiOH4, K_SiOOH3, H) ; attr(aquaenv[["SiOOH3"]], "unit") <<- "mol/kg-soln"
aquaenv[["SiO2OH2"]]<<- Abi (SumSiOH4, K_SiOH4, K_SiOOH3, H) ; attr(aquaenv[["SiO2OH2"]], "unit") <<- "mol/kg-soln"
aquaenv[["H2S"]] <<- H2Abi (SumH2S, K_H2S, K_HS, H) ; attr(aquaenv[["H2S"]], "unit") <<- "mol/kg-soln"
aquaenv[["HS"]] <<- HAbi (SumH2S, K_H2S, K_HS, H) ; attr(aquaenv[["HS"]], "unit") <<- "mol/kg-soln"
aquaenv[["S2min"]] <<- Abi (SumH2S, K_H2S, K_HS, H) ; attr(aquaenv[["S2min"]], "unit") <<- "mol/kg-soln"
aquaenv[["NH4"]] <<- HAuni (SumNH4, K_NH4, H) ; attr(aquaenv[["NH4"]], "unit") <<- "mol/kg-soln"
aquaenv[["NH3"]] <<- Auni (SumNH4, K_NH4, H) ; attr(aquaenv[["NH3"]], "unit") <<- "mol/kg-soln"
aquaenv[["H2SO4"]] <<- H2Abi (SumH2SO4, K_H2SO4, K_HSO4, H) ; attr(aquaenv[["H2SO4"]], "unit") <<- "mol/kg-soln"
aquaenv[["HSO4"]] <<- HAbi (SumH2SO4, K_H2SO4, K_HSO4, H) ; attr(aquaenv[["HSO4"]], "unit") <<- "mol/kg-soln"
aquaenv[["SO4"]] <<- Abi (SumH2SO4, K_H2SO4, K_HSO4, H) ; attr(aquaenv[["SO4"]], "unit") <<- "mol/kg-soln"
aquaenv[["HF"]] <<- HAuni (SumHF, K_HF, H) ; attr(aquaenv[["HF"]], "unit") <<- "mol/kg-soln"
aquaenv[["F"]] <<- Auni (SumHF, K_HF, H) ; attr(aquaenv[["F"]], "unit") <<- "mol/kg-soln"
aquaenv[["HNO3"]] <<- HAuni (SumHNO3, K_HNO3, H) ; attr(aquaenv[["HNO3"]], "unit") <<- "mol/kg-soln"
aquaenv[["NO3"]] <<- Auni (SumHNO3, K_HNO3, H) ; attr(aquaenv[["NO3"]], "unit") <<- "mol/kg-soln"
aquaenv[["HNO2"]] <<- HAuni (SumHNO2, K_HNO2, H) ; attr(aquaenv[["HNO2"]], "unit") <<- "mol/kg-soln"
aquaenv[["NO2"]] <<- Auni (SumHNO2, K_HNO2, H) ; attr(aquaenv[["NO2"]], "unit") <<- "mol/kg-soln"
aquaenv[["omega_calcite"]] <<- aquaenv[["Ca"]]*aquaenv[["CO3"]]/aquaenv[["Ksp_calcite"]]
attributes(aquaenv[["omega_calcite"]]) <<- NULL
aquaenv[["omega_aragonite"]] <<- aquaenv[["Ca"]]*aquaenv[["CO3"]]/aquaenv[["Ksp_aragonite"]]
attributes(aquaenv[["omega_aragonite"]]) <<- NULL
})
if (revelle)
{
aquaenv[["revelle"]] <- revelle(aquaenv)
attributes(aquaenv[["revelle"]]) <- NULL
}
}
if (dsa)
{
with (aquaenv,
{
if (!((length(SumCO2)==1) && (SumCO2==0)))
{
aquaenv[["c1"]] <<- CO2 /SumCO2 ; attributes(aquaenv[["c1"]]) <<- NULL
aquaenv[["c2"]] <<- HCO3/SumCO2 ; attributes(aquaenv[["c2"]]) <<- NULL
aquaenv[["c3"]] <<- CO3 /SumCO2 ; attributes(aquaenv[["c3"]]) <<- NULL
aquaenv[["dTAdSumCO2"]] <<- aquaenv[["c2"]] + 2*aquaenv[["c3"]]
attr(aquaenv[["dTAdSumCO2"]], "unit") <<- "(mol-TA/kg-soln)/(mol-SumCO2/kg-soln)"
}
if(!((length(SumBOH3)==1) && (SumBOH3==0)))
{
aquaenv[["b1"]] <<- BOH3/SumBOH3 ; attributes(aquaenv[["b1"]]) <<- NULL
aquaenv[["b2"]] <<- BOH4/SumBOH3 ; attributes(aquaenv[["b2"]]) <<- NULL
aquaenv[["dTAdSumBOH3"]] <<- aquaenv[["b2"]]
attr(aquaenv[["dTAdSumBOH3"]], "unit") <<- "(mol-TA/kg-soln)/(mol-SumBOH3/kg-soln)"
}
if(!((length(SumH3PO4)==1) && (SumH3PO4==0)))
{
aquaenv[["p1"]] <<- H3PO4/SumH3PO4 ; attributes(aquaenv[["p1"]]) <<- NULL
aquaenv[["p2"]] <<- H2PO4/SumH3PO4 ; attributes(aquaenv[["p2"]]) <<- NULL
aquaenv[["p3"]] <<- HPO4 /SumH3PO4 ; attributes(aquaenv[["p3"]]) <<- NULL
aquaenv[["p4"]] <<- PO4 /SumH3PO4 ; attributes(aquaenv[["p4"]]) <<- NULL
aquaenv[["dTAdSumH3PO4"]] <<- aquaenv[["p3"]] + 2*aquaenv[["p4"]] - aquaenv[["p1"]]
attr(aquaenv[["dTAdSumH3PO4"]], "unit") <<- "(mol-TA/kg-soln)/(mol-SumH3PO4/kg-soln)"
}
if(!((length(SumSiOH4)==1) && (SumSiOH4==0)))
{
aquaenv[["si1"]] <<- SiOH4 /SumSiOH4 ; attributes(aquaenv[["si1"]]) <<- NULL
aquaenv[["si2"]] <<- SiOOH3 /SumSiOH4 ; attributes(aquaenv[["si2"]]) <<- NULL
aquaenv[["si3"]] <<- SiO2OH2/SumSiOH4 ; attributes(aquaenv[["si3"]]) <<- NULL
aquaenv[["dTAdSumSumSiOH4"]] <<- aquaenv[["si2"]]
attr(aquaenv[["dTAdSumSumSiOH4"]], "unit") <<- "(mol-TA/kg-soln)/(mol-SumSiOH4/kg-soln)"
}
if(!((length(SumH2S)==1) && (SumH2S==0)))
{
aquaenv[["s1"]] <<- H2S /SumH2S ; attributes(aquaenv[["s1"]]) <<- NULL
aquaenv[["s2"]] <<- HS /SumH2S ; attributes(aquaenv[["s2"]]) <<- NULL
aquaenv[["s3"]] <<- S2min/SumH2S ; attributes(aquaenv[["s3"]]) <<- NULL
aquaenv[["dTAdSumH2S"]] <<- aquaenv[["s2"]] + 2*aquaenv[["s3"]]
attr(aquaenv[["dTAdSumH2S"]], "unit") <<- "(mol-TA/kg-soln)/(mol-SumH2S/kg-soln)"
}
if(!((length(SumNH4)==1) && (SumNH4==0)))
{
aquaenv[["n1"]] <<- NH4/SumNH4 ; attributes(aquaenv[["n1"]]) <<- NULL
aquaenv[["n2"]] <<- NH3/SumNH4 ; attributes(aquaenv[["n2"]]) <<- NULL
aquaenv[["dTAdSumNH4"]] <<- aquaenv[["n2"]]
attr(aquaenv[["dTAdSumNH4"]], "unit") <<- "(mol-TA/kg-soln)/(mol-SumNH4/kg-soln)"
}
if(!((length(SumH2SO4)==1) && (SumH2SO4==0)))
{
aquaenv[["so1"]] <<- H2SO4/SumH2SO4 ; attributes(aquaenv[["so1"]]) <<- NULL
aquaenv[["so2"]] <<- HSO4 /SumH2SO4 ; attributes(aquaenv[["so2"]]) <<- NULL
aquaenv[["so3"]] <<- SO4 /SumH2SO4 ; attributes(aquaenv[["so3"]]) <<- NULL
aquaenv[["dTAdSumH2SO4"]] <<- -aquaenv[["so2"]]
attr(aquaenv[["dTAdSumH2SO4"]], "unit") <<- "(mol-TA/kg-soln)/(mol-SumH2SO4/kg-soln)"
}
if(!((length(SumHF)==1) && (SumHF==0)))
{
aquaenv[["f1"]] <<- HF/SumHF ; attributes(aquaenv[["f1"]]) <<- NULL
aquaenv[["f2"]] <<- F /SumHF ; attributes(aquaenv[["f2"]]) <<- NULL
aquaenv[["dTAdSumHF"]] <<- -aquaenv[["f1"]]
attr(aquaenv[["dTAdSumHF"]], "unit") <<- "(mol-TA/kg-soln)/(mol-SumHF/kg-soln)"
}
if(!((length(SumHNO3)==1) && (SumHNO3==0)))
{
aquaenv[["na1"]] <<- HNO3/SumHNO3 ; attributes(aquaenv[["na1"]]) <<- NULL
aquaenv[["na2"]] <<- NO3 /SumHNO3 ; attributes(aquaenv[["na2"]]) <<- NULL
aquaenv[["dTAdSumHNO3"]] <<- -aquaenv[["na1"]]
attr(aquaenv[["dTAdSumHNO3"]], "unit") <<- "(mol-TA/kg-soln)/(mol-SumHNO3/kg-soln)"
}
if(!((length(SumHNO2)==1) && (SumHNO2==0)))
{
aquaenv[["ni1"]] <<- HNO2/SumHNO2 ; attributes(aquaenv[["ni1"]]) <<- NULL
aquaenv[["ni2"]] <<- NO2 /SumHNO2 ; attributes(aquaenv[["ni2"]]) <<- NULL
aquaenv[["dTAdSumHNO2"]] <<- -aquaenv[["ni1"]]
attr(aquaenv[["dTAdSumHNO2"]], "unit") <<- "(mol-TA/kg-soln)/(mol-SumHNO2/kg-soln)"
}
})
aquaenv[["dTAdH"]] <- dTAdH(aquaenv) ; attr(aquaenv[["dTAdH"]], "unit") <- "(mol-TA/kg-soln)/(mol-H/kg-soln)"
aquaenv[["dTAdKdKdS"]] <- dTAdKdKdS(aquaenv) ; attr(aquaenv[["dTAdKdKdS"]], "unit") <- "(mol-TA/kg-soln)/\"psu\""
aquaenv[["dTAdKdKdT"]] <- dTAdKdKdT(aquaenv) ; attr(aquaenv[["dTAdKdKdT"]], "unit") <- "(mol-TA/kg-soln)/K"
aquaenv[["dTAdKdKdp"]] <- dTAdKdKdp(aquaenv) ; attr(aquaenv[["dTAdKdKdp"]], "unit") <- "(mol-TA/kg-soln)/m"
aquaenv[["dTAdKdKdSumH2SO4"]] <- dTAdKdKdSumH2SO4(aquaenv) ; attr(aquaenv[["dTAdKdKdSumH2SO4"]], "unit") <- "(mol-TA/kg-soln)/(mol-SumH2SO4/kg-soln)"
aquaenv[["dTAdKdKdSumHF"]] <- dTAdKdKdSumHF(aquaenv) ; attr(aquaenv[["dTAdKdKdSumHF"]], "unit") <- "(mol-TA/kg-soln)/(mol-SumHF/kg-soln)"
}
}
return(aquaenv)
}
}
plot.aquaenv <- function(x, xval, what=NULL, bjerrum=FALSE, cumulative=FALSE, newdevice=TRUE, setpar=TRUE, device="x11", ...)
{
if ((!bjerrum) && (!cumulative))
{
if (is.null(what))
{
plotall(aquaenv=x, xval=xval, newdevice=newdevice, setpar=setpar, device=device, ...)
}
else
{
selectplot(aquaenv=x, xval=xval, what=what, newdevice=newdevice, setpar=setpar, device=device, ...)
}
}
else if (bjerrum)
{
bjerrumplot(aquaenv=x, what=what, newdevice=newdevice, setpar=setpar, device=device, ...)
}
else
{
cumulativeplot(aquaenv=x, xval=xval, what=what, newdevice=newdevice, setpar=setpar, device=device, ...)
}
if (!(device=="x11"))
{
dev.off()
}
}
as.data.frame.aquaenv <- function(x, ...)
{
len <- length(x)
temp <- list()
for (e in x)
{
if (length(e) > 1)
{
temp <- c(temp, list(e))
}
else
{
temp <- c(temp, list(rep(e,len)))
}
}
names(temp) <- names(x)
return(as.data.frame(temp))
}
#######################################################################
# Function BufferFactors for calculating the buffer factors describing
# the sensitivity of pH and concentrations of acid-base species to a
# change in ocean chemistry
#######################################################################
BufferFactors <- function(ae = NULL, parameters = NA,
species = c("SumCO2"), k_w = NULL,
k_co2 = NULL, k_hco3 = NULL, k_boh3 = NULL,
k_hso4 = NULL, k_hf = NULL, k1k2 = "lueker",
khf = "dickson", khso4 = "dickson")
{
# Test if object of class aquaenv is given as input
# If it is, test its class, then take its values
if(!is.null(ae)) {
if((class(ae)=="aquaenv")==FALSE) {
print(paste("Error! Object 'ae' is not of class 'aquaenv"))
return(NULL) } else {
# Provided parameters overwrite aquaenv input
if(is.na(parameters["DIC"])) {
parameters["DIC"] <- ae$SumCO2}
if(is.na(parameters["TotNH3"])) {
parameters["TotNH3"] <- ae$SumNH4}
if(is.na(parameters["TotP"])) {
parameters["TotP"] <- ae$SumH3PO4}
if(is.na(parameters["TotNO3"])) {
parameters["TotNO3"] <- ae$SumHNO3}
if(is.na(parameters["TotNO2"])) {
parameters["TotNO2"] <- ae$SumHNO2}
if(is.na(parameters["TotS"])) {
parameters["TotS"] <- ae$SumH3PO4}
if(is.na(parameters["TotSi"])) {
parameters["TotSi"] <- ae$SumSiOH4}
if(is.na(parameters["TB"])) {
parameters["TB"] <- ae$SumBOH3}
if(is.na(parameters["TotF"])) {
parameters["TotF"] <- ae$SumHF}
if(is.na(parameters["TotSO4"])) {
parameters["TotSO4"] <- ae$SumH2SO4}
if(is.na(parameters["sal"])) {
parameters["sal"] <- ae$S}
if(is.na(parameters["temp"])) {
parameters["temp"] <- ae$t}
if(is.na(parameters["pres"])) {
parameters["pres"] <- ae$p}
if(is.na(parameters["Alk"])) {
parameters["Alk"] <- ae$TA}
}
} else {
# Assign default values if one or more parameters are absent
# Default values are from Table 4 of Hagens and Middelburg (2016)
if(is.na(parameters["DIC"])) {
parameters["DIC"] <- 1e-6*2017.14} # mol/kg-soln
if(is.na(parameters["TotNH3"])) {parameters["TotNH3"] <-
convert(1e-6*0.3, "conc", "molar2molin", S = 34.617,
t = 18.252, p = 0.1*1.008)} # mol/kg-soln
if(is.na(parameters["TotP"])) {parameters["TotP"] <-
convert(1e-6*0.530, "conc", "molar2molin", S = 34.617,
t = 18.252, p = 0.1*1.008)} # mol/kg-soln
if(is.na(parameters["TotNO3"])) {parameters["TotNO3"] <-
convert(1e-6*5.207, "conc", "molar2molin", S = 34.617,
t = 18.252, p = 0.1*1.008)} # mol/kg-soln
if(is.na(parameters["TotNO2"])) {parameters["TotNO2"] <-
convert(1e-6*0.1, "conc", "molar2molin", S = 34.617,
t = 18.252, p = 0.1*1.008)} # mol/kg-soln
if(is.na(parameters["TotS"])) {parameters["TotS"] <-
convert(1e-9*2.35, "conc", "molar2molin", S = 34.617,
t = 18.252, p = 0.1*1.008)} # mol/kg-soln
if(is.na(parameters["TotSi"])) {parameters["TotSi"] <-
convert(1e-6*7.466, "conc", "molar2molin", S = 34.617,
t = 18.252, p = 0.1*1.008)} # mol/kg-soln
if(is.na(parameters["TB"])) {
parameters["TB"] <- 1e-6*428.4} # mol/kg-soln
if(is.na(parameters["TotF"])) {
parameters["TotF"] <- 1e-6*67.579} # mol/kg-soln
if(is.na(parameters["TotSO4"])) {
parameters["TotSO4"] <- 0.02793} # mol/kg-soln
if(is.na(parameters["sal"])) {
parameters["sal"] <- 34.617} # -
if(is.na(parameters["temp"])) {
parameters["temp"] <- 18.252} # degrees Celsius
if(is.na(parameters["pres"])) {
parameters["pres"] <- 0.1*1.008} # bar
if(is.na(parameters["Alk"])) {
parameters["Alk"] <- 1e-6*2304.91} # mol/kg-soln
}
with(as.list(parameters),
{
# Calculation of speciation
ae <- aquaenv(S=sal, t=temp, p=pres, TA=Alk, SumCO2=DIC, SumBOH3 =
TB, SumNH4 = TotNH3, SumH3PO4 = TotP, SumHNO3 =
TotNO3, SumHNO2 = TotNO2, SumH2S = TotS, SumSiOH4 =
TotSi, SumH2SO4 = TotSO4, SumHF = TotF, speciation =
TRUE, dsa = TRUE, k_w = k_w, k_co2 = k_co2,
k_hco3 = k_hco3, k_boh3 = k_boh3, k_hso4 = k_hso4,
k_hf = k_hf, k1k2 = k1k2, khf = khf, khso4 = khso4)
with(as.list(ae),
{
# General definitions and creation of output vectors
H <- 10^(-pH)
dTA.dH <- dtotX.dH <- dTA.dX <- dtotX.dX <- dTA.dpH <- dtotX.dpH <-
dH.dTA <- dX.dTA <- dX.dtotX <- dpH.dTA <-
rep(NA, length.out = length(species))
dH.dtotX <- dpH.dtotX <- rep(NA, length.out = length(species) + 5)
# Assign names to output vectors
names(dTA.dH) <- names(dtotX.dH) <- names(dTA.dX) <-
names(dtotX.dX) <- names(dTA.dpH) <- names(dtotX.dpH) <-
names(dH.dTA) <- names(dX.dTA) <- names(dX.dtotX) <-
names(dpH.dTA) <- species
names(dH.dtotX) <- names(dpH.dtotX) <-
c(species,"sal", "temp", "pres", "SumH2SO4_scaleconv",
"SumHF_scaleconv")
# Define function for calculating TA.X
TA.species <- function(X.name)
{
if(X.name == "CO2" || X.name == "HCO3" || X.name == "CO3" ||
X.name == "SumCO2") {HCO3 + 2*CO3} else
if(X.name == "NH3" || X.name == "NH4" || X.name == "SumNH4") {
NH3} else
if(X.name == "H2PO4" || X.name == "H3PO4" ||
X.name == "HPO4" || X.name == "PO4" ||
X.name == "SumH3PO4") {-H3PO4 + HPO4 + 2*PO4} else
if(X.name == "NO3" || X.name == "HNO3" ||
X.name == "SumHNO3") {-HNO3} else
if(X.name == "NO2" || X.name == "HNO2" ||
X.name == "SumHNO2") {-HNO2} else
if(X.name == "H2S" || X.name == "HS" ||
X.name == "S2min" || X.name == "SumH2S") {
HS + 2*S2min} else
if(X.name == "SiOH4" || X.name == "SiOOH3" ||
X.name == "SiO2OH2" || X.name == "SumSiOH4") {
SiOOH3 + 2*SiO2OH2} else
if(X.name == "BOH3" || X.name == "BOH4" ||
X.name == "SumBOH3") {BOH4} else
if(X.name == "F" || X.name == "HF" ||
X.name == "SumHF") {-HF} else
if(X.name == "SO4" || X.name == "H2SO4" ||
X.name == "HSO4" || X.name == "SumH2SO4") {
-2*H2SO4 - HSO4} else
NULL
}
# Define function for determining n
n.function <- function(X.name)
{
if(X.name == "CO2" || X.name == "BOH3" || X.name == "NH4" ||
X.name == "H2PO4" || X.name == "NO3" || X.name == "NO2" ||
X.name == "H2S" || X.name == "SiOH4" || X.name == "F" ||
X.name == "SO4" || X.name == "SumCO2" || X.name == "SumBOH3" ||
X.name == "SumNH4" || X.name == "SumH3PO4" ||
X.name == "SumHNO3" || X.name == "SumHNO2" ||
X.name == "SumH2S" || X.name == "SumSiOH4" ||
X.name == "SumHF" || X.name == "SumH2SO4") {n <- 0} else
if(X.name == "HCO3" || X.name == "NH3" ||
X.name == "HPO4" || X.name == "HS" ||
X.name == "SiOOH3" || X.name == "BOH4") {n <- 1} else
if(X.name == "CO3" || X.name == "PO4" || X.name == "S2min" ||
X.name == "SiO2OH2") {n <- 2} else
if(X.name == "H3PO4" || X.name == "HNO3" ||
X.name == "HNO2" || X.name == "HF" || X.name == "HSO4") {
n <- -1} else
if(X.name == "H2SO4") {n <- -2} else
NULL
}
# Define function for calculating dTAdH
dTAdH.function <- function(X.name)
{
n <- n.function(X.name)
TA.X <- TA.species(X.name)
if(parameters["DIC"]!=0) {
if(X.name == "CO2" || X.name == "HCO3" || X.name == "CO3" ||
X.name == "SumCO2") {
dTAdH.CO2 <- (-1/H)*(-n*TA.X + HCO3 + 4*CO3)} else {
dTAdH.CO2 <- (-1/H)*(HCO3*(c1-c3) + 2*CO3*(2*c1+c2))}
} else dTAdH.CO2 <- 0
if(parameters["TotNH3"]!=0) {
if(X.name == "NH3" || X.name == "NH4" || X.name == "SumNH4") {
dTAdH.NH4 <- (-1/H)*(-n*TA.X + NH3)} else {
dTAdH.NH4 <- (-1/H)*(NH3*n1)}
} else dTAdH.NH4 <- 0
if(parameters["TotP"]!=0) {
if(X.name == "H2PO4" || X.name == "H3PO4" || X.name == "HPO4" ||
X.name == "PO4" || X.name == "SumH3PO4") {
dTAdH.H2PO4 <- (-1/H)*(-n*TA.X + H3PO4 + HPO4 + 4*PO4)} else {
dTAdH.H2PO4 <- (-1/H)*(-H3PO4*(-p2-2*p3-3*p4) +
HPO4*(2*p1+p2-p4) + 2*PO4*(3*p1+2*p2+p3))}
} else dTAdH.H2PO4 <- 0
if(parameters["TotNO3"]!=0) {
if(X.name == "NO3" || X.name == "HNO3" || X.name == "SumHNO3") {
dTAdH.NO3 <- (-1/H)*(-n*TA.X + HNO3)} else {
dTAdH.NO3 <- (-1/H)*(-HNO3*na2)}
} else dTAdH.NO3 <- 0
if(parameters["TotNO2"]!=0) {
if(X.name == "NO2" || X.name == "HNO2" || X.name == "SumHNO2") {
dTAdH.NO2 <- (-1/H)*(-n*TA.X + HNO2)} else {
dTAdH.NO2 <- (-1/H)*(-HNO2*ni2)}
} else dTAdH.NO2 <- 0
if(parameters["TotS"]!=0) {
if(X.name == "H2S" || X.name == "HS" || X.name == "S2min" ||
X.name == "SumH2S") {
dTAdH.H2S <- (-1/H)*(-n*TA.X + HS + 4*S2min)} else {
dTAdH.H2S <- (-1/H)*(HS*(s1-s3) + 2*S2min*(2*s1+s2))}
} else dTAdH.H2S <- 0
if(parameters["TotSi"]!=0) {
if(X.name == "SiOH4" || X.name == "SiOOH3" ||
X.name == "SiO2OH2" || X.name == "SumSiOH4") {
dTAdH.SiOH4 <- (-1/H)*(-n*TA.X + SiOOH3 + 4*SiO2OH2)} else {
dTAdH.SiOH4 <- (-1/H)*(SiOOH3*(si1-si3) +
2*SiO2OH2*(2*si1+si2))}
} else dTAdH.SiOH4 <- 0
if(parameters["TB"]!=0) {
if(X.name == "BOH3" || X.name == "BOH4" || X.name == "SumBOH3") {
dTAdH.BOH3 <- (-1/H)*(-n*TA.X + BOH4)} else {
dTAdH.BOH3 <-(-1/H)*(BOH4*b1)}
} else dTAdH.BOH3 <- 0
if(parameters["TotF"]!=0) {
if(X.name == "F" || X.name == "HF" || X.name == "SumHF") {
dTAdH.F <- (-1/H)*(-n*TA.X + HF)} else {
dTAdH.F <- (-1/H)*(-HF*f2)}
} else dTAdH.F <- 0
if(parameters["TotSO4"]!=0) {
if(X.name == "SO4" || X.name == "H2SO4" || X.name == "HSO4" ||
X.name == "SumH2SO4") {
dTAdH.SO4 <- (-1/H)*(-n*TA.X + 4*H2SO4 + HSO4)} else {
dTAdH.SO4 <- (-1/H)*(-2*H2SO4*(-so2-2*so3) - HSO4*(so1-so3))}
} else dTAdH.SO4 <- 0
dTAdH.H <- (-1/H)*(OH+H) # Internal enhancement of buffering
return(dTAdH.CO2 + dTAdH.NH4 + dTAdH.H2PO4 + dTAdH.NO3 +
dTAdH.NO2 + dTAdH.H2S + dTAdH.SiOH4 + dTAdH.BOH3 + dTAdH.F +
dTAdH.SO4 + dTAdH.H)
}
# Define function for determining totX
totX.function <- function(X.name)
{
if(X.name == "CO2" || X.name == "HCO3" || X.name == "CO3" ||
X.name == "SumCO2") {SumCO2} else
if(X.name == "NH3" || X.name == "NH4" || X.name == "SumNH4") {
SumNH4} else
if(X.name == "H2PO4" || X.name == "H3PO4" ||
X.name == "HPO4" || X.name == "PO4" ||
X.name == "SumH3PO4") {SumH3PO4} else
if(X.name == "NO3" || X.name == "HNO3" ||
X.name == "SumHNO3") {SumHNO3} else
if(X.name == "NO2" || X.name == "HNO2" ||
X.name == "SumHNO2") {SumHNO2} else
if(X.name == "H2S" || X.name == "HS" ||
X.name == "S2min" || X.name == "SumH2S") {SumH2S} else
if(X.name == "SiOH4" || X.name == "SiOOH3" ||
X.name == "SiO2OH2" || X.name == "SumSiOH4") {
SumSiOH4} else
if(X.name == "BOH3" || X.name == "BOH4" ||
X.name == "SumBOH3") {SumBOH3} else
if(X.name == "F" || X.name == "HF" ||
X.name == "SumHF") {SumHF} else
if(X.name == "SO4" || X.name == "H2SO4" ||
X.name == "HSO4" || X.name == "SumH2SO4") {
SumH2SO4} else
NULL
}
# Define a function to calculate the Revelle factor
Revelle_func <- function(species)
{
X.name <- "CO2"
X <- get(X.name)
n <- n.function(X.name)
TA.X <- TA.species(X.name)
totX <- totX.function(X.name)
dTA.dH <- dTAdH.function(X.name)
dX.dtotX <- X * H * dTA.dH / (TA.X^2 + (H*dTA.dH - n*TA.X)*totX)
RF <- as.numeric(ae$SumCO2 / ae$CO2 * dX.dtotX)
return(RF)
}
# Loop that calculates output species per variable
for (i in 1:length(species))
{
# In case a change in the total concentration is specified,
# change X to the reference species for TA
X.name <- species[i]
if(X.name == "SumCO2") X <- get("CO2") else
if(X.name == "SumNH4") X <- get("NH4") else
if(X.name == "SumH3PO4") X <- get("H2PO4") else
if(X.name == "SumHNO3") X <- get("NO3") else
if(X.name == "SumHNO2") X <- get("NO2") else
if(X.name == "SumH2S") X <- get("H2S") else
if(X.name == "SumSiOH4") X <- get("SiOH4") else
if(X.name == "SumBOH3") X <- get("BOH3") else
if(X.name == "SumHF") X <- get("F") else
if(X.name == "SumH2SO4") X <- get("SO4") else
X <- get(species[i])
n <- n.function(X.name)
TA.X <- TA.species(X.name)
totX <- totX.function(X.name)
# Calculation of first half of factors
dTA.dH[i] <- dTAdH.function(X.name)
dtotX.dH[i] <- (n*totX - TA.X) / H
dTA.dX[i] <- TA.X / X
dtotX.dX[i] <- totX / X
# Transformation from dH to dpH where necessary
dH.dpH <- -log(10)*H
dTA.dpH[i] <- dH.dpH * dTA.dH[i]
dtotX.dpH[i] <- dH.dpH * dtotX.dH[i]
# Calculation of second half of factors
dH.dTA[i] <- totX*H / (TA.X^2 + (H*dTA.dH[i] - n*TA.X)*totX)
dH.dtotX[i] <- -TA.X*H / (TA.X^2 + (H*dTA.dH[i] - n*TA.X)*totX)
dX.dTA[i] <- -X * (n*totX - TA.X) / (TA.X^2 + (H*dTA.dH[i] -
n*TA.X)*totX)
dX.dtotX[i] <- X * H * dTA.dH[i] / (TA.X^2 + (H*dTA.dH[i] -
n*TA.X)*totX)
# Transformation from dH to dpH where necessary
dpH.dH <- 1/(-log(10)*H)
dpH.dTA[i] <- dpH.dH * dH.dTA[i]
dpH.dtotX[i] <- dpH.dH * dH.dtotX[i]
}
# Calculate the Revelle factor
RF <- Revelle_func(species)
# Define the sensitivities with respect to temperature, salinity and
# pressure (dH/dT, dH/dS, dH/dp, dH/dSumH2SO4, dH/dSumHF)
# changes in dissocation constants associated with sal changes
dH.dtotX[1+length(species)] <- (dTAdKdKdS) / (-dTAdH)
# changes in dissocation constants associated with temp changes
dH.dtotX[2+length(species)] <- (dTAdKdKdT) / (-dTAdH)
# changes in dissocation constants associated with pres changes
dH.dtotX[3+length(species)] <- (dTAdKdKdp) / (-dTAdH)
# changes in dissocation constants associated with TotSO4 changes
dH.dtotX[4+length(species)] <- (dTAdKdKdSumH2SO4) / (-dTAdH)
# changes in dissocation constants associated with TotF changes
dH.dtotX[5+length(species)] <- (dTAdKdKdSumHF) / (-dTAdH)
# Transform the above sensitivities from dH to dpH
dpH.dtotX[1+length(species)] <- dpH.dH * dH.dtotX[1+length(species)]
dpH.dtotX[2+length(species)] <- dpH.dH * dH.dtotX[2+length(species)]
dpH.dtotX[3+length(species)] <- dpH.dH * dH.dtotX[3+length(species)]
dpH.dtotX[4+length(species)] <- dpH.dH * dH.dtotX[4+length(species)]
dpH.dtotX[5+length(species)] <- dpH.dH * dH.dtotX[5+length(species)]
# Return statement
return(list(ae = ae, dTA.dH = dTA.dH, dtotX.dH = dtotX.dH,
dTA.dX = dTA.dX, dtotX.dX = dtotX.dX, dTA.dpH = dTA.dpH,
dtotX.dpH = dtotX.dpH, dH.dTA = dH.dTA,
dH.dtotX = dH.dtotX, dX.dTA = dX.dTA,
dX.dtotX = dX.dtotX, dpH.dTA = dpH.dTA,
dpH.dtotX = dpH.dtotX, beta.H = as.numeric(dTAdH),
RF = RF))
})
})
} | /scratch/gouwar.j/cran-all/cranData/AquaEnv/R/aquaenv_public_mainfunctions.R |
par(ask=TRUE)
require(deSolve)
######################################################################################
# Parameters
######################################################################################
parameters <- list(
t = 15 , # degrees C
S = 25 , # psu
k = 0.4 , # 1/d proportionality factor for air-water exchange
rOx = 0.0000003 , # mol-N/(kg*d) maximal rate of oxic mineralisation
rNitri = 0.0000002 , # mol-N/(kg*d) maximal rate of nitrification
rPP = 0.0000006 , # mol-N/(kg*d) maximal rate of primary production
ksSumNH4 = 0.000001 , # mol-N/kg
D = 0.1 , # 1/d (dispersive) transport coefficient
O2_io = 0.000296 , # mol/kg-soln
NO3_io = 0.000035 , # mol/kg-soln
SumNH4_io = 0.000008 , # mol/kg-soln
SumCO2_io = 0.002320 , # mol/kg-soln
TA_io = 0.002435 , # mol/kg-soln
C_Nratio = 8 , # mol C/mol N C:N ratio of organic matter
a = 30 , # timestep from which PP begins
b = 50 , # timestep where PP shuts off again
modeltime = 100 # duration of the model
)
######################################################################################
# The model function
######################################################################################
boxmodel <- function(timestep, currentstate, parameters)
{
with (
as.list(c(currentstate,parameters)),
{
ae <- aquaenv(S=S, t=t, SumCO2=SumCO2, SumNH4=SumNH4, TA=TA, dsa=TRUE)
ECO2 <- k * (ae$CO2_sat - ae$CO2)
EO2 <- k * (ae$O2_sat - O2)
RNit <- rNitri
ROx <- rOx
if ((timestep > a) && (timestep < b))
{
RPP <- rPP * (SumNH4/(ksSumNH4 + SumNH4))
}
else
{
RPP <- 0
}
dO2 <- EO2 - C_Nratio*ROx - 2*RNit + C_Nratio*RPP
dNO3 <- RNit
dSumCO2 <- ECO2 + C_Nratio*ROx - C_Nratio*RPP
dSumNH4 <- ROx - RNit - RPP
dTA <- ROx - 2*RNit - RPP
# The DSA pH
dH <- (dTA - (dSumCO2*ae$dTAdSumCO2 + dSumNH4*ae$dTAdSumNH4))/ae$dTAdH
DSApH <- -log10(H)
# The DSA pH using pH dependent fractional stoichiometry (= using partitioning coefficients)
rhoHECO2 <- ae$c2 + 2*ae$c3
rhoHRNit <- 1 + ae$n1
rhoHROx <- C_Nratio * (ae$c2 + 2*ae$c3) - ae$n1
rhoHRPP <- -(C_Nratio * (ae$c2 + 2*ae$c3)) + ae$n1
dH_ECO2 <- rhoHECO2*ECO2/(-ae$dTAdH)
dH_RNit <- rhoHRNit*RNit/(-ae$dTAdH)
dH_ROx <- rhoHROx*ROx /(-ae$dTAdH)
dH_RPP <- rhoHRPP*RPP /(-ae$dTAdH)
dH_stoich <- dH_ECO2 + dH_RNit + dH_ROx + dH_RPP
DSAstoichpH <- -log10(H_stoich)
ratesofchanges <- c(dO2, dNO3, dSumNH4, dSumCO2, dTA, dH, dH_stoich)
processrates <- c(ECO2=ECO2, EO2=EO2, RNit=RNit, ROx=ROx, RPP=RPP)
DSA <- c(DSApH=DSApH, rhoHECO2=rhoHECO2, rhoHRNit=rhoHRNit, rhoHROx=rhoHROx,
rhoHRPP=rhoHRPP, dH_ECO2=dH_ECO2, dH_RNit=dH_RNit, dH_ROx=dH_ROx, dH_RPP=dH_RPP, DSAstoichpH=DSAstoichpH)
return(list(ratesofchanges, list(processrates, DSA, ae)))
}
)
}
######################################################################################
# The model solution
######################################################################################
with (as.list(parameters),
{
H_init <<- 10^(-(aquaenv(S=S, t=t, SumCO2=SumCO2_io, SumNH4=SumNH4_io, TA=TA_io, speciation=FALSE)$pH))
initialstate <<- c(O2=O2_io, NO3=NO3_io, SumNH4=SumNH4_io, SumCO2=SumCO2_io, TA=TA_io, H=H_init, H_stoich=H_init)
times <<- c(0:modeltime)
output <<- as.data.frame(vode(initialstate, times, boxmodel, parameters, hmax=1))[-1,]
})
######################################################################################
# Output
######################################################################################
# plot the most important modelresults
what <- c("SumCO2", "TA", "SumNH4", "NO3", "ECO2", "EO2", "RNit", "ROx", "RPP", "dTAdH", "dTAdSumCO2", "dTAdSumNH4", "c1", "c2", "c3", "n1", "n2",
"rhoHECO2", "rhoHRNit", "rhoHROx", "rhoHRPP", "dH_ECO2", "dH_RNit", "dH_ROx", "dH_RPP",
"pH", "DSApH", "DSAstoichpH")
plot(aquaenv(ae=output, from.data.frame=TRUE), xval=output$time, what=what, xlab="time/d", mfrow=c(6,5), size=c(20,13), newdevice=FALSE)
# cumulative plot of the influences of the processes on the pH
par(mfrow=c(1,2))
what <- c("dH_ECO2", "dH_RNit", "dH_ROx", "dH_RPP")
plot(aquaenv(ae=output, from.data.frame=TRUE), xval=output$time, what=what, xlab="time/d", size=c(7,5), ylab="mol-H/(kg-soln*d)", legendposition="bottomright", cumulative=TRUE, newdevice=FALSE)
# check if all three methods of calculating the pH yield the same result
ylim <- range(output$DSApH, output$DSAstoichpH, output$pH)
plot(output$DSApH, ylim=ylim, type="l")
par(new=TRUE)
plot(output$DSApH, ylim=ylim, type="l", col="red")
par(new=TRUE)
plot(output$DSAstoichpH, ylim=ylim, type="l", col="blue")
| /scratch/gouwar.j/cran-all/cranData/AquaEnv/demo/DSAdynamicmodel.R |
par(ask=TRUE)
##############################################################################################
# Calculating TA from titration data
##############################################################################################
#### 1.) proof of concept ###########################
#####################################################
#####################################################
# generate "data":
S <- 35
t <- 15
SumCO2 <- 0.002000
TA <- 0.002200
initial_ae <- aquaenv(S=S, t=t, SumCO2=SumCO2, TA=TA)
mass_sample <- 0.01 # the mass of the sample solution in kg
mass_titrant <- 0.003 # the total mass of the added titrant solution in kg
conc_titrant <- 0.01 # the concentration of the titrant solution in mol/kg-soln
S_titrant <- 0.5 # the salinity of the titrant solution (the salinity of a solution with a ionic strength of 0.01 according to: I = (19.924 S) / (1000 - 1.005 S)
steps <- 20 # the amount of steps the mass of titrant is added in
type <- "HCl"
ae <- titration(initial_ae, mass_sample, mass_titrant, conc_titrant, S_titrant, steps, type)
plot(ae, ae$delta_mass_titrant, what="pH", newdevice=FALSE)
# the input data for the TA fitting routine: a table with the added mass of the titrant and the resulting free scale pH
titcurve <- cbind(ae$delta_mass_titrant, ae$pH)
# for the TA fitting procedure all total quantities except SumCO2 (SumNH4, SumH2S, SumH3PO4, SumSiOH4, SumHNO3, SumHNO2, SumBOH3, SumH2SO4, SumHF)
# need to be known. However, the latter three can be calculated from salinity as it is done in this example.
fit1 <- TAfit(initial_ae, titcurve, conc_titrant, mass_sample, S_titrant)
fit1
# E (V) values as input variables: generate E values using E0=0.4 V and the nernst equation
tottitcurve <- convert(titcurve[,2], "pHscale", "free2sws", S=S, t=t) # Nernst equation relates E to TOTAL [H+] (DOE1994, p.7, ch.4, sop.3), BUT, if fluoride is present, its SWS, so we use SWS!
Etitcurve <- cbind(titcurve[,1], (0.4 - ((PhysChemConst$R/10)*initial_ae$T/PhysChemConst$F)*log(10^-tottitcurve))) # Nernst equation
fit2 <- TAfit(initial_ae, Etitcurve, conc_titrant, mass_sample, S_titrant, Evals=TRUE, verbose=TRUE)
fit2
# k_co2 fitting: one K_CO2 (k_co2) for the whole titration curve is fitted, i.e. there is NO correction for K_CO2 changes due to changing S due to mixing with the titrant
fit3 <- TAfit(initial_ae, titcurve, conc_titrant, mass_sample, S_titrant, K_CO2fit=TRUE)
fit3
# assume the titrant has the same salinity as the sample (and is made up of natural seawater, i.e. containing SumBOH4, SumH2SO4 and SumHF as functions of S), then the "right" K_CO2 should be fitted
# i.e we do NOT give the argument S_titrant and set the flag seawater_titrant to TRUE
ae <- titration(initial_ae, mass_sample, mass_titrant, conc_titrant, steps=steps, type=type, seawater_titrant=TRUE)
titcurve <- cbind(ae$delta_mass_titrant, ae$pH)
fit4 <- TAfit(initial_ae, titcurve, conc_titrant, mass_sample, K_CO2fit=TRUE, seawater_titrant=TRUE)
fit4
# fitting of TA, SumCO2, K_CO2 and E0
Etitcurve <- cbind(titcurve[,1], (0.4 - ((PhysChemConst$R/10)*initial_ae$T/PhysChemConst$F)*log(10^-titcurve[,2])))
fit5 <- TAfit(initial_ae, Etitcurve, conc_titrant, mass_sample, K_CO2fit=TRUE, seawater_titrant=TRUE, Evals=TRUE)
fit5
# fitting of non equally spaced data:
neqsptitcurve <- rbind(titcurve[1:9,], titcurve[11:20,])
fit6 <- TAfit(initial_ae, neqsptitcurve, conc_titrant, mass_sample, seawater_titrant=TRUE, equalspaced=FALSE)
fit6
#add some "noise" on the generated data
noisetitcurve <- titcurve * rnorm(length(titcurve), mean=1, sd=0.01) #one percent error possible
plot(ae, ae$delta_mass_titrant, what="pH", type="l", col="red", xlim=c(0,0.003), ylim=c(3,8.1), newdevice=FALSE)
par(new=TRUE)
plot(noisetitcurve[,1],noisetitcurve[,2], type="l", xlim=c(0,0.003), ylim=c(3,8.1))
fit7 <- TAfit(initial_ae, noisetitcurve, conc_titrant, mass_sample, seawater_titrant=TRUE)
fit7
######## 2.) test with generated data from Dickson1981 ########
###############################################################
###############################################################
conc_titrant = 0.3 # mol/kg-soln
mass_sample = 0.2 # kg
S_titrant = 14.835 # is aequivalent to the ionic strength of 0.3 mol/kg-soln
SumBOH3 = 0.00042 # mol/kg-soln
SumH2SO4 = 0.02824 # mol/kg-soln
SumHF = 0.00007 # mol/kg-soln
sam <- cbind(sample_dickson1981[,1]/1000, sample_dickson1981[,2]) # convert mass of titrant from g to kg
dicksonfit <- TAfit(aquaenv(t=25, S=35, SumBOH3=SumBOH3, SumH2SO4=SumH2SO4, SumHF=SumHF), sam, conc_titrant, mass_sample, S_titrant=S_titrant, debug=TRUE)
dicksonfit
#TA Dickson1981: 0.00245
#SumCO2 Dickson1981: 0.00220
# => not exactly the same! why?
# a.) does salinity correction (S_titrant) matter or not?
##########################################################
# without salinity correction
dicksontitration1 <- titration(aquaenv(t=25, S=35, SumCO2=0.00220, SumBOH3=SumBOH3, SumH2SO4=SumH2SO4, SumHF=SumHF, TA=0.00245),
mass_sample=mass_sample, mass_titrant=0.0025, conc_titrant=conc_titrant, steps=50, type="HCl")
# with salinity correction
dicksontitration2 <- titration(aquaenv(t=25, S=35, SumCO2=0.00220, SumBOH3=SumBOH3, SumH2SO4=SumH2SO4, SumHF=SumHF, TA=0.00245),
mass_sample=mass_sample, mass_titrant=0.0025, conc_titrant=conc_titrant, S_titrant=S_titrant, steps=50, type="HCl")
plot(dicksontitration1, xval=dicksontitration1$delta_mass_titrant, what="pH", xlim=c(0,0.0025), ylim=c(3,8.2), newdevice=FALSE, col="red")
par(new=TRUE)
plot(dicksontitration2, xval=dicksontitration2$delta_mass_titrant, what="pH", xlim=c(0,0.0025), ylim=c(3,8.2), newdevice=FALSE, col="blue")
par(new=TRUE)
plot(sam[,1], sam[,2], type="l", xlim=c(0,0.0025), ylim=c(3,8.2))
# => salinity correction makes NO difference, because the relation between total sample and added titrant is very large: salinity only drops from 35 to 34.75105
#BUT: there is an offset between the "Dickson" curve and our curve:
plot(dicksontitration2$pH - sam[,2])
# b.) does it get better if we fit K_CO2 as well?
#################################################
dicksonfit2 <- TAfit(aquaenv(t=25, S=35, SumBOH3=SumBOH3, SumH2SO4=SumH2SO4, SumHF=SumHF), sam, conc_titrant, mass_sample, S_titrant=S_titrant, debug=TRUE, K_CO2fit=TRUE)
dicksonfit2
#TA Dickson1981: 0.00245
#SumCO2 Dickson1981: 0.00220
# => yes it does, but it is not perfect yet!
# c.) differing K values
#########################
# Dickson uses fixed K values that are slightly different than ours
dicksontitration3 <- titration(aquaenv(t=25, S=35, SumCO2=0.00220, SumBOH3=SumBOH3, SumH2SO4=SumH2SO4, SumHF=SumHF, TA=0.00245, k_w=4.32e-14, k_co2=1e-6, k_hco3=8.20e-10, k_boh3=1.78e-9, k_hso4=(1/1.23e1), k_hf=(1/4.08e2)),
mass_sample=mass_sample, mass_titrant=0.0025, conc_titrant=conc_titrant, steps=50, type="HCl", S_titrant=S_titrant,
k_w=4.32e-14, k_co2=1e-6, k_hco3=8.20e-10, k_boh3=1.78e-9, k_hso4=(1/1.23e1), k_hf=(1/4.08e2))
plot(dicksontitration3, xval=dicksontitration3$delta_mass_titrant, what="pH", xlim=c(0,0.0025), ylim=c(3,8.2), newdevice=FALSE, col="blue")
par(new=TRUE)
plot(sam[,1], sam[,2], type="l", xlim=c(0,0.0025), ylim=c(3,8.2))
plot(dicksontitration3$pH - sam[,2])
# => no offset between the pH curves
# => exactly the same curves!
dicksonfit3 <- TAfit(aquaenv(t=25, S=35, SumBOH3=SumBOH3, SumH2SO4=SumH2SO4, SumHF=SumHF, k_w=4.32e-14, k_co2=1e-6, k_hco3=8.20e-10, k_boh3=1.78e-9, k_hso4=(1/1.23e1), k_hf=(1/4.08e2)),
sam, conc_titrant, mass_sample, S_titrant=S_titrant, debug=TRUE,
k_w=4.32e-14, k_co2=1e-6, k_hco3=8.20e-10, k_boh3=1.78e-9, k_hso4=(1/1.23e1), k_hf=(1/4.08e2))
dicksonfit3
# PERFECT fit!
plot(sam[,1], sam[,2], xlim=c(0,0.0025), ylim=c(3,8.2), type="l")
par(new=TRUE)
plot(tit$delta_mass_titrant, calc, xlim=c(0,0.0025), ylim=c(3,8.2), type="l", col="red")
| /scratch/gouwar.j/cran-all/cranData/AquaEnv/demo/TAfitting.R |
par(ask=TRUE)
#######################################################################
# calling the K functions directly
#######################################################################
K1 <- K_CO2(30, 15)
K2 <- K_HCO3(30, 15)
K1
K2
#######################################################################
# Minimal aquaenv definition
#######################################################################
ae <- aquaenv(S=30, t=15)
ae$K_CO2
ae$Ksp_calcite
ae$Ksp_aragonite
ae <- aquaenv(S=30, t=15, p=10)
ae <- aquaenv(S=30, t=15, P=11)
ae <- aquaenv(S=30, t=15, d=100)
ae <- aquaenv(S=30, t=15, d=100, Pa=0.5)
ae$K_CO2
ae$Ksp_calcite
ae$Ksp_aragonite
ae
#######################################################################
# Defining the complete aquaenv system in different ways
#######################################################################
S <- 30
t <- 15
p <- gauge_p(d=10) # ~ p <- 0.1*10*1.01325
SumCO2 <- 0.0020
pH <- 8
TA <- 0.002140798
fCO2 <- 0.0005326744
CO2 <- 2.051946e-05
ae <- aquaenv(S, t, p, SumCO2=SumCO2, pH=pH)
ae$TA
ae <- aquaenv(S, t, p, SumCO2=SumCO2, TA=TA)
ae$pH
ae <- aquaenv(S, t, p, SumCO2=SumCO2, CO2=CO2)
ae$pH
ae <- aquaenv(S, t, p, SumCO2=SumCO2, fCO2=fCO2)
ae$pH
ae <- aquaenv(S, t, p, SumCO2=SumCO2, CO2=CO2, fCO2=fCO2)
ae <- aquaenv(S, t, p, SumCO2=SumCO2, pH=pH, TA=TA)
ae <- aquaenv(S, t, p, SumCO2=SumCO2, pH=pH, CO2=CO2)
ae <- aquaenv(S, t, p, SumCO2=SumCO2, pH=pH, fCO2=fCO2)
ae <- aquaenv(S, t, p, SumCO2=SumCO2, TA=TA, CO2=CO2)
ae <- aquaenv(S, t, p, SumCO2=SumCO2, TA=TA, fCO2=fCO2)
###########################################################################################
# having "aquaenv" calculated all properties that are needed to use the DSA for pH modelling
############################################################################################
S <- 30
t <- 15
p <- gauge_p(10) # ~ p <- 0.1*10*1.01325
SumCO2 <- 0.0020
pH <- 8
ae <- aquaenv(S=S, t=t, p=p, SumCO2=SumCO2, pH=pH, dsa=TRUE, revelle=TRUE)
#the buffer factor and auxilary buffer factors
ae$dTAdH
ae$dTAdSumCO2
ae$dTAdSumBOH3
ae$dTAdSumH2SO4
ae$dTAdSumHF
#the buffer factors concerning changes in the K's
ae$dTAdKdKdS
ae$dTAdKdKdT
ae$dTAdKdKdp
ae$dTAdKdKdSumH2SO4
ae$dTAdKdKdSumHF
#the partitioning coefficients
ae$c1
ae$c2
ae$c3
ae$b1
ae$b2
ae$so1
ae$so2
ae$so3
ae$f1
ae$f2
#not really DSA relevant: the revelle factor
ae$revelle
#######################################################################
# Cloning the aquaenv system: 1 to 1 and with different pH or TA
#######################################################################
S <- 30
t <- 15
SumCO2 <- 0.0020
TA <- 0.00214
ae <- aquaenv(S, t, SumCO2=SumCO2, TA=TA)
aeclone1 <- aquaenv(ae=ae)
pH <- 9
aeclone2 <- aquaenv(ae=ae, pH=pH)
TA <- 0.002
aeclone3 <- aquaenv(ae=ae, TA=TA)
ae$pH
aeclone1$pH
aeclone2$TA
aeclone3$pH
#######################################################################
#preparing input variables
#######################################################################
S <- 10
t <- 15
pH_NBS <- 8.142777
SumCO2molar <- 0.002016803
pH_free <- convert(pH_NBS, "pHscale", "nbs2free", S=S, t=t)
SumCO2molin <- convert(SumCO2molar, "conc", "molar2molin", S=S, t=t)
ae <- aquaenv(S, t, SumCO2=SumCO2molin, pH=pH_free)
ae$pH
ae$SumCO2
ae$TA
#########################################################################
# Vectors as input variables (only ONE input variable may be a vector)
# (with full output: including the Revelle factor and the DSA properties)
#########################################################################
SumCO2 <- 0.0020
pH <- 8
S <- 30
t <- 1:15
p <- gauge_p(10)
ae <- aquaenv(S, t, p, SumCO2=SumCO2, pH=pH, revelle=TRUE, dsa=TRUE)
plot(ae, xval=t, xlab="T/(deg C)", newdevice=FALSE)
S <- 1:30
t <- 15
ae <- aquaenv(S, t, p, SumCO2=SumCO2, pH=pH, revelle=TRUE, dsa=TRUE)
plot(ae, xval=S, xlab="S", newdevice=FALSE)
S <- 30
p <- gauge_p(seq(1,1000, 100))
ae <- aquaenv(S, t, p, SumCO2=SumCO2, pH=pH, revelle=TRUE, dsa=TRUE)
plot(ae, xval=p, xlab="gauge pressure/bar", newdevice=FALSE)
TA <- 0.0023
S <- 30
t <- 1:15
p <- gauge_p(10)
ae <- aquaenv(S, t, p, SumCO2=SumCO2, TA=TA, revelle=TRUE, dsa=TRUE)
plot(ae, xval=t, xlab="T/(deg C)", newdevice=FALSE)
S <- 1:30
t <- 15
ae <- aquaenv(S, t, p, SumCO2=SumCO2, TA=TA, revelle=TRUE, dsa=TRUE)
plot(ae, xval=S, xlab="S", newdevice=FALSE)
S <- 30
p <- gauge_p(seq(1,1000, 100))
ae <- aquaenv(S, t, p, SumCO2=SumCO2, TA=TA, revelle=TRUE, dsa=TRUE)
plot(ae, xval=p, xlab="gauge pressure/bar", newdevice=FALSE)
######################################################################################
# Conversion from and to a dataframe
#(conversion from a dataframe is needed to treat the results of a dynamic run with the
# package deSolve as an object of type "aquaenv")
######################################################################################
aedataframe <- as.data.frame(ae)
aetest <- aquaenv(ae=aedataframe, from.data.frame=TRUE)
######################################################################################
# Calculating SumCO2 by giving a constant pH&CO2, pH&fCO2, pH&TA, TA&CO2, or TA&fCO2
######################################################################################
fCO2 <- 0.0006952296
CO2 <- 2.678137e-05
pH <- 7.888573
TA <- 0.0021
S <- 30
t <- 15
p <- gauge_p(10)
ae <- aquaenv(S, t, p, SumCO2=NULL, pH=pH, CO2=CO2, dsa=TRUE, revelle=TRUE)
ae$SumCO2
ae$revelle
ae$dTAdH
ae <- aquaenv(S, t, p, SumCO2=NULL, pH=pH, fCO2=fCO2)
ae$SumCO2
ae <- aquaenv(S, t, p, SumCO2=NULL, pH=pH, TA=TA)
ae$SumCO2
ae <- aquaenv(S, t, p, SumCO2=NULL, TA=TA, CO2=CO2)
ae$SumCO2
ae <- aquaenv(S, t, p, SumCO2=NULL, TA=TA, fCO2=fCO2)
ae$SumCO2
t <- 1:15
ae <- aquaenv(S, t, p, SumCO2=NULL, pH=pH, CO2=CO2)
plot(ae, xval=t, xlab="T/(deg C)", mfrow=c(9,10), newdevice=FALSE)
ae <- aquaenv(S, t, p, SumCO2=NULL, pH=pH, CO2=CO2, revelle=TRUE, dsa=TRUE)
plot(ae, xval=t, xlab="T/(deg C)", newdevice=FALSE)
S <- 1:30
t <- 15
ae <- aquaenv(S, t, p, SumCO2=NULL, pH=pH, fCO2=fCO2, revelle=TRUE, dsa=TRUE)
plot(ae, xval=S, xlab="S", newdevice=FALSE)
S <- 30
p <- gauge_p(seq(1,1000, 100))
ae <- aquaenv(S, t, p, SumCO2=NULL, pH=pH, TA=TA, revelle=TRUE, dsa=TRUE)
plot(ae, xval=p, xlab="gauge pressure/bar", newdevice=FALSE)
| /scratch/gouwar.j/cran-all/cranData/AquaEnv/demo/basicfeatures.R |
par(ask=TRUE)
require(deSolve)
######################################################################################
# Parameters
######################################################################################
parameters <- list(
S = 25 , # psu
t_min = 5 , # degrees C
t_max = 25 , # degrees C
d = 10 , # m
k = 0.4 , # 1/d proportionality factor for air-water exchange
rOx = 0.0000003 , # mol-N/(kg*d) maximal rate of oxic mineralisation
rNitri = 0.0000002 , # mol-N/(kg*d) maximal rate of nitrification
rPP = 0.000006 , # mol-N/(kg*d) maximal rate of primary production
ksDINPP = 0.000001 , # mol-N/kg
ksNH4PP = 0.000001 , # mol-N/kg
D = 0.1 , # 1/d (dispersive) transport coefficient
O2_io = 0.000296 , # mol/kg-soln
NO3_io = 0.000035 , # mol/kg-soln
SumNH4_io = 0.000008 , # mol/kg-soln
SumCO2_io = 0.002320 , # mol/kg-soln
TA_io = 0.002435 , # mol/kg-soln
C_Nratio = 8 , # mol C/mol N C:N ratio of organic matter
a = 30 , # timestep from which PP begins
b = 50 , # timestep where PP shuts off again
modeltime = 100 # duration of the model
)
######################################################################################
# The model function
######################################################################################
Waddenzeebox <- function(timestep, currentstate, parameters)
{
with (
as.list(c(currentstate,parameters)),
{
t <- c(seq(t_min, t_max, (t_max-t_min)/(modeltime/2)), seq(t_max, t_min, -(t_max-t_min)/(modeltime/2)))[[round(timestep)+1]]
ae <- aquaenv(S=S, t=t, SumCO2=SumCO2, SumNH4=SumNH4, TA=TA)
ECO2 <- k * (ae$CO2_sat - ae$CO2)
EO2 <- k * (ae$O2_sat - O2)
TO2 <- D*(O2_io - O2)
TNO3 <- D*(NO3_io - NO3)
TSumNH4 <- D*(SumNH4_io - SumNH4)
TTA <- D*(TA_io - TA)
TSumCO2 <- D*(SumCO2_io - SumCO2)
RNit <- rNitri
ROx <- rOx
ROxCarbon <- ROx * C_Nratio
pNH4PP <- 0
RPP <- 0
if ((timestep > a) && (timestep < b))
{
RPP <- rPP * ((SumNH4+NO3)/(ksDINPP + (SumNH4+NO3)))
pNH4PP <- 1 - (ksNH4PP/(ksNH4PP + SumNH4))
}
else
{
RPP <- 0
}
RPPCarbon <- RPP * C_Nratio
dO2 <- TO2 + EO2 - ROxCarbon - 2*RNit + (2-2*pNH4PP)*RPP + RPPCarbon
dNO3 <- TNO3 + RNit -(1-pNH4PP)*RPP
dSumCO2 <- TSumCO2 + ECO2 + ROxCarbon - RPPCarbon
dSumNH4 <- TSumNH4 + ROx - RNit - pNH4PP*RPP
dTA <- TTA + ROx - 2*RNit -(2*pNH4PP-1)*RPP
ratesofchanges <- c(dO2, dNO3, dSumNH4, dSumCO2, dTA)
transport <- c(TO2=TO2, TNO3=TNO3, TSumNH4=TSumNH4, TTA=TTA, TSumCO2=TSumCO2)
airseaexchange <- c(ECO2=ECO2, EO2=EO2)
return(list(ratesofchanges, list(transport, airseaexchange, ae)))
}
)
}
######################################################################################
# The model solution
######################################################################################
with (as.list(parameters),
{
initialstate <<- c(O2=O2_io, NO3=NO3_io, SumNH4=SumNH4_io, SumCO2=SumCO2_io, TA=TA_io)
times <<- c(0:modeltime)
output <<- as.data.frame(vode(initialstate,times,Waddenzeebox,parameters, hmax=1))[-1,]
})
######################################################################################
# Output
######################################################################################
plot(aquaenv(ae=output, from.data.frame=TRUE), xval=output$time, xlab="time/d", mfrow=c(10,11), newdevice=FALSE)
| /scratch/gouwar.j/cran-all/cranData/AquaEnv/demo/dynamicmodel.R |
par(ask=TRUE)
require(deSolve)
what <- c("SumCO2", "TA", "Rc", "Rp", "omega_calcite", "pH")
mfrow <- c(2,3)
size <- c(15,7)
parameters <- list(
S = 35 , # psu
t = 15 , # degrees C
SumCO2_t0 = 0.002 , # mol/kg-soln (comparable to Wang2005)
TA_t0 = 0.0022 , # mol/kg-soln (comparable to Millero1998)
kc = 0.5 , # 1/d proportionality factor for air-water exchange
kp = 0.000001 , # mol/(kg-soln*d) max rate of calcium carbonate precipitation
n = 2.0 , # - exponent for kinetic rate law of precipitation
modeltime = 20 , # d duration of the model
outputsteps = 100 # number of outputsteps
)
boxmodel <- function(timestep, currentstate, parameters)
{
with (
as.list(c(currentstate,parameters)),
{
ae <- aquaenv(S=S, t=t, SumCO2=SumCO2, TA=TA, SumSiOH4=0, SumBOH3=0, SumH2SO4=0, SumHF=0)
Rc <- kc * ((ae$CO2_sat) - (ae$CO2))
Rp <- kp * (1-ae$omega_calcite)^n
dSumCO2 <- Rc - Rp
dTA <- -2*Rp
ratesofchanges <- c(dSumCO2, dTA)
processrates <- c(Rc=Rc, Rp=Rp)
return(list(ratesofchanges, list(processrates, ae)))
}
)
}
with (as.list(parameters),
{
initialstate <<- c(SumCO2=SumCO2_t0, TA=TA_t0)
times <<- seq(0,modeltime,(modeltime/outputsteps))
output <<- as.data.frame(vode(initialstate,times,boxmodel,parameters, hmax=1))
})
plot(aquaenv(ae=output, from.data.frame=TRUE), xval=output$time, xlab="", mfrow=mfrow, size=size, what=what, newdevice=FALSE)
| /scratch/gouwar.j/cran-all/cranData/AquaEnv/demo/pHmodelling1_implicit_method.R |
par(ask=TRUE)
require(deSolve)
what <- c("SumCO2", "TA", "Rc", "Rp", "omega_calcite", "pH", "dHRc", "dHRp")
mfrow <- c(3,3)
size <- c(15,10)
parameters <- list(
S = 35 , # psu
t = 15 , # degrees C
SumCO2_t0 = 0.002 , # mol/kg-soln (comparable to Wang2005)
TA_t0 = 0.0022 , # mol/kg-soln (comparable to Millero1998)
kc = 0.5 , # 1/d proportionality factor for air-water exchange
kp = 0.000001 , # mol/(kg-soln*d) max rate of calcium carbonate precipitation
n = 2.0 , # - exponent for kinetic rate law of precipitation
modeltime = 20 , # d duration of the model
outputsteps = 100 # number of outputsteps
)
boxmodel <- function(timestep, currentstate, parameters)
{
with (
as.list(c(currentstate,parameters)),
{
ae <- aquaenv(S=S, t=t, SumCO2=SumCO2, pH=-log10(H), SumSiOH4=0, SumBOH3=0, SumH2SO4=0, SumHF=0, dsa=TRUE)
Rc <- kc * ((ae$CO2_sat) - (ae$CO2))
Rp <- kp * (1-ae$omega_calcite)^n
dSumCO2 <- Rc - Rp
dHRc <- ( -(ae$dTAdSumCO2*Rc ))/ae$dTAdH
dHRp <- (-2*Rp -(ae$dTAdSumCO2*(-Rp)))/ae$dTAdH
dH <- dHRc + dHRp
ratesofchanges <- c(dSumCO2, dH)
processrates <- c(Rc=Rc, Rp=Rp)
outputvars <- c(dHRc=dHRc, dHRp=dHRp)
return(list(ratesofchanges, list(processrates, outputvars, ae)))
}
)
}
with (as.list(parameters),
{
aetmp <- aquaenv(t=t, S=S, SumCO2=SumCO2_t0, TA=TA_t0, SumSiOH4=0, SumBOH3=0, SumH2SO4=0, SumHF=0)
H_t0 <- 10^(-aetmp$pH)
initialstate <<- c(SumCO2=SumCO2_t0, H=H_t0)
times <<- seq(0,modeltime,(modeltime/outputsteps))
output <<- as.data.frame(vode(initialstate,times,boxmodel,parameters, hmax=1))
})
plot(aquaenv(ae=output, from.data.frame=TRUE), xval=output$time, xlab="time/d", mfrow=mfrow, size=size, what=what, newdevice=FALSE)
| /scratch/gouwar.j/cran-all/cranData/AquaEnv/demo/pHmodelling2_explicit_method.R |
par(ask=TRUE)
require(deSolve)
what <- c("SumCO2", "TA", "Rc", "Rp", "omega_calcite", "pH", "dHRc", "dHRp", "rhoc", "rhop")
mfrow <- c(3,4)
size <- c(15,10)
parameters <- list(
S = 35 , # psu
t = 15 , # degrees C
SumCO2_t0 = 0.002 , # mol/kg-soln (comparable to Wang2005)
TA_t0 = 0.0022 , # mol/kg-soln (comparable to Millero1998)
kc = 0.5 , # 1/d proportionality factor for air-water exchange
kp = 0.000001 , # mol/(kg-soln*d) max rate of calcium carbonate precipitation
n = 2.0 , # - exponent for kinetic rate law of precipitation
modeltime = 20 , # d duration of the model
outputsteps = 100 # number of outputsteps
)
boxmodel <- function(timestep, currentstate, parameters)
{
with (
as.list(c(currentstate,parameters)),
{
ae <- aquaenv(S=S, t=t, SumCO2=SumCO2, pH=-log10(H), SumSiOH4=0, SumBOH3=0, SumH2SO4=0, SumHF=0, dsa=TRUE)
Rc <- kc * ((ae$CO2_sat) - (ae$CO2))
Rp <- kp * (1-ae$omega_calcite)^n
dSumCO2 <- Rc - Rp
rhoc <- ae$c2 + 2*ae$c3
rhop <- 2*ae$c1 + ae$c2
dHRc <- rhoc*Rc/(-ae$dTAdH)
dHRp <- rhop*Rp/(-ae$dTAdH)
dH <- dHRc + dHRp
ratesofchanges <- c(dSumCO2, dH)
processrates <- c(Rc=Rc, Rp=Rp)
outputvars <- c(dHRc=dHRc, dHRp=dHRp, rhoc=rhoc, rhop=rhop)
return(list(ratesofchanges, list(processrates, outputvars, ae)))
}
)
}
with (as.list(parameters),
{
aetmp <- aquaenv(t=t, S=S, SumCO2=SumCO2_t0, TA=TA_t0, SumSiOH4=0, SumBOH3=0, SumH2SO4=0, SumHF=0)
H_t0 <- 10^(-aetmp$pH)
initialstate <<- c(SumCO2=SumCO2_t0, H=H_t0)
times <<- seq(0,modeltime,(modeltime/outputsteps))
output <<- as.data.frame(vode(initialstate,times,boxmodel,parameters, hmax=1))
})
plot(aquaenv(ae=output, from.data.frame=TRUE), xval=output$time, xlab="time/d", mfrow=mfrow, size=size, what=what, newdevice=FALSE)
par(mfrow=c(1,1))
what <- c("dHRc", "dHRp")
plot(aquaenv(ae=output, from.data.frame=TRUE), xval=output$time, xlab="time/d", what=what, ylab="mol-H/(kg-soln*d)", legendposition="topright", cumulative=TRUE, newdevice=FALSE)
| /scratch/gouwar.j/cran-all/cranData/AquaEnv/demo/pHmodelling3_fractional_stoichiometry.R |
par(ask=TRUE)
#######################################################################################################
# Titration with HCl
#######################################################################################################
S <- 35
t <- 15
SumCO2 <- 0.003500
SumNH4 <- 0.000020
mass_sample <- 0.01 # the mass of the sample solution in kg
mass_titrant <- 0.02 # the total mass of the added titrant solution in kg
conc_titrant <- 0.01 # the concentration of the titrant solution in mol/kg-soln
S_titrant <- 0.5 # the salinity of the titrant solution (the salinity of a solution with a ionic strength of 0.01 according to: I = (19.924 S) / (1000 - 1.005 S)
steps <- 50 # the amount of steps the mass of titrant is added in
type <- "HCl"
pHstart <- 11.3
ae <- titration(aquaenv(S=S, t=t, SumCO2=SumCO2, SumNH4=SumNH4, pH=pHstart), mass_sample, mass_titrant, conc_titrant, S_titrant, steps, type)
# plotting everything
plot(ae, xval=ae$delta_mass_titrant, xlab="HCl solution added [kg]", mfrow=c(10,10), newdevice=FALSE)
# plotting selectively
size <- c(12,8) #inches
mfrow <- c(4,4)
what <- c("TA", "pH", "CO2", "HCO3", "CO3", "BOH3", "BOH4", "OH", "NH4", "NH3", "H2SO4", "HSO4", "SO4", "HF", "F", "fCO2")
plot(ae, xval=ae$delta_mass_titrant, xlab="HCl solution added [kg]", what=what, size=size, mfrow=mfrow, newdevice=FALSE)
plot(ae, xval=ae$pH, xlab="free scale pH", what=what, size=size, mfrow=mfrow, newdevice=FALSE)
# different x values
plot(ae, xval=ae$delta_conc_titrant, xlab="[HCl] offset added [mol/kg-soln]", what=what, size=size, mfrow=mfrow, newdevice=FALSE)
plot(ae, xval=ae$delta_moles_titrant, xlab="HCl added [mol]", what=what, size=size, mfrow=mfrow, newdevice=FALSE)
# bjerrum plots
par(mfrow=c(1,1))
plot(ae, bjerrum=TRUE, newdevice=FALSE)
what <- c("CO2", "HCO3", "CO3")
plot(ae, what=what, bjerrum=TRUE, newdevice=FALSE)
plot(ae, what=what, bjerrum=TRUE, lwd=4, palette=c("cyan", "magenta", "yellow"), bg="gray", legendinset=0.1, legendposition="topleft", newdevice=FALSE)
what <- c("CO2", "HCO3", "CO3", "BOH3", "BOH4", "OH", "NH4", "NH3", "H2SO4", "HSO4", "SO4", "HF", "F")
plot(ae, what=what, bjerrum=TRUE, log=TRUE, newdevice=FALSE)
plot(ae, what=what, bjerrum=TRUE, log=TRUE, ylim=c(-6,-1), legendinset=0, lwd=3, palette=c(1,3,4,5,6,colors()[seq(100,250,6)]), newdevice=FALSE)
#######################################################################################################
# Titration with NaOH
#######################################################################################################
S <- 35
t <- 15
SumCO2 <- 0.003500
SumNH4 <- 0.000020
mass_sample <- 0.01 # the mass of the sample solution in kg
mass_titrant <- 0.02 # the total mass of the added titrant solution in kg
conc_titrant <- 0.01 # the concentration of the titrant solution in mol/kg-soln
S_titrant <- 0.5 # the salinity of the titrant solution
steps <- 50 # the amount of steps the mass of titrant is added in
type <- "NaOH"
pHstart <- 2
ae <- titration(aquaenv(S=S, t=t, SumCO2=SumCO2, SumNH4=SumNH4, pH=pHstart), mass_sample, mass_titrant, conc_titrant, S_titrant, steps, type)
# plottinge everything
plot(ae, xval=ae$delta_mass_titrant, xlab="NaOH solution added [kg]", mfrow=c(10,10), newdevice=FALSE)
# plotting selectively
size <- c(12,8) #inches
mfrow <- c(4,4)
what <- c("TA", "pH", "CO2", "HCO3", "CO3", "BOH3", "BOH4", "OH", "NH4", "NH3", "H2SO4", "HSO4", "SO4", "HF", "F", "fCO2")
plot(ae, xval=ae$delta_mass_titrant, xlab="NaOH solution added [kg]", what=what, size=size, mfrow=mfrow, newdevice=FALSE)
plot(ae, xval=ae$pH, xlab="free scale pH", what=what, size=size, mfrow=mfrow, newdevice=FALSE)
# bjerrum plots
par(mfrow=c(1,1))
what <- c("CO2", "HCO3", "CO3")
plot(ae, what=what, bjerrum=TRUE, newdevice=FALSE)
what <- c("CO2", "HCO3", "CO3", "BOH3", "BOH4", "OH", "NH4", "NH3", "H2SO4", "HSO4", "SO4", "HF", "F")
plot(ae, what=what, bjerrum=TRUE, log=TRUE, ylim=c(-6,-1), legendinset=0, lwd=3, palette=c(1,3,4,5,6,colors()[seq(100,250,6)]), newdevice=FALSE)
#########################################################################################################################################################################
# titration with a titrant with very high concentrations and a very large sample volume: the volume and salinity corrections do not matter: looks like "simpletitration"
#########################################################################################################################################################################
S <- 35
t <- 15
SumCO2 <- 0.003500
SumNH4 <- 0.000020
mass_sample <- 100 # the mass of the sample solution in kg
mass_titrant <- 0.5 # the total mass of the added titrant solution in kg
conc_titrant <- 3 # the concentration of the titrant solution in mol/kg-soln
S_titrant <- 0.5 # the salinity of the titrant solution (the salinity of a solution with a ionic strength of 0.01 according to: I = (19.924 S) / (1000 - 1.005 S)
steps <- 100 # the amount of steps the mass of titrant is added in
type <- "HCl"
pHstart <- 11.3
ae <- titration(aquaenv(S=S, t=t, SumCO2=SumCO2, SumNH4=SumNH4, pH=pHstart), mass_sample, mass_titrant, conc_titrant, S_titrant, steps, type)
# plotting everything
plot(ae, xval=ae$delta_mass_titrant, xlab="HCl solution added [kg]", mfrow=c(10,10), newdevice=FALSE)
# plotting selectively
size <- c(12,8) #inches
mfrow <- c(4,4)
what <- c("TA", "pH", "CO2", "HCO3", "CO3", "BOH3", "BOH4", "OH", "NH4", "NH3", "H2SO4", "HSO4", "SO4", "HF", "F", "fCO2")
plot(ae, xval=ae$delta_mass_titrant, xlab="HCl solution added [kg]", what=what, size=size, mfrow=mfrow, newdevice=FALSE)
plot(ae, xval=ae$pH, xlab="free scale pH", what=what, size=size, mfrow=mfrow, newdevice=FALSE)
# different x values
plot(ae, xval=ae$delta_conc_titrant, xlab="[HCl] offset added [mol/kg-soln]", what=what, size=size, mfrow=mfrow, newdevice=FALSE)
plot(ae, xval=ae$delta_moles_titrant, xlab="HCl added [mol]", what=what, size=size, mfrow=mfrow, newdevice=FALSE)
# bjerrum plots
par(mfrow=c(1,1))
plot(ae, bjerrum=TRUE, newdevice=FALSE)
what <- c("CO2", "HCO3", "CO3")
plot(ae, what=what, bjerrum=TRUE, newdevice=FALSE)
plot(ae, what=what, bjerrum=TRUE, lwd=4, palette=c("cyan", "magenta", "yellow"), bg="gray", legendinset=0.1, legendposition="topleft", newdevice=FALSE)
what <- c("CO2", "HCO3", "CO3", "BOH3", "BOH4", "OH", "NH4", "NH3", "H2SO4", "HSO4", "SO4", "HF", "F")
plot(ae, what=what, bjerrum=TRUE, log=TRUE, newdevice=FALSE)
plot(ae, what=what, bjerrum=TRUE, log=TRUE, ylim=c(-6,-1), legendinset=0, lwd=3, palette=c(1,3,4,5,6,colors()[seq(100,250,6)]), newdevice=FALSE)
| /scratch/gouwar.j/cran-all/cranData/AquaEnv/demo/titration.R |
### R code from vignette source 'AquaEnv.rnw'
###################################################
### code chunk number 1: Preliminaries
###################################################
library("AquaEnv")
library("deSolve")
options(width=80)
Plotit <- AquaEnv:::plot.aquaenv
plot.aquaenv <- function(...) {
if ("newdevice" %in% list(...))
Plotit(...)
else
Plotit(newdevice = FALSE, ...) # else Sweave does not work...
}
###################################################
### code chunk number 2: AquaenvElements
###################################################
test <- aquaenv(S = 35, t = 10)
test$t
###################################################
### code chunk number 3: CallingKFuncsDirectly
###################################################
K_CO2(S = 15, t = 30)
K0_CO2(S = 15, t = 30)
Ksp_calcite(S = 15, t = 30, p = 100)
###################################################
### code chunk number 4: Avector
###################################################
K_CO2(S = 10:15, t = 30)
###################################################
### code chunk number 5: MinimalAquaenv
###################################################
ae <- aquaenv(S = 30, t = 15)
ae$K_CO2
###################################################
### code chunk number 6: AquaenvWithDepth
###################################################
ae <- aquaenv(S = 30, t = 15, p = 10)
names(ae)
ae$Ksp_calcite
###################################################
### code chunk number 7: AquaenvPressures
###################################################
ae <- aquaenv(S = 30, t = 15, p = 10)
ae[c("p", "P")]
ae <- aquaenv(S = 30, t = 15, P = 10)
unlist(ae[c("p", "P")])
ae <- aquaenv(S = 30, t = 15, P = 10, Pa = 0.5)
unlist(ae[c("p", "P")])
ae <- aquaenv(S = 30, t = 15, d = 100)
unlist(ae[c("p", "P")])
ae <- aquaenv(S = 30, t = 15, d = 100, lat = 51)
unlist(ae[c("p", "P")])
###################################################
### code chunk number 8: SkeletonAquaenv
###################################################
ae <- aquaenv(S = 30, t = 15, p = 10, skeleton = TRUE)
names(ae)
###################################################
### code chunk number 9: CompleteAquaenvSystem
###################################################
S <- 30
t <- 15
p <- 10
SumCO2 <- 0.0020
pH <- 8
TA <- 0.002142233
fCO2 <- 0.0005272996
CO2 <- 2.031241e-05
ae <- aquaenv(S, t, p, SumCO2 = SumCO2, pH = pH)
ae$TA
ae <- aquaenv(S, t, p, SumCO2 = SumCO2, TA = TA)
ae$pH
ae <- aquaenv(S, t, p, SumCO2 = SumCO2, CO2 = CO2)
ae$pH
names(ae)
###################################################
### code chunk number 10: SpeciationSkeletonAquaenv
###################################################
ae <- aquaenv(S, t, p, SumCO2 = SumCO2, pH = pH, speciation = FALSE)
names(ae)
ae <- aquaenv(S, t, p, SumCO2 = SumCO2, pH = pH, speciation = FALSE,
skeleton = TRUE)
names(ae)
###################################################
### code chunk number 11: DSAAquaenv
###################################################
ae <- aquaenv(S, t, p, SumCO2 = SumCO2, fCO2 = fCO2, dsa = TRUE)
ae$dTAdH
ae$revelle
###################################################
### code chunk number 12: ErrorMessagesAquaenv
###################################################
ae <- aquaenv(S, t, p, SumCO2 = SumCO2, CO2 = CO2, fCO2 = fCO2)
ae <- aquaenv(S, t, p, SumCO2 = SumCO2, pH = pH, TA = TA)
ae <- aquaenv(S, t, p, SumCO2 = SumCO2, pH = pH, CO2 = CO2)
ae <- aquaenv(S, t, p, SumCO2 = SumCO2, pH = pH, fCO2 = fCO2)
ae <- aquaenv(S, t, p, SumCO2 = SumCO2, TA = TA, CO2 = CO2)
ae <- aquaenv(S, t, p, SumCO2 = SumCO2, TA = TA, fCO2 = fCO2)
###################################################
### code chunk number 13: SumCO2Calculating
###################################################
fCO2 <- 0.0006943363
CO2 <- 2.674693e-05
pH <- 7.884892
TA <- 0.0021
S <- 30
t <- 15
p <- 10
ae <- aquaenv(S, t, p, SumCO2 = NULL, pH = pH, CO2 = CO2)
ae$SumCO2
ae <- aquaenv(S, t, p, SumCO2 = NULL, pH = pH, fCO2 = fCO2)
ae$SumCO2
ae <- aquaenv(S, t, p, SumCO2 = NULL, pH = pH, TA = TA)
ae$SumCO2
ae <- aquaenv(S, t, p, SumCO2 = NULL, TA = TA, CO2 = CO2)
ae$SumCO2
ae <- aquaenv(S, t, p, SumCO2 = NULL, TA = TA, fCO2 = fCO2)
ae$SumCO2
###################################################
### code chunk number 14: CloningAquaenv
###################################################
S <- 30
t <- 15
SumCO2 <- 0.0020
TA <- 0.00214
ae <- aquaenv(S, t, SumCO2 = SumCO2, TA = TA)
ae$pH
ae1 <- aquaenv(ae = ae) # this is the same
ae1$pH
ae2 <- aquaenv(ae = ae, pH = 9)
c(ae$TA, ae2$TA)
ae3 <- aquaenv(ae = ae, TA = 0.002)
c(ae$pH, ae3$pH)
K_CO2 <- 1e-6
ae4 <- aquaenv(ae = ae, k_co2 = 1e-6)
c(ae$TA, ae4$TA)
###################################################
### code chunk number 15: PreparingInput
###################################################
S <- 10
t <- 15
pH_NBS <- 8.142777
SumCO2molar <- 0.002016803
(pH_free <- convert(pH_NBS, "pHscale", "nbs2free", S = S, t = t))
(SumCO2molin <- convert(SumCO2molar, "conc", "molar2molin", S = S, t = t))
ae <- aquaenv(S, t, SumCO2 = SumCO2molin, pH = pH_free)
ae$pH
ae$SumCO2
###################################################
### code chunk number 16: InputVectors
###################################################
SumCO2 <- 0.0020
pH <- 8
S <- 30
t <- 1:5
p <- 10
ae <- aquaenv(S, t, p, SumCO2 = SumCO2, pH = pH)
rbind(t = ae$t, TA = ae$TA)
###################################################
### code chunk number 17: Selectplot
###################################################
plot(ae, xval = t, xlab = "t/(deg C)",
what = c("pH", "CO2", "HCO3", "CO3"),
mfrow = c(1, 4))
###################################################
### code chunk number 18: MoreInputVectors1 (eval = FALSE)
###################################################
## ae <- aquaenv(S=20:24, t=15, p=10, SumCO2 = SumCO2, pH = pH, dsa = TRUE)
## rbind(ae$S, ae$TA)
###################################################
### code chunk number 19: MoreInputVectors6
###################################################
ae <- aquaenv(20, 10, SumCO2=seq(0.001, 0.002, 0.00025), TA = 0.002)
rbind(ae$SumCO2, ae$pH, ae$HCO3)
###################################################
### code chunk number 20: SumCO2CalcInputVecs1
###################################################
ae <- aquaenv(S = 30, t = 11:15, SumCO2 = NULL, pH = pH, CO2 = CO2,
dsa = TRUE)
ae$SumCO2
###################################################
### code chunk number 21: Dataframe
###################################################
ae <- aquaenv(S = 30, t = 11:15, SumCO2 = NULL, pH = 8, CO2 = 2e-5)
aedataframe <- as.data.frame(ae)
dim(aedataframe)
aedataframe[, 1:3]
aetest <- aquaenv(ae = aedataframe, from.data.frame = TRUE)
###################################################
### code chunk number 22: Elementconversion
###################################################
ae <- aquaenv(S = 30, t = 10)
ae$SumBOH3
ae <- convert(ae, "mol/kg-soln", "umol/kg-H2O", 1e6/ae$molal2molin, "unit")
ae$SumBOH3
###################################################
### code chunk number 23: DSAQuantities1
###################################################
ae <- aquaenv(S = 30, t = 15, d = 10, SumCO2 = 0.002, pH = 8, dsa = TRUE)
###################################################
### code chunk number 24: DSAQuantities2
###################################################
ae$dTAdH
ae$dTAdSumCO2
###################################################
### code chunk number 25: DSAQuantities3
###################################################
ae$dTAdKdKdS
ae$dTAdKdKdSumH2SO4
###################################################
### code chunk number 26: DSAQuantities4
###################################################
ae$c1
###################################################
### code chunk number 27: BufferFactors1
###################################################
BF <- BufferFactors()
names(BF)
BF$dtotX.dpH
###################################################
### code chunk number 28: BufferFactors2
###################################################
ae <- aquaenv(S = 30, t = 15, d = 10, SumCO2 = 0.002, pH = 8.1,
skeleton = TRUE)
BF <- BufferFactors(ae = ae)
BF$RF
###################################################
### code chunk number 29: BufferFactors3
###################################################
ae <- aquaenv(S = 30, t = 15, d = 10, SumCO2 = 0.002, pH = 8.1, dsa = TRUE)
BF <- BufferFactors(ae = ae)
cbind(ae$dTAdH,BF$beta.H)
###################################################
### code chunk number 30: BufferFactors4
###################################################
parameters <- c(DIC = 0.002, Alk = 0.0022)
BF <- BufferFactors(parameters = parameters)
BF$RF
###################################################
### code chunk number 31: BufferFactors5
###################################################
ae <- aquaenv(S = 30, t = 15, d = 10, SumCO2 = 0.002, pH = 8.1,
skeleton = TRUE)
BF <- BufferFactors(ae = ae)
BF$RF
parameters <- c(Alk = 0.0022)
BF_2 <- BufferFactors(ae = ae, parameters = parameters)
BF_2$RF
###################################################
### code chunk number 32: BufferFactors6
###################################################
BF <- BufferFactors(species = c("CO2", "HCO3", "CO3", "SumNH4"))
BF$dtotX.dX
###################################################
### code chunk number 33: BufferFactors7
###################################################
ae <- aquaenv(S = 30, t = 15, d = 10, SumCO2 = 0.002, pH = 8.1,
skeleton = TRUE)
BF <- BufferFactors(ae = ae, species = c("SumCO2", "SumNH4"))
BF$dtotX.dX
###################################################
### code chunk number 34: BufferFactors7
###################################################
BF <- BufferFactors(k1k2 = "roy")
BF$RF
BF <- BufferFactors(k_co2 = 1e-6)
BF$RF
###################################################
### code chunk number 35: Plot1
###################################################
ae <- aquaenv(20:30, 10)
plot(ae, xval = 20:30, xlab = "S", what = c("K_CO2", "K_HCO3", "K_BOH3"),
size = c(10, 2), mfrow = c(1,3))
###################################################
### code chunk number 36: OrdDynModParamList (eval = FALSE)
###################################################
## parameters <- list(
## S = 25 , # psu
## t_min = 5 , # degrees C
## t_max = 25 , # degrees C
##
## k = 0.4 , # 1/d proportionality factor for air-water exchange
## rOx = 0.0000003 , # mol-N/(kg*d) maximal rate of oxic mineralisation
## rNitri = 0.0000002 , # mol-N/(kg*d) maximal rate of nitrification
## rPP = 0.000006 , # mol-N/(kg*d) maximal rate of primary production
##
## ksDINPP = 0.000001 , # mol-N/kg
## ksNH4PP = 0.000001 , # mol-N/kg
##
## D = 0.1 , # 1/d (dispersive) transport coefficient
##
## O2_io = 0.000296 , # mol/kg-soln
## NO3_io = 0.000035 , # mol/kg-soln
## SumNH4_io = 0.000008 , # mol/kg-soln
## SumCO2_io = 0.002320 , # mol/kg-soln
## TA_io = 0.002435 , # mol/kg-soln
##
## C_Nratio = 8 , # mol C/mol N C:N ratio of organic matter
##
## a = 30 , # time at which PP begins
## b = 50 , # time at which PP stops again
##
## modeltime = 100 # duration of the model
## )
###################################################
### code chunk number 37: OrdDynModFunction (eval = FALSE)
###################################################
##
## temperature <- with (parameters,
## approxfun(x = 0:101,
## y = c(seq(t_min, t_max, (t_max-t_min)/50),
## seq(t_max, t_min, -(t_max-t_min)/50)))
## )
##
## boxmodel <- function(time, state, parameters) {
## with (
## as.list(c(state, parameters)), {
## t <- temperature(time)
## ae <- aquaenv(S = S, t = t, SumCO2 = SumCO2,
## SumNH4 = SumNH4, TA = TA)
##
## ECO2 <- k * (ae$CO2_sat - ae$CO2)
## EO2 <- k * (ae$O2_sat - O2)
##
## # dilution
## TO2 <- D*(O2_io - O2)
## TNO3 <- D*(NO3_io - NO3)
## TSumNH4 <- D*(SumNH4_io - SumNH4)
## TTA <- D*(TA_io - TA)
## TSumCO2 <- D*(SumCO2_io - SumCO2)
##
## RNit <- rNitri * SumNH4/(SumNH4+1e-8)
##
## ROx <- rOx
## ROxCarbon <- ROx * C_Nratio
##
## pNH4PP <- 0
## RPP <- 0
##
## if ((time > a) && (time < b)) {
## RPP <- rPP * ((SumNH4+NO3)/(ksDINPP + (SumNH4+NO3)))
## pNH4PP <- SumNH4/(SumNH4+NO3)
## }
##
## RPPCarbon <- RPP * C_Nratio
##
## dO2 <- TO2 + EO2 - ROxCarbon - 2*RNit + (2-2*pNH4PP)*RPP + RPPCarbon
## dNO3 <- TNO3 + RNit -(1-pNH4PP)*RPP
##
## dSumCO2 <- TSumCO2 + ECO2 + ROxCarbon - RPPCarbon
## dSumNH4 <- TSumNH4 + ROx - RNit - pNH4PP*RPP
##
## dTA <- TTA + ROx - 2*RNit -(2*pNH4PP-1)*RPP
##
## ratesofchanges <- c(dO2, dNO3, dSumNH4, dSumCO2, dTA)
##
## return(list(ratesofchanges, ae[c("t", "NH4", "NH3", "pH")]))
## } )
## }
###################################################
### code chunk number 38: OrdDynModSolution (eval = FALSE)
###################################################
## initialstate <- with (parameters,
## c(O2=O2_io, NO3=NO3_io, SumNH4=SumNH4_io, SumCO2=SumCO2_io, TA=TA_io))
##
## times <- 1:100
## output <- vode(initialstate,times,boxmodel,parameters, hmax = 1)
###################################################
### code chunk number 39: OrdDynModePlotting (eval = FALSE)
###################################################
## plot(output)
###################################################
### code chunk number 40: SinglePHModParams
###################################################
parameters <- list(
S = 25 , # psu
t = 15 , # degrees C
k = 0.4 , # 1/d proportionality factor for air-water exchange
rOx = 0.0000003 , # mol-N/(kg*d) maximal rate of oxic mineralisation
rNitri = 0.0000002 , # mol-N/(kg*d) maximal rate of nitrification
rPP = 0.0000006 , # mol-N/(kg*d) maximal rate of primary production
ksSumNH4 = 0.000001 , # mol-N/kg
D = 0.1 , # 1/d (dispersive) transport coefficient
SumNH4_io = 0.000008 , # mol/kg-soln
SumCO2_io = 0.002320 , # mol/kg-soln
TA_io = 0.002435 , # mol/kg-soln
C_Nratio = 8 , # mol C/mol N C:N ratio of organic matter
a = 5 , # time from which PP begins
b = 20 , # time where PP shuts off again
modeltime = 30 # duration of the model
)
###################################################
### code chunk number 41: SinglePHModFunction
###################################################
boxmodel <- function(timestep, currentstate, parameters)
{
with (
as.list(c(currentstate,parameters)),
{
# the "classical" implicit pH calculation method is applied in aquaenv
ae <- aquaenv(S=S, t=t, SumCO2=sumCO2,
SumNH4=sumNH4, TA=alkalinity, dsa=TRUE)
ECO2 <- k * (ae$CO2_sat - ae$CO2)
RNit <- rNitri
ROx <- rOx
if ((timestep > a) && (timestep < b))
RPP <- rPP * (sumNH4/(ksSumNH4 + sumNH4))
else
RPP <- 0
dsumCO2 <- ECO2 + C_Nratio*ROx - C_Nratio*RPP
dsumNH4 <- ROx - RNit - RPP
dalkalinity <- ROx - 2*RNit - RPP
# The DSA pH
dH <- (dalkalinity - (dsumCO2*ae$dTAdSumCO2 + dsumNH4*ae$dTAdSumNH4))/ae$dTAdH
DSApH <- -log10(H)
# The DSA pH using pH dependent fractional stoichiometry (= using partitioning coefficients)
rhoHECO2 <- ae$c2 + 2*ae$c3
rhoHRNit <- 1 + ae$n1
rhoHROx <- C_Nratio * (ae$c2 + 2*ae$c3) - ae$n1
rhoHRPP <- -(C_Nratio * (ae$c2 + 2*ae$c3)) + ae$n1
dH_ECO2 <- rhoHECO2*ECO2/(-ae$dTAdH)
dH_RNit <- rhoHRNit*RNit/(-ae$dTAdH)
dH_ROx <- rhoHROx*ROx /(-ae$dTAdH)
dH_RPP <- rhoHRPP*RPP /(-ae$dTAdH)
dH_stoich <- dH_ECO2 + dH_RNit + dH_ROx + dH_RPP
DSAstoichpH <- -log10(H_stoich)
ratesofchanges <- c(dsumNH4, dsumCO2, dalkalinity, dH, dH_stoich)
processrates <- c(ECO2=ECO2, RNit=RNit, ROx=ROx, RPP=RPP)
DSA <- c(DSApH=DSApH, rhoHECO2=rhoHECO2, rhoHRNit=rhoHRNit, rhoHROx=rhoHROx,
rhoHRPP=rhoHRPP, dH_ECO2=dH_ECO2, dH_RNit=dH_RNit, dH_ROx=dH_ROx,
dH_RPP=dH_RPP, DSAstoichpH=DSAstoichpH)
return(list(ratesofchanges, processrates, DSA, ae))
}
)
}
###################################################
### code chunk number 42: SinglPHModSolution
###################################################
with (as.list(parameters),
{
H_init <<- 10^(-(aquaenv(S=S, t=t, SumCO2=SumCO2_io, SumNH4=SumNH4_io, TA=TA_io,
speciation=FALSE)$pH))
initialstate <<- c(sumNH4=SumNH4_io, sumCO2=SumCO2_io, alkalinity =TA_io, H=H_init,
H_stoich=H_init)
times <<- c(0:modeltime)
})
output <- vode(initialstate, times, boxmodel, parameters, hmax=1)
###################################################
### code chunk number 43: SinglePHModePlotting1
###################################################
select <- c("sumCO2", "alkalinity", "sumNH4", "RPP", "dTAdH", "dTAdSumCO2",
"dTAdSumNH4","rhoHECO2", "rhoHRNit", "rhoHROx","dH_ECO2","dH_RNit",
"dH_RPP","pH", "DSApH", "DSAstoichpH")
plot(output, which = select, xlab="time/d", mfrow=c(4,4))
###################################################
### code chunk number 44: SinglepHModPlotting2
###################################################
what <- c("dH_ECO2", "dH_RNit", "dH_ROx", "dH_RPP")
plot(aquaenv(ae=as.data.frame(output), from.data.frame=TRUE),
xval = times, what = what, xlab = "time/d", size = c(7,5),
ylab = "mol-H/(kg-soln*d)", legendposition = "bottomright", cumulative = TRUE)
###################################################
### code chunk number 45: SinplePHModConsistencyCheck
###################################################
matplot(output[, "time"],
output[, c("pH", "DSApH", "DSAstoichpH")], type = "l", lty = 1, lwd = 2)
###################################################
### code chunk number 46: ImplicitPHModParams (eval = FALSE)
###################################################
## parameters <- list(
## t = 15 , # degrees C
## S = 35 , # psu
##
## SumCO2_t0 = 0.002 , # mol/kg-soln (comparable to Wang2005)
## TA_t0 = 0.0022 , # mol/kg-soln (comparable to Millero1998)
##
## kc = 0.5 , # 1/d proportionality factor for air-water exchange
## kp = 0.000001 , # mol/(kg-soln*d) max rate of calcium carbonate precipitation
## n = 2.0 , # - exponent for kinetic rate law of precipitation
##
## modeltime = 20 , # d duration of the model
## outputsteps = 100 # number of outputsteps
## )
###################################################
### code chunk number 47: ImplicitPHModFunction (eval = FALSE)
###################################################
## boxmodel <- function(timestep, currentstate, parameters)
## {
## with (
## as.list(c(currentstate,parameters)),
## {
## ae <- aquaenv(S=S, t=t, SumCO2=SumCO2, TA=TA, SumSiOH4=0,
## SumBOH3=0, SumH2SO4=0, SumHF=0)
##
## Rc <- kc * ((ae$CO2_sat) - (ae$CO2))
## Rp <- kp * (1-ae$omega_calcite)^n
##
## dSumCO2 <- Rc - Rp
## dTA <- -2*Rp
##
## ratesofchanges <- c(dSumCO2, dTA)
##
## processrates <- c(Rc=Rc, Rp=Rp)
##
## return(list(ratesofchanges, list(processrates, ae)))
## }
## )
## }
###################################################
### code chunk number 48: ImplicitPHModSolution (eval = FALSE)
###################################################
## with (as.list(parameters),
## {
## initialstate <<- c(SumCO2=SumCO2_t0, TA=TA_t0)
## times <<- seq(0,modeltime,(modeltime/outputsteps))
## })
## output <<- vode(initialstate,times,boxmodel,parameters, hmax=1)
###################################################
### code chunk number 49: ExplicitPHModParams (eval = FALSE)
###################################################
## parameters <- list(
## S = 35 , # psu
## t = 15 , # degrees C
##
## SumCO2_t0 = 0.002 , # mol/kg-soln (comparable to Wang2005)
## TA_t0 = 0.0022 , # mol/kg-soln (comparable to Millero1998)
##
## kc = 0.5 , # 1/d proportionality factor for air-water exchange
## kp = 0.000001 , # mol/(kg-soln*d) max rate of calcium carbonate precipitation
## n = 2.0 , # - exponent for kinetic rate law of precipitation
##
## modeltime = 20 , # d duration of the model
## outputsteps = 100 # number of outputsteps
## )
###################################################
### code chunk number 50: ExplicitPHModFunction (eval = FALSE)
###################################################
## boxmodel <- function(timestep, currentstate, parameters)
## {
## with (
## as.list(c(currentstate,parameters)),
## {
## ae <- aquaenv(S=S, t=t, SumCO2=SumCO2, pH=-log10(H), SumSiOH4=0,
## SumBOH3=0, SumH2SO4=0, SumHF=0, dsa=TRUE)
##
## Rc <- kc * ((ae$CO2_sat) - (ae$CO2))
## Rp <- kp * (1-ae$omega_calcite)^n
##
## dSumCO2 <- Rc - Rp
##
## dHRc <- ( -(ae$dTAdSumCO2*Rc ))/ae$dTAdH
## dHRp <- (-2*Rp -(ae$dTAdSumCO2*(-Rp)))/ae$dTAdH
## dH <- dHRc + dHRp
##
## ratesofchanges <- c(dSumCO2, dH)
##
## processrates <- c(Rc=Rc, Rp=Rp)
## outputvars <- c(dHRc=dHRc, dHRp=dHRp)
##
## return(list(ratesofchanges, list(processrates, outputvars, ae)))
## }
## )
## }
###################################################
### code chunk number 51: ExplicitPHModSolution (eval = FALSE)
###################################################
## with (as.list(parameters),
## {
## aetmp <- aquaenv(S=S, t=t, SumCO2=SumCO2_t0, TA=TA_t0, SumSiOH4=0, SumBOH3=0, SumH2SO4=0, SumHF=0)
## H_t0 <- 10^(-aetmp$pH)
##
## initialstate <<- c(SumCO2=SumCO2_t0, H=H_t0)
## times <<- seq(0,modeltime,(modeltime/outputsteps))
## })
## output <- vode(initialstate,times,boxmodel,parameters, hmax=1)
###################################################
### code chunk number 52: FracStoichModParams (eval = FALSE)
###################################################
## parameters <- list(
## S = 35 , # psu
## t = 15 , # degrees C
##
## SumCO2_t0 = 0.002 , # mol/kg-soln (comparable to Wang2005)
## TA_t0 = 0.0022 , # mol/kg-soln (comparable to Millero1998)
##
## kc = 0.5 , # 1/d proportionality factor for air-water exchange
## kp = 0.000001 , # mol/(kg-soln*d) max rate of calcium carbonate precipitation
## n = 2.0 , # - exponent for kinetic rate law of precipitation
##
## modeltime = 20 , # d duration of the model
## outputsteps = 100 # number of outputsteps
## )
###################################################
### code chunk number 53: FracStoichModFunction (eval = FALSE)
###################################################
## boxmodel <- function(timestep, currentstate, parameters)
## {
## with (
## as.list(c(currentstate,parameters)),
## {
## ae <- aquaenv(S=S, t=t, SumCO2=SumCO2, pH=-log10(H), SumSiOH4=0,
## SumBOH3=0, SumH2SO4=0, SumHF=0, dsa=TRUE)
##
## Rc <- kc * ((ae$CO2_sat) - (ae$CO2))
## Rp <- kp * (1-ae$omega_calcite)^n
##
## dSumCO2 <- Rc - Rp
##
## rhoc <- ae$c2 + 2*ae$c3
## rhop <- 2*ae$c1 + ae$c2
##
## dHRc <- rhoc*Rc/(-ae$dTAdH)
## dHRp <- rhop*Rp/(-ae$dTAdH)
## dH <- dHRc + dHRp
##
## ratesofchanges <- c(dSumCO2, dH)
##
## processrates <- c(Rc=Rc, Rp=Rp)
## outputvars <- c(dHRc=dHRc, dHRp=dHRp, rhoc=rhoc, rhop=rhop)
##
## return(list(ratesofchanges, list(processrates, outputvars, ae)))
## }
## )
## }
###################################################
### code chunk number 54: FracStoichModSolution (eval = FALSE)
###################################################
## with (as.list(parameters),
## {
## aetmp <- aquaenv(S=S, t=t, SumCO2=SumCO2_t0, TA=TA_t0, SumSiOH4=0,
## SumBOH3=0, SumH2SO4=0, SumHF=0)
## H_t0 <- 10^(-aetmp$pH)
##
## initialstate <<- c(SumCO2=SumCO2_t0, H=H_t0)
## times <<- seq(0,modeltime,(modeltime/outputsteps))
## output <<- as.data.frame(vode(initialstate,times,boxmodel,parameters, hmax=1))
## })
###################################################
### code chunk number 55: HClTit1
###################################################
ae_init <- aquaenv(S = 35, t = 15, SumCO2 = 0.0035, SumNH4 = 0.00002, pH = 11.3)
###################################################
### code chunk number 56: HClTit2
###################################################
ae <- titration(ae_init, mass_sample = 0.01, mass_titrant = 0.02,
conc_titrant = 0.01, S_titrant = 0.5, steps = 100)
###################################################
### code chunk number 57: HClTit3
###################################################
what <- c("TA", "pH", "CO2", "HCO3", "CO3", "BOH3", "BOH4", "OH",
"NH4", "NH3", "H2SO4", "HSO4", "SO4", "HF", "F", "fCO2")
plot(ae, xval = ae$delta_mass_titrant, xlab = "HCl solution added [kg]",
what = what, size = c(12,8), mfrow = c(4,4))
###################################################
### code chunk number 58: HClTit4 (eval = FALSE)
###################################################
## plot(ae, xval = ae$delta_conc_titrant, what = what,
## xlab = "[HCl] offset added [mol/kg-soln]",
## size = c(14,10), mfrow = c(4,4))
## plot(ae, xval=ae$delta_moles_titrant, xlab = "HCl added [mol]",
## what = what, size = c(14,10), mfrow = c(4,4))
###################################################
### code chunk number 59: HClTit5
###################################################
plot(ae, xval = ae$pH, xlab = "free scale pH", what = what,
size = c(12,8), mfrow = c(4,4))
###################################################
### code chunk number 60: HClTit6
###################################################
plot(ae, bjerrum = TRUE)
###################################################
### code chunk number 61: HClTit7
###################################################
what <- c("CO2", "HCO3", "CO3")
plot(ae, what = what, bjerrum = TRUE, lwd = 4,
palette = c("cyan", "magenta", "yellow"),
bg = "gray", legendinset = 0.1, legendposition = "topleft")
###################################################
### code chunk number 62: HClTit9
###################################################
what <- c("CO2", "HCO3", "CO3", "BOH3", "BOH4", "OH",
"NH4", "NH3", "H2SO4", "HSO4", "SO4", "HF", "F")
plot(ae, what = what, bjerrum = TRUE, log = TRUE)
###################################################
### code chunk number 63: HClTit10
###################################################
plot(ae, what = what, bjerrum = TRUE, log = TRUE, ylim = c(-6,-1),
legendinset = 0, lwd = 3,
palette = c(1, 3, 4, 5, 6, colors()[seq(100,250,6)]))
###################################################
### code chunk number 64: NaOHTit1 (eval = FALSE)
###################################################
## ae <- titration(aquaenv(S = 35, t = 15, SumCO2 = 0.0035, SumNH4 = 0.00002, pH = 2),
## mass_sample = 0.01, mass_titrant = 0.02, conc_titrant = 0.01,
## S_titrant = 0.5, steps = 50, type = "NaOH")
###################################################
### code chunk number 65: NaOHTit2 (eval = FALSE)
###################################################
## plot(ae, xval = ae$delta_mass_titrant, xlab = "NaOH solution added [kg]",
## mfrow = c(10,10))
###################################################
### code chunk number 66: NaOHTit3 (eval = FALSE)
###################################################
## what <- c("TA", "pH", "CO2", "HCO3", "CO3", "BOH3", "BOH4", "OH",
## "NH4", "NH3", "H2SO4", "HSO4", "SO4", "HF", "F", "fCO2")
## plot(ae, xval = ae$delta_mass_titrant, xlab = "NaOH solution added [kg]",
## what = what, size = c(12,8), mfrow = c(4,4))
## plot(ae, xval = ae$pH, xlab = "free scale pH", what = what,
## size = c(12,8), mfrow = c(4,4))
###################################################
### code chunk number 67: NaOHTit4 (eval = FALSE)
###################################################
## what <- c("CO2", "HCO3", "CO3")
## plot(ae, what=what, bjerrum=TRUE)
###################################################
### code chunk number 68: NaOHTit5 (eval = FALSE)
###################################################
## what <- c("CO2", "HCO3", "CO3", "BOH3", "BOH4", "OH",
## "NH4", "NH3", "H2SO4", "HSO4", "SO4", "HF", "F")
## plot(ae, what = what, bjerrum = TRUE, log = TRUE, ylim = c(-6,-1),
## legendinset = 0, lwd = 3, palette = c(1,3,4,5,6,colors()[seq(100,250,6)]))
###################################################
### code chunk number 69: TextbookTit1
###################################################
ae <- titration(aquaenv(S = 35, t = 15, SumCO2 = 0.0035, SumNH4 = 0.00002, pH = 11.3),
mass_sample = 100, mass_titrant = 0.5, conc_titrant = 3,
S_titrant = 0.5, steps = 100)
###################################################
### code chunk number 70: TextbookTit2 (eval = FALSE)
###################################################
## plot(ae, xval = ae$delta_mass_titrant,
## xlab = "HCl solution added [kg]", mfrow = c(10, 10))
###################################################
### code chunk number 71: TextbookTit3 (eval = FALSE)
###################################################
## what <- c("TA", "pH", "CO2", "HCO3", "CO3", "BOH3", "BOH4", "OH",
## "NH4", "NH3", "H2SO4", "HSO4", "SO4", "HF", "F", "fCO2")
## plot(ae, xval = ae$delta_mass_titrant, xlab = "HCl solution added [kg]",
## what = what, size = c(12, 8), mfrow = c(4,4))
## plot(ae, xval = ae$pH, xlab = "free scale pH", what = what,
## size = c(12,8), mfrow = c(4,4))
## plot(ae, xval = ae$delta_conc_titrant, xlab = "[HCl] offset added [mol/kg-soln]",
## what = what, size = c(12,8), mfrow = c(4,4))
## plot(ae, xval = ae$delta_moles_titrant, xlab = "HCl added [mol]",
## what = what, size = c(12,8), mfrow = c(4,4))
###################################################
### code chunk number 72: TextbookTit4 (eval = FALSE)
###################################################
## plot(ae, bjerrum=TRUE)
## what <- c("CO2", "HCO3", "CO3")
## plot(ae, what = what, bjerrum = TRUE)
## plot(ae, what = what, bjerrum = TRUE, lwd = 4,
## palette=c("cyan", "magenta", "yellow"), bg = "gray",
## legendinset = 0.1, legendposition = "topleft")
## what <- c("CO2", "HCO3", "CO3", "BOH3", "BOH4", "OH",
## "NH4", "NH3", "H2SO4", "HSO4", "SO4", "HF", "F")
## plot(ae, what = what, bjerrum = TRUE, log = TRUE)
###################################################
### code chunk number 73: TextbookTit5
###################################################
what <- c("CO2", "HCO3", "CO3", "BOH3", "BOH4", "OH",
"NH4", "NH3", "H2SO4", "HSO4", "SO4", "HF", "F")
plot(ae, what = what, bjerrum = TRUE, log = TRUE, ylim = c(-6,-1),
legendinset = 0, lwd = 3, palette = c(1,3,4,5,6,colors()[seq(100,250,6)]))
###################################################
### code chunk number 74: TAfit1
###################################################
ae_init <- aquaenv(S = 35, t = 15, SumCO2 = 0.0035, SumNH4 = 0.00002, pH = 11.3)
ae <- titration(ae_init, mass_sample = 0.01, mass_titrant = 0.02,
conc_titrant = 0.01, S_titrant = 0.5, steps = 100)
plot(ae, xval = ae$delta_mass_titrant, xlab = "HCl solution added [kg]",
what = "pH", xlim = c(0,0.015))
par(new = TRUE)
plot(ae$delta_mass_titrant[1:100], diff(ae$pH), type = "l",
col = "red", xlim = c(0,0.015), ylab = "", xlab = "", yaxt = "n")
par(new = TRUE)
plot(ae$delta_mass_titrant[2:100], diff(diff(ae$pH)), type = "l",
col = "blue", xlim = c(0,0.015), ylab = "", xlab = "", yaxt = "n")
abline(h =0, col = "blue")
abline(v = ae$TA[[1]])
abline(v = ae$TA[[1]] - ae$SumCO2[[1]])
###################################################
### code chunk number 75: TAfit2
###################################################
plot(ae, xval = ae$delta_mass_titrant, xlab = "HCl solution added [kg]",
what = "pH", xlim = c(0,0.015))
prot1 <- c()
for (i in 1:length(ae$pH))
prot1 <- c(prot1, (10^-(ae$pH[[i]])+ae$HSO4[[i]]+ae$HF[[i]]+
ae$CO2[[i]]-ae$CO3[[i]]-ae$BOH4[[i]]-ae$OH[[i]]))
par(new = TRUE)
plot(ae$delta_mass_titrant, prot1, type = "l", col = "blue", xlim = c(0,0.015),
ylab = "", xlab = "", yaxt = "n", ylim = c(-0.015,0.015))
prot2 <- c()
for (i in 1:length(ae$pH))
prot2 <- c(prot2, (10^-(ae$pH[[i]])+ae$HSO4[[i]]+ae$HF[[i]]-
ae$HCO3[[i]]-2*ae$CO3[[i]]-ae$BOH4[[i]]-ae$OH[[i]]))
par(new = TRUE)
plot(ae$delta_mass_titrant, prot2, type = "l", col = "green", xlim = c(0,0.015),
ylab = "", xlab = "", yaxt = "n", ylim = c(-0.015,0.015))
abline(v = ae$TA[[1]])
abline(v = ae$TA[[1]] - ae$SumCO2[[1]])
abline(h = 0)
###################################################
### code chunk number 76: TAfit3
###################################################
ae <- titration(aquaenv(S = 35, t = 15, SumCO2 = 0.0035, SumNH4 = 0.00002,
pH = 11.3),
mass_sample = 100, mass_titrant = 0.5, conc_titrant = 3,
S_titrant = 0.5, steps = 100)
plot(ae, xval = ae$delta_mass_titrant, xlab = "HCl solution added [kg]",
what = "pH", xlim = c(0, 0.5))
prot1 <- c()
for (i in 1:length(ae$pH))
prot1 <- c(prot1, (10^-(ae$pH[[i]])+ae$HSO4[[i]]+ae$HF[[i]]+
ae$CO2[[i]]-ae$CO3[[i]]-ae$BOH4[[i]]-ae$OH[[i]]))
par(new = TRUE)
plot(ae$delta_mass_titrant, prot1, type = "l", col = "blue",
xlim = c(0,0.5), ylab = "", xlab = "", yaxt = "n",
ylim = c(-0.015, 0.015))
prot2 <- c()
for (i in 1:length(ae$pH))
prot2 <- c(prot2, (10^-(ae$pH[[i]])+ae$HSO4[[i]]+ae$HF[[i]]-
ae$HCO3[[i]]-2*ae$CO3[[i]]-ae$BOH4[[i]]-ae$OH[[i]]))
par(new = TRUE)
plot(ae$delta_mass_titrant, prot2, type = "l", col = "green",
xlim = c(0,0.5), ylab = "", xlab = "", yaxt = "n",
ylim = c(-0.015,0.015))
abline(v = (ae$TA[[1]]*100/3))
abline(v = ((ae$TA[[1]] - ae$SumCO2[[1]])*100/3))
abline(h = 0)
###################################################
### code chunk number 77: TAfit4
###################################################
initial_ae <- aquaenv(S = 35, t = 15, SumCO2 = 0.002, TA = 0.0022)
ae <- titration(initial_ae, mass_sample = 0.01, mass_titrant = 0.003,
conc_titrant = 0.01, S_titrant = 0.5, steps = 20)
###################################################
### code chunk number 78: TAfit5
###################################################
titcurve <- cbind(ae$delta_mass_titrant, ae$pH)
###################################################
### code chunk number 79: TAfit6
###################################################
fit1 <- TAfit(initial_ae, titcurve, conc_titrant = 0.01,
mass_sample = 0.01, S_titrant = 0.5)
fit1
###################################################
### code chunk number 80: TAfit6a (eval = FALSE)
###################################################
## initial_ae_ <- aquaenv(S = 35, t = 15, SumCO2 = 0.002, TA = 0.0022,
## k1k2 = "lueker", khf = "perez")
## ae_ <- titration(initial_ae_, mass_sample = 0.01, mass_titrant = 0.003,
## conc_titrant = 0.01,
## S_titrant = 0.5, steps = 20, k1k2 = "roy",
## khf = "perez")
## titcurve_ <- cbind(ae_$delta_mass_titrant, ae_$pH)
## fit1_ <- TAfit(initial_ae_, titcurve_, conc_titrant = 0.01,
## mass_sample = 0.01, S_titrant = 0.5, k1k2 = "roy",
## khf = "perez", verbose = TRUE)
## fit1_
###################################################
### code chunk number 81: TAfit7 (eval = FALSE)
###################################################
## ae <- titration(initial_ae, mass_sample = 0.01, mass_titrant = 0.003,
## conc_titrant = 0.01, steps = 20, seawater_titrant = TRUE)
## titcurve <- cbind(ae$delta_mass_titrant, ae$pH)
## tottitcurve <- cbind(ae$pH, convert(ae$pH, "pHscale", "free2tot", S = 35, t = 15))
## Etitcurve <- cbind(ae$delta_mass_titrant,
## (0.4 - ((PhysChemConst$R/10)*initial_ae$T/PhysChemConst$F)*
## log(10^-tottitcurve[,2])))
###################################################
### code chunk number 82: TAfit8 (eval = FALSE)
###################################################
## fit2 <- TAfit(initial_ae, Etitcurve, conc_titrant = 0.01, mass_sample = 0.01,
## Evals = TRUE, verbose = TRUE, seawater_titrant = TRUE)
## fit2
###################################################
### code chunk number 83: TAfit9
###################################################
fit3 <- TAfit(initial_ae, titcurve, conc_titrant = 0.01, mass_sample = 0.01,
S_titrant = 0.5, K_CO2fit = TRUE)
fit3
initial_ae$K_CO2
###################################################
### code chunk number 84: TAfit10
###################################################
ae <- titration(initial_ae, mass_sample = 0.01, mass_titrant = 0.003,
conc_titrant = 0.01, steps = 20, seawater_titrant = TRUE)
titcurve <- cbind(ae$delta_mass_titrant, ae$pH)
fit4 <- TAfit(initial_ae, titcurve, conc_titrant = 0.01, mass_sample = 0.01,
K_CO2fit = TRUE, seawater_titrant = TRUE)
fit4
###################################################
### code chunk number 85: TAfit11 (eval = FALSE)
###################################################
## Etitcurve <- cbind(titcurve[,1], (0.4 - ((PhysChemConst$R/10)*initial_ae$T/
## PhysChemConst$F)*log(10^-titcurve[,2])))
## fit5 <- TAfit(initial_ae, Etitcurve, conc_titrant = 0.01, mass_sample = 0.01,
## K_CO2fit = TRUE, seawater_titrant = TRUE, Evals = TRUE)
## fit5
###################################################
### code chunk number 86: TAfit12 (eval = FALSE)
###################################################
## neqsptitcurve <- rbind(titcurve[1:9,], titcurve[11:20,])
## fit6 <- TAfit(initial_ae, neqsptitcurve, conc_titrant = 0.01,
## mass_sample = 0.01, seawater_titrant = TRUE, equalspaced = FALSE,
## verbose = TRUE, debug = TRUE)
## fit6
###################################################
### code chunk number 87: TAfit13
###################################################
noisetitcurve <- titcurve * rnorm(length(titcurve), mean = 1, sd = 0.01) #one percent error possible
fit7 <- TAfit(initial_ae, noisetitcurve, conc_titrant = 0.01, mass_sample = 0.01,
seawater_titrant = TRUE, verbose = FALSE, debug = TRUE)
fit7
###################################################
### code chunk number 88: TAfit14
###################################################
ylim <- range(noisetitcurve[,2], calc)
xlim <- range(tit$delta_mass_titrant, noisetitcurve[,1])
plot(noisetitcurve[,1], noisetitcurve[,2], xlim = xlim, ylim = ylim,
type = "l", xlab = "delta mass titrant", ylab = "pH (free scale)")
par(new = TRUE)
plot(tit$delta_mass_titrant, calc, xlim = xlim, ylim = ylim, type = "l",
col = "red", xlab = "", ylab = "")
###################################################
### code chunk number 89: TAfit15
###################################################
conc_titrant <- 0.3 # mol/kg-soln
mass_sample <- 0.2 # kg
S_titrant <- 14.835 # is aequivalent to the ionic strength of 0.3 mol/kg-soln
SumBOH3 <- 0.00042 # mol/kg-soln
SumH2SO4 <- 0.02824 # mol/kg-soln
SumHF <- 0.00007 # mol/kg-soln
###################################################
### code chunk number 90: TAfit16
###################################################
sam <- cbind(sample_dickson1981[,1]/1000, sample_dickson1981[,2]) # convert mass of titrant from g to kg
###################################################
### code chunk number 91: TAfit17
###################################################
dicksonfit <- TAfit(aquaenv(S = 35, t = 25, SumBOH3 = SumBOH3,
SumH2SO4 = SumH2SO4, SumHF=SumHF), sam, conc_titrant,
mass_sample, S_titrant = S_titrant, debug = TRUE)
dicksonfit
###################################################
### code chunk number 92: TAfit18
###################################################
dicksontitration1 <- titration(aquaenv(S = 35, t = 25, SumCO2 = 0.00220,
SumBOH3 = SumBOH3, SumH2SO4 = SumH2SO4, SumHF = SumHF, TA = 0.00245),
mass_sample = mass_sample, mass_titrant = 0.0025,
conc_titrant = conc_titrant, steps = 50, type = "HCl")
###################################################
### code chunk number 93: TAfit19
###################################################
dicksontitration2 <- titration(aquaenv(S = 35, t = 25, SumCO2 = 0.00220,
SumBOH3 = SumBOH3, SumH2SO4 = SumH2SO4, SumHF = SumHF, TA = 0.00245),
mass_sample = mass_sample, mass_titrant = 0.0025,
conc_titrant = conc_titrant, S_titrant = S_titrant, steps = 50, type = "HCl")
###################################################
### code chunk number 94: TAfit20
###################################################
plot(dicksontitration1, xval = dicksontitration1$delta_mass_titrant,
what = "pH", xlim = c(0,0.0025), ylim = c(3,8.2), col = "red",
xlab = "delta mass titrant")
par(new = TRUE)
plot(dicksontitration2, xval = dicksontitration2$delta_mass_titrant,
what = "pH", xlim = c(0,0.0025), ylim = c(3,8.2), col = "blue", xlab = "")
par(new = TRUE)
plot(sam[,1], sam[,2], type = "l", xlim = c(0,0.0025),
ylim = c(3,8.2), xlab = "", ylab = "")
###################################################
### code chunk number 95: TAfit21
###################################################
plot(dicksontitration2$pH - sam[,2])
###################################################
### code chunk number 96: TAfit22
###################################################
dicksonfit2 <- TAfit(aquaenv(S = 35, t = 25, SumBOH3 = SumBOH3,
SumH2SO4 = SumH2SO4, SumHF = SumHF), sam, conc_titrant,
mass_sample, S_titrant = S_titrant, debug = TRUE, K_CO2fit = TRUE)
dicksonfit2
###################################################
### code chunk number 97: AquaEnv.rnw:1763-1764
###################################################
###################################################
### code chunk number 98: TAfit23
###################################################
dicksontitration3 <- titration(aquaenv(S = 35, t = 25, SumCO2 = 0.00220,
SumBOH3 = SumBOH3, SumH2SO4 = SumH2SO4, SumHF = SumHF, TA = 0.00245,
k_w = 4.32e-14, k_co2 = 1e-6, k_hco3 = 8.20e-10, k_boh3 = 1.78e-9,
k_hso4 = (1/1.23e1), k_hf = (1/4.08e2)),
mass_sample = mass_sample, mass_titrant = 0.0025, conc_titrant = conc_titrant,
steps = 50, type = "HCl", S_titrant = S_titrant,
k_w = 4.32e-14, k_co2 = 1e-6, k_hco3 = 8.20e-10, k_boh3 = 1.78e-9,
k_hso4 = (1/1.23e1), k_hf = (1/4.08e2))
plot(dicksontitration3, xval = dicksontitration3$delta_mass_titrant,
what = "pH", xlim = c(0,0.0025), ylim = c(3,8.2), col = "blue",
xlab = "delta mass titrant")
par(new = TRUE)
plot(sam[,1], sam[,2], type = "l", xlim = c(0,0.0025), ylim = c(3,8.2),
xlab = "", ylab = "")
###################################################
### code chunk number 99: TAfit24
###################################################
plot(dicksontitration3$pH - sam[,2])
###################################################
### code chunk number 100: TAfit25
###################################################
dicksonfit3 <- TAfit(aquaenv(S = 35, t = 25, SumBOH3 = SumBOH3, SumH2SO4 = SumH2SO4,
SumHF = SumHF, k_w = 4.32e-14, k_co2 = 1e-6, k_hco3 = 8.20e-10,
k_boh3 = 1.78e-9, k_hso4 = (1/1.23e1), k_hf = (1/4.08e2)),
sam, conc_titrant, mass_sample, S_titrant = S_titrant, debug = TRUE,
k_w = 4.32e-14, k_co2 = 1e-6, k_hco3 = 8.20e-10, k_boh3 = 1.78e-9,
k_hso4 = (1/1.23e1), k_hf = (1/4.08e2))
dicksonfit3
###################################################
### code chunk number 101: extend1
###################################################
simpletitration <- function(aquaenv, # an object of class aquaenv: minimal definition,
# contains all information about the system:
# T, S, d, total concentrations of nutrients etc
volume, # the volume of the (theoretical) titration vessel in l
amount, # the amount of titrant added in mol
steps, # the amount of steps the amount of titrant is added in
type) # the type of titrant: either "HCl" or "NaOH"
{
directionTAchange <- switch(type, HCl = -1, NaOH = +1)
TAconcchangeperstep <- convert(((amount/steps)/volume), "conc", "molar2molin", aquaenv$t, aquaenv$S)
aquaenvtemp <- aquaenv
for (i in 1:steps)
{
TA <- aquaenvtemp$TA + (directionTAchange * TAconcchangeperstep)
aquaenvtemp <- aquaenv(ae=aquaenvtemp, TA=TA)
aquaenv <- merge(aquaenv, aquaenvtemp)
}
aquaenv[["DeltaCTitrant"]] <- convert((amount/volume)/steps*(1:(steps+1)),
"conc", "molar2molin", aquaenv$t, aquaenv$S)
return(aquaenv) # object of class aquaenv which contains a titration simulation
}
###################################################
### code chunk number 102: extend2
###################################################
ae <- simpletitration(aquaenv(S = 35, t = 15, SumCO2 = 0.003500,
SumNH4 = 0.000020, pH = 11.3),
volume =100, amount = 1.5, steps = 100, type = "HCl")
what <- c("CO2", "HCO3", "CO3", "BOH3", "BOH4", "OH", "NH4", "NH3",
"H2SO4", "HSO4", "SO4", "HF", "F")
plot(ae, what = what, bjerrum = TRUE, log = TRUE, ylim = c(-6,-1),
legendinset = 0, lwd = 3, palette = c(1,3,4,5,6,colors()[seq(100,250,6)]))
###################################################
### code chunk number 103: extend3
###################################################
simpleTAfit <- function(ae, # an object of class aquaenv: minimal definition,
# contains all information about the system:
# T, S, d, total concentrations of nutrients etc
pHmeasurements, # a table containing the titration curve:
# basically a series of pH values (pH on free proton scale)
volume, # the volume of the titration vessel
amount, # the total amount of the titrant added
TAguess=0.0025, # a first guess for [TA] and [SumCO2] to be used as
# initial values for the optimization procedure
type="HCl") # the type of titrant: either "HCl" or "NaOH"
{
ae$Na <- NULL # make sure ae gets cloned as "skeleton": cloneaquaenv determines "skeleton"
# TRUE or FALSE from the presence of a value for Na
residuals <- function(state)
{
ae$SumCO2 <- state[[1]]
pHcalc <- simpletitration(aquaenv(ae=ae, TA=state[[2]]), volume=volume,
amount=amount, steps=(length(pHmeasurements)-1), type=type)$pH
residuals <- pHmeasurements-pHcalc
return(residuals)
}
require(minpack.lm)
out <- nls.lm(fn=residuals, par=c(TAguess, TAguess)) #guess for TA is also used as guess for SumCO2
result <- list(out$par[[2]], out$par[[1]], out$deviance)
attr(result[[1]], "unit") <- "mol/kg-soln"
attr(result[[2]], "unit") <- "mol/kg-soln"
names(result) <- c("TA", "SumCO2", "sumofsquares")
return(result) # a list of three values
# ([TA] in mol/kg-solution, [SumCO2] in mol/kg-solution, sum of the squared residuals)
}
###################################################
### code chunk number 104: extend4
###################################################
pHmeasurements <- ae$pH
fit <- simpleTAfit(aquaenv(S = 35, t = 15, SumNH4 = 0.00002),
pHmeasurements, volume = 100, amount = 1.5)
fit
###################################################
### code chunk number 105: CleaningUp
###################################################
graphics.off()
| /scratch/gouwar.j/cran-all/cranData/AquaEnv/inst/doc/AquaEnv.R |
#' Introduction to AquaticLifeHistory
#'
#' @name AquaticLifeHistory
#' @author Jonathan Smart
#' @description Estimate aquatic species life history using robust techniques.
#' This package supports users undertaking two types of analysis: 1) Growth from
#' length-at-age data, and 2) maturity analyses for length and/or age data.
#'
#' Maturity analyses are performed using generalised linear model approaches incorporating
#' either a binomial or quasibinomial distribution.
#'
#' Growth modelling is performed using the multimodel approach presented by
#' Smart et al. (2016) "Multimodel approaches in shark and ray growth studies:
#' strengths, weaknesses and the future" <doi:10.1111/faf.12154>.
#' @docType package
#' @references To cite the AquaticLifeHistory package in publications, type citation('AquaticLifeHistory').
NULL
utils::globalVariables(c("Age", "Pred", "Model", "AVG", "w.AVG", ".", "Estimate", 'high', "low",
'Maturity', 'N', 'Maturity.prop','Maturity.group', 'prop', 'na.omit',
'term', 'Length', 'upp', 'Len.bin', 'Len.start', 'Len.fin', 'Maturity.group'))
#' Length-at-age data for blacktip sharks
#'
#' A data set containing the length-at-age data for common blacktip sharks (\emph{Carcharhinus limbatus})
#' from Indonesia. This data was published in Smart et al. (2015).
#'
#' \itemize{
#' \item Age. Number of growth bands determined from vertebral analysis
#' \item Length. Total Length in mm determined via back-calculation
#' \item Sex. Females (F) or males (M)
#' }
#'
#' @docType data
#' @keywords datasets
#' @name growth_data
#' @usage data(growth_data)
#' @format A data frame with 294 rows and 3 variables
#' @references Smart et al (2015) Age and growth of the common
#' blacktip shark Carcharhinus limbatus from Indonesia, incorporating an improved approach to
#' comparing regional population growth rates. African Journal of Marine Science 37:177-188.
#' \url{https://www.tandfonline.com/doi/abs/10.2989/1814232X.2015.1025428}
NULL
#' Age and length-at-maturity data for silky sharks
#'
#' A data set containing the length-at-maturity and age-at-maturity data for female silky sharks
#' (\emph{Carcharhinus falciformis}) from Papua New Guinea. This data was published in Grant et al (2018)
#'
#' \itemize{
#' \item Tag. Unique identifier for each Shark
#' \item Age. Number of growth bands determined from vertebral analysis
#' \item Length. Total Length in cm
#' \item Maturity. Binary maturity status: immature = 0 and mature = 1
#' }
#'
#' @docType data
#' @keywords datasets
#' @name maturity_data
#' @usage data(maturity_data)
#' @format A data frame with 284 rows and 4 variables
#' @references Grant et al (2018)
#' Life history characteristics of the silky shark (\emph{Carcharhinus falciformis})
#' from the central west Pacific. Marine and Freshwater Research 69:562-573
#' \url{http://www.publish.csiro.au/mf/MF17163}
NULL
| /scratch/gouwar.j/cran-all/cranData/AquaticLifeHistory/R/AquaticLifeHistory.R |
#' Estimate length-at-age parameters and growth curves for Elasmobranchs
#' @description A multi-model growth estimation approach is applied to length-at-age data. Three models can be applied which include the von Bertalanffy (VB), logistic (Log) and Gompertz (Gom) models. AIC values and weights are calculated. The outputs will return a list of model parameter estimates and will either print a plot to the screen or output the length-at-age estimates as part of the list.Use of this function should cite Smart et al. (2016).
#' @param data a data frame which includes 'Age' and 'Length - ideally with these names but the function will except some variation to these
#' @param models a vector of models to be fitted. These can include" VB", "Log" and "Gom". A subset can also be used
#' @param Birth.Len The length-at-birth to be used for two parameter models. If a value is provided, two parameter models are automatically run
#' @param correlation.matrix Should the correlation matrix of parameters be returned? This is the only object returned if TRUE.
#' @param n.bootstraps The number of bootstraps performed for model 95 confidence intervals
#' @param plots Should plots be printed to the screen. If FALSE then the model estimates and CI's are returned as an additional output
#' @param plot.legend Do you want a legend for the different models on the plot
#' @param Max.Age Specify the max age for bootstrapped confidence intervals to be produced over. Default is the max age in the data.
#' @return Returns a list of parameter estimates with errors and AIC results. If plots is TRUE then a plot is printed to the screen. If plots is FALSE then the length-at-age estimates are returned as a list element
#' @import broom MuMIn rlist minpack.lm dplyr tidyr ggplot2
#' @importFrom magrittr %>%
#' @importFrom stats glm lm nls nls.control predict quantile na.omit
#' @export
#' @examples
#' # load example data set
#' data("growth_data")
#' # Run function with three default model candidates. Use 100 bootstraps for
#' # testing and then increase to at least 1000 for actual model runs.
#' Estimate_Growth(growth_data, n.bootstraps = 100)
#' @references Smart et al. (2016) Multi-model approaches in shark and ray growth studies: strengths, weaknesses and the future. Fish and Fisheries. 17: 955-971\url{https://onlinelibrary.wiley.com/doi/abs/10.1111/faf.12154}
Estimate_Growth<-function(data, models = c("VB", "Log", "Gom"), Birth.Len = NULL, correlation.matrix = FALSE, n.bootstraps = 1000, plots = TRUE,
Max.Age = NULL,
plot.legend = TRUE){
if(!any(models %in% c("VB", "Log", "Gom"))) {stop("Models an only be 'VB', 'Log', 'Gom' or a combination of these")}
age_col <- grep("age", substr(tolower(names(data)),1,30))
len_col <- grep("len|tl|lt|siz|fl", substr(tolower(names(data)),1,30))
if(length(age_col) <1) {stop("Age column heading could not be distinguished ")}
if(length(age_col) >1) {stop("Multiple age columns detected. Please remove one")}
if(length(len_col) <1) {stop("Length column heading could not be distinguished ")}
if(length(len_col) >1) {stop("Multiple length columns detected. Please remove one")}
Data <- data.frame(Age = data[,age_col],
Length = data[,len_col])
Data <- stats::na.omit(Data)# remove NA's
mean.age<-tapply(Data$Length, round(Data$Age), mean,na.rm = TRUE)
Lt1<-mean.age[2:length(mean.age)]
Lt<-mean.age[1:length(mean.age)-1]
model<-lm(Lt1 ~ Lt)
k <- suppressWarnings(abs(-log(model$coef[2]))) #in case a nan occurs
k <- ifelse(is.nan(k),0.1,k) # in case a nan occurs
g<-k
Linf<-abs(model$coef[1]/(1-model$coef[2]))
if(is.null(Birth.Len)){
L0<-lm(mean.age ~ poly(as.numeric(names(mean.age)), 2, raw = TRUE))$coef[1]
vb3.start<-list(Linf = log(Linf) , k = log(k),L0 = log(L0))
gom.start<-list(Linf = log(Linf),g = log(g), L0 = log(L0))
log.start<-list(Linf = log(Linf),g = log(g), L0 = log(L0))
} else{
L0<-log(Birth.Len)
vb3.start<-list(Linf = log(Linf) , k = log(k))
gom.start<-list(Linf = log(Linf),g = log(g))
log.start<-list(Linf = log(Linf),g = log(g))
}
vb3.model<-Length~exp(Linf)-(exp(Linf)-exp(L0))*(exp(-exp(k)*Age)) #von bertalanffy equation
log.model<-Length~(exp(Linf)*exp(L0)*exp(exp(g)*Age))/(exp(Linf)+exp(L0)*(exp(exp(g)*Age)-1))#logistic equation
gom.model<-Length~exp(L0)*exp(log(exp(Linf)/exp(L0))*(1-exp(-exp(g)*Age))) # Gompertz equation
AIC.vals <- NULL
Results <- list()
if(is.null(Birth.Len)){
if(any(models %in% "VB")){
VB3<-minpack.lm::nlsLM(vb3.model, data = Data, start = vb3.start, algorithm = "port", control = nls.lm.control(maxiter = 1000, ftol = 1e-05))
VonB<-rbind(as.vector(c(exp(summary(VB3)$coef[1,1]),exp(summary(VB3)$coef[1,1])*((summary(VB3)$coef[1,2])*sqrt(length(Data[,1]))/sqrt(length(Data[,1]))))),
as.vector(c(exp(summary(VB3)$coef[2,1]),exp(summary(VB3)$coef[2,1])*((summary(VB3)$coef[2,2])*sqrt(length(Data[,1]))/sqrt(length(Data[,1]))))),
as.vector(c(exp(summary(VB3)$coef[3,1]),exp(summary(VB3)$coef[3,1])*((summary(VB3)$coef[3,2])*sqrt(length(Data[,1]))/sqrt(length(Data[,1]))))),
cbind(summary(VB3)$sigma,NA))
rownames(VonB)<-c("Linf","k","L0","RSE");colnames(VonB)<-c("Parameter","SE")
AIC.vals <- rbind(AIC.vals, AICc(VB3))
Results <- list.append(Results, VonB = VonB)
}
if(any(models %in% "Log")){
Log<-minpack.lm::nlsLM(log.model, data = Data, start = log.start, algorithm = "port", control = nls.lm.control(maxiter = 1000, ftol = 1e-05))
LOG<-rbind(as.vector(c(exp(summary(Log)$coef[1,1]),exp(summary(Log)$coef[1,1])*((summary(Log)$coef[1,2])*sqrt(length(Data[,1]))/sqrt(length(Data[,1]))))),
as.vector(c(exp(summary(Log)$coef[2,1]),exp(summary(Log)$coef[2,1])*((summary(Log)$coef[2,2])*sqrt(length(Data[,1]))/sqrt(length(Data[,1]))))),
as.vector(c(exp(summary(Log)$coef[3,1]),exp(summary(Log)$coef[3,1])*((summary(Log)$coef[3,2])*sqrt(length(Data[,1]))/sqrt(length(Data[,1]))))),
cbind(summary(Log)$sigma,NA))
rownames(LOG)<-c("Linf","g","L0","RSE");colnames(LOG)<-c("Parameter","SE")
AIC.vals <- rbind(AIC.vals, AICc(Log))
Results <- list.append(Results, Logistic = LOG)
}
if(any(models %in% "Gom")){
gom<-minpack.lm::nlsLM(gom.model, data = Data, start = gom.start, algorithm = "port", control = nls.lm.control(maxiter = 1000, ftol = 1e-05))
GOM<-rbind(as.vector(c(exp(summary(gom)$coef[1,1]),exp(summary(gom)$coef[1,1])*((summary(gom)$coef[1,2])*sqrt(length(Data[,1]))/sqrt(length(Data[,1]))))),
as.vector(c(exp(summary(gom)$coef[2,1]),exp(summary(gom)$coef[2,1])*((summary(gom)$coef[2,2])*sqrt(length(Data[,1]))/sqrt(length(Data[,1]))))),
as.vector(c(exp(summary(gom)$coef[3,1]),exp(summary(gom)$coef[3,1])*((summary(gom)$coef[3,2])*sqrt(length(Data[,1]))/sqrt(length(Data[,1]))))),
cbind(summary(gom)$sigma,NA))
rownames(GOM)<-c("Linf","g","L0","RSE");colnames(GOM)<-c("Parameter","SE")
AIC.vals <- rbind(AIC.vals, AICc(gom))
Results <- list.append(Results, Gompertz = GOM)
}
} else {
if(any(models %in% "VB")){
VB3<-minpack.lm::nlsLM(vb3.model, data = Data, start = vb3.start, algorithm = "port", control = nls.lm.control(maxiter = 1000, ftol = 1e-05))
VonB<-rbind(as.vector(c(exp(summary(VB3)$coef[1,1]),exp(summary(VB3)$coef[1,1])*((summary(VB3)$coef[1,2])*sqrt(length(Data[,1]))/sqrt(length(Data[,1]))))),
as.vector(c(exp(summary(VB3)$coef[2,1]),exp(summary(VB3)$coef[2,1])*((summary(VB3)$coef[2,2])*sqrt(length(Data[,1]))/sqrt(length(Data[,1]))))),
cbind(summary(VB3)$sigma,NA))
rownames(VonB)<-c("Linf","k","RSE");colnames(VonB)<-c("Parameter","SE")
AIC.vals <- rbind(AIC.vals, AICc(VB3))
Results <- list.append(Results, VonB = VonB)
}
if(any(models %in% "Log")){
Log<-minpack.lm::nlsLM(log.model, data = Data, start = log.start, algorithm = "port", control = nls.lm.control(maxiter = 1000, ftol = 1e-05))
LOG<-rbind(as.vector(c(exp(summary(Log)$coef[1,1]),exp(summary(Log)$coef[1,1])*((summary(Log)$coef[1,2])*sqrt(length(Data[,1]))/sqrt(length(Data[,1]))))),
as.vector(c(exp(summary(Log)$coef[2,1]),exp(summary(Log)$coef[2,1])*((summary(Log)$coef[2,2])*sqrt(length(Data[,1]))/sqrt(length(Data[,1]))))),
cbind(summary(Log)$sigma,NA))
rownames(LOG)<-c("Linf","g","RSE");colnames(LOG)<-c("Parameter","SE")
AIC.vals <- rbind(AIC.vals, AICc(Log))
Results <- list.append(Results, Logistic = LOG)
}
if(any(models %in% "Gom")){
gom<-minpack.lm::nlsLM(gom.model, data = Data, start = gom.start, algorithm = "port", control = nls.lm.control(maxiter = 1000, ftol = 1e-05))
GOM<-rbind(as.vector(c(exp(summary(gom)$coef[1,1]),exp(summary(gom)$coef[1,1])*((summary(gom)$coef[1,2])*sqrt(length(Data[,1]))/sqrt(length(Data[,1]))))),
as.vector(c(exp(summary(gom)$coef[2,1]),exp(summary(gom)$coef[2,1])*((summary(gom)$coef[2,2])*sqrt(length(Data[,1]))/sqrt(length(Data[,1]))))),
cbind(summary(gom)$sigma,NA))
rownames(GOM)<-c("Linf","g","RSE");colnames(GOM)<-c("Parameter","SE")
AIC.vals <- rbind(AIC.vals, AICc(gom))
Results <- list.append(Results, Gompertz = GOM)
}
}
if(correlation.matrix == TRUE)
{
correlation.matrices <- list()
if(any(models == "VB")){
correlation.matrices[["VonB"]] <- summary(VB3, correlation = TRUE)$cor
Vb_names <- c("Linf", "k", "L0")
colnames(correlation.matrices[["VonB"]] ) <- Vb_names[c(1:length(colnames(correlation.matrices[["VonB"]] )))]
rownames(correlation.matrices[["VonB"]] ) <- Vb_names[c(1:length(rownames(correlation.matrices[["VonB"]] )))]
}
if(any(models == "Log")){
Log_names <- c("Linf", "g", "L0")
correlation.matrices[["Logistic"]] <- summary(Log, correlation = TRUE)$cor
colnames(correlation.matrices[["Logistic"]] ) <- Log_names[c(1:length(colnames(correlation.matrices[["Logistic"]] )))]
rownames(correlation.matrices[["Logistic"]] ) <- Log_names[c(1:length(rownames(correlation.matrices[["Logistic"]] )))]
}
if(any(models == "Gom")){
Gom_names <- c("Linf", "g", "L0")
correlation.matrices[["Gompertz"]] <- summary(gom, correlation = TRUE)$cor
colnames(correlation.matrices[["Gompertz"]] ) <- Gom_names[c(1:length(colnames(correlation.matrices[["Logistic"]] )))]
rownames(correlation.matrices[["Gompertz"]] ) <- Gom_names[c(1:length(rownames(correlation.matrices[["Gompertz"]] )))]
}
return(correlation.matrices)
}
# Calculate AIC differences and weights
AIC.table<-cbind(round(AIC.vals,2),round(AIC.vals-min(AIC.vals),2),
round(exp(-0.5*as.numeric(AIC.vals-min(AIC.vals)))/sum(exp(-0.5*as.numeric(AIC.vals-min(AIC.vals)))),2))
AIC.table<-cbind(models,as.data.frame(AIC.table))
colnames(AIC.table)<-c("Model","AICc","AIC diff","Weight")
Results <- list.append(Results, AIC = AIC.table)
if(n.bootstraps == 0){
message("Only parameter estimates are returned. Set 'n.boostraps' to be larger than 0 for these results and associated plots \n")
return(Results)
}
####---------------------
# Length-at-age estimates
####---------------------
if(is.null(Max.Age)){
Max.Age <- max(Data$Age)
}
Age<-seq(0,Max.Age,0.1)
if(is.null(Birth.Len)){
if(any(models %in% "VB")){ VBTL<-VonB[1]-(VonB[1]-VonB[3])*(exp(-VonB[2]*Age))}
if(any(models %in% "Log")){ LogTL<-(LOG[1]*LOG[3]*exp(LOG[2]*Age))/(LOG[1]+LOG[3]*(exp(LOG[2]*Age)-1))}
if(any(models %in% "Gom")){GomTL<-GOM[3]*exp(log(GOM[1]/GOM[3])*(1-exp(-GOM[2]*Age)))}
} else {
if(any(models %in% "VB")){VBTL<-VonB[1]-(VonB[1]-Birth.Len)*(exp(-VonB[2]*Age))}
if(any(models %in% "Log")){LogTL<-(LOG[1]*Birth.Len*exp(LOG[2]*Age))/(LOG[1]+Birth.Len*(exp(LOG[2]*Age)-1))}
if(any(models %in% "Gom")){ GomTL<-Birth.Len*exp(log(GOM[1]/Birth.Len)*(1-exp(-GOM[2]*Age)))}
}
if(any(models %in% "VB")){
VB_Estimates <- data.frame(Model = "Von Bertalanffy",
Age = Age,
AVG = VBTL,
low = NA,
upp = NA)
}
if(any(models %in% "Log")){
Log_Estimates <- data.frame(Model = "Logistic",
Age = Age,
AVG = LogTL,
low = NA,
upp = NA)
}
if(any(models %in% "Gom")){
Gom_Estimates <- data.frame(Model = "Gompertz",
Age = Age,
AVG = GomTL,
low = NA,
upp = NA)
}
Estimates <- NULL
if(any(models %in% "VB")){
message("\nBootstrapping von Bertalanffy model \n")
if(is.null(Birth.Len)){
bootnls <- Data %>% boot_data(n.bootstraps) %>%
do(tryCatch(suppressWarnings(tidy(minpack.lm::nlsLM(formula = vb3.model,
data = .,
start = vb3.start))),
error=function(e){
suppressWarnings(tryCatch(tidy(minpack.lm::nlsLM(formula = vb3.model,
data = .,
start = list(Linf = log(max(.$Length)),
k = vb3.start$k,
L0 = log(min(.$Length))))),
error=function(e){
return(data.frame(term = as.character(c("Linf.(Intercept)","k.Lt","L0.(Intercept)")),
estimate = NA,
std.error= NA,
statistic = NA,
p.value= NA,stringsAsFactors = FALSE)
)
},
silent=TRUE
)
)
},
silent=TRUE)) %>% as.data.frame()
bootnls[which(bootnls$term == "Linf.(Intercept)"), "term"] <- "Linf"
bootnls[which(bootnls$term == "k.Lt"), "term"] <- "k"
bootnls[which(bootnls$term == "L0.(Intercept)"), "term"] <- "L0"
bootnls[1, "estimate"] <- NA
bootnls[2, "estimate"] <- NA
bootnls[3, "estimate"] <- NA
boot.Linf<- exp(as.numeric(as.matrix(subset(bootnls,term == "Linf")[,3])))
boot.K<-exp(as.numeric(as.matrix(subset(bootnls,term == "k")[,3])))
boot.L0<-exp(as.numeric(as.matrix(subset(bootnls,term == "L0")[,3])))
for (i in 1:length(Age)) {
pv <- boot.Linf-(boot.Linf-boot.L0)*(exp(-boot.K*Age[i]))
VB_Estimates[i,"low"] <- quantile(pv,0.025,na.rm = TRUE)
VB_Estimates[i,"upp"] <- quantile(pv,0.975,na.rm = TRUE)
}
} else {
bootnls <- Data %>% boot_data(n.bootstraps) %>%
do(tryCatch(suppressWarnings(tidy(minpack.lm::nlsLM(formula = vb3.model,
data = .,
start = vb3.start))),
error=function(e){
suppressWarnings(tryCatch(tidy(minpack.lm::nlsLM(formula = vb3.model,
data = .,
start = list(Linf = log(max(.$Length)),
k = vb3.start$k,
L0 = log(min(.$Length))))),
error=function(e){
return(data.frame(term = as.character(c("Linf.(Intercept)","k.Lt")),
estimate = NA,
std.error= NA,
statistic = NA,
p.value= NA,stringsAsFactors = FALSE)
)
},
silent=TRUE
)
)
},
silent=TRUE)) %>% as.data.frame()
bootnls[which(bootnls$term == "Linf.(Intercept)"), "term"] <- "Linf"
bootnls[which(bootnls$term == "k.Lt"), "term"] <- "k"
boot.Linf<- exp(as.numeric(as.matrix(subset(bootnls,term == "Linf")[,3])))
boot.K<-exp(as.numeric(as.matrix(subset(bootnls,term == "k")[,3])))
for (i in 1:length(Age)) {
pv <- boot.Linf-(boot.Linf-Birth.Len)*(exp(-boot.K*Age[i]))
VB_Estimates[i,"low"] <- quantile(pv,0.025,na.rm = TRUE)
VB_Estimates[i,"upp"] <- quantile(pv,0.975,na.rm = TRUE)
}
}
Estimates <- suppressWarnings(bind_rows(Estimates, VB_Estimates))
}
if(any(models %in% "Log")){
message("\nBootstrapping Logistic model \n")
if(is.null(Birth.Len)){
bootnls <- Data %>% boot_data(n.bootstraps) %>%
do(tryCatch(suppressWarnings(tidy(minpack.lm::nlsLM(formula = log.model,
data = .,
start = log.start))),
error=function(e){
suppressWarnings(tryCatch(tidy(minpack.lm::nlsLM(formula = log.model,
data = .,
start = list(Linf = log(max(.$Length)),
g = log.start$g,
L0 = log(min(.$Length))
)
)
),
error=function(e){
return(data.frame(term = as.character(c("Linf.(Intercept)","g.Lt","L0.(Intercept)")),
estimate = NA,
std.error= NA,
statistic = NA,
p.value= NA,stringsAsFactors = FALSE)
)
},
silent=TRUE
)
)
},
silent=TRUE)) %>% as.data.frame()
bootnls[which(bootnls$term == "Linf.(Intercept)"), "term"] <- "Linf"
bootnls[which(bootnls$term == "g.Lt"), "term"] <- "g"
bootnls[which(bootnls$term == "L0.(Intercept)"), "term"] <- "L0"
boot.Linf<- exp(as.numeric(as.matrix(subset(bootnls,term == "Linf")[,3])))
boot.g<-exp(as.numeric(as.matrix(subset(bootnls,term == "g")[,3])))
boot.L0<-exp(as.numeric(as.matrix(subset(bootnls,term == "L0")[,3])))
for (i in 1:length(Age)) {
pv <- (boot.Linf*boot.L0*exp(boot.g*Age[i]))/(boot.Linf+boot.L0*(exp(boot.g*Age[i])-1))
Log_Estimates[i,"low"] <- quantile(pv,0.025,na.rm = TRUE)
Log_Estimates[i,"upp"] <- quantile(pv,0.975,na.rm = TRUE)
}
} else {
bootnls <- Data %>% boot_data(n.bootstraps) %>%
do(tryCatch(suppressWarnings(tidy(minpack.lm::nlsLM(formula = log.model,
data = .,
start = log.start))),
error=function(e){
suppressWarnings(tryCatch(tidy(minpack.lm::nlsLM(formula = log.model,
data = .,
start = list(Linf = log(max(.$Length)),
g = log.start$g
)
)
),
error=function(e){
return(data.frame(term = as.character(c("Linf.(Intercept)","g.Lt")),
estimate = NA,
std.error= NA,
statistic = NA,
p.value= NA,stringsAsFactors = FALSE)
)
},
silent=TRUE
)
)
},
silent=TRUE)) %>% as.data.frame()
bootnls[which(bootnls$term == "Linf.(Intercept)"), "term"] <- "Linf"
bootnls[which(bootnls$term == "g.Lt"), "term"] <- "g"
boot.Linf<- exp(as.numeric(as.matrix(subset(bootnls,term == "Linf")[,3])))
boot.g<-exp(as.numeric(as.matrix(subset(bootnls,term == "g")[,3])))
for (i in 1:length(Age)) {
pv <- (boot.Linf*Birth.Len*exp(boot.g*Age[i]))/(boot.Linf+Birth.Len*(exp(boot.g*Age[i])-1))
Log_Estimates[i,"low"] <- quantile(pv,0.025,na.rm = TRUE)
Log_Estimates[i,"upp"] <- quantile(pv,0.975,na.rm = TRUE)
}
}
Estimates <- suppressWarnings(bind_rows(Estimates, Log_Estimates))
}
if(any(models %in% "Gom")){
message("\nBootstrapping Gompertz model")
if(is.null(Birth.Len)){
bootnls <- Data %>% boot_data(n.bootstraps) %>%
do(tryCatch(suppressWarnings(tidy(minpack.lm::nlsLM(formula = gom.model,
data = .,
start = gom.start))),
error=function(e){
suppressWarnings(try(tidy(minpack.lm::nlsLM(formula = gom.model,
data = .,
start = list(Linf = log(max(.$Length)),
g = gom.start$g,
L0 = log(min(.$Length)))))))
suppressWarnings(tryCatch(tidy(minpack.lm::nlsLM(formula = gom.model,
data = .,
start = list(Linf = log(max(.$Length)),
g = gom.start$g,
L0 = log(min(.$Length))
)
)
),
error=function(e){
return(data.frame(term = as.character(c("Linf.(Intercept)","g.Lt","L0.(Intercept)")),
estimate = NA,
std.error= NA,
statistic = NA,
p.value= NA,stringsAsFactors = FALSE)
)
},
silent=TRUE
)
)
},
silent=TRUE)) %>% as.data.frame()
bootnls[which(bootnls$term == "Linf.(Intercept)"), "term"] <- "Linf"
bootnls[which(bootnls$term == "g.Lt"), "term"] <- "g"
bootnls[which(bootnls$term == "L0.(Intercept)"), "term"] <- "L0"
boot.Linf<- exp(as.numeric(as.matrix(subset(bootnls,term == "Linf")[,3])))
boot.g<-exp(as.numeric(as.matrix(subset(bootnls,term == "g")[,3])))
boot.L0<-exp(as.numeric(as.matrix(subset(bootnls,term == "L0")[,3])))
for (i in 1:length(Age)) {
pv <- boot.L0*exp(log(boot.Linf/boot.L0)*(1-exp(-boot.g*Age[i])))
Gom_Estimates[i,"low"] <- quantile(pv,0.025,na.rm = TRUE)
Gom_Estimates[i,"upp"] <- quantile(pv,0.975,na.rm = TRUE)
}
} else {
bootnls <- Data %>% boot_data(n.bootstraps) %>%
do(tryCatch(suppressWarnings(tidy(minpack.lm::nlsLM(formula = gom.model,
data = .,
start = gom.start))),
error=function(e){
suppressWarnings(tryCatch(tidy(minpack.lm::nlsLM(formula = gom.model,
data = .,
start = list(Linf = log(max(.$Length)),
g = gom.start$g
)
)
),
error=function(e){
return(data.frame(term = as.character(c("Linf.(Intercept)","g.Lt")),
estimate = NA,
std.error= NA,
statistic = NA,
p.value= NA,stringsAsFactors = FALSE)
)
},
silent=TRUE
)
)
},
silent=TRUE)) %>% as.data.frame()
bootnls[which(bootnls$term == "Linf.(Intercept)"), "term"] <- "Linf"
bootnls[which(bootnls$term == "g.Lt"), "term"] <- "g"
boot.Linf<- exp(as.numeric(as.matrix(subset(bootnls,term == "Linf")[,3])))
boot.g<-exp(as.numeric(as.matrix(subset(bootnls,term == "g")[,3])))
for (i in 1:length(Age)) {
pv <- Birth.Len*exp(log(boot.Linf/Birth.Len)*(1-exp(-boot.g*Age[i])))
Gom_Estimates[i,"low"] <- quantile(pv,0.025,na.rm = TRUE)
Gom_Estimates[i,"upp"] <- quantile(pv,0.975,na.rm = TRUE)
}
}
Estimates <- suppressWarnings(bind_rows(Estimates, Gom_Estimates))
}
if(plots == TRUE){
max_len <- ifelse(max(Data$Length) > 500, "(mm)", "(cm)")
p <- ggplot(Estimates, aes(Age, AVG, col = Model, fill = Model))+
geom_point(data = Data, aes(Age, Length, col = NULL, fill = NULL), alpha = .2, col = "black") +
geom_ribbon(aes(ymin = low, ymax = upp), alpha = .4)+
geom_line(size = 1)+
scale_y_continuous(name = paste("Length",max_len))+
scale_x_continuous(name = "Age (years)", breaks = seq(0, Max.Age,1), expand = c(0,0), limits = c(0,Max.Age+0.5))+
theme_bw()+
theme(legend.position = c(0.8,0.2),
legend.background = element_rect(colour = "black"),
panel.grid.minor = element_blank())
if(plot.legend == FALSE){ p <- p + guides(col = "none", fill = "none")}
print(p)
} else {
Results <- list.append(Results, Estimates = Estimates)
}
return(Results)
}
#' Calculate model averaged length-at-age estimates and parameters
#' @description `Calculate_MMI` takes the outputs from an `Estimate_Growth` function with plots = FALSE and returns the calculated model averaged parameters, SE and estimates based on AIC scores. It should be used if no candidate model has an AIC weight higher than 0.9. Use of this function should cite Smart et al (2016)
#' @param data An output from the Estimate_Growth function with plots = FALSE
#'
#' @return A list with model averaged parameters and a dataframe of model averaged length-at-age estimates
#' @export
#' @import dplyr tidyr
#' @importFrom magrittr %>%
#' @importFrom plyr ldply
#' @importFrom stats glm lm nls nls.control predict quantile
#' @examples
#' # load example data set
#' data("growth_data")
#' # Run function with three default model candidates and return results
#' # without plots. Use 100 bootstraps for testing and then increase to at
#' # least 1000 for actual model runs.
#' models <- Estimate_Growth(growth_data, plots = FALSE, n.bootstraps = 100)
#' # Calculate the model average of the resulting growth estimates
#' Calculate_MMI(models)
#' @references Smart et al. (2016) Multi model approaches in shark and ray growth studies: strengths, weaknesses and the future. Fish and Fisheries. 17: 955-971\url{https://onlinelibrary.wiley.com/doi/abs/10.1111/faf.12154}
Calculate_MMI <- function(data){
if(!any(names(data) == "Estimates")) stop("No length-at-age estimates provided")
AICw<- data$AIC[,"Weight"]
Linfs <- NULL
L0s <- NULL
for(i in 1:length(AICw)){
Linfs[i] <- data[[i]][1] *AICw[i]
L0s[i] <- data[[i]][3] *AICw[i]
}
AVG.Linf <- sum(Linfs)
AVG.L0 <- sum(L0s)
Linfs.SE <- NULL
L0s.SE <- NULL
for(i in 1:length(AICw)){
Linfs.SE[i] <- AICw[i]*(data[[i]][1,2]^2+(Linfs[i]-AVG.Linf)^2)^0.5
L0s.SE[i] <- AICw[i]*(data[[i]][3,2]^2+(L0s[i]-AVG.L0)^2)^0.5
}
AVG.Linf.SE <- sum(Linfs.SE)
AVG.L0.SE <- sum(L0s.SE)
AVG.pars <- data.frame(Parameter = c("Linf", "L0"),
AVG = c(AVG.Linf, AVG.L0),
SE = c(AVG.Linf.SE, AVG.L0.SE))
Estimates <- data$Estimates %>% dplyr::filter(Age %in% seq(0,max(data$Estimates[,"Age"]),1)) %>% dplyr::select(Model, Age, AVG)
tmp<- list()
for(i in 1:length(AICw)){
tmp[[i]] <- dplyr::filter(Estimates, Model == unique(Estimates$Model)[i]) %>% mutate(w.AVG = AVG *AICw[i])
}
Estimates <- plyr::ldply(tmp) %>% dplyr::select(-AVG) %>% spread(Model, w.AVG) %>% apply(MARGIN = 1,sum) %>%
cbind(Age = 0:max(data$Estimates[,"Age"]), AVG = .) %>% as.data.frame()
return(list("MMI parametrs" = AVG.pars, "MMI estimates" = Estimates))
}
| /scratch/gouwar.j/cran-all/cranData/AquaticLifeHistory/R/Growth_functions.R |
#' boot_data
#'
#' @param .data Length at Age data
#' @param n number of bootstrap iterations
#'
#' @return a grouped_df produced by the group_by function in dplyr
boot_data <- function(.data, n = 100){
new.dat <- list()
for(i in 1:n){
new_ids <- sample(1:nrow(.data),replace = TRUE)
tmp <- .data[new_ids,]
tmp$id <- i
new.dat[[i]] <- tmp
}
new.dat <- plyr::ldply(new.dat) %>%
dplyr::group_by(id)
return(new.dat)
}
| /scratch/gouwar.j/cran-all/cranData/AquaticLifeHistory/R/Helper_functions.R |
#' Estimate age-at-maturity
#' @description Age-at-maturity is estimated from binary maturity data using a logistic ogive.
#'Two options are available depending on error structure. If binary data are used then a binomial
#'error structure is required. If the user wishes to bin the data by age class then a quasi binomial error
#'structure is needed with the data weighted by the sample size of each bin. This is handled automatically by the function.
#' @param data A dataframe that includes age and a binary maturity status (immature = 0 and mature = 1).
#' Columns should be named "Age" and "Maturity" but the function is robust enough to accept some reasonable variations to these
#' @param error.structure The distribution for the glm used to produce the logistic ogive. Must be either "binomial"
#' for binary data or "quasi binomial" for binned maturity at age. Proportion mature at each age is automatically calculated within the function
#' @param n.bootstraps Number of bootstrap iterations required to produce 95\% confidence intervals about the logistic ogive
#' @param display.points Should the raw data be plotted for the binomial model?
#' @param return Either: \describe{
#' \item{parameters}{The estimated logistic parameters and their standard error (A50 and A95)}
#' \item{estimates}{The logistic ogive predictions with 95 percent confidence intervals (useful for creating ones own plots)}
#' \item{plot}{a ggplot object of the logistic ogive.}
#' }
#'
#' @return Either: \describe{
#' \item{parameters}{a dataframe of the estimated logistic parameters and their standard error (A50 and A95)}
#' \item{estimates}{a dataframe of logistic ogive predictions with 95 percent confidence intervals}
#' \item{plot}{a ggplot object of the logistic ogive}
#' }
#' @import readr broom ggplot2 dplyr tidyr
#' @importFrom magrittr %>%
#' @importFrom MASS dose.p
#' @importFrom stats glm lm nls nls.control predict quantile
#' @examples
#' # load example data set
#' data("maturity_data")
#' # Run function to estimate age-at-maturity parameters
#' Estimate_Age_Maturity(maturity_data)
#' # A plot can also be returned with bootstrapped CI's. Use 100 bootstraps for
#' # testing and then increase to at least 1000 for actual model runs.
#' Estimate_Age_Maturity(maturity_data, return = "plot",n.bootstraps = 100)
#' @export
#'
Estimate_Age_Maturity <- function(data, error.structure = "binomial", n.bootstraps = 1000, display.points = FALSE, return = "parameters"){
if(!error.structure %in% c("binomial", "quasibinomial")) {
warning("'error.structure' has not been specified correctly. Defaulting to a logistic model with a binomial error structure")
error.structure <- "binomial"
}
if(!return %in% c("parameters", "estimates", "plot")) stop("return must be either parameters, estimates or plot")
if(return != "plot" & display.points == TRUE) warning("'display.points' argument ignored as no plot is being returned")
if(error.structure == "quasibinomial" & display.points == TRUE) warning("'display.points' argument ignored for quasibinomial models")
if(is.data.frame(data[,grep("age", substr(tolower(names(data)),1,3))])) stop("Age column heading could not be distinguished ")
if(is.data.frame(data[,grep("mat", substr(tolower(names(data)),1,3))])) stop("Maturity column heading could not be distinguished ")
age_col <- grep("age", substr(tolower(names(data)),1,3))
if(length(age_col)>1){stop("Multiple columns determined for age variable")}
mat_col <- grep("mat", substr(tolower(names(data)),1,3))
if(length(mat_col)>1){stop("Multiple columns determined for maturity variable")}
processed_data <- data.frame(Age = data[,age_col],
Maturity = data[,mat_col]) %>%
dplyr::filter_if(is.numeric, all_vars(!is.na(.)))
if(any(!unique(processed_data$Maturity) %in% c(0,1))) stop("Maturity data is not binary")
if(error.structure == "binomial"){
Maturity.Model<-glm(Maturity~Age,data = processed_data, family = "binomial")
A50<- MASS::dose.p(Maturity.Model,p=c(0.5))
A95<- MASS::dose.p(Maturity.Model,p=c(0.95))
if(return == "parameters") {
pars <- data.frame(rbind(A50,A95), rbind(attr(A50,"SE"), attr(A95,"SE")))
colnames(pars) <- c("Estimate", "SE")
return(pars)
}
new <- data.frame(Age = seq(0,max(processed_data$Age),0.01))
preddat<-cbind( Age = new, predict(Maturity.Model, data.frame(Age=new$Age),se.fit=T,type = "response"))
message("Bootstrapping logistic model with a binomial error structure")
boot_maturity <- processed_data %>% boot_data(n.bootstraps) %>%
dplyr::do( tryCatch( glm(Maturity~Age,data = ., family = "binomial")%>%
predict(data.frame(Age=new$Age),type="response") %>% cbind(Age = new$Age, Pred =.) %>% as.data.frame(),
warning=function(w){data.frame(Age = new$Age, Pred = NA)}))
boot_ests <- boot_maturity %>% dplyr::group_by(Age) %>% dplyr::summarize(high=quantile(Pred, 0.025, na.rm = TRUE),
low=quantile(Pred, 0.975, na.rm = TRUE))
results <- cbind(boot_ests, Estimate = preddat$fit) %>% dplyr::select(Age, Estimate, high,low)
p <- ggplot(results, aes(x = Age, y = Estimate)) +
geom_ribbon(aes(ymin = low, ymax = high), col = "darkgrey", fill = "grey", alpha =.3)+
geom_line(size = 2, col = "royalblue") +
geom_point(aes(A50[1], 0.5), col = 'black', size = 4)+
scale_y_continuous(name = "Proportion mature", limits = c(0,1), breaks = seq(0,1,.2), expand = c(0,0)) +
scale_x_continuous(name = "Age (years)", expand = c(0,0),breaks = seq(0,ceiling(max(processed_data$Age)),1))+
theme_bw()
if(display.points == TRUE){
p <- suppressMessages(p + geom_point(data = processed_data, aes(Age, Maturity), alpha = .3, size = 2)+
scale_y_continuous(name = "Proportion mature", limits = c(0,1), breaks = seq(0,1,.2)))
}
}
if(error.structure == "quasibinomial"){
weighted_data <- processed_data %>% dplyr::mutate(Age = round(Age)) %>%
dplyr::group_by(Age) %>%
dplyr::summarise(Maturity.prop = mean(Maturity), N = n())
Maturity.Model<-glm(Maturity.prop~Age,data = weighted_data, family = "quasibinomial", weights = N)
A50<- MASS::dose.p(Maturity.Model,p=c(0.5))
A95<- MASS::dose.p(Maturity.Model,p=c(0.95))
if(return == "parameters") {
pars <- data.frame(rbind(A50,A95), rbind(attr(A50,"SE"), attr(A95,"SE")))
colnames(pars) <- c("Estimate", "SE")
return(pars)
}
new <- data.frame(Age = seq(0,ceiling(max(processed_data$Age))+1,0.01))
preddat<-cbind(Age = new, predict(Maturity.Model, data.frame(Age=new$Age),se.fit=T,type = "response"))
message("Bootstrapping logistic model with a quasibinomial error structure")
boot_maturity <- processed_data %>% boot_data(n.bootstraps) %>%
dplyr::do( tryCatch( dplyr::mutate(.,Age = round(Age)) %>%
dplyr::group_by(Age) %>%
dplyr::summarise(Maturity.prop = mean(Maturity), N = n()) %>%
glm(Maturity.prop~Age, data=.,family= "quasibinomial", weights = N) %>%
predict(data.frame(Age=new$Age),type="response") %>% cbind(Age = new$Age, Pred =.) %>% as.data.frame(),
warning=function(w){data.frame(Age = new$Age, Pred = NA)}))
boot_ests <- boot_maturity %>% dplyr::group_by(Age) %>% dplyr::summarize(high=quantile(Pred, 0.025, na.rm = TRUE),
low=quantile(Pred, 0.975, na.rm = TRUE))
results <- cbind(boot_ests, Estimate = preddat$fit) %>% dplyr::select(Age, Estimate, high,low)
p <- ggplot(results, aes(x = Age, y = Estimate)) +
geom_bar(data = weighted_data %>% mutate(Immaturity.prop = 1 - Maturity.prop) %>%
tidyr::gather(Maturity.group, prop, -Age, -N),
aes(Age + 0.5, prop, fill = Maturity.group), col = "black", stat="identity", width = 1) +
geom_ribbon(aes(ymin = low, ymax = high), col = "royalblue", fill = "lightblue", alpha = .6)+
geom_line(size = 2, col = "royalblue") +
geom_text(data = weighted_data , inherit.aes = FALSE ,aes(Age + 0.5, y = 1.05, label = N))+
geom_point(aes(A50[1], 0.5), col = 'black', size = 4)+
scale_fill_manual(values=c("light grey", "grey"), guide = "none")+
scale_y_continuous(name = "Proportion mature", limits = c(0,1.1), expand = c(0,0), breaks = seq(0,1,.2)) +
scale_x_continuous(name = "Age (years)", expand = c(0,0), breaks = seq(0,ceiling(max(processed_data$Age)),1))+
theme_bw()+
theme(panel.grid = element_blank())
}
if (return == "estimates"){
return(results)
} else if(return == "plot"){
return(p)
}
}
#' Estimate length-at-maturity
#' @description Length-at-maturity is estimated from binary maturity data using a logistic ogive.
#'Two options are available depending on error structure. If binary data are used then a binomial
#'error structure is required. If the user wishes to bin the data by length class then a quasi binomial error
#'structure is needed with the data weighted by the sample size of each bin. This is handled automatically by the function.
#' @param data A dataframe that includes length and a binary maturity status (immature = 0 and mature = 1).
#' Columns should be named "Length" and "Maturity" but the function is robust enough to accept some reasonable variations to these
#' @param error.structure The distribution for the glm used to produce the logistic ogive. Must be either "binomial"
#' for binary data or "quasi binomial" for binned maturity at length. Proportion mature at each length bin is automatically calculated within the function
#' @param n.bootstraps Number of bootstrap iterations required to produce 95\% confidence intervals about the logistic ogive
#' @param bin.width The width of the length-class bins used for a quasi binomial logistic model. These should on the same unit as the length data.
#' The y axis on any plots will automatically scale to the correct unit ("cm" or "mm")
#' @param display.points Should the raw data be plotted for the binomial model?
#' @param return Either: \describe{
#' \item{parameters}{The estimated logistic parameters and their standard error (L50 and L95)}
#' \item{estimates}{The logistic ogive predictions with 95 percent confidence intervals (useful for creating ones own plots)}
#' \item{plot}{a ggplot object of the logistic ogive.}
#' }
#'
#' @return Either: \describe{
#' \item{parameters}{a dataframe of the estimated logistic parameters and their standard error (L50 and L95)}
#' \item{estimates}{a dataframe of logistic ogive predictions with 95 percent confidence intervals}
#' \item{plot}{a ggplot object of the logistic ogive. If binned length classes are used, this includes a bar plot of proportional maturity }
#' }
#' @import readr broom ggplot2 dplyr tidyr
#' @importFrom magrittr %>%
#' @importFrom MASS dose.p
#' @importFrom stats glm lm nls nls.control predict quantile
#' @examples
#' # load example data set
#' \donttest{
#' data("maturity_data")
#' # Run function to estimate length-at-maturity parameters
#' Estimate_Len_Maturity(maturity_data)
#' # A plot can also be returned with bootstrapped CI's. Use 100 bootstraps for
#' # testing and then increase to at least 1000 for actual model runs.
#' Estimate_Len_Maturity(maturity_data, return = "plot",n.bootstraps = 100)
#' }
#' @export
Estimate_Len_Maturity <- function(data, error.structure = "binomial", n.bootstraps = 1000, bin.width = NA, display.points = FALSE, return = "parameters"){
if(!error.structure %in% c("binomial", "quasibinomial")) {
warning("'error.structure' has not been specified correctly. Defaulting to a logistic model with a binomial error structure")
error.structure <- "binomial"
}
if(!return %in% c("parameters", "estimates", "plot")) stop("return must be either parameters, estimates or plot")
if(return != "plot" & display.points == TRUE) warning("'display.points' argument ignored as no plot is being returned")
if(error.structure == "quasibinomial" & is.na(bin.width))stop("'bin.width' must be specified for a quasibinomial model")
if(error.structure == "quasibinomial" & display.points == TRUE) warning("'display.points' argument ignored for quasibinomial models")
if(is.data.frame(data[,grep("len|tl|lt|siz", substr(tolower(names(data)),1,3))])) stop("Length column heading could not be distinguished ")
if(is.data.frame(data[,grep("mat", substr(tolower(names(data)),1,3))])) stop("Maturity column heading could not be distinguished ")
len_col <- grep("len|tl|lt|siz", substr(tolower(names(data)),1,3))
if(length(len_col)>1){stop("Multiple columns determined for length variable")}
mat_col <- grep("mat", substr(tolower(names(data)),1,3))
if(length(mat_col)>1){stop("Multiple columns determined for maturity variable")}
processed_data <- data.frame(Length = data[,len_col],
Maturity = data[,mat_col]) %>%
dplyr::filter_if(is.numeric, all_vars(!is.na(.)))
if(any(!unique(processed_data$Maturity) %in% c(0,1))) stop("Maturity data is not binary")
if(error.structure == "binomial"){
Maturity.Model<-glm(Maturity~Length,data = processed_data, family = "binomial")
L50<- MASS::dose.p(Maturity.Model,p=c(0.5))
L95<- MASS::dose.p(Maturity.Model,p=c(0.95))
if(return == "parameters") {
pars <- data.frame(rbind(L50,L95), rbind(attr(L50,"SE"), attr(L95,"SE")))
colnames(pars) <- c("Estimate", "SE")
return(pars)
}
if(max(processed_data$Length) < 500){
new <- data.frame(Length = seq(0,max(processed_data$Length),0.01))
} else{
new <- data.frame(Length = seq(0,max(processed_data$Length),0.1))
}
preddat<-cbind(Length = new, predict(Maturity.Model, data.frame(Length=new$Length),se.fit=T,type = "response"))
message("Bootstrapping logistic model with a binomial error structure")
boot_maturity <- processed_data %>% boot_data(n.bootstraps) %>%
dplyr::do(
tryCatch(glm(Maturity~Length,data = ., family = "binomial")%>%
predict(data.frame(Length=new$Length),type="response") %>%
cbind(Length = new$Length, Pred =.) %>%
as.data.frame(),
warning=function(w){data.frame(Length = new$Length, Pred = NA)}
)
)
boot_ests <- boot_maturity %>% dplyr::group_by(Length) %>% dplyr::summarize(high=quantile(Pred, 0.025, na.rm = TRUE),
low=quantile(Pred, 0.975, na.rm = TRUE))
results <- cbind(boot_ests, Estimate = preddat$fit) %>% dplyr::select(Length, Estimate, high,low)
p <- ggplot(results, aes(x = Length, y = Estimate)) +
geom_ribbon(aes(ymin = low, ymax = high), col = "darkgrey", fill = "grey", alpha =.3)+
geom_line(size = 2, col = "royalblue") +
geom_point(aes(L50[1], 0.5), col = 'black', size = 4)+
scale_y_continuous(name = "Proportion mature", limits = c(0,1), breaks = seq(0,1,.2), expand = c(0,0)) +
scale_x_continuous(name = "Length (cm)",limits =c(min(processed_data$Length)*.8,max(processed_data$Length)*1.1), expand = c(0,0))+
theme_bw()
if(display.points == TRUE){
p <- suppressMessages(p + geom_point(data = processed_data, aes(Length, Maturity), alpha = .3, size = 2)+
scale_y_continuous(name = "Proportion mature", limits = c(0,1), breaks = seq(0,1,.2)))
}
if(max(processed_data$Length) > 500){
p <- suppressMessages(p + scale_x_continuous(name = "Length (mm)",
limits =c(min(processed_data$Length)*.8,max(processed_data$Length)*1.1),
expand = c(0,0)))
}
}
if(error.structure == "quasibinomial"){
if(max(processed_data$Length) < 500){
weighted_data <- processed_data %>% dplyr::mutate(Len.bin = cut(Length, breaks = seq(0, max(Length)+bin.width, bin.width))) %>%
tidyr::separate(Len.bin, into = c("Len.start","Len.fin"), sep = ",", remove = FALSE) %>%
dplyr::mutate(Length = as.numeric(readr::parse_number(Len.start)),
Len.bin = paste(readr::parse_number(Len.start), readr::parse_number(Len.fin), sep = "-")) %>%
dplyr::group_by(Length, Len.bin) %>%
dplyr::summarise(Maturity.prop = mean(Maturity), N = n())
}else{
weighted_data <- processed_data %>% dplyr::mutate( Length = Length/10,
Len.bin = cut(Length, breaks = seq(0, max(Length)+bin.width, bin.width/10))) %>%
tidyr::separate(Len.bin, into = c("Len.start","Len.fin"), sep = ",", remove = FALSE) %>%
dplyr::mutate(Length = as.numeric(readr::parse_number(Len.start))*10,
Len.bin = paste(readr::parse_number(Len.start)*10, readr::parse_number(Len.fin)*10, sep = "-")) %>%
dplyr::group_by(Length, Len.bin) %>%
dplyr::summarise(Maturity.prop = mean(Maturity), N = n())
}
Maturity.Model<-glm(Maturity.prop~Length,data = weighted_data, family = "quasibinomial", weights = N)
L50<- MASS::dose.p(Maturity.Model,p=c(0.5))
L95<- MASS::dose.p(Maturity.Model,p=c(0.95))
if(return == "parameters") {
pars <- data.frame(rbind(L50,L95), rbind(attr(L50,"SE"), attr(L95,"SE")))
colnames(pars) <- c("Estimate", "SE")
return(pars)
}
if(max(processed_data$Length) < 500){
new <- data.frame(Length = seq(0,max(processed_data$Length),0.01))
} else{
new <- data.frame(Length = seq(0,max(processed_data$Length),0.1))
}
preddat<-cbind(Length = new, predict(Maturity.Model, data.frame(Length=new$Length),se.fit=T,type = "response"))
message("Bootstrapping logistic model with a quasibinomial error structure")
if(max(processed_data$Length) < 500){
boot_maturity <- processed_data %>% boot_data(n.bootstraps) %>%
dplyr::do( tryCatch(dplyr::mutate(.,Len.bin = cut(Length, breaks = seq(0, max(Length)+bin.width, bin.width))) %>%
tidyr::separate(Len.bin, into = c("Len.start","Len.fin"), sep = ",", remove = FALSE) %>%
dplyr::mutate(Length = as.numeric(readr::parse_number(Len.start)),
Len.bin = paste(readr::parse_number(Len.start), readr::parse_number(Len.fin), sep = "-")) %>%
dplyr::group_by(Length, Len.bin) %>%
dplyr::summarise(Maturity.prop = mean(Maturity), N = n()) %>%
glm(Maturity.prop~Length, data=.,family= "quasibinomial", weights = N) %>%
predict(data.frame(Length=new$Length),type="response") %>%
cbind(Length = new$Length, Pred =.) %>% as.data.frame(),
warning=function(w){data.frame(Length = new$Length, Pred = NA)}))
}else{
boot_maturity <- processed_data %>% boot_data(n.bootstraps) %>%
dplyr::do(tryCatch(dplyr::mutate(.,
Length = Length/10,
Len.bin = cut(Length, breaks = seq(0, max(Length)+bin.width, bin.width/10))) %>%
tidyr::separate(Len.bin, into = c("Len.start","Len.fin"), sep = ",", remove = FALSE) %>%
dplyr::mutate(Length = as.numeric(readr::parse_number(Len.start))*10,
Len.bin = paste(readr::parse_number(Len.start)*10, readr::parse_number(Len.fin)*10, sep = "-")) %>%
dplyr::group_by(Length, Len.bin) %>%
dplyr::summarise(Maturity.prop = mean(Maturity), N = n()) %>%
glm(Maturity.prop~Length, data=.,family= "quasibinomial", weights = N) %>%
predict(data.frame(Length=new$Length),type="response") %>%
cbind(Length = new$Length, Pred =.) %>% as.data.frame(),
warning=function(w){data.frame(Length = new$Length, Pred = NA)}
)
)
}
boot_ests <- boot_maturity %>% dplyr::group_by(Length) %>% dplyr::summarize(high=quantile(Pred, 0.025, na.rm = TRUE),
low=quantile(Pred, 0.975, na.rm = TRUE))
results <- cbind(boot_ests, Estimate = preddat$fit) %>% dplyr::select(Length, Estimate, high,low)
p <- ggplot(results, aes(x = Length, y = Estimate)) +
geom_bar(data = weighted_data %>% mutate(Immaturity.prop = 1 - Maturity.prop) %>%
tidyr::gather(Maturity.group, prop, -Length, -N, -Len.bin),
aes(Length, prop, fill = Maturity.group), col = "black", stat="identity", width = bin.width) +
geom_ribbon(aes(ymin = low, ymax = high), col = "royalblue", fill = "lightblue", alpha = .6)+
geom_line(size = 2, col = "royalblue") +
geom_text(data = weighted_data , inherit.aes = FALSE ,aes(Length, y = 1.1, label = N))+
geom_text(data = weighted_data , inherit.aes = FALSE ,aes(Length, y = 1.05, label = Len.bin))+
geom_point(aes(L50[1], 0.5), col = 'black', size = 4)+
scale_fill_manual(values=c("light grey", "grey"), guide = "none")+
scale_y_continuous(name = "Proportion mature", limits = c(0,1.15), expand = c(0,0), breaks = c(seq(0,1,.2),1.05,1.1),
labels = c(seq(0,1,.2), "Length bin", "n")) +
scale_x_continuous(name = "Length (cm)",
limits = c(floor(min(weighted_data$Length))-bin.width/2,ceiling(max(weighted_data$Length))+bin.width/2),
expand = c(0,0),
breaks = weighted_data$Length)+
theme_bw()+
theme(panel.grid = element_blank())
if(max(processed_data$Length) > 500){
p <- suppressMessages(p + scale_x_continuous(name = "Length (mm)",
limits =c(min(processed_data$Length)*.8,max(processed_data$Length)*1.1),
expand = c(0,0),
breaks = weighted_data$Length))
}
}
if (return == "estimates"){
return(results)
}
if(return == "plot"){
return(p)
}
}
| /scratch/gouwar.j/cran-all/cranData/AquaticLifeHistory/R/Maturity_functions.R |
## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
## -----------------------------------------------------------------------------
citation("AquaticLifeHistory")
## ----message=FALSE, warning=FALSE---------------------------------------------
library(AquaticLifeHistory)
data("growth_data")
head(growth_data)
## ----message=FALSE, fig.height = 6, fig.width = 8, eval=FALSE-----------------
# Estimate_Growth(data = growth_data)
## ----message=FALSE, fig.height = 6, fig.width = 8, echo =FALSE----------------
Estimate_Growth(data = growth_data, n.bootstraps = 10)
## ----message=FALSE, fig.height = 6, fig.width = 8, eval = FALSE---------------
# Estimate_Growth(data = growth_data, models = "VB")
## ----message=FALSE, fig.height = 6, fig.width = 8, echo=FALSE-----------------
Estimate_Growth(data = growth_data, models = "VB", n.bootstraps = 10)
## ----message=FALSE, fig.height = 6, fig.width = 8, eval = FALSE---------------
# Estimate_Growth(data = growth_data, models = c("Log", "Gom"))
## ----message=FALSE, fig.height = 6, fig.width = 8, echo = FALSE---------------
Estimate_Growth(data = growth_data, models = c("Log", "Gom"), n.bootstraps = 10)
## ----error = TRUE, message=FALSE, fig.height = 6, fig.width = 8, eval = FALSE----
# Estimate_Growth(data = growth_data, models = "VBGF")
## ----error = TRUE, message=FALSE, fig.height = 6, fig.width = 8,echo=FALSE----
Estimate_Growth(data = growth_data, models = "VBGF", n.bootstraps = 10)
## ----message=FALSE, fig.height = 6, fig.width = 8, eval = FALSE---------------
# Results <- Estimate_Growth(data = growth_data, models = "VB", plot.legend = FALSE)
## ----message=FALSE, fig.height = 6, fig.width = 8, echo = FALSE---------------
Results <- Estimate_Growth(data = growth_data, models = "VB", plot.legend = FALSE, n.bootstraps = 10)
## ----message=FALSE, fig.height = 6, fig.width = 8, eval = FALSE---------------
# new.dat <- growth_data
# new.dat$Length <- new.dat$Length/10
#
# Results <- Estimate_Growth(new.dat)
## ----message=FALSE, fig.height = 6, fig.width = 8, echo=FALSE-----------------
new.dat <- growth_data
new.dat$Length <- new.dat$Length/10
Results <- Estimate_Growth(new.dat, n.bootstraps = 10)
## ----message=FALSE, fig.height = 6, fig.width = 8, eval=FALSE-----------------
# results <- Estimate_Growth(data = growth_data, plots = FALSE)
#
# Length_at_age_estimates <- results$Estimates
#
# head(Length_at_age_estimates)
## ----message=FALSE, fig.height = 6, fig.width = 8, echo=FALSE-----------------
results <- Estimate_Growth(data = growth_data, plots = FALSE, n.bootstraps = 10)
Length_at_age_estimates <- results$Estimates
head(Length_at_age_estimates)
## ----message=FALSE, eval = FALSE----------------------------------------------
# results <- Estimate_Growth(data = growth_data, plots = FALSE)
# Calculate_MMI(results)
## ----message=FALSE, echo=FALSE------------------------------------------------
results <- Estimate_Growth(data = growth_data, plots = FALSE, n.bootstraps = 10)
Calculate_MMI(results)
## ----warning = FALSE, message=FALSE, fig.height = 8, fig.width = 6, eval = FALSE----
# # Create data.frames of separate sexes
# Females <- dplyr::filter(growth_data, Sex == "F")
# Males <- dplyr::filter(growth_data, Sex == "M")
#
# # Estimate growth
# Female_ests <- Estimate_Growth(Females,n.bootstraps = 1000, plots = FALSE)
# Male_ests <- Estimate_Growth(Males, n.bootstraps = 1000,plots = FALSE)
#
# # Combine data sets with a new variable designating sex
# Female_LAA <- Female_ests$Estimates
# Female_LAA$Sex <- "F"
#
# Male_LAA <- Male_ests$Estimates
# Male_LAA$Sex <- "M"
#
# combined_data <- rbind(Male_LAA, Female_LAA)
#
# library(ggplot2)
#
# ggplot(combined_data, aes(x = Age, y = AVG, fill = Model, col = Model)) +
# facet_wrap(~Sex, ncol = 1, scales = "free")+
# geom_point(data = Males, aes(x = Age, y = Length, fill = NULL, col = NULL), alpha = .3) +
# geom_point(data = Females, aes(x = Age, y = Length, fill = NULL, col = NULL), alpha = .3) +
# geom_ribbon(aes(ymin = low, ymax = upp, col = NA), alpha = 0.2)+
# geom_line(size = 1)+
# scale_y_continuous(name = "Length (mm)", limits = c(0,2500), expand = c(0,0))+
# scale_x_continuous(name = "Age (years)", limits = c(0,18), expand = c(0,0))+
# theme_bw()
## ----warning = FALSE, message=FALSE, fig.height = 8, fig.width = 6, echo = FALSE----
# Create data.frames of separate sexes
Females <- dplyr::filter(growth_data, Sex == "F")
Males <- dplyr::filter(growth_data, Sex == "M")
# Estimate growth
Female_ests <- Estimate_Growth(Females,n.bootstraps = 10, plots = FALSE)
Male_ests <- Estimate_Growth(Males, n.bootstraps = 10,plots = FALSE)
# Combine data sets with a new variable designating sex
Female_LAA <- Female_ests$Estimates
Female_LAA$Sex <- "F"
Male_LAA <- Male_ests$Estimates
Male_LAA$Sex <- "M"
combined_data <- rbind(Male_LAA, Female_LAA)
library(ggplot2)
ggplot(combined_data, aes(x = Age, y = AVG, fill = Model, col = Model)) +
facet_wrap(~Sex, ncol = 1, scales = "free")+
geom_point(data = Males, aes(x = Age, y = Length, fill = NULL, col = NULL), alpha = .3) +
geom_point(data = Females, aes(x = Age, y = Length, fill = NULL, col = NULL), alpha = .3) +
geom_ribbon(aes(ymin = low, ymax = upp, col = NA), alpha = 0.2)+
geom_line(size = 1)+
scale_y_continuous(name = "Length (mm)", limits = c(0,2500), expand = c(0,0))+
scale_x_continuous(name = "Age (years)", limits = c(0,18), expand = c(0,0))+
theme_bw()
## ----message=FALSE, fig.height = 6, fig.width = 8, eval=FALSE-----------------
# Estimate_Growth(growth_data, Birth.Len = 600)
## ----message=FALSE, fig.height = 6, fig.width = 8, echo=FALSE-----------------
Estimate_Growth(growth_data, Birth.Len = 600, n.bootstraps = 10)
## ----message=FALSE, fig.height = 6, fig.width = 8, eval = FALSE---------------
# # Fit models
# two_pars <- Estimate_Growth(growth_data, models = "VB", Birth.Len = 600, plots = FALSE)
# three_pars <- Estimate_Growth(growth_data, models = "VB", plots = FALSE)
#
# # Change Model name to represent how many parameters they have
# two_pars_Ests <- two_pars$Estimates
# two_pars_Ests$Model <- "2 parameter VBGF"
#
# three_pars_Ests <- three_pars$Estimates
# three_pars_Ests$Model <- "3 parameter VBGF"
#
# combined_data <- rbind(two_pars_Ests, three_pars_Ests)
#
# ggplot(combined_data, aes(x = Age, y = AVG, fill = Model, col = Model)) +
# geom_point(data = growth_data, aes(x = Age, y = Length, fill = NULL, col = NULL), alpha = .3) +
# geom_ribbon(aes(ymin = low, ymax = upp, col = NA), alpha = 0.2)+
# geom_line(size = 1)+
# scale_y_continuous(name = "Length (mm)", limits = c(0,2500), expand = c(0,0))+
# scale_x_continuous(name = "Age (years)", limits = c(0,18), expand = c(0,0))+
# theme_bw() +
# theme(legend.position = c(0.8, 0.2))
## ----message=FALSE, fig.height = 6, fig.width = 8, echo=FALSE-----------------
# Fit models
two_pars <- Estimate_Growth(growth_data, models = "VB", Birth.Len = 600, plots = FALSE, n.bootstraps = 10)
three_pars <- Estimate_Growth(growth_data, models = "VB", plots = FALSE, n.bootstraps = 10)
# Change Model name to represent how many parameters they have
two_pars_Ests <- two_pars$Estimates
two_pars_Ests$Model <- "2 parameter VBGF"
three_pars_Ests <- three_pars$Estimates
three_pars_Ests$Model <- "3 parameter VBGF"
combined_data <- rbind(two_pars_Ests, three_pars_Ests)
ggplot(combined_data, aes(x = Age, y = AVG, fill = Model, col = Model)) +
geom_point(data = growth_data, aes(x = Age, y = Length, fill = NULL, col = NULL), alpha = .3) +
geom_ribbon(aes(ymin = low, ymax = upp, col = NA), alpha = 0.2)+
geom_line(size = 1)+
scale_y_continuous(name = "Length (mm)", limits = c(0,2500), expand = c(0,0))+
scale_x_continuous(name = "Age (years)", limits = c(0,18), expand = c(0,0))+
theme_bw() +
theme(legend.position = c(0.8, 0.2))
## ----eval = FALSE-------------------------------------------------------------
# Estimate_Growth(growth_data, correlation.matrix = TRUE)
## ----echo=FALSE---------------------------------------------------------------
Estimate_Growth(growth_data, correlation.matrix = TRUE, n.bootstraps = 10)
| /scratch/gouwar.j/cran-all/cranData/AquaticLifeHistory/inst/doc/Growth_estimation.R |
---
title: "Growth estimation example using the AquaticLifeHistory package"
author: "Jonathan Smart"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Growth estimation example using the AquaticLifeHistory package}
%\VignetteEncoding{UTF-8}
%\VignetteEngine{knitr::rmarkdown}
editor_options:
chunk_output_type: console
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
# Citation
Please cite this package if it is used in any publication. The citation details can be accessed in the command line:
```{r}
citation("AquaticLifeHistory")
```
# Introduction
Growth information attained through length-at-age analysis is a key component in many fisheries analyses. This package gives the user the ability to quickly and efficiently estimate growth for an aquatic species (fishes, sharks, molluscs, crustaceans, etc.) using robust and contemporary techniques. This can be achieved using either a single model approach (i.e. application of a von Bertalanffy growth function) or through a multi-model approach where multiple models are applied simultaneously and compared.This package will provide parameter estimates with errors, length-at-age estimates with bootstrapped confidence intervals, plots and model statistics - providing users with everything required for scientific publication.
# Multi-model growth analysis with `Estimate_Growth()`
`Estimate_Growth()` is the main function for length-at-age modelling and offers the user a lot of flexibility which we will run through. This function applies the multi-model approach outlined in [Smart et al (2016)](https://onlinelibrary.wiley.com/doi/abs/10.1111/faf.12154) and will give the user the option of applying three growth models.
These include the von Bertalanffy growth model:
$$L_{a}=L_{0}+(L_{\infty}-L_{0})(1-e^{-ka})$$
the Gompertz model:
$$L_{a}=L_{0}e^{log(L_{\infty}/L_{0})(1-e^{-ga})})$$
and the Logistic model:
$$L_{a}=(L_{\infty}*L_{0}*e^{ga})/(L_{\infty}+L_{0}*e^{ga-1})$$
where $L_{a}$ is length-at-age $a$, $L_{\infty}$ is the asymptotic length and $L_{0}$ is the length-at-birth. Each model has its own growth coefficient ($k$ = von Bertalanfy, $g$ = Gompertz and $g$ = Logistic). These growth coefficients are incomparable between models (though the Gompertz and Logistic models share the same notation) whereas the $L_{\infty}$ and $L_{0}$ have the same interpretation between models.
Most applications of growth models for fish have used a $t_{0}$ rather than $L_{0}$ which represents the time-at-length-zero rather than a length-at-birth (i.e time-zero). However, $t_{0}$ does not have the same definition across multiple growth models whereas $L_{0}$ always refers to length-at-birth. This parameter is therefore used a multi-model approach. $t_{0}$ can be calculated from the VBGF parameters as:
$$t_{0}=(1/k)log(L_{\infty}-L_{0})/L_{\infty})$$
Each of these models provide different growth forms and applying them simultaneously and comparing their fits will increase the chance that an appropriate model is applied to the data. Alternatively, the user can apply a single model or select a combination (see further down).
Using `Estimate_Growth()` will perform the following:
* Fit the specified growth models using an `nls()` function, returning the parameters and summary statistics.
* Calculate Akaike's information criterion ($AIC$) values and calculate model weights ($w$).
* Bootstrap the data and return 95% confidence intervals for a growth curve over the age range of the data.
* Return a plot with the growth curves with confidence intervals (can be disabled to return raw results).
* Return parameter correlation matrices when requested.
## Input data
The `data` argument of `Estimate_Growth()` requires a data.frame of length and age data. However, this function is flexible and does not require the data to be preprocessed. The function will automatically determine the "Age" column and the "Length" column by looking for sensibly named columns. For example, the length column will accept a column named "Length", "Len", "STL", "TL", "LT" or "size". If a column can't be distinguished the user will be prompted to rename the necessary column. This setup means that a data set that contains additional columns (such as "Sex" or "Date") can be passed to the function. The only issue the user should be aware of is that multiple length columns can't be provided (i.e "TL" and "FL").
## Example applications
Growth functions can be tested using an included data set which contains length-at-age data for common blacktip sharks (*Carcharhinus limbatus*) from Indonesia.
```{r, message=FALSE, warning=FALSE}
library(AquaticLifeHistory)
data("growth_data")
head(growth_data)
```
Length-at-age 95% confidence intervals will be produced for the growth curve through bootstrapping with 1000 iterations being default. The `Estimate_growth()` will return a list of parameter estimates for three candidate models: the von Bertalanffy growth function ("VB"), Gompertz growth function ("Gom") and Logistic growth function ("Log"). The $AIC$ results for each model will also be returned as a list element, demonstrating which growth model best fit the data. A plot will be printed with the growth curves for all included models.
```{r, message=FALSE, fig.height = 6, fig.width = 8, eval=FALSE}
Estimate_Growth(data = growth_data)
```
```{r, message=FALSE, fig.height = 6, fig.width = 8, echo =FALSE}
Estimate_Growth(data = growth_data, n.bootstraps = 10)
```
The `Estimate_Growth()` function produces these outputs in three steps:
1. Starting parameters for the models are determined using the Ford-Walford method.
2. The models are fit to the data using the `nls()` function.
+ The `nls()` function can be very fragile and prone to non-convergence if the data is not well suited to a particular model. Using the `models` argument to specify different models is a good way to initially exclude problematic growth models if a non-convergence error message occurs.
3. Bootstrapping is performed to determine 95% confidence intervals along the growth curve. These are included in the plot or returned to the user if `plots = FALSE` is used.
+ The bootstrap iterations are specified using the `n.bootstraps` argument. The default is 1000.
## Fitting specific models
One model can also be specified using the `models` argument:
```{r, message=FALSE, fig.height = 6, fig.width = 8, eval = FALSE}
Estimate_Growth(data = growth_data, models = "VB")
```
```{r, message=FALSE, fig.height = 6, fig.width = 8, echo=FALSE}
Estimate_Growth(data = growth_data, models = "VB", n.bootstraps = 10)
```
Or several can be specified:
```{r, message=FALSE, fig.height = 6, fig.width = 8, eval = FALSE}
Estimate_Growth(data = growth_data, models = c("Log", "Gom"))
```
```{r, message=FALSE, fig.height = 6, fig.width = 8, echo = FALSE}
Estimate_Growth(data = growth_data, models = c("Log", "Gom"), n.bootstraps = 10)
```
Note: The three models must be specified as "VB", "Log" and "Gom". Otherwise there will be an error
```{r, error = TRUE, message=FALSE, fig.height = 6, fig.width = 8, eval = FALSE}
Estimate_Growth(data = growth_data, models = "VBGF")
```
```{r, error = TRUE, message=FALSE, fig.height = 6, fig.width = 8,echo=FALSE}
Estimate_Growth(data = growth_data, models = "VBGF", n.bootstraps = 10)
```
## Plot alterations
If you are plotting one model you probably don't want a legend included. This can be removed using the `plot.legend` argument. This also works when several models are plotted
```{r, message=FALSE, fig.height = 6, fig.width = 8, eval = FALSE}
Results <- Estimate_Growth(data = growth_data, models = "VB", plot.legend = FALSE)
```
```{r, message=FALSE, fig.height = 6, fig.width = 8, echo = FALSE}
Results <- Estimate_Growth(data = growth_data, models = "VB", plot.legend = FALSE, n.bootstraps = 10)
```
Lastly, the y-axis label will automatically scale the unit from mm to cm based on the input data
```{r, message=FALSE, fig.height = 6, fig.width = 8, eval = FALSE}
new.dat <- growth_data
new.dat$Length <- new.dat$Length/10
Results <- Estimate_Growth(new.dat)
```
```{r, message=FALSE, fig.height = 6, fig.width = 8, echo=FALSE}
new.dat <- growth_data
new.dat$Length <- new.dat$Length/10
Results <- Estimate_Growth(new.dat, n.bootstraps = 10)
```
## Returning length-at-age estimates
It is recommended that users create their own plots for publications. Therefore setting `plots = FALSE` will provide these estimates as an additional list object rather than printing a plot.
```{r, message=FALSE, fig.height = 6, fig.width = 8, eval=FALSE}
results <- Estimate_Growth(data = growth_data, plots = FALSE)
Length_at_age_estimates <- results$Estimates
head(Length_at_age_estimates)
```
```{r, message=FALSE, fig.height = 6, fig.width = 8, echo=FALSE}
results <- Estimate_Growth(data = growth_data, plots = FALSE, n.bootstraps = 10)
Length_at_age_estimates <- results$Estimates
head(Length_at_age_estimates)
```
# Model averaged results with `Calculate_MMI`
Multi-model inference (MMI) can be useful when no particular candidate model provides a better fit than the others ($\Delta AIC$ < 2). This involves averaging all models across the growth curve based on their AIC weights ($w$). It will return model averaged values of $L_{\infty}$ and $L_{0}$ with averaged standard errors. No model averaged growth completion parameters ($k$ for VBGF, $g$ for Gompertz or $g$ for Logistic) are returned as these parameters are not comparable across models.
`Calculate_MMI` takes the outputs of `Estimate_Growth` with `plots = FALSE` (so that length-at-age estimates are available) and will calculate MMI parameters and standard errors as well as model averaged length-at-age estimates.
```{r, message=FALSE, eval = FALSE}
results <- Estimate_Growth(data = growth_data, plots = FALSE)
Calculate_MMI(results)
```
```{r, message=FALSE, echo=FALSE}
results <- Estimate_Growth(data = growth_data, plots = FALSE, n.bootstraps = 10)
Calculate_MMI(results)
```
Be aware that bootstrapping cannot be applied for MMI so no length-at-age errors are available. Also multi-model theory dictates that model averaged errors will be larger than the cumulative errors of candidate models. So don't be alarmed if you get large parameter standard errors.
# Sex specific growth curves
Separating the sexes is common and is achieved by sub setting data and running the function multiple times. They can then be combined and plotted afterwards. This can be done for one model or several. Here is an example using the `ggplot2` package.
```{r, warning = FALSE, message=FALSE, fig.height = 8, fig.width = 6, eval = FALSE}
# Create data.frames of separate sexes
Females <- dplyr::filter(growth_data, Sex == "F")
Males <- dplyr::filter(growth_data, Sex == "M")
# Estimate growth
Female_ests <- Estimate_Growth(Females,n.bootstraps = 1000, plots = FALSE)
Male_ests <- Estimate_Growth(Males, n.bootstraps = 1000,plots = FALSE)
# Combine data sets with a new variable designating sex
Female_LAA <- Female_ests$Estimates
Female_LAA$Sex <- "F"
Male_LAA <- Male_ests$Estimates
Male_LAA$Sex <- "M"
combined_data <- rbind(Male_LAA, Female_LAA)
library(ggplot2)
ggplot(combined_data, aes(x = Age, y = AVG, fill = Model, col = Model)) +
facet_wrap(~Sex, ncol = 1, scales = "free")+
geom_point(data = Males, aes(x = Age, y = Length, fill = NULL, col = NULL), alpha = .3) +
geom_point(data = Females, aes(x = Age, y = Length, fill = NULL, col = NULL), alpha = .3) +
geom_ribbon(aes(ymin = low, ymax = upp, col = NA), alpha = 0.2)+
geom_line(size = 1)+
scale_y_continuous(name = "Length (mm)", limits = c(0,2500), expand = c(0,0))+
scale_x_continuous(name = "Age (years)", limits = c(0,18), expand = c(0,0))+
theme_bw()
```
```{r, warning = FALSE, message=FALSE, fig.height = 8, fig.width = 6, echo = FALSE}
# Create data.frames of separate sexes
Females <- dplyr::filter(growth_data, Sex == "F")
Males <- dplyr::filter(growth_data, Sex == "M")
# Estimate growth
Female_ests <- Estimate_Growth(Females,n.bootstraps = 10, plots = FALSE)
Male_ests <- Estimate_Growth(Males, n.bootstraps = 10,plots = FALSE)
# Combine data sets with a new variable designating sex
Female_LAA <- Female_ests$Estimates
Female_LAA$Sex <- "F"
Male_LAA <- Male_ests$Estimates
Male_LAA$Sex <- "M"
combined_data <- rbind(Male_LAA, Female_LAA)
library(ggplot2)
ggplot(combined_data, aes(x = Age, y = AVG, fill = Model, col = Model)) +
facet_wrap(~Sex, ncol = 1, scales = "free")+
geom_point(data = Males, aes(x = Age, y = Length, fill = NULL, col = NULL), alpha = .3) +
geom_point(data = Females, aes(x = Age, y = Length, fill = NULL, col = NULL), alpha = .3) +
geom_ribbon(aes(ymin = low, ymax = upp, col = NA), alpha = 0.2)+
geom_line(size = 1)+
scale_y_continuous(name = "Length (mm)", limits = c(0,2500), expand = c(0,0))+
scale_x_continuous(name = "Age (years)", limits = c(0,18), expand = c(0,0))+
theme_bw()
```
# Combining two and three parameter models
It is common practice for fish species to fix $L_{0}$ as this parameter has a direct relation to length-at-birth (often zero for fish). This is done via a single argument `Birth.Len`. If this is unspecified then three parameter models are used. However, if `Birth.Len` is specified then two parameters are used with that value used to fix the $L_{0}$ parameter.
```{r, message=FALSE, fig.height = 6, fig.width = 8, eval=FALSE}
Estimate_Growth(growth_data, Birth.Len = 600)
```
```{r, message=FALSE, fig.height = 6, fig.width = 8, echo=FALSE}
Estimate_Growth(growth_data, Birth.Len = 600, n.bootstraps = 10)
```
These can be plotted alongside there three parameter versions as well. Here is an example for the VBGF
```{r, message=FALSE, fig.height = 6, fig.width = 8, eval = FALSE}
# Fit models
two_pars <- Estimate_Growth(growth_data, models = "VB", Birth.Len = 600, plots = FALSE)
three_pars <- Estimate_Growth(growth_data, models = "VB", plots = FALSE)
# Change Model name to represent how many parameters they have
two_pars_Ests <- two_pars$Estimates
two_pars_Ests$Model <- "2 parameter VBGF"
three_pars_Ests <- three_pars$Estimates
three_pars_Ests$Model <- "3 parameter VBGF"
combined_data <- rbind(two_pars_Ests, three_pars_Ests)
ggplot(combined_data, aes(x = Age, y = AVG, fill = Model, col = Model)) +
geom_point(data = growth_data, aes(x = Age, y = Length, fill = NULL, col = NULL), alpha = .3) +
geom_ribbon(aes(ymin = low, ymax = upp, col = NA), alpha = 0.2)+
geom_line(size = 1)+
scale_y_continuous(name = "Length (mm)", limits = c(0,2500), expand = c(0,0))+
scale_x_continuous(name = "Age (years)", limits = c(0,18), expand = c(0,0))+
theme_bw() +
theme(legend.position = c(0.8, 0.2))
```
```{r, message=FALSE, fig.height = 6, fig.width = 8, echo=FALSE}
# Fit models
two_pars <- Estimate_Growth(growth_data, models = "VB", Birth.Len = 600, plots = FALSE, n.bootstraps = 10)
three_pars <- Estimate_Growth(growth_data, models = "VB", plots = FALSE, n.bootstraps = 10)
# Change Model name to represent how many parameters they have
two_pars_Ests <- two_pars$Estimates
two_pars_Ests$Model <- "2 parameter VBGF"
three_pars_Ests <- three_pars$Estimates
three_pars_Ests$Model <- "3 parameter VBGF"
combined_data <- rbind(two_pars_Ests, three_pars_Ests)
ggplot(combined_data, aes(x = Age, y = AVG, fill = Model, col = Model)) +
geom_point(data = growth_data, aes(x = Age, y = Length, fill = NULL, col = NULL), alpha = .3) +
geom_ribbon(aes(ymin = low, ymax = upp, col = NA), alpha = 0.2)+
geom_line(size = 1)+
scale_y_continuous(name = "Length (mm)", limits = c(0,2500), expand = c(0,0))+
scale_x_continuous(name = "Age (years)", limits = c(0,18), expand = c(0,0))+
theme_bw() +
theme(legend.position = c(0.8, 0.2))
```
A two parameter model is demonstrated here for sharks as this is the data used in these examples. However, fixing growth parameters for sharks is less appropriate than techniques such as back-calculation. However, for fish species, length-at-birth is close to zero due to their larval life stage. Therefore, length-at-birth is commonly fixed at zero to represent this.
# Correlation matrices
Each of the growth models fit in these analyses have a multivariate normal distribution. This means that each parameter has a normal distribution but are correlated to one another. Therefore, if you would like to use these parameters in simulation analyses, a correlation matrix is needed to include parameter values in the simulations. This is not an analysis that is included in this package. However, the ability to return the correlation matrix is included in the `Estimate_Growth()` function by using `correlation.matrix = TRUE`.
```{r, eval = FALSE}
Estimate_Growth(growth_data, correlation.matrix = TRUE)
```
```{r, echo=FALSE}
Estimate_Growth(growth_data, correlation.matrix = TRUE, n.bootstraps = 10)
```
Full details on these approaches can be found in:
Smart, J. J., Chin, A. , Tobin, A. J. and Simpfendorfer, C. A. (2016) Multimodel approaches in shark and ray growth studies:
strengths, weaknesses and the future. Fish and Fisheries, 17: 955-971.https://onlinelibrary.wiley.com/doi/abs/10.1111/faf.12154 which should be cited if this package is used in a publication.
| /scratch/gouwar.j/cran-all/cranData/AquaticLifeHistory/inst/doc/Growth_estimation.Rmd |
## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
## -----------------------------------------------------------------------------
citation("AquaticLifeHistory")
## ----logistic example, eval=FALSE---------------------------------------------
# glm(formula = Maturity~Age,data = my.data, family = "binomial")
#
## ----logistic input data, message=FALSE, warning=FALSE------------------------
library(AquaticLifeHistory)
data("maturity_data")
head(maturity_data)
# Maturity variable is binary (immature = 0, mature = 1)
range(maturity_data$Maturity)
## ----parameters, message=FALSE, warning=FALSE, eval=FALSE---------------------
#
# Estimate_Age_Maturity(maturity_data)
#
## ----bootstrapped, warning=FALSE, fig.height = 6, fig.width =7, eval=FALSE----
# # selecting return = "plot" returns a ggplot object rather than the parameters.
# Estimate_Age_Maturity(maturity_data, return = "plot", n.bootstraps = 1000)
#
## ----bootstrapped2, warning=FALSE, fig.height = 6, fig.width =7, echo=FALSE----
# selecting return = "plot" returns a ggplot object rather than the parameters.
Estimate_Age_Maturity(maturity_data, return = "plot", n.bootstraps = 10)
## ----with points bootstrapped, warning=FALSE, fig.height = 6, fig.width =7, eval=FALSE----
# # selecting return = "plot" returns a ggplot object rather than the parameters.
# Estimate_Age_Maturity(maturity_data, return = "plot", n.bootstraps = 1000, display.points = TRUE)
#
## ----with points bootstrapped2, warning=FALSE, fig.height = 6, fig.width =7, echo = FALSE----
# selecting return = "plot" returns a ggplot object rather than the parameters.
Estimate_Age_Maturity(maturity_data, return = "plot", n.bootstraps = 10, display.points = TRUE)
## ----comparison, message=FALSE, warning=FALSE, eval = FALSE-------------------
#
# Estimate_Age_Maturity(maturity_data)
#
# Estimate_Age_Maturity(maturity_data, error.structure = "quasibinomial")
#
## ----quasi age plot, warning=FALSE, fig.height = 6, fig.width =7, eval = FALSE----
# # selecting return = "plot" returns a ggplot object rather than the parameters.
# Estimate_Age_Maturity(maturity_data, return = "plot", n.bootstraps = 1000, error.structure = "quasibinomial")
#
## ----quasi age plot2, warning=FALSE, fig.height = 6, fig.width =7, echo=FALSE----
# selecting return = "plot" returns a ggplot object rather than the parameters.
Estimate_Age_Maturity(maturity_data, return = "plot", n.bootstraps = 10, error.structure = "quasibinomial")
## ----length parameters, message=FALSE, warning=FALSE, eval=FALSE--------------
#
# Estimate_Len_Maturity(maturity_data)
#
## ----bootstrapped length, warning=FALSE, fig.height = 6, fig.width =7, eval = FALSE----
# # selecting return = "plot" returns a ggplot object rather than the parameters.
# Estimate_Len_Maturity(maturity_data, return = "plot", n.bootstraps = 1000, display.points = TRUE)
#
## ----bootstrapped length2, warning=FALSE, fig.height = 6, fig.width =7, echo = FALSE----
# selecting return = "plot" returns a ggplot object rather than the parameters.
Estimate_Len_Maturity(maturity_data, return = "plot", n.bootstraps = 10, display.points = TRUE)
## ----length unit changed, warning=FALSE, fig.height = 6, fig.width =7, eval=FALSE----
# new_data <- maturity_data
# new_data$Length <- new_data$Length*10
#
# Estimate_Len_Maturity(new_data, return = "plot", n.bootstraps = 1000, display.points = TRUE)
#
## ----length unit changed2, warning=FALSE, fig.height = 6, fig.width =7,echo=FALSE----
new_data <- maturity_data
new_data$Length <- new_data$Length*10
Estimate_Len_Maturity(new_data, return = "plot", n.bootstraps = 10, display.points = TRUE)
## ----bin width, warning=FALSE, fig.height = 6, fig.width =8, eval=FALSE------
# # selecting return = "plot" returns a ggplot object rather than the parameters.
# Estimate_Len_Maturity(maturity_data,
# return = "plot",
# n.bootstraps = 1000,
# error.structure = "quasibinomial",
# bin.width = 25)
#
## ----bin width2, warning=FALSE, fig.height = 6, fig.width =8, echo = FALSE----
# selecting return = "plot" returns a ggplot object rather than the parameters.
Estimate_Len_Maturity(maturity_data,
return = "plot",
n.bootstraps = 10,
error.structure = "quasibinomial",
bin.width = 25)
## ----bin width comparison, warning=FALSE, eval = FALSE------------------------
# # Binomial model
# Estimate_Len_Maturity(maturity_data)
#
# # Length in 10 cm bins
# Estimate_Len_Maturity(maturity_data,
# error.structure = "quasibinomial",
# bin.width = 10)
#
# # Length in 25 cm bins
# Estimate_Len_Maturity(maturity_data,
# error.structure = "quasibinomial",
# bin.width = 25)
#
# # Length in 30 cm bins
# Estimate_Len_Maturity(maturity_data,
# error.structure = "quasibinomial",
# bin.width = 30)
#
## ----estimate, warning=FALSE, eval = FALSE------------------------------------
# # selecting return = "plot" returns a ggplot object rather than the parameters.
# Mat_at_age_estimates <- Estimate_Age_Maturity(maturity_data,
# return = "estimates",
# n.bootstraps = 1000,
# error.structure = "quasibinomial")
#
#
# Mat_at_len_estimates <- Estimate_Len_Maturity(maturity_data,
# return = "estimates",
# n.bootstraps = 1000,
# error.structure = "binomial")
#
# head(Mat_at_age_estimates)
#
# head(Mat_at_len_estimates)
#
## ----estimate2, warning=FALSE, echo=FALSE-------------------------------------
# selecting return = "plot" returns a ggplot object rather than the parameters.
Mat_at_age_estimates <- Estimate_Age_Maturity(maturity_data,
return = "estimates",
n.bootstraps = 10,
error.structure = "quasibinomial")
Mat_at_len_estimates <- Estimate_Len_Maturity(maturity_data,
return = "estimates",
n.bootstraps = 10,
error.structure = "binomial")
head(Mat_at_age_estimates)
head(Mat_at_len_estimates)
| /scratch/gouwar.j/cran-all/cranData/AquaticLifeHistory/inst/doc/Maturity_analyses.R |
---
title: "Maturity estimation for aquatic species through the AquaticLifeHistory package"
author: "Jonathan Smart"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Maturity estimation for aquatic species through the AquaticLifeHistory package}
%\VignetteEncoding{UTF-8}
%\VignetteEngine{knitr::rmarkdown}
editor_options:
chunk_output_type: console
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
# Citation
Please cite this package if it is used in any publication. The citation details can be accessed in the command line:
```{r}
citation("AquaticLifeHistory")
```
# Introduction
Maturity estimation is performed by fitting a maturity ogive to binary maturity statuses for either length or age data. Maturity ogives are fitted using a glm with a logit link function and usually with a binomial error structure (but we'll touch on this soon). A glm of this sort is fitted in R using:
```{r logistic example, eval=FALSE}
glm(formula = Maturity~Age,data = my.data, family = "binomial")
```
The default link function for a binomial error structure is the logit link function. Therefore this does not need to be specified.
All maturity analyses using a logistic ogive are fitted in this manner and this is the basic operation occurring in all the maturity functions in the `AquaticLifeHistory` package. However, getting all of the information needed to produce analyses for publication can involve several steps with a few different decisions needed. Therefore the `Estimate_Age_Maturity` and `Estimate_Len_Maturity` functions handle much of these additional steps. However, it is important for the user to understand that these are basically wrapper functions around a glm call. As such the analyses inside these functions are simple to implement outside of this package.
The `Estimate_Age_Maturity` and `Estimate_Len_Maturity` functions perform the following:
* Estimate the length or age at 50% ($L_{50}$ or $A_{50}$ ) and 95% ($L_{95}$ or $A_{95}$) maturity with standard errors. Standard errors are important outputs and should always be reported for parameters.
* Bootstrap the data with a specified number of iterations to produce 95% confidence intervals about the curve
* Produce a plot of either:
+ A standard logistic ogive with a binomial error structure. This is fit to binary data.
+ A binned logistic ogive with a quasi binomial error structure. This is fit to proportion mature data for specified length or age bins. These bins are created inside the function using a specified bin width.
* Return the parameter estimates, plots of the maturity ogive or the predicted ogive fits with bootstrapped estimates for the user to produce their own plots (recommended if the outputs are meant for publication).
# Input data
The input data for both `Estimate_Age_Maturity` and `Estimate_Len_Maturity` functions require an age or length variable as well as a binary maturity variable. These functions accept various column headings for flexibility. For example `Estimate_Len_Maturity` will accept a column named "Length", "Len", "STL", "TL", "LT" or "size" (plus others) as the input column for the length variable. However, the maturity and age columns must have names that begin with "mat" and "age", respectively. The variable names needed by the functions are **not** case sensitive.
A data set for female silky sharks (*Carcharhinus falciformis*) from Papua New Guinea is included as example data. This shows the typical format accepted by both functions.
```{r logistic input data, message=FALSE, warning=FALSE}
library(AquaticLifeHistory)
data("maturity_data")
head(maturity_data)
# Maturity variable is binary (immature = 0, mature = 1)
range(maturity_data$Maturity)
```
# Using `Estimate_Age_Maturity`
Both maturity functions produce very similar outputs based on either age or length data. They are built to handle the same data set so there is no need to subset your data for just length or age. Each function will identify the variables it needs and will ignore the others.
The `Estimate_Age_Maturity` function unsurprisingly estimates age-at-maturity. In doing so it gives you a choice of model:
* Binomial model fitted to binary data
* Quasi binomial model fitted to binned proportion mature data
The input data is the same for both as the age bins are handled automatically.
## Binomial model
The default call to `Estimate_Age_Maturity` will return your parameters with their standard errors (which you should **ALWAYS** report). The SE's are the asymptotic errors from the logistic ogive
```{r parameters, message=FALSE, warning=FALSE, eval=FALSE}
Estimate_Age_Maturity(maturity_data)
```
However, if you would like to get a little more out of this function, you can have it return a plot with bootstrapped confidence intervals around the curve
```{r bootstrapped, warning=FALSE, fig.height = 6, fig.width =7, eval=FALSE}
# selecting return = "plot" returns a ggplot object rather than the parameters.
Estimate_Age_Maturity(maturity_data, return = "plot", n.bootstraps = 1000)
```
```{r bootstrapped2, warning=FALSE, fig.height = 6, fig.width =7, echo=FALSE}
# selecting return = "plot" returns a ggplot object rather than the parameters.
Estimate_Age_Maturity(maturity_data, return = "plot", n.bootstraps = 10)
```
This is a standard logistic ogive with a binomial error structure that has been fitted to binary data. The blue line is the predicted maturity ogive over the age range of the species, the black point marks the length-at-50%-mature and the grey shading shows the bootstrapped 95% confidence intervals.
Additionally, you can display the binary data by setting `display.points = TRUE`
```{r with points bootstrapped, warning=FALSE, fig.height = 6, fig.width =7, eval=FALSE}
# selecting return = "plot" returns a ggplot object rather than the parameters.
Estimate_Age_Maturity(maturity_data, return = "plot", n.bootstraps = 1000, display.points = TRUE)
```
```{r with points bootstrapped2, warning=FALSE, fig.height = 6, fig.width =7, echo = FALSE}
# selecting return = "plot" returns a ggplot object rather than the parameters.
Estimate_Age_Maturity(maturity_data, return = "plot", n.bootstraps = 10, display.points = TRUE)
```
## Quasibinomial (binned) model
An alternative approach is to bin the data by age class and determine the proportion mature in each age class. This is performed by selecting `error.structure = "quasibinomial"`. Within the function, the binary data is binned by age and the model is fitted with the quasi binomial structure with each age bin weighted by its sample size. Doing so often returns similar parameter estimates:
```{r comparison, message=FALSE, warning=FALSE, eval = FALSE}
Estimate_Age_Maturity(maturity_data)
Estimate_Age_Maturity(maturity_data, error.structure = "quasibinomial")
```
However, a different plot is returned with stacked bars showing the proportion mature. The sample size of each bin is displayed above it.
```{r quasi age plot, warning=FALSE, fig.height = 6, fig.width =7, eval = FALSE}
# selecting return = "plot" returns a ggplot object rather than the parameters.
Estimate_Age_Maturity(maturity_data, return = "plot", n.bootstraps = 1000, error.structure = "quasibinomial")
```
```{r quasi age plot2, warning=FALSE, fig.height = 6, fig.width =7, echo=FALSE}
# selecting return = "plot" returns a ggplot object rather than the parameters.
Estimate_Age_Maturity(maturity_data, return = "plot", n.bootstraps = 10, error.structure = "quasibinomial")
```
With regards to age - both logistic model options return almost identical ogives. Therefore, the decision of which to use is up to the user.
# Using `Estimate_Len_Maturity`
Estimating length-at-maturity is handled the same as age was previously but with its own function. All of the arguments are the same with one exception (which we'll get to shortly).
You can get the parameters:
```{r length parameters, message=FALSE, warning=FALSE, eval=FALSE}
Estimate_Len_Maturity(maturity_data)
```
A plot of the binomial model with the the option of displaying the points
```{r bootstrapped length, warning=FALSE, fig.height = 6, fig.width =7, eval = FALSE}
# selecting return = "plot" returns a ggplot object rather than the parameters.
Estimate_Len_Maturity(maturity_data, return = "plot", n.bootstraps = 1000, display.points = TRUE)
```
```{r bootstrapped length2, warning=FALSE, fig.height = 6, fig.width =7, echo = FALSE}
# selecting return = "plot" returns a ggplot object rather than the parameters.
Estimate_Len_Maturity(maturity_data, return = "plot", n.bootstraps = 10, display.points = TRUE)
```
As the length unit can differ between data sets, the function determines whether cm or mm are being used and will adjust the axis as needed.
```{r length unit changed, warning=FALSE, fig.height = 6, fig.width =7, eval=FALSE}
new_data <- maturity_data
new_data$Length <- new_data$Length*10
Estimate_Len_Maturity(new_data, return = "plot", n.bootstraps = 1000, display.points = TRUE)
```
```{r length unit changed2, warning=FALSE, fig.height = 6, fig.width =7,echo=FALSE}
new_data <- maturity_data
new_data$Length <- new_data$Length*10
Estimate_Len_Maturity(new_data, return = "plot", n.bootstraps = 10, display.points = TRUE)
```
## Quasibinomial (binned) model
An additional argument is needed to use a quasi binomial model. Previously, we binned age by year class as there is no other sensible way to go about this. However, for length the bin width needs to be specified and this is very important. This is done using the `bin.width` argument.
```{r bin width, warning=FALSE, fig.height = 6, fig.width =8, eval=FALSE}
# selecting return = "plot" returns a ggplot object rather than the parameters.
Estimate_Len_Maturity(maturity_data,
return = "plot",
n.bootstraps = 1000,
error.structure = "quasibinomial",
bin.width = 25)
```
```{r bin width2, warning=FALSE, fig.height = 6, fig.width =8, echo = FALSE}
# selecting return = "plot" returns a ggplot object rather than the parameters.
Estimate_Len_Maturity(maturity_data,
return = "plot",
n.bootstraps = 10,
error.structure = "quasibinomial",
bin.width = 25)
```
Note that because now we have to chose the bin width, this can influence results:
```{r bin width comparison, warning=FALSE, eval = FALSE}
# Binomial model
Estimate_Len_Maturity(maturity_data)
# Length in 10 cm bins
Estimate_Len_Maturity(maturity_data,
error.structure = "quasibinomial",
bin.width = 10)
# Length in 25 cm bins
Estimate_Len_Maturity(maturity_data,
error.structure = "quasibinomial",
bin.width = 25)
# Length in 30 cm bins
Estimate_Len_Maturity(maturity_data,
error.structure = "quasibinomial",
bin.width = 30)
```
In each instance the $L_{50}$ changed which means that judicious choice of length bin is needed. Therefore, I usually advocate that for length-at-maturity you should used a binomial model with binary data as this avoids introducing potential bias. It should be noted that this is only an issue for length as binning data for age does not require decisions on bin width and therefore avoids biasing the results.
Therefore, if you plan on binning length data make sure you think things through carefully.
# Retrieving logistic model estimates
When producing outputs for publication, you should always aspire to create their own outputs. The figures produced by this function are publication quality but are intended to provide guidance and assistance rather than the final figures. To enable one to produce their own plots, the results of the maturity ogive and their 95% confidence intervals can be extracted instead of the plot. This works the same for both functions with either logistic model.
```{r estimate, warning=FALSE, eval = FALSE}
# selecting return = "plot" returns a ggplot object rather than the parameters.
Mat_at_age_estimates <- Estimate_Age_Maturity(maturity_data,
return = "estimates",
n.bootstraps = 1000,
error.structure = "quasibinomial")
Mat_at_len_estimates <- Estimate_Len_Maturity(maturity_data,
return = "estimates",
n.bootstraps = 1000,
error.structure = "binomial")
head(Mat_at_age_estimates)
head(Mat_at_len_estimates)
```
```{r estimate2, warning=FALSE, echo=FALSE}
# selecting return = "plot" returns a ggplot object rather than the parameters.
Mat_at_age_estimates <- Estimate_Age_Maturity(maturity_data,
return = "estimates",
n.bootstraps = 10,
error.structure = "quasibinomial")
Mat_at_len_estimates <- Estimate_Len_Maturity(maturity_data,
return = "estimates",
n.bootstraps = 10,
error.structure = "binomial")
head(Mat_at_age_estimates)
head(Mat_at_len_estimates)
```
| /scratch/gouwar.j/cran-all/cranData/AquaticLifeHistory/inst/doc/Maturity_analyses.Rmd |
---
title: "Growth estimation example using the AquaticLifeHistory package"
author: "Jonathan Smart"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Growth estimation example using the AquaticLifeHistory package}
%\VignetteEncoding{UTF-8}
%\VignetteEngine{knitr::rmarkdown}
editor_options:
chunk_output_type: console
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
# Citation
Please cite this package if it is used in any publication. The citation details can be accessed in the command line:
```{r}
citation("AquaticLifeHistory")
```
# Introduction
Growth information attained through length-at-age analysis is a key component in many fisheries analyses. This package gives the user the ability to quickly and efficiently estimate growth for an aquatic species (fishes, sharks, molluscs, crustaceans, etc.) using robust and contemporary techniques. This can be achieved using either a single model approach (i.e. application of a von Bertalanffy growth function) or through a multi-model approach where multiple models are applied simultaneously and compared.This package will provide parameter estimates with errors, length-at-age estimates with bootstrapped confidence intervals, plots and model statistics - providing users with everything required for scientific publication.
# Multi-model growth analysis with `Estimate_Growth()`
`Estimate_Growth()` is the main function for length-at-age modelling and offers the user a lot of flexibility which we will run through. This function applies the multi-model approach outlined in [Smart et al (2016)](https://onlinelibrary.wiley.com/doi/abs/10.1111/faf.12154) and will give the user the option of applying three growth models.
These include the von Bertalanffy growth model:
$$L_{a}=L_{0}+(L_{\infty}-L_{0})(1-e^{-ka})$$
the Gompertz model:
$$L_{a}=L_{0}e^{log(L_{\infty}/L_{0})(1-e^{-ga})})$$
and the Logistic model:
$$L_{a}=(L_{\infty}*L_{0}*e^{ga})/(L_{\infty}+L_{0}*e^{ga-1})$$
where $L_{a}$ is length-at-age $a$, $L_{\infty}$ is the asymptotic length and $L_{0}$ is the length-at-birth. Each model has its own growth coefficient ($k$ = von Bertalanfy, $g$ = Gompertz and $g$ = Logistic). These growth coefficients are incomparable between models (though the Gompertz and Logistic models share the same notation) whereas the $L_{\infty}$ and $L_{0}$ have the same interpretation between models.
Most applications of growth models for fish have used a $t_{0}$ rather than $L_{0}$ which represents the time-at-length-zero rather than a length-at-birth (i.e time-zero). However, $t_{0}$ does not have the same definition across multiple growth models whereas $L_{0}$ always refers to length-at-birth. This parameter is therefore used a multi-model approach. $t_{0}$ can be calculated from the VBGF parameters as:
$$t_{0}=(1/k)log(L_{\infty}-L_{0})/L_{\infty})$$
Each of these models provide different growth forms and applying them simultaneously and comparing their fits will increase the chance that an appropriate model is applied to the data. Alternatively, the user can apply a single model or select a combination (see further down).
Using `Estimate_Growth()` will perform the following:
* Fit the specified growth models using an `nls()` function, returning the parameters and summary statistics.
* Calculate Akaike's information criterion ($AIC$) values and calculate model weights ($w$).
* Bootstrap the data and return 95% confidence intervals for a growth curve over the age range of the data.
* Return a plot with the growth curves with confidence intervals (can be disabled to return raw results).
* Return parameter correlation matrices when requested.
## Input data
The `data` argument of `Estimate_Growth()` requires a data.frame of length and age data. However, this function is flexible and does not require the data to be preprocessed. The function will automatically determine the "Age" column and the "Length" column by looking for sensibly named columns. For example, the length column will accept a column named "Length", "Len", "STL", "TL", "LT" or "size". If a column can't be distinguished the user will be prompted to rename the necessary column. This setup means that a data set that contains additional columns (such as "Sex" or "Date") can be passed to the function. The only issue the user should be aware of is that multiple length columns can't be provided (i.e "TL" and "FL").
## Example applications
Growth functions can be tested using an included data set which contains length-at-age data for common blacktip sharks (*Carcharhinus limbatus*) from Indonesia.
```{r, message=FALSE, warning=FALSE}
library(AquaticLifeHistory)
data("growth_data")
head(growth_data)
```
Length-at-age 95% confidence intervals will be produced for the growth curve through bootstrapping with 1000 iterations being default. The `Estimate_growth()` will return a list of parameter estimates for three candidate models: the von Bertalanffy growth function ("VB"), Gompertz growth function ("Gom") and Logistic growth function ("Log"). The $AIC$ results for each model will also be returned as a list element, demonstrating which growth model best fit the data. A plot will be printed with the growth curves for all included models.
```{r, message=FALSE, fig.height = 6, fig.width = 8, eval=FALSE}
Estimate_Growth(data = growth_data)
```
```{r, message=FALSE, fig.height = 6, fig.width = 8, echo =FALSE}
Estimate_Growth(data = growth_data, n.bootstraps = 10)
```
The `Estimate_Growth()` function produces these outputs in three steps:
1. Starting parameters for the models are determined using the Ford-Walford method.
2. The models are fit to the data using the `nls()` function.
+ The `nls()` function can be very fragile and prone to non-convergence if the data is not well suited to a particular model. Using the `models` argument to specify different models is a good way to initially exclude problematic growth models if a non-convergence error message occurs.
3. Bootstrapping is performed to determine 95% confidence intervals along the growth curve. These are included in the plot or returned to the user if `plots = FALSE` is used.
+ The bootstrap iterations are specified using the `n.bootstraps` argument. The default is 1000.
## Fitting specific models
One model can also be specified using the `models` argument:
```{r, message=FALSE, fig.height = 6, fig.width = 8, eval = FALSE}
Estimate_Growth(data = growth_data, models = "VB")
```
```{r, message=FALSE, fig.height = 6, fig.width = 8, echo=FALSE}
Estimate_Growth(data = growth_data, models = "VB", n.bootstraps = 10)
```
Or several can be specified:
```{r, message=FALSE, fig.height = 6, fig.width = 8, eval = FALSE}
Estimate_Growth(data = growth_data, models = c("Log", "Gom"))
```
```{r, message=FALSE, fig.height = 6, fig.width = 8, echo = FALSE}
Estimate_Growth(data = growth_data, models = c("Log", "Gom"), n.bootstraps = 10)
```
Note: The three models must be specified as "VB", "Log" and "Gom". Otherwise there will be an error
```{r, error = TRUE, message=FALSE, fig.height = 6, fig.width = 8, eval = FALSE}
Estimate_Growth(data = growth_data, models = "VBGF")
```
```{r, error = TRUE, message=FALSE, fig.height = 6, fig.width = 8,echo=FALSE}
Estimate_Growth(data = growth_data, models = "VBGF", n.bootstraps = 10)
```
## Plot alterations
If you are plotting one model you probably don't want a legend included. This can be removed using the `plot.legend` argument. This also works when several models are plotted
```{r, message=FALSE, fig.height = 6, fig.width = 8, eval = FALSE}
Results <- Estimate_Growth(data = growth_data, models = "VB", plot.legend = FALSE)
```
```{r, message=FALSE, fig.height = 6, fig.width = 8, echo = FALSE}
Results <- Estimate_Growth(data = growth_data, models = "VB", plot.legend = FALSE, n.bootstraps = 10)
```
Lastly, the y-axis label will automatically scale the unit from mm to cm based on the input data
```{r, message=FALSE, fig.height = 6, fig.width = 8, eval = FALSE}
new.dat <- growth_data
new.dat$Length <- new.dat$Length/10
Results <- Estimate_Growth(new.dat)
```
```{r, message=FALSE, fig.height = 6, fig.width = 8, echo=FALSE}
new.dat <- growth_data
new.dat$Length <- new.dat$Length/10
Results <- Estimate_Growth(new.dat, n.bootstraps = 10)
```
## Returning length-at-age estimates
It is recommended that users create their own plots for publications. Therefore setting `plots = FALSE` will provide these estimates as an additional list object rather than printing a plot.
```{r, message=FALSE, fig.height = 6, fig.width = 8, eval=FALSE}
results <- Estimate_Growth(data = growth_data, plots = FALSE)
Length_at_age_estimates <- results$Estimates
head(Length_at_age_estimates)
```
```{r, message=FALSE, fig.height = 6, fig.width = 8, echo=FALSE}
results <- Estimate_Growth(data = growth_data, plots = FALSE, n.bootstraps = 10)
Length_at_age_estimates <- results$Estimates
head(Length_at_age_estimates)
```
# Model averaged results with `Calculate_MMI`
Multi-model inference (MMI) can be useful when no particular candidate model provides a better fit than the others ($\Delta AIC$ < 2). This involves averaging all models across the growth curve based on their AIC weights ($w$). It will return model averaged values of $L_{\infty}$ and $L_{0}$ with averaged standard errors. No model averaged growth completion parameters ($k$ for VBGF, $g$ for Gompertz or $g$ for Logistic) are returned as these parameters are not comparable across models.
`Calculate_MMI` takes the outputs of `Estimate_Growth` with `plots = FALSE` (so that length-at-age estimates are available) and will calculate MMI parameters and standard errors as well as model averaged length-at-age estimates.
```{r, message=FALSE, eval = FALSE}
results <- Estimate_Growth(data = growth_data, plots = FALSE)
Calculate_MMI(results)
```
```{r, message=FALSE, echo=FALSE}
results <- Estimate_Growth(data = growth_data, plots = FALSE, n.bootstraps = 10)
Calculate_MMI(results)
```
Be aware that bootstrapping cannot be applied for MMI so no length-at-age errors are available. Also multi-model theory dictates that model averaged errors will be larger than the cumulative errors of candidate models. So don't be alarmed if you get large parameter standard errors.
# Sex specific growth curves
Separating the sexes is common and is achieved by sub setting data and running the function multiple times. They can then be combined and plotted afterwards. This can be done for one model or several. Here is an example using the `ggplot2` package.
```{r, warning = FALSE, message=FALSE, fig.height = 8, fig.width = 6, eval = FALSE}
# Create data.frames of separate sexes
Females <- dplyr::filter(growth_data, Sex == "F")
Males <- dplyr::filter(growth_data, Sex == "M")
# Estimate growth
Female_ests <- Estimate_Growth(Females,n.bootstraps = 1000, plots = FALSE)
Male_ests <- Estimate_Growth(Males, n.bootstraps = 1000,plots = FALSE)
# Combine data sets with a new variable designating sex
Female_LAA <- Female_ests$Estimates
Female_LAA$Sex <- "F"
Male_LAA <- Male_ests$Estimates
Male_LAA$Sex <- "M"
combined_data <- rbind(Male_LAA, Female_LAA)
library(ggplot2)
ggplot(combined_data, aes(x = Age, y = AVG, fill = Model, col = Model)) +
facet_wrap(~Sex, ncol = 1, scales = "free")+
geom_point(data = Males, aes(x = Age, y = Length, fill = NULL, col = NULL), alpha = .3) +
geom_point(data = Females, aes(x = Age, y = Length, fill = NULL, col = NULL), alpha = .3) +
geom_ribbon(aes(ymin = low, ymax = upp, col = NA), alpha = 0.2)+
geom_line(size = 1)+
scale_y_continuous(name = "Length (mm)", limits = c(0,2500), expand = c(0,0))+
scale_x_continuous(name = "Age (years)", limits = c(0,18), expand = c(0,0))+
theme_bw()
```
```{r, warning = FALSE, message=FALSE, fig.height = 8, fig.width = 6, echo = FALSE}
# Create data.frames of separate sexes
Females <- dplyr::filter(growth_data, Sex == "F")
Males <- dplyr::filter(growth_data, Sex == "M")
# Estimate growth
Female_ests <- Estimate_Growth(Females,n.bootstraps = 10, plots = FALSE)
Male_ests <- Estimate_Growth(Males, n.bootstraps = 10,plots = FALSE)
# Combine data sets with a new variable designating sex
Female_LAA <- Female_ests$Estimates
Female_LAA$Sex <- "F"
Male_LAA <- Male_ests$Estimates
Male_LAA$Sex <- "M"
combined_data <- rbind(Male_LAA, Female_LAA)
library(ggplot2)
ggplot(combined_data, aes(x = Age, y = AVG, fill = Model, col = Model)) +
facet_wrap(~Sex, ncol = 1, scales = "free")+
geom_point(data = Males, aes(x = Age, y = Length, fill = NULL, col = NULL), alpha = .3) +
geom_point(data = Females, aes(x = Age, y = Length, fill = NULL, col = NULL), alpha = .3) +
geom_ribbon(aes(ymin = low, ymax = upp, col = NA), alpha = 0.2)+
geom_line(size = 1)+
scale_y_continuous(name = "Length (mm)", limits = c(0,2500), expand = c(0,0))+
scale_x_continuous(name = "Age (years)", limits = c(0,18), expand = c(0,0))+
theme_bw()
```
# Combining two and three parameter models
It is common practice for fish species to fix $L_{0}$ as this parameter has a direct relation to length-at-birth (often zero for fish). This is done via a single argument `Birth.Len`. If this is unspecified then three parameter models are used. However, if `Birth.Len` is specified then two parameters are used with that value used to fix the $L_{0}$ parameter.
```{r, message=FALSE, fig.height = 6, fig.width = 8, eval=FALSE}
Estimate_Growth(growth_data, Birth.Len = 600)
```
```{r, message=FALSE, fig.height = 6, fig.width = 8, echo=FALSE}
Estimate_Growth(growth_data, Birth.Len = 600, n.bootstraps = 10)
```
These can be plotted alongside there three parameter versions as well. Here is an example for the VBGF
```{r, message=FALSE, fig.height = 6, fig.width = 8, eval = FALSE}
# Fit models
two_pars <- Estimate_Growth(growth_data, models = "VB", Birth.Len = 600, plots = FALSE)
three_pars <- Estimate_Growth(growth_data, models = "VB", plots = FALSE)
# Change Model name to represent how many parameters they have
two_pars_Ests <- two_pars$Estimates
two_pars_Ests$Model <- "2 parameter VBGF"
three_pars_Ests <- three_pars$Estimates
three_pars_Ests$Model <- "3 parameter VBGF"
combined_data <- rbind(two_pars_Ests, three_pars_Ests)
ggplot(combined_data, aes(x = Age, y = AVG, fill = Model, col = Model)) +
geom_point(data = growth_data, aes(x = Age, y = Length, fill = NULL, col = NULL), alpha = .3) +
geom_ribbon(aes(ymin = low, ymax = upp, col = NA), alpha = 0.2)+
geom_line(size = 1)+
scale_y_continuous(name = "Length (mm)", limits = c(0,2500), expand = c(0,0))+
scale_x_continuous(name = "Age (years)", limits = c(0,18), expand = c(0,0))+
theme_bw() +
theme(legend.position = c(0.8, 0.2))
```
```{r, message=FALSE, fig.height = 6, fig.width = 8, echo=FALSE}
# Fit models
two_pars <- Estimate_Growth(growth_data, models = "VB", Birth.Len = 600, plots = FALSE, n.bootstraps = 10)
three_pars <- Estimate_Growth(growth_data, models = "VB", plots = FALSE, n.bootstraps = 10)
# Change Model name to represent how many parameters they have
two_pars_Ests <- two_pars$Estimates
two_pars_Ests$Model <- "2 parameter VBGF"
three_pars_Ests <- three_pars$Estimates
three_pars_Ests$Model <- "3 parameter VBGF"
combined_data <- rbind(two_pars_Ests, three_pars_Ests)
ggplot(combined_data, aes(x = Age, y = AVG, fill = Model, col = Model)) +
geom_point(data = growth_data, aes(x = Age, y = Length, fill = NULL, col = NULL), alpha = .3) +
geom_ribbon(aes(ymin = low, ymax = upp, col = NA), alpha = 0.2)+
geom_line(size = 1)+
scale_y_continuous(name = "Length (mm)", limits = c(0,2500), expand = c(0,0))+
scale_x_continuous(name = "Age (years)", limits = c(0,18), expand = c(0,0))+
theme_bw() +
theme(legend.position = c(0.8, 0.2))
```
A two parameter model is demonstrated here for sharks as this is the data used in these examples. However, fixing growth parameters for sharks is less appropriate than techniques such as back-calculation. However, for fish species, length-at-birth is close to zero due to their larval life stage. Therefore, length-at-birth is commonly fixed at zero to represent this.
# Correlation matrices
Each of the growth models fit in these analyses have a multivariate normal distribution. This means that each parameter has a normal distribution but are correlated to one another. Therefore, if you would like to use these parameters in simulation analyses, a correlation matrix is needed to include parameter values in the simulations. This is not an analysis that is included in this package. However, the ability to return the correlation matrix is included in the `Estimate_Growth()` function by using `correlation.matrix = TRUE`.
```{r, eval = FALSE}
Estimate_Growth(growth_data, correlation.matrix = TRUE)
```
```{r, echo=FALSE}
Estimate_Growth(growth_data, correlation.matrix = TRUE, n.bootstraps = 10)
```
Full details on these approaches can be found in:
Smart, J. J., Chin, A. , Tobin, A. J. and Simpfendorfer, C. A. (2016) Multimodel approaches in shark and ray growth studies:
strengths, weaknesses and the future. Fish and Fisheries, 17: 955-971.https://onlinelibrary.wiley.com/doi/abs/10.1111/faf.12154 which should be cited if this package is used in a publication.
| /scratch/gouwar.j/cran-all/cranData/AquaticLifeHistory/vignettes/Growth_estimation.Rmd |
---
title: "Maturity estimation for aquatic species through the AquaticLifeHistory package"
author: "Jonathan Smart"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{Maturity estimation for aquatic species through the AquaticLifeHistory package}
%\VignetteEncoding{UTF-8}
%\VignetteEngine{knitr::rmarkdown}
editor_options:
chunk_output_type: console
---
```{r setup, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
# Citation
Please cite this package if it is used in any publication. The citation details can be accessed in the command line:
```{r}
citation("AquaticLifeHistory")
```
# Introduction
Maturity estimation is performed by fitting a maturity ogive to binary maturity statuses for either length or age data. Maturity ogives are fitted using a glm with a logit link function and usually with a binomial error structure (but we'll touch on this soon). A glm of this sort is fitted in R using:
```{r logistic example, eval=FALSE}
glm(formula = Maturity~Age,data = my.data, family = "binomial")
```
The default link function for a binomial error structure is the logit link function. Therefore this does not need to be specified.
All maturity analyses using a logistic ogive are fitted in this manner and this is the basic operation occurring in all the maturity functions in the `AquaticLifeHistory` package. However, getting all of the information needed to produce analyses for publication can involve several steps with a few different decisions needed. Therefore the `Estimate_Age_Maturity` and `Estimate_Len_Maturity` functions handle much of these additional steps. However, it is important for the user to understand that these are basically wrapper functions around a glm call. As such the analyses inside these functions are simple to implement outside of this package.
The `Estimate_Age_Maturity` and `Estimate_Len_Maturity` functions perform the following:
* Estimate the length or age at 50% ($L_{50}$ or $A_{50}$ ) and 95% ($L_{95}$ or $A_{95}$) maturity with standard errors. Standard errors are important outputs and should always be reported for parameters.
* Bootstrap the data with a specified number of iterations to produce 95% confidence intervals about the curve
* Produce a plot of either:
+ A standard logistic ogive with a binomial error structure. This is fit to binary data.
+ A binned logistic ogive with a quasi binomial error structure. This is fit to proportion mature data for specified length or age bins. These bins are created inside the function using a specified bin width.
* Return the parameter estimates, plots of the maturity ogive or the predicted ogive fits with bootstrapped estimates for the user to produce their own plots (recommended if the outputs are meant for publication).
# Input data
The input data for both `Estimate_Age_Maturity` and `Estimate_Len_Maturity` functions require an age or length variable as well as a binary maturity variable. These functions accept various column headings for flexibility. For example `Estimate_Len_Maturity` will accept a column named "Length", "Len", "STL", "TL", "LT" or "size" (plus others) as the input column for the length variable. However, the maturity and age columns must have names that begin with "mat" and "age", respectively. The variable names needed by the functions are **not** case sensitive.
A data set for female silky sharks (*Carcharhinus falciformis*) from Papua New Guinea is included as example data. This shows the typical format accepted by both functions.
```{r logistic input data, message=FALSE, warning=FALSE}
library(AquaticLifeHistory)
data("maturity_data")
head(maturity_data)
# Maturity variable is binary (immature = 0, mature = 1)
range(maturity_data$Maturity)
```
# Using `Estimate_Age_Maturity`
Both maturity functions produce very similar outputs based on either age or length data. They are built to handle the same data set so there is no need to subset your data for just length or age. Each function will identify the variables it needs and will ignore the others.
The `Estimate_Age_Maturity` function unsurprisingly estimates age-at-maturity. In doing so it gives you a choice of model:
* Binomial model fitted to binary data
* Quasi binomial model fitted to binned proportion mature data
The input data is the same for both as the age bins are handled automatically.
## Binomial model
The default call to `Estimate_Age_Maturity` will return your parameters with their standard errors (which you should **ALWAYS** report). The SE's are the asymptotic errors from the logistic ogive
```{r parameters, message=FALSE, warning=FALSE, eval=FALSE}
Estimate_Age_Maturity(maturity_data)
```
However, if you would like to get a little more out of this function, you can have it return a plot with bootstrapped confidence intervals around the curve
```{r bootstrapped, warning=FALSE, fig.height = 6, fig.width =7, eval=FALSE}
# selecting return = "plot" returns a ggplot object rather than the parameters.
Estimate_Age_Maturity(maturity_data, return = "plot", n.bootstraps = 1000)
```
```{r bootstrapped2, warning=FALSE, fig.height = 6, fig.width =7, echo=FALSE}
# selecting return = "plot" returns a ggplot object rather than the parameters.
Estimate_Age_Maturity(maturity_data, return = "plot", n.bootstraps = 10)
```
This is a standard logistic ogive with a binomial error structure that has been fitted to binary data. The blue line is the predicted maturity ogive over the age range of the species, the black point marks the length-at-50%-mature and the grey shading shows the bootstrapped 95% confidence intervals.
Additionally, you can display the binary data by setting `display.points = TRUE`
```{r with points bootstrapped, warning=FALSE, fig.height = 6, fig.width =7, eval=FALSE}
# selecting return = "plot" returns a ggplot object rather than the parameters.
Estimate_Age_Maturity(maturity_data, return = "plot", n.bootstraps = 1000, display.points = TRUE)
```
```{r with points bootstrapped2, warning=FALSE, fig.height = 6, fig.width =7, echo = FALSE}
# selecting return = "plot" returns a ggplot object rather than the parameters.
Estimate_Age_Maturity(maturity_data, return = "plot", n.bootstraps = 10, display.points = TRUE)
```
## Quasibinomial (binned) model
An alternative approach is to bin the data by age class and determine the proportion mature in each age class. This is performed by selecting `error.structure = "quasibinomial"`. Within the function, the binary data is binned by age and the model is fitted with the quasi binomial structure with each age bin weighted by its sample size. Doing so often returns similar parameter estimates:
```{r comparison, message=FALSE, warning=FALSE, eval = FALSE}
Estimate_Age_Maturity(maturity_data)
Estimate_Age_Maturity(maturity_data, error.structure = "quasibinomial")
```
However, a different plot is returned with stacked bars showing the proportion mature. The sample size of each bin is displayed above it.
```{r quasi age plot, warning=FALSE, fig.height = 6, fig.width =7, eval = FALSE}
# selecting return = "plot" returns a ggplot object rather than the parameters.
Estimate_Age_Maturity(maturity_data, return = "plot", n.bootstraps = 1000, error.structure = "quasibinomial")
```
```{r quasi age plot2, warning=FALSE, fig.height = 6, fig.width =7, echo=FALSE}
# selecting return = "plot" returns a ggplot object rather than the parameters.
Estimate_Age_Maturity(maturity_data, return = "plot", n.bootstraps = 10, error.structure = "quasibinomial")
```
With regards to age - both logistic model options return almost identical ogives. Therefore, the decision of which to use is up to the user.
# Using `Estimate_Len_Maturity`
Estimating length-at-maturity is handled the same as age was previously but with its own function. All of the arguments are the same with one exception (which we'll get to shortly).
You can get the parameters:
```{r length parameters, message=FALSE, warning=FALSE, eval=FALSE}
Estimate_Len_Maturity(maturity_data)
```
A plot of the binomial model with the the option of displaying the points
```{r bootstrapped length, warning=FALSE, fig.height = 6, fig.width =7, eval = FALSE}
# selecting return = "plot" returns a ggplot object rather than the parameters.
Estimate_Len_Maturity(maturity_data, return = "plot", n.bootstraps = 1000, display.points = TRUE)
```
```{r bootstrapped length2, warning=FALSE, fig.height = 6, fig.width =7, echo = FALSE}
# selecting return = "plot" returns a ggplot object rather than the parameters.
Estimate_Len_Maturity(maturity_data, return = "plot", n.bootstraps = 10, display.points = TRUE)
```
As the length unit can differ between data sets, the function determines whether cm or mm are being used and will adjust the axis as needed.
```{r length unit changed, warning=FALSE, fig.height = 6, fig.width =7, eval=FALSE}
new_data <- maturity_data
new_data$Length <- new_data$Length*10
Estimate_Len_Maturity(new_data, return = "plot", n.bootstraps = 1000, display.points = TRUE)
```
```{r length unit changed2, warning=FALSE, fig.height = 6, fig.width =7,echo=FALSE}
new_data <- maturity_data
new_data$Length <- new_data$Length*10
Estimate_Len_Maturity(new_data, return = "plot", n.bootstraps = 10, display.points = TRUE)
```
## Quasibinomial (binned) model
An additional argument is needed to use a quasi binomial model. Previously, we binned age by year class as there is no other sensible way to go about this. However, for length the bin width needs to be specified and this is very important. This is done using the `bin.width` argument.
```{r bin width, warning=FALSE, fig.height = 6, fig.width =8, eval=FALSE}
# selecting return = "plot" returns a ggplot object rather than the parameters.
Estimate_Len_Maturity(maturity_data,
return = "plot",
n.bootstraps = 1000,
error.structure = "quasibinomial",
bin.width = 25)
```
```{r bin width2, warning=FALSE, fig.height = 6, fig.width =8, echo = FALSE}
# selecting return = "plot" returns a ggplot object rather than the parameters.
Estimate_Len_Maturity(maturity_data,
return = "plot",
n.bootstraps = 10,
error.structure = "quasibinomial",
bin.width = 25)
```
Note that because now we have to chose the bin width, this can influence results:
```{r bin width comparison, warning=FALSE, eval = FALSE}
# Binomial model
Estimate_Len_Maturity(maturity_data)
# Length in 10 cm bins
Estimate_Len_Maturity(maturity_data,
error.structure = "quasibinomial",
bin.width = 10)
# Length in 25 cm bins
Estimate_Len_Maturity(maturity_data,
error.structure = "quasibinomial",
bin.width = 25)
# Length in 30 cm bins
Estimate_Len_Maturity(maturity_data,
error.structure = "quasibinomial",
bin.width = 30)
```
In each instance the $L_{50}$ changed which means that judicious choice of length bin is needed. Therefore, I usually advocate that for length-at-maturity you should used a binomial model with binary data as this avoids introducing potential bias. It should be noted that this is only an issue for length as binning data for age does not require decisions on bin width and therefore avoids biasing the results.
Therefore, if you plan on binning length data make sure you think things through carefully.
# Retrieving logistic model estimates
When producing outputs for publication, you should always aspire to create their own outputs. The figures produced by this function are publication quality but are intended to provide guidance and assistance rather than the final figures. To enable one to produce their own plots, the results of the maturity ogive and their 95% confidence intervals can be extracted instead of the plot. This works the same for both functions with either logistic model.
```{r estimate, warning=FALSE, eval = FALSE}
# selecting return = "plot" returns a ggplot object rather than the parameters.
Mat_at_age_estimates <- Estimate_Age_Maturity(maturity_data,
return = "estimates",
n.bootstraps = 1000,
error.structure = "quasibinomial")
Mat_at_len_estimates <- Estimate_Len_Maturity(maturity_data,
return = "estimates",
n.bootstraps = 1000,
error.structure = "binomial")
head(Mat_at_age_estimates)
head(Mat_at_len_estimates)
```
```{r estimate2, warning=FALSE, echo=FALSE}
# selecting return = "plot" returns a ggplot object rather than the parameters.
Mat_at_age_estimates <- Estimate_Age_Maturity(maturity_data,
return = "estimates",
n.bootstraps = 10,
error.structure = "quasibinomial")
Mat_at_len_estimates <- Estimate_Len_Maturity(maturity_data,
return = "estimates",
n.bootstraps = 10,
error.structure = "binomial")
head(Mat_at_age_estimates)
head(Mat_at_len_estimates)
```
| /scratch/gouwar.j/cran-all/cranData/AquaticLifeHistory/vignettes/Maturity_analyses.Rmd |
#' Calculate the 40Ar*/39ArK-ratios
#'
#' Calculate the 40Ar*/39ArK-ratios of interference corrected logratio
#' intercept data
#'
#' @param X an object of class \code{redux} containing some
#' interference corrected logratio intercept data
#' @param irr the irradiation schedule
#' @return an object of class \code{link{redux}} containing the
#' 40Ar*/39ArK-ratios as \code{intercepts} and its covariance matrix
#' as \code{covmat}
#' @examples
#' data(Melbourne)
#' R <- get4039(Melbourne$X,Melbourne$irr)
#' plotcorr(R)
#' @export
get4039 <- function(X,irr){
Y <- getabcdef(X)
ns <- nruns(Y)
ni <- length(Y$intercepts)
out <- Y
out$intercepts <- rep(0,ns)
out$covmat <- matrix(0,ns,ns)
out$num <- rep(NA,ns)
out$den <- rep(NA,ns)
out$nlr <- rep(1,ns)
J <- matrix(0,nrow=ns,ncol=ni)
hasKglass <- "K-glass" %in% X$labels
hasCasalt <- "Ca-salt" %in% X$labels
for (i in 1:ns){
j <- (i-1)*6
label <- Y$labels[i]
aa <- Y$intercepts[getindices(Y,label,num='a')]
bb <- Y$intercepts[getindices(Y,label,num='b')]
cc <- Y$intercepts[getindices(Y,label,num='c')]
dd <- Y$intercepts[getindices(Y,label,num='d')]
ee <- Y$intercepts[getindices(Y,label,num='e')]
if (hasKglass){
ff <- Y$intercepts[getindices(Y,label,num='f')]
J[i,j+6] <- -1
} else {
ff <- 0
}
if (!hasCasalt | expired(irr[[Y$irr[i]]],Y$thedate[i],Y$param$l7)){
out$intercepts[i] <- (1-aa+cc)/dd-ff
J[i,j+1] <- -1/dd # dR/da
J[i,j+2] <- 0 # dR/db
J[i,j+3] <- 1/dd # dR/dc
J[i,j+4] <- -(1-aa+cc)/dd^2 # dR/dd
J[i,j+5] <- 0 # dR/de
} else {
out$intercepts[i] <- (1-aa+bb+cc)/(dd-ee)-ff
J[i,j+1] <- -1/(dd-ee)
J[i,j+2] <- 1/(dd-ee)
J[i,j+3] <- 1/(dd-ee)
J[i,j+4] <- -(1-aa+bb+cc)/(dd-ee)^2
J[i,j+5] <- (1-aa+bb+cc)/(dd-ee)^2
}
}
out$covmat <- J %*% Y$covmat %*% t(J)
return(out)
}
getJabcdef <- function(Z,Slabels,nl){
J <- matrix(0,nrow=nl,ncol=length(Z$intercepts))
i67ca <- getindices(Z,"Ca-salt","Ar36","Ar37")
i97ca <- getindices(Z,"Ca-salt","Ar39","Ar37")
i09k <- getindices(Z,"K-glass","Ar40","Ar39")
for (i in 1:length(Slabels)){
j <- (i-1)*6
label <- Slabels[i]
iair <- getindices(Z,"air-ratio","Ar40","Ar36")
i60 <- getindices(Z,label,"Ar36","Ar40")
i70 <- getindices(Z,label,"Ar37","Ar40")
i80 <- getindices(Z,label,"Ar38","Ar40")
i90 <- getindices(Z,label,"Ar39","Ar40")
i68cl <- getindices(Z,paste("Cl:",label,sep=""),"Ar36","Ar38")
J[j+1,c(iair,i60)] <- 1
J[j+2,c(iair,i67ca,i70)] <- 1
J[j+3,c(iair,i68cl,i80)] <- 1
J[j+4,i90] <- 1
J[j+5,c(i97ca,i70)] <- 1
J[j+6,i09k] <- 1
}
return(J)
}
getabcdef <- function(Cl){
Z <- concat(list(Cl,air(Cl))) # matrix with everything
i <- findrunindices(Z,c("Ca-salt","K-glass","Cl:","air-ratio"),invert=TRUE)
j <- findmatches(Z$pos,NA,invert=TRUE)
ii <- 1:nruns(Z)
si <- which((ii %in% i) & (ii %in% j))
ns <- length(si)
out <- subset(Z,si)
out$num <- c(rep(c("a","b","c","d","e","f"),ns))
out$den <- rep(NA,6*ns)
out$nlr <- rep(6,ns)
Jv <- getJabcdef(Z,Z$labels[si],length(out$num))
out$intercepts <- exp(Jv %*% Z$intercepts)
Jw <- apply(Jv,2,"*",out$intercepts)
out$covmat <- Jw %*% Z$covmat %*% t(Jw)
return(out)
}
| /scratch/gouwar.j/cran-all/cranData/ArArRedux/R/Ar40Ar39.R |
#' Process logratio data and calculate 40Ar/39Ar ages
#'
#' Performs detector calibration, mass fractionation correction, decay
#' corrections, interference corrections, interpolates J-factors and
#' calculates ages.
#'
#' @param X an object of class \code{\link{redux}}
#' @param irr the irradiation schedule
#' @param fract list with air shot data (one item per denominator isotope)
#' @param ca an object of class \code{\link{logratios}} with
#' Ca-interference data (not necessary if interferences are included in X)
#' @param k an object of class \code{\link{logratios}} with
#' K-interference data (not necessary if interferences are included in X)
#' @examples
#' data(Melbourne)
#' ages <- process(Melbourne$X,Melbourne$irr,Melbourne$fract)
#' summary(ages)
#' @export
process <- function(X,irr,fract=NULL,ca=NULL,k=NULL){
Cl <- corrections(X,irr,fract=fract,ca=ca,k=k)
# calculate the 40Ar*/39ArK-ratios
R <- get4039(Cl,irr)
# calculate J factors
J <- getJfactors(R)
# calculate ages
ages <- getages(J)
return(ages)
}
# apply calibration, fractionation, decay and interference corrections
corrections <- function(X,irr,fract=NULL,ca=NULL,k=NULL){
# apply the detector calibration (this won't affect the Ar40/Ar36 ratio)
CC <- calibration(X,"DCAL")
# apply the mass fractionation correction
if (is.null(fract)) A <- CC
else A <- massfractionation(CC,fract)
# decay corrections
D9 <- decaycorrection(A,irr,"Ar39")
D7 <- decaycorrection(D9,irr,"Ar37")
# interference corrections
if (is.null(k)) K <- average(D7,grep("K:",A$labels),newlabel="K-glass")
else K <- concat(list(D7,k))
if (is.null(ca)) Ca <- average(K,grep("Ca:",K$labels),newlabel="Ca-salt")
else Ca <- concat(list(K,ca))
clcorrection(Ca,irr)
}
| /scratch/gouwar.j/cran-all/cranData/ArArRedux/R/ArArRedux.R |
#' Cl-interference correction
#'
#' Apply the interference correction for the Cl-decay products
#'
#' @param X an object of class \code{redux}
#' @param irr the irradiation schedule
#' @return an object of class \code{redux}
#' @examples
#' data(Melbourne)
#' Cl <- clcorrection(Melbourne$X,Melbourne$irr)
#' plotcorr(Cl)
#' @export
clcorrection <- function(X,irr){
E <- getEmatrix(X,irr)
return(concat(list(X,E)))
}
getE <- function(P,T,dt,lambda){
if (any(T<0)) return(0)
num <- sum(P*(exp(-lambda*(T+dt))-exp(-lambda*T)))
den <- lambda*sum(P*dt)
return(log(1+num/den))
}
getdEdL <- function(P,T,dt,lambda){
if (any(T<0)) return(0)
num <- sum(P*((lambda*T +1)*exp(-lambda* T ) -
(lambda*T+lambda*dt+1)*exp(-lambda*(T+dt))))
den <- lambda*sum(P*(lambda*dt + exp(-lambda*(T+dt)) - exp(-lambda*T)))
return(num/den)
}
# computes Cl correction
getEmatrix <- function(X,irradiations){
out <- X
ns <- nruns(X)
lpcl <- log(X$param$pcl)
slpcl <- X$param$spcl/X$param$pcl
out$intercepts <- rep(lpcl,ns)
out$num <- rep("Ar36",ns)
out$den <- rep("Ar38",ns)
out$nlr <- rep(1,ns)
dEdL <- rep(0,ns)
lambda <- X$param$l6
for (i in 1:ns){ # loop through the samples
irr <- irradiations[[X$irr[i]]]
Tdt <- getTdt(irr,X$thedate[i])
out$intercepts[i] <- out$intercepts[i] +
getE(irr$P,Tdt$T,Tdt$dt,lambda)
dEdL[i] <- getdEdL(irr$P,Tdt$T,Tdt$dt,lambda)
out$labels[i] <- paste("Cl:",X$labels[i],sep='')
}
J <- cbind(rep(1,ns),dEdL)
covmatE <- matrix(c(slpcl^2,0,0,X$param$sl6^2),nrow=2)
out$covmat <- J %*% covmatE %*% t(J)
return(out)
}
expired <- function(irr,thedate,l7){
Tdt <- getTdt(irr,thedate)
return(any(Tdt$T>5*log(2)/l7))
}
| /scratch/gouwar.j/cran-all/cranData/ArArRedux/R/Cl.R |
#' Calculate the irradiation parameter ('J factor')
#'
#' Interpolate the irradiation parameters for the samples
#' given the 40Ar*/39ArK ratios of the samples and fluence monitors
#'
#' @param R a vector of 40Ar*/39ArK ratios
#' @return an object of class \code{redux} containing, as
#' \code{intercepts}, the 40Ar*/39ArK ratios of the samples, the
#' interpolated J-factors, and the 40K decay constant; and as
#' \code{covmat}: the covariance matrix. All other class properties
#' are inherited from \code{R}.
#' @examples
#' data(Melbourne)
#' R <- get4039(Melbourne$X,Melbourne$irr)
#' J <- getJfactors(R)
#' plotcorr(J)
#' @export
getJfactors <- function(R){
RS <- interpolateRJ(R)
lambda <- R$param$l0
ts <- R$param$ts
covmat <- mergematrices(RS$covmat,
matrix(c(R$param$sl0^2,0,0,R$param$sts^2),nrow=2))
ns <- length(RS$labels)/2
out <- RS
out$intercepts[(ns+1):(2*ns)] <-
(exp(lambda*ts)-1)/RS$intercepts[(ns+1):(2*ns)]
out$intercepts[2*ns+1] <- lambda
out$labels[2*ns+1] <- 'lambda'
out$thedate[2*ns+1] <- NA
out$irr[2*ns+1] <- NA
out$pos[2*ns+1] <- NA
out$num[2*ns+1] <- NA
out$den[2*ns+1] <- NA
out$nlr[2*ns+1] <- 1
J <- getJJ(RS$intercepts,ns,lambda,ts)
out$covmat <- J %*% covmat %*% t(J)
return(out)
}
interpolateRJ <- function(R){
S <- averagebypos(R,R$Jpos,newlabel="J")
ji <- getindices(S,pos=R$Jpos)
si <- getindices(S,pos=R$Jpos,invert=TRUE)
ns <- length(si)
J <- matrix(0,nrow=2*ns,ncol=length(S$intercepts))
for (i in 1:length(si)){ # loop through samples
J[i,si[i]] <- 1
px <- S$pos[si[i]]
dx <- px-R$Jpos
pm <- R$Jpos[which(dx==max(dx[dx<0]))]
pM <- R$Jpos[which(dx==min(dx[dx>0]))]
mi <- getindices(S,pos=pm)
Mi <- getindices(S,pos=pM)
J[ns+i,mi] <- (px-pm)/(pM-pm)
J[ns+i,Mi] <- (pM-px)/(pM-pm)
}
out <- R
samps <- subset(S,si)
out$thedate <- rep(samps$thedate,2)
out$irr <- rep(samps$irr,2)
out$pos <- rep(samps$pos,2)
out$num <- rep(samps$num,2)
out$den <- rep(samps$den,2)
out$nlr <- rep(samps$nlr,2)
out$labels <- c(samps$labels,paste('J:',samps$labels,sep=''))
out$intercepts <- J %*% S$intercepts
out$covmat <- J %*% S$covmat %*% t(J)
return(out)
}
getJJ <- function(RS,ns,lambda,ts){
J <- matrix(0,nrow=2*ns+1,ncol=2*ns+2)
J[1:ns,1:ns] <- diag(ns)
J[2*ns+1,2*ns+1] <- 1
for (i in (ns+1):(2*ns)){
J[i,i] <- (1-exp(lambda*ts))/(RS[i]^2)
J[i,2*ns+1] <- ts*exp(lambda*ts)/RS[i]
J[i,2*ns+2] <- lambda*exp(lambda*ts)/RS[i]
}
return(J)
}
| /scratch/gouwar.j/cran-all/cranData/ArArRedux/R/J.R |
#' Calculate 40Ar/39Ar ages
#'
#' Calculate 40Ar/39Ar ages from a vector of 40Ar/39Ar-ratios and
#' J-factors
#'
#' @param RJ an object of class \code{Redux}
#' containing the amalgamated $^{40}$Ar$^*$/$^{39}$Ar$_K$-ratios and
#' J-factors with their covariance matrix
#' @return an object of class \code{results} containing the
#' ages and their covariance matrix
#' @examples
#' data(Melbourne)
#' R <- get4039(Melbourne$X,Melbourne$irr)
#' J <- getJfactors(R)
#' ages <- getages(J)
#' plotcorr(ages)
#' @export
getages <- function(RJ){
out <- list()
class(out) <- "results"
ns <- (length(RJ$intercepts)-1)/2
lambda <- utils::tail(RJ$intercepts,n=1)
out$thedate <- RJ$thedate[1:ns]
out$labels <- RJ$labels[1:ns]
out$ages <- log(1+RJ$intercepts[1:ns]*
RJ$intercepts[(ns+1):(2*ns)])/lambda
J <- matrix(0,nrow=ns,ncol=2*ns+1)
for (i in 1:ns){
r <- RJ$intercepts[i]
j <- RJ$intercepts[ns+i]
J[i,i] <- j/(lambda*(1+j*r))
J[i,ns+i] <- r/(lambda*(1+j*r))
J[i,2*ns+1] <- - log(1+j*r)/(lambda^2)
}
out$covmat <- J %*% RJ$covmat %*% t(J)
return(out)
}
#' Summary table
#'
#' Plots the ages and their standard errors
#'
#' @param object an objct of class \code{\link{results}}
#' @param ... no other arguments
#' @examples
#' data(Melbourne)
#' ages <- process(Melbourne$X,Melbourne$irr,Melbourne$fract)
#' summary(ages)[1:5,]
#' @rdname summary
#' @method summary results
#' @export
summary.results <- function(object,...){
tab <- cbind(object$labels,object$ages,sqrt(diag(object$covmat)))
colnames(tab) <- c("name","age[Ma]","s.e.[Ma]")
return(tab)
}
| /scratch/gouwar.j/cran-all/cranData/ArArRedux/R/age.R |
#' Calculate the arithmetic mean
#'
#' Calculate the arithmetic mean of some logratio data
#'
#' @param x an object of class \code{redux} or \code{logratios}
#' @param i (optional) vector of sample indices
#' @param newlabel (optional) string with the new label to be assigned
#' to the averaged values
#' @return an object of the same class as \code{x}
#' @examples
#' data(Melbourne)
#' K <- average(Melbourne$X,grep("K:",Melbourne$X$labels),newlabel="K-glass")
#' plotcorr(K)
#' @export
average <- function(x,i=NULL,newlabel=NULL){
if (length(i)==0) return(x)
if (is.null(i)) i <- 1:nruns(x)
if (is.null(newlabel)) newlabel <- as.character(x$labels[i[1]])
j <- which(!((1:nruns(x)) %in% i))
out <- subset(x,c(i[1],j))
out$labels[1] <- newlabel
J <- Jmean(x$nlr,i)
out$intercepts <- J %*% x$intercepts
out$covmat <- J %*% x$covmat %*% t(J)
return(out)
}
#' Average all the data collected on the same day.
#'
#' This function is useful for grouping a number of replicate air
#' shots or calibration experiments
#'
#' @param x an object of class \code{timeresolved}, \code{logratios},
#' \code{PHdata} or \code{redux}
#' @param newlabel a string with the new label that should be given to
#' the average
#' @return an object of the same class as x
#' @examples
#' dfile <- system.file("Calibration.csv",package="ArArRedux")
#' dlabels <- c("H1","AX","L1","L2")
#' md <- loaddata(dfile,dlabels,PH=TRUE)
#' ld <- fitlogratios(blankcorr(md))
#' d <- averagebyday(ld,"DCAL")
#' plotcorr(d)
#' @export
averagebyday <- function(x,newlabel){
out <- x
thedays <- rle(theday(x$thedate))$values
for (i in 1:length(thedays)){
j <- which(theday(out$thedate)==thedays[i])
thelabel <- paste(newlabel,i,sep="-")
out <- average(out,j,thelabel)
}
return(out)
}
averagebypos <- function(X,pos,newlabel){
out <- X
for (i in 1:length(pos)){
j <- which(out$pos==pos[i])
thelabel <- paste(newlabel,i,sep="-")
out <- average(out,j,thelabel)
}
return(out)
}
#' Calculate the weighted mean age
#'
#' Computes the error weighted mean and MSWD of some samples taking
#' into covariances.
#'
#' @param ages an object of class \code{results}
#' @param prefix is either a string with the prefix of the
#' samples that need to be averaged, or a vector of sample names.
#' @return a list with items:
#'
#' \code{avgt}: the weighted mean age\cr
#' \code{err}: the standard error of \code{avgt}\cr
#' \code{MSWD}: the Mean Square of the Weighted Deviates
#' @examples
#' data(Melbourne)
#' ages <- process(Melbourne$X,Melbourne$irr,Melbourne$fract)
#' weightedmean(ages,"MD2-")
#' @export
weightedmean <- function(ages,prefix=NULL){
if (is.null(prefix)){
slabs <- ages$labels
} else if (length(prefix)==1){
slabs <- ages$labels[grep(prefix,ages$labels)]
slabs <- prefix
} else {
}
subs <- subset(ages,labels=slabs)
n <- nruns(subs)
W <- matrix(1,n,1) # design matrix
invSigma <- solve(subs$covmat)
vart <- solve(t(W) %*% invSigma %*% W)
avgt <- vart*(t(W) %*% invSigma %*% subs$ages)
mswd <- ((subs$ages - avgt) %*% solve(subs$covmat) %*%
(subs$ages - avgt))/(n-1)
return(list(avgt=avgt,err=sqrt(vart),MSWD=mswd))
}
# x = object of class "logratios"
# ireplace = vector of indices with runs that need replacing
Jmean <- function(nlr,ireplace){
nruns <- length(nlr)
idontreplace <- which(!((1:nruns) %in% ireplace))
nlrmean <- nlr[ireplace[1]]
nlrout <- c(nlrmean,nlr[-ireplace])
n <- length(ireplace)
J <- matrix(0,nrow=sum(nlrout),ncol=sum(nlr))
for (i in ireplace){ # first calculate the mean
j <- 1:nlrmean
k <- getindices.logratios(list(nlr=nlr),i)
J[j,k] <- diag(nlrmean)/n
}
if (length(idontreplace)==0) return(J)
for (i in 1:length(idontreplace)){
j <- getindices.logratios(list(nlr=nlrout),i+1)
k <- getindices.logratios(list(nlr=nlr),idontreplace[i])
J[j,k] <- diag(nlrout[i+1])
}
return(J)
}
| /scratch/gouwar.j/cran-all/cranData/ArArRedux/R/average.R |
#' Apply a blank correction
#'
#' Applies a blank correction to some time-resolved mass spectrometer data
#'
#' @param x an object of class \code{\link{timeresolved}} or
#' \code{\link{PHdata}}
#' @param ... other arguments
#' @param blanklabel as string denoting the prefix of the blanks
#' @param prefix a string to be prepended to the non-blanks
#' @return an object of class \code{\link{blankcorrected}}
#' @examples
#' samplefile <- system.file("Samples.csv",package="ArArRedux")
#' masses <- c("Ar37","Ar38","Ar39","Ar40","Ar36")
#' m <- loaddata(samplefile,masses) # samples and J-standards
#' blanklabel <- "EXB#"
#' l <- fitlogratios(blankcorr(m,blanklabel),"Ar40")
#' plotcorr(l)
#' @export
blankcorr <- function(x,...){ UseMethod("blankcorr",x) }
#' @rdname blankcorr
#' @export
blankcorr.default <- function(x,...){stop()}
#' @rdname blankcorr
#' @export
blankcorr.timeresolved <- function(x,blanklabel=NULL,prefix='',...){
if (is.null(blanklabel)){
out <- x
out$blankindices <- 1:nruns(x)
} else {
# find indices of the blanks and non-blanks
iblanks <- array(grep(blanklabel,x$labels))
iothers <- array(grep(blanklabel,x$labels,invert=TRUE))
blanks <- subset(x,iblanks)
others <- subset(x,iothers)
out <- others
out$labels <- unlist(lapply(prefix,paste0,others$labels))
inearestblanks <- nearest(others$thedate,blanks$thedate)
out$d <- others$d - getruns(blanks,inearestblanks)
out$blankindices <- as.vector(inearestblanks)
}
class(out) <- append(class(out),"blankcorrected")
return(out)
}
#' @rdname blankcorr
#' @export
blankcorr.PHdata <- function(x,blanklabel=NULL,prefix='',...){
out <- x
for (mass in out$masses){
out$signals[[mass]] <-
blankcorr.timeresolved(out$signals[[mass]],blanklabel,prefix)
}
return(out)
}
| /scratch/gouwar.j/cran-all/cranData/ArArRedux/R/blank.R |
#' Detector calibration
#'
#' Apply the detector calibration for multicollector data
#'
#' @param X an object of class \code{redux}
#' @param clabel the label of the detector calibration data
#' @return an object of class \code{redux}
#' @examples
#' data(Melbourne)
#' C <- calibration(Melbourne$X,"DCAL")
#' plotcorr(C)
#' @export
calibration <- function(X,clabel){
j <- grep(clabel,X$labels,invert=TRUE)
if (length(j)==length(X$labels)) return(X)
J <- Jcal(X,clabel,X$detectors)
out <- subset(X,j)
out$intercepts <- J %*% X$intercepts
out$covmat <- J %*% X$covmat %*% t(J)
return(out)
}
# X = object of class "redux"
Jcal <- function(X,clabel,detectors){
ci <- array(grep(clabel, X$labels)) # calibration indices
si <- array(grep(clabel, X$labels, invert=TRUE))
nc <- length(ci) # number of calibrations
ns <- length(si)
nci <- sum(X$nlr[ci]) # number of calibration intercepts
nsi <- sum(X$nlr[-ci]) # number of sample intercepts
J <- matrix(0,nrow=nsi,ncol=nsi+nci)
for (i in si){ # loop through all the samples
# indices of the nearest calibration data
ic <- ci[nearest(X$thedate[i],X$thedate[ci])]
# intercept indices of current sample
sj <- getindices(X,prefix=X$labels[i])
for (js in sj){ # loop through all the masses
num <- X$num[js]
den <- X$den[js]
# get the detectors for the numerator and denominator masses
ndet <- detectors[[num]]
ddet <- detectors[[den]]
if (ndet != ddet) {
jn <- getindices(X,prefix=X$labels[ic],num=ndet)
jd <- getindices(X,prefix=X$labels[ic],num=ddet)
J[js,jn] <- -1
J[js,jd] <- 1
}
J[js,js] <- 1
}
}
return(J)
}
| /scratch/gouwar.j/cran-all/cranData/ArArRedux/R/calibration.R |
#' Correct for radioactive decay occurred since irradiation
#'
#' Correct for radioactive decay of neutron-induced 37Ar and 39Ar
#' occurred since irradiation
#'
#' @param X an objects of class \code{redux}
#' @param irr the irradiation schedule
#' @param isotope a string denoting the isotope that needs correcting
#' @return an object of class \code{redux}
#' @examples
#' data(Melbourne)
#' C <- calibration(Melbourne$X,"DCAL")
#' A <- massfractionation(C,Melbourne$fract)
#' D9 <- decaycorrection(A,Melbourne$irr,"Ar39")
#' plotcorr(D9)
#' @export
decaycorrection <- function(X,irr,isotope){
out <- X
D <- getDmatrix(X,irr,isotope)
J <- Jdecay(X,isotope)
intercepts <- c(X$intercepts,D$intercepts)
covmat <- mergematrices(X$covmat,D$covmat)
out$intercepts <- J %*% intercepts
out$covmat <- J %*% covmat %*% t(J)
return(out)
}
getD <- function(P,T,dt,lambda){
num <- sum(P*dt)
den <- sum(P*(exp(-lambda*T)-exp(-lambda*(T+dt)))/lambda)
return(log(num)-log(den))
}
getdDdL <- function(P,T,dt,lambda){
num <- sum(P*((lambda*T-lambda*dt+1)*exp(-lambda*(T+dt)) -
(lambda*T +1)*exp(-lambda*T)))
den <- sum(P*(exp(-lambda*(T+dt))-exp(-lambda*T)))
return(num/den)
}
Jdecay <- function(X,isotope){
ni <- length(X$intercepts)
ns <- nruns(X)
J <- matrix(0,nrow=ni,ncol=ni+ns)
ii <- 0
for (i in 1:ns){
for (j in 1:X$nlr[i]){
ii <- ii + 1
J[ii,ii] <- 1
if (!is.na(X$num[ii]) & X$num[ii]==isotope) J[ii,ni+i] <- 1
if (!is.na(X$den[ii]) & X$den[ii]==isotope) J[ii,ni+i] <- -1
}
}
return(J)
}
getTdt <- function(irr,thedate){
dt <- (irr$tout-irr$tin)/(365*24*3600)
T <- (thedate-irr$tout)/(365*24*3600)
return(list(T=T,dt=dt))
}
# computes decay correction
getDmatrix <- function(X,irradiations,isotope){
ns <- nruns(X)
D <- rep(0,ns)
dDdL <- rep(0,ns)
if (isotope=="Ar37"){
lambda <- X$param$l7
vlambda <- X$param$sl7^2
}
if (isotope=="Ar39"){
lambda <- X$param$l9
vlambda <- X$param$sl9^2
}
for (i in 1:ns){ # loop through the samples
irr <- irradiations[[X$irr[i]]]
Tdt <- getTdt(irr,X$thedate[i])
D[i] <- getD(irr$P,Tdt$T,Tdt$dt,lambda)
dDdL[i] <- getdDdL(irr$P,Tdt$T,Tdt$dt,lambda)
}
covmatD <- (dDdL * vlambda) %*% t(dDdL)
return(list(intercepts=D,covmat=covmatD))
}
| /scratch/gouwar.j/cran-all/cranData/ArArRedux/R/decay.R |
#' An example dataset
#'
#' Contains all the relevant information needed for the data reduction
#' some ARGUS-IV data from the University of Melbourne
#'
#' @name Melbourne
#' @docType data
#' @author David Philips \email{dphillip@@unimelb.edu.au}
#' @examples
#' data(Melbourne)
#' plotcorr(Melbourne$X)
NULL
#' The \code{redux} class
#'
#' An object class that is used throughout Ar-Ar_Redux
#'
#' A list with the following items:
#'
#' \code{labels}: a vector of strings denoting the names of the runs\cr
#' \code{num}: a vector of strings denoting the numerator isotopes\cr
#' \code{den}: a vector of strings denoting the denominator isotopes\cr
#' \code{intercepts}: a vector of logratio intercepts or values\cr
#' \code{covmat}: the covariance matrix of \code{intercepts}\cr
#' \code{irr}: a vector of strings denoting the irradiation runs\cr
#' \code{pos}: a vector of integers with the positions in the
#' irradiation stack \cr
#' \code{thedate}: a vector containing the acquisition dates and times\cr
#' \code{nlr}: a vector with the number of logratios per run\cr
#' \code{param}: a list of global parameters
#' @seealso param
#' @name redux
#' @docType class
NULL
#' The \code{timeresolved} class
#'
#' An object class containing time resolved multi-collector mass spectrometry data
#'
#' A list with the following items:
#'
#' \code{masses}: a vector of strings denoting the isotopes monitored in each run\cr
#' \code{irr}: a vector of strings denoting the irradiation runs\cr
#' \code{pos}: a vector of integers with the positions in the
#' irradiation stack \cr
#' \code{thedate}: a vector containing the acquisition dates and times\cr
#' \code{d}: a data table\cr
#' \code{thetime}: a matrix with the measurement times
#' @name timeresolved
#' @docType class
#' @seealso \code{\link{loaddata}}
NULL
#' The \code{PHdata} class
#'
#' An object class containing time resolved 'peak-hopping' mass
#' spectrometry data
#'
#' A list with the following items:
#'
#' \code{masses}: a vector of strings denoting the isotopes monitored in each run\cr
#' \code{signals}: a list with objects of class \code{\link{timeresolved}}, each corresponding
#' to a detector (i.e. length(\code{signals})==1 for single collector instruments).
#' @name PHdata
#' @docType class
#' @seealso \code{\link{loaddata}}
NULL
#' The \code{blankcorrected} class
#'
#' An object class containing blank-corrected mass spectrometry data
#'
#' Extends the class classes \code{\link{timeresolved}} and
#' \code{\link{PHdata}} by adding an additional list item
#' \code{blankindices} containg the index of the nearest
#' blank. \code{\link{fitlogratios}} uses this information to group
#' the samples during regression to 'time zero'.
#' @name blankcorrected
#' @docType class
NULL
#' The \code{logratios} class
#'
#' An object class containing logratio intercepts
#'
#' A list with the following items:
#'
#' \code{labels}: a vector of strings denoting the names of the runs\cr
#' \code{num}: a vector of strings denoting the numerator isotopes\cr
#' \code{den}: a vector of strings denoting the denominator isotopes\cr
#' \code{intercepts}: a vector of logratio intercepts or values\cr
#' \code{covmat}: the covariance matrix of \code{intercepts}\cr
#' \code{irr}: a vector of strings denoting the irradiation runs\cr
#' \code{pos}: a vector of integers with the positions in the
#' irradiation stack \cr
#' \code{thedate}: a vector containing the acquisition dates and times\cr
#' \code{nlr}: a vector with the number of logratios per run\cr
#' @name logratios
#' @docType class
NULL
#' The \code{results} class
#'
#' A list with the following items:
#'
#' \code{labels}: a vector of strings denoting the names of the runs\cr
#' \code{intercepts}: a vector of ages\cr
#' \code{covmat}: the covariance matrix of \code{intercepts}\cr
#' \code{thedate}: a vector containing the acquisition dates and times\cr
#' @name results
#' @docType class
NULL
| /scratch/gouwar.j/cran-all/cranData/ArArRedux/R/documentation.R |
#' Apply the mass fractionation correction
#'
#' Applies the fractionation obtained from air shot data by
#' \code{\link{fractionation}} to the denominator detector in order to
#' correct it for the mass difference between the numerator and
#' denominator isotopes.
#'
#' @param X an object of class \code{redux}
#' @param fract a list with fractionation data for Ar37, Ar39 and Ar40
#' @return an object of class \code{redux}
#' @examples
#' data(Melbourne)
#' C <- calibration(Melbourne$X,"DCAL")
#' A <- massfractionation(C,Melbourne$fract)
#' plotcorr(A)
#' @export
massfractionation <- function(X,fract){
fdet <- X$detectors[c("Ar37","Ar39","Ar40")]
# add the air shot data
errorlessair <- air(X)
errorlessair$covmat <- 0
if (methods::is(fract,"logratios")){
Y <- concat(list(X,fract,errorlessair))
} else {
Y <- concat(c(list(X),fract,list(errorlessair)))
}
# apply the fractionation correction
J <- Jair(Y,fdet)
j <- findrunindices(Y,c(unlist(fdet),"air-ratio"),invert=TRUE)
out <- subset(Y,j)
out$intercepts <- J %*% Y$intercepts
out$covmat <- J %*% Y$covmat %*% t(J)
return(out)
}
#' Compute the mass fractionation correction
#'
#' Compares the measured 40Ar/36Ar ratio of an air shot on a given
#' detector with the atmospheric ratio.
#'
#' @param fname a .csv file with the air shot data
#' @param detector the name of the ion detector
#' @param MS the type of mass spectrometer
#' @param PH TRUE if the data were recorded in 'peak hopping' mode,
#' FALSE if recorded in multicollector mode.
#' @examples
#' data(Melbourne)
#' fd37file <- system.file("AirL2.csv",package="ArArRedux")
#' fd40file <- system.file("AirH1.csv",package="ArArRedux")
#' fract <- list(fractionation(fd37file,"L2",PH=TRUE),
#' fractionation(fd40file,"H1",PH=FALSE))
#' if (isTRUE(all.equal(Melbourne$fract,fract))){
#' print("We just re-created the fractionation correction for the Melbourne dataset")
#' }
#' @return an object of class \code{\link{logratios}}
#' @export
fractionation <- function(fname,detector,MS="ARGUS-VI",PH=FALSE){
mf <- loaddata(fname,c("Ar40","Ar36"),MS,PH)
lf <- fitlogratios(blankcorr(mf),"Ar40")
f <- averagebyday(lf,detector)
return(f)
}
Jair <- function(X,detectors){
ns <- nruns(X)
di <- findrunindices(X,detectors)
ai <- findrunindices(X,"air-ratio")
dai <- c(di,ai)
si <- (1:ns)[-dai] # sample indices
ndai <- sum(X$nlr[dai])
nsi <- sum(X$nlr[si])
J <- matrix(0,nsi,nsi+ndai)
for (i in si){ # loop through the samples
# intercept indices of current sample
sj <- getindices(X,prefix=X$labels[i])
for (js in sj){ # loop through all the masses
num <- X$num[js]
den <- X$den[js]
a <- as.integer(substr(num,start=3,stop=6))
b <- as.integer(substr(den,start=3,stop=6))
# indices of the nearest calibration data
dj <- array(grep(detectors[[den]],X$labels))
id <- di[nearest(X$thedate[i],X$thedate[dj])]
jd <- getindices(X,prefix=X$labels[id])
ja <- getindices(X,prefix="air-ratio")
J[js,js] <- 1
J[js,jd] <- (log(a)-log(b))/(log(40)-log(36))
J[js,ja] <- (log(a)-log(b))/(log(40)-log(36))
}
}
return(J)
}
air <- function(X){
out <- list(
num = "Ar40",
den = "Ar36",
intercepts = log(X$param$air),
covmat = (X$param$sair/X$param$air)^2, # variance of the air ratio
irr = NULL,
pos = NULL,
labels = "air-ratio",
thedate = as.numeric(as.Date("1970-01-01 00:00:00")),
nlr = 1
)
return(out)
}
| /scratch/gouwar.j/cran-all/cranData/ArArRedux/R/fractionation.R |
#' define the interference corrections
#'
#' create a new object of class \code{logratios} containing
#' the interferences from neutron reactions on Ca and K
#'
#' @param intercepts a vector with logratios
#' @param covmat the covariance matrix of the logratios
#' @param num a vector of strings marking the numerator isotopes of
#' \code{intercepts}
#' @param den a vector of strings marking the denominator isotopes of
#' \code{intercepts}
#' @param irr an object of class \code{irradiations}
#' @param label a string with a name which can be used to identify the
#' interference data in subsequent calculations
#' @return an object of class \code{logratios}
#' @examples
#' samplefile <- system.file("Samples.csv",package="ArArRedux")
#' irrfile <- system.file("irradiations.csv",package="ArArRedux")
#' masses <- c("Ar37","Ar38","Ar39","Ar40","Ar36")
#' X <- read(samplefile,masses,blabel="EXB#",Jpos=c(3,15))
#' irr <- loadirradiations(irrfile)
#'# assume log(36Ar/37Ar) = log(39Ar/37Ar) = 1 in co-irradiate Ca-salt
#'# with variances of 0.0001 and zero covariances
#' ca <- interference(intercepts=c(1,1),
#' covmat=matrix(c(0.001,0,0,0.001),nrow=2),
#' num=c("Ar39","Ar36"),den=c("Ar37","Ar37"),
#' irr=X$irr[1],label="Ca-salt")
#'# assume log(39Ar/40Ar) = 4.637788 in co-irradiate K-glass
#'# with variance 7.9817e-4
#' k <- interference(intercepts=4.637788,covmat=7.9817e-4,
#' num="Ar39",den="Ar40",irr=X$irr[1],
#' label="K-glass")
#' ages <- process(X,irr,ca=ca,k=k)
#' summary(ages)
#' @export
interference <- function(intercepts,covmat,num,den,irr,label){
out <- list()
class(out) <- "logratios"
out$irr <- irr
out$pos <- 0
out$labels <- label
out$thedate <- as.numeric(as.Date("1970-01-01 00:00:00"))
out$num <- num
out$den <- den
out$nlr <- length(intercepts)
out$intercepts <- intercepts
out$covmat <- covmat
return(out)
}
| /scratch/gouwar.j/cran-all/cranData/ArArRedux/R/interference.R |
#' Create a new \code{\link{redux}} object
#'
#' Initialises a new \code{\link{redux}} object by packing a
#' \code{\link{logratios}} dataset together with all the parameters
#' needed for age calculation
#'
#' @param X an object of class \code{\link{logratios}}
#' @param Jpos a vector of integers denoting the positions of the
#' fluence monitors in the irradiation stack
#' @param detectors a list of strings denoting the detectors for each
#' argon isotope
#' @return an object of class \code{\link{redux}}
#' @export
newredux <- function(X,Jpos,detectors=
list(Ar36="H1",Ar37="L2",Ar38="L1",Ar39="AX",Ar40="H1")){
out <- X
out$Jpos <- Jpos
out$detectors <- detectors
out$param$l0 = 5.5492e-4 # 40K decay constant [Ma-1]
out$param$sl0 = 0.0047e-4 # Renne et al. (2010)
out$param$l7 = 365.25*log(2)/34.95 # 37Ar decay constant [yr-1]
out$param$sl7 = out$param$l7*0.04/34.95 # Renne and Norman (2001)
out$param$l9 = log(2)/269 # 39Ar decay constant [a-1]
out$param$sl9 = out$param$l9*1.5/269 # Stoenner et al. (1965)
out$param$l6 = log(2)/301200 # 36Cl decay constant [a-1]
out$param$sl6 = out$param$l6*1000/301200 # uncertainty
out$param$pcl = 252.7 # P(36Cl/38Cl) for OSTR reactor
out$param$spcl = 1.8 # Renne et al. (2008)
out$param$ts = 28.201 # age of the Fish Canyon Tuff
out$param$sts = 0.023 # 1-sigma age uncertainty
out$param$air = 298.56 # atmospheric 40/36-ratio
out$param$sair = 0.155 # Lee et al. (2006)
class(out) <- "redux"
return(out)
}
cast <- function(x,...){ UseMethod("cast",x) }
cast.default <- function(x,...){stop()}
cast <- function(from,to){
out <- from
class(out) <- to
if (to == "logratios"){
nruns <- nruns(out)
num <- from$masses
den <- rep(from$denmass,nmasses(from))
out$num <- rep(num,nruns)
out$den <- rep(den,nruns)
out$masses <- NULL
out$denmass <- NULL
out$blankindices <- NULL
out$nlr <- rep(nmasses(from),nruns)
}
return(out)
}
readthedate <- function(x){
thedate <- strptime(x,"%d-%b-%Y %H:%M")
if (any(is.na(thedate))) thedate <- strptime(x,"%d/%m/%y %H:%M")
if (any(is.na(thedate))) thedate <- strptime(x,"%d-%b-%Y")
return(as.numeric(thedate))
}
# masses = vector of strings
# cirr = column with irradiation can label
# cpos = column with position in irradiation stack
# clabel = column containing the sample labels
# cdate = column containing the date
# ci = matrix with column indices of the masses of interest
newtimeresolved <- function(thetable,masses,cirr,cpos,clabel,cdate,ci){
out <- list()
class(out) <- "timeresolved"
out$masses <- masses
out$irr <- as.character(thetable[,cirr])
out$pos <- as.numeric(thetable[,cpos])
out$labels <- as.character(thetable[,clabel])
out$thedate <- readthedate(thetable[,cdate])
nmasses <- nmasses(out)
nruns <- nruns(out)
ncycles <- dim(ci)[1]
out$d <- matrix(0,nrow=ncycles,ncol=nmasses*nruns)
out$thetime <- t(thetable[,ci[,1]+1])
for (i in 1:ncycles){
for (j in 1:nmasses){
k <- seq(from=j,to=nmasses*nruns,by=nmasses)
out$d[i,k] <- thetable[,ci[i,j]]
}
}
return(out)
}
newPHdata <- function(thetable,masses,cirr,cpos,clabel,cdate,ci){
out <- list()
class(out) <- "PHdata"
out$masses <- masses
for (i in 1:nmasses(out)){
out$signals[[masses[i]]] <-
newtimeresolved(thetable,masses[i],
cirr,cpos,clabel,cdate,as.matrix(ci[,i]))
}
return(out)
}
#' Load mass spectrometer data
#'
#' Loads a .csv file with raw mass spectrometer data
#'
#' @param fname the file name, must end with .csv
#' @param masses a vector of strings denoting the order of the
#' isotopes listed in the table
#' @param MS the type of mass spectrometer
#' @param PH a boolean indicating whether the data are to be treated
#' as multicollector (PH=FALSE) or 'peak hopping' (PH=TRUE) data. The
#' default is PH=FALSE.
#' @return if PH=FALSE: an object of class \code{timeresolved}\cr
#' if PH=TRUE: an object of class \code{PHdata}
#' @examples
#' samplefile <- system.file("Samples.csv",package="ArArRedux")
#' masses <- c("Ar37","Ar38","Ar39","Ar40","Ar36")
#' m <- loaddata(samplefile,masses) # samples and J-standards
#' plot(m,"MD2-1a","Ar40")
#' @export
loaddata <- function(fname,masses,MS="ARGUS-VI",PH=FALSE){
thetable <- utils::read.csv(file=fname,header=FALSE,skip=3)
nrows <- dim(thetable)[1] # number of MS runs
ncols <- dim(thetable)[2] # number of columns
nmass <- length(masses) # number of isotopes
ncycles <- (ncols-3)/(2*nmass)
cirr <- 1
cpos <- 2
clabel <- 3
cdate <- 4 # column with the date
ci <- matrix(NA,nrow=ncycles,ncol=nmass) # column indices
for (i in 1:nmass){
ci[,i] <- seq(from=3+2*i,to=ncols,by=2*nmass)
}
if (PH) {
out <- newPHdata(thetable,masses,cirr,cpos,clabel,cdate,ci)
} else {
out <- newtimeresolved(thetable,masses,cirr,cpos,clabel,cdate,ci)
}
return(out)
}
#' Load the irradiation schedule
#'
#' Loads a .csv file with the schedule of a multi-stage neutron
#' irradiation
#'
#' @param fname file name (in .csv format)
#' @return a list of irradiations, where each irradiation is a named
#' list containing:
#'
#' \code{tin}: vector with the start times of irradiations \cr
#' \code{tout}: vector with the end times of irradiations \cr
#' \code{P}: vector with the power of the irradiations
#' @examples
#' irrfile <- system.file("irradiations.csv",package="ArArRedux")
#' irr <- loadirradiations(irrfile)
#' str(irr)
#' @export
loadirradiations <- function(fname){
f <- file(fname)
open(f)
out <- list()
while (TRUE) { # read the file line by line
line <- readLines(f, n=1, warn=FALSE)
if (length(line) <= 0){ # EOF
close(f)
return(out)
}
l <- unlist(strsplit(line, split=','))
if (l[1]=='In') {
out[[irrname]]$tin <- c(out[[irrname]]$tin,readthedate(l[2]))
out[[irrname]]$P <- c(out[[irrname]]$P,as.numeric(l[3]))
} else if (l[1]=='Out'){
out[[irrname]]$tout <- c(out[[irrname]]$tout,readthedate(l[2]))
} else {
irrname <- l[1]
out[[irrname]] <- list(P=c(),tin=c(),tout=c())
}
}
}
#' Read mass spectrometer data
#'
#' Reads raw mass spectrometer data and parses it into a
#' \code{\link{redux}} format for further processing.
#'
#' @param xfile a .csv file with samples and fluence monitor data
#' @param masses a list which specifies the order in which the isotopes
#' are recorded by the mass spectrometer
#' @param blabel a prefix string denoting the blanks
#' @param Jpos a vector of integers denoting the positions of the
#' fluence monitors in the irradiation stack
#' @param kfile a .csv file with the K-interference monitor data
#' (optional)
#' @param cafile a .csv file with the Ca-interference monitor data
#' (optional)
#' @param dfile a .csv file with the detector calibration data
#' (optional)
#' @param dlabels a list which specifies the names of the detectors
#' and the order in which they were recorded by the mass spectrometer
#' @param MS a string denoting the type of mass spectrometer. At the
#' moment only the ARGUS-IV is listed. Please contact the author to
#' add other file formats to Ar-Ar_Redux.
#' @return an object of class \code{\link{redux}}.
#' @examples
#' samplefile <- system.file("Samples.csv",package="ArArRedux")
#' kfile <- system.file("K-glass.csv",package="ArArRedux")
#' cafile <- system.file("Ca-salt.csv",package="ArArRedux")
#' dfile <- system.file("Calibration.csv",package="ArArRedux")
#' masses <- c("Ar37","Ar38","Ar39","Ar40","Ar36")
#' dlabels <- c("H1","AX","L1","L2")
#' X <- read(samplefile,masses,blabel="EXB#",Jpos=c(3,15),
#' kfile,cafile,dfile,dlabels)
#' plotcorr(X)
#' @export
read <- function(xfile,masses,blabel,Jpos,kfile=NULL,cafile=NULL,
dfile=NULL,dlabels=NULL,MS="ARGUS-VI"){
# load the .csv files
m <- loaddata(xfile,masses,MS,PH=FALSE) # samples and J-standards
x <- fitlogratios(blankcorr(m,blabel),"Ar40")
if (!is.null(kfile)){ # K-interference data
# subset of the relevant isotopes
mk <- loaddata(kfile,masses,MS)
lk <- fitlogratios(blankcorr(mk,blabel,"K:"),"Ar39")
k <- getmasses(lk,"Ar40","Ar39")
x <- concat(list(x,k))
}
if (!is.null(cafile)){ # Ca interference data
mca <- loaddata(cafile,masses,MS)
lca <- fitlogratios(blankcorr(mca,blabel,"Ca:"),"Ar37")
ca <- getmasses(lca,c("Ar36","Ar39"),c("Ar37","Ar37"))
x <- concat(list(x,ca))
}
if (!is.null(dfile)){
md <- loaddata(dfile,dlabels,MS,PH=TRUE)
ld <- fitlogratios(blankcorr(md))
d <- averagebyday(ld,"DCAL")
x <- concat(list(x,d))
}
return(newredux(x,Jpos))
}
#' Set or get Ar-Ar_Redux parameters
#'
#' This function is used to query and modify the half lives, standard
#' ages etc. associated with an object of class \code{\link{redux}}
#'
#' \code{\link{param}} grants access to the following parameters:
#'
#' \code{l0}: 40K decay constant (default value = 5.5492e-4 Ma-1,
#' Renne et al. [2010])\cr
#' \code{sl0}: standard error of the 40K decay constant (default value
#' = 0.0047e-4 Ma-1)\cr
#' \code{l7}: 37Ar decay constant (default value = 7.2438 yr-1, Renne
#' and Norman [2001])\cr
#' \code{sl7}: standard error of the 37Ar decay constant (default
#' value = 0.0083 yr-1)\cr
#' \code{l9}: 39Ar decay constant (0.002577 yr-1 Stoenner et
#' al. [1965])\cr
#' \code{sl9}: standard error of the 39Ar decay constant (0.000014
#' yr-1)\cr
#' \code{l6}: 36Cl decay constant (default value = 2301.3e-9 yr-1)\cr
#' \code{sl6}: standard error of the 36Cl decay constant (default
#' value = 7.6e-9 yr-1\cr
#' \code{pcl}: (36Cl/38Cl)-production rate (default value = 252.7 for
#' OSTR reactor, Renne et al. [2008])\cr
#' \code{spcl}: standard error of the (36Cl/38Cl)-production rate
#' (default value = 1.8)\cr
#' \code{ts}: age of the fluence monitor (default = 28.201 Myr for the
#' Fish Canyon Tuff, Kuiper et al. [2008])\cr
#' \code{sts}: standard error of the fluence monitor age (default
#' value = 0.023 Myr)\cr
#' \code{air}: atmospheric 40Ar/36Ar ratio (default value = 298.56,
#' Lee et al. [2006])\cr
#' \code{sair}: standard error of the atmospheric 40Ar/36Ar ratio
#' (default value = 0.155)
#'
#' @param X an object of class \code{\link{redux}}
#' @param ... any combination of the parameters given below
#' @return returns the modified \code{\link{redux}} object OR the
#' current parameter values if no optional arguments are supplied.
#' @examples
#' data(Melbourne)
#' param(Melbourne$X)$air
#' Y <- param(Melbourne$X,air=295.5)
#' param(Y)$air
#' @export
param <- function(X,...){
arguments <- list(...)
if (length(arguments)>0){
X$param[names(arguments)] <- arguments
return(X)
} else {
return(X$param)
}
}
| /scratch/gouwar.j/cran-all/cranData/ArArRedux/R/io.R |
#' Plot a time resolved mass spectrometry signal
#'
#' Plots the raw signal of a given isotope against time.
#'
#' @param x an object of class \code{\link{timeresolved}} or
#' \code{\link{PHdata}}
#' @param label a string with the name of the run
#' @param mass a string indicating the isotope of interest
#' @param ... optional parameters
#' @examples
#' samplefile <- system.file("Samples.csv",package="ArArRedux")
#' masses <- c("Ar37","Ar38","Ar39","Ar40","Ar36")
#' mMC <- loaddata(samplefile,masses)
#' plot(mMC,"MD2-1a","Ar40")
#' @rdname plot
#' @export
plot.timeresolved <- function(x,label,mass,...){
j <- which(x$labels==label)-1
if (length(j)!=1){
print('invalid input into plot function')
return(NA)
}
k <- which(x$masses==mass)
i <- j*nmasses(x)+k
graphics::plot(x$thetime[,i],x$d[,i],type='p')
}
#' @examples
#' mPH <- loaddata(samplefile,masses,PH=TRUE)
#' plot(mPH,"MD2-1a","Ar40")
#' @rdname plot
#' @export
plot.PHdata <- function(x,label,mass,...){
plot.timeresolved(x$signals[[mass]],label,mass,...)
}
#' Plot a matrix with correlation coefficients
#'
#' Converts the covariance matrix to a correlation matrix and plots
#' this is a coloured image for visual inspection.
#'
#' @param X a data structure (list) containing an item called `covmat' (covariance matrix)
#' @examples
#' data(Melbourne)
#' plotcorr(Melbourne$X)
#' @export
plotcorr <- function(X){
image.with.legend(z=stats::cov2cor(X$covmat),color.palette=grDevices::heat.colors)
}
# modified version of filled.contour with ".filled.contour" part replaced with "image"
# function. Note that the color palette is a flipped heat.colors rather than cm.colors
image.with.legend <- function (x = seq(1, nrow(z), length.out = nrow(z)), y = seq(1,
ncol(z), length.out=nrow(z)), z, xlim = range(x, finite = TRUE),
ylim = range(y, finite = TRUE), zlim = range(z, finite = TRUE),
levels = pretty(zlim, nlevels), nlevels = 20, color.palette = grDevices::heat.colors,
col = rev(color.palette(length(levels) - 1)), plot.title, plot.axes,
key.title, key.axes, asp = NA, xaxs = "i", yaxs = "i", las = 1,
axes = TRUE, frame.plot = axes, ...) {
if (missing(z)) {
if (!missing(x)) {
if (is.list(x)) {
z <- x$z
y <- x$y
x <- x$x
}
else {
z <- x
x <- seq.int(1, nrow(z), length.out = nrow(z))
}
}
else stop("no 'z' matrix specified")
}
else if (is.list(x)) {
y <- x$y
x <- x$x
}
if (any(diff(x) <= 0) || any(diff(y) <= 0))
stop("increasing 'x' and 'y' values expected")
mar.orig <- (par.orig <- graphics::par(c("mar", "las", "mfrow")))$mar
on.exit(graphics::par(par.orig))
w <- (3 + mar.orig[2L]) * graphics::par("csi") * 2.54
graphics::layout(matrix(c(2, 1), ncol = 2L), widths = c(1, graphics::lcm(w)))
graphics::par(las = las)
mar <- mar.orig
mar[4L] <- mar[2L]
mar[2L] <- 1
graphics::par(mar = mar)
graphics::plot.new()
graphics::plot.window(xlim = c(0, 1), ylim = range(levels),
xaxs = "i", yaxs = "i")
graphics::rect(0, levels[-length(levels)], 1, levels[-1L], col = col)
if (missing(key.axes)) {
if (axes)
graphics::axis(4)
}
else key.axes
graphics::box()
if (!missing(key.title))
key.title
mar <- mar.orig
mar[4L] <- 1
graphics::par(mar = mar)
graphics::image(x,y,z,col=col,xlab="",ylab="")
if (missing(plot.axes)) {
if (axes) {
graphics::title(main = "", xlab = "", ylab = "")
graphics::Axis(x, side = 1)
graphics::Axis(y, side = 2)
}
}
else plot.axes
if (frame.plot)
graphics::box()
if (missing(plot.title))
graphics::title(...)
else plot.title
invisible()
}
| /scratch/gouwar.j/cran-all/cranData/ArArRedux/R/plot.R |
#' Export \code{ArArRedux} data to \code{IsoplotR}
#'
#' Creates a data object compatible with the \code{IsoplotR} package
#'
#' @param x an object of class \code{\link{redux}}
#' @param irr the irradiation schedule
#' @param fract list with air shot data (one item per denominator
#' isotope)
#' @param ca an object of class \code{\link{logratios}} with
#' Ca-interference data (not necessary if interferences are
#' included in X)
#' @param k an object of class \code{\link{logratios}} with
#' K-interference data (not necessary if interferences are
#' included in X)
#' @param format input format for \code{IsoplotR}. I.e. one of
#'
#' \code{1}: 39/40, s[39/40], 36/40, s[36/40], 39/36, s[39/36]
#'
#' (other formats will be added later)
#' @param file optional (\code{.csv}) file name to write the output
#' to.
#' @return an object of class \code{ArAr}, i.e. a table with the
#' following columns: \code{'Ar4036'}, \code{'errAr4036'},
#' \code{'Ar3936'}, \code{'errAr3936'}, \code{'Ar4039'}, and
#' \code{'errAr4039'}
#' @examples
#' data(Melbourne)
#' print(redux2isoplotr(Melbourne$X,Melbourne$irr))
#' @export
redux2isoplotr <- function(x,irr,fract=NULL,ca=NULL,
k=NULL,format=1,file=NULL){
X <- redux2ArAr(x,irr,fract=fract,ca=ca,k=k,format=format,file=file)
if (format==1) out <- format1(X)
else out <- X
if (is.null(file)) return(out)
else utils::write.table(out,file=file,col.names=FALSE,
row.names=FALSE,sep=',')
}
# convert 'redux' data object to 'ArAr' data object
redux2ArAr <- function(x,irr,fract=NULL,ca=NULL,
k=NULL,format=1,file=NULL){
Cl <- corrections(x,irr,fract=fract,ca=ca,k=k)
Y <- getABCDEF(Cl)
ni <- length(Y$intercepts)
out <- list()
class(out) <- "ArAr"
R <- get4039(Cl,irr)
JJ <- getJfactors(R)
Jfact <- subset(JJ,labels="J:")
ns <- nruns(Jfact)
if (ns==1) {
out$J <- c(Jfact$intercepts,sqrt(Jfact$covmat))
} else if (diff(range(Jfact$pos))==0) {
out$J <- c(Jfact$intercepts[1],sqrt(Jfact$covmat[1,1]))
} else {
stop("The dataset contains more than one J-factor.")
}
labels <- rep(c('Ar39Ar40','Ar36Ar40','Ar39Ar36','Ar40Ar36'),ns)
out$x <- rep(0,4*ns)
out$covmat <- matrix(0,4*ns,4*ns)
J <- matrix(0,nrow=4*ns,ncol=ni)
hasKglass <- "K-glass" %in% Cl$labels
hasCasalt <- "Ca-salt" %in% Cl$labels
for (i in 1:ns){
ri <- (i-1)*4 # row index (39/40,36/40,39/36,40/36)
ci <- (i-1)*6 # column index (A,B,C,D,E,F)
label <- Y$labels[i]
AA <- Y$intercepts[getindices(Y,label,num='A')]
CC <- Y$intercepts[getindices(Y,label,num='C')]
EE <- Y$intercepts[getindices(Y,label,num='E')]
if (hasKglass) {
DD <- Y$intercepts[getindices(Y,label,num='D')]
} else {
DD <- 0
}
if (!hasCasalt | expired(irr[[Y$irr[i]]],Y$thedate[i],Y$param$l7)) {
BB <- 0
FF <- 0
} else {
BB <- Y$intercepts[getindices(Y,label,num='B')]
FF <- Y$intercepts[getindices(Y,label,num='F')]
}
out$x[ri+1] <- (EE-FF)/(1-DD) # X1=Ar39/Ar40
out$x[ri+2] <- (AA-BB-CC)/(1-DD) # Y1=Ar36/Ar40
out$x[ri+3] <- (EE-FF)/(AA-BB-CC) # X2=Ar39/Ar36
out$x[ri+4] <- (1-DD)/(AA-BB-CC) # Y2=Ar40/Ar36
J[ri+1,ci+4] <- -(EE-FF)/(1-DD)^2 # dX1dD
J[ri+1,ci+5] <- 1/(1-DD) # dX1dE
J[ri+1,ci+6] <- -1/(1-DD) # dX1dF
J[ri+2,ci+1] <- 1/(1-DD) # dY1dA
J[ri+2,ci+2] <- -1/(1-DD) # dY1dB
J[ri+2,ci+3] <- -1/(1-DD) # dY1dC
J[ri+2,ci+4] <- -(AA-BB-CC)/(1-DD)^2 # dY1dD
J[ri+3,ci+1] <- (FF-EE)/(AA-BB-CC)^2 # dX2dA
J[ri+3,ci+2] <- (EE-FF)/(AA-BB-CC)^2 # dX2dB
J[ri+3,ci+3] <- (EE-FF)/(AA-BB-CC)^2 # dX2dC
J[ri+3,ci+5] <- 1/(AA-BB-CC) # dX2dE
J[ri+3,ci+6] <- -1/(AA-BB-CC) # dX2dF
J[ri+4,ci+1] <- -(1-DD)/(AA-BB-CC)^2 # dY2dA
J[ri+4,ci+2] <- (1-DD)/(AA-BB-CC)^2 # dY2dB
J[ri+4,ci+3] <- (1-DD)/(AA-BB-CC)^2 # dY2dC
J[ri+4,ci+4] <- -1/(AA-BB-CC) # dY2dD
}
out$covmat <- J %*% Y$covmat %*% t(J)
names(out$x) <- labels
rownames(out$covmat) <- labels
colnames(out$covmat) <- labels
out
}
format1 <- function(x){
ns <- length(x$x)/4
out <- matrix('',ns+3,6)
out[1,1:2] <- c("J","err[J]")
out[2,1:2] <- x$J
out[3,] <- c("Ar39Ar40","errAr39Ar40",
"Ar36Ar40","errAr36Ar40",
"Ar39Ar36","errAr39Ar36")
i90 <- findmatches(labels=names(x$x),prefixes=c("Ar39Ar40"))
i60 <- findmatches(labels=names(x$x),prefixes=c("Ar36Ar40"))
i96 <- findmatches(labels=names(x$x),prefixes=c("Ar39Ar36"))
for (i in 1:ns){
out[i+3,1] <- x$x[i90[i]]
out[i+3,2] <- sqrt(x$covmat[i90[i],i90[i]])
out[i+3,3] <- x$x[i60[i]]
out[i+3,4] <- sqrt(x$covmat[i60[i],i60[i]])
out[i+3,5] <- x$x[i96[i]]
out[i+3,6] <- sqrt(x$covmat[i96[i],i96[i]])
}
out
}
getJABCDEF <- function(Z,Slabels,nl){
J <- matrix(0,nrow=nl,ncol=length(Z$intercepts))
hasKglass <- "K-glass" %in% Z$labels
hasCasalt <- "Ca-salt" %in% Z$labels
if (hasCasalt){
i67ca <- getindices(Z,"Ca-salt","Ar36","Ar37")
i97ca <- getindices(Z,"Ca-salt","Ar39","Ar37")
}
if (hasKglass)
i09k <- getindices(Z,"K-glass","Ar40","Ar39")
for (i in 1:length(Slabels)){
j <- (i-1)*6
label <- Slabels[i]
i60 <- getindices(Z,label,"Ar36","Ar40")
i70 <- getindices(Z,label,"Ar37","Ar40")
i80 <- getindices(Z,label,"Ar38","Ar40")
i90 <- getindices(Z,label,"Ar39","Ar40")
i68cl <- getindices(Z,paste("Cl:",label,sep=""),"Ar36","Ar38")
J[j+1,i60] <- 1 # A
if (hasCasalt) J[j+2,c(i67ca,i70)] <- 1 # B
J[j+3,c(i68cl,i80)] <- 1 # C
if (hasKglass) J[j+4,c(i09k,i90)] <- 1 # D
J[j+5,i90] <- 1 # E
if (hasCasalt) J[j+6,c(i70,i97ca)] <- 1 # F
}
return(J)
}
getABCDEF <- function(Z){
si <- findrunindices(Z,c("Ca-salt","K-glass","Cl:"),invert=TRUE)
ns <- length(si)
out <- subset(Z,si)
out$num <- c(rep(c("A","B","C","D","E","F"),ns))
out$den <- rep(NA,6*ns)
out$nlr <- rep(6,ns)
Jv <- getJABCDEF(Z,out$labels,6*ns)
out$intercepts <- exp(Jv %*% Z$intercepts)
Jw <- apply(Jv,2,"*",out$intercepts)
out$covmat <- Jw %*% Z$covmat %*% t(Jw)
return(out)
}
| /scratch/gouwar.j/cran-all/cranData/ArArRedux/R/redux2isoplotr.R |
test <- function(option='full'){
samplefile <- "../inst/Samples.csv"
kfile <- "../inst/K-glass.csv"
cafile <- "../inst/Ca-salt.csv"
fd37file <- "../inst/AirL2.csv"
fd39file <- "../inst/AirAX.csv"
fd40file <- "../inst/AirH1.csv"
irrfile <- "../inst/irradiations.csv"
dfile <- "../inst/Calibration.csv"
masses <- c("Ar37","Ar38","Ar39","Ar40","Ar36")
blanklabel <- "EXB#"
dlabels <- c("H1","AX","L1","L2")
Jpos <- c(3,15)
X <- read(samplefile,masses,blanklabel,Jpos,
kfile,cafile,dfile,dlabels)
irr <- loadirradiations(irrfile)
fract <- list(fractionation(fd37file,"L2",PH=TRUE),
fractionation(fd39file,"AX",PH=TRUE),
fractionation(fd40file,"H1",PH=FALSE))
if (identical(option,'full')){ # full propagation
ages <- process(X,irr,fract)
return(ages)
} else if (identical(option,'simple')){
mMC <- loaddata(samplefile,masses)
graphics::plot(mMC,"MD2-1a","Ar37")
} else if (identical(option,'builddata')){
Melbourne <- list(X=X,irr=irr,fract=fract)
save(Melbourne,file="../data/Melbourne.rda")
} else if (identical(option, 'subset')){
ages <- process(X,irr,fract)
out <- subset(ages,labels=c("MD2-1","MD2-2","MD2-3","MD2-4","MD2-5"))
} else if (identical(option, 'isoplotr')){
X <- read(samplefile,masses,blanklabel,Jpos)
Y <- subset(X,labels=c("MD2-2h","MD2-2i","MD2-2j","MD2-2k","MD2-2l",
"MD2-2m","MD2-2n","MD2-2o","MD2-2p","MD2-2q",
"MD2-2r","MD2-2s","MD2-2t","MD2-2u"),include.J=TRUE)
out <- redux2isoplotr(Y,irr,format=1,
file='/home/pvermees/Dropbox/Programming/R/IsoplotR/inst/ArAr3.csv')
#out <- redux2isoplotr(Y,irr,fract=fract,format=2)
# ArAr <- out; save(ArAr,file="/home/pvermees/Dropbox/Programming/R/IsoplotR/data/ArAr.rda")
}
out
}
| /scratch/gouwar.j/cran-all/cranData/ArArRedux/R/test.R |
#' Extrapolation to 'time zero'
#'
#' This function extrapolates time resolved mass spectrometer data to
#' t=0. When fed with multicollector data, it forms the ratios of the
#' raw signals, forms their logs and performs linear regression to t=0
#' When fed with single collector data, the function first takes their
#' logs and extrapolates them to t=0 before taking ratios, unless
#' \code{denmass}=NULL, in which case the logs of the raw signals are
#' extrapolated.
#'
#' @param x an object of class \code{timeresolved} or \code{PHdata}
#' @param ... further arguments (see below)
#' @return an object of class \code{logratios}
#' @examples
#' samplefile <- system.file("Samples.csv",package="ArArRedux")
#' masses <- c("Ar37","Ar38","Ar39","Ar40","Ar36")
#' m <- loaddata(samplefile,masses) # samples and J-standards
#' blanklabel <- "EXB#"
#' l <- fitlogratios(blankcorr(m,blanklabel),"Ar40")
#' plotcorr(l)
#' @export
fitlogratios <- function(x,...){ UseMethod("fitlogratios",x) }
#' @rdname fitlogratios
#' @export
fitlogratios.default <- function(x,...){ stop() }
#' @param denmass a string denoting the denominator isotope
#' @rdname fitlogratios
#' @export
fitlogratios.timeresolved <- function(x,denmass,...){
r <- takeratios(x,denmass)
l <- takelogs(r)
f <- timezero(l)
return(cast(f,"logratios"))
}
#' @rdname fitlogratios
#' @export
fitlogratios.PHdata <- function(x,denmass=NULL,...){
for (i in 1:nmasses(x)){
z <- newfit(x)
l <- takelogs(x$signals[[i]])
z <- setmasses(z,z$masses[i],timezero(l))
}
if (is.null(denmass)) {
f <- z
f$denmass <- NA
} else {
f <- takeratios(z,denmass)
}
return(cast(f,"logratios"))
}
Jtakeratios <- function(nruns,inum,iden){
nlr <- length(inum)
nmasses <- nlr+1
J <- matrix(0,nrow=nlr,ncol=nmasses) # elementary matrix
for (i in 1:length(inum)){
J[i,inum[i]] <- 1
J[,iden] <- -1
}
out <- matrix(0,nrow=nlr*nruns,ncol=nmasses*nruns)
for (i in 1:nruns){
irow <- ((i-1)*nlr+1):(i*nlr)
icol <- ((i-1)*nmasses+1):(i*nmasses)
out[irow,icol] <- J
}
return(out)
}
takeratios <- function(x,...){ UseMethod("takeratios",x) }
takeratios.default <- function(x,...){stop()}
takeratios.timeresolved <- function(x,denmass,...){
den <- getmasses(x,denmass)
num <- getmasses(x,denmass,invert=TRUE)
out <- num
for (mass in num$masses){ # loop through the isotopes
ratio <- getmasses(num,mass)$d/den$d
out <- setmasses(out,mass,ratio)
}
out$denmass <- denmass
class(out) <- append(class(out),"ratio")
return(out)
}
takeratios.fit <- function(x,denmass,...){
out <- x
iden <- which(x$mass == denmass)
inum <- which(x$mass != denmass)
J <- Jtakeratios(nruns(x),inum,iden)
out$masses <- x$masses[inum]
out$intercepts <- J %*% x$intercepts
out$covmat <- J %*% x$covmat %*% t(J)
out$denmass <- denmass
return(out)
}
takelogs <- function(x){
out <- x
out <- replacenegatives(x)
out$d <- log(out$d)
class(out) <- append(class(out),"logged")
return(out)
}
newfit <- function(x,...){ UseMethod("newfit",x) }
newfit.default <- function(x,...){ stop() }
newfit.timeresolved <- function(x,nmasses=NULL,nruns=NULL,...){
out <- x
class(out) <- "fit"
if (is.null(nmasses)) nmasses <- nmasses(x)
if (is.null(nruns)) nruns <- nruns(x)
out$d <- NULL
out$thetime <- NULL
out$intercepts <- rep(0,nmasses*nruns)
out$covmat <- matrix(0,nrow=nmasses*nruns,ncol=nmasses*nruns)
return(out)
}
newfit.PHdata <- function(x,...){
x1 <- x$signals[[1]]
out <- newfit(x1,nmasses(x),nruns(x1))
out$masses <- x$masses
out$signals <- NULL
return(out)
}
timezero <- function(x){
nmasses <- nmasses(x)
out <- newfit(x,nmasses)
bi <- rle(as.vector(x$blankindices))$values # blank indices
irunsout <- 0
for (i in bi){ # loop through the groups
irunsx <- which(i==x$blankindices)
irunsout <- utils::tail(irunsout,n=1) + (1:length(irunsx))
g <- subset(x,irunsx) # extract group
out <- setfit(out,fit(g),nmasses,irunsout)
}
return(out)
}
# x and f are both objects of class "fit"
# nmasses = number of masses or isotope ratios per sample
# iruns = indicates which samples need replacing
setfit <- function(x,f,nmasses,iruns){
out <- x
ii <- getindices(nmasses=nmasses,iruns=iruns)
out$intercepts[ii] <- f$intercepts
out$covmat[ii,ii] <- f$covmat
return(out)
}
fit <- function(x){
out <- newfit(x)
if (nruns(x)>1) { # average time for all samples in group
thetime <- apply(x$thetime,1,"mean")
} else {
thetime <- x$thetime
}
f <- stats::lm(x$d ~ thetime)
if (nruns(x) == 1 & nmasses(x) == 1) { # only one intercept
out$intercepts <- stats::coef(f)["(Intercept)"]
covcolname <- "(Intercept)"
} else { # an entire row of intercepts
out$intercepts <- stats::coef(f)["(Intercept)",]
covcolname <- ":(Intercept)"
}
myvcov <- stats::vcov(f)
j <- which(colnames(myvcov)==covcolname)
out$covmat <- myvcov[j,j]
return(out)
}
| /scratch/gouwar.j/cran-all/cranData/ArArRedux/R/timezero.R |
theday <- function(thedate){
dateinseconds <- as.POSIXlt(thedate,origin="1970-01-01 00:00:00")
dateindays <- (1900+dateinseconds$year-1970)*365 + dateinseconds$yday
dayinseconds <- dateindays*24*3600
return(dayinseconds)
}
mergematrices <- function(xcovmat,ycovmat){
if (is.null(xcovmat)) return(ycovmat)
if (is.null(ycovmat)) return(xcovmat)
nx <- max(1,nrow(xcovmat))
ny <- max(1,nrow(ycovmat))
covmat <- matrix(0,nrow=nx+ny,ncol=nx+ny)
covmat[1:nx,1:nx] <- xcovmat
covmat[(nx+1):(nx+ny),(nx+1):(nx+ny)] <- ycovmat
return(covmat)
}
# returns the indices of timevec2 which are closest to timevec1
nearest <- function(timevec1,timevec2){
ii <- NULL
for (i in 1:length(timevec1)) {
ii <- c(ii, which.min(abs(timevec2 - timevec1[i])))
}
return(ii)
}
nmasses <- function(x){
return(length(x$masses))
}
nruns <- function(x,...){ UseMethod("nruns",x) }
nruns.default <- function(x,...){
length(x$labels)
}
nruns.PHdata <- function(x,...){
return(nruns(x$signals[[1]]))
}
ncycles <- function(x,...){ UseMethod("ncycles",x) }
ncycles.default <- function(x,...){stop()}
ncycles.timeresolved <- function(x,...){
return(dim(x$thetime)[1])
}
getsignal <- function(X,prefix,num=NULL){
i <- getindices(X,prefix,num)
return(cbind(X$intercepts[i], sqrt(X$covmat[i,i])))
}
getindices <- function(...){ UseMethod("getindices") }
getindices.default <- function(nmasses,nruns=NULL,
imasses=NULL,iruns=NULL,...){
if (is.null(nruns)) nruns <- max(iruns)
if (is.null(imasses)) imasses <- 1:nmasses
if (is.null(iruns)) iruns <- 1:nruns
i <- NULL
for (irun in iruns){
i <- c(i,(irun-1)*nmasses + imasses)
}
return(i)
}
getindices.logratios <- function(x,iruns,...){
cs <- c(0,cumsum(x$nlr))
i <- NULL
for (irun in iruns){
i <- c(i,(cs[irun]+1):cs[irun+1])
}
return(i)
}
getindices.redux <- function(X,prefix=NULL,num=NULL,den=NULL,
pos=NULL,invert=FALSE,include.J=FALSE,...){
i <- 1:length(X$intercepts)
if (is.null(prefix)) {
i1 <- i
} else {
j <- findrunindices(X,prefixes=prefix,invert=invert,include.J=include.J)
i1 <- getindices.logratios(X,j)
}
if (is.null(num)) {
i2 <- i
} else {
i2 <- findmatches(X$num,prefixes=num,invert=invert)
}
if (is.null(den)) {
i3 <- i
} else {
i3 <- findmatches(X$den,prefixes=den,invert=invert)
}
if (is.null(pos)) {
i4 <- i
} else {
matches <- X$pos %in% pos
if (invert){
i4 <- which(!matches)
} else {
i4 <- which(matches)
}
}
return(which((i %in% i1) & (i %in% i2) &
(i %in% i3) & (i %in% i4)))
}
findrunindices <- function(X,prefixes,invert=FALSE,include.J=FALSE){
i <- 1:nruns(X)
i1 <- findmatches(X$labels,prefixes,invert)
out <- (i %in% i1)
if (include.J) {
i2 <- findmatches(X$pos,prefixes=X$Jpos,invert)
i3 <- findmatches(X$labels,prefixes=c("DCAL","K:","Ca:"),invert)
out <- out | (i %in% i2) | (i %in% i3)
}
which(out)
}
findmatches <- function(labels,prefixes,invert=FALSE){
ns <- length(labels)
i <- c() # vector of intercepts
for (prefix in prefixes){
matches <- labels %in% prefix
if (any(matches)) i <- c(i,which(matches))
else i <- c(i,grep(prefix, labels))
}
j <- sort(i)
if (invert){
if (length(j)==0) return(1:ns)
else return((1:ns)[-j])
} else {
return(j)
}
}
getruns <- function(x,...){ UseMethod("getruns",x) }
getruns.default <- function(x,...){stop()}
getruns.timeresolved <- function(x,i,...){
ii <- getindices(nmasses=nmasses(x),iruns=i)
return(x$d[,ii])
}
#' Select a subset of some data
#'
#' Extracts those intercepts, covariances etc. that match a given list
#' of indices or labels.
#'
#' @param x an object of class \code{\link{timeresolved}},
#' \code{\link{logratios}}, \code{\link{redux}} or
#' \code{\link{results}}
#' @param i a vector with indices of the selected runs
#' @param labels a string or a vector of strings with sample names
#' @param invert boolean flag indicating whether the selection should
#' be inverted, i.e. whether the selected indices or labels should
#' be removed rather than retained
#' @param include.J if \code{TRUE}, automatically adds the irradiation
#' monitors to the selection
#' @param ... other arguments
#' @return an object of the same class as \code{x}
#' @examples
#' data(Melbourne)
#' ages <- process(Melbourne$X,Melbourne$irr,Melbourne$fract)
#' MD <- subset(ages,labels=c("MD2-1","MD2-2","MD2-3","MD2-4","MD2-5"))
#' plotcorr(MD)
#' @rdname subset
#' @export
subset.timeresolved <- function(x,i=NULL,labels=NULL,invert=FALSE,include.J=FALSE,...){
if (is.null(i)) i <- findrunindices(x,prefixes=labels,invert=invert,include.J=include.J)
out <- x
out$d <- getruns(x,i)
out$thetime <- x$thetime[,i]
out$thedate <- x$thedate[i]
out$irr <- x$irr[i]
out$pos <- x$pos[i]
out$labels <- x$labels[i]
if (methods::is(x,"blankcorrected"))
out$blankindices <- x$blankindices[i]
return(out)
}
#' @rdname subset
#' @export
subset.logratios <- function(x,i=NULL,labels=NULL,invert=FALSE,include.J=FALSE,...){
if (is.null(i)) i <- findrunindices(x,prefixes=labels,invert=invert,include.J=include.J)
out <- x
out$irr <- x$irr[i]
out$pos <- x$pos[i]
out$labels <- x$labels[i]
out$thedate <- x$thedate[i]
out$nlr <- x$nlr[i]
j <- getindices.logratios(x,i)
out$num <- x$num[j]
out$den <- x$den[j]
out$intercepts <- x$intercepts[j]
out$covmat <- x$covmat[j,j]
return(out)
}
#' @rdname subset
#' @export
subset.redux <- function(x,i=NULL,labels=NULL,invert=FALSE,include.J=FALSE,...){
subset.logratios(x,i,labels,invert,include.J,...)
}
#' @rdname subset
#' @export
subset.results <- function(x,i=NULL,labels=NULL,invert=FALSE,...){
out <- x
if (is.null(i)) i <- findrunindices(x,prefixes=labels,invert=invert)
out$labels <- x$labels[i]
out$thedate <- x$thedate[i]
out$ages <- x$ages[i]
out$covmat <- x$covmat[i,i]
return(out)
}
#' Select a subset of isotopes from a dataset
#'
#' Extracts the intercepts, covariance matrix, etc. of a selection of
#' isotopes from a larger dataset
#'
#' @param x an object of class \code{\link{logratios}},
#' \code{\link{timeresolved}}, \code{\link{PHdata}} or
#' \code{\link{redux}}.
#' @param ... other arguments
#' @return an object of the same class as x
#' @examples
#' kfile <- system.file("K-glass.csv",package="ArArRedux")
#' masses <- c("Ar37","Ar38","Ar39","Ar40","Ar36")
#' mk <- loaddata(kfile,masses)
#' lk <- fitlogratios(blankcorr(mk,"EXB#","K:"),"Ar40")
#' k <- getmasses(lk,"Ar39","Ar40") # subset of the relevant isotopes
#' plotcorr(k)
#' @export
getmasses <- function(x,...){ UseMethod("getmasses",x) }
#' @rdname getmasses
#' @export
getmasses.default <- function(x,...){ stop() }
#' @param mass a vector of strings denoting the masses of interest
#' @param invert boolean parameter indicating whether the selection
#' should be inverted (default = FALSE)
#' @rdname getmasses
#' @export
getmasses.timeresolved <- function(x,mass,invert=FALSE,...){
out <- x
if (invert){ imasses <- which(x$masses != mass) }
else { imasses <- which(x$masses == mass) }
out$masses <- out$masses[imasses]
ii <- getindices(nmasses(x),nruns(x),imasses)
out$d <- x$d[,ii]
return(out)
}
#' @param num vector of strings indicating the numerator isotopes
#' @param den vector of string indicating the denominator isotopes
#' @rdname getmasses
#' @export
getmasses.logratios <- function(x,num,den,invert=FALSE,...){
out <- x
if (invert){ i <- which(!((x$num %in% num) & (x$den %in% den))) }
else { i <- which((x$num %in% num) & (x$den %in% den)) }
out$num <- x$num[i]
out$den <- x$den[i]
out$intercepts <- x$intercepts[i]
out$covmat <- x$covmat[i,i]
out$nlr <- graphics::hist(i,breaks=c(0,cumsum(x$nlr)),
plot=FALSE)$counts
return(out)
}
#' @rdname getmasses
#' @export
getmasses.redux <- function(x,num,den,invert=FALSE,...){
out <- x
if (invert){ hasmass <- !((x$num %in% num) & (x$den %in% den)) }
else { hasmass <- (x$num %in% num) & (x$den %in% den) }
i <- which(hasmass)
bi <- cumsum(c(1,x$nlr))
ei <- cumsum(x$nlr)
nn <- length(x$labels)
retain <- rep(FALSE,nn)
for (j in 1:nn) {
retain[j] <- any(hasmass[bi[j]:ei[j]])
}
out$irr <- x$irr[retain]
out$pos <- x$pos[retain]
out$labels <- x$labels[retain]
out$thedate <- x$thedate[i]
out$intercepts <- x$intercepts[i]
out$covmat <- x$covmat[i,i]
out$num <- x$num[i]
out$den <- x$den[i]
out$nlr <- graphics::hist(i,breaks=c(0,cumsum(x$nlr)),plot=FALSE)$counts[retain]
return(out)
}
setmasses <- function(x,mass,value){ UseMethod("setmasses",x) }
setmasses.default <- function(x,mass,value){stop()}
setmasses.timeresolved <- function(x,mass,value){
imasses <- which(x$masses == mass)
ii <- getindices(nmasses(x),nruns(x),imasses)
x$d[,ii] <- value
return(x)
}
setmasses.fit <- function(x,mass,value){
imasses <- which(x$masses == mass)
ii <- getindices(nmasses(x),nruns(x),imasses)
x$intercepts[ii] <- value$intercepts
for (i in 1:length(ii)){
x$covmat[ii[i],ii] <- value$covmat[i,]
}
return(x)
}
replacenegatives <- function(x){
out <- x
nmasses <- nmasses(x)
nruns <- nruns(x)
isnegative <- apply(x$d<0,2,"sum")>0
ntoreplace <- sum(isnegative)
out$d[,isnegative] <- # effectively set to zero
seq(from=1e-18,to=1e-20,length.out=ncycles(x)*ntoreplace)
return(out)
}
#' Merge a list of logratio data
#'
#' Recursively concatenates a list of logratio data into one big dataset
#'
#' @param lrlist a list containing items of class
#' \code{\link{logratios}} or \code{\link{redux}}
#' @return an object of the same class as \code{x} containing the
#' merged dataset
#' @examples
#' samplefile <- system.file("Samples.csv",package="ArArRedux")
#' kfile <- system.file("K-glass.csv",package="ArArRedux")
#' cafile <- system.file("Ca-salt.csv",package="ArArRedux")
#' dfile <- system.file("Calibration.csv",package="ArArRedux")
#' masses <- c("Ar37","Ar38","Ar39","Ar40","Ar36")
#' blanklabel <- "EXB#"
#' Jpos <- c(3,15)
#' dlabels <- c("H1","AX","L1","L2")
#'
#' m <- loaddata(samplefile,masses) # samples and J-standards
#' mk <- loaddata(kfile,masses) # K-interference data
#' mca <- loaddata(cafile,masses) # Ca interference data
#' md <- loaddata(dfile,dlabels,PH=TRUE) # detector intercalibrations
#'
#' # form and fit logratios
#' l <- fitlogratios(blankcorr(m,blanklabel),"Ar40")
#' lk <- fitlogratios(blankcorr(mk,blanklabel,"K:"),"Ar40")
#' k <- getmasses(lk,"Ar39","Ar40") # subset on the relevant isotopes
#' lca <- fitlogratios(blankcorr(mca,blanklabel,"Ca:"),"Ar37")
#' ca <- getmasses(lca,c("Ar36","Ar39"),c("Ar37","Ar37")) # subset
#' ld <- fitlogratios(blankcorr(md))
#' d <- averagebyday(ld,"DCAL")
#'
#' # merge all data (except air shots) into one big logratio structure
#' X <- newredux(concat(list(l,k,ca,d)),Jpos)
#' data(Melbourne)
#' if (isTRUE(all.equal(Melbourne$X,X))) {
#' print("We just reconstructed the built-in dataset Melbourne$X")}
#' @export
concat <- function(lrlist){
if (length(lrlist)==2) {
x <- lrlist[[1]]
y <- lrlist[[2]]
out <- x
out$irr <- c(x$irr,y$irr)
out$pos <- c(x$pos,y$pos)
out$labels <- c(x$labels,y$labels)
out$thedate <- c(x$thedate,y$thedate)
out$num <- c(x$num,y$num)
out$den <- c(x$den,y$den)
out$nlr <- c(x$nlr,y$nlr)
out$intercepts <- c(x$intercepts,y$intercepts)
out$covmat <- mergematrices(x$covmat,y$covmat)
} else {
x <- lrlist[[1]]
rest <- lrlist[2:length(lrlist)]
y <- concat(rest)
out <- concat(list(x,y))
}
return(out)
}
| /scratch/gouwar.j/cran-all/cranData/ArArRedux/R/toolbox.R |
VAR = function(Z,p) {
Z = as.matrix(Z)
q = dim(Z)[2]
n = dim(Z)[1]
aux=embed(Z,p+1)
Z=aux[,1:q]
X=cbind(1,aux[,-c(1:q)])
n=n-p
beta = solve(t(X)%*%X,t(X)%*%Z)
coef = list(C = t(beta)[,1])
if (p>0) {
AR = array(NA,dim = c(q,q,p))
for (i in 1:p) AR[,,i] = t(beta)[,((i-1)*q+2):(i*q+1)]
coef$AR = AR
}
e = Z - X%*%beta
SSR = t(e)%*%e
k = q + q^2*p
V = SSR/(n-k)
a = n*log(det(SSR/n)) + 2*k
b = n*log(det(SSR/n)) + k*log(n)
LR = V
if (p>0) {
D = solve(diag(1,q)- apply(AR, c(1,2), sum))
LR = t(D) %*% V %*% D
}
return(list(coef = coef, e = e, Cov = V, AIC = a, BIC = b, LR = LR, D=D))
}
neweywest = function(X,B=NULL, kernel.type = "QuadraticSpectral", prewhite = FALSE,VCOV.lag=1) {
n=nrow(X)
if (prewhite) {
fit = VAR(X,VCOV.lag)
X = fit$e
J = fit$D
}
if (is.null(B)) B = autobw(X,kernel.type)
T = dim(as.matrix(X))[1]
V = cov(X,X)
if(VCOV.lag!=0){
for (k in 1:(VCOV.lag)) {
D = kernel(k/B,kernel.type)*cov(X[(1 + k):nrow(X), ], X[1:(nrow(X)- k), ])
V = V + D + t(D)
}
}
if (prewhite) V = t(J)*V*J
return(V)
}
kernel = function(x,type, normalize = TRUE) {
if (normalize) ca = switch(type, Truncated = 2, Bartlett = 2/3, Parzen = 0.539285,
TukeyHanning = 3/4, QuadraticSpectral = 1)
else ca = 1
switch(type,
Truncated = ifelse(abs(ca*x) > 1, 0, 1),
Bartlett = ifelse(abs(ca*x) > 1, 0, 1 - abs(ca*x)),
Parzen = ifelse(abs(ca*x) > 1, 0, ifelse(abs(ca*x) < 0.5, 1 - 6 * (ca*
x)^2 + 6 * abs(ca*x)^3, 2*(1 - abs(ca*x))^3)),
TukeyHanning = ifelse(abs(ca*x) > 1, 0, (1 + cos(pi*ca*x))/2),
QuadraticSpectral = {y =6*pi*x/5
ifelse(abs(x) < 1e-04, 1, 3*(1/y)^2 * (sin(y)/y - cos(y)))})
}
autobw = function(X,type) {
T = dim(as.matrix(X))[1]
phi = 0.8
alpha = 4*phi^2/(1+2*phi+phi^2)^2
S = switch(type,
Truncated = 0.6611*(alpha*T)^(1/5),
Bartlett = 1.1447*(alpha*T)^(1/3),
Parzen = 2.6614*(alpha*T)^(1/5),
TukeyHanning = 1.7462*(alpha*T)^(1/5),
QuadraticSpectral = 1.3221*(alpha*T)^(1/5)
)
}
VARHAC = function(X,lag_max) {
M = 1e10
for (i in 0:lag_max) {
fit = VAR(X,i)
if (fit$BIC<M) {
M = fit$BIC
b = i
V = fit$LR
}
}
return(V)
}
| /scratch/gouwar.j/cran-all/cranData/ArCo/R/auxiliary_codes.R |
#' A generated dataset used in the examples
#'
#' This data contains 100 observations of 20 variables generated using the dgp from Carvalho, Masini and Medeiros (2016). Each variable is one ArCo unit. The intervention took place on the first unit at t0=51 by adding a constant equal to 0.628, which is one standard deviation of the treated unit variable before the intervention.
#'
#' @docType data
#' @keywords datasets
#' @name data.q1
#' @usage data(data.q1)
#' @format A matrix with 100 rows and 20 variables.
#' @references Carvalho, C., Masini, R., Medeiros, M. (2016) "ArCo: An Artificial Counterfactual Approach For High-Dimensional Panel Time-Series Data.".
NULL
#' A dataset used in the examples
#'
#' This data is a list with two matrixes, each have 100 observations and 6 variables. It was generatedthe using the dgp from Carvalho, Masini and Medeiros (2016). In the ArCo context, each matrix is a variable and each variable in the matrixes is an unit. The intervention took place on the first unit at t0=51 by adding constants of 0.840 and 0.511 (one standar deviation before the intervention) on variables (matrixes) 1 and 2.
#'
#' @docType data
#' @keywords datasets
#' @name data.q2
#' @usage data(data.q2)
#' @format A list with 2 matrixes of 100 rows and 6 variables.
#' @references Carvalho, C., Masini, R., Medeiros, M. (2016) "ArCo: An Artificial Counterfactual Approach For High-Dimensional Panel Time-Series Data.".
NULL
#' Dataset used on the empirical example by Carvalho, Masini and Medeiros (2016).
#'
#' This is the data from the \emph{nota fiscal paulista} (NFP) example from Carvalho, Masini and Medeiros (2016). The variables are the food away from home component of the inflation and the GDP for 9 metropolitan areas in Brazil. Each variable is represented by a matrix inside the list. The treated unit is the Sao Paulo metropolitan area, which is the first column in each matrix. The treatment took place at \eqn{t_0=34}.
#'
#' @docType data
#' @keywords datasets
#' @name inflationNFP
#' @usage data(inflationNFP)
#' @format A list with two matrixes of 56 rows and 9 variables.
#' @references Carvalho, C., Masini, R., Medeiros, M. (2016) "ArCo: An Artificial Counterfactual Approach For High-Dimensional Panel Time-Series Data.".
NULL | /scratch/gouwar.j/cran-all/cranData/ArCo/R/datasets.R |
#' Estimates the intervention time on a given treated unit
#'
#' Estimates the intervention time on a given treated unit based on any model supplied by the user.
#'
#' @details This description may be useful to clarify the notation and understand how the arguments must be supplied to the functions.
#' \itemize{
#' \item{units: }{Each unit is indexed by a number between \eqn{1,\dots,n}. They are for exemple: countries, states, municipalities, firms, etc.}
#' \item{Variables: }{For each unit and for every time period \eqn{t=1,\dots,T} we observe \eqn{q_i \ge 1} variables. They are for example: GDP, inflation, sales, etc.}
#' \item{Intervention: }{The intervention took place only in the treated unit at time \eqn{t_0=\lambda_0*T}, where \eqn{\lambda_0} is in (0,1).}
#' }
#'
#' @inheritParams fitArCo
#' @param start Initial value of \eqn{\lambda_0} to be tested.
#' @param end Final value of \eqn{\lambda_0} to be tested.
#' @export
#' @import Matrix glmnet
#' @return A list with the following items:
#' \item{t0}{Estimated t0.}
#' \item{delta.norm}{The norm of the delta corresponding to t0.}
#' \item{call}{The matched call.}
#' @examples
#' #############################
#' ## === Example for q=1 === ##
#' #############################
#' data(data.q1)
#' # = First unit was treated on t=51 by adding
#' # a constant equal to one standard deviation.
#'
#' data=list(data.q1) # = Even if q=1 the data must be in a list
#'
#' ## == Fitting the ArCo using linear regression == ##
#'
#' # = creating fn and p.fn function = #
#' fn=function(X,y){
#' return(lm(y~X))
#' }
#' p.fn=function(model,newdata){
#' b=coef(model)
#' return(cbind(1,newdata)%*%b)
#' }
#'
#' t0a=estimate_t0(data = data,fn = fn, p.fn = p.fn, treated.unit = 1 )
#'
#'
#' #############################
#' ## === Example for q=2 === ##
#' #############################
#'
#' # = First unit was treated on t=51 by adding constants of one standard deviation.
#' # for the first and second variables
#' data(data.q2) # data is already a list
#'
#'
#' t0b=estimate_t0(data = data.q2,fn = fn, p.fn = p.fn, treated.unit = 1, start=0.4)
#' @seealso \code{\link{fitArCo}}
estimate_t0=function (data, fn=NULL, p.fn=NULL, start = 0.4, end = 0.9, treated.unit = 1,
lag = 0, Xreg = NULL , ...)
{
if(is.null(fn)){
fn=function(x,y){stats::lm(y~x)}
}
if(is.null(p.fn)){
p.fn=function(model,newdata){
b=stats::coef(model)
return(cbind(1,newdata) %*% b)
}
}
for (i in 1:length(data)) {
if (is.null(colnames(data[[i]]))) {
colnames(data[[i]]) = paste("V", i, "-U", 1:ncol(data[[i]]),
sep = "")
}
}
for (i in 1:length(data)) {
aux = length(unique(colnames(data[[i]])))
k = ncol(data[[i]])
if (aux < k) {
colnames(data[[i]]) = paste("V", i, "-U", 1:ncol(data[[i]]),
sep = "")
}
}
T = nrow(data[[1]])
starting.point = floor(start * T)
ending.point = min(floor(end * T),nrow(data[[1]])-lag+1)
save.delta = matrix(0, T, length(data))
for (i in starting.point:ending.point) {
m = fitArCo(data = data, fn = fn, p.fn = p.fn, treated.unit = treated.unit,
lag = lag, t0 = i, Xreg = Xreg, ...)
delta = m$delta[,2]
save.delta[i, ] = delta
}
delta.norm = sqrt(rowSums((save.delta)^2))
t0 = which(delta.norm == max(delta.norm))
delta = delta.norm[t0]
return(c(t0 = t0, delta.norm = delta,call=match.call()))
}
| /scratch/gouwar.j/cran-all/cranData/ArCo/R/estimate_t0.R |
#' Estimates the ArCo using the model selected by the user
#'
#' Estimates the Artificial Counterfactual unsing any model supplied by the user, calculates the most relevant statistics and allows for the counterfactual confidence intervals to be estimated by block bootstrap. \cr
#' The model must be supplied by the user through the arguments fn and p.fn. The first determines which function will be used to estimate the model and the second determines the forecasting function. For more details see the examples and the description on the arguments.
#'
#' @details This description may be useful to clarify the notation and understand how the arguments must be supplied to the functions.
#' \itemize{
#' \item{units: }{Each unit is indexed by a number between \eqn{1,\dots,n}. They are for exemple: countries, states, municipalities, firms, etc.}
#' \item{Variables: }{For each unit and for every time period \eqn{t=1,\dots,T} we observe \eqn{q_i \ge 1} variables. They are for example: GDP, inflation, sales, etc.}
#' \item{Intervention: }{The intervention took place only in the treated unit at time \eqn{t_0=\lambda_0*T}, where \eqn{\lambda_0} is in (0,1).}
#' }
#'
#' @param data A list of matrixes or data frames of length q. Each matrix is T X n and it contains observations of a single variable for all units and all periods of time. Even in the case of a single variable (q=1), the matrix must be inside a list.
#' @param fn The function used to estimate the first stage model. This function must receive only two arguments in the following order: X (independent variables), y (dependent variable). If the model requires additional arguments they must be supplied inside the function fn. If not supplied the default is the lm function.
#' @param p.fn The forecasting function used to estimate the counterfactual using the first stage model (normally a predict funtion). This function also must receive only two arguments in the following order: model (model estimated in the first stage), newdata (out of sample data to estimate the second stage). If the prediction requires additional arguments they must be supplied inside the function p.fn.
#' @param treated.unit Single number indicating the unit where the intervention took place.
#' @param t0 Single number indicating the intervention period.
#' @param lag Number of lags in the first stage model. Default is 0, i.e. only contemporaneous variables are used.
#' @param Xreg Exogenous controls.
#' @param alpha Significance level for the delta confidence bands.
#' @param boot.cf Should bootstrap confidence intervals for the counterfactual be calculated (default=FALSE).
#' @param R Number of bootstrap replications in case boot.cf=TRUE.
#' @param l Block length for the block bootstrap.
#' @param VCOV.type Type of covariance matrix for the delta. "iid" for standard covariance matrix, "var" or "varhac" to use prewhitened covariance matrix using VAR models, "varhac" selects the order of the VAR automaticaly and "nw" for Newey West. In the last case the user may select the kernel type and combine the kernel with the VAR prewhitening. For more details see Andrews and Monahan (1992).
#' @param VCOV.lag Lag used on the robust covariance matrix if VCOV.type is different from "iid".
#' @param bandwidth.kernel Kernel bandwidth. If NULL the bandwidth is automatically calculated.
#' @param kernel.type Kernel to be used for VCOV.type="nw".
#' @param VHAC.max.lag Maximum lag of the VAR in case VCOV.type="varhac".
#' @param prewhitening.kernel If TRUE and VCOV.type="nw", the covariance matrix is calculated with prewhitening (default=FALSE).
#' @param ... Additional arguments used in the function fn.
#'
#' @return An object with S3 class fitArCo.
#' \item{cf}{estimated counterfactual}
#' \item{fitted.values}{In sample fitted values for the pre-treatment period.}
#' \item{model}{A list with q estimated models, one for each variable. Each element in the list is the output of the fn function.}
#' \item{delta}{The delta statistics and its confidence interval.}
#' \item{p.value}{ArCo p-value.}
#' \item{data}{The data used.}
#' \item{t0}{The intervention period used.}
#' \item{treated.unit}{The treated unit used.}
#' \item{omega}{Residual standard deviation.}
#' \item{residuals}{model residuals.}
#' \item{boot.cf}{A list with the bootstrap result (boot.cf=TRUE) or logical FALSE (boot.cf=FALSE). In the first case, each element in the list refers to one bootstrap replication of the counterfactual, i. e. the list length is R.}
#' \item{call}{The matched call.}
#' @keywords ArCo
#' @export
#' @import Matrix glmnet
#' @importFrom stats cov embed qnorm
#' @examples
#' #############################
#' ## === Example for q=1 === ##
#' #############################
#' data(data.q1)
#' # = First unit was treated on t=51 by adding
#' # a constant equal to one standard deviation
#'
#' data=list(data.q1) # = Even if q=1 the data must be in a list
#'
#' ## == Fitting the ArCo using linear regression == ##
#' # = creating fn and p.fn function = #
#' fn=function(X,y){
#' return(lm(y~X))
#' }
#' p.fn=function(model,newdata){
#' b=coef(model)
#' return(cbind(1,newdata) %*% b)
#' }
#'
#' ArCo=fitArCo(data = data,fn = fn, p.fn = p.fn, treated.unit = 1 , t0 = 51)
#'
#' #############################
#' ## === Example for q=2 === ##
#' #############################
#'
#' # = First unit was treated on t=51 by adding constants of one standard deviation
#' # for the first and second variables
#'
#' data(data.q2) # data is already a list
#'
#' ## == Fitting the ArCo using the package glmnet == ##
#' ## == Quadratic Spectral kernel weights for two lags == ##
#'
#' ## == Fitting the ArCo using the package glmnet == ##
#' ## == Bartlett kernel weights for two lags == ##
#' require(glmnet)
#' set.seed(123)
#' ArCo2=fitArCo(data = data.q2,fn = cv.glmnet, p.fn = predict,treated.unit = 1 , t0 = 51,
#' VCOV.type = "nw",kernel.type = "QuadraticSpectral",VCOV.lag = 2)
#'
#' @references Carvalho, C., Masini, R., Medeiros, M. (2016) "ArCo: An Artificial Counterfactual Approach For High-Dimensional Panel Time-Series Data.".
#'
#' Andrews, D. W., & Monahan, J. C. (1992). An improved heteroskedasticity and autocorrelation consistent covariance matrix estimator. Econometrica: Journal of the Econometric Society, 953-966.
#' @seealso \code{\link{plot}}, \code{\link{estimate_t0}}, \code{\link{panel_to_ArCo_list}}
fitArCo=function (data, fn=NULL, p.fn=NULL, treated.unit, t0, lag = 0, Xreg = NULL, alpha = 0.05, boot.cf = FALSE, R = 100, l = 3,VCOV.type=c("iid","var","nw","varhac"),VCOV.lag=1,bandwidth.kernel=NULL,kernel.type=c("QuadraticSpectral","Truncated","Bartlett","Parzen","TukeyHanning"),VHAC.max.lag=5,prewhitening.kernel=FALSE,...)
{
if(is.null(fn)){
fn=function(x,y){stats::lm(y~x)}
}
if(is.null(p.fn)){
p.fn=function(model,newdata){
b=stats::coef(model)
return(cbind(1,newdata) %*% b)
}
}
VCOV.type=match.arg(VCOV.type)
kernel.type=match.arg(kernel.type)
if (boot.cf == TRUE) {
if (R < 10) {
stop("Minimum number of bootstrap samples is 10.")
}
}
if (is.null(names(data))) {
names(data) = paste("Variable", 1:length(data), sep = "")
}
for (i in 1:length(data)) {
if (is.null(colnames(data[[i]]))) {
colnames(data[[i]]) = paste("unit", 1:ncol(data[[i]]),
sep = "")
}
}
for (i in 1:length(data)) {
aux = length(unique(colnames(data[[i]])))
k = ncol(data[[i]])
if (aux < k) {
colnames(data[[i]]) = paste("unit", 1:ncol(data[[i]]),
sep = "")
}
}
if (length(data) == 1) {
Y = matrix(data[[1]][, treated.unit], ncol = 1)
X = data[[1]][, -treated.unit]
X = as.matrix(X)
colnames(X) = paste(names(data), colnames(data[[1]])[-treated.unit],
sep = ".")
}else {
Y = Reduce("cbind", lapply(data, function(x) x[, treated.unit]))
X = Reduce("cbind", lapply(data, function(x) x[, -treated.unit]))
aux = list()
for (i in 1:length(data)) {
aux[[i]] = paste(names(data)[i], colnames(data[[i]])[-treated.unit],
sep = ".")
}
colnames(X) = unlist(aux)
}
Y.raw = Y
if (lag != 0) {
aux1 = sort(rep(0:lag, ncol(X)))
aux = paste(rep(colnames(X), lag + 1), "lag", aux1, sep = ".")
X = embed(as.matrix(X), lag + 1)
colnames(X) = aux
Y = tail(Y, nrow(X))
}
if (length(Xreg) != 0) {
X = cbind(X, tail(Xreg, nrow(X)))
}
if (is.vector(Y)) {
Y = matrix(Y, length(Y), 1)
}
T=nrow(X)
y.fit = matrix(Y[1:(t0 - 1 - lag), ], ncol = length(data))
y.pred = matrix(Y[-c(1:(t0 - 1 - lag)), ], ncol = length(data))
x.fit = X[1:(t0 - 1 - lag), ]
x.pred = X[-c(1:(t0 - 1 - lag)), ]
save.cf = matrix(NA, nrow(y.pred), length(data))
save.fitted = matrix(NA, nrow(Y), length(data))
model.list = list()
for (i in 1:length(data)) {
model = fn(x.fit, y.fit[, i],...)
model.list[[i]] = model
contra.fact = p.fn(model, x.pred)
save.cf[, i] = contra.fact
save.fitted[, i] = p.fn(model, X)
}
boot.list = FALSE
if (boot.cf == TRUE) {
serie = cbind(y.fit, x.fit)
q = length(data)
bootfunc = function(serie) {
y.fit = serie[, 1:q]
x.fit = serie[, -c(1:q)]
if (is.vector(y.fit)) {
y.fit = matrix(y.fit, ncol = 1)
}
save.cf.boot = matrix(NA, nrow(x.pred), q)
for (i in 1:q) {
model.boot = fn(x.fit, y.fit[, i],...)
contra.fact.boot = p.fn(model.boot, x.pred)
save.cf.boot[, i] = contra.fact.boot
}
return(as.vector(save.cf.boot))
}
boot.cf = boot::tsboot(serie, bootfunc, R = R, l = 3,
sim = "fixed")
boot.stat = boot.cf$t
boot.list = list()
for (i in 1:nrow(boot.stat)) {
boot.list[[i]] = matrix(boot.stat[i, ], ncol = q)
}
}
delta.aux = tail(Y.raw, nrow(save.cf)) - save.cf
delta = colMeans(delta.aux)
aux = matrix(0, T, length(data))
aux[(t0 - lag):nrow(aux), ] = 1
vhat = Y - (save.fitted + t(t(aux) * delta))
v1 = matrix(vhat[1:(t0 - lag - 1), ], ncol = length(data))
v2 = matrix(vhat[(t0 - lag):nrow(vhat), ], ncol = length(data))
t0lag=t0-lag
sigmahat=T*switch(VCOV.type,
iid = cov(v1)/(t0lag-1) + cov(v2)/(T-t0lag),
var = VAR(v1,VCOV.lag)$LR/(t0lag-1) + VAR(v2,VCOV.lag)$LR/(T-t0lag),
nw = neweywest(v1,NULL,kernel.type,prewhitening.kernel,VCOV.lag)/(t0lag-1) + neweywest(v2,NULL,kernel.type,prewhitening.kernel,VCOV.lag)/(T-t0lag),
varhac = VARHAC(v1,VHAC.max.lag)/(t0lag-1) + VARHAC(v2,VHAC.max.lag)/(T-t0lag)
)
#pvalue
W = T * t(delta) %*% solve(sigmahat) %*% delta
p.value = 1 - stats::pchisq(W, length(delta))
if(length(delta)>1){
p.ind=rep(NA,length(delta))
aux=diag(sigmahat)
for(i in 1:length(delta)){
Wi = T * t(delta)[i] %*% solve(aux[i]) %*% delta[i]
p.ind[i]=1 - stats::pchisq(Wi, 1)
}
p.value=c(p.value,p.ind)
names(p.value)=c("Joint",names(data))
}
#confidence
w = sqrt(diag(sigmahat))
uI = delta + (w * qnorm(1 - alpha/2))/sqrt(T)
lI = delta - (w * qnorm(1 - alpha/2))/sqrt(T)
delta.stat = cbind(LB = lI, delta = delta, UB = uI)
names(model.list) = names(data)
colnames(save.cf) = names(data)
rownames(save.cf) = tail(rownames(Y.raw), nrow(save.cf))
colnames(save.fitted) = names(data)
rownames(save.fitted) = head(rownames(Y), nrow(save.fitted))
rownames(delta.stat) = names(data)
save.fitted = head(save.fitted, nrow(save.fitted) - nrow(save.cf))
if (typeof(boot.list) == "list") {
NAboot = Reduce(sum, boot.list)
if (is.na(NAboot)) {
warning("Some of the boostrap counterfactuals may have returned NA values. \n \n A possible cause is the number of observations being close the number of variables if the lm function was used.")
}
}
result = list(cf = save.cf, fitted.values = save.fitted, model = model.list,
delta = delta.stat, p.value = p.value, data = data, t0 = t0,
treated.unit = treated.unit, residuals=vhat, omega = w, boot.cf = boot.list, call = match.call())
class(result) = "fitArCo"
return(result)
} | /scratch/gouwar.j/cran-all/cranData/ArCo/R/fitArCo.R |
#' Transforms a balanced panel into a list of matrices compatible with the fitArCo function
#'
#' Transforms a balanced panel into a list of matrices compatible with the fitArCo function. The user must identify the columns with the time, the unit identifier and the variables.
#'
#' @param panel Balanced panel in a data.frame with columns for units and time.
#' @param time Name or index of the time column.
#' @param unit Name or index of the unit column.
#' @param variables Names or indexes of the columns containing the variables.
#' @export
#' @examples
#' # = Generate a small panel as example = #
#' set.seed(123)
#' time=sort(rep(1:100,2))
#' unit=rep(c("u1","u2"),100)
#' v1=rnorm(200)
#' v2=rnorm(200)
#' panel=data.frame(time=time,unit=unit,v1=v1,v2=v2)
#' head(panel)
#'
#' data=panel_to_ArCo_list(panel,time="time",unit="unit",variables = c("v1","v2"))
#' head(data$v1)
#'
#' @seealso \code{\link{fitArCo}}
panel_to_ArCo_list=function(panel,time,unit,variables){
unit.nam=as.vector(unique(panel[,unit]))
ArColist=list()
for(q in 1:length(variables)){
unitstore=matrix(rep(NA,nrow(panel)),ncol=length(unit.nam))
colnames(unitstore)=unit.nam
for(i in 1:length(unit.nam)){
aux=panel[which(panel[,unit]==unit.nam[i]),c(time,unit,variables[q])]
aux=aux[order(aux[,1]),]
unitstore[,i]=aux[,3]
}
rownames(unitstore)=aux[,1]
ArColist[[q]]=unitstore
}
names(ArColist)=variables
return(ArColist)
}
| /scratch/gouwar.j/cran-all/cranData/ArCo/R/panel_to_ArCo_list.R |
#' Plots realized values and the counterfactual estimated by the fitArCo function
#'
#' Plots realized values and the counterfactual estimated by the fitArCo function. The plotted variables will be on the same level as supplied to the fitArCo function.
#'
#' @param x An ArCo object estimated using the fitArCo function.
#' @param ylab n dimensional character vector, where n is the length of the plot argument or n=q if plot=NULL.
#' @param main n dimensional character vector, where n is the length of the plot argument or n=q if plot=NULL.
#' @param plot n dimensional numeric vector where each element represents an ArCo unit. If NULL, all units will be plotted. If, for example, plot=c(1,2,5) only units 1 2 and 5 will be plotted according to the order specified by the user on the fitArCo.
#' @param ncol Number of columns when multiple plots are displayed.
#' @param display.fitted If TRUE the fitted values of the first step estimation are also plotted (default=FALSE).
#' @param y.min n dimensional numeric vector defining the lower bound for the y axis. n is the length of the plot argument or n=q if plot=NULL
#' @param y.max n dimensional numeric vector defining the upper bound for the y axis. n is the length of the plot argument or n=q if plot=NULL
#' @param ... Other graphical parameters to plot.
#' @param confidence.bands TRUE to plot the counterfactual confidence bands (default=FALSE). If the ArCo was estimated without bootstrap this argument will be forced to FALSE.
#' @param alpha Significance level for the confidence bands.
#' @export
#' @examples
#' ##############################################
#' ## === Example based on the q=1 fitArCo === ##
#' ##############################################
#'# = First unit was treated on t=51 by adding
#'# a constant equal to one standard deviation
#' data(data.q1)
#' data=list(data.q1) # = Even if q=1 the data must be in a list
#' ## == Fitting the ArCo using linear regression == ##
#' # = creating fn and p.fn function = #
#' fn=function(X,y){
#' return(lm(y~X))
#' }
#' p.fn=function(model,newdata){
#' b=coef(model)
#' return(cbind(1,newdata) %*% b)}
#' ArCo=fitArCo(data = data,fn = fn, p.fn = p.fn, treated.unit = 1 , t0 = 51)
#' plot(ArCo)
#' @seealso \code{\link{fitArCo}}
plot.fitArCo=function(x,ylab=NULL,main=NULL,plot=NULL,ncol=1,display.fitted=FALSE,y.min=NULL,y.max=NULL,confidence.bands=FALSE,alpha=0.05,...){
oldmar=graphics::par()$mar
oldmfrow=graphics::par()$mfrow
oldoma=graphics::par()$oma
t0=x$t0
data=x$data
fitted=x$fitted.values
treated.unit=x$treated.unit
cf=x$cf
boot.cf=x$boot.cf
if(typeof(boot.cf)=="list"){
NAboot=Reduce(sum,boot.cf)
if(is.na(NAboot)){
warning("NA values on the bootstrap counterfactual: unable to plot confidence bands.")
confidence.bands=FALSE
}
}
if(typeof(boot.cf)!="list"){
if(confidence.bands==TRUE){
confidence.bands=FALSE
cat("Confidence bands set to FALSE: The model has no confidence bands. Set boot.cf to TRUE on the ArCo estimation.")
}
}
if (length(data) == 1) {
Y = matrix(data[[1]][, treated.unit], ncol = 1)
}else {
Y = Reduce("cbind", lapply(data, function(x) x[, treated.unit]))
}
aux=nrow(Y)-nrow(fitted)-nrow(cf)
if(aux!=0){
fitted=rbind(matrix(NA,aux,ncol(fitted)),fitted)
}
##
if (is.null(plot)) {
if(is.null(ylab)){
ylab=ylab = paste("Y", 1:length(data), sep = "")
}
if(is.null(y.min)){
y.min=apply(rbind(Y,cf),2,min,na.rm=TRUE)
}
if(is.null(y.max)){
y.max=apply(rbind(Y,cf),2,max,na.rm=TRUE)
}
} else {
if(is.null(ylab)){
ylab=ylab = paste("Y", plot, sep = "")
}
if(is.null(y.min)){
y.min=apply(as.matrix(rbind(Y,cf)[,plot]),2,min,na.rm=TRUE)
}
if(is.null(y.max)){
y.max=apply(as.matrix(rbind(Y,cf)[,plot]),2,max,na.rm=TRUE)
}
}
if(is.null(plot)){
if(display.fitted==TRUE){
graphics::par(oma = c(4, 1, 1, 1))
}
graphics::par(mfrow = c(ceiling(length(data)/ncol), ncol))
for (i in 1:ncol(Y)) {
graphics::plot(Y[, i], type = "l", ylab = ylab[i], xlab = "Time",main=main[i],ylim=c(y.min[i],y.max[i]),...)
if(confidence.bands==TRUE){
aux=Reduce("cbind",lapply(boot.cf,function(x)x[,i]))
aux1=t(apply(aux,1,sort))
intervals=c(round(ncol(aux)*(alpha/2)),round(ncol(aux)*(1-alpha/2)))
xcord=t0:length(Y[,i])
ycord1=aux1[,intervals[1]]
ycord2=aux1[,intervals[2]]
graphics::polygon(c(rev(xcord),xcord),c(rev(ycord1),ycord2),col='gray60',border = NA)
graphics::lines(Y[, i])
}
graphics::lines(c(rep(NA, t0 - 2), Y[t0 - 1, i], cf[, i]), col = "blue")
graphics::abline(v = t0, col = "blue", lty = 2)
if(display.fitted==TRUE){
graphics::lines(fitted[,i],col="red")
}
}
if(display.fitted==TRUE){
graphics::par(fig = c(0, 1, 0, 1), oma = c(0, 0, 0, 0), mar = c(0, 0, 0, 0), new = TRUE)
graphics::plot(0, 0, type = "n", bty = "n", xaxt = "n", yaxt = "n")
graphics::legend("bottom",legend = c("Observed","Fitted","Counterfactual"),col=c(1,2,4),
lwd=c(2,2,2),lty=c(1,1,1),bty="n",seg.len = 1,horiz = TRUE, inset = c(0,0),xpd=TRUE,cex=1.2)
}
}else{
if(display.fitted==TRUE){
graphics::par(oma = c(4, 1, 1, 1))
}
graphics::par(mfrow = c(ceiling(length(plot)/ncol), ncol))
for(i in 1:length(plot)){
graphics::plot(Y[, plot[i]], type = "l", ylab = ylab[i], xlab = "Time",main=main[i],ylim=c(y.min[i],y.max[i]),...)
if(confidence.bands==TRUE){
aux=Reduce("cbind",lapply(boot.cf,function(x)x[,plot[i]]))
aux1=t(apply(aux,1,sort))
intervals=c(round(ncol(aux)*(alpha/2)),round(ncol(aux)*(1-alpha/2)))
xcord=t0:length(Y[,plot[i]])
ycord1=aux1[,intervals[1]]
ycord2=aux1[,intervals[2]]
graphics::polygon(c(rev(xcord),xcord),c(rev(ycord1),ycord2),col='gray60',border = NA)
graphics::lines(Y[, plot[i]])
}
graphics::lines(c(rep(NA, t0 - 2), Y[t0 - 1, plot[i]], cf[, plot[i]]), col = "blue")
graphics::abline(v = t0, col = "blue", lty = 2)
if(display.fitted==TRUE){
graphics::lines(fitted[,plot[i]],col="red")
}
}
if(display.fitted==TRUE){
graphics::par(fig = c(0, 1, 0, 1), oma = c(0, 0, 0, 0), mar = c(0, 0, 0, 0), new = TRUE)
graphics::plot(0, 0, type = "n", bty = "n", xaxt = "n", yaxt = "n")
graphics::legend("bottom",legend = c("Observed","Fitted","Counterfactual"),col=c(1,2,4),
lwd=c(2,2,2),lty=c(1,1,1),bty="n",seg.len = 1,cex=1.2,horiz = TRUE, inset = c(0,0),xpd=TRUE)
}
}
graphics::par(mar=oldmar,mfrow=oldmfrow,oma=oldoma)
}
| /scratch/gouwar.j/cran-all/cranData/ArCo/R/plot.fitArCo.R |
ardec <-
function(x,coef, ...) {
dat=x-mean(x)
p=length(coef)
ndat=length(x)
G=matrix(nrow=p,ncol=p)
G[1,]=coef
G[seq(2,p),seq(1,p-1)]=diag(1,(p-1))
G[seq(2,p),p]=0
modulus=Mod(eigen(G)[[1]])
lambda=2*pi/Arg(eigen(G)[[1]])
eigenvalues=eigen(G)
A=diag(eigenvalues[[1]])
E=eigenvalues[[2]]
B=solve(E)
F=rep(NA,p)
F[1]=1
F[seq(2,p)]=0
a=t(E) %*% F
d=diag(as.vector(a))
H=d %*% B
Z=matrix(nrow=p,ncol=ndat)
Z[1,]=dat
for (i in seq(1,p-1)){
Z[i+1,]=as.vector(filter(dat,c(rep(0,i),1), method="convolution", sides=1))}
g=matrix(nrow=p,ncol=ndat)
for (j in seq(1,p)){
for (t in seq(1,ndat)){
g[j,t]=H[j, ] %*% Z[,t] }}
return(list(period=lambda,modulus=modulus,comps=g))
}
| /scratch/gouwar.j/cran-all/cranData/ArDec/R/ardec.R |
ardec.lm <-
function(x) {
dat=x-mean(x)
ndat=length(dat)
p=ar(dat,method="burg")[[1]] # p=order of autoregressive model from AIC (burg method)
# linear autoregressive model fit
X=t(matrix(dat[rev(rep((1:p),ndat-p)+ rep((0:(ndat-p-1)),rep(p,ndat-p)))],p,ndat-p))
y=rev(dat[(p+1):ndat])
fit=lm(y~-1+X, x=TRUE)
return(fit)
}
| /scratch/gouwar.j/cran-all/cranData/ArDec/R/ardec.lm.R |
ardec.periodic <-
function(x,per,tol=0.95){
# if(frequency(x)!=12){stop("monthly time series required")}
# updated 29 Apr 2013
fit=ardec.lm(x)
comp=ardec(x,fit$coefficients)
if(any(comp$period > (per-tol) & comp$period < (per+tol))) {
candidates=which(comp$period > (per-tol) & comp$period < (per+tol))
lper=candidates[which.max(comp$modulus[candidates])]
l=comp$period[lper]
m=comp$modulus[lper]
gt=Re(comp$comps[lper,]+comp$comps[lper+1,]) }
return(list(period=l,modulus=m,component=gt))
}
| /scratch/gouwar.j/cran-all/cranData/ArDec/R/ardec.periodic.R |
ardec.trend <-
function(x){
options(warn=-1)
fit=ardec.lm(x)
comp=ardec(x,fit$coefficients)
if(any(comp$period==Inf)){warning("no trend component")}
if(any(comp$period ==Inf)){
l=comp$period[which(match(comp$period,Inf)==1)[1]]
m=comp$modulus[which(match(comp$period,Inf)==1)[1]]
gt=Re(comp$comps[which(match(comp$period,Inf)==1 )[1],])
}
return(list(modulus=m,trend=gt))
}
| /scratch/gouwar.j/cran-all/cranData/ArDec/R/ardec.trend.R |
#' Calibration of a fishpond chronology
#'
#' A data set containing information on the ages of two fishpond deposits.
#'
#' @format A data frame with 55,965 rows and 12 variables
#' \describe{
#' \item{Iteration}{iteration of the MCMC algorithm}
#' \item{beta.2..Layer.II.}{end date of Layer II}
#' \item{theta.5..Layer.II.}{age of dated event 5 in Layer II}
#' \item{theta.4..Layer.II.}{age of dated event 4 in Layer II}
#' \item{theta.3..Layer.II.}{age of dated event 3 in Layer II}
#' \item{theta.2..Layer.II.}{age of dated event 2 in Layer II}
#' \item{alpha.2..Layer.II.}{start date of Layer II}
#' \item{beta.1..Layer.III.}{end date of Layer III}
#' \item{theta.1..Layer.III.}{age of dated event 1 in Layer III}
#' \item{alpha.1..Layer.III.}{start date of Layer III}
#' \item{phi.1}{floating parameter}
#' \item{X}{superfluous column}
#' }
"Fishpond"
#' Ksar Akil dates calibrated by ChronoModel
#'
#' A data set.
#'
#' @format A data frame with 30,000 rows and 17 variables:
#' \describe{
#' \item{iter}{iteration of the MCMC algorithm}
#' \item{Layer.V}{Layer V}
#' \item{Layer.VI}{Layer VI}
#' \item{Layer.XI}{Layer XI}
#' \item{Layer.XII}{Layer XII}
#' \item{Layer.XVI.4}{Layer XVI 4}
#' \item{Layer.XVI.3}{Layer XVI 3}
#' \item{Layer.XVI.1}{Layer XVI 1}
#' \item{Layer.XVI.2}{Layer XVI 2}
#' \item{Layer.XVII.2}{Layer XVII 2}
#' \item{Layer.XVII.1}{Layer XVII 1}
#' \item{Layer.XVII.3}{Layer XVII 3}
#' \item{Layer.XVII.4}{Layer XVII 4}
#' \item{Layer.XVIII}{Layer XVIII}
#' \item{Layer.XIX}{Layer XIX}
#' \item{Layer.XX}{Layer XX}
#' \item{Layer.XXII}{Layer XXII}
#' }
"KADatesChronoModel"
#' Ksar Akil dates calibrated by OxCal
#'
#' A data set
#'
#' @format A data frame with 10,000 rows and 27 variables:
#' \describe{
#' \item{Pass}{iteration of the MCMC algorithm}
#' \item{Ethelruda}{Ethelruda}
#' \item{start.dated.IUP}{start dated IUP}
#' \item{GrA.53000}{GrA 5300}
#' \item{end.dated.IUP}{end dated IUP}
#' \item{start.Ahmarian}{start Ahmarian}
#' \item{GrA.57597}{GrA 57597}
#' \item{GrA.53004}{GrA 53004}
#' \item{GrA.57542}{GrA 57542}
#' \item{GrA.54846}{GrA 54846}
#' \item{GrA.57603}{GrA 57603}
#' \item{GrA.57602}{GrA 57602}
#' \item{GrA.53001}{GrA 53001}
#' \item{Egbert}{Egbert}
#' \item{GrA.54847}{GrA 54847}
#' \item{GrA.57599}{GrA 57599}
#' \item{GrA.57598}{GrA 57598}
#' \item{GrA.57544}{GrA 57544}
#' \item{end.Ahmarian}{end Ahmarian}
#' \item{start.UP}{start UP}
#' \item{GrA.57545}{GrA 57545}
#' \item{GrA.53006}{GrA 53006}
#' \item{GrA.54848}{GrA 54848}
#' \item{end.UP}{end UP}
#' \item{start.EPI}{start EPI}
#' \item{GrA.53005}{GrA 53005}
#' \item{end.EPI}{end EPI}
#' }
"KADatesOxcal"
#' Ksar Akil phases calibrated by ChronoModel
#'
#' A data set
#'
#' @format A data frame with 30,000 rows and 9 variables:
#' \describe{
#' \item{iter}{iteration of the MCMC algorithm}
#' \item{EPI.alpha}{start date of EPI}
#' \item{EPI.beta}{end date of EPI}
#' \item{UP.alpha}{start date of UP}
#' \item{UP.beta}{end date of UP}
#' \item{Ahmarian.alpha}{start date of Ahmarian}
#' \item{Ahmarian.beta}{end date of Ahmarian}
#' \item{IUP.alpha}{start date of IUP}
#' \item{IUP.beta}{end date of IUP}
#' }
"KAPhasesChronoModel"
#' Anglo-Saxon Female Burials with Beads
#'
#' Results of an OxCal calibration
#'
#' @format A data frame with 5,000 rows and 79 columns:
#' \describe{
#' \item{Begin all dates}{Early boundary}
#' \item{UB-6041 (CasD182)}{Date of burial CasD182}
#' \item{UB-6038 (CasD183)}{Date of burial CasD183}
#' \item{UB-4960 (BuD391B)}{Date of burial BuD391B}
#' \item{UB-4959 (BuD391A)}{Date of burial BuD391A}
#' \item{UB-4511 (EH090)}{Date of burial EH090}
#' \item{UB-4512 (EH091)}{Date of burial EH091}
#' \item{MelSG077}{Date of burial MelSG077}
#' \item{UB-4885 (MelSG078)}{Date of burial MelSG078}
#' \item{UB-4884 (MelSG079)}{Date of burial MelSG079}
#' \item{UB-4882 (MelSG080)}{Date of burial MelSG080}
#' \item{UB-6476 (BuD339)}{Date of burial BuD339}
#' \item{UB-4734 (MH105c)}{Date of burial MH105c}
#' \item{UB-4732 (MH094)}{Date of burial MH094}
#' \item{UB-4890 (MelSG075)}{Date of burial MelSG075}
#' \item{UB-4728 (MH064)}{Date of burial MH064}
#' \item{UB-4733 (MH095)}{Date of burial MH095}
#' \item{UB-6473 (BuD250)}{Date of burial BuD250}
#' \item{UB-4735 (Ber022)}{Date of burial Ber022}
#' \item{UB-4739 (Ber134/1)}{Date of burial Ber134/1}
#' \item{UB-4836 (WG27)}{Date of burial WG27}
#' \item{UB-6472 (BuD222)}{Date of burial BuD222}
#' \item{UB-6037 (CasD134)}{Date of burial CasD134}
#' \item{UB-4888 (MelSG089)}{Date of burial MelSG089}
#' \item{UB-6040 (CasD053)}{Date of burial CasD053}
#' \item{UB-4707 (EH079)}{Date of burial EH079}
#' \item{UB-6035 (CasD096)}{Date of burial CasD096}
#' \item{UB-4975 (AstCli12)}{Date of burial AstCli12}
#' \item{UB-4984 (Lec018)}{Date of burial Lec018}
#' \item{UB-4835 (ApD134)}{Date of burial ApD134}
#' \item{UB-4729 (MH068)}{Date of burial MH068}
#' \item{UB-6034 (CasD120)}{Date of burial CasD120}
#' \item{UB-4705 (WHes123)}{Date of burial WHes123}
#' \item{UB-6033 (WHes113)}{Date of burial WHes113}
#' \item{UB-4709 (EH014)}{Date of burial EH014}
#' \item{UB-4708 (EH083)}{Date of burial EH083}
#' \item{UB-5208 (ApD107)}{Date of burial ApD107}
#' \item{UB-4077 (But4275)}{Date of burial But4275}
#' \item{UB-4965 (ApD117)}{Date of burial ApD117}
#' \item{UB-4889 (MelSG069)}{Date of burial MesSG069}
#' \item{UB-4963 (SPTip208)}{Date of burial SPTip208}
#' \item{UB-6032 (SPTip073)}{Date of burial SPTip073}
#' \item{UB-6036 (CasD013)}{Date of burial CasD013}
#' \item{UB-4887 (MelSG082)}{Date of burial MeSG082}
#' \item{UB-4964 (Cod30)}{Date of burial Cod30}
#' \item{UB-4883 (MelSG095)}{Date of burial MelSG095}
#' \item{UB-4042 (But1674)}{Date of burial But1674}
#' \item{UB-4552 (MaDE3)}{Date of burial MaDE3}
#' \item{UB-4507 (Lec187)}{Date of burial Lec187}
#' \item{UB-4706 (WHes118)}{Date of burial WHes118}
#' \item{UB-4502 (Lec138)}{Date of burial Lec138}
#' \item{UB-4504 (Lec179)}{Date of burial Lec179}
#' \item{UB-4910 (BloodH22)}{Date of burial BloodH22}
#' \item{UB-4506 (Lec172/2)}{Date of burial Lec172/2}
#' \item{MaDE1 & E2}{Date of burial MaDE1 & E2}
#' \item{UB-4554 (MaDF2)}{Date of burial MaDF2}
#' \item{UB-4549 (MaDC7)}{Date of burial MaDC7}
#' \item{UB-4553 (MaDD10)}{Date of burial MaDD10}
#' \item{UB-6042 (CasD088)}{Date of burial CasD088}
#' \item{UB-4501 (Lec014)}{Date of burial Lec014}
#' \item{UB-4503 (Lec148)}{Date of burial Lec148}
#' \item{SUERC-51539 (ERL G353)}{Date of burial ERL G353}
#' \item{SUERC-51548 (ERL G210)}{Date of burial ERL G210}
#' \item{SUERC-51553 (ERL G116)}{Date of burial ERL G116}
#' \item{SUERC-39108 ERLK G322}{Date of burial ERLK G322}
#' \item{SUERC-39109 ERL G362}{Date of burial ERL G362}
#' \item{SUERC-39112 ERL G405}{Date of burial ERL G405}
#' \item{SUERC-51560 ERL G038}{Date of burial ERL G038}
#' \item{SUERC-39091 (ERL G003)}{Date of burial ERL G003}
#' \item{SUERC-39092 (ERL G005)}{Date of burial ERL G005}
#' \item{SUERC-39113 (ERL G417)}{Date of burial ERL G417}
#' \item{SUERC-51549 (ERL G195)}{Date of burial ERL G195}
#' \item{SUERC-51543 (ERL G281)}{Date of burial ERL G281}
#' \item{SUERC-51551 (ERL G193)}{Date of burial ERL G193}
#' \item{SUERC-51552 (ERL G107)}{Date of burial ERL G107}
#' \item{SUERC-39100 (ERL G266)}{Date of burial ERL G266}
#' \item{SUERC-51550 (ERL G254)}{Date of burial ERL G254}
#' \item{SUERC-39096 (ERL G112)}{Date of burial ERL G112}
#' \item{End all dates}{Late boundary}
#' }
"AngloSaxonBurials"
| /scratch/gouwar.j/cran-all/cranData/ArchaeoPhases.dataset/R/data.R |
#' @title Descriptive Statistics Of A Series
#' @description Provides descriptive statistics of a particular series. First column in the output result mentions 10 different statistics and second column contains the Statistics values of the particular series.
#' @param Y Univariate series
#' @import dplyr, psych, e1071, stats
#'
#' @return
#' \itemize{
#' \item desc_table - A table contains 10 descriptive statistics row-wise
#' }
#' @export
#'
#' @examples
#' Y <- rnorm(100, 100, 10)
#' result <- series_descstat(Y)
#' @references
#' \itemize{
#'\item Garai, S., & Paul, R. K. (2023). Development of MCS based-ensemble models using CEEMDAN decomposition and machine intelligence. Intelligent Systems with Applications, 18, 200202.
#' \item Garai, S., Paul, R. K., Rakshit, D., Yeasin, M., Paul, A. K., Roy, H. S., Barman, S. & Manjunatha, B. (2023). An MRA Based MLR Model for Forecasting Indian Annual Rainfall Using Large Scale Climate Indices. International Journal of Environment and Climate Change, 13(5), 137-150.
#' }
series_descstat <- function(Y){
sw_test <- shapiro.test(Y)
p_value <- sw_test$p.value
sw_stat <- round(sw_test$statistic, 3)
if (p_value <= 0.01) {
shapiro_wilk <- paste0("***")
} else if (p_value <= 0.05) {
shapiro_wilk <- paste0("**")
} else if (p_value <= 0.1) {
shapiro_wilk <- paste0("*")
} else {
shapiro_wilk <- paste0("")
}
# embedding
diff.1 <- embed(Y, 2)
Yt <- diff.1[,1]
Yt_1 <- diff.1[,2]
y <- log(Yt/Yt_1)
stats <- rbind(length(Y),
round(min(Y), 3),
round(max(Y), 3),
round(mean(Y), 3),
round(sd(Y), 3),
round(sd(y), 3),
round((sd(Y) / mean(Y) * 100), 3),
round((psych::skew(Y)), 3),
round(e1071::kurtosis(Y), 3),
paste0(sw_stat, shapiro_wilk))
desc_table <- data.frame(cbind(c('N', 'Minimum', 'Maximum', 'Mean', 'SD', 'Cond_SD', 'CV(%)',
'Skewness', 'Kurtosis', 'Shapiro-Wilk'), stats))
colnames(desc_table) <- c('Statistics', 'Values')
return(desc_table)
}
#'@title Non linearity test of a Data Frame
#' @description Performs non linearity test result for a series. Provides output as a single element (data frame) list. First column mentions different statistics (eps). Other columns are the Statistics values of the particular dimension.
#' @param df Data Frame with first column as serial number or date
#' @import DescribeDF
#'
#' @return
#' \itemize{
#' \item nonlinearity_list - A list with a single element (data frame) . Element is named as the name of the series provided. The element is such that first column mentions different statistics and other columns are the Statistics values of the particular dimension.
#' }
#' @export
#'
#' @examples
#' my_series <- rnorm(100, 100, 10)
#' nonlinearity <- series_nonlinearity(my_series)
#' nonlinearity$my_series
#' @references
#' \itemize{
#'\item Garai, S., & Paul, R. K. (2023). Development of MCS based-ensemble models using CEEMDAN decomposition and machine intelligence. Intelligent Systems with Applications, 18, 200202.
#' \item Garai, S., Paul, R. K., Rakshit, D., Yeasin, M., Paul, A. K., Roy, H. S., ... & Manjunatha, B. (2023). An MRA Based MLR Model for Forecasting Indian Annual Rainfall Using Large Scale Climate Indices. International Journal of Environment and Climate Change, 13(5), 137-150.
#' }
series_nonlinearity <- function(Y){
sl_no <- 1:length(Y)
df <- data.frame(sl_no = sl_no, X = Y)
colnames(df)[2] <- paste(deparse(substitute(Y)))
nonlinearity_list <- DescribeDF::df_nonlinearity(df)
return(nonlinearity_list)
}
#'@title Stationarity Tests Of A Series
#' @description Provides a list of three data frames: 'ADF', 'PP', 'KPSS'. Also indicates whether the data is stationary or not according to the null hypothesis of the corresponding tests.
#' @param Y Univariate time series
#' @import DescribeDF
#'
#' @return
#' \itemize{
#' \item stationarity_table - List of three data frames: 'ADF', 'PP', 'KPSS'
#' }
#' @export
#'
#' @examples
#' my_series <- rnorm(100, 100, 10)
#' series_stationarity(my_series)
#' @references
#' \itemize{
#'\item Garai, S., & Paul, R. K. (2023). Development of MCS based-ensemble models using CEEMDAN decomposition and machine intelligence. Intelligent Systems with Applications, 18, 200202.
#' \item Garai, S., Paul, R. K., Rakshit, D., Yeasin, M., Paul, A. K., Roy, H. S., ... & Manjunatha, B. (2023). An MRA Based MLR Model for Forecasting Indian Annual Rainfall Using Large Scale Climate Indices. International Journal of Environment and Climate Change, 13(5), 137-150.
#' }
series_stationarity <- function(Y){
sl_no <- 1:length(Y)
df <- data.frame(sl_no = sl_no, X = Y)
colnames(df)[2] <- paste(deparse(substitute(Y)))
stationarity_table <- DescribeDF::df_stationarity(df)
return(stationarity_table)
}
#' @title ARIMA-GARCH Hybrid Modeling
#' @description First fits the time series data by using ARIMA model. If the residuals are having "arch" effect, then GARCH is fitted. Based on the previously mentioned condition final prediction is obtained. More can be found from Paul and Garai (2021) <doi:10.1007/s00500-021-06087-4>.
#' @param Y Univariate time series
#' @param ratio Ratio of number of observations in training and testing sets
#' @param n_lag Lag of the provided time series data
#' @import DescribeDf
#' @return
#' \itemize{
#' \item Output_ariga: List of three data frames: predict_compare, forecast_compare, and metrics
#' }
#' @export
#'
#' @examples
#' Y <- rnorm(100, 100, 10)
#' result <- ariga(Y, ratio = 0.8, n_lag = 4)
#' @references
#' \itemize{
#' \item Paul, R. K., & Garai, S. (2021). Performance comparison of wavelets-based machine learning technique for forecasting agricultural commodity prices. Soft Computing, 25(20), 12857-12873.
#' \item Paul, R. K., & Garai, S. (2022). Wavelets based artificial neural network technique for forecasting agricultural prices. Journal of the Indian Society for Probability and Statistics, 23(1), 47-61.
#' \item Garai, S., Paul, R. K., Rakshit, D., Yeasin, M., Paul, A. K., Roy, H. S., Barman, S. & Manjunatha, B. (2023). An MRA Based MLR Model for Forecasting Indian Annual Rainfall Using Large Scale Climate Indices. International Journal of Environment and Climate Change, 13(5), 137-150.
#' }
ariga <- function(Y, ratio = 0.9, n_lag = 4){
# embedding for finding log return
diff.1 <- embed(Y, 2)
Yt <- diff.1[,1]
Yt_1 <- diff.1[,2]
y <- log(Yt/Yt_1)
# Compute the average of non-zero contents in the data
nonzero_data <- y[y != 0 & !is.na(y)]
average_nonzero <- mean(nonzero_data)
# Replace NaNs with the average of non-zero contents in the data
y[is.nan(y)] <- average_nonzero
# Check the result
y
# embedding for finding lag series of actual series
embed_size_y <- n_lag+1 # same lag (lags_y-1) for every sub series
diff.2 <- embed(Yt,embed_size_y)
dim(diff.2)
Y_actual <- diff.2[,1]
Y_actual_1 <- diff.2[,2]
# train-test split
n <- length(Y_actual) # this is already (original length-embed_y)
Y_train <- Y_actual[1:(n*ratio)]
Y_test <- Y_actual[(n*ratio+1):n]
Y_train_1 <- Y_actual_1[1:(n*ratio)]
Y_test_1 <- Y_actual_1[(n*ratio+1):n]
# embedding for finding lag series of log return series
diff.3 <- embed(y, embed_size_y)
y_actual <- diff.3[,1]
y_train <- y_actual[1:(n*ratio)]
y_test <- y_actual[(n*ratio+1):n]
# ARIMA
arima_ori <- forecast::auto.arima(y_train)
order_ori <- forecast::arimaorder(arima_ori)
model_arima_ori<-arima(y_train,order=c(order_ori[1], order_ori[2], order_ori[3]))
pred_arima_ori <-arima_ori$fitted
forecast_arima_ori <- data.frame(predict(arima_ori,n.ahead=(n-(n*ratio))))
forecast_arima_ori <-forecast_arima_ori$pred
#GARCH Model ####
ARCH_pvalue_ori <- as.numeric(FinTS::ArchTest(model_arima_ori$residuals)$p.value)
#ARCH_pvalue<-1
if(ARCH_pvalue_ori<=0.05){
garch.fit_ori <- fGarch::garchFit(~garch(1, 1), data = y_train, trace = FALSE)
pred_V_ori <- garch.fit_ori@fitted
forecast_V_ori <- predict(garch.fit_ori, n.ahead=(n-(n*ratio)))
forecast_V_ori <- forecast_V_ori$meanForecast
Resid_V_ori <- garch.fit_ori@residuals
for_resid_ori<-as.ts(y_test-forecast_V_ori)
}else {
pred_V_ori <- pred_arima_ori
forecast_V_ori <- forecast_arima_ori
Resid_V_ori <- as.ts(model_arima_ori$residuals)
for_resid_ori<-as.vector(y_test-as.vector(forecast_arima_ori))
}
ARIGA_train <- exp(pred_V_ori)*Y_train_1
ARIGA_test <- exp(forecast_V_ori)*Y_test_1
# validation_ARIGA
metrics_ariga_train <- data.frame(AllMetrics::all_metrics(Y_train, ARIGA_train))
metrics_ariga_test <- data.frame(AllMetrics::all_metrics(Y_test, ARIGA_test))
metrics <- cbind(metrics_ariga_train$Metrics,
as.numeric(metrics_ariga_train$Values),
as.numeric(metrics_ariga_test$Values))
colnames(metrics) <- c('Metrics', 'ARIGA_Train',
'ARIGA_Test')
predict_compare <- data.frame(cbind(train_actual = Y_train,
predicted = ARIGA_train))
colnames(predict_compare) <- c('train_actual', 'train_predicted')
forecast_compare <- data.frame(cbind(test_actual = Y_test,
forecast = ARIGA_test))
colnames(forecast_compare) <- c('test_actual', 'test_predicted')
Output_ariga <- list(predict_compare=predict_compare,
forecast_compare=forecast_compare,
metrics=metrics)
return(Output_ariga)
}
#' @title Specially Designed SVR-Based Modeling
#' @description Fits a ANN model to the uni-variate time series data. The contribution is related to the PhD work of the maintainer. More can be found from Paul and Garai (2021) <doi:10.1007/s00500-021-06087-4>.
#' @param Y Univariate time series
#' @param ratio Ratio of number of observations in training and testing sets
#' @param n_lag Lag of the provided time series data
#' @import forecast, AllMetrics, neuralnet
#' @return
#' \itemize{
#' \item Output_ann: List of three data frames: predict_compare, forecast_compare, and metrics
#' }
#' @export
#'
#' @examples
#' Y <- rnorm(100, 100, 10)
#' result <- my_ann(Y, ratio = 0.8, n_lag = 4)
#' @references
#' \itemize{
#' \item Paul, R. K., & Garai, S. (2021). Performance comparison of wavelets-based machine learning technique for forecasting agricultural commodity prices. Soft Computing, 25(20), 12857-12873.
#' \item Paul, R. K., & Garai, S. (2022). Wavelets based artificial neural network technique for forecasting agricultural prices. Journal of the Indian Society for Probability and Statistics, 23(1), 47-61.
#' \item Garai, S., Paul, R. K., Rakshit, D., Yeasin, M., Paul, A. K., Roy, H. S., Barman, S. & Manjunatha, B. (2023). An MRA Based MLR Model for Forecasting Indian Annual Rainfall Using Large Scale Climate Indices. International Journal of Environment and Climate Change, 13(5), 137-150.
#' }
my_ann <- function(Y, ratio = 0.9, n_lag = 4){
# embedding for finding log return
diff.1 <- embed(Y, 2)
Yt <- diff.1[,1]
Yt_1 <- diff.1[,2]
y <- log(Yt/Yt_1)
# Compute the average of non-zero contents in the data
nonzero_data <- y[y != 0 & !is.na(y)]
average_nonzero <- mean(nonzero_data)
# Replace NaNs with the average of non-zero contents in the data
y[is.nan(y)] <- average_nonzero
# Check the result
y
# embedding for finding lag series of actual series
embed_size_y <- n_lag+1 # same lag (lags_y-1) for every sub series
diff.2 <- embed(Yt,embed_size_y)
dim(diff.2)
Y_actual <- diff.2[,1]
Y_actual_1 <- diff.2[,2]
# train-test split
n <- length(Y_actual) # this is already (original length-embed_y)
Y_train <- Y_actual[1:(n*ratio)]
Y_test <- Y_actual[(n*ratio+1):n]
Y_train_1 <- Y_actual_1[1:(n*ratio)]
Y_test_1 <- Y_actual_1[(n*ratio+1):n]
# embedding for finding lag series of log return series
diff.3 <- embed(y, embed_size_y)
diff.3_train <- diff.3[1:(n*ratio),]
diff.3_test <- diff.3[(n*ratio+1):n,]
# Set the column names
colnames(diff.3_train) <- c("y_train", paste0("x", 1:(embed_size_y-1)))
colnames(diff.3_test) <- c("y_test", paste0("x", 1:(embed_size_y-1)))
# extract the predictors and response from the current matrix
predictors_train <- diff.3_train[, -1]
response_train <- diff.3_train[, 1]
allvars <- colnames(predictors_train)
predictorvars <- paste(allvars, collapse="+")
form <- as.formula(paste("y_train ~", predictorvars))
y_actual <- diff.3[,1]
y_train <- y_actual[1:(n*ratio)]
y_test <- y_actual[(n*ratio+1):n]
# ANN ####
nn <- neuralnet::neuralnet(form, diff.3_train, hidden = c(4))
train_predicted <- predict(nn, predictors_train)
predictors_test <- diff.3_test[, -1]
response_test <- diff.3_test[, 1]
test_predicted <- predict(nn, predictors_test)
ann_train <- exp(train_predicted)*Y_train_1
ann_test <- exp(test_predicted)*Y_test_1
# validation_ann
metrics_ann_train <- data.frame(AllMetrics:: all_metrics(Y_train, ann_train))
metrics_ann_test <- data.frame(AllMetrics:: all_metrics(Y_test, ann_test))
metrics <- cbind(metrics_ann_train$Metrics,
as.numeric(metrics_ann_train$Values),
as.numeric(metrics_ann_test$Values))
colnames(metrics) <- c('Metrics', 'ANN_Train',
'ANN_Test')
predict_compare <- data.frame(cbind(train_actual = Y_train,
predicted = ann_train))
colnames(predict_compare) <- c('train_actual', 'train_predicted')
forecast_compare <- data.frame(cbind(test_actual = Y_test,
forecast = ann_test))
colnames(forecast_compare) <- c('test_actual', 'test_predicted')
Output_ann <- list(predict_compare=predict_compare,
forecast_compare=forecast_compare,
metrics=metrics)
return(Output_ann)
}
#' @title Specially Designed SVR-Based Modeling
#' @description Fits a SVR model to the uni-variate time series data. The contribution is related to the PhD work of the maintainer. More can be found from Paul and Garai (2021) <doi:10.1007/s00500-021-06087-4>.
#' @param Y Univariate time series
#' @param ratio Ratio of number of observations in training and testing sets
#' @param n_lag Lag of the provided time series data
#' @import forecast, AllMetrics, e1071
#' @return
#' \itemize{
#' \item Output_ann: List of three data frames: predict_compare, forecast_compare, and metrics
#' }
#' @export
#'
#' @examples
#' Y <- rnorm(100, 100, 10)
#' result <- my_svr(Y, ratio = 0.8, n_lag = 4)
#' @references
#' \itemize{
#' \item Paul, R. K., & Garai, S. (2021). Performance comparison of wavelets-based machine learning technique for forecasting agricultural commodity prices. Soft Computing, 25(20), 12857-12873.
#' \item Paul, R. K., & Garai, S. (2022). Wavelets based artificial neural network technique for forecasting agricultural prices. Journal of the Indian Society for Probability and Statistics, 23(1), 47-61.
#' \item Garai, S., Paul, R. K., Rakshit, D., Yeasin, M., Paul, A. K., Roy, H. S., Barman, S. & Manjunatha, B. (2023). An MRA Based MLR Model for Forecasting Indian Annual Rainfall Using Large Scale Climate Indices. International Journal of Environment and Climate Change, 13(5), 137-150.
#' }
my_svr <- function(Y, ratio = 0.9, n_lag = 4){
# embedding for finding log return
diff.1 <- embed(Y, 2)
Yt <- diff.1[,1]
Yt_1 <- diff.1[,2]
y <- log(Yt/Yt_1)
# Compute the average of non-zero contents in the data
nonzero_data <- y[y != 0 & !is.na(y)]
average_nonzero <- mean(nonzero_data)
# Replace NaNs with the average of non-zero contents in the data
y[is.nan(y)] <- average_nonzero
# Check the result
y
# embedding for finding lag series of actual series
embed_size_y <- n_lag+1 # same lag (lags_y-1) for every sub series
diff.2 <- embed(Yt,embed_size_y)
dim(diff.2)
Y_actual <- diff.2[,1]
Y_actual_1 <- diff.2[,2]
# train-test split
n <- length(Y_actual) # this is already (original length-embed_y)
Y_train <- Y_actual[1:(n*ratio)]
Y_test <- Y_actual[(n*ratio+1):n]
Y_train_1 <- Y_actual_1[1:(n*ratio)]
Y_test_1 <- Y_actual_1[(n*ratio+1):n]
# embedding for finding lag series of log return series
diff.3 <- embed(y, embed_size_y)
diff.3_train <- diff.3[1:(n*ratio),]
diff.3_test <- diff.3[(n*ratio+1):n,]
# Set the column names
colnames(diff.3_train) <- c("y_train", paste0("x", 1:(embed_size_y-1)))
colnames(diff.3_test) <- c("y_test", paste0("x", 1:(embed_size_y-1)))
# extract the predictors and response from the current matrix
predictors_train <- diff.3_train[, -1]
response_train <- diff.3_train[, 1]
allvars <- colnames(predictors_train)
predictorvars <- paste(allvars, collapse="+")
form <- as.formula(paste("y_train ~", predictorvars))
y_actual <- diff.3[,1]
y_train <- y_actual[1:(n*ratio)]
y_test <- y_actual[(n*ratio+1):n]
# SVR ####
# train a svm model with radial basis function as kernel
svmmodel <- e1071::svm(form, diff.3_train, type="eps-regression", kernel = 'radial')
# predict the response for the current matrix in the training set
train_predicted <- as.numeric(predict(svmmodel, predictors_train))
predictors_test <- diff.3_test[, -1]
response_test <- diff.3_test[, 1]
# predict the response for the current matrix in the testing set
test_predicted <- as.numeric(predict(svmmodel, predictors_test))
svr_train <- exp(train_predicted)*Y_train_1
svr_test <- exp(test_predicted)*Y_test_1
# validation_svr
metrics_svr_train <- data.frame(AllMetrics:: all_metrics(Y_train, svr_train))
metrics_svr_test <- data.frame(AllMetrics:: all_metrics(Y_test, svr_test))
metrics <- cbind(metrics_svr_train$Metrics,
as.numeric(metrics_svr_train$Values),
as.numeric(metrics_svr_test$Values))
colnames(metrics) <- c('Metrics', 'SVR_Train',
'SVR_Test')
predict_compare <- data.frame(cbind(train_actual = Y_train,
predicted = svr_train))
colnames(predict_compare) <- c('train_actual', 'train_predicted')
forecast_compare <- data.frame(cbind(test_actual = Y_test,
forecast = svr_test))
colnames(forecast_compare) <- c('test_actual', 'test_predicted')
Output_svr <- list(predict_compare=predict_compare,
forecast_compare=forecast_compare,
metrics=metrics)
return(Output_svr)
}
| /scratch/gouwar.j/cran-all/cranData/AriGaMyANNSVR/R/arigamyannsvr.R |
#' @title example dataset
#' @description 2D image of the Altamura man fossil
#' @name Altapic
#' @docType data
#' @author Antonio Profico
#' @keywords Arothron
#' @usage data(Altapic)
NULL
| /scratch/gouwar.j/cran-all/cranData/Arothron/R/Altapic.R |
#' @name Arothron-package
#' @docType package
#' @aliases Arothron
#' @title eometric Morphometric Methods and Virtual Anthropology Tools
#' @author Antonio Profico, Costantino Buzi, Silvia Castiglione, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @description Tools for geometric morphometric analysis. The package includes tools of virtual anthropology to align two not articulated parts belonging to the same specimen, to build virtual cavities as endocast (Profico et al, 2021 <doi:10.1002/ajpa.24340>).
#' @import alphashape3d
#' @import doParallel
#' @import foreach
#' @import geometry
#' @import graphics
#' @import grDevices
#' @import methods
#' @import Morpho
#' @import parallel
#' @import rgl
#' @import Rvcg
#' @import stats
#' @import stringr
#' @import utils
#' @importFrom abind abind
#' @importFrom alphashape3d ashape3d
#' @importFrom parallel detectCores
#' @importFrom grDevices dev.new rainbow
#' @importFrom methods is
#' @importFrom rgl as.mesh3d
#' @importFrom stats dist kmeans rnorm
#' @importFrom utils read.table write.table
#' @importFrom vegan procrustes
#' @importFrom compositions plot3D
#' @importFrom Rvcg checkFaceOrientation
#' @importFrom stats4 mle
NULL
| /scratch/gouwar.j/cran-all/cranData/Arothron/R/Arothron.R |
#' CScorreffect
#' Plot showing the correlation in the shape space between original and combined dataset omitting or including the normalization factors calculated with Arothron and MLECScorrection
#' @param array1 array: first set of landmark configuration
#' @param array2 array: second set of landmark configuration
#' @param nPCs numeric vector: specify which PC scores will be selected in the correlation test
#' @param from numeric: the lower interval of the normalization factor distribution
#' @param to numeric: the lower interval of the normalization factor distribution
#' @param length.out numeric: number of values ranged between from and to
#' @return PCscores PCscores matrix of the combined dataset applying the normalization factor calculated by using the maximum likelihood estimation
#' @return PCs PCs matrix of the combined dataset applying the normalization factor calculated by using the maximum likelihood estimation
#' @return corr mean correlation between original and combined dataset
#' @return CSratios normalization factor calculated by using the maximum likelihood estimation
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @examples
#' \dontrun{
#' # Femora case study
#' data(femsets)
#' all_pois<-matrix(1:(200*61),nrow=61,ncol=200,byrow = FALSE)
#' set_ext_100<-femsets[all_pois[,1:100],,]
#'
#' set_int_100<-femsets[all_pois[,101:200],,]
#' set_int_50<-set_int_100[c(matrix(1:6100,ncol=61)[seq(1,100,2),]),,]
#' set_int_20<-set_int_100[c(matrix(1:6100,ncol=61)[seq(1,100,5),]),,]
#' set.seed(123)
#' sel<-sample(1:100,10)
#' set_int_10r<-set_int_100[c(matrix(1:6100,ncol=61)[sel,]),,]
#'
#' CScorreffect(set_ext_100,set_int_50,nPCs=1:3)
#' CScorreffect(set_ext_100,set_int_20,nPCs=1:3)
#' CScorreffect(set_ext_100,set_int_10r,nPCs=1:3)
#' }
#' @export
CScorreffect<-function(array1,array2,nPCs=c(1:3),from=0.02,to=0.90,length.out= 100){
data1<-MLECScorrection(array1,array2)
Array12<-bindArr(array1,array2,along=1)
PCscores_ref<-procSym(Array12,scale=TRUE)$PCscores
seqs<-seq(from=from,to=to,length.out = length.out)
gpa1 <- procSym(array1, scale = TRUE)
gpa2 <- procSym(array2, scale = TRUE)
CSratios<-NULL
corj<-NULL
for(j in 1:length(seqs)){
coo.r1<-gpa1$orpdata*seqs[j]
coo.r2<-gpa2$orpdata*(1-seqs[j])
Rots <- cbind(vecx(coo.r1), vecx(coo.r2))
Rots_pca <- prcomp(Rots, scale. = FALSE)
values <- 0
eigv <- Rots_pca$sdev^2
values <- eigv[which(eigv > 1e-16)]
lv <- length(values)
PCs <- Rots_pca$rotation[, 1:lv]
PCscores <- as.matrix(Rots_pca$x[, 1:lv])
corj[j]<-mean(PCscoresCorr(PCscores_ref,PCscores,nPCs)$corr)
CSratios[j]<-(seqs[j]/(1-seqs[j]))
}
plot(CSratios,corj,type="b",pch=19,main="red=Arothron CS correction, black= MLE CS correction,blue=no CS correction",
xlab="Centroid size correction", ylab="Correlation")
abline(h=data1$corr,lty=2,lwd=2)
abline(v=data1$CScorr,lty=2,lwd=2)
datalist1<-list("ext"=arraytolist(array1),"int"=arraytolist(array2))
aro_meth<-twodviews(datalist1,scale=TRUE,vector = 1:2)
aro_res<-mean(PCscoresCorr(PCscores_ref,aro_meth$PCscores,nPCs = nPCs)$corr)
abline(h=aro_res,lwd=2,lty=3,col="red")
aro_CSratio<- sqrt(dim(array1)[1] * 3)/sqrt(dim(array2)[1] * 3)
abline(v=aro_CSratio,lwd=2,lty=3,col="red")
coo.r1<-gpa1$orpdata
coo.r2<-gpa2$orpdata
Rots <- cbind(vecx(coo.r1), vecx(coo.r2))
Rots_pca <- prcomp(Rots, scale. = FALSE)
values <- 0
eigv <- Rots_pca$sdev^2
values <- eigv[which(eigv > 1e-16)]
lv <- length(values)
PCs <- Rots_pca$rotation[, 1:lv]
PCscores <- as.matrix(Rots_pca$x[, 1:lv])
standcorr<-mean(PCscoresCorr(PCscores_ref,PCscores,nPCs)$corr)
noCSratio<- mean(apply(array1,3,cSize))/mean(apply(array2,3,cSize))
abline(v=1,lwd=2,lty=2,col="blue")
abline(h=standcorr,lwd=2,lty=2,col="blue")
out<-list("MLE-cor"=data1$corr,"MLE-CS"=data1$CScorr,
"Aro-cor"=aro_res,"Aro-CS"=aro_CSratio,
"Sta-cor"=standcorr,"Sta-CS"=1)
return(out)
}
| /scratch/gouwar.j/cran-all/cranData/Arothron/R/CScorreffect.R |
#' @title example dataset
#' @description 3D mesh of the first part of the Homo sapiens disarticulated model
#' @name DM_base_sur
#' @docType data
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @keywords Arothron
#' @usage data(DM_base_sur)
NULL
| /scratch/gouwar.j/cran-all/cranData/Arothron/R/DM_base_sur.R |
#' @title example dataset
#' @description 3D mesh of the second part of the Homo sapiens disarticulated model
#' @name DM_face_sur
#' @docType data
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @keywords Arothron
#' @usage data(DM_face_sur)
NULL
| /scratch/gouwar.j/cran-all/cranData/Arothron/R/DM_face_sur.R |
#' @title example dataset
#' @description Landmark configurations of the two part of the disarticulated model
#' @name DM_set
#' @docType data
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @keywords Arothron
#' @usage data(DM_set)
NULL
| /scratch/gouwar.j/cran-all/cranData/Arothron/R/DM_set.R |
#' @title example dataset
#' @description List containing five 2D-landmark configurations acquired along five different anatomical views
#' @name Lset2D_list
#' @docType data
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @keywords Arothron
#' @usage data(Lset2D_list)
NULL
| /scratch/gouwar.j/cran-all/cranData/Arothron/R/Lset2D_list.R |
#' @title example dataset
#' @description Array containing a cranial 3D-landmark configuration acquired on a Primate sample
#' @name Lset3D_array
#' @docType data
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @keywords Arothron
#' @usage data(Lset3D_array)
NULL
| /scratch/gouwar.j/cran-all/cranData/Arothron/R/Lset3D_array.R |
#' @title example dataset
#' @description Landmark configurations of the manual alignments
#' @name MAs_sets
#' @docType data
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @keywords Arothron
#' @usage data(MAs_sets)
NULL
| /scratch/gouwar.j/cran-all/cranData/Arothron/R/MAs_sets.R |
#' MLECScorrection
#' Maximum Likelihood Estimation of the normalization factor to be applied to optimize the correlation between two landmark configurations to be combined by using twodviews and
#' @param array1 array: first set of landmark configuration
#' @param array2 array: second set of landmark configuration
#' @param scale logical: if FALSE the analysis is performed in the shape space, if TRUE the analysis is performed in the size and shape space (gpa without scaling)
#' @param nPCs numeric vector: specify which PC scores will be selected in the correlation test
#' @return PCscores PCscores matrix of the combined dataset applying the normalization factor calculated by using the maximum likelihood estimation
#' @return PCs PCs matrix of the combined dataset applying the normalization factor calculated by using the maximum likelihood estimation
#' @return corr mean correlation between original and combined dataset
#' @return CSratios normalization factor calculated by using the maximum likelihood estimation
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @export
#'
MLECScorrection<-function(array1,array2,scale=TRUE,nPCs=1:5){
Array12<-bindArr(array1,array2,along=1)
if (scale == TRUE) {
PCscores_ref<-procSym(Array12,scale=TRUE)$PCscores}else{
PCscores_ref<-procSym(Array12,scale=FALSE,CSinit = FALSE)$PCscores
}
if (scale == FALSE) {
gpa1 <- procSym(array1, scale = FALSE, CSinit = FALSE)
gpa2 <- procSym(array2, scale = FALSE, CSinit = FALSE)}else {
gpa1 <- procSym(array1, scale = TRUE)
gpa2 <- procSym(array2, scale = TRUE)
}
foo<-function(ssq){
coo.r1<-gpa1$orpdata* ssq
coo.r2<-gpa2$orpdata*(1-ssq)
Rots <- cbind(vecx(coo.r1), vecx(coo.r2))
Rots_pca <- prcomp(Rots, scale. = FALSE)
values <- 0
eigv <- Rots_pca$sdev^2
values <- eigv[which(eigv > 1e-16)]
lv <- length(values)
PCs <- Rots_pca$rotation[, 1:lv]
PCscores <- as.matrix(Rots_pca$x[, 1:lv])
corj<-mean(PCscoresCorr(PCscores_ref,PCscores,nPCs)$corr)
abs(1-corj)
}
# fit<-mle(foo, start = list(ssq=0.5), lower=.001, upper=0.999, method = "L-BFGS-B" )
fit<-mle(foo, start = list(ssq=0.1), lower=.001, upper=0.999, method = "L-BFGS-B" )
fit@coef->SSQ
coo.r1<-gpa1$orpdata*SSQ
coo.r2<-gpa2$orpdata*(1-SSQ)
Rots <- cbind(vecx(coo.r1), vecx(coo.r2))
Rots_pca <- prcomp(Rots, scale. = FALSE)
values <- 0
eigv <- Rots_pca$sdev^2
values <- eigv[which(eigv > 1e-16)]
lv <- length(values)
PCs <- Rots_pca$rotation[, 1:lv]
PCscores <- as.matrix(Rots_pca$x[, 1:lv])
corj<-mean(PCscoresCorr(PCscores_ref,PCscores,nPCs)$corr)
CSratios<-(SSQ/(1-SSQ))
out<-list("PCscores"=PCscores,"PCs"=PCs,"corr"=corj,"CScorr"=CSratios)
return(out)
}
| /scratch/gouwar.j/cran-all/cranData/Arothron/R/MLECScorrection.R |
#' PCscoresCorr
#' Perform a correlation test between two matrices of PCscores
#' @param matrix1 matrix: first set of PC scores
#' @param matrix2 matrix: second set of PC scores
#' @param nPCs numeric vector: specify which PC scores will be selected in the correlation test
#' @return corr the correlation values associated to each pair of PC scores
#' @return p.values p-values associated to the correlation test
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @export
#'
PCscoresCorr<-function(matrix1,matrix2,nPCs=1:5){
Rcors<-NULL
pvalues<-NULL
for(i in nPCs){
Rcorsi<-cor.test(matrix1[,i],matrix2[,i])$estimate
if(Rcorsi<0){Rcors[i]<-cor.test(matrix1[,i],matrix2[,i]*-1)$estimate}else{
Rcors[i]<-cor.test(matrix1[,i],matrix2[,i])$estimate
}
pvalues[i]<-cor.test(matrix1[,i],matrix2[,i])$p.value
}
out<-list("corr"=Rcors,"p.values"=pvalues)
return(out)
}
| /scratch/gouwar.j/cran-all/cranData/Arothron/R/PCscoresCorr.R |
#' @title example dataset
#' @description Array containing the landmark coordinates of the reference sample for Digital Alignment Tool example
#' @name RMs_sets
#' @docType data
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @keywords Arothron
#' @usage data(RMs_sets)
NULL
| /scratch/gouwar.j/cran-all/cranData/Arothron/R/RMs_sets.R |
#' @title example dataset
#' @description Mesh of the Saccopastore 1 Neanderthal skull
#' @name SCP1.mesh
#' @docType data
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @keywords Arothron
#' @usage data(SCP1.mesh)
NULL
| /scratch/gouwar.j/cran-all/cranData/Arothron/R/SCP1.mesh.R |
#' @title example dataset
#' @description Landmark configuration associated to the starting model
#' @name SM_set
#' @docType data
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @keywords Arothron
#' @usage data(SM_set)
NULL
| /scratch/gouwar.j/cran-all/cranData/Arothron/R/SM_set.R |
#' aro.clo.points
#'
#' Find the closest matches between a reference (2D or 3D matrix) and a target matrix (2D/3D) or mesh returning row indices and distances
#' @param target kxm matrix or object of class "mesh3d"
#' @param reference numeric: a kxm matrix (coordinates)
#' @return position numeric: a vector of the row indices
#' @return distances numeric: a vector of the coordinates distances
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @examples
#' #load an example: mesh, and L set
#' data(yoda_sur)
#' data(yoda_set)
#' sur<-yoda_sur
#' set<-yoda_set
#' ver_pos<-aro.clo.points(target=sur,reference=set)
#' @export
aro.clo.points<-function (target, reference)
{
if (is(target ,"mesh3d")) {
target = t(target$vb)[, -4]
}
if (is(reference,"mesh3d")) {
reference = t(reference$vb)[, -4]
}
if (dim(target)[2] != dim(reference)[2]) {
stop("the number of columns (d) must be the same")
}
position <- NULL
distances <- NULL
for (i in 1:dim(reference)[1]) {
distance <- sqrt((target[, 1] - reference[i, 1])^2 +
(target[, 2] - reference[i, 2])^2 + (target[, 3] -
reference[i, 3])^2)
mindist_selector <- which(distance == min(distance))
position <- c(position, mindist_selector)
distances <- c(distances, min(distance))
}
out = list(position = position, distances = distances)
return(out)
}
| /scratch/gouwar.j/cran-all/cranData/Arothron/R/aro.clo.points.R |
#' arraytolist
#'
#' converts an array in a list storing each element of the third dimension of the array (specimen) as element of the list
#' @param array a kx3xn array with landmark coordinates
#' @return a list containing the landmark configurations stored as separated elements
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @export
arraytolist<-function (array)
{
thelist <- NULL
for (i in 1:dim(array)[3]) {
eli <- array[, , i]
thelist <- c(thelist, list(eli))
}
if (is.null(dimnames(array)[[3]]) == F) {
names(thelist) <- dimnames(array)[[3]]
}
return(thelist)
}
| /scratch/gouwar.j/cran-all/cranData/Arothron/R/arraytolist.R |
#' bary.mesh
#'
#' This function calculates the barycenter of a matrix or a 3D mesh
#' @param mesh matrix mesh vertex
#' @return barycenter numeric: x,y,z coordinates of the barycenter of the mesh
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @examples
#' #load an example: mesh, and L set
#' data(SCP1.mesh)
#' sur<-SCP1.mesh
#' bary<-bary.mesh(mesh=sur)
#' @export
bary.mesh<-function(mesh){
if("mesh3d"%in%class(mesh)){
mesh<-t(mesh$vb)[,-4]
}
barycenter<-apply(mesh,2,mean)
return(barycenter)
}
| /scratch/gouwar.j/cran-all/cranData/Arothron/R/bary.mesh.R |
#' compare_check.set
#'
#' This function applyes the Digital Alignment Tool (DTA) on a disarticulated model using a reference landmark configuration
#' @param RM_set_1 matrix: 3D landmark set of the first module acquired on the reference model
#' @param RM_set_2 matrix: 3D landmark set of the second module acquired on the reference model
#' @param DM_set_1 matrix: 3D landmark set of the first module acquired on the disarticulated model
#' @param DM_set_2 matrix: 3D landmark set of the second module acquired on the disarticulated model
#' @param DM_mesh_1 mesh3d: mesh of the disarticulated model (first module)
#' @param DM_mesh_2 mesh3d: mesh of the disarticulated model (second module)
#' @return SF1 numeric: scale factor used to scale the reference set (first module)
#' @return SF2 numeric: scale factor used to scale the reference set (second module)
#' @return RM_set_1_sc matrix: scaled 3D reference set (first module)
#' @return RM_set_2_sc matrix: scaled 3D reference set (second module)
#' @return AM_model list: output of the Morpho::rotmesh.onto function
#' @return dist_from_mesh numeric: mesh distance between the aligned model and the scaled reference set
#' @return eucl_dist_1 numeric: euclidean distance between the landmark configuration of the disarticulated and reference model (first module)
#' @return eucl_dist_2 numeric: euclidean distance between the landmark configuration of the disarticulated and reference model (second module)
#' @return procr_dist numeric: procrustes distance between the landmark configuration of the aligned and reference model
#' @return procr_dist_1 numeric: procrustes distance between the landmark configuration of the disarticulated and reference model (first module)
#' @return procr_dist_2 numeric: procrustes distance between the landmark configuration of the disarticulated and reference model (second module)
#' @return eucl_dist numeric: euclidean distance between the landmark configuration of the aligned and reference model
#' @return single_l_1 numeric: euclidean distance between the landmark configuration of the disarticulated and reference model (first module)
#' @return single_l_2 numeric: euclidean distance between the landmark configuration of the disarticulated and reference model (second module)
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @export
compare_check.set<-function(RM_set_1,RM_set_2,DM_set_1,DM_set_2,DM_mesh_1,DM_mesh_2){
dim1<-dim(RM_set_1)[1]
dim2<-dim(RM_set_2)[1]
SF1<-cSize(DM_set_1)/cSize(RM_set_1)
SF2<-cSize(DM_set_2)/cSize(RM_set_2)
scale_factor<-(SF1+SF2)/2
RM_set_1_sc<-RM_set_1*scale_factor
RM_set_2_sc<-RM_set_2*scale_factor
AM_mesh_1<-rotmesh.onto(DM_mesh_1, DM_set_1,RM_set_1_sc, adnormals = FALSE, scale = FALSE,
reflection = FALSE)
AM_mesh_2<-rotmesh.onto(DM_mesh_2, DM_set_2,RM_set_2_sc, adnormals = FALSE, scale = FALSE,
reflection = FALSE)
AM_mesh<-mergeMeshes(AM_mesh_1$mesh,AM_mesh_2$mesh)
AM_rot<-rotmesh.onto(AM_mesh,rbind(AM_mesh_1$yrot,AM_mesh_2$yrot),
rbind(RM_set_1_sc,RM_set_2_sc), adnormals = FALSE, scale = FALSE,
reflection = FALSE)
check_dist<-abs(sum(projRead(rbind(RM_set_1_sc,RM_set_2_sc),AM_rot$mesh)$quality))
procr_dist<-vegan::procrustes(AM_rot$yrot,rbind(RM_set_1_sc,RM_set_2_sc))$ss
eucl_dist<-sum(sqrt(rowSums((AM_rot$yrot-rbind(RM_set_1_sc,RM_set_2_sc))^2)))
check_1<-sum(sqrt(rowSums((AM_rot$yrot[1:dim1,]-RM_set_1_sc)^2)))
check_2<-sum(sqrt(rowSums((AM_rot$yrot[(dim1+1):(dim1+dim2),]-RM_set_2_sc)^2)))
procr_dist_1<-vegan::procrustes(AM_rot$yrot[1:dim1,],RM_set_1_sc)$ss
procr_dist_2<-vegan::procrustes(AM_rot$yrot[(dim1+1):(dim1+dim2),],RM_set_2_sc)$ss
single_l_1<-sqrt(rowSums((AM_rot$yrot[1:dim1,]-RM_set_1_sc)^2))
single_l_2<-sqrt(rowSums((AM_rot$yrot[(dim1+1):(dim1+dim2),]-RM_set_2_sc)^2))
out<-list("SF1"=SF1,"SF2"=SF2,"RM_set_1_sc"=RM_set_1_sc,"RM_set_2_sc"=RM_set_2_sc,
"AM_model"=AM_rot,"dist_from_mesh"=check_dist,"eucl_dist_1"=check_1,"eucl_dist_2"=check_2,
"procr_dist"=procr_dist,"procr_dist_1"=procr_dist_1,"procr_dist_2"=procr_dist_2,"eucl_dist"=eucl_dist,"single_l_1"=single_l_1,"single_l_2"=single_l_2)
return(out)
} | /scratch/gouwar.j/cran-all/cranData/Arothron/R/compare_check.set.R |
#' dec.curve
#'
#' This function computes the order of points on a open 3D curve and finds intermediate points
#' @param mat_input numeric: a kx3 matrix
#' @param mag numeric: how many times will be divided by the number of initial points
#' @param plot logical: if TRUE will be plotted the starting and final point matrices
#' @return matt numeric: a kx3 matrix with points coordinates
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @examples
#' \dontrun{
#' ## Create and plot a 3D curve
#' require(compositions)
#' require(rgl)
#' curve_3D<-cbind(1:10,seq(1,5,length=10),rnorm(10,sd = 0.2))
#' plot3D(curve_3D,bbox=FALSE)
#' close3d()
#' ## Create and plot the new 3D curve (with intermediate points)
#' dec_curve_3D<-dec.curve(curve_3D, 2, plot = TRUE)
#' }
#' @export
dec.curve<-function(mat_input,mag,plot=TRUE){
matt<-mat_input
for(j in 1:mag){
magn_j=NULL
for(i in 1:((dim(matt)[1])-1)){
magn_j<-c((as.numeric(matt[i,])+as.numeric(matt[i+1,]))/2,magn_j)
}
matt_1_junk<-matrix(magn_j,ncol=3,byrow=T)
matt_1_mat<-rbind(matt,matt_1_junk)
orig<-1:dim(matt)[1]
deri<-(dim(matt)[1]*2-1):(dim(matt)[1]+1)
reordered<-NULL
for(i in 1:dim(matt)[1]){
reordered<-c(reordered,orig[i],deri[i])
}
reordered<-reordered[-length(reordered)]
matt<-matt_1_mat[reordered,]
}
if(plot=="TRUE"){
compositions::plot3D(mat_input,cex=1,col=2)
compositions::plot3D(matt,cex=0.5,col=3,add=TRUE)}
return(matt)} | /scratch/gouwar.j/cran-all/cranData/Arothron/R/dec.curve.R |
#' dta
#'
#' This function applyes the Digital Alignment Tool (DTA) on a disarticulated model using a reference sample
#' @param RM_sample 3D array: 3D landmark configurations of the reference sample
#' @param mod_1 numeric vector: vector containing the position of which landmarks belong to the first module
#' @param mod_2 numeric vector: vector containing the position of which landmarks belong to the second module
#' @param pairs_1 matrix: a X x 2 matrix containing the indices of right and left landmarks of the first module
#' @param pairs_2 matrix: a X x 2 matrix containing the indices of right and left landmarks of the second module
#' @param DM_mesh_1 mesh3d: mesh of the disarticulated model (first module)
#' @param DM_mesh_2 mesh3d: mesh of the disarticulated model (second module)
#' @param DM_set_1 matrix: 3D landmark set of the first module acquired on the disarticulated model
#' @param DM_set_2 matrix: 3D landmark set of the second module acquired on the disarticulated model
#' @param method character: specify method to be used to individuate the best DTA ("euclidean" or "procrustes")
#' @return AM_mesh mesh3d: mesh of the aligned model
#' @return AM_set matrix: landmark configuration of the aligned model
#' @return AM_id character: name of the item of the reference sample resulted as best DTA
#' @return AM_SF_1 numeric: scale factor used to scale the reference set (first module)
#' @return AM_SF_2 numeric: scale factor used to scale the reference set (second module)
#' @return distance numeric: distance between the landmark configuration of the aligned and the reference model
#' @return tot_proc numeric vector: procrustes distances between aligned and reference models (all DTAs)
#' @return tot_eucl numeric vector: euclidean distances between aligned and reference models (all DTAs)
#' @return setarray 3D array: landmark configurations of the disarticulated model aligned on each item of the reference sample
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @references Profico, A., Buzi, C., Davis, C., Melchionna, M., Veneziano, A., Raia, P., & Manzi, G. (2019).
#' A new tool for digital alignment in Virtual Anthropology. The Anatomical Record, 302(7), 1104-1115.
#' @examples
#' ## Load and plot the disarticulated model of the Homo sapiens case study
#' library(compositions)
#' library(rgl)
#' data(DM_base_sur)
#' data(DM_face_sur)
#' open3d()
#' wire3d(DM_base_sur,col="white")
#' wire3d(DM_face_sur,col="white")
#' ## Load the landmark configurations associated to the DM
#' data(DM_set)
#' ## Load the reference sample
#' data(RMs_sets)
#' ## Define the landmarks belonging to the first and second module
#' mod_1<-c(1:17) #cranial base
#' mod_2<-c(18:32) #facial complex
#' ## Define the paired landmarks for each module (optional symmetrization process)
#' pairs_1<-cbind(c(4,6,8,10,12,14,16),c(5,7,9,11,13,15,17))
#' pairs_2<-cbind(c(23,25,27,29,31),c(24,26,28,30,32))
#' ## Run DTA
#' ex.dta<-dta(RM_sample=RMs_sets, mod_1=mod_1, mod_2=mod_2, pairs_1=pairs_1, pairs_2=pairs_2,
#' DM_mesh_1=DM_base_sur,DM_mesh_2=DM_face_sur, DM_set_1= DM_set[mod_1,], DM_set_2=DM_set[mod_2,])
#' ## Print the name of the best RM
#' ex.dta$AM_id
#' ## Save the mesh and the landmark set of the AM
#' AM_mesh<-ex.dta$AM_mesh
#' AM_set<-ex.dta$AM_set
#' ## Plot the aligned 3D model
#' library(compositions)
#' library(rgl)
#' open3d()
#' wire3d(AM_mesh,col="white")
#' plot3D(AM_set,bbox=FALSE,add=TRUE)
#' @export
dta<-function (RM_sample, mod_1, mod_2, pairs_1, pairs_2, DM_mesh_1,
DM_mesh_2, DM_set_1, DM_set_2, method = c("euclidean"))
{
eu_dists <- NULL
eu_procr <- NULL
setarray <- array(NA, dim = dim(RM_sample))
for (i in 1:dim(RM_sample)[3]) {
RM_set_i <- RM_sample[, , i]
if (is.null(pairs_1) == FALSE & is.null(pairs_2) == FALSE) {
pairedLM <- rbind(pairs_1, pairs_2)
symm.set.i <- symmetrize(RM_set_i, pairedLM = pairedLM)
}
else {
symm.set.i = RM_set_i
}
RM_set_1 <- symm.set.i[mod_1, ]
RM_set_2 <- symm.set.i[mod_2, ]
AM_i <- compare_check.set(RM_set_1 = RM_set_1, RM_set_2 = RM_set_2,
DM_set_1 = DM_set_1, DM_set_2 = DM_set_2, DM_mesh_1 = DM_mesh_1,
DM_mesh_2 = DM_mesh_2)
setarray[, , i] = AM_i$AM_model$yrot
eu_dists[i] <- AM_i$eucl_dist
eu_procr[i] <- AM_i$procr_dist
}
if (method == "euclidean") {
i = which.min(eu_dists)
}
if (method == "procrustes") {
i = which.min(eu_procr)
}
RM_set_i <- RM_sample[, , i]
pairedLM <- rbind(pairs_1, pairs_2)
if (is.null(pairs_1) == FALSE & is.null(pairs_2) == FALSE){
symm.set.i <- symmetrize(RM_set_i, pairedLM = pairedLM)
}else{symm.set.i=RM_set_i}
RM_set_1 <- symm.set.i[mod_1, ]
RM_set_2 <- symm.set.i[mod_2, ]
AM_project <- compare_check.set(RM_set_1 = RM_set_1, RM_set_2 = RM_set_2,
DM_set_1 = DM_set_1, DM_set_2 = DM_set_2, DM_mesh_1 = DM_mesh_1,
DM_mesh_2 = DM_mesh_2)
AM_model <- AM_project$AM_model$mesh
AM_set <- AM_project$AM_model$yrot
if (method == "euclidean") {
distance = eu_dists[i]
}
if (method == "procrustes") {
distance = eu_procr[i]
}
out <- list(AM_mesh = AM_model, AM_set = AM_set, AM_id = dimnames(RM_sample)[[3]][i],
AM_SF_1 = AM_project$SF1, AM_SF_2 = AM_project$SF2, distance = distance,
tot_proc = eu_procr, tot_eucl = eu_dists, setarray = setarray)
} | /scratch/gouwar.j/cran-all/cranData/Arothron/R/dta.R |
#' @title example dataset
#' @description POVs defined inside the endocranial cavity
#' @name endo_set
#' @docType data
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @keywords Arothron
#' @usage data(endo_set)
NULL
| /scratch/gouwar.j/cran-all/cranData/Arothron/R/endo_set.R |
#' endomaker
#'
#' Build endocast from a skull 3D mesh
#' @param mesh mesh3d: 3D model of the skull
#' @param path_in character: path of the skull where is stored
#' @param param1_endo numeric: parameter for spherical flipping
#' @param npovs numeric: number of Points of View used in the endocast construction
#' @param decmesh numeric: decmesh
#' @param alpha_ext numeric: alpha shape for construction external cranial mesh
#' @param alpha_vol numeric: alpha shape for volume calculation
#' @param plot logical: if TRUE the endocast is plotted
#' @param save logical: if TRUE the mesh of the endocast is saved
#' @param outpath character: path where save the endocast
#' @param colmesh character: color of the mesh to be plotted
#' @param ncells numeric: approximative number of cell for 3D grid construction
#' @param npovs_calse numeric: number of Points of View for construction of skull shell
#' @param param1_calse numeric: parameter for calse (construction shell)
#' @param param1_ast numeric: parameter for ast3d (construction row endocast)
#' @param decendo numeric: desired number of triangles (row endocast)
#' @param scalendo numeric: scale factor row endocast (for definition of POVs)
#' @param alpha_end numeric: alpha shape value for concave hull (row endocast)
#' @param mpovdist numeric: mean value between POVs and mesh
#' @param volume logical: if TRUE the calculation of the volume (expressed in cc) through concave is returned
#' @param nVoxels numeric: number of voxels for estimation endocranial volume
#' @param num.cores numeric: numbers of cores to be used in parallel elaboration
#' @return endocast mesh3d: mesh of the endocast
#' @return volume numeric: volume of the endocast expressed in cc
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @references Profico, A., Buzi, C., Melchionna, M., Veneziano, A., & Raia, P. (2020).
#' Endomaker, a new algorithm for fully automatic extraction of cranial endocasts and the calculation of their volumes. American Journal of Physical Anthropology.
#' @examples
#' \dontrun{
#' library(rgl)
#' data(human_skull)
#' sapendo<-endomaker(human_skull,param1_endo = 1.0,decmesh = 20000, num.cores=NULL)
#' open3d()
#' wire3d(sapendo$endocast,col="violet")
#' ecv<-sapendo$volume
#' }
#' @export
endomaker<-function (mesh = NULL, path_in = NULL, param1_endo = 1, npovs = 50,
volume = TRUE, alpha_vol = 100, nVoxels = 1e+05, decmesh = 20000,
alpha_ext = 30, ncells = 50000, npovs_calse = 50, param1_calse = 2,
param1_ast = 1.3, decendo = 20000, scalendo = 0.5, alpha_end = 100,
mpovdist = 10, plot = FALSE, colmesh = "orange", save = FALSE,
outpath = tempdir(), num.cores = NULL)
{
if ((is.null(mesh) & is.null(path_in) == TRUE)) {
stop
cat("please, specify the mesh also input or path set where the mesh is stored")
}
if (is.null(mesh) == TRUE) {
mesh <- vcgIsolated(file2mesh(path_in))
}
if (is.null(path_in) == TRUE) {
mesh <- vcgIsolated(mesh)
}
dec_mesh <- vcgQEdecim(mesh, decmesh)
ver_mesh <- vert2points(dec_mesh)
conv_ver <- ashape3d(ver_mesh, alpha = alpha_ext, pert = TRUE,
eps = 1e-09)
x<-conv_ver
selrows = x$triang[, 8 + 1] %in% 2L
tr <- x$triang[selrows, c("tr1", "tr2", "tr3")]
m=rgl::tmesh3d(
vertices = t(x$x),
indices = t(tr),
homogeneous = FALSE)
sn=alphashape3d::surfaceNormals(x, indexAlpha = 1)
fn=facenormals(m)
dp=dot((fn$normals), t(sn$normals))
m$it[,dp<0]=m$it[c(1,3,2),dp<0]
conv_sur<-m
bbox <- meshcube(mesh)
bbox_w <- sqrt(sum((bbox[1, ] - bbox[3, ])^2))
bbox_h <- sqrt(sum((bbox[1, ] - bbox[2, ])^2))
bbox_l <- sqrt(sum((bbox[1, ] - bbox[5, ])^2))
bbox_c <- prod(bbox_w, bbox_h, bbox_l)
voxelsize <- (bbox_c/ncells)^(1/3)
xbox <- seq(min(bbox[, 1]), max(bbox[, 1]), by = voxelsize)
ybox <- seq(min(bbox[, 2]), max(bbox[, 2]), by = voxelsize)
zbox <- seq(min(bbox[, 3]), max(bbox[, 3]), by = voxelsize)
GRID <- as.matrix(expand.grid(xbox, ybox, zbox))
DISCR <- vcgClostKD(GRID, conv_sur, sign = TRUE)
matrice <- GRID[which(DISCR$quality >= 0), ]
DISCR2 <- vcgClostKD(GRID, mesh, sign = TRUE)
matrice2 <- GRID[which(DISCR2$quality >= 0), ]
field_mat <- vcgKDtree(matrice2, GRID, k = 5)
dist_mat <- rowSums(field_mat$distance)
QUANT <- quantile(dist_mat)
pos_1 <- which(dist_mat < QUANT[2])
pos_2 <- which(dist_mat >= QUANT[2] & dist_mat <= QUANT[3])
pos_3 <- which(dist_mat > QUANT[3])
cols <- NULL
ca_lse <- ext.int.mesh(mesh = mesh, views = npovs_calse,
param1 = param1_calse, default = TRUE, import_pov = NULL,
num.cores = num.cores)
vis <- out.inn.mesh(ca_lse, mesh, plot = FALSE)
vis_mesh <- vis$visible
GRID3 <- GRID[(pos_3), ]
DISCR3 <- vcgClostKD(GRID3, vis_mesh, sign = TRUE)
set_4 <- GRID3[which(DISCR3$quality >= 0), ]
center_bone <- colMeans(GRID[pos_1, ])
mat_center_bone <- repmat(center_bone, dim(set_4)[1], 3)
mat_center_dists <- sqrt(rowSums((set_4 - mat_center_bone)^2))
clusters <- kmeans(mat_center_dists, 2)
a <- set_4[clusters$cluster == 1, ]
b <- set_4[clusters$cluster == 2, ]
ast3d <- ext.int.mesh(mesh = mesh, views = 0, param1 = param1_ast,
default = FALSE, import_pov = TRUE, matrix_pov = t(as.matrix((colMeans(b)))),
num.cores = num.cores)
vis_inv_mesh <- out.inn.mesh(ast3d, mesh, plot = FALSE)
vis_mesh <- (vis_inv_mesh$visible)
raw_endo <- vcgQEdecim(vis_mesh, decendo)
raw_endo_s <- scalemesh(raw_endo, scalendo, center = "m")
raw_endo_v <- vert2points(raw_endo_s)
conv_endo_1 <- ashape3d(raw_endo_v, alpha = alpha_end, pert = TRUE,
eps = 1e-09)
x<-conv_endo_1
selrows = x$triang[, 8 + 1] %in% 2L
tr <- x$triang[selrows, c("tr1", "tr2", "tr3")]
m=rgl::tmesh3d(
vertices = t(x$x),
indices = t(tr),
homogeneous = FALSE)
sn=alphashape3d::surfaceNormals(x, indexAlpha = 1)
fn=facenormals(m)
dp=dot((fn$normals), t(sn$normals))
m$it[,dp<0]=m$it[c(1,3,2),dp<0]
conv_endo_s<-m
rmesh = vcgClostKD(as.matrix(GRID), conv_endo_s, sign = TRUE)
POVs <- as.matrix(kmeans(GRID[rmesh$quality >= 0, ], npovs,
iter.max = 10000)$centers)
size_ast <- mpovdist/mean(closemeshKD(POVs, mesh, k = 2)$quality)
mesh_end_s <- scalemesh(mesh, size_ast, center = "m")
povs_mean <- colMeans(vert2points(mesh))
povs <- translate3d(POVs, -povs_mean[1], -povs_mean[2], -povs_mean[3])
povs <- povs * size_ast
povs <- translate3d(povs, povs_mean[1], povs_mean[2], povs_mean[3])
ast3d2 <- ext.int.mesh(mesh = mesh_end_s, views = 0, param1 = param1_endo,
default = FALSE, import_pov = TRUE, matrix_pov = povs,
num.cores = num.cores)
vis_inv_mesh2 <- out.inn.mesh(ast3d2, mesh_end_s, plot = FALSE)
vis_mesh2 <- (vis_inv_mesh2$visible)
meshmean <- colMeans(vert2points(mesh))
endo_sur <- translate3d(vis_mesh2, -meshmean[1], -meshmean[2],
-meshmean[3])
endo_sur$vb[1:3, ] <- endo_sur$vb[1:3, ] * (1/size_ast)
endo_sur <- translate3d(endo_sur, meshmean[1], meshmean[2],
meshmean[3])
endo_sur <- vcgIsolated(endo_sur)
vol = NULL
if (volume == TRUE) {
vol <- volendo(endo_sur, alpha_vol = alpha_vol, ncells = ncells)
}
if (save == TRUE) {
pathout <- outpath
mesh2ply(endo_sur, "endocast")
}
if (plot == TRUE) {
open3d()
shade3d(endo_sur, col = colmesh)
}
out <- list(endocast = endo_sur, volume = vol)
} | /scratch/gouwar.j/cran-all/cranData/Arothron/R/endomaker.R |
#' endomaker_dir
#'
#' Build library of endocasts from skull 3D meshes
#' @param dir_path character: path of the folder where the skull meshes are stored
#' @param param1_endo numeric vector: parameter for spherical flipping
#' @param npovs numeric: number of Points of View used in the endocast construction
#' @param volume logical: if TRUE the volume of the endocast (ECV) is estimated
#' @param decmesh numeric: decmesh
#' @param alpha_ext numeric: alpha shape for construction external cranial mesh
#' @param alpha_vol numeric: alpha shape for volume calculation
#' @param ncells numeric: approximative number of cell for 3D grid construction
#' @param nVoxels numeric: number of voxels for estimation endocranial volume
#' @param plotall logical: if TRUE the endocasts are plotted
#' @param colmesh character: color of the mesh to be plotted
#' @param npovs_calse numeric: number of Points of View for construction of skull shell
#' @param save logical: if TRUE the mesh of the endocast is saved
#' @param outpath character: path where save the endocast
#' @param param1_calse numeric: parameter for calse (construction shell)
#' @param param1_ast numeric: parameter for ast3d (construction row endocast)
#' @param decendo numeric: desired number of triangles (row endocast)
#' @param scalendo numeric: scale factor row endocast (for definition of POVs)
#' @param alpha_end numeric: alpha shape value for concave hull (row endocast)
#' @param mpovdist numeric vector: mean value between POVs and mesh
#' @param num.cores numeric: number of cores to be used in parallel elaboration
#' @return endocasts mesh3d: list of meshes of the extracted endocasts
#' @return volumes numeric: volumes of the endocasts expressed in cc
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @references Profico, A., Buzi, C., Melchionna, M., Veneziano, A., & Raia, P. (2020).
#' Endomaker, a new algorithm for fully automatic extraction of cranial endocasts and the calculation of their volumes. American Journal of Physical Anthropology.
#' @export
endomaker_dir<-function(dir_path,param1_endo=1.5,npovs=50,
volume=TRUE,alpha_vol=50,nVoxels=100000,
decmesh=20000,alpha_ext=30,ncells=50000,npovs_calse=50,
param1_calse=3,param1_ast=1.3,decendo=20000,
scalendo=0.5,alpha_end=100,mpovdist=10,plotall=FALSE,colmesh="orange",save=FALSE,outpath=tempdir(),num.cores=NULL)
{
volumes=NULL
endos<-list()
crania<-list.files(dir_path)
for(i in 1:length(crania)){
path_in<-paste(dir_path,crania[i],sep="/")
if((length(param1_endo)!=length(crania))==TRUE){
param1_endo<-rep(param1_endo[1],length(crania))
}
if((length(mpovdist)!=length(crania))==TRUE){
mpovdist<-rep(mpovdist[1],length(crania))
}
if((length(param1_calse)!=length(crania))==TRUE){
param1_calse<-rep(param1_calse[1],length(crania))
}
if((length(param1_ast)!=length(crania))==TRUE){
param1_ast<-rep(param1_ast[1],length(crania))
}
endo_i<-endomaker(path_in=path_in,param1_endo=param1_endo[i],mpovdist=mpovdist[i],param1_calse=param1_calse[i],param1_ast=param1_ast[i],
num.cores=num.cores, volume=volume,plot=FALSE,save=FALSE)
endos[[i]]<-endo_i$endocast
volumes[[i]]<-endo_i$volume
}
if(plotall==TRUE){
for(j in 1:length(endos)){
open3d()
shade3d(endos[[j]],col=colmesh)
}}
if(save==TRUE){
dir.create(outpath)
for(j in 1:length(endos)){
pathout<-paste(outpath,"/_endocast_",j,sep="")
mesh2ply(endos[[j]],pathout)
}}
out<-list("endocasts"=endos,"volumes"=volumes)
}
| /scratch/gouwar.j/cran-all/cranData/Arothron/R/endomaker_dir.R |
#' export_amira
#'
#' This function exports a list of 3D landmark set in separate files (format landmarkAscii)
#' @param lista list containing 3D landmark sets
#' @param path character: path of the folder where saving the Amira landmark sets
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @examples
#' x<-c(1:20)
#' y<-seq(1,3,length=20)
#' z<-rnorm(20,0.01)
#' vertices<-cbind(x,y,z)
#' set<-list(vertices)
#' example<-export_amira(set,path=tempdir())
#' @export
export_amira<-function(lista,path){
if (is.null(names(lista))==TRUE) {
nomi<-paste("set",1:length(lista))
}else{NULL}
if (is.null(names(lista))==FALSE){
nomi<-names(lista)
for(i in 1:length(nomi)){
nomi[i]=strsplit(nomi[i],"\\.")[[1]][1]
}
}else{NULL}
for (i in 1:length(lista)){
while(tolower(paste(nomi[i],".txt",sep=""))%in%list.files(path)!=FALSE){
m<-1
nomi[i]<-paste(nomi[i],"(",m,")",sep="")
m<-m+1
}
cat(paste("# AmiraMesh 3D ASCII 2.0", "\r\n", sep = ""), file =paste(path,"/",nomi[i],".txt",sep=""),append = TRUE, sep = "")
cat(paste("define Markers ",dim(lista[[i]])[1] , "\r\n", sep = ""), file = paste(path,"/",nomi[i],".txt",sep=""),
append = TRUE, sep = "")
cat(paste("Parameters {", "\r\n", sep = ""), file= paste(path,"/",nomi[i],".txt",sep=""),
append = TRUE, sep = "")
cat(paste('NumSets 1,', "\r\n", sep = ""), file= paste(path,"/",nomi[i],".txt",sep=""),
append = TRUE, sep = "")
cat(paste('ContentType "LandmarkSet",', "\r\n", sep = ""), file= paste(path,"/",nomi[i],".txt",sep=""),
append = TRUE, sep = "")
cat(paste(" color 0 0 1", "\r\n", sep = ""), file= paste(path,"/",nomi[i],".txt",sep=""),
append = TRUE, sep = "")
cat(paste("}", "\r\n", sep = ""), file= paste(path,"/",nomi[i],".txt",sep=""),
append = TRUE, sep = "")
cat(paste("Markers { float[3] Coordinates } @1", "\r\n", sep = ""), file= paste(path,"/",nomi[i],".txt",sep=""),
append = TRUE, sep = "")
cat(paste("# Data section follows", "\r\n", sep = ""), file= paste(path,"/",nomi[i],".txt",sep=""),
append = TRUE, sep = "")
cat(paste("@1", "\r\n", sep = ""), file= paste(path,"/",nomi[i],".txt",sep=""),
append = TRUE, sep = "")
write.table(format(lista[[i]], scientific = F, trim = T),file= paste(path,"/",nomi[i],".txt",sep=""),
sep = " ", append = TRUE, quote = FALSE,
row.names = FALSE, col.names = FALSE, na = "")
}
}
| /scratch/gouwar.j/cran-all/cranData/Arothron/R/export_amira.R |
#' export_amira.path
#'
#' Convert and save a 3D matrix into a AmiraMesh ASCII Lineset (.am) object
#' @param vertices numeric: a kx3 matrix
#' @param filename character: name of the requested output
#' @param Lines numeric: sequence of the vertices that defines the line
#' @param path character: folder path
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @examples
#' x<-c(1:20)
#' y<-seq(1,3,length=20)
#' z<-rnorm(20,0.01)
#' vertices<-cbind(x,y,z)
#' export_amira.path(vertices=vertices,filename="example_line",path=tempdir())
#' @export
export_amira.path<-function(vertices,filename,Lines=c(1:(dim(vertices)[1]-1)-1,-1),path)
{
while(tolower(paste(filename,".am",sep=""))%in%list.files(path)!=FALSE){
i<-1
filename<-paste(filename,"(",i,")",sep="")
i<-i+1
}
cat(paste("# AmiraMesh 3D ASCII 2.0", "\n\n", sep = ""),
file = paste(path, "/", filename, ".am", sep = ""),
append = TRUE, sep = "",eol="\n")
cat(paste("define Lines ", length(Lines), "\n",
sep = ""), file = paste(path, "/", filename, ".am",
sep = ""), append = TRUE, sep = "")
cat(paste("nVertices ", dim(vertices)[1], "\n\n",
sep = ""), file = paste(path, "/", filename, ".am",
sep = ""), append = TRUE, sep = "")
cat(paste("Parameters {","\n",sep=""), file = paste(path, "/", filename, ".am",
sep = ""), append = TRUE, sep = "")
cat(paste(' ContentType "HxLineSet"',"\n",sep=""), file = paste(path, "/", filename, ".am",
sep = ""), append = TRUE, sep = "")
cat(paste("}", "\n\n", sep = ""), file = paste(path, "/", filename, ".am",
sep = ""), append = TRUE, sep = "")
cat(paste("Lines { int LineIdx } @1","\n",sep=""), file = paste(path, "/", filename, ".am",
sep = ""), append = TRUE, sep = "")
cat(paste("Vertices { float[3] Coordinates } @2", "\n\n", sep = ""), file = paste(path, "/", filename, ".am",
sep = ""), append = TRUE, sep = "")
cat(paste("# Data section follows","\n","@1","\n",sep=""), file = paste(path, "/", filename, ".am",
sep = ""), append = TRUE, sep = "")
cat(paste(Lines,"\n",sep=" "), file = paste(path, "/", filename, ".am",
sep = ""), append = TRUE, sep = "")
cat(paste("\n","@2","\n",sep=""), file = paste(path, "/", filename, ".am",
sep = ""), append = TRUE, sep = "")
write.table(format(vertices, scientific = F, trim = T),
file = paste(path, "/", filename, ".am", sep = ""),
sep = " ", append = TRUE, quote = FALSE, row.names = FALSE,
col.names = FALSE, na = "")
cat(paste("\n",sep=" "), file = paste(path, "/", filename, ".am",
sep = ""), append = TRUE, sep = "")
}
| /scratch/gouwar.j/cran-all/cranData/Arothron/R/export_amira.path.R |
#' ext.int.mesh
#'
#' This function finds the vertices visible from a set of points of view
#' @param mesh object of class mesh3d
#' @param views numeric: number of points of view
#' @param dist.sphere numeric: scale factor. This parameter the distance betweem the barycenter of the mesh and the radius of the sphere used to define set of points of view
#' @param param1 numeric: first parameter for spherical flipping (usually ranged from 0.5 to 5, try!)
#' @param param2 numeric second paramter for spherical flipping (don't change it!)
#' @param default logical: if TRUE the points of views are defined automatically, if FALSE define the matrix_pov
#' @param import_pov logical: if NULL an interactive 3D plot for the definition of the points of view is returned
#' @param matrix_pov matrix: external set of points of view
#' @param expand numeric: scale factor for the grid for the interactive 3D plot
#' @param scale.factor numeric: scale factor for sphere inscribed into the mesh
#' @param method character: select "a" or "c"
#' @param start.points numeric: number of POVs available
#' @param num.cores numeric: number of cores
#' @return position numeric: a vector with vertex number nearest the landmark set
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @references Profico, A., Schlager, S., Valoriani, V., Buzi, C., Melchionna, M., Veneziano, A., ... & Manzi, G. (2018).
#' Reproducing the internal and external anatomy of fossil bones: Two new automatic digital tools. American Journal of Physical Anthropology, 166(4), 979-986.
#' @export
ext.int.mesh<-function(mesh,views=20,dist.sphere=3,param1=2.5,param2=10,default=TRUE,import_pov,matrix_pov,expand=1,scale.factor,
method="ast3d",start.points=250,num.cores=NULL)
{
multiResultClass <- function(result1=NULL,result2=NULL)
{
me <- list(
result1 <- result1,
result2 <- result2
)
class(me) <- append(class(me),"multiResultClass")
return(me)
}
if(default==TRUE & is.null(import_pov)==TRUE){
barycenter<-bary.mesh(mesh)
sphere<-vcgSphere(2)
sphere$vb[1,]=sphere$vb[1,]+(barycenter[1])
sphere$vb[2,]=sphere$vb[2,]+(barycenter[2])
sphere$vb[3,]=sphere$vb[3,]+(barycenter[3])
bbox<-meshcube(mesh)
pos<-aro.clo.points(t(mesh$vb)[,-4],bbox)$position
max_dist<-as.matrix(dist(t(mesh$vb)[pos,-4],method = "euclidean"))
max_dist_pos<-which(max_dist==max(max_dist),arr.ind=TRUE)[1,]
sphere<-scalemesh(sphere,max_dist[max_dist_pos[1],max_dist_pos[2]]*dist.sphere,center = "mean")
bounding<-matrix(kmeans(t(sphere$vb)[,-4],views)$centers,ncol=3,byrow = FALSE)
}
if(default==FALSE & is.null(import_pov)==TRUE ){
grid3D<-grid_pov(mesh=mesh,expand=expand)
selection<-pov_selecter(mesh,grid3D)
bounding<-matrix(NA,ncol=3)
for(i in 1:dim(selection)[1]){
sphere<-vcgSphere(2)
sphere_cen<-trasf.mesh(sphere,selection[i,])
sphere_cen_sca<-scalemesh(sphere_cen,size=scale.factor,center="mean")
bounding_temp<-matrix(kmeans(t(sphere_cen_sca$vb)[,-4],views,iter.max = 1000)$centers,ncol=3,byrow = FALSE)
bounding<-rbind(bounding,bounding_temp)
}
bounding<-bounding[-1,]
}
if(is.null(import_pov)==FALSE){
bounding<-matrix_pov
}
if (is.null(num.cores)==TRUE){
visible_ver<-list()
for(m in 1:dim(bounding)[1]){
flip<-spherical.flipping(C=bounding[m,],mesh,param1=param1,param2=param2)
ver.mesh<-t(mesh$vb)[,-4]
C<-bounding[m,]
cloud<-rbind(C,flip,ver.mesh)
ptm <- proc.time()
tri<-t(convhulln(cloud,options=""))
subset<-unique(as.vector(tri))
subset<-subset[which(subset>1 & subset<=(dim(ver.mesh)[1]+1))]
subset<-subset-1
visible_ver[[m]]<-subset
}}
if (is.null(num.cores)==FALSE){
registerDoParallel(cores = num.cores)
visible_ver<-foreach(m=1:dim(bounding)[1],
.multicombine=TRUE,.packages=c("Arothron","geometry")) %dopar%
{
result <- multiResultClass()
flip<-spherical.flipping(C=bounding[m,],mesh,param1=param1,param2=param2)
ver.mesh<-t(mesh$vb)[,-4]
C<-bounding[m,]
cloud<-rbind(C,flip,ver.mesh)
tri<-t(convhulln(cloud,options=""))
subset<-unique(as.vector(tri))
subset<-subset[which(subset>1 & subset<=(dim(ver.mesh)[1]+1))]
subset<-subset-1
}
}
return(visible_ver)
}
| /scratch/gouwar.j/cran-all/cranData/Arothron/R/ext.int.mesh.R |
#' ext.mesh.rai
#'
#' This function returns a 3D mesh with colours based on the vertices visibile from each point of view
#' @param scans an ext.int.mesh
#' @param mesh matrix mesh vertex (the same of the ext.int.mesh object)
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @export
ext.mesh.rai<-function(scans,mesh){
data<-scans
open3d()
colors<-rainbow(length(data))
list_mesh<-list()
for(j in 1:length(data)){
surface_i<-rmVertex(mesh, data[[j]],keep = TRUE)
list_mesh[[j]]<-surface_i
wire3d(surface_i,col=colors[j],add=TRUE)
}
}
| /scratch/gouwar.j/cran-all/cranData/Arothron/R/ext.mesh.rai.R |
#' @title example dataset
#' @description 3D semilandmark configurations of 21 human femora
#' @name femsets
#' @docType data
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @keywords Arothron
#' @usage data(femsets)
NULL
| /scratch/gouwar.j/cran-all/cranData/Arothron/R/femsets.R |
#' grid_pov
#'
#' This function creates a grid for an interactive way to define the set of the points of view
#' @param mesh object of class mesh3d
#' @param expand numeric: scale factor for the grid for the interactive 3D plot
#' @return matrice matrix: matrix with the x,y,z coordinates of the points of view
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @export
grid_pov<-function (mesh, expand=1){
bounding <- as.matrix(meshcube(scalemesh(mesh,size =expand,center = "mean" )))
matrice <- bounding
for (z in 1:3) {
matrice <- matrice
dimension <- nrow(matrice)
for (i in 1:dimension) {
A <- matrice[i, ]
for (j in 1:dimension) {
B <- matrice[j, ]
C <- (A + B)/2
matrice <- rbind(matrice, C)
}
}
matrice <- unique(matrice)
}
return(matrice)
}
| /scratch/gouwar.j/cran-all/cranData/Arothron/R/grid_pov.R |
#' @title example dataset
#' @description 3D mesh of a human skull
#' @name human_skull
#' @docType data
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @keywords Arothron
#' @usage data(human_skull)
NULL
| /scratch/gouwar.j/cran-all/cranData/Arothron/R/human_skull.R |
#' image2palettes
#'
#' Create palettes from an image
#' @param array array: rgb array
#' @param resize numeric: desidered resize factor
#' @param unique logical: if TRUE each color is counted once
#' @param scale logical: if TRUE (color) variables are scaled
#' @param k numeric: desidered number of clusters (i.e., number of palettes)
#' @param lcols numeric: length of the color vector of each palette
#' @param plsaxis numeric: desidered PLS axis
#' @param cex numeric: size of colored squares
#' @param cext numeric: size of color names
#' @return paletteslist list: color palettes arranged in a list
#' @author Antonio Profico
#' @examples
#' \dontrun{
#' require(jpeg)
#' require(Morpho)
#' data("Altapic")
#' image2palettes(Altapic,resize=1,unique=T,scale=T,k=3,lcols=5,plsaxis=1,cext=0.5)
#' }
#' @export
image2palettes<-function(array,resize=4,unique=FALSE,scale=F,k=3,lcols=7,
plsaxis=1,cex=5,cext=0.5)
{
nrow<-dim(array)[1]
ncol<-dim(array)[2]
imageR<-array[round(seq(1,nrow,length.out=nrow/resize)),
round(seq(1,ncol,length.out=ncol/resize)),]
imageR[,,1]<-imageR[dim(imageR)[1]:1,dim(imageR)[2]:1,1]
imageR[,,2]<-imageR[dim(imageR)[1]:1,dim(imageR)[2]:1,2]
imageR[,,3]<-imageR[dim(imageR)[1]:1,dim(imageR)[2]:1,3]
cols<-(t(vecx(imageR)))
if(isTRUE(unique)) cols<-unique(cols)
rgbtoB<-function(rgbval){
out<-as.numeric(sum(rgbval*c(0.2126,0.7152,0.0722)))
}
RGB2XYZ<-function(mat){
# array<-image
# dim(array)
selr1<-which(mat[,1]>0.04045,arr.ind = T)
selg1<-which(mat[,2]>0.04045,arr.ind = T)
selb1<-which(mat[,3]>0.04045,arr.ind = T)
selr2<-which(mat[,1]<=0.04045,arr.ind = T)
selg2<-which(mat[,2]<=0.04045,arr.ind = T)
selb2<-which(mat[,3]<=0.04045,arr.ind = T)
mat[,1][selr1]<-((mat[,1][selr1] + 0.055 ) / 1.055 ) ^ 2.4
mat[,1][selr2]<-mat[,1][selr2]/ 12.92
mat[,2][selg1]<-((mat[,2][selg1] + 0.055 ) / 1.055 ) ^ 2.4
mat[,2][selg2]<-mat[,2][selg2]/ 12.92
mat[,3][selb1]<-((mat[,3][selb1] + 0.055 ) / 1.055 ) ^ 2.4
mat[,3][selb2]<-mat[,3][selb2]/ 12.92
mat<-mat*100
X = mat[,1] * 0.4124 + mat[,2] * 0.3576 + mat[,3] * 0.1805
Y = mat[,1] * 0.2126 + mat[,2] * 0.7152 + mat[,3] * 0.0722
Z = mat[,1] * 0.0193 + mat[,2] * 0.1192 + mat[,3] * 0.9505
out<-cbind(c(X),c(Y),c(Z))
return(out)
}
XYZ2Lab<-function(mat){
# mat<-RGB2XYZ(image)
# dim(mat)
selr1<-which(mat[,1]>0.008856 ,arr.ind = T)
selg1<-which(mat[,2]>0.008856 ,arr.ind = T)
selb1<-which(mat[,3]>0.008856 ,arr.ind = T)
selr2<-which(mat[,1]<=0.008856 ,arr.ind = T)
selg2<-which(mat[,2]<=0.008856 ,arr.ind = T)
selb2<-which(mat[,3]<=0.008856 ,arr.ind = T)
mat[,1][selr1]<-mat[selr1,1] ^ c(1/3)
mat[,1][selr2]<-(mat[selr2,1]*7.787) + ( 16 / 116 )
mat[,2][selg1]<-mat[selg1,2] ^ c(1/3)
mat[,2][selg2]<-(mat[selg2,2]*7.787) + ( 16 / 116 )
mat[,3][selb1]<-mat[selb1,3] ^ c(1/3)
mat[,3][selb2]<-(mat[selb2,3]*7.787) + ( 16 / 116 )
CIEL<-( 116 * mat[,2] ) - 16
CIEa<-500 * ( mat[,1] - mat[,2] )
CIEb<-200 * ( mat[,2] - mat[,3] )
out<-cbind(c(CIEL),c(CIEa),c(CIEb))
return(out)
}
allcols3<-c(apply(cols,1,function(x) rgb(red=x[1],green=x[2],blue=x[3])))
HSV<-XYZ2Lab(RGB2XYZ(cols))
H<-HSV[,1];S<-HSV[,2];V<-HSV[,3];B<-unlist(apply(cols,1,rgbtoB));G<-rowMeans(cols)
allcols4<-cbind(H,S,V,B,G)
selmat2<-which(apply(as.matrix(allcols4),2,sd)>0)
pcai<-(prcomp(cbind(cols,allcols4[,selmat2]),scale. = scale)$x)
kmpls<-kmeans(pcai,centers = k,iter.max = 1000)
paletteslist<-list()
paletteslistg<-list()
for(i in 1:k){
selmat3<-which(apply(as.matrix(allcols4[which(kmpls$cluster==i),selmat2]),2,sd)>0)
plsii<-pls2B(prcomp(cols[which(kmpls$cluster==i),],scale. = scale)$x,prcomp(allcols4[which(kmpls$cluster==i),selmat2[selmat3]],scale. = scale)$x,rounds = 0)
selk<-which(kmpls$cluster==i)
paletteslist[[i]]<-allcols3[selk[order(plsii$Xscores[,plsaxis])[seq(1,length(plsii$Xscores[,plsaxis]),length.out=lcols)]]]
ciccio<-cbind(rowMeans(t(col2rgb(paletteslist[[i]])/255)),rowMeans(t(col2rgb(paletteslist[[i]])/255)),rowMeans(t(col2rgb(paletteslist[[i]])/255)))
ciccia<-c(apply(ciccio,1,function(x) rgb(red=x[1],green=x[2],blue=x[3])))
paletteslistg[[i]]<-ciccia
}
plot(NA,xlim = c(0, dim(imageR)[2]),
ylim = c(0, dim(imageR)[1]), asp=1,axes = F,xaxt='n',yaxt='n',ann=FALSE)
rasterImage(imageR, dim(imageR)[2], dim(imageR)[1],0, 0)
plot(NA,xlim=c(0,lcols+2),ylim=c(0,k+2),bty="n",xlab="",ylab="",xaxt="n",yaxt="n",main="")
for(i in 1:k){
cols<-rep(1,length(paletteslist[[i]]))
cols[which(colMeans(col2rgb(paletteslist[[i]])/255)<0.5)]<-"white"
points(rep(i,lcols),col=paletteslist[[i]],pch=15,cex=cex)
text(rep(i,lcols),labels=paletteslist[[i]],cex=cext,col=cols)
}
return(paletteslist)
}
| /scratch/gouwar.j/cran-all/cranData/Arothron/R/image2palettes.r |
#' @title example dataset
#' @description 3D mesh of a decidous Neanderthal tooth
#' @name krd1_tooth
#' @docType data
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @keywords Arothron
#' @usage data(krd1_tooth)
NULL
| /scratch/gouwar.j/cran-all/cranData/Arothron/R/krd1_tooth.R |
#' landmark_frm2amira
#'
#' This function converts the .frm files, from Evan Toolbox, stored in a folder into the format landmarkAscii
#' @param path_folder_frm character: path of the folder where the .frm files are stored
#' @param path_amira_folder character: path folder to store the landmarkAscii configurations
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @export
landmark_frm2amira<-function(path_folder_frm,path_amira_folder){
dir.create(path_amira_folder)
for(j in 1:length(list.files(path_folder_frm))){
first<-readLines(paste(path_folder_frm,list.files(path_folder_frm)[j],sep="/"))
first_pos<-which(substr(first,1,9)=="<pointset")+1
first_range<-which(first[(first_pos+1)]=="</pointset>")
out_land<-matrix(NA,ncol=3,nrow=length(first_range))
for(i in 1:length(first_range)){
second<-strsplit(first[first_pos[first_range]][i],' ')
third<-unlist(strsplit(second[[1]],"<locations>"))
fourth<-unlist(strsplit(third,"</locations>"))
landmark<-as.numeric(fourth)
out_land[i,]<-landmark
}
ref_set<-out_land
lista<-list(ref_set)
names(lista)<-list.files(path_folder_frm)[j]
export_amira(lista,path_amira_folder)
}
}
| /scratch/gouwar.j/cran-all/cranData/Arothron/R/landmark_frm2amira.R |
#' listtoarray
#' convert a list into an array
#' @param mylist a list
#' @return a kx3xn array with landmark coordinates
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @export
listtoarray<-function(mylist){
final<-NULL
for(i in 1:length(mylist)){
temp<-array(mylist[[i]],dim=c(nrow(mylist[[i]]),ncol(mylist[[i]]),1))
final<-abind::abind(final,temp)
}
return(final)
} | /scratch/gouwar.j/cran-all/cranData/Arothron/R/listtoarray.R |
#' localmeshdiff
#' Calculate and Visualize local differences between two meshes
#' @param mesh1 reference mesh: object of class "mesh3d"
#' @param mesh2 target mesh: object of class "mesh3d"
#' @param ploton numeric: define which mesh will be used to visualize local differences
#' @param diffarea formula: define how calculating differences in area. area_shape1 refers to mesh1, area_shape2 refers to mesh2
#' @param paltot character vector: specify the colors which are used to create a color palette
#' @param from numeric: minimum distance to be colorised
#' @param to numeric: maximum distance to be colorised
#' @param n.int numeric: determines break points for color palette
#' @param out.rem logical: if TRUE outliers will be removed
#' @param fact numeric: factor k of the interquartile range
#' @param visual numeric: if equals to 1 the mesh is plotted without a wireframe, if set on 2 a wireframe is added
#' @param scale01 logical: if TRUE the vector of distances is scaled from 0 to 1
#' @param colwire character: color of the wireframe
#' @return vect numeric vector containing local differeces in area between the reference and the target mesh
#' @author Antonio Profico, Costantino Buzi, Silvia Castiglione, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @references Melchionna, M., Profico, A., Castiglione, S., Sansalone, G., Serio, C., Mondanaro, A., ... & Manzi, G. (2020).
#' From smart apes to human brain boxes. A uniquely derived brain shape in late hominins clade. Frontiers in Earth Science, 8, 273.
#' @examples
#' \dontrun{
#' library(Arothron)
#' library(rgl)
#' data("primendoR")
#' neaset<-primendoR$sets[,,11]
#' sapset<-primendoR$sets[,,14]
#' #defining a mesh for the neanderthal right hemisphere
#' neasur<-list("vb"=t(cbind(neaset,1)),"it"=primendoR$sur$it)
#' class(neasur)<-"mesh3d"
#' #defining a mesh for the modern human right hemisphere
#' sapsur<-list("vb"=t(cbind(sapset,1)),"it"=primendoR$sur$it)
#' class(neasur)<-"mesh3d"
#' layout3d(t(c(1,2)),sharedMouse = TRUE)
#' localmeshdiff(sapsur,neasur,1,scale01 = TRUE,
#' paltot=c("darkred","red","orange","white","lightblue","blue","darkblue"))
#' next3d()
#' localmeshdiff(neasur,sapsur,1,scale01 = TRUE,
#' paltot=c("darkred","red","orange","white","lightblue","blue","darkblue"))
#' }
#' @export
localmeshdiff<-function (mesh1, mesh2,ploton=1, diffarea=((area_shape1 - area_shape2)/area_shape2)*100, paltot = rainbow(200), from = NULL,
to = NULL, n.int = 200, out.rem = TRUE, fact = 1.5, visual = 1,
scale01 = TRUE, colwire = "pink")
{
range01 <- function(x) {
(x - min(x))/(max(x) - min(x))
}
area_shape1 <- vcgArea(mesh1, perface = T)$pertriangle
area_shape2 <- vcgArea(mesh2, perface = T)$pertriangle
diff_areas <- diffarea
sel <- which(is.na(diff_areas))
if (length(sel) > 0) {
mesh1$it <- mesh1$it[, -sel]
mesh2$it <- mesh2$it[, -sel]
mesh1 <- rmUnrefVertex(mesh1)
mesh2 <- rmUnrefVertex(mesh2)
area_shape1 <- vcgArea(mesh1, perface = T)$pertriangle
area_shape2 <- vcgArea(mesh2, perface = T)$pertriangle
diff_areas <- (area_shape1 - area_shape2)/area_shape1
}
if (out.rem == TRUE) {
x = diff_areas
qq <- quantile(x, c(1, 3)/4, names = FALSE)
r <- diff(qq) * fact
tst <- x < qq[1] - r | x > qq[2] + r
tstp <- qq[2] + r
tstn <- qq[1] - r
diff_areas[x > tstp] <- tstp
diff_areas[x < tstn] <- tstn
}
else {
diff_areas = diff_areas
}
if (scale01 == TRUE) {
diff_areas <- range01(diff_areas)
}
cat("the range of diff_areas is ", range(diff_areas), sep = "\n")
if (is.null(to) == TRUE) {
to <- max(diff_areas) * 1.01
}
if (is.null(from) == TRUE) {
from <- min(diff_areas) * 1.01
}
selfromto <- which(diff_areas < to & diff_areas >= from)
diff_areas_fromto <- diff_areas[selfromto]
if (ploton == 1) {
meshfromto <- mesh1
meshwhite <- mesh1
}
if (ploton == 2) {
meshfromto <- mesh2
meshwhite <- mesh2
}
meshfromto$it <- meshfromto$it[, selfromto]
meshwhite$it <- meshwhite$it[, -selfromto]
colmap_tot <- colorRampPalette(paltot)
breaks_tot <- cut(c(from, diff_areas_fromto, to), n.int)
cols_tot <- colmap_tot(n.int)[breaks_tot]
cols_tot <- cols_tot[-c(1, length(cols_tot))]
plot(density(c(from, diff_areas, to)), main = "", xlab = "",
ylab = "")
abline(v = seq(from, to, length.out = n.int), col = colmap_tot(n.int),
lwd = 5)
points(density(diff_areas), type = "l", lwd = 2)
if (visual == 1) {
triangles3d(t(meshfromto$vb[, meshfromto$it]), col = rep(cols_tot,
each = 3), alpha = 1, lit = T, specular = "black")
triangles3d(t(meshwhite$vb[, meshwhite$it]), col = "grey",
alpha = 1, lit = T, specular = "black")
}
if (visual == 2) {
triangles3d(t(meshfromto$vb[, meshfromto$it]), col = rep(cols_tot,
each = 3), alpha = 1, lit = F, specular = "black")
triangles3d(t(meshwhite$vb[, meshwhite$it]), col = "grey",
alpha = 1, lit = F, specular = "black")
wire3d(meshfromto, col = colwire, lit = F, lwd = 2)
}
out <- list(vect = diff_areas)
return(out)
} | /scratch/gouwar.j/cran-all/cranData/Arothron/R/localmeshdiff.R |
#' @title example dataset
#' @description 3D mesh of a human malleus
#' @name malleus_bone
#' @docType data
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @keywords Arothron
#' @usage data(malleus_bone)
NULL
| /scratch/gouwar.j/cran-all/cranData/Arothron/R/malleus_bone.R |
#' noise.mesh
#'
#' This function adds noise to a mesh
#' @param mesh triangular mesh stored as object of class "mesh3d"
#' @param noise sd deviation to define vertex noise
#' @param seed seed for random number generator
#' @return mesh_n a 3D model of class "mesh3d" with noise
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @examples
#' #load mesh
#' library(compositions)
#' library(rgl)
#' data("SCP1.mesh")
#' mesh<-SCP1.mesh
#' #add noise
#' noised<-noise.mesh(mesh,noise=0.05)
#' #plot original and mesh with noise added
#' open3d()
#' shade3d(mesh,col=3)
#' shade3d(noised,col=2,add=TRUE)
#' @export
noise.mesh<-function (mesh, noise = 0.025, seed = 123)
{
mesh_n <- NULL
set.seed(seed)
noise <- matrix(rnorm(3 * dim(mesh[[1]])[2], 0, sd = noise),
nrow = 3, ncol = dim(mesh[[1]])[2])
mesh_n_vb <- rbind(mesh$vb[1:3, ] + noise, rep(1, dim(mesh[[1]])[2]))
mesh_n <- list(vb = mesh_n_vb, it = mesh$it)
class(mesh_n) <- "mesh3d"
return(mesh_n)
}
| /scratch/gouwar.j/cran-all/cranData/Arothron/R/noise.mesh.R |
#' out.inn.mesh
#'
#' This function separates a 3D mesh subjected to the ext.int.mesh into two 3D models: the visible mesh and the not visible one
#' @param scans an ext.int.mesh
#' @param mesh matrix mesh vertex (the same of the ext.int.mesh object)
#' @param plot logical: if TRUE the wireframe of the mesh with the visible vertices is plotted
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @examples
#' \dontrun{
#' #CA-LSE tool on Neanderthal tooth
#' #load a mesh
#' data(krd1_tooth)
#' library(rgl)
#' library(Rvcg)
#' library(compositions)
#' ca_lse_krd1<-ext.int.mesh(mesh= krd1_tooth, views=50, param1=3, default=TRUE,
#' import_pov = NULL,expand=1, scale.factor=1,num.cores = NULL)
#' vis_inv_krd1<-out.inn.mesh(ca_lse_krd1, krd1_tooth, plot=TRUE)
#' inv_mesh<-vcgIsolated(vis_inv_krd1$invisible)
#' open3d()
#' shade3d(inv_mesh,col=2)
#' open3d()
#' shade3d(vis_inv_krd1$visible, col=3)
#' #CA-LSE tool on human malleus
#' #load a mesh
#' data(malleus_bone)
#' ca_lse_malleus<-ext.int.mesh(mesh= malleus_bone, views=50, param1=3,
#' default=TRUE, import_pov = NULL, expand=1, scale.factor=1)
#' vis_inv_malleus<-out.inn.mesh(ca_lse_malleus, malleus_bone, plot=TRUE)
#' inv_mesh<- vis_inv_malleus$invisible
#' inv_mesh<-ca_lse_malleus$invisible
#'
#' #AST-3D tool
#' #load a mesh
#' data(human_skull)
#' data(endo_set)
#' ast3d_endocast<-ext.int.mesh(mesh=human_skull, views=50, param1=0.6, default=FALSE,
#' import_pov = TRUE,expand=1, matrix_pov =endo_set, scale.factor=1,num.cores = NULL)
#' vis_inv_endo<-out.inn.mesh(ast3d_endocast,human_skull,plot=TRUE)
#' vis_mesh<-vcgIsolated(vis_inv_endo$visible)
#' open3d()
#' shade3d(vis_mesh,col=3)
#' open3d()
#' shade3d(vis_inv_endo$invisible, col=2)
#' }
#' @export
out.inn.mesh<-function(scans,mesh,plot=TRUE){
data<-scans
indices<-c()
for(j in 1:length(data)){
indices<-c(indices,data[[j]])
}
ext.mesh<-rmVertex(mesh, unique(indices),keep = TRUE)
if(plot==TRUE){
open3d()
wire3d(ext.mesh,col="grey")}
inn.mesh<-rmVertex(mesh, unique(indices),keep = FALSE)
if(plot==TRUE){
shade3d(inn.mesh,col="red")
}
meshes<-list("visible"=ext.mesh,"invisible"=inn.mesh)
} | /scratch/gouwar.j/cran-all/cranData/Arothron/R/out.inn.mesh.R |
#' patches_frm2amira
#'
#' This function converts the .frm files, from Evan Toolbox, stored in a folder into the format landmarkAscii (semilandmark patches)
#' @param path_folder_frm character: path of the folder where the .frm files are stored
#' @param path_amira_folder character: path folder to store the landmarkAscii configurations
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @export
patches_frm2amira<-function(path_folder_frm,path_amira_folder){
dir.create(path_amira_folder)
for(m in 1:length(list.files(path_folder_frm))){
first<-readLines(paste(path_folder_frm,list.files(path_folder_frm)[m],sep="/"))
first_pos<-which(substr(first,1,9)=="<pointset")+1
first_range<-which(first[(first_pos+1)]=="</pointset>")
curves_pos<-first_pos[-first_range]
for(j in 1:length(curves_pos)){
temp_num<-strsplit(first[curves_pos[j]-1],"")
temp_num2<-which(is.na(as.numeric(temp_num[[1]]))==FALSE)
if(length(temp_num2)==1){
pos_num<-as.numeric(temp_num[[1]][length(temp_num[[1]])-2])}
if(length(temp_num2)!=1){
pos_num<-as.numeric(paste(temp_num[[1]][temp_num2],sep=""))
pos_num<-pos_num[1]*10+pos_num[2]
}
#
patch_i<-as.matrix(read.table(paste(path_folder_frm,path_amira_folder,sep="/"),
skip=curves_pos[j], nrows=pos_num))
lista<-list(patch_i)
names(lista)<-paste("patch",j,list.files(path_folder_frm)[m])
export_amira(lista,path_amira_folder)
}
}
} | /scratch/gouwar.j/cran-all/cranData/Arothron/R/patches_frm2amira.R |
#' permutangle
#'
#' Create palettes from an image
#' @param mat array: rgb array
#' @param var numeric: desidered resize factor
#' @param group1 logical: if TRUE each color is counted once
#' @param group2 logical: if TRUE (color) variables are scaled
#' @param scale numeric: desidered number of clusters (i.e., number of palettes)
#' @param iter numeric: length of the color vector of each palette
#' @param cex1 numeric: desidered PLS axis
#' @param cex2 numeric: size of colored squares
#' @param cex3 numeric: size of color names
#' @param cex4 numeric: size of color names
#' @param labels numeric: size of color names
#' @param pch1 numeric: size of color names
#' @param pch2 numeric: size of color names
#' @param pch3 numeric: size of color names
#' @param col1 numeric: size of color names
#' @param col2 numeric: size of color names
#' @return angle list: color palettes arranged in a list
#' @return permangles list: color palettes arranged in a list
#' @return angle list: color palettes arranged in a list
#' @return iterangles list: color palettes arranged in a list
#' @return p-value list: color palettes arranged in a list
#' @return PCA_angle list: color palettes arranged in a list
#' @return PCA_interangles list: color palettes arranged in a list
#' @return PCA_p-value list: color palettes arranged in a list
#' @author Antonio Profico
#' @examples
#' \dontrun{
#' require(shapes)
#' require(Morpho)
#' data("gorf.dat")
#' data("gorm.dat")
#' Array<-bindArr(gorf.dat,gorm.dat,along=3)
#' CS<-apply(Array,3,cSize)
#' Sex<-c(rep("F",dim(gorf.dat)[3]),rep("M",dim(gorm.dat)[3]))
#'
#' #Shape and size space
#' AllTrajFB<-permutangle(procSym(Array,scale=FALSE,CSinit = FALSE)$PCscores,
#' var=CS,group1=which(Sex=="F"),group2=which(Sex=="M"),scale=FALSE,iter=50)
#' hist(AllTrajFB$iterangles,breaks = 100,xlim=c(0,90))
#' abline(v=AllTrajFB$angle,lwd=2,col="red")
#' hist(AllTrajFB$PCA_iterangles,breaks = 100,xlim=c(0,90))
#' abline(v=AllTrajFB$PCA_angle,lwd=2,col="red")
#'
#' #Shape space
#' AllTrajFB<-permutangle(procSym(Array)$PCscores,
#' var=CS,group1=which(Sex=="F"),group2=which(Sex=="M"),scale=FALSE,iter=50)
#' hist(AllTrajFB$iterangles,breaks = 100,xlim=c(0,90))
#' abline(v=AllTrajFB$angle,lwd=2,col="red")
#' hist(AllTrajFB$PCA_iterangles,breaks = 100,xlim=c(0,90))
#' abline(v=AllTrajFB$PCA_angle,lwd=2,col="red")
#' }
#' @export
permutangle<-function(mat,var,group1,group2,scale=FALSE,iter=100,cex1=range01(var[group1]+1),
cex2=range01(var[group2]+1),cex3=0.7,cex4=1.2,labels=c("stgr1","stgr2","endgr1","endgr2"),pch1=19, pch2=19,pch3=19,
col1="red",col2="blue"){
range01 <- function(x) {
(x - min(x))/(max(x) - min(x))
}
predict.var<-function(mat,var,value){
mylm<-lm(mat~var)
new <- data.frame(var = value)
pred<-predict(mylm,new)
return(pred)
}
set1<-as.matrix(mat[group1,])
set2<-as.matrix(mat[group2,])
sett<-rbind(set1,set2)
indep<-c(var[group1],var[group2])
pca<-prcomp(sett,scale. = scale,center = TRUE)
values <- 0
eigv <- pca$sdev^2
values <- eigv[which(eigv > 1e-16)]
lv <- length(values)
PCs <- pca$rotation[, 1:lv]
PCscores <- as.matrix(pca$x[, 1:lv])
Variance <- cbind(sqrt(eigv), eigv/sum(eigv), cumsum(eigv)/sum(eigv)) * 100
Variance <- Variance[1:lv, ]
y<-indep[c(1:dim(set1)[1])]
x<-PCscores[c(1:dim(set1)[1]),]
coeff1<-lm(x~y)[[1]][2,]
y<-indep[c((dim(set1)[1]+1):dim(sett)[1])]
x<-PCscores[c((dim(set1)[1]+1):dim(sett)[1]),]
coeff2<-lm(x~y)[[1]][2,]
Radangle<-angleTest(coeff1,coeff2)
Angles<-Radangle$angle*180/pi
tot<-sett
halfspecs<-round(dim(tot)[1]/2)
angles<-NULL
angles2<-NULL
for(i in 1:iter){
group1i<-sample(1:dim(tot)[1],halfspecs)
group2i<-(1:dim(tot)[1])[-group1i]
y<-indep[group1i]
x<-PCscores[group1i,]
coeffg1<-lm(x~y)[[1]][2,]
y<-indep[group2i]
x<-PCscores[group2i,]
coeffg2<-lm(x~y)[[1]][2,]
radangle<-angleTest(coeffg1,coeffg2)
angles[i]<-radangle$angle*180/pi
sFi<-predict.var(as.matrix(PCscores[group1i,]),indep[group1i],min(indep[group1i]))
bFi<-predict.var(as.matrix(PCscores[group1i,]),indep[group1i],max(indep[group1i]))
sMi<-predict.var(as.matrix(PCscores[group2i,]),indep[group2i],min(indep[group2i]))
bMi<-predict.var(as.matrix(PCscores[group2i,]),indep[group2i],max(indep[group2i]))
Rotsi<-rbind(sFi,sMi,bFi,bMi)
Rots_pcai <- prcomp(Rotsi, center = TRUE,scale=scale)
matangle<-Rots_pcai$x[c(1,3),1:2]
matangle[,1]<-matangle[,1]-matangle[1,1]
matangle[,2]<-matangle[,2]-matangle[1,2]
matangle2<-Rots_pcai$x[c(2,4),1:2]
matangle2[,1]<-matangle2[,1]-matangle2[1,1]
matangle2[,2]<-matangle2[,2]-matangle2[1,2]
Radangle<-angleTest(matangle,matangle2)
angles2[i]<-Radangle$angle*180/pi
}
perpvalue<-((length(which(angles>=Angles))+1)/length(angles))
sF<-predict.var(as.matrix(set1),indep[c(1:dim(set1)[1])],min(indep[c(1:dim(set1)[1])]))
bF<-predict.var(as.matrix(set1),indep[c(1:dim(set1)[1])],max(indep[c(1:dim(set1)[1])]))
sM<-predict.var(as.matrix(set2),indep[c((dim(set1)[1]+1):dim(sett)[1])],min(indep[c((dim(set1)[1]+1):dim(sett)[1])]))
bM<-predict.var(as.matrix(set2),indep[c((dim(set1)[1]+1):dim(sett)[1])],max(indep[c((dim(set1)[1]+1):dim(sett)[1])]))
Rots<-rbind(sF,sM,bF,bM)
Rots_pca <- prcomp(Rots, center = TRUE,scale=scale)
eigv <- Rots_pca$sdev^2
Variance <- cbind(sqrt(eigv), eigv/sum(eigv), cumsum(eigv)/sum(eigv)) * 100
matangle<-Rots_pca$x[c(1,3),1:2]
matangle[,1]<-matangle[,1]-matangle[1,1]
matangle[,2]<-matangle[,2]-matangle[1,2]
matangle2<-Rots_pca$x[c(2,4),1:2]
matangle2[,1]<-matangle2[,1]-matangle2[1,1]
matangle2[,2]<-matangle2[,2]-matangle2[1,2]
Radangle<-angleTest(matangle,matangle2)
Angles_plot<-Radangle$angle*180/pi
perpvalue2<-((length(which(angles2>=Angles_plot))+1)/length(angles2))
pred <- predict(Rots_pca, newdata=sett)
regr1<-indep[c(1:dim(set1)[1])]
regr2<-indep[c((dim(set1)[1]+1):dim(sett)[1])]
plot(Rots_pca$x,asp=1,xlim=range(pred[,1]),ylim=range(pred[,2]),pch=pch3,cex=cex3,
xlab=paste("PC1 (",round(Variance[1,2],2),"%)",sep=""),
ylab=paste("PC2 (",round(Variance[2,2],2),"%)",sep=""))
text(Rots_pca$x,labels=labels,pos=1,cex=cex4)
arrows(Rots_pca$x[1,1],Rots_pca$x[1,2],
Rots_pca$x[3,1],Rots_pca$x[3,2],lwd=2)
arrows(Rots_pca$x[2,1],Rots_pca$x[2,2],
Rots_pca$x[4,1],Rots_pca$x[4,2],lwd=2)
abline(v=0,h=0)
points(pred[c(1:dim(set1)[1]),],col=col1,cex=cex1,pch=pch1)
points(pred[c((dim(set1)[1]+1):dim(sett)[1]),],col=col2,pch=pch2,cex=cex2)
return(list("angle"=Angles,"iterangles"=angles,"p-value"=perpvalue,
"PCA_angle"=Angles_plot,"PCA_iterangles"=angles2,"PCA_p-value"=perpvalue2))
}
| /scratch/gouwar.j/cran-all/cranData/Arothron/R/permutangle.r |
#' pov_selecter
#'
#' Internal function to define the points of view
#' @param mesh object of class mesh3d
#' @param grid matrix: a 3D grid
#' @param start.points numeric: number of center to be found
#' @param method character: select "a" or "c" for respectively AST-3D and CA-LSE method
#' @return selection numeric: positioning vector of the selected points of the grid
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @export
pov_selecter<-function (mesh, grid,start.points=250,method="ast3d"){
method<-tolower(substr(method,1,1))
if(method=="c"){
cat("How many point(s) of view do you want to select?", "\n",
"select by using right click")
ans <- readLines(n = 1)
pov <- as.numeric(ans)
keep <- NULL
bounding2 <- as.matrix(meshcube(mesh))
v1 <- t(as.matrix(apply(bounding2, 2, mean)))
v2 <- t(as.matrix(apply(bounding2[c(1, 2, 3, 4), ], 2, mean)))
v3 <- t(as.matrix(apply(bounding2[c(1, 2, 5, 6), ], 2, mean)))
cut_1 <- cutMeshPlane(mesh, v1 = c(v1), v2 = c(v2), v3 = c(v3),
normal = NULL, keep.upper = FALSE)
cut_2 <- cutMeshPlane(mesh, v1 = c(v1), v2 = c(v2), v3 = c(v3),
normal = NULL, keep.upper = TRUE)
decim_mesh <- vcgQEdecim(mesh, percent = 0.8)
radius.s<- max(dist(bounding2,method="euclidean"))/25
open3d()
ids <- plot3d(grid, size = radius.s, col = "red", type = "s",
box = FALSE, axes = FALSE, aspect = FALSE, xaxis = NULL,
xlab = "", ylab = "", zlab = "")
wire3d(decim_mesh, col = "green")
selected<-NULL
keep<-NULL
j <- 1
repeat {
print(j)
if (j == (pov + 1)) {
break
}
selected <- selectpoints3d(ids["data"], value = FALSE,
closest = TRUE, button = "right")
keep <- c(keep, selected[2])
spheres3d(grid[keep, ], col = "green", radius = radius.s*1.01)
confirm <- NULL
cat("Do you confirm this lanmdark?", "\n", "'Y' to confirm, 'N' to discard")
confirm <- tolower(readLines(n = 1))
if (confirm == "n") {
j <- j + 1
keep <- keep[-length(keep)]
j <- j - 1
close3d()
open3d()
ids <- plot3d(grid, size = radius.s, col = "red", type = "s",
box = FALSE, axes = FALSE, aspect = FALSE, xaxis = NULL,
xlab = "", ylab = "", zlab = "")
wire3d(decim_mesh, col = "green")
spheres3d(grid[keep, ], col = "green", radius = radius.s*1.01)
}
if (confirm == "y") {
j <- j + 1
}
}
selection <- grid[keep, ]
close3d()
return(selection)
}
if(method=="a"){
cat("How many point(s) of view do you want to select?", "\n",
"select by using right click")
ans <- readLines(n = 1)
pov <- as.numeric(ans)
keep <- NULL
barycenter<-bary.mesh(mesh)
sphere<-vcgSphere(4)
sphere$vb[1,]=sphere$vb[1,]+(barycenter[1])
sphere$vb[2,]=sphere$vb[2,]+(barycenter[2])
sphere$vb[3,]=sphere$vb[3,]+(barycenter[3])
bbox<-meshcube(mesh)
pos<-aro.clo.points(t(mesh$vb)[,-4],bbox)$position
max_dist<-as.matrix(dist(t(mesh$vb)[pos,-4],method = "euclidean"))
max_dist_pos<-which(max_dist==max(max_dist),arr.ind=TRUE)[1,]
sphere<-scalemesh(sphere,max_dist[max_dist_pos[1],max_dist_pos[2]]*1.5,center = "mean") #dist.sphere = 1.5
bounding<-matrix(kmeans(t(sphere$vb)[,-4],start.points,iter.max = 100000)$centers,ncol=3,byrow = FALSE)
grid<-bounding
decim_mesh <- vcgQEdecim(mesh, percent = 0.8)
radius.s<-max_dist[max_dist_pos[1],max_dist_pos[2]]/25
open3d()
ids <- plot3d(grid, radius = radius.s, col = "red", type = "s",
box = FALSE, axes = FALSE, aspect = FALSE, xaxis = NULL,
xlab = "", ylab = "", zlab = "")
wire3d(decim_mesh, col = "green")
selected<-NULL
keep<-NULL
j <- 1
repeat {
print(j)
if (j == (pov + 1)) {
break
}
selected <- selectpoints3d(ids["data"], value = FALSE,
closest = TRUE, button = "right")
keep <- c(keep, selected[2])
spheres3d(grid[keep, ], col = "green", radius = radius.s*1.01)
confirm <- NULL
cat("Do you confirm this lanmdark?", "\n", "'Y' to confirm, 'N' to discard")
confirm <- tolower(readLines(n = 1))
if (confirm == "n") {
j = j + 1
keep = keep[-length(keep)]
j = j - 1
close3d()
open3d()
ids <- plot3d(grid, size = radius.s, col = "red", type = "s",
box = FALSE, axes = FALSE, aspect = FALSE, xaxis = NULL,
xlab = "", ylab = "", zlab = "")
wire3d(decim_mesh, col = "green")
spheres3d(grid[keep, ], col = "green", radius = radius.s*1.01)
}
if (confirm == "y") {
j = j + 1
}
}
selection <- grid[keep, ]
close3d()
return(selection)
}
}
| /scratch/gouwar.j/cran-all/cranData/Arothron/R/pov_selecter.R |
#' @title example dataset
#' @description right brain hemisphere of 19 primate species
#' @name primendoR
#' @docType data
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @keywords Arothron
#' @usage data(primendoR)
NULL
| /scratch/gouwar.j/cran-all/cranData/Arothron/R/primendoR.R |
#' read.amira.dir
#'
#' This function reads and stores in an array the coordinated allocated in a folder in separate files (format landmarkAscii)
#' @param path.dir character: path of the folder
#' @param nland numeric: number of landmark sampled in Amira
#' @return array.set numeric: a kx3xn array with landmark coordinates
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @export
read.amira.dir<-function(path.dir,nland){
names<-list.files(path.dir)
if(nland=="auto"){
dims<-c()
for(i in 1:length(names)){
dims[i]<-dim(read.amira.set(paste(path.dir,"/",names[i],sep=""),"auto"))[1]}
array.amira=array(NA,dim=c(as.numeric(names(sort(-table(dims)))[1]),3,length(names)))}
else{array.amira=array(NA,dim=c(nland,3,length(names)))}
for(i in 1:length(names)){
array.amira[,,i]=read.amira.set(paste(path.dir,"/",names[i],sep=""),nland)
}
if(length(names)==1){
dimnames(array.amira)[[3]]=list(names)}
if(length(names)!=1){
dimnames(array.amira)[[3]]=names}
return(array.amira)
} | /scratch/gouwar.j/cran-all/cranData/Arothron/R/read.amira.dir.R |
#' read.amira.set
#'
#' This function converts a landmarkAscii file set in a kx3x1 array
#' @param name.file character: path of a landmarkAscii file
#' @param nland numeric: number of landmark sampled in Amira, if is set on "auto" it will be automatically recognized
#' @return array.set numeric: a kx3x1 array with landmark coordinates
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @export
#'
read.amira.set<-function(name.file,nland){
A <- readLines(name.file, n = 100)
end <- which(A == "@1")
end_2 <- which(A == "@2")
if(length(end_2!=0)){
print(paste("file named",name.file, "contains a second matrix of 000"))
B_junk<-read.table(name.file,skip=end,nrows=(end_2-end-2))
if(nland!="auto"){
if (dim(B_junk)[1] != nland){
print(paste("nland is different from dim(matrix)[1]: ",paste("nland=",nland,",",sep=""),
paste("dim(matrix)[1]=", dim(B_junk)[1],sep="")))
B<-matrix(NA,ncol=3,nrow=nland)}
if(dim(B_junk)[1]==nland){
B<-B_junk
}}
if(nland=="auto"){
B<-read.table(name.file,skip=end,nrows=(end_2-end-2))
}}
if(length(end_2)==0){
B_junk<-read.table(name.file,skip=end)
if(nland!="auto"){
if (dim(B_junk)[1] != nland){
print(paste("nland is different from dim(matrix)[1]: ",paste("nland=",nland,",",sep=""),
paste("dim(matrix)[1]=", dim(B_junk)[1],sep="")))
B=matrix(NA,ncol=3,nrow=nland)}
if(dim(B_junk)[1]==nland){
B<-B_junk
}}
if(nland=="auto"){
B<-B_junk}}
array.set<-array(as.matrix(B),dim=c(dim(B)[1],3,1))
dimnames(array.set)[[3]]=list(name.file)
return(array.set)}
| /scratch/gouwar.j/cran-all/cranData/Arothron/R/read.amira.set.R |
#' read.path.amira
#'
#' This function extracts and orders the coordinate matrix from a surface path file from Amira
#' @param path.name character: path of surface path .ascii extension file
#' @return data numeric: a kxd matrix with xyz coordinates
#' @author Antonio Profico, Costantino Buzi, Marina Melchionna, Paolo Piras, Pasquale Raia, Alessio Veneziano
#' @export
read.path.amira<-function(path.name){
skip_1 <- which(readLines(path.name, n = 9999999) == "@1")
skip_2 <- which(readLines((path.name), n = 9999999) == "@2")
vertices <- read.table((path.name), skip = skip_2)
numbering <- read.table((path.name), skip = skip_1, nrows = dim(vertices)[1])
data<-vertices[(numbering[,1]+1),]
rownames(data)<-c(1:dim(data)[1])
return(data)} | /scratch/gouwar.j/cran-all/cranData/Arothron/R/read.path.amira.R |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.