content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
---|---|
#' Compute Capital Stock in Chinese Provinces
#'
#' This function compute capital stock of provinces in China using the method by Zhang (2008) or
#' Chen (2020).
#'
#' @param prv a province name, a scalar character. It's Chinese phonetic alphabets.
#' @param method a string. \code{'ZJ'} by Zhang (2008) or \code{'CP'} by Chen (2020).
#' @param startyr a numeric scalar. When use the method by Chen (2020), \code{delta} is
#' used before \code{startyr}, and after \code{startyr} depreciation in data \code{asset} is used.
#' When use the method by Zhang (2008), the parameters is not useful.
#' @param yr a numeric vector about years. If you only need capital stock before 2022,
#' you can use its default \code{NULL}. If you need to compute capital stocks after 2022,
#' you can set, for example, \code{yr = c(2023,2024)}.
#' @param invest a numeric vector about investment, its length equal the length of
#' \code{yr}, and its units is 100 million in current price.
#' @param InvestPrice a numeric vector about price indices of investment,
#' its length equal the length of \code{yr}, and it is a fixed base index
#' with equaling 1 in \code{bt}.
#' @param depr a numeric vector about depreciation,its length equal the length of \code{yr},
#' and its units is 100 million in current price. If use the method \code{'ZJ'}, the parameter
#' is not useful.
#' @param delta a rate of depreciation, a scalar number.
#' @param bt a scalar number, such as 2000. It means computing capital stock with its price equal
#' 1 in \code{bt}
#' @note The parameter \code{InvestPrice} is a fixed base index with equaling 1 in 1952 by default.
#' However, we often only get a price indices of investment with equaling 1
#' in last year. You can use \code{data(asset)} to get \code{InvestPrice}
#' in any year (before 2017) with equaling 1 in 1952. So, it is easy then.
#'
#' @return The function return a data.frame, and its 1st column is province, 2nd column
#' is year, 3rd column is capital stock, 4th column is the price index of investment.
#' @references Zhang, J., Estimation of China's provincial capital stock (1952-2004) with
#' applications. \emph{Journal of Chinese Economic and Business Studies}, 2008. 6(2): p. 177-196.
#' @examples
#' # Compute capital stock in Xinjiang province in 1952-2017
#' CompK(prv = 'xinjiang')
#' # Compute capital stock in Xinjiang province in 1952-2017 with its price equaling 1 in 2000
#' CompK(prv = 'xinjiang', bt = 2000)
#' # compute capital stock in Beijing in 2023 and 2024
#' CompK(yr = 2023:2024, invest = c(10801.2,11100),
#' InvestPrice = c(1.86*1.03,1.86*1.03*1.021),
#' prv = 'beijing',delta = 0.096)
#' # ...
#' # beijing 2023 42043.06533 1.9158000
#' # beijing 2024 43681.68543 1.9560318
#' # Compute capital stock in chongqing with its price equaling 1 in 1992 based on
#' # Chen and Wan (2020)
#' CompK(prv = 'chongqing', method = 'CP', startyr = 1996, bt = 1992)
#'
#' @export
CompK <- function(prv, method = 'ZJ', startyr = 1996, yr = NULL, invest = NULL, InvestPrice = NULL,
depr = NULL, delta = 0.096, bt = 1952){
if (method == 'ZJ'){
ans <- CompK_ZJ(prv = prv, yr = yr, invest = invest, InvestPrice = InvestPrice,
delta = delta, bt = bt)
}else if (method == 'CP'){
ans <- CompK_CP(prv = prv, startyr = startyr, yr = yr, invest = invest, InvestPrice = InvestPrice,
depr = depr, delta = delta, bt = bt)
}
return(ans)
}
|
/scratch/gouwar.j/cran-all/cranData/CHNCapitalStock/R/CompK.R
|
#' Compute Capital Stock in Chinese Provinces
#'
#' This function compute capital stock of provinces in China using the method by Chen (2020).
#'
#' @param prv a province name, a scalar character. It's Chinese phonetic alphabets.
#' @param startyr a numeric scalar. When use the method by Chen (2020), \code{delta} is
#' used before \code{startyr}, and after \code{startyr} depreciation in data \code{asset} is used.
#' @param yr a numeric vector about years. If you only need capital stock before 2017,
#' you can use its default \code{NULL}. If you need to compute capital stocks in other
#' years (for example 2018,2019), you can set, for example, \code{yr = c(2018,2019)}.
#' @param invest a numeric vector about investment, its length equal the length of
#' \code{yr}, and its units is 100 million in current price.
#' @param InvestPrice a numeric vector about price indices of investment,
#' its length equal the length of \code{yr}, and it is a fixed base index
#' with equaling 1 in \code{bt}.
#' @param depr a numeric vector about depreciation,its length equal the length of \code{yr},
#' and its units is 100 million in current price.
#' @param delta a rate of depreciation, a scalar number.
#' @param bt a scalar number, such as 2000. It means computing capital stock with its price equal
#' 1 in \code{bt}
#' @note The parameter \code{InvestPrice} is a fixed base index with equaling 1 in 1952 by default.
#' However, we often only get a price indices of investment with equaling 1
#' in last year. You can use \code{data(asset)} to get \code{InvestPrice}
#' in any year (before 2017) with equaling 1 in 1952. So, it is easy then.
#'
#' @return The function return a data.frame, and its 1st column is province, 2nd column
#' is year, 3rd column is capital stock, 4th column is the price index of investment.
#' @references Chen, Pu, 2020, Compute capital stocks of provinces in China (In Chinese).
#' @export
CompK_CP <- function(prv,startyr = 1993, yr = NULL, invest = NULL, InvestPrice = NULL,
depr = NULL, delta = 0.096, bt = 1992){
# Whether add data after 2017
if (!is.null(yr)){
asset <- rbind(asset[asset$yr < min(yr),],
data.frame(prv = prv, yr = yr, invest = invest,
InvestIndex = NA, InvestPrice = InvestPrice,
depr = depr))
asset <- dplyr::arrange(asset, prv, yr)
}
ans <- CompK_ZJ(prv = prv, yr = yr, invest = invest, InvestPrice = InvestPrice,
delta = delta, bt = bt)
# depreciation of price deflator
rawdata <- asset[asset$prv %in% prv,]
rawdata$InvestPrice <- ans$InvestPrice # invest price deflated
rawdata$depr <- rawdata$depr/rawdata$InvestPrice
rawdata$invest <- rawdata$invest/rawdata$InvestPrice
ans <- merge(ans, rawdata[,c('prv','yr','depr','invest')],all.x = T, by = c('prv','yr'))
ans$Kcp <- NA
# chongqing
if (prv %in% 'chongqing' & startyr < 1996)
stop('startyr in chongqing must larger than or equal 1996')
ans$Kcp[ans$yr == startyr] <- ans$K[ans$yr == startyr]
for (i in which(ans$yr == (startyr + 1)):nrow(ans)) {
ans$Kcp[i] <- ans$Kcp[i - 1] - ans$depr[i] + ans$invest[i]
}
# fixed format
ans <- ans[,c('prv','yr','Kcp','InvestPrice')]
ans <- dplyr::rename(ans, 'K' = 'Kcp')
return(ans)
}
|
/scratch/gouwar.j/cran-all/cranData/CHNCapitalStock/R/CompK_CP.R
|
#' Compute Capital Stock in Chinese Provinces
#'
#' This function compute capital stock of provinces in China using the method by Zhang (2008).
#'
#' @param yr a numeric vector about years. If you only need capital stock before 2017,
#' you can use its default \code{NULL}. If you need to compute capital stocks in other
#' years (for example 2018,2019), you can set, for example, \code{yr = c(2018,2019)}.
#' @param invest a numeric vector about investment, its length equal the length of
#' \code{yr}, and its units is 100 million in current price.
#' @param InvestPrice a numeric vector about price indices of investment,
#' its length equal the length of \code{yr}, and it is a fixed base index
#' with equaling 1 in \code{bt}.
#' @param delta a rate of depreciation, a scalar number.
#' @param prv a province name, a scalar character. It's Chinese phonetic alphabets.
#' @param bt a scalar number, such as 2000. It means computing capital stock with its price equal
#' 1 in \code{bt}
#' @note The parameter \code{InvestPrice} is a fixed base index with equaling 1 in 1952 by default.
#' However, we often only get a price indices of investment with equaling 1
#' in last year. You can use \code{data(asset)} to get \code{InvestPrice}
#' in any year (before 2017) with equaling 1 in 1952. So, it is easy then.
#'
#' @return The function return a data.frame, and its 1st column is province, 2nd column
#' is year, 3rd column is capital stock, 4th column is the price index of investment.
#' @references Zhang, J., Estimation of China's provincial capital stock (1952-2004) with
#' applications. \emph{Journal of Chinese Economic and Business Studies}, 2008. 6(2): p. 177-196.
#' @export
CompK_ZJ <- function(yr = NULL, invest = NULL, InvestPrice = NULL,
delta = 0.096, prv, bt = 1952){
# Whether add data after 2017
if (!is.null(yr)){
asset <- rbind(dplyr::select(asset[asset$yr < min(yr),],-'depr'),
data.frame(prv = prv, yr = yr, invest = invest,
InvestIndex = NA, InvestPrice = InvestPrice))
asset <- dplyr::arrange(asset, prv, yr)
}
K <- asset[asset$yr == 1952,c('prv','yr','invest')]
K$K <- K$invest/0.1
asset <- merge(asset, K[,c('prv','yr','K')], by = c('prv','yr'), all.x = T)
ans <- asset[asset$prv %in% prv,]
if (prv %in% 'chongqing') {
# modify base time
ifelse (bt < 1996,
ans$InvestPrice <- ans$InvestPrice/asset$InvestPrice[asset$yr == bt & asset$prv %in% 'sichuan'],
ans$InvestPrice <- ans$InvestPrice/ans$InvestPrice[ans$yr == bt])
ans$RealInvest <- ans$invest/ans$InvestPrice
ans$K[1] <- 1090*313/850
}else {
ans$InvestPrice <- ans$InvestPrice/ans$InvestPrice[ans$yr == bt]
ans$RealInvest <- ans$invest/ans$InvestPrice
}
for (i in 2:nrow(ans)) {
ans$K[i] <- ans$K[i-1] * (1-delta) + ans$RealInvest[i]
}
ans <- ans[,c('prv','yr','K','InvestPrice')]
class(ans) <- c('data.frame','CapStk')
return(ans)
}
|
/scratch/gouwar.j/cran-all/cranData/CHNCapitalStock/R/CompK_ZJ.R
|
#' Assets
#'
#' A dataset containing investment, the indices of investment and
#' the price indices of investment
#'
#' @format A data frame:
#' \describe{
#' \item{prv}{provinces}
#' \item{yr}{year}
#' \item{invest}{total fixed capital formation}
#' \item{InvestIndex}{index of fixed capital formation}
#' \item{InvestPrice}{price index of investment in fixed assets}
#' \item{depr}{depreciation}
#' }
'asset'
|
/scratch/gouwar.j/cran-all/cranData/CHNCapitalStock/R/asset.R
|
# CHNOSZ/AD.R
# Akinfiev-Diamond model for aqueous species
# 20190219 First version
# 20220206 Calculate S, Cp, and V
AD <- function(property = NULL, parameters = NULL, T = 298.15, P = 1, isPsat = TRUE) {
# Some constants (from Akinfiev and Diamond, 2004 doi:10.1016/j.fluid.2004.06.010)
MW <- 18.0153 # g mol-1
NW <- 1000 / MW # mol kg-1
#R <- 8.31441 # J K-1 mol-1 20190219
R <- 8.314463 # https://physics.nist.gov/cgi-bin/cuu/Value?r 20230630
# R expressed in volume units
RV <- 10 * R # cm3 bar K-1 mol-1
# Calculate H2O fugacity and derivatives of density
# These calculations are done through (unexported) functions
# to be able to test their output in test-AD.R 20220206
f1 <- .f1(T, P, isPsat)
drho1_dT <- mapply(.drho1_dT, T, P, MoreArgs = list(isPsat = isPsat))
drho1_dP <- mapply(.drho1_dP, T, P, MoreArgs = list(isPsat = isPsat))
d2rho1_dT2 <- mapply(.d2rho1_dT2, T, P, MoreArgs = list(isPsat = isPsat))
# Calculate other properties of H2O solvent
waterTP <- water(c("rho", "S", "Cp", "V"), T = T, P = P)
# Density (g cm-3)
rho1 <- waterTP$rho / 1000
# Entropy (dimensionless)
S1 <- waterTP$S / R
# Heat capacity (dimensionless)
Cp1 <- waterTP$Cp / R
# Volume (cm3 mol-1)
V1 <- waterTP$V
# Calculate properties of ideal H2O gas
S1_g <- sapply(T, .S1_g)
Cp1_g <- sapply(T, .Cp1_g)
# Initialize a list for the output
out <- list()
# Loop over species
nspecies <- nrow(parameters)
for(i in seq_len(nspecies)) {
# Get thermodynamic parameters for the gas and calculate properties at T, P
PAR <- parameters[i, ]
gasprops <- subcrt(PAR$name, "gas", T = T, P = P, convert = FALSE)$out[[1]]
# Send a message
message("AD: Akinfiev-Diamond model for ", PAR$name, " gas to aq")
# Start with an NA-filled data frame
myprops <- as.data.frame(matrix(NA, ncol = length(property), nrow = length(T)))
colnames(myprops) <- property
# Loop over properties
for(j in seq_along(property)) {
if(property[[j]] == "G") {
# Get gas properties (J mol-1)
G_gas <- gasprops$G
# Calculate G_hyd (J mol-1)
G_hyd <- R*T * ( -log(NW) + (1 - PAR$xi) * log(f1) + PAR$xi * log(RV * T * rho1 / MW) + rho1 * (PAR$a + PAR$b * (1000/T)^0.5) )
# Calculate the chemical potential (J mol-1)
G <- G_gas + G_hyd
# Insert into data frame of properties
myprops$G <- G
}
if(property[[j]] == "S") {
# Get S_gas
S_gas <- gasprops$S
# Calculate S_hyd
S_hyd <- R * (
(1 - PAR$xi) * (S1 - S1_g)
+ log(NW)
- (PAR$xi + PAR$xi * log(RV * T / MW) + PAR$xi * log(rho1) + PAR$xi * T / rho1 * drho1_dT)
- (
PAR$a * (rho1 + T * drho1_dT)
+ PAR$b * (0.5 * 10^1.5 * T^-0.5 * rho1 + 10^1.5 * T^0.5 * drho1_dT)
)
)
S <- S_gas + S_hyd
myprops$S <- S
}
if(property[[j]] == "Cp") {
# Get Cp_gas
Cp_gas <- gasprops$Cp
# Calculate Cp_hyd
Cp_hyd <- R * (
(1 - PAR$xi) * (Cp1 - Cp1_g)
- (PAR$xi + 2 * PAR$xi * T / rho1 * drho1_dT - PAR$xi * T^2 / rho1^2 * drho1_dT^2 + PAR$xi * T^2 / rho1 * d2rho1_dT2)
) - R*T * (
PAR$a * (2 * drho1_dT + T * d2rho1_dT2)
+ PAR$b * (-0.25 * 10^1.5 * T^-1.5 * rho1 + 10^1.5 * T^-0.5 * drho1_dT + 10^1.5 * T^0.5 * d2rho1_dT2)
)
Cp <- Cp_gas + Cp_hyd
myprops$Cp <- Cp
}
if(property[[j]] == "V") {
# Get V_gas
V_gas <- 0
# Calculate V_hyd
V_hyd <- V1 * (1 - PAR$xi) + PAR$xi * RV * T / rho1 * drho1_dP + RV * T * drho1_dP * (PAR$a + PAR$b * (1000/T)^0.5)
V <- V_gas + V_hyd
myprops$V <- V
}
}
# Calculate enthalpy 20220206
myprops$H <- myprops$G - 298.15 * entropy(PAR$formula) + T * myprops$S
out[[i]] <- myprops
}
out
}
### UNEXPORTED FUNCTIONS ###
.f1 <- function(T, P, isPsat) {
# Get H2O fugacity (bar)
GH2O_P <- water("G", T = T, P = P)$G
GH2O_1 <- water("G", T = T, P = 1)$G
f1 <- exp ( (GH2O_P - GH2O_1) / (8.31441 * T) )
# For Psat, calculate the real liquid-vapor curve (not 1 bar below 100 degC)
if(isPsat) {
P <- water("Psat", T = T, P = "Psat", P1 = FALSE)$Psat
f1[P < 1] <- P[P < 1]
}
f1
}
.rho1 <- function(T, P) {
# Density of H2O (g cm-3)
water("rho", T = T, P = P)$rho / 1000
}
.drho1_dT <- function(T, P, isPsat) {
# Partial derivative of density with respect to temperature at constant pressure 20220206
dT <- 0.1
T1 <- T - dT
T2 <- T + dT
# Add 1 bar to P so the derivative doesn't blow up when P = Psat at T > 100 degC
# TODO: Is there a better way?
if(isPsat) P <- P +1
rho1 <- .rho1(c(T1, T2), P)
diff(rho1) / (T2 - T1)
}
.drho1_dP <- function(T, P, isPsat) {
# Partial derivative of density with respect to pressure at constant temperature 20220206
dP <- 0.1
P1 <- P - dP
P2 <- P + dP
# Subtract 1 degC from T so the derivative doesn't blow up when P = Psat at T > 100 degC
# TODO: Is there a better way?
if(isPsat) T <- T - 1
rho1 <- .rho1(T, c(P1, P2))
diff(rho1) / (P2 - P1)
}
.d2rho1_dT2 <- function(T, P, isPsat) {
# Second partial derivative of density with respect to temperature at constant pressure 20220206
# NOTE: dT, Tval, and P <- P + 1 are chosen to produce demo/AD.R;
# these may not be the best settings for other T-P ranges 20220207
dT <- 0.2
# Calculate density at seven temperature values
Tval <- seq(T - 3 * dT, T + 3 * dT, dT)
# TODO: Is there a better way to calculate the partial derivative for P = Psat?
if(isPsat) P <- P + 2 else P <- P + 1
rho1 <- .rho1(Tval, P)
# At P = 281 bar there are identical values of rho1 between T = 683.15 and 683.35 K
# Don't allow duplicates because they produce artifacts in the second derivative 20220207
if(any(duplicated(rho1))) {
message(paste("AD: detected identical values of rho1 in second derivative calculation; returning NA at", T, "K and", P, "bar"))
return(NA)
}
# https://stackoverflow.com/questions/11081069/calculate-the-derivative-of-a-data-function-in-r
spl <- smooth.spline(Tval, rho1)
# The second derivative of the fitted spline function at the fourth point (i.e., T)
predict(spl, deriv = 2)$y[4]
}
.S1_g <- function(T) {
# Entropy of the ideal gas (dimensionless)
.Fortran(C_ideal2, T, 0, 0, 0, 0, 0, 0, 0)[[4]]
}
.Cp1_g <- function(T) {
# Heat capacity of the ideal gas (dimensionless)
.Fortran(C_ideal2, T, 0, 0, 0, 0, 0, 0, 0)[[8]]
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/AD.R
|
# CHNOSZ/Berman.R 20170930
# Calculate thermodynamic properties of minerals using equations from:
# Berman, R. G. (1988) Internally-consistent thermodynamic data for minerals
# in the system Na2O-K2O-CaO-MgO-FeO-Fe2O3-Al2O3-SiO2-TiO2-H2O-CO2.
# J. Petrol. 29, 445-522. https://doi.org/10.1093/petrology/29.2.445
Berman <- function(name, T = 298.15, P = 1, check.G = FALSE, calc.transition = TRUE, calc.disorder = TRUE) {
# Reference temperature and pressure
Pr <- 1
Tr <- 298.15
# Make T and P the same length
ncond <- max(length(T), length(P))
T <- rep(T, length.out = ncond)
P <- rep(P, length.out = ncond)
# Get parameters in the Berman equations
# Start with thermodynamic parameters provided with CHNOSZ
dat <- thermo()$Berman
# Is there a user-supplied data file?
userfile <- get("thermo", CHNOSZ)$opt$Berman
userfileexists <- FALSE
if(!is.na(userfile)) {
if(userfile != "") {
if(file.exists(userfile)) {
userfileexists <- TRUE
BDat_user <- read.csv(userfile, as.is = TRUE)
dat <- rbind(BDat_user, dat)
} else stop("the file named in thermo()$opt$Berman (", userfile, ") does not exist")
}
}
# Remove duplicates (only the first, i.e. most recent entry is kept)
dat <- dat[!duplicated(dat$name), ]
# Remove the multipliers on volume parameters
vcols <- 13:16 # columns with v1, v2, v3, v4
multexp <- c(5, 5, 5, 8)
dat[, vcols] <- t(t(dat[, vcols]) / 10^multexp)
# If name is missing, return the entire data frame (used in test-Berman.R)
if(missing(name)) return(dat) else {
# Which row has data for this mineral?
irow <- which(dat$name == name)
if(length(irow) == 0) {
if(userfileexists) stop("Data for ", name, " not available. Please add it to ", userfile)
if(!userfileexists) stop("Data for ", name, " not available. Please add it to your_data_file.csv and run thermo('opt$Berman' = 'path/to/your_data_file.csv')")
}
dat <- dat[irow, ]
}
# The function works fine with just the following assign() call,
# but an explicit dummy assignment here is used to avoid "Undefined global functions or variables" in R CMD check
GfPrTr <- HfPrTr <- SPrTr <- Tlambda <- Tmax <- Tmin <- Tref <- VPrTr <-
d0 <- d1 <- d2 <- d3 <- d4 <- Vad <- dTdP <- k0 <- k1 <- k2 <- k3 <-
k4 <- k5 <- k6 <- l1 <- l2 <- v1 <- v2 <- v3 <- v4 <- NA
# Assign values to the variables used below
for(i in 1:ncol(dat)) assign(colnames(dat)[i], dat[, i])
# Get the entropy of the elements using the chemical formula in thermo()$OBIGT
OBIGT <- thermo()$OBIGT
formula <- OBIGT$formula[match(name, OBIGT$name)]
SPrTr_elements <- entropy(formula)
# Check that G in data file is the G of formation from the elements --> Benson-Helgeson convention (DG = DH - T*DS)
if(check.G) {
GfPrTr_calc <- HfPrTr - Tr * (SPrTr - SPrTr_elements)
Gdiff <- GfPrTr_calc - GfPrTr
#if(is.na(GfPrTr)) warning(paste0(name, ": GfPrTr(table) is NA"), call.=FALSE)
if(!is.na(GfPrTr)) if(abs(Gdiff) >= 1000) warning(paste0(name, ": GfPrTr(calc) - GfPrTr(table) is too big! == ",
round(GfPrTr_calc - GfPrTr), " J/mol"), call. = FALSE)
# (the tabulated GfPrTr is unused below)
}
### Thermodynamic properties ###
# Calculate Cp and V (Berman, 1988 Eqs. 4 and 5)
# k4, k5, k6 terms from winTWQ documentation (doi:10.4095/223425)
Cp <- k0 + k1 * T^-0.5 + k2 * T^-2 + k3 * T^-3 + k4 * T^-1 + k5 * T + k6 * T^2
P_Pr <- P - Pr
T_Tr <- T - Tr
V <- VPrTr * (1 + v1 * T_Tr + v2 * T_Tr^2 + v3 * P_Pr + v4 * P_Pr^2)
## Calculate Ga (Ber88 Eq. 6) (superseded 20180328 as it does not include k4, k5, k6)
#Ga <- HfPrTr - T * SPrTr + k0 * ( (T - Tr) - T * (log(T) - log(Tr)) ) +
# 2 * k1 * ( (T^0.5 - Tr^0.5) + T*(T^-0.5 - Tr^-0.5) ) -
# k2 * ( (T^-1 - Tr^-1) - T / 2 * (T^-2 - Tr^-2) ) -
# k3 * ( (T^-2 - Tr^-2) / 2 - T / 3 * (T^-3 - Tr^-3) ) +
# VPrTr * ( (v3 / 2 - v4) * (P^2 - Pr^2) + v4 / 3 * (P^3 - Pr^3) +
# (1 - v3 + v4 + v1 * (T - Tr) + v2 * (T - Tr)^2) * (P - Pr) )
# Calculate Ha (symbolically integrated using sympy - expressions not simplified)
intCp <- T*k0 - Tr*k0 + k2/Tr - k2/T + k3/(2*Tr^2) - k3/(2*T^2) + 2.0*k1*T^0.5 - 2.0*k1*Tr^0.5 +
k4*log(T) - k4*log(Tr) + k5*T^2/2 - k5*Tr^2/2 - k6*Tr^3/3 + k6*T^3/3
intVminusTdVdT <- -VPrTr + P*(VPrTr + VPrTr*v4 - VPrTr*v3 - Tr*VPrTr*v1 + VPrTr*v2*Tr^2 - VPrTr*v2*T^2) +
P^2*(VPrTr*v3/2 - VPrTr*v4) + VPrTr*v3/2 - VPrTr*v4/3 + Tr*VPrTr*v1 + VPrTr*v2*T^2 - VPrTr*v2*Tr^2 + VPrTr*v4*P^3/3
Ha <- HfPrTr + intCp + intVminusTdVdT
# Calculate S (also symbolically integrated)
intCpoverT <- k0*log(T) - k0*log(Tr) - k3/(3*T^3) + k3/(3*Tr^3) + k2/(2*Tr^2) - k2/(2*T^2) + 2.0*k1*Tr^-0.5 - 2.0*k1*T^-0.5 +
k4/Tr - k4/T + T*k5 - Tr*k5 + k6*T**2/2 - k6*Tr**2/2
intdVdT <- -VPrTr*(v1 + v2*(-2*Tr + 2*T)) + P*VPrTr*(v1 + v2*(-2*Tr + 2*T))
S <- SPrTr + intCpoverT - intdVdT
# Calculate Ga --> Berman-Brown convention (DG = DH - T*S, no S(element))
Ga <- Ha - T * S
### Polymorphic transition properties ***
if(!is.na(Tlambda) & !is.na(Tref) & any(T > Tref) & calc.transition) {
# Starting transition contributions are 0
Cptr <- Htr <- Str <- Gtr <- numeric(ncond)
## Ber88 Eq. 8: Cp at 1 bar
#Cplambda_1bar <- T * (l1 + l2 * T)^2
# Eq. 9: Tlambda at P
Tlambda_P <- Tlambda + dTdP * (P - 1)
# Eq. 8a: Cp at P
Td <- Tlambda - Tlambda_P
Tprime <- T + Td
# With the condition that Tref < Tprime < Tlambda(1bar)
iTprime <- Tref < Tprime & Tprime < Tlambda
# Handle NA values (arising from NA in input P values e.g. Psat above Tcritical) 20180925
iTprime[is.na(iTprime)] <- FALSE
Tprime <- Tprime[iTprime]
Cptr[iTprime] <- Tprime * (l1 + l2 * Tprime)^2
# We got Cp, now calculate the integrations for H and S
# The lower integration limit is Tref
iTtr <- T > Tref
Ttr <- T[iTtr]
Tlambda_P <- Tlambda_P[iTtr]
Td <- Td[iTtr]
# Handle NA values 20180925
Tlambda_P[is.na(Tlambda_P)] <- Inf
# The upper integration limit is Tlambda_P
Ttr[Ttr >= Tlambda_P] <- Tlambda_P[Ttr >= Tlambda_P]
# Derived variables
tref <- Tref - Td
x1 <- l1^2 * Td + 2 * l1 * l2 * Td^2 + l2^2 * Td^3
x2 <- l1^2 + 4 * l1 * l2 * Td + 3 * l2^2 * Td^2
x3 <- 2 * l1 * l2 + 3 * l2^2 * Td
x4 <- l2 ^ 2
# Eqs. 10, 11, 12
Htr[iTtr] <- x1 * (Ttr - tref) + x2 / 2 * (Ttr^2 - tref^2) + x3 / 3 * (Ttr^3 - tref^3) + x4 / 4 * (Ttr^4 - tref^4)
Str[iTtr] <- x1 * (log(Ttr) - log(tref)) + x2 * (Ttr - tref) + x3 / 2 * (Ttr^2 - tref^2) + x4 / 3 * (Ttr^3 - tref^3)
Gtr <- Htr - T * Str
# Apply the transition contributions
Ga <- Ga + Gtr
Ha <- Ha + Htr
S <- S + Str
Cp <- Cp + Cptr
}
### Disorder thermodynamic properties ###
if(!is.na(Tmin) & !is.na(Tmax) & any(T > Tmin) & calc.disorder) {
# Starting disorder contributions are 0
Cpds <- Hds <- Sds <- Vds <- Gds <- numeric(ncond)
# The lower integration limit is Tmin
iTds <- T > Tmin
Tds <- T[iTds]
# The upper integration limit is Tmax
Tds[Tds > Tmax] <- Tmax
# Ber88 Eqs. 15, 16, 17
Cpds[iTds] <- d0 + d1*Tds^-0.5 + d2*Tds^-2 + d3*Tds + d4*Tds^2
Hds[iTds] <- d0*(Tds - Tmin) + d1*(Tds^0.5 - Tmin^0.5)/0.5 +
d2*(Tds^-1 - Tmin^-1)/-1 + d3*(Tds^2 - Tmin^2)/2 + d4*(Tds^3 - Tmin^3)/3
Sds[iTds] <- d0*(log(Tds) - log(Tmin)) + d1*(Tds^-0.5 - Tmin^-0.5)/-0.5 +
d2*(Tds^-2 - Tmin^-2)/-2 + d3*(Tds - Tmin) + d4*(Tds^2 - Tmin^2)/2
# "d5 is a constant computed in such as way as to scale the disordring enthalpy to the volume of disorder" (Berman, 1988)
# 20180331: however, having a "d5" that isn't a coefficient in the same equation as d0, d1, d2, d3, d4 is confusing notation
# therefore, CHNOSZ now uses "Vad" for this variable, following the notation in the Theriak-Domino manual
# Eq. 18; we can't do this if Vad == 0 (dolomite and gehlenite)
if(Vad != 0) Vds <- Hds / Vad
# Berman puts the Vds term directly into Eq. 19 (commented below), but that necessarily makes Gds != Hds - T * Sds
#Gds <- Hds - T * Sds + Vds * (P - Pr)
# Instead, we include the Vds term with Hds
Hds <- Hds + Vds * (P - Pr)
# Disordering properties above Tmax (Eq. 20)
ihigh <- T > Tmax
# Again, Berman put the Sds term (for T > Tmax) into Eq. 20 for Gds (commented below), which would also make Gds != Hds - T * Sds
#Gds[ihigh] <- Gds[ihigh] - (T[ihigh] - Tmax) * Sds[ihigh]
# Instead, we add the Sds[ihigh] term to Hds
Hds[ihigh] <- Hds[ihigh] - (T[ihigh] - Tmax) * Sds[ihigh]
# By writing Gds = Hds - T * Sds, the above two changes w.r.t. Berman's
# equations affect the computed values only for Hds, not Gds
Gds <- Hds - T * Sds
# Apply the disorder contributions
Ga <- Ga + Gds
Ha <- Ha + Hds
S <- S + Sds
V <- V + Vds
Cp <- Cp + Cpds
}
### (for testing) Use G = H - TS to check that integrals for H and S are written correctly
Ga_fromHminusTS <- Ha - T * S
if(!isTRUE(all.equal(Ga_fromHminusTS, Ga))) stop(paste0(name, ": incorrect integrals detected using DG = DH - T*S"))
### Thermodynamic and unit conventions used in SUPCRT ###
# Use entropy of the elements in calculation of G --> Benson-Helgeson convention (DG = DH - T*DS)
Gf <- Ga + Tr * SPrTr_elements
# The output will just have "G" and "H"
G <- Gf
H <- Ha
# Convert J/bar to cm^3/mol
V <- V * 10
data.frame(T = T, P = P, G = G, H = H, S = S, Cp = Cp, V = V)
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/Berman.R
|
# CHNOSZ/DEW.R
# R functions for the Deep Earth Water model
# 20170924 jmd
# Most code here was translated from VBA macros in the DEW spreadsheet (DEW_May19_2017_11.0.2 .xlsm)
# Comments starting with ' were transferred from the DEW spreadsheet
# In the original, functions return zero for invalid input; here, NA is used instead
# Equations were selected using default options in the DEW spreadsheet:
# Density of water equation (1) - Zhang & Duan (2005)
# Dielectric Constant Equation (4) - Sverjensky et al. (2014)
# Water Free Energy Equation (2) - Integral of Volume
# 'Returns the density of water at the input pressure and temperature, in units of g/cm^3.
# 'pressure - The pressure to calculate the density of water at, in bars
# 'temperature - The temperature to calculate the density of water at, in Celsius
# 'error - The density returned will calculate a pressure which differs from the input pressure by the value of "error" or less.
# The default value of error is taken from equations in DEW spreadsheet (table "Calculations")
calculateDensity <- function(pressure, temperature, error = 0.01) {
myfunction <- function(pressure, temperature) {
minGuess <- 1E-05
guess <- 1E-05
equation <- 1 # 'The maxGuess is dependent on the value of "equation"
maxGuess <- 7.5 * equation - 5
calcP <- 0
# 'Loop through and find the density
calculateDensity <- NA
for(i in 1:50) {
# 'Calculates the pressure using the specified equation
calcP <- calculatePressure(guess, temperature)
# 'If the calculated pressure is not equal to input pressure, this determines a new
# 'guess for the density based on current guess and how the calculated pressure
# 'relates to the input pressure. In effect, this a form of a bisection method.
if(abs(calcP - pressure) > error) {
if(calcP > pressure) {
maxGuess <- guess
guess <- (guess + minGuess) / 2
} else if(calcP < pressure) {
minGuess <- guess
guess <- (guess + maxGuess) / 2
}
} else {
calculateDensity <- guess
break
}
}
calculateDensity
}
# Make input pressure and temperature the same length
if(length(pressure) < length(temperature)) pressure <- rep(pressure, length.out = length(temperature))
if(length(temperature) < length(pressure)) temperature <- rep(temperature, length.out = length(pressure))
# Use a loop to process vectorized input
sapply(1:length(pressure), function(i) myfunction(pressure[i], temperature[i]))
}
# 'Returns the Gibbs Free Energy of water in units of cal/mol.
# 'pressure - The pressure to calculate the Gibbs Free Energy at, in bars
# 'temperature - The temperature to calculate the Gibbs Free Energy at, in Celsius
calculateGibbsOfWater <- function(pressure, temperature) {
# 'Equation created by Brandon Harrison. This models data for the Gibbs energy at 1 kb as a function of temperature,
# 'then defines the gibbs free energy as the integral over the volume as a function of temperature.
myfunction <- function(pressure, temperature) {
# 'Gibbs Free Energy of water at 1 kb. This equation is a polynomial fit to data as a function of temperature.
# 'It is valid in the range of 100 to 1000 C.
GAtOneKb <- 2.6880734E-09 * temperature^4 + 6.3163061E-07 * temperature^3 -
0.019372355 * temperature^2 - 16.945093 * temperature - 55769.287
if(pressure < 1000) { # 'Simply return zero, this method only works at P >= 1000 bars
integral <- NA
} else if(pressure == 1000) { # 'Return the value calculated above from the polynomial fit
integral <- 0
} else if(pressure > 1000) { # 'Integrate from 1 kb to P over the volume
integral <- 0
# 'Integral is sum of rectangles with this width. This function in effect limits the spacing
# 'to 20 bars so that very small pressures do not have unreasonably small widths. Otherwise the width
# 'is chosen such that there are always 500 steps in the numerical integration. This ensures that for very
# 'high pressures, there are not a huge number of steps calculated which is very computationally taxing.
spacing <- ifelse((pressure - 1000) / 500 < 20, 20, (pressure - 1000) / 500)
for(i in seq(1000, pressure, by = spacing)) {
# 'This integral determines the density only down to an error of 100 bars
# 'rather than the standard of 0.01. This is done to save computational
# 'time. Tests indicate this reduces the computation by about a half while
# 'introducing little error from the standard of 0.01.
integral <- integral + (18.01528 / calculateDensity(i, temperature, 100) / 41.84) * spacing
}
}
GAtOneKb + integral
}
# Make input pressure and temperature the same length
if(length(pressure) < length(temperature)) pressure <- rep(pressure, length.out = length(temperature))
if(length(temperature) < length(pressure)) temperature <- rep(temperature, length.out = length(pressure))
# Use a loop to process vectorized input
sapply(1:length(pressure), function(i) myfunction(pressure[i], temperature[i]))
}
# 'Returns the Dielectric constant of water at the given density and temperature.
# 'density - The density of water to use in calculating epsilon, in g/cm^3
# 'temperature - The temperature to calculate epsilon with, in Celsius
calculateEpsilon <- function(density, temperature) {
# 'Power Function - Created by Dimitri Sverjensky and Brandon Harrison
# 'Relevant parameters
a1 <- -0.00157637700752506
a2 <- 0.0681028783422197
a3 <- 0.754875480393944
b1 <- -8.01665106535394E-05
b2 <- -0.0687161761831994
b3 <- 4.74797272182151
A <- a1 * temperature + a2 * sqrt(temperature) + a3
B <- b1 * temperature + b2 * sqrt(temperature) + b3
exp(B) * density ^ A
}
# 'Outputs the value of Q in units of bar^-1
# 'pressure - The pressure to calculate Q at, in bars
# 'temperature - The temperature to calculate Q at, in Celsius
# 'density - The density at the input pressure and temperature, input simply to save time, in g/cm^3
calculateQ <- function(density, temperature) {
eps <- calculateEpsilon(density, temperature)
depsdrho <- calculate_depsdrho(density, temperature)
drhodP <- calculate_drhodP(density, temperature)
depsdrho * drhodP / eps ^2
}
### Unexported functions ###
# 'Returns the pressure of water corresponding to the input density and temperature, in units of bars.
# 'density - The density to use in finding a pressure, in g/cm^3
# 'temperature - The temperature to use in finding a pressure, in Celsius
calculatePressure <- function(density, temperature) {
m <- 18.01528 # 'Molar mass of water molecule in units of g/mol
ZD05_R <- 83.144 # 'Gas Constant in units of cm^3 bar/mol/K
ZD05_Vc <- 55.9480373 # 'Critical volume in units of cm^3/mol
ZD05_Tc <- 647.25 # 'Critical temperature in units of Kelvin
TK <- temperature + 273.15 # 'Temperature must be converted to Kelvin
Vr <- m / density / ZD05_Vc
Tr <- TK / ZD05_Tc
B <- 0.349824207 - 2.91046273 / (Tr * Tr) + 2.00914688 / (Tr * Tr * Tr)
C <- 0.112819964 + 0.748997714 / (Tr * Tr) - 0.87320704 / (Tr * Tr * Tr)
D <- 0.0170609505 - 0.0146355822 / (Tr * Tr) + 0.0579768283 / (Tr * Tr * Tr)
E <- -0.000841246372 + 0.00495186474 / (Tr * Tr) - 0.00916248538 / (Tr * Tr * Tr)
f <- -0.100358152 / Tr
g <- -0.00182674744 * Tr
delta <- 1 + B / Vr + C / (Vr * Vr) + D / Vr^4 + E / Vr^5 + (f / (Vr * Vr) + g / Vr^4) * exp(-0.0105999998 / (Vr * Vr))
ZD05_R * TK * density * delta / m
}
# 'Calculates the partial derivative of density with respect to pressure, i.e. (d(rho)/dP)_T, in units of g^3/cm^3/bar
# 'density - The density of water, in g/cm^3
# 'temperature - The temperature of water, in Celsius
calculate_drhodP <- function(density, temperature) {
m <- 18.01528 # 'Molar mass of water molecule in units of g/mol
ZD05_R <- 83.144 # 'Gas Constant in units of cm^3 bar/mol/K
ZD05_Vc <- 55.9480373 # 'Critical volume in units of cm^3/mol
ZD05_Tc <- 647.25 # 'Critical temperature in units of Kelvin
TK <- temperature + 273.15 # 'temperature must be converted to Kelvin
Tr <- TK / ZD05_Tc
cc <- ZD05_Vc / m # 'This term appears frequently in the equation and is defined here for convenience
Vr <- m / (density * ZD05_Vc)
B <- 0.349824207 - 2.91046273 / (Tr * Tr) + 2.00914688 / (Tr * Tr * Tr)
C <- 0.112819964 + 0.748997714 / (Tr * Tr) - 0.87320704 / (Tr * Tr * Tr)
D <- 0.0170609505 - 0.0146355822 / (Tr * Tr) + 0.0579768283 / (Tr * Tr * Tr)
E <- -0.000841246372 + 0.00495186474 / (Tr * Tr) - 0.00916248538 / (Tr * Tr * Tr)
f <- -0.100358152 / Tr
g <- 0.0105999998 * Tr
delta <- 1 + B / Vr + C / (Vr^2) + D / Vr^4 + E / Vr^5 + (f / (Vr^2) + g / Vr^4) * exp(-0.0105999998 / Vr^2)
kappa <- B * cc + 2 * C * (cc^2) * density + 4 * D * cc^4 * density^3 + 5 * E * cc^5 * density^4 +
(2 * f * (cc^2) * density + 4 * g * cc^4 * density^3 - (f / (Vr^2) + g / Vr^4) * (2 * 0.0105999998 * (cc^2) * density)) * exp(-0.0105999998 / (Vr^2))
m / (ZD05_R * TK * (delta + density * kappa))
}
# 'Returns the partial derivative of the dielectric constant with respect to density in units of cm^3/g.
# 'density - The density of water to calculate with, in g/cm^3
# 'temperature - The temperature to calculate with, in Celsius
calculate_depsdrho <- function(density, temperature) {
# 'Power Function - Created by Dimitri Sverjensky and Brandon Harrison
# 'Relevant parameters
a1 <- -0.00157637700752506
a2 <- 0.0681028783422197
a3 <- 0.754875480393944
b1 <- -8.01665106535394E-05
b2 <- -0.0687161761831994
b3 <- 4.74797272182151
A <- a1 * temperature + a2 * sqrt(temperature) + a3
B <- b1 * temperature + b2 * sqrt(temperature) + b3
A * exp(B) * density ^ (A - 1)
}
### Testing functions ###
# These unexported functions are included for testing purposes only.
# In CHNOSZ, the g function and omega(P,T) are calculated via hkf().
# 'Returns the value of omega at the input P and T.
# The value returned is 'in units of cal/mol and NOT multiplied by 10^-5.
#'pressure - Pressure to calculate at, in bars
#'temperature- Temperature to calculate at, in Celsius
#'density - Density of water to calculate omega at, in g/cm^3.
#'wref - The value of omega at standard pressure and temperature, in units of cal/mol.
#'Z - The charge of the species
calculateOmega <- function(pressure, temperature, density, wref, Z) {
# 'These equations are given by Shock et al. (1992)
eta <- 166027 # 'Value in units of Angstroms cal mol^-1
# 'Defines the electrostatic radius at reference pressure and temperature
reref <- Z * Z / (wref / eta + Z / 3.082)
# 'This represents the pressure and temperature dependent solvent function
g <- calculateG(pressure, temperature, density)
# 'Defines the electrostatic radius at the input P and T
re <- reref + abs(Z) * g
omega <- eta * (Z * Z / re - Z / (3.082 + g))
# 'If species is hydrogen, the species is neutral, or the pressure is above 6 kb,
# 'this equation is not necessary because omega is very close to wref.
if(Z == 0) omega[] <- wref
omega[pressure > 6000] <- wref
}
# 'Returns the value of the g function. If the density is greater than 1 g/cm^3, then zero is returned.
# 'pressure - The pressure to calculate at, in bars
# 'temperature- The temperature to calculate at, in celsius
# 'density - The density of water at which to calculate g at, in g/cm^3
calculateG <- function(pressure, temperature, density) {
T <- temperature
P <- pressure
a_g <- -2.037662 + 0.005747 * T - 6.557892E-06 * T * T
b_g <- 6.107361 - 0.01074377 * T + 1.268348E-05 * T * T
# 'Calculates the difference function in the case where we need to calculate at Psat conditions
f <- (((T - 155) / 300)^4.8 + 36.66666 * ((T - 155) / 300)^16) *
(-1.504956E-10 * (1000 - P)^3 + 5.017997E-14 * (1000 - P)^4)
f[P > 1000 | T < 155 | T > 355] <- 0
g <- a_g * (1 - density)^b_g - f
# Use g = 0 for density >= 1
g[density >= 1] <- 0
g
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/DEW.R
|
# CHNOSZ/EOSregress.R
# Model volumes and heat capacities of aqueous species
# 20091105 first version
# 20110429 revise and merge with CHNOSZ package
Cp_s_var <- function(T = 298.15, P = 1, omega.PrTr = 0, Z = 0) {
# Solvation contribution to heat capacity in the HKF EOS, divided by omega(Pr,Tr) (Joules)
Cp_s <- hkf("Cp", parameters = data.frame(omega = omega.PrTr, Z = Z), T = T, P = P, contrib = "s")$aq
return(Cp_s[[1]][, 1] / omega.PrTr)
}
V_s_var <- function(T = 298.15, P = 1, omega.PrTr = 0, Z = 0) {
# Solvation contribution to volume in the HKF EOS, divided by omega(Pr,Tr) (cm3.bar)
# [the negative sign on this term as written in the HKF EOS is accounted for by hkf()]
V_s <- hkf("V", parameters = data.frame(omega = omega.PrTr, Z = Z), T = T, P = P, contrib = "s")$aq
return(V_s[[1]][, 1]/convert(omega.PrTr, "cm3bar"))
}
EOSvar <- function(var, T, P, ...) {
# Get the variables of a term in a regression equation
# T (K), P (bar)
Theta <- 228 # K
Psi <- 2600 # bar
out <- switch(EXPR = var,
"(Intercept)" = rep(1, length(T)),
"T" = T,
"P" = P,
"TTheta" = T - Theta, # T-Theta
"invTTheta" = (T - Theta)^-1, # 1/(T-Theta)
"TTheta2" = (T - Theta)^2, # (T-Theta)^2
"invTTheta2" = (T - Theta)^-2, # 1/(T-Theta)^2
"invPPsi" = (P + Psi)^-1, # 1/(P+Psi)
"invPPsiTTheta" = (P + Psi)^-1 * (T - Theta)^-1, # 1/[(P+Psi)(T-Theta)]
"TXBorn" = T*water("XBorn", T = T, P = P)[, 1],
"drho.dT" = -water("rho", T = T, P = P)[, 1]*water("E", T = T, P = P)[, 1],
"V.kT" = water("V", T = T, P = P)[, 1]*water("kT", T = T, P = P)[, 1],
# Fallback: get a variable that is a property of water, or
# is any other function by name (possibly a user-defined function)
( if(var %in% water.SUPCRT92()) water(var, T, P)[, 1]
else if(exists(var)) {
if(is.function(get(var))) {
if(all(c("T", "P") %in% names(formals(get(var))))) get(var)(T = T, P = P, ...)
else stop(paste("the arguments of ", var, "() do not contain T and P", sep = ""))
}
else stop(paste("an object named", var, "is not a function"))
}
else stop(paste("can't find a variable named", var))
)
)
# 20151126 Apply the negative sign in the HKF EOS for V to the variable
# (not to omega as previously assumed)
if(var == "QBorn") out <- -out
return(out)
}
EOSlab <- function(var, coeff = "") {
# Make pretty labels for the variables
lab <- switch(EXPR = var,
# These are regression variables listed in EOSregress.Rd
"(Intercept)" = substitute(YYY*" ", list(YYY = coeff)),
"T" = substitute(YYY%*%italic(T), list(YYY = coeff)),
"P" = substitute(YYY%*%italic(P), list(YYY = coeff)),
"TTheta" = substitute(YYY%*%(italic(T)-Theta), list(YYY = coeff)),
"invTTheta" = substitute(YYY/(italic(T)-Theta), list(YYY = coeff)),
"TTheta2" = substitute(YYY%*%(italic(T)-Theta)^2, list(YYY = coeff)),
"invTTheta2" = substitute(YYY/(italic(T)-Theta)^2, list(YYY = coeff)),
"invPPsi" = substitute(YYY/(italic(P)+Psi),list(YYY = coeff)),
"invPPsiTTheta" = substitute(YYY/((italic(P)+Psi)(italic(T)-Theta)), list(YYY = coeff)),
"TXBorn" = substitute(YYY%*%italic(TX), list(YYY = coeff)),
"drho.dT" = substitute(YYY%*%(d~rho/dT), list(YYY = coeff)),
"V.kT" = substitute(YYY%*%V~kappa[italic(T)], list(YYY = coeff)),
# These are non-single-letter properties of water as listed in water.Rd
"kT" = substitute(YYY%*%kappa[italic(T)], list(YYY = coeff)),
"alpha" = substitute(YYY%*%alpha, list(YYY = coeff)),
"beta" = substitute(YYY%*%beta, list(YYY = coeff)),
"epsilon" = substitute(YYY%*%epsilon, list(YYY = coeff)),
"rho" = substitute(YYY%*%rho, list(YYY = coeff)),
"NBorn" = substitute(YYY%*%italic(N), list(YYY = coeff)),
"QBorn" = substitute(YYY%*%italic(Q), list(YYY = coeff)),
"XBorn" = substitute(YYY%*%italic(X), list(YYY = coeff)),
"YBorn" = substitute(YYY%*%italic(Y), list(YYY = coeff)),
"ZBorn" = substitute(YYY%*%italic(Z), list(YYY = coeff)),
(
# If var is a function, does have an attribute named "label"?
if(exists(var)) {
if(is.function(get(var))) {
if(!is.null(attr(get(var), "label"))) {
return(substitute(YYY*XXX, list(YYY = coeff, XXX = attr(get(var), "label"))))
# Fallback, use the name of the variable
# (e.g. for a property of water such as A, G, S, U, H, or name of a user-defined function)
} else substitute(YYY%*%italic(XXX), list(YYY = coeff, XXX = var))
} else substitute(YYY%*%italic(XXX), list(YYY = coeff, XXX = var))
} else substitute(YYY%*%italic(XXX), list(YYY = coeff, XXX = var))
)
)
return(lab)
}
EOSregress <- function(exptdata, var = "", T.max = 9999, ...) {
# Regress exptdata using terms listed in fun
# Which values to use
iT <- which(exptdata$T <= T.max)
exptdata <- exptdata[iT, ]
# Temperature and pressure
T <- exptdata$T
P <- exptdata$P
# The third column is the property of interest: Cp or V
X <- exptdata[, 3]
# Now build a regression formula
if(length(var) == 0) stop("var is missing")
fmla <- as.formula(paste("X ~ ", paste(var, collapse = "+")))
# Retrieve the values of the variables
for(i in seq_along(var)) assign(var[i], EOSvar(var[i], T = T, P = P, ...))
# Now regress away!
EOSlm <- lm(fmla)
return(EOSlm)
}
EOScalc <- function(coefficients, T, P, ...) {
# Calculate values of volume or heat capacity from regression fit
X <- 0
for(i in 1:length(coefficients)) {
coeff.i <- coefficients[[i]]
fun.i <- EOSvar(names(coefficients)[i], T, P, ...)
X <- X + coeff.i * fun.i
}
return(X)
}
EOSplot <- function(exptdata, var = NULL, T.max = 9999, T.plot = NULL,
fun.legend = "topleft", coefficients = NULL, add = FALSE,
lty = par("lty"), col = par("col"), ...) {
# Plot experimental and modelled volumes and heat capacities
# First figure out the property (Cp or V) from the exptdata
prop <- colnames(exptdata)[3]
# If var is NULL use HKF equations
if(is.null(var)) {
if(prop == "Cp") var <- c("invTTheta2","TXBorn")
if(prop == "V") var <- c("invTTheta","QBorn")
}
# Perform the regression, only using temperatures up to T.max
if(is.null(coefficients)) {
EOSlm <- EOSregress(exptdata, var, T.max, ...)
coefficients <- EOSlm$coefficients
}
# Only plot points below a certain temperature
iexpt <- 1:nrow(exptdata)
if(!is.null(T.plot)) iexpt <- which(exptdata$T < T.plot)
# For a nicer plot, extend the ranges, but don't go below -20 degrees C
ylim <- extendrange(exptdata[iexpt, prop], f = 0.1)
xlim <- extendrange(exptdata$T[iexpt], f = 0.1)
xlim[xlim < 253.15] <- 253.15
# Start plot
if(!add) {
thermo.plot.new(xlim = xlim, ylim = ylim, xlab = axis.label("T", units = "K"),
ylab = axis.label(paste(prop, "0", sep = "")), yline = 2, mar = NULL)
# Different plot symbols to represent size of residuals
pch.open <- 1
pch.filled <- 16
# Find the calculated values at these conditions
calc.X <- EOScalc(coefficients, exptdata$T, exptdata$P, ...)
expt.X <- exptdata[, prop]
# Are we within 10% of the values?
in10 <- which(abs((calc.X-expt.X)/expt.X) < 0.1)
pch <- rep(pch.open, length(exptdata$T))
pch[in10] <- pch.filled
points(exptdata$T, exptdata[, prop], pch = pch)
}
# Plot regression line at a single P
P <- mean(exptdata$P)
message("EOSplot: plotting line for P = ", P, " bar")
xs <- seq(xlim[1], xlim[2], length.out = 200)
calc.X <- EOScalc(coefficients, xs, P, ...)
lines(xs, calc.X, lty = lty, col = col)
# Make legend
if(!is.null(fun.legend) & !add) {
# 20161101: negate QBorn and V_s_var
iQ <- names(coefficients) %in% c("QBorn", "V_s_var")
coefficients[iQ] <- -coefficients[iQ]
coeffs <- as.character(round(as.numeric(coefficients), 4))
# So that positive ones appear with a plus sign
ipos <- which(coeffs >= 0)
coeffs[ipos] <- paste("+", coeffs[ipos], sep = "")
# Make labels for the functions
fun.lab <- as.expression(lapply(1:length(coeffs),
function(x) {EOSlab(names(coefficients)[x],coeffs[x])} ))
#fun.lab <- paste(names(coeffs),round(as.numeric(coeffs),4))
legend(fun.legend, legend = fun.lab, pt.cex = 0.1)
}
return(invisible(list(xrange = range(exptdata$T[iexpt]), coefficients = coefficients)))
}
EOScoeffs <- function(species, property, P = 1) {
# Get the HKF coefficients for species in the database
iis <- info(info(species, "aq"))
if(property == "Cp") {
out <- as.numeric(iis[,c("c1", "c2", "omega")])
names(out) <- c("(Intercept)", "invTTheta2", "TXBorn")
} else if(property == "V") {
iis <- iis[,c("a1", "a2", "a3", "a4", "omega")]
# Calculate sigma and xi and convert to volumetric units: 1 J = 10 cm^3 bar
sigma <- convert( iis$a1 + iis$a2 / (2600 + P), "cm3bar" )
xi <- convert( iis$a3 + iis$a4 / (2600 + P), "cm3bar" )
omega <- convert( iis$omega, "cm3bar" )
# 20151126: We _don't_ put a negative sign on omega here;
# now, the negative sign in the HKF EOS is with the variable (QBorn or V_s_var)
out <- c(sigma, xi, omega)
names(out) <- c("(Intercept)", "invTTheta", "QBorn")
}
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/EOSregress.R
|
# Calculate properties of water using the IAPWS-95 formulation (Wagner and Pruss, 2002)
IAPWS95 <- function(property,T = 298.15,rho = 1000) {
property <- tolower(property)
# Triple point
T.triple <- 273.16 # K
P.triple <- 611.657 # Pa
rho.triple.liquid <- 999.793
rho.triple.vapor <- 0.00485458
# Normal boiling point
T.boiling <- 373.124
P.boiling <- 0.101325
rho.boiling.liquid <- 958.367
rho.boiling.vapor <- 0.597657
# Critical point constants
T.critical <- 647.096 # K
rho.critical <- 322 # kg m-3
# Specific and molar gas constants
R <- 0.46151805 # kJ kg-1 K-1
# R.M <- 8.314472 # J mol-1 K-1
# Molar mass
M <- 18.015268 # g mol-1
## Define functions idealgas and residual, supplying arguments delta and tau
idealgas <- function(p) IAPWS95.idealgas(p, delta, tau)
residual <- function(p) IAPWS95.residual(p, delta, tau)
## Relation of thermodynamic properties to Helmholtz free energy
a <- function() {
x <- idealgas('phi')+residual('phi')
return(x*R*T)
}
# Table 6.3
p <- function() {
x <- 1 + delta*residual('phi.delta')
return(x*rho*R*T/1000) # for MPa
}
s <- function() {
x <- tau * (idealgas('phi.tau')+residual('phi.tau'))-idealgas('phi')-residual('phi')
return(x*R)
}
u <- function() {
x <- tau * (idealgas('phi.tau')+residual('phi.tau'))
return(x*R*T)
}
h <- function() {
x <- 1 + tau * (idealgas('phi.tau')+residual('phi.tau')) + delta*residual('phi.delta')
return(x*R*T)
}
g <- function() {
x <- 1 + idealgas('phi') + residual('phi') + delta*residual('phi.delta')
return(x*R*T)
}
cv <- function() {
x <- -tau^2*(idealgas('phi.tau.tau')+residual('phi.tau.tau'))
return(x*R)
}
cp <- function() {
x <- -tau^2*(idealgas('phi.tau.tau')+residual('phi.tau.tau')) +
(1+delta*residual('phi.delta')-delta*tau*residual('phi.delta.tau'))^2 /
(1+2*delta*residual('phi.delta')+delta^2*residual('phi.delta.delta'))
return(x*R)
}
# 20090420 Speed of sound calculation is incomplete
# (delta.liquid and drhos.dT not visible)
# cs <- function() {
# x <- -tau^2*(idealgas('phi.tau.tau')+residual('phi.tau.tau')) +
# (1+delta*residual('phi.delta')-delta*tau*residual('phi.delta.tau'))^2 /
# (1+2*delta*residual('phi.delta')+delta^2*residual('phi.delta.delta')) *
# ((1+delta.liquid*residual('phi.delta')-delta.liquid*tau*residual('phi.tau.tau'))-rho.critical/(R*delta.liquid)*drhos.dT)
# return(x*R)
# }
w <- function() {
x <- 1 + 2*delta*residual('phi.delta') + delta^2*residual('phi.delta.delta') -
(1+delta*residual('phi.delta')-delta*tau*residual('phi.delta.tau'))^2 /
tau^2*(idealgas('phi.tau.tau')+residual('phi.tau.tau'))
return(sqrt(x*R*T))
}
mu <- function() {
x <- -(delta*residual('phi.delta')+delta^2*residual('phi.delta.delta')+delta*tau*residual('phi.delta.tau')) /
( ( 1+delta*residual('phi.delta')-delta*tau*residual('phi.delta.tau')^2 ) - tau^2 *
(idealgas('phi.tau.tau')+residual('phi.tau.tau'))*(1+2*delta*residual('phi.delta')+delta^2*residual('phi.delta.delta')) )
return(x/(R*rho))
}
## Run the calculations
ww <- NULL
my.T <- T
my.rho <- rho
for(j in 1:length(property)) {
t <- numeric()
for(i in 1:length(my.T)) {
T <- my.T[i]
rho <- my.rho[i]
# Equation 6.4
delta <- rho / rho.critical
tau <- T.critical / T
t <- c(t,get(property[j])())
}
t <- data.frame(t)
if(j == 1) ww <- t else ww <- cbind(ww,t)
}
colnames(ww) <- property
return(ww)
}
### Unexported functions ###
# IAPWS95.idealgas and IAPWS95.residual are supporting functions to IAPWS95 for calculating
# the ideal-gas and residual parts in the IAPWS-95 formulation.
# The value of p can be one of phi, phi.delta, phi.delta.delta, phi.tau, phi.tau.tau, or phi.delta.tau,
# to calculate the specific dimensionless Helmholtz free energy (phi) or one of its derivatives.
IAPWS95.idealgas <- function(p, delta, tau) {
## The ideal gas part in the IAPWS-95 formulation
# From Table 6.1 of Wagner and Pruss, 2002
n <- c( -8.32044648201, 6.6832105268, 3.00632, 0.012436,
0.97315, 1.27950, 0.96956, 0.24873 )
gamma <- c( NA, NA, NA, 1.28728967,
3.53734222, 7.74073708, 9.24437796, 27.5075105 )
# Equation 6.5
phi <- function() log(delta) + n[1] + n[2]*tau + n[3]*log(tau) +
sum( n[4:8] * log(1-exp(-gamma[4:8]*tau)) )
# Derivatives from Table 6.4
phi.delta <- function() 1/delta+0+0+0+0
phi.delta.delta <- function() -1/delta^2+0+0+0+0
phi.tau <- function() 0+0+n[2]+n[3]/tau+sum(n[4:8]*gamma[4:8]*((1-exp(-gamma[4:8]*tau))^-1-1))
phi.tau.tau <- function() 0+0+0-n[3]/tau^2-sum(n[4:8]*gamma[4:8]^2 *
exp(-gamma[4:8]*tau)*(1-exp(-gamma[4:8]*tau))^-2)
phi.delta.tau <- function() 0+0+0+0+0
return(get(p)())
}
IAPWS95.residual <- function(p, delta, tau) {
## The residual part in the IAPWS-95 formulation
# From Table 6.2 of Wagner and Pruss, 2002
c <- c(rep(NA,7),rep(1,15),rep(2,20),rep(3,4),4,rep(6,4),rep(NA,5))
d <- c(1,1,1,2,2,3,4,1,1,1,2,2,3,4,
4,5,7,9,10,11,13,15,1,2,2,2,3,4,
4,4,5,6,6,7,9,9,9,9,9,10,10,12,
3,4,4,5,14,3,6,6,6,3,3,3,NA,NA)
t <- c(-0.5,0.875,1,0.5,0.75,0.375,1,4,6,12,1,5,4,2,
13,9,3,4,11,4,13,1,7,1,9,10,10,3,
7,10,10,6,10,10,1,2,3,4,8,6,9,8,
16,22,23,23,10,50,44,46,50,0,1,4,NA,NA)
n <- c( 0.12533547935523E-1, 0.78957634722828E1 ,-0.87803203303561E1 ,
0.31802509345418 ,-0.26145533859358 ,-0.78199751687981E-2,
0.88089493102134E-2,-0.66856572307965 , 0.20433810950965 ,
-0.66212605039687E-4,-0.19232721156002 ,-0.25709043003438 ,
0.16074868486251 ,-0.40092828925807E-1, 0.39343422603254E-6,
-0.75941377088144E-5, 0.56250979351888E-3,-0.15608652257135E-4,
0.11537996422951E-8, 0.36582165144204E-6,-0.13251180074668E-11,
-0.62639586912454E-9,-0.10793600908932 , 0.17611491008752E-1,
0.22132295167546 ,-0.40247669763528 , 0.58083399985759 ,
0.49969146990806E-2,-0.31358700712549E-1,-0.74315929710341 ,
0.47807329915480 , 0.20527940895948E-1,-0.13636435110343 ,
0.14180634400617E-1, 0.83326504880713E-2,-0.29052336009585E-1,
0.38615085574206E-1,-0.20393486513704E-1,-0.16554050063734E-2,
0.19955571979541E-2, 0.15870308324157E-3,-0.16388568342530E-4,
0.43613615723811E-1, 0.34994005463765E-1,-0.76788197844621E-1,
0.22446277332006E-1,-0.62689710414685E-4,-0.55711118565645E-9,
-0.19905718354408 , 0.31777497330738 ,-0.11841182425981 ,
-0.31306260323435E2 , 0.31546140237781E2 ,-0.25213154341695E4 ,
-0.14874640856724 , 0.31806110878444)
alpha <- c(rep(NA,51),20,20,20,NA,NA)
beta <- c(rep(NA,51),150,150,250,0.3,0.3)
gamma <- c(rep(NA,51),1.21,1.21,1.25,NA,NA)
epsilon <- c(rep(NA,51),1,1,1,NA,NA)
a <- c(rep(NA,54),3.5,3.5)
b <- c(rep(NA,54),0.85,0.95)
B <- c(rep(NA,54),0.2,0.2)
C <- c(rep(NA,54),28,32)
D <- c(rep(NA,54),700,800)
A <- c(rep(NA,54),0.32,0.32)
# from Table 6.5
i1 <- 1:7
i2 <- 8:51
i3 <- 52:54
i4 <- 55:56
# Deriviatives of distance function
Delta <- function(i) { Theta(i)^2 + B[i] * ((delta-1)^2)^a[i] }
Theta <- function(i) { (1-tau) + A[i] * ((delta-1)^2)^(1/(2*beta[i])) }
Psi <- function(i) { exp ( -C[i]*(delta-1)^2 - D[i]*(tau-1)^2 ) }
dDelta.bi.ddelta <- function(i) { b[i]*Delta(i)^(b[i]-1)*dDelta.ddelta(i) }
d2Delta.bi.ddelta2 <- function(i) { b[i]*( Delta(i)^(b[i]-1) * d2Delta.ddelta2(i) +
(b[i]-1)*Delta(i)^(b[i]-2)*dDelta.ddelta(i)^2 ) }
dDelta.bi.dtau <- function(i) { -2*Theta(i)*b[i]*Delta(i)^(b[i]-1) }
d2Delta.bi.dtau2 <- function(i) { 2*b[i]*Delta(i)^(b[i]-1) + 4*Theta(i)^2*b[i]*(b[i]-1)*Delta(i)^(b[i]-2) }
d2Delta.bi.ddelta.dtau <- function(i) { -A[i]*b[i]*2/beta[i]*Delta(i)^(b[i]-1)*(delta-1) *
((delta-1)^2)^(1/(2*beta[i])-1) - 2*Theta(i)*b[i]*(b[i]-1)*Delta(i)^(b[i]-2)*dDelta.ddelta(i) }
dDelta.ddelta <- function(i) { (delta-1) * ( A[i]*Theta(i)*2/beta[i]*((delta-1)^2)^(1/(2*beta[i])-1) +
2*B[i]*a[i]*((delta-1)^2)^(a[i]-1) ) }
d2Delta.ddelta2 <- function(i) { 1/(delta-1)*dDelta.ddelta(i) + (delta-1)^2 * (
4*B[i]*a[i]*(a[i]-1)*((delta-1)^2)^(a[i]-2) + 2*A[i]^2*(1/beta[i])^2 *
(((delta-1)^2)^(1/(2*B[i])-1))^2 + A[i]*Theta(i)*4/beta[i]*(1/(2*B[i])-1) *
((delta-1)^2)^(1/(2*beta[i])-2) ) }
# Derivatives of exponential function
dPsi.ddelta <- function(i) { -2*C[i]*(delta-1)*Psi(i) }
d2Psi.ddelta2 <- function(i) { ( 2*C[i]*(delta-1)^2 - 1 ) * 2*C[i]*Psi(i) }
dPsi.dtau <- function(i) { -2*D[i]*(tau-1)*Psi(i) }
d2Psi.dtau2 <- function(i) { (2*D[i]*(tau-1)^2 - 1) * 2*D[i]*Psi(i) }
d2Psi.ddelta.dtau <- function(i) { 4*C[i]*D[i]*(delta-1)*(tau-1)*Psi(i) }
# Dimensionless Helmholtz free energy and derivatives
phi <- function() {
sum(n[i1]*delta^d[i1]*tau^t[i1]) +
sum(n[i2]*delta^d[i2]*tau^t[i2]*exp(-delta^c[i2])) +
sum(n[i3]*delta^d[i3]*tau^t[i3] *
exp( -alpha[i3]*(delta-epsilon[i3])^2 - beta[i3]*(tau-gamma[i3])^2 ) ) +
sum(n[i4]*Delta(i4)^b[i4]*delta*Psi(i4))
}
phi.delta <- function() {
sum(n[i1]*d[i1]*delta^(d[i1]-1)*tau^t[i1]) +
sum(n[i2]*exp(-delta^c[i2])*(delta^(d[i2]-1)*tau^t[i2]*(d[i2]-c[i2]*delta^c[i2]))) +
sum(n[i3]*delta^d[i3]*tau^t[i3] *
exp( -alpha[i3]*(delta-epsilon[i3])^2 - beta[i3]*(tau-gamma[i3])^2 ) *
(d[i3]/delta - 2 * alpha[i3]*(delta-epsilon[i3])) ) +
sum(n[i4] * ( Delta(i4)^b[i4] * (Psi(i4)+delta*dPsi.ddelta(i4)) + dDelta.bi.ddelta(i4)*delta*Psi(i4) ) )
}
phi.delta.delta <- function() {
sum(n[i1]*d[i1]*(d[i1]-1)*delta^(d[i1]-2)*tau^t[i1]) +
sum(n[i2]*exp(-delta^c[i2])*(delta^(d[i2]-2)*tau^t[i2]*((d[i2]-c[i2]*delta^c[i2]) *
(d[i2]-1-c[i2]*delta^c[i2])-c[i2]^2*delta^c[i2]))) +
sum(n[i3]*tau^t[i3]*exp(-alpha[i3]*(delta-epsilon[i3])^2 - beta[i3]*(tau-gamma[i3])^2) * (
-2*alpha[i3]*delta^d[i3]+4*alpha[i3]^2*delta^d[i3]*(delta-epsilon[i3])^2 -
4*d[i3]*alpha[i3]*delta^(d[i3]-1)*(delta-epsilon[i3])+d[i3]*(d[i3]-1)*delta^(d[i3]-2) ) ) +
sum(n[i4]*( Delta(i4)^b[i4]*(2*dPsi.ddelta(i4)+delta*d2Psi.ddelta2(i4)) +
2*dDelta.bi.ddelta(i4)*(Psi(i4)+delta*dPsi.ddelta(i4)) + d2Delta.bi.ddelta2(i4)*delta*Psi(i4) ) )
}
phi.tau <- function() {
sum(n[i1]*t[i1]*delta^d[i1]*tau^(t[i1]-1)) +
sum(n[i2]*t[i2]*delta^d[i2]*tau^(t[i2]-1)*exp(-delta^c[i2])) +
sum(n[i3]*delta^d[i3]*tau^t[i3]*exp(-alpha[i3]*(delta-epsilon[i3])^2-beta[i3]*(tau-gamma[i3])^2) *
(t[i3]/tau-2*beta[i3]*(tau-gamma[i3]))) +
sum(n[i4]*delta*(dDelta.bi.dtau(i4)*Psi(i4)+Delta(i4)^b[i4]*dPsi.dtau(i4)))
}
phi.tau.tau <- function() {
sum(n[i1]*t[i1]*(t[i1]-1)*delta^d[i1]*tau^(t[i1]-2)) +
sum(n[i2]*t[i2]*(t[i2]-1)*delta^d[i2]*tau^(t[i2]-2)*exp(-delta^c[i2])) +
sum(n[i3]*delta^d[i3]*tau^t[i3]*exp(-alpha[i3]*(delta-epsilon[i3])^2-beta[i3]*(tau-gamma[i3])^2) *
(((t[i3]/tau)-2*beta[i3]*(tau-gamma[i3]))^2-t[i3]/tau^2-2*beta[i3])) +
sum(n[i4]*delta*(d2Delta.bi.dtau2(i4)*Psi(i4)+2*dDelta.bi.dtau(i4)*dPsi.dtau(i4) +
Delta(i4)^b[i4]*d2Psi.dtau2(i4)))
}
phi.delta.tau <- function() {
sum(n[i1]*d[i1]*t[i1]*delta^(d[i1]-1)*tau^(t[i1]-1)) +
sum(n[i2]*t[i2]*delta^(d[i2]-1)*tau^(t[i2]-1)*(d[i2]-c[i2]*delta^c[i2])*exp(-delta^c[i2])) +
sum(n[i3]*delta^d[i3]*tau^t[i3]*exp(-alpha[i3]*(delta-epsilon[i3])^2-beta[i3]*(tau-gamma[i3])^2) *
((d[i3]/delta)-2*alpha[i3]*(delta-epsilon[i3]))*(t[i3]/tau-2*beta[i3]*(tau-gamma[i3])) ) +
sum(n[i4]*(Delta(i4)^b[i4]*(dPsi.dtau(i4)+delta*d2Psi.ddelta.dtau(i4)) +
delta*dDelta.bi.ddelta(i4)*dPsi.dtau(i4)+dDelta.bi.dtau(i4) * (Psi(i4)+delta*dPsi.ddelta(i4)) +
d2Delta.bi.ddelta.dtau(i4)*delta*Psi(i4) ))
}
return(get(p)())
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/IAPWS95.R
|
# CHNOSZ/NaCl.R
# Calculate ionic strength and molalities of species given a total molality of NaCl
# 20181102 First version (jmd)
# 20181106 Use activity coefficients of Na+ and Nacl
# 20221122 Make it work with m_tot = 0
# 20221210 Rewritten to include pH dependence;
# uses affinity() and equilibrate() instead of algebraic equations
NaCl <- function(m_tot = 1, T = 25, P = "Psat", pH = NA, attenuate = FALSE) {
# Store existing thermo data frame
thermo <- get("thermo", CHNOSZ)
# Get length of longest variable
nTP <- max(length(T), length(P), length(pH))
pH.arg <- pH
pH <- rep(pH, length.out = nTP)
# Start with complete dissociation into Na+ and Cl-,
# so ionic strength and molality of Na+ are equal to m_tot
m_Na <- IS <- m_tot
# Make them same length as T and P
IS <- rep(IS, length.out = nTP)
m_Na <- rep(m_Na, length.out = nTP)
# Set tolerance for convergence to 1/100th of m_tot
tolerance <- m_tot / 100
# If m_tot is 0, return 0 for all variables 20221122
zeros <- rep(0, nTP)
if(m_tot == 0) return(list(IS = zeros, m_Na = zeros, m_Cl = zeros, m_NaCl = zeros, m_HCl = zeros))
maxiter <- 100
for(i in 1:maxiter) {
# Setup chemical system and calculate affinities
if(identical(pH.arg, NA)) {
basis(c("Na+", "Cl-", "e-"))
species(c("Cl-", "NaCl"))
a <- suppressMessages(affinity(T = T, P = P, "Na+" = log10(m_Na), IS = IS, transect = TRUE))
} else {
basis(c("Na+", "Cl-", "H+", "e-"))
species(c("Cl-", "NaCl", "HCl"))
a <- suppressMessages(affinity(T = T, P = P, pH = pH, "Na+" = log10(m_Na), IS = IS, transect = TRUE))
}
# Speciate Cl-
e <- suppressMessages(equilibrate(a, loga.balance = log10(m_tot)))
# Get molality of each Cl-bearing species
m_Cl <- 10^e$loga.equil[[1]]
m_NaCl <- 10^e$loga.equil[[2]]
if(identical(pH.arg, NA)) m_HCl <- NA else m_HCl <- 10^e$loga.equil[[3]]
# Store previous ionic strength and molality of Na+
IS_prev <- IS
m_Na_prev <- m_Na
# Calculate new molality of Na+ and deviation
m_Na <- m_tot - m_NaCl
# Only go halfway to avoid overshoot
if(attenuate) m_Na <- (m_Na_prev + m_Na) / 2
dm_Na <- m_Na - m_Na_prev
# Calculate ionic strength and deviation
IS <- (m_Na + m_Cl) / 2
dIS <- IS - IS_prev
# Keep going until the deviations in ionic strength and molality of Na+ at all temperatures are less than tolerance
converged <- abs(dIS) < tolerance & abs(dm_Na) < tolerance
if(all(converged)) {
# Add one step without attenuating the deviation of m_Na
if(attenuate) attenuate <- FALSE else break
}
}
if(i == maxiter) {
if(attenuate) stop(paste("reached", maxiter, "iterations without converging"))
else stop(paste("reached", maxiter, "iterations without converging (try setting attenuate = TRUE)"))
}
# Restore thermo data frame
assign("thermo", thermo, CHNOSZ)
# Return the calculated values
list(IS = IS, m_Na = m_Na, m_Cl = m_Cl, m_NaCl = m_NaCl, m_HCl = m_HCl)
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/NaCl.R
|
# CHNOSZ/add.OBIGT.R
# Add or change entries in the thermodynamic database
## If this file is interactively sourced, the following are also needed to provide unexported functions:
#source("info.R")
#source("util.data.R")
mod.OBIGT <- function(..., zap = FALSE) {
# Add or modify species in thermo()$OBIGT
thermo <- get("thermo", CHNOSZ)
# The names and values are in the arguments
# This works for providing arguments via do.call
args <- list(...)
# This is needed if we are called with a list as the actual argument
if(is.list(args[[1]])) args <- args[[1]]
if(length(args) < 2) stop("please supply at least a species name and a property to update")
if(is.null(names(args))) stop("all arguments after the first should be named")
if(any(tail(nchar(names(args)), -1) == 0)) stop("all arguments after the first should be named")
# If the first argument is numeric, it's the species index
if(is.numeric(args[[1]][1])) {
ispecies <- args[[1]]
args <- args[-1]
speciesname <- info(ispecies, check.it = FALSE)$name
} else {
# If the name of the first argument is missing, assume it's the species name
if(names(args)[1] == "") names(args)[1] <- "name"
speciesname <- args$name
# Search for this species, use check.protein = FALSE to avoid infinite loop when adding proteins
# and suppressMessages to not show messages about matches of this name to other states
if("state" %in% names(args)) ispecies <- suppressMessages(mapply(info.character,
species = args$name, state = args$state, check.protein = FALSE, SIMPLIFY = TRUE, USE.NAMES = FALSE))
else ispecies <- suppressMessages(mapply(info.character,
species = args$name, check.protein = FALSE, SIMPLIFY = TRUE, USE.NAMES = FALSE))
}
# The column names of thermo()$OBIGT, split at the "."
cnames <- c(do.call(rbind, strsplit(colnames(thermo$OBIGT), ".", fixed = TRUE)), colnames(thermo$OBIGT))
# The columns we are updating
icol <- match(names(args), cnames)
if(any(is.na(icol))) stop(paste("properties not in thermo$OBIGT:", paste(names(args)[is.na(icol)], collapse = " ")) )
# The column numbers for properties that matched after the split
icol[icol > 44] <- icol[icol > 44] - 44
icol[icol > 22] <- icol[icol > 22] - 22
# Which species are new and which are old
inew <- which(is.na(ispecies))
iold <- which(!is.na(ispecies))
# The arguments as data frame
args <- data.frame(args, stringsAsFactors = FALSE)
if(length(inew) > 0) {
# The right number of blank rows of thermo()$OBIGT
newrows <- thermo$OBIGT[1:length(inew), ]
# If we don't know something it's NA
newrows[] <- NA
# Put in a default state
newrows$state <- thermo$opt$state
# The formula defaults to the name
newrows$formula <- args$name[inew]
# The units should also be set 20190530
newrows$E_units <- thermo$opt$E.units
# Fill in the columns
newrows[, icol] <- args[inew, ]
# Guess model from state 20220919
namodel <- is.na(newrows$model)
if(any(namodel)) newrows$model[namodel] <- ifelse(newrows$state[namodel] == "aq", "HKF", "CGL")
# Now check the formulas
e <- tryCatch(makeup(newrows$formula), error = function(e) e)
if(inherits(e, "error")) {
warning("please supply a valid chemical formula as the species name or in the 'formula' argument")
# Transmit the error from makeup
stop(e)
}
# Assign to thermo()$OBIGT
thermo$OBIGT <- rbind(thermo$OBIGT, newrows)
rownames(thermo$OBIGT) <- NULL
assign("thermo", thermo, CHNOSZ)
# Update ispecies
ntotal <- nrow(thermo$OBIGT)
ispecies[inew] <- (ntotal-length(inew)+1):ntotal
# Inform user
message(paste("mod.OBIGT: added ", newrows$name, "(", newrows$state, ")", " with ", newrows$model,
" model and energy units of ", newrows$E_units, sep = "", collapse = "\n"))
}
if(length(iold) > 0) {
# Loop over species
for(i in 1:length(iold)) {
# The old values and the state
oldprop <- thermo$OBIGT[ispecies[iold[i]], icol]
state <- thermo$OBIGT$state[ispecies[iold[i]]]
model <- thermo$OBIGT$model[ispecies[iold[i]]]
# Zap (clear) all preexisting values except for state and model 20220324
if(zap) {
thermo$OBIGT[ispecies[iold[i]], ] <- NA
thermo$OBIGT$state[ispecies[iold[i]]] <- state
thermo$OBIGT$model[ispecies[iold[i]]] <- model
}
# Convert NA to NA_real_ so no change is detected 20230210
newprop <- args[iold[i], ]
newprop[is.na(newprop)] <- NA_real_
if(isTRUE(all.equal(oldprop, newprop, check.attributes = FALSE))) {
# No change to OBIGT; tell the user about it
message("mod.OBIGT: no change for ", speciesname[iold[i]], "(", state, ")")
} else {
# Update the data in OBIGT
thermo$OBIGT[ispecies[iold[i]], icol] <- newprop
assign("thermo", thermo, CHNOSZ)
message("mod.OBIGT: updated ", speciesname[iold[i]], "(", state, ")")
}
}
}
return(ispecies)
}
add.OBIGT <- function(file, species = NULL, force = TRUE) {
# Add/replace entries in thermo$OBIGT from values saved in a file
# Only replace if force == TRUE
thermo <- get("thermo", CHNOSZ)
to1 <- thermo$OBIGT
id1 <- paste(to1$name,to1$state)
# We match system files with the file suffixes (.csv) removed
sysfiles <- dir(system.file("extdata/OBIGT/", package = "CHNOSZ"))
sysnosuffix <- sapply(strsplit(sysfiles, "\\."), "[", 1)
isys <- match(file, sysnosuffix)
if(!is.na(isys)) file <- system.file(paste0("extdata/OBIGT/", sysfiles[isys]), package = "CHNOSZ")
# Read data from the file
to2 <- read.csv(file, as.is = TRUE)
Etxt <- paste(unique(to2$E_units), collapse = " and ")
# Load only selected species if requested
if(!is.null(species)) {
idat <- match(species, to2$name)
ina <- is.na(idat)
if(!any(ina)) to2 <- to2[idat, ]
else stop(paste("file", file, "doesn't have", paste(species[ina], collapse = ", ")))
}
id2 <- paste(to2$name,to2$state)
# Check if the data table is compatible with thermo$OBIGT
if(!identical(colnames(to1), colnames(to2))) stop(paste(file, "does not have same column names as thermo$OBIGT data frame."))
# Match the new species to existing ones
does.exist <- id2 %in% id1
ispecies.exist <- na.omit(match(id2, id1))
nexist <- sum(does.exist)
# Keep track of the species we've added
inew <- numeric()
if(force) {
# Replace existing entries
if(nexist > 0) {
to1[ispecies.exist, ] <- to2[does.exist, ]
to2 <- to2[!does.exist, ]
inew <- c(inew, ispecies.exist)
}
} else {
# Ignore any new entries that already exist
to2 <- to2[!does.exist, ]
nexist <- 0
}
# Add new entries
if(nrow(to2) > 0) {
to1 <- rbind(to1, to2)
inew <- c(inew, (length(id1)+1):nrow(to1))
}
# Commit the change
thermo$OBIGT <- to1
rownames(thermo$OBIGT) <- 1:nrow(thermo$OBIGT)
assign("thermo", thermo, CHNOSZ)
# Give the user a message
message("add.OBIGT: read ", length(does.exist), " rows; made ",
nexist, " replacements, ", nrow(to2), " additions [energy units: ", Etxt, "]")
#message("add.OBIGT: use OBIGT() or reset() to restore default database")
return(invisible(inew))
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/add.OBIGT.R
|
# CHNOSZ/add.protein.R
# Calculate properties of proteins 20061109 jmd
# Reorganize protein functions 20120513
# Count numbers of amino acids in a sequence
seq2aa <- function(sequence, protein = NA) {
# Remove newlines and whitespace
sequence <- gsub("\\s", "", gsub("[\r\n]", "", sequence))
# Make a data frame from counting the amino acids in the sequence
caa <- count.aa(sequence)
colnames(caa) <- aminoacids(3)
# Now make the data frame
po <- strsplit(as.character(protein), "_")[[1]]
aa <- data.frame(protein = po[1], organism = po[2], ref = NA, abbrv = NA, stringsAsFactors = FALSE)
# chains = 1 for any sequence, chains = 0 for no sequence
chains <- sum(nchar(sequence) > 0)
aa <- cbind(aa, chains = chains, caa)
return(aa)
}
# Add amino acid counts to thermo()$protein (returns iprotein)
add.protein <- function(aa, as.residue = FALSE) {
# Add a properly constructed data frame of
# amino acid counts to thermo()$protein
thermo <- get("thermo", CHNOSZ)
if(!identical(colnames(aa), colnames(thermo$protein)))
stop("'aa' does not have the same columns as thermo()$protein")
# Check that new protein IDs are unique 20220418
po <- paste(aa$protein, aa$organism, sep = "_")
idup <- duplicated(po)
if(any(idup)) stop(paste("some protein IDs are duplicated:", paste(unique(po[idup]), collapse = " ")))
# Normalize by protein length if as.residue = TRUE 20220416
if(as.residue) {
pl <- protein.length(aa)
aa[, 5:25] <- aa[, 5:25] / pl
}
# Find any protein IDs that are already present
ip <- pinfo(po)
ip.present <- !is.na(ip)
# Now we're ready to go
tp.new <- thermo$protein
if(!all(ip.present)) tp.new <- rbind(tp.new, aa[!ip.present, ])
if(any(ip.present)) tp.new[ip[ip.present], ] <- aa[ip.present, ]
rownames(tp.new) <- NULL
thermo$protein <- tp.new
assign("thermo", thermo, CHNOSZ)
# Return the new rownumbers
ip <- pinfo(po)
# Make some noise
if(!all(ip.present)) message("add.protein: added ", nrow(aa)-sum(ip.present), " new protein(s) to thermo()$protein")
if(any(ip.present)) message("add.protein: replaced ", sum(ip.present), " existing protein(s) in thermo()$protein")
return(ip)
}
# Combine amino acid counts (sum, average, or weighted sum by abundance)
aasum <- function(aa, abundance = 1, average = FALSE, protein = NULL, organism = NULL) {
# Returns the sum of the amino acid counts in aa,
# multiplied by the abundances of the proteins
abundance <- rep(abundance, length.out = nrow(aa))
# Drop any NA rows or abundances
ina.aa <- is.na(aa$chains)
ina.ab <- is.na(abundance)
ina <- ina.aa | ina.ab
if(any(ina)) {
aa <- aa[!ina, ]
abundance <- abundance[!ina]
message("aasum: dropped ", sum(ina), " proteins with NA composition and/or abundance")
}
# Multiply
aa[, 6:25] <- aa[, 6:25] * abundance
# Sum
out <- aa[1, ]
out[, 5:25] <- colSums(aa[, 5:25])
# Average if told to do so
if(average) {
# Polypeptide chains by number of proteins, residues by frequency
out[, 5] <- out[, 5]/nrow(aa)
out[, 6:25] <- out[, 6:25]/sum(abundance)
}
# Add protein and organism names if given
if(!is.null(protein)) out$protein <- protein
if(!is.null(organism)) out$organism <- organism
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/add.protein.R
|
# CHNOSZ/affinity.R
# Calculate affinities of formation reactions
## If this file is interactively sourced, the following are also needed to provide unexported functions:
#source("util.affinity.R")
#source("util.units.R")
#source("util.character.R")
#source("util.list.R")
#source("subcrt.R")
#source("buffer.R")
#source("util.args.R")
#source("util.data.R")
#source("species.R")
#source("info.R")
#source("hkf.R")
#source("cgl.R")
affinity <- function(..., property = NULL, sout = NULL, exceed.Ttr = FALSE, exceed.rhomin = FALSE,
return.buffer = FALSE, return.sout = FALSE, balance = "PBB", iprotein = NULL, loga.protein = 0, transect = NULL) {
# ...: variables over which to calculate
# property: what type of energy
# (G.basis, G.species, logact.basis, logK, logQ, A)
# return.buffer: return buffered activities
# balance: balance protein buffers on PBB
# exceed.Ttr: extrapolate Gibbs energies
# of minerals beyond their T-limits?
# sout: provide a previously calculated output from subcrt
# iprotein: build these proteins from residues (speed optimization)
# History: 20061027 jmd version 1
# this is where energy.args() used to sit
# this is where energy() used to sit
# Argument recall 20190117
# If the first argument is the result from a previous affinity() calculation,
# just update the remaining arguments
args.orig <- list(...)
# We can only do anything with at least one argument
if(length(args.orig) > 0) {
if(identical(args.orig[[1]][1], list(fun = "affinity"))) {
aargs <- args.orig[[1]]$args
# We can only update arguments given after the first argument
if(length(args.orig) > 1) {
for(i in 2:length(args.orig)) {
if(names(args.orig)[i] %in% names(aargs)) aargs[[names(args.orig)[i]]] <- args.orig[[i]]
else aargs <- c(aargs, args.orig[i])
}
}
return(do.call(affinity, aargs))
}
}
# The argument list
args <- energy.args(args.orig, transect = transect)
args <- c(args, list(sout = sout, exceed.Ttr = exceed.Ttr, exceed.rhomin = exceed.rhomin))
# The user-defined species (including basis species, formed species, and proteins)
thermo <- get("thermo", CHNOSZ)
myspecies <- thermo$species
if(!is.null(property)) {
# The user just wants an energy property
buffer <- FALSE
args$what <- property
energy_result <- do.call("energy", args)
affinity_values <- energy_result$a
energy_sout <- energy_result$sout
} else {
# Affinity calculations
property <- args$what
# Protein stuff
# Note that affinities of the residues are modified by ionization calculations in energy(), not here
if(!is.null(iprotein)) {
# Check all proteins are available
if(any(is.na(iprotein))) stop("`iprotein` has some NA values")
if(!all(iprotein %in% 1:nrow(thermo$protein))) stop("some value(s) of `iprotein` are not rownumbers of thermo()$protein")
# Add protein residues to the species list
resnames <- c("H2O", aminoacids(3))
# Residue activities set to zero; account for protein activities later
resprot <- paste(resnames, "RESIDUE", sep = "_")
species(resprot, 0)
# Re-read thermo because the preceding command changed the species
thermo <- get("thermo", CHNOSZ)
ires <- match(resprot, thermo$species$name)
}
# Buffer stuff
buffer <- FALSE
# The buffered basis species are those that have non-numeric logact and are not listed in the arguments
which.basis.is.buffered <- which(!can.be.numeric(thermo$basis$logact) & !rownames(thermo$basis) %in% args$vars)
if(!is.null(thermo$basis) & length(which.basis.is.buffered) > 0) {
buffer <- TRUE
message('affinity: loading buffer species')
if(!is.null(thermo$species)) is.species <- 1:nrow(thermo$species) else is.species <- numeric()
# Load the species in the buffer and get their species number(s)
is.buffer <- buffer(logK = NULL)
# Re-read thermo because the preceding command changed the species
thermo <- get("thermo", CHNOSZ)
buffers <- names(is.buffer)
# Find species that are only in the buffer, not in the starting species list
is.only.buffer <- setdiff(unlist(is.buffer), is.species)
}
# Here we call 'energy'
energy_result <- do.call("energy", args)
affinity_values <- energy_result$a
energy_sout <- energy_result$sout
if(return.sout) return(energy_sout)
# More buffer stuff
if(buffer) {
args$what <- "logact.basis"
args$sout <- energy_sout
logact.basis.new <- logact.basis <- do.call("energy", args)$a
ibasis.new <- numeric()
for(k in 1:length(buffers)) {
ibasis <- which(as.character(thermo$basis$logact) == buffers[k])
# Calculate the logKs from the affinities
logK <- affinity_values
for(i in 1:length(logK)) {
logK[[i]] <- logK[[i]] + thermo$species$logact[i]
for(j in 1:length(logact.basis.new)) {
logK[[i]] <- logK[[i]] - logact.basis.new[[j]] * thermo$species[i, j]
}
}
buffer_result <- buffer(logK = logK, ibasis = ibasis, logact.basis = logact.basis.new, is.buffer = is.buffer[[k]], balance = balance)
for(j in 1:length(logact.basis.new)) if(j %in% ibasis) logact.basis.new[[j]] <- buffer_result[[2]][[j]]
# Calculation of the buffered activities' effect on chemical affinities
is.only.buffer.new <- is.only.buffer[is.only.buffer %in% is.buffer[[k]]]
for(i in 1:length(affinity_values)) {
if(i %in% is.only.buffer.new) next
for(j in 1:nrow(thermo$basis)) {
# Let's only do this for the basis species specified by the user even if others could be buffered
if(!j %in% which.basis.is.buffered) next
if(!j %in% ibasis) next
affinity_values[[i]] <- affinity_values[[i]] + (logact.basis.new[[j]] - logact.basis[[j]]) * thermo$species[i, j]
}
}
if(k == length(buffers) & return.buffer) {
logact.basis.new <- buffer_result[[2]]
ibasis.new <- c(ibasis.new, buffer_result[[1]])
} else ibasis.new <- c(ibasis.new, ibasis)
}
species(is.only.buffer, delete = TRUE)
if(length(is.only.buffer) > 0) affinity_values <- affinity_values[-is.only.buffer]
# To return the activities of buffered basis species
tb <- logact.basis.new[unique(ibasis.new)]
if(!is.null(ncol(tb[[1]]))) {
nd <- sum(dim(tb[[1]]) > 1)
# TODO: apply names for more than two dimensions
if(nd < 3) {
for(i in 1:length(tb)) {
#tb[[i]] <- as.data.frame(tb[[i]])
if(nd > 0) rownames(tb[[i]]) <-
seq(args$lims[[1]][1], args$lims[[1]][2], length.out = args$lims[[1]][3])
if(nd > 1) colnames(tb[[i]]) <-
seq(args$lims[[2]][1], args$lims[[2]][2], length.out = args$lims[[2]][3])
}
}
}
}
# More iprotein stuff
if(!is.null(iprotein)) {
# Fast protein calculations 20090331
# Function to calculate affinity of formation reactions from those of residues
loga.protein <- rep(loga.protein, length.out = length(iprotein))
protein.fun <- function(ip) {
tpext <- as.numeric(thermo$protein[iprotein[ip], 5:25])
return(Reduce("+", pprod(affinity_values[ires], tpext)) - loga.protein[ip])
}
# Use another level of indexing to let the function report on its progress
jprotein <- 1:length(iprotein)
protein.affinity <- palply("", jprotein, protein.fun)
## Update the species list
# We use negative values for ispecies to denote that
# they index thermo$protein and not thermo$species
ispecies <- -iprotein
# The current species list, containing the residues
resspecies <- thermo$species
# Now we can delete the residues from the species list
species(ires, delete = TRUE)
# State and protein names
state <- resspecies$state[1]
name <- paste(thermo$protein$protein[iprotein], thermo$protein$organism[iprotein], sep = "_")
# The numbers of basis species in formation reactions of the proteins
protbasis <- t(t((resspecies[ires, 1:nrow(thermo$basis)])) %*% t((thermo$protein[iprotein, 5:25])))
# Put them together
protspecies <- cbind(protbasis, data.frame(ispecies = ispecies, logact = loga.protein, state = state, name = name))
myspecies <- rbind(myspecies, protspecies)
rownames(myspecies) <- 1:nrow(myspecies)
## Update the affinity values
names(protein.affinity) <- ispecies
affinity_values <- c(affinity_values, protein.affinity)
affinity_values <- affinity_values[-ires]
}
}
# Put together return values
# Constant T and P, in Kelvin and bar
T <- args$T
P <- args$P
# The variable names and values
vars <- args$vars
vals <- args$vals
# If T or P is variable it's not constant;
# and set it to user's units
iT <- match("T", vars)
if(!is.na(iT)) {
T <- numeric()
vals[[iT]] <- outvert(vals[[iT]], "K")
}
iP <- match("P", vars)
if(!is.na(iP) > 0) {
P <- numeric()
vals[[iP]] <- outvert(vals[[iP]], "bar")
}
# Get Eh
iEh <- match("Eh", names(args.orig))
if(!is.na(iEh)) {
vars[[iEh]] <- "Eh"
# We have to reconstruct the values used because
# they got converted to log_a(e-) at an unknown temperature
Eharg <- args.orig[[iEh]]
if(length(Eharg) > 3) Ehvals <- Eharg
else if(length(Eharg) == 3) Ehvals <- seq(Eharg[1], Eharg[2], length.out = Eharg[3])
else if(length(Eharg) == 2) Ehvals <- seq(Eharg[1], Eharg[2], length.out = 256)
vals[[iEh]] <- Ehvals
}
# Get pe and pH
ipe <- match("pe", names(args.orig))
if(!is.na(ipe)) {
ie <- match("e-", names(args$lims))
vars[[ie]] <- "pe"
vals[[ie]] <- -args$vals[[ie]]
}
ipH <- match("pH", names(args.orig))
if(!is.na(ipH)) {
iH <- match("H+", names(args$lims))
vars[[iH]] <- "pH"
vals[[iH]] <- -args$vals[[iH]]
}
# Use the variable names for the vals list 20190415
names(vals) <- vars
# Content of return value depends on buffer request
if(return.buffer) return(c(tb, list(vars = vars, vals = vals)))
# For argument recall, include all arguments (except sout) in output 20190117
allargs <- c(args.orig, list(property = property, exceed.Ttr = exceed.Ttr, exceed.rhomin = exceed.rhomin,
return.buffer = return.buffer, balance = balance, iprotein = iprotein, loga.protein = loga.protein))
# Add IS value only if it given as an argument 20171101
# (even if its value is 0, the presence of IS will trigger diagram() to use "m" instead of "a" in axis labels)
iIS <- match("IS", names(args.orig))
if(!is.na(iIS)) out <- list(fun = "affinity", args = allargs, sout = energy_sout, property = property,
basis = thermo$basis, species = myspecies, T = T, P = P, IS = args$IS, vars = vars, vals = vals, values = affinity_values)
else out <- list(fun = "affinity", args = allargs, sout = energy_sout, property = property,
basis = thermo$basis, species = myspecies, T = T, P = P, vars = vars, vals = vals, values = affinity_values)
if(buffer) out <- c(out, list(buffer = tb))
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/affinity.R
|
# CHNOSZ/basis.R
# Set up the basis species of a thermodynamic system
basis <- function(species = NULL, state = NULL, logact = NULL, delete = FALSE, add = FALSE) {
# Get the current thermo and basis settings
thermo <- get("thermo", CHNOSZ)
oldbasis <- thermo$basis
# Delete the basis species if requested
if(delete | identical(species, "")) {
thermo$basis <- NULL
thermo$species <- NULL
assign("thermo", thermo, CHNOSZ)
return(invisible(oldbasis))
}
# Return the basis definition if requested
if(is.null(species)) return(oldbasis)
# From now on we need something to work with
if(length(species) == 0) stop("species argument is empty")
# Is the species one of the preset keywords?
if(species[1] %in% preset.basis()) return(preset.basis(species[1]))
# The species names/formulas have to be unique
if(!length(unique(species)) == length(species)) stop("species names are not unique")
# Processing 'state' and 'logact' arguments
# They should be same length as species
if(!is.null(state)) state <- rep(state, length.out = length(species))
if(!is.null(logact)) logact <- rep(logact, length.out = length(species))
# Results should be identical for
# basis(c("H2O", "CO2", "H2"), rep("aq", 3), c(0, -3, -3))
# basis(c("H2O", "CO2", "H2"), c(0, -3, -3), rep("aq", 3))
# First of all, do we have a third argument?
if(!is.null(logact)) {
# Does the 3rd argument look like states?
if(is.character(logact[1])) {
# Swap the arguments into their correct places
tmp <- logact
logact <- state
state <- tmp
}
} else {
# If the second argument is numeric, treat it like logacts
if(is.numeric(state[1])) {
logact <- state
state <- NULL
}
}
# Processing 'species' argument
# pH transformation
if("pH" %in% species) {
logact[species == "pH"] <- -logact[species == "pH"]
if(!is.null(logact)) species[species == "pH"] <- "H+"
}
# Eh and pe transformations
if("pe" %in% species) {
logact[species == "pe"] <- -logact[species == "pe"]
if(!is.null(logact)) species[species == "pe"] <- "e-"
}
if("Eh" %in% species) {
# 20090209 Should be careful with this conversion as it's only for 25 degC
# To be sure, just don't call species("Eh")
if(!is.null(logact)) logact[species == "Eh"] <- -convert(logact[species == "Eh"],"pe")
species[species == "Eh"] <- "e-"
}
# If all species are in the existing basis definition,
# *and* at least one of state or logact is not NULL,
# *and* add is not TRUE,
# then modify the states and/or logacts of the existing basis species
if(all(species %in% rownames(oldbasis)) | all(species %in% oldbasis$ispecies))
if(!is.null(state) | !is.null(logact))
if(!add)
return(mod.basis(species, state, logact))
# If we get to this point, we're making a new basis definition or adding to an existing one
# Use default logacts if they aren't present
if(is.null(logact)) logact <- rep(0, length(species))
# If species argument is numeric, it's species indices
if(is.numeric(species[1])) {
ispecies <- species
ina <- ispecies > nrow(thermo$OBIGT)
} else {
# Get species indices using states from the argument, or default states
if(!is.null(state)) ispecies <- suppressMessages(info(species, state))
else ispecies <- suppressMessages(info(species))
# Check if we got all the species
ina <- is.na(ispecies)
# info() returns a list if any of the species had multiple approximate matches
# We don't accept any of those
if(is.list(ispecies)) ina <- ina | sapply(ispecies,length) > 1
}
if(any(ina)) stop(paste("species not available:", paste(species[ina], "(", state[ina], ")", sep = "", collapse = " ")))
# Are we adding a species to an existing basis definition? 20220208
if(add) {
# Check that the species aren't already in the basis definition 20220208
ihave <- ispecies %in% oldbasis$ispecies
if(any(ihave)) {
if(length(ihave) == 1) stop(paste("this species is already in the basis definition:", species[ihave]))
stop(paste("these species are already in the basis definition:", paste(species[ihave], collapse = " ")))
}
# Append the new basis species
ispecies <- c(oldbasis$ispecies, ispecies)
logact <- c(oldbasis$logact, logact)
}
# Load new basis species
newthermo <- put.basis(ispecies, logact)
newbasis <- newthermo$basis
if(add) {
oldspecies <- thermo$species
# If there are formed species, we need to update their formation reactions
if(!is.null(oldspecies)) {
nold <- nrow(oldbasis)
nnew <- nrow(newbasis)
nspecies <- nrow(oldspecies)
# Stoichiometric coefficients have zero for the added basis species
stoich <- cbind(oldspecies[, 1:nold], matrix(0, nspecies, nnew - nold))
colnames(stoich) <- rownames(newbasis)
# Complete species data frame
newspecies <- cbind(stoich, oldspecies[, -(1:nold)])
newthermo$species <- newspecies
assign("thermo", newthermo, CHNOSZ)
}
} else {
# Remove the formed species since there's no guarantee the new basis includes all their elements
species(delete = TRUE)
}
newbasis
}
### Unexported functions ###
# To add the basis to thermo()$OBIGT
put.basis <- function(ispecies, logact = rep(NA, length(ispecies))) {
thermo <- get("thermo", CHNOSZ)
state <- thermo$OBIGT$state[ispecies]
# Make the basis matrix, revised 20120114
# Get the elemental makeup of each species,
# counting zero for any element that only appears in other species in the set
comp <- makeup(ispecies, count.zero = TRUE)
# Turn the list into a matrix
comp <- sapply(comp, c)
# Transpose to get put basis species on the rows
comp <- t(comp)
# Note, makeup(count.zero = TRUE) above gave elements (colnames) sorted alphabetically
# rownames identify the species
rownames(comp) <- as.character(thermo$OBIGT$formula[ispecies])
# FIXME: the electron doesn't look like a chemical formula
# This is needed for affinity() to understand a 'pe' or 'Eh' variable
if("(Z-1)" %in% rownames(comp)) rownames(comp)[rownames(comp) == "(Z-1)"] <- "e-"
# Now check it for validity of basis species
# The first test: matrix is square
if( nrow(comp) > ncol(comp) ) {
if("Z" %in% colnames(comp)) stop("the number of basis species is greater than the number of elements and charge")
else stop("the number of basis species is greater than the number of elements")
}
if( nrow(comp) < ncol(comp) ) {
if("Z" %in% colnames(comp)) stop("the number of basis species is less than the number of elements and charge")
else stop("the number of basis species is less than the number of elements")
}
# The second test: matrix is invertible
if(inherits(tryCatch(solve(comp), error = identity), "error"))
stop("singular stoichiometric matrix")
# Store the basis definition in thermo()$basis, including
# both numeric and character data, so we need to use a data frame
comp <- cbind(as.data.frame(comp), ispecies, logact, state, stringsAsFactors = FALSE)
# Ready to assign to the global thermo object
thermo$basis <- comp
assign("thermo", thermo, CHNOSZ)
}
# Modify the states or logact values in the existing basis definition
mod.basis <- function(species, state = NULL, logact = NULL) {
thermo <- get("thermo", CHNOSZ)
# The basis must be defined
if(is.null(thermo$basis)) stop("basis is not defined")
# Loop over each species to modify
for(i in 1:length(species)) {
# Which basis species are we looking at?
if(is.numeric(species)) {
ib <- match(species[i], thermo$basis$ispecies)
if(is.na(ib)) stop(paste(species[i],"is not a species index of one of the basis species"))
} else {
ib <- match(species[i], rownames(thermo$basis))
if(is.na(ib)) stop(paste(species[i],"is not a formula of one of the basis species"))
}
# First modify the state
if(!is.null(state)) {
if(state[i] %in% thermo$buffer$name) {
# This is the name of a buffer
ibuff <- which(as.character(thermo$buffer$name) == state[i])
# Check that each species in the buffer is compositionally compatible with the basis definition
for(k in 1:length(ibuff)) {
ispecies <- suppressMessages(info(as.character(thermo$buffer$species)[ibuff[k]],
as.character(thermo$buffer$state)[ibuff[k]]))
bufmakeup <- makeup(ispecies)
inbasis <- names(bufmakeup) %in% colnames(basis())
if(FALSE %in% inbasis) {
stop(paste("the elements '",c2s(names(bufmakeup)[!inbasis]),
"' of species '",thermo$buffer$species[ibuff[k]],"' in buffer '",state[i],
"' are not in the basis\n",sep = ""))
}
}
thermo$basis$logact[ib] <- state[i]
} else {
# First, look for a species with the same _name_ in the requested state
myname <- thermo$OBIGT$name[thermo$basis$ispecies[ib]]
ispecies <- suppressMessages(info(myname, state[i]))
if(is.na(ispecies) | is.list(ispecies)) {
# If that failed, look for a species with the same _formula_ in the requested state
myformula <- thermo$OBIGT$formula[thermo$basis$ispecies[ib]]
ispecies <- suppressMessages(info(myformula, state[i]))
if(is.na(ispecies) | is.list(ispecies)) {
# If that failed, we're out of luck
if(myname == myformula) nametxt <- myname else nametxt <- paste(myname, "or", myformula)
stop(paste0("state or buffer '", state[i], "' not found for ", nametxt, "\n"))
}
}
thermo$basis$ispecies[ib] <- ispecies
thermo$basis$state[ib] <- state[i]
}
}
# Then modify the logact
if(!is.null(logact)) {
# Allow this to be non-numeric in case we're called by swap.basis() while a buffer is active 20181109
if(can.be.numeric(logact[i])) thermo$basis$logact[ib] <- as.numeric(logact[i])
else thermo$basis$logact[ib] <- logact[i]
}
# Assign the result to the CHNOSZ environment
assign("thermo", thermo, CHNOSZ)
}
return(thermo$basis)
}
# To load a preset basis definition by keyword
preset.basis <- function(key = NULL) {
# The available keywords
basis.key <- c("CHNOS", "CHNOS+", "CHNOSe", "CHNOPS+", "CHNOPSe", "MgCHNOPS+", "MgCHNOPSe", "FeCHNOS", "FeCHNOS+", "QEC4", "QEC", "QEC+", "QCa", "QCa+")
# Just list the keywords if none is specified
if(is.null(key)) return(basis.key)
# Delete any previous basis definition
basis("")
# Match the keyword to the available ones
ibase <- match(key, basis.key)
if(is.na(ibase)) stop(paste(key, "is not a keyword for preset basis species"))
if(ibase == 1) species <- c("CO2", "H2O", "NH3", "H2S", "oxygen")
else if(ibase == 2) species <- c("CO2", "H2O", "NH3", "H2S", "oxygen", "H+")
else if(ibase == 3) species <- c("CO2", "H2O", "NH3", "H2S", "e-", "H+")
else if(ibase == 4) species <- c("CO2", "H2O", "NH3", "H3PO4", "H2S", "oxygen", "H+")
else if(ibase == 5) species <- c("CO2", "H2O", "NH3", "H3PO4", "H2S", "e-", "H+")
else if(ibase == 6) species <- c("Mg+2", "CO2", "H2O", "NH3", "H3PO4", "H2S", "oxygen", "H+")
else if(ibase == 7) species <- c("Mg+2", "CO2", "H2O", "NH3", "H3PO4", "H2S", "e-", "H+")
else if(ibase == 8) species <- c("Fe2O3", "CO2", "H2O", "NH3", "H2S", "oxygen")
else if(ibase == 9) species <- c("Fe2O3", "CO2", "H2O", "NH3", "H2S", "oxygen", "H+")
else if(ibase %in% c(10, 11)) species <- c("glutamine", "glutamic acid", "cysteine", "H2O", "oxygen")
else if(ibase == 12) species <- c("glutamine", "glutamic acid", "cysteine", "H2O", "oxygen", "H+")
else if(ibase == 13) species <- c("glutamine", "cysteine", "acetic acid", "H2O", "oxygen")
else if(ibase == 14) species <- c("glutamine", "cysteine", "acetic acid", "H2O", "oxygen", "H+")
# Get the preset logact
logact <- preset.logact(species)
# For QEC4, we use logact = -4 for the amino acids
if(key == "QEC4") logact[1:3] <- -4
# Load the species and return the result
return(basis(species, logact))
}
# Logarithms of activities for preset basis definitions
preset.logact <- function(species) {
bases <- c("H2O", "CO2", "NH3", "H2S", "oxygen", "H+", "e-", "Fe2O3",
"glutamine", "glutamic acid", "cysteine")
# Values for QEC amino acids from Dick, 2017 (http://doi.org/10.1101/097667)
logact <- c(0, -3, -4, -7, -80, -7, -7, 0,
-3.2, -4.5, -3.6)
ibase <- match(species, bases)
logact <- logact[ibase]
# Any unmatched species gets a logarithm of activity of -3
logact[is.na(logact)] <- -3
return(logact)
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/basis.R
|
# CHNOSZ/buffer.R
# Calculate chemical activities of buffered species
# 20061102 jmd
mod.buffer <- function(name, species = NULL, state = "cr", logact = 0) {
# 20071102 add or change a buffer system
thermo <- get("thermo", CHNOSZ)
if(is.null(species)) {
iname <- which(name == thermo$buffer$name)
if(length(iname) > 0) species <- thermo$buffer$species[iname]
else species <- character()
}
ls <- length(species)
if(ls < length(name) | ls < length(state) | ls < length(logact))
stop('species must be at least as long as the other arguments')
if(length(name) != ls) name <- rep(name, length.out = ls)
add <- TRUE
if(TRUE %in% (name %in% thermo$buffer$name)) {
add <- FALSE
imod <- which(thermo$buffer$name %in% name & thermo$buffer$species %in% species)
if(length(imod)>0) {
if(state[1] == '') {
thermo$buffer <- thermo$buffer[-imod, ]
assign("thermo", thermo, CHNOSZ)
message(paste('mod.buffer: removed ', c2s(species), ' in ', c2s(unique(name)), ' buffer', sep = ''))
} else {
if(missing(state)) state <- thermo$buffer$state[imod]
if(missing(logact)) logact <- thermo$buffer$logact[imod]
if(length(state) != ls) state <- rep(state,length.out = ls)
if(length(logact) != ls) logact <- rep(logact,length.out = ls)
state.old <- thermo$buffer$state[imod]
logact.old <- thermo$buffer$logact[imod]
thermo$buffer$state[imod] <- state
thermo$buffer$logact[imod] <- logact
assign("thermo", thermo, CHNOSZ)
if(identical(state.old, state) & identical(logact.old, logact)) {
message(paste('mod.buffer: nothing changed for ', c2s(species), ' in ', c2s(unique(name)), ' buffer', sep = ''))
} else {
message(paste('mod.buffer: changed state and/or logact of ', c2s(species), ' in ', c2s(unique(name)), ' buffer', sep = ''))
}
}
} else {
add <- TRUE
}
}
if(add) {
if(state[1] == '') state <- rep(thermo$opt$state, length.out = ls)
t <- data.frame(name = name, species = species, state = state, logact = logact)
thermo$buffer <- rbind(thermo$buffer, t)
assign("thermo", thermo, CHNOSZ)
message(paste('mod.buffer: added',c2s(unique(name))))
}
return(invisible(thermo$buffer[thermo$buffer$name %in% name, ]))
}
### Unexported functions ###
buffer <- function(logK = NULL, ibasis = NULL, logact.basis = NULL, is.buffer = NULL, balance = 'PBB') {
thermo <- get("thermo", CHNOSZ)
# If logK is NULL load the buffer species,
# otherwise perform buffer calculations
if(is.null(logK)) {
# Load the buffer species
buffers <- unique(as.character(thermo$basis$logact)[!can.be.numeric(as.character(thermo$basis$logact))])
ispecies.new <- list()
for(k in 1:length(buffers)) {
ibasis <- which(thermo$basis$logact == buffers[k])
ispecies <- numeric()
for(i in 1:length(ibasis)) {
ib <- as.character(thermo$buffer$name) == as.character(thermo$basis$logact[ibasis[i]])
species <- as.character(thermo$buffer$species)[ib]
state <- as.character(thermo$buffer$state)[ib]
#ibuff <- info(species,state,quiet = TRUE)
ispecies <- c(ispecies, species(species, state, index.return = TRUE, add = TRUE))
}
ispecies.new <- c(ispecies.new, list(ispecies))
# Make sure to set the activities
species(ispecies, thermo$buffer$logact[ib])
}
names(ispecies.new) <- buffers
return(ispecies.new)
}
# Sometimes (e.g. PPM) the buffer species are identified multiple
# times, causing problems for square matrices
# Make the species appear singly
is.buffer <- unique(is.buffer)
bufbasis <- species.basis(thermo$species$ispecies[is.buffer])
bufname <- thermo$basis$logact[ibasis[1]]
basisnames <- rownames(thermo$basis)
are.proteins <- grep('_', as.character(thermo$species$name[is.buffer]))
if((length(are.proteins) > 0 & balance == 'PBB') | balance == 1) {
if(balance == 1) {
basisnames <- c('product', basisnames)
nb <- rep(1, nrow(bufbasis))
bufbasis <- cbind(data.frame(product = nb), bufbasis)
} else {
basisnames <- c('PBB', basisnames)
# Prepend a PBB column to bufbasis and increment ibasis by 1
nb <- as.numeric(protein.length(thermo$species$name[is.buffer]))
bufbasis <- cbind(data.frame(PBB = nb), bufbasis)
}
ibasis <- ibasis + 1
# Make logact.basis long enough
tl <- length(logact.basis)
logact.basis[[tl+1]] <- logact.basis[[tl]]
# Rotate the entries so that the new one is first
ilb <- c(tl+1, 1:tl)
logact.basis <- logact.basis[ilb]
}
# Say hello
#message(paste("buffer: '",bufname,"', of ",length(is.buffer),' species, ',length(ibasis),' activity(s) requested.',sep = ''))
ibasisrequested <- ibasis
# Check and maybe add to the number of buffered activities
ibasisadded <- numeric()
if( (length(ibasis)+1) != length(is.buffer) & length(is.buffer) > 1) {
# Try to add buffered activities the user didn't specify
# (e.g. H2S in PPM buffer if only H2 was requested)
for(i in 1:(length(is.buffer) - (length(ibasis)+1))) {
newbasis <- NULL
# We want to avoid any basis species that might be used as the conservant
# look for additional activities to buffer ... do columns in reverse
for(j in ncol(bufbasis):1) {
if(j %in% ibasis) next
if(FALSE %in% (bufbasis[,j] == 0)) {
newbasis <- j
break
}
}
if(!is.null(newbasis)) {
ibasis <- c(ibasis, newbasis)
ibasisadded <- c(ibasisadded, newbasis)
} else {
stop('can not find enough buffered basis species for ', thermo$basis$logact[ibasis[1]], '.', sep = '')
}
}
}
# And the leftovers
#xx <- as.data.frame(bufbasis[,-ibasis])
# The final buffered activity: the would-be conserved component
newbasis <- NULL
if(length(is.buffer) > 1) {
# First try to get one that is present in all species
for(i in ncol(bufbasis):1) {
if(i %in% ibasis) next
if(!TRUE %in% (bufbasis[, i] == 0)) newbasis <- i
}
# Or look for one that is present at all
if(is.null(newbasis)) for(i in ncol(bufbasis):1) {
if(i %in% ibasis) next
if(FALSE %in% (bufbasis[, i] == 0)) newbasis <- i
}
if(!is.null(newbasis)) {
ibasis <- c(ibasis,newbasis)
#message(paste('buffer: the conserved activity is ', basisnames[newbasis], '.', sep = ''))
#thermo$basis$logact[newbasis] <<- thermo$basis$logact[ibasis[1]]
}
else stop('no conserved activity found in your buffer (not enough basis species?)!')
}
if(is.null(newbasis)) context <- '' else context <- paste(', ', basisnames[newbasis], ' (conserved)', sep = '')
reqtext <- paste(c2s(basisnames[ibasisrequested]), ' (active)', sep = '')
if(length(ibasisadded) == 0) addtext <- '' else addtext <- paste(', ', c2s(basisnames[ibasisadded]), sep = '')
message(paste("buffer: '", bufname, "' for activity of ", reqtext, addtext, context, sep = ""))
# There could still be stuff here (over-defined system?)
xx <- bufbasis[, -ibasis, drop = FALSE]
# For the case when all activities are buffered
if(ncol(xx) == 0) xx <- data.frame(xx = 0)
# Our stoichiometric matrix - should be square
A <- as.data.frame(bufbasis[,ibasis])
# Determine conservation coefficients
# Values for the known vector
B <- list()
for(i in 1:length(is.buffer)) {
b <- -logK[[is.buffer[i]]] + thermo$species$logact[is.buffer[i]]
if(ncol(xx) > 0) {
if(is.list(xx)) xxx <- xx[[1]] else xxx <- xx
if(ncol(xx) == 1 & identical(as.numeric(xxx), 0)) {
# Do nothing
} else {
for(j in 1:ncol(xx)) {
bs <- xx[i, j] * logact.basis[[match(colnames(xx)[j], basisnames)]]
if(!is.matrix(bs)) bs <- matrix(bs, byrow = TRUE, nrow = nrow(as.data.frame(logact.basis[[1]])))
if(ncol(bs) == 1) b <- matrix(b)
b <- b - bs
}
}
}
# Force this to be matrix so indexing works at a single point (no variables defined in affinity()) 20201102
B[[i]] <- as.matrix(b)
}
# A place to put the results
X <- rep(B[1],length(ibasis))
for(i in 1:nrow(B[[1]])) {
for(j in 1:ncol(B[[1]])) {
b <- numeric()
for(k in 1:length(B)) b <- c(b, B[[k]][i, j])
AAA <- A
# solve for the activities in the buffer
t <- solve(AAA, b)
for(k in 1:length(ibasis))
X[[k]][i, j] <- t[k]
}
}
# Store results
for(i in 1:length(ibasis)) {
if(ncol(X[[i]]) == 1) X[[i]] <- as.numeric(X[[i]])
else if(nrow(X[[i]]) == 1) X[[i]] <- as.matrix(X[[i]], nrow = 1)
logact.basis[[ibasis[i]]] <- X[[i]]
}
names(logact.basis) <- basisnames
return(list(ibasis = ibasis, logact.basis = logact.basis))
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/buffer.R
|
# CHNOSZ/cgl.R
# Calculate standard thermodynamic properties of non-aqueous species
# 20060729 jmd
cgl <- function(property = NULL, parameters = NULL, T = 298.15, P = 1) {
# Calculate properties of crystalline, liquid (except H2O) and gas species
Tr <- 298.15
Pr <- 1
# The number of T, P conditions
ncond <- max(c(length(T), length(P)))
# Initialize output list
out <- list()
# Loop over each species
for(k in 1:nrow(parameters)) {
# The parameters for *this* species
PAR <- parameters[k, ]
if(PAR$model == "Berman") {
# Use Berman equations (parameters not in thermo()$OBIGT)
properties <- Berman(PAR$name, T = T, P = P)
iprop <- match(property, colnames(properties))
values <- properties[, iprop, drop = FALSE]
} else {
# In CHNOSZ, we have
# 1 cm^3 bar --> convert(1, "calories") == 0.02390057 cal
# but REAC92D.F in SUPCRT92 uses
cm3bar_to_cal <- 0.023901488 # cal
cm3bar_to_J <- convert(cm3bar_to_cal, "J")
# Start with NA values
values <- data.frame(matrix(NA, ncol = length(property), nrow=ncond))
colnames(values) <- property
# A test for availability of heat capacity coefficients (a, b, c, d, e, f)
# based on the column assignments in thermo()$OBIGT
if(any(!is.na(PAR[, 15:20]))) {
# We have at least one of the heat capacity coefficients;
# zero out any NA's in the rest (leave lambda and T of transition (columns 19-20) alone)
PAR[, 15:20][, is.na(PAR[, 15:20])] <- 0
# calculate the heat capacity and its integrals
Cp <- PAR$a + PAR$b*T + PAR$c*T^-2 + PAR$d*T^-0.5 + PAR$e*T^2 + PAR$f*T^PAR$lambda
intCpdT <- PAR$a*(T - Tr) + PAR$b*(T^2 - Tr^2)/2 + PAR$c*(1/T - 1/Tr)/-1 + PAR$d*(T^0.5 - Tr^0.5)/0.5 + PAR$e*(T^3-Tr^3)/3
intCpdlnT <- PAR$a*log(T / Tr) + PAR$b*(T - Tr) + PAR$c*(T^-2 - Tr^-2)/-2 + PAR$d*(T^-0.5 - Tr^-0.5)/-0.5 + PAR$e*(T^2 - Tr^2)/2
# Do we also have the lambda parameter (Cp term with adjustable exponent on T)?
if(!is.na(PAR$lambda) & !identical(PAR$lambda, 0)) {
# Equations for lambda adapted from Helgeson et al., 1998 (doi:10.1016/S0016-7037(97)00219-6)
if(PAR$lambda == -1) intCpdT <- intCpdT + PAR$f*log(T/Tr)
else intCpdT <- intCpdT - PAR$f*( T^(PAR$lambda + 1) - Tr^(PAR$lambda + 1) ) / (PAR$lambda + 1)
intCpdlnT <- intCpdlnT + PAR$f*(T^PAR$lambda - Tr^PAR$lambda) / PAR$lambda
}
} else {
# Use constant heat capacity if the coefficients are not available
Cp <- PAR$Cp
intCpdT <- PAR$Cp*(T - Tr)
intCpdlnT <- PAR$Cp*log(T / Tr)
# In case Cp is listed as NA, set the integrals to 0 at Tr
intCpdT[T == Tr] <- 0
intCpdlnT[T == Tr] <- 0
}
# Volume and its integrals
if(PAR$name %in% c("quartz", "coesite")) {
# Volume calculations for quartz and coesite
qtz <- quartz_coesite(PAR, T, P)
V <- qtz$V
intVdP <- qtz$intVdP
intdVdTdP <- qtz$intdVdTdP
} else {
# For other minerals, volume is constant (Helgeson et al., 1978)
V <- rep(PAR$V, ncond)
# If the volume is NA, set its integrals to zero
if(is.na(PAR$V)) intVdP <- intdVdTdP <- numeric(ncond)
else {
intVdP <- PAR$V*(P - Pr) * cm3bar_to_J
intdVdTdP <- 0
}
}
# Get the values of each of the requested thermodynamic properties
for(i in 1:length(property)) {
if(property[i] == "Cp") values[, i] <- Cp
if(property[i] == "V") values[, i] <- V
if(property[i] == "E") values[, i] <- rep(NA, ncond)
if(property[i] == "kT") values[, i] <- rep(NA, ncond)
if(property[i] == "G") {
# Calculate S * (T - Tr), but set it to 0 at Tr (in case S is NA)
Sterm <- PAR$S*(T - Tr)
Sterm[T==Tr] <- 0
values[, i] <- PAR$G - Sterm + intCpdT - T*intCpdlnT + intVdP
}
if(property[i] == "H") values[, i] <- PAR$H + intCpdT + intVdP - T*intdVdTdP
if(property[i] == "S") values[, i] <- PAR$S + intCpdlnT - intdVdTdP
}
} # End calculations using parameters from thermo()$OBIGT
out[[k]] <- values
} # End loop over species
return(out)
}
### Unexported function ###
# Calculate GHS and V corrections for quartz and coesite 20170929
# (these are the only mineral phases for which SUPCRT92 uses an inconstant volume)
quartz_coesite <- function(PAR, T, P) {
# The corrections are 0 for anything other than quartz and coesite
if(!PAR$name %in% c("quartz", "coesite")) return(list(G = 0, H = 0, S = 0, V = 0))
ncond <- max(c(length(T), length(P)))
# Tr, Pr and TtPr (transition temperature at Pr)
Pr <- 1 # bar
Tr <- 298.15 # K
TtPr <- 848 # K
# Constants from SUP92D.f
aa <- 549.824
ba <- 0.65995
ca <- -0.4973e-4
VPtTta <- 23.348
VPrTtb <- 23.72
Stran <- 0.342
# Constants from REAC92D.f
VPrTra <- 22.688 # VPrTr(a-quartz)
Vdiff <- 2.047 # VPrTr(a-quartz) - VPrTr(coesite)
k <- 38.5 # dPdTtr(a/b-quartz)
#k <- 38.45834 # calculated in CHNOSZ: dPdTtr(info("quartz"))
# Code adapted from REAC92D.f
qphase <- gsub("cr", "", PAR$state)
if(qphase == 2) {
Pstar <- P
Sstar <- rep(0, ncond)
V <- rep(VPrTtb, ncond)
} else {
Pstar <- Pr + k * (T - TtPr)
Sstar <- rep(Stran, ncond)
V <- VPrTra + ca*(P-Pr) + (VPtTta - VPrTra - ca*(P-Pr))*(T-Tr) / (TtPr + (P-Pr)/k - Tr)
}
Pstar[T < TtPr] <- Pr
Sstar[T < TtPr] <- 0
if(PAR$name == "coesite") {
VPrTra <- VPrTra - Vdiff
VPrTtb <- VPrTtb - Vdiff
V <- V - Vdiff
}
cm3bar_to_cal <- 0.023901488
GVterm <- cm3bar_to_cal * (VPrTra * (P - Pstar) + VPrTtb * (Pstar - Pr) -
0.5 * ca * (2 * Pr * (P - Pstar) - (P^2 - Pstar^2)) -
ca * k * (T - Tr) * (P - Pstar) +
k * (ba + aa * ca * k) * (T - Tr) * log((aa + P/k) / (aa + Pstar/k)))
SVterm <- cm3bar_to_cal * (-k * (ba + aa * ca * k) *
log((aa + P/k) / (aa + Pstar/k)) + ca * k * (P - Pstar)) - Sstar
# Note the minus sign on "SVterm" in order that intdVdTdP has the correct sign
list(intVdP = convert(GVterm, "J"), intdVdTdP = convert(-SVterm, "J"), V = V)
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/cgl.R
|
# CHNOSZ/diagram.R
# Plot equilibrium chemical activity and predominance diagrams
# 20061023 jmd v1
# 20120927 work with output from either equil() or affinity(),
# gather plotvals independently of plot parameters (including nd),
# single return statement
## If this file is interactively sourced, the following are also needed to provide unexported functions:
#source("equilibrate.R")
#source("util.plot.R")
#source("util.character.R")
#source("util.misc.R")
diagram <- function(
# Species affinities or activities
eout,
# Type of plot
type = "auto", alpha = FALSE, normalize = FALSE, as.residue = FALSE, balance = NULL,
groups = as.list(1:length(eout$values)), xrange = NULL,
# Figure size and sides for axis tick marks
mar = NULL, yline = par("mgp")[1]+0.3, side = 1:4,
# Axis limits and labels
ylog = TRUE, xlim = NULL, ylim = NULL, xlab = NULL, ylab = NULL,
# Sizes
cex = par("cex"), cex.names = 1, cex.axis = par("cex"),
# Line styles
lty = NULL, lty.cr = NULL, lty.aq = NULL, lwd = par("lwd"), dotted = NULL,
spline.method = NULL, contour.method = "edge", levels = NULL,
# Colors
col = par("col"), col.names = par("col"), fill = NULL,
fill.NA = "gray80", limit.water = NULL,
# Field and line labels
names = NULL, format.names = TRUE, bold = FALSE, italic = FALSE,
font = par("font"), family = par("family"), adj = 0.5, dx = 0, dy = 0, srt = 0,
min.area = 0,
# Title and legend
main = NULL, legend.x = NA,
# Plotting controls
add = FALSE, plot.it = TRUE, tplot = TRUE, ...
) {
### Argument handling ###
## Check that eout is a valid object
efun <- eout$fun
if(length(efun) == 0) efun <- ""
if(!(efun %in% c("affinity", "rank.affinity", "equilibrate") | grepl("solubilit", efun)))
stop("'eout' is not the output from one of these functions: affinity, rank.affinity, equilibrate, or solubility")
# For solubilities(), default type is loga.balance 20210303
if(grepl("solubilities", efun) & missing(type)) type <- "loga.balance"
# Check balance argument for rank.affinity() 20220416
if(efun == "rank.affinity") {
if(!identical(balance, 1)) {
if(!is.null(balance)) stop("balance = 1 or NULL is required for plotting output of rank.affinity()")
if(is.null(balance)) message("diagram: setting balance = 1 for plotting output of rank.affinity()")
balance <- 1
}
}
## 'type' can be:
# 'auto' - property from affinity() (1D) or maximum affinity (affinity 2D) (aout) or loga.equil (eout)
# 'loga.equil' - equilibrium activities of species of interest (eout)
# name of basis species - equilibrium activity of a basis species (aout)
# 'saturation' - affinity=0 line for each species (2D)
# 'loga.balance' - activity of balanced basis species (eout from solubility() or solubilities())
eout.is.aout <- FALSE
plot.loga.basis <- FALSE
if(type %in% c("auto", "saturation")) {
if(!"loga.equil" %in% names(eout)) {
eout.is.aout <- TRUE
# Get the balancing coefficients
if(type == "auto") {
bal <- balance(eout, balance)
n.balance <- bal$n.balance
balance <- bal$balance
} else n.balance <- rep(1, length(eout$values))
# In case all coefficients are negative (for bimetal() examples) 20200713
# e.g. H+ for minerals with basis(c("Fe+2", "Cu+", "hydrogen sulfide", "oxygen", "H2O", "H+"))
if(all(n.balance < 0)) n.balance <- -n.balance
}
} else if(type %in% rownames(eout$basis)) {
# To calculate the loga of basis species at equilibrium
if(!missing(groups)) stop("can't plot equilibrium activities of basis species for grouped species")
if(isTRUE(alpha) | is.character(alpha)) stop("equilibrium activities of basis species not available with alpha = TRUE")
plot.loga.basis <- TRUE
} else if(type == "loga.equil" & !"loga.equil" %in% names(eout)) stop("'eout' is not the output from equil()")
else if(!type %in% c("loga.equil", "loga.balance")) stop(type, " is not a valid diagram type")
## Consider a different number of species if we're grouping them together
ngroups <- length(groups)
## Keep the values we plot in one place so they can be modified, plotted and eventually returned
# Unless something happens below, we'll plot the loga.equil from equilibrate()
plotvals <- eout$loga.equil
plotvar <- "loga.equil"
## Handle loga.balance here (i.e. solubility calculations)
if(type == "loga.balance") {
plotvals <- list(eout$loga.balance)
plotvar <- "loga.balance"
}
## Modify default arguments with add = TRUE
if(add) {
# Change missing fill.NA to transparent
if(missing(fill.NA)) fill.NA <- "transparent"
# Change missing limit.water to FALSE 20200819
if(missing(limit.water)) limit.water <- FALSE
}
## Number of dimensions (T, P or chemical potentials that are varied)
# length(eout$vars) - the number of variables = the maximum number of dimensions
# length(dim(eout$values[[1]])) - nd = 1 if it was a transect along multiple variables
nd <- min(length(eout$vars), length(dim(eout$values[[1]])))
## Deal with output from affinity()
if(eout.is.aout) {
# Plot property from affinity(), divided by balancing coefficients
plotvals <- lapply(1:length(eout$values), function(i) {
# We divide by the balancing coefficients if we're working with affinities
# This is not normalizing the formulas! it's balancing the reactions...
# normalizing the formulas is done below
eout$values[[i]] / n.balance[i]
})
names(plotvals) <- names(eout$values)
plotvar <- eout$property
if(efun == "rank.affinity") {
plotvar <- "rank.affinity"
message(paste("diagram: plotting average affinity ranking for", length(plotvals), "groups"))
} else if(plotvar == "A") {
# We change 'A' to 'A/(2.303RT)' so the axis label is made correctly
# 20171027 use parentheses to avoid ambiguity about order of operations
plotvar <- "A/(2.303RT)"
if(nd == 2 & type == "auto") message("diagram: using maximum affinity method for 2-D diagram")
else if(nd == 2 & type == "saturation") message("diagram: plotting saturation lines for 2-D diagram")
else message("diagram: plotting A/(2.303RT) / n.balance")
} else message(paste("diagram: plotting", plotvar, " / n.balance"))
}
## Use molality instead of activity if the affinity calculation includes ionic strength 20171101
molality <- "IS" %in% names(eout)
## When can normalize and as.residue be used
if(normalize | as.residue) {
if(normalize & as.residue) stop("'normalize' and 'as.residue' can not both be TRUE")
if(!eout.is.aout) stop("'normalize' or 'as.residue' can be TRUE only if 'eout' is the output from affinity()")
if(nd != 2) stop("'normalize' or 'as.residue' can be TRUE only for a 2-D (predominance) diagram")
if(normalize) message("diagram: using 'normalize' in calculation of predominant species")
else message("diagram: using 'as.residue' in calculation of predominant species")
}
## Sum affinities or activities of species together in groups 20090524
# Use lapply/Reduce 20120927
if(!missing(groups)) {
# Loop over the groups
plotvals <- lapply(groups, function(ispecies) {
# Remove the logarithms ...
if(eout.is.aout) act <- lapply(plotvals[ispecies], function(x) 10^x)
# and, for activity, multiply by n.balance 20170207
else act <- lapply(seq_along(ispecies), function(i) eout$n.balance[ispecies[i]] * 10^plotvals[[ispecies[i]]])
# then, sum the activities
return(Reduce("+", act))
})
# Restore the logarithms
plotvals <- lapply(plotvals, function(x) log10(x))
# Combine the balancing coefficients for calculations using affinity
if(eout.is.aout) n.balance <- sapply(groups, function(ispecies) sum(n.balance[ispecies]))
}
## Calculate the equilibrium logarithm of activity of a basis species
## (such that affinities of formation reactions are zero)
if(plot.loga.basis) {
ibasis <- match(type, rownames(eout$basis))
# The logarithm of activity used in the affinity calculation
is.loga.basis <- can.be.numeric(eout$basis$logact[ibasis])
if(!is.loga.basis) stop(paste("the logarithm of activity for basis species", type, "is not numeric - was a buffer selected?"))
loga.basis <- as.numeric(eout$basis$logact[ibasis])
# The reaction coefficients for this basis species
nu.basis <- eout$species[, ibasis]
# The logarithm of activity where affinity = 0
plotvals <- lapply(1:length(eout$values), function(x) {
# NB. eout$values is a strange name for affinity ... should be named something like eout$affinity ...
loga.basis - eout$values[[x]]/nu.basis[x]
})
plotvar <- type
}
## alpha: plot fractional degree of formation
# Scale the activities to sum = 1 ... 20091017
# Allow scaling by balancing component 20171008
if(isTRUE(alpha) | is.character(alpha)) {
# Remove the logarithms
act <- lapply(plotvals, function(x) 10^x)
if(identical(alpha, "balance")) for(i in 1:length(act)) act[[i]] <- act[[i]] * eout$n.balance[i]
# Sum the activities
sumact <- Reduce("+", act)
# Divide activities by the total
alpha <- lapply(act, function(x) x/sumact)
plotvals <- alpha
plotvar <- "alpha"
}
## Identify predominant species
predominant <- NA
H2O.predominant <- NULL
if(plotvar %in% c("loga.equil", "alpha", "A/(2.303RT)", "rank.affinity") & type != "saturation") {
pv <- plotvals
# Some additional steps for affinity values, but not for equilibrated activities
if(eout.is.aout) {
for(i in 1:length(pv)) {
# TODO: The equilibrium.Rmd vignette shows predominance diagrams using
# 'normalize' and 'as.residue' settings that are consistent with equilibrate(),
# but what is the derivation of these equations?
if(normalize) pv[[i]] <- (pv[[i]] + eout$species$logact[i] / n.balance[i]) - log10(n.balance[i])
else if(as.residue) pv[[i]] <- pv[[i]] + eout$species$logact[i] / n.balance[i]
}
}
if(grepl("solubilities", efun)) {
# For solubilites of multiple minerals, find the minimum value (most stable mineral) 20210321
mypv <- Map("-", pv)
predominant <- which.pmax(mypv)
} else {
# For all other diagrams, we want the maximum value (i.e. maximum affinity method)
predominant <- which.pmax(pv)
}
# Show water stability region
if((is.null(limit.water) | isTRUE(limit.water)) & nd == 2) {
wl <- water.lines(eout, plot.it = FALSE)
# Proceed if water.lines produced calculations for this plot
if(!identical(wl, NA)) {
H2O.predominant <- predominant
# For each x-point, find the y-values that are outside the water stability limits
for(i in seq_along(wl$xpoints)) {
ymin <- min(c(wl$y.oxidation[i], wl$y.reduction[i]))
ymax <- max(c(wl$y.oxidation[i], wl$y.reduction[i]))
if(!wl$swapped) {
# The actual calculation
iNA <- eout$vals[[2]] < ymin | eout$vals[[2]] > ymax
# Assign NA to the predominance matrix
H2O.predominant[i, iNA] <- NA
} else {
# As above, but x- and y-axes are swapped
iNA <- eout$vals[[1]] < ymin | eout$vals[[1]] > ymax
H2O.predominant[iNA, i] <- NA
}
}
}
}
}
## Create some names for lines/fields if they are missing
is.pname <- FALSE
onames <- names
if(identical(names, FALSE) | identical(names, NA)) names <- ""
else if(!is.character(names)) {
# Properties of basis species or reactions?
if(eout$property %in% c("G.basis", "logact.basis")) names <- rownames(eout$basis)
else {
if(!missing(groups)) {
if(is.null(names(groups))) names <- paste("group", 1:length(groups), sep = "")
else names <- names(groups)
}
else names <- as.character(eout$species$name)
# Remove non-unique organism or protein names
if(all(grepl("_", names))) {
is.pname <- TRUE
# Everything before the underscore (the protein)
pname <- gsub("_.*$", "", names)
# Everything after the underscore (the organism)
oname <- gsub("^.*_", "", names)
# If the pname or oname are all the same, use the other one as identifying name
if(length(unique(pname)) == 1) names <- oname
if(length(unique(oname)) == 1) names <- pname
}
# Append state to distinguish ambiguous species names
isdup <- names %in% names[duplicated(names)]
if(any(isdup)) names[isdup] <- paste(names[isdup],
" (", eout$species$state[isdup], ")", sep = "")
}
}
# Numeric values indicate a subset 20181007
if(all(is.numeric(onames))) {
if(isTRUE(all(onames > 0))) names[-onames] <- ""
else if(isTRUE(all(onames < 0))) names[-onames] <- ""
else stop("numeric 'names' should be all positive or all negative")
}
## Apply formatting to chemical formulas 20170204
if(all(grepl("_", names))) is.pname <- TRUE
if(format.names & !is.pname) {
# Check if names are a deparsed expression (used in mix()) 20200718
parsed <- FALSE
if(any(grepl("paste\\(", names))) {
exprnames <- parse(text = names)
if(length(exprnames) != length(names)) stop("parse()-ing names gives length not equal to number of names")
parsed <- TRUE
} else {
exprnames <- as.expression(names)
# Get formatted chemical formulas
for(i in seq_along(exprnames)) {
# Don't try to format the names if they have "+" followed by a character
# (created by mix()ing diagrams with format.names = FALSE);
# expr.species() can't handle it 20200722
if(!grepl("\\+[a-zA-Z]", names[i])) exprnames[[i]] <- expr.species(exprnames[[i]])
}
}
# Apply bold or italic
bold <- rep(bold, length.out = length(exprnames))
italic <- rep(italic, length.out = length(exprnames))
for(i in seq_along(exprnames)) {
if(bold[i]) exprnames[[i]] <- substitute(bold(a), list(a = exprnames[[i]]))
if(italic[i]) exprnames[[i]] <- substitute(italic(a), list(a = exprnames[[i]]))
}
# Only use the expression if it's different from the unformatted names
if(parsed | !identical(as.character(exprnames), names)) names <- exprnames
}
## Where we'll put extra output for predominance diagrams (namesx, namesy)
out2D <- list()
### Now we're getting to the plotting ###
if(plot.it) {
### General plot parameters ###
## Handle line type/width/color arguments
if(is.null(lty)) {
if(type == "loga.balance" | nd == 2) lty <- 1
else lty <- 1:ngroups
}
lty <- rep(lty, length.out = length(plotvals))
lwd <- rep(lwd, length.out = length(plotvals))
col <- rep(col, length.out = length(plotvals))
# Function to get label for i'th variable 20230809
# (uses custom labels from 'labels' list element added by mosaic)
getlabel <- function(ivar) {
label <- eout$vars[ivar]
if(!is.null(eout$labels)) {
if(label %in% names(eout$labels)) {
label <- eout$labels[[label]]
}
}
label
}
if(nd == 0) {
### 0-D diagram - bar graph of properties of species or reactions
# Plot setup
if(missing(ylab)) ylab <- axis.label(plotvar, units = "", molality = molality)
barplot(unlist(plotvals), names.arg = names, ylab = ylab, cex.names = cex.names, col = col, ...)
if(!is.null(main)) title(main = main)
} else if(nd == 1) {
### 1-D diagram - lines for properties or chemical activities
xvalues <- eout$vals[[1]]
if(missing(xlim)) xlim <- c(xvalues[1], rev(xvalues)[1])
# Initialize the plot
if(!add) {
if(missing(xlab)) xlab <- axis.label(getlabel(1), basis = eout$basis, molality = molality)
if(missing(ylab)) {
ylab <- axis.label(plotvar, units = "", molality = molality)
if(plotvar == "rank.affinity") ylab <- "Average affinity ranking"
# Use ppb, ppm, ppt (or log ppb etc.) for converted values of solubility 20190526
if(grepl("solubility.", eout$fun, fixed = TRUE)) {
ylab <- strsplit(eout$fun, ".", fixed = TRUE)[[1]][2]
ylab <- gsub("log", "log ", ylab)
}
}
# To get range for y-axis, use only those points that are in the xrange
if(is.null(ylim)) {
isx <- xvalues >= min(xlim) & xvalues <= max(xlim)
xfun <- function(x) x[isx]
myval <- sapply(plotvals, xfun)
ylim <- extendrange(myval)
}
if(tplot) thermo.plot.new(xlim = xlim, ylim = ylim, xlab = xlab, ylab = ylab, cex = cex, mar = mar, yline = yline, side = side, ...)
else plot(0, 0, type = "n", xlim = xlim, ylim = ylim, xlab = xlab, ylab = ylab, ...)
}
# Draw the lines
spline.n <- 256 # the number of values at which to calculate splines
if(is.null(spline.method) | length(xvalues) > spline.n) {
for(i in 1:length(plotvals)) lines(xvalues, plotvals[[i]], col = col[i], lty = lty[i], lwd = lwd[i])
} else {
# Plot splines instead of lines connecting the points 20171116
spline.x <- seq(xlim[1], xlim[2], length.out = spline.n)
for(i in 1:length(plotvals)) {
spline.y <- splinefun(xvalues, plotvals[[i]], method = spline.method)(spline.x)
lines(spline.x, spline.y, col = col[i], lty = lty[i], lwd = lwd[i])
}
}
if(type %in% c("auto", "loga.equil") & !is.null(legend.x)) {
# 20120521: use legend.x = NA to label lines rather than make legend
if(is.na(legend.x)) {
maxvals <- do.call(pmax, pv)
# Label placement and rotation
dx <- rep(dx, length.out = length(plotvals))
dy <- rep(dy, length.out = length(plotvals))
srt <- rep(srt, length.out = length(plotvals))
cex.names <- rep(cex.names, length.out = length(plotvals))
# Don't assign to adj becuase that messes up the missing test below
alladj <- rep(adj, length.out = length(plotvals))
for(i in 1:length(plotvals)) {
# y-values for this line
myvals <- as.numeric(plotvals[[i]])
# Don't take values that lie close to or above the top of plot
myvals[myvals > ylim[1] + 0.95*diff(ylim)] <- ylim[1]
# If we're adding to a plot, don't take values that are above the top of this plot
if(add) {
this.ylim <- par("usr")[3:4]
myvals[myvals > this.ylim[1] + 0.95*diff(this.ylim)] <- this.ylim[1]
}
# The starting x-adjustment
thisadj <- alladj[i]
# If this line has any of the overall maximum values, use only those values
# (useful for labeling straight-line affinity comparisons 20170221)
is.max <- myvals == maxvals
if(any(is.max) & plotvar != "alpha") {
# Put labels on the median x-position
imax <- median(which(is.max))
} else {
# Put labels on the maximum of the line
# (useful for labeling alpha plots)
imax <- which.max(myvals)
# Avoid the sides of the plot; take care of reversed x-axis
if(missing(adj)) {
if(sign(diff(xlim)) > 0) {
if(xvalues[imax] > xlim[1] + 0.8*diff(xlim)) thisadj <- 1
if(xvalues[imax] < xlim[1] + 0.2*diff(xlim)) thisadj <- 0
} else {
if(xvalues[imax] > xlim[1] + 0.2*diff(xlim)) thisadj <- 0
if(xvalues[imax] < xlim[1] + 0.8*diff(xlim)) thisadj <- 1
}
}
}
# Also include y-offset (dy) and y-adjustment (labels bottom-aligned with the line)
# ... and srt (string rotation) 20171127
text(xvalues[imax] + dx[i], plotvals[[i]][imax] + dy[i], labels = names[i], adj = c(thisadj, 0),
cex = cex.names[i], srt = srt[i], font = font, family = family)
}
} else legend(x = legend.x, lty = lty, legend = names, col = col, cex = cex.names, lwd = lwd, ...)
}
# Add a title
if(!is.null(main)) title(main = main)
} else if(nd == 2) {
### 2-D diagram - fields indicating species predominance, or contours for other properties
### Functions for constructing predominance area diagrams
## Color fill function
fill.color <- function(xs, ys, out, fill, nspecies) {
# Handle min/max reversal
if(xs[1] > xs[length(xs)]) {
tc <- out
t <- numeric()
for(i in 1:length(xs)) {
t[i] <- xs[length(xs)+1-i]
tc[, i] <- out[, length(xs)+1-i]
}
out <- tc
xs <- t
}
if(ys[1] > ys[length(ys)]) {
tc <- out
t <- numeric()
for(i in 1:length(ys)) {
t[i] <- ys[length(ys)+1-i]
tc[i, ] <- out[length(ys)+1-i, ]
}
out <- tc
ys <- t
}
# The z values
zs <- out
for(i in 1:nrow(zs)) zs[i,] <- out[nrow(zs)+1-i,]
zs <- t(zs)
breaks <- c(-1, 0, 1:nspecies) + 0.5
# Use fill.NA for NA values
zs[is.na(zs)] <- 0
image(x = xs, y = ys, z = zs, col = c(fill.NA, fill), add = TRUE, breaks = breaks, useRaster = TRUE)
}
## Curve plot function
# 20091116 replaced plot.curve with plot.line; different name, same functionality, *much* faster
plot.line <- function(out, xlim, ylim, dotted, col, lwd, xrange) {
# Plot boundary lines between predominance fields
vline <- function(out, ix) {
ny <- nrow(out)
xs <- rep(ix, ny*2+1)
ys <- c(rep(ny:1, each = 2), 0)
y1 <- out[, ix]
y2 <- out[, ix+1]
# No line segment inside a stability field
iy <- which(y1 == y2)
ys[iy*2] <- NA
# No line segment at a dotted position
iyd <- rowSums(sapply(dotted, function(y) ys%%y == 0)) > 0
ys[iyd] <- NA
return(list(xs = xs, ys = ys))
}
hline <- function(out, iy) {
nx <- ncol(out)
ys <- rep(iy, nx*2+1)
xs <- c(0, rep(1:nx, each = 2))
x1 <- out[iy, ]
x2 <- out[iy+1, ]
# No line segment inside a stability field
ix <- which(x1 == x2)
xs[ix*2] <- NA
# No line segment at a dotted position
ixd <- rowSums(sapply(dotted, function(x) xs%%x == 0)) > 0
xs[ixd] <- NA
return(list(xs = xs, ys = ys))
}
clipfun <- function(z, zlim) {
if(zlim[2] > zlim[1]) {
z[z>zlim[2]] <- NA
z[z<zlim[1]] <- NA
} else {
z[z>zlim[1]] <- NA
z[z<zlim[2]] <- NA
}
return(z)
}
rx <- (xlim[2] - xlim[1]) / (ncol(out) - 1)
ry <- (ylim[2] - ylim[1]) / (nrow(out) - 1)
# Vertical lines
xs <- ys <- NA
for(ix in 1:(ncol(out)-1)) {
vl <- vline(out,ix)
xs <- c(xs,vl$xs,NA)
ys <- c(ys,vl$ys,NA)
}
xs <- xlim[1] + (xs - 0.5) * rx
ys <- ylim[1] + (ys - 0.5) * ry
ys <- clipfun(ys, ylim)
if(!is.null(xrange)) xs <- clipfun(xs, xrange)
lines(xs, ys, col = col, lwd = lwd)
# Horizontal lines
xs <- ys <-NA
for(iy in 1:(nrow(out)-1)) {
hl <- hline(out, iy)
xs <- c(xs, hl$xs, NA)
ys <- c(ys, hl$ys, NA)
}
xs <- xlim[1] + (xs - 0.5) * rx
ys <- ylim[2] - (ys - 0.5) * ry
xs <- clipfun(xs, xlim)
if(!is.null(xrange)) xs <- clipfun(xs, xrange)
lines(xs, ys, col = col, lwd = lwd)
}
## New line plotting function 20170122
contour.lines <- function(predominant, xlim, ylim, lty, col, lwd) {
# The x and y values
xs <- seq(xlim[1], xlim[2], length.out = dim(predominant)[1])
ys <- seq(ylim[1], ylim[2], length.out = dim(predominant)[2])
# Reverse any axis that has decreasing values
if(diff(xlim) < 0) {
predominant <- predominant[nrow(predominant):1, ]
xs <- rev(xs)
}
if(diff(ylim) < 0) {
predominant <- predominant[, ncol(predominant):1]
ys <- rev(ys)
}
# The categories (species/groups/etc) on the plot
zvals <- na.omit(unique(as.vector(predominant)))
if(is.null(lty.aq) & is.null(lty.cr)) {
# DEFAULT method: loop over species
for(i in 1:(length(zvals)-1)) {
# Get the "z" values
# Use + 0 trick to convert T/F to 1/0 20220524
z <- (predominant == zvals[i]) + 0
z[is.na(z)] <- 0
# Use contourLines() instead of contour() in order to get line coordinates 20181029
cLines <- contourLines(xs, ys, z, levels = 0.5)
if(length(cLines) > 0) {
# Loop in case contourLines returns multiple lines
for(k in 1:length(cLines)) {
# Draw the lines
lines(cLines[[k]][2:3], lty = lty[zvals[i]], col = col[zvals[i]], lwd = lwd[zvals[i]])
}
}
# Mask species to prevent double-plotting contour lines
predominant[z == zvals[i]] <- NA
}
} else {
# ALTERNATE (slower) method to handle lty.aq and lty.cr: take each possible pair of species
# Reinstated on 20210301
for(i in 1:(length(zvals)-1)) {
for(j in (i+1):length(zvals)) {
z <- predominant
# Draw contours only for this pair
z[!z %in% c(zvals[i], zvals[j])] <- NA
# Give them neighboring values (so we get one contour line)
z[z == zvals[i]] <- 0
z[z == zvals[j]] <- 1
# Use contourLines() instead of contour() in order to get line coordinates 20181029
cLines <- contourLines(xs, ys, z, levels = 0.5)
if(length(cLines) > 0) {
# Loop in case contourLines returns multiple lines
for(k in 1:length(cLines)) {
# Draw the lines
mylty <- lty[zvals[i]]
if(!is.null(lty.cr)) {
# Use lty.cr for cr-cr boundaries 20190530
if(all(grepl("cr", eout$species$state[c(zvals[i], zvals[j])]))) mylty <- lty.cr
}
if(!is.null(lty.aq)) {
# Use lty.aq for aq-aq boundaries 20190531
if(all(grepl("aq", eout$species$state[c(zvals[i], zvals[j])]))) mylty <- lty.aq
}
lines(cLines[[k]][2:3], lty = mylty, col = col[zvals[i]], lwd = lwd[zvals[i]])
}
}
}
}
}
}
## To add labels
plot.names <- function(out, xs, ys, xlim, ylim, names, srt, min.area) {
# Calculate coordinates for field labels
# Revisions: 20091116 for speed, 20190223 work with user-specified xlim and ylim
namesx <- namesy <- rep(NA, length(names))
# Even if 'names' is NULL, we run the loop in order to generate namesx and namesy for the output 20190225
area.plot <- length(xs) * length(ys)
for(i in seq_along(groups)) {
this <- which(out == i, arr.ind = TRUE)
if(length(this) == 0) next
xsth <- xs[this[, 2]]
ysth <- rev(ys)[this[, 1]]
# Use only values within the plot range
rx <- range(xlim)
ry <- range(ylim)
xsth <- xsth[xsth >= rx[1] & xsth <= rx[2]]
ysth <- ysth[ysth >= ry[1] & ysth <= ry[2]]
if(length(xsth) == 0 | length(ysth) == 0) next
# Skip plotting names if the fields are too small 20200720
area <- max(length(xsth), length(ysth))
frac.area <- area / area.plot
if(!frac.area >= min.area) next
namesx[i] <- mean(xsth)
namesy[i] <- mean(ysth)
}
# Fields that really exist on the plot
if(!is.null(names)) {
cex <- rep(cex.names, length.out = length(names))
col <- rep(col.names, length.out = length(names))
font <- rep(font, length.out = length(names))
family <- rep(family, length.out = length(names))
srt <- rep(srt, length.out = length(names))
dx <- rep(dx, length.out = length(names))
dy <- rep(dy, length.out = length(names))
for(i in seq_along(names)) {
if(!(identical(col[i], 0)) & !is.na(col[i]))
text(namesx[i] + dx[i], namesy[i] + dy[i], labels = names[i], cex = cex[i], col = col[i], font = font[i], family = family[i], srt = srt[i])
}
}
return(list(namesx = namesx, namesy = namesy))
}
### Done with supporting functions
### Now we really get to make the diagram itself
# Colors to fill predominance fields
if(is.null(fill)) {
if(length(unique(eout$species$state)) == 1) fill <- "transparent"
else fill <- ifelse(grepl("cr,cr", eout$species$state), "#DEB88788", ifelse(grepl("cr", eout$species$state), "#FAEBD788", "#F0F8FF88"))
} else if(identical(fill, NA) | length(fill) == 0) fill <- "transparent"
else if(isTRUE(fill[1] == "rainbow")) fill <- rainbow(ngroups)
else if(isTRUE(fill[1] %in% c("heat", "terrain", "topo", "cm"))) fill <- get(paste0(fill[1], ".colors"))(ngroups)
else if(getRversion() >= "3.6.0" & length(fill) == 1) {
# Choose an HCL palette 20190411
# Matching adapted from hcl.colors()
fx <- function(x) tolower(gsub("[-, _, \\,, (, ), \\ , \\.]", "", x))
p <- charmatch(fx(fill), fx(hcl.pals()))
if(!is.na(p)) {
if(!p < 1L) {
fill <- hcl.colors(ngroups, fill)
}
}
}
fill <- rep(fill, length.out = ngroups)
# The x and y values
xs <- eout$vals[[1]]
ys <- eout$vals[[2]]
# The limits of the calculation; they aren't necessarily increasing, so don't use range()
xlim.calc <- c(xs[1], tail(xs, 1))
ylim.calc <- c(ys[1], tail(ys, 1))
# Add if(is.null) to allow user-specified limits 20190223
if(is.null(xlim)) {
if(add) xlim <- par("usr")[1:2]
else xlim <- xlim.calc
}
if(is.null(ylim)) {
if(add) ylim <- par("usr")[3:4]
else ylim <- ylim.calc
}
# Initialize the plot
if(!add) {
if(is.null(xlab)) xlab <- axis.label(getlabel(1), basis = eout$basis, molality = molality)
if(is.null(ylab)) ylab <- axis.label(getlabel(2), basis = eout$basis, molality = molality)
if(tplot) thermo.plot.new(xlim = xlim, ylim = ylim, xlab = xlab, ylab = ylab,
cex = cex, cex.axis = cex.axis, mar = mar, yline = yline, side = side, ...)
else plot(0, 0, type = "n", xlim = xlim, ylim = ylim, xlab = xlab, ylab = ylab, ...)
# Add a title
if(!is.null(main)) title(main = main)
}
if(identical(predominant, NA)) {
# No predominance matrix, so we're contouring properties
contour.method <- rep(contour.method, length.out = length(plotvals))
if(type == "saturation") {
# For saturation plot, contour affinity = 0 for all species
for(i in 1:length(plotvals)) {
zs <- plotvals[[i]]
# Skip plotting if this species has no possible saturation line, or a line outside the plot range
if(length(unique(as.numeric(zs))) == 1) {
message("diagram: no saturation line possible for ", names[i])
next
}
if(all(zs < 0) | all(zs > 0)) {
message("diagram: beyond range for saturation line of ", names[i])
next
}
if(identical(contour.method, NULL) | identical(contour.method[1], NA) | identical(contour.method[1], ""))
contour(xs, ys, zs, add = TRUE, col = col, lty = lty, lwd = lwd, labcex = cex, levels = 0, labels = names[i], drawlabels = FALSE)
else contour(xs, ys, zs, add = TRUE, col = col, lty = lty, lwd = lwd, labcex = cex, levels = 0, labels = names[i], method = contour.method[i])
}
} else {
# Contour solubilities (loga.balance), or properties using first species only
if(length(plotvals) > 1) warning("showing only first species in 2-D property diagram")
zs <- plotvals[[1]]
drawlabels <- TRUE
if(identical(contour.method, NULL) | identical(contour.method[1], NA) | identical(contour.method[1], "")) drawlabels <- FALSE
if(is.null(levels)) {
if(drawlabels) contour(xs, ys, zs, add = TRUE, col = col, lty = lty, lwd = lwd, labcex = cex, method = contour.method[1])
else contour(xs, ys, zs, add = TRUE, col = col, lty = lty, lwd = lwd, labcex = cex, drawlabels = FALSE)
} else {
if(drawlabels) contour(xs, ys, zs, add = TRUE, col = col, lty = lty, lwd = lwd, labcex = cex, method = contour.method[1], levels = levels)
else contour(xs, ys, zs, add = TRUE, col = col, lty = lty, lwd = lwd, labcex = cex, levels = levels, drawlabels = FALSE)
}
}
pn <- list(namesx = NULL, namesy = NULL)
} else {
# Put predominance matrix in the right order for image()
zs <- t(predominant[, ncol(predominant):1])
if(!is.null(H2O.predominant)) {
zsH2O <- t(H2O.predominant[, ncol(H2O.predominant):1])
# This colors in fields and greyed-out H2O non-stability regions
if(!is.null(fill)) fill.color(xs, ys, zsH2O, fill, ngroups)
# Clip entire diagram to H2O stability region?
if(isTRUE(limit.water)) zs <- zsH2O
}
# This colors in fields (possibly a second time, to overlay on H2O regions)
if(!is.null(fill)) fill.color(xs, ys, zs, fill, ngroups)
# Plot field labels
pn <- plot.names(zs, xs, ys, xlim, ylim, names, srt, min.area)
# Only draw the lines if there is more than one field 20180923
# (to avoid warnings from contour, which seem to be associated with weird
# font metric state and subsequent errors adding e.g. subscripted text to plot)
if(length(na.omit(unique(as.vector(zs)))) > 1) {
if(!is.null(dotted)) plot.line(zs, xlim.calc, ylim.calc, dotted, col, lwd, xrange = xrange)
else contour.lines(predominant, xlim.calc, ylim.calc, lty = lty, col = col, lwd = lwd)
}
# Re-draw the tick marks and axis lines in case the fill obscured them
has.color <- FALSE
if(!identical(unique(fill), "transparent")) has.color <- TRUE
if(!is.null(H2O.predominant) & !identical(fill.NA, "transparent")) has.color <- TRUE
if(any(is.na(zs)) & !identical(fill.NA, "transparent")) has.color <- TRUE
if(tplot & !add & has.color) {
thermo.axis()
box()
}
} # Done with the 2D plot!
out2D <- list(namesx = pn$namesx, namesy = pn$namesy)
} # end if(nd == 2)
} # end if(plot.it)
# Even if plot = FALSE, return the diagram clipped to the water stability region (for testing) 20200719
if(isTRUE(limit.water) & !is.null(H2O.predominant)) predominant <- H2O.predominant
# Make a matrix with the affinities or activities of predominant species 20200724
# (for calculating affinities of metastable species - multi-metal.Rmd example)
predominant.values <- NA
if(!identical(predominant, NA)) {
predominant.values <- plotvals[[1]]
predominant.values[] <- NA
for(ip in na.omit(unique(as.vector(predominant)))) {
ipp <- predominant == ip
ipp[is.na(ipp)] <- FALSE
# 20201219 Change eout$values to plotvals (return normalized affinities or equilibrium activities)
predominant.values[ipp] <- plotvals[[ip]][ipp]
}
}
outstuff <- list(plotvar = plotvar, plotvals = plotvals, names = names, predominant = predominant, predominant.values = predominant.values)
# Include the balance name and coefficients if we diagrammed affinities 20200714
if(eout.is.aout) outstuff <- c(list(balance = balance, n.balance = n.balance), outstuff)
out <- c(eout, outstuff, out2D)
invisible(out)
}
find.tp <- function(x) {
# Find triple points in an matrix of integers 20120525 jmd
# these are the locations closest to the greatest number of different values
# Rearrange the matrix in the same way that diagram() does for 2-D predominance diagrams
x <- t(x[, ncol(x):1])
# All of the indexes for the matrix
id <- which(x > 0, arr.ind = TRUE)
# We'll do a brute-force count at each position
n <- sapply(1:nrow(id), function(i) {
# Row and column range to look at (3x3 except at edges)
r1 <- max(id[i, 1] - 1, 0)
r2 <- min(id[i, 1] + 1, nrow(x))
c1 <- max(id[i, 2] - 1, 0)
c2 <- min(id[i, 2] + 1, ncol(x))
# The number of unique values
return(length(unique(as.numeric(x[r1:r2, c1:c2]))))
})
# Which positions have the most counts?
imax <- which(n == max(n))
# Return the indices
return(id[imax, ])
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/diagram.R
|
# CHNOSZ/equilibrate.R
# Functions to calculation logarithm of activity
# of species in (metastable) equilibrium
## If this file is interactively sourced, the following are also needed to provide unexported functions:
#source("util.misc.R")
#source("util.character.R")
equilibrate <- function(aout, balance = NULL, loga.balance = NULL,
ispecies = !grepl("cr", aout$species$state), normalize = FALSE, as.residue = FALSE,
method = c("boltzmann", "reaction"), tol = .Machine$double.eps^0.25) {
### Calculate equilibrium activities of species from the affinities
### of their formation reactions from basis species at given activities
### Split from diagram() 20120925 jmd
## If aout is the output from mosaic(), combine the equilibrium activities of basis species
## and formed species into an object that can be plotted with diagram() 20190505
if(aout$fun == "mosaic") {
# Calculate equilibrium activities of species
if(missing(ispecies)) ispecies <- 1:length(aout$A.species$values)
if(missing(method)) eqc <- equilibrate(aout$A.species, balance = balance, loga.balance = loga.balance,
ispecies = ispecies, normalize = normalize, as.residue = as.residue, tol = tol)
else eqc <- equilibrate(aout$A.species, balance = balance, loga.balance = loga.balance,
ispecies = ispecies, normalize = normalize, as.residue = as.residue, method = method, tol = tol)
# Make combined object for basis species and species:
# put together the species matrix and logarithms of equilibrium activity
eqc$species <- rbind(aout$E.bases[[1]]$species, eqc$species)
eqc$loga.equil <- c(aout$E.bases[[1]]$loga.equil, eqc$loga.equil)
# We also need to combine 'values' (values of affinity) because diagram() uses this to get the number of species
eqc$values <- c(aout$E.bases[[1]]$values, eqc$values)
return(eqc)
}
## Number of possible species
nspecies <- length(aout$values)
## Get the balancing coefficients
bout <- balance(aout, balance)
n.balance.orig <- n.balance <- bout$n.balance
balance <- bout$balance
## If solids (cr) species are present, find them on a predominance diagram 20191111
iscr <- grepl("cr", aout$species$state)
ncr <- sum(iscr)
if(ncr > 0) dout <- diagram(aout, balance = balance, normalize = normalize, as.residue = as.residue, plot.it = FALSE, limit.water = FALSE)
if(ncr == nspecies) {
## We get here if there are only solids 20200714
m.balance <- NULL
Astar <- NULL
loga.equil <- aout$values
for(i in 1:length(loga.equil)) loga.equil[[i]][] <- NA
} else {
## We get here if there are any aqueous species 20200714
## Take selected species in 'ispecies'
if(length(ispecies) == 0) stop("the length of ispecies is zero")
if(is.logical(ispecies)) ispecies <- which(ispecies)
# Take out species that have NA affinities
ina <- sapply(aout$values, function(x) all(is.na(x)))
ispecies <- ispecies[!ina[ispecies]]
if(length(ispecies) == 0) stop("all species have NA affinities")
if(!identical(ispecies, 1:nspecies)) {
message(paste("equilibrate: using", length(ispecies), "of", nspecies, "species"))
aout$species <- aout$species[ispecies, ]
aout$values <- aout$values[ispecies]
n.balance <- n.balance[ispecies]
}
## Number of species that are left
nspecies <- length(aout$values)
## Say what the balancing coefficients are
if(length(n.balance) < 100) message(paste("equilibrate: n.balance is", c2s(n.balance)))
## Logarithm of total activity of the balancing basis species
if(is.null(loga.balance)) {
# Sum up the activities, then take absolute value
# in case n.balance is negative
sumact <- abs(sum(10^aout$species$logact * n.balance))
loga.balance <- log10(sumact)
}
# Make loga.balance the same length as the values of affinity
loga.balance <- unlist(loga.balance)
nvalues <- length(unlist(aout$values[[1]]))
if(length(loga.balance) == 1) {
# We have a constant loga.balance
message(paste0("equilibrate: loga.balance is ", loga.balance))
loga.balance <- rep(loga.balance, nvalues)
} else {
# We are using a variable loga.balance (supplied by the user)
if(!identical(length(loga.balance), nvalues)) stop("length of loga.balance (", length(loga.balance), ") doesn't match the affinity values (", nvalues, ")")
message(paste0("equilibrate: loga.balance has same length as affinity values (", length(loga.balance), ")"))
}
## Normalize the molar formula by the balance coefficients
m.balance <- n.balance
isprotein <- grepl("_", as.character(aout$species$name))
if(any(normalize) | as.residue) {
if(any(n.balance < 0)) stop("one or more negative balancing coefficients prohibit using normalized molar formulas")
n.balance[normalize|as.residue] <- 1
if(as.residue) message(paste("equilibrate: using 'as.residue' for molar formulas"))
else message(paste("equilibrate: using 'normalize' for molar formulas"))
# Set the formula divisor (m.balance) to 1 for species whose formulas are *not* normalized
m.balance[!(normalize|as.residue)] <- 1
} else m.balance[] <- 1
## Astar: the affinities/2.303RT of formation reactions with
## formed species in their standard-state activities
Astar <- lapply(1:nspecies, function(i) {
# 'starve' the affinity of the activity of the species,
# and normalize the value by the nor-molar ratio
(aout$values[[i]] + aout$species$logact[i]) / m.balance[i]
})
## Chose a method and compute the equilibrium activities of species
if(missing(method)) {
if(all(n.balance == 1)) method <- method[1]
else method <- method[2]
}
message(paste("equilibrate: using", method[1], "method"))
if(method[1] == "boltzmann") loga.equil <- equil.boltzmann(Astar, n.balance, loga.balance)
else if(method[1] == "reaction") loga.equil <- equil.reaction(Astar, n.balance, loga.balance, tol)
## If we normalized the formulas, get back to activities to species
if(any(normalize) & !as.residue) {
loga.equil <- lapply(1:nspecies, function(i) {
loga.equil[[i]] - log10(m.balance[i])
})
}
}
## Process cr species 20191111
if(ncr > 0) {
# cr species were excluded from equilibrium calculation, so get values back to original lengths
norig <- length(dout$values)
n.balance <- n.balance.orig
imatch <- match(1:norig, ispecies)
m.balance <- m.balance[imatch]
Astar <- Astar[imatch]
loga.equil1 <- loga.equil[[1]]
loga.equil <- loga.equil[imatch]
# Replace NULL loga.equil with input values (cr only)
ina <- which(is.na(imatch))
for(i in ina) {
loga.equil[[i]] <- loga.equil1
loga.equil[[i]][] <- dout$species$logact[[i]]
}
aout$species <- dout$species
aout$values <- dout$values
# Find the grid points where any cr species is predominant
icr <- which(grepl("cr", dout$species$state))
iscr <- lapply(icr, function(x) dout$predominant == x)
iscr <- Reduce("|", iscr)
# At those grid points, make the aqueous species' activities practically zero
for(i in 1:norig) {
if(i %in% icr) next
loga.equil[[i]][iscr] <- -999
}
# At the other grid points, make the cr species' activities practically zero
for(i in icr) {
ispredom <- dout$predominant == i
loga.equil[[i]][!ispredom] <- -999
}
}
## Put together the output
out <- c(aout, list(balance = balance, m.balance = m.balance, n.balance = n.balance,
loga.balance = loga.balance, Astar = Astar, loga.equil = loga.equil))
# Done!
return(out)
}
equil.boltzmann <- function(Astar, n.balance, loga.balance) {
# 20090217 new "abundance" function
# Return equilibrium logarithms of activity of species
# Works using Boltzmann distribution
# A/At = e^(Astar/n.balance) / sum(e^(Astar/n.balance))
# where A is activity of the ith residue and
# At is total activity of residues
# Advantages over equil.reaction
# 2) loops over species only - much faster
# 3) no root finding - those games might fail at times
# Disadvantage:
# 1) only works for per-residue reactions
# 2) can create NaN logacts if the Astars are huge/small
if(any(n.balance != 1)) stop("won't run equil.boltzmann for balance <> 1")
# Initialize output object
A <- Astar
# Remember the dimensions of elements of Astar (could be vector,matrix)
Astardim <- dim(Astar[[1]])
Anames <- names(Astar)
# First loop: make vectors
A <- palply("", 1:length(A), function(i) as.vector(A[[i]]))
loga.balance <- as.vector(loga.balance)
# Second loop: get the exponentiated Astars (numerators)
# Need to convert /2.303RT to /RT
#A[[i]] <- exp(log(10)*Astar[[i]]/n.balance[i])/n.balance[i]
A <- palply("", 1:length(A), function(i) exp(log(10)*Astar[[i]]/n.balance[i]))
# Third loop: accumulate the denominator
# Initialize variable to hold the sum
At <- A[[1]]
At[] <- 0
for(i in 1:length(A)) At <- At + A[[i]]*n.balance[i]
# Fourth loop: calculate log abundances
A <- palply("", 1:length(A), function(i) loga.balance + log10(A[[i]]/At))
# Fifth loop: replace dimensions
for(i in 1:length(A)) dim(A[[i]]) <- Astardim
# Add names and we're done!
names(A) <- Anames
return(A)
}
equil.reaction <- function(Astar, n.balance, loga.balance, tol = .Machine$double.eps^0.25) {
# To turn the affinities/RT (A) of formation reactions into
# logactivities of species (logact(things)) at metastable equilibrium
# 20090217 extracted from diagram and renamed to abundance.old
# 20080217 idea / 20120128 cleaned-up strategy
# For any reaction stuff = thing,
# A = logK - logQ
# = logK - logact(thing) + logact(stuff)
# given Astar = A + logact(thing),
# given Abar = A / n.balance,
# logact(thing) = Astar - Abar * n.balance [2]
# where n.balance is the number of the balanced quanitity
# (conserved component) in each species
# equilibrium values of logact(thing) satifsy:
# 1) Abar is equal for all species
# 2) log10( sum of (10^logact(thing) * n.balance) ) = loga.balance [1]
#
# Because of the logarithms, we can't solve the equations directly
# Instead, use uniroot() to compute Abar satisfying [1]
# We can't run on one species
if(length(Astar) == 1) stop("at least two species needed for reaction-based equilibration")
# Remember the dimensions and names
Adim <- dim(Astar[[1]])
Anames <- names(Astar)
# Make a matrix out of the list of Astar
Astar <- list2array(lapply(Astar, c))
if(length(loga.balance) != nrow(Astar)) stop("length of loga.balance must be equal to the number of conditions for affinity()")
# That produces the same result (other than colnames) and is much faster than
#Astar <- sapply(Astar, c)
# Also, latter has NULL nrow for length(Astar[[x]]) == 1
# Some function definitions:
# To calculate log of activity of balanced quantity from logact(thing) of all species [1]
logafun <- function(logact) log10(sum(10^logact * n.balance))
# To calculate logact(thing) from Abar for the ith condition [2]
logactfun <- function(Abar, i) Astar[i,] - Abar * n.balance
# To calculate difference between logafun and loga.balance for the ith condition
logadiff <- function(Abar, i) loga.balance[i] - logafun(logactfun(Abar, i))
# To calculate a range of Abar that gives negative and positive values of logadiff for the ith condition
Abarrange <- function(i) {
# Starting guess of Abar (min/max) from range of Astar / n.balance
Abar.range <- range(Astar[i, ] / n.balance)
# diff(Abar.range) can't be 0 (dlogadiff.dAbar becomes NaN)
if(diff(Abar.range) == 0) {
Abar.range[1] <- Abar.range[1] - 0.1
Abar.range[2] <- Abar.range[2] + 0.1
}
# The range of logadiff
logadiff.min <- logadiff(Abar.range[1], i)
logadiff.max <- logadiff(Abar.range[2], i)
# We're out of luck if they're both infinite
if(is.infinite(logadiff.min) & is.infinite(logadiff.max))
stop("FIXME: there are no initial guesses for Abar that give
finite values of the differences in logarithm of activity
of the conserved component")
# If one of them is infinite we might have a chance
if(is.infinite(logadiff.min)) {
# Decrease the Abar range by increasing the minimum
Abar.range[1] <- Abar.range[1] + 0.99 * diff(Abar.range)
logadiff.min <- logadiff(Abar.range[1], i)
if(is.infinite(logadiff.min)) stop("FIXME: the second initial guess for Abar.min failed")
}
if(is.infinite(logadiff.max)) {
# Decrease the Abar range by decreasing the maximum
Abar.range[2] <- Abar.range[2] - 0.99 * diff(Abar.range)
logadiff.max <- logadiff(Abar.range[2], i)
if(is.infinite(logadiff.max)) stop("FIXME: the second initial guess for Abar.max failed")
}
iter <- 0
while(logadiff.min > 0 | logadiff.max < 0) {
# The change of logadiff with Abar
# It's a weighted mean of the n.balance
dlogadiff.dAbar <- (logadiff.max - logadiff.min) / diff(Abar.range)
# Change Abar to center logadiff (min/max) on zero
logadiff.mean <- mean(c(logadiff.min, logadiff.max))
Abar.range <- Abar.range - logadiff.mean / dlogadiff.dAbar
# One iteration is enough for the examples in the package
# but there might be a case where the range of logadiff doesn't cross zero
# (e.g. for the carboxylic acid example previously in revisit.Rd)
logadiff.min <- logadiff(Abar.range[1], i)
logadiff.max <- logadiff(Abar.range[2], i)
iter <- 1
if(iter > 5) {
stop("FIXME: we seem to be stuck! This function (Abarrange() in
equil.reaction()) can't find a range of Abar such that the differences
in logarithm of activity of the conserved component cross zero")
}
}
return(Abar.range)
}
# To calculate an equilibrium Abar for the ith condition
Abarfun <- function(i) {
# Get limits of Abar where logadiff brackets zero
Abar.range <- Abarrange(i)
# Now for the real thing: uniroot!
Abar <- uniroot(logadiff, interval = Abar.range, i = i, tol = tol)$root
return(Abar)
}
# Calculate the logact(thing) for each condition
logact <- palply("", 1:nrow(Astar), function(i) {
# Get the equilibrium Abar for each condition
Abar <- Abarfun(i)
return(logactfun(Abar, i))
})
# Restore the dimensions and names
if(length(Adim) == 1) logact <- list2array(logact)
else logact <- sapply(logact, c)
logact <- lapply(1:nrow(logact), function(i) {
thisla <- list(logact[i,])[[1]]
dim(thisla) <- Adim
return(thisla)
})
names(logact) <- Anames
# All done!
return(logact)
}
# A function to calculate the total moles of the elements in the output from equilibrate 20190505
moles <- function(eout) {
# Exponentiate loga.equil to get activities
act <- lapply(eout$loga.equil, function(x) 10^x)
# Initialize list for moles of basis species
nbasis <- rep(list(act[[1]] * 0), nrow(eout$basis))
# Loop over species
for(i in 1:nrow(eout$species)) {
# Loop over basis species
for(j in 1:nrow(eout$basis)) {
# The coefficient of this basis species in the formation reaction of this species
n <- eout$species[i, j]
# Accumulate the number of moles of basis species
nbasis[[j]] <- nbasis[[j]] + act[[i]] * n
}
}
# Initialize list for moles of elements (same as number of basis species)
nelem <- rep(list(act[[1]] * 0), nrow(eout$basis))
# Loop over basis species
for(i in 1:nrow(eout$basis)) {
# Loop over elements
for(j in 1:nrow(eout$basis)) {
# The coefficient of this element in the formula of this basis species
n <- eout$basis[i, j]
# Accumulate the number of moles of elements
nelem[[j]] <- nelem[[j]] + nbasis[[i]] * n
}
}
# Add element names
names(nelem) <- colnames(eout$basis)[1:nrow(eout$basis)]
nelem
}
### Unexported functions ###
# Return a list containing the balancing coefficients (n.balance) and a textual description (balance)
balance <- function(aout, balance = NULL) {
## Generate n.balance from user-given or automatically identified basis species
## Extracted from equilibrate() 20120929
# 'balance' can be:
# NULL - autoselect using which.balance
# name of basis species - balanced on this basis species
# "length" - balanced on sequence length of proteins
# (default if balance is missing and all species are proteins)
# 1 - balanced on one mole of species (formula units)
# numeric vector - user-defined n.balance
# "volume" - standard-state volume listed in thermo()$OBIGT
# The index of the basis species that might be balanced
ibalance <- numeric()
# Deal with proteins
isprotein <- grepl("_", as.character(aout$species$name))
if(is.null(balance) & all(isprotein)) balance <- "length"
# Try to automatically find a balance
if(is.null(balance)) {
ibalance <- which.balance(aout$species)
# No shared basis species and balance not specified by user - an error
if(length(ibalance) == 0) stop("no basis species is present in all formation reactions")
}
# Change "1" to 1 (numeric) 20170206
if(identical(balance, "1")) balance <- 1
if(is.numeric(balance[1])) {
# A numeric vector
n.balance <- rep(balance, length.out = length(aout$values))
msgtxt <- paste0("balance: on supplied numeric argument (", paste(balance, collapse = ","), ")")
if(identical(balance, 1)) msgtxt <- paste(msgtxt, "[1 means balance on formula units]")
message(msgtxt)
} else {
# "length" for balancing on protein length
if(identical(balance, "length")) {
if(!all(isprotein)) stop("'length' was the requested balance, but some species are not proteins")
n.balance <- protein.length(aout$species$name)
message("balance: on protein length")
} else if(identical(balance, "volume")) {
n.balance <- info(aout$species$ispecies, check.it = FALSE)$V
message("balance: on volume")
} else {
# Is the balance the name of a basis species?
if(length(ibalance) == 0) {
ibalance <- match(balance, rownames(aout$basis))
if(is.na(ibalance)) stop("basis species (", balance, ") not available to balance reactions")
}
# The name of the basis species (need this if we got ibalance which which.balance, above)
balance <- colnames(aout$species)[ibalance[1]]
message(paste("balance: on moles of", balance, "in formation reactions"))
# The balancing coefficients
n.balance <- aout$species[, ibalance[1]]
# We check if that all formation reactions contain this basis species
if(any(n.balance == 0)) stop("some species have no ", balance, " in the formation reaction")
}
}
return(list(n.balance = n.balance, balance = balance))
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/equilibrate.R
|
# CHNOSZ/examples.R
# Functions to run all examples and demos in the package
examples <- function(save.png = FALSE) {
# Run examples in each of the CHNOSZ help pages
.ptime <- proc.time()
topics <- c("thermo", "examples",
"util.array", "util.data", "util.expression", "util.legend", "util.plot",
"util.fasta", "util.formula", "util.misc", "util.seq", "util.units",
"util.water", "taxonomy", "info", "retrieve", "add.OBIGT", "protein.info",
"water", "IAPWS95", "subcrt", "Berman",
"makeup", "basis", "swap.basis", "species", "affinity",
"solubility", "equilibrate",
"diagram", "mosaic", "mix",
"buffer", "nonideal", "NaCl",
"add.protein", "ionize.aa", "EOSregress", "rank.affinity",
"DEW", "logB.to.OBIGT", "stack_mosaic"
)
plot.it <- FALSE
if(is.character(save.png))
png(paste(save.png, "%d.png", sep = ""), width = 500, height = 500, pointsize = 12)
else if(save.png) plot.it <- TRUE
for(i in 1:length(topics)) {
if(plot.it) png(paste(topics[i], "%d.png", sep = ""), width = 500, height = 500, pointsize = 12)
myargs <- list(topic = topics[i], ask = FALSE)
do.call(example, myargs)
if(plot.it) dev.off()
}
if(is.character(save.png)) dev.off()
cat("Time elapsed: ", proc.time() - .ptime, "\n")
}
demos <- function(which = c("sources", "protein.equil", "affinity", "NaCl", "density",
"ORP", "ionize", "buffer", "protbuff", "glycinate",
"mosaic", "copper", "arsenic", "solubility", "gold", "contour", "sphalerite", "minsol",
"Shh", "saturation", "adenine", "DEW", "lambda", "potassium", "TCA", "aluminum",
"AD", "comproportionation", "Pourbaix", "E_coli", "yttrium", "rank.affinity"), save.png = FALSE) {
# Run one or more demos from CHNOSZ with ask = FALSE, and return the value of the last one
out <- NULL
for(i in 1:length(which)) {
# A message so the user knows where we are
message("------------")
if(which[i] == "dehydration" & !save.png) {
message("demos: skipping dehydration demo as save.png is FALSE")
next
} else message(paste("demos: running '", which[i], "'", sep = ""))
if(save.png & !which[i] == "dehydration") {
width <- 500
height <- 500
if(which[i] == "comproportionation") width <- 600
png(paste(which[i], "%d.png", sep = ""), width = width, height = height, pointsize = 12)
}
out <- demo(which[i], package = "CHNOSZ", character.only = TRUE, echo = FALSE, ask = FALSE)
if(save.png & !which[i] == "dehydration") dev.off()
}
return(invisible(out))
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/examples.R
|
# CHNOSZ/hkf.R
# Calculate thermodynamic properties using equations of state
# 11/17/03 jmd
## If this file is interactively sourced, the following is also needed to provide unexported functions:
#source("util.args.R")
hkf <- function(property = NULL, parameters = NULL, T = 298.15, P = 1,
contrib = c("n", "s", "o"), H2O.props="rho") {
# Calculate G, H, S, Cp, V, kT, and/or E using the revised HKF equations of state
# H2O.props - H2O properties needed for subcrt() output
# Constants
Tr <- 298.15 # K
Pr <- 1 # bar
Theta <- 228 # K
Psi <- 2600 # bar
# Make T and P equal length
if(!identical(P, "Psat")) {
if(length(P) < length(T)) P <- rep(P, length.out = length(T))
if(length(T) < length(P)) T <- rep(T, length.out = length(P))
}
# Nonsolvation, solvation, and origination contribution
notcontrib <- ! contrib %in% c("n", "s", "o")
if(TRUE %in% notcontrib) stop(paste("contrib must be in c('n', 's', 'o); got", c2s(contrib[notcontrib])))
# Get water properties
# rho - for subcrt() output and g function
# Born functions and epsilon - for HKF calculations
H2O.props <- c(H2O.props, "QBorn", "XBorn", "YBorn", "epsilon")
thermo <- get("thermo", CHNOSZ)
if(grepl("SUPCRT", thermo$opt$water)) {
# Using H2O92D.f from SUPCRT92: alpha, daldT, beta - for partial derivatives of omega (g function)
H2O.props <- c(H2O.props, "alpha", "daldT", "beta")
}
if(grepl("IAPWS", thermo$opt$water)) {
# Using IAPWS-95: NBorn, UBorn - for compressibility, expansibility
H2O.props <- c(H2O.props, "NBorn", "UBorn")
}
if(grepl("DEW", thermo$opt$water)) {
# Using DEW model: get beta to calculate dgdP
H2O.props <- c(H2O.props, "beta")
} else {
# Don't allow DEW aqueous species if DEW water model isn't loaded 20220919
if(any(grepl("DEW", toupper(parameters$model)))) stop('The DEW water model is needed for one or more aqueous species. Run water("DEW") first.')
}
H2O <- water(H2O.props, T = c(Tr, T), P = c(Pr, P))
H2O.PrTr <- H2O[1, ]
H2O.PT <- H2O[-1, ]
ZBorn <- -1 / H2O.PT$epsilon
ZBorn.PrTr <- -1 / H2O.PrTr$epsilon
# A list to store the result
aq.out <- list()
nspecies <- nrow(parameters)
for(k in seq_len(nspecies)) {
# Loop over each species
PAR <- parameters[k, ]
# Substitute Cp and V for missing EoS parameters
# Here we assume that the parameters are in the same position as in thermo()$OBIGT
# We don't need this if we're just looking at solvation properties (Cp_s_var, V_s_var)
if("n" %in% contrib) {
# Put the heat capacity in for c1 if both c1 and c2 are missing
if(all(is.na(PAR[, 19:20]))) PAR[, 19] <- PAR$Cp
# Put the volume in for a1 if a1, a2, a3 and a4 are missing
if(all(is.na(PAR[, 15:18]))) PAR[, 15] <- convert(PAR$V, "joules")
# Test for availability of the EoS parameters
hasEOS <- any(!is.na(PAR[, 15:22]))
# If at least one of the EoS parameters is available, zero out any NA's in the rest
if(hasEOS) PAR[, 15:22][, is.na(PAR[, 15:22])] <- 0
}
# Compute values of omega(P,T) from those of omega(Pr,Tr)
# Using g function etc. (Shock et al., 1992 and others)
omega <- PAR$omega # omega.PrTr
# The derivatives are zero unless the g function kicks in
dwdP <- dwdT <- d2wdT2 <- numeric(length(T))
Z <- PAR$Z
omega.PT <- rep(PAR$omega, length(T))
if(!identical(Z, 0) & !is.na(Z) & !identical(PAR$name, "H+")) {
# Compute derivatives of omega: g and f functions (Shock et al., 1992; Johnson et al., 1992)
rhohat <- H2O.PT$rho/1000 # just converting kg/m3 to g/cm3
g <- gfun(rhohat, convert(T, "C"), P, H2O.PT$alpha, H2O.PT$daldT, H2O.PT$beta)
# After SUPCRT92/reac92.f
# eta needs to be converted to Joules! 20220325
eta <- convert(1.66027E5, "J")
reref <- Z^2 / (omega/eta + Z/(3.082 + 0))
re <- reref + abs(Z) * g$g
omega.PT <- eta * (Z^2/re - Z/(3.082 + g$g))
Z3 <- abs(Z^3)/re^2 - Z/(3.082 + g$g)^2
Z4 <- abs(Z^4)/re^3 - Z/(3.082 + g$g)^3
dwdP <- (-eta * Z3 * g$dgdP)
dwdT <- (-eta * Z3 * g$dgdT)
d2wdT2 <- (2 * eta * Z4 * g$dgdT^2 - eta * Z3 * g$d2gdT2)
}
# Loop over each property
w <- NULL
for(i in 1:length(property)) {
PROP <- property[i]
# Over nonsolvation, solvation, or origination contributions
hkf.p <- numeric(length(T))
for(icontrib in contrib) {
# Various contributions to the properties
if(icontrib == "n") {
# Nonsolvation ghs equations
if(PROP == "H") {
p.c <- PAR$c1*(T-Tr) - PAR$c2*(1/(T-Theta)-1/(Tr-Theta))
p.a <- PAR$a1*(P-Pr) + PAR$a2*log((Psi+P)/(Psi+Pr)) +
((2*T-Theta)/(T-Theta)^2)*(PAR$a3*(P-Pr)+PAR$a4*log((Psi+P)/(Psi+Pr)))
p <- p.c + p.a
} else if(PROP == "S") {
p.c <- PAR$c1*log(T/Tr) -
(PAR$c2/Theta)*( 1/(T-Theta)-1/(Tr-Theta) +
log( (Tr*(T-Theta))/(T*(Tr-Theta)) )/Theta )
p.a <- (T-Theta)^(-2)*(PAR$a3*(P-Pr)+PAR$a4*log((Psi+P)/(Psi+Pr)))
p <- p.c + p.a
} else if(PROP == "G") {
p.c <- -PAR$c1*(T*log(T/Tr)-T+Tr) -
PAR$c2*( (1/(T-Theta)-1/(Tr-Theta))*((Theta-T)/Theta) -
(T/Theta^2)*log((Tr*(T-Theta))/(T*(Tr-Theta))) )
p.a <- PAR$a1*(P-Pr) + PAR$a2*log((Psi+P)/(Psi+Pr)) +
(PAR$a3*(P-Pr) + PAR$a4*log((Psi+P)/(Psi+Pr)))/(T-Theta)
p <- p.c + p.a
# If the origination contribution is not NA at Tr,Pr, ensure the solvation contribution is 0, not NA
if(!is.na(PAR$G)) p[T==Tr & P==Pr] <- 0
# Nonsolvation cp v kt e equations
} else if(PROP == "Cp") {
p <- PAR$c1 + PAR$c2 * ( T - Theta ) ^ (-2)
} else if(PROP == "V") {
p <- convert(PAR$a1, "cm3bar") +
convert(PAR$a2, "cm3bar") / (Psi + P) +
(convert(PAR$a3, "cm3bar") + convert(PAR$a4, "cm3bar") / (Psi + P)) / (T - Theta)
} else if(PROP == "kT") {
p <- (convert(PAR$a2, "cm3bar") +
convert(PAR$a4, "cm3bar") / (T - Theta)) * (Psi + P) ^ (-2)
} else if(PROP == "E") {
p <- convert( - (PAR$a3 + PAR$a4 / convert((Psi + P), "joules")) *
(T - Theta) ^ (-2), "cm3bar")
}
}
if(icontrib == "s") {
# Solvation ghs equations
if(PROP == "G") {
p <- -omega.PT*(ZBorn+1) + omega*(ZBorn.PrTr+1) + omega*H2O.PrTr$YBorn*(T-Tr)
# If the origination contribution is not NA at Tr,Pr, ensure the solvation contribution is 0, not NA
if(!is.na(PAR$G)) p[T == Tr & P == Pr] <- 0
}
if(PROP == "H")
p <- -omega.PT*(ZBorn+1) + omega.PT*T*H2O.PT$YBorn + T*(ZBorn+1)*dwdT +
omega*(ZBorn.PrTr+1) - omega*Tr*H2O.PrTr$YBorn
if(PROP == "S")
p <- omega.PT*H2O.PT$YBorn + (ZBorn+1)*dwdT - omega*H2O.PrTr$YBorn
# Solvation cp v kt e equations
if(PROP == "Cp") p <- omega.PT*T*H2O.PT$XBorn + 2*T*H2O.PT$YBorn*dwdT +
T*(ZBorn+1)*d2wdT2
if(PROP == "V") p <- -convert(omega.PT, "cm3bar") *
H2O.PT$QBorn + convert(dwdP, "cm3bar") * (-ZBorn - 1)
# TODO: the partial derivatives of omega are not included here here for kt and e
# (to do it, see p. 820 of SOJ+92 ... but kt requires d2wdP2 which we don"t have yet)
if(PROP == "kT") p <- convert(omega, "cm3bar") * H2O.PT$NBorn
if(PROP == "E") p <- -convert(omega, "cm3bar") * H2O.PT$UBorn
}
if(icontrib == "o") {
# Origination ghs equations
if(PROP == "G") {
p <- PAR$G - PAR$S * (T-Tr)
# Don't inherit NA from PAR$S at Tr
p[T == Tr] <- PAR$G
}
else if(PROP == "H") p <- PAR$H
else if(PROP == "S") p <- PAR$S
# Origination eos equations (Cp, V, kT, E): senseless
else p <- 0 * T
}
# Accumulate the contribution
hkf.p <- hkf.p + p
}
wnew <- data.frame(hkf.p)
if(i > 1) w <- cbind(w, wnew) else w <- wnew
}
colnames(w) <- property
aq.out[[k]] <- w
}
return(list(aq = aq.out, H2O = H2O.PT))
}
### Unexported functions ###
gfun <- function(rhohat, Tc, P, alpha, daldT, beta) {
## g and f functions for describing effective electrostatic radii of ions
## Split from hkf() 20120123 jmd
## Based on equations in
## Shock EL, Oelkers EH, Johnson JW, Sverjensky DA, Helgeson HC, 1992
## Calculation of the Thermodynamic Properties of Aqueous Species at High Pressures
## and Temperatures: Effective Electrostatic Radii, Dissociation Constants and
## Standard Partial Molal Properties to 1000 degrees C and 5 kbar
## J. Chem. Soc. Faraday Trans., 88(6), 803-826 doi:10.1039/FT9928800803
# rhohat - density of water in g/cm3
# Tc - temperature in degrees Celsius
# P - pressure in bars
# Start with an output list of zeros
out0 <- numeric(length(rhohat))
out <- list(g=out0, dgdT=out0, d2gdT2=out0, dgdP=out0)
# Only rhohat less than 1 will give results other than zero
idoit <- rhohat < 1 & !is.na(rhohat)
rhohat <- rhohat[idoit]
Tc <- Tc[idoit]
P <- P[idoit]
alpha <- alpha[idoit]
daldT <- daldT[idoit]
beta <- beta[idoit]
# eta in Eq. 1
eta <- 1.66027E5
# Table 3
ag1 <- -2.037662
ag2 <- 5.747000E-3
ag3 <- -6.557892E-6
bg1 <- 6.107361
bg2 <- -1.074377E-2
bg3 <- 1.268348E-5
# Eq. 25
ag <- ag1 + ag2 * Tc + ag3 * Tc ^ 2
# Eq. 26
bg <- bg1 + bg2 * Tc + bg3 * Tc ^ 2
# Eq. 24
g <- ag * (1 - rhohat) ^ bg
# Table 4
af1 <- 0.3666666E2
af2 <- -0.1504956E-9
af3 <- 0.5017997E-13
# Eq. 33
f <-
( ((Tc - 155) / 300) ^ 4.8 + af1 * ((Tc - 155) / 300) ^ 16 ) *
( af2 * (1000 - P) ^ 3 + af3 * (1000 - P) ^ 4 )
# Limits of the f function (region II of Fig. 6)
ifg <- Tc > 155 & P < 1000 & Tc < 355
# In case any T or P are NA
ifg <- ifg & !is.na(ifg)
# Eq. 32
g[ifg] <- g[ifg] - f[ifg]
# At P > 6000 bar (in DEW calculations), g is zero 20170926
g[P > 6000] <- 0
## Now we have g at P, T
# Put the results in their right place (where rhohat < 1)
out$g[idoit] <- g
## The rest is to get its partial derivatives with pressure and temperature
## After Johnson et al., 1992
# alpha - coefficient of isobaric expansivity (K^-1)
# daldT - temperature derivative of coefficient of isobaric expansivity (K^-2)
# beta - coefficient of isothermal compressibility (bar^-1)
# If these are NULL or NA (for IAPWS-95 and DEW), we skip the calculation
if(is.null(alpha)) alpha <- NA
if(is.null(daldT)) daldT <- NA
if(is.null(beta)) beta <- NA
# Eqn. 76
d2fdT2 <- (0.0608/300*((Tc-155)/300)^2.8 + af1/375*((Tc-155)/300)^14) * (af2*(1000-P)^3 + af3*(1000-P)^4)
# Eqn. 75
dfdT <- (0.016*((Tc-155)/300)^3.8 + 16*af1/300*((Tc-155)/300)^15) * (af2*(1000-P)^3 + af3*(1000-P)^4)
# Eqn. 74
dfdP <- -(((Tc-155)/300)^4.8 + af1*((Tc-155)/300)^16) * (3*af2*(1000-P)^2 + 4*af3*(1000-P)^3)
d2bdT2 <- 2 * bg3 # Eqn. 73
d2adT2 <- 2 * ag3 # Eqn. 72
dbdT <- bg2 + 2*bg3*Tc # Eqn. 71
dadT <- ag2 + 2*ag3*Tc # Eqn. 70
if(!all(is.na(alpha)) & !all(is.na(daldT))) {
# Eqn. 69
dgadT <- bg*rhohat*alpha*(1-rhohat)^(bg-1) + log(1-rhohat)*g/ag*dbdT
D <- rhohat
# Transcribed from SUPCRT92/reac92.f
dDdT <- -D * alpha
#dDdP <- D * beta
dDdTT <- -D * (daldT - alpha^2)
Db <- (1-D)^bg
dDbdT <- -bg*(1-D)^(bg-1)*dDdT + log(1-D)*Db*dbdT
dDbdTT <- -(bg*(1-D)^(bg-1)*dDdTT + (1-D)^(bg-1)*dDdT*dbdT +
bg*dDdT*(-(bg-1)*(1-D)^(bg-2)*dDdT + log(1-D)*(1-D)^(bg-1)*dbdT)) +
log(1-D)*(1-D)^bg*d2bdT2 - (1-D)^bg*dbdT*dDdT/(1-D) + log(1-D)*dbdT*dDbdT
d2gdT2 <- ag*dDbdTT + 2*dDbdT*dadT + Db*d2adT2
d2gdT2[ifg] <- d2gdT2[ifg] - d2fdT2[ifg]
dgdT <- g/ag*dadT + ag*dgadT # Eqn. 67
dgdT[ifg] <- dgdT[ifg] - dfdT[ifg]
# phew! done with those derivatives
out$dgdT[idoit] <- dgdT
out$d2gdT2[idoit] <- d2gdT2
}
if(!all(is.na(beta))) {
dgdP <- -bg*rhohat*beta*g*(1-rhohat)^-1 # Eqn. 66
dgdP[ifg] <- dgdP[ifg] - dfdP[ifg]
out$dgdP[idoit] <- dgdP
}
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/hkf.R
|
# CHNOSZ/info.R
# Search database for species names or formulas
# and retrieve thermodynamic properties of species
# 20061024 Extracted from species.R jmd
# 20120507 Code rewrite and split into info.[character,approx,numeric];
# These functions expect arguments of length 1;
# info() handles longer arguments
## If this file is interactively sourced, the following are also needed to provide unexported functions:
#source("util.data.R")
info <- function(species = NULL, state = NULL, check.it = TRUE) {
## Return information for one or more species in thermo()$OBIGT
thermo <- get("thermo", CHNOSZ)
# That should give us the data, not the thermo() function 20190928
if(is.function(thermo)) stop("CHNOSZ package data is not available; use reset() or library(CHNOSZ) to load it")
## If no species are requested, summarize the available data 20101129
if(is.null(species)) {
message("info: 'species' is NULL; summarizing information about thermodynamic data...")
message(paste("thermo()$OBIGT has", nrow(thermo$OBIGT[thermo$OBIGT$state == "aq", ]), "aqueous,",
nrow(thermo$OBIGT), "total species"))
message(paste("number of literature sources: ", nrow(thermo$refs), ", elements: ",
nrow(thermo$element), ", buffers: ", length(unique(thermo$buffer$name)), sep = ""))
message(paste("number of proteins in thermo()$protein is", nrow(thermo$protein), "from",
length(unique(thermo$protein$organism)), "organisms"))
return()
}
## Run info.numeric or info.character depending on the input type
if(is.numeric(species)) {
out <- lapply(species, info.numeric, check.it)
# If we have different states the column names could be different
if(length(unique(unlist(lapply(out, names)))) > ncol(thermo$OBIGT)) {
# make them the same as thermo$OBIGT
out <- lapply(out, function(row) {
colnames(row) <- colnames(thermo$OBIGT); return(row)
})
}
# Turn the list into a data frame
out <- do.call(rbind, out)
# Ensure that the rownames are numeric values (not names possibly inherited from retrieve()) 20190224
if(!is.null(attr(species, "names"))) row.names(out) <- species
} else {
# State and species should be same length
if(!is.null(state)) {
lmax <- max(length(species), length(state))
state <- rep(state, length.out = lmax)
species <- rep(species, length.out = lmax)
}
# Loop over the species
out <- sapply(seq_along(species), function(i) {
# First look for exact match
ispecies <- info.character(species[i], state[i])
# If no exact match and it's not a protein, show approximate matches (side effect of info.approx)
if(identical(ispecies, NA) & !grepl("_", species[i])) ispecies.notused <- info.approx(species[i], state[i])
# Do not accept multiple matches
if(length(ispecies) > 1) ispecies <- NA
return(ispecies)
})
}
## All done!
return(out)
}
### Unexported functions ###
info.text <- function(ispecies, withsource = TRUE) {
# a textual description of species name, formula, source, e.g.
# CO2 [CO2(aq)] (SSW01, SHS89, 11.Oct.07)
this <- get("thermo", CHNOSZ)$OBIGT[ispecies, ]
out <- paste(this$name, " [", this$formula, "(", this$state, ")", "]", sep = "")
if(!withsource) return(out)
sourcetext <- this$ref1
ref2 <- this$ref2
if(!is.na(ref2)) sourcetext <- paste(sourcetext, ref2, sep = ", ")
date <- this$date
if(!is.na(date)) sourcetext <- paste(sourcetext, date, sep = ", ")
out <- paste(out, " (", sourcetext, ")", sep = "")
return(out)
}
info.character <- function(species, state = NULL, check.protein = TRUE) {
# Return the rownumbers of thermo()$OBIGT having an exact match of 'species' to
# thermo()$OBIGT$[species|abbrv|formula] or NA otherwise
# A match to thermo()$OBIGT$state is also required if 'state' is not NULL
# (first occurence of a match to species is returned otherwise)
thermo <- get("thermo", CHNOSZ)
# Find matches for species name, abbreviation or formula
matches.species <- thermo$OBIGT$name == species | thermo$OBIGT$abbrv == species | thermo$OBIGT$formula == species
# Since thermo()$OBIGT$abbrv contains NAs, convert NA results to FALSE
matches.species[is.na(matches.species)] <- FALSE
# Turn it in to no match if it's a protein in the wrong state
ip <- pinfo(species)
if(any(matches.species) & !is.na(ip) & !is.null(state)) {
matches.state <- matches.species & grepl(state, thermo$OBIGT$state)
if(!any(matches.state)) matches.species <- FALSE
}
# No match, not available
if(!any(matches.species)) {
# Unless it's a protein
if(check.protein) {
# Did we find a protein? add its properties to OBIGT
if(!is.na(ip)) {
# Here we use a default state from thermo()$opt$state
if(is.null(state)) state <- thermo$opt$state
# Add up protein properties
eos <- protein.OBIGT(ip, state = state)
# The real assignment work
nrows <- suppressMessages(mod.OBIGT(eos))
thermo <- get("thermo", CHNOSZ)
matches.species <- rep(FALSE, nrows)
matches.species[nrows] <- TRUE
} else return(NA)
} else return(NA)
}
# Do we demand a particular state
if(!is.null(state)) {
# Special treatment for H2O: aq retrieves the liq
if(species %in% c("H2O", "water") & state == "aq") state <- "liq"
# The matches for both species and state
matches.state <- matches.species & state == thermo$OBIGT$state
if(!any(matches.state)) {
# The requested state is not available for this species
available.states <- thermo$OBIGT$state[matches.species]
if(length(available.states) == 1) a.s.verb <- "is" else a.s.verb <- "are"
a.s.text <- paste("'", available.states, "'", sep = "", collapse = " ")
message("info.character: requested state '", state, "' for ", species,
" but only ", a.s.text, " ", a.s.verb, " available")
# Warn about looking for aqueous methane (changed to CH4) 20200707
if(identical(species, "methane") & identical(state, "aq")) {
warning("'methane' is not an aqueous species; use 'CH4' instead\nTo revert to the old behavior, run mod.OBIGT(info('CH4'), name = 'methane')")
}
return(NA)
}
matches.species <- matches.state
}
# All of the species that match
ispecies.out <- ispecies <- which(matches.species)
# Processing for more than one match
if(length(ispecies) > 1) {
# If a single name matches, use that one (useful for distinguishing pseudo-H4SiO4 and H4SiO4) 20171020
matches.name <- matches.species & thermo$OBIGT$name == species
if(sum(matches.name) == 1) ispecies.out <- which(matches.name)
else ispecies.out <- ispecies[1] # otherwise, return only the first species that matches
# Let user know if there is more than one state for this species
mystate <- thermo$OBIGT$state[ispecies.out]
ispecies.other <- ispecies[!ispecies %in% ispecies.out]
otherstates <- thermo$OBIGT$state[ispecies.other]
# For non-aqueous species, list other substances (isomers) in the same state 20210321
if(mystate != "aq" & sum(otherstates == mystate) > 0) {
otherstates[otherstates == mystate] <- thermo$OBIGT$name[ispecies.other[otherstates == mystate]]
}
transtext <- othertext <- ""
# We count, but don't show the states for polymorphic transitions (cr2, cr3, etc)
istrans <- otherstates %in% c("cr2", "cr3", "cr4", "cr5", "cr6", "cr7", "cr8", "cr9")
if(mystate == "cr") {
# If we are "cr" we show the number of polymorphic transitions
ntrans <- sum(istrans)
if(ntrans == 1) transtext <- paste(" with", ntrans, "polymorphic transition")
else if(ntrans > 1) transtext <- paste(" with", ntrans, "polymorphic transitions")
}
myname <- NULL
if(mystate != "aq") {
# If it's not already in the species name, append the substance name 20210323
myname <- thermo$OBIGT$name[ispecies.out]
if(species == myname) myname <- NULL
}
otherstates <- unique(otherstates[!istrans])
if(length(otherstates) == 1) othertext <- paste0("; also available in ", otherstates)
if(length(otherstates) > 1) othertext <- paste0("; also available in ", paste(otherstates, collapse = ", "))
if(transtext != "" | othertext != "") {
starttext <- paste0("info.character: found ", species, "(", mystate, ")")
if(!is.null(myname)) starttext <- paste0(starttext, " [", myname, "]")
message(starttext, transtext, othertext)
}
}
return(ispecies.out)
}
info.numeric <- function(ispecies, check.it = TRUE) {
# From a numeric species index in 'ispecies' return the
# thermodynamic properties and equations-of-state parameters
thermo <- get("thermo", CHNOSZ)
# if we're called with NA, return an empty row
if(is.na(ispecies)) {
this <- thermo$OBIGT[1,]
this[] <- NA
return(this)
}
this <- thermo$OBIGT[ispecies,]
# Species indices must be in range
ispeciesmax <- nrow(thermo$OBIGT)
if(ispecies > ispeciesmax | ispecies < 1)
stop(paste("species index", ispecies, "not found in thermo()$OBIGT\n"))
# Remove scaling factors on EOS parameters depending on state
# Use new OBIGT2eos function here
this <- OBIGT2eos(this, this$state)
# Stop with an informative message if species don't have a model 20220929
namodel <- is.na(this$model)
if(namodel) stop(paste("Species has NA model:", info.text(ispecies, FALSE)), call. = FALSE)
if(tolower(this$model) == "berman") { # this is Berman
# Get G, H, S, and V for minerals with Berman parameters 20220203
Bermandat <- Berman()
Bermandat <- Bermandat[Bermandat$name == this$name, ]
this[, c("G", "H", "S", "V")] <- Bermandat[, c("GfPrTr", "HfPrTr", "SPrTr", "VPrTr")] * c(1, 1, 1, 10)
isBerman <- TRUE
} else isBerman <- FALSE
# Identify any missing GHS values
naGHS <- is.na(this[10:12])
# A missing one of G, H or S can cause problems for subcrt calculations at high T
if(sum(naGHS) == 1) {
# calculate a single missing one of G, H, or S from the others
GHS <- as.numeric(GHS(as.character(this$formula), G = this[, 10], H = this[, 11], S = this[, 12], E_units = this$E_units))
message("info.numeric: ", colnames(this)[10:12][naGHS], " of ",
this$name, "(", this$state, ") is NA; set to ", round(GHS[naGHS],2), " ", this$E_units, " mol-1")
this[, which(naGHS) + 9] <- GHS[naGHS]
}
# Perform consistency checks for GHS and EOS parameters if check.it = TRUE
# Don't do it for the AD species 20190219
if(check.it & this$model != "AD") {
# Check GHS if they are all present
if(sum(naGHS) == 0) calcG <- check.GHS(this, return.difference = FALSE)
# Check heat capacities in database against EOS parameters
calcCp <- check.EOS(this, this$model, "Cp", return.difference = FALSE)
# Fill in NA heat capacity
if(!is.na(calcCp) & is.na(this$Cp)) {
message("info.numeric: Cp\u00B0 of ", this$name, "(", this$state, ") is NA; set by EOS parameters to ", round(calcCp, 2), " ", this$E_units, " K-1 mol-1")
this$Cp <- as.numeric(calcCp)
} else if(isBerman) {
# Calculate Cp for Berman minerals 20220208
calcCp <- Berman(this$name)$Cp
this$Cp <- calcCp
}
# Check volumes in database - only for HKF model (aq species)
if(this$model %in% c("HKF", "DEW")) {
calcV <- check.EOS(this, this$model, "V", return.difference = FALSE)
# Fill in NA volume
if(!is.na(calcV) & is.na(this$V)) {
message("info.numeric: V\u00B0 of ", this$name, "(", this$state, ") is NA; set by EOS parameters to ", round(calcV, 2), " cm3 mol-1")
this$V <- as.numeric(calcV)
}
}
} # Done checking
# All done!
return(this)
}
info.approx <- function(species, state = NULL) {
# Returns species indices that have an approximate match of 'species'
# to thermo$OBIGT$[name|abbrv|formula], possibly restricted to a given state
thermo <- get("thermo", CHNOSZ)
if(!is.null(state)) this <- thermo$OBIGT[thermo$OBIGT$state == state, ]
else this <- thermo$OBIGT
# Only look for fairly close matches
max.distance <- 0.1
approx.name <- agrep(species, this$name, max.distance)
approx.abbrv <- agrep(species, this$abbrv, max.distance)
approx.formula <- agrep(species, this$formula, max.distance)
approx.species <- unique(c(approx.name, approx.abbrv, approx.formula))
if(!is.na(approx.species[1])) {
# Show the names of the species
if(length(approx.species) == 1) {
message("info.approx: '", species, "' is similar to ", info.text(approx.species))
} else {
napprox.max <- 100
exttext <- ":"
if(length(approx.species) > napprox.max) exttext <- paste(" (showing first ", napprox.max, ")", sep = "")
message("info.approx: '", species, "' is ambiguous; has approximate matches to ",
length(approx.species), " species", exttext)
printout <- capture.output(print(thermo$OBIGT$name[head(approx.species, napprox.max)]))
message(paste(printout, collapse = "\n"))
}
return(approx.species)
}
# If we got here there were no approximate matches
# 20190127 look for the species in optional data files
for(opt in c("SLOP98", "SUPCRT92", "AD")) {
optdat <- read.csv(system.file(paste0("extdata/OBIGT/", opt, ".csv"), package = "CHNOSZ"), as.is = TRUE)
if(species %in% optdat$name) {
message('info.approx: ', species, ' is in an optional database; use add.OBIGT("', opt, '", "', species, '") to load it')
return(NA)
}
}
message("info.approx: '", species, "' has no approximate matches")
return(NA)
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/info.R
|
# CHNOSZ/ionize.aa.R
# Rewritten ionization function 20120526 jmd
ionize.aa <- function(aa, property = "Z", T = 25, P = "Psat", pH = 7, ret.val = NULL, suppress.Cys = FALSE) {
# Calculate the additive ionization property of proteins with amino acid
# composition in aa as a function of vectors of T, P and pH;
# property if NULL is the net charge, if not NULL is one of the subcrt() properties
# or "A" to calculate A/2.303RT for the ionization reaction
# ret.val can be 'pK', 'alpha' or 'aavals' to get these values;
# T, P and pH should be same length, or larger a multiple of the smaller
lmax <- max(c(length(T), length(P), length(pH)))
T <- rep(T, length.out = lmax)
P <- rep(P, length.out = lmax)
pH <- rep(pH, length.out = lmax)
# Turn pH into a matrix with as many columns as ionizable groups
pH <- matrix(rep(pH, 9), ncol = 9)
# Turn charges into a matrix with as many rows as T,P,pH conditions
charges <- c(-1, -1, -1, 1, 1, 1, -1, 1, -1)
charges <- matrix(rep(charges, lmax), nrow = lmax, byrow = TRUE)
# The rownumbers of the ionizable groups in thermo()$OBIGT
neutral <- c("[Cys]", "[Asp]", "[Glu]", "[His]", "[Lys]", "[Arg]", "[Tyr]", "[AABB]", "[AABB]")
charged <- c("[Cys-]","[Asp-]","[Glu-]","[His+]","[Lys+]","[Arg+]","[Tyr-]","[AABB+]","[AABB-]")
ineutral <- info(neutral, "aq")
icharged <- info(charged, "aq")
# We'll only call subcrt() with the unique pressure/temperature combinations
pTP <- paste(T, P)
dupPT <- duplicated(pTP)
# What property are we after
sprop <- c("G", property)
if(property %in% c("A", "Z")) sprop <- "G"
# Use convert = FALSE so we get results in Joules 20210407
# (means we need to supply temperature in Kelvin)
TK <- convert(T, "K")
sout <- subcrt(c(ineutral, icharged), T = TK[!dupPT], P = P[!dupPT], property = sprop, convert = FALSE)$out
# The G-values
Gs <- sapply(sout, function(x) x$G)
# Keep it as a matrix even if we have only one unique T, P-combo
if(length(pTP[!dupPT]) == 1) Gs <- t(Gs)
# Now the Gibbs energy difference for each group
DG <- Gs[, 10:18, drop = FALSE] - Gs[, 1:9, drop = FALSE]
# Build a matrix with one row for each of the (possibly duplicated) T, P values
uPT <- unique(pTP)
DG <- t(sapply(pTP, function(x) DG[match(x, uPT), , drop = FALSE]))
# The pK values (-logK)
DG <- DG * charges
pK <- apply(DG, 2, function(x) convert(x, "logK", T = TK))
# Keep it as a matrix even if we have only one T, P-combo
if(lmax == 1) pK <- t(pK)
if(identical(ret.val, "pK")) {
colnames(pK) <- charged
return(pK)
}
# Now to calculate alpha! - degrees of formation of the charged groups
alpha <- 1 / (1 + 10 ^ (charges * (pH - pK)))
# Suppress cysteine ionization if requested
if(suppress.Cys) alpha[, 1] <- 0
if(identical(ret.val, "alpha")) return(alpha)
# Now to calculate the properties of the ionizable groups - can be charges,
# the chemical affinities of the ionization reactions,
# or another property from subcrt()
if(identical(property, "Z")) aavals <- charges
else if(identical(property, "A")) aavals <- - charges * (pH - pK)
else {
# It's not charge, so compile it from the subcrt output
# the property-values
icol <- match(property, colnames(sout[[1]]))
aavals <- sapply(sout, function(x) x[,icol])
# Keep it as a matrix even if we have only one unique T, P-combo
if(length(pTP[!dupPT]) == 1) aavals <- t(aavals)
# Build a matrix with one row for each of the (possibly duplicated) T, P values
aavals <- t(sapply(pTP, function(x) aavals[match(x, uPT), , drop = FALSE], USE.NAMES = FALSE))
# The property difference for each group
aavals <- aavals[, 10:18, drop = FALSE] - aavals[, 1:9, drop = FALSE]
}
if(identical(ret.val, "aavals")) {
colnames(aavals) <- charged
return(aavals)
}
# The contribution from each group to the ionization property of the protein
aavals <- aavals * alpha
# Now work with 'aa'; the next line is so that a missing argument shows
# The name of this function in the error message
aa <- aa
# The columns where we find the counts of ionizable groups
iionize <- match(c("Cys", "Asp", "Glu", "His", "Lys", "Arg", "Tyr", "chains", "chains"), colnames(aa))
aa <- as.matrix(aa[, iionize])
# Add it all up
out <- apply(aa, 1, function(x) {
aavals %*% x
})
# Keep it as a matrix even if we have only one T, P-combo
if(lmax == 1) out <- t(out)
rownames(out) <- rownames(aavals)
# That's all folks!
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/ionize.aa.R
|
# CHNOSZ/logB.to.OBIGT.R
# Get thermodynamic parameters from formation constants (logB) as a function of temperature
# 20220324 v1 Regress three parameters (G, S, and Cp)
# 20221202 v2 Regress HKF parameters (assume constant pressure and optimize omega parameter for charged species)
logB.to.OBIGT <- function(logB, species, coeffs, T, P, npar = 3, optimize.omega = FALSE, tolerance = 0.05) {
# We need at least five temperature values to optimize omega
if(optimize.omega & length(unique(T)) < 5) {
message("logB.to.OBIGT: forcing optimize.omega = FALSE because there are < 5 T values")
optimize.omega <- FALSE
}
# We need five parameters to optimize omega 20221209
if(optimize.omega & npar != 5) {
message("logB.to.OBIGT: forcing optimize.omega = FALSE because npar != 5")
optimize.omega <- FALSE
}
## Get the formula of the formed species (used as the species name in OBIGT)
### NOTE: the formed species has to be *last* in this list
name <- tail(species, 1)
# Add the formed species to the thermodynamic database with ΔG°f = 0 at all temperatures
# Be sure to zap properties of a formed species that is already in the database
suppressMessages(mod.OBIGT(name, formula = name, E_units = E.units(), G = 0, S = 0, Cp = 0, zap = TRUE))
# Calculate logK of the formation reaction with ΔG°f = 0 for the formed species
logK0 <- suppressMessages(subcrt(species, coeffs, T = T, P = P)$out$logK)
## Get Gibbs energy of species from logB of reaction
# Calculate T in Kelvin
TK <- convert(T, "K")
# logB gives values for ΔG°r of the reaction
Gr <- convert(logB, "G", TK)
# logK0 gives values for ΔG°r of the reaction with ΔG°f = 0 for the formed species
Gr0 <- convert(logK0, "G", TK)
# Calculate ΔG°f of the formed species
Gf <- Gr - Gr0
## Fit to HKF 20221202
# Get blank set of HKF parameters
PAR <- info(info("H+"))
# DON'T keep the name H+, becuase it tells hkf() to not calculate g function
PAR$name <- name
# Insert charge of formed species (for calculating g function and variable omega)
Z <- makeup(c(name, "Z0"), sum = TRUE)["Z"]
# Force charge to be 0 when optimize.omega is FALSE 20221208
if(!optimize.omega) Z <- 0
PAR$Z <- Z
# Get values of T and P (so "Psat" becomes numeric) 20221208
tpargs <- TP.args(T = TK, P = P)
# Calculate variable terms for S, c1, c2, and omega
# NOTE: Units of Kelvin for HKF
S_var <- hkf("G", T = tpargs$T, P = tpargs$P, parameters = transform(PAR, S = 1))$aq[[1]]$G
c1_var <- hkf("G", T = tpargs$T, P = tpargs$P, parameters = transform(PAR, c1 = 1))$aq[[1]]$G
c2_var <- hkf("G", T = tpargs$T, P = tpargs$P, parameters = transform(PAR, c2 = 1))$aq[[1]]$G
omega_var <- hkf("G", T = tpargs$T, P = tpargs$P, parameters = transform(PAR, omega = 1))$aq[[1]]$G
if(!optimize.omega) {
# Default values
omega <- NA
c2 <- NA
c1 <- NA
S <- NA
if(npar == 5) {
# Perform linear regression with constant omega
Glm <- lm(Gf ~ S_var + c1_var + c2_var + omega_var)
omega <- Glm$coefficients["omega_var"]
c2 <- Glm$coefficients["c2_var"]
c1 <- Glm$coefficients["c1_var"]
S <- Glm$coefficients["S_var"]
G <- Glm$coefficients["(Intercept)"]
} else if(npar == 4) {
# Now with fewer parameters
Glm <- lm(Gf ~ S_var + c1_var + c2_var)
c2 <- Glm$coefficients["c2_var"]
c1 <- Glm$coefficients["c1_var"]
S <- Glm$coefficients["S_var"]
G <- Glm$coefficients["(Intercept)"]
} else if(npar == 3) {
Glm <- lm(Gf ~ S_var + c1_var)
c1 <- Glm$coefficients["c1_var"]
S <- Glm$coefficients["S_var"]
G <- Glm$coefficients["(Intercept)"]
} else if(npar == 2) {
Glm <- lm(Gf ~ S_var)
S <- Glm$coefficients["S_var"]
G <- Glm$coefficients["(Intercept)"]
} else if(npar == 1) {
G <- mean(Gf)
} else stop("invalid value for npar (should be from 1 to 5)")
} else {
# Function to perform linear regression for a given omega(Pr,Tr)
Gfun <- function(omega) {
PAR$omega <- omega
omega_var <- hkf("G", T = tpargs$T, P = tpargs$P, parameters = PAR)$aq[[1]]$G
# Subtract omega term from Gf
Gf_omega <- Gf - omega_var
# Perform linear regression with all terms except omega
lm(Gf_omega ~ S_var + c1_var + c2_var)
}
# Calculate the sum of squares of residuals for given omega(Pr,Tr)
Sqfun <- function(omega) sum(Gfun(omega)$residuals ^ 2)
# Find the omega(Pr,Tr) that minimizes the sum of squares of residuals
omega <- optimize(Sqfun, c(-1e10, 1e10))$minimum
# Construct the linear model with this omega
Glm <- Gfun(omega)
# Get coefficients other than omega
G <- Glm$coefficients["(Intercept)"]
S <- Glm$coefficients["S_var"]
c1 <- Glm$coefficients["c1_var"]
c2 <- Glm$coefficients["c2_var"]
}
# NAs propagate as zero in the HKF equations
if(is.na(S)) S <- 0
if(is.na(c1)) c1 <- 0
if(is.na(c2)) c2 <- 0
if(is.na(omega)) omega <- 0
# Calculate Cp at 25 °C (not used in HKF - just for info() and check.EOS())
PAR$c1 <- c1
PAR$c2 <- c2
PAR$omega <- omega
Cp <- hkf("Cp", parameters = PAR)$aq[[1]]$Cp
## Update the thermodynamic parameters of the formed species
# NOTE: we have to apply OOM scaling
ispecies <- do.call(mod.OBIGT, list(name = name, G = G, S = S, Cp = Cp, c1 = c1, c2 = c2 * 1e-4, omega = omega * 1e-5, z = Z))
# Calculate logK of the formation reaction with "real" ΔG°f for the formed species
logK <- suppressMessages(subcrt(species, coeffs, T = T, P = P)$out$logK)
# Calculate the mean absolute difference
mad <- mean(abs(logK - logB))
message(paste("logB.to.OBIGT: mean difference between logB (experimental) and logK (calculated) is", round(mad, 4)))
# Check that calculated values are close to input values
stopifnot(all.equal(logK, logB, tolerance = tolerance, scale = 1))
# Return the species index in OBIGT
ispecies
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/logB.to.OBIGT.R
|
# CHNOSZ/makeup.R
## If this file is interactively sourced, the following are also needed to provide unexported functions:
#source("util.formula.R")
#source("util.character.R")
makeup <- function(formula, multiplier = 1, sum = FALSE, count.zero = FALSE) {
# Return the elemental makeup (counts) of a chemical formula
# that may contain suffixed and/or parenthetical subformulas and/or charge
# and negative or positive, fractional coefficients
# A matrix is processed by rows
if(is.matrix(formula))
return(lapply(seq_len(nrow(formula)),
function(i) makeup(formula[i, ])))
# A named numeric object is returned untouched
# (needed for recursive operation of the function?
# - if this is not done it messes up the HOX example in protein.info.Rd)
if(!is.null(names(formula)) & is.numeric(formula)) return(formula)
# A list of named objects is also returned untouched
if(is.list(formula) & !is.null(names(formula[[1]]))) return(formula)
# Prepare to multiply the formula by the multiplier, if given
if(length(multiplier) > 1 & length(multiplier) != length(formula))
stop("multiplier does not have length = 1 or length = number of formulas")
multiplier <- rep(multiplier, length(formula))
# If the formula argument has length > 1, apply the function over each formula
if(length(formula) > 1) {
# Get formulas for any species indices in the argument
formula <- get.formula(formula)
out <- lapply(seq_along(formula), function(i) {
makeup(formula[i], multiplier[i])
})
# If sum is TRUE, take the sum of all formulas
if(sum) {
out <- unlist(out)
out <- tapply(out, names(out), sum)
} else if(count.zero) {
# If count.zero is TRUE, all elements appearing in any
# of the formulas are counted for each species
# First construct elemental makeup showing zero of each element
em0 <- unlist(out)
# Exclude NA from the element names 20190802
em0 <- em0[!is.na(em0)]
em0 <- tapply(em0, names(em0), sum)
em0[] <- 0
# Create NA matrix for NA formulas 20190802
emNA <- em0
emNA[] <- NA
# Then sum each formula and the zero vector,
# using tapply to group the elements
out <- lapply(out, function(x) {
if(anyNA(x)) emNA else {
xem <- c(x, em0)
tapply(xem, names(xem), sum)
}
})
}
return(out)
}
# If the formula argument is numeric,
# and if the thermo object is available,
# get the formula of that numbered species from thermo()$OBIGT
if("CHNOSZ" %in% .packages()) {
thermo <- get("thermo", CHNOSZ)
if(is.numeric(formula)) formula <- thermo$OBIGT$formula[formula]
}
# First deal with charge
cc <- count.charge(formula)
# count.elements doesn't know about charge so we need
# to explicate the elemental symbol for it
formula <- cc$uncharged
if(cc$Z != 0 ) formula <- paste(formula, "Z", cc$Z, sep = "")
# Now "Z" will be counted
# If there are no subformulas, just use count.elements
if(length(grep("(\\(|\\)|\\*|\\:)", formula)) == 0) {
out <- count.elements(formula)
} else {
# Count the subformulas
cf <- count.formulas(formula)
# Count the elements in each subformula
ce <- lapply(names(cf), count.elements)
# Multiply elemental counts by respective subformula counts
mcc <- lapply(seq_along(cf), function(i) ce[[i]]*cf[i])
# Unlist the subformula counts and sum them together by element
um <- unlist(mcc)
out <- unlist(tapply(um, names(um), sum, simplify = FALSE))
}
# All done with the counting, now apply the multiplier
out <- out * multiplier
# Complain if there are any elements that look strange
if("CHNOSZ" %in% .packages()) {
are.elements <- names(out) %in% thermo$element$element
if(!all(are.elements)) warning(paste("element(s) not in thermo()$element:",
paste(names(out)[!are.elements], collapse = " ") ))
}
# Done!
return(out)
}
count.elements <- function(formula) {
# Count the elements in a chemical formula 20120111 jmd
# This function expects a simple formula,
# no charge or parenthetical or suffixed subformulas
# Regular expressions inspired by an answer on
# http://stackoverflow.com/questions/4116786/parsing-a-chemical-formula-from-a-string-in-c
if(is.na(formula)) return(NA)
#elementRegex <- "([A-Z][a-z]*)([0-9]*)"
elementSymbol <- "([A-Z][a-z]*)"
# Here, element coefficients can be signed (+ or -) and have a decimal point
elementCoeff <- "((\\+|-|\\.|[0-9])*)"
elementRegex <- paste(elementSymbol, elementCoeff, sep = "")
# Stop if it doesn't look like a chemical formula
validateRegex <- paste("^(", elementRegex, ")+$", sep = "")
if(length(grep(validateRegex, formula)) == 0)
stop(paste("'",formula,"' is not a simple chemical formula", sep = "", collapse = "\n"))
# Where to put the output
element <- character()
count <- numeric()
# From now use "f" for formula to make writing the code easier
f <- formula
# We want to find the starting positions of all the elemental symbols
# Make substrings, starting at every position in the formula
fsub <- sapply(1:nchar(f), function(i) substr(f, i, nchar(f)))
# Get the numbers (positions) that start with an elemental symbol
# i.e. an uppercase letter
ielem <- grep("^[A-Z]", fsub)
# For each elemental symbol, j is the position before the start of the next
# symbol (or the position of the last character of the formula)
jelem <- c(tail(ielem - 1, -1), nchar(f))
# Assemble the stuff: each symbol-coefficient combination
ec <- sapply(seq_along(ielem), function(i) substr(f, ielem[i], jelem[i]))
# Get the individual element symbols and coefficients
myelement <- gsub(elementCoeff, "", ec)
mycount <- as.numeric(gsub(elementSymbol, "", ec))
# Any missing coefficients are unity
mycount[is.na(mycount)] <- 1
# Append to the output
element <- c(element, myelement)
count <- c(count, mycount)
# In case there are repeated elements, sum all of their counts
# (tapply hint from https://stat.ethz.ch/pipermail/r-help/2011-January/265341.html)
# use simplify = FALSE followed by unlist to get a vector, not array 20171005
out <- unlist(tapply(count, element, sum, simplify = FALSE))
# tapply returns alphabetical sorted list. keep the order appearing in the formula
out <- out[match(unique(element), names(out))]
return(out)
}
### Unexported functions ###
# Returns a list with named elements
# `Z` - the numeric value of the charge
# `uncharged` - the original formula string excluding the charge
count.charge <- function(formula) {
# Count the charge in a chemical formula 20120113 jmd
# Everything else is counted as the uncharged part of the formula
# Examples:
# C3H6NO2- # charge is -1, uncharged part is C3H6NO2
# XYZ-1.2 # charge is -1.2, uncharged part is XYZ
# ( makeup() treats this equivalently to XY-0.2 )
# C-1.567 # charge is -1.567, uncharged part is C1 (one carbon)
# C-1.567+0 # charge is zero, uncharged part C-1.567 (-1.567 carbons)
# Most of the time the formula isn't charged
Z <- 0
uncharged <- formula
# We have charge if there is a plus or minus sign that is
# followed by only digits (possibly also a decimal point)
# at the end of the formula
charged <- grep("(\\+|-)(\\.|[0-9])*$", formula)
if(length(charged) > 0) {
fsplit <- unlist(strsplit(formula, ""))
# The position of the sign of charge
isign <- tail(grep("(\\+|-)", fsplit), 1)
# The sign as +1 or -1
if(fsplit[isign] == "+") sign <- 1 else sign <- -1
# If the +/- symbol is at the end by itself thats a +/- 1
# otherwise we multiply the magnitude by the sign
nf <- nchar(formula)
if(isign == nf) Z <- sign
else Z <- sign * as.numeric(substr(formula, isign+1 ,nf))
# All set ... Zzzz this is wearing me out!
# got our charge, so remove it from the formula
uncharged <- substr(formula, 1, isign-1)
}
# Assemble the output
out <- list(Z = Z, uncharged = uncharged)
return(out)
}
# Returns a numeric vector with names refering to each of the subformulas or the whole formula if there are no subformulas
count.formulas <- function(formula) {
# Count the subformulas in a chemical formula 20120112 jmd
# The formula may include multiple unnested parenthetical subformulas
# and/or one suffixed subformula (separated by * or :, with no parentheses in suffix)
# e.g. formula for sepiolite, Mg4Si6O15(OH)2(H2O)2*4H2O gives
# count
# OH 2
# H2O 6
# Mg4Si6O15 1
# Other formulas that are able to be parsed
# NaCa2(Al5Si13)O36*14H2O # multiple-digit coefficient on suffix
# and no explicit coefficient on parenthetical term
# C6H14N2O2:HCl # a suffix with no numbers at all
# Where to keep the output
subform <- character()
count <- numeric()
# Deal with parentheses if we have them
# First split the characters
fsplit <- strsplit(formula, "")[[1]]
# Then identify the positions of the parentheses
iopen <- grep("\\(", fsplit)
iclose <- grep("\\)", fsplit)
# Do we have parentheses?
if(length(iopen) > 0 | length(iclose) > 0) {
# Are all parentheses paired?
if(length(iopen) != length(iclose)) stop("formula has unpaired parentheses")
# Are the parentheses unnested?
iparen <- as.numeric(matrix(c(iopen, iclose), nrow = 2, byrow = TRUE))
if(any(diff(iparen) < 0)) stop(paste("formula has nested parentheses: ", formula))
# iend will be the last position including coefficients
# (e.g. the position of 2 in (OH)2)
iend <- iclose
# inum are all the positions with any part of a number
# (including sign and decimal point)
inum <- grep("\\+|-|\\.|[0-9]", fsplit)
# ichar are all other positions
nf <- nchar(formula)
ichar <- (1:nf)[-inum]
# Loop over the parentheses
for(i in seq_along(iopen)) {
# If the position after close paren is a number, parse it
if((iclose[i]+1) %in% inum) {
# iend is the position of the next character, minus one
ic <- head(ichar[ichar-iclose[i] > 0], 1)
# If it's not present, then we're at the end of the formula
if(length(ic) == 0) iend[i] <- nf else iend[i] <- ic - 1
# All the stuff after the iclose up to iend is the coefficient
count <- c(count, as.numeric(substr(formula,iclose[i]+1, iend[i])))
} else count <- c(count, 1)
# Everything between iopen and iclose is the subformula
subform <- c(subform, substr(formula,iopen[i]+1, iclose[i]-1))
}
# We can remove all of the paranthetical terms and their coefficients
for(i in seq_along(iopen)) fsplit[iopen[i]:iend[i]] <- ""
formula <- paste(fsplit, collapse = "")
}
# Deal with a suffixed subformula if we have one
# We assume that there is at most one suffix, so
# at most two strings after both of these splitting tests
fsplit <- unlist(strsplit(formula, "*", fixed = TRUE))
fsplit <- unlist(strsplit(fsplit, ":", fixed = TRUE))
formula <- fsplit[1]
if(length(fsplit) > 1) {
# Parse the coefficient; this time it's in front
f2 <- fsplit[2]
f2split <- unlist(strsplit(f2, ""))
# The positions of the numbers
inum <- grep("\\+|-|\\.|[0-9]", f2split)
if(length(inum) == 0) {
# No numbers, we have one of the subformula
mycount <- 1
mysub <- f2
} else {
# The position of the first character
ic <- head((seq_along(f2split))[-inum], 1)
# If the first character is before the first number,
# the coefficient is one
if(ic < inum[1]) mycount <- 1
else mycount <- as.numeric(substr(f2, inum[1], ic-1))
# We also have the subformula
mysub <- substr(f2, ic, nchar(f2))
}
# Add to existing subformula (as with H2O in sepiolite)
# or append the coefficient and subformula
subform <- c(subform, mysub)
count <- c(count, mycount)
}
# Add in the remaining formula, if there is any left
if(!is.null(formula)) {
subform <- c(subform, formula)
count <- c(count, 1)
}
# Assemble the counts
out <- tapply(count, subform, sum)
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/makeup.R
|
# CHNOSZ/mix.R
# Combine diagrams for two metals
# 20200713 first version jmd
## If this file is interactively sourced, the following are also needed to provide unexported functions:
#source("equilibrate.R")
# Function to combine two diagrams (simple overlay, no interaction) 20200717
# -- makes new "species" from all combinations of those in d1 and d2
mash <- function(d1, d2) {
# It's just mixing d1 and d2 (two single-metal diagrams) without adding d3 (bimetal) 20200722
mix(d1, d2)
}
# Mix the systems to include bimetal species 20200721
# 'parts' gives number of moles of each metal in 1 mole of the mixture
mix <- function(d1, d2, d3 = NULL, parts = c(1, 1), .balance = NULL) {
if(is.null(.balance)) check_d1_d2(d1, d2)
else check_d1_d3(d1, d3)
# Handle mixing here
if(!is.null(d3) & is.null(.balance)) {
# Mix d1 (e.g. Fe only) and d2 (e.g. V only)
m12 <- mix(d1, d2, parts = parts)
# Mix d1 (Fe) and d3 (FeV bimetallic species)
# - '.balance' is defined to add d3 to get required amount of V
# - second 'd3' in argument list is used only for check_d1_d3()
m13 <- mix(d1, d3, d3, parts = parts, .balance = d2$balance)
# Mix d2 (V) and d3 (FeV)
# - '.balance' is defined to add d3 to get required amount of Fe
# - d2 (V) is first, so we need to reverse the 'parts' values
m23 <- mix(d2, d3, d3, parts = rev(parts), .balance = d1$balance)
# Merge all the species and affinity values
species <- rbind(m12$species, m13$species, m23$species)
values <- c(m12$values, m13$values, m23$values)
if(nrow(d3$species) > 1) {
# Mix d3 with itself (combinations of bimetallic species)
m33 <- mix(d3, d3, d3, parts = parts, .balance = c(d1$balance, d2$balance))
# Merge all the species and affinity values
species <- rbind(species, m33$species)
values <- c(values, m33$values)
}
# Remove duplicates
# (i.e. bimetallic species that exactly match the composition in 'parts'
# and therefore appear in multiple combinations with
# mono-metallic species that have zero mole fractions)
idup <- duplicated(species$name)
species <- species[!idup, ]
values <- values[!idup]
# Put together the output
anew <- m12
anew$species <- species
anew$values <- values
return(anew)
}
# Index all combinations of species in d1 and d2
i1 <- 1:nrow(d1$species)
i2 <- 1:nrow(d2$species)
combs <- expand.grid(i1, i2)
# For bimetallic species (m33)
if(length(.balance) == 2) {
# Remove combinations of a species with itself
combs <- combs[combs[, 1] != combs[, 2], ]
# Remove duplicated combinations
isdup <- duplicated(paste(apply(combs, 1, sort)[1, ], apply(combs, 1, sort)[2, ]))
combs <- combs[!isdup, ]
}
# Get species rows for each combination
s1 <- d1$species[combs[, 1], ]
s2 <- d2$species[combs[, 2], ]
# Get balancing coefficients for each combination
b1 <- d1$n.balance[combs[, 1]]
b2 <- d2$n.balance[combs[, 2]]
# Locate the columns for the two metals in the formation reactions
ibal <- match(c(d1$balance, d2$balance), colnames(s1))
# With non-null '.balance', d2 is really d3 so we calculate the needed balancing coefficients
if(!is.null(.balance)) {
if(length(.balance) == 2) {
# For combinations of bimetallic species (m33)
b1 <- suppressMessages(balance(d1, .balance[1])$n.balance[combs[, 1]])
b2 <- suppressMessages(balance(d2, .balance[2])$n.balance[combs[, 2]])
ibal <- match(.balance, colnames(s1))
} else {
b2 <- suppressMessages(balance(d2, .balance)$n.balance[combs[, 2]])
ibal <- match(c(d1$balance, .balance), colnames(s1))
}
}
# Solve for the mole fractions of each species that give the required mixture
isingular <- frac1 <- frac2 <- numeric()
for(i in 1:nrow(combs)) {
# The stoichiometric matrix
A <- matrix(as.numeric(c(s1[i, ibal], s2[i, ibal])), nrow = 2, byrow = TRUE)
x <- tryCatch(solve(t(A), parts), error = function(e) e)
# Check if we have a singular combination (e.g. FeV and FeVO4)
if(inherits(x, "error")) {
isingular <- c(isingular, i)
} else {
frac1 <- c(frac1, x[1])
frac2 <- c(frac2, x[2])
}
}
if(length(isingular) > 0) {
if(length(isingular) > 1) stxt <- "s" else stxt <- ""
message(paste0("mix: removing ", length(isingular), " combination", stxt, " with a singular stoichiometric matrix"))
combs <- combs[-isingular, ]
s1 <- s1[-isingular, ]
s2 <- s2[-isingular, ]
}
# Note that some of frac1 or frac2 might be < 0 ... we remove these combinations below
# Make a new species data frame starting with sum of scaled formation reactions
nbasis <- nrow(d1$basis)
species <- s1[, 1:nbasis] * frac1 + s2[, 1:nbasis] * frac2
# Concatenate ispecies, logact, state
ispecies <- paste(s1$ispecies, s2$ispecies, sep = ",")
logact <- paste(s1$logact, s2$logact, sep = ",")
state <- paste(s1$state, s2$state, sep = ",")
# Omit species with zero mole fraction from concatenated values 20200722
ispecies[frac1 == 0] <- s2$ispecies[frac1 == 0]
logact[frac1 == 0] <- s2$logact[frac1 == 0]
state[frac1 == 0] <- s2$state[frac1 == 0]
ispecies[frac2 == 0] <- s1$ispecies[frac2 == 0]
logact[frac2 == 0] <- s1$logact[frac2 == 0]
state[frac2 == 0] <- s1$state[frac2 == 0]
# Use names from diagram()
if(is.expression(d1$names) | is.expression(d2$names)) {
# Convert non-expressions to lists so we can use [[ indexing below
if(!is.expression(d1$names)) d1$names <- as.list(d1$names)
if(!is.expression(d2$names)) d2$names <- as.list(d2$names)
name <- lapply(1:nrow(combs), function(i) {
# Don't include names of species that are not present (zero mole fractions)
if(frac1[i] == 0 & frac2[i] == 0) bquote("")
else if(frac1[i] == 0) bquote(.(d2$names[[combs[i, 2]]]))
else if(frac2[i] == 0) bquote(.(d1$names[[combs[i, 1]]]))
else {
# Put the names together, with the species from d2 first if it is has a higher mole fraction 20200722
if(frac2[i] > frac1[i]) bquote(.(d2$names[[combs[i, 2]]])+.(d1$names[[combs[i, 1]]]))
else bquote(.(d1$names[[combs[i, 1]]])+.(d2$names[[combs[i, 2]]]))
}
})
name <- unlist(lapply(name, deparse, width.cutoff = 500, control = NULL))
if(length(name) != nrow(combs)) stop("deparse()-ing expressions gives unequal length; try diagram(., format.names = FALSE)")
} else {
# Plain text names
name <- sapply(1:nrow(combs), function(i) {
if(frac1[i] <= 0) d2$names[combs[i, 2]]
else if(frac2[i] <= 0) d1$names[combs[i, 1]]
else paste(d1$names[combs[i, 1]], d2$names[combs[i, 2]], sep = "+")
})
}
species <- cbind(species, ispecies, logact, state, name, stringsAsFactors = FALSE)
# Get affinities for each combination of species
v1 <- d1$values[combs[, 1]]
v2 <- d2$values[combs[, 2]]
# Scale affinities by mole fractions computed for the mixture
v1 <- Map("*", v1, as.list(frac1))
v2 <- Map("*", v2, as.list(frac2))
# Add together the scaled affinities
values <- Map("+", v1, v2)
ipredominant <- logical(length(values))
if(length(.balance) == 2) {
# For combinations of bimetallic species (m33), don't do predominance masking
# (there are no mono-metallic species to look at)
ipredominant[] <- TRUE
} else {
# Loop over combinations to find predominant species in the single-metal diagram(s)
for(i in seq_along(values)) {
# Get predominant species in first diagram
i1 <- combs[i, 1]
ip1 <- d1$predominant == i1
# If the mole fraction is zero, it is predominant by definition
# (this allows a single bimetallic species (that is paired with
# the zero-mole-fraction mono-metallic species) to be formed)
if(frac1[i] == 0) ip1[] <- TRUE
if(is.null(.balance)) {
# Get predominant species in second diagram
i2 <- combs[i, 2]
ip2 <- d2$predominant == i2
# If the mole fraction is zero, it is predominant by definition
# (this allows us to recover the first single-element diagram with frac = c(1, 0))
if(frac2[i] == 0) ip2[] <- TRUE
# Assign -Inf affinity where any species isn't predominant in the corresponding single-metal diagram
ip12 <- ip1 & ip2
values[[i]][!ip12] <- -Inf
if(any(ip12)) ipredominant[i] <- TRUE
} else {
# For non-null '.balance', only the first diagram is for a single metal
values[[i]][!ip1] <- -Inf
if(any(ip1)) ipredominant[i] <- TRUE
}
}
}
# Remove combinations that:
# 1) involve a mono-metallic species with no predominance field in the corresponding single-metal diagram or
# 2) have a negative mole fraction of any species
inotnegative <- frac1 >= 0 & frac2 >= 0
values <- values[ipredominant & inotnegative]
species <- species[ipredominant & inotnegative, ]
# Use d1 as a template for the new affinity object
anew <- d1[1:11]
# Insert combined results
anew$species <- species
anew$values <- values
# We don't have sout (results from subcrt()) for the combined "species"
anew$sout <- NULL
anew
}
# Function to make a new "affinity" object from two diagrams 20200713
# -- uses *secondary* balancing coefficients to combine the diagrams
rebalance <- function(d1, d2, balance = NULL) {
check_d1_d2(d1, d2)
# Combine the species data frames
species <- rbind(d1$species, d2$species)
# Combine the sout objects (results from subcrt())
only2 <- !d2$sout$species$ispecies %in% d1$sout$species$ispecies
sout <- d1$sout
sout$species <- rbind(sout$species, d2$sout$species[only2, ])
sout$out <- c(sout$out, d2$sout$out[only2])
# Combine the affinity values divided by the *primary*
# balancing coefficients ("plotvals" from diagram())
values <- c(d1$plotvals, d2$plotvals)
# Use d1 as a template for the new affinity object
anew <- d1[1:11]
# Insert combined results
anew$species <- species
anew$sout <- sout
anew$values <- values
# Figure out the *secondary* balancing coefficients
n.balance <- balance(anew, balance = balance)$n.balance
# In the Fe-Cu-S-O-H example all the coefficients on H+ are negative
if(all(n.balance < 0)) n.balance <- -n.balance
n1 <- nrow(d1$species)
n.balance.1 <- n.balance[1:n1]
n.balance.2 <- n.balance[(n1+1):length(n.balance)]
# Make empty matrices to hold affinities and balancing coefficients
a1 <- d1$values[[1]]
a1[] <- NA
b2 <- a2 <- b1 <- a1
# Get the affinities (per mole of species, not divided by any balancing coefficients)
# and the secondary balancing coefficients for the predominant species in each diagram
p1 <- d1$predominant
for(ip in unique(as.vector(p1))) {
a1[p1 == ip] <- d1$values[[ip]][p1 == ip]
b1[p1 == ip] <- n.balance.1[ip]
}
p2 <- d2$predominant
for(ip in unique(as.vector(p2))) {
a2[p2 == ip] <- d2$values[[ip]][p2 == ip]
b2[p2 == ip] <- n.balance.2[ip]
}
# Divide the affinities by the secondary balancing coefficients
ab1 <- a1 / b1
ab2 <- a2 / b2
# Identify the species with the highest affinity (predominant in the *secondary* reactions)
i1 <- ab1 > ab2
# Suppress non-predominant species at each grid point
for(i in 1:n1) anew$values[[i]][!i1] <- -Inf
for(i in (n1+1):length(n.balance)) anew$values[[i]][i1] <- -Inf
anew
}
### Unexported functions ###
# Check that d1 and d2 can be combined
# Extracted from duplex() (now rebalance()) 20200717
check_d1_d2 <- function(d1, d2) {
# Check that the basis species are the same
if(!identical(d1$basis, d2$basis)) stop(paste0("basis species in objects 'd1' and 'd2' are not identical"))
# Check that the variables and their values are the same
if(!identical(d1$vars, d2$vars)) stop(paste0("plot variables in objects 'd1' and 'd2' are not identical"))
if(!identical(d1$vals, d2$vals)) stop(paste0("plot ranges in objects 'd1' and 'd2' are not identical"))
# Check that T and P are the same
if(!identical(d1$T, d2$T)) stop(paste0("temperatures in objects 'd1' and 'd2' are not identical"))
if(!identical(d1$P, d2$P)) stop(paste0("pressures in objects 'd1' and 'd2' are not identical"))
# Check that we have plotvals and predominant (from diagram())
if(is.null(d1$plotvals) | is.null(d1$predominant)) stop("object 'd1' is missing 'plotvals' or 'predominant' components (not made by diagram()?)")
if(is.null(d2$plotvals) | is.null(d2$predominant)) stop(paste0("object 'd2' is missing 'plotvals' or 'predominant' components (not made by diagram()?)"))
}
# Check that d1 and d3 can be combined
check_d1_d3 <- function(d1, d3) {
# Check that the basis species are the same
if(!identical(d1$basis, d3$basis)) stop(paste0("basis species in objects 'd1' and 'd3' are not identical"))
# Check that the variables and their values are the same
if(!identical(d1$vars, d3$vars)) stop(paste0("plot variables in objects 'd1' and 'd3' are not identical"))
if(!identical(d1$vals, d3$vals)) stop(paste0("plot ranges in objects 'd1' and 'd3' are not identical"))
# Check that T and P are the same
if(!identical(d1$T, d3$T)) stop(paste0("temperatures in objects 'd1' and 'd3' are not identical"))
if(!identical(d1$P, d3$P)) stop(paste0("pressures in objects 'd1' and 'd3' are not identical"))
# Check that we have plotvals and predominant (from diagram())
if(is.null(d1$plotvals) | is.null(d1$predominant)) stop("object 'd1' is missing 'plotvals' or 'predominant' components (not made by diagram()?)")
if(is.null(d3$plotvals) | is.null(d3$predominant)) stop(paste0("object 'd3' is missing 'plotvals' or 'predominant' components (not made by diagram()?)"))
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/mix.R
|
# CHNOSZ/mosaic.R
# Calculate affinities with changing basis species
# 20141220 jmd initial version
# 20190129 complete rewrite to use any number of groups of changing basis species
# and improve speed by pre-calculating subcrt values (sout)
# 20190505 bug fix: adjust affinities of species formation reactions for mole fractions of basis species
## If this file is interactively sourced, the following are also needed to provide unexported functions:
#source("basis.R")
#source("util.character.R")
#source("util.args.R")
# Function to calculate affinities with mosaic of basis species
mosaic <- function(bases, blend = TRUE, stable = list(), loga_aq = NULL, ...) {
# Get the arguments for affinity() before doing anything else 20230809
affinityargs <- list(...)
# Argument recall 20190120
# If the first argument is the result from a previous mosaic() calculation,
# just update the remaining arguments
if(is.list(bases)) {
if(identical(bases[1], list(fun = "mosaic"))) {
bargs <- bases$args
# We can only update arguments for affinity()
if(length(affinityargs) > 0) {
for(i in 1:length(affinityargs)) {
if(names(affinityargs)[i] %in% names(bargs)) bargs[[names(affinityargs)[i]]] <- affinityargs[[i]]
else bargs <- c(bargs, affinityargs[i])
}
}
return(do.call(mosaic, bargs))
}
}
# Backward compatibility 20190131:
# bases can be a vector instead of a list
if(!is.list(bases)) {
bases <- list(bases)
allargs <- c(list(bases = bases, blend = blend, stable = stable), affinityargs)
out <- do.call(mosaic, allargs)
# Replace A.bases (affinity calculations for all groups of basis species) with backwards-compatible A.bases
out$A.bases <- out$A.bases[[1]]
return(out)
}
if(length(stable) == 2) {
# Use only predominant basis species for mosaic stacking 20220723
stable2.orig <- stable2 <- stable[[2]]
# Why c(1, ?
# The first basis species should always be included (because it has to be swapped out for the others)
istable2 <- sort(unique(c(1, as.numeric(stable2))))
for(i in seq_along(istable2)) stable2[stable2.orig == istable2[i]] <- i
bases2 <- bases[[2]][istable2]
bases[[2]] <- bases2
stable[[2]] <- stable2
}
# Save starting basis and species definition
basis0 <- get("thermo", CHNOSZ)$basis
species0 <- get("thermo", CHNOSZ)$species
# Get species indices of requested basis species
ispecies <- lapply(bases, info)
if(any(is.na(unlist(ispecies)))) stop("one or more of the requested basis species is unavailable")
# Identify starting basis species
ispecies0 <- sapply(ispecies, "[", 1)
ibasis0 <- match(ispecies0, basis0$ispecies)
# Quit if starting basis species are not present
ina <- is.na(ibasis0)
if(any(ina)) {
names0 <- unlist(lapply(bases, "[", 1))
stop("the starting basis species do not have ", paste(names0[ina], collapse = " and "))
}
if("sout" %in% names(affinityargs)) {
affinityargs_has_sout <- TRUE
# Get sout from affinityargs (from solubility()) 20210322
sout <- affinityargs$sout
} else {
affinityargs_has_sout <- FALSE
# Run subcrt() calculations for all basis species and formed species 20190131
# - This avoids repeating the calculations in different calls to affinity()
# Add all the basis species here - the formed species are already present
lapply(bases, species, add = TRUE)
sout <- do.call(affinity, c(affinityargs, list(return.sout = TRUE)))
}
# Calculate affinities of the basis species themselves
A.bases <- list()
for(i in 1:length(bases)) {
message("mosaic: calculating affinities of basis species group ", i, ": ", paste(bases[[i]], collapse = " "))
mysp <- species(bases[[i]])
# Include only aq species in total activity 20191111
iaq <- mysp$state == "aq"
# Use as.numeric in case a buffer is active 20201014
if(any(iaq)) species(which(iaq), as.numeric(basis0$logact[ibasis0[i]]))
if(affinityargs_has_sout) A.bases[[i]] <- suppressMessages(do.call(affinity, affinityargs))
else A.bases[[i]] <- suppressMessages(do.call(affinity, c(affinityargs, list(sout = sout))))
}
# Get all combinations of basis species (species indices in OBIGT)
newbases <- as.matrix(expand.grid(ispecies))
allbases <- matrix(basis0$ispecies, nrow = 1)[rep(1, nrow(newbases)), , drop = FALSE]
allbases[, ibasis0] <- newbases
# Also get all combinations of names of basis species (for modifying affinityargs) 20230809
newbnames <- as.matrix(expand.grid(bases))
allbnames <- matrix(rownames(basis0), nrow = 1)[rep(1, nrow(newbnames)), , drop = FALSE]
allbnames[, ibasis0] <- newbnames
# Look for argument names for affinity() in starting basis species
# (i.e., basis species that are variables on the diagram)
matches.bnames <- names(affinityargs) %in% allbnames[1, ]
# Find the name(s) of the starting basis species that are variables on the diagram
ibnames <- match(names(affinityargs)[matches.bnames], allbnames[1, ])
# Figure out the element to make labels (total C, total S, etc.)
labels <- NULL
if(any(matches.bnames)) {
element.matrix <- basis0[, 1:nrow(basis0)]
elements.in.basis0 <- colSums(element.matrix)
labelnames <- allbnames[1, ibnames]
labels <- lapply(1:length(labelnames), function(i) {
has.element <- element.matrix[match(labelnames[i], rownames(element.matrix)), ] > 0
ielement <- has.element & elements.in.basis0 == 1
# Use the element or fallback to species name if element isn't found
if(any(ielement)) colnames(element.matrix)[ielement][1]
else labelnames[i]
})
names(labels) <- labelnames
}
# Calculate affinities of species for all combinations of basis species
aff.species <- list()
message("mosaic: calculating affinities of species for all ", nrow(allbases), " combinations of the basis species")
# Run backwards so that we end up with the starting basis species
for(i in nrow(allbases):1) {
# Get default loga from starting basis species
thislogact <- basis0$logact
# Use logact = 0 for solids 20191111
states <- sout$species$state[match(allbases[i, ], sout$species$ispecies)]
icr <- grepl("cr", states)
thislogact[icr] <- 0
# Use loga_aq for log(activity) of mosaiced aqueous basis species 20220722
if(!is.null(loga_aq)) {
if(length(loga_aq) != length(ibasis0)) stop("'loga_aq' should have same length as 'bases'")
iaq <- grep("aq", states)
# Loop over sets of mosaiced basis species
for(j in 1:length(ibasis0)) {
if(is.na(loga_aq[j])) next
iaqbasis0 <- intersect(iaq, ibasis0[j])
thislogact[iaqbasis0] <- loga_aq[j]
}
}
put.basis(allbases[i, ], thislogact)
# Load the formed species using the current basis
species(species0$ispecies, species0$logact)
# If mosaic() changes variables on the diagram, argument names for affinity() also have to be changed 20230809
myaffinityargs <- affinityargs
if(any(matches.bnames)) {
# At least one basis species in 'bases' is a variable on the diagram
# Use the name of the current swapped-in basis species
names(myaffinityargs)[matches.bnames] <- allbnames[i, ibnames]
}
if(affinityargs_has_sout) aff.species[[i]] <- suppressMessages(do.call(affinity, myaffinityargs))
else aff.species[[i]] <- suppressMessages(do.call(affinity, c(myaffinityargs, list(sout = sout))))
}
# Calculate equilibrium mole fractions for each group of basis species
group.fraction <- list()
blend <- rep(blend, length(A.bases))
E.bases <- list()
for(i in 1:length(A.bases)) {
if(blend[i] & is.null(stable[i][[1]])) {
# This isn't needed (and doesn't work) if all the affinities are NA 20180925
if(any(!sapply(A.bases[[1]]$values, is.na))) {
# When equilibrating the changing basis species, use a total activity equal to the activity from the basis definition 20190504
# Use equilibrate(loga.balance = ) instead of setting activities in species definition 20191111
e <- equilibrate(A.bases[[i]], loga.balance = as.numeric(basis0$logact[ibasis0[i]]))
# Exponentiate to get activities then divide by total activity
a.equil <- lapply(e$loga.equil, function(x) 10^x)
a.tot <- Reduce("+", a.equil)
group.fraction[[i]] <- lapply(a.equil, function(x) x / a.tot)
# Include the equilibrium activities in the output of this function 20190504
E.bases[[i]] <- e
} else {
group.fraction[[i]] <- A.bases[[i]]$values
}
} else {
# For blend = FALSE, we just look at whether a basis species predominates within its group
if(is.null(stable[i][[1]])) {
d <- diagram(A.bases[[i]], plot.it = FALSE, limit.water = FALSE)
predom <- d$predominant
} else {
# Get the stable species from the argument 20200715
predom <- stable[i][[1]]
}
group.fraction[[i]] <- list()
for(j in 1:length(bases[[i]])) {
# If a basis species predominates, it has a mole fraction of 1, or 0 otherwise
yesno <- predom
yesno[yesno != j] <- 0
yesno[yesno == j] <- 1
group.fraction[[i]][[j]] <- yesno
}
}
}
# Make an indexing matrix for all combinations of basis species
ind.mat <- list()
for(i in 1:length(ispecies)) ind.mat[[i]] <- 1:length(ispecies[[i]])
ind.mat <- as.matrix(expand.grid(ind.mat))
# Loop over combinations of basis species
for(icomb in 1:nrow(ind.mat)) {
# Loop over groups of changing basis species
for(igroup in 1:ncol(ind.mat)) {
# Get mole fractions for this particular basis species
basisx <- group.fraction[[igroup]][[ind.mat[icomb, igroup]]]
# Loop over species
for(jspecies in 1:length(aff.species[[icomb]]$values)) {
# Get coefficient of this basis species in the formation reaction for this species
nbasis <- aff.species[[icomb]]$species[jspecies, ibasis0[igroup]]
# Adjust affinity of species for mole fractions (i.e. lower activity) of basis species 20190505
aff.adjust <- nbasis * log10(basisx)
# Avoid infinite values (from log10(0))
isfin <- is.finite(aff.adjust)
aff.species[[icomb]]$values[[jspecies]][isfin] <- aff.species[[icomb]]$values[[jspecies]][isfin] + aff.adjust[isfin]
}
# Multiply fractions of basis species from each group to get overall fraction
if(igroup==1) groupx <- basisx
else groupx <- groupx * basisx
}
# Multiply affinities by the mole fractions of basis species
aff.species[[icomb]]$values <- lapply(aff.species[[icomb]]$values, function(values) values * groupx)
}
# Get total affinities for the species
A.species <- aff.species[[1]]
for(i in 1:length(A.species$values)) {
# Extract the affinity contributions from each basis species
A.values <- lapply(lapply(aff.species, "[[", "values"), "[[", i)
# Sum them to get total affinities for this species
A.species$values[[i]] <- Reduce("+", A.values)
}
# Insert custom labels 20230809
A.species$labels <- labels
# For argument recall, include all arguments in output 20190120
allargs <- c(list(bases = bases, blend = blend), affinityargs)
# Return the affinities for the species and basis species
return(list(fun = "mosaic", args = allargs, A.species = A.species, A.bases = A.bases, E.bases = E.bases))
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/mosaic.R
|
# CHNOSZ/nonideal.R
# First version of function: 20080308 jmd
# Moved to nonideal.R from util.misc.R 20151107
# Added Helgeson method 20171012
nonideal <- function(species, speciesprops, IS, T, P, A_DH, B_DH, m_star = NULL, method = thermo()$opt$nonideal) {
# Generate nonideal contributions to thermodynamic properties
# number of species, same length as speciesprops list
# T in Kelvin, same length as nrows of speciespropss
# arguments A_DH and B_DH are needed for all methods other than "Alberty", and P is needed for "bgamma"
# m_star is the total molality of all dissolved species; if not given, it is taken to be equal to ionic strength
mettext <- function(method) {
mettext <- paste(method, "equation")
if(method == "Bdot0") mettext <- "B-dot equation (B-dot = 0)"
mettext
}
# We can use this function to change the nonideal method option
if(missing(speciesprops)) {
if(species[1] %in% c("Bdot", "Bdot0", "bgamma", "bgamma0", "Alberty")) {
thermo <- get("thermo", CHNOSZ)
oldnon <- thermo$opt$nonideal
thermo$opt$nonideal <- species[1]
assign("thermo", thermo, CHNOSZ)
message("nonideal: setting nonideal option to use ", mettext(species))
return(invisible(oldnon))
} else stop(species[1], " is not a valid nonideality setting (Bdot, Bdot0, bgamma, bgamma0, or Alberty)")
}
# Check if we have a valid method setting
if(!method %in% c("Alberty", "Bdot", "Bdot0", "bgamma", "bgamma0")) {
if(missing(method)) stop("invalid setting (", thermo$opt$nonideal, ") in thermo()$opt$nonideal")
else stop("invalid method (", thermo$opt$nonideal, ")")
}
# Gas constant
#R <- 1.9872 # cal K^-1 mol^-1 Value used in SUPCRT92
#R <- 8.314445 # = 1.9872 * 4.184 J K^-1 mol^-1 20220325
R <- 8.314463 # https://physics.nist.gov/cgi-bin/cuu/Value?r 20230630
# Function to calculate extended Debye-Huckel equation and derivatives using Alberty's parameters
Alberty <- function(prop = "loggamma", Z, I, T) {
# Extended Debye-Huckel equation ("log")
# and its partial derivatives ("G","H","S","Cp")
# T in Kelvin
B <- 1.6 # L^0.5 mol^-0.5 (Alberty, 2003 p. 47)
# Equation for A from Clarke and Glew, 1980
#A <- expression(-16.39023 + 261.3371/T + 3.3689633*log(T)- 1.437167*(T/100) + 0.111995*(T/100)^2)
# A = alpha / 3 (Alberty, 2001)
alpha <- expression(3 * (-16.39023 + 261.3371/T + 3.3689633*log(T)- 1.437167*(T/100) + 0.111995*(T/100)^2))
## Equation for alpha from Alberty, 2003 p. 48
#alpha <- expression(1.10708 - 1.54508E-3 * T + 5.95584E-6 * T^2)
# from examples for deriv() to take first and higher-order derivatives
DD <- function(expr, name, order = 1) {
if(order < 1) stop("'order' must be >= 1")
if(order == 1) D(expr, name)
else DD(D(expr, name), name, order - 1)
}
# Alberty, 2003 Eq. 3.6-1
lngamma <- function(alpha, Z, I, B) - alpha * Z^2 * I^(1/2) / (1 + B * I^(1/2))
# 20171013 convert lngamma to common logarithm
# 20190603 use equations for H, S, and Cp from Alberty, 2001 (doi:10.1021/jp011308v)
if(prop == "loggamma") return(lngamma(eval(alpha), Z, I, B) / log(10))
else if(prop == "G") return(R * T * lngamma(eval(alpha), Z, I, B))
else if(prop == "H") return(- R * T^2 * lngamma(eval(DD(alpha, "T", 1)), Z, I, B))
else if(prop == "S") return( ( - R * T^2 * lngamma(eval(DD(alpha, "T", 1)), Z, I, B) - R * T * lngamma(eval(alpha), Z, I, B) ) / T)
else if(prop == "Cp") return(- 2 * R * T * lngamma(eval(DD(alpha, "T", 1)), Z, I, B) - R * T^2 * lngamma(eval(DD(alpha, "T", 2)), Z, I, B))
}
# Function for Debye-Huckel equation with b_gamma or B-dot extended term parameter (Helgeson, 1969)
Helgeson <- function(prop = "loggamma", Z, I, T, A_DH, B_DH, acirc, m_star, bgamma) {
loggamma <- - A_DH * Z^2 * I^0.5 / (1 + acirc * B_DH * I^0.5) - log10(1 + 0.0180153 * m_star) + bgamma * I
if(prop == "loggamma") return(loggamma)
else if(prop == "G") return(R * T * log(10) * loggamma)
# note the log(10) (=2.303) ... use natural logarithm to calculate G
}
# Function for Setchenow equation with b_gamma or B-dot extended term parameter (Shvarov and Bastrakov, 1999) 20181106
Setchenow <- function(prop = "loggamma", I, T, m_star, bgamma) {
loggamma <- - log10(1 + 0.0180153 * m_star) + bgamma * I
if(prop == "loggamma") return(loggamma)
else if(prop == "G") return(R * T * log(10) * loggamma)
}
# Get species indices
if(!is.numeric(species[[1]])) species <- info(species, "aq")
# loop over species #1: get the charge
Z <- numeric(length(species))
for(i in 1:length(species)) {
# force a charge count even if it's zero
mkp <- makeup(c("Z0", species[i]), sum = TRUE)
thisZ <- mkp[match("Z", names(mkp))]
# no charge if Z is absent from the formula or equal to zero
if(is.na(thisZ)) next
if(thisZ == 0) next
Z[i] <- thisZ
}
# Use formulas of species to get acirc 20181105
formula <- get("thermo", CHNOSZ)$OBIGT$formula[species]
if(grepl("Bdot", method)) {
# "ion size paramter" taken from UT_SIZES.REF of HCh package (Shvarov and Bastrakov, 1999),
# based on Table 2.7 of Garrels and Christ, 1965
Bdot_acirc <- thermo()$Bdot_acirc
acirc <- as.numeric(Bdot_acirc[formula])
acirc[is.na(acirc)] <- 4.5
## Make a message
#nZ <- sum(Z != 0)
#if(nZ > 1) message("nonideal: using ", paste(acirc[Z != 0], collapse = " "), " for ion size parameters of ", paste(formula[Z != 0], collapse = " "))
#else if(nZ == 1) message("nonideal: using ", acirc[Z != 0], " for ion size parameter of ", formula[Z != 0])
# Use correct units (cm) for ion size parameter
acirc <- acirc * 10^-8
} else if(grepl("bgamma", method)) {
# "distance of closest approach" of ions in NaCl solutions (HKF81 Table 2)
acirc <- rep(3.72e-8, length(species))
}
# Get b_gamma or B-dot
if(method == "bgamma") bgamma <- bgamma(convert(T, "C"), P)
else if(method == "Bdot") bgamma <- Bdot(convert(T, "C"))
else if(method %in% c("Bdot0", "bgamma0")) bgamma <- 0
# Loop over species #2: activity coefficient calculations
if(is.null(m_star)) m_star <- IS
iH <- info("H+")
ie <- info("e-")
speciesprops <- as.list(speciesprops)
icharged <- ineutral <- logical(length(species))
for(i in 1:length(species)) {
myprops <- speciesprops[[i]]
# To keep unit activity coefficients of the proton and electron
if(species[i] == iH & get("thermo", CHNOSZ)$opt$ideal.H) next
if(species[i] == ie & get("thermo", CHNOSZ)$opt$ideal.e) next
didcharged <- didneutral <- FALSE
# Logic for neutral and charged species 20181106
if(Z[i] == 0) {
for(j in 1:ncol(myprops)) {
pname <- colnames(myprops)[j]
if(!pname %in% c("G", "H", "S", "Cp")) next
if(identical(get("thermo", CHNOSZ)$opt$Setchenow, "bgamma")) {
myprops[, j] <- myprops[, j] + Setchenow(pname, IS, T, m_star, bgamma)
didneutral <- TRUE
} else if(identical(get("thermo", CHNOSZ)$opt$Setchenow, "bgamma0")) {
myprops[, j] <- myprops[, j] + Setchenow(pname, IS, T, m_star, bgamma = 0)
didneutral <- TRUE
}
}
} else {
for(j in 1:ncol(myprops)) {
pname <- colnames(myprops)[j]
if(!pname %in% c("G", "H", "S", "Cp")) next
if(method == "Alberty") {
myprops[, j] <- myprops[, j] + Alberty(pname, Z[i], IS, T)
didcharged <- TRUE
} else {
myprops[, j] <- myprops[, j] + Helgeson(pname, Z[i], IS, T, A_DH, B_DH, acirc[i], m_star, bgamma)
didcharged <- TRUE
}
}
}
# Append a loggam column if we did any calculations of adjusted thermodynamic properties
if(didcharged) {
if(method == "Alberty") myprops <- cbind(myprops, loggam = Alberty("loggamma", Z[i], IS, T))
else myprops <- cbind(myprops, loggam = Helgeson("loggamma", Z[i], IS, T, A_DH, B_DH, acirc[i], m_star, bgamma))
}
if(didneutral) {
if(get("thermo", CHNOSZ)$opt$Setchenow == "bgamma") myprops <- cbind(myprops, loggam = Setchenow("loggamma", IS, T, m_star, bgamma))
else if(get("thermo", CHNOSZ)$opt$Setchenow == "bgamma0") myprops <- cbind(myprops, loggam = Setchenow("loggamma", IS, T, m_star, bgamma = 0))
}
# Save the calculated properties and increment progress counters
speciesprops[[i]] <- myprops
if(didcharged) icharged[i] <- TRUE
if(didneutral) ineutral[i] <- TRUE
}
if(sum(icharged) > 0) message("nonideal: calculations for ", paste(formula[icharged], collapse = ", "), " (", mettext(method), ")")
if(sum(ineutral) > 0) message("nonideal: calculations for ", paste(formula[ineutral], collapse = ", "), " (Setchenow equation)")
return(speciesprops)
}
bgamma <- function(TC = 25, P = 1, showsplines = "") {
# 20171012 calculate b_gamma using P, T, points from:
# Helgeson, 1969 (doi:10.2475/ajs.267.7.729)
# Helgeson et al., 1981 (doi:10.2475/ajs.281.10.1249)
# Manning et al., 2013 (doi:10.2138/rmg.2013.75.5)
# T in degrees C
T <- TC
# Are we at a pre-fitted constant pressure?
uP <- unique(P)
is1 <- identical(uP, 1) & all(T == 25)
is500 <- identical(uP, 500)
is1000 <- identical(uP, 1000)
is2000 <- identical(uP, 2000)
is3000 <- identical(uP, 3000)
is4000 <- identical(uP, 4000)
is5000 <- identical(uP, 5000)
is10000 <- identical(uP, 10000)
is20000 <- identical(uP, 20000)
is30000 <- identical(uP, 30000)
is40000 <- identical(uP, 40000)
is50000 <- identical(uP, 50000)
is60000 <- identical(uP, 60000)
isoP <- is1 | is500 | is1000 | is2000 | is3000 | is4000 | is5000 | is10000 | is20000 | is30000 | is40000 | is50000 | is60000
# Values for Bdot x 100 from Helgeson (1969), Figure (P = Psat)
if(!isoP | showsplines != "") {
T0 <- c(23.8, 49.4, 98.9, 147.6, 172.6, 197.1, 222.7, 248.1, 268.7)
B0 <- c(4.07, 4.27, 4.30, 4.62, 4.86, 4.73, 4.09, 3.61, 1.56) / 100
# We could use the values from Hel69 Table 2 but extrapolation of the
# their fitted spline function turns sharply upward above 300 degC
#T0a <- c(25, 50, 100, 150, 200, 250, 270, 300)
#B0a <- c(4.1, 4.35, 4.6, 4.75, 4.7, 3.4, 1.5, 0)
S0 <- splinefun(T0, B0)
}
# Values for bgamma x 100 from Helgeson et al., 1981 Table 27
if(is500 | !isoP | showsplines != "") {
T0.5 <- seq(0, 400, 25)
B0.5 <- c(5.6, 7.1, 7.8, 8.0, 7.8, 7.5, 7.0, 6.4, 5.7, 4.8, 3.8, 2.6, 1.0, -1.2, -4.1, -8.4, -15.2) / 100
S0.5 <- splinefun(T0.5, B0.5)
if(is500) return(S0.5(T))
}
if(is1000 | !isoP | showsplines != "") {
T1 <- seq(0, 500, 25)
B1 <- c(6.6, 7.7, 8.7, 8.3, 8.2, 7.9, 7.5, 7.0, 6.5, 5.9, 5.2, 4.4, 3.5, 2.5, 1.1, -0.6, -2.8, -5.7, -9.3, -13.7, -19.2) / 100
S1 <- splinefun(T1, B1)
if(is1000) return(S1(T))
}
if(is2000 | !isoP | showsplines != "") {
# 550 and 600 degC points from Manning et al., 2013 Fig. 11
T2 <- c(seq(0, 500, 25), 550, 600)
B2 <- c(7.4, 8.3, 8.8, 8.9, 8.9, 8.7, 8.5, 8.1, 7.8, 7.4, 7.0, 6.6, 6.2, 5.8, 5.2, 4.6, 3.8, 2.9, 1.8, 0.5, -1.0, -3.93, -4.87) / 100
S2 <- splinefun(T2, B2)
if(is2000) return(S2(T))
}
if(is3000 | !isoP | showsplines != "") {
T3 <- seq(0, 500, 25)
B3 <- c(6.5, 8.3, 9.2, 9.6, 9.7, 9.6, 9.4, 9.3, 9.2, 9.0, 8.8, 8.6, 8.3, 8.1, 7.8, 7.5, 7.1, 6.6, 6.0, 5.4, 4.8) / 100
S3 <- splinefun(T3, B3)
if(is3000) return(S3(T))
}
if(is4000 | !isoP | showsplines != "") {
T4 <- seq(0, 500, 25)
B4 <- c(4.0, 7.7, 9.5, 10.3, 10.7, 10.8, 10.8, 10.8, 10.7, 10.6, 10.5, 10.4, 10.3, 10.2, 10.0, 9.8, 9.6, 9.3, 8.9, 8.5, 8.2) / 100
S4 <- splinefun(T4, B4)
if(is4000) return(S4(T))
}
if(is5000 | !isoP | showsplines != "") {
# 550 and 600 degC points from Manning et al., 2013 Fig. 11
T5 <- c(seq(0, 500, 25), 550, 600)
B5 <- c(0.1, 6.7, 9.6, 11.1, 11.8, 12.2, 12.4, 12.4, 12.4, 12.4, 12.4, 12.3, 12.3, 12.2, 12.1, 11.9, 11.8, 11.5, 11.3, 11.0, 10.8, 11.2, 12.52) / 100
S5 <- splinefun(T5, B5)
if(is5000) return(S5(T))
}
# 10, 20, and 30 kb points from Manning et al., 2013 Fig. 11
# Here, one control point at 10 degC is added to make the splines curve down at low T
if(is10000 | !isoP | showsplines != "") {
T10 <- c(25, seq(300, 1000, 50))
B10 <- c(12, 17.6, 17.8, 18, 18.2, 18.9, 21, 23.3, 26.5, 28.8, 31.4, 34.1, 36.5, 39.2, 41.6, 44.1) / 100
S10 <- splinefun(T10, B10)
if(is10000) return(S10(T))
}
if(is20000 | !isoP | showsplines != "") {
T20 <- c(25, seq(300, 1000, 50))
B20 <- c(16, 21.2, 21.4, 22, 22.4, 23.5, 26.5, 29.2, 32.6, 35.2, 38.2, 41.4, 44.7, 47.7, 50.5, 53.7) / 100
S20 <- splinefun(T20, B20)
if(is20000) return(S20(T))
}
if(is30000 | !isoP | showsplines != "") {
T30 <- c(25, seq(300, 1000, 50))
B30 <- c(19, 23.9, 24.1, 24.6, 25.2, 26.7, 30.3, 32.9, 36.5, 39.9, 43, 46.4, 49.8, 53.2, 56.8, 60) / 100
S30 <- splinefun(T30, B30)
if(is30000) return(S30(T))
}
# 40-60 kb points extrapolated from 10-30 kb points of Manning et al., 2013
if(is40000 | !isoP | showsplines != "") {
T40 <- c(seq(300, 1000, 50))
B40 <- c(25.8, 26, 26.4, 27.2, 28.9, 33, 35.5, 39.2, 43.2, 46.4, 49.9, 53.4, 57.1, 61.2, 64.4) / 100
S40 <- splinefun(T40, B40)
if(is40000) return(S40(T))
}
if(is50000 | !isoP | showsplines != "") {
T50 <- c(seq(300, 1000, 50))
B50 <- c(27.1, 27.3, 27.7, 28.5, 30.5, 34.8, 37.3, 41.1, 45.5, 48.7, 52.4, 55.9, 59.8, 64.3, 67.5) / 100
S50 <- splinefun(T50, B50)
if(is50000) return(S50(T))
}
if(is60000 | !isoP | showsplines != "") {
T60 <- c(seq(300, 1000, 50))
B60 <- c(28, 28.2, 28.6, 29.5, 31.6, 36.1, 38.6, 42.5, 47.1, 50.4, 54.1, 57.6, 61.6, 66.5, 69.7) / 100
S60 <- splinefun(T60, B60)
if(is60000) return(S60(T))
}
# Show points and spline(T) curves
if(showsplines == "T") {
thermo.plot.new(c(0, 1000), c(-.2, .7), xlab = axis.label("T"), ylab = expression(italic(b)[gamma]))
points(T0, B0, pch = 0)
points(T0.5, B0.5, pch = 1)
points(T1, B1, pch = 1)
points(T2[-c(22:23)], B2[-c(22:23)], pch = 1)
points(T2[c(22:23)], B2[c(22:23)], pch = 2)
points(T3, B3, pch = 1)
points(T4, B4, pch = 1)
points(T5[-c(22:23)], B5[-c(22:23)], pch = 1)
points(T5[c(22:23)], B5[c(22:23)], pch = 2)
points(T10[-1], B10[-1], pch = 2)
points(T20[-1], B20[-1], pch = 2)
points(T30[-1], B30[-1], pch = 2)
points(T10[1], B10[1], pch = 5)
points(T20[1], B20[1], pch = 5)
points(T30[1], B30[1], pch = 5)
points(T40, B40, pch = 6)
points(T50, B50, pch = 6)
points(T60, B60, pch = 6)
col <- rev(topo.colors(13))
T0 <- seq(0, 350, 5); lines(T0, S0(T0), col = col[1])
T0.5 <- seq(0, 500, 5); lines(T0.5, S0.5(T0.5), col = col[2])
T1 <- seq(0, 500, 5); lines(T1, S1(T1), col = col[3])
T2 <- seq(0, 600, 5); lines(T2, S2(T2), col = col[4])
T3 <- seq(0, 600, 5); lines(T3, S3(T3), col = col[5])
T4 <- seq(0, 600, 5); lines(T4, S4(T4), col = col[6])
T5 <- seq(0, 600, 5); lines(T5, S5(T5), col = col[7])
T10 <- c(25, seq(100, 1000, 5)); lines(T10, S10(T10), col = col[8])
T20 <- c(80, seq(100, 1000, 5)); lines(T20, S20(T20), col = col[9])
T30 <- c(125, seq(200, 1000, 5)); lines(T30, S30(T30), col = col[10])
T40 <- c(175, seq(300, 1000, 5)); lines(T40, S40(T40), col = col[11])
T50 <- c(225, seq(300, 1000, 5)); lines(T50, S50(T50), col = col[12])
T60 <- c(250, seq(300, 1000, 5)); lines(T60, S60(T60), col = col[13])
legend("topleft", pch = c(0, 1, 2, 5, 6), bty = "n",
legend = c("Helgeson, 1969", "Helgeson et al., 1981", "Manning et al., 2013", "spline control point", "high-P extrapolation"))
legend("bottomright", col=c(NA, rev(col)), lty=1, bty = "n",
legend = c("kbar", "60", "50", "40", "30", "20", "10", "5", "4", "3", "2", "1", "0.5", "Psat"))
title(main = expression("Deybe-H\u00FCckel extended term ("*italic(b)[gamma]*") parameter"))
} else if(showsplines == "P") {
thermo.plot.new(c(0, 5), c(-.2, .7), xlab = expression(log~italic(P)*"(bar)"), ylab = expression(italic(b)[gamma]))
# Pressures that are used to make the isothermal splines (see below)
P25 <- c(1, 500, 1000, 2000, 3000, 4000, 5000)
P100 <- c(1, 500, 1000, 2000, 3000, 4000, 5000, 10000, 20000)
P200 <- c(16, 500, 1000, 2000, 3000, 4000, 5000, 10000, 20000, 30000, 40000)
P300 <- c(86, 500, 1000, 2000, 3000, 4000, 5000, 10000, 20000, 30000, 40000, 50000, 60000)
P400 <- c(500, 1000, 2000, 3000, 4000, 5000, 10000, 20000, 30000, 40000, 50000, 60000)
P500 <- c(1000, 2000, 3000, 4000, 5000, 10000, 20000, 30000, 40000, 50000, 60000)
P600 <- c(2000, 3000, 4000, 5000, 10000, 20000, 30000, 40000, 50000, 60000)
P700 <- c(10000, 20000, 30000, 40000, 50000, 60000)
P800 <- c(10000, 20000, 30000, 40000, 50000, 60000)
P900 <- c(10000, 20000, 30000, 40000, 50000, 60000)
P1000 <- c(10000, 20000, 30000, 40000, 50000, 60000)
# Plot the pressure and B-dot values used to make the isothermal splines
points(log10(P25), bgamma(25, P25))
points(log10(P100), bgamma(100, P100))
points(log10(P200), bgamma(200, P200))
points(log10(P300), bgamma(300, P300))
points(log10(P400), bgamma(400, P400))
points(log10(P500), bgamma(500, P500))
points(log10(P600), bgamma(600, P600))
points(log10(P700), bgamma(700, P700))
points(log10(P800), bgamma(800, P800))
points(log10(P900), bgamma(900, P900))
points(log10(P1000), bgamma(1000, P1000))
# Plot the isothermal spline functions
col <- tail(rev(rainbow(12)), -1)
P <- c(1, seq(50, 5000, 50)); lines(log10(P), bgamma(25, P), col = col[1])
P <- c(1, seq(50, 20000, 50)); lines(log10(P), bgamma(100, P), col = col[2])
P <- c(1, seq(50, 40000, 50)); lines(log10(P), bgamma(200, P), col = col[3])
P <- c(1, seq(50, 60000, 50)); lines(log10(P), bgamma(300, P), col = col[4])
P <- seq(500, 60000, 50); lines(log10(P), bgamma(400, P), col = col[5])
P <- seq(1000, 60000, 50); lines(log10(P), bgamma(500, P), col = col[6])
P <- seq(2000, 60000, 50); lines(log10(P), bgamma(600, P), col = col[7])
P <- seq(10000, 60000, 50); lines(log10(P), bgamma(700, P), col = col[8])
P <- seq(10000, 60000, 50); lines(log10(P), bgamma(800, P), col = col[9])
P <- seq(10000, 60000, 50); lines(log10(P), bgamma(900, P), col = col[10])
P <- seq(10000, 60000, 50); lines(log10(P), bgamma(1000, P), col = col[11])
legend("topleft", col = c(NA, col), lty = 1, bty = "n", legend = c("degrees C", 25, 100, 200, 300, 400, 500, 600, 700, 800, 900, 1000))
legend("bottomright", pch = 1, bty = "n", legend = "points from iso-P splines")
title(main = expression("Deybe-H\u00FCckel extended term ("*italic(b)[gamma]*") parameter"))
} else {
# Make T and P the same length
ncond <- max(length(T), length(P))
T <- rep(T, length.out = ncond)
P <- rep(P, length.out = ncond)
# Loop over P, T conditions
bgamma <- numeric()
lastT <- NULL
for(i in 1:length(T)) {
# Make it fast: skip splines at 25 degC and 1 bar
if(T[i] == 25 & P[i] == 1) bgamma <- c(bgamma, 0.041)
else {
if(!identical(T[i], lastT)) {
# Get the spline fits from particular pressures for each T
if(T[i] >= 700) {
PT <- c(10000, 20000, 30000, 40000, 50000, 60000)
B <- c(S10(T[i]), S20(T[i]), S30(T[i]), S40(T[i]), S50(T[i]), S60(T[i]))
} else if(T[i] >= 600) {
PT <- c(2000, 3000, 4000, 5000, 10000, 20000, 30000, 40000, 50000, 60000)
B <- c(S2(T[i]), S3(T[i]), S4(T[i]), S5(T[i]), S10(T[i]), S20(T[i]), S30(T[i]), S40(T[i]), S50(T[i]), S60(T[i]))
} else if(T[i] >= 500) {
PT <- c(1000, 2000, 3000, 4000, 5000, 10000, 20000, 30000, 40000, 50000, 60000)
B <- c(S1(T[i]), S2(T[i]), S3(T[i]), S4(T[i]), S5(T[i]), S10(T[i]), S20(T[i]), S30(T[i]), S40(T[i]), S50(T[i]), S60(T[i]))
} else if(T[i] >= 400) {
PT <- c(500, 1000, 2000, 3000, 4000, 5000, 10000, 20000, 30000, 40000, 50000, 60000)
B <- c(S0.5(T[i]), S1(T[i]), S2(T[i]), S3(T[i]), S4(T[i]), S5(T[i]), S10(T[i]), S20(T[i]), S30(T[i]), S40(T[i]), S50(T[i]), S60(T[i]))
} else if(T[i] >= 300) {
# Here the lowest P is Psat
PT <- c(86, 500, 1000, 2000, 3000, 4000, 5000, 10000, 20000, 30000, 40000, 50000, 60000)
B <- c(S0(T[i]), S0.5(T[i]), S1(T[i]), S2(T[i]), S3(T[i]), S4(T[i]), S5(T[i]), S10(T[i]), S20(T[i]), S30(T[i]), S40(T[i]), S50(T[i]), S60(T[i]))
} else if(T[i] >= 200) {
# Drop highest pressures because we get into ice
PT <- c(16, 500, 1000, 2000, 3000, 4000, 5000, 10000, 20000, 30000, 40000)
B <- c(S0(T[i]), S0.5(T[i]), S1(T[i]), S2(T[i]), S3(T[i]), S4(T[i]), S5(T[i]), S10(T[i]), S20(T[i]), S30(T[i]), S40(T[i]))
} else if(T[i] >= 100) {
PT <- c(1, 500, 1000, 2000, 3000, 4000, 5000, 10000, 20000)
B <- c(S0(T[i]), S0.5(T[i]), S1(T[i]), S2(T[i]), S3(T[i]), S4(T[i]), S5(T[i]), S10(T[i]), S20(T[i]))
} else if(T[i] >= 0) {
PT <- c(1, 500, 1000, 2000, 3000, 4000, 5000)
B <- c(S0(T[i]), S0.5(T[i]), S1(T[i]), S2(T[i]), S3(T[i]), S4(T[i]), S5(T[i]))
}
# Make a new spline as a function of pressure at this T
ST <- splinefun(PT, B)
# Remember this T; if it's the same as the next one, we won't re-make the spline
lastT <- T[i]
}
bgamma <- c(bgamma, ST(P[i]))
}
}
return(bgamma)
}
}
### Unexported function ###
Bdot <- function(TC) {
Bdot <- splinefun(c(25, 50, 100, 150, 200, 250, 300), c(0.0418, 0.0439, 0.0468, 0.0479, 0.0456, 0.0348, 0))(TC)
Bdot[TC > 300] <- 0
return(Bdot)
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/nonideal.R
|
# CHNOSZ/palply.R
palply <- function(varlist, X, FUN, ...) {
# A wrapper function to run parLapply if length(X) >= thermo()$opt$paramin
# and package 'parallel' is available, otherwise run lapply
if(length(X) >= get("thermo", CHNOSZ)$opt$paramin) {
# Use option mc.cores to choose an appropriate cluster size.
# and set max at 2 for now (per CRAN policies)
nCores <- min(getOption("mc.cores"), get("thermo", CHNOSZ)$opt$maxcores)
# Don't load methods package, to save startup time - ?makeCluster
cl <- parallel::makeCluster(nCores, methods = FALSE)
# Export the variables and notify the user
if(! "" %in% varlist) {
parallel::clusterExport(cl, varlist)
message(paste("palply:", caller.name(4), "running", length(X), "calculations on",
nCores, "cores with variable(s)", paste(varlist, collapse = ", ")))
} else {
message(paste("palply:", caller.name(4), "running", length(X), "calculations on",
nCores, "cores"))
}
# Run the calculations
out <- parallel::parLapply(cl, X, FUN, ...)
parallel::stopCluster(cl)
} else out <- lapply(X, FUN, ...)
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/palply.R
|
# CHNOSZ/protein.info.R
# Calculate formulas and summarize properties of proteins
# pinfo: find rownumber in thermo()$protein
# protein.length: lengths of the indicated proteins
# protein.formula: chemical makeup of the indicated proteins
# protein.OBIGT: perform group additivity calculations
# protein.basis: coefficients of basis species in formation reactions of [ionized] proteins [residues]
# protein.equil: step-by-step example of protein equilibrium calculation
pinfo <- function(protein, organism = NULL, residue = FALSE, regexp = FALSE) {
# Return the `protein` (possibly per residue) for:
# dataframe `protein`
# Return the rownumber(s) of thermo()$protein for:
# character `protein`, e.g. LYSC_CHICK
# character `protein` and `organism`, e.g. 'LYSC', 'CHICK'
# Return the row(s) of thermo()$protein (possibly per residue) for:
# numeric `protein` (the rownumber itself)
if(is.data.frame(protein)) out <- protein
if(is.numeric(protein)) {
t_p <- get("thermo", CHNOSZ)$protein
# Drop NA matches to thermo()$protein
iproteins <- 1:nrow(t_p)
protein[!protein %in% iproteins] <- NA
# Get amino acid counts
out <- t_p[protein, ]
}
if(is.data.frame(protein) | is.numeric(protein)) {
# Compute per-residue counts if requested
if(residue) out[, 5:25] <- out[, 5:25]/rowSums(out[, 6:25])
} else {
t_p <- get("thermo", CHNOSZ)$protein
# Search for protein by regular expression
if(regexp) {
iprotein <- grepl(protein, t_p$protein)
iorganism <- iprotein
if(!is.null(organism)) iorganism <- grepl(organism, t_p$organism)
iprotein <- which(iprotein & iorganism)
} else {
# Search for protein or protein_organism in thermo()$protein
t_p_names <- paste(t_p$protein, t_p$organism, sep = "_")
if(is.null(organism)) my_names <- protein
else my_names <- paste(protein, organism, sep = "_")
iprotein <- match(my_names, t_p_names)
}
out <- iprotein
}
out
}
protein.formula <- function(protein, organism = NULL, residue = FALSE) {
# Return a matrix with chemical formulas of proteins
aa <- pinfo(pinfo(protein, organism))
rf <- group.formulas()
out <- as.matrix(aa[, 5:25]) %*% as.matrix(rf)
if(residue) out <- out / rowSums(aa[, 6:25])
row.names(out) <- make.unique(paste(aa$protein, aa$organism, sep = "_"))
return(out)
}
protein.length <- function(protein, organism = NULL) {
# Calculate the length(s) of proteins
aa <- pinfo(pinfo(protein, organism))
# Use rowSums on the columns containing amino acid counts
pl <- as.numeric(rowSums(aa[, 6:25]))
return(pl)
}
protein.OBIGT <- function(protein, organism = NULL, state = thermo()$opt$state) {
# Display and return the properties of
# proteins calculated from amino acid composition
aa <- pinfo(pinfo(protein, organism))
# The names of the protein backbone groups depend on the state
# [UPBB] for aq or [PBB] for cr
if(state == "aq") bbgroup <- "UPBB" else bbgroup <- "PBB"
# Names of the AABB, sidechain and protein backbone groups
groups <- c("AABB", colnames(aa)[6:25], bbgroup)
# Put brackets around the group names
groups <- paste("[", groups, "]", sep = "")
# The rownumbers of the groups in thermo()$OBIGT
groups_state <- paste(groups, state)
OBIGT <- get("thermo", CHNOSZ)$OBIGT
OBIGT_state <- paste(OBIGT$name, OBIGT$state)
igroup <- match(groups_state, OBIGT_state)
# The properties are in columns 10-22 of thermo()$OBIGT
groupprops <- OBIGT[igroup, 10:22]
# The elements in each of the groups
groupelements <- i2A(igroup)
# A function to work on a single row of aa
eosfun <- function(aa) {
# Numbers of groups: chains [=AABB], sidechains, protein backbone
nchains <- as.numeric(aa[, 5])
length <- sum(as.numeric(aa[, 6:25]))
npbb <- length - nchains
ngroups <- c(nchains, as.numeric(aa[, 6:25]), npbb)
# The actual adding and multiplying of thermodynamic properties
# Hmm. seems like we have to split up the multiplication/transposition
# operations to get the result into multiple columns. 20071213
eos <- t(data.frame(colSums(groupprops * ngroups)))
# To get the formula, add up and round the group compositions 20090331
f.in <- round(colSums(groupelements * ngroups), 3)
# Take out any elements that don't appear (sometimes S)
f.in <- f.in[f.in != 0]
# Turn it into a formula
f <- as.chemical.formula(f.in)
# Now the species name
name <- paste(aa$protein, aa$organism, sep = "_")
# Tell the user about it
message("protein.OBIGT: found ", appendLF = FALSE)
message(name, " (", f, ", ", appendLF = FALSE)
message(round(length, 3), " residues)")
ref <- aa$ref
# Include 'model' column 20220919
model <- ifelse(state == "aq", "HKF", "CGL")
header <- data.frame(name = name, abbrv = NA, formula = f, state = state, ref1 = ref, ref2 = NA,
date = NA, model = model, E_units = "cal", stringsAsFactors = FALSE)
eosout <- cbind(header, eos)
return(eosout)
}
# Loop over each row of aa
out <- lapply(1:nrow(aa), function(i) eosfun(aa[i, ]))
out <- do.call(rbind, out)
rownames(out) <- NULL
return(out)
}
protein.basis <- function(protein, T = 25, normalize = FALSE) {
# 20090902 Calculate the coefficients of basis species in reactions
# to form proteins (possibly per normalized by length) listed in protein
# 20120528 Renamed protein.basis from residue.info
# What are the elemental compositions of the proteins
aa <- pinfo(pinfo(protein))
pf <- protein.formula(aa)
# What are the coefficients of the basis species in the formation reactions
sb <- species.basis(pf)
# Calculate ionization states if H+ is a basis species
thermo <- get("thermo", CHNOSZ)
iHplus <- match("H+", rownames(thermo$basis))
if(!is.na(iHplus)) {
pH <- -thermo$basis$logact[iHplus]
Z <- ionize.aa(aa, T = T, pH = pH)[1, ]
sb[, iHplus] <- sb[, iHplus] + Z
}
# Compute per length-normalized coefficients if requested
if(normalize) {
# get lengths of proteins
plen <- protein.length(aa)
sb <- sb/plen
}
# Return the result
return(sb)
}
protein.equil <- function(protein, T = 25, loga.protein = 0, digits = 4) {
out <- character()
mymessage <- function(...) {
message(...)
text <- paste(list(...), collapse = " ")
out <<- c(out, text)
}
# Show the individual steps in calculating metastable equilibrium among proteins
mymessage("protein.equil: temperature from argument is ", T, " degrees C")
# Display units
E_units <- E.units()
mymessage("protein.equil: energy units is ", E_units)
TK <- convert(T, "K")
# Get the amino acid compositions of the proteins
aa <- pinfo(pinfo(protein))
# Get some general information about the proteins
pname <- paste(aa$protein, aa$organism, sep = "_")
plength <- protein.length(aa)
# Use thermo()$basis to decide whether to ionize the proteins
thermo <- get("thermo", CHNOSZ)
ionize.it <- FALSE
iword <- "nonionized"
bmat <- basis.elements()
if("H+" %in% rownames(bmat)) {
ionize.it <- TRUE
iword <- "ionized"
pH <- -thermo$basis$logact[match("H+", rownames(bmat))]
mymessage("protein.equil: pH from thermo$basis is ", pH)
}
# Tell the user whose [Met] is in thermo$OBIGT
info.Met <- info(info('[Met]', "aq"))
mymessage("protein.equil: [Met] is from reference ", info.Met$ref1)
## First set of output: show results of calculations for a single protein
mymessage("protein.equil [1]: first protein is ", pname[1], " with length ", plength[1])
# Standard Gibbs energies of basis species
G0basis <- unlist(suppressMessages(subcrt(thermo$basis$ispecies, T = T, property = "G")$out))
# Coefficients of basis species in formation reactions of proteins
protbasis <- suppressMessages(protein.basis(aa, T = T))
# Sum of standard Gibbs energies of basis species in each reaction
G0basissum <- colSums(t(protbasis) * G0basis)
# Standard Gibbs energies of nonionized proteins
G0prot <- unlist(suppressMessages(subcrt(pname, T = T, property = "G")$out))
# Standard Gibbs energy of formation reaction of nonionized protein, E_units/mol
G0protform <- G0prot - G0basissum
mymessage("protein.equil [1]: reaction to form nonionized protein from basis species has G0(", E_units, "/mol) of ", signif(G0protform[1], digits))
if(ionize.it) {
# Standard Gibbs energy of ionization of protein, J/mol
G0ionization <- suppressMessages(ionize.aa(aa, property = "G", T = T, pH = pH))[1, ]
# Standard Gibbs energy of ionization of protein, E_units/mol
if(E_units == "cal") G0ionization <- convert(G0ionization, "cal")
mymessage("protein.equil [1]: ionization reaction of protein has G0(", E_units, "/mol) of ", signif(G0ionization[1], digits))
# Standard Gibbs energy of formation reaction of ionized protein, E_units/mol
G0protform <- G0protform + G0ionization
}
# Standard Gibbs energy of formation reaction of non/ionized residue equivalents, dimensionless
# Gas constant
#if(E_units == "cal") R <- 1.9872 # gas constant, cal K^-1 mol^-1
#if(E_units == "J") R <- 8.314445 # = 1.9872 * 4.184 J K^-1 mol^-1 20220325
if(E_units == "J") R <- 8.314463 # https://physics.nist.gov/cgi-bin/cuu/Value?r 20230630
if(E_units == "cal") R <- 8.314463 / 4.184
G0res.RT <- G0protform/R/TK/plength
mymessage("protein.equil [1]: per residue, reaction to form ", iword, " protein from basis species has G0/RT of ", signif(G0res.RT[1], digits))
# Coefficients of basis species in formation reactions of residues
resbasis <- suppressMessages(protein.basis(aa, T = T, normalize = TRUE))
# logQstar and Astar/RT
logQstar <- colSums(t(resbasis) * - thermo$basis$logact)
mymessage("protein.equil [1]: per residue, logQstar is ", signif(logQstar[1], digits))
Astar.RT <- -G0res.RT - log(10)*logQstar
mymessage("protein.equil [1]: per residue, Astar/RT = -G0/RT - 2.303logQstar is ", signif(Astar.RT[1], digits))
if(!is.numeric(protein)) mymessage("protein.equil [1]: not comparing calculations with affinity() because 'protein' is not numeric")
else {
# For **Astar** we have to set the activities of the proteins to zero, not loga.protein!
a <- suppressMessages(affinity(iprotein = protein, T = T, loga.protein = 0))
aAstar.RT <- log(10) * as.numeric(a$values) / plength
mymessage("check it! per residue, Astar/RT calculated using affinity() is ", signif(aAstar.RT[1], digits))
if(!isTRUE(all.equal(Astar.RT, aAstar.RT, check.attributes = FALSE)))
stop("Bug alert! The same value for Astar/RT cannot be calculated manually as by using affinity()")
}
if(length(pname) == 1) mymessage("protein.equil [all]: all done... give me more than one protein for equilibrium calculations")
else {
## Next set of output: equilibrium calculations
mymessage("protein.equil [all]: lengths of all proteins are ", paste(plength, collapse = " "))
mymessage("protein.equil [all]: Astar/RT of all residue equivalents are ", paste(signif(Astar.RT, digits), collapse = " "))
expAstar.RT <- exp(Astar.RT)
sumexpAstar.RT <- sum(expAstar.RT)
mymessage("protein.equil [all]: sum of exp(Astar/RT) of all residue equivalents is ", signif(sumexpAstar.RT, digits))
# Boltzmann distribution
alpha <- expAstar.RT / sumexpAstar.RT
mymessage("protein.equil [all]: equilibrium degrees of formation (alphas) of residue equivalents are ", paste(signif(alpha, digits), collapse = " "))
# Check with equilibrate()
if(is.numeric(protein)) {
loga.equil.protein <- unlist(suppressMessages(equilibrate(a, normalize = TRUE))$loga.equil)
# Here we do have to convert from logarithms of activities of proteins to degrees of formation of residue equivalents
a.equil.residue <- plength*10^loga.equil.protein
ealpha <- a.equil.residue/sum(a.equil.residue)
mymessage("check it! alphas of residue equivalents from equilibrate() are ", paste(signif(ealpha, digits), collapse = " "))
if(!isTRUE(all.equal(alpha, ealpha, check.attributes = FALSE)))
stop("Bug alert! The same value for alpha cannot be calculated manually as by using equilibrate()")
}
# Total activity of residues
loga.residue <- log10(sum(plength * 10^loga.protein))
mymessage("protein.equil [all]: for activity of proteins equal to 10^", signif(loga.protein, digits), ", total activity of residues is 10^", signif(loga.residue, digits))
# Equilibrium activities of residues
loga.residue.equil <- log10(alpha*10^loga.residue)
mymessage("protein.equil [all]: log10 equilibrium activities of residue equivalents are ", paste(signif(loga.residue.equil, digits), collapse = " "))
# Equilibrium activities of proteins
loga.protein.equil <- log10(10^loga.residue.equil/plength)
mymessage("protein.equil [all]: log10 equilibrium activities of proteins are ", paste(signif(loga.protein.equil, digits), collapse = " "))
# Check with equilibrate()
if(is.numeric(protein)) {
eloga.protein.equil <- unlist(suppressMessages(equilibrate(a, loga.balance = loga.residue, normalize = TRUE))$loga.equil)
mymessage("check it! log10 eq'm activities of proteins from equilibrate() are ", paste(signif(eloga.protein.equil, digits), collapse = " "))
if(!isTRUE(all.equal(loga.protein.equil, eloga.protein.equil, check.attributes = FALSE)))
stop("Bug alert! The same value for log10 equilibrium activities of proteins cannot be calculated manually as by using equilibrate()")
}
}
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/protein.info.R
|
# Calculate normalized sum of ranking of affinities for species in designated groups
# 20220416 jmd first version
rank.affinity <- function(aout, groups, percent = TRUE) {
# Put the affinities into matrix form
amat <- sapply(aout$values, as.numeric)
# Calculate ranks
# https://stackoverflow.com/questions/1412775/pmax-parallel-maximum-equivalent-for-rank-in-r
arank <- apply(amat, 1, rank)
# Get the normalized ranks for each group
grank <- sapply(groups, function(group) {
# Sum the ranks for this group and divide by number of species in the group
if(inherits(group, "logical")) n <- sum(group)
if(inherits(group, "integer")) n <- length(group)
colSums(arank[group, ]) / n
})
# Calculate rank-sum percentage 20240106
if(percent) grank <- grank / rowSums(grank) * 100
# Restore dims
dims <- dim(aout$values[[1]])
# apply() got 'simplify' argument in R 4.1.0 20230313
# Using 'simplify = FALSE' in R < 4.1.0 caused error: 3 arguments passed to 'dim<-' which requires 2
if(getRversion() < "4.1.0") glist <- lapply(lapply(apply(grank, 2, list), "[[", 1), "dim<-", dims)
else glist <- apply(grank, 2, "dim<-", dims, simplify = FALSE)
aout$values <- glist
# Rename species to group names (for use by diagram())
aout$species <- aout$species[1:length(groups), ]
aout$species$name <- names(groups)
# "Sign" the object with our function name
aout$fun <- "rank.affinity"
aout
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/rank.affinity.R
|
# CHNOSZ/retrieve.R
# Retrieve species with given elements
# 20190214 initial version
# 20190224 define a chemical system using multiple arguments [defunct; use list() for chemical system]
# 20190304 update the stoichiometric matrix instead of doing a full recalculation when the database changes
# 20190305 use c() for combination of elements, list() for chemical system,
# and add 'ligands' argument to retrieve element-bearing species
retrieve <- function(elements = NULL, ligands = NULL, state = NULL, T = NULL, P = "Psat", add.charge = TRUE, hide.groups = TRUE) {
## Empty argument handling
if(is.null(elements)) return(integer())
## Stoichiometric matrix
# What are the formulas of species in the current database?
formula <- thermo()$OBIGT$formula
# Get a previously calculated stoichiometric matrix
stoich <- thermo()$stoich
# If it doesn't match the current database, update it
if(!identical(rownames(stoich), formula)) {
message("retrieve: updating stoichiometric matrix")
# First put rows in the right order for the current database
istoich <- match(formula, rownames(stoich))
stoich <- stoich[na.omit(istoich), ]
# Deal with any missing formulas
if(any(is.na(istoich))) {
# Convert the stoichiometric matrix to data frame with a 'formula' column
oldstoich <- cbind(formula = rownames(stoich), as.data.frame(stoich))
# Get the stoichiometry of the additional formulas
# and suppress warning messages about missing elements
addstoich <- suppressWarnings(i2A(formula[is.na(istoich)]))
addstoich <- cbind(formula = rownames(addstoich), as.data.frame(addstoich))
# Merge the old and added stoichiometries, and assign 0 for missing elements in either one
newstoich <- merge(oldstoich, addstoich, all = TRUE)
newstoich[is.na(newstoich)] <- 0
# Convert the data frame to matrix with rownames corresponding to formulas
stoich <- as.matrix(newstoich[, 2:ncol(newstoich)])
rownames(stoich) <- newstoich$formula
# Put rows in the right order for the current database
istoich <- match(formula, rownames(stoich))
stoich <- stoich[istoich, ]
}
# Store the stoichiometric matrix for later calculations
thermo("stoich" = stoich)
}
## Generate error for missing element(s)
allelements <- c(unlist(elements), unlist(ligands))
not.present <- ! allelements %in% c(colnames(stoich), "all")
if(any(not.present)) {
if(sum(not.present) == 1) stop('"', allelements[not.present], '" is not an element that is present in any species in the database')
else stop('"', paste(allelements[not.present], collapse = '", "'), '" are not elements that are present in any species in the database')
}
## Handle 'ligands' argument
if(!is.null(ligands)) {
# If 'ligands' is cr, liq, gas, or aq, use that as the state
if(any(ligands %in% c("cr", "liq", "gas", "aq")) & length(ligands) == 1) {
state <- ligands
ispecies <- retrieve(elements, add.charge = add.charge)
} else {
# Include the element in the system defined by the ligands list
ligands <- c(elements, as.list(ligands))
# Call retrieve() for each argument and take the intersection
r1 <- retrieve(elements, add.charge = add.charge)
r2 <- retrieve(ligands, add.charge = add.charge)
ispecies <- intersect(r1, r2)
}
} else {
## Species identification
ispecies <- list()
# Automatically add charge to a system 20190225
if(add.charge & is.list(elements) & !"Z" %in% elements) elements <- c(elements, "Z")
# Proceed element-by-element
for(i in seq_along(elements)) {
element <- unlist(elements[i])
if(identical(element, "all")) {
ispecies[[i]] <- 1:nrow(thermo()$OBIGT)
} else {
# Identify the species that have the element
has.element <- rowSums(stoich[, element, drop = FALSE] != 0) == 1
ispecies[[i]] <- which(has.element)
}
}
# Now we have a list of ispecies (one vector for each element)
# What we do next depends on whether the argument is a list() or c()
if(is.list(elements)) {
# For a chemical system, all species are included that do not contain any other elements
ispecies <- unique(unlist(ispecies))
ielements <- colnames(thermo()$stoich) %in% elements
if(any(!ielements)) {
otherstoich <- thermo()$stoich[, !ielements]
iother <- rowSums(otherstoich[ispecies, ] != 0) > 0
ispecies <- ispecies[!iother]
}
} else {
# Get species that have all the elements; the species must be present in each vector
# Reduce() hint from https://stackoverflow.com/questions/27520310/union-of-intersecting-vectors-in-a-list-in-r
ispecies <- Reduce(intersect, ispecies)
}
}
# Exclude groups
if(hide.groups) {
igroup <- grepl("^\\[.*\\]$", thermo()$OBIGT$name[ispecies])
ispecies <- ispecies[!igroup]
}
# Filter on state
if(!is.null(state)) {
istate <- thermo()$OBIGT$state[ispecies] %in% state
ispecies <- ispecies[istate]
}
# Require non-NA Delta G0 at specific temperature 20200825
if(!is.null(T)) {
G <- sapply(suppressMessages(subcrt(ispecies, T = T, P = P))$out, "[[", "G")
ispecies <- ispecies[!is.na(G)]
}
# Assign names; use e- instead of (Z-1)
names(ispecies) <- thermo()$OBIGT$formula[ispecies]
names(ispecies)[names(ispecies) == "(Z-1)"] <- "e-"
# If there's nothing, don't give it a name
if(length(ispecies) == 0) ispecies <- integer()
ispecies
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/retrieve.R
|
# solubility.R: vectorized solubility calculations without uniroot
# 20181031 first version jmd
# 20181106 work on the output from affinity(); no "equilibrate()" needed!
# 20190117 add find.IS and test for dissociation reaction
# 20210319 use vector of aqueous species as main argument (with back-compatibility for affinity output) and handle multiple minerals
## If this file is interactively sourced, the following are also needed to provide unexported functions:
#source("equilibrate.R")
#source("util.misc.R")
#source("species.R")
#source("util.args.R")
#source("util.character.R")
#source("mosaic.R")
#source("basis.R")
# Function to calculate solubilities of multiple minerals 20210303
# species() should be used first to load the minerals (all bearing the same metal)
# 'iaq' lists aqueous species that can be produced by dissolution of the minerals
# '...' contains arguments for affinity() or mosaic() (i.e. plotting variables)
solubility <- function(iaq, ..., in.terms.of = NULL, dissociate = FALSE, find.IS = FALSE) {
# If iaq is the output of affinity(), use old calling style 20210318
if(is.list(iaq)) return(solubility_calc(aout = iaq, in.terms.of = in.terms.of, dissociate = dissociate, find.IS = find.IS))
# Check whether to use affinity() or mosaic()
affargs <- ddd <- list(...)
is.mosaic <- FALSE
if(identical(names(ddd)[1], "bases")) {
is.mosaic <- TRUE
# For getting 'sout' from affinity(), drop arguments specific for mosaic()
affargs <- ddd[-1]
affargs <- affargs[!names(affargs) %in% c("bases", "stable", "blend", "loga_aq")]
}
# Save current thermodynamic system settings
thermo <- get("thermo", CHNOSZ)
# Use current basis species as a template for the solubility calculations
ispecies <- basis()$ispecies
logact <- basis()$logact
# The current formed species are the minerals to be dissolved
mineral <- species()
if(is.null(mineral)) stop("please load minerals or gases with species()")
if(!find.IS) {
# Get subcrt() output for all aqueous species and minerals 20210322
# Add aqueous species here - the minerals are already present
lapply(iaq, species, add = TRUE)
# Also add basis species for mosaic()!
if(is.mosaic) lapply(unlist(ddd$bases), species, add = TRUE)
sout <- suppressMessages(do.call(affinity, c(affargs, return.sout = TRUE)))
}
# Make a list to store the calculated solubilities for each mineral
slist <- list()
# Loop over minerals
for(i in seq_along(mineral$ispecies)) {
# Print message
message(paste("solubility: calculating for", mineral$name[i]))
# Define basis species with the mineral first (so it will be dissolved)
ispecies[1] <- mineral$ispecies[i]
logact[1] <- mineral$logact[i]
# Use numeric values first and put in buffer names second (needed for demo/gold.R)
loga.numeric <- suppressWarnings(as.numeric(logact))
basis(ispecies, loga.numeric)
is.na <- is.na(loga.numeric)
if(any(is.na)) basis(rownames(basis())[is.na], logact[is.na])
# Add aqueous species (no need to define activities here - they will be calculated by solubility_calc)
species(iaq)
if(find.IS) {
if(is.mosaic) aout <- suppressMessages(mosaic(...)) else aout <- suppressMessages(affinity(...))
} else {
if(is.mosaic) aout <- suppressMessages(mosaic(..., sout = sout)) else aout <- suppressMessages(affinity(..., sout = sout))
}
# Calculate solubility of this mineral
scalc <- solubility_calc(aout, in.terms.of = in.terms.of, dissociate = dissociate, find.IS = find.IS)
# Store the solubilities in the list
slist[[i]] <- scalc$loga.balance
}
# Restore the original thermodynamic system settings
assign("thermo", thermo, CHNOSZ)
if(length(mineral$ispecies) == 1) {
# For one mineral, return the results of the solubility calculation
scalc
} else {
# For multiple minerals, the overall solubility is the *minimum* among all the minerals
smin <- do.call(pmin, slist)
# Put this into the last-computed 'solubility' object
scalc$loga.balance <- smin
scalc$loga.equil <- slist
scalc$species <- mineral
# Change the function name stored in the object so diagram() plots loga.balance automatically
scalc$fun <- "solubilities"
# Return the object
scalc
}
}
# The "nuts and bolts" of solubility calculations
# Moved from solubility() to solubility_calc() 20210318
solubility_calc <- function(aout, dissociate = NULL, find.IS = FALSE, in.terms.of = NULL) {
## Concept: the logarithms of activities of species at equilibrium are equal to
## Astar, the affinities calculated for unit activities of species
## Is aout the output from mosaic() instead of affinity()?
aout.save <- aout
thisfun <- aout$fun
if(thisfun == "mosaic") aout <- aout$A.species
# Get starting ionic strength (probably zero, but could be anything set by user)
IS <- aout$IS
if(is.null(IS)) IS <- 0
## To output loga.balance we need the balancing coefficients
bout <- balance(aout)
n.balance <- bout$n.balance
balance <- bout$balance
# Get logarithm of total activity of the conserved basis species
logabfun <- function(loga.equil, n.balance) {
# Exponentiate, multiply by n.balance, sum, logarithm
a.equil <- mapply("^", 10, loga.equil, SIMPLIFY = FALSE)
a.balance <- mapply("*", a.equil, n.balance, SIMPLIFY = FALSE)
a.balance <- Reduce("+", a.balance)
log10(a.balance)
}
# For find.IS = TRUE, iterate to converge on ionic strength
niter <- 1
while(TRUE) {
## The values in aout can be calculated for other than
## unit activities of species, so we have to take away the activites
Astar <- function(i) aout$values[[i]] + aout$species$logact[i]
loga.equil <- lapply(1:length(aout$values), Astar)
## For a dissociation on a *per reaction* (not system) basis, apply the divisor here
## (can be used to reproduce Fig. 4 of Manning et al., 2013)
if(is.numeric(dissociate)) {
loga.equil <- lapply(loga.equil, "/", dissociate)
}
# Get the total activity of the balancing basis species
loga.balance <- logabfun(loga.equil, n.balance)
# Recalculate things for a dissociation reaction (like CaCO3 = Ca+2 + CO3+2)
if(isTRUE(dissociate)) {
ndissoc <- 2
# The number of dissociated products is the exponent in the activity product
loga.dissoc <- loga.balance / ndissoc
# The contribution to affinity
Adissoc <- lapply(n.balance, "*", loga.dissoc)
# Adjust the affinity and get new equilibrium activities
aout$values <- mapply("-", aout$values, Adissoc, SIMPLIFY = FALSE)
loga.equil <- lapply(1:length(aout$values), Astar)
loga.balance <- logabfun(loga.equil, n.balance)
# Check that the new loga.balance == loga.dissoc
# TODO: does this work for non-1:1 species?
stopifnot(all.equal(loga.balance, loga.dissoc))
}
# Get the old IS
IS.old <- rep(IS, length.out = length(aout$values[[1]]))
# Calculate the ionic strength for unpaired ions: IS = sum(molality * Z^2) / 2
sum.mZ2 <- 0
ion.names <- character()
# is there an ion in the basis species?
if(dissociate) {
basis.ion <- rownames(aout$basis)[2]
Z.basis.ion <- makeup(basis.ion)["Z"]
if(!is.na(Z.basis.ion)) {
sum.mZ2 <- sum.mZ2 + 10^loga.balance * Z.basis.ion^2
ion.names <- c(ion.names, basis.ion)
}
}
# Add ions present in the species of interest
# Instead of using aout$species$name, use info() to get formulas 20190309
species.formulas <- suppressMessages(info(aout$species$ispecies, check.it = FALSE)$formula)
for(i in 1:length(loga.equil)) {
species.ion <- species.formulas[i]
Z.species.ion <- makeup(species.ion)["Z"]
if(!is.na(Z.species.ion)) {
sum.mZ2 <- sum.mZ2 + 10^loga.equil[[i]] * Z.species.ion^2
ion.names <- c(ion.names, species.ion)
}
}
IS <- sum.mZ2 / 2
# Report ions used in the ionic strength calculation
if(find.IS & niter == 1) message("solubility: ionic strength calculated for ", paste(ion.names, collapse = " "))
# Report the current ionic strength
if(find.IS) message("solubility: (iteration ", niter, ") ionic strength range is ", paste(round(range(IS), 4), collapse = " "))
# Stop iterating if we reached the tolerance (or find.IS = FALSE)
if(!find.IS | all(IS - IS.old < 1e-4)) break
# On the first iteration, expand argument values for affinity() or mosaic()
# (e.g. convert pH = c(0, 14) to pH = seq(0, 14, 256) so that it has the same length as the IS values)
# We don't do this if aout$vals is NA 20190731
if(niter == 1 & !all(is.na(aout$vals))) {
if(thisfun == "affinity") for(i in 1:length(aout$vals)) {
aout.save$args[[i]] <- aout$vals[[i]]
}
else if(thisfun == "mosaic") {
for(i in 1:length(aout$vals)) {
argname <- names(aout$args)[i]
aout.save$args[[argname]] <- aout$vals[[i]]
}
}
}
# Recalculate the affinity using the new IS
aout <- suppressMessages(do.call(thisfun, list(aout.save, IS = IS)))
if(thisfun == "mosaic") aout <- aout$A.species
niter <- niter + 1
}
# Do we want the solubility expressed in terms of
# something other than the first basis species? 20190123
if(!is.null(in.terms.of)) {
# write the reaction between the basis species and the new species
sbasis <- species.basis(in.terms.of)
# divide the activity of the conserved basis species by the coefficient in the formation reaction
ibalance <- which.balance(aout$species)
coeff <- sbasis[, ibalance][1]
loga.balance <- loga.balance - log10(coeff)
}
# Make the output (we don't deal with normalized formulas yet, so for now m.balance == n.balance)
# Indicate the function used to make this output 20190525
aout$fun <- "solubility"
# Add names to loga.equil 20190731
names(loga.equil) <- aout$species$name
c(aout, list(balance = bout$balance, m.balance = bout$n.balance, n.balance = bout$n.balance, in.terms.of = in.terms.of,
loga.balance = loga.balance, Astar = loga.equil, loga.equil = loga.equil))
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/solubility.R
|
# CHNOSZ/species.R
# Define species of interest
# Function to create or add to the species data frame
species <- function(species = NULL, state = NULL, delete = FALSE, add = FALSE, index.return = FALSE) {
# 20080925 default quiet = TRUE 20101003 default quiet = FALSE
# 20120128 remove 'quiet' argument (messages can be hidden with suppressMessages())
# 20120523 return thermo()$species instead of rownumbers therein, and remove message showing thermo()$species
# 20200714 add 'add' argument (by default, previous species are deleted)
thermo <- get("thermo", CHNOSZ)
## Argument processing
# We can't deal with NA species
if(identical(species, NA)) {
cn <- caller.name()
if(length(cn) > 0) ctext <- paste("(calling function was ", cn, ")", sep = "") else ctext <- ""
stop(paste("'species' is NA", ctext))
}
# Delete the entire species definition or only selected species
if(delete) {
# Delete the entire definition if requested
if(is.null(species)) {
thermo$species <- NULL
assign("thermo", thermo, CHNOSZ)
return(thermo$species)
}
# From here we're trying to delete already defined species
if(is.null(thermo$species)) stop("nonexistent species definition")
# Match species to delete by name and species number
isp <- rep(NA, length(species))
ispname <- match(species, thermo$species$name)
ispnum <- match(species, 1:nrow(thermo$species))
isp[!is.na(ispname)] <- ispname[!is.na(ispname)]
isp[!is.na(ispnum)] <- ispnum[!is.na(ispnum)]
# Filter out non-matching species
ina <- is.na(isp)
if(any(ina)) warning(paste("species:",
paste(species[ina], collapse = " "), "not present, so can not be deleted"))
isp <- isp[!ina]
# Go on to delete this/these species
if(length(isp) > 0) {
thermo$species <- thermo$species[-isp,]
if(nrow(thermo$species) == 0) thermo$species <- NULL
else rownames(thermo$species) <- 1:nrow(thermo$species)
assign("thermo", thermo, CHNOSZ)
}
return(thermo$species)
}
# If no species or states are given, just return the species list
if(is.null(species) & is.null(state)) return(thermo$species)
# If no species are given use all of them if available
if(is.null(species) & !is.null(thermo$species)) species <- 1:nrow(thermo$species)
# Parse state argument
state <- state.args(state)
# Make species and state arguments the same length
if(length(species) > length(state) & !is.null(state)) state <- rep(state,length.out = length(species)) else
if(length(state) > length(species) & !is.null(species)) species <- rep(species,length.out = length(state))
# Rename state as logact if it's numeric, or get default values of logact
if(is.numeric(state[1])) {
logact <- state
state <- NULL
} else logact <- NULL
# If they don't look like states (aq,gas,cr) or activities (numeric),
# use them as a suffix for species name (i.e., a protein_organism)
allstates <- unique(thermo$OBIGT$state)
if( sum(state %in% allstates) < length(state) & !can.be.numeric(state[1]) & !can.be.numeric(species[1]) ) {
species <- paste(species, state, sep = "_")
state <- rep(thermo$opt$state, length.out = length(state))
}
# Parse species argument
iOBIGT <- NULL
if(is.character(species[1])) {
# Look for named species in species definition
ispecies <- match(species, thermo$species$name)
# If all species names match, and logact is given, re-call the function with the species indices
if(!any(is.na(ispecies)) & !is.null(logact)) return(species(ispecies, state = logact, index.return = index.return))
# Look for species in thermo()$OBIGT
iOBIGT <- suppressMessages(info(species, state))
# Since that could have updated thermo()$OBIGT (with proteins), re-read thermo
thermo <- get("thermo", CHNOSZ)
# Check if we got all the species
ina <- is.na(iOBIGT)
if(any(ina)) stop(paste("species not available:", paste(species[ina], collapse = " ")))
} else {
# If species is numeric and a small number it refers to the species definition,
# else to species index in thermo()$OBIGT
nspecies <- nrow(thermo$species)
if(is.null(thermo$species)) nspecies <- 0
if(max(species) > nspecies) iOBIGT <- species
}
## Done with argument processing ... now to do work
# Create or add to species definition
if(!is.null(iOBIGT)) {
if(is.null(thermo$basis)) stop("basis species are not defined")
# The coefficients in reactions to form the species from basis species
# Wrap values in unname in case they have names from retrieve(), otherwise makeup() doesn't work as intended 20190225
f <- (species.basis(unname(iOBIGT)))
# The states and species names
state <- as.character(thermo$OBIGT$state[iOBIGT])
name <- as.character(thermo$OBIGT$name[iOBIGT])
# Get default values of logact
if(is.null(logact)) {
logact <- rep(0, length(species))
logact[state == "aq"] <- -3
}
# Create the new species
newspecies <- data.frame(f, ispecies = iOBIGT, logact = logact, state = state, name = name, stringsAsFactors = FALSE)
# "H2PO4-" looks better than "H2PO4."
colnames(newspecies)[1:nrow(thermo$basis)] <- rownames(thermo$basis)
# Initialize or add to species data frame
if(is.null(thermo$species) | !add) {
thermo$species <- newspecies
ispecies <- 1:nrow(thermo$species)
} else {
# Don't add species that already exist
idup <- newspecies$ispecies %in% thermo$species$ispecies
thermo$species <- rbind(thermo$species, newspecies[!idup, ])
ispecies <- match(newspecies$ispecies, thermo$species$ispecies)
}
rownames(thermo$species) <- seq(nrow(thermo$species))
} else {
# Update activities or states of existing species
# First get the rownumbers in thermo()$species
if(is.numeric(species[1])) {
ispecies <- species
# If state and logact are both NULL we don't do anything but return the selected species
if(is.null(state) & is.null(logact)) {
if(index.return) return(ispecies)
else return(thermo$species[ispecies, ])
}
} else ispecies <- match(species, thermo$species$name)
# Replace activities?
if(!is.null(logact)) {
thermo$species$logact[ispecies] <- logact
} else {
# Change states, checking for availability of the desired state
for(i in 1:length(ispecies)) {
myform <- thermo$OBIGT$formula[thermo$species$ispecies[ispecies[i]]]
#iOBIGT <- which(thermo$OBIGT$name == thermo$species$name[ispecies[k]] | thermo$OBIGT$formula == myform)
# 20080925 Don't match formula -- two proteins might have the
# same formula (e.g. YLR367W and YJL190C)
#iOBIGT <- which(thermo$OBIGT$name == thermo$species$name[ispecies[k]])
# 20091112 Do match formula if it's not a protein -- be able to
# change "carbon dioxide(g)" to "CO2(aq)"
if(length(grep("_",thermo$species$name[ispecies[i]])) > 0)
iOBIGT <- which(thermo$OBIGT$name == thermo$species$name[ispecies[i]])
else {
iOBIGT <- which(thermo$OBIGT$name == thermo$species$name[ispecies[i]] & thermo$OBIGT$state == state[i])
if(length(iOBIGT) == 0)
iOBIGT <- which(thermo$OBIGT$name == thermo$species$name[ispecies[i]] | thermo$OBIGT$formula == myform)
}
if(!state[i] %in% thermo$OBIGT$state[iOBIGT])
warning(paste("can't update state of species", ispecies[i], "to", state[i], "\n"), call. = FALSE)
else {
ii <- match(state[i], thermo$OBIGT$state[iOBIGT])
thermo$species$state[ispecies[i]] <- state[i]
thermo$species$name[ispecies[i]] <- thermo$OBIGT$name[iOBIGT[ii]]
thermo$species$ispecies[ispecies[i]] <- as.numeric(rownames(thermo$OBIGT)[iOBIGT[ii]])
}
}
}
}
assign("thermo", thermo, CHNOSZ)
# Return the new species definition or the index(es) of affected species
if(index.return) return(ispecies)
else return(thermo$species)
}
### Unexported functions ###
# To retrieve the coefficients of reactions to form the species from the basis species
species.basis <- function(species = get("thermo", CHNOSZ)$species$ispecies, mkp = NULL) {
# Current basis elements
bmat <- basis.elements()
tbmat <- t(bmat)
# What are the elements?
belem <- rownames(tbmat)
# Get the species makeup into a matrix
# If 'species' is NULL, get it from the 'mkp' argument (for use by subcrt()) 20210321
if(!is.null(species)) mkp <- as.matrix(sapply(makeup(species, count.zero = TRUE), c))
# The positions of the species elements in the basis elements
ielem <- match(rownames(mkp), belem)
# The elements of the species must be contained by the basis species
if(any(is.na(ielem))) stop(paste("element(s) not in the basis:",
paste(rownames(mkp)[is.na(ielem)], collapse = " ")))
# The positions of the basis elements in the species elements
jelem <- match(belem, rownames(mkp))
# Keep track of which ones are NA's;
# index them as one here but turn them to zero later
ina <- is.na(jelem)
jelem[ina] <- 1
# Now put the species matrix into the same order as the basis
mkp <- mkp[jelem, , drop = FALSE]
# Fill zeros for any basis element not in the species
mkp[ina, ] <- 0
# Solve for the basis coefficients and transpose
nbasis <- t(apply(mkp, 2, function(x) solve(tbmat, x)))
# Very small numbers are probably a floating point artifact
# can cause problems in situations where zeros are needed
# (manifests as issue in longex("phosphate"), where which.balance()
# identifies H2O as conserved component)
# 20140201 set digits (to R default) becuase getOption("digits") is changed in knitr
out <- zapsmall(nbasis, digits = 7)
# Add names of species and basis species
colnames(out) <- colnames(tbmat)
# Add names of species only if it was a character argument
if(all(is.character(species))) rownames(out) <- species
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/species.R
|
# CHNOSZ/stack_mosaic.R
# Function to create mosaic stack 20220617
# Adapted from vignettes/multi-metal.Rmd
# col: Colors for species1, species2, and species12
# (default of NA for col[3] means to plot species12 boundaries with color for species2)
# ...: Arguments for mosaic() (including affinity() arguments)
stack_mosaic <- function(bases, species1, species2, species12, names = NULL, col = list(4, 3, 6), col.names = list(4, 3, 6),
fill = NULL, dx = list(0, 0, 0), dy = list(0, 0, 0), srt = list(0, 0, 0), lwd = list(1, 1, 1), lty = list(1, 1, 1),
loga_aq = NULL, plot.it = TRUE, ...) {
# Default is to use semi-transparent fill for bimetallic species
if(is.null(fill)) fill <- list(NA, NA, add.alpha(col.names[3], "50"))
# Load species1 (first metal-bearing species)
isp1 <- species(species1)
# Set activities 20220722
if(!is.null(loga_aq)) {
iaq1 <- which(isp1$state == "aq")
if(length(iaq1) > 0) species(iaq1, loga_aq)
loga_aq_arg <- c(NA, loga_aq)
} else loga_aq_arg <- NULL
# Calculate affinity of species1 while speciating bases (e.g. aqueous S species)
mosaic1 <- mosaic(bases, loga_aq = loga_aq_arg, ...)
# Show predominance fields
diagram1 <- diagram(mosaic1$A.species, names = names[[1]], col = col[[1]], col.names = col.names[[1]], fill = fill[[1]],
dx = dx[[1]], dy = dy[[1]], srt = srt[[1]], lwd = lwd[[1]], lty = lty[[1]], plot.it = plot.it)
# Load species12 (bimetallic species) and species2 (second metal-bearing species)
isp2 <- species(c(species12, species2))
# Set activities 20220722
if(!is.null(loga_aq)) {
iaq2 <- which(isp2$state == "aq")
if(length(iaq2) > 0) species(iaq2, loga_aq)
}
# Speciate bases again (NULL)
# Take the predominant members of species1 (diagram1$predominant)
mosaic2 <- mosaic(list(bases, species1), stable = list(NULL, diagram1$predominant), loga_aq = loga_aq_arg, ...)
# Set colors
col <- c(rep_len(col[[3]], length(species12)), rep_len(col[[2]], length(species2)))
col.names <- c(rep_len(col.names[[3]], length(species12)), rep_len(col.names[[2]], length(species2)))
# For NULL names, use the species names
if(is.null(names[[3]])) names[[3]] <- species12
if(is.null(names[[2]])) names[[2]] <- species2
names <- c(names[[3]], names[[2]])
# Set other parameters
dx <- c(rep_len(dx[[3]], length(species12)), rep_len(dx[[2]], length(species2)))
dy <- c(rep_len(dy[[3]], length(species12)), rep_len(dy[[2]], length(species2)))
srt <- c(rep_len(srt[[3]], length(species12)), rep_len(srt[[2]], length(species2)))
lwd <- c(rep_len(lwd[[3]], length(species12)), rep_len(lwd[[2]], length(species2)))
lty <- c(rep_len(lty[[3]], length(species12)), rep_len(lty[[2]], length(species2)))
fill <- c(rep_len(fill[[3]], length(species12)), rep_len(fill[[2]], length(species2)))
diagram2 <- diagram(mosaic2$A.species, add = TRUE, names = names, col = col, col.names = col.names, fill = fill,
dx = dx, dy = dy, srt = srt, lwd = lwd, lty = lty, plot.it = plot.it)
out <- list(diagram1, diagram2)
invisible(out)
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/stack_mosaic.R
|
# CHNOSZ/subcrt.R
# Calculate standard molal thermodynamic propertes
# 20060817 jmd
## If this file is interactively sourced, the following are also needed to provide unexported functions:
#source("util.args.R")
#source("util.character.R")
#source("info.R")
#source("util.units.R")
#source("util.data.R")
#source("species.R")
#source("AD.R")
#source("nonideal.R")
#source("hkf.R")
#source("cgl.R")
subcrt <- function(species, coeff = 1, state = NULL, property = c("logK", "G", "H", "S", "V", "Cp"),
T = seq(273.15, 623.15, 25), P = "Psat", grid = NULL, convert = TRUE, exceed.Ttr = FALSE,
exceed.rhomin = FALSE, logact = NULL, autobalance = TRUE, use.polymorphs = TRUE, IS = 0) {
# Revise the call if the states are the second argument
if(!is.null(coeff[1])) {
if(is.character(coeff[1])) {
newstate <- coeff
# This is missing coeff and T in order that missing values are correctly detected further below 20230621
newargs <- list(species = species, state = newstate,
property = property, P = P, grid = grid, convert = convert,
exceed.Ttr = exceed.Ttr, exceed.rhomin = exceed.rhomin, logact = logact,
autobalance = autobalance, use.polymorphs = use.polymorphs, IS = IS)
if(!missing(state)) {
if(is.numeric(state[1])) newcoeff <- state else stop("If they are both given, one of arguments 2 and 3 should be numeric reaction coefficients")
newargs <- c(list(coeff = newcoeff), newargs)
}
if(!missing(T)) newargs <- c(list(T = T), newargs)
return(do.call(subcrt, newargs))
}
}
do.reaction <- FALSE
if(!missing(coeff)) do.reaction <- TRUE
# Species and states are made the same length
if(!is.null(state[1])) {
if(length(state) > length(species)) species <- rep(species, length.out = length(state))
if(length(species) > length(state)) state <- rep(state, length.out = length(species))
state <- state.args(state)
}
# Allowed properties
properties <- c("rho", "logK", "G", "H", "S", "Cp", "V", "kT", "E")
# Property checking
calcprop <- property
notprop <- property[!calcprop %in% properties]
if(length(notprop) == 1) stop(paste("invalid property name:", paste(notprop, collapse = " ")))
if(length(notprop) > 1) stop(paste("invalid property names:", paste(notprop, collapse = " ")))
# Length checking
if(do.reaction & length(species) != length(coeff))
stop("the length of 'coeff' must equal the number of species")
if(!is.null(logact)) {
if(length(logact) != length(species)) stop("the length of 'logact' must equal the number of species")
}
# Normalize temperature and pressure units
if(!missing(T)) {
if(convert) T <- envert(T, "K")
else if(!missing(convert) & convert) T <- envert(T, "K")
}
if(is.numeric(P[1])) {
if(convert) P <- envert(P, "bar")
}
# Warn for too high temperatures for Psat 20171110
warnings <- character()
if(identical(P, "Psat") & any(T > 647.067)) {
nover <- sum(T > 647.067)
if(nover==1) vtext <- "value" else vtext <- "values"
warnings <- c(warnings, paste0("P = 'Psat' undefined for T > Tcritical (", nover, " T ", vtext, ")"))
}
# Are we gridding?
isPsat <- FALSE
do.grid <- FALSE
if(!is.null(grid)) if(!is.logical(grid)) do.grid <- TRUE
newIS <- IS
if(do.grid) {
if(grid == "T") {
newT <- numeric()
for(i in 1:length(T)) newT <- c(newT, rep(T[i], length(P)))
newP <- rep(P, length(T))
T <- newT; P <- newP
}
if(grid == "P") {
newP <- numeric()
for(i in 1:length(P)) newP <- c(newP, rep(P[i], length(T)))
newT <- rep(T, length(P))
T <- newT; P <- newP
}
if(grid == "IS") {
ll <- length(T)
if(length(P) > 1) ll <- length(P)
newIS <- numeric()
for(i in 1:length(IS)) newIS <- c(newIS, rep(IS[i], ll))
tpargs <- TP.args(T = T, P = P)
T <- rep(tpargs$T, length.out = length(newIS))
P <- rep(tpargs$P, length.out = length(newIS))
}
} else {
# For AD, remember if P = "Psat" 20190219
if(identical(P, "Psat")) isPsat <- TRUE
# Expansion of Psat and equivalence of argument lengths
tpargs <- TP.args(T = T,P = P)
T <- tpargs$T; P <- tpargs$P
if(length(newIS) > length(T)) T <- rep(T, length.out = length(newIS))
if(length(newIS) > length(P)) P <- rep(P, length.out = length(newIS))
}
# Get species information
thermo <- get("thermo", CHNOSZ)
# Before 20110808, we sent numeric species argument through info() to get species name and state(s)
# But why slow things down if we already have a species index?
if(is.numeric(species[1])) {
ispecies <- species
species <- as.character(thermo$OBIGT$name[ispecies])
state <- as.character(thermo$OBIGT$state[ispecies])
newstate <- as.character(thermo$OBIGT$state[ispecies])
} else {
# Species are named ... look up the index
ispecies <- numeric()
newstate <- character()
for(i in 1:length(species)) {
# Get the species index for a named species
if(!can.be.numeric(species[i])) sindex <- info.character(species[i], state[i])
else {
# Check that a coerced-to-numeric argument is a rownumber of thermo()$OBIGT
sindex <- as.numeric(species[i])
if(!sindex %in% 1:nrow(thermo$OBIGT)) stop(paste(species[i], "is not a row number of thermo()$OBIGT"))
}
# info.character() has the possible side-effect of adding a protein; re-read thermo to use the (possible) additions
thermo <- get("thermo", CHNOSZ)
if(is.na(sindex[1])) stop("no info found for ", species[i], " ",state[i])
if(!is.null(state[i])) is.cr <- state[i]=="cr" else is.cr <- FALSE
# If we found multiple species, take the first one (useful for minerals with polymorphs)
if(thermo$OBIGT$state[sindex[1]] == "cr" & (is.null(state[i]) | is.cr)) {
newstate <- c(newstate, "cr")
ispecies <- c(ispecies, sindex[1])
} else {
newstate <- c(newstate, as.character(thermo$OBIGT$state[sindex[1]]))
ispecies <- c(ispecies, sindex[1])
}
}
}
# Stop if species not found
noname <- is.na(ispecies)
if(TRUE %in% noname)
stop(paste("species", species[noname], "not found.\n"))
# Take care of mineral phases
state <- as.character(thermo$OBIGT$state[ispecies])
name <- as.character(thermo$OBIGT$name[ispecies])
# A counter of all species considered
# iphases is longer than ispecies if multiple polymorphs (cr, cr2, ...) are present
# polymorph.species shows which of ispecies correspond to iphases
# Before 20091114: the success of this depends on there not being duplicated aqueous or other
# non-mineral species (i.e., two entries in OBIGT for Cu+ mess this up when running the skarn example).
# After 20091114: we can deal with duplicated species (aqueous at least)
iphases <- polymorph.species <- coeff.new <- numeric()
for(i in 1:length(ispecies)) {
# Add check for use.polymorphs argument 20230620
if(newstate[i] == "cr" & use.polymorphs) {
# Check for available polymorphs in OBIGT
polymorph.states <- c("cr", "cr2", "cr3", "cr4", "cr5", "cr6", "cr7", "cr8", "cr9")
tghs <- thermo$OBIGT[(thermo$OBIGT$name %in% name[i]) & thermo$OBIGT$state %in% polymorph.states, ]
# Only take the first one if they are duplicated non-mineral species (i.e., not polymorphs)
if(all(tghs$state == tghs$state[1])) tghs <- thermo$OBIGT[ispecies[i], ]
} else tghs <- thermo$OBIGT[ispecies[i], ]
iphases <- c(iphases, as.numeric(rownames(tghs)))
polymorph.species <- c(polymorph.species, rep(ispecies[i], nrow(tghs)))
coeff.new <- c(coeff.new, rep(coeff[i], nrow(tghs)))
}
# Where we keep info about the species involved
# Add model information 20220919
model <- thermo$OBIGT$model[iphases]
# Label specific water model;
# this is also how we record a "wet" reaction
isH2O <- model == "H2O"
isH2O[is.na(isH2O)] <- FALSE
model[isH2O] <- paste0("water.", thermo$opt$water)
reaction <- data.frame(coeff = coeff.new, name = thermo$OBIGT$name[iphases],
formula = thermo$OBIGT$formula[iphases], state = thermo$OBIGT$state[iphases],
ispecies = iphases, model = model, stringsAsFactors = FALSE)
# Make the rownames readable ... but they have to be unique
if(length(unique(iphases))==length(iphases)) rownames(reaction) <- as.character(iphases)
# Which species use models for aqueous species
# This breaks things if we have state = "aq" and model = "CGL" 20230220
#isaq <- reaction$state == "aq"
isaq <- toupper(reaction$model) %in% c("HKF", "AD", "DEW")
# Produce message about conditions
if(length(species)==1 & convert==FALSE) {
# No message produced here (internal calls from other functions)
} else {
# Include units here 20190530
uT <- outvert(T, "K")
if(identical(grid, "IS")) uT <- unique(uT)
Tunits <- T.units()
if(Tunits == "C") Tunits <- "\u00BAC"
if(length(uT) == 1) T.text <- paste(uT, Tunits) else {
T.text <- paste0(length(uT), " values of T (", Tunits, ")")
}
uP <- outvert(P, "bar")
if(length(P) == 1) {
if(can.be.numeric(P)) P.text <- paste(round(as.numeric(uP),2), P.units())
else P.text <- paste0("P (", P.units(), ")")
} else P.text <- paste0("P (", P.units(), ")")
if(identical(P[[1]], "Psat")) P.text <- P
if(any(c(isH2O, isaq))) P.text <- paste(P.text, " (wet)", sep = "")
E.text <- paste0("[energy units: ", E.units(), "]")
message(paste("subcrt:", length(species), "species at", T.text, "and", P.text, E.text))
}
# Inform about unbalanced reaction
if(do.reaction) {
# The mass balance; should be zero for a balanced reaction
mss <- makeup(ispecies, coeff, sum = TRUE)
# Take out very small numbers
mss[abs(mss) < 1e-7] <- 0
# Report and try to fix any non-zero mass balance
if(any(mss != 0)) {
# The missing composition: the negative of the mass balance
miss <- -mss
# Drop elements that are zero
miss <- miss[miss != 0]
message("subcrt: reaction is not balanced; it is missing this composition:")
# We have to do this awkward dance to send a formatted matrix to message
message(paste(capture.output(print(miss)), collapse = "\n"))
# Look for basis species that have our compositoin
tb <- thermo$basis
if(!is.null(tb) & autobalance) {
if(all(names(miss) %in% colnames(tb)[1:nrow(tb)])) {
# The missing composition in terms of the basis species
bc <- species.basis(species = NULL, mkp = as.matrix(miss))
# Drop zeroes
bc.new <- bc[, (bc[1, ] != 0), drop = FALSE]
# and get the states
b.state <- as.character(thermo$basis$state)[bc[1, ] != 0]
bc <- bc.new
# Special thing for Psat
if(identical(P[[1]], "Psat")) P <- "Psat"
else P <- outvert(P, "bar")
# Add to logact values if present
if(!is.null(logact)) {
ila <- match(colnames(bc), rownames(thermo$basis))
nla <- !(can.be.numeric(thermo$basis$logact[ila]))
if(any(nla)) warning("subcrt: logact values of basis species",
c2s(rownames(thermo$basis)[ila]), "are NA.")
logact <- c(logact, thermo$basis$logact[ila])
}
# Warn user and do it!
ispecies.new <- tb$ispecies[match(colnames(bc),rownames(tb))]
b.species <- thermo$OBIGT$formula[ispecies.new]
if(identical(species,b.species) & identical(state,b.state))
message("subcrt: balanced reaction, but it is a non-reaction; restarting...")
else message("subcrt: adding missing composition from basis definition and restarting...")
newspecies <- c(species, tb$ispecies[match(colnames(bc), rownames(tb))])
newcoeff <- c(coeff, as.numeric(bc[1, ]))
newstate <- c(state, b.state)
return(subcrt(species = newspecies, coeff = newcoeff, state = newstate,
property = property, T = outvert(T, "K"), P = P, grid = grid, convert = convert, logact = logact,
exceed.Ttr = exceed.Ttr, exceed.rhomin = exceed.rhomin, IS = IS))
} else warnings <- c(warnings, paste("reaction among", paste(species, collapse = ","), "was unbalanced, missing", as.chemical.formula(miss)))
} else warnings <- c(warnings, paste("reaction among", paste(species, collapse = ","), "was unbalanced, missing", as.chemical.formula(miss)))
}
}
# Calculate the properties
# If we want affinities we must have logK; include it in the ouput
if(!is.null(logact)) if(!"logK" %in% calcprop) calcprop <- c("logK", calcprop)
# If logK but not G was requested, we need to calculate G
eosprop <- calcprop
if("logK" %in% calcprop & ! "G" %in% calcprop) eosprop <- c(eosprop, "G")
# Also get G if we are dealing with mineral phases
if(!"G" %in% eosprop & length(iphases) > length(ispecies)) eosprop <- c(eosprop, "G")
# Don't request logK or rho from the eos ...
eosprop <- eosprop[!eosprop %in% c("logK", "rho")]
# The reaction result will go here
outprops <- list()
# Aqueous species and H2O properties
if(TRUE %in% isaq) {
# 20110808 get species parameters using OBIGT2eos()
# (this is faster than using info() and is how we get everything in the same units)
param <- OBIGT2eos(thermo$OBIGT[iphases[isaq], ], "aq", fixGHS = TRUE, toJoules = TRUE)
# Aqueous species with model = "AD" use the AD model 20210407
model <- thermo$OBIGT$model[iphases[isaq]]
model[is.na(model)] <- ""
isAD <- model == "AD"
# Always get density
H2O.props <- "rho"
# Calculate A_DH and B_DH if we're using the B-dot (Helgeson) equation
if(any(IS != 0) & thermo$opt$nonideal %in% c("Bdot", "Bdot0", "bgamma", "bgamma0")) H2O.props <- c(H2O.props, "A_DH", "B_DH")
# Get other properties for H2O only if it's in the reaction
if(any(isH2O)) H2O.props <- c(H2O.props, eosprop)
# In case everything is AD, run hkf (for water properties) but exclude all species
hkfpar <- param
if(all(isAD)) hkfpar <- param[0, ]
hkfstuff <- hkf(eosprop, parameters = hkfpar, T = T, P = P, H2O.props = H2O.props)
p.aq <- hkfstuff$aq
H2O.PT <- hkfstuff$H2O
# Set properties to NA for density below 0.35 g/cm3 (a little above the critical isochore, threshold used in SUPCRT92) 20180922
if(!exceed.rhomin & !all(isAD)) {
ilowrho <- H2O.PT$rho < 350
ilowrho[is.na(ilowrho)] <- FALSE
if(any(ilowrho)) {
for(i in 1:length(p.aq)) p.aq[[i]][ilowrho, ] <- NA
if(sum(ilowrho) == 1) ptext <- "pair" else ptext <- "pairs"
warnings <- c(warnings, paste0("below minimum density for applicability of revised HKF equations (", sum(ilowrho), " T,P ", ptext, ")"))
}
}
# Calculate properties using Akinfiev-Diamond model 20190219
if(any(isAD)) {
# get the parameters with the right names
param <- OBIGT2eos(param[isAD, ], "aq", toJoules = TRUE)
p.aq[isAD] <- AD(eosprop, parameters = param, T = T, P = P, isPsat = isPsat)
}
# Calculate activity coefficients if ionic strength is not zero
if(any(IS != 0)) {
if(thermo$opt$nonideal %in% c("Bdot", "Bdot0", "bgamma", "bgamma0")) p.aq <- nonideal(iphases[isaq], p.aq, newIS, T, P, H2O.PT$A_DH, H2O.PT$B_DH)
else if(thermo$opt$nonideal=="Alberty") p.aq <- nonideal(iphases[isaq], p.aq, newIS, T)
}
outprops <- c(outprops, p.aq)
} else if(any(isH2O)) {
# We're not using the HKF, but still want water
H2O.PT <- water(c("rho", eosprop), T = T, P = P)
}
# Crystalline, gas, or liquid (except water) species
iscgl <- reaction$model %in% c("CGL", "Berman")
if(TRUE %in% iscgl) {
param <- OBIGT2eos(thermo$OBIGT[iphases[iscgl],], "cgl", fixGHS = TRUE, toJoules = TRUE)
p.cgl <- cgl(eosprop, parameters = param, T = T, P = P)
# Replace Gibbs energies with NA where the
# phases are beyond their temperature range
if("G" %in% eosprop) {
# 20080304 This code is weird and hard to read - needs a lot of cleanup!
# 20120219 Cleaned up somewhat; using exceed.Ttr and NA instead of do.phases and 999999
# The numbers of the cgl species (becomes 0 for any that aren't cgl)
ncgl <- iscgl
ncgl[iscgl] <- 1:nrow(param)
for(i in 1:length(iscgl)) {
# Not if we're not cgl
if(!iscgl[i]) next
# Name and state
myname <- reaction$name[i]
mystate <- reaction$state[i]
# If we are considering multiple polymorphs, and if this polymorph is cr2 or higher, check if we're below the transition temperature
if(length(iphases) > length(ispecies) & i > 1) {
if(!(reaction$state[i] %in% c("liq", "cr", "gas")) & reaction$name[i-1] == reaction$name[i]) {
# After add.OBIGT("SUPCRT92"), quartz cr and cr2 are not next to each other in thermo()$OBIGT,
# so use iphases[i-1] here, not iphases[i]-1 20181107
Ttr <- Ttr(iphases[i-1], iphases[i], P = P, dPdT = dPdTtr(iphases[i-1], iphases[i]))
if(all(is.na(Ttr))) next
if(any(T <= Ttr)) {
status.Ttr <- "(extrapolating G)"
if(!exceed.Ttr) {
# put NA into the value of G
p.cgl[[ncgl[i]]]$G[T <= Ttr] <- NA
status.Ttr <- "(using NA for G)"
}
#message(paste("subcrt: some points below transition temperature for", myname, mystate, status.Ttr))
}
}
}
# Check for a polymorphic transition
is.polymorphic.transition <- FALSE
Ttr <- thermo$OBIGT$z.T[iphases[i]]
if(i < nrow(reaction)) {
# If the next one is cr2, cr3, etc we have a polymorphic transition
if(reaction$state[i+1] %in% c("cr1", "cr2", "cr3", "cr4", "cr5", "cr6", "cr7", "cr8", "cr9") & reaction$name[i+1] == reaction$name[i]) {
# Calculate Ttr at higher P for a polymorphic transition
Ttr <- Ttr(iphases[i], iphases[i+1], P = P, dPdT = dPdTtr(iphases[i], iphases[i+1]))
# Put in NA for G
p.cgl[[ncgl[i]]]$G[T > Ttr] <- NA
is.polymorphic.transition <- TRUE
}
}
if(!is.polymorphic.transition) {
# Check if we're above the T limit for a Cp equation or T for phase change (e.g. melting or vaporization) listed in OBIGT
is.Cp.equation <- FALSE
if(all(is.na(Ttr))) next
if(all(Ttr == 0)) next
ineg <- Ttr < 0
if(any(ineg)) {
# This is the T limit for a Cp equation (not a phase change)
Ttr[ineg] <- -Ttr[ineg]
is.Cp.equation <- TRUE
}
if(any(T > Ttr)) {
if(!exceed.Ttr) {
if(is.Cp.equation) {
warning(paste0("above T limit of ", Ttr, " K for the Cp equation for ", myname, "(", mystate, ")"))
} else {
message(paste0("subcrt: G is set to NA for ", myname, "(", mystate, ") above its stability limit of ", Ttr, " K (use exceed.Ttr = TRUE to output G)"))
p.cgl[[ncgl[i]]]$G[T > Ttr] <- NA
}
} else {
message(paste0("subcrt: showing G for ", myname, "(", mystate, ") above its stability limit of ", Ttr, " K (use exceed.Ttr = FALSE to prevent this)"))
}
}
}
# Use variable-pressure standard Gibbs energy for gases if varP is TRUE (not the default)
if(mystate == "gas" & thermo$opt$varP) p.cgl[[ncgl[i]]]$G <- p.cgl[[ncgl[i]]]$G - convert(log10(P), "G", T = T)
}
}
outprops <- c(outprops,p.cgl)
}
# Water
if(any(isH2O)) {
p.H2O <- H2O.PT[, match(eosprop, colnames(H2O.PT)), drop = FALSE]
p.H2O <- list(p.H2O)
outprops <- c(outprops, rep(p.H2O, sum(isH2O == TRUE)))
}
# logK
if("logK" %in% calcprop) {
for(i in 1:length(outprops)) {
outprops[[i]] <- cbind(outprops[[i]],data.frame(logK = convert(outprops[[i]]$G, "logK", T = T)))
colnames(outprops[[i]][ncol(outprops[[i]])]) <- "logK"
}
}
# Ordering the output
# The indices of the species in outprops thus far
ns <- 1:nrow(reaction)
is <- c(ns[isaq],ns[iscgl],ns[isH2O])
if(length(ns) != length(is)) stop("subcrt: not all species are accounted for.")
v <- list()
for(i in 1:length(is)) v[[i]] <- outprops[[match(ns[i], is)]]
outprops <- v
# Deal with polymorphs (cr,cr2) here:
# We have to eliminate rows from outprops,
# reaction and values from isaq, iscgl, isH2O
out.new <- list()
reaction.new <- reaction
isaq.new <- logical()
iscgl.new <- logical()
isH2O.new <- logical()
for(i in 1:length(ispecies)) {
are.polymorphs <- which(ispecies[i] == polymorph.species)
# Deal with repeated species here
if(TRUE %in% duplicated(iphases[are.polymorphs])) {
# Only take the first, not the duplicates
ndups <- sum(ispecies == ispecies[i])
npolymorphs <- length(are.polymorphs) / ndups
are.polymorphs <- are.polymorphs[1:npolymorphs]
}
if(length(are.polymorphs) > 1) {
message(paste("subcrt:", length(are.polymorphs), "polymorphs for", thermo$OBIGT$name[ispecies[i]], "... "), appendLF = FALSE)
# Assemble the Gibbs energies for each species
for(j in 1:length(are.polymorphs)) {
G.this <- outprops[[are.polymorphs[j]]]$G
# if(sum(is.na(G.this)) > 0 & exceed.Ttr) warning(paste("subcrt: NAs found for G of ",
# reaction$name[are.polymorphs[j]], " ", reaction$state[are.polymorphs[j]], " at T-P point(s) ",
# c2s(which(is.na(G.this)), sep = " "), sep = ""), call. = FALSE)
if(j == 1) G <- as.data.frame(G.this)
else G <- cbind(G, as.data.frame(G.this))
}
# Find the minimum-energy polymorph at each T-P point
stable.polymorph <- numeric()
out.new.entry <- outprops[[are.polymorphs[1]]]
for(j in 1:nrow(G)) {
ps <- which.min(as.numeric(G[j, ]))
if(length(ps) == 0) {
# minimum not found (we have NAs)
# - no non-NA value of G to begin with (e.g. aegerine) --> probably should use lowest-T phase
#ps <- 1
# - above temperature limit for the highest-T phase (subcrt.Rd skarn example) --> use highest-T phase 20171110
ps <- ncol(G)
if(exceed.Ttr) warning("subcrt: stable polymorph for ", reaction$name[are.polymorphs[ps]], " at T-P point ", j,
" undetermined (using ", reaction$state[are.polymorphs[ps]], ")", call. = FALSE)
}
stable.polymorph <- c(stable.polymorph, ps)
out.new.entry[j, ] <- outprops[[ are.polymorphs[ps] ]][j, ]
}
# Update our objects
out.new[[i]] <- cbind(out.new.entry, data.frame(polymorph = stable.polymorph))
reaction.new[i, ] <- reaction[are.polymorphs[stable.polymorph[1]], ]
# Mark the minerals with multiple polymorphs
reaction.new$state[i] <- "cr*"
isaq.new <- c(isaq.new, isaq[are.polymorphs[stable.polymorph[1]]])
iscgl.new <- c(iscgl.new, iscgl[are.polymorphs[stable.polymorph[1]]])
isH2O.new <- c(isH2O.new, isH2O[are.polymorphs[stable.polymorph[1]]])
# Info for the user
up <- unique(stable.polymorph)
if(length(up) > 1) { word <- "are"; p.word <- "polymorphs" }
else { word <- "is"; p.word <- "polymorph" }
message(paste(p.word, paste(unique(stable.polymorph), collapse = ","), word, "stable"))
} else {
# Multiple polymorphs aren't involved ... things stay the same
out.new[[i]] <- outprops[[are.polymorphs]]
reaction.new[i, ] <- reaction[are.polymorphs, ]
reaction.new$state[i] <- reaction$state[are.polymorphs]
isaq.new <- c(isaq.new, isaq[are.polymorphs])
iscgl.new <- c(iscgl.new, iscgl[are.polymorphs])
isH2O.new <- c(isH2O.new, isH2O[are.polymorphs])
}
}
outprops <- out.new
# Remove the rows that were added to keep track of polymorphs
reaction <- reaction.new[1:length(ispecies), ]
# The manipulations above should get the correct species indices and state labels,
# but if species are (intentionally) repeated, include only the first
# (and possibly incorrect) reaction coefficients, so use the originals here 20180822
reaction$coeff <- coeff
isaq <- isaq.new
iscgl <- iscgl.new
isH2O <- isH2O.new
# Adjust the output order of the properties
for(i in 1:length(outprops)) {
# the calculated properties are first
ipp <- match(calcprop, colnames(outprops[[i]]))
# move polymorph/loggam columns to end
if("polymorph" %in% colnames(outprops[[i]])) ipp <- c(ipp, match("polymorph", colnames(outprops[[i]])))
if("loggam" %in% colnames(outprops[[i]])) ipp <- c(ipp, match("loggam", colnames(outprops[[i]])))
outprops[[i]] <- outprops[[i]][, ipp, drop = FALSE]
}
# Add up reaction properties
if(do.reaction) {
o <- 0
morphcols <- NULL
# do our affinity calculations here
if(!is.null(logact)) {
logQ <- logK <- rep(0, length(T))
for(i in 1:length(coeff)) {
logK <- logK + outprops[[i]]$logK * coeff[i]
logQ <- logQ + logact[i] * coeff[i]
}
reaction <- cbind(reaction, logact)
A <- logK - logQ
# convert A/2.303RT (dimensionless) to J mol-1
# then outvert to the user's units from J mol-1
A <- outvert(convert(-A, "G", T = T), "J")
}
# Loop over reaction coefficients
for(i in 1:length(coeff)) {
# Assemble polymorph columns separately
if("polymorph" %in% colnames(outprops[[i]])) {
sc <- as.data.frame(outprops[[i]]$polymorph)
outprops[[i]] <- outprops[[i]][, -match("polymorph", colnames(outprops[[i]]))]
colnames(sc) <- as.character(reaction$name[i])
if(is.null(morphcols)) morphcols <- sc
else morphcols <- cbind(morphcols, sc)
}
# Include a zero loggam column if needed (for those species that are ideal)
o.i <- outprops[[i]]
if("loggam" %in% colnames(o.i)) if(!"loggam" %in% colnames(o))
o <- cbind(o, loggam = 0)
if("loggam" %in% colnames(o)) if(!"loggam" %in% colnames(o.i))
o.i <- cbind(o.i, loggam = 0)
# the real addition of properties
o <- o + o.i * coeff[i]
}
# Output for reaction (stack on polymorph columns if exist)
if(!is.null(morphcols)) OUT <- list(reaction = reaction,out = o,polymorphs = morphcols)
else OUT <- list(reaction = reaction,out = o)
} else {
# Output for species: strip the coeff column from reaction
reaction <- reaction[,-match("coeff",colnames(reaction))]
OUT <- c(list(species = reaction),outprops)
}
# Append T, P, rho, A, logQ columns and convert units
for(i in 2:length(OUT)) {
# affinity and logQ
if(i==2) if(do.reaction & !is.null(logact)) {
OUT[[i]] <- cbind(OUT[[i]], data.frame(logQ = logQ, A = A))
}
# 20120114 Only prepend T, P, rho columns if we have more than one T
# 20171020 or if the "property" argument is missing (it's nice to see everything using e.g. subcrt("H2O", T = 150))
# 20171021 or if the "property" argument is not missing, but is identical to the default (happens when auto-balancing reactions)
if(length(T) > 1 | missing(property) | identical(property, c("logK", "G", "H", "S", "V", "Cp"))) {
# 20090329 Added checks for converting T, P units
if(convert) T.out <- outvert(T, "K") else T.out <- T
if(convert) P.out <- outvert(P, "bar") else P.out <- P
# Try to stuff in a column of rho if we have aqueous species
# watch out! supcrt-ish densities are in g/cc not kg/m3
if("rho" %in% calcprop | ( (missing(property) | identical(property, c("logK", "G", "H", "S", "V", "Cp"))) &
any(c(isaq, isH2O))) & (names(OUT)[i]) != "polymorph")
OUT[[i]] <- cbind(data.frame(T = T.out, P = P.out, rho = H2O.PT$rho/1000), OUT[[i]])
else
OUT[[i]] <- cbind(data.frame(T = T.out, P = P.out, OUT[[i]]))
}
}
# Put ionic strength next to any loggam columns
for(i in 2:length(OUT)) {
if("loggam" %in% colnames(OUT[[i]])) OUT[[i]] <- cbind(OUT[[i]], IS = newIS)
}
# More fanagling for species
if(!do.reaction) {
OUT <- list(species = OUT$species, out = OUT[2:length(OUT)])
# add names to the output
names(OUT$out) <- as.character(reaction$name)
}
# Rewritten code to convert energy units 20220325
if(convert) {
if(do.reaction) {
isenergy <- colnames(OUT$out) %in% c("G", "H", "S", "Cp")
if(any(isenergy)) OUT$out[, isenergy] <- outvert(OUT$out[, isenergy], "J")
} else {
isenergy <- colnames(OUT$out[[1]]) %in% c("G", "H", "S", "Cp")
if(any(isenergy)) {
for(i in 1:length(OUT$out)) OUT$out[[i]][, isenergy] <- outvert(OUT$out[[i]][, isenergy], "J")
}
}
}
# Add warnings to output 20180922
if(length(warnings) > 0) {
OUT <- c(OUT, list(warnings = warnings))
for(warn in warnings) warning(warn)
}
return(OUT)
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/subcrt.R
|
# CHNOSZ/swap.basis.R
# Functions related to swapping basis species
# Extracted from basis() 20120114 jmd
## If this file is interactively sourced, the following are also needed to provide unexported functions:
#source("basis.R")
# Return the current basis elements
basis.elements <- function(basis = thermo()$basis) {
if(is.null(basis)) stop("basis species are not defined")
return(as.matrix(basis[, 1:nrow(basis), drop=FALSE]))
}
# Calculate chemical potentials of elements from logarithms of activity of basis species
element.mu <- function(basis = thermo()$basis, T = 25) {
# Matrix part of the basis definition
basis.mat <- basis.elements(basis)
# The standard Gibbs energies of the basis species
# Don't take it from thermo()$OBIGT, even at 25 degC, because G for H2O is NA there
# the sapply(..., "[", 1) is needed to get the first value, in case subcrt appends a polymorph column (i.e. for S(cr)) 20171105
TK <- convert(T, "K")
G <- unlist(sapply(subcrt(basis$ispecies, T = TK, property="G", convert = FALSE)$out, "[", 1))
# Chemical potentials of the basis species
species.mu <- G - convert(basis$logact, "G", T = TK)
# Chemical potentials of the elements
element.mu <- solve(basis.mat, species.mu)
# Give them useful names
names(element.mu) <- colnames(basis.mat)
return(element.mu)
}
# Calculate logarithms of activity of basis species from chemical potentials of elements
basis.logact <- function(emu, basis = thermo()$basis, T = 25) {
# Matrix part of the basis definition
basis.mat <- basis.elements(basis)
# Elements in emu can't be less than the number in the basis
if(length(emu) < ncol(basis.mat)) stop("number of elements in 'emu' is less than those in basis")
# Sort names of emu in order of those in basis.mat
ielem <- match(names(emu), colnames(basis.mat))
# Check that elements of basis.mat and emu are identical
if(any(is.na(ielem))) stop(paste("element(s)", paste(names(emu)[is.na(ielem)], collapse = " "), "not found in basis"))
# The standard Gibbs energies of the basis species
# Don't take it from thermo()$OBIGT, even at 25 degC, because G for H2O is NA there
# The sapply(..., "[", 1) is needed to get the first value, in case subcrt appends a polymorph column (i.e. for S(cr)) 20171105
TK <- convert(T, "K")
G <- unlist(sapply(subcrt(basis$ispecies, T = TK, property = "G", convert = FALSE)$out, "[", 1))
# The chemical potentials of the basis species in equilibrium
# with the chemical potentials of the elements
basis.mu <- colSums((t(basis.mat)*emu)) - G
# Convert chemical potentials to logarithms of activity
basis.logact <- -convert(basis.mu, "logK", T = TK)
# Give them useful names
names(basis.logact) <- rownames(basis.mat)
return(basis.logact)
}
ibasis <- function(species) {
# Get the index of a basis species from a species index, name or formula
basis <- basis()
if(is.numeric(species)) ib <- match(species, basis$ispecies)
else {
# Character: first look for formula of basis species
ib <- match(species, rownames(basis))
# If that doesn't work, look for name of basis species
if(is.na(ib)) ib <- match(species, get("thermo", CHNOSZ)$OBIGT$name[basis$ispecies])
}
return(ib)
}
# Swap in one basis species for another
swap.basis <- function(species, species2, T = 25) {
# Before we do anything, remember the old basis and species definitions
oldbasis <- get("thermo", CHNOSZ)$basis
ts <- species()
if(is.null(oldbasis))
stop("swapping basis species requires an existing basis definition")
# Both arguments must have length 1
if(missing(species) | missing(species2))
stop("two species must be identified")
if(length(species) > 1 | length(species2) > 2)
stop("can only swap one species for one species")
# Replace pH with H+ and pe and Eh with e- 20170205
if(species == "pH") species <- "H+"
if(species %in% c("Eh", "pe")) species <- "e-"
if(species2 == "pH") species2 <- "H+"
if(species2 %in% c("Eh", "pe")) species2 <- "e-"
# Arguments are good, now find the basis species to swap out
ib <- ibasis(species)
if(is.na(ib)) stop(paste("basis species '",species,"' is not defined",sep = ""))
# Find species2 in the thermodynamic database
if(is.numeric(species2)) ispecies2 <- species2
else ispecies2 <- suppressMessages(info(species2))
if(is.na(ispecies2) | is.list(ispecies2))
stop(paste("a species matching '",species2,"' is not available in thermo()$OBIGT",sep = ""))
# Try to load the new basis species
ispecies <- oldbasis$ispecies
ispecies[ib] <- ispecies2
newbasis <- put.basis(ispecies)$basis
# Now deal with the activities
if(!all(can.be.numeric(oldbasis$logact))) {
# If there are any buffers, just set the old activities
bl <- oldbasis$logact
} else {
# No buffers, so we can recalculate activities to maintain the chemical potentials of the elements
# What were the original chemical potentials of the elements?
emu <- element.mu(oldbasis, T = T)
# The corresponding logarithms of activities of the new basis species
bl <- basis.logact(emu, newbasis, T = T)
}
# Update the basis with these logacts
mb <- mod.basis(ispecies, state = newbasis$state, logact = bl)
# Delete, then restore species if they were defined
species(delete = TRUE)
if(!is.null(ts)) {
suppressMessages(species(ts$ispecies))
suppressMessages(species(1:nrow(get("thermo", CHNOSZ)$species), ts$logact))
}
# All done, return the new basis definition
return(mb)
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/swap.basis.R
|
# CHNOSZ/taxonomy.R
# Functions to work with NCBI taxonomy files
# 20100311 jmd
# 20100613 getnames and getnodes now only use the 'scan' function
# to read files (instead of 'read.table')
## Read the entire taxonomy nodes file
getnodes <- function(taxdir) {
# We only read the first five tab-separated fields
n <- scan(paste(taxdir, "nodes.dmp", sep = "/"), what = as.list(character(5)),
quote = "", flush = TRUE, sep = "\t")
# The information we want is in fields 1, 3 and 5
# (fields 2 and 4 contain the vertical bar)
id <- as.numeric(n[[1]])
parent <- as.numeric(n[[3]])
rank <- n[[5]]
nodes <- data.frame(id, parent, rank)
return(nodes)
}
## Get the taxonomic rank of the selected node
getrank <- function(id, taxdir, nodes = NULL) {
if(is.null(nodes)) nodes <- getnodes(taxdir)
return(as.character(nodes$rank[match(id, nodes$id)]))
}
# Get the parent id of the selected node
# or higher ranking ancestor if specified
parent <- function(id, taxdir, rank = NULL, nodes = NULL) {
if(is.null(nodes)) nodes <- getnodes(taxdir)
id.out <- numeric()
for(i in 1:length(id)) {
myid <- id[i]
if(is.null(rank)) {
# The immediate parent
id.out <- c(id.out, nodes$parent[nodes$id == myid])
} else {
# Parent, grandparent, etc.
myrank <- getrank(myid, taxdir, nodes)
if(is.na(myrank)) myid <- NA
else while(myrank != rank) {
myid <- parent(myid, taxdir, nodes = nodes)
myrank <- getrank(myid, taxdir, nodes)
if(myid == 1) break
}
id.out <- c(id.out, myid)
}
}
return(id.out)
}
## Get the ids of all of the parents of the selected node
allparents <- function(id, taxdir, nodes = NULL) {
if(is.null(nodes)) nodes <- getnodes(taxdir)
thisid <- id
while(thisid != 1) {
thisid <- parent(thisid, taxdir = taxdir, nodes = nodes)
id <- c(id, thisid)
}
return(id)
}
## Read the entire taxonomy names file
getnames <- function(taxdir) {
n <- scan(paste(taxdir, "names.dmp", sep = "/"),
what = as.list(character(7)), flush = TRUE, quote = "", sep = "\t")
id <- as.numeric(n[[1]])
name <- n[[3]]
type <- n[[7]]
names <- data.frame(id, name, type)
return(names)
}
## Get the scientific name(s) of the selected node(s)
sciname <- function(id, taxdir, names = NULL) {
if(is.null(names)) names <- getnames(taxdir)
# We're only interested in the scientific names
isci <- which(names$type == "scientific name")
names <- names[isci, ]
# Now identify the entries of interest
names <- names[match(id, names$id), ]
n <- as.character(names$name)
if(length(id) == 1) n <- s2c(n, sep = "\t")[1]
return(n)
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/taxonomy.R
|
# CHNOSZ/data/thermo.R
# Create or restore, and access the 'thermo' data object
# 20190213: Move from data/thermo.R to R/thermo.R
# --> invocation changes from data(thermo) to reset()
# --> invocation changes from data(OBIGT) to OBIGT()
reset <- function() {
# Create thermo list
thermodir <- system.file("extdata/thermo/", package = "CHNOSZ")
thermo <- list(
# Use as.is = TRUE to keep character values as character and not factor
opt = as.list(read.csv(file.path(thermodir, "opt.csv"), as.is = TRUE)),
element = read.csv(file.path(thermodir, "element.csv"), as.is = 1:3),
OBIGT = NULL,
refs = NULL,
Berman = NULL,
buffer = read.csv(file.path(thermodir, "buffer.csv"), as.is = 1:3),
protein = read.csv(file.path(thermodir, "protein.csv"), as.is = 1:4),
groups = read.csv(file.path(thermodir, "groups.csv"), row.names = 1, check.names = FALSE),
stoich = read.csv(file.path(thermodir, "stoich.csv.xz"), as.is = TRUE),
Bdot_acirc = read.csv(file.path(thermodir, "Bdot_acirc.csv"), as.is = TRUE),
basis = NULL,
species = NULL,
opar = NULL
)
# Store stoich as matrix (with non-unique row names), not data frame
formula <- thermo$stoich[, 1]
thermo$stoich <- as.matrix(thermo$stoich[, 2:ncol(thermo$stoich)])
rownames(thermo$stoich) <- formula
# Make a named numeric vector for Bdot_acirc 20230309
Bdot_acirc <- thermo$Bdot_acirc[, "acirc"]
names(Bdot_acirc) <- thermo$Bdot_acirc[, "species"]
thermo$Bdot_acirc <- Bdot_acirc
# Get parameters in Berman equations from data files 20220203
path <- system.file("extdata/Berman/", package = "CHNOSZ")
files <- dir(path, "\\.csv$")
# Put files in reverse chronological order (youngest first)
files <- rev(files[order(sapply(strsplit(files, "_"), "[", 2))])
# Read the parameters from each file
Berman <- list()
for(i in 1:length(files)) Berman[[i]] <- read.csv(file.path(path, files[i]), as.is = TRUE)
# Assemble the parameters in a single data frame
thermo$Berman <- do.call(rbind, Berman)
# Message about what we are doing
if(!"thermo" %in% ls(CHNOSZ)) packageStartupMessage("reset: creating \"thermo\" object")
else packageStartupMessage("reset: resetting \"thermo\" object")
# Place thermo in CHNOSZ environment
assign("thermo", thermo, CHNOSZ)
# Run OBIGT() to add the thermodynamic data
OBIGT()
}
# Load default thermodynamic data (OBIGT) in thermo
OBIGT <- function(no.organics = FALSE) {
# We only work if thermo is already in the CHNOSZ environment
if(!"thermo" %in% ls(CHNOSZ)) stop("The CHNOSZ environment doesn't have a \"thermo\" object. Try running reset()")
# Identify OBIGT data files
sources_aq <- paste0(c("H2O", "inorganic", "organic"), "_aq")
sources_cr <- paste0(c("Berman", "inorganic", "organic"), "_cr")
sources_liq <- paste0(c("organic"), "_liq")
sources_gas <- paste0(c("inorganic", "organic"), "_gas")
sources <- c(sources_aq, sources_cr, sources_gas, sources_liq)
OBIGTdir <- system.file("extdata/OBIGT/", package = "CHNOSZ")
# Read data from each file
datalist <- lapply(sources, function(source) {
# Need explicit "/" for Windows
file <- paste0(OBIGTdir, "/", source, ".csv")
dat <- read.csv(file, as.is = TRUE)
# Include CH4 with no.organics = TRUE 20220411
if(no.organics & grepl("^organic", source)) dat <- subset(dat, formula == "CH4")
dat
})
# Create OBIGT data frame
OBIGT <- do.call(rbind, datalist)
# Also read references file
refs <- read.csv(file.path(OBIGTdir, "refs.csv"), as.is = TRUE)
# Get thermo from CHNOSZ environment
thermo <- get("thermo", CHNOSZ)
# Set OBIGT and refs
thermo$OBIGT <- OBIGT
thermo$refs <- refs
# Place modified thermo in CHNOSZ environment
assign("thermo", thermo, CHNOSZ)
# Message with brief summary of the data
packageStartupMessage(paste("OBIGT: loading", ifelse(no.organics, "inorganic", "default"), "database with",
nrow(thermo$OBIGT[thermo$OBIGT$state == "aq",]),
"aqueous,", nrow(thermo$OBIGT), "total species"))
# Warn if there are duplicated species
idup <- duplicated(paste(thermo$OBIGT$name, thermo$OBIGT$state))
if(any(idup)) warning("OBIGT: duplicated species: ",
paste(thermo$OBIGT$name[idup], "(", thermo$OBIGT$state[idup], ")", sep = "", collapse = " "))
}
# A function to access or modify the thermo object 20190214
# Revised for argument handling more like par() 20230310
thermo <- function (...) {
# Get the arguments
args <- list(...)
# This part is taken from graphics::par()
# To handle only names in c(), e.g. thermo(c("basis", "species"))
if (all(unlist(lapply(args, is.character))))
args <- as.list(unlist(args))
# # To handle an argument analogous to old.par in the example for ?par
# # ... but it breaks the "Adding an element" example in ?thermo
# if (length(args) == 1) {
# if (is.list(args[[1L]]) || is.null(args[[1L]]))
# args <- args[[1L]]
# }
# Get the name of the arguments
argnames <- names(args)
# Use "" for the name of each unnamed argument
if(is.null(argnames)) argnames <- character(length(args))
# Get the current 'thermo' object
value <- original <- thermo <- get("thermo", CHNOSZ)
# Loop over arguments
if(length(args) > 0) {
# Start with an empty return value with the right length
value <- vector("list", length(args))
for(i in 1:length(argnames)) {
if(argnames[i] == "") {
# For an unnnamed argument, retrieve the parameter from thermo
# Parse the argument value to get the slots
slots <- strsplit(args[[i]], "$", fixed = TRUE)[[1]]
names <- args[[i]]
} else {
# For a named argument, assign the parameter in thermo
# Parse the name of the argument to get the slots
slots <- strsplit(argnames[i], "$", fixed = TRUE)[[1]]
names <- argnames[i]
# Perform the assignment in the local 'thermo' object
if(length(slots) == 1) thermo[[slots[1]]] <- args[[i]]
if(length(slots) == 2) thermo[[slots[1]]][[slots[2]]] <- args[[i]]
}
# Get the (original) parameter value
if(length(slots) == 1) orig <- original[[slots[1]]]
if(length(slots) == 2) orig <- original[[slots[1]]][[slots[2]]]
# Put the parameter into the output value
if(!is.null(orig)) value[[i]] <- orig
names(value)[i] <- names
}
# Finally perform the assignment to 'thermo' in the CHNOSZ environment
assign("thermo", thermo, CHNOSZ)
}
# Don't encapsulate a single unassigned parameter in a list
if(is.null(names(args)) & length(value) == 1) value <- value[[1]]
# Return the value
value
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/thermo.R
|
# CHNOSZ/util-affinity.R
# Helper functions for affinity()
## If this file is interactively sourced, the following are also needed to provide unexported functions:
#source("util.units.R")
slice.affinity <- function(affinity, d = 1, i = 1) {
# Take a slice of affinity along one dimension
a <- affinity
for(j in 1:length(a$values)) {
# Preserve the dimensions (especially: names(mydim))
# - fix for change in behavior of aperm in R-devel 2015-11-17
mydim <- dim(a$values[[j]])
a$values[[j]] <- as.array(slice(a$values[[j]], d = d, i = i))
# The dimension from which we take the slice vanishes
dim(a$values[[j]]) <- mydim[-d]
}
return(a)
}
### Unexported functions ###
energy <- function(what, vars, vals, lims, T = 298.15, P = "Psat", IS = 0, sout = NULL, exceed.Ttr = FALSE, exceed.rhomin = FALSE, transect = FALSE) {
# 20090329 Dxtracted from affinity() and made to
# deal with >2 dimensions (variables)
# Calculate "what" property
# logK - logK of formation reactions
# logact.basis - logarithms of activities of basis species in reactions
# logact.species - logarithms of activities of species in reactions
# logQ - logQ of formation reactions
# A - A/2.303RT of formation reactions
# "vars": vector of variables (T, P, basisnames, IS)
# "vals": list of values for each variable
# "lims": used to get the dimensions (resolution for each variable)
### Some argument checking
if(length(unique(vars)) != length(vars)) stop("please supply unique variable names")
## Basis definition / number of basis species
mybasis <- basis()
nbasis <- nrow(mybasis)
## Species definition / number of species
myspecies <- get("thermo", CHNOSZ)$species
if(is.character(what)) {
if(is.null(myspecies)) stop('species properties requested, but species have not been defined')
nspecies <- nrow(myspecies)
if(!identical(what, "logact.basis")) ispecies <- 1:nspecies
}
## The dimensions of our arrays
resfun <- function(lim) lim[3]
mydim <- sapply(lims, resfun)
if(transect) {
if(!isTRUE(all.equal(min(mydim), max(mydim)))) stop("variables define a transect but their lengths are not all equal")
mydim <- mydim[[1]]
}
## The number of dimensions we have
if(transect) nd <- 1 else nd <- length(vars) # == length(mydim)
## Basis names / which vars denote basis species
basisnames <- rownames(mybasis)
ibasisvar <- match(vars, basisnames)
varisbasis <- !is.na(ibasisvar)
ibasisvar <- ibasisvar[!is.na(ibasisvar)]
## Which vars are in P, T, IS
varissubcrt <- vars %in% c("P", "T", "IS")
if(sum(varissubcrt) > 2) stop("only up to 2 of P,T,IS are supported")
## Categorize the basis species:
# 0 - not in the vars; 1 - one of the vars
ibasis <- 1:nbasis
ibasis0 <- ibasis[!ibasis %in% ibasisvar]
ibasis1 <- ibasis[ibasis %in% ibasisvar]
if(identical(what, "logact.basis")) ispecies <- ibasis
## What subcrt variable is used to make a 2-D grid?
workaround.IS <- FALSE
if(sum(varissubcrt) > 1 & !transect) {
grid <- vars[varissubcrt][1]
if("IS" %in% vars) {
if(grid != "IS") workaround.IS <- TRUE
grid <- "IS"
}
} else grid <- NULL
### Done argument processing
### Function to index the variables in a permuted order
# by swapping ivar for the first
# e.g. for nd = 5, ivars(4) = c(4, 2, 3, 1, 5)
ivars <- function(ivar, iv = NULL) {
if(nd == 0) return(1)
if(is.null(iv)) iv <- 1:nd
iv.1 <- iv[1]
iv[1] <- ivar
iv[ivar] <- iv.1
return(iv)
}
### Functions for logact / logQ
# A basis species not in var
logact.basis0.fun <- function(ibasis) {
logact <- mybasis$logact[ibasis]
# for the case where this basis species is buffered
if(!can.be.numeric(logact)) logact <- 0
else logact <- as.numeric(logact)
return(array(logact, mydim))
}
# A basis species in var
logact.basis1.fun <- function(ivar) {
dim.in <- dim(vals[[ivar]])
if(is.null(dim.in)) dim.in <- 0
# why doesn't this work?
# if(identical(dim.in, mydim))
if(all(dim.in == mydim) | transect) return(vals[[ivar]])
else return(aperm(array(vals[[ivar]], mydim[ivars(ivar)]), ivars(ivar)))
}
# Any basis species
logact.basis.fun <- function(ibasis) {
if(ibasis %in% ibasis0) return(logact.basis0.fun(ibasis))
else return(logact.basis1.fun(match(basisnames[ibasis], vars)))
}
# All basis species
logact.basis <- function() lapply(ibasis, logact.basis.fun)
# logact of a single species
logact.species.fun <- function(ispecies) array(myspecies$logact[ispecies], mydim)
## Contributions to logQ
# From a single basis species
logQ.basis.fun <- function(ibasis, coeff) - coeff * logact.basis.fun(ibasis)
# From all basis species in a single formation reaction
logQ.basis.species <- function(ispecies)
Reduce("+", mapply(logQ.basis.fun, ibasis, myspecies[ispecies, 1:nbasis], SIMPLIFY = FALSE))
# All basis species in all reactions
logQ.basis <- function() mapply(logQ.basis.species, 1:nspecies, SIMPLIFY = FALSE)
# By a single species
logQ.species.fun <- function(ispecies, coeff) coeff * logact.species.fun(ispecies)
# By all species
logQ.species <- function()
mapply(logQ.species.fun, 1:nspecies, 1, SIMPLIFY = FALSE)
# Total logQ of all reactions
logQ <- function() lsum(logQ.basis(), logQ.species())
### Function for calling subcrt
sout.fun <- function(property = "logK") {
species <- c(mybasis$ispecies, myspecies$ispecies)
if(!is.null(sout)) {
# Extract the needed species from a provided sout 20190131
isout <- match(species, sout$species$ispecies)
this.sout <- sout
this.sout$species <- this.sout$species[isout, ]
this.sout$out <- this.sout$out[isout]
return(this.sout)
} else {
## subcrt arguments
if("T" %in% vars) T <- vals[[which(vars == "T")]]
if("P" %in% vars) P <- vals[[which(vars == "P")]]
if("IS" %in% vars) IS <- vals[[which(vars == "IS")]]
s.args <- list(species = species, property = property, T = T, P = P, IS = IS, grid = grid,
convert = FALSE, exceed.Ttr = exceed.Ttr, exceed.rhomin = exceed.rhomin)
sout <- do.call("subcrt", s.args)
# 20191210 workaround a limitation in subcrt(): only IS (if present) can be the 'grid' variable
if(workaround.IS) {
lenIS <- length(IS)
# Only T or P has length > 1
lenTP <- max(length(T), length(P))
# Make an indexing matrix "byrow" then vectorize it (not byrow) to get permutation indices
indmat <- matrix(1:(lenIS * lenTP), nrow = lenIS, byrow = TRUE)
ind <- as.vector(indmat)
sout$out <- lapply(sout$out, function(x) x[indmat, ])
}
# Species indices are updated by subcrt() for minerals with polymorphic transitions
# e.g. i <- info("chalcocite"); subcrt(i, T = 200)$species$ispecies == i + 1
# so we should keep the original species index to be able to find the species in a provided 'sout'
# (noted for Mosaic diagram section of anintro.Rmd 20190203)
sout$species$ispecies <- species
return(sout)
}
}
### Functions for logK/subcrt props
# The logK contribution by any species or basis species
X.species <- function(ispecies, coeff, X) coeff * sout$out[[ispecies]][, names(sout$out[[ispecies]]) == X]
# The logK contribution by all basis species in a reaction
X.basis <- function(ispecies, X) Reduce("+", mapply(X.species, ibasis, -myspecies[ispecies, ibasis], X, SIMPLIFY = FALSE))
# The logK of any reaction
X.reaction <- function(ispecies, X) X.species((ispecies+nbasis), 1, X) + X.basis(ispecies, X)
# To get logK or subcrt props or other values into the dimensions we are using
dim.fun <- function(x, idim = NULL) {
if(is.null(idim)) {
if(transect) idim <- 1
else if(is.null(grid)) {
# One of T, P, IS
ivar <- which(vars %in% c("T", "P", "IS"))
if(length(ivar) == 0) ivar <- 1
idim <- ivars(ivar)
} else {
# Two of T, P, IS
ivar1 <- which(varissubcrt)[1]
ivar2 <- which(varissubcrt)[2]
idim <- ivars(ivar2, ivars(ivar1))
}
}
return(aperm(array(x, mydim[idim]), idim))
}
# Properties of all species
X.fun <- function(X) lapply(lapply(ispecies, X.reaction, X), dim.fun)
logK <- function() lapply(ispecies, X.reaction, "logK")
# A/2.303RT
A <- function() {
out <- mapply(`-`, X.fun("logK"), logQ(), SIMPLIFY = FALSE)
# Deal with affinities of protein ionization here 20120527
if("H+" %in% rownames(mybasis)) {
# Which species are proteins
isprotein <- grepl("_", myspecies$name)
if(any(isprotein)) {
if(get("thermo", CHNOSZ)$opt$ionize.aa) {
message("affinity: ionizing proteins ...")
# The rownumbers in thermo()$protein
ip <- pinfo(myspecies$name[isprotein])
# Get the affinity of ionization
iHplus <- match("H+", rownames(mybasis))
# as.numeric is needed in case the logact column is character mode
# due to buffer definition (that means we can't do pH buffers)
pH <- -as.numeric(mybasis$logact[iHplus])
A.ionization <- A.ionization(ip, vars, vals, T = T, P = P, pH = pH, transect = transect)
# Add it to the affinities of formation reactions of the non-ionized proteins
out[isprotein] <- lsum(out[isprotein], A.ionization)
} else message("affinity: NOT ionizing proteins because thermo()$opt$ionize.aa is FALSE")
}
}
return(out)
}
### Call the necessary functions
if(!is.character(what)) {
# Expand numeric values into our dimensions
# (used by energy.args() for calculating pe = f(Eh, T) )
# TODO: document that sout here denotes the dimension
# we're expanding into
return(dim.fun(what, ivars(sout$out)))
} else if(what %in% c('G', 'H', 'S', 'Cp', 'V', 'E', 'kT', 'logK')) {
# Get subcrt properties for reactions
sout <- sout.fun(what)
a <- X.fun(what)
} else if(length(agrep("species", what)) > 0) {
# Get subcrt properties for species
# e.g. what = G.species, Cp.species etc
mywhat <- s2c(what, sep = ".", keep.sep = FALSE)[1]
sout <- sout.fun(mywhat)
a <- lapply(mapply(X.species, ispecies+nbasis, 1, mywhat, SIMPLIFY = FALSE), dim.fun)
} else {
# Get affinities or logact.basis, logact.species or logQ
if(what == "A") sout <- sout.fun("logK")
a <- do.call(what, list())
}
### Use species indices as the names
if(what == "logact.basis") names(a) <- mybasis$ispecies
else names(a) <- myspecies$ispecies
### Return the results
return(list(sout = sout, a = a))
}
energy.args <- function(args, transect = FALSE) {
## Extracted from affinity() and modified 20090329 jmd
# Takes a list of arguments which define the dimensions
# over which to calculate logQ, logK and affinity
# The names should be T, P, IS and names of basis species
# (or pH, pe, Eh)
thermo <- get("thermo", CHNOSZ)
## Inputs are like c(T1, T2, res)
# and outputs are like seq(T1, T2, length.out = res)
# unless transect: do the variables specify a transect? 20090627
transect <- any(transect, any(sapply(args, length) > 3))
## Convert T, P args and take care of
# Single values for T, P or IS
T <- 298.15
P <- "Psat"
IS <- 0
T.is.var <- P.is.var <- IS.is.var <- FALSE
arg.is.T <- names(args) == "T"
arg.is.P <- names(args) == "P"
arg.is.IS <- names(args) == "IS"
if(any(arg.is.T)) {
T <- args[[which(arg.is.T)]]
if(length(T) > 1) T.is.var <- TRUE
if(transect) args[[which(arg.is.T)]] <- T <- envert(T, 'K')
else args[[which(arg.is.T)]][1:2] <- T[1:2] <- envert(T[1:2], 'K')
T <- T[!is.na(T)]
}
if(any(arg.is.P)) {
P <- args[[which(arg.is.P)]]
if(length(P) > 1) P.is.var <- TRUE
if(!identical(P, "Psat")) {
if(transect) args[[which(arg.is.P)]] <- P <- envert(P, 'bar')
else args[[which(arg.is.P)]][1:2] <- P[1:2] <- envert(P[1:2], 'bar')
}
P <- P[!is.na(P)]
}
if(any(arg.is.IS)) {
IS <- args[[which(arg.is.IS)]]
if(length(IS) > 1) IS.is.var <- TRUE
}
# Report non-variables to user
if(!T.is.var) {
Tunits <- T.units()
if(Tunits == "C") Tunits <- "\u00BAC"
message('affinity: temperature is ', outvert(T, 'K'), ' ', Tunits)
}
if(!P.is.var) {
if(identical(P, "Psat")) message("affinity: pressure is Psat")
else message('affinity: pressure is ', outvert(P, 'bar'), ' ', P.units())
}
if(!IS.is.var & !identical(IS, 0)) message('affinity: ionic strength is ', IS)
# Default value for resolution
res <- 256
# Where we store the output
what <- "A"
vars <- character()
vals <- list(NA)
# This needs to have 1 as the third component because
# energy() uses it to build an array with the given dimension
lims <- list(c(NA, NA, 1))
# Clean out non-variables
if(any(arg.is.T) & !T.is.var) args <- args[names(args) != "T"]
if(any(arg.is.P) & !P.is.var) args <- args[names(args) != "P"]
if(any(arg.is.IS) & !IS.is.var) args <- args[names(args) != "IS"]
# The property we're interested in
if("what" %in% names(args)) {
what <- args[[names(args) == "what"]]
args <- args[names(args) != "what"]
}
# Assemble the variables
if(length(args) > 0) {
for(i in 1:length(args)) {
nametxt <- names(args)[i]
if(transect) lims.orig <- c(min(args[[i]]), max(args[[i]]))
else lims.orig <- args[[i]][1:2]
if(names(args)[i] == "pH") {
names(args)[i] <- "H+"
if(transect) args[[i]] <- -args[[i]]
else args[[i]][1:2] <- -args[[i]][1:2]
}
if(names(args)[i] == "pe") {
names(args)[i] <- "e-"
if(transect) args[[i]] <- -args[[i]]
else args[[i]][1:2] <- -args[[i]][1:2]
}
if(length(args[[i]]) < 3 & !transect) args[[i]] <- c(args[[i]], res)
vars[length(vars)+1] <- names(args)[i]
if(transect) {
vals[[length(vars)]] <- args[[i]]
lims[[length(vars)]] <- c(lims.orig, length(vals[[i]]))
} else {
vals[[length(vars)]] <- seq(args[[i]][1], args[[i]][2], length.out = args[[i]][3])
lims[[length(vars)]] <- args[[i]]
}
names(lims)[length(vars)] <- names(args)[i]
# Say something about the identities, ranges, and units of the variables
unittxt <- ""
# Number of values
if(transect) n <- length(args[[i]]) else n <- args[[i]][3]
# Physical state
ibasis <- match(nametxt, rownames(thermo$basis))
if(isTRUE(as.logical(ibasis))) {
if(thermo$basis$state[ibasis] == "gas") nametxt <- paste("log10(f_", nametxt, ")", sep = "")
else nametxt <- paste("log10(a_", nametxt, ")", sep = "")
} else {
# Stop if the argument doesn't correspond to a basis species, T, P, or IS
if(!nametxt %in% c("T", "P", "IS")) {
if(! (nametxt == "pH" & 'H+' %in% rownames(thermo$basis) | nametxt %in% c("pe", "Eh") & 'e-' %in% rownames(thermo$basis))) {
stop(nametxt, " is not one of T, P, or IS, and does not match any basis species")
}
}
}
# Temperature and pressure and Eh
if(nametxt == "T") unittxt <- " K"
if(nametxt == "P") unittxt <- " bar"
if(nametxt == "Eh") unittxt <- " V"
message("affinity: variable ", length(vars), " is ", nametxt,
" at ", n, " values from ", lims.orig[1], " to ", lims.orig[2], unittxt)
}
}
args <- list(what = what, vars = vars, vals = vals, lims = lims, T = T, P = P, IS = IS, transect = transect)
# Convert Eh to pe
if("Eh" %in% args$vars) {
# Get Eh into our dimensions
Eh.args <- args
# What variable is Eh
Eh.var <- which(args$vars == "Eh")
Eh.args$what <- args$vals[[Eh.var]]
Eh.args$sout$out <- Eh.var
Eh <- do.call("energy", Eh.args)
# Get temperature into our dimensions
T.args <- args
if("T" %in% args$vars) {
T.var <- which(args$vars == "T")
T.args$what <- args$vals[[T.var]]
} else {
T.var <- 1
T.args$what <- T
}
T.args$sout$out <- T.var
T <- do.call("energy", T.args)
# Do the conversion on vectors
mydim <- dim(Eh)
Eh <- as.vector(Eh)
T <- as.vector(T)
pe <- convert(Eh, "pe", T=T)
dim(pe) <- mydim
# Update the arguments list
args$vars[Eh.var] <- "e-"
args$vals[[Eh.var]] <- -pe
}
return(args)
}
A.ionization <- function(iprotein, vars, vals, T = 298.15, P = "Psat", pH = 7, transect = FALSE) {
# A function to build a list of values of A/2.303RT of protein ionization
# that can be used by energy(); 20120527 jmd
# Some of the variables might not affect the values (e.g. logfO2)
# What are the variables that affect the values
T <- convert(T, "C")
if(!is.na(iT <- match("T", vars))) T <- convert(vals[[iT]], "C")
if(!is.na(iP <- match("P", vars))) P <- vals[[iP]]
if(!is.na(iHplus <- match("H+", vars))) pH <- -vals[[iHplus]]
# Is it a transect (single points) or a grid?
if(transect) TPpH <- list(T = T, P = P, pH = pH)
else {
# Make a grid of all combinations
# Put T, P, pH in same order as they show up vars
egargs <- list(T = T, P = P, pH = pH)
# order(c(NA, NA, NA)) might segfault in some versions of R (seen in R 2.15.3 on Linux)
if(is.na(iT) & is.na(iP) & is.na(iHplus)) TPpHorder <- c(1, 2, 3)
else TPpHorder <- order(c(iT, iP, iHplus))
egargs <- c(egargs[TPpHorder], list(stringsAsFactors = FALSE))
TPpH <- do.call(expand.grid, egargs)
# Figure out the dimensions of T-P-pH (making sure to drop any that aren't in vars)
TPpHdim <- numeric(3)
TPpHdim[iT] <- length(T)
TPpHdim[iP] <- length(P)
TPpHdim[iHplus] <- length(pH)
TPpHdim <- TPpHdim[!TPpHdim == 0]
# Figure out the dimensions of the other vars
othervars <- vars[!vars %in% c("T", "P", "H+")]
iother <- match(othervars, vars)
otherdim <- sapply(vals, length)[iother]
# If Eh was given to energy.args, values of pe were calculated in all dimensions
# Figure out the original length of the Eh variable
ieminus <- match("e-", vars[iother])
if(!is.na(ieminus)) {
otherdim[ieminus] <- NA
edim <- dim(vals[[iother[ieminus]]])
# Loop TPpHdim and otherdim, taking out each one from edim
for(dim in c(TPpHdim, otherdim)) {
id <- match(dim, edim)
edim[id] <- NA
}
otherdim[ieminus] <- edim[!is.na(edim)]
}
# The permutation vector
if(length(iother) > 0) allvars <- c(vars[-iother], vars[iother])
else allvars <- vars
perm <- match(vars, allvars)
}
# Initialize output list
out <- vector("list", length(iprotein))
# Get aa from iprotein
aa <- pinfo(iprotein)
# Calculate the values of A/2.303RT as a function of T-P-pH
A <- ionize.aa(aa = aa, property = "A", T = TPpH$T, P = TPpH$P, pH = TPpH$pH)
if(transect) {
# Just turn the values into a list
for(i in 1:length(iprotein)) out[[i]] <- A[, i]
} else for(i in 1:length(iprotein)) {
# What are the values of ionization affinity for this protein
thisA <- A[, i]
# Apply the dimensions of T-P-pH
tpphdim <- TPpHdim
if(length(tpphdim) == 0) tpphdim <- 1
thisA <- array(thisA, tpphdim)
# Grow into the dimensions of all vars
alldim <- c(TPpHdim, otherdim)
if(length(alldim) == 0) alldim <- 1
thisA <- array(thisA, alldim)
# Now permute the array to put dimensions in same order as the variables
thisA <- aperm(thisA, perm)
# Store in output list
out[[i]] <- thisA
}
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/util.affinity.R
|
# CHNOSZ/util.args.R
# Functions to create argument lists and get name of calling function
### Unexported functions ###
# Force T and P to equal length
# Also looks for the keyword Psat in the value of P and substitutes calculated values of the saturation vapor pressure
TP.args <- function(T = NULL, P = NULL) {
# Keep the [1] here because some functions (e.g. subcrt) will repeat "Psat"
if(identical(P[1], "Psat")) {
P <- water("Psat", T, P = "Psat")[, 1]
# water.SUPCRT92 issues its own warnings about
# exceeding Psat's temperature limit
if(get("thermo", CHNOSZ)$opt$water == "IAPWS95")
if(sum(is.na(P))>0)
warning('TP.args: NAs in Psat (likely T > Tc where Tc = 647.096 K)', call. = FALSE)
}
if(length(P) < length(T) & !is.null(P)) P <- rep(P, length.out = length(T))
else if(length(T) < length(P) & !is.null(T)) T <- rep(T, length.out = length(P))
# Something we do here so the SUPCRT water calculations work
T[T == 273.15] <- 273.16
return(list(T = T, P = P))
}
# Make the argument lowercase, then transform a, c, g, and l to aq, gas, cr, and liq
state.args <- function(state = NULL) {
if(is.null(state) | is.numeric(state[1])) return(state)
# Normalize state arguments
for(i in 1:length(state)) {
if(tolower(state[i]) == 'a') state[i] <- 'aq'
if(tolower(state[i]) == 'c') state[i] <- 'cr'
if(tolower(state[i]) == 'g') state[i] <- 'gas'
if(tolower(state[i]) == 'l') state[i] <- 'liq'
}
return(state)
}
caller.name <- function(n = 2) {
# Returns the name of the calling function n frames up
# (n=2: the caller of the function that calls this one)
# or character() if called interactively
if(sys.nframe() < n) name <- character()
else {
sc <- sys.call(-n)[[1]]
name <- tryCatch(as.character(sc), error = function(e) character())
# Also return character() if the value from sys.call is
# the function itself (why does this sometimes happen,
# e.g. when called from affinity()?)
}
return(name)
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/util.args.R
|
# CHNOSZ/util.array.R
# Functions to work on multidimensional arrays
# 20100314 jmd
list2array <- function(l) {
# Turn a list of arrays (each with the same dimension) into an array,
# which has an additional dimension with size equal to the number of initial arrays
d <- dim(l[[1]])
if(is.null(d)) d <- length(l[[1]])
n <- length(l)
# The size of each of the input arrays
ni <- prod(d)
# The total size of the output array
nt <- prod(c(ni, n))
# lapply is fast, but it just returns another list
# and sapply (and unlist) is slow
#arr <- sapply(l, as.numeric)
arr <- numeric(nt)
# Enter values into the vector
for(i in 1:n) arr[(1:ni)+(i-1)*ni] <- l[[i]]
# Turn the vector into an array with the required dimensions
dim(arr) <- c(d, n)
return(arr)
}
slice <- function(arr, d = NULL, i = 1, value = NULL) {
# Extract/assign values from/to the ith slice(s)
# in the dth dimension of an array
mydim <- dim(arr)
nd <- length(mydim)
# Build an expression used to index the array 20101031
prefix <- paste(rep(",", d-1), collapse = "")
suffix <- paste(rep(",", nd-d), collapse = "")
# The ith slices of the dth dimension
expr <- paste(prefix, deparse(i), suffix, sep = "")
# The old (maybe slower) way
#expr <- rep("", nd)
#expr[d] <- "i"
#expr <- c2s(expr, sep = ",")
if(is.null(value)) {
expr <- paste("arr[", expr, "]", sep = "")
return(eval(parse(text = expr)))
} else {
expr <- paste("arr[", expr, "] <- value", sep = "")
# The following performs the given operation on arr
eval(parse(text = expr))
return(arr)
}
}
dimSums <- function(arr, d = 1, i = NULL) {
# Sum an n-dimensional array along the dth dimension
# using only the ith slices in that dimension
# Merged from mj/plot.R 20100314 jmd
# e.g., if 'arr' is a matrix, the following are TRUE:
# identical(dimSums(arr, 1), colSums(arr))
# identical(dimSums(arr, 2), rowSums(arr))
# If i is NULL we use all slices in the dth dimension
if(is.null(i)) i <- 1:dim(arr)[d]
# Now take the sum
for(j in 1:length(i)) {
s <- slice(arr, d = d, i = i[j])
if(j == 1) out <- s else out <- out + s
}
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/util.array.R
|
# CHNOSZ/util.character.R
# Functions to work with character objects
### Unexported functions ###
# Join the elements of a character object into a character object of length 1 (a string)
c2s <- function(x, sep = ' ') {
# Make a string out of a character vector
if(length(x) %in% c(0,1)) return(x)
s <- paste(x, collapse = sep)
return(s)
}
# Split a string into elements of a character object of length n+1, where n is the number of separators in the string
# Default sep = NULL indicates a separator at every position of x
# keep.sep is used to keep the separators in the output
s2c <- function(x, sep = NULL, keep.sep = TRUE) {
# Recursively split 'x' according to separation strings in 'sep'
do.split <- function(x, sep, keep.sep = TRUE) {
# Split the elements of x according to sep
# Output is a list the length of x
if(is.list(x)) stop("x is a list; it must be a character object (can have length > 1)")
x <- as.list(x)
for(i in 1:length(x)) {
# Do the splitting
xi <- strsplit(x[[i]], sep, fixed = TRUE)[[1]]
# Paste the separation term term back in
if(keep.sep & !is.null(sep)) {
xhead <- character()
xtail <- xi
if(length(xi) > 1) {
xhead <- head(xi, 1)
xtail <- tail(xi, -1)
# In-between matches
xtail <- paste("", xtail, sep = sep)
}
# A match at the end ... grep here causes problems
# when sep contains control characters
#if(length(grep(paste(sep, "$", sep = ""), x[[i]]) > 0)) xtail <- c(xtail, sep)
# Use substr instead
nx <- nchar(x[[i]])
ns <- nchar(sep)
if(substr(x[[i]], nx-ns+1, nx) == sep) xtail <- c(xtail, sep)
xi <- c(xhead, xtail)
}
x[[i]] <- xi
}
return(x)
}
# Now do it!
for(i in 1:length(sep)) x <- unlist(do.split(x, sep[i], keep.sep = keep.sep))
return(x)
}
# Return a value of TRUE or FALSE for each element of x
can.be.numeric <- function(x) {
# Return FALSE if length of argument is zero
if(length(x) == 0) FALSE else
if(length(x) > 1) as.logical(sapply(x, can.be.numeric)) else {
if(is.numeric(x)) TRUE else
if(!is.na(suppressWarnings(as.numeric(x)))) TRUE else
if(x %in% c('.', '+', '-')) TRUE else FALSE
}
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/util.character.R
|
# CHNOSZ/util.data.R
# Check entries in the thermodynamic database
## If this file is interactively sourced, the following are also needed to provide unexported functions:
#source("util.formula.R")
#source("util.data.R")
#source("util.character.R")
thermo.refs <- function(key = NULL, keep.duplicates = FALSE) {
## Return references for thermodynamic data.
## 20110615 browse.refs() first version
## 20170212 thermo.refs() remove browsing (except for table of all sources)
# 'key' can be
# NULL: show a table of all sources in a browser
# character: return data for each listed source key
# numeric: open one or two web pages for each listed species
# list: the output of subcrt()
## First retrieve the sources table
thermo <- get("thermo", CHNOSZ)
x <- thermo$refs[order(thermo$refs$note), ]
## Show a table in the browser if 'key' is NULL
if(is.null(key)) {
# Create the html links
cite <- x$citation
x$citation <- sprintf("<a href='%s' target='_blank'>%s</a>", x$URL, cite)
notlinked <- x$URL=="" | is.na(x$URL)
x$citation[notlinked] <- cite[notlinked]
# Remove the last (URL) component
#x$URL <- NULL
x <- x[1:5]
# Count the number of times each source is cited in thermo()$OBIGT
# e.g. if key is "Kel60" we match "Kel60 [S92]" but not "Kel60.1 [S92]"
# http://stackoverflow.com/questions/6713310/how-to-specify-space-or-end-of-string-and-space-or-start-of-string
# We also have to escape keys with "+" signs
ns1 <- sapply(x$key, function(x) sum(grepl(gsub("+", "\\+", paste0(x, "($|\\s)"), fixed = TRUE), thermo$OBIGT$ref1)) )
ns2 <- sapply(x$key, function(x) sum(grepl(gsub("+", "\\+", paste0(x, "($|\\s)"), fixed = TRUE), thermo$OBIGT$ref2)) )
number <- ns1 + ns2
number[number == 0] <- ""
# Now that we're using the sortTable() from w3schools.com, numbers are sorted like text
# Add leading zeros to make the numbers sortable 20170317
# (the zeros disappear somewhere in the rendering of the page)
number <- formatC(number, width = 3, format = "d", flag = "0")
# append the counts to the table to be shown
x <- c(list(number = number), x)
# Title to display for web page
title <- "References for thermodynamic data in CHNOSZ"
### The following is adapted from print.findFn in package 'sos'
f0 <- tempfile()
File <- paste(f0, ".html", sep = "")
#Dir <- dirname(File)
#js <- system.file("extdata/js", "sorttable.js", package = "CHNOSZ")
#file.copy(js, Dir)
## Sundar's original construction:
con <- file(File, "wt")
on.exit(close(con))
.cat <- function(...)
cat(..., "\n", sep = "", file = con, append = TRUE)
## Start
cat('<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN"
"http://www.w3.org/TR/html4/strict.dtd">\n', file = con)
.cat("<html>")
.cat("<head>")
.cat("<title>", title, "</title>")
# sorttable.js is "Blocked for security reasons" in Gmail 20170317
#.cat("<script src=sorttable.js type='text/javascript'></script>")
# https://www.w3schools.com/howto/howto_js_sort_table.asp
.cat('<script type="text/javascript">
function sortTable(n) {
var table, rows, switching, i, x, y, shouldSwitch, dir, switchcount = 0;
table = document.getElementById("thermorefs");
switching = true;
dir = "asc";
while (switching) {
switching = false;
rows = table.getElementsByTagName("TR");
for (i = 1; i < (rows.length - 1); i++) {
shouldSwitch = false;
x = rows[i].getElementsByTagName("TD")[n];
y = rows[i + 1].getElementsByTagName("TD")[n];
if (dir == "asc") {
if (x.innerHTML > y.innerHTML) {
shouldSwitch= true;
break;
}
} else if (dir == "desc") {
if (x.innerHTML < y.innerHTML) {
shouldSwitch= true;
break;
}
}
}
if (shouldSwitch) {
rows[i].parentNode.insertBefore(rows[i + 1], rows[i]);
switching = true;
switchcount ++;
} else {
if (switchcount == 0 && dir == "asc") {
dir = "desc";
switching = true;
}
}
}
}
</script>')
.cat("</head>")
### Boilerplate text
.cat("<body>")
.cat(paste0('<h1>References for thermodynamic data in <a href="https://chnosz.net"><font color="red">CHNOSZ</font></a> ',
packageDescription("CHNOSZ")$Version), " (", packageDescription("CHNOSZ")$Date, ')</h1>')
.cat("<h3>Click on a column header to sort, or on a citation to open the URL in new window.</h3>")
.cat("<h4>Column 'number' gives the number of times each reference appears in thermo()$OBIGT.</h4>")
.cat('<p>See also the vignette <a href="https://chnosz.net/vignettes/OBIGT.html">OBIGT thermodynamic database</a>.</p>')
### Start table and headers
.cat("<table id='thermorefs' border='1'>")
.cat("<tr>")
#.cat(sprintf(" <th>%s</th>\n</tr>",
# paste(names(x), collapse = "</th>\n <th>")))
for(i in 1:length(x)) .cat(sprintf(' <th onclick="sortTable(%s)">%s</th>', i-1, names(x)[i]))
.cat("</tr>")
### Now preparing the body of the table
paste.list <- c(lapply(x, as.character), sep = "</td>\n <td>")
tbody.list <- do.call("paste", paste.list)
tbody <- sprintf("<tr>\n <td>%s</td>\n</tr>", tbody.list)
tbody <- sub("<td><a", "<td class=link><a", tbody, useBytes = TRUE)
.cat(tbody)
### Finish it!
.cat("</table></body></html>")
### End adaptation from print.findFn
# Show table in browser
browseURL(File)
cat("thermo.refs: table of references is shown in browser\n")
} else if(is.character(key)) {
# Return citation information for the given source(s)
# We omit the [S92] in "HDNB78 [S92]" etc.
key <- gsub("\ .*", "", key)
ix <- match(key, x$key)
ina <- is.na(ix)
if(any(is.na(ix))) message(paste("thermo.refs: reference key(s)",
paste(key[ina], collapse = ","), "not found"))
return(x[ix, ])
} else if(is.numeric(key)) {
# Get the source keys for the indicated species
sinfo <- suppressMessages(info(key, check.it = FALSE))
if(keep.duplicates) {
# Output a single reference for each species 20180927
# (including duplicated references, and not including ref2)
mysources <- sinfo$ref1
} else {
mysources <- unique(c(sinfo$ref1, sinfo$ref2))
mysources <- mysources[!is.na(mysources)]
}
return(thermo.refs(mysources))
} else if(is.list(key)) {
if("species" %in% names(key)) ispecies <- key$species$ispecies
else if("reaction" %in% names(key)) ispecies <- key$reaction$ispecies
else stop("list does not appear to be a result from subcrt()")
if(is.null(ispecies)) stop("list does not appear to be a result from subcrt()")
return(thermo.refs(ispecies))
}
}
check.EOS <- function(eos, model, prop, return.difference = TRUE) {
# Compare calculated properties from thermodynamic parameters with given (database) values.
# Print message and return the calculated value if tolerance is exceeded
# or NA if the difference is within the tolerance.
# 20110808 jmd
thermo <- get("thermo", CHNOSZ)
# Get calculated value based on EOS
Theta <- 228 # K
if(model %in% c("HKF", "DEW")) {
# Run checks for aqueous species
if(prop == "Cp") {
## Value of X consistent with IAPWS95
#X <- -2.773788E-7
# We use the value of X consistent with SUPCRT
X <- -3.055586E-7
refval <- eos$Cp
calcval <- eos$c1 + eos$c2/(298.15-Theta)^2 + eos$omega*298.15*X
tol <- thermo$opt$Cp.tol
units <- paste(eos$E_units, "K-1 mol-1")
} else if(prop == "V") {
## Value of Q consistent with IAPWS95
#Q <- 0.00002483137
# Value of Q consistent with SUPCRT92
Q <- 0.00002775729
refval <- eos$V
calcval <- 41.84*eos$a1 + 41.84*eos$a2/2601 +
(41.84*eos$a3 + 41.84*eos$a4/2601) / (298.15-Theta) - Q * eos$omega
isJoules <- eos$E_units == "J"
if(any(isJoules)) calcval[isJoules] <- convert(calcval[isJoules], "cal")
tol <- thermo$opt$V.tol
units <- "cm3 mol-1"
}
} else {
# Run checks for non-aqueous species (i.e., CGL)
if(prop == "Cp") {
refval <- eos$Cp
Tr <- 298.15
calcval <- eos$a + eos$b*Tr + eos$c*Tr^-2 + eos$d*Tr^-0.5 + eos$e*Tr^2 + eos$f*Tr^eos$lambda
tol <- thermo$opt$Cp.tol
units <- paste(eos$E_units, "K-1 mol-1")
}
}
# Calculate the difference
diff <- calcval - refval
if(return.difference) return(diff)
else {
# Return the calculated value if the difference is greater than tol
if(!is.na(calcval)) {
if(!is.na(refval)) {
if(abs(diff) > tol) {
message(paste("check.EOS: calculated ", prop, "\u00B0 of ", eos$name, "(", eos$state,
") differs by ", round(diff,2), " ", units, " from database value", sep = ""))
return(calcval)
}
} else return(calcval)
}
}
# Return NA in most cases
return(NA)
}
check.GHS <- function(ghs, return.difference = TRUE) {
# Compare G calculated from H and S with given (database) values
# Print message and return the calculated value if tolerance is exceeded
# or NA if the difference is within the tolerance
# 20110808 jmd
thermo <- get("thermo", CHNOSZ)
# Get calculated value based on H and S
Se <- entropy(as.character(ghs$formula))
iscalories <- ghs$E_units == "cal"
if(any(iscalories)) Se[iscalories] <- convert(Se[iscalories], "cal")
refval <- ghs$G
DH <- ghs$H
S <- ghs$S
Tr <- 298.15
calcval <- DH - Tr * (S - Se)
# Now on to the comparison
# Calculate the difference
diff <- calcval - refval
if(return.difference) return(diff)
else if(!is.na(calcval)) {
if(!is.na(refval)) {
diff <- calcval - refval
if(abs(diff) > thermo$opt$G.tol) {
message(paste("check.GHS: calculated \u0394G\u00B0f of ", ghs$name, "(", ghs$state,
") differs by ", round(diff), " ", ghs$E_units, " mol-1 from database value", sep = ""))
return(calcval)
}
} else return(calcval)
} else {
# Calculating a value of G failed, perhaps because of missing elements
return(NULL)
}
# Return NA in most cases
return(NA)
}
check.OBIGT <- function() {
# Function to check self-consistency between
# values of Cp and V vs. EOS parameters
# and among G, H, S values
# 20110808 jmd replaces 'check = TRUE' argument of info()
checkfun <- function(what) {
message(paste("check.OBIGT: checking", what))
# Looking at thermo$OBIGT
if(what == "OBIGT") tdata <- get("thermo", CHNOSZ)$OBIGT
else if(what == "DEW") tdata <- read.csv(system.file("extdata/OBIGT/DEW.csv", package = "CHNOSZ"), as.is = TRUE)
else if(what == "SLOP98") tdata <- read.csv(system.file("extdata/OBIGT/SLOP98.csv", package = "CHNOSZ"), as.is = TRUE)
else if(what == "SUPCRT92") tdata <- read.csv(system.file("extdata/OBIGT/SUPCRT92.csv", package = "CHNOSZ"), as.is = TRUE)
else if(what == "AS04") tdata <- read.csv(system.file("extdata/OBIGT/AS04.csv", package = "CHNOSZ"), as.is = TRUE)
else if(what == "AD") tdata <- read.csv(system.file("extdata/OBIGT/AD.csv", package = "CHNOSZ"), as.is = TRUE)
else if(what == "GEMSFIT") tdata <- read.csv(system.file("extdata/OBIGT/GEMSFIT.csv", package = "CHNOSZ"), as.is = TRUE)
ntot <- nrow(tdata)
# Where to keep the results
DCp <- DV <- DG <- rep(NA, ntot)
# First get the species that use HKF equations
isHKF <- tdata$model %in% c("HKF", "DEW")
if(any(isHKF)) {
eos.HKF <- OBIGT2eos(tdata[isHKF,], "HKF")
DCp.HKF <- check.EOS(eos.HKF, "HKF", "Cp")
DV.HKF <- check.EOS(eos.HKF, "HKF", "V")
cat(paste("check.OBIGT: GHS for", sum(isHKF), "species with HKF model in", what, "\n"))
DG.HKF <- check.GHS(eos.HKF)
# Store the results
DCp[isHKF] <- DCp.HKF
DV[isHKF] <- DV.HKF
DG[isHKF] <- DG.HKF
}
# Then other species, if they are present
if(sum(!isHKF) > 0) {
eos.cgl <- OBIGT2eos(tdata[!isHKF,], "cgl")
DCp.cgl <- check.EOS(eos.cgl, "CGL", "Cp")
cat(paste("check.OBIGT: GHS for", sum(!isHKF), "cr,gas,liq species in", what, "\n"))
DG.cgl <- check.GHS(eos.cgl)
DCp[!isHKF] <- DCp.cgl
DG[!isHKF] <- DG.cgl
}
# Put it all together
out <- data.frame(table = what, ispecies = 1:ntot, name = tdata$name, state = tdata$state, E_units = tdata$E_units, DCp = DCp, DV = DV, DG = DG)
return(out)
}
# Check default database (OBIGT)
out <- checkfun("OBIGT")
# Check optional data
out <- rbind(out, checkfun("DEW"))
out <- rbind(out, checkfun("SLOP98"))
out <- rbind(out, checkfun("SUPCRT92"))
out <- rbind(out, checkfun("AS04"))
out <- rbind(out, checkfun("GEMSFIT"))
# Set differences within a tolerance to NA
out$DCp[abs(out$DCp) < 1] <- NA
out$DV[abs(out$DV) < 1] <- NA
out$DG[abs(out$DG) < 500] <- NA
# Take out species where all reported differences are NA
ina <- is.na(out$DCp) & is.na(out$DV) & is.na(out$DG)
out <- out[!ina,]
# Round the values
out$DCp <- round(out$DCp, 2)
out$DV <- round(out$DV, 2)
out$DG <- round(out$DG)
# Return the results
return(out)
}
RH2OBIGT <- function(compound = NULL, state = "cr", file = system.file("extdata/adds/RH98_Table15.csv", package = "CHNOSZ")) {
# Get thermodynamic properties and equations of state parameters using
# group contributions from Richard and Helgeson, 1998 20120609 jmd
# Read the compound names, physical states, chemical formulas and group stoichiometry from the file
# We use check.names=FALSE because the column names are the names of the groups,
# and are not syntactically valid R names, and stringsAsFactors = FALSE
# so that formulas are read as characters (for checking with as.chemical.formula)
dat <- read.csv(file, check.names = FALSE, stringsAsFactors = FALSE)
# "compound" the compound names and states from the file
comate.arg <- comate.dat <- paste(dat$compound, "(", dat$state, ")", sep = "")
# "compound" the compound names and states from the arguments
if(!is.null(compound)) comate.arg <- paste(compound, "(", state, ")", sep = "")
# Identify the compounds
icomp <- match(comate.arg, comate.dat)
# Check if all compounds were found
ina <- is.na(icomp)
if(any(ina)) stop(paste("compound(s)", paste(comate.arg[ina], collapse = " "), "not found in", file))
# Initialize output data frame
out <- get("thermo", CHNOSZ)$OBIGT[0, ]
# Loop over the compounds
for(i in icomp) {
# The group stoichiometry for this compound
thisdat <- dat[i, ]
# Take out groups that are NA or 0
thisdat <- thisdat[, !is.na(thisdat)]
thisdat <- thisdat[, thisdat != 0]
# Identify the groups in this compound
igroup <- 4:ncol(thisdat)
ispecies <- info(colnames(thisdat)[igroup], state = thisdat$state)
# Check if all groups were found
ina <- is.na(ispecies)
if(any(ina)) stop(paste("group(s)", paste(colnames(thisdat)[igroup][ina], collapse = " "), "not found in", thisdat$state, "state"))
# Group additivity of properties and parameters: add contributions from all groups
thiseos <- t(colSums(get("thermo", CHNOSZ)$OBIGT[ispecies, 10:22] * as.numeric(thisdat[, igroup])))
# Group additivity of chemical formula
formula <- as.chemical.formula(colSums(i2A(ispecies) * as.numeric(thisdat[, igroup])))
# Check if the formula is the same as in the file
if(!identical(formula, thisdat$formula))
stop(paste("formula", formula, "of", comate.dat[i], "(from groups) is not identical to", thisdat$formula, "(listed in file)" ))
# Build the front part of OBIGT data frame
thishead <- data.frame(name = thisdat$compound, abbrv = NA, formula = formula, state = thisdat$state,
ref1 = NA, ref2 = NA, date = as.character(Sys.Date()), E_units = "cal", stringsAsFactors = FALSE)
# Insert the result into the output
out <- rbind(out, cbind(thishead, thiseos))
}
return(out)
}
# Dump all thermodynamic data in default and optional OBIGT files 20171121
dumpdata <- function(file = NULL) {
# The default database (OBIGT)
dat <- get("thermo", CHNOSZ)$OBIGT
OBIGT <- cbind(source = "OBIGT", dat)
# Optional data
dat <- read.csv(system.file("extdata/OBIGT/DEW.csv", package = "CHNOSZ"), as.is = TRUE)
DEW <- cbind(source = "DEW", dat)
dat <- read.csv(system.file("extdata/OBIGT/SLOP98.csv", package = "CHNOSZ"), as.is = TRUE)
SLOP98 <- cbind(source = "SLOP98", dat)
dat <- read.csv(system.file("extdata/OBIGT/SUPCRT92.csv", package = "CHNOSZ"), as.is = TRUE)
SUPCRT92 <- cbind(source = "SUPCRT92", dat)
# More optional data 20220929
dat <- read.csv(system.file("extdata/OBIGT/AS04.csv", package = "CHNOSZ"), as.is = TRUE)
AS04 <- cbind(source = "AS04", dat)
dat <- read.csv(system.file("extdata/OBIGT/AD.csv", package = "CHNOSZ"), as.is = TRUE)
AD <- cbind(source = "AD", dat)
dat <- read.csv(system.file("extdata/OBIGT/GEMSFIT.csv", package = "CHNOSZ"), as.is = TRUE)
GEMSFIT <- cbind(source = "GEMSFIT", dat)
# Put it all together
out <- rbind(OBIGT, SUPCRT92, SLOP98, AS04, AD, DEW, GEMSFIT)
# Quote columns 2 (name) and 3 (abbrv) because they have commas for some entries
if(!is.null(file)) write.csv(out, file, row.names = FALSE, quote = c(2, 3))
else(return(out))
}
### Unexported functions ###
# Take a data frame in the format of thermo()$OBIGT of one or more rows,
# remove scaling factors from equations-of-state parameters,
# and apply new column names depending on the state.
# If fixGHS is TRUE a missing one of G, H or S for any species is calculated
# from the other two and the chemical formula of the species.
# If toJoules is TRUE, convert parameters to Joules 20220325
# This function is used by both info() and subcrt() when retrieving entries from the thermodynamic database.
OBIGT2eos <- function(OBIGT, state, fixGHS = FALSE, toJoules = FALSE) {
# Figure out the model for each species 20220929
model <- OBIGT$model
model[is.na(model)] <- ""
isCGL <- model == "CGL"
isHKF <- model == "HKF"
isDEW <- model == "DEW"
isAD <- model == "AD"
# Remove scaling factors for the HKF and DEW species
# protect this by an if statement to workaround error in subassignment to empty subset of data frame in R < 3.6.0
# (https://bugs.r-project.org/bugzilla/show_bug.cgi?id=17483) 20190302
is_HKF <- isHKF | isDEW
if(any(is_HKF)) OBIGT[is_HKF, 15:22] <- t(t(OBIGT[is_HKF, 15:22]) * 10 ^ c(-1, 2, 0, 4, 0, 4, 5, 0))
# For AD species, set NA values in unused columns
if(any(isAD)) OBIGT[isAD, 18:21] <- NA
# Change column names depending on the model
if(all(isAD)) colnames(OBIGT)[15:22] <- c("a", "b", "xi", "XX1", "XX2", "XX3", "XX4", "Z")
else if(all(isHKF | isAD | isDEW)) colnames(OBIGT)[15:22] <- c("a1", "a2", "a3", "a4", "c1", "c2", "omega", "Z")
else colnames(OBIGT)[15:22] <- c("a", "b", "c", "d", "e", "f", "lambda", "T")
if(toJoules) {
# Convert parameters from calories to Joules 20220325
# [Was: convert parameters from Joules to calories 20190530]
iscal <- OBIGT$E_units == "cal"
if(any(iscal)) {
OBIGT[iscal, c(10:13, 15:20)] <- convert(OBIGT[iscal, c(10:13, 15:20)], "J")
# We only convert the last column for aqueous species (HKF parameter: omega), not for CGL species (arbitrary exponent: lambda) 20190903
isaq <- OBIGT$state == "aq"
if(any(isaq)) OBIGT[iscal & isaq, 21] <- convert(OBIGT[iscal & isaq, 21], "J")
# Also update the E_units column 20220325
OBIGT$E_units[iscal] <- "J"
}
}
if(fixGHS) {
# Fill in one of missing G, H, S;
# for use esp. by subcrt() because NA for one of G, H or S precludes calculations at high T
# Which entries are missing just one
imiss <- which(rowSums(is.na(OBIGT[, 10:12])) == 1)
if(length(imiss) > 0) {
for(i in 1:length(imiss)) {
# Calculate the missing value from the others
ii <- imiss[i]
GHS <- as.numeric(GHS(as.character(OBIGT$formula[ii]), G = OBIGT[ii, 10], H = OBIGT[ii, 11], S = OBIGT[ii, 12],
E_units = ifelse(toJoules, "J", OBIGT$E_units[ii])))
icol <- which(is.na(OBIGT[ii, 10:12]))
OBIGT[ii, icol + 9] <- GHS[icol]
}
}
}
OBIGT
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/util.data.R
|
# CHNOSZ/util.expression.R
# Write descriptions of chemical species, properties, reactions, conditions
# Modified from describe(), axis.label() 20120121 jmd
## If this file is interactively sourced, the following are also needed to provide unexported functions:
#source("util.character.R")
expr.species <- function(species, state = "aq", value = NULL, log = FALSE, molality = FALSE, use.state = FALSE, use.makeup = FALSE) {
# Make plotting expressions for chemical formulas
# that include subscripts, superscripts (if charged)
# and optionally designations of states +/- loga or logf prefix
if(length(species) > 1) (stop("more than one species"))
# Convert to character so that "1", "2", etc. don't get converted to chemical formulas via makeup()
species <- as.character(species)
if(use.makeup) {
# The counts of elements in the species:
# here we don't care too much if an "element" is a real element
# (listed in thermo()$element), so we suppress warnings
elements <- suppressWarnings(try(makeup(species), TRUE))
} else elements <- split.formula(species)
# If species can't be parsed as a chemical formula, we don't do the formula formatting
if(inherits(elements, "try-error") | !is.numeric(elements)) expr <- species
else {
# Where we'll put the expression
expr <- ""
# Loop over elements
for(i in 1:length(elements)) {
if(names(elements)[i] != 'Z') {
# Append the elemental symbol
expr <- substitute(paste(a, b), list(a = expr, b = names(elements)[i]))
# Recover the coefficient
coeff <- elements[i]
if(coeff != 1) {
# Append the coefficient
expr <- substitute(a[b], list(a = expr, b = as.character(coeff)))
}
} else {
# For charged species, don't show "Z" but do show e.g. "+2"
coeff <- elements[i]
if(coeff == -1) coeff <- "-"
else if(coeff == 1) coeff <- "+"
else if(coeff > 0) coeff <- paste("+", as.character(coeff), sep = "")
else coeff <- as.character(coeff)
# Append the coefficient as a superscript
expr <- substitute(a^b, list(a = expr, b = coeff))
}
}
}
# Write the physical state
if(use.state) {
# Subscript it if we're not giving the value
if(is.null(value)) expr <- substitute(a[group('(',italic(b),')')],list(a = expr, b = state))
else expr <- substitute(a*group('(',italic(b),')'),list(a = expr, b = state))
}
# Write a variable and value if given
if(!is.null(value) | log | molality) {
# Write [logarithm of] activity or fugacity (or molality 20171101)
var <- "a"
if(molality) var <- "m"
if(state %in% c("g", "gas")) var <- "f"
expr <- substitute(italic(a)[b], list(a = var, b = expr))
# Use the logarithm?
if(log) expr <- substitute(log ~ a, list(a = expr))
# Write the value if not NULL or NA
if(!is.null(value)) {
if(!is.na(value)) expr <- substitute(a == b, list(a = expr, b = value))
}
}
return(expr)
}
expr.property <- function(property, molality = FALSE) {
# A way to make expressions for various properties
# e.g. expr.property('DG0r') for standard molal Gibbs
# Energy change of reaction
propchar <- s2c(property)
expr <- ""
# Some special cases
if(is.na(property)) return("")
if(property == "logK") return(quote(log~italic(K)))
if(property == "logB") return(quote(log~beta))
# Use grepl here b/c diagram() uses "loga.equil" and "loga.basis"
if(grepl("loga", property)) {
if(molality) return(quote(log~italic(m)))
else return(quote(log~italic(a)))
}
if(property == "alpha") return(quote(alpha))
if(property == "Eh") return("Eh")
if(property == "pH") return("pH")
if(property == "pe") return("pe")
if(property == "IS") return(quote(italic(I)))
if(property == "ZC") return(quote(italic(Z)[C]))
# Process each character in the property abbreviation
prevchar <- character()
for(i in 1:length(propchar)) {
if(i > 1) prevchar <- thischar
thischar <- propchar[i]
# Unless indicated below, uppercase letters are italicized
# and lowercase letters are italicized and subscripted
# (includes f for property of formation and r for property of reaction)
if(thischar %in% LETTERS) thisexpr <- substitute(italic(a), list(a = thischar))
else if(thischar %in% letters) thisexpr <- substitute(""[italic(a)], list(a = thischar))
else thisexpr <- substitute(a, list(a = thischar))
# D for greek Delta
# p for subscript italic P (in Cp)
# 0 for degree sign (but not immediately following a number e.g. 2.303)
# l for subscript small lambda
# ' for prime symbol (like "minute")
if(thischar == 'D') thisexpr <- substitute(Delta)
if(thischar == 'p') thisexpr <- substitute(a[italic(P)], list(a = ""))
if(thischar == '0' & !can.be.numeric(prevchar)) thisexpr <- substitute(degree)
if(thischar == 'l') thisexpr <- substitute(a[lambda], list(a = ""))
if(thischar == "'") thisexpr <- substitute(minute)
# Put it together
expr <- substitute(a*b, list(a = expr, b = thisexpr))
}
return(expr)
}
expr.units <- function(property, prefix = "", per = "mol") {
# Make an expression describing units
# Unless we have match below, there will be no units
# (e.g., logK, pH, pe)
expr <- ""
# A, G, H - energy
if(grepl("A", property)) expr <- substitute(a, list(a = E.units()))
if(grepl("G", property)) expr <- substitute(a, list(a = E.units()))
if(grepl("H", property) & !grepl("pH", property)) expr <- substitute(a, list(a = E.units()))
# Cp, S - energy (per K)
if(grepl("Cp", property)) expr <- substitute(a~K^-1, list(a = E.units()))
if(grepl("S", property)) expr <- substitute(a~K^-1, list(a = E.units()))
# V - volume
if(grepl("V", property)) expr <- substitute(a^3, list(a = "cm"))
# E - volume (per K)
if(grepl("E", property)) expr <- substitute(a^3~K^-1, list(a = "cm"))
# P - pressure
if(grepl("P", property)) expr <- substitute(a, list(a = P.units()))
# T - temperature
if(grepl("T", property)) {
expr <- substitute(a, list(a = T.units()))
# Add a degree sign for Celsius
if(T.units() == "C") expr <- substitute(degree*a, list(a = expr))
}
# Eh - electrical potential
if(grepl("Eh", property)) expr <- substitute(a, list(a = "volt"))
# IS - ionic strength
if(grepl("IS", property)) expr <- substitute(a, list(a = mol~kg^-1))
if(!expr == "") {
# Add prefix if appropriate
if(!prefix == "") expr <- substitute(a*b, list(a = prefix, b = expr))
# Add mol^-1 if appropriate
if(!any(sapply(c("P", "T", "Eh", "IS"), function(x) grepl(x, property))))
expr <- substitute(a~b^-1, list(a = expr, b = per))
}
return(expr)
}
axis.label <- function(label, units = NULL, basis = thermo()$basis, prefix = "", molality = FALSE) {
# Make a formatted axis label from a generic description
# It can be a chemical property, condition, or chemical activity in the system;
# if the label matches one of the basis species or if the state is specified, it's a chemical activity
# 20090826: Just return the argument if a comma is already present
# (used for custom labels that shouldn't be italicized)
if(grepl(",", label)) return(label)
if(label %in% rownames(basis)) {
# 20090215: The state this basis species is in
state <- basis$state[match(label, rownames(basis))]
# Get the formatted label
desc <- expr.species(label, state = state, log = TRUE, molality = molality)
} else if(label %in% colnames(basis)) {
# Make a label for an element (total C, total S, etc.) 20230809
if(molality) desc <- bquote(log~italic(m)~"(total "*.(label)*")")
else desc <- bquote(log~italic(a)~"(total "*.(label)*")")
} else {
# The label is for a chemical property or condition
# Make the label by putting a comma between the property and the units
property <- expr.property(label, molality = molality)
if(is.null(units)) units <- expr.units(label, prefix = prefix)
# No comma needed if there are no units
if(units == "") desc <- substitute(a, list(a = property))
else desc <- substitute(a~"("*b*")", list(a = property, b = units))
}
# Done!
return(desc)
}
describe.basis <- function(ibasis = 1:nrow(basis), basis = thermo()$basis,
digits = 1, oneline = FALSE, molality = FALSE, use.pH = TRUE) {
# Make expressions for the chemical activities/fugacities of the basis species
propexpr <- valexpr <- character()
for(i in ibasis) {
if(can.be.numeric(basis$logact[i])) {
# We have an as.numeric here in case the basis$logact is character
# (by inclusion of a buffer for one of the other basis species)
if(rownames(basis)[i] == "H+" & use.pH) {
propexpr <- c(propexpr, "pH")
valexpr <- c(valexpr, format(round(-as.numeric(basis$logact[i]), digits), nsmall = digits))
} else {
# propexpr is logarithm of activity or fugacity
propexpr <- c(propexpr, expr.species(rownames(basis)[i], state = basis$state[i], log = TRUE, molality = molality))
valexpr <- c(valexpr, format(round(as.numeric(basis$logact[i]), digits), nsmall = digits))
}
} else {
# A non-numeric value is the name of a buffer
valexpr <- c(valexpr, basis$logact[i])
# propexpr is pH, activity or fugacity
if(rownames(basis)[i] == "H+" & use.pH) propexpr <- c(propexpr, "pH")
else propexpr <- c(propexpr, expr.species(rownames(basis)[i], state = basis$state[i], value = NA, log = FALSE, molality = molality))
}
}
# Write an equals sign between the property and value
desc <- character()
for(i in seq_along(propexpr)) {
thisdesc <- substitute(a == b, list(a = propexpr[[i]], b = valexpr[[i]]))
if(oneline) {
# put all the property/value equations on one line, separated by commas
if(i == 1) desc <- substitute(a, list(a = thisdesc))
else desc <- substitute(list(a, b), list(a = desc, b = thisdesc))
} else desc <- c(desc, thisdesc)
}
return(as.expression(desc))
}
describe.property <- function(property = NULL, value = NULL, digits = 0, oneline = FALSE, ret.val = FALSE) {
# Make expressions for pressure, temperature, other conditions
if(is.null(property) | is.null(value)) stop("property or value is NULL")
propexpr <- valexpr <- character()
for(i in 1:length(property)) {
propexpr <- c(propexpr, expr.property(property[i]))
if(is.na(value[i])) thisvalexpr <- ""
else if(value[i] == "Psat") thisvalexpr <- quote(italic(P)[sat])
else {
thisvalue <- format(round(as.numeric(value[i]), digits), nsmall = digits)
thisunits <- expr.units(property[i])
thisvalexpr <- substitute(a~b, list(a = thisvalue, b = thisunits))
}
valexpr <- c(valexpr, as.expression(thisvalexpr))
}
# With ret.val = TRUE, return just the value with the units (e.g. 55 degC)
if(ret.val) return(valexpr)
# Write an equals sign between the property and value
desc <- character()
for(i in seq_along(propexpr)) {
if(is.na(value[i])) thisdesc <- propexpr[[i]]
else thisdesc <- substitute(a == b, list(a = propexpr[[i]], b = valexpr[[i]]))
if(oneline) {
# Put all the property/value equations on one line, separated by commas
if(i == 1) desc <- substitute(a, list(a = thisdesc))
else desc <- substitute(list(a, b), list(a = desc, b = thisdesc))
} else desc <- c(desc, thisdesc)
}
return(as.expression(desc))
}
describe.reaction <- function(reaction, iname = numeric(), states = NULL) {
# Make an expression describing the reaction that is
# the 'reaction' part of subcrt() output
reactexpr <- prodexpr <- character()
# Loop over the species in the reaction
for(i in 1:nrow(reaction)) {
# Get the name or the chemical formula of the species
if(i %in% iname) species <- reaction$name[i]
else {
# Should the chemical formula have a state?
if(identical(states,"all") | i %in% states) species <- expr.species(reaction$formula[i], state = reaction$state[i], use.state = TRUE)
else species <- expr.species(reaction$formula[i], state = reaction$state[i])
}
# Get the absolute value of the reaction coefficient
abscoeff <- abs(reaction$coeff[i])
# Put the coefficient in if it's not 1
if(abscoeff == 1) coeffspec <- species
else {
# We put in some space if the coefficient comes before a name
if(i %in% iname) coeffspec <- substitute(a~b, list(a = abscoeff, b = species))
else coeffspec <- substitute(a*b, list(a = abscoeff, b = species))
}
# Is it a reactant or product?
if(reaction$coeff[i] < 0) {
if(length(reactexpr) == 0) reactexpr <- substitute(a, list(a = coeffspec))
else reactexpr <- substitute(a+b, list(a = reactexpr, b = coeffspec))
} else {
# It's a product
if(length(prodexpr) == 0) prodexpr <- substitute(a, list(a = coeffspec))
else prodexpr <- substitute(a+b, list(a = prodexpr, b = coeffspec))
}
}
# Put an equals sign between reactants and products
# Change this to unicode for the reaction double-arrow 20190218 \u21cc
# Go back to equals - the arrow doesn't work out-of-the-box on all OSes 20190817
desc <- substitute(a ~ "=" ~ b, list(a = reactexpr, b = prodexpr))
return(desc)
}
# Make formatted text for activity ratio 20170217
# Allow changing the bottom ion 20200716
ratlab <- function(top = "K+", bottom = "H+", molality = FALSE) {
# The charges
Ztop <- makeup(top)["Z"]
Zbottom <- makeup(bottom)["Z"]
# The text for the exponents
exp.bottom <- as.character(Ztop)
exp.top <- as.character(Zbottom)
if(exp.top == "1") exp.top <- ""
if(exp.bottom == "1") exp.bottom <- ""
# The expression for the top and bottom
expr.top <- expr.species(top)
expr.bottom <- expr.species(bottom)
# With molality, change a to m
a <- ifelse(molality, "m", "a")
# The final expression
substitute(log~(italic(a)[expr.top]^exp.top / italic(a)[expr.bottom]^exp.bottom),
list(a = a, expr.top = expr.top, exp.top = exp.top, expr.bottom = expr.bottom, exp.bottom = exp.bottom))
}
# Make formatted text for thermodynamic system 20170217
syslab <- function(system = c("K2O", "Al2O3", "SiO2", "H2O"), dash = "-") {
for(i in seq_along(system)) {
expr <- expr.species(system[i])
# Use en dash here
if(i == 1) lab <- expr else lab <- substitute(a*dash*b, list(a = lab, dash = dash, b = expr))
}
lab
}
### Unexported function ###
split.formula <- function(formula) {
## Like makeup(), but split apart the formula based on
## numbers (subscripts); don't scan for elemental symbols 20171018
# If there are no numbers or charge, return the formula as-is
# Change [0-9]? to [\\.0-9]* (recognize decimal point in numbers, recognize charge longer than one digit) 20220608
if(! (grepl("[\\.0-9]", formula) | grepl("\\+[\\.0-9]*$", formula) | grepl("-[\\.0-9]*$", formula))) return(formula)
# First split off charge
# (assume that no subscripts are signed)
Z <- 0
hascharge <- grepl("\\+[\\.0-9]*$", formula) | grepl("-[\\.0-9]*$", formula)
if(hascharge) {
# For charge, we match + or - followed by zero or more numbers at the end of the string
if(grepl("\\+[\\.0-9]*$", formula)) {
fsplit <- strsplit(formula, "+", fixed = TRUE)[[1]]
if(is.na(fsplit[2])) Z <- 1 else Z <- as.numeric(fsplit[2])
}
if(grepl("-[\\.0-9]*$", formula)) {
fsplit <- strsplit(formula, "-")[[1]]
# For formula == "H-citrate-2", unsplit H-citrate
if(length(fsplit) > 2) {
f2 <- tail(fsplit, 1)
f1 <- paste(head(fsplit, -1), collapse = "-")
fsplit <- c(f1, f2)
}
if(is.na(fsplit[2])) Z <- -1 else Z <- -as.numeric(fsplit[2])
}
formula <- fsplit[1]
}
# To get strings, replace all numbers with placeholder (#), then split on that symbol
# The outer gsub is to replace multiple #'s with one
numhash <- gsub("#+", "#", gsub("[\\.0-9]", "#", formula))
strings <- strsplit(numhash, "#")[[1]]
# To get coefficients, replace all characters (non-numbers) with placeholder, then split
charhash <- gsub("#+", "#", gsub("[^\\.0-9]", "#", formula))
coeffs <- strsplit(charhash, "#")[[1]]
# If the first coefficient is empty, remove it
if(coeffs[1] == "") coeffs <- tail(coeffs, -1) else {
# If the first string is empty, treat the first coefficient as a leading string (e.g. in 2-octanone)
if(strings[1] == "") {
strings[2] <- paste0(coeffs[1], strings[2])
coeffs <- tail(coeffs, -1)
strings <- tail(strings, -1)
}
}
# If we're left with no coefficients, just return the string
if(length(coeffs) == 0 & Z == 0) return(strings)
# If we're missing a coefficient, append one
if(length(coeffs) < length(strings)) coeffs <- c(coeffs, 1)
# Use strings as names for the numeric coefficients
coeffs <- as.numeric(coeffs)
names(coeffs) <- strings
# Include charge if it is not 0
if(Z != 0) coeffs <- c(coeffs, Z = Z)
return(coeffs)
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/util.expression.R
|
# CHNOSZ/util.fasta.R
# Read and manipulate FASTA sequence files
read.fasta <- function(file, iseq = NULL, ret = "count", lines = NULL, ihead = NULL,
start = NULL, stop = NULL, type = "protein", id = NULL) {
# Read sequences from a fasta file
# Some of the following code was adapted from
# read.fasta in package seqinR
# value of 'iseq' is what sequences to read (default is all)
# value of 'ret' determines format of return value:
# count: amino acid composition (same columns as thermo()$protein, can be used by add.protein)
# or nucleic acid base composition (A-C-G-T)
# seq: amino acid sequence
# fas: fasta entry
# value of 'id' is used for 'protein' in output table,
# otherwise ID is parsed from FASTA header (can take a while)
# Check if the file is in an archive (https://github.com/jimhester/archive)
if(inherits(file, "archive_read")) {
is.archive <- TRUE
filebase <- gsub("]", "", basename(summary(file)$description))
} else {
is.archive <- FALSE
filebase <- basename(file)
}
if(is.null(lines)) {
message("read.fasta: reading ", filebase, " ... ", appendLF = FALSE)
is.nix <- Sys.info()[[1]] == "Linux"
if(is.archive) {
# We can't use scan here?
lines <- readLines(file)
} else if(is.nix) {
# Retrieve contents using system command (seems slightly faster even than scan())
# Figure out whether to use 'cat', 'zcat' or 'xzcat'
suffix <- substr(file,nchar(file)-2,nchar(file))
if(suffix == ".gz") mycat <- "zcat"
else if(suffix == ".xz") mycat <- "xzcat"
else mycat <- "cat"
lines <- system(paste(mycat,' "',file,'"',sep = ""),intern = TRUE)
} else lines <- scan(file, what = character(), sep = "\n", quiet = TRUE)
}
nlines <- length(lines)
message(nlines, " lines ... ", appendLF = FALSE)
if(is.null(ihead)) ihead <- which(substr(lines, 1, 1) == ">")
message(length(ihead), " sequences")
linefun <- function(i1, i2) lines[i1:i2]
# Identify the lines that begin and end each sequence
begin <- ihead + 1
end <- ihead - 1
end <- c(end[-1], nlines)
# Use all or selected sequences
if(is.null(iseq)) iseq <- seq_along(begin)
# Just return the lines from the file
if(ret == "fas") {
iline <- numeric()
for(i in iseq) iline <- c(iline, (begin[i]-1):end[i])
return(lines[iline])
}
# Get each sequence from the begin to end lines
seqfun <- function(i) paste(linefun(begin[i], end[i]), collapse = "")
sequences <- lapply(iseq, seqfun)
# Organism name is from file name
# (basename minus extension)
bnf <- strsplit(filebase, split = ".", fixed = TRUE)[[1]][1]
organism <- bnf
# Protein/gene name is from header line for entry
# (strip the ">" and go to the first space)
missid <- missing(id)
if(is.null(id)) id <- as.character(lapply(iseq, function(j) {
# Get the text of the line
f1 <- linefun(ihead[j], ihead[j])
# Stop if the first character is not ">"
# or the first two charaters are "> "
if(substr(f1, 1, 1) != ">" | length(grep("^> ", f1)>0))
stop(paste("file", filebase, "line", j, "doesn't begin with FASTA header '>'."))
# Discard the leading '>'
f2 <- substr(f1, 2, nchar(f1))
# Keep everything before the first space
return(strsplit(f2, " ")[[1]][1])
} ))
if(ret == "count") {
counts <- count.aa(sequences, start, stop, type)
ref <- abbrv <- NA
chains <- 1
if(type == "protein") {
colnames(counts) <- aminoacids(3)
# 20090507 Made stringsAsFactors FALSE
out <- cbind(data.frame(protein = id, organism = organism,
ref = ref, abbrv = abbrv, chains = chains, stringsAsFactors = FALSE), counts)
# 20170117 Extra processing for files from UniProt
isUniProt <- grepl("\\|......\\|.*_", out$protein[1])
if(isUniProt & missid) {
p1 <- sapply(strsplit(out$protein, "\\|"), "[", 1)
p2 <- sapply(strsplit(out$protein, "\\|"), "[", 2)
p3 <- sapply(strsplit(out$protein, "\\|"), "[", 3)
out$abbrv <- sapply(strsplit(p3, "_"), "[", 1)
out$organism <- sapply(strsplit(p3, "_"), "[", 2)
out$protein <- paste0(p1, "|", p2)
}
out
} else if(type %in% c("DNA", "RNA")) {
cbind(data.frame(gene = id, organism = organism,
ref = ref, abbrv = abbrv, chains = chains, stringsAsFactors = FALSE), counts)
}
} else return(sequences)
}
count.aa <- function(seq, start = NULL, stop = NULL, type = "protein") {
# Count amino acids or DNA bases in one or more sequences given as elements of the list seq
if(type == "protein") letts <- aminoacids(1)
else if(type == "DNA") letts <- c("A", "C", "G", "T")
else if(type == "RNA") letts <- c("A", "C", "G", "U")
else stop(paste("unknown sequence type", type))
# The numerical positions of the letters in alphabetical order (i.e. for amino acids, same order as in thermo()$protein)
ilett <- match(letts, LETTERS)
# The letters A-Z represented by raw values
rawAZ <- charToRaw("ABCDEFGHIJKLMNOPQRSTUVWXYZ")
# To count the letters in each sequence
countfun <- function(seq, start, stop) {
# Get a substring if one or both of start or stop are given
# If only one of start or stop is given, get a default value for the other
if(!is.null(start)) {
if(is.null(stop)) stop <- nchar(seq)
seq <- substr(seq, start, stop)
} else if(!is.null(stop)) {
seq <- substr(seq, 1, stop)
}
## The actual counting ...
#nnn <- table(strsplit(toupper(seq), "")[[1]])
# ... Replaced with C version 20180217
counts <- .C(C_count_letters, seq, integer(26))[[2]]
# which is equivalent to this R code:
#rawseq <- charToRaw(toupper(seq))
#counts <- sapply(rawAZ, function(x) sum(rawseq == x))
return(counts)
}
# Counts for each sequence
counts <- lapply(seq, countfun, start, stop)
counts <- do.call(rbind, counts)
# Check for letters that aren't in our alphabet
ina <- colSums(counts[, -ilett, drop = FALSE]) > 0
if(any(ina)) {
message(paste("count.aa: unrecognized letter(s) in", type, "sequence:", paste(LETTERS[-ilett][ina], collapse = " ")))
}
counts <- counts[, ilett, drop = FALSE]
# Clean up row/column names
colnames(counts) <- letts
rownames(counts) <- 1:nrow(counts)
return(counts)
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/util.fasta.R
|
# CHNOSZ/util.formula.R
# Functions to compute some properties of chemical formulas
i2A <- function(formula) {
## Assemble the stoichiometric matrix (A)
## for the given formulas 20120108 jmd
if(is.matrix(formula)) {
# dDo nothing if the argument is already a matrix
A <- formula
} else if(is.numeric(formula) & !is.null(names(formula))) {
# Turn a named numeric object into a formula matrix
A <- t(as.matrix(formula))
} else {
# Get the elemental makeup of each formula, counting
# zero for elements that appear only in other formulas
msz <- makeup(formula, count.zero = TRUE)
# Convert formulas into a stoichiometric matrix with elements on the columns
A <- t(sapply(msz, c))
# Add names from character argument
# or from thermo()$OBIGT for numeric argument
if(is.numeric(formula[1])) rownames(A) <- get("thermo", CHNOSZ)$OBIGT$name[formula]
else rownames(A) <- formula
}
return(A)
}
as.chemical.formula <- function(makeup, drop.zero = TRUE) {
# Make a formula character string from the output of makeup()
# or from a stoichiometric matrix (output of i2A() or protein.formula())
# First define a function to work with a single makeup object
cffun <- function(makeup) {
# First strip zeroes if needed
if(drop.zero) makeup <- makeup[makeup != 0]
# Z always goes at end
makeup <- c(makeup[names(makeup) != "Z"], makeup[names(makeup) == "Z"])
# The elements and coefficients
elements <- names(makeup)
coefficients <- as.character(makeup)
# Any 1's get zapped
coefficients[makeup == 1] <- ""
# Any Z's get zapped (if they're followed by a negative number)
# or turned into a plus sign (to indicate a positive charge)
elements[elements == "Z" & makeup < 0] <- ""
elements[elements == "Z" & makeup >= 0] <- "+"
# Put the elements and coefficients together
formula <- paste(elements, coefficients, sep = "", collapse = "")
# If the formula is uncharged, and the last element has a negative
# coefficient, add an explicit +0 at the end
if(!"Z" %in% names(makeup) & tail(makeup,1) < 0)
formula <- paste(formula, "+0", sep = "")
return(formula)
}
# Call cffun() once for a single makeup, or loop for a matrix
if(is.matrix(makeup)) out <- sapply(1:nrow(makeup), function(i) {
mkp <- makeup[i, ]
return(cffun(mkp))
}) else out <- cffun(makeup)
return(out)
}
mass <- function(formula) {
# Calculate the mass of elements in chemical formulas
thermo <- get("thermo", CHNOSZ)
formula <- i2A(get.formula(formula))
ielem <- match(colnames(formula), thermo$element$element)
if(any(is.na(ielem))) stop(paste("element(s)",
colnames(formula)[is.na(ielem)], "not available in thermo()$element"))
mass <- as.numeric(formula %*% thermo$element$mass[ielem])
return(mass)
}
entropy <- function(formula) {
# Calculate the standard molal entropy at Tref of elements in chemical formulas
thermo <- get("thermo", CHNOSZ)
formula <- i2A(get.formula(formula))
ielem <- match(colnames(formula), thermo$element$element)
if(any(is.na(ielem))) warning(paste("element(s)",
paste(colnames(formula)[is.na(ielem)], collapse = " "), "not available in thermo()$element"))
# Entropy per atom
Sn <- thermo$element$s[ielem] / thermo$element$n[ielem]
# If there are any NA values of entropy, put NA in the matrix, then set the value to zero
# this allows mixed finite and NA values to be calculated 20190802
ina <- is.na(Sn)
if(any(ina)) {
for(i in which(ina)) {
hasNA <- formula[, i] != 0
formula[hasNA, i] <- NA
}
Sn[ina] <- 0
}
entropy <- as.numeric( formula %*% Sn )
# Convert to Joules 20220325
convert(entropy, "J")
}
GHS <- function(formula, G = NA, H = NA, S = NA, T = 298.15, E_units = "J") {
# For all NA in G, H and S, do nothing
# For no NA in G, H and S, do nothing
# For one NA in G, H and S, calculate its value from the other two:
# G - standard molal Gibbs energy of formation from the elements
# H - standard molal enthalpy of formation from the elements
# S - standard molal entropy
# Argument checking
if(!all(diff(sapply(list(formula, G, H, S), length)) == 0))
stop("formula, G, H and S arguments are not same length")
# Calculate Se (entropy of elements)
Se <- entropy(formula)
if(E_units == "cal") Se <- convert(Se, "cal")
# Calculate one of G, H, or S if the other two are given
GHS <- lapply(seq_along(G), function(i) {
G <- G[i]
H <- H[i]
S <- S[i]
Se <- Se[i]
if(is.na(G)) G <- H - T * (S - Se)
else if(is.na(H)) H <- G + T * (S - Se)
else if(is.na(S)) S <- (H - G) / T + Se
list(G, H, S)
})
# Turn the list into a matrix and add labels
GHS <- t(sapply(GHS, c))
colnames(GHS) <- c("G", "H", "S")
rownames(GHS) <- formula
GHS
}
ZC <- function(formula) {
# Calculate average oxidation state of carbon
# from chemical formulas of species
# If we haven't been supplied with a stoichiometric matrix, first get the formulas
formula <- i2A(get.formula(formula))
# Is there carbon there?
iC <- match("C", colnames(formula))
if(is.na(iC)) stop("carbon not found in the stoichiometric matrix")
# The nominal charges of elements other than carbon
# FIXME: add more elements, warn about missing ones
knownelement <- c("H", "N", "O", "S", "Z")
charge <- c(-1, 3, 2, 2, 1)
# Where are these elements in the formulas?
iknown <- match(knownelement, colnames(formula))
# Any unknown elements in formula get dropped with a warning
iunk <- !colnames(formula) %in% c(knownelement, "C")
if(any(iunk)) warning(paste("element(s)", paste(colnames(formula)[iunk], collapse = " "),
"not in", paste(knownelement, collapse = " "), "so not included in this calculation"))
# Contribution to charge only from known elements that are in the formula
formulacharges <- t(formula[, iknown[!is.na(iknown)]]) * charge[!is.na(iknown)]
# Sum of the charges; the arrangement depends on the number of formulas
if(nrow(formula) == 1) formulacharge <- rowSums(formulacharges)
else formulacharge <- colSums(formulacharges)
# Numbers of carbons
nC <- formula[, iC]
# Average oxidation state
ZC <- as.numeric(formulacharge/nC)
return(ZC)
}
### Unexported functions ###
# Accept a numeric or character argument; the character argument can be mixed
# (i.e. include quoted numbers). as.numeric is tested on every value; numeric values
# are then interpreted as species indices in the thermodynamic database (rownumbers of thermo()$OBIGT),
# and the chemical formulas for those species are returned.
# Values that can not be converted to numeric are returned as-is.
get.formula <- function(formula) {
# Return the argument if it's a matrix or named numeric
if(is.matrix(formula)) return(formula)
if(is.numeric(formula) & !is.null(names(formula))) return(formula)
# Return the argument as matrix if it's a data frame
if(is.data.frame(formula)) return(as.matrix(formula))
# Return the values in the argument, or chemical formula(s) for values that are species indices
# For numeric values, get the formulas from those rownumbers of thermo()$OBIGT
i <- suppressWarnings(as.integer(formula))
# We can't have more than the number of rows in thermo()$OBIGT
thermo <- get("thermo", CHNOSZ)
iover <- i > nrow(thermo$OBIGT)
iover[is.na(iover)] <- FALSE
if(any(iover)) stop(paste("species number(s)", paste(i[iover], collapse = " "),
"not available in thermo()$OBIGT"))
# We let negative numbers pass as formulas
i[i < 0] <- NA
# Replace any species indices with formulas from thermo()$OBIGT
formula[!is.na(i)] <- thermo$OBIGT$formula[i[!is.na(i)]]
return(formula)
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/util.formula.R
|
# CHNOSZ/util.legend.R
# Functions for making legend text
# 20190530 jmd first version
lNaCl <- function(x, digits = 2) substitute(italic(m)[NaCl] == x~mol~kg^-1, list(x = round(x, digits)))
lS <- function(x, digits = 3) substitute(sum(S) == x~mol~kg^-1, list(x = round(x, digits)))
lT <- function(x, digits = 0) substitute(x~degree*C, list(x = round(x, digits)))
lP <- function(x, digits = 0) if(identical(x, "Psat")) quote(italic(P)[sat]) else substitute(x~bar, list(x = round(x, digits)))
lTP <- function(x, y, digits = 0) substitute(list(x, y), list(x = lT(x, digits), y = lP(y, digits)))
lex <- function(...) as.expression(c(...))
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/util.legend.R
|
# CHNOSZ/util.list.R
# Functions to work with lists
# Which list elements have the maximum (or minimum) values
# Revised for speed 20200725
which.pmax <- function(x, maximum = TRUE) {
# Start with NA indices, -Inf (or Inf) working values, and a record of NA values
iiNA <- tmp <- imax <- x[[1]]
imax[] <- NA
if(maximum) tmp[] <- -Inf else tmp[] <- Inf
iiNA[] <- 0
# Loop over elements of x
for(i in seq_along(x)) {
# Find values that are greater (or lesser) than working values
if(maximum) iimax <- x[[i]] > tmp
else iimax <- x[[i]] < tmp
# Keep NAs out
iNA <- is.na(iimax)
iiNA[iNA] <- 1
iimax[iNA] <- FALSE
# Save the indices and update working values
imax[iimax] <- i
tmp[iimax] <- x[[i]][iimax]
}
imax[iiNA == 1] <- NA
# Keep attributes from x
mostattributes(imax) <- attributes(x[[1]])
imax
}
### Unexported functions ###
lsum <- function(x,y) {
# Sum up the respective elements of lists
# x and y to give list z of the same length
z <- x
for(i in 1:length(x)) z[[i]] <- x[[i]] + y[[i]]
return(z)
}
pprod <- function(x,y) {
# Multiply each element of vector y
# by corresponding value in list x
pfun <- function(i) x[[i]]*y[i]
lapply(1:length(y),pfun)
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/util.list.R
|
# CHNOSZ/util.misc.R
# Some utility functions for the CHNOSZ package
# speciate/thermo.R 20051021 jmd
dPdTtr <- function(ispecies, ispecies2 = NULL) {
# Calculate dP/dT for a polymorphic transition
# (argument is index of the lower-T phase)
thermo <- get("thermo", CHNOSZ)
if(is.null(ispecies2)) ispecies2 <- ispecies + 1
# Use OBIGT2eos to ensure that all parameters are in Joules 20240211
pars <- OBIGT2eos(thermo$OBIGT[c(ispecies, ispecies2), ], "cgl", fixGHS = TRUE, toJoules = TRUE)
# If these aren't the same mineral, we shouldn't be here
if(as.character(pars$name[1]) != as.character(pars$name[2])) stop("different names for species ", ispecies, " and ", ispecies2)
# The special handling for quartz and coesite interfere with this function,
# so we convert to uppercase names to prevent cgl() from calling quartz_coesite()
pars$name <- toupper(pars$name)
props <- cgl(c("G", "S", "V"), pars, P = 0, T = thermo$OBIGT$z.T[ispecies])
# The G's should be the same ...
#if(abs(props[[2]]$G - props[[1]]$G) > 0.1) warning('dP.dT: inconsistent values of G for different polymorphs of ',ispecies,call. = FALSE)
dP.dT <- convert( ( props[[2]]$S - props[[1]]$S ) / ( props[[2]]$V - props[[1]]$V ), 'cm3bar' )
return(dP.dT)
}
Ttr <- function(ispecies, ispecies2 = NULL, P = 1, dPdT = NULL) {
# Calculate polymorphic transition temperature for given P
TtrPr <- get("thermo", CHNOSZ)$OBIGT$z.T[ispecies]
# The constant slope, dP/dT
if(is.null(dPdT)) dPdT <- dPdTtr(ispecies, ispecies2)
Pr <- 1
TtrPr + (P - Pr) / dPdT
}
GHS_Tr <- function(ispecies, Htr) {
# Calculate G, H, and S at Tr for cr2, cr3, ... phases 20170301
# Htr: enthalpy(ies) of transition
# ispecies: the species index for cr (the lowest-T phase)
thisinfo <- info(ispecies)
name <- thisinfo$name
# Start from Tr (T=298.15 K)
Tprev <- 298.15
# The GHS at T
Gf <- thisinfo$G
Hf <- thisinfo$H
S <- thisinfo$S
# Where to store the calculated GHS at Tr
Gf_Tr <- Hf_Tr <- S_Tr <- numeric()
for(i in 1:(length(Htr)+1)) {
# Check that we have the correct one of cr, cr2, cr3, ...
if(i == 1) thiscr <- "cr" else thiscr <- paste0("cr", i)
if(thisinfo$state != thiscr | thisinfo$name != name) stop(paste("species", thisis, "is not", name, thiscr))
# If we're above cr (lowest-T), calculate the equivalent GHS at Tr
if(i > 1) {
# Set the starting GHS to 0 (in case they're NA - we only need the increments over temperature)
thisinfo$G <- thisinfo$H <- thisinfo$S <- 0
# The HS increments from 298.15 to Ttr
HSinc <- cgl(c("H", "S"), parameters = thisinfo, T = c(298.15, Ttr))
Hf_Tr <- c(Hf_Tr, Hf - diff(HSinc[[1]]$H))
S_Tr <- c(S_Tr, S - diff(HSinc[[1]]$S))
# Plug in the calculated S_Tr to calculate the G increment correctly
thisinfo$S <- tail(S_Tr, 1)
Ginc <- cgl("G", parameters = thisinfo, T = c(298.15, Ttr))
Gf_Tr <- c(Gf_Tr, Gf - diff(Ginc[[1]]$G))
}
# The temperature of the next transition
Ttr <- thisinfo$T
# The GHS increments from Tprev to Ttr
GHCinc <- cgl(c("G", "H", "S"), parameters = thisinfo, T = c(Tprev, Ttr))
# The GHS + transition at Tr
Gf <- Gf + diff(GHCinc[[1]]$G)
Hf <- Hf + diff(GHCinc[[1]]$H) + Htr[i]
S <- S + diff(GHCinc[[1]]$S) + Htr[i] / Ttr
# Prepare next phase
thisis <- ispecies + i
thisinfo <- info(thisis)
Tprev <- Ttr
}
list(Gf_Tr = Gf_Tr, Hf_Tr = Hf_Tr, S_Tr = S_Tr)
}
unitize <- function(logact = NULL,length = NULL,logact.tot = 0) {
# Scale the logarithms of activities given in loga
# so that the logarithm of total activity of residues
# is zero (i.e. total activity of residues is one),
# or some other value set in loga.tot.
# length indicates the number of residues in each species.
# If loga is NULL, take the logarithms of activities from the current species definition
# If any of those species are proteins, get their lengths using protein.length
thermo <- get("thermo", CHNOSZ)
if(is.null(logact)) {
if(is.null(thermo$species)) stop("loga is NULL and no species are defined")
ts <- thermo$species
logact <- ts$logact
length <- rep(1,length(logact))
ip <- grep("_",ts$name)
if(length(ip) > 0) length[ip] <- protein.length(ts$name[ip])
}
# The lengths of the species
if(is.null(length)) length <- 1
length <- rep(length,length.out = length(logact))
# Remove the logarithms
act <- 10^logact
# The total activity
act.tot <- sum(act*length)
# The target activity
act.to.get <- 10^logact.tot
# The factor to apply
act.fact <- act.to.get/act.tot
# Apply the factor
act <- act * act.fact
# Take the logarithms
log10(act)
# Done!
}
### Unexported functions ###
# Return, in order, which column(s) of species all have non-zero values.
which.balance <- function(species) {
# Find the first basis species that
# is present in all species of interest
# ... it can be used to balance the system
nbasis <- function(species) return(ncol(species)-4)
ib <- NULL
nb <- 1
nbs <- nbasis(species)
for(i in 1:nbs) {
coeff <- species[,i]
if(length(coeff) == length(coeff[coeff != 0])) {
ib <- c(ib,i)
nb <- nb + 1
} else ib <- c(ib,NA)
}
return(ib[!is.na(ib)])
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/util.misc.R
|
# CHNOSZ/util.plot.R
# Functions to create and modify plots
thermo.plot.new <- function(xlim,ylim,xlab,ylab,cex = par('cex'),mar = NULL,lwd = par('lwd'),side = c(1,2,3,4),
mgp = c(1.7,0.3,0),cex.axis = par('cex'),col = par('col'),yline = NULL,axs = 'i',plot.box = TRUE,
las = 1,xline = NULL, grid = "", col.grid = "gray", ...) {
# Start a new plot with some customized settings
thermo <- get("thermo", CHNOSZ)
# 20120523 store the old par in thermo()$opar
if(is.null(thermo$opar)) {
thermo$opar <- par(no.readonly = TRUE)
assign("thermo", thermo, CHNOSZ)
}
# 20090324 mar handling: NULL - a default setting; NA - par's setting
# 20090413 changed mar of top side from 2 to 2.5
marval <- c(3, 3.5, 2.5, 1)
if(identical(mar[1], NA)) marval <- par("mar")
# 20181007 get mar from the current device (if it exists) and par("mar") is not the default
if(!is.null(dev.list())) {
if(!identical(par("mar"), c(5.1, 4.1, 4.1, 2.1))) marval <- par("mar")
}
# Assign marval to mar if the latter is NULL or NA
if(!is.numeric(mar)) mar <- marval
par(mar = mar,mgp = mgp,tcl = 0.3,las = las,xaxs = axs,yaxs = axs,cex = cex,lwd = lwd,col = col,fg = col, ...)
plot.new()
plot.window(xlim = xlim,ylim = ylim)
if(plot.box) box()
# Labels
if(is.null(xline)) xline <- mgp[1]
thermo.axis(xlab,side = 1,line = xline,cex = cex.axis,lwd = NULL)
if(is.null(yline)) yline <- mgp[1]
thermo.axis(ylab,side = 2,line = yline,cex = cex.axis,lwd = NULL)
# (optional) tick marks
if(1 %in% side) thermo.axis(NULL,side = 1,lwd = lwd, grid = grid, col.grid = col.grid, plot.line = !plot.box)
if(2 %in% side) thermo.axis(NULL,side = 2,lwd = lwd, grid = grid, col.grid = col.grid, plot.line = !plot.box)
if(3 %in% side) thermo.axis(NULL,side = 3,lwd = lwd, plot.line = !plot.box)
if(4 %in% side) thermo.axis(NULL,side = 4,lwd = lwd, plot.line = !plot.box)
}
label.plot <- function(x, xfrac = 0.07, yfrac = 0.93, paren = FALSE, italic = FALSE, ...) {
# Make a text label e.g., "(a)" in the corner of a plot
# xfrac, yfrac: fraction of axis where to put label (default top right)
# paren: put a parenthesis around the text, and italicize it?
if(italic) x <- substitute(italic(a), list(a = x))
if(paren) x <- substitute(group('(', a, ')'), list(a = x))
if(italic | paren) x <- as.expression(x)
pu <- par('usr')
text(pu[1]+xfrac*(pu[2]-pu[1]), pu[3]+yfrac*(pu[4]-pu[3]), labels = x, ...)
}
usrfig <- function() {
# Function to get the figure limits in user coordinates
# Get plot limits in user coordinates (usr) and as fraction [0,1] of figure region (plt)
xusr <- par('usr')[1:2]; yusr <- par('usr')[3:4]
xplt <- par('plt')[1:2]; yplt <- par('plt')[3:4]
# Linear model to calculate figure limits in user coordinates
xlm <- lm(xusr ~ xplt); ylm <- lm(yusr ~ yplt)
xfig <- predict.lm(xlm, data.frame(xplt = c(0, 1)))
yfig <- predict.lm(ylm, data.frame(yplt = c(0, 1)))
return(list(x = xfig, y = yfig))
}
label.figure <- function(x, xfrac = 0.05, yfrac = 0.95, paren = FALSE, italic = FALSE, ...) {
# Function to add labels outside of the plot region 20151020
f <- usrfig()
# Similar to label.plot(), except we have to set xpd here
opar <- par(xpd = NA)
if(italic) x <- substitute(italic(a), list(a = x))
if(paren) x <- substitute(group('(',a,')'), list(a = x))
if(italic | paren) x <- as.expression(x)
text(f$x[1]+xfrac*(f$x[2]-f$x[1]), f$y[1]+yfrac*(f$y[2]-f$y[1]), labels = x, ...)
par(opar)
}
water.lines <- function(eout, which = c('oxidation','reduction'),
lty = 2, lwd = 1, col = par('fg'), plot.it = TRUE) {
# Draw water stability limits for Eh-pH, logfO2-pH, logfO2-T or Eh-T diagrams
# (i.e. redox variable is on the y axis)
# Get axes, T, P, and xpoints from output of affinity() or equilibrate()
if(missing(eout)) stop("'eout' (the output of affinity(), equilibrate(), or diagram()) is missing")
# Number of variables used in affinity()
nvar1 <- length(eout$vars)
# If these were on a transect, the actual number of variables is less
dim <- dim(eout$loga.equil[[1]]) # for output from equilibrate()
if(is.null(dim)) dim <- dim(eout$values[[1]]) # for output from affinity()
nvar2 <- length(dim)
# We only work on diagrams with 1 or 2 variables
if(!nvar1 %in% c(1, 2) | !nvar2 %in% c(1, 2)) return(NA)
# If needed, swap axes so redox variable is on y-axis
# Also do this for 1-D diagrams 20200710
if(is.na(eout$vars[2])) eout$vars[2] <- "nothing"
swapped <- FALSE
if(eout$vars[2] %in% c("T", "P", "nothing")) {
eout$vars <- rev(eout$vars)
eout$vals <- rev(eout$vals)
swapped <- TRUE
}
xaxis <- eout$vars[1]
yaxis <- eout$vars[2]
xpoints <- eout$vals[[1]]
# Make xaxis "nothing" if it is not pH, T, or P 20201110
# (so that horizontal water lines can be drawn for any non-redox variable on the x-axis)
if(!identical(xaxis, "pH") & !identical(xaxis, "T") & !identical(xaxis, "P")) xaxis <- "nothing"
# T and P are constants unless they are plotted on one of the axes
T <- eout$T
if(eout$vars[1] == "T") T <- envert(xpoints, "K")
P <- eout$P
if(eout$vars[1] == "P") P <- envert(xpoints, "bar")
# logaH2O is 0 unless given in eout$basis
iH2O <- match("H2O", rownames(eout$basis))
if(is.na(iH2O)) logaH2O <- 0 else logaH2O <- as.numeric(eout$basis$logact[iH2O])
# pH is 7 unless given in eout$basis or plotted on one of the axes
iHplus <- match("H+", rownames(eout$basis))
if(eout$vars[1] == "pH") pH <- xpoints
else if(!is.na(iHplus)) {
minuspH <- eout$basis$logact[iHplus]
# Special treatment for non-numeric value (happens when a buffer is used, even for another basis species)
if(can.be.numeric(minuspH)) pH <- -as.numeric(minuspH) else pH <- NA
}
else pH <- 7
# O2state is gas unless given in eout$basis
iO2 <- match("O2", rownames(eout$basis))
if(is.na(iO2)) O2state <- "gas" else O2state <- eout$basis$state[iO2]
# H2state is gas unles given in eout$basis
iH2 <- match("H2", rownames(eout$basis))
if(is.na(iH2)) H2state <- "gas" else H2state <- eout$basis$state[iH2]
# Where the calculated values will go
y.oxidation <- y.reduction <- NULL
if(xaxis %in% c("pH", "T", "P", "nothing") & yaxis %in% c("Eh", "pe", "O2", "H2")) {
# Eh/pe/logfO2/logaO2/logfH2/logaH2 vs pH/T/P
if('reduction' %in% which) {
logfH2 <- logaH2O # usually 0
if(yaxis == "H2") {
logK <- suppressMessages(subcrt(c("H2", "H2"), c(-1, 1), c("gas", H2state), T = T, P = P, convert = FALSE))$out$logK
# This is logfH2 if H2state == "gas", or logaH2 if H2state == "aq"
logfH2 <- logfH2 + logK
y.reduction <- rep(logfH2, length.out = length(xpoints))
} else {
logK <- suppressMessages(subcrt(c("H2O", "O2", "H2"), c(-1, 0.5, 1), c("liq", O2state, "gas"), T = T, P = P, convert = FALSE))$out$logK
# This is logfO2 if O2state == "gas", or logaO2 if O2state == "aq"
logfO2 <- 2 * (logK - logfH2 + logaH2O)
if(yaxis == "O2") y.reduction <- rep(logfO2, length.out = length(xpoints))
else if(yaxis == "Eh") y.reduction <- convert(logfO2, 'E0', T = T, P = P, pH = pH, logaH2O = logaH2O)
else if(yaxis == "pe") y.reduction <- convert(convert(logfO2, 'E0', T = T, P = P, pH = pH, logaH2O = logaH2O), "pe", T = T)
}
}
if('oxidation' %in% which) {
logfO2 <- logaH2O # usually 0
if(yaxis == "H2") {
logK <- suppressMessages(subcrt(c("H2O", "O2", "H2"), c(-1, 0.5, 1), c("liq", "gas", H2state), T = T, P = P, convert = FALSE))$out$logK
# This is logfH2 if H2state == "gas", or logaH2 if H2state == "aq"
logfH2 <- logK - 0.5*logfO2 + logaH2O
y.oxidation <- rep(logfH2, length.out = length(xpoints))
} else {
logK <- suppressMessages(subcrt(c("O2", "O2"), c(-1, 1), c("gas", O2state), T = T, P = P, convert = FALSE))$out$logK
# This is logfO2 if O2state == "gas", or logaO2 if O2state == "aq"
logfO2 <- logfO2 + logK
if(yaxis == "O2") y.oxidation <- rep(logfO2, length.out = length(xpoints))
else if(yaxis == "Eh") y.oxidation <- convert(logfO2, 'E0', T = T, P = P, pH = pH, logaH2O = logaH2O)
else if(yaxis == "pe") y.oxidation <- convert(convert(logfO2, 'E0', T = T, P = P, pH = pH, logaH2O = logaH2O), "pe", T = T)
}
}
} else return(NA)
# Now plot the lines
if(plot.it) {
if(swapped) {
if(nvar1 == 1 | nvar2 == 2) {
# Add vertical lines on 1-D diagram 20200710
abline(v = y.oxidation[1], lty = lty, lwd = lwd, col = col)
abline(v = y.reduction[1], lty = lty, lwd = lwd, col = col)
} else {
# xpoints above is really the ypoints
lines(y.oxidation, xpoints, lty = lty, lwd = lwd, col = col)
lines(y.reduction, xpoints, lty = lty, lwd = lwd, col = col)
}
} else {
lines(xpoints, y.oxidation, lty = lty, lwd = lwd, col = col)
lines(xpoints, y.reduction, lty = lty, lwd = lwd, col = col)
}
}
# Return the values
return(invisible(list(xpoints = xpoints, y.oxidation = y.oxidation, y.reduction = y.reduction, swapped = swapped)))
}
mtitle <- function(main, line = 0, spacing = 1, ...) {
# Make a possibly multi-line plot title
# Useful for including expressions on multiple lines
# 'line' is the margin line of the last (bottom) line of the title
len <- length(main)
for(i in 1:len) mtext(main[i], line = line + (len - i)*spacing, ...)
}
# Get colors for range of ZC values 20170206
ZC.col <- function(z) {
# Scale values to [1, 1000]
z <- z * 999/diff(range(z))
z <- round(z - min(z)) + 1
# Diverging (blue - light grey - red) palette
# dcol <- colorspace::diverge_hcl(1000, c = 100, l = c(50, 90), power = 1)
# Use precomputed values
file <- system.file("extdata/cpetc/bluered.txt", package = "CHNOSZ")
dcol <- read.table(file, as.is = TRUE)[[1]]
# Reverse the palette so red is at lower ZC (more reduced)
rev(dcol)[z]
}
# Function to add axes and axis labels to plots,
# with some default style settings (rotation of numeric labels)
# With the default arguments (no labels specified), it plots only the axis lines and tick marks
# (used by diagram() for overplotting the axis on diagrams filled with colors).
thermo.axis <- function(lab = NULL, side = 1:4,line = 1.5, cex = par('cex'), lwd = par('lwd'),
col = par('col'), grid = "", col.grid = "gray", plot.line = FALSE) {
if(!is.null(lwd)) {
for(thisside in side) {
## Get the positions of major tick marks
at <- axis(thisside,labels = FALSE,tick = FALSE)
# Get nicer divisions for axes that span exactly 15 units 20200719
if(thisside %in% c(1,3)) lim <- par("usr")[1:2]
if(thisside %in% c(2,4)) lim <- par("usr")[3:4]
if(abs(diff(lim)) == 15) at <- seq(lim[1], lim[2], length.out = 6)
if(abs(diff(lim)) == 1.5) at <- seq(lim[1], lim[2], length.out = 4)
# Make grid lines
if(grid %in% c("major", "both") & thisside == 1) abline(v = at, col = col.grid)
if(grid %in% c("major", "both") & thisside == 2) abline(h = at, col = col.grid)
## Plot major tick marks and numeric labels
do.label <- TRUE
if(missing(side) | (missing(cex) & thisside %in% c(3,4))) do.label <- FALSE
# col and col.ticks: plot the tick marks but no line (we make it with box() in thermo.plot.new()) 20190416
# mat: don't plot ticks at the plot limits 20190416
if(thisside %in% c(1, 3)) pat <- par("usr")[1:2]
if(thisside %in% c(2, 4)) pat <- par("usr")[3:4]
mat <- setdiff(at, pat)
if(plot.line) axis(thisside, at = mat, labels = FALSE, tick = TRUE, lwd = lwd, col.axis = col, col = col)
else axis(thisside, at = mat, labels = FALSE, tick = TRUE, lwd = lwd, col.axis = col, col = NA, col.ticks = col)
# Plot only the labels at all major tick points (including plot limits) 20190417
if(do.label) axis(thisside, at = at, tick = FALSE, col = col)
## Plot minor tick marks
# The distance between major tick marks
da <- abs(diff(at[1:2]))
# Distance between minor tick marks
di <- da / 4
if(!da %% 3) di <- da / 3
else if(da %% 2 | !(da %% 10)) di <- da / 5
# Number of minor tick marks
if(thisside %in% c(1,3)) {
ii <- c(1,2)
myasp <- par('xaxp')
} else {
ii <- c(3,4)
myasp <- par('yaxp')
}
myusr <- par('usr')[ii]
daxis <- abs(diff(myusr))
nt <- daxis / di + 1
## If nt isn't an integer, it probably
## means the axis limits don't correspond
## to major tick marks (expect problems)
##at <- seq(myusr[1],myusr[2],length.out = nt)
# Start from (bottom/left) of axis?
bl <- 1
#if(myasp[2] == myusr[2]) bl <- 2
# Is forward direction (top/right)?
tr <- 1
if(xor(myusr[2] < myusr[1] , bl == 2)) tr <- -1
#at <- myusr[bl] + tr * di * seq(0:(nt-1))
# Well all of that doesn't work in a lot of cases,
# where none of the axis limits correspond to
# major tick marks. perhaps the following will work
at <- myusr[1] + tr * di * (0:(nt-1))
# Apply an offset
axt <- axTicks(thisside)[1]
daxt <- (axt - myusr[1])/di
daxt <- (daxt-round(daxt))*di
at <- at + daxt
## Get the positions of major tick marks and make grid lines
if(grid %in% c("minor", "both") & thisside == 1) abline(v = at, col=col.grid, lty = 3)
if(grid %in% c("minor", "both") & thisside == 2) abline(h = at, col=col.grid, lty = 3)
tcl <- par('tcl') * 0.5
at <- setdiff(at, pat)
if(plot.line) axis(thisside, labels = FALSE, tick = TRUE, lwd = lwd, col.axis = col, at = at, tcl = tcl, col = col)
else axis(thisside, labels = FALSE, tick = TRUE, lwd = lwd, col.axis = col, at = at, tcl = tcl, col = NA, col.ticks = col)
}
}
# Rotate labels on side axes
for(thisside in side) {
if(thisside %in% c(2,4)) las <- 0 else las <- 1
if(!is.null(lab)) mtext(lab, side = thisside, line = line, cex = cex, las = las)
}
}
# Function to add transparency to given color 20220223
add.alpha <- function(col, alpha) {
x <- col2rgb(col)
newcol <- rgb(x[1], x[2], x[3], maxColorValue = 255)
newcol <- paste0(newcol, alpha)
newcol
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/util.plot.R
|
# CHNOSZ/util.protein.R
# MP90.cp: additive heat capacity from groups of Makhatadze and Privalov, 1990
MP90.cp <- function(protein, T) {
# T (temperature, degrees C), protein (name of protein)
# Returns heat capacity of protein (kJ/mol)
# using algorithm of Makhatadze and Privalov, 1990.
TMP <- c(5,25,50,75,100,125)
A.cp <- splinefun(TMP,c(175.7,166.7,156.2,144.7,134.6,124.1))
C.cp <- splinefun(TMP,c(225.4,237.6,250.8,260.7,268.2,276.1))
D.cp <- splinefun(TMP,c( 72.8, 89.0,106.2,124.5,140.7,154.3))
E.cp <- splinefun(TMP,c(168.3,179.0,192.0,203.7,211.4,217.8))
F.cp <- splinefun(TMP,c(395.7,383.0,370.3,358.4,348.3,339.6))
G.cp <- splinefun(TMP,c( 82.3, 78.0, 71.7, 66.4, 59.7, 53.9))
H.cp <- splinefun(TMP,c(205.7,179.6,177.2,179.6,187.1,196.8))
I.cp <- splinefun(TMP,c(406.8,402.3,397.1,390.8,386.0,380.8))
K.cp <- splinefun(TMP,c(328.8,332.5,334.0,337.5,339.4,343.6))
L.cp <- splinefun(TMP,c(385.9,381.7,377.8,372.9,369.4,365.5))
M.cp <- splinefun(TMP,c(197.1,175.9,158.1,150.3,148.1,143.9))
N.cp <- splinefun(TMP,c( 72.9, 88.8,109.8,125.2,140.5,154.2))
P.cp <- splinefun(TMP,c(214.6,177.7,152.3,142.8,135.6,130.1))
Q.cp <- splinefun(TMP,c(168.0,180.2,193.4,203.3,210.8,218.7))
R.cp <- splinefun(TMP,c(204.6,273.4,305.8,315.1,318.7,318.5))
S.cp <- splinefun(TMP,c( 75.6, 81.2, 85.7, 91.4, 97.3,102.1))
T.cp <- splinefun(TMP,c(194.2,184.5,182.2,186.5,199.0,216.2))
V.cp <- splinefun(TMP,c(324.6,314.4,305.0,294.7,285.7,269.6))
W.cp <- splinefun(TMP,c(471.2,458.5,445.8,433.9,423.8,415.1))
Y.cp <- splinefun(TMP,c(310.6,301.7,295.2,294.5,300.1,304.0))
AA.cp <- splinefun(TMP,c(-158.3,-90.4,-21.5,-32.3,-92.4,-150.0))
UPBB.cp <- splinefun(TMP,c(3.7,15.2,26.2,29.8,33.7,33.7))
cnew <- numeric()
for(i in 1:length(T)) {
Ti <- T[i]
cp <- c(A.cp(Ti),C.cp(Ti),D.cp(Ti),E.cp(Ti),F.cp(Ti),
G.cp(Ti),H.cp(Ti),I.cp(Ti),K.cp(Ti),L.cp(Ti),
M.cp(Ti),N.cp(Ti),P.cp(Ti),Q.cp(Ti),R.cp(Ti),
S.cp(Ti),T.cp(Ti),V.cp(Ti),W.cp(Ti),Y.cp(Ti))
# Get the protein composition
tt <- pinfo(pinfo(protein))[,6:25]
cnew <- c(cnew, sum(cp * as.numeric(tt)) + sum(as.numeric(tt)) * UPBB.cp(Ti))
}
return(cnew)
}
### Unexported functions ###
group.formulas <- function() {
# Return a matrix with chemical formulas of residues
# Memoize this 20200509
## Names of the sidechain groups
#groups <- paste("[", aminoacids(3), "]", sep = "")
## The indices of H2O, sidechain groups, and [UPBB]
#ig <- suppressMessages(info(c("H2O", groups, "[UPBB]")))
## Their formulas
#A <- i2A(ig)
A <- structure(c(0, 1, 1, 2, 3, 7, 0, 4, 4, 4, 4, 3, 2, 3, 3, 4, 1,
2, 3, 9, 7, 2, 2, 3, 3, 3, 5, 7, 1, 5, 9, 10, 9, 7, 4, 5, 6,
10, 3, 5, 7, 8, 7, 2, 0, 0, 0, 0, 0, 0, 0, 2, 0, 1, 0, 0, 1,
0, 1, 3, 0, 0, 0, 1, 0, 1, 1, 0, 0, 2, 2, 0, 0, 0, 0, 0, 0, 0,
1, 0, 1, 0, 1, 1, 0, 0, 1, 1, 0, 0, 1, 0, 0, 0, 0, 0, 0, 0, 0,
1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0), .Dim = c(22L, 5L), .Dimnames = list(
c("water", "[Ala]", "[Cys]", "[Asp]", "[Glu]", "[Phe]", "[Gly]",
"[His]", "[Ile]", "[Lys]", "[Leu]", "[Met]", "[Asn]", "[Pro]",
"[Gln]", "[Arg]", "[Ser]", "[Thr]", "[Val]", "[Trp]", "[Tyr]",
"[UPBB]"), c("C", "H", "N", "O", "S")))
# Add [UPBB] to the sidechain groups to get residues
out <- A[1:21,]
out[2:21,] <- t(t(A) + A[22,])[2:21,]
# Make "H2O" not "water"
rownames(out)[1] <- "H2O"
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/util.protein.R
|
# CHNOSZ/util.seq.R
# Functions to work with sequence data
aminoacids <- function(nchar = 1, which = NULL) {
# Return the abbreviations or names of the amino acids
# The following are all in the same order as thermo()$protein
# The single-letter codes
aa1 <- c("A", "C", "D", "E", "F", "G", "H", "I", "K", "L",
"M", "N", "P", "Q", "R", "S", "T", "V", "W", "Y")
# The 3-letter codes
aa3 <- c("Ala", "Cys", "Asp", "Glu", "Phe", "Gly", "His", "Ile", "Lys", "Leu",
"Met", "Asn", "Pro", "Gln", "Arg", "Ser", "Thr", "Val", "Trp", "Tyr")
# Names of the neutral amino acids
aaneutral <- c("alanine", "cysteine", "aspartic acid", "glutamic acid", "phenylalanine",
"glycine", "histidine", "isoleucine", "lysine", "leucine", "methionine", "asparagine",
"proline", "glutamine", "arginine", "serine", "threonine", "valine", "tryptophan", "tyrosine")
# Names of the amino acids with ionized side chains
aacharged <- c("alanine", "cysteinate", "aspartate", "glutamate", "phenylalanine",
"glycine", "histidinium", "isoleucine", "lysinium", "leucine", "methionine", "asparagine",
"proline", "glutamine", "argininium", "serine", "threonine", "valine", "tryptophan", "tyrosinate")
# Defaults are in the same order as in thermo()$protein
if(is.null(which)) which <- aa1
# Figure out which amino acids are wanted (can use 1- or 3-letter codes, or neutral names)
if(all(nchar(which) == 1)) iaa <- match(which, aa1)
else if(all(nchar(which) == 3)) iaa <- match(which, aa3)
else iaa <- match(which, aaneutral)
# Return the desired abbreviations or names
if(nchar == 1) return(aa1[iaa])
else if(nchar == 3) return(aa3[iaa])
else if(nchar == "") return(aaneutral[iaa])
else if(nchar == "Z") return(aacharged[iaa])
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/util.seq.R
|
# CHNOSZ/util.units.R
# Set units and convert values between units
P.units <- function(units = NULL) {
## Change units of pressure or list the current one
# Show the current units, if none is specified
if(is.null(units)) return(get("thermo", CHNOSZ)$opt$P.units)
# Argument handling
units <- tolower(units)
if(!units %in% c("bar", "mpa")) stop("units of pressure must be either bar or MPa")
# Set the units and return them
if(units == "bar") with(CHNOSZ, thermo$opt$P.units <- "bar")
if(units == "mpa") with(CHNOSZ, thermo$opt$P.units <- "MPa")
message("changed pressure units to ", get("thermo", CHNOSZ)$opt$P.units)
}
T.units <- function(units = NULL) {
## Change units of temperature or list the current one
# Show the current units, if none is specified
if(is.null(units)) return(get("thermo", CHNOSZ)$opt$T.units)
# Argument handling
units <- tolower(units)
if(!units %in% c("c", "k")) stop("units of temperature must be either C or K")
# Set the units and return them
if(units == "c") with(CHNOSZ, thermo$opt$T.units <- "C")
if(units == "k") with(CHNOSZ, thermo$opt$T.units <- "K")
message("changed temperature units to ", get("thermo", CHNOSZ)$opt$T.units)
}
E.units <- function(units = NULL) {
## Change units of energy or list the current one
# Show the current units, if none is specified
if(is.null(units)) return(get("thermo", CHNOSZ)$opt$E.units)
# Argument handling
units <- tolower(units)
if(!units %in% c("cal", "j")) stop("units of energy must be either cal or J")
# Set the units and return them
if(units == "cal") with(CHNOSZ, thermo$opt$E.units <- "cal")
if(units == "j") with(CHNOSZ, thermo$opt$E.units <- "J")
message("changed energy units to ", get("thermo", CHNOSZ)$opt$E.units)
}
convert <- function(value, units, T = 298.15,
P = 1, pH = 7, logaH2O = 0) {
# Converts value(s) to the specified units
# Process a list value if it's the output from solubility 20190525
if(is.list(value) & !is.data.frame(value)) {
if(!isTRUE(value$fun %in% c("solubility", "solubilities"))) stop("'value' is a list but is not the output from solubility()")
if(!is.character(units)) stop("please specify a character argument for the destination units (e.g. ppm or logppm)")
# Determine the element from 'balance' or 'in.terms.of', if it's available
element <- value$in.terms.of
if(is.null(element)) element <- value$balance
grams.per.mole <- mass(element)
message(paste("solubility: converting to", units, "by weight using the mass of", element))
ppfun <- function(loga, units, grams.per.mole) {
# Exponentiate loga to get molality
moles <- 10^loga
# Convert moles to mass (g)
grams <- moles * grams.per.mole
# Convert grams to ppb, ppm, or ppt
ppx <- NULL
# 1 ppt = 1 g / kg H2O
# 1 ppm = 1 mg / kg H2O
if(grepl("ppt", units)) ppx <- grams * 1e0
if(grepl("ppm", units)) ppx <- grams * 1e3
if(grepl("ppb", units)) ppx <- grams * 1e6
if(is.null(ppx)) stop(paste("units", units, "not available for conversion"))
# Use the logarithm if specified
if(grepl("log", units)) ppx <- log10(ppx)
ppx
}
# Do the conversion for the conserved basis species, then each species
value$loga.balance <- ppfun(value$loga.balance, units, grams.per.mole)
value$loga.equil <- lapply(value$loga.equil, ppfun, units = units, grams.per.mole = grams.per.mole)
# Identify the units in the function text
value$fun <- paste(value$fun, units, sep = ".")
# Return the updated object
return(value)
}
### Argument handling for non-list value
if(is.null(value)) return(NULL)
if(!is.character(units)) stop(paste('convert: please specify',
'a character argument for the destination units.\n',
'possibilities include (G or logK) (C or K) (J or cal) (cm3bar or calories) (Eh or pe)\n',
'or their lowercase equivalents.\n'), call. = FALSE)
Units <- units # For the possible message to user
units <- tolower(units)
# Tests and calculations for the specified units
if(units %in% c('c', 'k')) {
CK <- 273.15
if(units == 'k') value <- value + CK
if(units == 'c') value <- value - CK
}
else if(units[1] %in% c('j', 'cal')) {
Jcal <- 4.184
if(units == 'j') value <- value * Jcal
if(units == 'cal') value <- value / Jcal
}
else if(units %in% c('g', 'logk')) {
# Gas constant
#R <- 1.9872 # cal K^-1 mol^-1 Value used in SUPCRT92
#R <- 8.314445 # = 1.9872 * 4.184 J K^-1 mol^-1 20220325
R <- 8.314463 # https://physics.nist.gov/cgi-bin/cuu/Value?r 20230630
if(units == 'logk') value <- value / (-log(10) * R * T)
if(units == 'g') value <- value * (-log(10) * R * T)
}
else if(units %in% c('cm3bar', 'joules')) {
if(units == 'cm3bar') value <- value * 10
if(units == 'joules') value <- value / 10
}
else if(units %in% c('eh', 'pe')) {
R <- 0.00831470
F <- 96.4935
if(units == 'pe') value <- value * F / ( log(10) * R * T )
if(units == 'eh') value <- value * ( log(10) * R * T ) / F
}
else if(units %in% c('bar', 'mpa')) {
barmpa <- 10
if(units == 'mpa') value <- value / barmpa
if(units == 'bar') value <- value * barmpa
}
else if(units %in% c('e0', 'logfo2')) {
# Convert between Eh and logfO2
supcrt.out <- suppressMessages(subcrt(c("H2O", "oxygen", "H+", "e-"), c(-1, 0.5, 2, 2), T = T, P = P, convert = FALSE))
if(units == 'logfo2') value <- 2*(supcrt.out$out$logK + logaH2O + 2*pH + 2*(convert(value, 'pe', T = T)))
if(units == 'e0') value <- convert(( -supcrt.out$out$logK - 2*pH + value/2 - logaH2O )/2, 'Eh', T = T)
}
else cat(paste('convert: no conversion to ', Units, ' found.\n', sep = ''))
return(value)
}
### Unexported functions ###
outvert <- function(value, units) {
# Converts the given value from the given units to those specified in thermo()$opt
units <- tolower(units)
opt <- get("thermo", CHNOSZ)$opt
if(units %in% c("c", "k")) {
if(units == "c" & opt$T.units == "K") return(convert(value, "k"))
if(units == "k" & opt$T.units == "C") return(convert(value, "c"))
}
if(units %in% c("j", "cal")) {
if(units == "j" & opt$E.units == "cal") return(convert(value, "cal"))
if(units == "cal" & opt$E.units == "J") return(convert(value, "j"))
}
if(units %in% c("bar", "mpa")) {
if(units == "mpa" & opt$P.units == "bar") return(convert(value, "bar"))
if(units == "bar" & opt$P.units == "MPa") return(convert(value, "mpa"))
}
return(value)
}
envert <- function(value, units) {
# Convert values to the specified units
# from those given in thermo()$opt
if(!is.numeric(value[1])) return(value)
units <- tolower(units)
opt <- get("thermo", CHNOSZ)$opt
if(units %in% c('c', 'k', 't.units')) {
if(units == 'c' & opt$T.units == 'K') return(convert(value, 'c'))
if(units == 'k' & opt$T.units == 'C') return(convert(value, 'k'))
}
if(units %in% c('j', 'cal', 'e.units')) {
if(units == 'j' & opt$T.units == 'Cal') return(convert(value, 'j'))
if(units == 'cal' & opt$T.units == 'J') return(convert(value, 'cal'))
}
if(units %in% c('bar', 'mpa', 'p.units')) {
if(units == 'mpa' & opt$P.units == 'bar') return(convert(value, 'mpa'))
if(units == 'bar' & opt$P.units == 'MPa') return(convert(value, 'bar'))
}
return(value)
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/util.units.R
|
# CHNOSZ/util.water.R
WP02.auxiliary <- function(property='rho.liquid',T=298.15) {
# Auxiliary equations for liquid-vapor phase boundary
# From Wagner and Pruss, 2002
# Critical point
T.critical <- 647.096 # K
P.critical <- 22.064 # MPa
rho.critical <- 322 # kg m-3
if(property %in% c("P.sigma","dP.sigma.dT")) {
# Vapor pressure
V <- 1 - T / T.critical # theta (dimensionless)
a1 <- -7.85951783
a2 <- 1.84408259
a3 <- -11.7866497
a4 <- 22.6807411
a5 <- -15.9618719
a6 <- 1.80122502
ln.P.sigma.P.critical <- T.critical / T *
( a1*V + a2*V^1.5 + a3*V^3 + a4*V^3.5 + a5*V^4 + a6*V^7.5 )
P.sigma <- P.critical * exp(ln.P.sigma.P.critical)
if(property=="dP.sigma.dT") out <- - P.sigma / T * ( ln.P.sigma.P.critical +
a1 + 1.5*a2*V^0.5 + 3*a3*V^2 + 3.5*a4*V^2.5 + 4*a5*V^3 + 7.5*a6*V^6.5 )
else out <- P.sigma
} else if(property=="rho.liquid") {
# Saturated liquid density
V <- 1 - T / T.critical
b1 <- 1.99274064
b2 <- 1.09965342
b3 <- -0.510839303
b4 <- -1.75493479
b5 <- -45.5170352
b6 <- -6.74694450E5
rho.liquid <- rho.critical * (
1 + b1*V^(1/3) + b2*V^(2/3) + b3*V^(5/3) + b4*V^(16/3) + b5*V^(43/3) + b6*V^(110/3) )
out <- rho.liquid
} else if(property=="rho.vapor") {
# Saturated vapor density
V <- 1 - T / T.critical
c1 <- -2.03150240
c2 <- -2.68302940
c3 <- -5.38626492
c4 <- -17.2991605
c5 <- -44.7586581
c6 <- -63.9201063
rho.vapor <- rho.critical * exp (
c1*V^(2/6) + c2*V^(4/6) + c3*V^(8/6) + c4*V^(18/6) + c5*V^(37/6) + c6*V^(71/6) )
out <- rho.vapor
} else stop(paste('i can not calculate',property))
return(out)
}
# Return a density in kg m-3
# corresponding to the given pressure (bar) and temperature (K)
rho.IAPWS95 <- function(T=298.15, P=1, state="", trace=0) {
# Function for which to find a zero
dP <- function(rho, T, P.MPa) IAPWS95("P", rho=rho, T=T)[, 1] - P.MPa
# Convert bar to MPa
P.MPa <- convert(P, "MPa")
rho <- numeric()
T.critical <- 647.096 # K
P.critical <- 22.064 # MPa
for(i in 1:length(T)) {
Psat <- WP02.auxiliary("P.sigma", T[i])
if(T[i] > T.critical) {
# Above critical temperature
interval <- c(0.1, 1)
extendInt <- "upX"
if(trace > 0) message("supercritical (T) ", appendLF=FALSE)
} else if(P.MPa[i] > P.critical) {
# Above critical pressure
rho.sat <- WP02.auxiliary("rho.liquid", T=T[i])
interval <- c(rho.sat, rho.sat + 1)
extendInt <- "upX"
if(trace > 0) message("supercritical (P) ", appendLF=FALSE)
} else if(P.MPa[i] <= 0.9999*Psat) {
# Steam
rho.sat <- WP02.auxiliary("rho.vapor", T=T[i])
interval <- c(rho.sat*0.1, rho.sat)
extendInt <- "upX"
if(trace > 0) message("steam ", appendLF=FALSE)
} else if(P.MPa[i] >= 1.00005*Psat) {
# Water
rho.sat <- WP02.auxiliary("rho.liquid", T=T[i])
interval <- c(rho.sat, rho.sat + 1)
extendInt <- "upX"
if(trace > 0) message("water ", appendLF=FALSE)
} else if(!state %in% c("liquid", "vapor")) {
# We're close to the saturation curve;
# Calculate rho and G for liquid and vapor and return rho for stable phase
if(trace > 0) message("close to saturation; trying liquid and vapor")
rho.liquid <- rho.IAPWS95(T[i], P[i], state="liquid", trace=trace)
rho.vapor <- rho.IAPWS95(T[i], P[i], state="vapor", trace=trace)
G.liquid <- IAPWS95("G", rho=rho.liquid, T=T[i])
G.vapor <- IAPWS95("G", rho=rho.vapor, T=T[i])
if(G.liquid < G.vapor) {
this.rho <- rho.liquid
if(trace > 0) message(paste0("G.liquid(", G.liquid, ") < G.vapor(", G.vapor, ")"))
} else {
this.rho <- rho.vapor
if(trace > 0) message(paste0("G.vapor(", G.vapor, ") < G.liquid (", G.liquid, ")"))
}
rho <- c(rho, this.rho)
next
} else {
# We are looking at a specific state
if(trace > 0) message(paste("specified state:", state, " "), appendLF=FALSE)
if(state=="vapor") rho0 <- WP02.auxiliary("rho.vapor", T[i])
else if(state=="liquid") rho0 <- WP02.auxiliary("rho.liquid", T[i])
# A too-big range may cause problems e.g.
# interval <- c(rho0*0.9, rho0*1.1) fails for T=253.15, P=1
interval <- c(rho0*0.95, rho0*1.05)
# If P on the initial interval are both higher or lower than target P,
# set the direction of interval extension
P.init <- IAPWS95("P", rho=interval, T=c(T[i], T[i]))[, 1]
if(all(P.init < P.MPa[i])) extendInt <- "downX"
else if(all(P.init > P.MPa[i])) extendInt <- "upX"
else extendInt <- "yes"
}
if(trace > 0) message(paste0("T=", T[i], " P=", P[i], " rho=[", interval[1], ",", interval[2], "]"))
this.rho <- try(uniroot(dP, interval, extendInt=extendInt, trace=trace, T=T[i], P.MPa=P.MPa[i])$root, TRUE)
if(!is.numeric(this.rho)) {
warning("rho.IAPWS95: problems finding density at ", T[i], " K and ", P[i], " bar", call.=FALSE)
this.rho <- NA
}
rho <- c(rho, this.rho)
}
return(rho)
}
water.AW90 <- function(T=298.15,rho=1000,P=0.1) {
# Equations for the dielectric constant of water
# from Archer and Wang, 1990
# T in K
# rho in kg m-3
# p in MPa
# Table 2
b <- c(-4.044525E-2, 103.6180 , 75.32165 ,
-23.23778 ,-3.548184 ,-1246.311 ,
263307.7 ,-6.928953E-1,-204.4473)
alpha <- 18.1458392E-30 # m^3
#alpha <- 14.7E-30
mu <- 6.1375776E-30 # C m
N.A <- 6.0221367E23 # mol-1
k <- 1.380658E-23 # Boltzmann constant, J K-1
M <- 0.0180153 # kg mol-1
rho.0 <- 1000 # kg m-3
# Equation 1
epsilon.0 <- 8.8541878E-12 # Permittivity of vacuum, C^2 J-1 m-1
#epsfun.lhs <- function(e) (e-1)*(2*e+1)/(9*e)
epsfun.rhs <- function(T,V.m) N.A*(alpha+mufun()/(3*epsilon.0*k*T))/(3*V.m)
#epsfun <- function(e,T,V.m) epsfun.lhs(e) - epsfun.rhs(T,V.m)
mufun <- function() gfun()*mu^2
gfun <- function() rhofun()*rho/rho.0 + 1
# Equation 3
rhofun <- function() b[1]*P*T^-1 + b[2]*T^-0.5 + b[3]*(T-215)^-1 +
b[4]*(T-215)^-0.5 + b[5]*(T-215)^-0.25 +
exp(b[6]*T^-1 + b[7]*T^-2 + b[8]*P*T^-1 + b[9]*P*T^-2)
epsilon <- function(T,rho) {
#tu <- try(uniroot(epsfun,c(1E-1,1E3),T=T,V.m=M/rho)$root,TRUE)
epspoly <- function() epsfun.rhs(T,V.m=M/rho)
tu <- (9*epspoly() + 1 + ((9*epspoly()+1)*(9*epspoly()+1) + 8)^0.5) / 4 #Marc Neveu added 4/24/2013
if(!is.numeric(tu)) {
warning('water.AW90: no root for density at ',T,' K and ',rho,' kg m-3.',call.=FALSE,immediate.=TRUE)
tu <- NA
}
return(tu)
}
# Get things into the right length
our.T <- T; our.rho <- rho; our.P <- P
t <- numeric()
for(i in 1:length(our.T)) {
T <- our.T[i]
rho <- our.rho[i]
P <- our.P[i]
t <- c(t,epsilon(T,rho))
}
return(t)
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/util.water.R
|
# CHNOSZ/water.R
# Calculate thermodynamic and electrostatic properties of H2O
# 20061016 jmd
water <- function(property = NULL, T = 298.15, P = "Psat", P1 = TRUE) {
# Calculate the properties of liquid H2O as a function of T and P
# T in Kelvin, P in bar
if(is.null(property)) return(get("thermo", CHNOSZ)$opt$water)
# Set water option
if(length(property) == 1 & any(property %in% c("SUPCRT", "SUPCRT92", "IAPWS", "IAPWS95", "DEW"))) {
# Change references 20200629
if(property %in% c("SUPCRT", "SUPCRT92")) {
suppressMessages(mod.OBIGT("water", ref1 = "HGK84"))
suppressMessages(mod.OBIGT("water", ref2 = "JOH92"))
} else if(property %in% c("IAPWS", "IAPWS95")) {
suppressMessages(mod.OBIGT("water", ref1 = "WP02"))
suppressMessages(mod.OBIGT("water", ref2 = NA))
} else if(property == "DEW") {
suppressMessages(mod.OBIGT("water", ref1 = "SHA14"))
suppressMessages(mod.OBIGT("water", ref2 = NA))
}
oldwat <- thermo()$opt$water
thermo("opt$water" = property)
message(paste("water: setting water model to", property))
return(invisible(oldwat))
}
# Make T and P equal length
if(!identical(P, "Psat")) {
if(length(P) < length(T)) P <- rep(P, length.out = length(T))
else if(length(T) < length(P)) T <- rep(T, length.out = length(P))
}
wopt <- get("thermo", CHNOSZ)$opt$water
if(grepl("SUPCRT", wopt)) {
# Change 273.15 K to 273.16 K (needed for water.SUPCRT92 at Psat)
if(identical(P, "Psat")) T[T == 273.15] <- 273.16
# Get properties using SUPCRT92
w.out <- water.SUPCRT92(property, T, P, P1)
}
if(grepl("IAPWS", wopt)) {
# Get properties using IAPWS-95
w.out <- water.IAPWS95(property, T, P)
}
if(grepl("DEW", wopt)) {
# Use the Deep Earth Water (DEW) model
w.out <- water.DEW(property, T, P)
}
w.out
}
water.SUPCRT92 <- function(property = NULL, T = 298.15, P = 1, P1 = TRUE) {
### Interface to H2O92D.f: FORTRAN subroutine taken from
### SUPCRT92 for calculating the thermodynamic and
### electrostatic properties of H2O.
## We restrict the calculations to liquid water
## except for getting Psat (vapor-liquid saturation
## pressure as a function of T>100 C). 20071213 jmd
available_properties <- c("A", "G", "S", "U", "H", "Cv", "Cp",
"Speed", "alpha", "beta", "epsilon", "visc",
"tcond", "surten", "tdiff", "Prndtl", "visck", "albe",
"ZBorn", "YBorn", "QBorn", "daldT", "XBorn",
"V", "rho", "Psat", "E", "kT",
"A_DH", "B_DH")
if(is.null(property)) return(available_properties)
# Check for availability of properties
iprop <- match(property, available_properties)
if(any(is.na(iprop))) stop(paste("property(s) not available:", paste(property[is.na(iprop)], collapse = " ")))
# Make sure Psat in properties comes with isat = 1
if("Psat" %in% property & !identical(P, "Psat")) stop('please set P = "Psat" to calculate the property Psat')
# for Psat(T) (1) or T-P (2)
if(identical(P, "Psat")) iopt <- 1 else iopt <- 2
if(identical(P, "Psat")) isat <- 1 else isat <- 0
# Input values, gleaned from H2O92D.f and SUP92D.f
# it, id, ip, ih, itripl, isat, iopt, useLVS, epseqn, icrit
specs <- c(2, 2, 2, 5, 1, isat, iopt, 1, 4, 0)
states <- rep(0, 4)
# Initialize the output matrix
w.out <- matrix(NA, nrow = length(T), ncol = 23, byrow = TRUE)
err.out <- numeric(length(T))
rho.out <- numeric(length(T))
P.out <- numeric(length(T))
# 20091022 TODO: parallelize this
Tc <- convert(T, "C")
for(i in 1:length(T)) {
states[1] <- Tc[i]
if(identical(P, "Psat")) states[2] <- 0
else states[2] <- P[i]
if(is.na(Tc[i]) | is.na(P[i]) & !identical(P, "Psat")) {
# If T or P is NA, all properties are NA
# (NA's are already in w.out)
P.out[i] <- NA
rho.out[i] <- NA
} else {
# Now to the actual calculations
H2O <- .Fortran(C_h2o92, as.integer(specs), as.double(states),
as.double(rep(0, 46)), as.integer(0))
# Errors
err.out[i] <- H2O[[4]]
# Density of two states
rho <- H2O[[2]][3]
rho2 <- H2O[[2]][4]
if(rho2 > rho) {
# Liquid is denser than vapor
rho <- rho2
inc <- 1 # second state is liquid
} else inc <- 0 # first state is liquid
rho.out[i] <- rho
# 23 properties of the phase in the liquid state
w <- t(H2O[[3]][seq(1, 45, length.out = 23)+inc])
if(err.out[i] == 1) w[1, ] <- NA
# Update the ith row of the output matrix
w.out[i,] <- w
# Psat
if(identical(P, "Psat")) {
w.P <- H2O[[2]][2]
w.P[w.P == 0] <- NA
# Psat specifies P = 1 below 100 degC
if(P1) w.P[w.P < 1] <- 1
P.out[i] <- w.P
}
}
}
# Turn output into dataframe
w.out <- as.data.frame(w.out)
# Add names of properties to the output
names(w.out) <- available_properties[1:23]
# Assemble additional properties: V, rho, Psat, E, kT
if(any(iprop > 23)) {
mwH2O <- 18.0152 # SUP92.f
V <- mwH2O/rho.out
rho <- rho.out*1000
# rho == 0 should be NA 20180923
rho[rho == 0] <- NA
Psat <- P.out
E <- V*w.out$alpha
kT <- V*w.out$beta
# A and B parameters in Debye-Huckel equation:
# Helgeson (1969) doi:10.2475/ajs.267.7.729
# Manning (2013) doi:10.2138/rmg.2013.76.5
A_DH <- 1.8246e6 * rho.out^0.5 / (w.out$epsilon * T)^1.5
B_DH <- 50.29e8 * rho.out^0.5 / (w.out$epsilon * T)^0.5
w.out <- cbind(w.out, data.frame(V = V, rho = rho, Psat = Psat, E = E, kT = kT, A_DH = A_DH, B_DH = B_DH))
}
# Tell the user about any problems
if(any(err.out == 1)) {
if(length(T) > 1) plural <- "s" else plural <- ""
nerr <- sum(err.out == 1)
if(nerr > 1) plural2 <- "s" else plural2 <- ""
if(identical(P, "Psat")) message(paste("water.SUPCRT92: error", plural2, " calculating ",
nerr, " of ", length(T), " point", plural, "; for Psat we need 273.16 < T < 647.067 K", sep = ""))
else message(paste("water.SUPCRT92: error", plural2, " calculating ", nerr,
" of ", length(T), " point", plural,
"; T < Tfusion@P, T > 2250 degC, or P > 30kb.", sep = ""))
# that last bit is taken from SUP92D.f in SUPCRT92
}
# Keep only the selected properties
w.out <- w.out[, iprop, drop = FALSE]
# Convert energies to Joules 20220325
isenergy <- names(w.out) %in% c("A", "G", "S", "U", "H", "Cv", "Cp", "tcond")
if(any(isenergy)) w.out[, isenergy] <- convert(w.out[, isenergy], "J")
# Return result
w.out
}
water.IAPWS95 <- function(property = NULL, T = 298.15, P = 1) {
available_properties <- c("A", "G", "S", "U", "H", "Cv", "Cp",
"Speed", "epsilon",
"YBorn", "QBorn", "XBorn", "NBorn", "UBorn",
"V", "rho", "Psat", "de.dT", "de.dP", "pressure",
"A_DH", "B_DH")
if(is.null(property)) return(available_properties)
# To get the properties of water via IAPWS-95
message(paste("water.IAPWS95: calculating", length(T), "values for"), appendLF = FALSE)
M <- 18.015268 # g mol-1
V <- function() return(M*1000/my.rho)
# Psat stuff
Psat <- function() {
P <- WP02.auxiliary("P.sigma", T)
P[T < 373.124] <- 0.1
return(convert(P, "bar"))
}
## Thermodynamic properties
Tr <- 298.15
# Convert to SUPCRT reference state at the triple point
# difference = SUPCRT - IAPWS ( + entropy in G )
dH <- convert(-68316.76 - 451.75437, "J")
dS <- convert(16.7123 - 1.581072, "J")
dG <- convert(-56687.71 + 19.64228 - dS * (T - Tr), "J")
# Does the reference state used for GHS also go here?
dU <- convert(-67434.5 - 451.3229, "J")
dA <- convert(-55814.06 + 20.07376 - dS * (T - Tr), "J")
# Calculate pressure from the given T and estimated rho
pressure <- function() return(convert(IAPWS95("p", T = T, rho = my.rho), "bar"))
# Convert specific values to molar values
S <- function()
return(IAPWS95("s", T = T, rho = my.rho)$s*M + dS)
# u (internal energy) is not here because the letter
# is used to denote one of the Born functions
# Scratch that! let's put u here and call the other one uborn
U <- function()
return(IAPWS95("u", T = T, rho = my.rho)$u*M + dU)
A <- function()
return(IAPWS95("a", T = T, rho = my.rho)$a*M + dA)
H <- function()
return(IAPWS95("h", T = T, rho = my.rho)$h*M + dH)
G <- function()
return(IAPWS95("g", T = T, rho = my.rho)$g*M + dG)
Cv <- function()
return(IAPWS95("cv", T = T, rho = my.rho)$cv*M)
Cp <- function()
return(IAPWS95("cp", T = T, rho = my.rho)$cp*M)
Speed <- function()
return(IAPWS95("w", T = T, rho = my.rho)$w*100) # to cm/s
## Electrostatic properties
epsilon <- function() return(water.AW90(T = T, rho = my.rho, P = convert(P, "MPa")))
de.dT <- function() {
p <- numeric()
for(i in 1:length(T)) {
this.T <- T[i]
this.P <- P[i]
this.rho <- my.rho[i]
dt <- 0.001; t1 <- this.T-dt; t2 <- this.T+dt
rho <- rho.IAPWS95(T = c(t1, t2), P = rep(this.P, 2))
e <- water.AW90(T = c(t1,t2),rho = rho,rep(this.P,2))
p <- c(p,(e[2]-e[1])/(2*dt))
}
return(p)
}
de.dP <- function() {
p <- numeric()
for(i in 1:length(T)) {
this.T <- T[i]
this.P <- P[i]
this.rho <- my.rho[i]
dp <- 0.001; p1 <- this.P-dp; p2 <- this.P+dp
rho <- rho.IAPWS95(T = rep(this.T, 2), P = c(p1, p2))
e <- water.AW90(P = c(p1,p2),rho = rho,T = rep(this.T,2))
p <- c(p,(e[2]-e[1])/(2*dp))
}
return(p)
}
## Born functions
QBorn <- function() {
p <- numeric()
for(i in 1:length(T)) {
this.T <- T[i]; this.P <- P[i]; this.rho <- my.rho[i]
dp <- 0.01; p1 <- this.P-dp; p2 <- this.P+dp
rho <- rho.IAPWS95(T = rep(this.T, 2), P = c(p1, p2))
e <- water.AW90(T = rep(this.T,2),rho = rho,P = convert(c(p1,p2),'MPa'))
#p <- c(p,convert(-(1/e[2]-1/e[1])/(2*dp),'cm3bar'))
p <- c(p,-(1/e[2]-1/e[1])/(2*dp))
}
return(p)
}
NBorn <- function() {
p <- numeric()
for(i in 1:length(T)) {
this.T <- T[i]; this.P <- P[i]; this.rho <- my.rho[i]
dp <- 0.01; p1 <- this.P-dp; p2 <- this.P+dp
rho <- rho.IAPWS95(T = rep(this.T, 3), P = c(p1, this.P, p2))
e <- water.AW90(T = rep(this.T,3),rho = rho,P = convert(c(p1,this.P,p2),'MPa'))
#p <- c(p,convert(convert((-(1/e[3]-1/e[2])/dp+(1/e[2]-1/e[1])/dp)/dp,'cm3bar'),'cm3bar'))
p <- c(p,(-(1/e[3]-1/e[2])/dp+(1/e[2]-1/e[1])/dp)/dp)
}
return(p)
}
YBorn <- function() {
p <- numeric()
for(i in 1:length(T)) {
this.T <- T[i]; this.P <- P[i]; this.rho <- my.rho[i]
dt <- 0.001; t1 <- this.T-dt; t2 <- this.T+dt
rho <- rho.IAPWS95(T = c(t1, t2), P = rep(this.P, 2))
e <- water.AW90(T = c(t1,t2),rho = rho,P = convert(rep(this.P,2),'MPa'))
p <- c(p,-(1/e[2]-1/e[1])/(2*dt))
}
return(p)
}
XBorn <- function() {
p <- numeric()
for(i in 1:length(T)) {
this.T <- T[i]; this.P <- P[i]; this.rho <- my.rho[i]
dt <- 0.001; t1 <- this.T-dt; t2 <- this.T+dt
rho <- rho.IAPWS95(T = c(t1, this.T, t2), P = rep(this.P, 3))
e <- water.AW90(T = c(t1,this.T,t2),rho = rho,P = convert(rep(this.P,3),'MPa'))
p <- c(p,(-(1/e[3]-1/e[2])/dt+(1/e[2]-1/e[1])/dt)/dt)
}
return(p)
}
UBorn <- function() {
p <- numeric()
for(i in 1:length(T)) {
this.T <- T[i]; this.P <- P[i]; this.rho <- my.rho[i]
dt <- 0.001; this.T1 <- this.T - dt; this.T2 <- this.T + dt
dp <- 0.001; p1 <- this.P-dp; p2 <- this.P+dp
rho1 <- rho.IAPWS95(T = rep(this.T1, 2), P = c(p1, p2))
rho2 <- rho.IAPWS95(T = rep(this.T2, 2), P = c(p1, p2))
e1 <- water.AW90(T = rep(this.T1,2),rho = rho1,P = convert(c(p1,p2),'MPa'))
e2 <- water.AW90(T = rep(this.T2,2),rho = rho2,P = convert(c(p1,p2),'MPa'))
#p1 <- convert(-(1/e1[2]-1/e1[1])/(2*dp),'cm3bar')
#p2 <- convert(-(1/e2[2]-1/e2[1])/(2*dp),'cm3bar')
p1 <- -(1/e1[2]-1/e1[1])/(2*dp)
p2 <- -(1/e2[2]-1/e2[1])/(2*dp)
p <- c(p,(p2-p1)/(2*dt))
}
return(p)
}
### Main loop; init dataframe output and density holders
w.out <- data.frame(matrix(nrow = length(T), ncol = length(property)))
my.rho <- NULL
# Get densities unless only Psat is requested
if(!identical(property, "Psat")) {
# Calculate values of P for Psat
if(identical(P, "Psat")) P <- Psat()
message(" rho", appendLF = FALSE)
my.rho <- rho.IAPWS95(T, P, get("thermo", CHNOSZ)$opt$IAPWS.sat)
rho <- function() my.rho
}
# Get epsilon and A_DH, B_DH (so we calculate epsilon only once)
if(any(property %in% c("epsilon", "A_DH", "B_DH"))) {
my.epsilon <- epsilon()
epsilon <- function() my.epsilon
A_DH <- function() 1.8246e6 * (my.rho/1000)^0.5 / (my.epsilon * T)^1.5
B_DH <- function() 50.29e8 * (my.rho/1000)^0.5 / (my.epsilon * T)^0.5
}
for(i in 1:length(property)) {
if(property[i] %in% c("E", "kT", "alpha", "daldT", "beta")) {
# E and kT aren't here yet... set them to NA
# Also set alpha, daldT, and beta (for derivatives of g function) to NA 20170926
warning("water.IAPWS95: values of ", property[i], " are NA", call. = FALSE)
wnew <- rep(NA, length(T))
} else {
message(paste(" ", property[i], sep = ""), appendLF = FALSE)
wnew <- get(property[i])()
}
w.out[, i] <- wnew
}
message("")
# Include properties available in SUPCRT that might be NA here
wprop <- unique(c(water.SUPCRT92(), available_properties))
iprop <- match(property, wprop)
property[!is.na(iprop)] <- wprop[na.omit(iprop)]
colnames(w.out) <- property
return(w.out)
}
# Get water properties from DEW model for use by subcrt() 20170925
water.DEW <- function(property = NULL, T = 373.15, P = 1000) {
available_properties <- c("G", "epsilon", "QBorn", "V", "rho", "beta", "A_DH", "B_DH")
if(is.null(property)) return(available_properties)
# We can't use Psat here
if(identical(P, "Psat")) stop("Psat isn't supported in this implementation of the DEW model. Try setting P to at least 1000 bar.")
# Use uppercase property names (including H, S, etc., so we get them from the SUPCRT properties)
wprop <- water.SUPCRT92()
iprop <- match(property, wprop)
property[!is.na(iprop)] <- wprop[na.omit(iprop)]
# Convert temperature units
pressure <- P
temperature <- convert(T, "C")
# Initialize output data frame with NA for all properties and conditions
ncond <- max(length(T), length(P))
out <- matrix(NA, ncol = length(property), nrow = ncond)
out <- as.data.frame(out)
colnames(out) <- property
# Calculate rho and epsilon if they're needed for any other properties
if(any(c("rho", "V", "QBorn", "epsilon", "beta", "A_DH", "B_DH") %in% property)) rho <- calculateDensity(pressure, temperature)
if(any(c("epsilon", "A_DH", "B_DH") %in% property)) epsilon <- calculateEpsilon(rho, temperature)
# Fill in columns with values
if("rho" %in% property) out$rho <- rho*1000 # use kg/m^3 (like SUPCRT)
if("V" %in% property) out$V <- 18.01528/rho
if("G" %in% property) out$G <- calculateGibbsOfWater(pressure, temperature)
if("QBorn" %in% property) out$QBorn <- calculateQ(rho, temperature)
if("epsilon" %in% property) out$epsilon <- epsilon
# Divide drhodP by rho to get units of bar^-1
if("beta" %in% property) out$beta <- calculate_drhodP(rho, temperature) / rho
if("A_DH" %in% property) out$A_DH <- 1.8246e6 * rho^0.5 / (epsilon * T)^1.5
if("B_DH" %in% property) out$B_DH <- 50.29e8 * rho^0.5 / (epsilon * T)^0.5
# Use SUPCRT-calculated values below 100 degC and/or below 1000 bar
ilow <- T < 373.15 | P < 1000
if(any(ilow)) {
out[ilow, ] <- water.SUPCRT92(property, T = T[ilow], P = P[ilow])
iPrTr <- T == 298.15 & P == 1
if(sum(iPrTr) == sum(ilow)) message(paste("water.DEW: using SUPCRT calculations for Pr,Tr"))
if(sum(iPrTr) == 0) message(paste("water.DEW: using SUPCRT calculations for", sum(ilow), "low-T or low-P condition(s)"))
if(sum(iPrTr) == 1 & sum(ilow) > sum(iPrTr)) message(paste("water.DEW: using SUPCRT calculations for Pr,Tr and", sum(ilow)-1, "other low-T or low-P condition(s)"))
# However, we also have this:
# epsilon(Pr,Tr) from SUPCRT: 78.24514
# epsilon(Pr,Tr) in DEW spreadsheet: 78.47
if("epsilon" %in% property) out$epsilon[iPrTr] <- 78.47
}
# Convert energies to Joules 20220325
isenergy <- names(out) %in% "G"
if(any(isenergy)) out[, isenergy] <- convert(out[, isenergy], "J")
out
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/water.R
|
# CHNOSZ/zzz.R
# This has the .onAttach function for package startup message and data initialization
# The CHNOSZ environment is made here in open code 20190214
# https://stackoverflow.com/questions/41954302/where-to-create-package-environment-variables
CHNOSZ <- new.env()
.onLoad <- function(libname, pkgname) {
# Add placeholder functions not present in earlier R versions 20190420
# code inspired by backports::import
if(getRversion() < "3.6.0") {
pkg = getNamespace(pkgname)
no.fun <- function(...) stop("this function is not available in this version of R")
assign("hcl.pals", no.fun, envir = pkg)
assign("hcl.colors", no.fun, envir = pkg)
}
}
.onAttach <- function(libname,pkgname) {
# Version figuring adapted from package mgcv
pkghelp <- library(help = CHNOSZ)$info[[1]]
# Things are different for older versions of R
if(length(pkghelp) == 1) pkghelp <- library(help = CHNOSZ)$info[[2]]
version <- pkghelp[pmatch("Version:", pkghelp)]
um <- strsplit(version, " ")[[1]]
version <- um[nchar(um)>0][2]
date <- pkghelp[pmatch("Date:", pkghelp)]
um <- strsplit(date, " ")[[1]]
date <- um[nchar(um)>0][2]
# Identify the program and version
packageStartupMessage(paste("CHNOSZ version ", version, " (", date, ")", sep = ""))
# Initialize the 'thermo' data object
reset()
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/R/zzz.R
|
# CHNOSZ/demo/AD.R
# Calculate Henry's constant using the Akinfiev-Diamond model 20190220
# Add volume and heat capacity 20220207
library(CHNOSZ)
# Start with default settings
reset()
########################
### HENRY'S CONSTANT ###
########################
# Function to plot natural logarithm of Henry's constant
lines.KH <- function(name = "CO2", T = 1:373, P = "Psat", HKF = FALSE, altH2S = FALSE) {
# use AD or HKF model?
if(HKF) add.OBIGT("inorganic_aq")
if(!HKF) add.OBIGT("AD")
# use alternative parameters for H2S? (AD03 Table 1)
if(altH2S) mod.OBIGT("H2S", state = "aq", a = -11.2303, b = 12.6104, c = -0.2102)
# get properties of aq - gas reaction
sres <- suppressWarnings(subcrt(c(name, name), c("aq", "gas"), c(-1, 1), T = T, P = P))
# calculate natural logarithm of Henry's constant in mole-fraction units
ln_KH <- log(1000/18.0153) + log(10) * sres$out$logK
# plot with units of reciprocal temperature (1000/K)
TK <- convert(T, "K")
if(HKF) lty <- 2 else lty <- 1
if(HKF) col <- 2 else col <- 1
if(altH2S) lty <- 3
lines(1000/TK, ln_KH, lty = lty, col = col)
}
# Set up plot
opar <- par(no.readonly = TRUE)
par(mfrow = c(2, 2))
par(mar = c(3.5, 3.5, 2.5, 1))
par(mgp = c(2.4, 1, 0))
ylab <- quote(ln~italic(K[H]))
xlab <- quote(1000 / list(italic(T), K))
# CO2 (Fig. 1a of AD03)
plot(0, 0, xlim = c(1, 4), ylim = c(4, 10), xlab = xlab, ylab = ylab)
lines.KH("CO2", 1:373, "Psat")
lines.KH("CO2", seq(100, 650, 10), 500)
lines.KH("CO2", 1:373, "Psat", HKF = TRUE)
lines.KH("CO2", seq(100, 650, 10), 500, HKF = TRUE)
dat <- read.csv(system.file("extdata/cpetc/AD03_Fig1a.csv", package = "CHNOSZ"))
points(dat$x, dat$y, pch = dat$pch)
text(3.5, 7.8, quote(italic(P)[sat]))
text(3.05, 9.2, "500 bar")
legend("bottom", c("Data (AD03, Fig. 1a)", "AD model", "Revised HKF model"),
lty = c(0, 1, 2), pch = c(1, NA, NA), col = c(1, 1, 2), bty = "n")
title(main = syslab(c("CO2", "H2O"), dash = " - "))
# H2 (Fig. 1b of AD03)
plot(0, 0, xlim = c(1, 4), ylim = c(8, 12), xlab = xlab, ylab = ylab)
lines.KH("H2", 1:373, "Psat")
lines.KH("H2", seq(100, 650, 10), 1000)
lines.KH("H2", 1:373, "Psat", HKF = TRUE)
lines.KH("H2", seq(100, 650, 10), 1000, HKF = TRUE)
text(3.4, 11.4, quote(italic(P)[sat]))
text(1.5, 11, "1000 bar")
dat <- read.csv(system.file("extdata/cpetc/AD03_Fig1b.csv", package = "CHNOSZ"))
points(dat$x, dat$y, pch = dat$pch)
legend("bottomright", c("Data (AD03, Fig. 1b)", "AD model", "Revised HKF model"),
lty = c(0, 1, 2), pch = c(1, NA, NA), col = c(1, 1, 2), bty = "n")
title(main = syslab(c("H2", "H2O"), dash = " - "))
# H2S (Fig. 1c of AD03)
plot(0, 0, xlim = c(1, 4), ylim = c(4, 9), xlab = xlab, ylab = ylab)
lines.KH("H2S", 1:373, "Psat")
lines.KH("H2S", seq(100, 650, 10), 1000)
lines.KH("H2S", 1:373, "Psat", altH2S = TRUE)
lines.KH("H2S", seq(100, 650, 10), 1000, altH2S = TRUE)
lines.KH("H2S", 1:373, "Psat", HKF = TRUE)
lines.KH("H2S", seq(100, 650, 10), 1000, HKF = TRUE)
dat <- read.csv(system.file("extdata/cpetc/AD03_Fig1c.csv", package = "CHNOSZ"))
points(dat$x, dat$y, pch = dat$pch)
text(3.4, 6.9, quote(italic(P)[sat]))
text(3.1, 8.6, "1000 bar")
legend("bottom", c("Data (AD03, Fig. 1c)", "AD model", "AD model (alt. H2S)", "Revised HKF model"),
lty = c(0, 1, 3, 2), pch = c(1, NA, NA, NA), col = c(1, 1, 1, 2), bty = "n")
title(main = syslab(c("H2S", "H2O"), dash = " - "))
# CH4 (Fig. 1d of AD03)
plot(0, 0, xlim = c(1.5, 4), ylim = c(8, 12), xlab = xlab, ylab = ylab)
lines.KH("CH4", 1:350, "Psat")
lines.KH("CH4", 1:350, "Psat", HKF = TRUE)
dat <- read.csv(system.file("extdata/cpetc/AD03_Fig1d.csv", package = "CHNOSZ"))
points(dat$x, dat$y, pch = dat$pch)
text(3.4, 11, quote(italic(P)[sat]))
legend("bottomright", c("Data (AD03, Fig. 1d)", "AD model", "Revised HKF model"),
lty = c(0, 1, 2), pch = c(1, NA, NA), col = c(1, 1, 2), bty = "n")
title(main = syslab(c("CH4", "H2O"), dash = " - "))
##############
### VOLUME ###
##############
# Function to plot volume
lines.V <- function(species = "CO2", T = seq(300, 440, 1), P = 280, HKF = FALSE) {
# Use AD or HKF model?
if(HKF) add.OBIGT("inorganic_aq")
if(!HKF) add.OBIGT("AD")
# Calculate V; use exceed.rhomin to allow HKF calculations in low-density region
V <- subcrt(species, T = T, P = P, exceed.rhomin = HKF)$out[[1]]$V
if(HKF) lty <- 2 else lty <- 1
if(HKF) col <- 2 else col <- "gray20"
lines(T, V, lty = lty, col = col, lwd = 1.5)
}
# Read file with V data for four species
file <- system.file("extdata/cpetc/HWM96_V.csv", package = "CHNOSZ")
dat <- read.csv(file)
# Use data near 280 bar
dat <- dat[abs(dat$P - 28) < 0.1, ]
# Setup plot
par(mfrow = c(2, 2))
par(mar = c(4, 4, 3, 1))
par(cex = 1.2)
par(mgp = c(2.5, 1, 0))
# Loop over species
for(species in c("CH4", "CO2", "H2S", "NH3")) {
thisdat <- dat[dat$species == species, ]
T <- convert(thisdat$T, "C")
if(species %in% c("CH4", "CO2")) ylim <- c(0, 2200)
if(species %in% c("H2S", "NH3")) ylim <- c(0, 1200)
plot(T, thisdat$V, xlim = c(300, 440), ylim = ylim, xlab = axis.label("T"), ylab = axis.label("V"))
lines.V(species)
lines.V(species, HKF = TRUE)
legend("topleft", legend = expr.species(species, use.state = TRUE), bty = "n")
}
par(mfrow = c(1, 1))
plot.window(c(0, 1), c(0, 1))
box(col = "transparent")
legend <- c("Hn\u011bdkovsk\u00fd et al. (1996)", "AD model", "Revised HKF model")
legend(0.26, 0.54, legend, pch = c(1, NA, NA), lty = c(NA, 1, 2), col = c(1, "gray20", 2), lwd = 1.5, inset = c(-10, -10), bty = "n", text.font = 2)
title(main = "Aqueous nonelectrolytes (280 bar)")
#####################
### HEAT CAPACITY ###
#####################
# Function to plot heat capacity
lines.Cp <- function(species = "CO2", T = seq(300, 440, 1), P = 280, HKF = FALSE) {
# Use AD or HKF model?
if(HKF) add.OBIGT("inorganic_aq")
if(!HKF) add.OBIGT("AD")
# Calculate Cp; use exceed.rhomin to allow HKF calculations in low-density region
Cp <- subcrt(species, T = T, P = P, exceed.rhomin = HKF)$out[[1]]$Cp
if(HKF) lty <- 2 else lty <- 1
if(HKF) col <- 2 else col <- "gray20"
lines(T, Cp, lty = lty, col = col, lwd = 1.5)
}
# Read file with Cp data for four species
file <- system.file("extdata/cpetc/HW97_Cp.csv", package = "CHNOSZ")
dat <- read.csv(file)
# Setup plot
par(mfrow = c(2, 2))
par(mar = c(4, 4, 3, 1))
par(cex = 1.2)
par(mgp = c(2.5, 1, 0))
# Loop over species
for(species in c("CH4", "CO2", "H2S", "NH3")) {
thisdat <- dat[dat$species == species, ]
T <- convert(thisdat$T, "C")
if(species %in% c("CH4", "CO2")) ylim <- c(-40000, 40000)
if(species %in% c("H2S", "NH3")) ylim <- c(-20000, 20000)
plot(T, thisdat$Cp, xlim = c(300, 440), ylim = ylim, xlab = axis.label("T"), ylab = axis.label("Cp"))
lines.Cp(species)
lines.Cp(species, HKF = TRUE)
legend("topleft", legend = expr.species(species, use.state = TRUE), bty = "n")
}
par(mfrow = c(1, 1))
plot.window(c(0, 1), c(0, 1))
box(col = "transparent")
legend <- c("Hn\u011bdkovsk\u00fd and Wood (1997)", "AD model", "Revised HKF model")
legend(0.26, 0.54, legend, pch = c(1, NA, NA), lty = c(NA, 1, 2), col = c(1, "gray20", 2), lwd = 1.5, inset = c(-10, -10), bty = "n", text.font = 2)
title(main = "Aqueous nonelectrolytes (280 bar)")
par(opar)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/demo/AD.R
|
# CHNOSZ/demo/DEW.R
# Demo for the Deep Earth Water (DEW) model in CHNOSZ 20170927
library(CHNOSZ)
# Set up subplots
opar <- par(no.readonly = TRUE)
par(mfrow = c(2, 2), mar = c(3.0, 3.5, 2.5, 1.0), mgp = c(1.7, 0.3, 0), las = 1, tcl = 0.3, xaxs = "i", yaxs = "i")
# Activate DEW model
oldwat <- water("DEW")
###########
#### Plot 1: quartz solubility at high pressure
## after Figure 7D of Sverjensky et al., 2014a [SHA14]
## (Geochim. Cosmochim. Acta, https://doi.org/10.1016/j.gca.2013.12.019)
###########
# Load SiO2 and Si2O4 data taken from DEW spreadsheet
iSi <- add.OBIGT("DEW", c("SiO2", "Si2O4"))
# Print the data references to confirm we got the right ones
thermo.refs(iSi)
# Set temperature ranges for different pressures
# data.frame is used to make P and T the same length
PT0.5 <- data.frame(P = 500, T = seq(200, 550, 10))
PT1.0 <- data.frame(P = 1000, T = seq(200, 700, 10))
PT2.0 <- data.frame(P = 2000, T = seq(200, 700, 10))
PT5.0 <- data.frame(P = 5000, T = seq(200, 850, 10))
PT10.0 <- data.frame(P = 10000, T = seq(200, 825, 10))
PT20.0 <- data.frame(P = 20000, T = seq(200, 800, 10))
PT <- rbind(PT0.5, PT1.0, PT2.0, PT5.0, PT10.0, PT20.0)
# Reaction 1: quartz = SiO2(aq) [equivalent to quartz + 3 H2O = Si(OH)4]
SiO2_logK <- suppressWarnings(subcrt(c("quartz", "SiO2"), c("cr", "aq"), c(-1, 1), P = PT$P, T = PT$T))$out$logK
# Reaction 2: 2 quartz = Si2O4(aq) [equivalent to 2 quartz + 3 H2O = Si2O(OH)6]
Si2O4_logK <- suppressWarnings(subcrt(c("quartz", "Si2O4"), c("cr", "aq"), c(-2, 1), P = PT$P, T = PT$T))$out$logK
# Plot the sum of molalities (== activities) for each pressure
plot(c(200, 1000), c(-2.5, 0.5), type = "n", xlab = axis.label("T"), ylab = "log molality")
for(P in unique(PT$P)) {
icond <- PT$P == P
SiO2_logm <- SiO2_logK[icond]
Si2O4_logm <- Si2O4_logK[icond]
logm <- log10(10^SiO2_logm + 10^Si2O4_logm)
lines(PT$T[icond], logm)
# add text label
lastT <- tail(PT$T[icond], 1)
Pkb <- paste(format(P/1000, nsmall = 1), "kb")
text(lastT+25, tail(logm, 1), Pkb, adj = 0)
}
t1 <- quote("Solubility of"~alpha*"-quartz")
t2 <- "after Sverjensky et al., 2014a"
mtitle(as.expression(c(t1, t2)))
# TODO: lines are a little low at highest P and T ...
###########
#### Plot 2: correlations between non-solvation volume and HKF a1 parameter
## after Figures 12B and 12C of Sverjensky et al., 2014a [SHA14]
###########
# We can't use the DEW water model at 25 degC
reset()
# Load the fitted parameters for species as used by SHA14
# TODO: also use their Ca+2??
# NOTE: don't load NaCl, NH4+, or HS- here because the DEW spreadsheet lists a1 from the correlation
iDEW <- add.OBIGT("DEW", c("CO3-2", "BO2-", "MgCl+", "SiO2", "HCO3-", "Si2O4"))
# Override the check in subcrt() for the DEW water model 20220929
lapply(iDEW, mod.OBIGT, model = "HKF")
# Set up the plot
V0nlab <- expression(Delta * italic(V) * degree[n]~~(cm^3~mol^-1))
a1lab <- expression(italic(a)[1]%*%10~~(cal~mol~bar^-1))
plot(c(-25, 50), c(-4, 12), type = "n", xlab = V0nlab, ylab = a1lab)
# A function to get the HKF parameters, calculate nonsolvation volume, plot points, labels, error bars, and correlation lines
plotfun <- function(species, col, pch, cex, dy, error, xlim, corrfun) {
# Get HKF a1 parameter
a1 <- info(info(species), check.it = FALSE)$a1 * 10
# Set omega to zero to calculate non-solvation volume 20220326
mod.OBIGT(species, omega = 0)
Vn <- do.call(rbind, subcrt(species, T = 25)$out)$V
points(Vn, a1, col = col, pch = pch, cex = cex)
for(i in 1:length(species)) text(Vn[i], a1[i] + dy, expr.species(species[i]))
arrows(Vn, a1 - error, Vn, a1 + error, length = 0.03, angle = 90, code = 3, col = col)
lines(xlim, corrfun(xlim), col = col)
}
# Monovalent ions: Na+, K+, Cl-, Br-
monofun <- function(Vn) 2.0754 + 0.10871 * Vn
# For easier reading, set y-offset to NA so the labels aren't plotted
plotfun(c("Na+", "K+", "Cl-", "Br-"), "red", 19, 1, NA, 0.5, c(-7, 35), monofun)
# Divalent ions: Mg+2, Ca+2, CO3-2, SO4-2
difun <- function(Vn) 3.5321 + 0.23911 * Vn
plotfun(c("Mg+2", "Ca+2", "CO3-2", "SO4-2"), "black", 15, 1, 1.2, 0.7, c(-20, 25), difun)
# Complexes and neutral molecules: BO2-, MgCl+, SiO2, NaCl, HCO3-, Si2O4, NH4+, HS-
compfun <- function(Vn) 1.5204 + 0.19421 * Vn
plotfun(c("MgCl+", "SiO2", "NaCl", "HCO3-", "Si2O4"), "blue1", 18, 1.5, 1, 0.5, c(-20, 50), compfun)
# For easier reading, put some labels below the points
plotfun(c("BO2-", "NH4+", "HS-"), "blue1", 18, 1.5, -1.2, 0.5, c(-20, 50), compfun)
# Include an empty subscript for better spacing between the lines
t1 <- quote("Correlations between non-solvation"[])
t2 <- quote("volume and HKF "*italic(a)[1]*" parameter")
mtitle(as.expression(c(t1, t2)))
# Clean up for next plot
OBIGT()
water("DEW")
###########
#### Plot 3: logfO2-pH diagram for aqueous inorganic and organic carbon species at high pressure
## after Figure 1b of Sverjensky et al., 2014b [SSH14]
## (Nature Geoscience, https://doi.org/10.1038/NGEO2291)
###########
# Define system
basis("CHNOS+")
inorganic <- c("CO2", "HCO3-", "CO3-2", "CH4")
organic <- c("formic acid", "formate", "acetic acid", "acetate", "propanoic acid", "propanoate")
species(c(inorganic, organic), 0)
fill <- c(rep("aliceblue", length(inorganic)), rep("aquamarine", length(organic)))
# A function to make the diagrams
dfun <- function(T = 600, P = 50000, res = 300) {
a <- affinity(pH = c(0, 10, res), O2 = c(-24, -12, res), T = T, P = P)
# Set total C concentration to 0.03 molal
# (from EQ3NR model for eclogite [Supporting Information of SSH14])
e <- equilibrate(a, loga.balance = log10(0.03))
diagram(e, fill = fill)
dp <- describe.property(c(" T", " P"), c(T, P), digits = 0)
legend("bottomleft", legend = dp, bty = "n")
}
water("DEW")
## Not run: make diagram using CHNOSZ default database
## (not recommended for high P)
#dfun()
# Make diagram using CO2, HCO3-, CO3-2, CH4, and acetic acid data from DEW spreadsheet
# (the acetate field disappears if we also use the data for acetate from the spreadsheet 20200629)
#add.OBIGT("DEW", c("CO2", "HCO3-", "CO3-2", "CH4", "acetic acid"))
add.OBIGT("DEW")
dfun()
mtitle(c("Inorganic and organic species", "C[total] = 0.03 molal"))
###########
#### Plot 4: speciation of carbon as a function T, logfO2 and pH (added 20171008)
## after SSH14 Fig. 3
###########
# Conditions:
# T = 600, 700, 800, 900, 1000 degC
# P = 5.0GPa (50000 bar)
# fO2 = QFM - 2
# pH set by jadeite + kyanite + coesite
# output from EQ3NR calculations (SSH14 Supporting Information)
# dissolved carbon: 0.03, 0.2, 1, 4, 20 molal
# true ionic strength: 0.39, 0.57, 0.88, 1.45, 2.49
# pH: 3.80, 3.99, 4.14, 4.25, 4.33
## Activate DEW model
reset()
water("DEW")
# Add species data for DEW
inorganics <- c("CH4", "CO2", "HCO3-", "CO3-2")
organics <- c("formic acid", "formate", "acetic acid", "acetate", "propanoic acid", "propanoate")
add.OBIGT("DEW")
## Set basis species
basis(c("Fe", "SiO2", "CO3-2", "H2O", "oxygen", "H+"))
## Calculate logfO2 in QFM buffer
basis("O2", "QFM")
T <- seq(600, 1000, 100)
buf <- affinity(T = T, P = 50000, return.buffer = TRUE)
## Add species
species(c(inorganics, organics))
## Generate spline functions from IS, pH, and molC values at every 100 degC
IS <- c(0.39, 0.57, 0.88, 1.45, 2.49)
pH <- c(3.80, 3.99, 4.14, 4.25, 4.33)
molC <- c(0.03, 0.2, 1, 4, 20)
## Use extended Debye-Huckel equation with b_gamma set to zero
nonideal("bgamma0")
## Calculate affinities on the T-logfO2-pH-IS transect
a <- affinity(T = T, O2 = buf$O2 - 2, IS = IS, pH = pH, P = 50000)
## Calculate metastable equilibrium activities using the total
## Carbon molality as an approximation of total activity
e <- equilibrate(a, loga.balance = log10(molC))
## Make the diagram; don't plot names of low-abundance species
names <- c(inorganics, organics)
names[c(4, 5, 7, 9)] <- ""
col <- rep("black", length(names))
col[c(1, 3, 6, 8, 10)] <- c("red", "darkgreen", "purple", "orange", "navyblue")
if(packageVersion("CHNOSZ") > "1.1.3") {
diagram(e, alpha = "balance", names = names, col = col, ylim = c(0, 0.8), ylab = "carbon fraction", spline.method = "natural")
} else {
diagram(e, alpha = "balance", names = names, col = col, ylim = c(0, 0.8), ylab = "carbon fraction")
}
## Add legend and title
ltxt1 <- "P = 50000 bar"
ltxt2 <- substitute(logfO2=="QFM-2", list(logfO2 = axis.label("O2")))
pH <- seq(3.8, 4.3, length.out = length(T))
legend("left", legend = as.expression(c(ltxt1, ltxt2)), bty = "n")
t1 <- "Aqueous carbon speciation"
t2 <- "after Sverjensky et al., 2014b"
mtitle(c(t1, t2))
### Additional checks
# The maximum absolute pairwise difference between x and y
maxdiff <- function(x, y) max(abs(y - x))
## Check that we're within 0.1 of the QFM-2 values used by SSH14
stopifnot(maxdiff((buf$O2-2), c(-17.0, -14.5, -12.5, -10.8, -9.4)) < 0.1)
# Here are the logKs of aqueous species dissociation reactions at 600 degC and 50000 bar,
# values from EQ3NR output in Supporting Information of the paper (p. 103-109):
inorganic.logK <- c(24.4765, -9.0784, -5.3468, 0)
organic.logK <- c(1.7878, 2.5648, 15.3182, 16.9743, 30.4088, 28.9185)
# Calculate equilibrium constants of the reactions in CHNOSZ; use a negative sign to change from formation to dissociation
logK.calc <- -unlist(affinity(T = 600, P = 50000, property = "logK")$values)
logK.calc - c(inorganic.logK, organic.logK)
## Except for acetate, we're within 0.021 of the logK values used by SSH14
stopifnot(maxdiff(logK.calc[-8], c(inorganic.logK, organic.logK)[-8]) < 0.021)
## Check that we get similar activity coefficients
# Activity coefficients for monovalent species from EQ3NR output
loggamma <- c(-0.15, -0.18, -0.22, -0.26, -0.31)
# Activity coefficients calculated in CHNOSZ
sres <- subcrt("propanoate", T = seq(600, 1000, 100), P = 50000, IS = c(0.39, 0.57, 0.88, 1.45, 2.49))
stopifnot(maxdiff(sres$out[[1]]$loggam, loggamma) < 0.023)
# If m_star in nonideal() was zero, we could decrease the tolerance here
#stopifnot(maxdiff(sres$out[[1]]$loggam, loggamma) < 0.004)
# Reset OBIGT database
reset()
par(opar)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/demo/DEW.R
|
# CHNOSZ/demo/E_coli.R
# Calculate Gibbs energy of biomass synthesis in E. coli
# 20210316 jmd version 1
# After LaRowe and Amend (2016): https://doi.org/10.1038/ismej.2015.227
# Polymerization scheme from Amend et al. (2013): https://doi.org/10.1098/rstb.2012.0255
library(CHNOSZ)
opar <- par(no.readonly = TRUE)
# Concentrations of biomolecules (mol (g cell)-1)
# (from Table 1 of LaRowe and Amend, 2016)
concentrations <- c(
# Amino acids
alanine = 5.43e-04, arginine = 2.81e-04, asparagine = 2.29e-04, aspartate = 2.29e-04,
cysteine = 8.70e-05, glutamate = 2.78e-04, glutamine = 2.50e-04, glycine = 5.82e-04,
histidine = 9.00e-05, isoleucine = 2.76e-04, leucine = 4.28e-04, lysine = 3.26e-04,
methionine = 1.46e-04, phenylalanine = 1.76e-04, proline = 2.10e-04, serine = 2.05e-04,
threonine = 2.41e-04, tryptophan = 5.40e-05, tyrosine = 1.31e-04, valine = 4.02e-04,
# Amines
ethanolamine = 1.31e-04, `diaminopimelic acid` = 2.79e-05, putrescine = 3.40e-05, spermidine = 6.88e-06,
# Nucleotides
`AMP2-` = 1.65E-04, `GMP2-` = 1.26E-04, `CMP2-` = 2.03E-04, `UMP2-` = 1.36E-04,
`dAMP2-` = 2.46E-05, `dGMP2-` = 2.54E-05, `dCMP2-` = 2.54E-05, `dTMP2-` = 2.46E-05,
# Fatty acids
palmitate = 1.12e-04, oleate = 6.22e-05, palmitoleate = 8.56e-05, myristate = 1.67e-05, `beta-hydroxymyristate` = 3.37e-05,
# Saccharides and more
glycerol = 1.61e-04, glucose = 2.50e-05, heptose = 2.52e-05, galactose = 8.33e-06, rhamnose = 8.53e-06,
glucoseamine = 1.67e-05, `N-acetylglucosamine` = 3.62e-05, `N-acetylmuramic acid` = 2.76e-05
)
# Keep the names of the biomolecules here
biomolecules <- names(concentrations)
# Set temperature values
T <- 0:125
T.K <- convert(T, "K")
# Convert Eh to pe for oxidizing and reducing conditions
pe_ox <- convert(0.858, "pe", T = T.K)
pe_red <- convert(-0.384, "pe", T = T.K)
pe <- list(pe_ox, pe_red)
# Parameters for [UPBB] in OBIGT are from Kitadai (2014)
# (https://doi.org/10.1007/s00239-014-9616-1)
# This command loads "old" parameters for [UPBB]
# (Dick et al., 2006; https://doi.org/10.5194/bg-3-311-2006)
# - increases G.P278 by ca. 35-40% (closer to Figure 5 of Amend et al., 2013)
mod.OBIGT("[UPBB]", G = -21436, H = -45220, S = 1.62)
# Calculate polymerization contribution
# Standard Gibbs energy (J / mol) for AABB -> PBB + H2O
# (Figure 4 of Amend et al., 2013)
G0.AABB_to_PBB_plus_H2O <- subcrt(c("[AABB]", "[UPBB]", "H2O"), c(-1, 1, 1), T = T)$out$G
# Standard Gibbs energy for 278 AA -> P[278] + 277H2O
G0.P278 <- 277 * G0.AABB_to_PBB_plus_H2O
# logQ for this reaction (decimal logarithm)
logQ <- log10(8.7e-6) - 278 * log10(6.5e-3)
# Gibbs energy for this reaction
# G = G0 + 2.303*RT*logQ
# (cf. Figure 5 of Amend et al., 2013)
G.P278 <- G0.P278 + log(10) * 8.3145 * T.K * logQ
# Gibbs energy (J / peptide bond)
G.P278_per_bond <- G.P278 / 277 / 6.02e23
# Gibbs energy of protein polymerization (J / g cell)
bonds_per_g_cell <- 2.82e21 # Table 2 of Amend et al., 2013
Gpoly_protein_per_g_cell <- G.P278_per_bond * bonds_per_g_cell
# The value calculated at 25 degrees C is equal to that given by Amend et al., 2013
stopifnot(round(Gpoly_protein_per_g_cell[26]) == 191)
# Calculate energy for non-protein polymerization (J / g cell)
Gpoly_nonprotein_per_g_cell <- 45 / 55 * Gpoly_protein_per_g_cell
Gpoly_per_g_cell <- Gpoly_protein_per_g_cell + Gpoly_nonprotein_per_g_cell
# Function to plot Gibbs energy of biomolecule synthesis
# for a given combination of C-, N- and S-bearing basis species
plot_G <- function(C, N, S) {
# Retrieve logarithm of activity for given basis species
# (from Table 2 of LaRowe and Amend, 2016)
loga_C <- switch(C, "CO2" = -3, "CH3COO-" = -5, "CH4" = -6)
loga_N <- switch(N, "NO3-" = -5, "NH4+" = -6)
loga_S <- switch(S, "SO4-2" = -3, "HS-" = -6)
# Set basis species
# (Note: we set activity of e- in affinity() below)
basis(c(C, N, S, "HPO4-2", "H2O", "H+", "e-"), c(loga_C, loga_N, loga_S, -5, 0, -7, 0))
# Load formed species
species(biomolecules, -9)
# Start plot
ylab <- quote(list(Delta*italic(G[synth]), kJ*(dry~g~cells)^-1))
plot(c(0, 125), c(-15, 30), xlab = axis.label("T"), ylab = ylab, type = "n", xaxs = "i", yaxs = "i")
axis(3, labels = FALSE)
axis(4, labels = FALSE)
# Loop over oxidizing/reducing conditions
for(ipe in 1:2) {
# Calculate dimensionless affinity (A/2.303RT) from 0 to 125 degC at 1 bar
a <- affinity(T = T, `e-` = -pe[[ipe]])
# Convert affinity to Gibbs energy (kJ/mol)
G.J <- lapply(a$values, convert, "G", T = T.K)
G.kJ <- lapply(G.J, "*", 1e-3)
# Calculate Gibbs energy (kJ (g cell)-1) for each biomolecule
G.kJ.g_cell <- Map("*", G.kJ, concentrations)
# Sum Gibbs energy for all biomolecules
sum.G.kJ.g_cell <- Reduce("+", G.kJ.g_cell)
# Add polymerization contribution
total.G.kJ.g_cell <- sum.G.kJ.g_cell + Gpoly_per_g_cell / 1000
# Add line to plot
# (Note: ipe * 2 = 2 (red) or 4 (blue))
lines(T, total.G.kJ.g_cell, col = ipe * 2, lwd = 2)
# Add label
dy_ox <- 3
dy_red <- ifelse(C == "CH4", 3, -3)
if(ipe == 1) text(T[25], total.G.kJ.g_cell[25] + dy_ox, "Oxidizing")
if(ipe == 2) text(T[25], total.G.kJ.g_cell[25] + dy_red, "Reducing")
}
# Add legend
Cexpr <- expr.species(C)
Nexpr <- expr.species(N)
Sexpr <- expr.species(S)
legend <- bquote(list(.(Cexpr), .(Nexpr), .(Sexpr)))
x <- ifelse(C == "CO2", "bottomright", "topright")
legend(x, legend = legend, bty = "n")
}
# Set graphical parameters
par(mfrow = c(3, 2))
par(mar = c(2.5, 3, 1.5, 1), mgp = c(1.5, 0.3, 0))
par(tcl = 0.25)
par(cex = 1)
# Make plots with different combinations of basis species
plot_G("CO2", "NO3-", "SO4-2")
plot_G("CO2", "NH4+", "HS-")
plot_G("CH3COO-", "NO3-", "SO4-2")
plot_G("CH3COO-", "NH4+", "HS-")
plot_G("CH4", "NO3-", "SO4-2")
plot_G("CH4", "NH4+", "HS-")
# Restore OBIGT database
OBIGT()
# Reset plot settings
par(opar)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/demo/E_coli.R
|
# CHNOSZ/demo/NaCl.R
## NaCl dissocation logK f(T,P)
## after Shock et al., 1992, Fig. 1
## (Shock, E. L., Oelkers, E. H., Johnson, J. W., Sverjensky, D. A. and Helgeson, H. C. (1992)
## Calculation of the thermodynamic properties of aqueous species at high pressures and temperatures:
## Effective electrostatic radii, dissociation constants and standard partial molal properties to 1000 degrees C and 5 kbar.
## J. Chem. Soc. Faraday Trans. 88, 803-826. https://doi.org/10.1039/FT9928800803 )
library(CHNOSZ)
## Uncomment these lines to make the plot with the g-function disabled
#mod.OBIGT("Cl-", z=0)
#mod.OBIGT("Na+", z=0)
# Start a new plot and show the experimental logK
thermo.plot.new(xlim=c(0, 1000), ylim=c(-5.5, 1),
xlab=axis.label("T"), ylab=axis.label("logK"))
expt <- read.csv(system.file("extdata/cpetc/SOJSH.csv",
package="CHNOSZ"), as.is=TRUE)
points(expt$T,expt$logK, pch=expt$pch)
# We'll be at 9 distinct pressure conditions, including Psat
# Psat is repeated to show "not considered" region
# (T >= 355 degC; Fig. 6 of Shock et al., 1992)
P <- c(list("Psat", "Psat"), as.list(seq(500, 4000, by=500)))
# For each of those what's the range of temperature
T <- list()
T[[1]] <- seq(0, 354, 1)
T[[2]] <- seq(354, 370, 1)
T[[3]] <- seq(265, 465, 1)
T[[4]] <- seq(285, 760, 1)
T[[5]] <- seq(395, 920, 1)
T[[6]] <- T[[7]] <- T[[8]] <- T[[9]] <- T[[10]] <- seq(400, 1000, 1)
# Calculate and plot the logK
species <- c("NaCl", "Na+", "Cl-")
coeffs <- c(-1, 1, 1)
logK <- numeric()
for(i in 1:length(T)) {
s <- suppressWarnings(subcrt(species, coeffs, T=T[[i]], P=P[[i]]))
if(i==2) lty <- 3 else lty <- 1
lines(s$out$T, s$out$logK, lty=lty)
# keep the calculated values for each experimental condition (excluding Psat)
iexpt <- which(P[[i]]==expt$P)
Texpt <- expt$T[iexpt]
if(i > 2) logK <- c(logK, splinefun(s$out$T, s$out$logK)(Texpt))
}
# Add title, labels, and legends
title(describe.reaction(s$reaction, states = 1))
text(150, -0.1, quote(italic(P)[sat]), cex=1.2)
text(462, -4, "500 bar")
text(620, -4.3, "1000 bar")
text(796, -4.3, "1500 bar")
text(813, -1.4, "4000 bar")
legend("bottomleft",pch=unique(expt$pch),
legend=c(unique(expt$source),tail(expt$source,1)), bty="n")
#mtitle(c(describe.reaction(s$reaction), expression(italic(P)[sat]~"and 500-4000 bar")))
l1 <- quote("Revised HKF model with " * italic(g) * " function (Shock et al., 1992)")
l2 <- "Non-recommended region (Shock et al., 1992, Fig. 6)"
legend("topright", as.expression(c(l1, l2)), lty=c(1, 3), bty="n")
# Test for average divergence (excluding Psat)
expt <- expt[!expt$P %in% "Psat", ]
stopifnot(mean(abs(logK - expt$logK)) < 0.09)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/demo/NaCl.R
|
# CHNOSZ/demo/ORP.R
# First version 20100715 jmd
library(CHNOSZ)
# Calculate the temperature dependence of
# potentials vs. standard hydrogen electrode (SHE) of various electrodes (Ag/AgCl)
# and ORP standards (ZoBell, Light's, (tri)iodide)
# Use the extended Debye-Huckel equation with Alberty's parameters
oldnon <- nonideal("Alberty")
# Bard et al.'s fit to the potential
# (Bard, Parson, Jordan, Standard Potentials In Aqueous Solution, 1985)
AgAgCl.Bard <- function(T, high.T = TRUE) {
# we use the corrected high-T formula from wikipedia
if(high.T) return(0.23737 - 5.3783e-4 * T - 2.3728e-6 * T^2 - 2.2671e-9 * (T+273))
else return(0.23695 - 4.8564e-4 * T - 3.4205e-6 * T^2 - 5.869e-9 * (T+273))
}
# Function to calculate the potential of Ag/AgCl vs. SHE
# Ag(s) + Cl- = AgCl(s) + e-
# logK = -pe - logaCl
# pe = -logK - logmCl - loggamCl
# ORP = RT/F * (logK - logmCl - loggamCl)
AgAgCl <- function(T, mKCl = 4) {
# mKCl is the molality of KCl in the electrolyte
# We take it as a first approximation to be equal to
# the molality of Cl- (and to the ionic strength)
logmCl <- log10(mKCl)
# Get the logK for the reaction
logK <- subcrt(c("Ag", "Cl-", "AgCl", "e-"), c(-1, -1, 1, 1), c("cr", "aq", "cr", "aq"), T = T)$out$logK
# Get the activity coefficient for Cl-
loggamCl <- log(10) * subcrt("Cl-", T = T, IS = mKCl)$out[[1]]$loggam
# Get the pe for the solution
pe <- -logK - logmCl - loggamCl
# Convert that to Eh
Eh <- convert(pe, "Eh", T = convert(T, "K"))
return(Eh)
}
ZoBell <- function(T) {
# Doesn't work very well because we ignore the
# ferricyanide and ferrocyanide complexes
# Fe+2 = Fe+3 + e-
# logK = logaFe3 - logaFe2 - pe
# Get the logK for the reaction
logK <- subcrt(c("Fe+2", "Fe+3", "e-"), c(-1, 1, 1), T = T)$out$logK
# We use the recipe from standard methods (table 2580:II)
# 1.4080 g K4Fe(CN)6.3H2O -> 0.0033333 mol Fe+2
# 1.0975 g K3Fe(CN)6 -> 0.0033333 mol Fe+3
# 7.4555 g KCl -> 0.1 mol Cl-
logmFe2 <- logmFe3 <- log10(0.0033333)
# Get the loggam for the iron species
loggamFe2 <- log(10) * subcrt("Fe+2", T = T, IS = 1)$out[[1]]$loggam
loggamFe3 <- log(10) * subcrt("Fe+3", T = T, IS = 1)$out[[1]]$loggam
# Get the pe for the solution
pe <- -logK + logmFe3 + loggamFe3 - logmFe2 - loggamFe2
# Convert to Eh
Eh <- convert(pe, "Eh", T = convert(T, "K"))
return(Eh)
}
ZoBell.table <- function(T = NULL, which = NULL) {
# Oxidation-reduction potential of ZoBell's solution
# from Standard Methods for Water and Wastewater or YSI
# (interpolated and/or extrapolated as necessary)
# Standard methods (1997) table 2580:I
Eh.T.SMW <- 1:30
Eh.SMW <- c(0.481, 0.479, 0.476, 0.474, 0.472, 0.47, 0.468, 0.465, 0.463, 0.461,
0.459, 0.457, 0.454, 0.452, 0.45, 0.448, 0.446, 0.443, 0.441, 0.439, 0.437,
0.435, 0.432, 0.43, 0.428, 0.426, 0.424, 0.421, 0.419, 0.417)
# From YSI (2005):
# Measuring ORP on YSI 6-Series Sondes: Tips, Cautions and Limitations
# NOTE: these values are vs. Ag/AgCl (4 M KCl)
Eh.T.YSI <- seq(-5, 50, by = 5)
Eh.YSI <- c(267.0, 260.5, 254.0, 247.5, 241.0, 234.5, 228.0, 221.5, 215.0, 208.5, 202.0, 195.5)/1000
# Spline function for each of the tables
SMW <- splinefun(Eh.T.SMW, Eh.SMW)
YSI <- splinefun(Eh.T.YSI, Eh.YSI)
# Just one of the tables
Eh.fun <- get(which)
Eh.T <- get(paste("Eh.T", which, sep = "."))
if(is.null(T)) T <- Eh.T
return(data.frame(T = T, Eh = Eh.fun(T)))
}
Light <- function(T) {
# This is going to look something like
# Fe+2 = Fe+3 + e-
# logK = logaFe3 - logaFe2 - pe
# Get the logK for the reaction
logK <- subcrt(c("Fe+2", "Fe+3", "e-"), c(-1, 1, 1), T = T)$out$logK
# We use the recipe from standard methods (table 2580:II)
# 39.21 g Fe(NH4)2(SO4)2(H2O)6 -> 0.1 mol Fe+2
# 48.22 g Fe(NH4)(SO4)2(H2O)12 -> 0.1 mol Fe+3
logmFe2 <- logmFe3 <- log10(0.1)
# Get the loggam for the iron species
loggamFe2 <- log(10) * subcrt("Fe+2", T = T, IS = 0.2)$out[[1]]$loggam
loggamFe3 <- log(10) * subcrt("Fe+3", T = T, IS = 0.2)$out[[1]]$loggam
# Get the pe for the solution
pe <- -logK + logmFe3 + loggamFe3 - logmFe2 - loggamFe2
# Convert to Eh
Eh <- convert(pe, "Eh", T = convert(T, "K"))
return(Eh)
}
Iodide.table <- function(T=NULL) {
# Oxidation-reduction potential of Thermo's iodide solution
# from thermo instruction sheet 255218-001 (articlesFile_18739)
T.Iodide <- seq(0, 50, 5)
Eh.Iodide <- c(438, 435, 431, 428, 424, 420, 415, 411, 406, 401, 396)/1000
Iodide <- splinefun(T.Iodide, Eh.Iodide)
if(is.null(T)) T <- T.Iodide
return(data.frame(T = T, Eh = Iodide(T)))
}
Iodide <- function(T) {
# This is going to look something like
# 3I- = I3- + 2e-
# logK = -2pe + logaI3 - 3logaI
# Get the logK for the reaction
logK <- subcrt(c("I-", "I3-", "e-"), c(-3, 1, 2), T = T)$out$logK
# Could the activities be 0.1 M ... or something else?
logmI <- log10(2)
logmI3 <- log10(0.01)
# Get the loggam for the iodine species
loggamI <- log(10) * subcrt("I-", T = T, IS = 0.2)$out[[1]]$loggam
loggamI3 <- log(10) * subcrt("I3-", T = T, IS = 0.2)$out[[1]]$loggam
# Get the pe for the solution
pe <- ( -logK + logmI3 + loggamI3 - 3 * (logmI - loggamI) ) / 2
# Convert to Eh
Eh <- convert(pe, "Eh", T = convert(T, "K"))
return(Eh)
}
figure <- function() {
# Make some figures
# Temperatures in degrees C
T <- seq(0, 100, 5)
# Temperature-Eh diagram for various electrodes
thermo.plot.new(ylim = c(0, 0.8), xlim = c(0, 100),
ylab = axis.label("Eh"), xlab = axis.label("T"))
# Ag/AgCl electrode (Bard et al. fit)
points(T, AgAgCl.Bard(T), pch = 0)
# Ag/AgCl electrode (equilibrium calculations)
lines(T, AgAgCl(T))
# ZoBell's solution (SMW table 2580)
SMW <- ZoBell.table(which = "SMW")
points(SMW$T, SMW$Eh, pch = 1)
# ZoBell's solution (YSI tech report table)
YSI <- ZoBell.table(which = "YSI")
# Make these values referenced to SHE instead of Ag/AgCl
Eh.YSI <- YSI$Eh + AgAgCl(YSI$T)
points(YSI$T, Eh.YSI, pch = 2)
# Light's solution (equilibrium values)
lines(T, Light(T))
# Light's solution (at 25 degrees only)
points(25, 0.475 + 0.200, pch = 3)
# Thermo's I-/I3- solution
Thermo <- Iodide.table()
points(Thermo$T, Thermo$Eh, pch = 4)
# Calculated I-/I3- values
lines(T, Iodide(T))
# Add some labels
text(c(30, 30, 30, 50), c(0.72, 0.5, 0.35, 0.25),
c("Light", "ZoBell", "(Tri)Iodide", "Ag/AgCl"))
title(main = "Potentials vs standard hydrogen electrode (SHE)")
}
# Finally, make the plot
figure()
# Reset the nonideality method to default
nonideal(oldnon)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/demo/ORP.R
|
# CHNOSZ/demo/Pourbaix.R
# Eh-pH diagram for Fe-O-H with equisolubility lines
# After Pourbaix (1974, p. 312)
# 20210301 jmd first version
library(CHNOSZ)
# Load OBIGT database without organic species
# (speeds up and reduces memory needed for C diagram)
OBIGT(no.organics = TRUE)
### PARAMETERS (to be changed by the user) ###
# Choose an element
# Some mostly working ones: Fe, Cu, Au, Rh, Mn, C
# Incomplete: Al (no native metal), Ni, ...
# Not working: Cr, ...
# (Cr has no solids in OBIGT)
element <- "Fe"
# Set temperature and pressure
T <- 25
# Can use "Psat" for T >= 100 degC
P <- 1
# Ionic strength (mol/kg)
IS <- 0
# Set plot limits and resolution
pH <- c(-2, 16)
Eh <- c(-2, 2)
res <- 700
# Assign levels for equisolubility lines
levels <- seq(-6, 0, 2)
# Switches for using colors
color.fields <- TRUE
color.water <- TRUE
color.lines <- TRUE
color.names <- TRUE
# Names of aqueous species to move down
# (to avoid conflict with water lines or mineral names)
namesdown <- c("MnOH+", "MnO", "Cu+2", "CuO")
# Names of aqueous species to move down even more
namesdown2 <- c("Fe+3", "FeOH+2", "FeO+", "HFeO2", "FeO2-",
"HMnO2-", "MnO2-2")
### SCRIPT (can also be changed by the user if wanted!) ###
# Find a species with this element
# (to be used as a basis species)
elem_basis <- element
if(is.na(suppressMessages(info(elem_basis)))) {
elem_basis <- paste0(element, "+")
if(is.na(suppressMessages(info(elem_basis)))) {
elem_basis <- paste0(element, "+2")
if(is.na(suppressMessages(info(elem_basis)))) {
elem_basis <- paste0(element, "+3")
}
}
}
# Define system
basis(c(elem_basis, "H2O", "H+", "e-"))
# Find species
icr <- retrieve(element, c("O", "H"), "cr", T = T, P = P)
iaq <- retrieve(element, c("O", "H"), "aq", T = T, P = P)
# Add solids with unit activity
species(icr, 0)
# Add aqueous species with activity for first equisolubility line
species(iaq, levels[1], add = TRUE)
# Calculate affinities of formation of species
# from basis species as a function of Eh and pH
a_all <- affinity(pH = c(pH, res), Eh = c(Eh, res), T = T, P = P, IS = IS)
# Plot diagram (LAYER 1: colors for all fields)
limit.water <- fill <- NULL
if(!color.water) limit.water <- FALSE
if(!color.fields) fill <- NA
d_all <- diagram(a_all, names = FALSE, lty = 0, min.area = 0.1, limit.water = limit.water, fill = fill)
# Calculate affinities for minerals
species(icr)
# Calculate overall solubility (i.e. minimum solubility given all candidate minerals)
s <- solubility(iaq, pH = c(pH, res), Eh = c(Eh, res), T = T, P = P, IS = IS, in.terms.of = element)
# Plot diagram (LAYER 2: equisolubility lines)
diagram(s, levels = levels, contour.method = "flattest", add = TRUE, lwd = 1.5)
# Calculate affinities for aqueous species
# FIXME: should be able to remove cr species from previous affinity object
species(iaq, 0)
a_aq <- affinity(pH = c(pH, res), Eh = c(Eh, res), T = T, P = P, IS = IS)
# Plot diagram (LAYER 3: equal-activity lines for aqueous species)
col <- ifelse(color.lines, 4, 1)
# Use a white background to improve contrast
# (so the line remains visible if it coincides with an equisolubility contour)
diagram(a_aq, add = TRUE, col = "white", lwd = 1.3, names = FALSE)
# Plot diagram (LAYER 4: labels for aqueous species fields)
# Apply y offset for specified names
dy <- rep(0, nrow(a_aq$species))
dy[a_aq$species$name %in% namesdown] <- -0.3
dy[a_aq$species$name %in% namesdown2] <- -0.5
# Use a white background for names
rx <- diff(par("usr")[1:2])
for(ddx in c(-rx/700, rx/700))
diagram(a_aq, add = TRUE, lty = 2, lwd = 0.6, col = col, dx = ddx, dy = dy, col.names = "white", bold = TRUE)
ry <- diff(par("usr")[3:4])
for(ddy in c(-ry/700, ry/700))
diagram(a_aq, add = TRUE, lty = 2, lwd = 0.6, col = col, dy = dy + ddy, col.names = "white", bold = TRUE)
col.names <- ifelse(color.names, 4, 1)
diagram(a_aq, add = TRUE, lty = 0, col = col, dy = dy, col.names = col.names)
# Add solids with unit activity
species(icr, 0)
# Add aqueous species with activity for last equisolubility line
# (i.e. unit activity)
species(iaq, levels[length(levels)], add = TRUE)
# Calculate affinities of formation of species
# from basis species as a function of Eh and pH
a_all_0 <- affinity(pH = c(pH, res), Eh = c(Eh, res), T = T, P = P, IS = IS)
# Plot diagram (LAYER 5: mineral stability boundaries and water lines)
d_all_0 <- diagram(a_all_0, fill = NA, names = FALSE, lty = 0, lty.cr = 1, lwd = 3, add = TRUE)
water.lines(d_all_0, lty = 5, lwd = 1.3)
# Plot diagram (LAYER 6: large bold labels for all mineral fields)
# (this is the last layer, so names are above equal-activity lines,
# but we use positions calculated with the first equisolubility line
# so that names are within the shrunken parts of the mineral fields)
# Create labels using chemical formulas instead of name of minerals
formulas <- info(a_all$species$ispecies, check.it = FALSE)$formula
formulas[a_all$species$state == "aq"] <- ""
diagram(a_all, fill = NA, names = formulas, bold = TRUE, cex.names = 1.2, lty = 0, add = TRUE)
# Add title
Texpr <- lT(T)
Pexpr <- lP(P)
main <- bquote(.(element)*"-O-H at "*.(Texpr)*" and "*.(Pexpr))
title(main = main)
# Reset OBIGT database to run other demos
reset()
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/demo/Pourbaix.R
|
# CHNOSZ/demo/Shh.R
# Compare affinities of Sonic hedgehog and transcription factors involved in dorsal-ventral patterning
# (Dick, 2015. Chemical integration of proteins in signaling and development. https://doi.org/10.1101/015826)
library(CHNOSZ)
# To reproduce the calculations in the paper, use superseded data for [Gly] and [UPBB] 20190206
mod.OBIGT("[Gly]", G = -6075, H = -5570, S = 17.31)
mod.OBIGT("[UPBB]", G = -21436, H = -45220, S = 1.62)
# UniProt names of the proteins
pname <- c("SHH", "OLIG2", "NKX22", "FOXA2", "IRX3", "PAX6", "NKX62", "DBX1",
"DBX2", "NKX61", "PAX7", "GLI1", "GLI2", "GLI3", "PTC1", "SMO", "GLI3R")[1:11]
# Colors modified from Dessaud et al., 2008 and Hui and Angers, 2011
fill <- c(SHH = "#c8c7c8", OLIG2 = "#f9a330", NKX22 = "#ef2b2c", FOXA2 = "#6ab0b9",
NKX61 = "#b76775", DBX2 = "#35bcba", PAX7 = "#f6ef42",
PAX6 = "#4d2a59", IRX3 = "#63c54e", NKX62 = "#f24e33", DBX1 = "#d4e94e",
PTC1 = "#c7b0ee", SMO = "#8fd4ef", GLI1 = "#fcdc7e", GLI2 = "#c7e3b0", GLI3 = "#fcdc7e",
GLI3R = "#f1b1ae")
# Names for plotting
names <- c(SHH = "Shh", OLIG2 = "Olig2", NKX22 = "Nkx2.2", FOXA2 = "Foxa2",
NKX61 = "Nkx6.1", DBX2 = "Dbx2", PAX7 = "Pax7",
PAX6 = "Pax6", IRX3 = "Irx3", NKX62 = "Nkx6.2", DBX1 = "Dbx1",
PTC1 = "Ptch1", SMO = "Smo", GLI1 = "Gli1A", GLI2 = "Gli2A", GLI3 = "Gli3A",
GLI3R = "Gli3R")
# Protein indices of Shh and the transcription factors
ip <- match(pname, thermo()$protein$protein)
aa <- thermo()$protein[ip, ]
# Set up basis species
basis("CHNOS")
basis("NH3", -7)
# Save as PDF file?
pdf <- FALSE
# Draw interpretive legend?
interp <- TRUE
# Set up ranges of logfO2 and logaH2O
O2 <- seq(-70, -100, length.out = 500)
H2O <- seq(0.5, -4.5, length.out = 500)
A <- affinity(H2O = H2O, O2 = O2, iprotein = ip)
# Plot affinities per residue, compared to SHH
pl <- protein.length(ip)
names(A$values) <- pname
for(i in 1:length(A$values)) A$values[[i]] <- A$values[[i]] / pl[i]
A.SSH <- A$values$SHH
for(i in 1:length(A$values)) A$values[[i]] <- A$values[[i]] - A.SSH
ylab <- expression(bold(A)/2.303*italic(RT)*" vs Shh")
xlab <- expression(log*italic(a)[H[2]][O])
# Set up normal plot, or plot with interpretive drawings
opar <- par(no.readonly = TRUE)
par(mar = c(5.1, 4.1, 4.1, 2.1))
if(interp) {
if(pdf) pdf("tfactor_interp.pdf", width = 6, height = 6)
plot.new()
plot.window(rev(range(H2O)), c(-0.7, 4.7), xaxs = "i", yaxs = "i")
par(xpd=FALSE)
clip(range(H2O)[1], range(H2O)[2], -0.3, 4.2)
} else {
if(pdf) pdf("tfactor_affinity.pdf", width = 6, height = 6)
plot(range(H2O), c(-0.5, 4.5), type = "n", xaxs = "i", yaxs = "i", xlab = xlab, ylab = ylab, xlim = rev(range(H2O)), mgp = c(2.5, 1, 0))
}
for(i in 1:length(pl)) {
lty <- 3
lwd <- 1
# Highlight SHH with solid line
if(pname[i] == "SHH") {
lty <- 1
lwd <- 3
}
lines(H2O, A$values[[i]], lty = lty, lwd = lwd)
}
# Highlight lines for reaction sequence from OLIG2 to SHH
A <- A$values
names(A) <- pname
# Olig2
iOLIG2 <- A$OLIG2 > A$SHH
lines(H2O[iOLIG2], A$OLIG2[iOLIG2], col = fill["OLIG2"], lwd = 3)
# Foxa2 with offset to distinguish it from Nkx6.1/Dbx2
iFOXA2 <- A$FOXA2 > A$OLIG2 & A$FOXA2 > A$NKX22
lines(H2O[iFOXA2], A$FOXA2[iFOXA2], col = fill["FOXA2"], lwd = 3)
# Nkx2.2
iNKX22 <- A$NKX22 > A$FOXA2 & A$NKX22 > A$SHH
lines(H2O[iNKX22], A$NKX22[iNKX22], col = fill["NKX22"], lwd = 3)
# Pax6
iPAX6 <- A$PAX6 > A$SHH
lines(H2O[iPAX6], A$PAX6[iPAX6], col = fill["PAX6"], lwd = 3)
# Nkx6.1 with overstepping
iNKX61 <- A$NKX61 > A$DBX2
imax <- max(which(iNKX61))
iNKX61[1: (imax-20)] <- FALSE
lines(H2O[iNKX61], A$NKX61[iNKX61], col = fill["NKX61"], lwd = 3)
# Dbx2
iDBX2 <- A$DBX2 > A$NKX61 & A$DBX2 < A$IRX3
lines(H2O[iDBX2], A$DBX2[iDBX2], col = fill["DBX2"], lwd = 3)
# Irx3
iIRX3 <- A$IRX3 > A$NKX62 & A$IRX3 > A$OLIG2
lines(H2O[iIRX3], A$IRX3[iIRX3], col = fill["IRX3"], lwd = 3)
# Nkx6.2
iNKX62 <- A$NKX62 > A$IRX3 & A$NKX62 > A$DBX1
lines(H2O[iNKX62], A$NKX62[iNKX62], col = fill["NKX62"], lwd = 3)
# Dbx1
iDBX1 <- A$DBX1 > A$NKX62 & A$DBX1 > A$SHH
lines(H2O[iDBX1], A$DBX1[iDBX1], col = fill["DBX1"], lwd = 3)
# Shh
#iSHH <- A$SHH > A$DBX1
#lines(H2O[iSHH], A$SHH[iSHH], col = fill["SHH"], lwd = 3)
# The lines need names
if(interp) {
# Remove plot clip region
par(xpd = NA)
text(-2.12, -0.48, "Nkx2.2", srt = 90)
text(-0.87, -0.65, "Olig2", srt = 90)
text(0, -0.72, "Pax6", srt = 90)
text(0.06, 4.3, "Olig2", srt = 90)
text(-0.13, 4.3, "Irx3", srt = 90)
text(-0.77, 4.3, "Nkx6.1", srt = 90)
text(-.97, 4.3, "Dbx2", srt = 90)
text(-3.45, 4.3, "Nkx6.2", srt = 90)
text(-3.65, 4.3, "Dbx1", srt = 90)
} else {
text(-1.5, 0.5, "Nkx2.2")
text(-0.1, 0.3, "Pax6")
text(-0.2, 3.8, "Olig2")
text(-0.75, 2.45, "Irx3")
text(-1.13, 1.3, "Nkx6.1")
text(-1.5, 1, "Dbx2")
text(-2.4, 1.3, "Nkx6.2")
text(-3.8, 0.3, "Dbx1")
}
text(0.3, -0.15, "Shh")
text(-4.25, 0.15, "Shh")
text(-0.47, 0.5, "Pax7", srt = -35)
text(-0.22, 2, "Foxa2", srt = -61)
# Are we making an interpretive plot?
if(interp) {
# The left,bottom x,y-position and horizontal width of the bottom gradient wedge
xbot <- H2O[1]
ybot <- -1.4
wbot <- 3
# The height of the bottom gradient wedge as a function of the x position
hbot <- function(x) 0.3 + 0.08*(xbot - x)
lines(c(xbot, xbot-wbot), ybot+hbot(c(xbot, xbot-wbot)))
# Draw the base and sides of the bottom gradient wedge
lines(c(xbot, xbot-wbot), c(ybot, ybot))
lines(rep(xbot, 2), c(ybot, ybot+hbot(xbot)))
lines(rep(xbot, 2)-wbot, c(ybot, ybot+hbot(xbot-wbot)))
# Draw drop lines from reactions between TFs and Shh
xNKX22 <- H2O[max(which(A$NKX22 > A$SHH))]
lines(rep(xNKX22, 2), c(ybot, 0), lty = 2)
xOLIG2 <- H2O[max(which(A$OLIG2 > A$SHH))]
lines(rep(xOLIG2, 2), c(ybot, 0), lty = 2)
xPAX6 <- H2O[max(which(A$PAX6 > A$SHH))]
lines(rep(xPAX6, 2), c(ybot, 0), lty = 2)
# The left,bottom x,y-position and horizontal width of the top gradient wedge
xtop <- H2O[2]
ytop <- 4.7
wtop <- 5
# The height of the top gradient wedge as a function of the x position
htop <- function(x) 0.4 - 0.08*(xtop - x)
lines(c(xtop, xtop-wtop), ytop+htop(c(xtop, xtop-wtop)))
# Draw the base and sides of the top gradient wedge
lines(c(xtop, xtop-wtop), c(ytop, ytop))
lines(rep(xtop, 2), c(ytop, ytop+htop(xtop)))
lines(rep(xtop, 2)-wtop, c(ytop, ytop+htop(xtop-wtop)))
# Draw drop lines to reactions between TFs
iIRX3 <- min(which(A$IRX3 > A$OLIG2))
lines(rep(H2O[iIRX3], 2), c(A$IRX3[iIRX3], ytop+htop(H2O[iIRX3])), lty = 2)
iDBX2 <- min(which(A$DBX2 > A$NKX61))
lines(rep(H2O[iDBX2], 2), c(A$DBX2[iDBX2], ytop+htop(H2O[iDBX2])), lty = 2)
iDBX1 <- min(which(A$DBX1 > A$NKX62))
lines(rep(H2O[iDBX1], 2), c(A$DBX1[iDBX1], ytop+htop(H2O[iDBX1])), lty = 2)
# Indicate plot variables
arrows(-2.7, 2, -2.7, 2.5, 0.1)
text(-2.8, 2.3, "affinity\nvs. Shh", adj = 0)
arrows(-2.7, 2, -2.27, 2, 0.1)
text(-2.3, 1.8, expression(list(log*italic(f)[O[2]], )), adj = 0)
text(-2.3, 1.6, expression(list(log*italic(a)[H[2]*O])), adj = 0)
# Label neural progenitors
text(-2.37, -1.55, "FP")
text(-1.6, -1.55, "p3")
text(-0.53, -1.55, "pMN")
text(0.2, -1.55, "p2")
text(0.2, 5.25, "pMN")
text(-0.47, 5.25, "p2")
text(-2.2, 5.25, "p1")
text(-4, 5.25, "p0")
# Label Shh gradient and stages
text(1.2, -1.2, "Shh\ngradient", adj = 0)
text(1.2, 4.9, "Shh\ngradient", adj = 0)
text(-2.6, -0.6, expression(italic("Stage 1: loading")), adj = 0)
text(-1.5, 4.3, expression(italic("Stage 2: unloading")), adj = 0)
} else {
# Add second axis: logfO2
pu <- par("usr")
pu[1:2] <- rev(range(O2))
par(usr = pu)
axis(3, at = seq(-75, -105, by = -5))
mtext(expression(log*italic(f)[O[2]]), line = 2)
}
# All done!
par(opar)
if(pdf) dev.off()
reset()
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/demo/Shh.R
|
# CHNOSZ/demo/TCA.R 20171010
# Reproduce Fig. 6 in Canovas and Shock, 2016:
# Plots of the standard partial molal Gibbs energy of reaction for each step in
# the citric acid cycle for temperatures to 500 degrees C and pressures to 5 kbar.
library(CHNOSZ)
# These plots use calories 20220325
E.units("cal")
# Species in reactions
NADox <- "NAD(ox)-"; NADred <- "NAD(red)-2"
ADP <- "ADP-3"; ATP <- "ATP-4"
species <- list(
c("oxaloacetate-2", "pyruvate", "H2O", NADox, "citrate-3", NADred, "CO2", "H+"),
c("citrate-3", "cis-aconitate-3", "H2O"),
c("cis-aconitate-3", "H2O", "isocitrate-3"),
c("isocitrate-3", NADox, "a-ketoglutarate-2", NADred, "CO2"),
c("a-ketoglutarate-2", ADP, "HPO4-2", NADox, "succinate-2", ATP, NADred, "CO2"),
c("succinate-2", "fumarate-2", "H2"),
c("fumarate-2", "H2O", "malate-2"),
c("malate-2", NADox, "oxaloacetate-2", NADred, "H+"),
c("pyruvate", NADox, ADP, "HPO4-2", "H2O", "CO2", NADred, "H+", ATP, "H2")
)
# Reaction coefficients
coeffs <- list(
c(-1, -1, -1, -1, 1, 1, 1, 1),
c(-1, 1, 1),
c(-1, -1, 1),
c(-1, -1, 1, 1, 1),
c(-1, -1, -1, -1, 1, 1, 1, 1),
c(-1, 1, 1),
c(-1, -1, 1),
c(-1, -1, 1, 1, 1),
c(-1, -4, -1, -1, -2, 3, 4, 2, 1, 1)
)
# Species names
oxal <- quote(Oxaloacetate^-2)
pyr <- quote(Pyruvate^-"")
h2o <- quote(H[2]*O)
nox <- quote(NAD[ox]^-"")
cit <- quote(Citrate^-3)
nred <- quote(NAD[red]^-2)
co2 <- quote(CO[2*(italic(aq))])
hplus <- quote(H^+"")
iso <- quote(Isocitrate^-3)
aco <- quote(italic(cis)*"-Aconitate"^-3)
ket <- quote(alpha*"-Ketoglutarate"^-2)
adp <- quote(ADP^-3)
hpo4 <- quote(HPO[4]^-2)
suc <- quote(Succinate^-2)
atp <- quote(ATP^-4)
fum <- quote(Fumarate^-2)
h2 <- quote(H[2*(italic(aq))])
mal <- quote(Malate^-2)
# the reaction double arrow
eq <- "\u21cc"
sublist <- list(oxal = oxal, pyr = pyr, h2o = h2o, nox = nox, cit = cit, nred = nred,
co2 = co2, hplus = hplus, aco = aco, iso = iso, ket = ket, adp = adp,
hpo4 = hpo4, suc = suc, atp = atp, fum = fum, h2 = h2, mal = mal, eq = eq)
# Reaction titles
rtitle <- list(
c(substitute(" "*oxal + pyr + h2o + nox ~eq~ "", sublist), substitute(cit + nred + co2 + hplus, sublist)),
substitute(cit ~eq~ aco + h2o, sublist),
substitute(aco + h2o ~eq~ iso*" ", sublist),
c(substitute(iso + nox ~eq~ " ", sublist), substitute(ket + nred + co2*" ", sublist)),
c(substitute(ket + adp + hpo4 + nox ~eq~ "", sublist), substitute(" "*suc + atp + nred + co2, sublist)),
c(substitute(suc ~eq~ "", sublist), substitute(fum + h2, sublist)),
substitute(fum + h2o ~eq~ mal, sublist),
c(substitute(mal + nox ~eq~ " ", sublist), substitute(oxal + nred + hplus * " ", sublist)),
c(substitute(pyr + 4*nox + adp + hpo4 + 2*h2o ~eq~ " ", sublist),
substitute(3*co2 + 4*nred + 2*hplus + atp + h2 * " ", sublist))
)
# Set up plot
opar <- par(no.readonly = TRUE)
par(mfrow = c(3, 3))
ylims <- list(
c(-10, 45), c(1, 6), c(-2.5, 7.5),
c(-35, 5), c(-9, 5), c(5, 28),
c(-1.5, 6), c(14, 18), c(20, 80)
)
# Loop over reactions
for(i in seq_along(species)) {
thermo.plot.new(xlim = c(0, 500), ylim = ylims[[i]], xlab = axis.label("T"),
ylab = axis.label("DrG0", prefix = "k"), mar = c(3.0, 3.5, 3.5, 2.0))
# Loop over isobars
for(P in seq(500, 5000, 500)) {
T <- seq(0, 500, 10)
if(P==500) T <- seq(0, 350, 10)
if(P==5000) T <- seq(100, 500, 10)
# Calculate and plot standard Gibbs energy
sout <- subcrt(species[[i]], coeffs[[i]], T = T, P = P)$out
lines(T, sout$G/1000)
}
if(is.list(rtitle[[i]])) mtitle(as.expression(rtitle[[i]]), spacing = 1.6, cex = 0.8)
else mtitle(as.expression(rtitle[[i]]), line = 0.4, cex = 0.8)
}
# Make an overall title
par(xpd = NA)
text(-70, 284, "Citric Acid Cycle, after Canovas and Shock, 2016", font = 2, cex = 1.5)
par(xpd = FALSE)
par(opar)
# Reset the units
reset()
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/demo/TCA.R
|
# CHNOSZ/demo/adenine.R
# Plot thermodynamic data and model fits for aqueous adenine 20170725
library(CHNOSZ)
# Notable functions in this demo:
# EOSregress() - to regress HKF coefficients from Cp data
# mod.OBIGT() - to modify the thermodynamic database for comparisons with an older set of parameters for adenine
# LCT17 = Lowe et al., 2017 (J. Chem. Thermodyn., doi:10.1016/j.jct.2017.04.005)
# LH06 = LaRowe and Helgeson, 2006 (Geochim. Cosmochim. Acta, doi:10.1016/j.gca.2006.04.010)
# HKF = Helgeson-Kirkham-Flowers equations (e.g. Am. J. Sci., doi:10.2475/ajs.281.10.1249)
# Cp0 and V0 of adenine from LCT17 Table 4
AdH <- data.frame(
T = seq(288.15, 363.15, 5),
V = c(89.1, 89.9, 90.6, 91.3, 92, 92.7, 93.1, 93.6, 94.1, 94.9, 95.4, 95.9, 96.3, 96.9, 97.1, 97.8),
V_SD = c(1.1, 1.3, 1.1, 1, 1.1, 1, 0.9, 0.9, 0.8, 0.6, 0.7, 0.7, 0.7, 0.4, 1.1, 0.7),
Cp = c(207, 212, 216, 220, 224, 227, 230, 234, 237, 241, 243, 245, 248, 250, 252, 255),
Cp_SD = c(5, 7, 8, 7, 8, 7, 6, 7, 6, 5, 6, 6, 5, 4, 7, 5)
)
# Functions to calculate V and Cp using density model (LCT17 Eq. 28)
Vfun <- function(v1, v2, k, T) {
# Gas constant (cm3 bar K-1 mol-1)
R <- 83.144598
# Isothermal compressibility (bar-1)
beta <- water("beta", TK)$beta
v1 + v2 / (T - 228) - k * R * beta
}
Cpfun <- function(c1, c2, k, T) {
# Gas constant (J K-1 mol-1)
R <- 8.3144598
# Isobaric temperature derivative of expansivity (K-2)
daldT <- water("daldT", TK)$daldT
c1 + c2 / (T - 228) ^ 2 - k * R * T * daldT
}
# Set up units (used for axis labels and HKF calculations)
T.units("K")
# Temperature and pressure points for calculations
TK <- seq(275, 425)
P <- water("Psat", TK)$Psat
# Set up plots
opar <- par(no.readonly = TRUE)
layout(matrix(1:3), heights=c(1, 8, 8))
# Title at top
par(mar=c(0, 0, 0, 0), cex=1)
plot.new()
text(0.5, 0.5, "Heat capacity and volume of aqueous adenine\n(Lowe et al., 2017)", font=2)
# Settings for plot areas
par(mar = c(4, 4, 0.5, 1), mgp = c(2.4, 0.5, 0))
# Location of x-axis tick marks
xaxp <- c(275, 425, 6)
### Cp plot (LCT17 Figures 4 and 12) ###
plot(AdH$T, AdH$Cp, type = "p", xlim = range(TK), ylim = c(150, 350),
xlab = axis.label("T"), ylab = axis.label("Cp0"),
pch = 5, tcl = 0.3, xaxs = "i", yaxs = "i", las = 1, xaxp = xaxp
)
# Error bars (arrows trick from https://stackoverflow.com/questions/13032777/scatter-plot-with-error-bars)
arrows(AdH$T, AdH$Cp - AdH$Cp_SD, AdH$T, AdH$Cp + AdH$Cp_SD, length = 0.05, angle = 90, code = 3)
# Get LH06 predictions using HKF model;
# this version of adenine parameters has been superseded by LCT17,
# so we add them by hand
mod.OBIGT("adenine-old", formula="C5H5N5", a1=21.5046, a2=8.501, a3=-2.6632, a4=-5.3561, c1=87.88, c2=-15.87, omega=0.065)
LH06 <- subcrt("adenine-old", T = TK)$out$adenine
lines(TK, LH06$Cp, lty = 3)
# Density model (parameters from LCT17 Table 11)
lines(TK, Cpfun(160.4, -653239, -7930.3, TK), lty = 2)
# Regress HKF parameters
# Specify the terms in the HKF equations
var <- c("invTTheta2", "TXBorn")
# Build a data frame with T, P, and Cp columns
Cpdat <- data.frame(T = AdH[, "T"], P = 1, Cp = AdH[, "Cp"])
# Convert Cp data from J to cal
Cpdat$Cp <- convert(Cpdat$Cp, "cal")
# Regress HKF parameters from Cp data
HKFcoeffs <- EOSregress(Cpdat, var)$coefficients
# Get predictions from the fitted model
Cpfit <- EOScalc(HKFcoeffs, TK, P)
# Plot the fitted model
lines(TK, convert(Cpfit, "J"), lwd = 2, col = "green3")
# Format coefficients for legend; use scientific notation for c2 and omega
coeffs <- format(signif(HKFcoeffs, 4), scientific = TRUE)
# Keep c1 out of scientific notation
coeffs[1] <- signif(HKFcoeffs[[1]], 4)
ipos <- which(coeffs >= 0)
coeffs[ipos] <- paste("+", coeffs[ipos], sep = "")
fun.lab <- as.expression(lapply(1:length(coeffs), function(x) {
EOSlab(names(HKFcoeffs)[x], coeffs[x])
}))
# Add legend: regressed HKF coefficients
legend("topleft", legend = fun.lab, pt.cex = 0.1, box.col = "green3")
# Add legend: lines
legend("bottomright", lty = c(3, 2, 1), lwd = c(1, 1, 2), col = c("black", "black", "green3"), bty = "n",
legend = c("HKF model (LaRowe and Helgeson, 2006)",
"density model (Lowe et al., 2017)", "HKF model (fit using CHNOSZ)")
)
### V plot (LCT17 Figures 3 and 11) ###
plot(AdH$T, AdH$V, type = "p", xlim = range(TK), ylim = c(85, 105),
xlab = axis.label("T"), ylab = axis.label("V0"),
pch = 5, tcl = 0.3, xaxs = "i", yaxs = "i", las = 1, xaxp = xaxp
)
axis(3, labels = FALSE, tcl = 0.3, xaxp = xaxp)
axis(4, labels = FALSE, tcl = 0.3)
arrows(AdH$T, AdH$V - AdH$V_SD, AdH$T, AdH$V + AdH$V_SD, length = 0.05, angle = 90, code = 3)
# HKF model with coefficients from LH06
lines(TK, LH06$V, lty = 3)
# Density model with coefficients from LCT17
lines(TK, Vfun(73.9, -917.0, -7930.3, TK), lty = 2)
# HKF heat capacity coefficients from LCT17
LCT17 <- subcrt("adenine", T = TK)$out$adenine
lines(TK, LCT17$V, lwd = 2, col = "royalblue")
legend("bottomright", lty = c(3, 2, 1), lwd = c(1, 1, 2), col = c("black", "black", "royalblue"), bty = "n",
legend=c("HKF model (LaRowe and Helgeson, 2006)",
"density model (Lowe et al., 2017)", "HKF model (fit by Lowe et al., 2017 using CHNOSZ)")
)
# Reset database and computational settings
reset()
layout(matrix(1))
par(opar)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/demo/adenine.R
|
# CHNOSZ/demo/affinity.R
## Affinities of metabolic reactions
## After Amend and Shock, 2001, Fig. 7
## Amend, J. P. and Shock, E. L. (2001) Energetics of overall metabolic reactions of thermophilic and hyperthermophilic Archaea and Bacteria.
## FEMS Microbiol. Rev. 25, 175--243. https://doi.org/10.1016/S0168-6445(00)00062-0
library(CHNOSZ)
# Use aq state for all basis species (including O2)
basis(c("CO2", "H2", "NH3", "O2", "H2S", "H+"), "aq")
# We're going to make H2O
species("H2O")
# A function to create the plots
doplot <- function(T) {
res <- 20
# calculate affinity/2.303RT as a function of loga(H2) and loga(O2)
a <- affinity(H2 = c(-10, 0, res), O2 = c(-10, 0, res), T = T)
# Temperature in Kelvin
T.K <- convert(T, "K")
# Convert dimensionless affinity (A/2.303RT) to Gibbs energy (J/mol)
GJ <- convert(a$values[[1]], "G", T.K)
# Convert J/mol to kJ/mol
GkJ <- GJ / 1000
# Now contour the values
xyvals <- seq(-10, 0, length.out = res)
contour(x = xyvals, y = xyvals, z = t(GkJ), levels = seq(-150, -250, -20),
labcex = 1, xlab = axis.label("H2"), ylab = axis.label("O2"))
# Show the temperature
legend("topleft", bg = "white", cex = 1,
legend = describe.property("T", T, digits = 0, ret.val = TRUE) )
}
# Plot layout with space for title at top
opar <- par(no.readonly = TRUE)
layout(matrix(c(1, 1, 2, 3, 4, 5), ncol=2, byrow = TRUE), heights = c(1, 4, 4))
par(mar = c(0, 0, 0, 0))
plot.new()
# We use subcrt() to generate a reaction for titling the plot
rxnexpr <- describe.reaction(subcrt("H2O", 1)$reaction, states = "all")
# Also in the title is the property with its units
Gexpr <- axis.label("DGr", prefix="k")[[2]]
text(0.5, 0.6, substitute(paste(G~"(kJ/mol) for"~r), list(G = Gexpr, r = rxnexpr)), cex = 2)
text(0.5, 0.2, "after Amend and Shock, 2001 Figure 7", cex = 2)
# Now make the plots
par(mar = c(3, 3, 0.5, 0.5), cex = 1.3, mgp = c(2, 1, 0))
sapply(c(25, 55, 100, 150), doplot)
# affinity() can handle the three dimensions simultaneously
print(affinity(H2 = c(-10, 0, 3), O2 = c(-10, 0, 3), T = c(25, 150, 4))$values)
# Reset plot settings
layout(matrix(1))
par(opar)
## Amino acid synthesis at low and high temperatures, based on:
## Amend, J. P. and Shock, E. L. (1998) Energetics of amino acid synthesis in hydrothermal ecosystems.
## Science 281, 1659--1662. https://doi.org/10.1126/science.281.5383.1659
# Select the basis species and species of interest
# and set their activities, first for the 18 degree C case
basis(c("H2O", "CO2", "NH4+", "H2", "H+", "H2S"),
log10(c(1, 1e-4, 5e-8, 2e-9, 5e-9, 1e-15)))
species(sort(aminoacids("Z")),
log10(c(3.9, 0.7, 1.1, 3.3, 0.5, 3.8, 1.0, 5.8, 1.2, 0.7,
0.8, 1.0, 2.8, 0.5, 0.5, 4.6, 5.8, 0.6, 0.9, 2.8)/1e9))
T <- 18
TK <- convert(T, "K")
# Calculate A/2.303RT (dimensionless), convert to G of reaction (J/mol)
a <- affinity(T = T)
G.18.J <- convert(unlist(a$values), "G", T = TK)
# Convert to kJ/mol
G.18.kJ <- G.18.J / 1000
# The 100 degree C case
basis(c("H2O", "CO2", "NH4+", "H2", "H+", "H2S"),
log10(c(1, 2.2e-3, 2.9e-6, 3.4e-4, 1.9e-6, 1.6e-3)))
species(1:20, log10(c(2.8e-9, 5.0e-10, 7.9e-10, 2.4e-9, 3.6e-10,
2.7e-9, 7.2e-10, 4.2e-9, 8.6e-10, 5.0e-10, 5.7e-10, 7.2e-10, 2.0e-9,
3.6e-10,3.6e-10, 3.3e-9, 4.2e-9, 4.3e-10, 6.5e-10, 2.0e-9)))
T <- 100
TK <- convert(T, "K")
a <- affinity(T = T)
G.100.J <- convert(unlist(a$values), "G", T = TK)
G.100.kJ <- G.100.J / 1000
# Rhe average oxidation states of carbon
Z.C <- ZC(thermo()$OBIGT$formula[thermo()$species$ispecies])
# Put everything together like Table 3 in the paper
print(out <- data.frame(G.18 = G.18.kJ, G.100 = G.100.kJ, Z.C = Z.C))
# Make a plot; set units to get correct label
plot(out$Z.C, out$G.18, pch = 20, xlim = c(-1.1, 1.1), ylim = c(-200, 500),
xlab = axis.label("ZC"), ylab = axis.label("DGr", prefix = "k"))
points(out$Z.C, out$G.100, col = "red", pch = 20)
legend("topleft", pch = c(20, 20), col = c("black", "red"),
legend = describe.property(c("T", "T"), c(18, 100)))
title(main = "Amino acid synthesis, after Amend and Shock, 1998")
# 9 amino acids have negative delta Gr under hydrothermal conditions
# (cf. AS98 with 11; we are using more recent thermodynamic data)
stopifnot(sum(out$G.100 < 0) == 9)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/demo/affinity.R
|
# CHNOSZ/demo/aluminum.R
# 20171018 comparisons with calculations of SUPCRTBL
# 20190415 add diagrams from Tutolo et al., 2014
library(CHNOSZ)
## Set up plotting area
opar <- par(no.readonly = TRUE)
par(mfrow = c(2, 2))
###########
### Plot 1: boehmite - kaolinite equilibrium
###########
# After Zhu and Lu, 2009 (doi:10.1016/j.gca.2009.03.015)
# Experimental data from Table 1 of Hemley et al., 1980 (doi:10.2113/gsecongeo.75.2.210)
xT <- c(200, 200, 200, 200, 250, 250, 265, 300, 300, 300, 300)
xlogaSiO2 <- -c(2.54, 2.59, 2.65, 2.77, 2.21, 2.32, 2.12, 1.90, 1.95, 1.94, 1.90)
## Set up basis species so that axis.label shows activity of SiO2
basis(c("Al2O3","SiO2", "H2O", "O2"))
T <- 125:350
thermo.plot.new(xlim = range(T), ylim = c(-3.5, -1.5), xlab = axis.label("T"), ylab = axis.label("SiO2"))
points(xT, xlogaSiO2)
basis(delete = TRUE)
## First calculation: CHNOSZ default
# kaolinite from Berman, 1988
# boehmite from Hemingway et al., 1991
r1 <- subcrt(c("boehmite", "H2O", "SiO2", "kaolinite"), c(-1, -0.5, -1, 0.5), T = T, P = 1000, exceed.Ttr = TRUE)
## Second calculation: get SiO2(aq) from Apps and Spycher, 2004
add.OBIGT("AS04")
r2 <- subcrt(c("boehmite", "H2O", "SiO2", "kaolinite"), c(-1, -0.5, -1, 0.5), T = T, P = 1000, exceed.Ttr = TRUE)
reset()
## Third calculation: get Si(OH)4 from Akinfiev and Plyasunov, 2014
add.OBIGT("AD")
r3 <- subcrt(c("boehmite", "Si(OH)4", "H2O", "kaolinite"), c(-1, -1, 1.5, 0.5), T = T, P = 1000, exceed.Ttr = TRUE)
reset()
## Fourth calculation: minerals as in SUPCRT92
add.OBIGT("SUPCRT92") # gets kaolinite and boehmite from HDNB78
# We need exceed.Ttr = TRUE because the T limit for boehmite is 500 K (Helgeson et al., 1978)
r4 <- subcrt(c("boehmite", "H2O", "SiO2", "kaolinite"), c(-1, -0.5, -1, 0.5), T = T, P = 1000, exceed.Ttr = TRUE)
reset()
## log activity of SiO2 is -ve logK
lines(T, -r1$out$logK, lwd = 1.5)
lines(T, -r2$out$logK, col = "red", lty = 2)
lines(T, -r3$out$logK, col = "purple", lty = 3)
lines(T, -r4$out$logK, col = "blue1", lty = 4)
## Add points calculated using the SUPCRTBL package
points(seq(125, 350, 25), -c(3.489, 3.217, 2.967, 2.734, 2.517, 2.314, 2.124, 1.946, 1.781, 1.628), pch = 4, col = "red")
## Add legend and title
title(main = describe.reaction(r4$reaction), cex.main = 1.1)
legend("bottomright", lty = c(0, 0, 1, 2, 3, 0), pch = c(1, 4, NA, NA, NA, NA), lwd = c(1, 1, 1.5, 1, 1, 0),
col = c("black", "red", "black", "red", "purple", NA), bty = "n", cex = 0.9,
legend = c("Hemley et al., 1980", "SUPCRTBL", "CHNOSZ", 'add.OBIGT("AS04")', 'add.OBIGT("AD")', ""))
legend("bottomright", lty = 4, pch = NA, lwd = 1, col = "blue", legend = 'add.OBIGT("SUPCRT92")', bty = "n", cex = 0.9)
legend("topleft", c("Boehmite - Kaolinite", "After Zhu and Lu, 2009 Fig. A1"), bty = "n")
# Helgeson et al., 1978 (HDNB78): http://www.worldcat.org/oclc/13594862
# Shock et al., 1989 (SHS89): doi:10.1016/0016-7037(89)90341-4
# Berman, 1988 (Ber88): doi:10.1093/petrology/29.2.445
# Holland and Powell, 2011 (HP11): 10.1111/j.1525-1314.2010.00923.x
# Hemingway et al., 1991 (HRA91): https://pubs.usgs.gov/publication/70016664
# Apps and Spycher, 2004 (AS04): Bechtel SAIC Company, LLC ANL-NBS-HS-000043 REV 00 (DOC.20041118.0004)
###########
### Plot 2: dawsonite solubility
###########
# After Zimmer et al., 2016 (doi:10.1016/j.cageo.2016.02.013)
# Dxperimental data from Benezeth et al., 2007 Table 5 (doi:10.1016/j.gca.2007.07.003)
# (averages for each temperature in a single run)
T <- c(100.1, 100.1, 150.1, 100.1, 150.1, 99.8, 99.8, 200.7, 99.8, 50.1, 75.1, 100.3, 150.1)
logK <- -c(14.825, 14.735, 13.625, 14.79, 13.665, 14.725, 14.1775, 12.74, 14.4925, 16.8625, 15.61, 14.51, 13.455)
thermo.plot.new(c(25, 250), c(-18, -10), axis.label("T"), axis.label("logK"))
points(T, logK)
# Calculation 1: CHNOSZ default
T <- 0:250
species <- c("dawsonite", "H2O", "Al(OH)4-", "HCO3-", "Na+", "H+")
coeffs <- c(-1, -2, 1, 1, 1, 1)
Daw1 <- subcrt(species, coeffs, T = T)
lines(T, Daw1$out$logK, lwd = 1.5)
# Calculation 2: dawsonite with Cp = 0
mod.OBIGT("dawsonite", Cp = 0, a = 0, b = 0, c = 0)
Daw2 <- subcrt(species, coeffs, T = T)
lines(T, Daw2$out$logK, col = "red", lty = 2)
## Add points calculated using the SUPCRTBL package
#points(seq(25, 250, 25), c(-17.829, -16.523, -15.402, -14.425, -13.568, -12.815, -12.154, -11.581, -11.094, -10.699), pch=4, col="red")
## 20190417: recalculated using the SUPCRTBL package (timestamp: 20190309)
## with a locally updated data file that includes heat capacity coefficients of dawsonite
## from Robie and Hemingway, 1995, with typos corrected in Tutolo et al., 2014
points(seq(25, 250, 25), c(-17.829, -16.546, -15.485, -14.599, -13.856, -13.236, -12.724, -12.312, -11.997, -11.782), pch=4, col="red")
## Add legend and title
title(main = describe.reaction(Daw1$reaction), cex.main = 0.95)
legend("bottomright", lty = c(0, 0, 0, 1, 2), pch = c(1, 4, NA, NA, NA), col = c("black", "red", NA, "black", "red"), lwd = c(1, 1, 0, 1.5, 1),
bty = "n", cex = 0.9, legend = c("Ben\u00e9z\u00e9th et al., 2007", "SUPCRTBL with Cp", " coefficients for dawsonite", "CHNOSZ", "Cp(dawsonite) = 0"))
legend("topleft", c("Dawsonite solubility", "After Zimmer et al., 2016 Fig. 2"), bty = "n")
reset()
###########
### Plot 3: kaolinite solubility
###########
# After Tutolo et al., 2014, Fig. 2 (doi:10.1016/j.gca.2014.02.036)
dat <- read.csv(system.file("extdata/cpetc/TKSS14_Fig2.csv", package = "CHNOSZ"))
thermo.plot.new(c(3.5, 1.5), c(-2, 14), quote(1000 / italic(T)*"(K)"), quote(p*italic(K)))
points(dat)
# Plot line: default database
invTK <- seq(3.5, 1.6, -0.02)
T <- 1000/invTK - 273.15
sres <- subcrt(c("kaolinite", "OH-", "H2O", "Al(OH)4-", "SiO2"), c(-1, -2, -1, 2, 2), T = T)
pK <- -sres$out$logK
lines(invTK, pK, lwd = 1.5)
# Plot line: SiO2 from Apps and Spycher, 2004
add.OBIGT("AS04")
sres <- subcrt(c("kaolinite", "OH-", "H2O", "Al(OH)4-", "SiO2"), c(-1, -2, -1, 2, 2), T = T)
pK <- -sres$out$logK
lines(invTK, pK, col = "red", lty = 2)
reset()
# Plot line: Si(OH)4 from Akinfiev and Plyasunov, 2014
add.OBIGT("AD")
sres <- subcrt(c("kaolinite", "OH-", "H2O", "Al(OH)4-", "Si(OH)4"), c(-1, -2, -5, 2, 2), T = T)
pK <- -sres$out$logK
lines(invTK, pK, col = "purple", lty = 3)
reset()
# Plot line: SUPCRT92
add.OBIGT("SUPCRT92")
sres <- subcrt(c("kaolinite", "OH-", "H2O", "Al(OH)4-", "SiO2"), c(-1, -2, -1, 2, 2), T = T)
pK <- -sres$out$logK
lines(invTK, pK, col = "blue", lty = 4)
reset()
# Add points calculated using the SUPCRTBL package
T <- seq(25, 300, 25)
invTK <- 1000/(T + 273.15)
points(invTK, c(12.621, 11.441, 10.383, 9.402, 8.477, 7.597, 6.756, 5.948, 5.171, 4.422, 3.703, 3.023), pch = 4, col = "red")
# Add title and legend
par(xpd = NA)
title(main = describe.reaction(sres$reaction), cex.main = 1.1)
par(xpd = FALSE)
legend("topright", c("Kaolinite solubility", "After Tutolo et al., 2014 Fig. 2"), bty = "n")
legend("bottomleft", lty = c(0, 0, 0, 1, 2, 3, 4), pch = c(1, NA, 4, NA, NA, NA, NA),
lwd = c(1, 1, 1, 1.5, 1, 1, 1), col = c("black", "black", "red", "black", "red", "purple", "blue"),
legend = c("Various sources \u2013", " see Tutolo et al., 2014", "SUPCRTBL", "CHNOSZ", 'add.OBIGT("AS04")', 'add.OBIGT("AD")', 'add.OBIGT("SUPCRT92")'),
bty = "n", cex = 0.9)
###########
### Plot 4: albite - K-feldspar exchange
###########
# After Tutolo et al., 2014, Fig. 5 (doi:10.1016/j.gca.2014.02.036)
# Experimental data from Merino, 1975, Table 4 (doi:10.1016/0016-7037(75)90085-X)
# Plot line calculated using default database
basis(c("Al2O3", "SiO2", "K+", "Na+", "O2", "H2O", "H+"))
species(c("albite", "K-feldspar"))
T <- 100
P <- 150
a <- affinity("K+" = c(4, 7), "Na+" = c(6, 9), T = T, P = P)
diagram(a, lwd = 1.5, xlab = ratlab("K+"), ylab = ratlab("Na+"), names = FALSE)
# Plot experimental data
dat <- read.csv(system.file("extdata/cpetc/Mer75_Table4.csv", package = "CHNOSZ"))
points(dat$log.aK..aH.., dat$log.aNa..aH..)
# Plot line calculated using SUPCRT92 data
add.OBIGT("SUPCRT92")
a <- affinity("K+" = c(4, 7), "Na+" = c(6, 9), T = 100, P = 150)
diagram(a, col = "blue", lty = 4, add = TRUE, names = FALSE)
# Add SUPCRTBL calculation
logK_BL <- 2.092
logaK <- seq(4, 7, 0.5)
logaNa <- logaK + logK_BL
points(logaK, logaNa, pch = 4, col = "red")
# Add title and legend
sres <- subcrt(c("albite", "K+", "K-feldspar", "Na+"), c(-1, -1, 1, 1))
title(main = describe.reaction(sres$reaction), cex.main = 1.1)
legend("topleft", c("Albite - K-feldspar", "After Tutolo et al., 2014 Fig. 5"), bty = "n", cex = 0.9)
legend("bottomright", lty = c(0, 0, 1, 0), pch = c(1, 4, NA, NA), lwd = c(1, 1, 1.5, 0), col = c("black", "red", "black", NA),
legend = c("Merino, 1975", "SUPCRTBL", "CHNOSZ", ""), bty = "n", cex = 0.9)
legend("bottomright", lty = 4, pch = NA, lwd = 1, col = "blue", legend = 'add.OBIGT("SUPCRT92")', bty = "n", cex = 0.9)
legend("left", describe.property(c("T", "P"), c(T, P)), bty = "n")
reset()
par(opar)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/demo/aluminum.R
|
# CHNOSZ/demo/arsenic.R
# Eh-pH diagram for the system As-O-H-S,
# After Lu and Zhu, 2011 (doi:10.1007/s12665-010-0652-x)
# 20190415 extracted from go-IU.R; use retrieve()
library(CHNOSZ)
# Define temperature (degrees C), pressure (bar), grid resolution
res <- 500
T <- 25
P <- 1
# Change this to FALSE to make sharp transitions between the basis species,
# giving a diagram with straight lines around the AsS(OH)HS- wedge
blend <- TRUE
# Set basis species
basis(c("As", "H2O", "H2S", "H+", "e-"))
basis(c("H2S"), c(-3))
# Find and set formed species
iaq <- retrieve("As", c("S", "O", "H"), "aq")
icr <- retrieve("As", c("S", "O", "H"), "cr")
species(c(iaq, icr))
# Set activities of aqueous species
species(1:length(iaq), -5)
# The possible S-bearing basis species
bases <- c("H2S", "HS-", "HSO4-", "SO4-2")
# Calculate affinties of formation reactions using the speciated S basis species
m <- mosaic(bases, pH = c(0, 14, res), Eh = c(-0.8, 0.8, res), T = T, P = 1, blend = blend)
# Adjust name of realgar
m$A.species$species$name <- gsub(",alpha", "", m$A.species$species$name)
# Make the plot!
diagram(m$A.species)
# Add legend and title
dprop <- describe.property(c("T", "P"), c(T, P))
legend("bottomleft", legend = dprop, bty = "n")
t1 <- quote("As-O-H-S, "~list(Sigma*S == 10^-3~M, Sigma*As == 10^-5~M))
t2 <- "After Lu and Zhu, 2011 Fig. 2b"
mtitle(as.expression(c(t1, t2)), cex = 0.95)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/demo/arsenic.R
|
# CHNOSZ/demo/buffer.R
# Calculate buffered activities of basis species using two methods
# Ater Figure 6 of Schulte and Shock, 1995 (doi:10.1007/BF01581580)
library(CHNOSZ)
# Use Helgeson et al. (1978) minerals for closer reproduction 20201110
add.OBIGT("SUPCRT92")
b.species <- c("Fe", "CO2", "H2O", "N2", "H2", "H2S", "SiO2")
b.state <- c("cr", "gas", "liq", "gas", "gas", "aq", "aq")
b.logact <- c(0, 1, 0, 0, 0, 0, 0)
basis(b.species, b.state, b.logact)
xlim <- c(0, 350)
thermo.plot.new(xlim = xlim, ylim = c(-4, 4), xlab = axis.label("T"), ylab = axis.label("H2"))
# Method 1: in affinity(), assign name of buffer to basis species
bufferline <- function(buffer, ixlab) {
basis("H2", buffer)
a <- affinity(T = xlim, P = 300, return.buffer = TRUE, exceed.Ttr = TRUE)
lines(a$vals[[1]], a$H2, col = 3, lwd = 2)
text(a$vals[[1]][ixlab], a$H2[ixlab] + 0.2, buffer, font = 2)
}
bufferline("FeFeO", 40)
bufferline("QFM", 70)
bufferline("PPM", 204)
bufferline("HM", 102)
# Method 2: in diagram(), use the `type` argument
basis("H2", 0)
for(logact in c(-6, -10, -15)) {
species(c("formaldehyde", "HCN"), logact)
a <- affinity(T = xlim, P = 300)
d <- diagram(a, type = "H2", lty = c(3, 2), add = TRUE)
text(a$vals[[1]][13], mean(sapply(d$plotvals, c)[13, ]), logact)
}
# Add legends and title
legend("topright", legend = c("minerals", "formaldehyde", "HCN"),
lty = c(1, 3, 2), lwd = c(2, 1, 1), col = c(3, 1, 1), bg = "white", cex = 0.9)
legend("bottomright", legend = c(describe.property("P", 300),
describe.basis(c(2,4))), bg = "white", cex = 0.9)
title(main = paste("Mineral buffers and activities of aqueous species",
"(Schulte and Shock, 1995)", sep = "\n"), cex.main = 0.9)
# Reset OBIGT database
reset()
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/demo/buffer.R
|
# CHNOSZ/demo/carboxylase.R
# Animate rank-activity diagrams over a temperature
# and logaH2 gradient, or plot a single one for a single temperature
# First version ca. 200903; packaged anim.carboxylase() 20110818; converted to demo 20171030
library(CHNOSZ)
T <- 25:125
ntop <- 5
lcex <- 0.8
width <- 380
height <- 380
# Plot rank-activity diagrams for 24 carboxylases;
# 12 ribulose phosphate carboxylase
# 12 acetyl-coenzyme A carboxylase
# 6 of each type are nominally from mesophilic organisms
# and 6 from thermophilic organisms
# arranged here in order of increasing growth temperature
rubisco <- c("RBL_BRAJA", "A6YF84_9PROT", "A1E8R4_9CHLO", "A8C9T6_9MYCO", "A3EQE1_9BACT", "A5CKC7_9CHRO",
"RBL_SYNJA", "Q6JAI0_9RHOD", "RBL_METJA", "A3DND9_STAMF", "A1RZJ5_THEPD", "RBL_PYRHO")
rubisco.organisms <- c("a-proteobacterium-R", "b-proteobacterium", "Bracteacoccus", "Mycobacterium",
"Leptospirillum", "Cyanobium", "Synechococcus", "Cyanidiales",
"Methanococcus-R", "Desulfurococcus", "Thermofilum", "Pyrococcus")
accoaco <- c("Q9F7M8_PRB01", "ACCA_DEIRA", "A6CDM2_9PLAN", "A4AGS7_9ACTN", "ACCA_CAUCR", "A1VC70_DESVV",
"A6VIX9_METM7", "Q2JSS7_SYNJA", "A0GZU2_9CHLR", "A7WGI1_9AQUI", "Q05KD0_HYDTH", "ACCA_AQUAE")
accoaco.organisms <- c("g-proteobacterium", "Deinococcus", "Planctomyces", "Actinobacterium",
"a-proteobacterium-A", "d-proteobacterium", "Methanococcus-A", "Synechococcus",
"Chloroflexus", "Hydrogenobaculum", "Hydrogenobacter", "Aquifex")
# Assemble them all
organisms <- c(rubisco.organisms, accoaco.organisms)
# New scheme 20090611: red for hot, blue for cold
# Open for rubisco, filled for accoaco
col <- rep(c(rep("blue", 6), rep("red", 6)), 2)
pch <- c(rep(c(0:2, 5:7), 2), rep(c(15:20), 2))
# How many frames do we want?
res <- length(T)
if(res == 1) ido <- 1 else {
# Check for png directory
if(!"png" %in% dir()) stop("directory 'png' not present")
else if(length(dir("png")) > 0) stop("directory 'png' not empty")
# Start the plot device - multiple png figures
png(filename = "png/Rplot%04d.png", width = width, height = height)
# Add counters for lead-in and lead-out frames
ido <- c(rep(1, 15), 1:res, rep(res, 20))
}
# Set up system
basis(c("CO2", "H2O", "NH3", "H2", "H2S", "H+"),
c("aq", "liq", "aq", "aq", "aq", "aq"), c(-3, 0, -4, -6, -7, -7))
species(c(rubisco,accoaco))
# Equation for logaH2 as a function of temperature
# from Dick and Shock, 2011
# http://dx.plos.org/10.1371/journal.pone.0022782
get.logaH2 <- function(T) return(-11 + T * 3 / 40)
H2 <- get.logaH2(T)
# Calculate affinities
if(res == 1) {
basis("H2",H2)
a <- affinity(T = T)
} else a <- affinity(T = T,H2 = H2)
# Calculate activities
e <- equilibrate(a, normalize = TRUE)
# For each point make a rank plot
rank <- 1:length(e$loga.equil)
for(i in 1:length(ido)) {
# Print some progress
if(i%%20 == 0) cat("\n") else cat(".")
# Keep track of positions of previous points
loga <- numeric()
for(j in 1:length(e$loga.equil)) loga <- c(loga, e$loga.equil[[j]][ido[i]])
if(i > 4) myrank4 <- myrank3
if(i > 3) myrank3 <- myrank2
if(i > 2) myrank2 <- myrank1
if(i > 1) myrank1 <- myrank
order <- order(loga,decreasing = TRUE)
myrank <- rank(loga)
cex <- rep(1.2,24)
# Show changes by increasing point size
# Any points that changed on the step before the step before the step before?
if(i > 4) {
ichanged <- myrank3 != myrank4
cex[ichanged[order]] <- cex[ichanged[order]] + 0.1
}
# Any points that changed on the step before the step before?
if(i > 3) {
ichanged <- myrank2 != myrank3
cex[ichanged[order]] <- cex[ichanged[order]] + 0.2
}
# Any points that changed on the step before?
if(i > 2) {
ichanged <- myrank1 != myrank2
cex[ichanged[order]] <- cex[ichanged[order]] + 0.3
}
# Any points that changed on this step?
if(i > 1) {
ichanged <- myrank != myrank1
cex[ichanged[order]] <- cex[ichanged[order]] + 0.4
}
plot(rank,loga[order],col = col[order],pch = pch[order],
ylab = expression(log~italic(a)), cex = cex, cex.main = 1, cex.lab = 1, cex.axis = 1)
myT <- format(round(T, 1))[ido[i]]
myH2 <- format(round(H2, 2))[ido[i]]
title(main = substitute(list(X~degree*C, log*italic(a)[paste(H2)] == Y),
list(X = myT, Y = myH2)))
# Legends showing highest and lowest few
legend("topright", legend = c(paste("top", ntop), organisms[order[1:ntop]]),
pch = c(NA, pch[order[1:ntop]]), col = c(NA, col[order[1:ntop]]),
pt.cex = c(NA, cex[1:ntop]), cex = lcex)
order <- order(loga)
legend("bottomleft", legend = c(paste("low", ntop), organisms[order[ntop:1]]),
pch = c(NA, pch[order[ntop:1]]), col = c(NA, col[order[ntop:1]]),
pt.cex = c(NA, cex[24:(24-ntop+1)]), cex = lcex)
}
# Finish up animation stuff
if(res > 1) {
# Finish progress report
cat("\n")
# Close PNG plot device
dev.off()
# Make animated GIF using ImageMagick
cat("anim.carboxylase: converting to animated GIF...\n")
outfile <- "carboxylase.gif"
syscmd <- paste("convert -loop 0 -delay 10 png/*.png png/", outfile, sep = "")
cat(paste(syscmd,"\n"))
if(.Platform$OS.type == "unix") sres <- system(syscmd)
else sres <- shell(syscmd)
if(sres == 0) cat(paste("anim.carboxylase: animation is at png/", outfile, "\n", sep = ""))
else {
cat("anim.carboxylase: error converting to animated GIF\n")
cat("anim.carboxylase: check that 'convert' tool from ImageMagick is in your PATH\n")
}
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/demo/carboxylase.R
|
# CHNOSZ/demo/comproportionation.R
# Gibbs energy of sulfur comproportionation,
# after Fig. 1 of Amend et al., 2020 (doi:10.1111/1462-2920.14982)
# 20191112 jmd first version
library(CHNOSZ)
# Set basis species and activities
basis(c("H2S", "SO4-2", "H2O", "H+"))
basis("H2S", -3)
basis("SO4-2", -2)
# Form native sulfur from sulfide and sulfate
species("S")
# If we calculate the affinity like this, we're stuck with H2S and SO4-2
#a <- affinity(T = c(0, 100), pH = c(0, 7))
# Instead, use mosaic() to speciate H2S/HS- and SO4-2/HSO4-
bases <- list(c("H2S", "HS-"), c("SO4-2", "HSO4-"))
m <- mosaic(bases, T = c(0, 100), pH = c(0, 7))
a <- m$A.species
# Get plot values
T <- a$vals[[1]]
pH <- a$vals[[2]]
# The affinity as a function of T (rows) and pH (columns)
A <- a$values[[1]]
# Convert dimensionless affinity (A/2.303RT) to delta G (kJ / mol)
TK <- convert(T, "K")
G.J <- convert(A, "G", T = TK)
G.kJ <- G.J / 1000
# Multiply by 4
# (formation reaction in CHNOSZ is for 1 S; reaction in paper has 4 S)
G.kJ.4 <- G.kJ * 4
# Use subcrt() to write the balanced reaction (shown on the plot)
rxn <- subcrt("S", 1)$reaction
rxn$coeff <- rxn$coeff * 4
rxntext <- describe.reaction(rxn)
# Get label for Delta G (kJ / mol)
DGlab <- axis.label("DGr", prefix = "k")
# Calculate pK of H2S and HSO4-
pK_H2S <- subcrt(c("HS-", "H+", "H2S"), c(-1, -1, 1), T = T)$out$logK
pK_HSO4 <- subcrt(c("SO4-2", "H+", "HSO4-"), c(-1, -1, 1), T = T)$out$logK
# Make contour plot
filled.contour(T, pH, G.kJ.4, xlab = axis.label("T"), ylab = axis.label("pH"),
levels = -55:0,
color.palette = ifelse(getRversion() >= "3.6.0", function(n) hcl.colors(n), topo.colors),
# use plot.axes to label the contour plot (see ?filled.contour)
plot.axes = {
contour(T, pH, G.kJ.4, levels = c(-10, -30, -50), add = TRUE, col = "white", lwd = 2, labcex = 0.8)
legend("topleft", legend = rxntext, bty = "n", inset = c(0, 0.03))
legend("topleft", describe.basis(1:2), bty = "n", inset = c(0, 0.08))
lines(T, pK_H2S, lty = 2)
text(85, 6.7, expr.species("HS-"))
text(85, 6.3, expr.species("H2S"))
lines(T, pK_HSO4, lty = 2)
text(85, 3.0, expr.species("SO4-2"))
text(85, 2.5, expr.species("HSO4-"))
axis(1)
axis(2)
title("Sulfur comproportionation, after Amend et al., 2020", font.main = 1)
}
)
# Add legend text
par(xpd = NA)
text(87, 7.3, DGlab)
par(xpd = FALSE)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/demo/comproportionation.R
|
# CHNOSZ/demo/contour.R
# Gold solubility contours on logfO2-pH diagram
# After Williams-Jones et al., 2009, Fig. 3
# doi:10.2113/gselements.5.5.281
# 20181107 initial version
# 20190415 cleanup for demo
library(CHNOSZ)
# Define temperature (degrees C), pressure (bar), grid resolution
T <- 250
P <- 500
res <- 600
# Make smooth (TRUE) or sharp (FALSE) transitions between basis species
blend <- TRUE
# Set up system
basis(c("Au", "Cl-", "H2S", "H2O", "oxygen", "H+"))
iaq <- info(c("Au(HS)2-", "AuHS", "AuOH", "AuCl2-"))
species(iaq)
# This gets us close to total S = 0.01 m
basis("H2S", -2)
# Calculate solution composition for 1 mol/kg NaCl
NaCl <- NaCl(m_tot = 1, T = T, P = P)
basis("Cl-", log10(NaCl$m_Cl))
# Calculate affinity with changing basis species
bases <- c("H2S", "HS-", "HSO4-", "SO4-2")
m <- mosaic(bases, pH = c(2, 10, res), O2 = c(-41, -29, res), T = T, P = P, IS = NaCl$IS, blend = blend)
# Show predominance fields
diagram(m$A.bases, col = "red", col.names = "red", lty = 2, italic = TRUE)
diagram(m$A.species, add=TRUE, col = "blue", col.names = "blue", lwd = 2, bold = TRUE)
# Calculate and plot solubility of Au (use named 'bases' argument to trigger mosaic calculation)
species("Au")
s <- solubility(iaq, bases = bases, pH = c(2, 10, res), O2 = c(-41, -29, res), T = T, P = P, IS = NaCl$IS, blend = blend)
# Convert to ppb
s <- convert(s, "ppb")
diagram(s, type = "loga.balance", levels = c(1, 10, 100, 1000), add = TRUE)
# Add legend and title
dP <- describe.property(c("T", "P"), c(250, 500))
legend("top", dP, bty = "n", inset = c(0, 0.06))
lx <- lex(lNaCl(1), lS(0.01))
legend("topright", lx, bty = "n", inset = c(0.1, 0.05))
title(main = ("Solubility of gold (ppb), after Williams-Jones et al., 2009, Fig. 3"), font.main = 1)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/demo/contour.R
|
# CHNOSZ/demo/copper.R
## Eh-pH diagrams for copper-water-glycine
## After Fig. 2 of Aksu and Doyle, 2001
## (Aksu, S. and Doyle, F. M., 2001. Electrochemistry of copper in aqueous glycine
## solutions. J. Electrochem. Soc., 148, B51-B57. doi:10.1149/1.1344532)
library(CHNOSZ)
# We need data for Cu-Gly complexes 20190206
add.OBIGT(system.file("extdata/adds/SK95.csv", package = "CHNOSZ"))
# Add some new species to thermo()$OBIGT
m1 <- makeup(info(c("Cu+", "glycinate", "glycinate")), sum = TRUE)
mod.OBIGT(name = "Cu(Gly)2-", formula = as.chemical.formula(m1))
m2 <- makeup(info(c("Cu+2", "glycinate", "H+")), sum = TRUE)
mod.OBIGT(name = "HCu(Gly)+2", formula = as.chemical.formula(m2))
# Names of species in AD01 Table 1 and Table II
Cu_s <- c("copper", "cuprite", "tenorite")
Gly <- c("glycinium", "glycine", "glycinate")
Cu_aq <- c("Cu+", "Cu+2", "CuO2-2", "HCuO2-")
CuGly <- c("Cu(Gly)+", "Cu(Gly)2", "Cu(Gly)2-", "HCu(Gly)+2")
names <- c(Cu_s, Gly, Cu_aq, CuGly)
G <- c(
# Table I: Gibbs energies in kJ/mol
c(0, -146, -129.7,
-384.061, -370.647, -314.833,
49.98, 65.49, -183.6, -258.5, -298.2)*1000,
# Table II: Association constants, converted to Gibbs energy
convert(c(15.64, 10.1, 2.92), "G")
)
# Run updates in order so later species take account of prev. species' values
getG <- function(x) info(info(x))$G
for(i in 1:length(G)) {
myG <- G[i]
if(i == 12) myG <- myG + getG("Cu+2") + 2*getG("glycinate")
if(i == 13) myG <- myG + getG("Cu+") + 2*getG("glycinate")
if(i == 14) myG <- myG + getG("Cu(Gly)+")
# Energies are in Joules, so we have to change units of species in default OBIGT 20220325
mod.OBIGT(names[i], G = myG, E_units = "J")
}
# In Fig. 2b, total log activities of Cu (Cu_T) and glycine (L_T) are -4 and -1
basis(c("Cu+2", "H2O", "H+", "e-", "glycinium", "CO2"), c(999, 0, 999, 999, -1, 999))
# Add solids and aqueous species
species(Cu_s)
species(c(Cu_aq, CuGly), -4, add = TRUE)
names <- c(Cu_s, Cu_aq, CuGly)
# Mosaic diagram with glycine speciation as a function of pH
m <- mosaic(bases = Gly, pH = c(0, 16, 500), Eh = c(-0.6, 1.0, 500))
fill <- c(rep("lightgrey", 3), rep("white", 4), rep("lightblue", 4))
d <- diagram(m$A.species, fill = fill, names = FALSE, xaxs = "i", yaxs = "i", fill.NA = "pink2", limit.water = TRUE)
# Adjustments for labels
names <- names[sort(unique(as.numeric(d$predominant)))]
for(i in 1:length(names)) {
if(i %in% 1:3) lab <- names[i] else lab <- expr.species(names[i])
# Some manual adjustment so labels don't collide
srt <- dy <- dx <- 0
if(names[i] == "tenorite") dy <- -0.1
if(names[i] == "CuO2-2") dy <- -0.1
if(names[i] == "HCu(Gly)+2") srt <- 90
if(names[i] == "HCu(Gly)+2") dx <- -0.2
if(names[i] == "Cu(Gly)+") srt <- 90
text(na.omit(d$namesx)[i]+dx, na.omit(d$namesy)[i]+dy, lab, srt = srt)
}
# Add glycine ionization lines
d <- diagram(m$A.bases, add = TRUE, col = "darkblue", lty = 3, names = FALSE)
text(d$namesx, -0.5, Gly, col = "darkblue")
# Add water lines and title
water.lines(d)
mtitle(expression("Copper-water-glycine at 25"~degree*"C and 1 bar",
"After Aksu and Doyle, 2001 (Fig. 2b)"))
# Done!
reset()
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/demo/copper.R
|
# CHNOSZ/demo/dehydration.R
# Plot temperature dependence of log K for some dehydration reactions
library(CHNOSZ)
# The RSVGTipsDevice package allows us to create an SVG file with
# tooltips and hyperlinks
if(require("RSVGTipsDevice")) {
# Because the tooltip titles in the SVG file are shown by recent browsers,
# we do not need to draw the tooltips explicitly, so set toolTipMode = 0
devSVGTips("dehydration.svg", toolTipMode = 0, title = "Dehydration reactions")
# Unfortunately, plotmath can't be used with devSVGTips,
# so axis labels here don't contain italics.
T <- seq(1, 175)
plot(range(T), c(-2, 1), type = "n", xlab = "T, °C", ylab = "log K")
title(main = "Dehydration reactions")
reactants <- c("[AABB]", "[AABB]", "malate-2", "goethite", "gypsum", "epsomite", "ethanol")
products <- c("[UPBB]", "[PBB]", "fumarate-2", "hematite", "anhydrite", "hexahydrite", "ethylene")
rstate <- c("aq", "cr", "aq", "cr", "cr", "cr", "aq")
pstate <- c("aq", "cr", "aq", "cr", "cr", "cr", "gas")
rcoeff <- c(-1, -1, -1, -2, -0.5, -1, -1)
pcoeff <- c(1, 1, 1, 1, 0.5, 1, 1)
# Position and rotation of the names
ilab <- c(140, 120, 60, 60, 20, 120, 120)
srt <- c(10, 29, 25, 12, 13, 20, 35)
# Reference and temperature for examples of similar calculations
ex.T <- c(NA, NA, NA, NA, 40, NA, 170)
ex.txt <- c(NA, NA, NA, NA, "cf. Mercury et al., 2001", NA, "Shock, 1993")
ex.doi <- c(NA, NA, NA, NA, "10.1016/S0883-2927(00)00025-1", NA, "10.1016/0016-7037(93)90542-5")
for(i in 1:length(reactants)) {
# Lines
s <- subcrt(c(reactants[i], products[i], "H2O"),
c(rstate[i], pstate[i], "liq"),
c(rcoeff[i], pcoeff[i], 1), T = T)
lines(T, s$out$logK)
# Points
if(!is.na(ex.T[i])) {
URL <- paste0("https://doi.org/", ex.doi[i])
setSVGShapeURL(URL, target = "_blank")
setSVGShapeContents(paste0("<title>", ex.txt[i], "</title>"))
# We would use this instead with toolTipMode = 1 :
#setSVGShapeToolTip(title = ex.txt[i])
points(ex.T[i], s$out$logK[ex.T[i]])
}
# Names
for(j in 1:2) {
formula <- thermo()$OBIGT$formula[s$reaction$ispecies[j]]
key1 <- thermo()$OBIGT$ref1[s$reaction$ispecies[j]]
# Remove suffix from the key (e.g. "DLH06 [S15]" --> "DLH06")
key1 <- strsplit(key1, " ")[[1]][1]
ikey1 <- which(thermo()$refs$key == key1)
URL1 <- thermo()$refs$URL[ikey1]
setSVGShapeURL(URL1, target = "_blank")
setSVGShapeContents(paste0("<title>", paste(formula, s$reaction$state[j]), "</title>"))
if(j == 1) dy <- 0.08 else dy <- -0.03
if(j == 1) dx <- 0 else dx <- 5
# Strip charge from names
name <- gsub("-.*", "", s$reaction$name[j])
text(T[ilab[i]] + dx, s$out$logK[ilab[i]] + dy, name, adj = 1, srt = srt[i])
# Add a second reference link if needed
key2 <- thermo()$OBIGT$ref2[s$reaction$ispecies[j]]
if(!is.na(key2)) {
ikey2 <- which(thermo()$refs$key == key2)
URL2 <- thermo()$refs$URL[ikey2]
setSVGShapeURL(URL2, target = "_blank")
setSVGShapeContents("<title>2nd reference</title>")
text(T[ilab[i]] + dx, s$out$logK[ilab[i]] + dy, "(*)", adj = 0)
}
}
}
# Dotted line for logaH2O = 0
abline(h = 0, lty = 3)
# Done!
dev.off()
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/demo/dehydration.R
|
# CHNOSZ/demo/density.R
# Make T-P diagram for H2O, colored according to density
library(CHNOSZ)
# IAPWS95 or SUPCRT92
method <- "IAPWS95"
# Low or high T,P range
TPrange <- "low"
blue <- "blue"
if(TPrange == "low") {
T <- seq(300, 800, 10)
P <- seq(0, 600, 12)
## Uncomment these lines to make high-resolution plot (used on https://chnosz.net/demos/)
#T <- seq(300, 800, 2)
#P <- seq(0, 600, 2)
bias <- 1.68
} else {
# Upper T,P limit for SUPCRT92: 2250 degC, 30000 bar
T <- seq(273, 2523, 50)
P <- seq(1, 30000, length.out=50)
# To attempt to match the colors using the different methods
# (ranges are different because IAPWS95 reports higher density in
# the high-P, low-T region, where SUPCRT92 doesn't give output)
if(method == "IAPWS95") bias <- 2.2
else if(method == "SUPCRT92") {
bias <- 2.1
blue <- "#0d0dff"
}
}
TP <- expand.grid(T = T, P = P)
if(method == "IAPWS95") {
# The following should trigger parallel calculations
# if nrow(TP) (5751 for TPrange = "low") is >= thermo()$opt$paramin (default 1000)
rho <- palply("TP", 1:nrow(TP), function(i){CHNOSZ::rho.IAPWS95(TP$T[i], TP$P[i])})
} else if(method == "SUPCRT92") {
rho <- water.SUPCRT92("rho", TP$T, TP$P)
# water.SUPCRT92 returns 0 when the density can't be calculated
rho[rho == 0] <- NA
}
rho.num <- unlist(rho)
rho.mat <- matrix(rho.num, nrow = length(T), ncol = length(P))
# Blueest for most dense, reddest for least dense
# bias is adjusted to white for the critical density
ncol <- 500
col <- colorRampPalette(c("red", "white", blue), bias = bias)(ncol)
# First make a background image (for debugging -
# will be visible only if some density calculations fail)
fill.mat <- matrix(0, nrow = length(T), ncol = length(P))
image(T, P, fill.mat, col = "black", xlab = axis.label("T", "K"), ylab = axis.label("P"), useRaster = TRUE, yaxt = "n")
axis(2, at = c(1, seq(100, 600, 100)))
# Now plot densities
image(T, P, rho.mat, col = col, add = TRUE, useRaster = TRUE)
# Add a title and calculate saturation line
if(method == "IAPWS95") {
title(main = expression("Density of"~H[2]*O~"inverted from IAPWS-95 equations"))
## title(main = expression("Line calculated using auxiliary equations for saturation"), line = 0.8)
Psat <- convert(WP02.auxiliary("P.sigma", T), "bar")
} else if(method == "SUPCRT92") {
title(main = expression("Density of"~H[2]*O~"calculated using SUPCRT92"))
Psat <- water.SUPCRT92("Psat", T, "Psat")[,1]
}
### Plot saturation line
##lines(T, Psat, lwd = 6)
##lines(T, Psat, lwd = 3, col = "gold")
# Add a color key
if(TPrange == "low") {
x <- c(355, 395, 402)
y <- c(170, 520)
} else if(TPrange == "high") {
x <- c(600, 780, 800)
y <- c(10000, 25000)
}
ykey <- seq(y[1], y[2], length.out = ncol+1)
for(i in 1:ncol) rect(x[1], ykey[i], x[2], ykey[i+1], col = col[i], border = NA)
rect(x[1], ykey[1], x[2], rev(ykey)[1])
# Label the extrema
rrange <- range(rho.num, na.rm = TRUE)
text(x[3], ykey[1], as.expression(substitute(x~kg/m^3, list(x = round(rrange[1], 4)))), adj = 0, col = "white")
text(x[3], rev(ykey)[1], as.expression(substitute(x~kg/m^3, list(x = round(rrange[2], 4)))), adj = 0, col = "white")
# Label the critical density
rlevels <- seq(rrange[1], rrange[2], length.out = ncol+1)
rho.critical <- 322
icrit <- which.min(abs(rlevels-rho.critical))
text(x[3], ykey[icrit], as.expression(substitute(x~kg/m^3~group("(", rho[c], ")"), list(x = rho.critical))), adj = 0, col = "white")
#if(method == "IAPWS95") {
# # The saturation line is very accurate but not quite perfect;
# # we can show whether it is on the liquid or vapor side
# ina <- is.na(P.sigma)
# rho.sigma <- rho.IAPWS95(T[!ina], P.sigma[!ina])
# col <- rep("blue", length(rho.sigma))
# col[rho.sigma < 322] <- "red"
# points(T[!ina], P.sigma[!ina], col=col, pch=20)
#}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/demo/density.R
|
# CHNOSZ/demo/glycinate.R
# Plot logK of metal-glycinate complexes
# 20190207
library(CHNOSZ)
# Divalent metals
di <- c("Cu+2", "Ni+2", "Co+2", "Mn+2", "Zn+2", "Cd+2")
# Divalent metals with one glycinate
di1 <- c("Cu(Gly)+", "Ni(Gly)+", "Co(Gly)+", "Mn(Gly)+", "Zn(Gly)+", "Cd(Gly)+")
# Divalent metals with two glycinates
di2 <- c("Cu(Gly)2", "Ni(Gly)2", "Co(Gly)2", "Mn(Gly)2", "Zn(Gly)2", "Cd(Gly)2")
# Monovalent metals
mo <- c("Au+", "Ag+", "Na+", "Tl+", "Cu+")
# Monovalent metals with one glycinate
mo1 <- c("Au(Gly)", "Ag(Gly)", "Na(Gly)", "Tl(Gly)", "Cu(Gly)")
# Monovalent metals with two glycinates
mo2 <- c("Au(Gly)2-", "Ag(Gly)2-", "Na(Gly)2-", "Tl(Gly)2-", "Cu(Gly)2-")
# Set the temperature values
T <- seq(0, 150, 10)
# Calculate the logKs using data from Azadi et al., 2019
# doi:10.1016/j.fluid.2018.10.002
logK_di1 <- logK_di2 <- logK_mo1 <- logK_mo2 <- list()
for(i in 1:length(di1)) logK_di1[[i]] <- subcrt(c(di[i], "glycinate", di1[i]), c(-1, -1, 1), T = T)$out$logK
for(i in 1:length(di2)) logK_di2[[i]] <- subcrt(c(di[i], "glycinate", di2[i]), c(-1, -2, 1), T = T)$out$logK
for(i in 1:length(mo1)) logK_mo1[[i]] <- subcrt(c(mo[i], "glycinate", mo1[i]), c(-1, -1, 1), T = T)$out$logK
for(i in 1:length(mo2)) logK_mo2[[i]] <- subcrt(c(mo[i], "glycinate", mo2[i]), c(-1, -2, 1), T = T)$out$logK
# Calculate the logKs for divalent metals using data from Shock and Koretsky, 1995
# doi:10.1016/0016-7037(95)00058-8
add.OBIGT(system.file("extdata/adds/SK95.csv", package = "CHNOSZ"))
logK_di1_SK95 <- logK_di2_SK95 <- list()
for(i in 1:length(di1)) logK_di1_SK95[[i]] <- subcrt(c(di[i], "glycinate", di1[i]), c(-1, -1, 1), T = T)$out$logK
for(i in 1:length(di2)) logK_di2_SK95[[i]] <- subcrt(c(di[i], "glycinate", di2[i]), c(-1, -2, 1), T = T)$out$logK
reset()
# Set up the plots
opar <- par(no.readonly = TRUE)
layout(matrix(1:6, byrow = TRUE, nrow = 2), widths = c(2, 2, 1))
par(mar = c(4, 3.2, 2.5, 0.5), mgp = c(2.1, 1, 0), las = 1, cex = 0.8)
xlab <- axis.label("T")
ylab <- axis.label("logK")
# First row: divalent metals
matplot(T, sapply(logK_di1, c), type = "l", lwd = 2, lty = 1, xlab = xlab, ylab = ylab)
matplot(T, sapply(logK_di1_SK95, c), type = "l", lwd = 2, lty = 2, add = TRUE)
legend(-9, 7.7, c("Azadi et al., 2019", "Shock and Koretsky, 1995"), lty = c(1, 2), bty = "n", cex = 1)
mtext(expression(M^"+2" + Gly^"-" == M*(Gly)^"+"), line = 0.5)
matplot(T, sapply(logK_di2, c), type = "l", lwd = 2, lty = 1, xlab = xlab, ylab = ylab)
matplot(T, sapply(logK_di2_SK95, c), type = "l", lwd = 2, lty = 2, add = TRUE)
legend(-9, 14, c("Azadi et al., 2019", "Shock and Koretsky, 1995"), lty = c(1, 2), bty = "n", cex = 1)
mtext(expression(M^"+2" + 2*Gly^"-" == M*(Gly)[2]), line = 0.5)
plot.new()
par(xpd = NA)
legend("right", as.expression(lapply(di, expr.species)), lty = 1, col = 1:6, bty = "n", cex = 1.2, lwd = 2)
# Add overall title
text(0, 1, "metal-\nglycinate\ncomplexes", cex = 1.3, font = 2)
par(xpd = FALSE)
# Second row: monovalent metals
matplot(T, sapply(logK_mo1, c), type = "l", lwd = 2, lty = 1, xlab = xlab, ylab = ylab)
mtext(expression(M^"+" + Gly^"-" == M*(Gly)), line = 0.5)
matplot(T, sapply(logK_mo2, c), type = "l", lwd = 2, lty = 1, xlab = xlab, ylab = ylab)
mtext(expression(M^"+" + 2*Gly^"-" == M*(Gly)[2]^"-"), line = 0.5)
plot.new()
par(xpd = NA)
legend("right", as.expression(lapply(mo, expr.species)), lty = 1, col = 1:5, bty = "n", cex = 1.2, lwd = 2)
par(xpd = FALSE)
layout(matrix(1))
par(opar)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/demo/glycinate.R
|
# CHNOSZ/demo/gold.R: Au solubility calculations
# 20181101 jmd first version
# 20181109 add calculation of K+ molality
# 20190127 update Au species in OBIGT, not here
library(CHNOSZ)
# Set up system
# Use H2S here: it's the predominant species at the pH of the QMK buffer -- see sulfur()
basis(c("Au", "Al2O3", "quartz", "Fe", "K+", "Cl-", "H2S", "H2O", "oxygen", "H+"))
# set molality of K+ in completely dissociated 0.5 molal KCl
# NOTE: This value is used only for making the legend;
# activities corrected for ionic strength are computed below
basis("K+", log10(0.5))
# Create a pH buffer
mod.buffer("QMK", c("quartz", "muscovite", "K-feldspar"), "cr", 0)
# Define colors for Au(HS)2-, AuHS, AuOH, AuCl2-
# after Williams-Jones et al., 2009
# (doi:10.2113/gselements.5.5.281)
col <- c("#ED4037", "#F58645", "#0F9DE2", "#22CC88")
# Sulfur logfO2-pH diagrams showing redox and pH buffers at four temperatures 20181031
sulfur <- function() {
species(c("H2S", "HS-", "HSO4-", "SO4-2"))
T <- c(200, 300, 400, 500)
P <- 1000
O2min <- c(-50, -40, -30, -25)
O2max <- c(-30, -20, -20, -10)
par(mfrow=c(2, 2))
for(i in 1:4) {
a <- affinity(pH = c(0, 14), O2 = c(O2min[i], O2max[i]), T = T[i], P = 1000)
diagram(a)
basis("H+", "QMK")
pH_QMK <- -affinity(T = T[i], P = P, return.buffer = TRUE)$`H+`
abline(v = pH_QMK, lty = 2)
basis("O2", "HM")
O2_HM <- affinity(T = T[i], P = P, return.buffer = TRUE)$O2
abline(h = O2_HM, lty = 2, col = "blue")
text(12, O2_HM, "HM", adj = c(0, -0.5), col = "blue")
basis("O2", "PPM")
O2_PPM <- affinity(T = T[i], P = P, return.buffer = TRUE)$O2
abline(h = O2_PPM, lty = 2, col = "blue")
text(12, O2_PPM, "PPM", adj = c(0, -0.5), col = "blue")
# remove the buffers for next plot
basis("O2", 0)
basis("pH", 0)
}
}
# log(m_Au)-pH diagram like Fig. 7 of Akinfiev and Zotov, 2001
# (http://pleiades.online/cgi-perl/search.pl/?type=abstract&name=geochem&number=10&year=1&page=990)
Au_pH1 <- function() {
# Apply PPM buffer for fO2 and aH2S
basis("O2", "PPM")
basis("H2S", "PPM")
# Calculate solubility of gold
species("Au")
iaq <- info(c("Au(HS)2-", "AuHS", "AuOH"))
# (set IS = 0 for diagram to show "log m" instead of "log a")
s <- solubility(iaq, pH = c(3, 8), T = 300, P = 1000, IS = 0)
# Make diagram and show total log molality
diagram(s, ylim = c(-10, -5), col = col, lwd = 2, lty = 1)
diagram(s, add = TRUE, type = "loga.balance", lwd = 3, lty = 2)
# Add neutral pH line
pH <- -subcrt(c("H2O", "H+", "OH-"), c(-1, 1, 1), T = 300, P = 1000)$out$logK/2
abline(v = pH, lty = 3)
# Make legend and title
dprop <- describe.property(c("T", "P", "IS"), c(300, 1000, 0))
legend("topleft", dprop, bty = "n")
dbasis <- describe.basis(c(9, 7))
legend("bottomright", dbasis, bty = "n")
title(main=("After Akinfiev and Zotov, 2001, Fig. 7"), font.main = 1)
}
# log(m_Au)-pH diagram similar to Fig. 12b of Stefansson and Seward, 2004
# (doi:10.1016/j.gca.2004.04.006)
Au_pH2 <- function() {
# Apply PPM buffer for fO2 and aH2S
basis("O2", "PPM")
basis("H2S", "PPM")
# Calculate solubility of gold
# (set IS = 0 for diagram to show "log m" instead of "log a")
species("Au")
iaq <- info(c("Au(HS)2-", "AuHS", "AuOH", "AuCl2-"))
s <- solubility(iaq, pH = c(3, 8), T = 450, P = 1000, IS = 0)
# Make diagram and show total log molality
diagram(s, ylim = c(-8, -3), col = col, lwd = 2, lty = 1)
diagram(s, add = TRUE, type = "loga.balance", lwd = 3, lty = 2)
# Add neutral pH line
pH <- -subcrt(c("H2O", "H+", "OH-"), c(-1, 1, 1), T = 450, P = 1000)$out$logK/2
abline(v = pH, lty = 3)
# Make legend and title
dprop <- describe.property(c("T", "P", "IS"), c(450, 1000, 0))
legend("topleft", dprop, bty = "n")
dbasis <- describe.basis(c(6, 9, 7))
legend("topright", dbasis, bty = "n")
title(main=("After Stef\u00e1nsson and Seward, 2004, Fig. 12b"), font.main = 1, cex.main = 1.1)
}
# Estimate the Cl- molality and ionic strength for a hypothetical
# NaCl solution with total chloride equal to specified NaCl + KCl solution,
# then estimate the molality of K+ in that solution 20181109
chloride <- function(T, P, m_NaCl, m_KCl) {
NaCl <- NaCl(m_tot = m_NaCl + m_KCl, T = T, P = P)
# Calculate logK of K+ + Cl- = KCl, adjusted for ionic strength
logKadj <- subcrt(c("K+", "Cl-", "KCl"), c(-1, -1, 1), T = T, P = P, IS = NaCl$IS)$out$logK
# What is the molality of K+ from 0.5 mol KCl in solution with 2 mol total Cl
m_K <- m_KCl / (10^logKadj * NaCl$m_Cl + 1)
list(IS = NaCl$IS, m_Cl = NaCl$m_Cl, m_K = m_K)
}
# log(m_Au)-T diagram like Fig. 2B of Williams-Jones et al., 2009
# (doi:10.2113/gselements.5.5.281)
Au_T1 <- function() {
# Apply PPM buffer for fO2 and aH2S
basis("O2", "PPM")
basis("H2S", "PPM")
# Apply QMK buffer for pH
basis("H+", "QMK")
# Estimate solution composition for 1.5 m NaCl and 0.5 m KCl
chl <- chloride(T = seq(150, 550, 10), P = 1000, m_NaCl = 1.5, m_KCl = 0.5)
# Calculate solubility of gold
species("Au")
iaq <- info(c("Au(HS)2-", "AuHS", "AuOH", "AuCl2-"))
s <- solubility(iaq, T = seq(150, 550, 10), `Cl-` = log10(chl$m_Cl), `K+` = log10(chl$m_K), P = 1000, IS = chl$IS)
# Make diagram and show total log molality
diagram(s, ylim = c(-10, -3), col = col, lwd = 2, lty = 1)
diagram(s, add = TRUE, type = "loga.balance", lwd = 3, lty = 2)
# Make legend and title
dP <- describe.property("P", 1000)
dNaCl <- expression(italic(m)[NaCl] == 1.5)
dKCl <- expression(italic(m)[KCl] == 0.5)
legend("topleft", c(dP, dNaCl, dKCl), bty = "n")
dH2S <- describe.basis(7, molality=TRUE)
dO2 <- describe.basis(9)
dpH <- describe.basis(10)
legend(300, -3, c(dH2S, dO2, dpH), bty = "n")
title(main=("After Williams-Jones et al., 2009, Fig. 2B"), font.main = 1)
}
# log(m_Au)-T diagram like Fig. 2A of Williams-Jones et al., 2009 and Fig. 8a of Pokrovski et al., 2014
# (doi:10.2113/gselements.5.5.281)
# (doi:10.1144/SP402.4)
Au_T2 <- function() {
# Total S = 0.01 m
basis("H2S", -2)
# Apply HM buffer for fO2
basis("O2", "HM")
# Apply QMK buffer for pH
basis("H+", "QMK")
# Estimate solution composition for 1.5 m NaCl and 0.5 m KCl
chl <- chloride(T = seq(150, 550, 10), P = 1000, m_NaCl = 1.5, m_KCl = 0.5)
# Calculate solubility of gold
species("Au")
iaq <- info(c("Au(HS)2-", "AuHS", "AuOH", "AuCl2-"))
s <- solubility(iaq, T = seq(150, 550, 10), `Cl-` = log10(chl$m_Cl), `K+` = log10(chl$m_K), P = 1000, IS = chl$IS)
# # Uncomment to calculate solubility considering speciation of sulfur
# bases <- c("H2S", "HS-", "SO4-2", "HSO4-")
# s <- solubility(iaq, bases = bases, T = seq(150, 550, 10), `Cl-` = log10(chl$m_Cl), `K+` = log10(chl$m_K), P = 1000, IS = chl$IS)
# Make diagram and show total log molality
diagram(s, ylim = c(-10, -3), col = col, lwd = 2, lty = 1)
diagram(s, add = TRUE, type = "loga.balance", lwd = 3, lty = 2)
# Make legend and title
dP <- describe.property("P", 1000)
dNaCl <- expression(italic(m)[NaCl] == 1.5)
dKCl <- expression(italic(m)[KCl] == 0.5)
legend("topleft", c(dP, dNaCl, dKCl), bty = "n")
dH2S <- expr.species("H2S", value = 0.01, molality = TRUE)
dO2 <- describe.basis(9)
dpH <- describe.basis(10)
legend(300, -3, c(dH2S, dO2, dpH), bty = "n")
title(main=("After Williams-Jones et al., 2009, Fig. 2A"), font.main = 1)
}
# Make plots
opar <- par(no.readonly = TRUE)
par(mfrow = c(2, 2))
Au_pH1()
Au_pH2()
Au_T1()
Au_T2()
par(opar)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/demo/gold.R
|
# CHNOSZ/demo/ionize.R
## ionize.aa(): Contour plots of net charge and ionization properties of LYSC_CHICK
library(CHNOSZ)
aa <- pinfo(pinfo("LYSC_CHICK"))
pH <- seq(0, 14, 0.2)
T <- seq(0, 200, 2)
val <- expand.grid(pH = pH, T = T)
par(mfrow = c(2, 2))
for(X in c("Z", "A", "Cp", "V")) {
Y <- ionize.aa(aa, property = X, pH = val$pH, T = val$T)
contour(pH, T, matrix(Y[, 1], ncol = length(T)),
xlab = "pH", ylab = axis.label("T"))
title(main = axis.label(X))
}
par(mfrow = c(1, 1))
pu <- par("usr")
text(mean(pu[1:2]), sum(pu[3:4])*0.45,
"additive properties of ionization of LYSC_CHICK")
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/demo/ionize.R
|
# CHNOSZ/demo/lambda.R
# Plot effects of lambda transition in quartz
# After Berman 1988 Figs. 1 and 2
library(CHNOSZ)
opar <- par(no.readonly = TRUE)
layout(matrix(c(1, 4:2, 1, 7:5), nrow = 4), heights = c(0.7, 3, 3, 3))
# Plot title first
par(mar = c(0, 0, 0, 0))
plot.new()
text(0.5, 0.5, "Effects of lambda transition in quartz, after Berman (1988) Figs. 1 and 2", cex = 1.8)
par(mar = c(4, 4.5, 1, 0.5), cex = 0.8)
TC <- 0:1200
T <- convert(TC, "K")
labplot <- function(x) label.plot(x, xfrac = 0.9, yfrac = 0.1, paren = TRUE)
Cplab <- axis.label("Cp")
Vlab <- axis.label("V")
Tlab <- axis.label("T")
# Calculate properties at 1 kbar with and without transition
Qz_1bar <- Berman("quartz", T = T)
Qz_1bar_notrans <- Berman("quartz", T = T, calc.transition = FALSE)
## Fig. 1a: volume
plot(TC, Qz_1bar$V, type = "l", xlab = Tlab, ylab = Vlab, ylim = c(22.5, 24))
# FIXME: Why don't we get the curvature his plot for V shows?
# Should it be in the v4 parameter (but it's zero)??
## Add data points digitized from Fig. 3B of Helgeson et al., 1978
## and Fig. 1a of Berman, 1988
skinner <- list(T = c(550, 560, 570, 580, 590), V = c(23.44, 23.48, 23.54, 23.72, 23.72))
robie <- list(T = 575, V = 23.72)
ghioroso <- list(T = c(0, 100, 200, 300, 400, 500, 575, 575, 675, 775, 875, 975),
V = c(22.7, 22.77, 22.85, 22.94, 23.1, 23.3, 23.5, 23.71, 23.69, 23.69, 23.71, 23.73))
points(skinner$T, skinner$V, pch = 19)
points(robie$T, robie$V)
points(ghioroso$T, ghioroso$V, pch = 0)
## Calculate finite difference derivative of dGlambda/dP = Vlambda between 1 and 1.001 bar
Glambda_1bar <- Qz_1bar_notrans$G - Qz_1bar$G
Qz_1.001bar <- Berman("quartz", T = T, P = 1.001)
Qz_1.001bar_notrans <- Berman("quartz", T = T, P = 1.001, calc.transition = FALSE)
Glambda_1.001bar <- Qz_1.001bar_notrans$G - Qz_1.001bar$G
dGlambdadP <- (Glambda_1.001bar - Glambda_1bar) / 0.001
# We're using Joules, so multiply by ten to get cm^3
Vlambda <- -10 * dGlambdadP
VQz <- Qz_1bar$V + Vlambda
# Above 848K, we have beta quartz
Qz_beta <- Berman("quartz,beta", T = T, P = 1)
VQz[T >= 848.15] <- Qz_beta$V[T >= 848.14]
lines(TC, VQz, lty = 2)
legend("topleft", legend = "1 bar", bty = "n")
labplot("a")
## Fig. 1b: heat capacity
plot(TC, Qz_1bar$Cp, type = "l", xlab = Tlab, ylab = Cplab)
lines(TC, Qz_1bar_notrans$Cp, lty = 3)
legend("topleft", legend = "1 bar", bty = "n")
labplot("b")
## Calculate properties at 10 kbar with and without transition
Qz_10bar <- Berman("quartz", T = T, P = 10000)
Qz_10bar_notrans <- Berman("quartz", T = T, P = 10000, calc.transition = FALSE)
## Fig. 1c: heat capacity
plot(TC, Qz_10bar$Cp, type = "l", xlab = Tlab, ylab = Cplab)
lines(TC, Qz_10bar_notrans$Cp, lty = 3)
legend("topleft", legend = "10 kb", bty = "n")
labplot("c")
# Like Ber88 Fig. 2
Tlambda <- 848 # Kelvin
dTdP <- 0.0237
Pkb <- seq(1, 50, 1)
P <- 1000 * Pkb
T <- Tlambda + dTdP * (P - 1)
Qz_withtrans <- Berman("quartz", T = T, P = P)
Qz_notrans <- Berman("quartz", T = T, P = P, calc.transition = FALSE)
Qz_lambda <- Qz_withtrans - Qz_notrans
Plab <- expression(list(italic(P), "kb"))
plot(Pkb, Qz_lambda$G, type = "l", ylim = c(-300, -50), ylab = axis.label("DlG"), xlab = Plab)
labplot("d")
plot(Pkb, Qz_lambda$H, type = "l", ylim = c(1200, 1800), ylab = axis.label("DlH"), xlab = Plab)
labplot("e")
plot(Pkb, Qz_lambda$S, type = "l", ylim = c(0, 3), ylab = axis.label("DlS"), xlab = Plab)
labplot("f")
reset()
layout(matrix(1))
par(opar)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/demo/lambda.R
|
# CHNOSZ/demo/minsol.R
# Make solubility diagram with multiple minerals
# 20190530 jmd first version (plot_Zn.R)
# 20201008 combine solubility contours for different minerals
# 20201014 added to CHNOSZ
# 20220715 Allow to change metals (renamed from zinc.R to minsol.R)
library(CHNOSZ)
opar <- par(no.readonly = TRUE)
par(mfrow = c(2, 2))
# System variables
metal <- "Zn"
res <- 300
T <- 100
P <- "Psat"
Stot <- 1e-3
pH <- c(0, 14, res)
O2 <- c(-62, -40, res)
# Mass fraction NaCl in saturated solution at 100 degC, from CRC handbook
wNaCl <- 0.2805
# Set up basis species
basis(c(metal, "H2S", "Cl-", "oxygen", "H2O", "H+"))
basis("H2S", log10(Stot))
# Molality of NaCl
mNaCl <- 1000 * wNaCl / (mass("NaCl") * (1 - wNaCl))
# Estimate ionic strength and molality of Cl-
sat <- NaCl(m_tot = mNaCl, T = T)
basis("Cl-", log10(sat$m_Cl))
# Add minerals and aqueous species
icr <- retrieve(metal, c("Cl", "S", "O"), state = "cr")
iaq <- retrieve(metal, c("Cl", "S", "O"), state = "aq")
logm_metal <- -3
species(icr)
species(iaq, logm_metal, add = TRUE)
# Calculate affinities and make diagram
bases <- c("H2S", "HS-", "HSO4-", "SO4-2")
m <- mosaic(bases, pH = pH, O2 = O2, T = T, P = P, IS = sat$IS)
d <- diagram(m$A.species, bold = TRUE)
diagram(m$A.bases, add = TRUE, col = "slategray", lwd = 2, lty = 3, names = NA)
title(bquote(log * italic(m)[.(metal)*"(aq) species"] == .(logm_metal)))
label.figure("A")
# Add legend
plot.new()
l <- c(
lTP(T, P),
lNaCl(mNaCl),
lS(Stot)
)
legend("topleft", legend = lex(l), bty = "n", cex = 1.5)
# Describe steps
par(xpd = NA)
legend("bottomleft", c("Predominance diagram: molality of aqueous", "species defines one solubility contour.",
"Take away aqueous species to see", "all possible minerals.",
"Calculate solubility for each mineral separately", "then find the minimum to plot solubilities", "of stable minerals across the diagram."),
pch = c("A", "", "B", "", "C", "", ""), inset = c(-0.1, 0), cex = 0.95)
par(xpd = FALSE)
# Make diagram for minerals only 20201007
if(packageVersion("CHNOSZ") <= "1.3.6") species(delete = TRUE)
species(icr)
mcr <- mosaic(bases, pH = pH, O2 = O2, T = T, P = P, IS = sat$IS)
diagram(mcr$A.species, col = 2)
label.figure("B")
# Calculate *minimum* solubility among all the minerals 20201008
# (i.e. saturation condition for the solution)
# Use solubility() 20210303
s <- solubility(iaq, bases = bases, pH = pH, O2 = O2, T = T, P = P, IS = sat$IS, in.terms.of = metal)
# Specify contour levels
levels <- seq(-12, 9, 3)
diagram(s, type = "loga.balance", levels = levels, contour.method = "flattest")
# Show the mineral stability boundaries
diagram(mcr$A.species, names = NA, add = TRUE, lty = 2, col = 2)
title(paste("Solubilities of", length(icr), "minerals"), font.main = 1, line = 1.5)
title(bquote(log[10]~"moles of"~.(metal)~"in solution"), line = 0.7)
label.figure("C")
par(opar)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/demo/minsol.R
|
# CHNOSZ/demo/mosaic.R
# 20141221 first version jmd
# 20200819 revision:
# - comment out GC65 thermodynamic data
# - use mash() to show S and C species together
# - reorder plot layers to make better use of transparency
# - add 'dy' argument to adjust positions of labels
# - add legend to show activity of aqueous Fe species
library(CHNOSZ)
# Fe-bearing minerals and aqueous species in the Fe-S-O-H-C system
# after Figure 7.21 of Garrels and Christ, 1965
## Uncomment these lines to use thermodynamic data from Appendix 2 of GC65 (at 25 degrees C only)
#mod.OBIGT(c("Fe+2", "Fe+3"), G = c(-20300, -2520))
#mod.OBIGT(c("hematite", "magnetite", "pyrrhotite", "pyrite", "siderite"), G = c(-177100, -242400, -23320, -36000, -161060))
#mod.OBIGT(c("SO4-2", "HS-", "H2S", "HSO4-"), G = c(-177340, 3010, -6540, -179940))
#mod.OBIGT(c("CO2", "HCO3-", "CO3-2"), G = c(-92310, -140310, -126220))
# Define conditions
res <- 500
pH <- c(0, 14, res)
Eh <- c(-1, 1, res)
T <- 25
P <- 1
loga_S <- -6
loga_C <- 0
# Define chemical system
basis(c("FeO", "SO4-2", "CO3-2", "H2O", "H+", "e-"))
basis("SO4-2", loga_S)
basis("CO3-2", loga_C)
# Start with log(activity of aqueous Fe species) = -4
species(c("Fe+2", "Fe+3", "HFeO2-"), -4)
species(c("pyrrhotite", "pyrite", "hematite", "magnetite", "siderite"), add = TRUE)
# Use two sets of changing basis species:
# speciate SO4-2, HSO4-, HS-, H2S as a function of Eh and pH
# speciate CO3-2, HCO3-, CO2 as a function of pH
bases <- list(
c("SO4-2", "HSO4-", "HS-", "H2S"),
c("CO3-2", "HCO3-", "CO2")
)
# Make a diagram with dotted lines and aqueous species labels for log(activity of aqueous Fe species) = -4
m4 <- mosaic(bases, pH = pH, Eh = Eh, T = T, P = P)
names.aq <- species()$name; names.aq[4:8] <- ""
diagram(m4$A.species, lty = 3, names = names.aq, col.names = 4)
# Overlay solid lines and mineral labels for log(activity of aqueous Fe species) = -6
species(c("Fe+2", "Fe+3", "HFeO2-"), -6)
m6 <- mosaic(bases, pH = pH, Eh = Eh, T = T, P = P)
names <- species()$name; names[1:3] <- ""
# Adjust labels
srt <- dy <- numeric(length(names))
dy[names == "hematite"] <- -0.4
dy[names == "siderite"] <- 0.2
srt[names == "pyrite"] <- -25
diagram(m6$A.species, add = TRUE, names = names, dy = dy, srt = srt, bold = TRUE)
# Replot the aqueous species labels for stronger contrast
diagram(m4$A.species, lty = 3, names = names.aq, col.names = 4, add = TRUE, fill = NA)
# Show the predominance fields for the sulfur and carbonate basis species
dS <- diagram(m4$A.bases[[1]], italic = TRUE, plot.it = FALSE)
dC <- diagram(m4$A.bases[[2]], italic = TRUE, plot.it = FALSE)
dSC <- mash(dS, dC)
diagram(dSC, lty = 2, col = 8, col.names = 8, add = TRUE, srt = 90)
# Add water lines
water.lines(dSC, lty = 5)
# Add legend and title
TP <- describe.property(c("T", "P"), c(T, P))
SC <- c(
bquote(sum("S(aq)") == 10^.(loga_S)~m),
bquote(sum("C(aq)") == 10^.(loga_C)~m)
)
legend1 <- lex(TP, SC)
legend("topright", legend1, bty = "n")
Fe <- c(
bquote(10^-4~"m Fe"),
bquote(10^-6~"m Fe")
)
legend2 <- lex(Fe)
legend("bottomleft", legend2, lty = c(3, 1), bty = "n")
title(main = paste("Iron oxides, sulfides, and carbonate in water,",
"after Garrels and Christ, 1965, Figure 7.21", sep = "\n"), font.main = 1)
## Reset the database if we changed it using mod.OBIGT()
#reset()
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/demo/mosaic.R
|
# CHNOSZ/demo/potassium.R
# Moved from berman.Rd 20200727
### Compare mineral stabilities predicted with the Berman and Helgeson datasets
### on a T - log(K+/H+) diagram, after Sverjensky et al., 1991
### (doi:10.1016/0016-7037(91)90157-Z)
library(CHNOSZ)
## Set up the system: basis species
basis(c("K+", "Al+3", "quartz", "H2O", "O2", "H+"))
# Use pH = 0 so that aK+ = aK+/aH+
basis("pH", 0)
# Load the species
species(c("K-feldspar", "muscovite", "kaolinite",
"pyrophyllite", "andalusite"), "cr")
## Start with the data from Helgeson et al., 1978
add.OBIGT("SUPCRT92")
# Calculate affinities in aK+ - temperature space
# exceed.Tr: enable calculations above stated temperature limit of pyrophyllite
res <- 400
a <- suppressWarnings(affinity(`K+` = c(0, 5, res), T = c(200, 650, res), P = 1000, exceed.Ttr = TRUE))
# Make base plot with colors and no lines
diagram(a, xlab = ratlab("K+", molality = TRUE), lty = 0, fill = "terrain")
# Add the lines, extending into the low-density region (exceed.rhomin = TRUE)
a <- affinity(`K+` = c(0, 5, res), T = c(200, 650, res), P = 1000,
exceed.Ttr = TRUE, exceed.rhomin = TRUE)
diagram(a, add = TRUE, names = FALSE, col = 2, lwd = 1.5, lty = 2)
# The list of references:
ref1 <- thermo.refs(species()$ispecies)$key
## Now use the (default) data from Berman, 1988
# This resets the thermodynamic database
# without affecting the basis and species settings
OBIGT()
# Check that we have Berman's quartz
# and not coesite or some other phase of SiO2
iSiO2 <- rownames(basis()) == "SiO2"
stopifnot(info(basis()$ispecies[iSiO2])$name == "quartz")
# Berman's dataset doesn't have the upper temperature limits,
# so we don't need exceed.Ttr here
a <- affinity(`K+` = c(0, 5, res), T = c(200, 650, res), P = 1000, exceed.rhomin = TRUE)
diagram(a, add = TRUE, names = FALSE, col = 4, lwd = 1.5)
# The list of references:
ref2 <- thermo.refs(species()$ispecies)$key
ref2 <- paste(ref2, collapse = ", ")
# Add legend and title
legend("top", "low-density region", text.font = 3, bty = "n")
legend("topleft", describe.property(c("P", "IS"), c(1000, 1)), bty = "n", inset = c(0, 0.1))
legend("topleft", c("Helgeson et al., 1978", "Berman, 1988 and\nSverjensky et al., 1991"),
lty = c(2, 1), lwd = 1.5, col = c(2, 4), bty = "n", inset = c(0.25, 0.08))
title(main = syslab(c("K2O", "Al2O3", "SiO2", "H2O", "HCl")), line = 1.8)
title(main = "After Sverjensky et al., 1991",
line = 0.3, font.main = 1)
# Cleanup for next example
reset()
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/demo/potassium.R
|
# CHNOSZ/demo/protbuff.R
## Buffer + ionization: Metastablilities of
## thiol peroxidases from model bactera
## (ECOLI, BACSU mesophile; AQUAE thermophile,
## THIDA acidophile, BACHD alkaliphile)
library(CHNOSZ)
basis("CHNOS+")
organisms <- c("ECOLI", "AQUAE", "BACSU", "BACHD", "THIDA")
species("TPX", organisms)
# Create a buffer with our proteins in it
mod.buffer("TPX", paste("TPX", organisms, sep = "_"))
# Set up the buffered activities
basis(c("CO2", "H2O", "NH3", "O2"), "TPX")
a <- affinity(return.buffer = TRUE, T = 50)
basis(c("CO2", "H2O", "NH3", "O2"), as.numeric(a[1:4]))
a <- affinity(pH = c(4, 10, 300), T = c(40, 60, 300))
e <- equilibrate(a, normalize = TRUE)
fill <- ZC.col(ZC(protein.formula(species()$name)))
diagram(e, fill = fill)
title(main = "Thiol peroxidases from bacteria")
legend("topleft", describe.basis(basis = thermo()$basis[-6,]), bg = "slategray1", box.lwd = 0)
## Buffer + ionization: relative stabilities
## of E. coli sigma factors on a T-pH diagram
# (sigma factors 24, 32, 38, 54, 70, i.e.
# RpoE, RpoH, RpoS, RpoN, RpoD)
proteins <- c("RPOE", "RP32", "RPOS", "RP54", "RPOD")
basis("CHNOS+")
basis("pH", 7.4)
# Define and set the buffer
mod.buffer("sigma", paste(proteins, "ECOLI", sep = "_"))
basis(c("CO2", "NH3", "H2S", "O2"), "sigma")
logact <- affinity(return.buffer = TRUE, T = 25)
# Set the activities of the basis species to constants
# corresponding to the buffer, and diagram the relative
# stabilities as a function of T and pH
basis(c("CO2", "NH3", "H2S", "O2"), as.numeric(logact))
species(paste(proteins, "ECOLI", sep = "_"))
a <- affinity(pH = c(5, 10, 300), T = c(10, 40, 300))
fill <- ZC.col(ZC(protein.formula(species()$name)))
diagram(a, normalize = FALSE, fill = fill)
title(main = expression("Sigma factors in"~italic("E. coli")))
ptext <- c(describe.property("T", 25),
describe.basis(c(2, 6), oneline = TRUE))
legend("topleft", legend = c("preset conditions:", ptext), bg = "slategray1", box.lwd = 0)
btext <- describe.basis(c(1, 3, 4, 5), oneline = TRUE)
legend("bottomright", legend = c("buffered conditions:", btext), bg = "slategray1", box.lwd = 0)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/demo/protbuff.R
|
# CHNOSZ/demo/protein.equil.R
## Steps in calculation of chemical activities of two proteins
## in metastable equilibrium, after Dick and Shock, 2011
library(CHNOSZ)
protein <- pinfo(c("CSG_METVO", "CSG_METJA"))
# Use superseded properties of [Met], [Gly], and [UPBB] (Dick et al., 2006)
mod.OBIGT("[Met]", G = -35245, H = -59310, S = 40.38)
mod.OBIGT("[Gly]", G = -6075, H = -5570, S = 17.31)
mod.OBIGT("[UPBB]", G = -21436, H = -45220, S = 1.62)
# Set up the basis species to those used in DS11
basis("CHNOS+")
# Note this yields logaH2 = -4.657486
swap.basis("O2", "H2")
# Demonstrate the steps of the equilibrium calculation
protein.equil(protein, loga.protein = -3)
## We can also look at the affinities
# (Reaction 7, Dick and Shock, 2011)
# A/2.303RT for protein at unit activity (A-star for the protein)
a <- affinity(iprotein = protein[1], loga.protein = 0)
Astar.protein <- a$values[[1]]
# Divide affinity by protein length (A-star for the residue)
pl <- protein.length(protein[1])
Astar.residue <- a$values[[1]]/pl # 0.1893, Eq. 11
# A/2.303RT per residue corresponding to protein activity of 10^-3
loga.residue <- log10(pl*10^-3)
Aref.residue <- Astar.residue - loga.residue # 0.446, after Eq. 16
# A-star of the residue in natural log units (A/RT)
log(10) * Astar.residue # 0.4359, after Eq. 23
# Forget about the superseded group properties for whatever comes next
reset()
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/demo/protein.equil.R
|
# CHNOSZ/demo/rank.affinity.R
## Affinity ranking for proteins coded by differentially expressed
## genes in response to carbon limitation in yeast
# Demo written on 20220620
# Adapted from an example previously in read.expr.Rd (CHNOSZ 1.1.0) and yeast.Rd (CHNOSZ 1.2.0-1.3.0)
library(CHNOSZ)
# Experimental data are from Tai et al. (2005)
# https://doi.org/10.1074/jbc.M410573200
file <- system.file("extdata/protein/TBD+05.csv", package = "CHNOSZ")
dat <- read.csv(file, row.names = 1, check.names = FALSE)
# The activities of ammonium and sulfate are similar to the
# non-growth-limiting concentrations used by Boer et al. (2003)
# https://doi.org/10.1074/jbc.M209759200
basis(c("glucose", "H2O", "NH4+", "oxygen", "SO4-2", "H+"),
c(-1, 0, -1.3, 999, -1.4, -7))
aafile <- system.file("extdata/protein/TBD+05_aa.csv", package = "CHNOSZ")
aa <- read.csv(aafile)
iprotein <- add.protein(aa, as.residue = TRUE)
res <- 200
aout <- affinity(C6H12O6 = c(-60, -20, res), O2 = c(-72, -60, res), iprotein = iprotein)
groups <- apply(dat, 2, which)
names(groups) <- paste0(names(groups), "\n(", colSums(dat), ")")
arank <- rank.affinity(aout, groups)
fill <- c("#d2b48c", "#b0e0e6", "#d3d3d3", "#d8bfd8")
diagram(arank, format.names = FALSE, fill = fill)
title(main = paste("Affinity ranking for proteins coded by differentially expressed\n",
"genes under carbon limitation in yeast (data from Tai et al., 2005)"), font.main = 1)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/demo/rank.affinity.R
|
# CHNOSZ/demo/saturation.R
## Make equilibrium activity diagrams including saturation limits
## and using activity ratios as variables
# first version (activity_ratios.R) 20170217
# keep one diagram and add saturation lines 20190127
library(CHNOSZ)
# The ratios are calculated with pH = 0 (activity of H+ = 1), so (activity of the ion) is equal to
# (activity of the ion) / [(activity of H+) ^ (charge of the ion)]
# NOTE: Bowers et al. use more complicated variables
# (involving the hydration numbers of H2O and the ion)
# with subsequently different axis ranges
## H2O-CaO-MgO-SiO2 at 300 degree C and 1000 bar
## Helgeson et al., 1969, p. 136 (http://www.worldcat.org/oclc/902423149)
## Bowers et al., 1984, p. 246 (http://www.worldcat.org/oclc/224591948)
par(cex = 1.4)
basis(c("SiO2", "Ca+2", "Mg+2", "carbon dioxide", "H2O", "O2", "H+"))
species(c("quartz", "talc", "chrysotile", "forsterite", "tremolite",
"diopside", "wollastonite", "monticellite", "merwinite"))
# Calculate the chemical affinities of formation reactions
a <- affinity("Mg+2" = c(4, 10, 500), "Ca+2" = c(5, 15, 500), T = 300, P = 1000)
diagram(a, xlab = ratlab("Mg+2"), ylab = ratlab("Ca+2"), fill = "terrain", yline = 1.7)
# Add saturation limits for specified CO2 fugacity
basis("CO2", -1)
species(c("calcite", "dolomite", "magnesite", "brucite"))
# Use argument recall feature to rerun affinity over the same range of conditions
a <- affinity(a)
diagram(a, type = "saturation", add = TRUE, contour.method = c("edge", "edge", "flattest", "flattest"), lty = 2, cex = 1.4, col = "blue3")
# Add title and legend
title(main = syslab(c("H2O", "CO2", "CaO", "MgO", "SiO2")))
dprop <- describe.property(c("T", "P"), c(300, 1000))
dbasis <- describe.basis(4)
legend("bottomright", c(dprop, dbasis), bty = "n", cex = 0.9)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/demo/saturation.R
|
# CHNOSZ/demo/solubility.R: solubility of CO2 and calcite
# 20150306 jmd first version; used uniroot() to find zero affinity
# 20181031 use new vectorized, non-uniroot solubility(); add T-pH plots
library(CHNOSZ)
# For comparison with published CO2 solubility plot, see Fig. 4.5 in
# Stumm and Morgan, 1996, Aquatic Chemistry: Chemical Equilibria and Rates in Natural Waters
# (New York: John Wiley & Sons), 3rd edition
# For comparison with published calcite solubility plot, see Fig. 4A in
# Manning et al., 2013, Reviews in Mineralogy & Geochemistry, v. 75, pp. 109-148
# (doi: 10.2138/rmg.2013.75.5)
opar <- par(no.readonly = TRUE)
layout(matrix(1:4, nrow = 2))
# Set pH and T range and resolution, constant temperature and ionic strength
pH <- c(0, 14)
T <- c(0, 300)
res <- 100
T1 <- 25
IS <- 0
# Start with CO2
basis(c("CO2", "H2O", "O2", "H+"))
# This is ca. atmospheric PCO2
species("carbon dioxide", -3.5)
iaq <- info(c("CO2", "HCO3-", "CO3-2"))
s <- solubility(iaq, pH = c(pH, res), T = T1, IS = IS)
# First plot total activity line
diagram(s, ylim = c(-10, 4), type = "loga.balance", lwd = 4, col = "green2")
# Add activities of species
diagram(s, ylim=c(-10, 4), add = TRUE, dy = 1)
# Add legend
lexpr <- as.expression(c("total", expr.species("CO2", state = "aq"),
expr.species("HCO3-"), expr.species("CO3-2")))
legend("topleft", lty = c(1, 1:3), lwd = c(4, 2, 2, 2),
col = c("green2", rep("black", 3)), legend = lexpr)
title(main = substitute("Solubility of"~what~"at"~T~degree*"C",
list(what = expr.species("CO2"), T = T1)), line = 1.6)
mtext("cf. Fig. 4.5 of Stumm and Morgan, 1996")
# Check the endpoints
stopifnot(round(s$loga.balance[c(1, res)])==c(-5, 6))
# CO2 T-pH plot
s <- solubility(iaq, pH = c(pH, res), T = c(T, res), IS = IS)
diagram(s, type = "loga.balance")
title(main = substitute("Solubility of"~what, list(what = expr.species("CO2"))))
# Now do calcite
basis(c("CO2", "Ca+2", "H2O", "O2", "H+"))
species("calcite")
iaq <- info(c("CO2", "HCO3-", "CO3-2"))
# Change this to dissociate = 2 to reproduce straight lines in Fig. 4A of Manning et al., 2013
s <- solubility(iaq, pH = c(pH, res), T = T1, IS = IS, dissociate = TRUE)
diagram(s, ylim = c(-10, 4), type = "loga.balance", lwd = 4, col = "green2")
diagram(s, add = TRUE, dy = 1)
legend("topright", lty = c(1, 1:3), lwd = c(4, 2, 2, 2),
col = c("green2", rep("black", 3)), legend = lexpr)
title(main = substitute("Solubility of"~what~"at"~T~degree*"C",
list(what = "calcite", T = T1)), line = 1.6)
mtext("cf. Fig. 4A of Manning et al., 2013")
# Check the endpoints
stopifnot(round(s$loga.balance[c(1, res)])==c(4, -4))
# Calcite T-pH plot
s <- solubility(iaq, pH = c(pH, res), T = c(T, res), IS = IS, dissociate = TRUE)
diagram(s, type = "loga.balance")
title(main = "Solubility of calcite", font.main = 1)
layout(matrix(1))
par(opar)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/demo/solubility.R
|
# CHNOSZ/demo/sources.R
## Cross-checking sources
library(CHNOSZ)
# The reference sources
ref.source <- thermo()$refs$key
# Sources in the primary thermodynamic database
# Se omit the [S92] in "HDNB78 [S92]" etc.
tdata <- thermo()$OBIGT
ps1 <- gsub("\ .*", "", tdata$ref1)
ps2 <- gsub("\ .*", "", tdata$ref2)
# Sources in the optional datafiles
tdata <- read.csv(system.file("extdata/OBIGT/DEW.csv", package="CHNOSZ"), as.is=TRUE)
os1 <- gsub("\ .*", "", tdata$ref1)
os2 <- gsub("\ .*", "", tdata$ref2)
tdata <- read.csv(system.file("extdata/OBIGT/SLOP98.csv", package="CHNOSZ"), as.is=TRUE)
os3 <- gsub("\ .*", "", tdata$ref1)
os4 <- gsub("\ .*", "", tdata$ref2)
tdata <- read.csv(system.file("extdata/OBIGT/SUPCRT92.csv", package="CHNOSZ"), as.is=TRUE)
os5 <- gsub("\ .*", "", tdata$ref1)
os6 <- gsub("\ .*", "", tdata$ref2)
tdata <- read.csv(system.file("extdata/OBIGT/AS04.csv", package="CHNOSZ"), as.is=TRUE)
os7 <- gsub("\ .*", "", tdata$ref1)
os8 <- gsub("\ .*", "", tdata$ref2)
tdata <- read.csv(system.file("extdata/OBIGT/AD.csv", package="CHNOSZ"), as.is=TRUE)
os9 <- gsub("\ .*", "", tdata$ref1)
os10 <- gsub("\ .*", "", tdata$ref2)
tdata <- read.csv(system.file("extdata/OBIGT/GEMSFIT.csv", package="CHNOSZ"), as.is=TRUE)
os11 <- gsub("\ .*", "", tdata$ref1)
os12 <- gsub("\ .*", "", tdata$ref2)
# All of the thermodynamic data sources - some of them might be NA
OBIGT.source <- unique(c(ps1, ps2, os1, os2, os3, os4, os5, os6, os7, os8, os9, os10, os11, os12))
OBIGT.source <- OBIGT.source[!is.na(OBIGT.source)]
# These all produce character(0) if the sources are all accounted for
print("missing these sources for thermodynamic properties:")
print(unique(OBIGT.source[!(OBIGT.source %in% ref.source)]))
# Determine if all the reference sources are cited
# This should produce character(0)
print("these sources are present but not cited:")
print(ref.source[!(ref.source %in% OBIGT.source)])
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/demo/sources.R
|
# CHNOSZ/demo/sphalerite.R
# Sphalerite solubility after Akinfiev and Tagirov, 2014, Fig. 13
# 20190526 jmd initial version
library(CHNOSZ)
opar <- par(no.readonly = TRUE)
# Set up chemical system
basis(c("Zn+2", "Cl-", "H2S", "H2O", "O2", "H+"))
basis("H2S", log10(0.05))
species("ZnS")
iaq <- retrieve("Zn", c("O", "H", "Cl", "S"), "aq")
# A function to make a single plot
plotfun <- function(T = 400, P = 500, m_tot = 0.1, pHmin = 4, logppmmax = 3) {
# Get pH values
res <- 100
pH <- seq(pHmin, 10, length.out = res)
# Calculate speciation in NaCl-H2O system at given pH
NaCl <- NaCl(m_tot = m_tot, T = T, P = P, pH = pH)
# Calculate solubility with mosaic (triggered by bases argument) to account for HS- and H2S speciation
s <- solubility(iaq, bases = c("H2S", "HS-"), pH = pH, "Cl-" = log10(NaCl$m_Cl), T = T, P = P, IS = NaCl$IS)
# Convert log activity to log ppm
sp <- convert(s, "logppm")
diagram(sp, ylim = c(-5, logppmmax))
diagram(sp, type = "loga.balance", add = TRUE, lwd = 2, col = "green3")
# Add water neutrality line
pKw <- - subcrt(c("H2O", "OH-", "H+"), c(-1, 1, 1), T = T, P = P)$out$logK
abline(v = pKw / 2, lty = 2, lwd = 2, col = "blue1")
# Add legend
l <- lex(lNaCl(m_tot), lTP(T, P))
legend("topright", legend = l, bty = "n")
}
plotfun()
title(main = ("Solubility of sphalerite, after Akinfiev and Tagirov, 2014, Fig. 13"), font.main = 1)
par(opar)
### The following code for making multiple plots is not used in the demo ###
# A function to make a page of plots
pagefun <- function() {
# Set the values of temperature, pressure, and total NaCl
T <- c(400, 400, 250, 250, 100, 100)
# Use a list to be able to mix numeric and character values for P
P <- list(500, 500, "Psat", "Psat", "Psat", "Psat")
m_tot <- c(0.1, 1, 0.1, 1, 0.1, 1)
# The plots have differing limits
pHmin <- c(4, 4, 2, 2, 2, 2)
logppmmax <- c(3, 3, 2, 2, 0, 0)
# Make the plots
par(mfrow = c(3, 2))
for(i in 1:6) plotfun(T = T[i], P = P[[i]], m_tot = m_tot[i], pHmin = pHmin[i], logppmmax = logppmmax[i])
}
# A function to make a png file with all the plots
pngfun <- function() {
png("sphalerite.png", width = 1000, height = 1200, pointsize = 24)
pagefun()
# Add an overall title
par(xpd = NA)
text(1, 14, "Solubility of sphalerite, after Akinfiev and Tagirov, 2014, Fig. 13", cex = 1.5)
par(xpd = FALSE)
dev.off()
}
# We don't run these functions in the demo
#pagefun()
#pngfun()
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/demo/sphalerite.R
|
# CHNOSZ/demo/yttrium.R
# Make diagrams similar to Figure 11 of Guan et al. (2020)
# https://doi.org/10.1016/j.gca.2020.04.015
# 20221122 jmd version 1
library(CHNOSZ)
# Function to add Y(III)-Cl species using logB values from Table 9 of Guan et al. (2020)
add.Y.species <- function(P, plot.it = FALSE) {
# Temperature
T <- c(25, seq(50, 500, 50))
if(P == 800) {
logB <- list(
c(1.04, 0.48, 0.13, 0.43, 1.12, 2.06, 3.21, 4.58, 6.26, 8.39, 11.14),
c(-9.14, -7.34, -4.14, -1.37, 1.12, 3.46, 5.78, 8.24, 11.05, 14.48, 18.77),
c(-14, -11.48, -7.06, -3.25, 0.14, 3.32, 6.45, 9.74, 13.47, 18.01, 23.65),
c(-15.94, -13.2, -8.39, -4.27, -0.61, 2.79, 6.15, 9.67, 13.63, 18.45, 24.41)
)
} else if(P == 1000) {
logB <- list(
c(1.13, 0.54, 0.16, 0.43, 1.09, 2, 3.1, 4.39, 5.9, 7.69, 9.85),
c(-9.33, -7.51, -4.3, -1.55, 0.9, 3.18, 5.4, 7.68, 10.15, 12.94, 16.16),
c(-14.24, -11.71, -7.27, -3.49, -0.14, 2.95, 5.95, 9.01, 12.3, 16, 20.25),
c(-16.19, -13.43, -8.62, -4.52, -0.91, 2.41, 5.62, 8.89, 12.4, 16.33, 20.84)
)
} else stop("logB values for P =", P, "are not available here")
# Define species and coefficients in formation reactions
species <- list(
c("Y+3", "Cl-", "YCl+2"),
c("Y+3", "Cl-", "YCl2+"),
c("Y+3", "Cl-", "YCl3"),
c("Y+3", "Cl-", "YCl4-")
)
coeffs <- list(
c(-1, -1, 1),
c(-1, -2, 1),
c(-1, -3, 1),
c(-1, -4, 1)
)
# Fit the formation constants to thermodynamic parameters and add them to OBIGT
for(i in 1:4) logB.to.OBIGT(logB[[i]], species[[i]], coeffs[[i]], T = T, P = P, tolerance = 0.6, npar = 5)
# Plot the given and fitted values
if(plot.it) {
par(mfrow = c(2, 2))
for(i in 1:4) {
sres <- subcrt(species[[i]], coeffs[[i]], T = T, P = P)
plot(T, sres$out$logK, type = "l", xlab = axis.label("T"), ylab = axis.label("logK"))
points(T, logB[[i]], pch = 19)
title(describe.reaction(sres$reaction))
if(i == 1) legend("topleft", c("Guan et al. (2020)", "logB.to.OBIGT()"), pch = c(19, NA), lty = c(NA, 1))
legend("bottomright", paste(P, "bar"), bty = "n")
}
}
}
# Function to plot distribution of Y(III) chloride species at T and P
Y_Cl <- function() {
# Define total molality of NaCl
# Start at 0.1 because we can't use 0 in the logarithmic value needed for affinity()
mNaCl <- seq(0.1, 4.9, 0.2)
# Define T, P, and pH values
Ts <- c(200, 350, 500)
Ps <- c(800, 800, 1000)
pHs <- c(3, 0.3)
# Setup plot
par(mfrow = c(3, 2))
par(cex = 0.9)
# Loop over T and P
for(i in 1:3) {
T <- Ts[i]
P <- Ps[i]
# Add new species
add.Y.species(P)
# Setup chemical system
basis(c("Y+3", "Cl-", "e-"))
species(c("Y+3", "YCl+2", "YCl2+", "YCl3", "YCl4-"))
# Loop over pH
for(j in 1:2) {
pH <- pHs[j]
# Calculate molality of Cl- and ionic strength
NaCl_props <- suppressMessages(lapply(mNaCl, NaCl, T = T, P = P, pH = pH))
# Turn the list into a data frame
NaCl_props <- do.call(rbind, lapply(NaCl_props, as.data.frame))
# Calculate affinity of formation reactions
a <- affinity("Cl-" = log10(NaCl_props$m_Cl), IS = NaCl_props$IS, T = T, P = P)
# Calculate species distribution for total Y(III) equal to 0.01 m
m_Y <- 0.01
e <- equilibrate(a, loga.balance = log10(m_Y))
# Make x-axis show total m(NaCl) instead of logm(Cl-) 20221208
e$vals[[1]] <- mNaCl
# Set colors similar to Guan et al. (2020)
col <- 2:6
# Only label lines above 1/20 = 0.05 mol fraction
mol <- 10^do.call(cbind, lapply(e$loga.equil, as.data.frame))
molfrac <- mol / rowSums(mol)
ilab <- apply(molfrac > 0.05, 2, any)
names <- e$species$name
names[!ilab] <- ""
d <- diagram(e, alpha = TRUE, xlim = c(0, 5), ylim = c(0, 1),
xlab = expr.species("NaCl", molality = TRUE), ylab = "Fraction of Y-Cl species",
names = names, col = col, lty = 1, lwd = 2, mar = c(3, 3.5, 2.5, 3.5))
# Calculate and plot coordination number
CN <- 1 * d$plotvals[[2]] + 2 * d$plotvals[[3]] + 3 * d$plotvals[[4]] + 4 * d$plotvals[[5]]
# Rescale to y-axis limits [0, 1]
CN_scaled <- CN / 4
lines(mNaCl, CN_scaled, lty = 3, lwd = 3, col = "darkorange")
# Add ticks for CN
axis(4, seq(0, 1, 0.25), labels = 0:4, lwd.ticks = 2, tcl = -0.5, mgp = c(1.7, 0.8, 0))
mtext("Cl coordination number", 4, 1.7, las = 0, cex = par("cex"))
# Make title
lab <- lTP(T, P)
lab[[4]] <- bquote(pH == .(pH))
title(lab, cex.main = 1)
}
if(i==1) mtext("After Guan et al. (2020)", line = 0.8, adj = -2.7, cex = 0.9, font = 2)
}
}
# Use non-default ion size parameters 20230309
Bdot_acirc <- thermo()$Bdot_acirc
# Cl- and Y+3 override the defaults, and YCl+2 is a new species
Bdot_acirc <- c("Cl-" = 4, "Y+3" = 5, "YCl+2" = 4, "YCl2+" = 4, "YCl3" = 4, "YCl4-" = 4, Bdot_acirc)
thermo("Bdot_acirc" = Bdot_acirc)
# Run the functions to make plots for the demo
opar <- par(no.readonly = TRUE)
add.Y.species(800, plot.it = TRUE)
add.Y.species(1000, plot.it = TRUE)
Y_Cl()
# Restore plot settings and CHNOSZ settings
par(opar)
reset()
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/demo/yttrium.R
|
## ----setup, include = FALSE---------------------------------------------------
library(CHNOSZ)
options(width = 80)
# Use pngquant to optimize PNG images
library(knitr)
knit_hooks$set(pngquant = hook_pngquant)
pngquant <- "--speed=1 --quality=0-25"
if (!nzchar(Sys.which("pngquant"))) pngquant <- NULL
# To make warnings appear in text box 20230619
# https://selbydavid.com/2017/06/18/rmarkdown-alerts/
knitr::knit_hooks$set(
error = function(x, options) {
paste('\n\n<div class="alert alert-danger">',
gsub('##', '\n', gsub('^##\ Error', '**Error:**', x)),
'</div>', sep = '\n')
},
warning = function(x, options) {
paste('\n\n<div class="alert alert-warning">',
gsub('##', '\n', gsub('^##\ Warning:', '**Warning:**', x)),
'</div>', sep = '\n')
},
message = function(x, options) {
paste('\n\n<div class="alert alert-info">',
gsub('##', '\n', x),
'</div>', sep = '\n')
}
)
# Set dpi 20231129
knitr::opts_chunk$set(
dpi = if(nzchar(Sys.getenv("CHNOSZ_BUILD_LARGE_VIGNETTES"))) 100 else 72
)
## ----echo = F, cache = F------------------------------------------------------
# Merge consecutive messages into a single div 20231114
knitr::knit_hooks$set(document = function(x){
# Not sure why this is needed, but simply computing on 'x' doesn't work
file <- tempfile()
writeLines(x, file)
x <- readLines(file)
# Line numbers of the document with </div>
enddiv <- which(x == "</div>")
# Line numbers with <div class="alert alert-info">
beginalert <- which(x == '<div class="alert alert-info">')
# Find </div> followed <div class="alert alert-info"> (skip empty lines)
removediv <- (enddiv + 2) %in% beginalert
if(any(removediv)) {
# Lines to remove
rmlines1 <- enddiv[removediv]
rmlines2 <- enddiv[removediv] + 1
rmlines3 <- enddiv[removediv] + 2
# Do the removing
x <- x[-c(rmlines1, rmlines2, rmlines3)]
}
x
})
## ----HTML, include = FALSE----------------------------------------------------
NOTE <- '<span style="background-color: yellow;">NOTE</span>'
# CHNOSZ functions
equilibrate_ <- '<code>equilibrate()</code>'
info_ <- '<code>info()</code>'
thermo.refs_ <- '<code>thermo.refs()</code>'
# Math stuff
logK <- "log <i>K</i>"
Hplus <- "H<sup>+</sup>"
HCO2_ <- "HCO<sub>2</sub><sup>−</sup>"
HCO3_ <- "HCO<sub>3</sub><sup>−</sup>"
O2 <- "O<sub>2</sub>"
S2 <- "S<sub>2</sub>"
log <- "log "
aHCO2_ <- "<i>a</i><sub>HCO<sub>2</sub><sup>−</sup></sub>"
aHCO3_ <- "<i>a</i><sub>HCO<sub>3</sub><sup>−</sup></sub>"
logfO2 <- "log <i>f</i><sub>O<sub>2</sub></sub>"
Ctot <- "C<sub>tot</sub>"
C3H5O2_ <- "C<sub>3</sub>H<sub>5</sub>O<sub>2</sub><sup>−</sup>"
a3HCO3_ <- "<i>a</i><sup>3</sup><sub>HCO<sub>3</sub><sup>−</sup></sub>"
aC3H5O2_ <- "<i>a</i><sub>C<sub>3</sub>H<sub>5</sub>O<sub>2</sub><sup>−</sup></sub>"
a2HCO3_ <- "<i>a</i><sup>2</sup><sub>HCO<sub>3</sub><sup>−</sup></sub>"
logCtot <- "log C<sub>tot</sub>"
CO2 <- "CO<sub>2</sub>"
H2O <- "H<sub>2</sub>O"
S3minus <- "S<sub>3</sub><sup>-</sup>"
H2S <- "H<sub>2</sub>S"
SO4__ <- "SO<sub>4</sub><sup>-2</sup>"
Kplus <- "K<sup>+</sup>"
Naplus <- "Na<sup>+</sup>"
Clminus <- "Cl<sup>-</sup>"
H2 <- "H<sub>2</sub>"
## ----alanine_refs, message = FALSE--------------------------------------------
info(info("alanine"))[c("ref1", "ref2")]
thermo.refs(info("alanine"))
## ----PPM_refs, message = FALSE------------------------------------------------
basis(c("pyrite", "pyrrhotite", "oxygen"))
sres <- subcrt("magnetite", 1)
info(sres$reaction$ispecies)[, 1:6]
thermo.refs(sres)
reset()
## ----DEW_Ctot, eval = FALSE---------------------------------------------------
# ### Based on demo/DEW.R in CHNOSZ
#
# # Set up subplots
# par(mfrow = c(1, 2), mar = c(3.0, 3.5, 2.5, 1.0), mgp = c(1.7, 0.3, 0), las = 1, tcl = 0.3, xaxs = "i", yaxs = "i")
#
# # Activate DEW model
# water("DEW")
#
# ###########
# ## logfO2-pH diagram for aqueous inorganic and organic carbon species at high pressure
# ## After Figure 1b of Sverjensky et al., 2014b [SSH14]
# ## (Nature Geoscience, https://doi.org/10.1038/NGEO2291)
# ###########
#
# # Define system
# basis("CHNOS+")
# inorganic <- c("CO2", "HCO3-", "CO3-2", "CH4")
# organic <- c("formic acid", "formate", "acetic acid", "acetate", "propanoic acid", "propanoate")
# species(c(inorganic, organic), 0)
# fill <- c(rep("aliceblue", length(inorganic)), rep("aquamarine", length(organic)))
#
# # A function to make the diagrams
# dfun <- function(T = 600, P = 50000, res = 200, Ctot = 0.03) {
# a <- affinity(pH = c(0, 10, res), O2 = c(-24, -12, res), T = T, P = P)
# # Set total C concentration to 0.03 molal
# # (from EQ3NR model for eclogite [Supporting Information of SSH14])
# e <- equilibrate(a, loga.balance = log10(Ctot))
# diagram(e, fill = fill)
# dp <- describe.property(c(" T", " P"), c(T, P), digits = 0)
# legend("bottomleft", legend = dp, bty = "n")
# }
#
# water("DEW")
# add.OBIGT("DEW")
# dfun(Ctot = 0.03)
# mtitle(c("Inorganic and organic species", "C[total] = 0.03 molal"))
# dfun(Ctot = 3)
# mtitle(c("Inorganic and organic species", "C[total] = 3 molal"))
#
# # Restore default settings for the questions below
# reset()
## ----DEW_Ctot, echo = FALSE, message = FALSE, results = "hide", fig.width = 8, fig.height = 4, out.width = "100%", fig.align = "center", pngquant = pngquant, cache = TRUE----
### Based on demo/DEW.R in CHNOSZ
# Set up subplots
par(mfrow = c(1, 2), mar = c(3.0, 3.5, 2.5, 1.0), mgp = c(1.7, 0.3, 0), las = 1, tcl = 0.3, xaxs = "i", yaxs = "i")
# Activate DEW model
water("DEW")
###########
## logfO2-pH diagram for aqueous inorganic and organic carbon species at high pressure
## After Figure 1b of Sverjensky et al., 2014b [SSH14]
## (Nature Geoscience, https://doi.org/10.1038/NGEO2291)
###########
# Define system
basis("CHNOS+")
inorganic <- c("CO2", "HCO3-", "CO3-2", "CH4")
organic <- c("formic acid", "formate", "acetic acid", "acetate", "propanoic acid", "propanoate")
species(c(inorganic, organic), 0)
fill <- c(rep("aliceblue", length(inorganic)), rep("aquamarine", length(organic)))
# A function to make the diagrams
dfun <- function(T = 600, P = 50000, res = 200, Ctot = 0.03) {
a <- affinity(pH = c(0, 10, res), O2 = c(-24, -12, res), T = T, P = P)
# Set total C concentration to 0.03 molal
# (from EQ3NR model for eclogite [Supporting Information of SSH14])
e <- equilibrate(a, loga.balance = log10(Ctot))
diagram(e, fill = fill)
dp <- describe.property(c(" T", " P"), c(T, P), digits = 0)
legend("bottomleft", legend = dp, bty = "n")
}
water("DEW")
add.OBIGT("DEW")
dfun(Ctot = 0.03)
mtitle(c("Inorganic and organic species", "C[total] = 0.03 molal"))
dfun(Ctot = 3)
mtitle(c("Inorganic and organic species", "C[total] = 3 molal"))
# Restore default settings for the questions below
reset()
## ----pyrrhotite_values, message = FALSE---------------------------------------
# The formula of the new mineral and literature reference
formula <- "Fe0.877S"
ref1 <- "PMW87"
# Because the properties from Pankratz et al. (1987) are listed in calories,
# we need to change the output of subcrt() to calories (the default is Joules)
E.units("cal")
# Use temperature in Kelvin for the calculations below
T.units("K")
# Thermodynamic properties of polymorph 1 at 25 °C (298.15 K)
G1 <- -25543
H1 <- -25200
S1 <- 14.531
Cp1 <- 11.922
# Heat capacity coefficients for polymorph 1
a1 <- 7.510
b1 <- 0.014798
# For volume, use the value from Helgeson et al. (1978)
V1 <- V2 <- 18.2
# Transition temperature
Ttr <- 598
# Transition enthalpy (cal/mol)
DHtr <- 95
# Heat capacity coefficients for polymorph 2
a2 <- -1.709
b2 <- 0.011746
c2 <- 3073400
# Maximum temperature of polymorph 2
T2 <- 1800
## ----pyrrhotite_Ttr, message = FALSE------------------------------------------
DGtr <- 0 # DON'T CHANGE THIS
TDStr <- DHtr - DGtr # TΔS° = ΔH° - ΔG°
DStr <- TDStr / Ttr
## ----pyrrhotite_Cp, results = "hide", message = FALSE-------------------------
mod.OBIGT("pyrrhotite_new", formula = formula, state = "cr", ref1 = ref1,
E_units = "cal", G = 0, H = 0, S = 0, V = V1, Cp = Cp1,
a = a1, b = b1, c = 0, d = 0, e = 0, f = 0, lambda = 0, T = Ttr)
mod.OBIGT("pyrrhotite_new", formula = formula, state = "cr2", ref1 = ref1,
E_units = "cal", G = 0, H = 0, S = 0, V = V2,
a = a2, b = b2, c = c2, d = 0, e = 0, f = 0, lambda = 0, T = T2)
## ----pyrrhotite_info, results = "hide", collapse = TRUE-----------------------
info(info("pyrrhotite_new", "cr"))
info(info("pyrrhotite_new", "cr2"))
## ----pyrrhotite_S, message = FALSE--------------------------------------------
DS1 <- subcrt("pyrrhotite_new", "cr", P = 1, T = Ttr, use.polymorphs = FALSE)$out[[1]]$S
DS2 <- subcrt("pyrrhotite_new", "cr2", P = 1, T = Ttr)$out[[1]]$S
DS298 <- DS1 + DStr - DS2
## ----pyrrhotite_D1_D2, message = FALSE, results = "hide"----------------------
mod.OBIGT("pyrrhotite_new", state = "cr", S = S1)
mod.OBIGT("pyrrhotite_new", state = "cr2", S = S1 + DS298)
D1 <- subcrt("pyrrhotite_new", "cr", P = 1, T = Ttr, use.polymorphs = FALSE)$out[[1]]
D2 <- subcrt("pyrrhotite_new", "cr2", P = 1, T = Ttr)$out[[1]]
## ----pyrrhotite_check_S, results = "hide"-------------------------------------
stopifnot(all.equal(D2$S - D1$S, DStr))
## ----pyrrhotite_DG298_DH298, results = "hide", message = FALSE----------------
DG298 <- D1$G + DGtr - D2$G
DH298 <- D1$H + DHtr - D2$H
mod.OBIGT("pyrrhotite_new", state = "cr", G = G1, H = H1)
mod.OBIGT("pyrrhotite_new", state = "cr2", G = G1 + DG298, H = H1 + DH298)
## ----pyrrhotite_info2, collapse = TRUE----------------------------------------
cr_parameters <- info(info("pyrrhotite_new", "cr"))
stopifnot(abs(check.GHS(cr_parameters)) < 1)
cr2_parameters <- info(info("pyrrhotite_new", "cr2"))
stopifnot(abs(check.GHS(cr2_parameters)) < 1)
## ----pyrrhotite_parameters----------------------------------------------------
cr_parameters
cr2_parameters
## ----pyrrhotite_T, eval = FALSE-----------------------------------------------
# T <- seq(550, 650, 1)
# sout <- subcrt("pyrrhotite_new", T = T, P = 1)$out[[1]]
# par(mfrow = c(1, 4), mar = c(4, 4.2, 1, 1))
# labels <- c(G = "DG0f", H = "DH0f", S = "S0", Cp = "Cp0")
# for(property in c("G", "H", "S", "Cp")) {
# plot(sout$T, sout[, property], col = sout$polymorph,
# xlab = axis.label("T"), ylab = axis.label(labels[property])
# )
# abline(v = Ttr, lty = 3, col = 8)
# if(property == "G")
# legend("bottomleft", c("1", "2"), pch = 1, col = c(1, 2), title = "Polymorph")
# }
#
# # Restore default settings for the questions below
# reset()
## ----pyrrhotite_T, echo = FALSE, message = FALSE, results = "hide", fig.width = 8, fig.height = 2.5, out.width = "100%", fig.align = "center", pngquant = pngquant----
T <- seq(550, 650, 1)
sout <- subcrt("pyrrhotite_new", T = T, P = 1)$out[[1]]
par(mfrow = c(1, 4), mar = c(4, 4.2, 1, 1))
labels <- c(G = "DG0f", H = "DH0f", S = "S0", Cp = "Cp0")
for(property in c("G", "H", "S", "Cp")) {
plot(sout$T, sout[, property], col = sout$polymorph,
xlab = axis.label("T"), ylab = axis.label(labels[property])
)
abline(v = Ttr, lty = 3, col = 8)
if(property == "G")
legend("bottomleft", c("1", "2"), pch = 1, col = c(1, 2), title = "Polymorph")
}
# Restore default settings for the questions below
reset()
## ----trisulfur, eval = FALSE, echo = FALSE------------------------------------
# par(mfrow = c(1, 3))
#
# ## BLOCK 1
# T <- 350
# P <- 5000
# res <- 200
#
# ## BLOCK 2
# wt_percent_S <- 10
# wt_permil_S <- wt_percent_S * 10
# molar_mass_S <- mass("S") # 32.06
# moles_S <- wt_permil_S / molar_mass_S
# grams_H2O <- 1000 - wt_permil_S
# molality_S <- 1000 * moles_S / grams_H2O
# logm_S <- log10(molality_S)
#
# ## BLOCK 3
# basis(c("Ni", "SiO2", "Fe2O3", "H2S", "H2O", "oxygen", "H+"))
# species(c("H2S", "HS-", "SO2", "HSO4-", "SO4-2", "S3-"))
# a <- affinity(pH = c(2, 10, res), O2 = c(-34, -22, res), T = T, P = P)
# e <- equilibrate(a, loga.balance = logm_S)
# diagram(e)
#
# ## BLOCK 4
# mod.buffer("NNO", c("nickel", "bunsenite"), state = "cr", logact = 0)
# for(buffer in c("HM", "QFM", "NNO")) {
# basis("O2", buffer)
# logfO2_ <- affinity(return.buffer = TRUE, T = T, P = P)$O2
# abline(h = logfO2_, lty = 3, col = 2)
# text(8.5, logfO2_, buffer, adj = c(0, 0), col = 2, cex = 0.9)
# }
#
# ## BLOCK 5
# pH <- subcrt(c("H2O", "H+", "OH-"), c(-1, 1, 1), T = T, P = P)$out$logK / -2
# abline(v = pH, lty = 2, col = 4)
#
# ## BLOCK 6
# lTP <- describe.property(c("T", "P"), c(T, P))
# lS <- paste(wt_percent_S, "wt% S(aq)")
# ltext <- c(lTP, lS)
# legend("topright", ltext, bty = "n", bg = "transparent")
# title(quote("Parameters for"~S[3]^"-"~"from Pokrovski and Dubessy (2015)"), xpd = NA)
#
# ######## Plot 2: Modify Gibbs energy
#
# oldG <- info(info("S3-"))$G
# newG <- oldG - 12548
# mod.OBIGT("S3-", G = newG)
# a <- affinity(pH = c(2, 10, res), O2 = c(-34, -22, res), T = T, P = P)
# e <- equilibrate(a, loga.balance = logm_S)
# diagram(e)
# legend("topright", ltext, bty = "n", bg = "transparent")
# title(quote("Modified"~log*italic(K)~"after Pokrovski and Dubrovinsky (2011)"), xpd = NA)
# OBIGT()
#
# ######## Plot 3: Do it with DEW
#
# T <- 700
# P <- 10000 # 10000 bar = 1 GPa
# oldwat <- water("DEW")
# add.OBIGT("DEW")
# info(species()$ispecies)
# a <- affinity(pH = c(2, 10, res), O2 = c(-18, -10, res), T = T, P = P)
# e <- equilibrate(a, loga.balance = logm_S)
# diagram(e)
# lTP <- describe.property(c("T", "P"), c(T, P))
# ltext <- c(lTP, lS)
# legend("topright", ltext, bty = "n", bg = "transparent")
# title(quote("Deep Earth Water (DEW)"~"model"))
# water(oldwat)
# OBIGT()
## ----trisulfur, eval = FALSE, echo = 3:43-------------------------------------
# par(mfrow = c(1, 3))
#
# ## BLOCK 1
# T <- 350
# P <- 5000
# res <- 200
#
# ## BLOCK 2
# wt_percent_S <- 10
# wt_permil_S <- wt_percent_S * 10
# molar_mass_S <- mass("S") # 32.06
# moles_S <- wt_permil_S / molar_mass_S
# grams_H2O <- 1000 - wt_permil_S
# molality_S <- 1000 * moles_S / grams_H2O
# logm_S <- log10(molality_S)
#
# ## BLOCK 3
# basis(c("Ni", "SiO2", "Fe2O3", "H2S", "H2O", "oxygen", "H+"))
# species(c("H2S", "HS-", "SO2", "HSO4-", "SO4-2", "S3-"))
# a <- affinity(pH = c(2, 10, res), O2 = c(-34, -22, res), T = T, P = P)
# e <- equilibrate(a, loga.balance = logm_S)
# diagram(e)
#
# ## BLOCK 4
# mod.buffer("NNO", c("nickel", "bunsenite"), state = "cr", logact = 0)
# for(buffer in c("HM", "QFM", "NNO")) {
# basis("O2", buffer)
# logfO2_ <- affinity(return.buffer = TRUE, T = T, P = P)$O2
# abline(h = logfO2_, lty = 3, col = 2)
# text(8.5, logfO2_, buffer, adj = c(0, 0), col = 2, cex = 0.9)
# }
#
# ## BLOCK 5
# pH <- subcrt(c("H2O", "H+", "OH-"), c(-1, 1, 1), T = T, P = P)$out$logK / -2
# abline(v = pH, lty = 2, col = 4)
#
# ## BLOCK 6
# lTP <- describe.property(c("T", "P"), c(T, P))
# lS <- paste(wt_percent_S, "wt% S(aq)")
# ltext <- c(lTP, lS)
# legend("topright", ltext, bty = "n", bg = "transparent")
# title(quote("Parameters for"~S[3]^"-"~"from Pokrovski and Dubessy (2015)"), xpd = NA)
#
# ######## Plot 2: Modify Gibbs energy
#
# oldG <- info(info("S3-"))$G
# newG <- oldG - 12548
# mod.OBIGT("S3-", G = newG)
# a <- affinity(pH = c(2, 10, res), O2 = c(-34, -22, res), T = T, P = P)
# e <- equilibrate(a, loga.balance = logm_S)
# diagram(e)
# legend("topright", ltext, bty = "n", bg = "transparent")
# title(quote("Modified"~log*italic(K)~"after Pokrovski and Dubrovinsky (2011)"), xpd = NA)
# OBIGT()
#
# ######## Plot 3: Do it with DEW
#
# T <- 700
# P <- 10000 # 10000 bar = 1 GPa
# oldwat <- water("DEW")
# add.OBIGT("DEW")
# info(species()$ispecies)
# a <- affinity(pH = c(2, 10, res), O2 = c(-18, -10, res), T = T, P = P)
# e <- equilibrate(a, loga.balance = logm_S)
# diagram(e)
# lTP <- describe.property(c("T", "P"), c(T, P))
# ltext <- c(lTP, lS)
# legend("topright", ltext, bty = "n", bg = "transparent")
# title(quote("Deep Earth Water (DEW)"~"model"))
# water(oldwat)
# OBIGT()
## ----trisulfur_logK, message = FALSE, echo = 1:3------------------------------
species <- c("H2S", "SO4-2", "H+", "S3-", "oxygen", "H2O")
coeffs <- c(-2, -1, -1, 1, 0.75, 2.5)
(calclogK <- subcrt(species, coeffs, T = seq(300, 450, 50), P = 5000)$out$logK)
fcalclogK <- formatC(calclogK, format = "f", digits = 1)
reflogK <- -9.6
dlogK <- calclogK[2] - reflogK
# Put in a test so that we don't get surprised by
# future database updates or changes to this vignette
stopifnot(round(dlogK, 4) == -4.4132)
## ----trisulfur, eval = FALSE, echo = 46:55------------------------------------
# par(mfrow = c(1, 3))
#
# ## BLOCK 1
# T <- 350
# P <- 5000
# res <- 200
#
# ## BLOCK 2
# wt_percent_S <- 10
# wt_permil_S <- wt_percent_S * 10
# molar_mass_S <- mass("S") # 32.06
# moles_S <- wt_permil_S / molar_mass_S
# grams_H2O <- 1000 - wt_permil_S
# molality_S <- 1000 * moles_S / grams_H2O
# logm_S <- log10(molality_S)
#
# ## BLOCK 3
# basis(c("Ni", "SiO2", "Fe2O3", "H2S", "H2O", "oxygen", "H+"))
# species(c("H2S", "HS-", "SO2", "HSO4-", "SO4-2", "S3-"))
# a <- affinity(pH = c(2, 10, res), O2 = c(-34, -22, res), T = T, P = P)
# e <- equilibrate(a, loga.balance = logm_S)
# diagram(e)
#
# ## BLOCK 4
# mod.buffer("NNO", c("nickel", "bunsenite"), state = "cr", logact = 0)
# for(buffer in c("HM", "QFM", "NNO")) {
# basis("O2", buffer)
# logfO2_ <- affinity(return.buffer = TRUE, T = T, P = P)$O2
# abline(h = logfO2_, lty = 3, col = 2)
# text(8.5, logfO2_, buffer, adj = c(0, 0), col = 2, cex = 0.9)
# }
#
# ## BLOCK 5
# pH <- subcrt(c("H2O", "H+", "OH-"), c(-1, 1, 1), T = T, P = P)$out$logK / -2
# abline(v = pH, lty = 2, col = 4)
#
# ## BLOCK 6
# lTP <- describe.property(c("T", "P"), c(T, P))
# lS <- paste(wt_percent_S, "wt% S(aq)")
# ltext <- c(lTP, lS)
# legend("topright", ltext, bty = "n", bg = "transparent")
# title(quote("Parameters for"~S[3]^"-"~"from Pokrovski and Dubessy (2015)"), xpd = NA)
#
# ######## Plot 2: Modify Gibbs energy
#
# oldG <- info(info("S3-"))$G
# newG <- oldG - 12548
# mod.OBIGT("S3-", G = newG)
# a <- affinity(pH = c(2, 10, res), O2 = c(-34, -22, res), T = T, P = P)
# e <- equilibrate(a, loga.balance = logm_S)
# diagram(e)
# legend("topright", ltext, bty = "n", bg = "transparent")
# title(quote("Modified"~log*italic(K)~"after Pokrovski and Dubrovinsky (2011)"), xpd = NA)
# OBIGT()
#
# ######## Plot 3: Do it with DEW
#
# T <- 700
# P <- 10000 # 10000 bar = 1 GPa
# oldwat <- water("DEW")
# add.OBIGT("DEW")
# info(species()$ispecies)
# a <- affinity(pH = c(2, 10, res), O2 = c(-18, -10, res), T = T, P = P)
# e <- equilibrate(a, loga.balance = logm_S)
# diagram(e)
# lTP <- describe.property(c("T", "P"), c(T, P))
# ltext <- c(lTP, lS)
# legend("topright", ltext, bty = "n", bg = "transparent")
# title(quote("Deep Earth Water (DEW)"~"model"))
# water(oldwat)
# OBIGT()
## ----trisulfur_DEW, message = FALSE, echo = 8:22, collapse = TRUE, fig.keep = "none"----
# The first four lines are stand-ins to make this block runnable and get the right output from info();
# the diagram actually shown in the vignette is made using the 'trisulfur' block above
b <- basis("CHNOS+")
s <- species(c("H2S", "HS-", "SO2", "HSO4-", "SO4-2", "S3-"))
res <- 10
wt_percent_S <- logm_S <- 0
######## End of stand-in code ########
T <- 700
P <- 10000 # 10000 bar = 1 GPa
oldwat <- water("DEW")
add.OBIGT("DEW")
info(species()$ispecies)[, 1:8]
a <- affinity(pH = c(2, 10, res), O2 = c(-18, -10, res), T = T, P = P)
e <- equilibrate(a, loga.balance = logm_S)
diagram(e)
lTP <- describe.property(c("T", "P"), c(T, P))
lS <- paste(wt_percent_S, "wt% S(aq)")
ltext <- c(lTP, lS)
legend("topright", ltext, bty = "n", bg = "transparent")
title(quote("Deep Earth Water (DEW)"~"model"))
water(oldwat)
OBIGT()
## ----trisulfur, echo = FALSE, message = FALSE, results = "hide", fig.width = 10, fig.height = 3.33, out.width = "100%", out.extra='class="full-width"', pngquant = pngquant, cache = TRUE----
par(mfrow = c(1, 3))
## BLOCK 1
T <- 350
P <- 5000
res <- 200
## BLOCK 2
wt_percent_S <- 10
wt_permil_S <- wt_percent_S * 10
molar_mass_S <- mass("S") # 32.06
moles_S <- wt_permil_S / molar_mass_S
grams_H2O <- 1000 - wt_permil_S
molality_S <- 1000 * moles_S / grams_H2O
logm_S <- log10(molality_S)
## BLOCK 3
basis(c("Ni", "SiO2", "Fe2O3", "H2S", "H2O", "oxygen", "H+"))
species(c("H2S", "HS-", "SO2", "HSO4-", "SO4-2", "S3-"))
a <- affinity(pH = c(2, 10, res), O2 = c(-34, -22, res), T = T, P = P)
e <- equilibrate(a, loga.balance = logm_S)
diagram(e)
## BLOCK 4
mod.buffer("NNO", c("nickel", "bunsenite"), state = "cr", logact = 0)
for(buffer in c("HM", "QFM", "NNO")) {
basis("O2", buffer)
logfO2_ <- affinity(return.buffer = TRUE, T = T, P = P)$O2
abline(h = logfO2_, lty = 3, col = 2)
text(8.5, logfO2_, buffer, adj = c(0, 0), col = 2, cex = 0.9)
}
## BLOCK 5
pH <- subcrt(c("H2O", "H+", "OH-"), c(-1, 1, 1), T = T, P = P)$out$logK / -2
abline(v = pH, lty = 2, col = 4)
## BLOCK 6
lTP <- describe.property(c("T", "P"), c(T, P))
lS <- paste(wt_percent_S, "wt% S(aq)")
ltext <- c(lTP, lS)
legend("topright", ltext, bty = "n", bg = "transparent")
title(quote("Parameters for"~S[3]^"-"~"from Pokrovski and Dubessy (2015)"), xpd = NA)
######## Plot 2: Modify Gibbs energy
oldG <- info(info("S3-"))$G
newG <- oldG - 12548
mod.OBIGT("S3-", G = newG)
a <- affinity(pH = c(2, 10, res), O2 = c(-34, -22, res), T = T, P = P)
e <- equilibrate(a, loga.balance = logm_S)
diagram(e)
legend("topright", ltext, bty = "n", bg = "transparent")
title(quote("Modified"~log*italic(K)~"after Pokrovski and Dubrovinsky (2011)"), xpd = NA)
OBIGT()
######## Plot 3: Do it with DEW
T <- 700
P <- 10000 # 10000 bar = 1 GPa
oldwat <- water("DEW")
add.OBIGT("DEW")
info(species()$ispecies)
a <- affinity(pH = c(2, 10, res), O2 = c(-18, -10, res), T = T, P = P)
e <- equilibrate(a, loga.balance = logm_S)
diagram(e)
lTP <- describe.property(c("T", "P"), c(T, P))
ltext <- c(lTP, lS)
legend("topright", ltext, bty = "n", bg = "transparent")
title(quote("Deep Earth Water (DEW)"~"model"))
water(oldwat)
OBIGT()
## ----pyrrhotite_polymorphs, collapse = TRUE-----------------------------------
subcrt("pyrrhotite", T = c(25, 150, 350), property = "G")$out
## ----pyrite_limit-------------------------------------------------------------
subcrt("pyrite", T = seq(200, 1000, 200), P = 1)
## ----mineral_Ttr, collapse = TRUE---------------------------------------------
file <- system.file("extdata/OBIGT/inorganic_cr.csv", package = "CHNOSZ")
dat <- read.csv(file)
# Reverse rows so highest-T polymorph for each mineral is listed first
dat <- dat[nrow(dat):1, ]
# Remove low-T polymorphs
dat <- dat[!duplicated(dat$name), ]
# Remove minerals with no T limit for phase stability (+ve) or Cp equation (-ve)
dat <- dat[!is.na(dat$z.T), ]
# Keep minerals with phase stability limit
dat <- dat[dat$z.T > 0, ]
# Get names of minerals and put into original order
rev(dat$name)
## ----muscovite_limit, message = FALSE-----------------------------------------
add.OBIGT("SUPCRT92")
subcrt("muscovite", T = 850, P = 4500)
reset()
## ----KMQ_basis_species, message = FALSE---------------------------------------
basis(c("Al+3", "quartz", "K+", "H+", "H2O", "oxygen"))
species(c("kaolinite", "muscovite", "K-feldspar"))
## ----KMQ_m_K, message = FALSE-------------------------------------------------
# Define temperature, pressure, and molality of Cl- (==IS)
T <- 150
P <- 500
IS <- m_Cl <- 1
# Calculate equilibrium constant for Ab-Kfs reaction, corrected for ionic strength
logK_AK <- subcrt(c("albite", "K+", "K-feldspar", "Na+"), c(-1, -1, 1, 1),
T = T, P = P, IS = IS)$out$logK
K_AK <- 10 ^ logK_AK
# Calculate molality of K+
(m_K <- m_Cl / (K_AK + 1))
## ----KMQ_diagram, eval = FALSE, echo = 2:10-----------------------------------
# par(mfrow = c(1, 2))
# basis("K+", log10(m_K))
# a <- affinity(pH = c(2, 10), O2 = c(-55, -38), T = T, P = P, IS = IS)
# diagram(a, srt = 90)
# lTP <- as.expression(c(lT(T), lP(P)))
# legend("topleft", legend = lTP, bty = "n", inset = c(-0.05, 0), cex = 0.9)
# ltxt <- c(quote("Unit molality of Cl"^"-"), "Quartz saturation")
# legend("topright", legend = ltxt, bty = "n", cex = 0.9)
# title("Mineral data from Berman (1988)\nand Sverjensky et al. (1991) (OBIGT default)",
# font.main = 1, cex.main = 0.9)
# add.OBIGT("SUPCRT92")
# a <- affinity(pH = c(2, 10), O2 = c(-55, -38), T = T, P = P, IS = IS)
# diagram(a, srt = 90)
# title("Mineral data from Helgeson et al. (1978)\n(as used in SUPCRT92)",
# font.main = 1, cex.main = 0.9)
# OBIGT()
## ----KMQ_diagram, message = FALSE, fig.width = 8, fig.height = 4, out.width = "100%", results = "hide", echo = FALSE----
par(mfrow = c(1, 2))
basis("K+", log10(m_K))
a <- affinity(pH = c(2, 10), O2 = c(-55, -38), T = T, P = P, IS = IS)
diagram(a, srt = 90)
lTP <- as.expression(c(lT(T), lP(P)))
legend("topleft", legend = lTP, bty = "n", inset = c(-0.05, 0), cex = 0.9)
ltxt <- c(quote("Unit molality of Cl"^"-"), "Quartz saturation")
legend("topright", legend = ltxt, bty = "n", cex = 0.9)
title("Mineral data from Berman (1988)\nand Sverjensky et al. (1991) (OBIGT default)",
font.main = 1, cex.main = 0.9)
add.OBIGT("SUPCRT92")
a <- affinity(pH = c(2, 10), O2 = c(-55, -38), T = T, P = P, IS = IS)
diagram(a, srt = 90)
title("Mineral data from Helgeson et al. (1978)\n(as used in SUPCRT92)",
font.main = 1, cex.main = 0.9)
OBIGT()
## ----KMQ_refs, message = FALSE------------------------------------------------
thermo.refs(species()$ispecies)
## ----KMQ_diagram, eval = FALSE, echo = 11:15----------------------------------
# par(mfrow = c(1, 2))
# basis("K+", log10(m_K))
# a <- affinity(pH = c(2, 10), O2 = c(-55, -38), T = T, P = P, IS = IS)
# diagram(a, srt = 90)
# lTP <- as.expression(c(lT(T), lP(P)))
# legend("topleft", legend = lTP, bty = "n", inset = c(-0.05, 0), cex = 0.9)
# ltxt <- c(quote("Unit molality of Cl"^"-"), "Quartz saturation")
# legend("topright", legend = ltxt, bty = "n", cex = 0.9)
# title("Mineral data from Berman (1988)\nand Sverjensky et al. (1991) (OBIGT default)",
# font.main = 1, cex.main = 0.9)
# add.OBIGT("SUPCRT92")
# a <- affinity(pH = c(2, 10), O2 = c(-55, -38), T = T, P = P, IS = IS)
# diagram(a, srt = 90)
# title("Mineral data from Helgeson et al. (1978)\n(as used in SUPCRT92)",
# font.main = 1, cex.main = 0.9)
# OBIGT()
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/doc/FAQ.R
|
---
title: "CHNOSZ FAQ"
author: "Jeffrey M. Dick"
output:
html_vignette:
mathjax: null
toc: true
vignette: >
%\VignetteIndexEntry{CHNOSZ FAQ}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
bibliography: vig.bib
csl: elementa.csl
link-citations: true
---
<style>
/* https://gomakethings.com/how-to-break-an-image-out-of-its-parent-container-with-css/ */
@media (min-width: 700px) {
.full-width {
left: 50%;
margin-left: -50vw;
margin-right: -50vw;
max-width: 100vw;
position: relative;
right: 50%;
width: 100vw;
}
}
@media (min-width: 1100px) {
.full-width {
left: 50vw; /* fallback if needed */
left: calc(50vw - 200px);
width: 1100px;
position: relative;
}
}
/* zero margin around pre blocks (looks more like R console output) */
pre {
margin-top: 0;
margin-bottom: 0;
}
/* CSS snippet from boostrap.css modified by Jeffrey Dick on 2023-11-14 */
/*!
* Bootstrap v5.3.2 (https://getbootstrap.com/)
* Copyright 2011-2023 The Bootstrap Authors
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
*/
:root,
[data-bs-theme=light] {
--bs-info-text-emphasis: #055160;
--bs-warning-text-emphasis: #664d03;
--bs-info-bg-subtle: #cff4fc;
--bs-warning-bg-subtle: #fff3cd;
--bs-info-border-subtle: #9eeaf9;
--bs-warning-border-subtle: #ffe69c;
--bs-border-width: 1px;
--bs-border-radius: 0.375rem;
}
.alert {
--bs-alert-bg: transparent;
--bs-alert-padding-x: 0.5rem;
--bs-alert-padding-y: 0.5rem;
--bs-alert-margin-bottom: 1rem;
--bs-alert-color: inherit;
--bs-alert-border-color: transparent;
--bs-alert-border: var(--bs-border-width) solid var(--bs-alert-border-color);
--bs-alert-border-radius: var(--bs-border-radius);
--bs-alert-link-color: inherit;
position: relative;
padding: var(--bs-alert-padding-y) var(--bs-alert-padding-x);
margin-bottom: var(--bs-alert-margin-bottom);
color: var(--bs-alert-color);
background-color: var(--bs-alert-bg);
border: var(--bs-alert-border);
border-radius: var(--bs-alert-border-radius);
}
.alert-info {
--bs-alert-color: var(--bs-info-text-emphasis);
--bs-alert-bg: var(--bs-info-bg-subtle);
--bs-alert-border-color: var(--bs-info-border-subtle);
--bs-alert-link-color: var(--bs-info-text-emphasis);
}
.alert-warning {
--bs-alert-color: var(--bs-warning-text-emphasis);
--bs-alert-bg: var(--bs-warning-bg-subtle);
--bs-alert-border-color: var(--bs-warning-border-subtle);
--bs-alert-link-color: var(--bs-warning-text-emphasis);
}
</style>
<script>
function ToggleDiv(ID) {
var D = document.getElementById("D-" + ID);
var B = document.getElementById("B-" + ID);
if (D.style.display === "none") {
// open the div and change button text
D.style.display = "block";
B.innerText = "Hide code";
} else {
// close the div and change button text
D.style.display = "none";
B.innerText = "Show code";
}
}
</script>
```{r setup, include = FALSE}
library(CHNOSZ)
options(width = 80)
# Use pngquant to optimize PNG images
library(knitr)
knit_hooks$set(pngquant = hook_pngquant)
pngquant <- "--speed=1 --quality=0-25"
if (!nzchar(Sys.which("pngquant"))) pngquant <- NULL
# To make warnings appear in text box 20230619
# https://selbydavid.com/2017/06/18/rmarkdown-alerts/
knitr::knit_hooks$set(
error = function(x, options) {
paste('\n\n<div class="alert alert-danger">',
gsub('##', '\n', gsub('^##\ Error', '**Error:**', x)),
'</div>', sep = '\n')
},
warning = function(x, options) {
paste('\n\n<div class="alert alert-warning">',
gsub('##', '\n', gsub('^##\ Warning:', '**Warning:**', x)),
'</div>', sep = '\n')
},
message = function(x, options) {
paste('\n\n<div class="alert alert-info">',
gsub('##', '\n', x),
'</div>', sep = '\n')
}
)
# Set dpi 20231129
knitr::opts_chunk$set(
dpi = if(nzchar(Sys.getenv("CHNOSZ_BUILD_LARGE_VIGNETTES"))) 100 else 72
)
```
```{r echo = F, cache = F}
# Merge consecutive messages into a single div 20231114
knitr::knit_hooks$set(document = function(x){
# Not sure why this is needed, but simply computing on 'x' doesn't work
file <- tempfile()
writeLines(x, file)
x <- readLines(file)
# Line numbers of the document with </div>
enddiv <- which(x == "</div>")
# Line numbers with <div class="alert alert-info">
beginalert <- which(x == '<div class="alert alert-info">')
# Find </div> followed <div class="alert alert-info"> (skip empty lines)
removediv <- (enddiv + 2) %in% beginalert
if(any(removediv)) {
# Lines to remove
rmlines1 <- enddiv[removediv]
rmlines2 <- enddiv[removediv] + 1
rmlines3 <- enddiv[removediv] + 2
# Do the removing
x <- x[-c(rmlines1, rmlines2, rmlines3)]
}
x
})
```
```{r HTML, include = FALSE}
NOTE <- '<span style="background-color: yellow;">NOTE</span>'
# CHNOSZ functions
equilibrate_ <- '<code>equilibrate()</code>'
info_ <- '<code>info()</code>'
thermo.refs_ <- '<code>thermo.refs()</code>'
# Math stuff
logK <- "log <i>K</i>"
Hplus <- "H<sup>+</sup>"
HCO2_ <- "HCO<sub>2</sub><sup>−</sup>"
HCO3_ <- "HCO<sub>3</sub><sup>−</sup>"
O2 <- "O<sub>2</sub>"
S2 <- "S<sub>2</sub>"
log <- "log "
aHCO2_ <- "<i>a</i><sub>HCO<sub>2</sub><sup>−</sup></sub>"
aHCO3_ <- "<i>a</i><sub>HCO<sub>3</sub><sup>−</sup></sub>"
logfO2 <- "log <i>f</i><sub>O<sub>2</sub></sub>"
Ctot <- "C<sub>tot</sub>"
C3H5O2_ <- "C<sub>3</sub>H<sub>5</sub>O<sub>2</sub><sup>−</sup>"
a3HCO3_ <- "<i>a</i><sup>3</sup><sub>HCO<sub>3</sub><sup>−</sup></sub>"
aC3H5O2_ <- "<i>a</i><sub>C<sub>3</sub>H<sub>5</sub>O<sub>2</sub><sup>−</sup></sub>"
a2HCO3_ <- "<i>a</i><sup>2</sup><sub>HCO<sub>3</sub><sup>−</sup></sub>"
logCtot <- "log C<sub>tot</sub>"
CO2 <- "CO<sub>2</sub>"
H2O <- "H<sub>2</sub>O"
S3minus <- "S<sub>3</sub><sup>-</sup>"
H2S <- "H<sub>2</sub>S"
SO4__ <- "SO<sub>4</sub><sup>-2</sup>"
Kplus <- "K<sup>+</sup>"
Naplus <- "Na<sup>+</sup>"
Clminus <- "Cl<sup>-</sup>"
H2 <- "H<sub>2</sub>"
```
This vignette was compiled on `r Sys.Date()` with CHNOSZ version `r sessionInfo()$otherPkgs$CHNOSZ$Version`.
## How is 'CHNOSZ' pronounced?
As one syllable that starts with an *sh* sound and [rhymes with *Oz*](https://en.wiktionary.org/wiki/Rhymes:English/%C9%92z).
CHNOSZ and [schnoz](https://en.wiktionary.org/wiki/schnozz) are homophones.
*Added on 2023-05-22.*
## How should CHNOSZ be cited?
* This paper is the general reference for CHNOSZ: @Dic19.
* This paper describes diagrams with multiple metals: @Dic21b.
* This paper describes metastable equilibrium calculations for proteins: @Dic08.
* The [<span style="color:blue">*OBIGT thermodynamic database*</span>](OBIGT.html) represents the work of many researchers.
**If you publish results that depend on any of these data, please cite the primary sources.**
Use `r info_` to show the reference keys for particular species and `r thermo.refs_` to list the bibliographic details.
The following example shows the sources of data for aqueous alanine:
```{r alanine_refs, message = FALSE}
info(info("alanine"))[c("ref1", "ref2")]
thermo.refs(info("alanine"))
```
* Mineral data in OBIGT are based on @Ber88 together with sulfides and other non-conflicting minerals from @HDNB78. For a reaction such as the pyrite-pyrrhotite-magnetite (PPM) oxygen fugacity buffer, all the sources of data can be listed as follows:
```{r PPM_refs, message = FALSE}
basis(c("pyrite", "pyrrhotite", "oxygen"))
sres <- subcrt("magnetite", 1)
info(sres$reaction$ispecies)[, 1:6]
thermo.refs(sres)
reset()
```
* Additional minerals from @HDNB78, that were available in SUPCRT92 but may conflict with the @Ber88 compilation, can be loaded from an optional database with `add.OBIGT("SUPCRT92")`. When using these data, it is appropriate to cite @HDNB78 rather than SUPCRT92.
*Added on 2023-05-27; PPM example added on 2023-11-15.*
## What thermodynamic models are used in CHNOSZ?
* The thermodynamic properties of liquid water are calculated using Fortran code from SUPCRT92 [@JOH92] or optionally an implementation in R of the IAPWS-95 formulation [@WP02].
* Thermodynamic properties of other species are taken from a database for minerals and inorganic and organic aqueous species including biomolecules, or from amino acid group additivity for proteins [@DLH06].
* The corresponding high-temperature properties are calculated using the @BB85 equations for minerals and the revised [@TH88;@SH88] Helgeson-Kirkham-Flowers [@HKF81] equations for aqueous species.
* The revised HKF equations are augmented with the Deep Earth Water (DEW) model [@SHA14] and estimates of parameters in the extended Debye-Hückel equation [@MSS13] to calculate standard-state properties and activity coefficients for given ionic strength at high pressure (to 6 GPa).
* Activity coefficients are implemented via adjusted standard Gibbs energies at specified ionic strength [@Alb96], which converts all activity variables in the workflow to molalities.
* A related adjustment is available to convert standard Gibbs energies for gases from the 1 bar standard state used in SUPCRT92 to a variable-pressure standard state [@AC93,Ch.12].
*Added to <https://chnosz.net/> website on 2018-11-13; moved to FAQ on 2023-05-27; added references for **revised** HKF on 2023-11-17.*
## When and why do equal-activity boundaries depend on total activity?
Short answer: When the species have the same number of the conserved element (let's take C for example),
their activities are raised to the same exponent in reaction quotient, so the activity ratio in the law of mass action becomes unity.
But when the species have different numbers of the conserved element (for example, propanoate with 3 C and bicarbonate with 1 C),
their activities are raised to different exponents, and the activity ratio does not become unity even when the activities are equal
(except for the specific case where the activities themselves are equal to 1).
Therefore, in general, the condition of "equal activity" is not sufficient to define boundaries on a relative stability diagram;
instead, we need to say "activity of each species equal to *x*" or alternatively "total activity equal to *y*".
Long answer: First, consider a reaction between formate and bicarbonate: `r HCO2_` + 0.5 `r O2` $\rightleftharpoons$ `r HCO3_`.
The law of mass action (LMA) is <strong>`r logK` $=$ `r log`(`r aHCO3_` / `r aHCO2_`) $-$ 0.5 `r logfO2`</strong>.
The condition of equal activity is <font color="red">`r aHCO2_` $=$ `r aHCO3_`</font>.
Then, the LMA simplifies to <strong>`r logK` $=$ $-$ 0.5 `r logfO2`</strong>.
The total activity of C is given by <font color="blue">`r Ctot` $=$ `r aHCO2_` $+$ `r aHCO3_`</font>.
According to the LMA, `r logfO2` is a function only of `r logK`, so <font color="green">*d*`r logfO2`/*d*`r logCtot` $=$ 0</font>.
In other words, the position of the equal-activity boundary is independent of the value of `r Ctot`.
Next, consider a reaction between propanoate and bicarbonate: `r C3H5O2_` + <sup>7</sup>⁄<sub>2</sub> `r O2` $\rightleftharpoons$ 3 `r HCO3_` + 2 `r Hplus`.
The LMA is <strong>`r logK` $=$ `r log`(`r a3HCO3_` / `r aC3H5O2_`) $-$ pH $-$ <sup>7</sup>⁄<sub>2</sub> `r logfO2`</strong>.
The condition of equal activity is <font color="red">`r aC3H5O2_` $=$ `r aHCO3_`</font>.
Then, the LMA simplifies to <strong>`r logK` $=$ `r log``r a2HCO3_` $-$ pH $-$ <sup>7</sup>⁄<sub>2</sub> `r logfO2`</strong>.
The total activity of C is given by <font color="blue">`r Ctot` $=$ 3 `r aC3H5O2_` $+$ `r aHCO3_`</font>; combined with the condition of equal activity,
this gives <font color="blue">`r Ctot` $=$ 4 `r aHCO3_`</font>.
Substituting this into the LMA gives <strong>`r logK` $=$ `r log`(`r Ctot` / 4)<sup>2</sup> $-$ pH $-$ <sup>7</sup>⁄<sub>2</sub> `r logfO2`</strong>,
which can be rearranged to write `r logfO2` $=$ <sup>2</sup>⁄<sub>7</sub> (2 `r log``r Ctot` $-$ `r logK` $-$ `r log`16 $-$ pH).
It follows that <font color="green">*d*`r logfO2`/*d*`r logCtot` $=$ <sup>4</sup>⁄<sub>7</sub></font>,
and the position of the equal-activity boundary depends on `r Ctot`.
According to this analysis, increasing `r Ctot` from 0.03 to 3 molal (a 2 log-unit increase)
would have no effect on the location of the formate-bicarbonate equal-activity boundary,
but would raise the propanoate-bicarbonate equal-activity boundary by <sup>8</sup>⁄<sub>7</sub> units on the `r logfO2` scale.
Because the reaction between bicarbonate and `r CO2` does not involve `r O2` (but rather `r H2O` and `r Hplus`),
the same effect should occur on the propanoate-`r CO2` equal-activity boundary.
The plots below, which are made using `r equilibrate_` for species in the Deep Earth Water (DEW) model, illustrate this effect.
<button id="B-DEW_Ctot" onclick="ToggleDiv('DEW_Ctot')">Show code</button>
<div id="D-DEW_Ctot" style="display: none">
```{r DEW_Ctot, eval = FALSE}
### Based on demo/DEW.R in CHNOSZ
# Set up subplots
par(mfrow = c(1, 2), mar = c(3.0, 3.5, 2.5, 1.0), mgp = c(1.7, 0.3, 0), las = 1, tcl = 0.3, xaxs = "i", yaxs = "i")
# Activate DEW model
water("DEW")
###########
## logfO2-pH diagram for aqueous inorganic and organic carbon species at high pressure
## After Figure 1b of Sverjensky et al., 2014b [SSH14]
## (Nature Geoscience, https://doi.org/10.1038/NGEO2291)
###########
# Define system
basis("CHNOS+")
inorganic <- c("CO2", "HCO3-", "CO3-2", "CH4")
organic <- c("formic acid", "formate", "acetic acid", "acetate", "propanoic acid", "propanoate")
species(c(inorganic, organic), 0)
fill <- c(rep("aliceblue", length(inorganic)), rep("aquamarine", length(organic)))
# A function to make the diagrams
dfun <- function(T = 600, P = 50000, res = 200, Ctot = 0.03) {
a <- affinity(pH = c(0, 10, res), O2 = c(-24, -12, res), T = T, P = P)
# Set total C concentration to 0.03 molal
# (from EQ3NR model for eclogite [Supporting Information of SSH14])
e <- equilibrate(a, loga.balance = log10(Ctot))
diagram(e, fill = fill)
dp <- describe.property(c(" T", " P"), c(T, P), digits = 0)
legend("bottomleft", legend = dp, bty = "n")
}
water("DEW")
add.OBIGT("DEW")
dfun(Ctot = 0.03)
mtitle(c("Inorganic and organic species", "C[total] = 0.03 molal"))
dfun(Ctot = 3)
mtitle(c("Inorganic and organic species", "C[total] = 3 molal"))
# Restore default settings for the questions below
reset()
```
</div>
```{r DEW_Ctot, echo = FALSE, message = FALSE, results = "hide", fig.width = 8, fig.height = 4, out.width = "100%", fig.align = "center", pngquant = pngquant, cache = TRUE}
```
*Added on 2023-05-17.*
## How can minerals with polymorphic transitions be added to the database?
The different crystal forms of a mineral are called polymorphs.
Many minerals undergo polymorphic transitions upon heating.
Each polymorph for a given mineral should have its own entry in OBIGT, including values of the standard thermodynamic properties (Δ*G*°~*f*~, Δ*H*°~*f*~, and *S*°) at 25 °C.
The 25 °C (or 298.15 K) values for high-temperature polymorphs are often not listed in thermodynamic tables, but they can be calculated.
This thermodynamic cycle shows how: we calculate the changes of a thermodyamic property (pictured here as `DS1` and `DS2`) between 298.15 K and the transition temperature (`Ttr`) for two polymorphs, then combine those with the property of the polymorphic transition (`DStr`) to obtain the difference of the property between the polymorphs at 298.15 K (`DS298`).
```text
DStr DStr: entropy of transition between polymorphs 1 and 2
Ttr o---------->o Ttr: temperature of transition
^ |
| |
DS1 | | DS2 DS1: entropy change of polymorph 1 from 298.15 K to Ttr
| | DS2: entropy change of polymorph 2 from 298.15 K to Ttr
| v
298.15 K o==========>o DS298: entropy difference between polymorphs 1 and 2 at 298.15 K
DS298 DS298 = DS1 + DStr - DS2
Polymorph 1 2
```
As an example, let's add pyrrhotite (Fe0.877S) from @PMW87.
The formula and thermodynamic properties of this pyrrhotite differ from those of FeS from @HDNB78, which is already in OBIGT.
We begin by defining all the input values in the next code block.
In addition to `G`, `H`, `S`, and the heat capacity coefficients, non-NA values of volume (`V`) must be provided for the polymorph transitions to be calculated correctly by `subcrt()`.
```{r pyrrhotite_values, message = FALSE}
# The formula of the new mineral and literature reference
formula <- "Fe0.877S"
ref1 <- "PMW87"
# Because the properties from Pankratz et al. (1987) are listed in calories,
# we need to change the output of subcrt() to calories (the default is Joules)
E.units("cal")
# Use temperature in Kelvin for the calculations below
T.units("K")
# Thermodynamic properties of polymorph 1 at 25 °C (298.15 K)
G1 <- -25543
H1 <- -25200
S1 <- 14.531
Cp1 <- 11.922
# Heat capacity coefficients for polymorph 1
a1 <- 7.510
b1 <- 0.014798
# For volume, use the value from Helgeson et al. (1978)
V1 <- V2 <- 18.2
# Transition temperature
Ttr <- 598
# Transition enthalpy (cal/mol)
DHtr <- 95
# Heat capacity coefficients for polymorph 2
a2 <- -1.709
b2 <- 0.011746
c2 <- 3073400
# Maximum temperature of polymorph 2
T2 <- 1800
```
Use the temperature (`Ttr`) and enthalpy of transition (`DHtr`) to calculate the entropy of transition (`DStr`).
Note that the Gibbs energy of transition (`DGtr`) is zero at `Ttr`.
```{r pyrrhotite_Ttr, message = FALSE}
DGtr <- 0 # DON'T CHANGE THIS
TDStr <- DHtr - DGtr # TΔS° = ΔH° - ΔG°
DStr <- TDStr / Ttr
```
Start new database entries that include basic information, volume, and heat capacity coefficients for each polymorph.
@PMW87 don't list *C~p~*° of the high-temperature polymorph extrapolated to 298.15 K, so leave it out.
If the properties were in Joules, we would omit `E_units = "cal"` or change it to `E_units = "J"`.
```{r pyrrhotite_Cp, results = "hide", message = FALSE}
mod.OBIGT("pyrrhotite_new", formula = formula, state = "cr", ref1 = ref1,
E_units = "cal", G = 0, H = 0, S = 0, V = V1, Cp = Cp1,
a = a1, b = b1, c = 0, d = 0, e = 0, f = 0, lambda = 0, T = Ttr)
mod.OBIGT("pyrrhotite_new", formula = formula, state = "cr2", ref1 = ref1,
E_units = "cal", G = 0, H = 0, S = 0, V = V2,
a = a2, b = b2, c = c2, d = 0, e = 0, f = 0, lambda = 0, T = T2)
```
For the time being, we set `G`, `H`, and `S` (i.e., the properties at 25 °C) to zero in order to easily calculate the temperature integrals of the properties from 298.15 K to `Ttr`.
Values of zero are placeholders that don't satisfy Δ*G*°~*f*~ = Δ*H*°~*f*~ − *T*Δ*S*°~*f*~ for either polymorph (the subscript *f* represents formation from the elements), as indicated by the following messages.
We will check again for consistency of the thermodynamic parameters at the end of the example.
```{r pyrrhotite_info, results = "hide", collapse = TRUE}
info(info("pyrrhotite_new", "cr"))
info(info("pyrrhotite_new", "cr2"))
```
In order to calculate the temperature integral of Δ*G*°~*f*~, we need not only the heat capacity coefficients but also actual values of *S*°.
Therefore, we start by calculating the entropy changes of each polymorph from 298.15 to `r Ttr` K (`DS1` and `DS2`) and combining those with the entropy of transition to obtain the difference of entropy between the polymorphs at 298.15 K.
For polymorph 1 (with `state = "cr"`) it's advisable to include `use.polymorphs = FALSE` to prevent `subcrt()` from trying to identify the most stable polymorph at the indicated temperature.
```{r pyrrhotite_S, message = FALSE}
DS1 <- subcrt("pyrrhotite_new", "cr", P = 1, T = Ttr, use.polymorphs = FALSE)$out[[1]]$S
DS2 <- subcrt("pyrrhotite_new", "cr2", P = 1, T = Ttr)$out[[1]]$S
DS298 <- DS1 + DStr - DS2
```
Put the values of *S*° at 298.15 into OBIGT, then calculate the changes of all thermodynamic properties of each polymorph between 298.15 K and `Ttr`.
```{r pyrrhotite_D1_D2, message = FALSE, results = "hide"}
mod.OBIGT("pyrrhotite_new", state = "cr", S = S1)
mod.OBIGT("pyrrhotite_new", state = "cr2", S = S1 + DS298)
D1 <- subcrt("pyrrhotite_new", "cr", P = 1, T = Ttr, use.polymorphs = FALSE)$out[[1]]
D2 <- subcrt("pyrrhotite_new", "cr2", P = 1, T = Ttr)$out[[1]]
```
It's a good idea to check that the entropy of transition is calculated correctly.
```{r pyrrhotite_check_S, results = "hide"}
stopifnot(all.equal(D2$S - D1$S, DStr))
```
Now we're ready to add up the contributions to Δ*G*°~*f*~ and Δ*H*°~*f*~ from the left, top, and right sides of the cycle.
This gives us the differences between the polymorphs at 298.15 K, which we use to make the final changes to the database.
```{r pyrrhotite_DG298_DH298, results = "hide", message = FALSE}
DG298 <- D1$G + DGtr - D2$G
DH298 <- D1$H + DHtr - D2$H
mod.OBIGT("pyrrhotite_new", state = "cr", G = G1, H = H1)
mod.OBIGT("pyrrhotite_new", state = "cr2", G = G1 + DG298, H = H1 + DH298)
```
It's a good idea to check that the values of `G`, `H`, and `S` at 25 °C for a given polymorph are consistent with each other.
Here we use `check.GHS()` to calculate the difference between the value given for `G` and the value calculated from `H` and `S`.
The difference of less than 1 `r E.units()`/mol can probably be attributed to small differences in the entropies of the elements used by @PMW87 and in CHNOSZ.
We still get a message that the database value of *C~p~*° at 25 °C for the high-temperature polymorph is NA; this is OK because the (extrapolated) value can be calculated from the heat capacity coefficients.
```{r pyrrhotite_info2, collapse = TRUE}
cr_parameters <- info(info("pyrrhotite_new", "cr"))
stopifnot(abs(check.GHS(cr_parameters)) < 1)
cr2_parameters <- info(info("pyrrhotite_new", "cr2"))
stopifnot(abs(check.GHS(cr2_parameters)) < 1)
```
For the curious, here are the parameter values:
```{r pyrrhotite_parameters}
cr_parameters
cr2_parameters
```
Finally, let's look at the thermodynamic properties of the newly added pyrrhotite as a function of temperature around `Ttr`.
Here, we use the feature of `subcrt()` that identifies the stable polymorph at each temperature.
Note that Δ*G*°~*f*~ is a continuous function -- visual confirmation that the parameters yield zero for `DGtr` -- but Δ*H*°~*f*~, *S*°, and *C~p~*° are discontinuous at the transition temperature.
<button id="B-pyrrhotite_T" onclick="ToggleDiv('pyrrhotite_T')">Show code</button>
<div id="D-pyrrhotite_T" style="display: none">
```{r pyrrhotite_T, eval = FALSE}
T <- seq(550, 650, 1)
sout <- subcrt("pyrrhotite_new", T = T, P = 1)$out[[1]]
par(mfrow = c(1, 4), mar = c(4, 4.2, 1, 1))
labels <- c(G = "DG0f", H = "DH0f", S = "S0", Cp = "Cp0")
for(property in c("G", "H", "S", "Cp")) {
plot(sout$T, sout[, property], col = sout$polymorph,
xlab = axis.label("T"), ylab = axis.label(labels[property])
)
abline(v = Ttr, lty = 3, col = 8)
if(property == "G")
legend("bottomleft", c("1", "2"), pch = 1, col = c(1, 2), title = "Polymorph")
}
# Restore default settings for the questions below
reset()
```
</div>
```{r pyrrhotite_T, echo = FALSE, message = FALSE, results = "hide", fig.width = 8, fig.height = 2.5, out.width = "100%", fig.align = "center", pngquant = pngquant}
```
For additional polymorphs, we could repeat the above procedure using polymorph 2 as the starting point to calculate `G`, `H`, and `S` of polymorph 3, and so on.
*Added on 2023-06-23.*
## How can I make a diagram with the trisulfur radical ion (`r S3minus`)?
A `r logfO2`--pH plot for aqueous sulfur species including `r S3minus` was first presented by @PD11.
Later, @PD15 reported parameters in the revised HKF equations of state for `r S3minus`, which are available in OBIGT.
```{r trisulfur, eval = FALSE, echo = FALSE}
par(mfrow = c(1, 3))
## BLOCK 1
T <- 350
P <- 5000
res <- 200
## BLOCK 2
wt_percent_S <- 10
wt_permil_S <- wt_percent_S * 10
molar_mass_S <- mass("S") # 32.06
moles_S <- wt_permil_S / molar_mass_S
grams_H2O <- 1000 - wt_permil_S
molality_S <- 1000 * moles_S / grams_H2O
logm_S <- log10(molality_S)
## BLOCK 3
basis(c("Ni", "SiO2", "Fe2O3", "H2S", "H2O", "oxygen", "H+"))
species(c("H2S", "HS-", "SO2", "HSO4-", "SO4-2", "S3-"))
a <- affinity(pH = c(2, 10, res), O2 = c(-34, -22, res), T = T, P = P)
e <- equilibrate(a, loga.balance = logm_S)
diagram(e)
## BLOCK 4
mod.buffer("NNO", c("nickel", "bunsenite"), state = "cr", logact = 0)
for(buffer in c("HM", "QFM", "NNO")) {
basis("O2", buffer)
logfO2_ <- affinity(return.buffer = TRUE, T = T, P = P)$O2
abline(h = logfO2_, lty = 3, col = 2)
text(8.5, logfO2_, buffer, adj = c(0, 0), col = 2, cex = 0.9)
}
## BLOCK 5
pH <- subcrt(c("H2O", "H+", "OH-"), c(-1, 1, 1), T = T, P = P)$out$logK / -2
abline(v = pH, lty = 2, col = 4)
## BLOCK 6
lTP <- describe.property(c("T", "P"), c(T, P))
lS <- paste(wt_percent_S, "wt% S(aq)")
ltext <- c(lTP, lS)
legend("topright", ltext, bty = "n", bg = "transparent")
title(quote("Parameters for"~S[3]^"-"~"from Pokrovski and Dubessy (2015)"), xpd = NA)
######## Plot 2: Modify Gibbs energy
oldG <- info(info("S3-"))$G
newG <- oldG - 12548
mod.OBIGT("S3-", G = newG)
a <- affinity(pH = c(2, 10, res), O2 = c(-34, -22, res), T = T, P = P)
e <- equilibrate(a, loga.balance = logm_S)
diagram(e)
legend("topright", ltext, bty = "n", bg = "transparent")
title(quote("Modified"~log*italic(K)~"after Pokrovski and Dubrovinsky (2011)"), xpd = NA)
OBIGT()
######## Plot 3: Do it with DEW
T <- 700
P <- 10000 # 10000 bar = 1 GPa
oldwat <- water("DEW")
add.OBIGT("DEW")
info(species()$ispecies)
a <- affinity(pH = c(2, 10, res), O2 = c(-18, -10, res), T = T, P = P)
e <- equilibrate(a, loga.balance = logm_S)
diagram(e)
lTP <- describe.property(c("T", "P"), c(T, P))
ltext <- c(lTP, lS)
legend("topright", ltext, bty = "n", bg = "transparent")
title(quote("Deep Earth Water (DEW)"~"model"))
water(oldwat)
OBIGT()
```
The blocks of code are commented here:
1. Set temperature, pressure, and resolution.
2. Calculate molality of S from given weight percent [this is rather tedious and could be condensed to fewer lines of code].
- Define the given weight percent (10 wt% S).
- Calculate weight permil S.
- Divide by molar mass to calculate moles of S in 1 kg of solution.
- Calculate grams of `r H2O` in 1 kg of solution.
- Calculate molality (moles of S per kg of `r H2O`, not kg of solution).
- Calculate decimal logarithm of molality.
3. Define the basis species and formed species, calculate affinity, equilibrate activities, and make the diagram.
- If we didn't want to plot the buffer lines, we could just use `basis(c("H2S", "H2O", "oxygen", "H+"))`.
- Basis species with Fe, Si, and Ni are needed for the HM, QFM, and NNO buffers.
- Note that "oxygen" matches `r O2`(gas), not `r O2`(aq), so the variable on the diagram is `r logfO2`.
4. Define Ni-NiO (NNO) buffer and plot buffer lines for HM, QFM, and NNO.
- QFM (quartz-fayalite-magnetite) is also known as FMQ.
5. Calculate and plot pH of neutrality for water.
6. Add a legend and title.
<button id="B-trisulfur-1" onclick="ToggleDiv('trisulfur-1')">Show code</button>
<div id="D-trisulfur-1" style="display: none">
```{r trisulfur, eval = FALSE, echo = 3:43}
```
</div>
### Why does the published diagram have a much larger stability field for `r S3minus`?
Let's calculate `r logK` for the reaction 2 `r H2S`(aq) + `r SO4__` + `r Hplus` = `r S3minus` + 0.75 `r O2`(gas) + 2.5 `r H2O`.
```{r trisulfur_logK, message = FALSE, echo = 1:3}
species <- c("H2S", "SO4-2", "H+", "S3-", "oxygen", "H2O")
coeffs <- c(-2, -1, -1, 1, 0.75, 2.5)
(calclogK <- subcrt(species, coeffs, T = seq(300, 450, 50), P = 5000)$out$logK)
fcalclogK <- formatC(calclogK, format = "f", digits = 1)
reflogK <- -9.6
dlogK <- calclogK[2] - reflogK
# Put in a test so that we don't get surprised by
# future database updates or changes to this vignette
stopifnot(round(dlogK, 4) == -4.4132)
```
By using the thermodynamic parameters for `r S3minus` in OBIGT that are taken from @PD15, `r logK` is calculated to be `r paste(paste(fcalclogK[1:3], collapse = ", "), fcalclogK[4], sep = ", and ")` at 300, 350, 400, and 450 °C and 5000 bar.
In contrast, ref. 22 of @PD11 lists `r reflogK` for `r logK` at 350 °C; this is `r round(-dlogK, 1)` log units higher than the calculated value of `r fcalclogK[2]`.
This corresponds to a difference of Gibbs energy of -2.303 * 1.9872 * (350 + 273.15) * `r round(-dlogK, 1)` = `r formatC(-2.303 * 1.9872 * (350 + 273.15) * -dlogK, format = "f", digits = 0)` cal/mol.
In the code below, we use the difference of Gibbs energy to temporarily update the OBIGT entry for `r S3minus`.
Then, we make a new diagram that is more similar to that from @PD11.
Finally, we reset the OBIGT database so that the temporary parameters don't interfere with later calculations.
<button id="B-trisulfur-2" onclick="ToggleDiv('trisulfur-2')">Show code</button>
<div id="D-trisulfur-2" style="display: none">
```{r trisulfur, eval = FALSE, echo = 46:55}
```
</div>
### Can I make the diagram using the Deep Earth Water (DEW) model?
Yes! Just set a new temperature and pressure and activate the DEW water model and load the DEW aqueous species.
You can also use `r info_` to see which species are affected by loading the DEW parameters; it turns out that `r SO4__` isn't.
Then, use similar commands as above to make the diagram.
At the end, reset the water model and OBIGT database.
<button id="B-trisulfur-DEW" onclick="ToggleDiv('trisulfur-DEW')">Show code</button>
<div id="D-trisulfur-DEW" style="display: none">
```{r trisulfur_DEW, message = FALSE, echo = 8:22, collapse = TRUE, fig.keep = "none"}
# The first four lines are stand-ins to make this block runnable and get the right output from info();
# the diagram actually shown in the vignette is made using the 'trisulfur' block above
b <- basis("CHNOS+")
s <- species(c("H2S", "HS-", "SO2", "HSO4-", "SO4-2", "S3-"))
res <- 10
wt_percent_S <- logm_S <- 0
######## End of stand-in code ########
T <- 700
P <- 10000 # 10000 bar = 1 GPa
oldwat <- water("DEW")
add.OBIGT("DEW")
info(species()$ispecies)[, 1:8]
a <- affinity(pH = c(2, 10, res), O2 = c(-18, -10, res), T = T, P = P)
e <- equilibrate(a, loga.balance = logm_S)
diagram(e)
lTP <- describe.property(c("T", "P"), c(T, P))
lS <- paste(wt_percent_S, "wt% S(aq)")
ltext <- c(lTP, lS)
legend("topright", ltext, bty = "n", bg = "transparent")
title(quote("Deep Earth Water (DEW)"~"model"))
water(oldwat)
OBIGT()
```
</div>
Here are the three plots that we made:
```{r trisulfur, echo = FALSE, message = FALSE, results = "hide", fig.width = 10, fig.height = 3.33, out.width = "100%", out.extra='class="full-width"', pngquant = pngquant, cache = TRUE}
```
*Added on 2023-09-08.*
## In OBIGT, what is the meaning of `T` for solids, liquids, and gases?
The value in this column can be one of the following:
1. The temperature of transition to the next polymorph of a mineral;
2. For the highest-temperature (or only) polymorph, if `T` is positive, it is the phase stability limit (i.e., the temperature of melting or decomposition of a solid or vaporization of a liquid);
3. For the highest-temperature polymorph, if `T` is negative, the opposite (positive) value is the *T* limit for validity of the *C~p~* equation. (*New feature in development version of CHNOSZ*)
These cases are handled by `subcrt()` as follows.
The units of `T` in OBIGT are Kelvin, but `subcrt()` by default uses °C:
**1. For polymorphic transitions, the properties of specific polymorphs are returned:**
```{r pyrrhotite_polymorphs, collapse = TRUE}
subcrt("pyrrhotite", T = c(25, 150, 350), property = "G")$out
```
Note: In both SUPCRT92 and OBIGT, tin, sulfur, and selenium are listed as minerals with one or more polymorphic transitions, but the highest-temperature polymorph actually represents the liquid state.
Furthermore, quicksilver is listed as a mineral whose polymorphs actually correspond to the liquid and gaseous states.
**2. For a phase stability limit, Δ*G*° is set to NA above the temperature limit:**
```{r pyrite_limit}
subcrt("pyrite", T = seq(200, 1000, 200), P = 1)
```
This feature is intended to make it harder to obtain potentially unreliable results at temperatures where a mineral (or an organic solid or liquid) is not stable.
If you want the extrapolated Δ*G*° above the listed phase stability limit, then add `exceed.Ttr = TRUE` to the function call to `subcrt()`.
OBIGT has a non-exhaustive list of temperatures of melting, decomposition, or other phase change, some of which were taken from SUPCRT92 while others were taken from @RH95.
These minerals are listed below:
```{r mineral_Ttr, collapse = TRUE}
file <- system.file("extdata/OBIGT/inorganic_cr.csv", package = "CHNOSZ")
dat <- read.csv(file)
# Reverse rows so highest-T polymorph for each mineral is listed first
dat <- dat[nrow(dat):1, ]
# Remove low-T polymorphs
dat <- dat[!duplicated(dat$name), ]
# Remove minerals with no T limit for phase stability (+ve) or Cp equation (-ve)
dat <- dat[!is.na(dat$z.T), ]
# Keep minerals with phase stability limit
dat <- dat[dat$z.T > 0, ]
# Get names of minerals and put into original order
rev(dat$name)
```
<!--
Use square brackets to suppress parentheses around citation 20231115
https://stackoverflow.com/questions/64209134/r-markdown-suppress-parentheses-in-specific-citations
-->
OBIGT now uses the decomposition temperature of covellite [780.5 K from @RH95] in contrast to the previous Tmax from SUPCRT92 [1273 K, which is referenced to a \Cp equation described as "estimated" on p. 62 of @Kel60].
Selected organic solids and liquids have melting or vaporization temperatures listed as well.
However, no melting temperatures are listed for minerals that use the `Berman` model.
**3. For a *C~p~* equation limit, extrapolated values of Δ*G*° are shown and a warning is produced:**
```{r muscovite_limit, message = FALSE}
add.OBIGT("SUPCRT92")
subcrt("muscovite", T = 850, P = 4500)
reset()
```
The warning is similar to that produced by SUPCRT92 ("CAUTION: BEYOND T LIMIT OF CP COEFFS FOR A MINERAL OR GAS") at temperatures above maximum temperature of validity of the Maier-Kelley equation (Tmax).
Notably, SUPCRT92 outputs Δ*G*° and other standard thermodynamic properties at temperatures higher than Tmax despite the warning.
This is a new feature in CHNOSZ version 2.1.0.
In previous versions of CHNOSZ, values of Δ*G*° above the *C~p~* equation limit were set to NA without a warning, as with the phase stability limit described above.
**4. Finally, if `T` is NA or 0, then no upper temerature limit is imposed by `subcrt()`.**
*Added on 2023-11-15.*
## How can mineral pH buffers be plotted?
Unlike mineral redox buffers, the K-feldspar–muscovite–quartz (KMQ) and muscovite–kaolinite (MC) pH buffers are known as "sliding scale" buffers because they do not determine pH but rather the activity ratio of `r Kplus` to `r Hplus` [@HA05].
To add these buffers to a `r logfO2`–pH diagram in CHNOSZ, choose basis species that include Al<sup>+3</sup> (the least mobile element, which the reactions are balanced on), quartz (this is needed for the KMQ buffer), the mobile ions `r Kplus` and `r Hplus`, and the remaining elements in `r H2O` and `r O2`; `oxygen` denotes the gas in OBIGT.
The formation reactions for these minerals don't involve `r O2`, but it must be present so that the number of basis species equals the number of elements +1 (i.e. elements plus charge).
```{r KMQ_basis_species, message = FALSE}
basis(c("Al+3", "quartz", "K+", "H+", "H2O", "oxygen"))
species(c("kaolinite", "muscovite", "K-feldspar"))
```
We could go right ahead and make a `r logfO2`–pH diagram, but the implied assumption would be that the `r Kplus` activity is unity, which may not be valid.
Instead, we can obtain an independent estimate for `r Kplus` activity based on 1) the activity ratio of `r Naplus` to `r Kplus` for the reaction between albite and K-feldspar and 2) charge balance among `r Naplus`, `r Kplus`, and `r Clminus` for a given activity of the latter [@HC14].
Using the variables defined below, those conditions are expressed as `K_AK = m_Na / m_K` and `m_Na + m_K = m_Cl`, which combine to give `m_K = m_Cl / (K_AK + 1)`.
The reason for writing the equations with molality instead of activity is that ionic strength (`IS`) is provided in the arguments to `subcrt()`, so the function returns a value of `r logK` adjusted for ionic strength.
Furthermore, it is assumed that this is a chloride-dominated solution, so ionic strength is taken to be equal to the molality of `r Clminus`.
```{r KMQ_m_K, message = FALSE}
# Define temperature, pressure, and molality of Cl- (==IS)
T <- 150
P <- 500
IS <- m_Cl <- 1
# Calculate equilibrium constant for Ab-Kfs reaction, corrected for ionic strength
logK_AK <- subcrt(c("albite", "K+", "K-feldspar", "Na+"), c(-1, -1, 1, 1),
T = T, P = P, IS = IS)$out$logK
K_AK <- 10 ^ logK_AK
# Calculate molality of K+
(m_K <- m_Cl / (K_AK + 1))
```
This calculation gives a molality of `r Kplus` that is lower than unity and accordingly makes the buffers less acidic [@HC14].
Now we can apply the calculated molality of `r Kplus` to the basis species and add the buffer lines to the diagram.
The `IS` argument is also used for `affinity()` so that activities are replaced by molalities (that is, affinity is calculated with standard Gibbs energies adjusted for ionic strength; this has the same effect as calculating activity coefficients).
```{r KMQ_diagram, eval = FALSE, echo = 2:10}
par(mfrow = c(1, 2))
basis("K+", log10(m_K))
a <- affinity(pH = c(2, 10), O2 = c(-55, -38), T = T, P = P, IS = IS)
diagram(a, srt = 90)
lTP <- as.expression(c(lT(T), lP(P)))
legend("topleft", legend = lTP, bty = "n", inset = c(-0.05, 0), cex = 0.9)
ltxt <- c(quote("Unit molality of Cl"^"-"), "Quartz saturation")
legend("topright", legend = ltxt, bty = "n", cex = 0.9)
title("Mineral data from Berman (1988)\nand Sverjensky et al. (1991) (OBIGT default)",
font.main = 1, cex.main = 0.9)
add.OBIGT("SUPCRT92")
a <- affinity(pH = c(2, 10), O2 = c(-55, -38), T = T, P = P, IS = IS)
diagram(a, srt = 90)
title("Mineral data from Helgeson et al. (1978)\n(as used in SUPCRT92)",
font.main = 1, cex.main = 0.9)
OBIGT()
```
```{r KMQ_diagram, message = FALSE, fig.width = 8, fig.height = 4, out.width = "100%", results = "hide", echo = FALSE}
```
The gray area, which is automatically drawn by `diagram()`, is below the reducing stability limit of water; that is, this area is where the equilibrium fugacity of `r H2` exceeds unity.
NOTE: Although the muscovite–kaolinite (MC) buffer was mentioned by @HC14 in the context of "clay-rich but feldspar-free sediments", this example uses the feldspathic Ab–Kfs reaction for calculating `r Kplus` molality for both the KMQ and MC buffers.
A more appropriate reaction to constrain the Na/K ratio with the MC buffer may be that between paragonite and muscovite [e.g., @Yar05].
The diagram in Fig. 4 of @HC14 shows the buffer lines at somewhat higher pH values of ca. 5 and 6.
Removing `IS` from the code moves the lines to lower rather than higher pH (*not shown -- try it yourself!*), so the calculation of activity coefficients does not explain the differences.
One possible reason for these differences is the use of different thermodynamic data for the minerals.
The parameters for these minerals in the default OBIGT database come from @Ber88 and @SHD91.
```{r KMQ_refs, message = FALSE}
thermo.refs(species()$ispecies)
```
CHNOSZ doesn't implement the thermodynamic model for minerals from @HP98, which is one of the sources cited by @HC14.
If we use the thermodynamic parameters for minerals from @HDNB78 [these do not include the revisions for aluminosilicates described by @SHD91], we get the lines shown in the second plot above, representing a larger stability field for muscovite.
This moves the KMQ buffer closer to the value shown by @HC14, but the MC buffer further away, so this still doesn't explain why we get a different result.
```{r KMQ_diagram, eval = FALSE, echo = 11:15}
```
*Added on 2023-11-28.*
## References
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/doc/FAQ.Rmd
|
## ----CHNOSZ_reset, include=FALSE----------------------------------------------
library(CHNOSZ)
reset()
## ----setfile, include=FALSE---------------------------------------------------
# Assign the file name to a variable and print the file name and number of species
setfile <- function(csvfile, dat=NULL) {
# Assign csvfile outside this function
assign("csvfile", csvfile, parent.frame())
file <- system.file(paste0("extdata/OBIGT/", csvfile), package="CHNOSZ")
dat <- read.csv(file, as.is=TRUE)
## Exclude entries for high-T polymorphs
#dat <- dat[!dat$state %in% c("cr2", "cr3", "cr4", "cr5", "cr6", "cr7", "cr8", "cr9"), ]
# The state and class of substance (used as section header), followed by number of species
basename <- gsub(".csv", "", csvfile)
class <- strsplit(basename, "_")[[1]][1]
substr(class, 1, 1) <- toupper(substr(class, 1, 1))
state <- strsplit(basename, "_")[[1]][2]
if(identical(state, "aq")) state <- "Aqueous "
else if(identical(state, "cr")) state <- "Solid "
else if(identical(state, "gas")) state <- "Gas "
else if(identical(state, "liq")) state <- "Liquid "
else state <- "Optional "
paste0(state, class, " (", nrow(dat), " species)")
}
## ----filerefs, include=FALSE--------------------------------------------------
filerefs <- function(csvfile, dat=NULL, message=FALSE) {
# With dat, look for ref2 in dat
whichref <- "ref2"
# Without dat, look for ref1 in csvfile
if(is.null(dat)) {
file <- system.file(paste0("extdata/OBIGT/", csvfile), package="CHNOSZ")
dat <- read.csv(file, as.is=TRUE)
whichref <- "ref1"
}
## Exclude entries for high-T polymorphs
#dat <- dat[!dat$state %in% c("cr2", "cr3", "cr4", "cr5", "cr6", "cr7", "cr8", "cr9"), ]
# Count number of times each reference is used
tab <- table(dat[, whichref])
# In case there are not references (previously for H2O_aq.csv) we return the species here
if(length(tab)==0) return(paste(dat$name, dat$state))
# The reference keys
keys <- names(tab)
# Warn if any keys aren't in thermo()$ref$key
ikey <- match(keys, thermo()$ref$key)
ina <- is.na(ikey)
if(any(ina)) cat(paste("**WARNING: key(s)", paste(names(tab)[ina], collapse=" "), "not found in `thermo()$ref$key`**\n\n"))
# Put the table in chronological order, according to thermo()$ref
ikey <- order(match(keys, thermo()$ref$key))
tab <- tab[ikey]
keys <- keys[ikey]
xxx <- lapply(seq_along(tab), function(i){
thiskey <- keys[i]
# Read thermo()$ref$note
iref <- match(thiskey, thermo()$ref$key)
note <- thermo()$ref$note[iref]
# Show the note in italics
if(!identical(note, "")) note <- paste0(" *", note, "* ")
# Use bullets for ref2
if(whichref=="ref2") bullet <- "- " else bullet <- ""
# Convert key (e.g. LD12.2) to ref in OBIGT.bib (e.g. LD12)
thisref <- gsub("\\..*$", "", thiskey)
# Replace SLOP98 with slop98.dat, etc.
# (we don't actually cite them here to keep the year from showing -- it's annoying to see e.g. "slop98.dat (1998)")
citemark <- "@"
if(thisref=="SLOP16") { thisref <- "slop16.dat"; citemark <- "" }
if(thisref=="SLOP07") { thisref <- "slop07.dat"; citemark <- "" }
if(thisref=="SLOP98") { thisref <- "slop98.dat"; citemark <- "" }
if(thisref=="SPRONS92") { thisref <- "sprons92.dat"; citemark <- "" }
if(thisref=="OBIGT") { thisref <- paste0("OBIGT (", thermo()$ref$year[iref], ")"); citemark <- "" }
cat(bullet, citemark, thisref, " -- ", tab[i], note, "\n\n", sep="")
# Get ref2 if we're in the outer list
if(whichref!="ref2") filerefs(dat=dat[dat$ref1==names(tab)[i], ])
})
# Return all the species listed
paste(dat$name, dat$state)
}
## ----used, include=FALSE------------------------------------------------------
# Initialize the list of used species
used <- character()
# Initialize the list of used optional species
optused <- character()
## ----reflist, results="asis", echo=FALSE--------------------------------------
used <- c(used, filerefs(csvfile))
## ----reflist, results="asis", echo=FALSE--------------------------------------
used <- c(used, filerefs(csvfile))
## ----reflist, results="asis", echo=FALSE--------------------------------------
used <- c(used, filerefs(csvfile))
## ----reflist, results="asis", echo=FALSE--------------------------------------
used <- c(used, filerefs(csvfile))
## ----reflist, results="asis", echo=FALSE--------------------------------------
used <- c(used, filerefs(csvfile))
## ----reflist, results="asis", echo=FALSE--------------------------------------
used <- c(used, filerefs(csvfile))
## ----reflist, results="asis", echo=FALSE--------------------------------------
used <- c(used, filerefs(csvfile))
## ----reflist, results="asis", echo=FALSE--------------------------------------
used <- c(used, filerefs(csvfile))
## ----reflist, results="asis", echo=FALSE--------------------------------------
used <- c(used, filerefs(csvfile))
## ----optreflist, results="asis", echo=FALSE-----------------------------------
optused <- c(optused, filerefs(csvfile))
## ----optreflist, results="asis", echo=FALSE-----------------------------------
optused <- c(optused, filerefs(csvfile))
## ----optreflist, results="asis", echo=FALSE-----------------------------------
optused <- c(optused, filerefs(csvfile))
## ----optreflist, results="asis", echo=FALSE-----------------------------------
optused <- c(optused, filerefs(csvfile))
## ----optreflist, results="asis", echo=FALSE-----------------------------------
optused <- c(optused, filerefs(csvfile))
## ----optreflist, results="asis", echo=FALSE-----------------------------------
optused <- c(optused, filerefs(csvfile))
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/doc/OBIGT.R
|
---
title: "OBIGT thermodynamic database"
output:
html_vignette:
mathjax: null
vignette: >
%\VignetteIndexEntry{OBIGT thermodynamic database}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
bibliography: OBIGT.bib
# So that these appear in the bibliography
nocite: |
@SPRONS92, @SLOP98, @SLOP07, @SLOP16, @JOH92, @WP02, @CWM89, @PRPG97, @TH88, @Kul06, @Sho09, @HKF81
csl: elementa.csl
link-citations: true
---
<style>
/* https://css-tricks.com/hash-tag-links-padding/ */
a.anchor::before {
display: block;
content: " ";
margin-top: -220px;
height: 220px;
visibility: hidden;
pointer-events: none;
}
</style>
<script>
function ToggleDiv(ID) {
var D = document.getElementById("D-" + ID);
if (D.style.display === "none") {
// close all divs then open this one
CloseAllDivs();
OpenDiv(ID);
} else {
// close all divs
CloseAllDivs();
}
}
function OpenDiv(ID) {
// open the div
var D = document.getElementById("D-" + ID);
D.style.display = "block";
// style the button
var B = document.getElementById("B-" + ID);
var Btext = ID.split("-")[1];
B.innerHTML = "<b>" + Btext + "</b>";
B.style.color = "red";
}
function CloseDiv(ID) {
// close the div
var D = document.getElementById("D-" + ID);
D.style.display = "none";
// style the button
var B = document.getElementById("B-" + ID);
var Btext = ID.split("-")[1];
B.innerHTML = Btext;
B.style.color = "black";
}
function OpenAllDivs() {
OpenDiv("aqueous-H2O");
OpenDiv("aqueous-inorganic");
OpenDiv("aqueous-organic");
OpenDiv("solid-inorganic");
OpenDiv("solid-organic");
OpenDiv("solid-Berman");
OpenDiv("gas-inorganic");
OpenDiv("gas-organic");
OpenDiv("liquid-organic");
OpenDiv("optional-SUPCRT92");
OpenDiv("optional-SLOP98");
OpenDiv("optional-AD");
OpenDiv("optional-AS04");
OpenDiv("optional-DEW");
OpenDiv("optional-GEMSFIT");
// change the footer message
document.getElementById("footer").style.display = "none";
document.getElementById("all-open").style.display = "block";
}
function CloseAllDivs() {
CloseDiv("aqueous-H2O");
CloseDiv("aqueous-inorganic");
CloseDiv("aqueous-organic");
CloseDiv("solid-inorganic");
CloseDiv("solid-organic");
CloseDiv("solid-Berman");
CloseDiv("gas-inorganic");
CloseDiv("gas-organic");
CloseDiv("liquid-organic");
CloseDiv("optional-SUPCRT92");
CloseDiv("optional-SLOP98");
CloseDiv("optional-AD");
CloseDiv("optional-AS04");
CloseDiv("optional-DEW");
CloseDiv("optional-GEMSFIT");
// change the footer message
document.getElementById("footer").style.display = "block";
document.getElementById("all-open").style.display = "none";
}
</script>
```{r CHNOSZ_reset, include=FALSE}
library(CHNOSZ)
reset()
```
```{r setfile, include=FALSE}
# Assign the file name to a variable and print the file name and number of species
setfile <- function(csvfile, dat=NULL) {
# Assign csvfile outside this function
assign("csvfile", csvfile, parent.frame())
file <- system.file(paste0("extdata/OBIGT/", csvfile), package="CHNOSZ")
dat <- read.csv(file, as.is=TRUE)
## Exclude entries for high-T polymorphs
#dat <- dat[!dat$state %in% c("cr2", "cr3", "cr4", "cr5", "cr6", "cr7", "cr8", "cr9"), ]
# The state and class of substance (used as section header), followed by number of species
basename <- gsub(".csv", "", csvfile)
class <- strsplit(basename, "_")[[1]][1]
substr(class, 1, 1) <- toupper(substr(class, 1, 1))
state <- strsplit(basename, "_")[[1]][2]
if(identical(state, "aq")) state <- "Aqueous "
else if(identical(state, "cr")) state <- "Solid "
else if(identical(state, "gas")) state <- "Gas "
else if(identical(state, "liq")) state <- "Liquid "
else state <- "Optional "
paste0(state, class, " (", nrow(dat), " species)")
}
```
```{r filerefs, include=FALSE}
filerefs <- function(csvfile, dat=NULL, message=FALSE) {
# With dat, look for ref2 in dat
whichref <- "ref2"
# Without dat, look for ref1 in csvfile
if(is.null(dat)) {
file <- system.file(paste0("extdata/OBIGT/", csvfile), package="CHNOSZ")
dat <- read.csv(file, as.is=TRUE)
whichref <- "ref1"
}
## Exclude entries for high-T polymorphs
#dat <- dat[!dat$state %in% c("cr2", "cr3", "cr4", "cr5", "cr6", "cr7", "cr8", "cr9"), ]
# Count number of times each reference is used
tab <- table(dat[, whichref])
# In case there are not references (previously for H2O_aq.csv) we return the species here
if(length(tab)==0) return(paste(dat$name, dat$state))
# The reference keys
keys <- names(tab)
# Warn if any keys aren't in thermo()$ref$key
ikey <- match(keys, thermo()$ref$key)
ina <- is.na(ikey)
if(any(ina)) cat(paste("**WARNING: key(s)", paste(names(tab)[ina], collapse=" "), "not found in `thermo()$ref$key`**\n\n"))
# Put the table in chronological order, according to thermo()$ref
ikey <- order(match(keys, thermo()$ref$key))
tab <- tab[ikey]
keys <- keys[ikey]
xxx <- lapply(seq_along(tab), function(i){
thiskey <- keys[i]
# Read thermo()$ref$note
iref <- match(thiskey, thermo()$ref$key)
note <- thermo()$ref$note[iref]
# Show the note in italics
if(!identical(note, "")) note <- paste0(" *", note, "* ")
# Use bullets for ref2
if(whichref=="ref2") bullet <- "- " else bullet <- ""
# Convert key (e.g. LD12.2) to ref in OBIGT.bib (e.g. LD12)
thisref <- gsub("\\..*$", "", thiskey)
# Replace SLOP98 with slop98.dat, etc.
# (we don't actually cite them here to keep the year from showing -- it's annoying to see e.g. "slop98.dat (1998)")
citemark <- "@"
if(thisref=="SLOP16") { thisref <- "slop16.dat"; citemark <- "" }
if(thisref=="SLOP07") { thisref <- "slop07.dat"; citemark <- "" }
if(thisref=="SLOP98") { thisref <- "slop98.dat"; citemark <- "" }
if(thisref=="SPRONS92") { thisref <- "sprons92.dat"; citemark <- "" }
if(thisref=="OBIGT") { thisref <- paste0("OBIGT (", thermo()$ref$year[iref], ")"); citemark <- "" }
cat(bullet, citemark, thisref, " -- ", tab[i], note, "\n\n", sep="")
# Get ref2 if we're in the outer list
if(whichref!="ref2") filerefs(dat=dat[dat$ref1==names(tab)[i], ])
})
# Return all the species listed
paste(dat$name, dat$state)
}
```
```{r used, include=FALSE}
# Initialize the list of used species
used <- character()
# Initialize the list of used optional species
optused <- character()
```
This vignette, produced on `r Sys.Date()`, lists the references for thermodynamic data in the OBIGT database in CHNOSZ version `r sessionInfo()$otherPkgs$CHNOSZ$Version`.
Except for Optional Data, all data are present in the default database, which is loaded when the package is attached, or by running `reset()` or `OBIGT()`.
Each section below corresponds to one of the CSV data files in the `extdata/OBIGT` package directory.
Clicking on a button opens that section, which contains a list of primary references (from column `ref1` in the file) in chronological order.
Any secondary references (`ref2`) are listed with bullet points under the primary reference.
Each citation is followed by the number of species, and a note taken from the file `extdata/OBIGT/refs.csv`.
Additional comments (from this vignette) are present for some sections.
Abbreviations: T (temperature), P (pressure), GHS (standard Gibbs energy, enthalpy, entropy), Cp (heat capacity), V (volume), HKF (<abbr title="Tanger and Helgeson, 1988">revised</abbr> <abbr title="Helgeson et al., 1981">Helgeson-Kirkham-Flowers</abbr> equations).
<!-- All buttons at top -->
### Aqueous Species <button id="B-aqueous-H2O" onclick='ToggleDiv("aqueous-H2O")'>H2O</button> <button id="B-aqueous-inorganic" onclick='ToggleDiv("aqueous-inorganic")'>Inorganic</button> <button id="B-aqueous-organic" onclick='ToggleDiv("aqueous-organic")'>Organic</button>
### Solids <button id="B-solid-inorganic" onclick='ToggleDiv("solid-inorganic")'>Inorganic</button> <button id="B-solid-organic" onclick='ToggleDiv("solid-organic")'>Organic</button> <button id="B-solid-Berman" onclick='ToggleDiv("solid-Berman")'>Berman</button>
### Gases <button id="B-gas-inorganic" onclick='ToggleDiv("gas-inorganic")'>Inorganic</button> <button id="B-gas-organic" onclick='ToggleDiv("gas-organic")'>Organic</button> Liquids <button id="B-liquid-organic" onclick='ToggleDiv("liquid-organic")'>Organic</button>
### Optional Data <button id="B-optional-SUPCRT92" onclick='ToggleDiv("optional-SUPCRT92")'>SUPCRT92</button> <button id="B-optional-SLOP98" onclick='ToggleDiv("optional-SLOP98")'>SLOP98</button> <button id="B-optional-AD" onclick='ToggleDiv("optional-AD")'>AD</button> <button id="B-optional-AS04" onclick='ToggleDiv("optional-AS04")'>AS04</button> <button id="B-optional-DEW" onclick='ToggleDiv("optional-DEW")'>DEW</button> <button id="B-optional-GEMSFIT" onclick='ToggleDiv("optional-GEMSFIT")'>GEMSFIT</button>
<!-- Normal or "all open" footer message -->
<div id="footer" style="display: block">
*Press a button above to show the citations in that data file.*
*Or, <a href = "#showall" onclick='OpenAllDivs()'>click here</a> to show all citations.*
</div>
<div id="all-open" style="display: none">
*Showing citations in all data files.*
*Press any button above to hide them.*
</div>
<!-- Aqueous species divs -->
<div id="D-aqueous-H2O" style="display: none">
## <a id="aqueous-H2O" class="anchor"></a> `r setfile("H2O_aq.csv")`
```{r reflist, results="asis", echo=FALSE}
used <- c(used, filerefs(csvfile))
```
This file contains H<sub>2</sub>O, *e*<sup>-</sup>, and H<sup>+</sup>.
The properties of H<sub>2</sub>O are listed as NA; CHNOSZ calculates its properties using a Fortran subroutine taken from SUPRCT92 ([Johnson et al., 1992](https://doi.org/10.1016/0098-3004(92)90029-Q)) (default) or using the IAPWS-95 equations ([Wagner and Pruß, 2002](https://doi.org/10.1063/1.1461829)) or the Deep Earth Water (DEW) model ([Sverjensky et al., 2014](https://doi.org/10.1016/j.gca.2013.12.019)).
By convention, the standard Gibbs energy of formation, entropy, and heat capacity of the aqueous proton (H<sup>+</sup>) are 0 at all *T* and *P* ([e.g. Cox et al., 1989](https://www.worldcat.org/oclc/18559968)).
The formation reaction of the proton can be expressed as ½H<sub>2,(*g*)</sub> + Z = H<sup>+</sup>, where Z is the "element" of positive charge.
Because the conventional standard Gibbs energy of this reaction is 0 at all *T*, the standard entropy of the reaction is also constrained to be zero (cf. Puigdomenech et al., 1997).
Therefore, the "element" of positive charge (Z) has zero thermodynamic properties except for an entropy, *S*°<sub>*T*<sub>r</sub></sub>, that is negative one-half that of H<sub>2,(*g*)</sub>.
The standard entropy of the aqueous electron, which is a solely a pseudospecies defined by *e*<sup>-</sup> = -Z, is opposite that of Z.
Likewise, [GEM-Selektor](http://gems.web.psi.ch/) defines "independent components" to be stoichiometric units usually consisting of elements and charge; the latter, [which is named Zz](http://gems.web.psi.ch/tests/TestNaCl-dep.html) and has a standard molal entropy of -65.34 J/mol/K and heat capacity of -14.418 J/mol/K (negative one-half those of gaseous hydrogen), is negated in the formula of the fictive "aqueous electron" ([Kulik, 2006](https://doi.org/10.1016/j.chemgeo.2005.08.014)).
Despite these considerations, the final column of the thermodynamic database (`thermo()$OBIGT`) lists a charge of "0" for both the aqueous proton and electron.
Data in this this column are used in CHNOSZ only to specify the charge that is input to the "*g*-function" ([Tanger and Helgeson, 1988](https://doi.org/10.2475/ajs.288.1.19); [Shock and Helgeson, 1988](https://doi.org/10.1016/0016-7037(88)90181-0)).
Setting it to zero prevents activation of the *g*-function, which would result in non-zero contributions to thermodynamic properties, conflicting with the conventions mentioned above.
All other calculations in CHNOSZ obtain the elemental makeup, including the correct charge for the species, by parsing the chemical formulas stored in the database.
</div>
<div id="D-aqueous-inorganic" style="display: none">
## <a id="aqueous-inorganic" class="anchor"></a> `r setfile("inorganic_aq.csv")`
```{r reflist, results="asis", echo=FALSE}
```
</div>
<div id="D-aqueous-organic" style="display: none">
## <a id="aqueous-organic" class="anchor"></a> `r setfile("organic_aq.csv")`
Charged amino acid sidechain groups have a Z parameter that is tabulated as zero; their chemical formulas indicate the correct charge.
Non-zero values of Z would yield derivatives of the omega parameter (ω) in the revised HKF equations of state for the cations and anions *that are not opposites of each other*.
This would be incompatible with group additivity of cations and anions to give a neutral species, for which the derivatives of ω are taken to be zero (cf. [Dick et al., 2006](https://doi.org/10.5194/bg-3-311-2006)).
```{r reflist, results="asis", echo=FALSE}
```
</div>
<!-- Solid species divs -->
<div id="D-solid-inorganic" style="display: none">
## <a id="solid-inorganic" class="anchor"></a> `r setfile("inorganic_cr.csv")`
Chamosite,7A and witherite were present in sprons92.dat but not in slop98.dat or later files, and are not included in CHNOSZ.
The source of parameters used here for goethite is different from that in the slop files ([Shock, 2009](https://doi.org/10.2113/gsecongeo.104.8.1235)).
```{r reflist, results="asis", echo=FALSE}
```
</div>
<div id="D-solid-organic" style="display: none">
## <a id="solid-organic" class="anchor"></a> `r setfile("organic_cr.csv")`
```{r reflist, results="asis", echo=FALSE}
```
</div>
<div id="D-solid-Berman" style="display: none">
## <a id="solid-Berman" class="anchor"></a> `r setfile("Berman_cr.csv")`
This file gives the identifiying information for minerals whose properties are calculated using the formulation of [Berman (1988)](https://doi.org/10.1093/petrology/29.2.445).
Thermodynamic properties for these minerals are listed as NA in `thermo()$OBIGT`; the actual data are stored separately, as CSV files in `extdata/Berman/*.csv`.
```{r reflist, results="asis", echo=FALSE}
```
</div>
<!-- Gas species divs -->
<div id="D-gas-inorganic" style="display: none">
## <a id="gas-inorganic" class="anchor"></a> `r setfile("inorganic_gas.csv")`
```{r reflist, results="asis", echo=FALSE}
```
</div>
<div id="D-gas-organic" style="display: none">
## <a id="gas-organic" class="anchor"></a> `r setfile("organic_gas.csv")`
```{r reflist, results="asis", echo=FALSE}
```
</div>
<!-- Liquid species divs -->
<div id="D-liquid-organic" style="display: none">
## <a id="liquid-organic" class="anchor"></a> `r setfile("organic_liq.csv")`
```{r reflist, results="asis", echo=FALSE}
```
</div>
<!-- Optional species divs -->
<div id="D-optional-SUPCRT92" style="display: none">
## <a id="optional-SUPCRT92" class="anchor"></a> `r setfile("SUPCRT92.csv")`
These minerals and aqueous species, taken from the SUPCRT92 database, were present in earlier versions of CHNOSZ but have since been superseded by @Ber88 (minerals) and @NA03 (H<sub>2</sub>AsO<sub>3</sub><sup>-</sup>).
The thermodynamic properties and parameters are kept here as optional data for reproducing published calculations and making comparisons with newer data.
The minerals here include all of the silicates and Al-bearing minerals from @HDNB78, as well as calcite, dolomite, hematite, and magnetite.
Use `add.OBIGT("SUPCRT92")` to load the data.
**NOTE:** Other minerals from SUPCRT92, including native elements, sulfides, halides, sulfates, and selected carbonates and oxides that do not duplicate those in the Berman dataset, are still present in the default database (**inorganic_cr.csv**).
```{r optreflist, results="asis", echo=FALSE}
```
</div>
<div id="D-optional-SLOP98" style="display: none">
## <a id="optional-SLOP98" class="anchor"></a> `r setfile("SLOP98.csv")`
These species, which were taken from or are linked to slop98.dat (or later versions) and were present in earlier versions of CHNOSZ, have been replaced by or are incompatible with species currently in the default database, including aqueous Al species [@TS01], As species [@NA03], Au, Ag, and Cu species [@AZ01; @AZ10], Pd species [@TBZ+13], Zn species [@AT14], Pt species [@TBB15], Nb species [@AKK+20], and CoCl<sub>2</sub><sup>+</sup> [@LBT+11].
This file also contains aqueous transuranic actinide complexes, for which estimated thermodynamic properties have been reported, but no entropies of the corresponding elements at 298.15 K are available to check the self-consistency of the GHS values for the complexes.
Use `add.OBIGT("SLOP98")` to load the data.
**NOTE:** Many other species found in slop98.dat and later versions are still present in the default database.
```{r optreflist, results="asis", echo=FALSE}
```
</div>
<div id="D-optional-AD" style="display: none">
## <a id="optional-AD" class="anchor"></a> `r setfile("AD.csv")`
This file has parameters for aqueous nonelectrolytes in the Akinfiev-Diamond model [@AD03].
Use `add.OBIGT("AD")` to load the data; see `demo(AD)` for an example.
```{r optreflist, results="asis", echo=FALSE}
```
</div>
<div id="D-optional-AS04" style="display: none">
## <a id="optional-AS04" class="anchor"></a> `r setfile("AS04.csv")`
This file has data for aqueous SiO<sub>2</sub> from @AS04 and a HSiO<sub>3</sub><sup>-</sup> modified to be consistent with the SiO<sub>2</sub> here.
This file also has H<sub>4</sub>SiO<sub>4</sub> from an earlier publication [@Ste01] that is roughly consistent with the SiO<sub>2</sub> here.
Use `add.OBIGT("AS04")` to load the data; see `demo(aluminum)` for an example.
```{r optreflist, results="asis", echo=FALSE}
```
</div>
<div id="D-optional-DEW" style="display: none">
## <a id="optional-DEW" class="anchor"></a> `r setfile("DEW.csv")`
The Deep Earth Water (DEW) model extends the applicability of the revised HKF equations of state to 60 kbar.
Accuracy of the thermodynamic calculations at these conditions is improved by revised correlations for the <i>a</i><sub>1</sub> HKF parameter, as described by [Sverjensky et al. (2014)](https://doi.org/10.1016/j.gca.2013.12.019).
The thermodynamic parameters for species were taken from the May 2017 and January 2019 versions of the DEW spreadsheet.
The following species are present in the spreadsheet, but are not used here because the parameters are unchanged from the default database in CHNOSZ: B(OH)<sub>3</sub>, Br<sup>-</sup>, Ca<sup>+2</sup>, Cl<sup>-</sup>, Cs<sup>+</sup>, F<sup>-</sup>, H<sup>+</sup>, H<sub>2</sub>, He, I<sup>-</sup>, K<sup>+</sup>, Kr, Li<sup>+</sup>, Mg<sup>+2</sup>, Na<sup>+</sup>, Ne, O<sub>2</sub>, Rb<sup>+</sup>, Rn, SO<sub>4</sub><sup>-2</sup>.
Besides using `add.OBIGT("DEW")` to load these data, you should also run `water("DEW")` to activate the DEW equations in CHNOSZ.
See `demo(DEW)` for some examples.
Most of the comments below were transcribed from the DEW spreadsheet. (Comments in parentheses were added by JMD.)
```{r optreflist, results="asis", echo=FALSE}
optused <- c(optused, filerefs(csvfile))
```
</div>
<div id="D-optional-GEMSFIT" style="display: none">
## <a id="optional-GEMSFIT" class="anchor"></a> `r setfile("GEMSFIT.csv")`
[Miron et al. (2016)](https://doi.org/10.1016/j.gca.2016.04.026) and [Miron et al. (2017)](https://doi.org/10.2475/07.2017.01) described an internally consistent thermodynamic dataset for aqueous species in the system Ca-Mg-Na-K-Al-Si-O-H-C-Cl that was obtained by using the [GEMSFIT](https://doi.org/10.1016/j.apgeochem.2014.10.013) package.
Use `add.OBIGT("GEMSFIT")` to load the data.
```{r optreflist, results="asis", echo=FALSE}
```
</div>
<hr>
<b>Total count of species</b>: References were found for `r length(used)` of `r nrow(thermo()$OBIGT)` species in the default OBIGT database and `r length(optused)` optional species.
# References
<script>
// Open button corresponding to hash target in URL 20200703
// Keep this at the end of the body:
// https://stackoverflow.com/questions/9899372/pure-javascript-equivalent-of-jquerys-ready-how-to-call-a-function-when-t
var url = window.location.href;
if (url.indexOf("#") > 0) {
var activeButton = url.substring(url.indexOf("#") + 1);
if(activeButton == "showall") {
OpenAllDivs();
// hide the footer message
document.getElementById("footer").style.display = "none";
} else {
OpenDiv(activeButton);
}
// https://stackoverflow.com/questions/3163615/how-to-scroll-html-page-to-given-anchor
location.hash = "#" + activeButton;
}
</script>
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/doc/OBIGT.Rmd
|
## ----options, include=FALSE---------------------------------------------------
options(width = 80)
options(digits = 6)
## ----HTML, include=FALSE------------------------------------------------------
## Some frequently used HTML expressions
logfO2 <- "log<i>f</i><sub>O<sub>2</sub></sub>"
# Use lowercase here because these tend to be variable names in the examples
zc <- "<i>Z</i><sub>C</sub>"
o2 <- "O<sub>2</sub>"
h2o <- "H<sub>2</sub>O"
sio2 <- "SiO<sub>2</sub>"
ch4 <- "CH<sub>4</sub>"
## ----setup, include=FALSE-----------------------------------------------------
library(knitr)
## From "Tufte Handout" example dated 2016-12-27
# Invalidate cache when the tufte version changes
opts_chunk$set(tidy = FALSE, cache.extra = packageVersion('tufte'))
options(htmltools.dir.version = FALSE)
## Adjust plot margins
## First one from https://yihui.name/knitr/hooks/
knit_hooks$set(small.mar = function(before, options, envir) {
if (before) par(mar = c(4.2, 4.2, .1, .1)) # smaller margin on top and right
})
knit_hooks$set(tiny.mar = function(before, options, envir) {
if (before) par(mar = c(.1, .1, .1, .1)) # tiny margin all around
})
knit_hooks$set(smallish.mar = function(before, options, envir) {
if (before) par(mar = c(4.2, 4.2, 0.9, 0.9)) # smallish margins on top and right
})
## Use pngquant to optimize PNG images
knit_hooks$set(pngquant = hook_pngquant)
pngquant <- "--speed=1 --quality=0-25"
# pngquant isn't available on R-Forge ...
if (!nzchar(Sys.which("pngquant"))) pngquant <- NULL
# Set dpi 20231129
knitr::opts_chunk$set(
dpi = if(nzchar(Sys.getenv("CHNOSZ_BUILD_LARGE_VIGNETTES"))) 72 else 50
)
hidpi = if(nzchar(Sys.getenv("CHNOSZ_BUILD_LARGE_VIGNETTES"))) 100 else 50
## http://stackoverflow.com/questions/23852753/knitr-with-gridsvg
## Set up a chunk hook for manually saved plots.
knit_hooks$set(custom.plot = hook_plot_custom)
## Hook to change <img /> to <embed /> -- required for interactive SVG
hook_plot <- knit_hooks$get("plot")
knit_hooks$set(plot = function(x, options) {
x <- hook_plot(x, options)
if (!is.null(options$embed.tag) && options$embed.tag) x <- gsub("<img ", "<embed ", x)
x
})
## http://stackoverflow.com/questions/30530008/hook-to-time-knitr-chunks
now = Sys.time()
knit_hooks$set(timeit = function(before) {
if (before) { now <<- Sys.time() }
else {
paste("%", sprintf("Chunk rendering time: %s seconds.\n", round(Sys.time() - now, digits = 3)))
}
})
timeit <- NULL
## Colorize messages 20171031
## Adapted from https://gist.github.com/yihui/2629886#file-knitr-color-msg-rnw
color_block = function(color) {
function(x, options) sprintf('<pre style="color:%s">%s</pre>', color, x)
}
knit_hooks$set(warning = color_block('magenta'), error = color_block('red'), message = color_block('blue'))
## ----install_CHNOSZ, eval=FALSE-----------------------------------------------
# install.packages("CHNOSZ")
## ----library_CHNOSZ-----------------------------------------------------------
library(CHNOSZ)
## ----reset--------------------------------------------------------------------
reset()
## ----pseudocode, eval=FALSE---------------------------------------------------
# basis(...)
# species(...)
# a <- affinity(...)
# e <- equilibrate(a) ## optional
# diagram(e) ## or diagram(a)
# reset() ## clear settings for next calculation
## ----info_CH4-----------------------------------------------------------------
info("CH4")
## ----info_CH4_gas-------------------------------------------------------------
info("CH4", "gas")
## ----info_names_gas-----------------------------------------------------------
info("methane")
info("oxygen")
info("carbon dioxide")
## ----info_S_S2----------------------------------------------------------------
info("S")
info("S2")
## ----iCH4, message=FALSE------------------------------------------------------
iCH4 <- info("CH4")
info(iCH4)
## ----info_info_water----------------------------------------------------------
info(info("water"))
## ----width180, include=FALSE------------------------------------------------------------------------------------------------------------------------------------------------------
options(width = 180)
## ----info_acid--------------------------------------------------------------------------------------------------------------------------------------------------------------------
info("acid")
## ----width80, include=FALSE---------------------------------------------------
options(width = 80)
## ----info_ribose--------------------------------------------------------------
info(" ribose")
## ----info_CH4_formula, message=FALSE------------------------------------------
info(iCH4)$formula
## ----makeup_iCH4--------------------------------------------------------------
makeup(iCH4)
as.chemical.formula(makeup(iCH4))
## ----ZC_iCH4, message=FALSE---------------------------------------------------
ZC(iCH4)
ZC(info(iCH4)$formula)
ZC(makeup(iCH4))
## ----subcrt_water-------------------------------------------------------------
subcrt("water")
## ----subcrt_water_grid--------------------------------------------------------
subcrt("water", T = c(400, 500, 600), P = c(200, 400, 600), grid = "P")$out$water
## ----subcrt_water_plot, fig.margin=TRUE, fig.width=4, fig.height=4, small.mar=TRUE, out.width="100%", echo=FALSE, message=FALSE, fig.cap="Isothermal contours of density (g cm<sup>-3</sup>) and pressure (bar) of water.", cache=TRUE, pngquant=pngquant, timeit=timeit----
sres <- subcrt("water", T=seq(0,1000,100), P=c(NA, seq(1,500,1)), grid="T")
water <- sres$out$water
plot(water$P, water$rho, type = "l")
## ----subcrt_water_plot, eval=FALSE--------------------------------------------
# sres <- subcrt("water", T=seq(0,1000,100), P=c(NA, seq(1,500,1)), grid="T")
# water <- sres$out$water
# plot(water$P, water$rho, type = "l")
## ----units_CH4----------------------------------------------------------------
T.units("K")
P.units("MPa")
subcrt("CH4", T = 298.15, P = 0.1)$out$CH4$G
E.units("cal")
subcrt("CH4", T = 298.15, P = 0.1)$out$CH4$G
## ----convert_G, message=FALSE-------------------------------------------------
(CH4dat <- info(info("CH4")))
convert(CH4dat$G, "J")
## ----reset--------------------------------------------------------------------
reset()
## ----subcrt_CO2---------------------------------------------------------------
subcrt(c("CO2", "CO2"), c("gas", "aq"), c(-1, 1), T = seq(0, 250, 50))
## ----CO2_logK, echo=FALSE, message=FALSE--------------------------------------
T <- seq(0, 350, 10)
CO2 <- subcrt(c("CO2", "CO2"), c("gas", "aq"), c(-1, 1), T = T)$out$logK
CO <- subcrt(c("CO", "CO"), c("gas", "aq"), c(-1, 1), T = T)$out$logK
CH4 <- subcrt(c("CH4", "CH4"), c("gas", "aq"), c(-1, 1), T = T)$out$logK
logK <- data.frame(T, CO2, CO, CH4)
## ----CO2_plot, fig.margin=TRUE, fig.width=4, fig.height=4, small.mar=TRUE, out.width="100%", echo=FALSE, message=FALSE, fig.cap="Calculated equilibrium constants for dissolution of CO<sub>2</sub>, CO, and CH<sub>4</sub>.", cache=TRUE, pngquant=pngquant, timeit=timeit----
matplot(logK[, 1], logK[, -1], type = "l", col = 1, lty = 1,
xlab = axis.label("T"), ylab = axis.label("logK"))
text(80, -1.7, expr.species("CO2"))
text(240, -2.37, expr.species("CO"))
text(300, -2.57, expr.species("CH4"))
## ----CO2_logK, eval=FALSE-----------------------------------------------------
# T <- seq(0, 350, 10)
# CO2 <- subcrt(c("CO2", "CO2"), c("gas", "aq"), c(-1, 1), T = T)$out$logK
# CO <- subcrt(c("CO", "CO"), c("gas", "aq"), c(-1, 1), T = T)$out$logK
# CH4 <- subcrt(c("CH4", "CH4"), c("gas", "aq"), c(-1, 1), T = T)$out$logK
# logK <- data.frame(T, CO2, CO, CH4)
## ----CO2_plot, eval=FALSE-----------------------------------------------------
# matplot(logK[, 1], logK[, -1], type = "l", col = 1, lty = 1,
# xlab = axis.label("T"), ylab = axis.label("logK"))
# text(80, -1.7, expr.species("CO2"))
# text(240, -2.37, expr.species("CO"))
# text(300, -2.57, expr.species("CH4"))
## ----subcrt_unbalanced, results="hide"----------------------------------------
subcrt(c("CO2", "CH4"), c(-1, 1))
## ----basis_singular, error=TRUE-----------------------------------------------
basis(c("CO2", "H2", "H2CO2"))
## ----basis_CHO----------------------------------------------------------------
basis(c("CO2", "H2", "H2O"))
## ----basis_CHOZ---------------------------------------------------------------
basis(c("CO2", "H2", "H2O", "H+"))
## ----subcrt_acetoclastic, message=FALSE---------------------------------------
subcrt(c("acetate", "CH4"), c(-1, 1))$reaction
## ----subcrt_methanogenesis, message=FALSE-------------------------------------
acetate_oxidation <- subcrt("acetate", -1)
hydrogenotrophic <- subcrt("CH4", 1)
acetoclastic <- subcrt(c("acetate", "CH4"), c(-1, 1))
## ----describe_reaction_plot, fig.margin=TRUE, fig.width=3.5, fig.height=1.8, tiny.mar=TRUE, out.width="100%", pngquant=pngquant, timeit=timeit----
plot(0, 0, type = "n", axes = FALSE, ann=FALSE, xlim=c(0, 5), ylim=c(5.2, -0.2))
text(0, 0, "acetoclastic methanogenesis", adj = 0)
text(5, 1, describe.reaction(acetoclastic$reaction), adj = 1)
text(0, 2, "acetate oxidation", adj = 0)
text(5, 3, describe.reaction(acetate_oxidation$reaction), adj = 1)
text(0, 4, "hydrogenotrophic methanogenesis", adj = 0)
text(5, 5, describe.reaction(hydrogenotrophic$reaction), adj = 1)
## ----basis_mayumi, message=FALSE, results="hide"------------------------------
basis(c("CO2", "H2", "H2O", "H+"))
basis(c("CO2", "H2"), "gas")
basis(c("H2", "pH"), c(-3.92, 7.3))
## ----affinity_acetoclastic, message=FALSE-------------------------------------
subcrt(c("acetate", "CH4"), c(-1, 1),
c("aq", "gas"), logact = c(-3.4, -0.18), T = 55, P = 50)$out
## ----affinity_hydrogenotrophic, message=FALSE---------------------------------
subcrt("CH4", 1, "gas", logact = -0.18, T = 55, P = 50)$out
## ----rxnfun, message=FALSE----------------------------------------------------
rxnfun <- function(coeffs) {
subcrt(c("acetate", "CH4"), coeffs,
c("aq", "gas"), logact = c(-3.4, -0.18), T = 55, P = 50)$out
}
## ----methanogenesis_plot, fig.margin=TRUE, fig.width=4.1, fig.height=4.1, small.mar=TRUE, out.width="100%", echo=FALSE, message=FALSE, fig.cap="Gibbs energies of acetate oxidation and methanogenesis (after Mayumi et al., 2013).", cache=TRUE, pngquant=pngquant, timeit=timeit----
Adat <- lapply(c(-3, 3), function(logfCO2) {
basis("CO2", logfCO2)
data.frame(logfCO2,
rxnfun(c(0, 0))$A,
rxnfun(c(-1, 0))$A,
rxnfun(c(-1, 1))$A,
rxnfun(c(0, 1))$A
)
})
Adat <- do.call(rbind, Adat)
matplot(Adat[, 1], -Adat[, -1]/1000, type = "l", lty = 1, lwd = 2,
xlab = axis.label("CO2"), ylab = axis.label("DG", prefix = "k"))
legend("topleft", c("acetate oxidation", "acetoclastic methanogenesis",
"hydrogenotrophic methanogenesis"), lty = 1, col = 2:4)
## ----methanogenesis_plot, eval=FALSE------------------------------------------
# Adat <- lapply(c(-3, 3), function(logfCO2) {
# basis("CO2", logfCO2)
# data.frame(logfCO2,
# rxnfun(c(0, 0))$A,
# rxnfun(c(-1, 0))$A,
# rxnfun(c(-1, 1))$A,
# rxnfun(c(0, 1))$A
# )
# })
# Adat <- do.call(rbind, Adat)
# matplot(Adat[, 1], -Adat[, -1]/1000, type = "l", lty = 1, lwd = 2,
# xlab = axis.label("CO2"), ylab = axis.label("DG", prefix = "k"))
# legend("topleft", c("acetate oxidation", "acetoclastic methanogenesis",
# "hydrogenotrophic methanogenesis"), lty = 1, col = 2:4)
## ----reset, message=FALSE-----------------------------------------------------
reset()
## ----basis_CHNOSZ, results="hide"---------------------------------------------
basis("CHNOSe")
## ----species_sulfur-----------------------------------------------------------
species(c("H2S", "HS-", "HSO4-", "SO4-2"))
## ----affinity-----------------------------------------------------------------
unlist(affinity()$values)
## ----EhpH_plot, fig.margin=TRUE, fig.width=4, fig.height=4, out.width="100%", echo = FALSE, message=FALSE, cache=TRUE, fig.cap="Aqueous sulfur species at 25 °C.", pngquant=pngquant, timeit=timeit----
a <- affinity(pH = c(0, 12), Eh = c(-0.5, 1))
diagram(a, limit.water = TRUE)
## ----EhpH_plot, echo=TRUE, eval=FALSE-----------------------------------------
# a <- affinity(pH = c(0, 12), Eh = c(-0.5, 1))
# diagram(a, limit.water = TRUE)
## ----EhpH_plot_color, fig.margin=TRUE, fig.width=4, fig.height=4, smallish.mar=TRUE, out.width="100%", echo=FALSE, message=FALSE, cache=TRUE, fig.cap="The same plot, with different colors and labels.", pngquant=pngquant, timeit=timeit----
diagram(a, fill = "terrain", lwd = 2, lty = 3,
names = c("hydrogen sulfide", "bisulfide", "bisulfate", "sulfate"),
las = 0)
water.lines(a, col = 6, lwd = 2)
## ----EhpH_plot_color, echo=TRUE, eval=FALSE-----------------------------------
# diagram(a, fill = "terrain", lwd = 2, lty = 3,
# names = c("hydrogen sulfide", "bisulfide", "bisulfate", "sulfate"),
# las = 0)
# water.lines(a, col = 6, lwd = 2)
## ----retrieve-----------------------------------------------------------------
retrieve("Mn", c("O", "H"), "aq")
retrieve("Mn", c("O", "H"), "cr")
## ----retrieve_diagram, fig.margin=TRUE, fig.width=5, fig.height=5, out.width="100%", message=FALSE, results = "hide", cache=TRUE, fig.cap="Eh-pH diagram for the Mn-O-H system.", pngquant=pngquant, timeit=timeit----
# Set decimal logarithm of activity of aqueous species,
# temperature and plot resolution
logact <- -4
T <- 100
res <- 400
# Start with the aqueous species
basis(c("Mn+2", "H2O", "H+", "e-"))
iaq <- retrieve("Mn", c("O", "H"), "aq")
species(iaq, logact)
aaq <- affinity(pH = c(4, 16, res), Eh = c(-1.5, 1.5, res), T = T)
# Show names for only the metastable species here
names <- names(iaq)
names[!names(iaq) %in% c("MnOH+", "MnO", "HMnO2-")] <- ""
diagram(aaq, lty = 2, col = "#4169E188", names = names, col.names = 4)
# Overlay mineral stability fields
icr <- retrieve("Mn", c("O", "H"), "cr")
species(icr, add = TRUE)
# Supply the previous result from affinity() to use
# argument recall (for plotted variables and T)
acr <- affinity(aaq)
diagram(acr, add = TRUE, bold = acr$species$state=="cr", limit.water = FALSE)
# Add legend
legend <- c(
bquote(log * italic(a)["Mn(aq)"] == .(logact)),
bquote(italic(T) == .(T) ~ degree*C)
)
legend("topright", legend = as.expression(legend), bty = "n")
## ----info_CuCl, results="hide"------------------------------------------------
info(" CuCl")
## ----copper_setup, echo=TRUE, results="hide"----------------------------------
basis(c("Cu", "H2S", "Cl-", "H2O", "H+", "e-"))
basis("H2S", -6)
basis("Cl-", -0.7)
species(c("CuCl", "CuCl2-", "CuCl3-2", "CuCl+", "CuCl2", "CuCl3-", "CuCl4-2"))
species(c("chalcocite", "tenorite", "cuprite", "copper"), add = TRUE)
## ----info_chalcocite, message=FALSE-------------------------------------------
info(info("chalcocite", c("cr", "cr2", "cr3")))$T
## ----copper_mosaic, fig.margin=TRUE, fig.width=4, fig.height=4, out.width="100%", message=FALSE, cache=TRUE, fig.cap="Copper minerals and aqueous complexes with chloride, 200 °C.", pngquant=pngquant, timeit=timeit----
T <- 200
res <- 200
bases <- c("H2S", "HS-", "HSO4-", "SO4-2")
m1 <- mosaic(bases, pH = c(0, 12, res), Eh=c(-1.2, 0.75, res), T=T)
diagram(m1$A.species, lwd = 2)
diagram(m1$A.bases, add = TRUE, col = 4, col.names = 4, lty = 3,
italic = TRUE)
water.lines(m1$A.species, col = "blue1")
## ----rainbow_data-------------------------------------------------------------
file <- system.file("extdata/cpetc/SC10_Rainbow.csv", package = "CHNOSZ")
rb <- read.csv(file, check.names = FALSE)
## ----rainbow_species, results="hide"------------------------------------------
basis(c("CO2", "H2", "NH4+", "H2O", "H2S", "H+"))
species("CH4", -3)
species(c("adenine", "cytosine", "aspartic acid", "deoxyribose",
"CH4", "leucine", "tryptophan", "n-nonanoic acid"), -6)
## ----rainbow_affinity, message=FALSE------------------------------------------
a <- affinity(T = rb$T, CO2 = rb$CO2, H2 = rb$H2,
`NH4+` = rb$`NH4+`, H2S = rb$H2S, pH = rb$pH)
T <- convert(a$vals[[1]], "K")
a$values <- lapply(a$values, convert, "G", T)
a$values <- lapply(a$values, convert, "cal")
a$values <- lapply(a$values, `*`, -0.001)
## ----rainbow_diagram, fig.margin=TRUE, fig.width=4, fig.height=4, out.width="100%", echo=FALSE, message=FALSE, cache=TRUE, fig.cap="Affinities of organic synthesis in a hydrothermal system, after Shock and Canovas (2010).", pngquant=pngquant, timeit=timeit----
diagram(a, balance = 1, ylim = c(-100, 100), ylab = quote(italic(A)*", kcal/mol"),
col = rainbow(8), lwd = 2, bg = "slategray3")
abline(h = 0, lty = 2, lwd = 2)
## ----rainbow_diagram, eval=FALSE----------------------------------------------
# diagram(a, balance = 1, ylim = c(-100, 100), ylab = quote(italic(A)*", kcal/mol"),
# col = rainbow(8), lwd = 2, bg = "slategray3")
# abline(h = 0, lty = 2, lwd = 2)
## ----PPM_basis, results="hide", message=FALSE---------------------------------
basis(c("FeS2", "H2S", "O2", "H2O"))
species(c("pyrite", "magnetite"))
species("pyrrhotite", "cr2", add = TRUE)
## ----PPM_affinity, message=FALSE----------------------------------------------
unlist(affinity(T = 300, P = 100)$values)
## ----PPM_setup, results="hide"------------------------------------------------
mod.buffer("PPM", "pyrrhotite", "cr2")
basis(c("H2S", "O2"), c("PPM", "PPM"))
## ----PPM_activities, message=FALSE--------------------------------------------
unlist(affinity(T = 300, P = 100, return.buffer = TRUE)[1:3])
## ----demo_buffer_noecho, fig.margin=TRUE, fig.width=4, fig.height=4, out.width="100%", message=FALSE, echo=FALSE, cache=TRUE, fig.cap="Values of log<i>f</i><sub>H<sub>2</sub></sub> corresponding to mineral buffers or to given activities of aqueous species.", pngquant=pngquant, timeit=timeit----
demo(buffer, echo = FALSE)
## ----PPM_basis, echo = FALSE, results = "hide"--------------------------------
basis(c("FeS2", "H2S", "O2", "H2O"))
species(c("pyrite", "magnetite"))
species("pyrrhotite", "cr2", add = TRUE)
## ----PPM_setup, echo = FALSE, results = "hide", message = FALSE---------------
mod.buffer("PPM", "pyrrhotite", "cr2")
basis(c("H2S", "O2"), c("PPM", "PPM"))
## ----PPM_affinity, message = FALSE--------------------------------------------
unlist(affinity(T = 300, P = 100)$values)
## ----demo_buffer, eval=FALSE--------------------------------------------------
# demo(buffer)
## ----bjerrum_diagram, fig.margin=TRUE, fig.width=3, fig.height=6, out.width="100%", echo=FALSE, results="hide", message=FALSE, cache=TRUE, fig.cap="Three views of carbonate speciation: affinity, activity, degree of formation.", pngquant=pngquant, timeit=timeit----
par(mfrow = c(3, 1))
basis("CHNOS+")
species(c("CO2", "HCO3-", "CO3-2"))
a25 <- affinity(pH = c(4, 13))
a150 <- affinity(pH = c(4, 13), T = 150)
diagram(a25, dy = 0.4)
diagram(a150, add = TRUE, names = FALSE, col = "red")
e25 <- equilibrate(a25, loga.balance = -3)
e150 <- equilibrate(a150, loga.balance = -3)
diagram(e25, ylim = c(-6, 0), dy = 0.15)
diagram(e150, add = TRUE, names = FALSE, col = "red")
diagram(e25, alpha = TRUE, dy = -0.25)
diagram(e150, alpha = TRUE, add = TRUE, names = FALSE, col = "red")
## ----bjerrum_diagram, echo=1:7, eval=FALSE------------------------------------
# par(mfrow = c(3, 1))
# basis("CHNOS+")
# species(c("CO2", "HCO3-", "CO3-2"))
# a25 <- affinity(pH = c(4, 13))
# a150 <- affinity(pH = c(4, 13), T = 150)
# diagram(a25, dy = 0.4)
# diagram(a150, add = TRUE, names = FALSE, col = "red")
# e25 <- equilibrate(a25, loga.balance = -3)
# e150 <- equilibrate(a150, loga.balance = -3)
# diagram(e25, ylim = c(-6, 0), dy = 0.15)
# diagram(e150, add = TRUE, names = FALSE, col = "red")
# diagram(e25, alpha = TRUE, dy = -0.25)
# diagram(e150, alpha = TRUE, add = TRUE, names = FALSE, col = "red")
## ----bjerrum_diagram, echo=8:11, eval=FALSE-----------------------------------
# par(mfrow = c(3, 1))
# basis("CHNOS+")
# species(c("CO2", "HCO3-", "CO3-2"))
# a25 <- affinity(pH = c(4, 13))
# a150 <- affinity(pH = c(4, 13), T = 150)
# diagram(a25, dy = 0.4)
# diagram(a150, add = TRUE, names = FALSE, col = "red")
# e25 <- equilibrate(a25, loga.balance = -3)
# e150 <- equilibrate(a150, loga.balance = -3)
# diagram(e25, ylim = c(-6, 0), dy = 0.15)
# diagram(e150, add = TRUE, names = FALSE, col = "red")
# diagram(e25, alpha = TRUE, dy = -0.25)
# diagram(e150, alpha = TRUE, add = TRUE, names = FALSE, col = "red")
## ----bjerrum_diagram, echo=12:13, eval=FALSE----------------------------------
# par(mfrow = c(3, 1))
# basis("CHNOS+")
# species(c("CO2", "HCO3-", "CO3-2"))
# a25 <- affinity(pH = c(4, 13))
# a150 <- affinity(pH = c(4, 13), T = 150)
# diagram(a25, dy = 0.4)
# diagram(a150, add = TRUE, names = FALSE, col = "red")
# e25 <- equilibrate(a25, loga.balance = -3)
# e150 <- equilibrate(a150, loga.balance = -3)
# diagram(e25, ylim = c(-6, 0), dy = 0.15)
# diagram(e150, add = TRUE, names = FALSE, col = "red")
# diagram(e25, alpha = TRUE, dy = -0.25)
# diagram(e150, alpha = TRUE, add = TRUE, names = FALSE, col = "red")
## ----corundum, fig.margin=TRUE, fig.width=4, fig.height=4, out.width="100%", results="hide", message=FALSE, cache=TRUE, fig.cap="Solubility of corundum (green line) and equilibrium concentrations of aqueous species (black lines).", pngquant=pngquant, timeit=timeit----
add.OBIGT("SLOP98")
basis(c("Al+3", "H2O", "H+", "O2"))
species("corundum")
iaq <- c("Al+3", "AlO2-", "AlOH+2", "AlO+", "HAlO2")
s <- solubility(iaq, pH = c(0, 10), IS = 0, in.terms.of = "Al+3")
diagram(s, type = "loga.balance", ylim = c(-10, 0), lwd = 4, col = "green3")
diagram(s, add = TRUE, adj = c(0, 1, 2.1, -0.2, -1.5), dy = c(0, 0, 4, -0.3, 0.1))
legend("topright", c("25 °C", "1 bar"), text.font = 2, bty = "n")
reset()
## ----Alberty------------------------------------------------------------------
oldnon <- nonideal("Alberty")
## ----subcrt_IS----------------------------------------------------------------
subcrt(c("MgATP-2", "MgHATP-", "MgH2ATP"),
T = c(25, 100), IS = c(0, 0.25), property = "G")$out
## ----info_ATP, results="hide"-------------------------------------------------
info(" ATP")
## ----T_100--------------------------------------------------------------------
T <- 100
## ----ATP, eval=FALSE, echo=2:6------------------------------------------------
# par(mfrow = c(1, 4), mar = c(3.1, 3.6, 2.1, 1.6), mgp = c(1.8, 0.5, 0))
# basis("MgCHNOPS+")
# species(c("ATP-4", "HATP-3", "H2ATP-2", "H3ATP-", "H4ATP"))
# a <- affinity(pH = c(3, 9), T = T)
# e <- equilibrate(a)
# d <- diagram(e, alpha = TRUE, tplot = FALSE)
# title(main = describe.property("T", T))
# alphas <- do.call(rbind, d$plotvals)
# nH <- alphas * 0:4
# Hlab <- substitute(italic(N)[H^`+`])
# plot(a$vals[[1]], colSums(nH), type = "l", xlab = "pH", ylab=Hlab, lty=2, col=2)
# a <- affinity(pH = c(3, 9), IS = 0.25, T = T)
# e <- equilibrate(a)
# d <- diagram(e, alpha = TRUE, plot.it = FALSE)
# alphas <- do.call(rbind, d$plotvals)
# nH <- alphas * 0:4
# lines(a$vals[[1]], colSums(nH))
# legend("topright", legend = c("I = 0 M", "I = 0.25 M"), lty = 2:1, col = 2:1, cex = 0.8)
# ATP.H <- substitute("ATP and H"^`+`)
# title(main = ATP.H)
# species(c("MgATP-2", "MgHATP-", "MgH2ATP", "Mg2ATP"), add = TRUE)
# Hplot <- function(pMg, IS = 0.25) {
# basis("Mg+2", -pMg)
# a <- affinity(pH = c(3, 9), IS = IS, T = T)
# e <- equilibrate(a)
# d <- diagram(e, alpha = TRUE, plot.it = FALSE)
# alphas <- do.call(rbind, d$plotvals)
# NH <- alphas * c(0:4, 0, 1, 2, 0)
# lines(a$vals[[1]], colSums(NH), lty = 7 - pMg, col = 7 - pMg)
# }
# plot(c(3, 9), c(0, 2), type = "n", xlab = "pH", ylab = Hlab)
# lapply(2:6, Hplot)
# legend("topright", legend = paste("pMg = ", 2:6), lty = 5:1, col = 5:1, cex = 0.8)
# ATP.H.Mg <- substitute("ATP and H"^`+`~"and Mg"^`+2`)
# title(main = ATP.H.Mg)
# Mgplot <- function(pH, IS = 0.25) {
# basis("pH", pH)
# a <- affinity(`Mg+2` = c(-2, -7), IS = IS, T = T)
# e <- equilibrate(a)
# d <- diagram(e, alpha = TRUE, plot.it = FALSE)
# alphas <- do.call(rbind, d$plotvals)
# NMg <- alphas * species()$`Mg+`
# lines(-a$vals[[1]], colSums(NMg), lty = 10 - pH, col = 10 - pH)
# }
# Mglab <- substitute(italic(N)[Mg^`+2`])
# plot(c(2, 7), c(0, 1.2), type = "n", xlab = "pMg", ylab = Mglab)
# lapply(3:9, Mgplot)
# legend("topright", legend = paste("pH = ", 3:9), lty = 7:1, col = 7:1, cex = 0.8)
# title(main = ATP.H.Mg)
## ----ATP, eval=FALSE, echo=8:11-----------------------------------------------
# par(mfrow = c(1, 4), mar = c(3.1, 3.6, 2.1, 1.6), mgp = c(1.8, 0.5, 0))
# basis("MgCHNOPS+")
# species(c("ATP-4", "HATP-3", "H2ATP-2", "H3ATP-", "H4ATP"))
# a <- affinity(pH = c(3, 9), T = T)
# e <- equilibrate(a)
# d <- diagram(e, alpha = TRUE, tplot = FALSE)
# title(main = describe.property("T", T))
# alphas <- do.call(rbind, d$plotvals)
# nH <- alphas * 0:4
# Hlab <- substitute(italic(N)[H^`+`])
# plot(a$vals[[1]], colSums(nH), type = "l", xlab = "pH", ylab=Hlab, lty=2, col=2)
# a <- affinity(pH = c(3, 9), IS = 0.25, T = T)
# e <- equilibrate(a)
# d <- diagram(e, alpha = TRUE, plot.it = FALSE)
# alphas <- do.call(rbind, d$plotvals)
# nH <- alphas * 0:4
# lines(a$vals[[1]], colSums(nH))
# legend("topright", legend = c("I = 0 M", "I = 0.25 M"), lty = 2:1, col = 2:1, cex = 0.8)
# ATP.H <- substitute("ATP and H"^`+`)
# title(main = ATP.H)
# species(c("MgATP-2", "MgHATP-", "MgH2ATP", "Mg2ATP"), add = TRUE)
# Hplot <- function(pMg, IS = 0.25) {
# basis("Mg+2", -pMg)
# a <- affinity(pH = c(3, 9), IS = IS, T = T)
# e <- equilibrate(a)
# d <- diagram(e, alpha = TRUE, plot.it = FALSE)
# alphas <- do.call(rbind, d$plotvals)
# NH <- alphas * c(0:4, 0, 1, 2, 0)
# lines(a$vals[[1]], colSums(NH), lty = 7 - pMg, col = 7 - pMg)
# }
# plot(c(3, 9), c(0, 2), type = "n", xlab = "pH", ylab = Hlab)
# lapply(2:6, Hplot)
# legend("topright", legend = paste("pMg = ", 2:6), lty = 5:1, col = 5:1, cex = 0.8)
# ATP.H.Mg <- substitute("ATP and H"^`+`~"and Mg"^`+2`)
# title(main = ATP.H.Mg)
# Mgplot <- function(pH, IS = 0.25) {
# basis("pH", pH)
# a <- affinity(`Mg+2` = c(-2, -7), IS = IS, T = T)
# e <- equilibrate(a)
# d <- diagram(e, alpha = TRUE, plot.it = FALSE)
# alphas <- do.call(rbind, d$plotvals)
# NMg <- alphas * species()$`Mg+`
# lines(-a$vals[[1]], colSums(NMg), lty = 10 - pH, col = 10 - pH)
# }
# Mglab <- substitute(italic(N)[Mg^`+2`])
# plot(c(2, 7), c(0, 1.2), type = "n", xlab = "pMg", ylab = Mglab)
# lapply(3:9, Mgplot)
# legend("topright", legend = paste("pH = ", 3:9), lty = 7:1, col = 7:1, cex = 0.8)
# title(main = ATP.H.Mg)
## ----ATP, eval=FALSE, echo=12:17----------------------------------------------
# par(mfrow = c(1, 4), mar = c(3.1, 3.6, 2.1, 1.6), mgp = c(1.8, 0.5, 0))
# basis("MgCHNOPS+")
# species(c("ATP-4", "HATP-3", "H2ATP-2", "H3ATP-", "H4ATP"))
# a <- affinity(pH = c(3, 9), T = T)
# e <- equilibrate(a)
# d <- diagram(e, alpha = TRUE, tplot = FALSE)
# title(main = describe.property("T", T))
# alphas <- do.call(rbind, d$plotvals)
# nH <- alphas * 0:4
# Hlab <- substitute(italic(N)[H^`+`])
# plot(a$vals[[1]], colSums(nH), type = "l", xlab = "pH", ylab=Hlab, lty=2, col=2)
# a <- affinity(pH = c(3, 9), IS = 0.25, T = T)
# e <- equilibrate(a)
# d <- diagram(e, alpha = TRUE, plot.it = FALSE)
# alphas <- do.call(rbind, d$plotvals)
# nH <- alphas * 0:4
# lines(a$vals[[1]], colSums(nH))
# legend("topright", legend = c("I = 0 M", "I = 0.25 M"), lty = 2:1, col = 2:1, cex = 0.8)
# ATP.H <- substitute("ATP and H"^`+`)
# title(main = ATP.H)
# species(c("MgATP-2", "MgHATP-", "MgH2ATP", "Mg2ATP"), add = TRUE)
# Hplot <- function(pMg, IS = 0.25) {
# basis("Mg+2", -pMg)
# a <- affinity(pH = c(3, 9), IS = IS, T = T)
# e <- equilibrate(a)
# d <- diagram(e, alpha = TRUE, plot.it = FALSE)
# alphas <- do.call(rbind, d$plotvals)
# NH <- alphas * c(0:4, 0, 1, 2, 0)
# lines(a$vals[[1]], colSums(NH), lty = 7 - pMg, col = 7 - pMg)
# }
# plot(c(3, 9), c(0, 2), type = "n", xlab = "pH", ylab = Hlab)
# lapply(2:6, Hplot)
# legend("topright", legend = paste("pMg = ", 2:6), lty = 5:1, col = 5:1, cex = 0.8)
# ATP.H.Mg <- substitute("ATP and H"^`+`~"and Mg"^`+2`)
# title(main = ATP.H.Mg)
# Mgplot <- function(pH, IS = 0.25) {
# basis("pH", pH)
# a <- affinity(`Mg+2` = c(-2, -7), IS = IS, T = T)
# e <- equilibrate(a)
# d <- diagram(e, alpha = TRUE, plot.it = FALSE)
# alphas <- do.call(rbind, d$plotvals)
# NMg <- alphas * species()$`Mg+`
# lines(-a$vals[[1]], colSums(NMg), lty = 10 - pH, col = 10 - pH)
# }
# Mglab <- substitute(italic(N)[Mg^`+2`])
# plot(c(2, 7), c(0, 1.2), type = "n", xlab = "pMg", ylab = Mglab)
# lapply(3:9, Mgplot)
# legend("topright", legend = paste("pH = ", 3:9), lty = 7:1, col = 7:1, cex = 0.8)
# title(main = ATP.H.Mg)
## ----ATP, eval=FALSE, echo=21-------------------------------------------------
# par(mfrow = c(1, 4), mar = c(3.1, 3.6, 2.1, 1.6), mgp = c(1.8, 0.5, 0))
# basis("MgCHNOPS+")
# species(c("ATP-4", "HATP-3", "H2ATP-2", "H3ATP-", "H4ATP"))
# a <- affinity(pH = c(3, 9), T = T)
# e <- equilibrate(a)
# d <- diagram(e, alpha = TRUE, tplot = FALSE)
# title(main = describe.property("T", T))
# alphas <- do.call(rbind, d$plotvals)
# nH <- alphas * 0:4
# Hlab <- substitute(italic(N)[H^`+`])
# plot(a$vals[[1]], colSums(nH), type = "l", xlab = "pH", ylab=Hlab, lty=2, col=2)
# a <- affinity(pH = c(3, 9), IS = 0.25, T = T)
# e <- equilibrate(a)
# d <- diagram(e, alpha = TRUE, plot.it = FALSE)
# alphas <- do.call(rbind, d$plotvals)
# nH <- alphas * 0:4
# lines(a$vals[[1]], colSums(nH))
# legend("topright", legend = c("I = 0 M", "I = 0.25 M"), lty = 2:1, col = 2:1, cex = 0.8)
# ATP.H <- substitute("ATP and H"^`+`)
# title(main = ATP.H)
# species(c("MgATP-2", "MgHATP-", "MgH2ATP", "Mg2ATP"), add = TRUE)
# Hplot <- function(pMg, IS = 0.25) {
# basis("Mg+2", -pMg)
# a <- affinity(pH = c(3, 9), IS = IS, T = T)
# e <- equilibrate(a)
# d <- diagram(e, alpha = TRUE, plot.it = FALSE)
# alphas <- do.call(rbind, d$plotvals)
# NH <- alphas * c(0:4, 0, 1, 2, 0)
# lines(a$vals[[1]], colSums(NH), lty = 7 - pMg, col = 7 - pMg)
# }
# plot(c(3, 9), c(0, 2), type = "n", xlab = "pH", ylab = Hlab)
# lapply(2:6, Hplot)
# legend("topright", legend = paste("pMg = ", 2:6), lty = 5:1, col = 5:1, cex = 0.8)
# ATP.H.Mg <- substitute("ATP and H"^`+`~"and Mg"^`+2`)
# title(main = ATP.H.Mg)
# Mgplot <- function(pH, IS = 0.25) {
# basis("pH", pH)
# a <- affinity(`Mg+2` = c(-2, -7), IS = IS, T = T)
# e <- equilibrate(a)
# d <- diagram(e, alpha = TRUE, plot.it = FALSE)
# alphas <- do.call(rbind, d$plotvals)
# NMg <- alphas * species()$`Mg+`
# lines(-a$vals[[1]], colSums(NMg), lty = 10 - pH, col = 10 - pH)
# }
# Mglab <- substitute(italic(N)[Mg^`+2`])
# plot(c(2, 7), c(0, 1.2), type = "n", xlab = "pMg", ylab = Mglab)
# lapply(3:9, Mgplot)
# legend("topright", legend = paste("pH = ", 3:9), lty = 7:1, col = 7:1, cex = 0.8)
# title(main = ATP.H.Mg)
## ----ATP, eval=FALSE, echo=22:30----------------------------------------------
# par(mfrow = c(1, 4), mar = c(3.1, 3.6, 2.1, 1.6), mgp = c(1.8, 0.5, 0))
# basis("MgCHNOPS+")
# species(c("ATP-4", "HATP-3", "H2ATP-2", "H3ATP-", "H4ATP"))
# a <- affinity(pH = c(3, 9), T = T)
# e <- equilibrate(a)
# d <- diagram(e, alpha = TRUE, tplot = FALSE)
# title(main = describe.property("T", T))
# alphas <- do.call(rbind, d$plotvals)
# nH <- alphas * 0:4
# Hlab <- substitute(italic(N)[H^`+`])
# plot(a$vals[[1]], colSums(nH), type = "l", xlab = "pH", ylab=Hlab, lty=2, col=2)
# a <- affinity(pH = c(3, 9), IS = 0.25, T = T)
# e <- equilibrate(a)
# d <- diagram(e, alpha = TRUE, plot.it = FALSE)
# alphas <- do.call(rbind, d$plotvals)
# nH <- alphas * 0:4
# lines(a$vals[[1]], colSums(nH))
# legend("topright", legend = c("I = 0 M", "I = 0.25 M"), lty = 2:1, col = 2:1, cex = 0.8)
# ATP.H <- substitute("ATP and H"^`+`)
# title(main = ATP.H)
# species(c("MgATP-2", "MgHATP-", "MgH2ATP", "Mg2ATP"), add = TRUE)
# Hplot <- function(pMg, IS = 0.25) {
# basis("Mg+2", -pMg)
# a <- affinity(pH = c(3, 9), IS = IS, T = T)
# e <- equilibrate(a)
# d <- diagram(e, alpha = TRUE, plot.it = FALSE)
# alphas <- do.call(rbind, d$plotvals)
# NH <- alphas * c(0:4, 0, 1, 2, 0)
# lines(a$vals[[1]], colSums(NH), lty = 7 - pMg, col = 7 - pMg)
# }
# plot(c(3, 9), c(0, 2), type = "n", xlab = "pH", ylab = Hlab)
# lapply(2:6, Hplot)
# legend("topright", legend = paste("pMg = ", 2:6), lty = 5:1, col = 5:1, cex = 0.8)
# ATP.H.Mg <- substitute("ATP and H"^`+`~"and Mg"^`+2`)
# title(main = ATP.H.Mg)
# Mgplot <- function(pH, IS = 0.25) {
# basis("pH", pH)
# a <- affinity(`Mg+2` = c(-2, -7), IS = IS, T = T)
# e <- equilibrate(a)
# d <- diagram(e, alpha = TRUE, plot.it = FALSE)
# alphas <- do.call(rbind, d$plotvals)
# NMg <- alphas * species()$`Mg+`
# lines(-a$vals[[1]], colSums(NMg), lty = 10 - pH, col = 10 - pH)
# }
# Mglab <- substitute(italic(N)[Mg^`+2`])
# plot(c(2, 7), c(0, 1.2), type = "n", xlab = "pMg", ylab = Mglab)
# lapply(3:9, Mgplot)
# legend("topright", legend = paste("pH = ", 3:9), lty = 7:1, col = 7:1, cex = 0.8)
# title(main = ATP.H.Mg)
## ----ATP, eval=FALSE, echo=31:32----------------------------------------------
# par(mfrow = c(1, 4), mar = c(3.1, 3.6, 2.1, 1.6), mgp = c(1.8, 0.5, 0))
# basis("MgCHNOPS+")
# species(c("ATP-4", "HATP-3", "H2ATP-2", "H3ATP-", "H4ATP"))
# a <- affinity(pH = c(3, 9), T = T)
# e <- equilibrate(a)
# d <- diagram(e, alpha = TRUE, tplot = FALSE)
# title(main = describe.property("T", T))
# alphas <- do.call(rbind, d$plotvals)
# nH <- alphas * 0:4
# Hlab <- substitute(italic(N)[H^`+`])
# plot(a$vals[[1]], colSums(nH), type = "l", xlab = "pH", ylab=Hlab, lty=2, col=2)
# a <- affinity(pH = c(3, 9), IS = 0.25, T = T)
# e <- equilibrate(a)
# d <- diagram(e, alpha = TRUE, plot.it = FALSE)
# alphas <- do.call(rbind, d$plotvals)
# nH <- alphas * 0:4
# lines(a$vals[[1]], colSums(nH))
# legend("topright", legend = c("I = 0 M", "I = 0.25 M"), lty = 2:1, col = 2:1, cex = 0.8)
# ATP.H <- substitute("ATP and H"^`+`)
# title(main = ATP.H)
# species(c("MgATP-2", "MgHATP-", "MgH2ATP", "Mg2ATP"), add = TRUE)
# Hplot <- function(pMg, IS = 0.25) {
# basis("Mg+2", -pMg)
# a <- affinity(pH = c(3, 9), IS = IS, T = T)
# e <- equilibrate(a)
# d <- diagram(e, alpha = TRUE, plot.it = FALSE)
# alphas <- do.call(rbind, d$plotvals)
# NH <- alphas * c(0:4, 0, 1, 2, 0)
# lines(a$vals[[1]], colSums(NH), lty = 7 - pMg, col = 7 - pMg)
# }
# plot(c(3, 9), c(0, 2), type = "n", xlab = "pH", ylab = Hlab)
# lapply(2:6, Hplot)
# legend("topright", legend = paste("pMg = ", 2:6), lty = 5:1, col = 5:1, cex = 0.8)
# ATP.H.Mg <- substitute("ATP and H"^`+`~"and Mg"^`+2`)
# title(main = ATP.H.Mg)
# Mgplot <- function(pH, IS = 0.25) {
# basis("pH", pH)
# a <- affinity(`Mg+2` = c(-2, -7), IS = IS, T = T)
# e <- equilibrate(a)
# d <- diagram(e, alpha = TRUE, plot.it = FALSE)
# alphas <- do.call(rbind, d$plotvals)
# NMg <- alphas * species()$`Mg+`
# lines(-a$vals[[1]], colSums(NMg), lty = 10 - pH, col = 10 - pH)
# }
# Mglab <- substitute(italic(N)[Mg^`+2`])
# plot(c(2, 7), c(0, 1.2), type = "n", xlab = "pMg", ylab = Mglab)
# lapply(3:9, Mgplot)
# legend("topright", legend = paste("pH = ", 3:9), lty = 7:1, col = 7:1, cex = 0.8)
# title(main = ATP.H.Mg)
## ----ATP, eval=FALSE, echo=36:44----------------------------------------------
# par(mfrow = c(1, 4), mar = c(3.1, 3.6, 2.1, 1.6), mgp = c(1.8, 0.5, 0))
# basis("MgCHNOPS+")
# species(c("ATP-4", "HATP-3", "H2ATP-2", "H3ATP-", "H4ATP"))
# a <- affinity(pH = c(3, 9), T = T)
# e <- equilibrate(a)
# d <- diagram(e, alpha = TRUE, tplot = FALSE)
# title(main = describe.property("T", T))
# alphas <- do.call(rbind, d$plotvals)
# nH <- alphas * 0:4
# Hlab <- substitute(italic(N)[H^`+`])
# plot(a$vals[[1]], colSums(nH), type = "l", xlab = "pH", ylab=Hlab, lty=2, col=2)
# a <- affinity(pH = c(3, 9), IS = 0.25, T = T)
# e <- equilibrate(a)
# d <- diagram(e, alpha = TRUE, plot.it = FALSE)
# alphas <- do.call(rbind, d$plotvals)
# nH <- alphas * 0:4
# lines(a$vals[[1]], colSums(nH))
# legend("topright", legend = c("I = 0 M", "I = 0.25 M"), lty = 2:1, col = 2:1, cex = 0.8)
# ATP.H <- substitute("ATP and H"^`+`)
# title(main = ATP.H)
# species(c("MgATP-2", "MgHATP-", "MgH2ATP", "Mg2ATP"), add = TRUE)
# Hplot <- function(pMg, IS = 0.25) {
# basis("Mg+2", -pMg)
# a <- affinity(pH = c(3, 9), IS = IS, T = T)
# e <- equilibrate(a)
# d <- diagram(e, alpha = TRUE, plot.it = FALSE)
# alphas <- do.call(rbind, d$plotvals)
# NH <- alphas * c(0:4, 0, 1, 2, 0)
# lines(a$vals[[1]], colSums(NH), lty = 7 - pMg, col = 7 - pMg)
# }
# plot(c(3, 9), c(0, 2), type = "n", xlab = "pH", ylab = Hlab)
# lapply(2:6, Hplot)
# legend("topright", legend = paste("pMg = ", 2:6), lty = 5:1, col = 5:1, cex = 0.8)
# ATP.H.Mg <- substitute("ATP and H"^`+`~"and Mg"^`+2`)
# title(main = ATP.H.Mg)
# Mgplot <- function(pH, IS = 0.25) {
# basis("pH", pH)
# a <- affinity(`Mg+2` = c(-2, -7), IS = IS, T = T)
# e <- equilibrate(a)
# d <- diagram(e, alpha = TRUE, plot.it = FALSE)
# alphas <- do.call(rbind, d$plotvals)
# NMg <- alphas * species()$`Mg+`
# lines(-a$vals[[1]], colSums(NMg), lty = 10 - pH, col = 10 - pH)
# }
# Mglab <- substitute(italic(N)[Mg^`+2`])
# plot(c(2, 7), c(0, 1.2), type = "n", xlab = "pMg", ylab = Mglab)
# lapply(3:9, Mgplot)
# legend("topright", legend = paste("pH = ", 3:9), lty = 7:1, col = 7:1, cex = 0.8)
# title(main = ATP.H.Mg)
## ----ATP, eval=FALSE, echo=45:47----------------------------------------------
# par(mfrow = c(1, 4), mar = c(3.1, 3.6, 2.1, 1.6), mgp = c(1.8, 0.5, 0))
# basis("MgCHNOPS+")
# species(c("ATP-4", "HATP-3", "H2ATP-2", "H3ATP-", "H4ATP"))
# a <- affinity(pH = c(3, 9), T = T)
# e <- equilibrate(a)
# d <- diagram(e, alpha = TRUE, tplot = FALSE)
# title(main = describe.property("T", T))
# alphas <- do.call(rbind, d$plotvals)
# nH <- alphas * 0:4
# Hlab <- substitute(italic(N)[H^`+`])
# plot(a$vals[[1]], colSums(nH), type = "l", xlab = "pH", ylab=Hlab, lty=2, col=2)
# a <- affinity(pH = c(3, 9), IS = 0.25, T = T)
# e <- equilibrate(a)
# d <- diagram(e, alpha = TRUE, plot.it = FALSE)
# alphas <- do.call(rbind, d$plotvals)
# nH <- alphas * 0:4
# lines(a$vals[[1]], colSums(nH))
# legend("topright", legend = c("I = 0 M", "I = 0.25 M"), lty = 2:1, col = 2:1, cex = 0.8)
# ATP.H <- substitute("ATP and H"^`+`)
# title(main = ATP.H)
# species(c("MgATP-2", "MgHATP-", "MgH2ATP", "Mg2ATP"), add = TRUE)
# Hplot <- function(pMg, IS = 0.25) {
# basis("Mg+2", -pMg)
# a <- affinity(pH = c(3, 9), IS = IS, T = T)
# e <- equilibrate(a)
# d <- diagram(e, alpha = TRUE, plot.it = FALSE)
# alphas <- do.call(rbind, d$plotvals)
# NH <- alphas * c(0:4, 0, 1, 2, 0)
# lines(a$vals[[1]], colSums(NH), lty = 7 - pMg, col = 7 - pMg)
# }
# plot(c(3, 9), c(0, 2), type = "n", xlab = "pH", ylab = Hlab)
# lapply(2:6, Hplot)
# legend("topright", legend = paste("pMg = ", 2:6), lty = 5:1, col = 5:1, cex = 0.8)
# ATP.H.Mg <- substitute("ATP and H"^`+`~"and Mg"^`+2`)
# title(main = ATP.H.Mg)
# Mgplot <- function(pH, IS = 0.25) {
# basis("pH", pH)
# a <- affinity(`Mg+2` = c(-2, -7), IS = IS, T = T)
# e <- equilibrate(a)
# d <- diagram(e, alpha = TRUE, plot.it = FALSE)
# alphas <- do.call(rbind, d$plotvals)
# NMg <- alphas * species()$`Mg+`
# lines(-a$vals[[1]], colSums(NMg), lty = 10 - pH, col = 10 - pH)
# }
# Mglab <- substitute(italic(N)[Mg^`+2`])
# plot(c(2, 7), c(0, 1.2), type = "n", xlab = "pMg", ylab = Mglab)
# lapply(3:9, Mgplot)
# legend("topright", legend = paste("pH = ", 3:9), lty = 7:1, col = 7:1, cex = 0.8)
# title(main = ATP.H.Mg)
## ----ATP, fig.fullwidth=TRUE, fig.width=10, fig.height=2.5, dpi=hidpi, out.width="100%", echo=FALSE, message=FALSE, results="hide", fig.cap="Binding of H<sup>+</sup> and Mg<sup>+2</sup> to ATP at 100 °C and *I* = 0 M (first plot) or *I* = 0.25 M (third and fourth plots).", cache=TRUE, pngquant=pngquant, timeit=timeit----
par(mfrow = c(1, 4), mar = c(3.1, 3.6, 2.1, 1.6), mgp = c(1.8, 0.5, 0))
basis("MgCHNOPS+")
species(c("ATP-4", "HATP-3", "H2ATP-2", "H3ATP-", "H4ATP"))
a <- affinity(pH = c(3, 9), T = T)
e <- equilibrate(a)
d <- diagram(e, alpha = TRUE, tplot = FALSE)
title(main = describe.property("T", T))
alphas <- do.call(rbind, d$plotvals)
nH <- alphas * 0:4
Hlab <- substitute(italic(N)[H^`+`])
plot(a$vals[[1]], colSums(nH), type = "l", xlab = "pH", ylab=Hlab, lty=2, col=2)
a <- affinity(pH = c(3, 9), IS = 0.25, T = T)
e <- equilibrate(a)
d <- diagram(e, alpha = TRUE, plot.it = FALSE)
alphas <- do.call(rbind, d$plotvals)
nH <- alphas * 0:4
lines(a$vals[[1]], colSums(nH))
legend("topright", legend = c("I = 0 M", "I = 0.25 M"), lty = 2:1, col = 2:1, cex = 0.8)
ATP.H <- substitute("ATP and H"^`+`)
title(main = ATP.H)
species(c("MgATP-2", "MgHATP-", "MgH2ATP", "Mg2ATP"), add = TRUE)
Hplot <- function(pMg, IS = 0.25) {
basis("Mg+2", -pMg)
a <- affinity(pH = c(3, 9), IS = IS, T = T)
e <- equilibrate(a)
d <- diagram(e, alpha = TRUE, plot.it = FALSE)
alphas <- do.call(rbind, d$plotvals)
NH <- alphas * c(0:4, 0, 1, 2, 0)
lines(a$vals[[1]], colSums(NH), lty = 7 - pMg, col = 7 - pMg)
}
plot(c(3, 9), c(0, 2), type = "n", xlab = "pH", ylab = Hlab)
lapply(2:6, Hplot)
legend("topright", legend = paste("pMg = ", 2:6), lty = 5:1, col = 5:1, cex = 0.8)
ATP.H.Mg <- substitute("ATP and H"^`+`~"and Mg"^`+2`)
title(main = ATP.H.Mg)
Mgplot <- function(pH, IS = 0.25) {
basis("pH", pH)
a <- affinity(`Mg+2` = c(-2, -7), IS = IS, T = T)
e <- equilibrate(a)
d <- diagram(e, alpha = TRUE, plot.it = FALSE)
alphas <- do.call(rbind, d$plotvals)
NMg <- alphas * species()$`Mg+`
lines(-a$vals[[1]], colSums(NMg), lty = 10 - pH, col = 10 - pH)
}
Mglab <- substitute(italic(N)[Mg^`+2`])
plot(c(2, 7), c(0, 1.2), type = "n", xlab = "pMg", ylab = Mglab)
lapply(3:9, Mgplot)
legend("topright", legend = paste("pH = ", 3:9), lty = 7:1, col = 7:1, cex = 0.8)
title(main = ATP.H.Mg)
## ----oldnon-------------------------------------------------------------------
nonideal(oldnon)
## ----pinfo_LYSC_CHICK---------------------------------------------------------
p1 <- pinfo("LYSC_CHICK")
p2 <- pinfo(c("SHH", "OLIG2"), "HUMAN")
pinfo(c(p1, p2))
## ----formula_LYSC_CHICK-------------------------------------------------------
pl <- protein.length("LYSC_CHICK")
pf <- protein.formula("LYSC_CHICK")
list(length = pl, protein = pf, residue = pf / pl,
ZC_protein = ZC(pf), ZC_residue = ZC(pf / pl))
## ----subcrt_LYSC_CHICK, message=FALSE-----------------------------------------
subcrt("LYSC_CHICK")$out[[1]][1:6, ]
## ----protein_Cp, fig.margin=TRUE, fig.width=4, fig.height=4, small.mar=TRUE, out.width="100%", echo=FALSE, message=FALSE, fig.cap='The heat capacity calculated by group additivity closely approximates experimental values for aqueous proteins. For a related figure showing the effects of ionization in the calculations, see <span style="color:blue">`?ionize.aa`</span>.', cache=TRUE, pngquant=pngquant, timeit=timeit----
PM90 <- read.csv(system.file("extdata/cpetc/PM90.csv", package = "CHNOSZ"))
plength <- protein.length(colnames(PM90)[2:5])
Cp_expt <- t(t(PM90[, 2:5]) / plength)
matplot(PM90[, 1], Cp_expt, type = "p", pch = 19,
xlab = axis.label("T"), ylab = axis.label("Cp0"), ylim = c(110, 280))
for(i in 1:4) {
pname <- colnames(Cp_expt)[i]
aq <- subcrt(pname, "aq", T = seq(0, 150))$out[[1]]
cr <- subcrt(pname, "cr", T = seq(0, 150))$out[[1]]
lines(aq$T, aq$Cp / plength[i], col = i)
lines(cr$T, cr$Cp / plength[i], col = i, lty = 2)
}
legend("right", legend = colnames(Cp_expt),
col = 1:4, pch = 19, lty = 1, bty = "n", cex = 0.9)
legend("bottomright", legend = c("experimental", "calculated (aq)",
"calculated (cr)"), lty = c(NA, 1, 2), pch = c(19, NA, NA), bty = "n")
## ----protein_Cp, eval=FALSE, echo=1:5-----------------------------------------
# PM90 <- read.csv(system.file("extdata/cpetc/PM90.csv", package = "CHNOSZ"))
# plength <- protein.length(colnames(PM90)[2:5])
# Cp_expt <- t(t(PM90[, 2:5]) / plength)
# matplot(PM90[, 1], Cp_expt, type = "p", pch = 19,
# xlab = axis.label("T"), ylab = axis.label("Cp0"), ylim = c(110, 280))
# for(i in 1:4) {
# pname <- colnames(Cp_expt)[i]
# aq <- subcrt(pname, "aq", T = seq(0, 150))$out[[1]]
# cr <- subcrt(pname, "cr", T = seq(0, 150))$out[[1]]
# lines(aq$T, aq$Cp / plength[i], col = i)
# lines(cr$T, cr$Cp / plength[i], col = i, lty = 2)
# }
# legend("right", legend = colnames(Cp_expt),
# col = 1:4, pch = 19, lty = 1, bty = "n", cex = 0.9)
# legend("bottomright", legend = c("experimental", "calculated (aq)",
# "calculated (cr)"), lty = c(NA, 1, 2), pch = c(19, NA, NA), bty = "n")
## ----protein_Cp, eval=FALSE, echo=-(1:5)--------------------------------------
# PM90 <- read.csv(system.file("extdata/cpetc/PM90.csv", package = "CHNOSZ"))
# plength <- protein.length(colnames(PM90)[2:5])
# Cp_expt <- t(t(PM90[, 2:5]) / plength)
# matplot(PM90[, 1], Cp_expt, type = "p", pch = 19,
# xlab = axis.label("T"), ylab = axis.label("Cp0"), ylim = c(110, 280))
# for(i in 1:4) {
# pname <- colnames(Cp_expt)[i]
# aq <- subcrt(pname, "aq", T = seq(0, 150))$out[[1]]
# cr <- subcrt(pname, "cr", T = seq(0, 150))$out[[1]]
# lines(aq$T, aq$Cp / plength[i], col = i)
# lines(cr$T, cr$Cp / plength[i], col = i, lty = 2)
# }
# legend("right", legend = colnames(Cp_expt),
# col = 1:4, pch = 19, lty = 1, bty = "n", cex = 0.9)
# legend("bottomright", legend = c("experimental", "calculated (aq)",
# "calculated (cr)"), lty = c(NA, 1, 2), pch = c(19, NA, NA), bty = "n")
## ----protein_ionization, fig.margin=TRUE, fig.width=4, fig.height=4, small.mar=TRUE, out.width="100%", echo=FALSE, results="hide", message=FALSE, fig.cap='Affinity of ionization of proteins. See [<span style="color:blue">demo(ionize)</span>](../demo) for ionization properties calculated as a function of temperature and pH.', cache=TRUE, pngquant=pngquant, timeit=timeit----
ip <- pinfo(c("CYC_BOVIN", "LYSC_CHICK", "MYG_PHYCA", "RNAS1_BOVIN"))
basis("CHNOS+")
a_ion <- affinity(pH = c(0, 14), iprotein = ip)
basis("CHNOS")
a_nonion <- affinity(iprotein = ip)
plot(c(0, 14), c(50, 300), xlab = "pH", ylab = quote(italic(A/2.303*RT)), type="n")
for(i in 1:4) {
A_ion <- as.numeric(a_ion$values[[i]])
A_nonion <- as.numeric(a_nonion$values[[i]])
lines(a_ion$vals[[1]], A_ion - A_nonion, col=i)
}
legend("topright", legend = a_ion$species$name,
col = 1:4, lty = 1, bty = "n", cex = 0.9)
## ----protein_ionization, eval=FALSE-------------------------------------------
# ip <- pinfo(c("CYC_BOVIN", "LYSC_CHICK", "MYG_PHYCA", "RNAS1_BOVIN"))
# basis("CHNOS+")
# a_ion <- affinity(pH = c(0, 14), iprotein = ip)
# basis("CHNOS")
# a_nonion <- affinity(iprotein = ip)
# plot(c(0, 14), c(50, 300), xlab = "pH", ylab = quote(italic(A/2.303*RT)), type="n")
# for(i in 1:4) {
# A_ion <- as.numeric(a_ion$values[[i]])
# A_nonion <- as.numeric(a_nonion$values[[i]])
# lines(a_ion$vals[[1]], A_ion - A_nonion, col=i)
# }
# legend("topright", legend = a_ion$species$name,
# col = 1:4, lty = 1, bty = "n", cex = 0.9)
## ----basis_CHNOS, echo=FALSE, results="hide"----------------------------------
basis("CHNOS")
## ----species_protein, results="hide", message=FALSE, echo=1:2-----------------
species(c("CYC_BOVIN", "LYSC_CHICK", "MYG_PHYCA", "RNAS1_BOVIN"))
a_nonion_species <- affinity()
## ----nonion_species_values----------------------------------------------------
unlist(a_nonion_species$values)
## ----nonion_values------------------------------------------------------------
unlist(a_nonion$values)
## ----rubisco_svg, echo=FALSE, results="hide", fig.margin=TRUE, fig.width=4, fig.height=4, small.mar=TRUE, out.width="100%", fig.ext='svg', custom.plot=TRUE, embed.tag=TRUE, fig.cap='Average oxidation state of carbon in Rubisco compared with optimal growth temperature of organisms. **This is an interactive image.** Move the mouse over the points to show the names of the organisms, and click to open a reference in a new window. (Made with [**RSVGTipsDevice**](https://cran.r-project.org/package=RSVGTipsDevice) using code that can be found in the source of this document.)'----
## copies the premade SVG image to the knitr figure path
file.copy("rubisco.svg", fig_path(".svg"))
## the code for making the SVG image -- not "live" in the vignette because RSVGTipsDevice isn't available on Windows
#if(require(RSVGTipsDevice)) {
# datfile <- system.file("extdata/cpetc/rubisco.csv", package = "CHNOSZ")
# fastafile <- system.file("extdata/protein/rubisco.fasta", package = "CHNOSZ")
# dat <- read.csv(datfile)
# aa <- read.fasta(fastafile)
# Topt <- (dat$T1 + dat$T2) / 2
# idat <- match(dat$ID, substr(aa$protein, 4, 9))
# aa <- aa[idat, ]
# ZC <- ZC(protein.formula(aa))
# pch <- match(dat$domain, c("E", "B", "A")) - 1
# col <- match(dat$domain, c("A", "B", "E")) + 1
# # because the tooltip titles in the SVG file are shown by recent browsers,
# # we do not need to draw the tooltips explicitly, so set toolTipMode=0
# devSVGTips("rubisco.svg", toolTipMode=0, title="Rubisco")
# par(cex=1.4)
# # unfortunately, plotmath can't be used with devSVGTips,
# # so axis labels here don't contain italics.
# plot(Topt, ZC, type="n", xlab="T, °C", ylab="ZC")
# n <- rep(1:9, 3)
# for(i in seq_along(Topt)) {
# # adjust cex to make the symbols look the same size
# cex <- ifelse(pch[i]==1, 2.5, 3.5)
# points(Topt[i], ZC[i], pch=pch[i], cex=cex, col=col[i])
# URL <- dat$URL[i]
# setSVGShapeURL(URL, target="_blank")
# setSVGShapeContents(paste0("<title>", dat$species[i], "</title>"))
# text(Topt[i], ZC[i], n[i], cex = 1.2)
# }
# abline(v = c(36, 63), lty = 2, col = "grey")
# legend("topright", legend = c("Archaea", "Bacteria", "Eukaryota"),
# pch = c(2, 1, 0), col = 2:4, cex=1.5, pt.cex = c(3, 2.3, 3), bty="n")
# dev.off()
#}
## ----rubisco_ZC, fig.keep="none", message=FALSE-------------------------------
datfile <- system.file("extdata/cpetc/rubisco.csv", package = "CHNOSZ")
fastafile <- system.file("extdata/protein/rubisco.fasta", package = "CHNOSZ")
dat <- read.csv(datfile)
aa <- read.fasta(fastafile)
Topt <- (dat$T1 + dat$T2) / 2
idat <- match(dat$ID, substr(aa$protein, 4, 9))
aa <- aa[idat, ]
ZC <- ZC(protein.formula(aa))
pch <- match(dat$domain, c("E", "B", "A")) - 1
col <- match(dat$domain, c("A", "B", "E")) + 1
plot(Topt, ZC, pch = pch, cex = 2, col = col,
xlab = expression(list(italic(T)[opt], degree*C)),
ylab = expression(italic(Z)[C]))
text(Topt, ZC, rep(1:9, 3), cex = 0.8)
abline(v = c(36, 63), lty = 2, col = "grey")
legend("topright", legend = c("Archaea", "Bacteria", "Eukaryota"),
pch = c(2, 1, 0), col = 2:4, pt.cex = 2)
## ----rubisco_O2, fig.margin=TRUE, fig.width=4, fig.height=4, small.mar=TRUE, out.width="100%", echo=FALSE, results="hide", message=FALSE, fig.cap="Elemental compositions of proteins projected into different sets of basis species.", cache=TRUE, pngquant=pngquant, timeit=timeit----
layout(matrix(1:4, nrow = 2))
par(mgp = c(1.8, 0.5, 0))
pl <- protein.length(aa)
ZClab <- axis.label("ZC")
nO2lab <- expression(bar(italic(n))[O[2]])
nH2Olab <- expression(bar(italic(n))[H[2]*O])
lapply(c("CHNOS", "QEC"), function(thisbasis) {
basis(thisbasis)
pb <- protein.basis(aa)
nO2 <- pb[, "O2"] / pl
plot(ZC, nO2, pch = pch, col = col, xlab = ZClab, ylab = nO2lab)
nH2O <- pb[, "H2O"] / pl
plot(ZC, nH2O, pch = pch, col = col, xlab = ZClab, ylab = nH2Olab)
mtext(thisbasis, font = 2)
})
## ----rubisco_O2, eval=FALSE---------------------------------------------------
# layout(matrix(1:4, nrow = 2))
# par(mgp = c(1.8, 0.5, 0))
# pl <- protein.length(aa)
# ZClab <- axis.label("ZC")
# nO2lab <- expression(bar(italic(n))[O[2]])
# nH2Olab <- expression(bar(italic(n))[H[2]*O])
# lapply(c("CHNOS", "QEC"), function(thisbasis) {
# basis(thisbasis)
# pb <- protein.basis(aa)
# nO2 <- pb[, "O2"] / pl
# plot(ZC, nO2, pch = pch, col = col, xlab = ZClab, ylab = nO2lab)
# nH2O <- pb[, "H2O"] / pl
# plot(ZC, nH2O, pch = pch, col = col, xlab = ZClab, ylab = nH2Olab)
# mtext(thisbasis, font = 2)
# })
## ----yeastgfp-----------------------------------------------------------------
protein <- c("YDL195W", "YHR098C", "YIL109C", "YLR208W", "YNL049C", "YPL085W")
abundance <- c(1840, 12200, NA, 21400, 1720, 358)
ina <- is.na(abundance)
## ----add_protein_yeast, message=FALSE-----------------------------------------
ip <- match(protein[!ina], thermo()$protein$protein)
## ----unitize------------------------------------------------------------------
pl <- protein.length(ip)
logact <- unitize(numeric(5), pl)
logabundance <- unitize(log10(abundance[!ina]), pl)
## ----yeastplot, eval=FALSE, echo=1:5------------------------------------------
# par(mfrow = c(1, 3))
# basis("CHNOS+")
# a <- affinity(O2 = c(-80, -73), iprotein = ip, loga.protein = logact)
# e <- equilibrate(a)
# diagram(e, ylim = c(-5, -2), col = 1:5, lwd = 2)
# e <- equilibrate(a, normalize = TRUE)
# diagram(e, ylim = c(-5, -2.5), col = 1:5, lwd = 2)
# abline(h = logabundance, lty = 1:5, col = 1:5)
## ----yeastplot, eval=FALSE, echo=6:8------------------------------------------
# par(mfrow = c(1, 3))
# basis("CHNOS+")
# a <- affinity(O2 = c(-80, -73), iprotein = ip, loga.protein = logact)
# e <- equilibrate(a)
# diagram(e, ylim = c(-5, -2), col = 1:5, lwd = 2)
# e <- equilibrate(a, normalize = TRUE)
# diagram(e, ylim = c(-5, -2.5), col = 1:5, lwd = 2)
# abline(h = logabundance, lty = 1:5, col = 1:5)
## ----yeastplot, fig.width=6, fig.height=2.5, dpi=hidpi, out.width="100%", echo=FALSE, message=FALSE, results="hide", cache=TRUE, fig.cap="ER-to-Golgi proteins: calculations without and with length normalization.", pngquant=pngquant, timeit=timeit----
par(mfrow = c(1, 3))
basis("CHNOS+")
a <- affinity(O2 = c(-80, -73), iprotein = ip, loga.protein = logact)
e <- equilibrate(a)
diagram(e, ylim = c(-5, -2), col = 1:5, lwd = 2)
e <- equilibrate(a, normalize = TRUE)
diagram(e, ylim = c(-5, -2.5), col = 1:5, lwd = 2)
abline(h = logabundance, lty = 1:5, col = 1:5)
## ----read_csv-----------------------------------------------------------------
file <- system.file("extdata/protein/POLG.csv", package = "CHNOSZ")
aa_POLG <- read.csv(file, as.is = TRUE, nrows = 5)
## ----read_fasta, message=FALSE------------------------------------------------
file <- system.file("extdata/protein/EF-Tu.aln", package = "CHNOSZ")
aa_Ef <- read.fasta(file, iseq = 1:2)
## ----seq2aa-------------------------------------------------------------------
aa_PRIO <- seq2aa("
MANLGCWMLVLFVATWSDLGLCKKRPKPGGWNTGGSRYPGQGSPGGNRYPPQGGGGWGQP
HGGGWGQPHGGGWGQPHGGGWGQPHGGGWGQGGGTHSQWNKPSKPKTNMKHMAGAAAAGA
VVGGLGGYMLGSAMSRPIIHFGSDYEDRYYRENMHRYPNQVYYRPMDEYSNQNNFVHDCV
NITIKQHTVTTTTKGENFTETDVKMMERVVEQMCITQYERESQAYYQRGSSMVLFSSPPV
ILLISFLIFLIVG
", "PRIO_HUMAN")
## ----protein_length-----------------------------------------------------------
myaa <- rbind(aa_Ef, aa_PRIO)
protein.length(myaa)
## ----thermo_refs_table, eval=FALSE--------------------------------------------
# thermo.refs() ## shows table in a browser
## ----width180, include=FALSE------------------------------------------------------------------------------------------------------------------------------------------------------
options(width = 180)
## ----thermo_refs_numeric----------------------------------------------------------------------------------------------------------------------------------------------------------
iATP <- info("ATP-4")
iMgATP <- info("MgATP-2")
thermo.refs(c(iATP, iMgATP))
## ----thermo_refs_character--------------------------------------------------------------------------------------------------------------------------------------------------------
thermo.refs(c("HDNB78", "MGN03"))
## ----thermo_refs_subcrt, message=FALSE--------------------------------------------------------------------------------------------------------------------------------------------
sres <- subcrt(c("C2H5OH", "O2", "CO2", "H2O"), c(-1, -3, 2, 3))
thermo.refs(sres)
## ----width80, include=FALSE---------------------------------------------------
options(width = 80)
## ----thermo_refs_browse, eval=FALSE-------------------------------------------
# iFo <- info("forsterite")
# ref <- thermo.refs(iFo)
# browseURL(ref$URL) ## opens a link to worldcat.org
## ----info_S3, results="hide"--------------------------------------------------
info(info("S3-"))
## ----check_OBIGT--------------------------------------------------------------
file <- system.file("extdata/adds/OBIGT_check.csv", package = "CHNOSZ")
dat <- read.csv(file, as.is = TRUE)
nrow(dat)
## ----citation_CHNOSZ, results="asis", echo = FALSE----------------------------
cref <- citation("CHNOSZ")
print(cref[1], style = "html")
## ----citation_multimetal, results="asis", echo = FALSE------------------------
print(cref[2], style = "html")
## ----maintainer_CHNOSZ--------------------------------------------------------
maintainer("CHNOSZ")
## ----file_edit_anintro, eval=FALSE--------------------------------------------
# file.edit(system.file("doc/anintro.Rmd", package = "CHNOSZ"))
## ----the_end------------------------------------------------------------------
###### ## ## ## ## ###### ##### #####
## ##===## ## \\## ## ## \\ //
###### ## ## ## ## ###### ##### #####
## ----sessionInfo--------------------------------------------------------------
sessionInfo()
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/doc/anintro.R
|
---
title: "An Introduction to CHNOSZ"
author: "Jeffrey M. Dick"
date: "`r Sys.Date()`"
output:
tufte::tufte_html:
tufte_features: ["background"]
toc: true
mathjax: null
tufte::tufte_handout:
citation_package: natbib
latex_engine: xelatex
tufte::tufte_book:
citation_package: natbib
latex_engine: xelatex
vignette: >
%\VignetteIndexEntry{An Introduction to CHNOSZ}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
bibliography: vig.bib
link-citations: yes
csl: elementa.csl
---
<style>
html {
font-size: 14px;
}
body {
font-family: ‘Times New Roman’, Times, serif;
}
li {
padding: 0.25rem 0;
}
/* zero margin around pre blocks (looks more like R console output) */
pre {
margin-top: 0;
margin-bottom: 0;
}
</style>
```{r options, include=FALSE}
options(width = 80)
options(digits = 6)
```
```{r HTML, include=FALSE}
## Some frequently used HTML expressions
logfO2 <- "log<i>f</i><sub>O<sub>2</sub></sub>"
# Use lowercase here because these tend to be variable names in the examples
zc <- "<i>Z</i><sub>C</sub>"
o2 <- "O<sub>2</sub>"
h2o <- "H<sub>2</sub>O"
sio2 <- "SiO<sub>2</sub>"
ch4 <- "CH<sub>4</sub>"
```
```{r setup, include=FALSE}
library(knitr)
## From "Tufte Handout" example dated 2016-12-27
# Invalidate cache when the tufte version changes
opts_chunk$set(tidy = FALSE, cache.extra = packageVersion('tufte'))
options(htmltools.dir.version = FALSE)
## Adjust plot margins
## First one from https://yihui.name/knitr/hooks/
knit_hooks$set(small.mar = function(before, options, envir) {
if (before) par(mar = c(4.2, 4.2, .1, .1)) # smaller margin on top and right
})
knit_hooks$set(tiny.mar = function(before, options, envir) {
if (before) par(mar = c(.1, .1, .1, .1)) # tiny margin all around
})
knit_hooks$set(smallish.mar = function(before, options, envir) {
if (before) par(mar = c(4.2, 4.2, 0.9, 0.9)) # smallish margins on top and right
})
## Use pngquant to optimize PNG images
knit_hooks$set(pngquant = hook_pngquant)
pngquant <- "--speed=1 --quality=0-25"
# pngquant isn't available on R-Forge ...
if (!nzchar(Sys.which("pngquant"))) pngquant <- NULL
# Set dpi 20231129
knitr::opts_chunk$set(
dpi = if(nzchar(Sys.getenv("CHNOSZ_BUILD_LARGE_VIGNETTES"))) 72 else 50
)
hidpi = if(nzchar(Sys.getenv("CHNOSZ_BUILD_LARGE_VIGNETTES"))) 100 else 50
## http://stackoverflow.com/questions/23852753/knitr-with-gridsvg
## Set up a chunk hook for manually saved plots.
knit_hooks$set(custom.plot = hook_plot_custom)
## Hook to change <img /> to <embed /> -- required for interactive SVG
hook_plot <- knit_hooks$get("plot")
knit_hooks$set(plot = function(x, options) {
x <- hook_plot(x, options)
if (!is.null(options$embed.tag) && options$embed.tag) x <- gsub("<img ", "<embed ", x)
x
})
## http://stackoverflow.com/questions/30530008/hook-to-time-knitr-chunks
now = Sys.time()
knit_hooks$set(timeit = function(before) {
if (before) { now <<- Sys.time() }
else {
paste("%", sprintf("Chunk rendering time: %s seconds.\n", round(Sys.time() - now, digits = 3)))
}
})
timeit <- NULL
## Colorize messages 20171031
## Adapted from https://gist.github.com/yihui/2629886#file-knitr-color-msg-rnw
color_block = function(color) {
function(x, options) sprintf('<pre style="color:%s">%s</pre>', color, x)
}
knit_hooks$set(warning = color_block('magenta'), error = color_block('red'), message = color_block('blue'))
```
# Overview
This vignette was made for version `r sessionInfo()$otherPkgs$CHNOSZ$Version` of CHNOSZ, a package for the [R software environment](https://www.r-project.org/).
For more information on R, see "[An Introduction to R](https://cran.r-project.org/manuals.html)" and the [contributed documentation](https://cran.r-project.org/other-docs.html) for R.
CHNOSZ has been developed since 2006 as a tool for thermodynamic calculations in geochemistry and compositional biology.
The package provides functions and a thermodynamic database that can be used to calculate the stoichiometric and energetic properties of reactions involving minerals and inorganic and/or organic aqueous species.
These functions also enable calculations of chemical affinities and metastable equilibrium distributions of proteins.
A major feature of the package is the production of diagrams to visualize the effects of changing temperature, pressure, and activities of basis species on the potential for reactions among various species.
## Installing and loading CHNOSZ
After starting R, install CHNOSZ by selecting the "Install packages from CRAN" or similar menu item in the R GUI or by using the following command:
```{r install_CHNOSZ, eval=FALSE}
install.packages("CHNOSZ")
```
Then load the CHNOSZ package to make its data and functions available in your R session:
```{r library_CHNOSZ}
library(CHNOSZ)
```
CHNOSZ is now ready to go with the default thermodynamic database and an empty system definition.
After running some calculations, you may want to "start over" with the default values.
To clear the system settings and restore the default thermodynamic database, use <span style="color:red">`reset()`</span>.
```{r reset}
reset()
```
Note: Throughout this document, syntax highlighting is applied to the *input* of the code chunks.
Double hash marks (`##`) precede the *output*, where black text denotes *results* and blue text is used for *messages*.
## Getting help
After CHNOSZ is installed, type <span style="color:blue">`help.start()`</span> to browse the R help documents, then choose "Packages" followed by "CHNOSZ".
That shows an index of the *manual* (help pages) for each function; many of the help pages include examples.
There are also links to the *demos* (longer examples) and *vignettes* (more in-depth documentation; this document is a vignette).
Suggestions for accessing the documentation are indicated here with <span style="color:blue">blue text</span>.
For example, read <span style="color:blue">``?`CHNOSZ-package` ``</span> to get an overview of the package and a list of features.
```{marginfigure}
"`?`" is a shortcut to R's `help()` function.
The command here is equivalent to <span style="color:blue">`help("CHNOSZ-package")`</span>.
```
## Organization of major functions
CHNOSZ is made up of a set of functions and supporting datasets.
The major components of the package are shown in the figure below, which is an updated version of the diagram in @Dic08.
Rectangles and ellipses represent functions and datasets; bold text indicates primary functions.
<!-- https://stackoverflow.com/questions/14675913/how-to-change-image-size-markdown -->
{ width=75% }
Many functions in CHNOSZ have no side effects.
That is, the function only returns a result; to use the result elsewhere, it can be assigned to a variable with `<-`.
In this document, the names of these functions are shown in <span style="color:green">green text</span> (not applicable to the code chunks).
```{marginfigure}
When they are mentioned, names of functions in the base and recommended packages of R are said to belong to R.
Example: Use R's `plot()` to plot the data.
```
Major functions without side effects in CHNOSZ are:
* <span style="color:green">`info()`</span>: search for species in the thermodynamic database;
* <span style="color:green">`subcrt()`</span>: calculate the thermodynamic properties of species and reactions;
* <span style="color:green">`affinity()`</span>: calculate the affinities of formation reactions using given chemical activities;
* <span style="color:green">`equilibrate()`</span>: calculate the equilibrium chemical activities of the species of interest;
* <span style="color:green">`diagram()`</span>: plot the results.
Some functions in CHNOSZ do have side effects: they modify the `thermo` data object in the current R session.
In this document, the names of these functions are shown in <span style="color:red">red text</span> (but not in the code chunks).
Major functions with side effects are:
* <span style="color:red">`basis()`</span>: set the basis species and their chemical activities;
* <span style="color:red">`species()`</span>: set the species of interest and their (non-equilibrium) chemical activities;
* <span style="color:red">`reset()`</span>: reset the database, restoring all settings to their default values.
The following pseudocode shows a common sequence of commands.
In actual usage, the `...` are replaced by arguments that define the chemical species and variables:
```{r pseudocode, eval=FALSE}
basis(...)
species(...)
a <- affinity(...)
e <- equilibrate(a) ## optional
diagram(e) ## or diagram(a)
reset() ## clear settings for next calculation
```
# Querying the thermodynamic database
## The <span style="color:green">`info()`</span> function
<span style="color:green">`info()`</span> provides an interface to the OBIGT thermodynamic database that is packaged with CHNOSZ.
Suppose you are interested in the thermodynamic properties of aqueous methane.
Because the database is assembled with aqueous species first, they take precedence over other states.
Searching by chemical formula alone gives the first matching species, in this case aqueous methane:
```{r info_CH4}
info("CH4")
```
The number that is returned is the species index in the database.
A second argument can be used to specify a physical state with lower precedence:
```{r info_CH4_gas}
info("CH4", "gas")
```
While some species are identified only by chemical formula, others have distinct names (in English) listed in the database.
For `r ch4` and inorganic substances that are represented by both gaseous and aqueous forms, the name is applied only to the gas.
However, the names of organic substances other than methane are applied to aqueous species, which have precedence, and those in other states.
The following commands get the species indices for some common gases:
```{r info_names_gas}
info("methane")
info("oxygen")
info("carbon dioxide")
```
A special case is sulfur; the name refers to both the native mineral, which has precedence, and the gas.
These two phases can be identifed with the formulas S<sub>2</sub> and S, respectively.
```{r info_S_S2}
info("S")
info("S2")
```
Taking the species number of aqueous methane returned by <span style="color:green">`info()`</span>, use the function again to retrieve the set of standard molal thermodynamic properties and equations of state parameters:
```{r iCH4, message=FALSE}
iCH4 <- info("CH4")
info(iCH4)
```
Liquid water is species number 1; it has NA entries in the database because dedicated functions are used to compute its properties:
```{r info_info_water}
info(info("water"))
```
## Fuzzy searches
Calling <span style="color:green">`info()`</span> with a string that does not exactly match the name of any species invokes a fuzzy search of the database:
```{r width180, include=FALSE}
options(width = 180)
```
```{r info_acid}
info("acid")
```
```{r width80, include=FALSE}
options(width = 80)
```
The message includes e.g. "uracil" and "metacinnabar" because their names have some similarity to the search term.
Since "ribose" is the name of a species in the database, to find species with similar names, add an extra character to the search:
```{r info_ribose}
info(" ribose")
```
The messages may be useful for browsing the database, but owing to their ambiguous results, these fuzzy searches return an `NA` value for the species index.
## Counting elements, chemical formulas, <span style="color:green">`ZC()`</span>
Continuing with the example of aqueous methane, let's look at its chemical formula:
```{r info_CH4_formula, message=FALSE}
info(iCH4)$formula
```
We can use <span style="color:green">`makeup()`</span> to count the elements in the formula, followed by <span style="color:green">`as.chemical.formula()`</span> to rewrite the formula on one line:
```{r makeup_iCH4}
makeup(iCH4)
as.chemical.formula(makeup(iCH4))
```
For organic species, a calculation of the average oxidation state of carbon (`r zc`) is possible given the species index, chemical formula, or elemental count:
```{r ZC_iCH4, message=FALSE}
ZC(iCH4)
ZC(info(iCH4)$formula)
ZC(makeup(iCH4))
```
# Calculating thermodynamic properties
To calculate the standard molal properties of species and reactions, use <span style="color:green">`subcrt()`</span>.
The name of this function is derived from the SUPCRT package [@JOH92], which is also the source of the Fortran subroutine used to calculate the thermodynamic properties of H<sub>2</sub>O.
If no reaction coefficients are given, <span style="color:green">`subcrt()`</span> calculates the standard molal properties of individual species:
```{r subcrt_water}
subcrt("water")
```
That uses the default temperature and pressure settings, i.e. equally spaced temperature intervals from 0 to 350 °C at *P*<sub>sat</sub>, i.e. 1 bar below 100 °C, or the pressure of liquid-vapor saturation (i.e. boiling) at higher temperatures.
The columns in the output are temperature, pressure, density of water, logarithm of the equilibrium constant (only meaningful for reactions; [see below](#properties-of-reactions)), standard molal Gibbs energy and enthalpy of formation from the elements, standard molal entropy, volume, and heat capacity.
```{marginfigure}
The corresponding units are °C (`T`), bar (`P`), g cm<sup>-3</sup> (`rho`), cal mol<sup>-1</sup> (`G` and `H`), cal K<sup>-1</sup> mol<sup>-1</sup> (`S` and `Cp`), and cm<sup>3</sup> mol<sup>-1</sup> (`V`).
```
A custom temperature-pressure grid can be specified.
Here, we calculate the properties of `r h2o` on a *T*, *P* grid in the supercritical region, with conditions grouped by pressure:
```{r subcrt_water_grid}
subcrt("water", T = c(400, 500, 600), P = c(200, 400, 600), grid = "P")$out$water
```
```{r subcrt_water_plot, fig.margin=TRUE, fig.width=4, fig.height=4, small.mar=TRUE, out.width="100%", echo=FALSE, message=FALSE, fig.cap="Isothermal contours of density (g cm<sup>-3</sup>) and pressure (bar) of water.", cache=TRUE, pngquant=pngquant, timeit=timeit}
sres <- subcrt("water", T=seq(0,1000,100), P=c(NA, seq(1,500,1)), grid="T")
water <- sres$out$water
plot(water$P, water$rho, type = "l")
```
The additional operations (`$out$water`) are used to extract a specific part of the results; this can be used with e.g. R's `write.table()` or `plot()` for further processing:
```{r subcrt_water_plot, eval=FALSE}
```
## Changing units
The default units of temperature, pressure, and energy in the input and output of <span style="color:green">`subcrt()`</span> are °C, bar, and Joules.
The functions <span style="color:red">`T.units()`</span>, <span style="color:red">`P.units()`</span>, and <span style="color:red">`E.units()`</span> can be used to change the units used by <span style="color:green">`subcrt()`</span> and some other functions in CHNOSZ.
What is the Gibbs energy in J/mol (the default) and cal/mol of aqueous methane at 298.15 K and 0.1 MPa?
```{r units_CH4}
T.units("K")
P.units("MPa")
subcrt("CH4", T = 298.15, P = 0.1)$out$CH4$G
E.units("cal")
subcrt("CH4", T = 298.15, P = 0.1)$out$CH4$G
```
The parameters for each species in the OBIGT database have the units indicated by the `E_units` column there, which is independent of the setting of <span style="color:red">`E.units()`</span>.
Unlike <span style="color:green">`subcrt()`</span>, <span style="color:green">`info()`</span> always displays the database values in the units given in the database.
A separate function, <span style="color:green">`convert()`</span>, can be used to convert values to selected units.
The following code shows that the database parameters for CH<sub>4</sub>(aq) are in calories, then converts the standard Gibbs energy from cal/mol to J/mol.
```{r convert_G, message=FALSE}
(CH4dat <- info(info("CH4")))
convert(CH4dat$G, "J")
```
Note that converting the database value to J/mol gives the same result as running `subcrt("CH4", T = 25)` with the default <span style="color:red">`E.units()`</span> setting of J.
Use <span style="color:red">`reset()`</span> to restore the units and all other settings for CHNOSZ to their defaults:
```{r reset}
```
# Properties of reactions
## Reaction definitions
To calculate the thermodynamic properties of reactions, give the names of species, the physical states (optional), and reaction coefficients as the arguments to <span style="color:green">`subcrt()`</span>.
Here we calculate properties for the dissolution of CO<sub>2</sub>.
This doesn't correspond to the _solubility_ of CO<sub>2</sub>; see the [solubility section](#complete-equilibrium-solubility) in this vignette and [<span style="color:blue">`demo(solubility)`</span>](../demo) for examples of solubility calculations.
```{r subcrt_CO2}
subcrt(c("CO2", "CO2"), c("gas", "aq"), c(-1, 1), T = seq(0, 250, 50))
```
In order to make a plot like Figure 18 of @MSS13, let's run more calculations and store the results.
In addition to the reaction definition, we specify a greater number of temperature points than the default:
```{r CO2_logK, echo=FALSE, message=FALSE}
T <- seq(0, 350, 10)
CO2 <- subcrt(c("CO2", "CO2"), c("gas", "aq"), c(-1, 1), T = T)$out$logK
CO <- subcrt(c("CO", "CO"), c("gas", "aq"), c(-1, 1), T = T)$out$logK
CH4 <- subcrt(c("CH4", "CH4"), c("gas", "aq"), c(-1, 1), T = T)$out$logK
logK <- data.frame(T, CO2, CO, CH4)
```
```{r CO2_plot, fig.margin=TRUE, fig.width=4, fig.height=4, small.mar=TRUE, out.width="100%", echo=FALSE, message=FALSE, fig.cap="Calculated equilibrium constants for dissolution of CO<sub>2</sub>, CO, and CH<sub>4</sub>.", cache=TRUE, pngquant=pngquant, timeit=timeit}
matplot(logK[, 1], logK[, -1], type = "l", col = 1, lty = 1,
xlab = axis.label("T"), ylab = axis.label("logK"))
text(80, -1.7, expr.species("CO2"))
text(240, -2.37, expr.species("CO"))
text(300, -2.57, expr.species("CH4"))
```
```{r CO2_logK, eval=FALSE}
```
Now we can make the plot, using R's `matplot()`.
Here, <span style="color:green">`axis.label()`</span> and <span style="color:green">`expr.species()`</span> are used to create formatted axis labels and chemical formulas:
```{r CO2_plot, eval=FALSE}
```
## Unbalanced reactions
A balanced chemical reaction conserves mass.
<span style="color:green">`subcrt()`</span> won't stop you from running an unbalanced reaction, but it will give you a warning:
```{r subcrt_unbalanced, results="hide"}
subcrt(c("CO2", "CH4"), c(-1, 1))
```
In other words, to balance the reaction, we should add 4 H to the left and 2 O to the right.
That could be done manually be redefining the reaction with the appropriate species.
There is another option: balancing the reaction automatically using basis species.
## Setting the basis species
_Basis species_ are a minimal number of chemical species that linearly combine to give the composition of any species in the system.
The basis species are similar to thermodynamic components, but can include charged species.
Basis species are used in CHNOSZ to automatically balance reactions; they are also required for making chemical activity diagrams.
Let's start with an example that doesn't work:
```{r basis_singular, error=TRUE}
basis(c("CO2", "H2", "H2CO2"))
```
That set of species has a singular (non-invertible) stoichiometric matrix.
An error would also result from either an underdetermined or overdetermined system.
A valid set of basis species has an invertible stoichiometric matrix and the same number of species as elements:
```{r basis_CHO}
basis(c("CO2", "H2", "H2O"))
```
The composition of any species made up of C, H, and O can be represented by a single linear combination of these basis species.
## Automatically balancing reactions
Methanogenic metabolism in reducing environments may proceed by acetoclastic or hydrogenotrophic processes.
To consider reactions involving a charged species (acetate), let's define a basis with H<sup>+</sup>:
```{r basis_CHOZ}
basis(c("CO2", "H2", "H2O", "H+"))
```
By identifying species *other than* the basis species, the reactions will be automatically balanced.
This produces the balanced reaction for acetoclastic methanogenesis:
```{r subcrt_acetoclastic, message=FALSE}
subcrt(c("acetate", "CH4"), c(-1, 1))$reaction
```
We can similarly consider reactions for hydrogenotrophic methanogenesis as well as acetate oxidation (without production of methane):
```{r subcrt_methanogenesis, message=FALSE}
acetate_oxidation <- subcrt("acetate", -1)
hydrogenotrophic <- subcrt("CH4", 1)
acetoclastic <- subcrt(c("acetate", "CH4"), c(-1, 1))
```
Use <span style="color:green">`describe.reaction()`</span> to write the reactions on a plot:
```{r describe_reaction_plot, fig.margin=TRUE, fig.width=3.5, fig.height=1.8, tiny.mar=TRUE, out.width="100%", pngquant=pngquant, timeit=timeit}
plot(0, 0, type = "n", axes = FALSE, ann=FALSE, xlim=c(0, 5), ylim=c(5.2, -0.2))
text(0, 0, "acetoclastic methanogenesis", adj = 0)
text(5, 1, describe.reaction(acetoclastic$reaction), adj = 1)
text(0, 2, "acetate oxidation", adj = 0)
text(5, 3, describe.reaction(acetate_oxidation$reaction), adj = 1)
text(0, 4, "hydrogenotrophic methanogenesis", adj = 0)
text(5, 5, describe.reaction(hydrogenotrophic$reaction), adj = 1)
```
## Chemical affinity
Usually, <span style="color:green">`subcrt()`</span> returns only standard state thermodynamic properties.
```{marginfigure}
The standard state adopted for H<sub>2</sub>O is unit activity of the pure component at any *T* and *P*.
The standard state for aqueous species is unit activity of a hypothetical one molal solution referenced to infinite dilution at any *T* and *P*.
```
Thermodynamic models often consider a non-standard state (i.e. non-unit activity).
The activities of basis species can be modified with <span style="color:red">`basis()`</span>, and those of the other species using the `logact` argument in <span style="color:green">`subcrt()`</span>.
Let us calculate the chemical affinity of acetoclastic methanogenesis.
```{marginfigure}
The affinity is equal to the negative of the overall (non-standard) Gibbs energy change of the reaction.
```
We change the states of CO<sub>2</sub> and H<sub>2</sub> in the basis from `aq` (aqueous) to `gas`, and set the logarithm of fugacity of gaseous H<sub>2</sub> and the pH, using values from @MDS_13.
The activity of acetate and fugacity of methane, as well as temperature and pressure, are set in the call to <span style="color:green">`subcrt()`</span>:
```{r basis_mayumi, message=FALSE, results="hide"}
basis(c("CO2", "H2", "H2O", "H+"))
basis(c("CO2", "H2"), "gas")
basis(c("H2", "pH"), c(-3.92, 7.3))
```
```{r affinity_acetoclastic, message=FALSE}
subcrt(c("acetate", "CH4"), c(-1, 1),
c("aq", "gas"), logact = c(-3.4, -0.18), T = 55, P = 50)$out
```
The new `A` column shows the affinity; the other columns are unaffected and still show the standard-state properties.
Let's repeat the calculation for hydrogenotrophic methanogenesis.
```{r affinity_hydrogenotrophic, message=FALSE}
subcrt("CH4", 1, "gas", logact = -0.18, T = 55, P = 50)$out
```
Under the specified conditions, the affinities of hydrogenotrophic and acetoclastic methanogenesis are somewhat greater than and less than 20 kJ, respectively.
This result matches Figure 4b in Mayumi et al. (2013) at unit fugacity of CO<sub>2</sub>.
We can go even further and reproduce their plot.
```{marginfigure}
The reproduction is not identical, owing to differences of thermodynamic data and of calculations of the effects of temperature and pressure.
```
To make the code neater, we write a function that can run any of the reactions:
```{r rxnfun, message=FALSE}
rxnfun <- function(coeffs) {
subcrt(c("acetate", "CH4"), coeffs,
c("aq", "gas"), logact = c(-3.4, -0.18), T = 55, P = 50)$out
}
```
Now we're ready to calculate and plot the affinities.
Here, we use R's `lapply()` to list the results at two values of logarithm of fugacity of CO<sub>2</sub>.
We insert an empty reaction to get a line at zero affinity.
R's `do.call()` and `rbind()` are used to turn the list into a data frame that can be plotted with R's `matplot()`.
There, we plot the negative affinities, equal to Gibbs energy, as shown in the plot of Mayumi et al. (2013).
```{r methanogenesis_plot, fig.margin=TRUE, fig.width=4.1, fig.height=4.1, small.mar=TRUE, out.width="100%", echo=FALSE, message=FALSE, fig.cap="Gibbs energies of acetate oxidation and methanogenesis (after Mayumi et al., 2013).", cache=TRUE, pngquant=pngquant, timeit=timeit}
Adat <- lapply(c(-3, 3), function(logfCO2) {
basis("CO2", logfCO2)
data.frame(logfCO2,
rxnfun(c(0, 0))$A,
rxnfun(c(-1, 0))$A,
rxnfun(c(-1, 1))$A,
rxnfun(c(0, 1))$A
)
})
Adat <- do.call(rbind, Adat)
matplot(Adat[, 1], -Adat[, -1]/1000, type = "l", lty = 1, lwd = 2,
xlab = axis.label("CO2"), ylab = axis.label("DG", prefix = "k"))
legend("topleft", c("acetate oxidation", "acetoclastic methanogenesis",
"hydrogenotrophic methanogenesis"), lty = 1, col = 2:4)
```
```{r methanogenesis_plot, eval=FALSE}
```
Let's not forget to clear the system settings, which were modified by <span style="color:red">`basis()`</span>, before running other calculations:
```{r reset, message=FALSE}
```
# Using <span style="color:green">`affinity()`</span>
<span style="color:green">`affinity()`</span> offers calculations of chemical affinity of formation reactions over a configurable range of *T*, *P*, and activities of basis species.
## From affinity to diagrams
By *formation reaction* is meant the stoichiometric requirements for formation of one mole of any species from the basis species.
The <span style="color:red">`species()`</span> function is used to set these *formed species*.
Let's consider the stoichiometry of some aqueous sulfur-bearing species.
Here we use <span style="color:red">`basis()`</span> with a keyword to load a preset basis definition.
To use Eh as a variable, the electron (*e*<sup>-</sup>) should be in the basis, so we use the keyword (<span style="color:red">`basis("CHNOSe")`</span>).
```{marginfigure}
Some available keywords are `CHNOS` (including CO<sub>2</sub>, H<sub>2</sub>O, NH<sub>3</sub>, H<sub>2</sub>S, and O<sub>2</sub>), `CHNOS+` (also including H<sup>+</sup>), and `CHNOSe` (including H<sup>+</sup>, and *e*<sup>-</sup> instead of O<sub>2</sub>).
See <span style="color:blue">`?basis`</span> for more options.
```
```{marginfigure}
What is `SO42-`? Is it 1 S, 4 O, and 2 negative charges, or 1 S, 42 O, and 1 negative charge?
The ambiguity of a digit that could belong to the coefficient for the following charge or to that for the preceding element is why formulas in CHNOSZ are written with the number of charges after the + or - symbol.
`SO4-2` is unambiguously parsed as 1 S, 4 O and 2 negative charges.
```
```{r basis_CHNOSZ, results="hide"}
basis("CHNOSe")
```
```{r species_sulfur}
species(c("H2S", "HS-", "HSO4-", "SO4-2"))
```
Aqueous species are assigned default activities of 10<sup>-3</sup> (`logact` is -3).
Now, we can use <span style="color:green">`affinity()`</span> to calculate the affinities of the formation reactions of each of the species.
R's `unlist()` is used here to turn the list of values of affinity into a numeric object that can be printed in a couple of lines (note that the names correspond to `ispecies` above):
```{r affinity}
unlist(affinity()$values)
```
The values returned by <span style="color:green">`affinity()`</span> are dimensionless, i.e. *A*/(2.303*RT*).
Although <span style="color:green">`subcrt()`</span> can also calculate affinities (in units of cal/mol or J/mol), the main advantage of <span style="color:green">`affinity()`</span> is that it can perform calculations on an arbitrary grid of *T*, *P*, or activities of basis species.
This is the foundation for making many types of diagrams that are useful in geochemistry.
Given the values of affinity, the <span style="color:green">`diagram()`</span> function identifies the species that has the maximum affinity at each grid point.
The result is equivalent to a "predominance diagram" [@Dic19], where the fields represent the predominant aqueous species and the boundaries are equal-activity lines.
If both aqueous species and minerals are present, it is common practice to assign a constant activity to all aqueous species and unit activity (i.e. log activity = 0) for minerals.
More sophisticated diagrams can be made by showing the solubility contours of a metal on the diagram; see [<span style="color:blue">`demo(contour)`</span>](../demo) for an example.
```{r EhpH_plot, fig.margin=TRUE, fig.width=4, fig.height=4, out.width="100%", echo = FALSE, message=FALSE, cache=TRUE, fig.cap="Aqueous sulfur species at 25 °C.", pngquant=pngquant, timeit=timeit}
a <- affinity(pH = c(0, 12), Eh = c(-0.5, 1))
diagram(a, limit.water = TRUE)
```
Let's use <span style="color:green">`diagram()`</span> to make a simple Eh-pH diagram for aqueous species in the system S-O-H.
After running the <span style="color:red">`basis()`</span> and <span style="color:red">`species()`</span> commands above, we can calculate the affinities on an Eh-pH grid.
With the default settings in <span style="color:green">`diagram()`</span>, areas beyond the stability limits of water are colored gray.
This can be changed by setting the `limit.water` argument to FALSE (to not show the stability region of water) or TRUE (to plot the main diagram only in the stable region of water).
The names of species that can be parsed as chemical formulas are formatted with subscripts and superscripts; if this is not desired, set `format.names = FALSE`.
```{r EhpH_plot, echo=TRUE, eval=FALSE}
```
```{r EhpH_plot_color, fig.margin=TRUE, fig.width=4, fig.height=4, smallish.mar=TRUE, out.width="100%", echo=FALSE, message=FALSE, cache=TRUE, fig.cap="The same plot, with different colors and labels.", pngquant=pngquant, timeit=timeit}
diagram(a, fill = "terrain", lwd = 2, lty = 3,
names = c("hydrogen sulfide", "bisulfide", "bisulfate", "sulfate"),
las = 0)
water.lines(a, col = 6, lwd = 2)
```
Other arguments in <span style="color:green">`diagram()`</span> can be used to control the line type (`lty`), width (`lwd`), and color (`col`), field colors (`fill`), and species labels (`name`).
Additional arguments are passed to R's plotting functions; here, we use `las` to change the orientation of axes labels.
Another function, <span style="color:green">`water.lines()`</span>, can be used to draw lines at the water stability limits:
```{r EhpH_plot_color, echo=TRUE, eval=FALSE}
```
See the demos in the package for other examples of Eh-pH diagrams.
In particular, [<span style="color:blue">`demo(Pourbaix)`</span>](../demo) shows how to plot the concentrations of metals as equisolubility (or isosolubility) lines on Eh-pH diagrams [@Pou74].
Mineral stability diagrams often depict activity ratios, e.g. log (*a*<sub>Ca<sup>+2</sup></sub>/*a*<sub>H<sup>+</sup></sub><sup>2</sup>), on one or both axes.
The variables used for potential calculations in CHNOSZ include only a single chemical activity, e.g. log *a*<sub>Ca<sup>+2</sup></sub>.
However, you can set pH = 0 to generate diagrams that are geometrically equivalent to those calculated using activity ratios, and use <span style="color:green">`ratlab()`</span> to make the axes labels for the ratios.
Moreover, <span style="color:green">`diagram()`</span> has a "saturation" option that can be used to draw saturation limits for minerals that do not contain the conserved basis species.
See [<span style="color:blue">`demo(saturation)`</span>](../demo) for an example that uses activity ratios on the axes and plots saturation limits for calcite, magnesite, dolomite, and brucite on a diagram for the H<sub>2</sub>O–CO<sub>2</sub>–CaO–MgO–SiO<sub>2</sub> system.
That demo can be used as a template to produce a wide range of diagrams similar to those in @BJH84.
## Retrieving species in a chemical system
Most of the diagrams in this vignette are made by giving the names of all the species.
However, it can be tedious to find all the species by manually searching the OBIGT database.
The <span style="color:green">`retrieve()`</span> function can be used to identify the available species that contain particular chemical elements.
For example, to get Mn-bearing aqueous species and minerals including the single element, oxides and oxyhydroxides, use this:
```{r retrieve}
retrieve("Mn", c("O", "H"), "aq")
retrieve("Mn", c("O", "H"), "cr")
```
Below, these commands are used to identify the species in an Eh-pH diagram for the Mn-O-H system at 100 °C.
This diagram includes Mn oxides (pyrolusite, bixbyite, hausmannite), Mn(OH)<sub>2</sub>, and aqueous Mn species.
```{r retrieve_diagram, fig.margin=TRUE, fig.width=5, fig.height=5, out.width="100%", message=FALSE, results = "hide", cache=TRUE, fig.cap="Eh-pH diagram for the Mn-O-H system.", pngquant=pngquant, timeit=timeit}
# Set decimal logarithm of activity of aqueous species,
# temperature and plot resolution
logact <- -4
T <- 100
res <- 400
# Start with the aqueous species
basis(c("Mn+2", "H2O", "H+", "e-"))
iaq <- retrieve("Mn", c("O", "H"), "aq")
species(iaq, logact)
aaq <- affinity(pH = c(4, 16, res), Eh = c(-1.5, 1.5, res), T = T)
# Show names for only the metastable species here
names <- names(iaq)
names[!names(iaq) %in% c("MnOH+", "MnO", "HMnO2-")] <- ""
diagram(aaq, lty = 2, col = "#4169E188", names = names, col.names = 4)
# Overlay mineral stability fields
icr <- retrieve("Mn", c("O", "H"), "cr")
species(icr, add = TRUE)
# Supply the previous result from affinity() to use
# argument recall (for plotted variables and T)
acr <- affinity(aaq)
diagram(acr, add = TRUE, bold = acr$species$state=="cr", limit.water = FALSE)
# Add legend
legend <- c(
bquote(log * italic(a)["Mn(aq)"] == .(logact)),
bquote(italic(T) == .(T) ~ degree*C)
)
legend("topright", legend = as.expression(legend), bty = "n")
```
This introductory vignette shows examples for diagrams with a single metal.
Other functions are available to make diagrams for multiple metals; see the vignette [<span style="color:blue">*Diagrams with multiple metals*</span>](multi-metal.html) for more information.
## Mosaic diagrams
If sulfur is an element in the basis species, then we should consider that its speciation is sensitive to Eh and pH, as shown in a previous diagram.
Mosaic diagrams account for speciation of the basis species and are useful for visualizing the stabilities of many types of minerals including oxides, sulfides, and carbonates.
These diagrams are made by constructing individual diagrams for the possible basis species.
The individual diagrams are then combined, each one contributing to the final diagram only in the range of stability of the corresponding basis species.
Let's use <span style="color:green">`mosaic()`</span> to make a diagram for aqueous species and minerals in the Cu-S-Cl-`r h2o` system.
To know what aqueous copper chloride complexes are available in the database, we can use a fuzzy search:
```{r info_CuCl, results="hide"}
info(" CuCl")
```
Next we define the basis, and set the activities of the H<sub>2</sub>S and Cl<sup>-</sup> basis species.
These represent the total activity of S and Cl in the system, which are distributed among the minerals and aqueous species.
Aqueous copper chloride complexes and four minerals are added.
Be sure to include `add = TRUE` in the second call to <span style="color:red">`species()`</span>; otherwise, the minerals would simply replace the previously added aqueous species.
```{r copper_setup, echo=TRUE, results="hide"}
basis(c("Cu", "H2S", "Cl-", "H2O", "H+", "e-"))
basis("H2S", -6)
basis("Cl-", -0.7)
species(c("CuCl", "CuCl2-", "CuCl3-2", "CuCl+", "CuCl2", "CuCl3-", "CuCl4-2"))
species(c("chalcocite", "tenorite", "cuprite", "copper"), add = TRUE)
```
Note that chalcocite (Cu<sub>2</sub>S) undergoes polymorphic transitions.
To get the temperatures of the polymorphic transitions from `thermo()$OBIGT` (in Kelvin, regardless of the <span style="color:red">`T.units()`</span>), we can use <span style="color:green">`info()`</span>.
We see that at 200 °C (473.15 K) the second phase is stable; this one is automatially used by CHNOSZ for this diagram.
```{r info_chalcocite, message=FALSE}
info(info("chalcocite", c("cr", "cr2", "cr3")))$T
```
We use <span style="color:green">`mosaic()`</span> to generate and combine diagrams for each candidate basis species (H<sub>2</sub>S, HS<sup>-</sup>, HSO<sub>4</sub><sup>-</sup>, or SO<sub>4</sub><sup>-2</sup>) as a function of Eh and pH.
The key argument is `bases`, which identifies the candidate basis species, starting with the one in the current basis.
The other arguments, like those of <span style="color:green">`affinity()`</span>, specify the ranges of the variables; `res` indicates the grid resolution to use for each variable (the default is 256).
The first call to <span style="color:green">`diagram()`</span> plots the species of interest; the second adds the predominance fields of the basis species.
We also use <span style="color:green">`water.lines()`</span> to draw dashed blue lines at the water stability limits:
```{r copper_mosaic, fig.margin=TRUE, fig.width=4, fig.height=4, out.width="100%", message=FALSE, cache=TRUE, fig.cap="Copper minerals and aqueous complexes with chloride, 200 °C.", pngquant=pngquant, timeit=timeit}
T <- 200
res <- 200
bases <- c("H2S", "HS-", "HSO4-", "SO4-2")
m1 <- mosaic(bases, pH = c(0, 12, res), Eh=c(-1.2, 0.75, res), T=T)
diagram(m1$A.species, lwd = 2)
diagram(m1$A.bases, add = TRUE, col = 4, col.names = 4, lty = 3,
italic = TRUE)
water.lines(m1$A.species, col = "blue1")
```
The diagrams are combined according to the relative abundances of the different possible basis species listed in `bases` along with a term for the Gibbs energy of mixing (see <span style="color:blue">`?mosaic`</span>).
The smooth transitions between basis species can result in curved field boundaries, in this case around the chalcocite field.
If we added the argument `blend = FALSE`, the diagrams would instead be assembled using the single predominant basis species at any point on the Eh-pH grid, and all of the line segments would be straight.
The reactions used to make this diagram are balanced on Cu, so that no Cu appears in reactions between any two other species (minerals or aqueous species).
If <span style="color:green">`diagram()`</span> is run with `balance = 1`, then the reactions are balanced on formula units.
That is, one mole of the mineral formulas appears on each side of the reaction, with the possibility of Cu appearing as an additional species to conserve the elements.
This may be problematic, as Cu would be be present in some reactions in Eh-pH space where it is not a stable phase.
However, it is common in low-temperature aqueous geochemical calculations to "turn off" particular redox reactions that are not thought to attain equilibrium, so decoupling a species from equilibrium may be justified in some circumstances.
Changing the balance to 1 results in the loss of the tenorite stability field and extension of chalcocite stability to lower pH, as shown in Figure 5a of @CPCC17.
## *T*, *P*, activity transects
Above, we used evenly-spaced grids of chemical activities of basis species; the ranges of variables were given by two or three values (minimum, maximum, and optionally resolution).
<span style="color:green">`affinity()`</span> can also perform calculations along a transect, i.e. a particular path along one or more variables.
A transect is calculated when there are four or more values assigned to the variable(s).
Let's use this feature to calculate affinities (negative Gibbs energies) of methanogenesis and biosynthetic reactions in a hydrothermal system.
Some results of mixing calculations for seawater and vent fluid from the Rainbow hydrothermal field, calculated using EQ3/6 by @SC10, are included in a data file in CHNOSZ.
Reading the file with R's `read.csv()`, we set `check.names = FALSE` to preserve the `NH4+` column name (which is not a syntactically valid variable name):
```{r rainbow_data}
file <- system.file("extdata/cpetc/SC10_Rainbow.csv", package = "CHNOSZ")
rb <- read.csv(file, check.names = FALSE)
```
We take a selection of the species from Shock and Canovas (2010) with activities equal to 10<sup>-6</sup>; aqueous `r ch4` is assigned an activity of 10<sup>-3</sup>.
We will write the synthesis reactions of organic species in terms of these basis species:
```{marginfigure}
The constant activity of CH<sub>4</sub> is a simplification of the calculation reported by Shock and Canovas (2010).
The code here could be expanded to vary the activity of CH<sub>4</sub>.
```
```{r rainbow_species, results="hide"}
basis(c("CO2", "H2", "NH4+", "H2O", "H2S", "H+"))
species("CH4", -3)
species(c("adenine", "cytosine", "aspartic acid", "deoxyribose",
"CH4", "leucine", "tryptophan", "n-nonanoic acid"), -6)
```
Now we can calculate affinities along the transect of changing temperature and activities of five basis species.
Each variable is given as a named argument; `NH4+` must be quoted.
```{marginfigure}
A shorter expression would use R's `do.call()` to construct the function call: `do.call(`<span style="color:green">`affinity`</span>`, as.list(rb))`.
```
```{marginfigure}
The target of the conversion is `G`, or free energy, from `logK`.
That conversion requires temperature in Kelvin, which is obtained by conversion from °C.
We finish with a negation (affinity is negative Gibbs energy) and scaling from cal to kcal.
```
Using R's `lapply()` to run <span style="color:green">`convert()`</span> for each species, we first convert the affinity from dimensionless values (*A*/(2.303*RT*)) to J/mol.
A second call to <span style="color:green">`convert()`</span> is used to obtain energies in cal/mol, and these are finally converted to kcal/mol.
```{r rainbow_affinity, message=FALSE}
a <- affinity(T = rb$T, CO2 = rb$CO2, H2 = rb$H2,
`NH4+` = rb$`NH4+`, H2S = rb$H2S, pH = rb$pH)
T <- convert(a$vals[[1]], "K")
a$values <- lapply(a$values, convert, "G", T)
a$values <- lapply(a$values, convert, "cal")
a$values <- lapply(a$values, `*`, -0.001)
```
```{r rainbow_diagram, fig.margin=TRUE, fig.width=4, fig.height=4, out.width="100%", echo=FALSE, message=FALSE, cache=TRUE, fig.cap="Affinities of organic synthesis in a hydrothermal system, after Shock and Canovas (2010).", pngquant=pngquant, timeit=timeit}
diagram(a, balance = 1, ylim = c(-100, 100), ylab = quote(italic(A)*", kcal/mol"),
col = rainbow(8), lwd = 2, bg = "slategray3")
abline(h = 0, lty = 2, lwd = 2)
```
Finally, we use <span style="color:green">`diagram()`</span> to plot the results.
Although only temperature is shown on the *x* axis, pH and the activities of CO<sub>2</sub>, H<sub>2</sub>, NH<sub>4</sub><sup>+</sup>, and H<sub>2</sub>S are also varied according to the data in `rb`.
By default, <span style="color:green">`diagram()`</span> attempts to scale the affinities by dividing by the reaction coefficients of a shared basis species (in this case, CO<sub>2</sub>).
To override that behavior, we set `balance = 1` to plot the affinities of the formation reactions as written (per mole of the product species).
```{r rainbow_diagram, eval=FALSE}
```
When making line plots, <span style="color:green">`diagram()`</span> automatically places the labels near the lines.
The additional arguments `adj` and `dy` can be used to fine-tune the positions of the labels (they are used in a couple of examples below).
If labeling of the lines is not desired, add e.g. `legend.x = "topright"` to make a legend instead, or `names = FALSE` to prevent any plotting of the names.
## Buffers
There is one other feature of <span style="color:green">`affinity()`</span> that can be mentioned here.
Can we go the other direction: calculate the activities of basis species from the activities of the species of interest?
This question relates to the concept of chemical activity buffers.
In CHNOSZ there are two ways to perform buffer calculations:
1. Assign the name of a buffer (listed in `thermo()$buffer`) to the basis species:
* more versatile (multiple activities can be buffered, e.g. both S<sub>2</sub> and O<sub>2</sub> by pyrite-pyrrhotite-magnetite);
* the buffers are active in calculations of affinity of other species;
* use <span style="color:red">`mod.buffer()`</span> to change or add buffers in `thermo()$buffer`;
* [<span style="color:blue">`demo(buffer)`</span>](../demo) uses it for mineral buffers (solid lines).
2. Use the `type` argument of <span style="color:green">`diagram()`</span> to solve for the activity of the indicated basis species:
* more convenient (the buffers come from the currently defined species of interest), but only a single basis species can be buffered, and it's not used in the calculation of affinity;
* [<span style="color:blue">`demo(buffer)`</span>](../demo) uses it for aqueous organic species as buffers (dotted and dashed lines).
As an example of method 1, let's look at the pyrite-pyrrhotite-magnetite (PPM) buffer at 300 °C.
```{marginfigure}
For other examples, see <span style="color:blue">`?buffer`</span> and [<span style="color:blue">`demo(protbuff)`</span>](../demo) (hypothetical buffer made of proteins).
```
Without the buffer, the basis species have default activities of zero.
Under these conditions, the minerals are not in equilibrium, as shown by their different affinities of formation:
```{r PPM_basis, results="hide", message=FALSE}
basis(c("FeS2", "H2S", "O2", "H2O"))
species(c("pyrite", "magnetite"))
species("pyrrhotite", "cr2", add = TRUE)
```
```{marginfigure}
The affinity of formation of pyrite happens to be zero because it is identical to one of the selected basis species.
```
```{r PPM_affinity, message=FALSE}
unlist(affinity(T = 300, P = 100)$values)
```
We use <span style="color:red">`mod.buffer()`</span> to choose the `cr2` phase of pyrrhotite, which is stable at this temperature ([see above](#mosaic-diagrams) for how to get this information for minerals with polymorphic transitions).
Then, we set up H<sub>2</sub>S and `r o2` to be buffered by PPM, and inspect their buffered activities (logarithmic values):
```{r PPM_setup, results="hide"}
mod.buffer("PPM", "pyrrhotite", "cr2")
basis(c("H2S", "O2"), c("PPM", "PPM"))
```
```{r PPM_activities, message=FALSE}
unlist(affinity(T = 300, P = 100, return.buffer = TRUE)[1:3])
```
<!-- put demo(buffer) here for appealing placement on page -->
```{r demo_buffer_noecho, fig.margin=TRUE, fig.width=4, fig.height=4, out.width="100%", message=FALSE, echo=FALSE, cache=TRUE, fig.cap="Values of log<i>f</i><sub>H<sub>2</sub></sub> corresponding to mineral buffers or to given activities of aqueous species.", pngquant=pngquant, timeit=timeit}
demo(buffer, echo = FALSE)
```
We have found log*a*<sub>H<sub>2</sub>S</sub> and `r logfO2` that are compatible with the coexistence of the three minerals.
Under these conditions, the affinities of formation reactions of the minerals in the buffer are all equal to zero:
<!-- re-run the commands from above because demo(buffer) changes the system -->
```{r PPM_basis, echo = FALSE, results = "hide"}
```
```{r PPM_setup, echo = FALSE, results = "hide", message = FALSE}
```
```{r PPM_affinity, message = FALSE}
```
Another example, based on Figure 6 of @SS95, is given in [<span style="color:blue">`demo(buffer)`</span>](../demo).
Here, values of log*f*<sub>H<sub>2</sub></sub> buffered by minerals or set by equilibrium with given activities of aqueous species are calculated using the two methods:
```{r demo_buffer, eval=FALSE}
demo(buffer)
```
# Equilibrium
Above we considered this question: for equal activities of species, what are the affinities of their formation reactions from basis species?
Turning the question around, we would like to know: for equal affinities of formation reactions, what are the activities of species?
The first question is about non-equilibrium conditions; the second is about equilibrium.
Before presenting some examples, it is helpful to know about the limitations of the functions.
CHNOSZ does not take account of all possible reactions in the speciation of a system.
Instead, it assumes that the total activity of species in the system is set by the activity of *one* basis species.
```{marginfigure}
When activity coefficients are assumed to be zero, activities are equal to concentration and we can refer to "total activity".
If the ionic strength is specified, <span style="color:green">`nonideal()`</span> ([see below](#activity-coefficients)) can be used to calculate activity coefficients.
```
This balanced, or conserved, basis species must be present (with a positive or negative coefficient) in the formation reactions of all species considered.
For a given total activity of the balanced basis species, activities of the species can be found such that the affinities of the formation reactions are all equal.
This is an example of metastable equilibrium.
With additional constraints, the affinities of the formation reactions are not only equal to each other, but equal to zero.
This is total equilibrium.
An example of total equilibrium was given above for the PPM buffer.
In contrast, models for systems of organic and biomolecules often involve metastable equilibrium constraints.
## Equilibration methods
The <span style="color:green">`equilibrate()`</span> function in CHNOSZ automatically chooses between two methods for calculating equilibrium.
The method based on the Boltzmann equation is fast, but is applicable only to systems where the coefficient on the balanced basis species in each of the formation reactions is one.
The reaction-matrix method is slower, but can be applied to systems were the balanced basis species has reaction coefficients other than one.
```{r bjerrum_diagram, fig.margin=TRUE, fig.width=3, fig.height=6, out.width="100%", echo=FALSE, results="hide", message=FALSE, cache=TRUE, fig.cap="Three views of carbonate speciation: affinity, activity, degree of formation.", pngquant=pngquant, timeit=timeit}
par(mfrow = c(3, 1))
basis("CHNOS+")
species(c("CO2", "HCO3-", "CO3-2"))
a25 <- affinity(pH = c(4, 13))
a150 <- affinity(pH = c(4, 13), T = 150)
diagram(a25, dy = 0.4)
diagram(a150, add = TRUE, names = FALSE, col = "red")
e25 <- equilibrate(a25, loga.balance = -3)
e150 <- equilibrate(a150, loga.balance = -3)
diagram(e25, ylim = c(-6, 0), dy = 0.15)
diagram(e150, add = TRUE, names = FALSE, col = "red")
diagram(e25, alpha = TRUE, dy = -0.25)
diagram(e150, alpha = TRUE, add = TRUE, names = FALSE, col = "red")
```
The distribution of aqueous carbonate species as a function of pH (a type of Bjerrum plot) is a classic example of an equilibrium calculation.
We can begin by plotting the affinities of formation, for equal activities of the species, calculated at 25 °C and 150 °C.
Here, CO<sub>2</sub> is in the basis, so it has zero affinity, which is greater than the affinities of HCO<sub>3</sub><sup>-</sup> and CO<sub>3</sub><sup>-2</sup> at low pH.
To avoid overplotting the lines, we offset the species labels in the *y* direction using the `dy` argument:
```{r bjerrum_diagram, echo=1:7, eval=FALSE}
```
Now we use <span style="color:green">`equilibrate()`</span> to calculate the activities of species.
Our balancing constraint is that the total activity of C is 10<sup>-3</sup>.
This shows a hypothetical metastable equilibrium; we know that for true equilibrium the total activity of C is affected by pH.
```{r bjerrum_diagram, echo=8:11, eval=FALSE}
```
To display the species distribution, or degree of formation, add `alpha = TRUE` to the argument list:
```{r bjerrum_diagram, echo=12:13, eval=FALSE}
```
## Complete equilibrium: Solubility
It is important to remember that <span style="color:green">`equilibrate()`</span> calculates an equilibrium distribution of species for a given total activity of the conserved basis species.
For instance, the previous diagram shows the relative abundances of CO<sub>2</sub>, HCO<sub>3</sub><sup>-</sup>, and CO<sub>3</sub><sup>-2</sup> as a function of pH assuming that the possible reactions between species are all balanced on 1 C and the total activity of C is constant.
Although this assumption of metastable equilibrium is useful for making many types of diagrams for aqueous species, the aqueous solutions would not be in equilibrium with other phases, including gases or solids such as carbon dioxide or calcite.
Moving away from metastable equilibrium to complete equilibrium actually involves a simplification of the computations.
Instead of finding the activities of aqueous species where the affinities of formation reactions are equal to each other, equilibrium occurs when the affinities of all formation reactions are equal to zero.
However, the solubility calculation comes with a different constraint: all reactions between the pure substance that is being dissolved and any of the possible formed aqueous species must be able to be balanced on the same element (usually the main metal in the system).
This balancing constraint can be expressed as a conserved basis species, i.e. one that is present in non-zero quantity in the formation reactions of all species considered.
The <span style="color:green">`solubility()`</span> function provides a way to compute activities of aqueous species in equilibrium with one or more minerals or gases.
The following example for corundum (Al<sub>2</sub>O<sub>3</sub>) is based on Figure 15 of @Man13.
To more closely reproduce the diagram, we use superseded thermodynamic data that are kept in the `SLOP98` optional data file.
The basis species are defined with the main element (Al) first.
The mineral we want to dissolve, corundum, is loaded as a formed species.
The aqueous species that can form by dissolution of corundum are listed in the `iaq` argument of <span style="color:green">`solubility()`</span>.
The next arguments describe the variables for the <span style="color:green">`affinity()`</span> calculations.
Note that setting `IS` to 0 has no effect on the calculations, but signals <span style="color:green">`diagram()`</span> to label the *y* axis with logarithm of molality instead of logarithm of activity.
An additional argument, `in.terms.of`, is used to compute the total molality of Al in solution, that is, twice the number of moles of Al<sub>2</sub>O<sub>3</sub> that are dissolved.
<span style="color:green">`diagram()`</span> is used twice, first to plot the total molality of Al, then the concentrations of the individual species, using `adj` and `dy` to adjust the positions of labels in the *x*- and *y*-directions.
At the end of the calculation, we use <span style="color:red">`reset()`</span> to restore the default thermodynamic database.
```{r corundum, fig.margin=TRUE, fig.width=4, fig.height=4, out.width="100%", results="hide", message=FALSE, cache=TRUE, fig.cap="Solubility of corundum (green line) and equilibrium concentrations of aqueous species (black lines).", pngquant=pngquant, timeit=timeit}
add.OBIGT("SLOP98")
basis(c("Al+3", "H2O", "H+", "O2"))
species("corundum")
iaq <- c("Al+3", "AlO2-", "AlOH+2", "AlO+", "HAlO2")
s <- solubility(iaq, pH = c(0, 10), IS = 0, in.terms.of = "Al+3")
diagram(s, type = "loga.balance", ylim = c(-10, 0), lwd = 4, col = "green3")
diagram(s, add = TRUE, adj = c(0, 1, 2.1, -0.2, -1.5), dy = c(0, 0, 4, -0.3, 0.1))
legend("topright", c("25 °C", "1 bar"), text.font = 2, bty = "n")
reset()
```
Other examples of using <span style="color:green">`solubility()`</span> are available in CHNOSZ.
See [<span style="color:blue">`demo(solubility)`</span>](../demo) for calculations of the solubility of CO<sub>2(<i>gas</i>)</sub> and calcite as a function of pH and temperature.
The calculation considers the stoichiometric dissolution of calcite, in which CaCO<sub>3</sub> dissociates to form equal quantities of Ca<sup>+2</sup> and CO<sub>3</sub><sup>-2</sup> ions.
Adding in activity coefficients, an example in <span style="color:blue">`?solubility`</span> uses the `find.IS` option to find the final ionic strength for dissolving calcite into pure water.
[<span style="color:blue">`demo(gold)`</span>](../demo) shows calculations of the solubility of gold as a function of pH and *T* as well as oxygen fugacity set by diferent mineral buffers, and considers ionic strength effects on activity coefficients, so that activities are transformed to molalities ([see below](#from-activity-to-molality)).
# Activity coefficients
For calculating activity coefficients of charged species, <span style="color:green">`nonideal()`</span> uses the extended Debye--Hückel equation as parameterized by @HKF81 for NaCl-dominated solutions to high pressure and temperature, or optionally using parameters described in Chapter 3 of @Alb03, which are applicable to relatively low-temperature biochemical reactions.
The activity coefficients are calculated as a function of ionic strength (*I*), temperature, and charge of each species, without any other species-specific parameters.
Using the default `Helgeson` method, the extended term parameter ("B-dot") is derived from data of @Hel69 and Helgeson et al. (1981), and extrapolations of @MSS13.
## From activity to molality
Following the main workflow of CHNOSZ, <span style="color:green">`nonideal()`</span> normally does not need to be used directly.
Intead, invoke the calculations by setting the `IS` argument in <span style="color:green">`subcrt()`</span> or <span style="color:green">`affinity()`</span>.
There are a few things to remember when using activity coefficients:
* H<sup>+</sup> is assumed to behave ideally, so its activity coefficient is 1 for any ionic strength. You can calculate activity coefficients of H<sup>+</sup> by running `thermo("opt$ideal.H" = FALSE)`.
* Using <span style="color:green">`subcrt()`</span> with `IS` not equal to zero, calculated values of `G` are the **adjusted** Gibbs energy at specified ionic strength [denoted by Δ*G*°(*I*); @Alb96].
* Using <span style="color:green">`subcrt()`</span> with `IS` not equal to zero, values in the `logact` argument stand for **log molality** of aqueous species in affinity calculations.
* Using <span style="color:green">`affinity()`</span> with `IS` not equal to zero, the following values stand for **log molality** of aqueous species:
+ values of `logact` set by <span style="color:green">`basis()`</span>;
+ values of `logact` set by <span style="color:green">`species()`</span>.
* Using <span style="color:green">`equilibrate()`</span> on the output of affinity calculated with `IS` not equal to zero, the following values stand for **log molality** of aqueous species:
+ the value of `loga.balance` used by <span style="color:green">`equilibrate()`</span> (i.e., logarithm of total molality of the balancing basis species);
+ values of `loga.equil` returned by <span style="color:green">`equilibrate()`</span>.
In other words, the activation of activity coefficients effects a transformation from activity to molality in the main workflow.
A simple but comprehensive series of calculations demonstrating these tranformations is in `inst/tinytest/test-logmolality.R`.
Because it is not possible to dynamically change the names of arguments in the functions, the user should be aware of the transformations mentioned above.
However, the labels on diagrams *can* be automatically adjusted; accordingly, activities of aqueous species are relabeled as molalities by <span style="color:green">`diagram()`</span> when `IS` is used in the calculation of <span style="color:green">`affinity()`</span>.
## Biochemical example
For the following calculations, we change the nonideality method to `Alberty`; this is a simpler formulation with parameters that are suitable for biochemical species at relatively low temperatures:
```{r Alberty}
oldnon <- nonideal("Alberty")
```
Let's take a look at calculated activity coefficients at two temperatures and their effect on the standard Gibbs energies of formation (Δ*G*°<sub>*f*</sub>) of species with different charge:
```{r subcrt_IS}
subcrt(c("MgATP-2", "MgHATP-", "MgH2ATP"),
T = c(25, 100), IS = c(0, 0.25), property = "G")$out
```
The logarithms of the activity coefficients (`loggam`) are more negative for the higher-charged species, as well as at higher temperature, and have a stabilizing effect.
That is, the adjusted Gibbs energies at *I* > 0 are less than the standard Gibbs energies at *I* = 0.
We can use these calculations to make some speciation plots, similar to Figures 1.2--1.5 in Alberty (2003).
These figures show the distribution of differently charged species of adenosine triphosphate (ATP) as a function of pH, and the average number of H<sup>+</sup> and Mg<sup>+2</sup> bound to ATP in solution as a function of pH or pMg (-log*a*<sub>Mg<sup>+2</sup></sub>).
Use <span style="color:green">`info()`</span> to see what ATP species are available.
The sources of high-temperature thermodynamic data for these species are two papers by LaRowe and Helgeson [-@LH06a; -@LH06b].
```{r info_ATP, results="hide"}
info(" ATP")
```
The plots for this system in Alberty's book were made for *I* = 0.25 M and *T* = 25 °C.
As a demonstration of CHNOSZ's capabilities, we can assign a temperature of 100 °C.
```{r T_100}
T <- 100
```
Use the following commands to set the basis species, add the variously protonated ATP species, calculate the affinities of the formation reactions, equilibrate the system, and make a degree of formation (α) or mole fraction diagram.
This is similar to Figure 1.3 of Alberty (2003), but is calculated for *I* = 0 M and *T* = 100 °C:
```{marginfigure}
To make the code more readable, commands for plotting titles and legends are not shown.
All of the commands are available in the source of this document.
```
```{r ATP, eval=FALSE, echo=2:6}
par(mfrow = c(1, 4), mar = c(3.1, 3.6, 2.1, 1.6), mgp = c(1.8, 0.5, 0))
basis("MgCHNOPS+")
species(c("ATP-4", "HATP-3", "H2ATP-2", "H3ATP-", "H4ATP"))
a <- affinity(pH = c(3, 9), T = T)
e <- equilibrate(a)
d <- diagram(e, alpha = TRUE, tplot = FALSE)
title(main = describe.property("T", T))
alphas <- do.call(rbind, d$plotvals)
nH <- alphas * 0:4
Hlab <- substitute(italic(N)[H^`+`])
plot(a$vals[[1]], colSums(nH), type = "l", xlab = "pH", ylab=Hlab, lty=2, col=2)
a <- affinity(pH = c(3, 9), IS = 0.25, T = T)
e <- equilibrate(a)
d <- diagram(e, alpha = TRUE, plot.it = FALSE)
alphas <- do.call(rbind, d$plotvals)
nH <- alphas * 0:4
lines(a$vals[[1]], colSums(nH))
legend("topright", legend = c("I = 0 M", "I = 0.25 M"), lty = 2:1, col = 2:1, cex = 0.8)
ATP.H <- substitute("ATP and H"^`+`)
title(main = ATP.H)
species(c("MgATP-2", "MgHATP-", "MgH2ATP", "Mg2ATP"), add = TRUE)
Hplot <- function(pMg, IS = 0.25) {
basis("Mg+2", -pMg)
a <- affinity(pH = c(3, 9), IS = IS, T = T)
e <- equilibrate(a)
d <- diagram(e, alpha = TRUE, plot.it = FALSE)
alphas <- do.call(rbind, d$plotvals)
NH <- alphas * c(0:4, 0, 1, 2, 0)
lines(a$vals[[1]], colSums(NH), lty = 7 - pMg, col = 7 - pMg)
}
plot(c(3, 9), c(0, 2), type = "n", xlab = "pH", ylab = Hlab)
lapply(2:6, Hplot)
legend("topright", legend = paste("pMg = ", 2:6), lty = 5:1, col = 5:1, cex = 0.8)
ATP.H.Mg <- substitute("ATP and H"^`+`~"and Mg"^`+2`)
title(main = ATP.H.Mg)
Mgplot <- function(pH, IS = 0.25) {
basis("pH", pH)
a <- affinity(`Mg+2` = c(-2, -7), IS = IS, T = T)
e <- equilibrate(a)
d <- diagram(e, alpha = TRUE, plot.it = FALSE)
alphas <- do.call(rbind, d$plotvals)
NMg <- alphas * species()$`Mg+`
lines(-a$vals[[1]], colSums(NMg), lty = 10 - pH, col = 10 - pH)
}
Mglab <- substitute(italic(N)[Mg^`+2`])
plot(c(2, 7), c(0, 1.2), type = "n", xlab = "pMg", ylab = Mglab)
lapply(3:9, Mgplot)
legend("topright", legend = paste("pH = ", 3:9), lty = 7:1, col = 7:1, cex = 0.8)
title(main = ATP.H.Mg)
```
Note that we have saved the numeric results of <span style="color:green">`diagram()`</span>, i.e. the degrees of formation of the species (α).
With that, we can calculate and plot the average number of protons bound per ATP molecule.
To do so, we use R's `rbind()` and `do.call()` to turn `alpha` into a matrix, then multiply by the number of protons bound to each species, and sum the columns to get the total (i.e. average proton number, *N*<sub>H<sup>+</sup></sub>):
```{r ATP, eval=FALSE, echo=8:11}
```
Adding the `IS` argument to <span style="color:green">`affinity()`</span>, we can now plot *N*<sub>H<sup>+</sup></sub> at the given ionic strength.
Here we set `plot.it = FALSE` in <span style="color:green">`diagram()`</span> because we use the computed α to make our own plot.
This is similar to Figure 1.3 of Alberty (2003), but at higher temperature:
```{r ATP, eval=FALSE, echo=12:17}
```
Next, we add the Mg<sup>+2</sup>-complexed ATP species:
```{r ATP, eval=FALSE, echo=21}
```
Here is a function to calculate and plot *N*<sub>H<sup>+</sup></sub> for a given pMg:
```{r ATP, eval=FALSE, echo=22:30}
```
With that function in hand, we plot the lines corresponding to pMg = 2 to 6.
This is similar to Figure 1.4 of Alberty (2003):
```{r ATP, eval=FALSE, echo=31:32}
```
The next function calculates and plots the average number of Mg<sup>+2</sup> bound to ATP (*N*<sub>Mg<sup>+2</sup></sub>) for a given pH.
Here we multiply `alpha` by the number of Mg<sup>+2</sup> in each species, and negate log*a*<sub>Mg<sup>+2</sup></sub> (the variable used in <span style="color:green">`affinity()`</span>) to get pMg:
```{r ATP, eval=FALSE, echo=36:44}
```
Using that function, we plot the lines corresponding to pH = 3 to 9.
This is similar to Figure 1.5 of Alberty (2003):
```{r ATP, eval=FALSE, echo=45:47}
```
<p>
```{r ATP, fig.fullwidth=TRUE, fig.width=10, fig.height=2.5, dpi=hidpi, out.width="100%", echo=FALSE, message=FALSE, results="hide", fig.cap="Binding of H<sup>+</sup> and Mg<sup>+2</sup> to ATP at 100 °C and *I* = 0 M (first plot) or *I* = 0.25 M (third and fourth plots).", cache=TRUE, pngquant=pngquant, timeit=timeit}
```
</p>
We have calculated the distribution of ATP species and average binding number of H<sup>+</sup> and Mg<sup>+2</sup> for given pH, pMg, ionic strength, and temperature.
Accounting for the distribution of chemical species lends itself to thermodynamic models for reactions between reactants that have multiple ionized and complexed states.
In contrast, Alberty (2003) and others propose models for biochemical reactions where the ionized and complexed species are combined into a single representation.
Those models invoke Legendre-transformed thermodynamic properties, such as transformed Gibbs energies that are tabulated for specified pH, pMg, and ionic strength.
Although the conceptual pathways are different, the two approaches lead to equivalent results concerning the energetics of the overall reactions and the conditions for equilibrium [@SVI12].
The example here shows how the required calculations can be performed at the species level using conventional standard Gibbs energies for species referenced to infinite dilution (zero ionic strength).
The effects of ionic strength are modeled "on the fly" in CHNOSZ by setting the `IS` argument in <span style="color:green">`subcrt()`</span> or <span style="color:green">`affinity()`</span> to invoke the nonideality model on top of the standard Gibbs energies of species.
Now that we're finished, we can reset the nonideality method to the default.
(This really isn't needed here, because there aren't any nonideality calculations below):
```{r oldnon}
nonideal(oldnon)
```
# Proteins
Proteins in CHNOSZ are handled a little bit differently from other species.
Amino acid group additivity is used to obtain the thermodynamic properties of proteins.
Therefore, CHNOSZ has a data file with amino acid compositions of selected proteins, as well as functions for reading and downloading amino acid sequence data.
When proteins in CHNOSZ are identified by name, they include an underscore, such as in `LYSC_CHICK` (chicken lysozyme C).
Use <span style="color:green">`pinfo()`</span> to search for one or more proteins by name; multiple proteins from the same organism can be specified using the `organism` argument.
The name search returns the rownumbers of `thermo()$protein` (i.e. `iprotein`, the protein indices).
Supply those protein indices to <span style="color:green">`pinfo()`</span> to get the amino acid compositions:
```{r pinfo_LYSC_CHICK}
p1 <- pinfo("LYSC_CHICK")
p2 <- pinfo(c("SHH", "OLIG2"), "HUMAN")
pinfo(c(p1, p2))
```
The length and chemical formula of one or more proteins are returned by <span style="color:green">`protein.length()`</span> and <span style="color:green">`protein.formula()`</span>.
We can calculate the formula of the protein, and the per-residue formula, and show that both have the same average oxidation state of carbon:
```{marginfigure}
These functions accept either names or the protein indices (`iprotein`).
```
```{r formula_LYSC_CHICK}
pl <- protein.length("LYSC_CHICK")
pf <- protein.formula("LYSC_CHICK")
list(length = pl, protein = pf, residue = pf / pl,
ZC_protein = ZC(pf), ZC_residue = ZC(pf / pl))
```
## Group additivity and ionization
The group additivity calculations for proteins are based on equations and data from @AH00, @DLH06, and @LD12.
There are two major options for the calculations: whether to calculate properties for crystalline or aqueous groups, and, for the latter, whether to model the ionization of the sidechain and terminal groups as a function of pH (and *T* and *P*).
By default, additivity of aqueous groups is used, but the ionization calculations are not available in <span style="color:green">`subcrt()`</sub>:
```{r subcrt_LYSC_CHICK, message=FALSE}
subcrt("LYSC_CHICK")$out[[1]][1:6, ]
```
Let's compare experimental values of heat capacity of four proteins, from @PM90, with those calculated using group additivity.
We divide Privalov and Makhatadze's experimental values by the lengths of the proteins to get per-residue values, then plot them.
```{r protein_Cp, fig.margin=TRUE, fig.width=4, fig.height=4, small.mar=TRUE, out.width="100%", echo=FALSE, message=FALSE, fig.cap='The heat capacity calculated by group additivity closely approximates experimental values for aqueous proteins. For a related figure showing the effects of ionization in the calculations, see <span style="color:blue">`?ionize.aa`</span>.', cache=TRUE, pngquant=pngquant, timeit=timeit}
PM90 <- read.csv(system.file("extdata/cpetc/PM90.csv", package = "CHNOSZ"))
plength <- protein.length(colnames(PM90)[2:5])
Cp_expt <- t(t(PM90[, 2:5]) / plength)
matplot(PM90[, 1], Cp_expt, type = "p", pch = 19,
xlab = axis.label("T"), ylab = axis.label("Cp0"), ylim = c(110, 280))
for(i in 1:4) {
pname <- colnames(Cp_expt)[i]
aq <- subcrt(pname, "aq", T = seq(0, 150))$out[[1]]
cr <- subcrt(pname, "cr", T = seq(0, 150))$out[[1]]
lines(aq$T, aq$Cp / plength[i], col = i)
lines(cr$T, cr$Cp / plength[i], col = i, lty = 2)
}
legend("right", legend = colnames(Cp_expt),
col = 1:4, pch = 19, lty = 1, bty = "n", cex = 0.9)
legend("bottomright", legend = c("experimental", "calculated (aq)",
"calculated (cr)"), lty = c(NA, 1, 2), pch = c(19, NA, NA), bty = "n")
```
```{r protein_Cp, eval=FALSE, echo=1:5}
```
The loop calculates the properties of each protein using group additivity with aqueous or crystalline groups, then plots the per-residue values.
```{r protein_Cp, eval=FALSE, echo=-(1:5)}
```
Although <span style="color:green">`subcrt()`</span> has no provision for protein ionization, the properties of ionization can be calculated via <span style="color:green">`affinity()`</span>, which calls <span style="color:green">`ionize.aa()`</span> if a charged species is in the basis.
```{marginfigure}
Whether to calculate properties using aqueous or crystalline groups is determined by the value of `thermo()\$opt\$state`; if it is changed from its default of `aq` to `cr`, no ionization is possible.
```
The following plot shows the calculated affinity of reaction between nonionized proteins and their ionized forms as a function of pH.
Charged and uncharged sets of basis species are used to to activate and suppress the ionization calculations.
The calculation of affinity for the ionized proteins returns multiple values (as a function of pH), but there is only one value of affinity returned for the nonionized proteins, so we need to use R's `as.numeric()` to avoid subtracting nonconformable arrays:
```{r protein_ionization, fig.margin=TRUE, fig.width=4, fig.height=4, small.mar=TRUE, out.width="100%", echo=FALSE, results="hide", message=FALSE, fig.cap='Affinity of ionization of proteins. See [<span style="color:blue">demo(ionize)</span>](../demo) for ionization properties calculated as a function of temperature and pH.', cache=TRUE, pngquant=pngquant, timeit=timeit}
ip <- pinfo(c("CYC_BOVIN", "LYSC_CHICK", "MYG_PHYCA", "RNAS1_BOVIN"))
basis("CHNOS+")
a_ion <- affinity(pH = c(0, 14), iprotein = ip)
basis("CHNOS")
a_nonion <- affinity(iprotein = ip)
plot(c(0, 14), c(50, 300), xlab = "pH", ylab = quote(italic(A/2.303*RT)), type="n")
for(i in 1:4) {
A_ion <- as.numeric(a_ion$values[[i]])
A_nonion <- as.numeric(a_nonion$values[[i]])
lines(a_ion$vals[[1]], A_ion - A_nonion, col=i)
}
legend("topright", legend = a_ion$species$name,
col = 1:4, lty = 1, bty = "n", cex = 0.9)
```
```{r protein_ionization, eval=FALSE}
```
The affinity is always positive, showing the strong energetic drive for ionization of proteins in aqueous solution.
The degrees of ionization of amino and carboxyl groups increase at low and high pH, respectively, giving rise to the U-shaped lines.
There, we used the indices returned by <span style="color:green">`pinfo()`</span> in the `iprotein` argument of <span style="color:green">`affinity()`</span> to specify the proteins in the calculation.
That approach utilizes some optimizations that can be realized due to group additivity, and is useful for calculations involving many proteins.
An alternative, but slower, approach is to identify the proteins to <span style="color:green">`species()`</span>; this produces results that are equivalent to using the `iprotein` argument:
<!-- this is needed because the figure above might be cached, preventing the call to basis() there -->
```{r basis_CHNOS, echo=FALSE, results="hide"}
basis("CHNOS")
```
```{r species_protein, results="hide", message=FALSE, echo=1:2}
species(c("CYC_BOVIN", "LYSC_CHICK", "MYG_PHYCA", "RNAS1_BOVIN"))
a_nonion_species <- affinity()
```
```{r nonion_species_values}
unlist(a_nonion_species$values)
```
```{marginfigure}
The `ispecies` index (top) refers to the rownumber of `thermo()\$species`; that is distinct from the `iprotein` index (bottom, printed as negative integers), which refers to the rownumber of `thermo()\$protein`.
```
```{r nonion_values}
unlist(a_nonion$values)
```
## Chemical analysis of proteins
Functions in CHNOSZ make it easy to get the chemical formulas of proteins from their amino acid compositions.
Calculations based on the formulas, such as the average oxidation state of carbon (`r zc`), and the coefficients of basis species in formation reactions, are also available.
Let's compare the `r zc` of Rubisco with optimal growth temperature of organisms, as shown in Figure 6a of @Dic14.
First we read a CSV file with the IDs of the proteins and the optimal growth temperatures (*T*<sub>opt</sub>); the midpoint of the range of *T*<sub>opt</sub> is used for plotting.
Then we use <span style="color:green">`read.fasta()`</span> to read a FASTA file holding the amino acid sequences of the proteins; the function returns a data frame with the amino acid counts.
To put the proteins in the right order, the IDs in the CSV file are matched to the names of the proteins in the FASTA file.
Then, we calculate `r zc` from the formulas of the proteins.
Next, point symbols are assigned according to domain (Archaea, Bacteria, Eukaryota); numbers inside the symbols show the ordering of *T*<sub>opt</sub> in three temperature ranges (0--35 °C, 37.5--60 °C, and 65--100 °C).
```{r rubisco_svg, echo=FALSE, results="hide", fig.margin=TRUE, fig.width=4, fig.height=4, small.mar=TRUE, out.width="100%", fig.ext='svg', custom.plot=TRUE, embed.tag=TRUE, fig.cap='Average oxidation state of carbon in Rubisco compared with optimal growth temperature of organisms. **This is an interactive image.** Move the mouse over the points to show the names of the organisms, and click to open a reference in a new window. (Made with [**RSVGTipsDevice**](https://cran.r-project.org/package=RSVGTipsDevice) using code that can be found in the source of this document.)'}
## copies the premade SVG image to the knitr figure path
file.copy("rubisco.svg", fig_path(".svg"))
## the code for making the SVG image -- not "live" in the vignette because RSVGTipsDevice isn't available on Windows
#if(require(RSVGTipsDevice)) {
# datfile <- system.file("extdata/cpetc/rubisco.csv", package = "CHNOSZ")
# fastafile <- system.file("extdata/protein/rubisco.fasta", package = "CHNOSZ")
# dat <- read.csv(datfile)
# aa <- read.fasta(fastafile)
# Topt <- (dat$T1 + dat$T2) / 2
# idat <- match(dat$ID, substr(aa$protein, 4, 9))
# aa <- aa[idat, ]
# ZC <- ZC(protein.formula(aa))
# pch <- match(dat$domain, c("E", "B", "A")) - 1
# col <- match(dat$domain, c("A", "B", "E")) + 1
# # because the tooltip titles in the SVG file are shown by recent browsers,
# # we do not need to draw the tooltips explicitly, so set toolTipMode=0
# devSVGTips("rubisco.svg", toolTipMode=0, title="Rubisco")
# par(cex=1.4)
# # unfortunately, plotmath can't be used with devSVGTips,
# # so axis labels here don't contain italics.
# plot(Topt, ZC, type="n", xlab="T, °C", ylab="ZC")
# n <- rep(1:9, 3)
# for(i in seq_along(Topt)) {
# # adjust cex to make the symbols look the same size
# cex <- ifelse(pch[i]==1, 2.5, 3.5)
# points(Topt[i], ZC[i], pch=pch[i], cex=cex, col=col[i])
# URL <- dat$URL[i]
# setSVGShapeURL(URL, target="_blank")
# setSVGShapeContents(paste0("<title>", dat$species[i], "</title>"))
# text(Topt[i], ZC[i], n[i], cex = 1.2)
# }
# abline(v = c(36, 63), lty = 2, col = "grey")
# legend("topright", legend = c("Archaea", "Bacteria", "Eukaryota"),
# pch = c(2, 1, 0), col = 2:4, cex=1.5, pt.cex = c(3, 2.3, 3), bty="n")
# dev.off()
#}
```
```{r rubisco_ZC, fig.keep="none", message=FALSE}
datfile <- system.file("extdata/cpetc/rubisco.csv", package = "CHNOSZ")
fastafile <- system.file("extdata/protein/rubisco.fasta", package = "CHNOSZ")
dat <- read.csv(datfile)
aa <- read.fasta(fastafile)
Topt <- (dat$T1 + dat$T2) / 2
idat <- match(dat$ID, substr(aa$protein, 4, 9))
aa <- aa[idat, ]
ZC <- ZC(protein.formula(aa))
pch <- match(dat$domain, c("E", "B", "A")) - 1
col <- match(dat$domain, c("A", "B", "E")) + 1
plot(Topt, ZC, pch = pch, cex = 2, col = col,
xlab = expression(list(italic(T)[opt], degree*C)),
ylab = expression(italic(Z)[C]))
text(Topt, ZC, rep(1:9, 3), cex = 0.8)
abline(v = c(36, 63), lty = 2, col = "grey")
legend("topright", legend = c("Archaea", "Bacteria", "Eukaryota"),
pch = c(2, 1, 0), col = 2:4, pt.cex = 2)
```
Let's look at the different ways of representing the chemical compositions of the proteins.
<span style="color:green">`protein.basis()`</span> returns the stoichiometry for the formation reaction of each proteins.
Dividing by <span style="color:green">`protein.length()`</span> gives the per-residue reaction coefficients (*n*̅).
Using the set of basis species we have seen before (CO<sub>2</sub>, NH<sub>3</sub>, H<sub>2</sub>S, `r h2o`, `r o2`) there is a noticeable correlation between *n*̅<sub>`r o2`</sub> and `r zc`, but even more so between *n*̅<sub>`r h2o`</sub> and `r zc` (shown in the plots on the left).
```{marginfigure}
The calculation of *Z*<sub>C</sub>, which sums elemental ratios, is not affected by the choice of basis species.
```
The `QEC` keyword to <span style="color:red">`basis()`</span> loads basis species including three amino acids (glutamine, glutamic acid, cysteine, `r h2o`, `r o2`).
This basis strengthens the relationship between `r zc` and *n*̅<sub>`r o2`</sub>, but weakens that between `r zc` and *n*̅<sub>`r h2o`</sub> (shown in the plots on the right).
```{r rubisco_O2, fig.margin=TRUE, fig.width=4, fig.height=4, small.mar=TRUE, out.width="100%", echo=FALSE, results="hide", message=FALSE, fig.cap="Elemental compositions of proteins projected into different sets of basis species.", cache=TRUE, pngquant=pngquant, timeit=timeit}
layout(matrix(1:4, nrow = 2))
par(mgp = c(1.8, 0.5, 0))
pl <- protein.length(aa)
ZClab <- axis.label("ZC")
nO2lab <- expression(bar(italic(n))[O[2]])
nH2Olab <- expression(bar(italic(n))[H[2]*O])
lapply(c("CHNOS", "QEC"), function(thisbasis) {
basis(thisbasis)
pb <- protein.basis(aa)
nO2 <- pb[, "O2"] / pl
plot(ZC, nO2, pch = pch, col = col, xlab = ZClab, ylab = nO2lab)
nH2O <- pb[, "H2O"] / pl
plot(ZC, nH2O, pch = pch, col = col, xlab = ZClab, ylab = nH2Olab)
mtext(thisbasis, font = 2)
})
```
```{r rubisco_O2, eval=FALSE}
```
By projecting the compositions of proteins into the `QEC` set of basis species, *n*̅<sub>`r o2`</sub> emerges as a strong indicator of oxidation state, while *n*̅<sub>`r h2o`</sub> is a relatively uncorrelated (i.e. independent) compositional variable.
These independent variables make it easier to distinguish the effects of oxidation and hydration state in proteomic datasets [@DYT20].
## Normalization to residues
As with other systems, a balance must be chosen for calculations of the metastable equilibrium distribution for proteins.
Balancing on the number of backbone units (the sequence length) seems a reasonable choice given the polymeric structure of proteins.
```{marginfigure}
Balancing on one of the basis species remains a possibility, using the `balance` argument in <span style="color:green">`equilibrate()`</span> or <span style="color:green">`diagram()`</span>.
```
However, there is an additional consideration: owing to the large size of proteins compared to the basis species, the distribution of *proteins* in metastable equilibrium has many orders of magnitude separation between the activities of the dominant and less-dominant proteins.
The metastable coexistence of the *residues* (i.e. per-residue formulas, or residue equivalents) of the same proteins spans a much smaller range of chemical activities.
In CHNOSZ, the calculation of metastable equilibrium activities of the residue equivalents is referred to as *normalization*.
Let's look at the metastable equilibrium distribution of selected proteins in the ER-to-Golgi location of *S. cerevisiae* (yeast) (this example is taken from @Dic09)
Here, we list the names and relative abundances of proteins taken from the YeastGFP study of @GHB_03.
There are six proteins identified in the ER-to-Golgi location; one has NA abundance, so it is excluded from the comparisons:
```{marginfigure}
This can be done programmatically using data from the YeastGFP study that are in the [JMDplots](https://github.com/jedick/JMDplots) package:
<br>
`y <- JMDplots::yeastgfp("ER.to.Golgi")`
<br>
`ina <- is.na(y[["abundance"]])`
<br>
`aa <- JMDplots::yeast.aa(y$protein[!ina])`
<br>
`ip <- add.protein(aa)`
```
```{r yeastgfp}
protein <- c("YDL195W", "YHR098C", "YIL109C", "YLR208W", "YNL049C", "YPL085W")
abundance <- c(1840, 12200, NA, 21400, 1720, 358)
ina <- is.na(abundance)
```
Next, we find the rownumbers of the proteins in `thermo()$protein`:
```{r add_protein_yeast, message=FALSE}
ip <- match(protein[!ina], thermo()$protein$protein)
```
The YeastGFP study reported absolute abundances of molecules, but the thermodynamic calculations give relative chemical activities of the proteins.
In order to make a comparison between them, we use <span style="color:green">`unitize()`</span> to scale the abundances or activities of proteins (in logarithmic units) such that the total abundance or activity of residue equivalents is unity.
To do that, we must have the lengths of the proteins.
Here, the first call to <span style="color:green">`unitize()`</span> generates equal logarithms of activities of proteins for unit total activity of residues; this is used as the reference state for <span style="color:green">`affinity()`</span>.
The second call to <span style="color:green">`unitize()`</span> scales the logarithms of experimental abundances for unit total activity of residues; this is used for comparison with the theoretical results:
```{r unitize}
pl <- protein.length(ip)
logact <- unitize(numeric(5), pl)
logabundance <- unitize(log10(abundance[!ina]), pl)
```
Now we can load the proteins and calculate their activities in metastable equilibrium as a function of `r logfO2`.
The commented line uses <span style="color:red">`add.OBIGT()`</span> to load group additivity parameters that were present in older versions of CHNOSZ (Dick et al., 2006).
The default database contains newer group additivity parameters for the sidechain groups of methionine (LaRowe and Dick, 2012) and glycine and the protein backbone [@Kit14].
```{r yeastplot, eval=FALSE, echo=1:5}
par(mfrow = c(1, 3))
basis("CHNOS+")
a <- affinity(O2 = c(-80, -73), iprotein = ip, loga.protein = logact)
e <- equilibrate(a)
diagram(e, ylim = c(-5, -2), col = 1:5, lwd = 2)
e <- equilibrate(a, normalize = TRUE)
diagram(e, ylim = c(-5, -2.5), col = 1:5, lwd = 2)
abline(h = logabundance, lty = 1:5, col = 1:5)
```
Whoa! The proteins look very non-coexistent in metastable equilibrium.
We get a different view by considering per-residue rather than per-protein reactions, through the `normalize` argument for <span style="color:green">`equilibrate()`</span>:
```{marginfigure}
The normalization step is followed by conversion of activities of residues to activities of proteins; that conversion can be skipped using the `as.residue` argument in <span style="color:green">`equilibrate()`</span>.
```
```{r yeastplot, eval=FALSE, echo=6:8}
```
The experimental relative abundances are plotted as thin horizontal lines with the same style and color as the thicker curved lines calculated for metastable equilibrium.
With the exception of YNL049C, the correspondence between the calculations and experiments looks to be greatest near the middle-left part of the figure.
```{r yeastplot, fig.width=6, fig.height=2.5, dpi=hidpi, out.width="100%", echo=FALSE, message=FALSE, results="hide", cache=TRUE, fig.cap="ER-to-Golgi proteins: calculations without and with length normalization.", pngquant=pngquant, timeit=timeit}
```
## Getting amino acid compositions
In the Rubisco example above, we saw the use of <span style="color:green">`read.fasta()`</span> to read amino acid sequences from a FASTA file.
There are several other methods for inputting amino acid compositions.
R's `read.csv()` can be used to read amino acid compositions from a CSV file with the same columns that are present in `thermo()$protein`.
Note the use of `as.is = TRUE` to prevent reading character data as factors.
The `nrows` argument can be added to read that number of rows:
```{r read_csv}
file <- system.file("extdata/protein/POLG.csv", package = "CHNOSZ")
aa_POLG <- read.csv(file, as.is = TRUE, nrows = 5)
```
<span style="color:green">`read.fasta()`</span> reads a FASTA file and returns the amino acid compositions of the sequences.
The `iseq` argument can be used to read those sequences from the file:
```{r read_fasta, message=FALSE}
file <- system.file("extdata/protein/EF-Tu.aln", package = "CHNOSZ")
aa_Ef <- read.fasta(file, iseq = 1:2)
```
<span style="color:green">`seq2aa()`</span> counts the amino acids in a user-supplied sequence and generates a data frame of the amino acid composition:
```{marginfigure}
See also <span style="color:blue">`?count.aa`</span>, which can process both protein and nucleic acid sequences.
```
```{r seq2aa}
aa_PRIO <- seq2aa("
MANLGCWMLVLFVATWSDLGLCKKRPKPGGWNTGGSRYPGQGSPGGNRYPPQGGGGWGQP
HGGGWGQPHGGGWGQPHGGGWGQPHGGGWGQGGGTHSQWNKPSKPKTNMKHMAGAAAAGA
VVGGLGGYMLGSAMSRPIIHFGSDYEDRYYRENMHRYPNQVYYRPMDEYSNQNNFVHDCV
NITIKQHTVTTTTKGENFTETDVKMMERVVEQMCITQYERESQAYYQRGSSMVLFSSPPV
ILLISFLIFLIVG
", "PRIO_HUMAN")
```
These amino acid compositions can be processed using functions such as <span style="color:green">`protein.length()`</span> and <span style="color:green">`protein.formula()`</span>:
```{r protein_length}
myaa <- rbind(aa_Ef, aa_PRIO)
protein.length(myaa)
```
# Sources of thermodynamic data
An attempt has been made to assemble a default database that has no major inconsistencies between species.
As the database includes thermodynamic data from many sources, it can not be guaranteed to be fully internally consistent.
For crucial problems, check not only the accuracy of entries in the database, but also the *suitability of the data* for your problem.
If there are any doubts, consult the primary sources.
Most of the species in OBIGT have parameters for one of two models for calculating thermodynamic properties.
The coefficients in these models are indicated by the column names with a dot, for example `a1.a`.
Most aqueous species use the revised Helgeson-Kirkham-Flowers (HKF) equations (text before the dot), and crystalline, gas and liquid species other than `r h2o` use a polynomial equation for heat capacity.
See <span style="color:blue">`?hkf`</span> and <span style="color:blue">`?cgl`</span> for information about the equations used for thermodynamic properties.
Besides this vignette, here's where to look for more information about the database:
- Be sure to read the help page at <span style="color:blue">`?thermo`</span> for information about the format of the OBIGT data frame.
- See the vignette [<span style="color:blue">*OBIGT thermodynamic database*</span>](OBIGT.html) for a summary of all sources for the default database and optional data files.
- See the vignette [<span style="color:blue">*Customizing the thermodynamic database*</span>](custom_data.html) for a broader description of the structure of OBIGT, data entry conventions, and examples of adding species to the database.
## Viewing data sources: <span style="color:green">`thermo.refs()`</span>
The OBIGT database lists one or two sources for each entry, and citation information for the sources is listed in `thermo()$refs`.
You can locate and view the references with <span style="color:green">`thermo.refs()`</span>.
Running the function without any arguments opens a browser window with the complete table of references.
```{marginfigure}
See the vignette [<span style="color:blue">*OBIGT thermodynamic database*</span>](OBIGT.html) for a more nicely formatted presentation of the sources of thermodynamic data, along with notes and additional comments.
```
Where available, links to the web page for the articles and books are displayed:
```{r thermo_refs_table, eval=FALSE}
thermo.refs() ## shows table in a browser
```
A numeric argument to <span style="color:green">`thermo.refs()`</span> gives one or more species indices for which to get the references:
```{r width180, include=FALSE}
```
```{r thermo_refs_numeric}
iATP <- info("ATP-4")
iMgATP <- info("MgATP-2")
thermo.refs(c(iATP, iMgATP))
```
A character argument gives the source key(s):
```{r thermo_refs_character}
thermo.refs(c("HDNB78", "MGN03"))
```
If the argument holds the result of <span style="color:green">`subcrt()`</span>, references for all species in the reaction are returned:
```{marginfigure}
The exception is H<sub>2</sub>O.
With the default settings, thermodynamic properties for H<sub>2</sub>O are derived from SUPCRT92 (Johnson et al., 1992).
```
```{r thermo_refs_subcrt, message=FALSE}
sres <- subcrt(c("C2H5OH", "O2", "CO2", "H2O"), c(-1, -3, 2, 3))
thermo.refs(sres)
```
```{r width80, include=FALSE}
```
The URLs of the references can be copied to a browser, or opened using R's `browseURL()`:
```{r thermo_refs_browse, eval=FALSE}
iFo <- info("forsterite")
ref <- thermo.refs(iFo)
browseURL(ref$URL) ## opens a link to worldcat.org
```
## Default database
Thermodynamic properties of minerals in the default database are mostly taken from @Ber88 (including silicates, aluminosilicates, calcite, dolomite, hematite, and magnetite) and @HDNB78 (native elements, sulfides, halides, sulfates, and selected carbonates and oxides that do not duplicate any in the Berman dataset).
Minerals are identified by the state `cr`, and (for the Helgeson dataset) `cr2`, `cr3`, etc. for higher-temperature polymorphs.
Compared to SUPCRT92/SLOP98 (see below), the default database include updates for aqueous Al species [@TS01], Au species [@PAB_14] (see [<span style="color:blue">`demo(gold)`</span>](../demo)), and arsenic-bearing aqueous species and minerals, as compiled in the SUPCRTBL package [@ZZL_16].
This list of updates is incomplete; see the vignette [<span style="color:blue">*OBIGT thermodynamic database*</span>](OBIGT.html) for a detailed list of data sources.
## Optional data files
Some optional datasets can be activated by using <span style="color:red">`add.OBIGT()`</span>. The first couple of these contain data that have been replaced by or are incompatible with later updates; the superseded data are kept here to reproduce published calculations and for comparison with the newer data:
<span style="color:red">`add.OBIGT("SUPCRT92")`</span> -- This file contains data for minerals from SUPCRT92 (mostly Helgeson et al., 1978) that have been replaced by the Berman data set.
<span style="color:red">`add.OBIGT("SLOP98")`</span> -- This file contains data from `slop98.dat` or later slop files, from Everett Shock's GEOPIG group at Arizona State University, that were previously used in CHNOSZ but have been replaced by more recent data updates.
Some calculations using the older data are shown in [this vignette](#complete-equilibrium-solubility).
The updates for these data have been taken from various publications ([LaRowe and Dick, 2012](https://doi.org/10.1016/j.gca.2011.11.041); [Kitadai, 2014](https://doi.org/10.1007/s00239-014-9616-1); [Azadi et al., 2019](https://doi.org/10.1016/j.fluid.2018.10.002))
A comparison of log*K* of metal-glycinate complexes using the updated data is in [<span style="color:blue">`demo(glycinate)`</span>](../demo).
The next three optional datasets are provided to support newer data or models:
<span style="color:red">`add.OBIGT("DEW")`</span> -- These are parameters for aqueous species that are intended for use with the Deep Earth Water (DEW) model [@SHA14].
You should also run <span style="color:red">`water("DEW")`</span> to activate the equations in the model; then, they will be used by <span style="color:green">`subcrt()`</span> and <span style="color:green">`affinity()`</span>.
Examples are in [<span style="color:blue">`demo(DEW)`</span>](../demo).
<span style="color:red">`add.OBIGT("AD")`</span> -- These data are used in the Akinfiev-Diamond model for aqeuous nonelectrolytes [@AD03].
<span style="color:red">`add.OBIGT("GEMSFIT")`</span> -- Thermodynamic data for aqueous species in the system Ca-Mg-Na-K-Al-Si-O-H-C-Cl obtained from global optimization of Gibbs energies with the GEMSFIT package [@MWKL17].
<span style="color:red">`add.OBIGT("AS04")`</span> -- This file has data for aqueous `r sio2` from @AS04 and modified HSiO<sub>3</sub><sup>-</sup>.
These data reflect a revised (higher) solubility of quartz compared to previous compilations, but are not included in the default database in order to maintain compatibility with existing data for minerals that are linked to the older aqueous `r sio2` data.
See [<span style="color:blue">`demo(aluminum)`</span>](../demo) for an example.
## Cross-checking data entries
<span style="color:green">`info()`</span> automatically performs some cross-checks of the thermodynamic data.
```{marginfigure}
This only checks the parameters for individual species, not the internal consistency among different species.
```
Given a numeric species index, it runs <span style="color:green">`check.EOS()`</span>, which compares the given values of *C*<sub>*P*</sub>° and *V*° with those calculated from the HKF or heat capacity parameters.
<span style="color:green">`info()`</span> also runs <span style="color:green">`check.GHS()`</span>, which compares the given value of Δ*G*°<sub>*f*</sub> with that calculated from Δ*H*°<sub>*f*</sub>, *S*°, and the entropy of the elements [@CWM89] in the chemical formula of the species.
If any of the differences is above a certain tolerance (see <span style="color:blue">`?check.GHS`</span> for details), a message to this effect is produced.
Some species in the default and optional databases are known to have inconsistent parameters.
For instance, we can check the data for the trisulfur radical ion (S<sub>3</sub><sup>-</sup>) from @PD15:
```{r info_S3, results="hide"}
info(info("S3-"))
```
The calculated value of Δ*G*°<sub>*f*</sub> is `r round(suppressMessages(check.GHS(info(info("S3-")))))` cal mol<sup>-1</sup> higher than the given value.
After checking for any typographical errors in the entries for Δ*G*°<sub>*f*</sub>, Δ*H*°<sub>*f*</sub>, *S*°, and the chemical formula, the literature may need to be revisited for further clarification.
All of the species with inconsistencies detected in this manner, in both OBIGT and the optional data files, are listed in the file `OBIGT_check.csv`.
```{r check_OBIGT}
file <- system.file("extdata/adds/OBIGT_check.csv", package = "CHNOSZ")
dat <- read.csv(file, as.is = TRUE)
nrow(dat)
```
Without additional information, there is often no clear strategy for "fixing" these inconsistent data, and they are provided as-is.
Users are encouraged to send any corrections to the package maintainer.
## Water: SUPCRT92 or IAPWS-95 or DEW
For calculations of the thermodynamic and dielectric properties of liquid and supercritical H<sub>2</sub>O, CHNOSZ uses a Fortran subroutine (`H2O92`) from SUPCRT92 (Johnson et al., 1992).
Alternatively, the IAPWS-95 formulation for thermodynamic properties [@WP02] can be utilized.
In part because of intrinsic thermodynamic differences between SUPCRT92 and IAPWS-95, as well as different equations used in CHNOSZ for calculating the dielectric constant when the IAPWS-95 option is active, this option could introduce inconsistencies with the data for aqueous species in the database and is not recommended for general use in CHNOSZ.
However, the IAPWS-95 equations are useful for other applications, and may be extrapolated to a greater range of *T* and *P* than SUPCRT.
See <span style="color:blue">`?water`</span> for more information, as well as the last example in <span style="color:blue">`?subcrt`</span>, where uncommenting the line for the `IAPWS95` option allows extrapolation to lower temperatures for supercooled water.
An implementation of the Deep Earth Water (DEW) model is also available; see [Optional data](#optional-data) for more information.
# Functions outside the main workflow
Some functions in CHNOSZ lie outside the main workflow described above.
* <span style="color:green">`RH2OBIGT()`</span> implements a group additivity calculation of standard molal thermodynamic properties and equations of state parameters of crystalline and liquid organic molecules from @RH98.
* <span style="color:green">`EOSregress()`</span> and related functions can be used to regress "equation of state" parameters (e.g. coefficients in the HKF equations) from heat capacity and volumetric data. See <span style="color:blue">`?EOSregress`</span> and the vignette [<span style="color:blue">*Regressing thermodynamic data*</span>](eos-regress.html).
* Some functions are available (see <span style="color:blue">`?taxonomy`</span>) to read data from [NCBI taxonomy files](https://www.ncbi.nlm.nih.gov/taxonomy), traverse taxonomic ranks, and get scientific names of taxonomic nodes.
# Citation and contact information
To cite CHNOSZ, use this reference:
```{r citation_CHNOSZ, results="asis", echo = FALSE}
cref <- citation("CHNOSZ")
print(cref[1], style = "html")
```
For the features described in the [<span style="color:blue">multi-metal vignette</span>](multi-metal.html), use this reference:
```{r citation_multimetal, results="asis", echo = FALSE}
print(cref[2], style = "html")
```
If you found a bug or have questions that aren't answered in the documentation please contact the maintainer:
```{r maintainer_CHNOSZ}
maintainer("CHNOSZ")
```
Thank you for reading, and have fun!
> "The real fun of life is this perpetual testing to realize how far out you can go with any potentialities."
>
> `r tufte::quote_footer('--- Richard P. Feynman')`
# Document history
* 2010-09-30 Initial version, titled "Getting started with CHNOSZ".
<!--
* 2011-08-15 Add <span style="color:green">`browse.refs()`</span>; modifying database hint changed to <span style="color:blue">`help(thermo)`</span>.
```{marginfigure}
<span style="color:green">`browse.refs()`</span> was renamed to <span style="color:green">`thermo.refs()`</span> in 2017.
```
-->
* 2012-06-16 Add "More activity diagrams" (section no longer exists).
* 2015-05-14 Add warning about [internal consistency of thermodynamic data](#thermodynamic-database).
* 2017-02-15 Completely rewritten; switch from Sweave to [knitr](https://yihui.org/knitr/) ([Tufte style](https://rstudio.github.io/tufte/)).
* 2019-01-24 Add [section on solubility calculations](#complete-equilibrium-solubility).
View the R Markdown source of this document [on R-Forge](https://r-forge.r-project.org/scm/viewvc.php/pkg/CHNOSZ/vignettes/anintro.Rmd?view=markup&root=chnosz) or in R:
```{r file_edit_anintro, eval=FALSE}
file.edit(system.file("doc/anintro.Rmd", package = "CHNOSZ"))
```
<p>
```{r the_end}
###### ## ## ## ## ###### ##### #####
## ##===## ## \\## ## ## \\ //
###### ## ## ## ## ###### ##### #####
```
</p>
<!-- for finding what versions of packages are on R-Forge and winbuilder
```{r sessionInfo}
sessionInfo()
```
-->
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/doc/anintro.Rmd
|
## ----setup, include = FALSE---------------------------------------------------
library(CHNOSZ)
options(width = 80)
## Use pngquant to optimize PNG images
library(knitr)
knit_hooks$set(pngquant = hook_pngquant)
pngquant <- "--speed=1 --quality=0-25"
if (!nzchar(Sys.which("pngquant"))) pngquant <- NULL
# Set dpi 20231129
knitr::opts_chunk$set(
dpi = if(nzchar(Sys.getenv("CHNOSZ_BUILD_LARGE_VIGNETTES"))) 100 else 72
)
## ----HTML, include = FALSE----------------------------------------------------
NOTE <- '<span style="background-color: yellow;">NOTE</span>'
# OBIGT columns
model <- '<span style="color: blue;">model</span>'
name <- '<tt style="color: blue;">name</tt>'
abbrv <- '<tt style="color: blue;">abbrv</tt>'
formula <- '<tt style="color: blue;">formula</tt>'
state <- '<tt style="color: blue;">state</tt>'
ref1 <- '<tt style="color: blue;">ref1</tt>'
ref2 <- '<tt style="color: blue;">ref2</tt>'
date <- '<tt style="color: blue;">date</tt>'
E_units <- '<tt style="color: blue;">E_units</tt>'
b <- '<tt style="color: blue;">b</tt>'
c <- '<tt style="color: blue;">c</tt>'
e <- '<tt style="color: blue;">e</tt>'
f <- '<tt style="color: blue;">f</tt>'
lambda <- '<tt style="color: blue;">lambda</tt>'
c1 <- '<tt style="color: blue;">c1</tt>'
c2 <- '<tt style="color: blue;">c2</tt>'
omega <- '<tt style="color: blue;">omega</tt>'
G_ <- '<tt style="color: blue;">G</tt>'
H_ <- '<tt style="color: blue;">H</tt>'
S_ <- '<tt style="color: blue;">S</tt>'
Cp_ <- '<tt style="color: blue;">Cp</tt>'
V_ <- '<tt style="color: blue;">V</tt>'
T_ <- '<tt style="color: blue;">T</tt>'
# CHNOSZ functions
reset_ <- '<code style="color: red;">reset()</code>'
OBIGT_ <- '<code style="color: red;">OBIGT()</code>'
add.OBIGT_ <- '<code style="color: red;">add.OBIGT()</code>'
mod.OBIGT_ <- '<code style="color: red;">mod.OBIGT()</code>'
logB.to.OBIGT_ <- '<code style="color: red;">logB.to.OBIGT()</code>'
basis_ <- '<code style="color: red;">basis()</code>'
species_ <- '<code style="color: red;">species()</code>'
E.units_ <- '<code style="color: red;">E.units()</code>'
info_ <- '<code style="color: green;">info()</code>'
subcrt_ <- '<code style="color: green;">subcrt()</code>'
affinity_ <- '<code style="color: green;">affinity()</code>'
thermo.refs_ <- '<code style="color: green;">thermo.refs()</code>'
thermo_ <- '<code style="color: green;">thermo()</code>'
check.GHS_ <- '<code style="color: green;">check.GHS()</code>'
check.EOS_ <- '<code style="color: green;">check.EOS()</code>'
# Math stuff
logK <- "log <i>K</i>"
logB <- "log β"
F_ <- "F<sup>-</sup>"
Hplus <- "H<sup>+</sup>"
HWO4_ <- "HWO<sub>4</sub><sup>-</sup>"
H2WO4 <- "H<sub>2</sub>WO<sub>4</sub>"
H3WO4F2_ <- "H<sub>3</sub>WO<sub>4</sub>F<sub>2</sub><sup>-</sup>"
# Thermodynamic properties
Cp_0 <- "<i>C<sub>p</sub></i>°"
DG_0 <- "Δ<i>G</i>°"
## ----system.file--------------------------------------------------------------
system.file("extdata/OBIGT", package = "CHNOSZ")
## ----dir.system.file----------------------------------------------------------
dir(system.file("extdata/OBIGT", package = "CHNOSZ"))
## ----reset_-------------------------------------------------------------------
reset()
## ----thermo.OBIGT-------------------------------------------------------------
head(thermo()$OBIGT)
## ----colnames.OBIGT, echo = FALSE---------------------------------------------
paste(1:22, colnames(thermo()$OBIGT))
## ----icr, message = FALSE-----------------------------------------------------
icr <- info(c("orpiment,amorphous", "arsenic,alpha", "tin"))
thermo()$OBIGT[icr, ]
## ----orpiment-----------------------------------------------------------------
subcrt("orpiment,amorphous", T = c(25, 50, 75))$out[[1]]
## ----arsenic------------------------------------------------------------------
subcrt("arsenic,alpha", T = c(25, 50, 75))$out[[1]]
## ----tin----------------------------------------------------------------------
subcrt("tin", T = c(25, 50, 75))$out[[1]]
## ----info_.tin----------------------------------------------------------------
info(info("tin"))
## ----Berman-------------------------------------------------------------------
info(info(c("quartz", "pyrite")))
## ----add.OBIGT_quartz---------------------------------------------------------
add.OBIGT("SUPCRT92", "quartz")
info(info("quartz"))
## ----add.OBIGT_SUPCRT92-------------------------------------------------------
iSUPCRT92 <- add.OBIGT("SUPCRT92")
unique(suppressMessages(info(iSUPCRT92))$name)
## ----BZA10--------------------------------------------------------------------
file <- system.file("extdata/adds/BZA10.csv", package = "CHNOSZ")
read.csv(file, as.is = TRUE)
## ----BZA10_Cd-----------------------------------------------------------------
iCd <- add.OBIGT(file)
subcrt(c("CdCl+", "Cl-", "CdCl2"), c(-1, -1, 1), T = 25, P = c(1, 2000))
## ----SSH97_subcrt-------------------------------------------------------------
reset()
thermo.refs(iCd)[, 1:3]
subcrt(c("CdCl+", "Cl-", "CdCl2"), c(-1, -1, 1), T = 25, P = c(1, 2000))
## ----mod.OBIGT__CoCl4_ghs-----------------------------------------------------
mod.OBIGT("CoCl4-2", formula = "CoCl4-2", state = "aq", ref1 = "LBT+11", E_units = "cal",
date = as.character(Sys.Date()), G = -134150, H = -171558, S = 19.55, Cp = 72.09, V = 27.74)
## ----mod.OBIGT__CoCl4_eos-----------------------------------------------------
mod.OBIGT("CoCl4-2", a1 = 6.5467, a2 = 8.2069, a3 = 2.0130, a4 = -3.1183,
c1 = 76.3357, c2 = 11.6389, omega = 2.9159, z = -2)
## ----CoCl4_reaction, message = FALSE, echo = 1:3------------------------------
T <- c(25, seq(50, 350, 50))
sres <- subcrt(c("Co+2", "Cl-", "CoCl4-2"), c(-1, -4, 1), T = T)
round(sres$out$logK, 2)
stopifnot(identical(round(sres$out$logK, 2), c(-3.2, -2.96, -2.02, -0.74, 0.77, 2.5, 4.57, 7.29)))
## ----info__CoCl4, results = "hide"--------------------------------------------
inew <- info("CoCl4-2")
info(inew)
## ----mod.OBIGT__magnesiochromite_ghs------------------------------------------
H <- -1762000
S <- 119.6
V <- 43.56
mod.OBIGT("magnesiochromite", formula = "MgCr2O4", state = "cr", ref1 = "KOSG00",
date = as.character(Sys.Date()), E_units = "J", H = H, S = S, V = V)
## ----mod.OBIGT__magnesiochromite_eos------------------------------------------
a <- 221.4
b <- -0.00102030
c <- -1757210
d <- -1247.9
mod.OBIGT("magnesiochromite", E_units = "J", a = a, b = b, c = c, d = d,
e = 0, f = 0, lambda = 0, T = 1500)
## ----subcrt__magnesiochromite-------------------------------------------------
T.units("K")
Tref <- c(250, 300, 340)
(sres <- subcrt("magnesiochromite", property = "Cp", T = Tref, P = 1))
## ----magnesiochromite_check_Cp------------------------------------------------
Cpref <- c(114.3, 129.8, 138.4)
stopifnot(max(abs(sres$out[[1]]$Cp - Cpref)) < 0.3)
## ----restore_units_magnesiochromite-------------------------------------------
T.units("C")
## ----Psat---------------------------------------------------------------------
P <- "Psat"
## ----HWO4_--------------------------------------------------------------------
T <- c(250, 300, 350)
logB <- c(5.58, 6.51, 7.99)
species <- c("WO4-2", "H+", "HWO4-")
coeff <- c(-1, -1, 1)
logB.to.OBIGT(logB, species, coeff, T, P)
## ----H3WO4F2------------------------------------------------------------------
T <- seq(100, 250, 25)
logB <- c(17.00, 17.11, 17.46, 17.75, 18.17, 18.71, 19.23)
# Species and coefficients in the formation reaction
species <- c("H+", "WO4-2", "F-", "H3WO4F2-")
coeff <- c(-3, -1, -2, 1)
logB.to.OBIGT(logB, species, coeff, T, P)
## ----H2WO4--------------------------------------------------------------------
logB <- c(7.12, 7.82, 7.07, 7.76, 7.59, 7.98, 8.28)
species <- c("H+", "WO4-2", "H2WO4")
coeff <- c(-2, -1, 1)
logB.to.OBIGT(logB, species, coeff, T, P, tolerance = 0.3)
## ----diagram1, message = FALSE, results = "hide", fig.width = 6, fig.height = 5, out.width = "75%", fig.align = "center", pngquant = pngquant----
basis(c("H+", "WO4-2", "F-", "H2O", "O2"))
basis("F-", log10(0.1))
iaq <- retrieve("W", c("O", "H", "F"), "aq")
species(iaq)
a <- affinity(pH = c(2, 7), T = 300, IS = 0.9)
e <- equilibrate(a)
col <- c(1, 4, 5, 2)
diagram(e, alpha = TRUE, col = col, lty = 1, lwd = 2, ylab = "Fraction total W")
## ----a_F----------------------------------------------------------------------
T <- 300
pH <- seq(2, 7, 0.1)
logK_HF <- subcrt(c("H+", "F-", "HF"), c(-1, -1, 1), T = T, IS = 0.9)$out$logK
F_tot <- 0.1
a_F <- F_tot / (1 + 10^(logK_HF - pH))
## ----diagram2, message = FALSE, results = "hide", results = "hide", fig.width = 6, fig.height = 5, out.width = "75%", fig.align = "center", pngquant = pngquant----
basis(c("H+", "WO4-2", "F-", "H2O", "O2"))
iaq <- retrieve("W", c("O", "H", "F"), "aq")
species(iaq)
a <- affinity(pH = pH, "F-" = log10(a_F), T = T, IS = 0.9)
e <- equilibrate(a)
diagram(e, alpha = TRUE, col = col, lty = 1, lwd = 2, ylab = "Fraction total W")
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/doc/custom_data.R
|
---
title: "Customizing the thermodynamic database"
author: "Jeffrey M. Dick"
output:
html_vignette:
mathjax: null
toc: true
vignette: >
%\VignetteIndexEntry{Customizing the thermodynamic database}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
bibliography: vig.bib
csl: elementa.csl
link-citations: true
---
```{r setup, include = FALSE}
library(CHNOSZ)
options(width = 80)
## Use pngquant to optimize PNG images
library(knitr)
knit_hooks$set(pngquant = hook_pngquant)
pngquant <- "--speed=1 --quality=0-25"
if (!nzchar(Sys.which("pngquant"))) pngquant <- NULL
# Set dpi 20231129
knitr::opts_chunk$set(
dpi = if(nzchar(Sys.getenv("CHNOSZ_BUILD_LARGE_VIGNETTES"))) 100 else 72
)
```
```{r HTML, include = FALSE}
NOTE <- '<span style="background-color: yellow;">NOTE</span>'
# OBIGT columns
model <- '<span style="color: blue;">model</span>'
name <- '<tt style="color: blue;">name</tt>'
abbrv <- '<tt style="color: blue;">abbrv</tt>'
formula <- '<tt style="color: blue;">formula</tt>'
state <- '<tt style="color: blue;">state</tt>'
ref1 <- '<tt style="color: blue;">ref1</tt>'
ref2 <- '<tt style="color: blue;">ref2</tt>'
date <- '<tt style="color: blue;">date</tt>'
E_units <- '<tt style="color: blue;">E_units</tt>'
b <- '<tt style="color: blue;">b</tt>'
c <- '<tt style="color: blue;">c</tt>'
e <- '<tt style="color: blue;">e</tt>'
f <- '<tt style="color: blue;">f</tt>'
lambda <- '<tt style="color: blue;">lambda</tt>'
c1 <- '<tt style="color: blue;">c1</tt>'
c2 <- '<tt style="color: blue;">c2</tt>'
omega <- '<tt style="color: blue;">omega</tt>'
G_ <- '<tt style="color: blue;">G</tt>'
H_ <- '<tt style="color: blue;">H</tt>'
S_ <- '<tt style="color: blue;">S</tt>'
Cp_ <- '<tt style="color: blue;">Cp</tt>'
V_ <- '<tt style="color: blue;">V</tt>'
T_ <- '<tt style="color: blue;">T</tt>'
# CHNOSZ functions
reset_ <- '<code style="color: red;">reset()</code>'
OBIGT_ <- '<code style="color: red;">OBIGT()</code>'
add.OBIGT_ <- '<code style="color: red;">add.OBIGT()</code>'
mod.OBIGT_ <- '<code style="color: red;">mod.OBIGT()</code>'
logB.to.OBIGT_ <- '<code style="color: red;">logB.to.OBIGT()</code>'
basis_ <- '<code style="color: red;">basis()</code>'
species_ <- '<code style="color: red;">species()</code>'
E.units_ <- '<code style="color: red;">E.units()</code>'
info_ <- '<code style="color: green;">info()</code>'
subcrt_ <- '<code style="color: green;">subcrt()</code>'
affinity_ <- '<code style="color: green;">affinity()</code>'
thermo.refs_ <- '<code style="color: green;">thermo.refs()</code>'
thermo_ <- '<code style="color: green;">thermo()</code>'
check.GHS_ <- '<code style="color: green;">check.GHS()</code>'
check.EOS_ <- '<code style="color: green;">check.EOS()</code>'
# Math stuff
logK <- "log <i>K</i>"
logB <- "log β"
F_ <- "F<sup>-</sup>"
Hplus <- "H<sup>+</sup>"
HWO4_ <- "HWO<sub>4</sub><sup>-</sup>"
H2WO4 <- "H<sub>2</sub>WO<sub>4</sub>"
H3WO4F2_ <- "H<sub>3</sub>WO<sub>4</sub>F<sub>2</sub><sup>-</sup>"
# Thermodynamic properties
Cp_0 <- "<i>C<sub>p</sub></i>°"
DG_0 <- "Δ<i>G</i>°"
```
This vignette was compiled on `r Sys.Date()` with CHNOSZ version `r sessionInfo()$otherPkgs$CHNOSZ$Version`.
This vignette will cover some topics about using custom thermodynamic data in CHNOSZ.
The two main functions to remember are `r add.OBIGT_` to add data from a CSV file and `r mod.OBIGT_` to add or modify data through a function interface.
A third function, `r logB.to.OBIGT_`, is provided to fit thermodynamic parameters to experimental formation constants (`r logB`).
Before describing the methods to add or modify data, some notes on the basic structure of the database and data entry conventions are given.
Column names (or parts thereof) are formatted in blue (e.g. `r formula`), and important notes are highlighted in yellow (`r NOTE`).
Function names in CHNOSZ are colored red for functions that have side effects (including those that modify the database; e.g. `r add.OBIGT_`) and green for functions that don't have side effects.
Note that `r info_` is used for querying the OBIGT thermodynamic database, and `r subcrt_` is the main function in CHNOSZ for calculating standard thermodynamic properties as a function of temperature and pressure from the parameters in the database.
<!-- ######## SECTION MARKER ######## -->
## Basic structure of OBIGT
OBIGT is the name of the thermodynamic database in CHNOSZ.
The data are distributed in CSV files in the `inst/extdata/OBIGT` directory of the CHNOSZ package.
When the package is installed, the files are copied to the `exdata/OBIGT` directory of the installed package location.
To find out where this is on your computer, run the following command.
```{r system.file}
system.file("extdata/OBIGT", package = "CHNOSZ")
```
The directory path on your computer will be different.
Although possible, it is **NOT** recommended to edit the data files at that location.
This is because they will be overwritten by package updates; moreover, it is good practice to keep all the files needed for your project in a project directory.
This lists the files in the installation directory:
```{r dir.system.file}
dir(system.file("extdata/OBIGT", package = "CHNOSZ"))
```
Some of these files are used to build the default OBIGT database that is created when CHNOSZ starts up.
There are also a number of additional data files that have optional datasets.
The [<span style="color:blue">*OBIGT thermodynamic database*</span>](OBIGT.html) vignette summarizes the contents of the default and optional data files.
The files can also be opened by a spreadsheet program and used as templates for adding data yourself.
`thermo()$OBIGT` (hereafter, just OBIGT) is the "live" version of the database that is assembled from the CSV data files when CHNOSZ starts up or by using the `r reset_` or `r OBIGT_` functions.
The OBIGT data frame is stored in an environment named `CHNOSZ` that is part of the namespace of the CHNOSZ package.
More specifically, it is part of a list named `thermo`, which has the OBIGT database and other parameters and settings used by CHNOSZ.
`r reset_` restores the entire `thermo` object to default values; `r OBIGT_` restores just the OBIGT data frame.
The latter is useful for seeing the effects of changing the thermodynamic database on on chemical affinities calculated with `r affinity_`, without changing the chemical species.
OBIGT can be modified during an R session; if it couldn't, some of the examples in this vignette would not be possible!
When you quit R, it offers the option of saving your workspace so it can be reloaded it when R is restarted.
I always say "no" here; my preference is to load data into a fresh session every time I start R.
This "load saved workspace" feature means that OBIGT might not be the default database in any given R session.
To ensure that this vignette is run using the default database, we start by running `r reset_` to reset OBIGT and the other settings used by CHNOSZ.
```{r reset_}
reset()
```
`r thermo_` is a convenience function to access or modify parts of the `thermo` list object.
To see the first few entries in OBIGT, do this:
```{r thermo.OBIGT}
head(thermo()$OBIGT)
```
<!-- ######## SECTION MARKER ######## -->
## Conventions for data entry in OBIGT
The format of OBIGT is described in the CHNOSZ manual: see `r thermo_`.
Next, we point out some particular conventions including types of data, required and optional data, order-of-magnitude scaling.
Here are the numbered column names for reference:
```{r colnames.OBIGT, echo = FALSE}
paste(1:22, colnames(thermo()$OBIGT))
```
### Types of data
- Columns 1--9 have character data.
- Column 8 is named `r model`; here are the two models that are most frequent in the default database:
- `HKF`: Revised Helgeson-Kirkham-Flowers "equation-of-state" parameters for aqueous species
- `CGL`: Heat capacity coefficients for crystalline, gaseous, and liquid species. The first three terms in the CGL heat capacity equation correspond to the Maier-Kelley equation for heat capacity [@MK32]; the additional terms are useful for representing heat capacities of minerals [@RH95] and organic gases and liquids [@HOKR98].
- Columns 10--22 have numeric data.
- Columns 10--14 have standard-state thermodynamic properties at 25 °C and 1 bar.
- Columns 15--21 have parameters for calculating thermodynamic properties at other temperatures and pressures.
- The columns are named by combining the the names of the HKF and CGL coefficients, separated by a dot.
- Column 22 has the charge used in the HKF EOS or the maximum temperature for CGL species.
- `r NOTE`: The value of charge used in the HKF EOS (in particular, the *g* function for the temperature derivatives of the ω parameter [@SOJSH92]) is taken from this column and not from the chemical formula of the species.
### Ranges of HKF and CGL models
To a first approximation, the revised HKF equations of state are applicable within the stability region of liquid water or the supercritical fluid with a density greater than 0.35 g/cm3, and not exceeding the ranges of 0 to 1000 °C and 1 to 5000 bar [see @SOJSH92 for details].
There are two ways in which these limits are enforced in CHNOSZ:
- The default source of water properties (H2O92D Fortran subroutine modified from SUPCRT92) yields NA values beyonds these T and P ranges.
Note that the Deep Earth Water (DEW) model is available to extend the applicable range to pressures of up to 60 kbar (6 GPa) [@SHA14].
- `r subcrt_` generates NA values beyond the density limit; the `exceed.rhomin` argument can be used to enable calculations at lower density in the supercritical region.
The upper temperature limit for validity of the CGL heat-capacity equation is a species-dependent parameter.
This value is stored as a negative value in the `r T_` column of OBIGT and is used by `r subcrt_` to issue a warning at temperatures beyond this limit.
### Required and optional data
REQUIRED:
- All species need a `r name` and a `r state`.
- The state can be one of `aq`, `gas`, or `cr`.
- For minerals with higher-temperature polymorphs, they are named `cr2`, `cr3`, etc.
- `r NOTE`: `cr` stands for "crystalline"; this naming convention (which was inherited from SUPCRT92 data files) refers to any solid phases including amorphous SiO<sub>2</sub> and other minerals.
- A chemical `r formula` is required to do almost anything useful in CHNOSZ (e.g. check reaction balancing with `r subcrt_` and add species with `r basis_` or `r species_`).
- `r NOTE`: The `r name` of *inorganic* aqueous species *and CH<sub>4</sub>* in OBIGT is the same as the chemical formula.
- Most minerals, gases, liquids, and organic aqueous species have a `r name` that is a common name. This permits a shortcut to identify commonly used species in `r subcrt_`.
- For example, `info("O2")` refers to dissolved oxygen, while `info("oxygen")` or `info("O2", "gas")` refers to the gas.
- `E_units` needs to be defined to perform any calculations of thermodynamic properties.
- The value can be `J` for Joules or `cal` for calories.
OPTIONAL: Everything else.
Really, it depends on what you need.
For instance, if you just want to use `r subcrt_` to calculate `r logK` of a reaction from `r DG_0` of species at 25 °C, then `r G_` is the only parameter that is needed.
OPTIONAL but useful:
- `r abbrv` *may be* an abbreviation (e.g. Qtz for quartz). It is used by `r info_` (together with `r name` and `r formula`) to look up species in the database.
- `r date` is a timestamp for the data entry (YYYY-MM-DD format in the default OBIGT database).
- `r ref1` and `r ref2` are bibliographic reference keys. They have matching entries in `extdata/OBIGT/refs.csv`, which is used by `r thermo.refs_` to display references, and in `vignettes/OBIGT.bib`, which is used in the [<span style="color:blue">*OBIGT thermodynamic database*</span>](OBIGT.html) vignette to produce a reference list.
`r NOTE`: Other functions in CHNOSZ do not depend on `r date`, `r ref1`, and `r ref2`, so you can put anything there that is convenient for you.
### NA or 0?
If a character value (in Columns 1--9) or thermodynamic parameter (in Columns 10--14) is unknown, use `NA`.
Note that a missing (blank) value in the file is treated as NA.
- Unknown values for character values (usually `r abbrv`, `r date`, `r ref1`, or `r ref2`) should be NA.
- If you have only two of `r G_`, `r H_`, and `r S_`, then the missing one should be NA.
- Do **NOT** set a missing value of `r G_`, `r H_`, or `r S_` to 0. Zero is a numeric value that is incorrect except for very special cases.
- `r NOTE`: `r info_` -- and, by extension, `r subcrt_` -- "know" about the equation Δ<i>G</i>°<sub><i>f</i></sub> = Δ<i>H</i>°<sub><i>f</i></sub> - <i>T</i>Δ<i>S</i>°<sub><i>f</i></sub> and the entropies of the elements needed to calculate Δ<i>S</i>°<sub><i>f</i></sub> from values of `r S_` in OBIGT. This equation is used to compute a missing value of `r G_`, `r H_`, or `r S_` from the other two, or to cross-check the values if all three are present for any species.
- If you don't have `r Cp_` or `r V_`, then set it to NA.
- If HKF or CGL parameters are present, they will be used to calculate `r Cp_`, so thermodynamic properties *can* be calculated at T > 25 °C.
- If HKF or CGL parameters aren't present, thermodynamic properties *can't* be calculated at T > 25 °C (NAs will propagate to higher T).
If an "equation-of-state" parameter or heat capacity coefficient (Columns 15-21) is unknown, use 0.
- Furthermore, if you would like to assume that `r Cp_` or `r V_` is 0, then set it to 0.
- Then, thermodynamic properties will be extrapolated to T > 25 °C and P > 1 bar assuming that `r Cp_` and `r V_` are 0.
More detail on the inner working of the functions: For both HKF and CGL, if at least one parameter for a species is provided, any NA values of the other parameters are taken to be zero.
If all EOS parameters are NA, but values of `r Cp_` and/or `r V_` are present, they are assumed to be constants for extrapolating thermodynamic properties (e.g. `r DG_0`) as a function of temperature and pressure.
### OOM scaling and `r info_`
HKF parameters in the the CSV files and OBIGT data frame are scaled by order-of-magnitude (OOM) factors.
For these parameters, OOM scaling is nearly always used in published data tables.
See `r thermo_` for details of the OOM scaling.
`r info_` provides a simple user interface to the OBIGT database and is called by other functions in CHNOSZ to retrieve unscaled values from the database.
This is a summary of its main features:
- Remove OOM scaling. This is used primarily by other functions in CHNOSZ to get a set of unscaled `r model` parameters for calculating thermodynamic properties as a function of T and P.
- Extract the HKF or CGL parts of column names (only if all matching species have the same `r model`).
- Calculate a missing one of `r G_`, `r H_`, or `r S_` if two of them are present.
- Cross-check `r G_`, `r H_`, and `r S_` if all of them are present, and print a message if the difference is above a threshold (see `r check.GHS_`).
- Calculate a missing `r Cp_` or `r V_` from the `r model` parameters, if possible.
- Cross-check `r Cp_` or `r V_` (if present) against the `r model` parameters, if possible, and print a message if the difference is above a threshold (see `r check.EOS_`).
`r NOTE`: `r info_` does **NOT** change the units of energy; the values it displays (including possibly calculated ones) correspond to the `r E_units` for that species in OBIGT.
On the other hand, `r subcrt_` outputs values in the units previously selected with the function `r E.units_`.
<!-- ######## SECTION MARKER ######## -->
## Case study: NA and 0 in the default database
Use the `r info_` function to look at the database and `r subcrt_` to calculate thermodynamic properties.
Let's look at some minerals first.
First use `r info_` to get the species indices (i.e. rownumbers) in OBIGT, then pull out the "raw" data (including any NA values).
```{r icr, message = FALSE}
icr <- info(c("orpiment,amorphous", "arsenic,alpha", "tin"))
thermo()$OBIGT[icr, ]
```
Based on the values in the `r Cp_` column, would you predict that thermodynamic properties at T > 25 °C could be calculated for all of these minerals?
Let's see ...
For conciseness we'll consider a relatively small temperature range and display only the `out` part of the `r subcrt_` output.
```{r orpiment}
subcrt("orpiment,amorphous", T = c(25, 50, 75))$out[[1]]
```
That makes sense; integrating NA `r Cp_` to calculate Gibbs energy and other thermodynamic properties would propagate NA, and that is what appears in the output.
Now let's run the calculation for the alpha phase of arsenic.
```{r arsenic}
subcrt("arsenic,alpha", T = c(25, 50, 75))$out[[1]]
```
What happened here?
Even though there are no heat capacity coefficients (see above), there is a non-NA value of `r Cp_`, and that value is used together with the entropy for calculating Gibbs energy at T > 25 °C.
Note that zero for the 25 °C values of G and H in this case is not a placeholder for unknown values (as noted above, unknown values should be represented by NA).
Instaed, this is the reference state for the element, for which G and H are by convention equal to zero.
Let's look at another element in its reference state, tin:
```{r tin}
subcrt("tin", T = c(25, 50, 75))$out[[1]]
```
Are you surprised?
You might be if you only noticed the NA value for `r Cp_` in OBIGT.
However, there are non-NA values for the heat capacity coefficients, which are used to calculate `r Cp_0` as a function of temperature.
When supplied with a numeric argument (a species index), `r info_` actually does this to fill in missing 25 °C values of `r Cp_`, `r V_`, and `r G_`, `r H_`, or `r S_` if possible, in addition to simplifying column names:
```{r info_.tin}
info(info("tin"))
```
## Examples of adding data from a file
Using `r add.OBIGT_` to add data from optional data files for OBIGT or CSV files you make yourself.
### `r add.OBIGT_` with optional data files
The default database has parameters for many minerals from @Ber88; a notable exception is sulfide minerals, which are from @HDNB78.
Besides the different literature sources in `r ref1`, the `r model` column indicates that a different model is used for these minerals (Berman equations or CGL).
```{r Berman}
info(info(c("quartz", "pyrite")))
```
Sometimes it is useful to load mineral data from the SUPCRT92 database, corresponding largely to the compilation by @HDNB78.
This can be done with `r add.OBIGT_`.
In this example we load SUPCRT92 data for just one mineral, quartz.
```{r add.OBIGT_quartz}
add.OBIGT("SUPCRT92", "quartz")
info(info("quartz"))
```
Here we load all minerals available in the optional SUPCRT92 data file and then list the names.
`r NOTE`: `suppressMessages()` is used to suppress messages from `r info_` about missing parameters, and `unique()` is used to list each mineral only once (because each polymorph has a separate entry).
```{r add.OBIGT_SUPCRT92}
iSUPCRT92 <- add.OBIGT("SUPCRT92")
unique(suppressMessages(info(iSUPCRT92))$name)
```
### `r add.OBIGT_` with other CSV files
`r add.OBIGT_` can also be used to add data from a user-specified file to the OBIGT database.
The file must be a CSV (comma separated value) file with column headers that match those in the default database (i.e., `thermo()$OBIGT`).
As an example, here are the contents of `BZA10.csv`, which has parameters taken from @BZA10.
Missing values are indicated by `NA`:
```{r BZA10}
file <- system.file("extdata/adds/BZA10.csv", package = "CHNOSZ")
read.csv(file, as.is = TRUE)
```
Loading the data with `r add.OBIGT_` produces a message that the new data replace existing species.
We can then use `r subcrt_` to calculate the equilibrium constant for a reaction involving the new species.
Note the decrease in the stepwise stability constant for the second cadmium chloride complex with increasing pressure (Bazarkina et al., 2010, Fig. 4).
```{r BZA10_Cd}
iCd <- add.OBIGT(file)
subcrt(c("CdCl+", "Cl-", "CdCl2"), c(-1, -1, 1), T = 25, P = c(1, 2000))
```
After running `r reset_` we can look up the source of data in the default OBIGT database [@SSH97].
Running the reaction with thermodynamic parameters from the default database, we now see that the equilibrium constant is not as sensitive to pressure:
```{r SSH97_subcrt}
reset()
thermo.refs(iCd)[, 1:3]
subcrt(c("CdCl+", "Cl-", "CdCl2"), c(-1, -1, 1), T = 25, P = c(1, 2000))
```
<!-- ######## SECTION MARKER ######## -->
## Examples of adding and modifying data with a function
Use `r mod.OBIGT_` to add or modify the database in the current session.
The function requires the name of a species and one or more properties to change.
### `r mod.OBIGT_` for aqueous species
Let's add data for CoCl<sub>4</sub><sup>-2</sup> from @LBT_11.
The values are taken from Table 5 of that paper; note that they are reported in caloric units, which is rather common for the HKF model.
The entry includes the date in ISO 8601 extended format (e.g. 2020-08-16); `Sys.Date()` is used in this example to get the current date.
```{r mod.OBIGT__CoCl4_ghs}
mod.OBIGT("CoCl4-2", formula = "CoCl4-2", state = "aq", ref1 = "LBT+11", E_units = "cal",
date = as.character(Sys.Date()), G = -134150, H = -171558, S = 19.55, Cp = 72.09, V = 27.74)
```
The function prints a message saying that the species was added and returns the species index of the new species.
Now let's modify the new species by adding the HKF coefficients including the OOM multipliers, as they are usually given in publications.
The `z` at the end refers to the charge of the species, and is used only for calculating the "*g* function" in the revised HKF model, not for balancing reactions.
```{r mod.OBIGT__CoCl4_eos}
mod.OBIGT("CoCl4-2", a1 = 6.5467, a2 = 8.2069, a3 = 2.0130, a4 = -3.1183,
c1 = 76.3357, c2 = 11.6389, omega = 2.9159, z = -2)
```
Let us now calculate the equilibrium constant for the formation of CoCl<sub>4</sub><sup>-2</sup> from Co<sup>+2</sup> and Cl<sup>-</sup>.
```{r CoCl4_reaction, message = FALSE, echo = 1:3}
T <- c(25, seq(50, 350, 50))
sres <- subcrt(c("Co+2", "Cl-", "CoCl4-2"), c(-1, -4, 1), T = T)
round(sres$out$logK, 2)
stopifnot(identical(round(sres$out$logK, 2), c(-3.2, -2.96, -2.02, -0.74, 0.77, 2.5, 4.57, 7.29)))
```
The calculated values of log*K* are identical to those in Table 9 of @LBT_11, which provides a good indication that the thermodynamic parameters were entered correctly.
Nevertheless, this isn't a guarantee that the thermodynamic parameters are consistent with the provided values of *C*<sub>*P*</sub>° and *V*°.
We can see this by running `r info_` to cross-check the parameters for the new CoCl<sub>4</sub><sup>-2</sup> species:
```{r info__CoCl4, results = "hide"}
inew <- info("CoCl4-2")
info(inew)
```
The messages indicate that the given values of *C*<sub>*P*</sub>° and *V*° differ slightly from those calculated using the HKF parameters.
### `r mod.OBIGT_` for minerals
Let's add data for magnesiochromite from @KOSG00.
The parameters in this paper are reported in Joules, so we set the `r E.units_` to J.
The value for volume, in cm<sup>3</sup> mol<sup>-1</sup>, is from @RH95.
```{r mod.OBIGT__magnesiochromite_ghs}
H <- -1762000
S <- 119.6
V <- 43.56
mod.OBIGT("magnesiochromite", formula = "MgCr2O4", state = "cr", ref1 = "KOSG00",
date = as.character(Sys.Date()), E_units = "J", H = H, S = S, V = V)
```
Here are the heat capacity parameters for the Haas-Fisher polynomial equation ($Cp = a + bT + cT^{-2} + dT^{-0.5} + eT^2$).
As of CHNOSZ 2.0.0, OOM multipliers are not used for these coefficients.
1500 K is a generic value for the high-temperature limit; experimental heat capacities were only reported up to 340 K [@KOSG00].
```{r mod.OBIGT__magnesiochromite_eos}
a <- 221.4
b <- -0.00102030
c <- -1757210
d <- -1247.9
mod.OBIGT("magnesiochromite", E_units = "J", a = a, b = b, c = c, d = d,
e = 0, f = 0, lambda = 0, T = 1500)
```
`r NOTE`: An additional `r f` term is available, which can have any exponent given in `r lambda`.
This offers some flexibility for using heat capacity equations that are different from the Haas-Fisher polynomial.
Now we can use `r subcrt_` to calculate the heat capacity of magnesiochromite.
For this calculation, we set the temperature units to Kelvin.
We also specify a pressure of 1 bar because the default setting of *P*<sub>sat</sub> (liquid-vapor saturation) causes an error below the freezing temperature of water.
```{r subcrt__magnesiochromite}
T.units("K")
Tref <- c(250, 300, 340)
(sres <- subcrt("magnesiochromite", property = "Cp", T = Tref, P = 1))
```
Next we check that the calculated values are within 0.3 J K<sup>-1</sup> mol<sup>-1</sup> of reference values taken from Fig. 1 of @KOSG00.
```{r magnesiochromite_check_Cp}
Cpref <- c(114.3, 129.8, 138.4)
stopifnot(max(abs(sres$out[[1]]$Cp - Cpref)) < 0.3)
```
Finally, let's restore the units setting for later calculations with `r subcrt_`.
(Another way would be to run `r reset_`, which also resets the OBIGT database.)
```{r restore_units_magnesiochromite}
T.units("C")
```
<!-- ######## SECTION MARKER ########
## Other models
Here we'll look at how to add minerals that use the Berman equations and aqueous nonelectrolytes that use the Akinfiev-Diamond model.
### Akinfiev-Diamond model
The Akinfiev-Diamond model for aqueous species [@AD03] is activated by setting \code{abbrv = "AD"} in `r thermo_` for a given aqueous species.
The database must also include a corresponding gaseous species with the same name or chemical formula.
TODO
TODO: Add van't Hoff example?
-->
<!-- ######## SECTION MARKER ######## -->
## Case study: Formation constants for aqueous tungsten species
Here we use `r logB.to.OBIGT_` to fit to thermodynamic parameters to experimental formation constants.
Some additional steps are shown to refine a thermodynamic model to generate a speciation diagram as a function of pH.
### Fitting formation constants
`r logB.to.OBIGT_` requires three things:
- Experimental decimal logarithms of formation constants (`r logB`) as a function of temperature;
- The stoichiometry of the formation reaction in terms of known species (the new species must be last);
- The experimental temperature and pressure.
`r logB.to.OBIGT_` does three things:
- Combines the formation constants with standard Gibbs energies (`r DG_0`) of the known species to calculate `r DG_0` of the new species;
- Fits `r DG_0` of the new species using 25 °C thermodynamic properties and selected HKF model parameters (i.e., `r G_`, `r S_`, `r c1`, `r c2`, and `r omega` parameters in OBIGT);
- Adds the parameters to OBIGT for use by other functions in CHNOSZ.
First we set the pressure for all `r logB` data.
```{r Psat}
P <- "Psat"
```
Add first species: `r HWO4_` [@WTW_19].
```{r HWO4_}
T <- c(250, 300, 350)
logB <- c(5.58, 6.51, 7.99)
species <- c("WO4-2", "H+", "HWO4-")
coeff <- c(-1, -1, 1)
logB.to.OBIGT(logB, species, coeff, T, P)
```
Add second species: `r H3WO4F2_` [@WWH_21].
```{r H3WO4F2-}
T <- seq(100, 250, 25)
logB <- c(17.00, 17.11, 17.46, 17.75, 18.17, 18.71, 19.23)
# Species and coefficients in the formation reaction
species <- c("H+", "WO4-2", "F-", "H3WO4F2-")
coeff <- c(-3, -1, -2, 1)
logB.to.OBIGT(logB, species, coeff, T, P)
```
Add third species: `r H2WO4` [@WWH_21].
Here we increase the tolerance because there is considerable scatter in the experimental values.
```{r H2WO4}
logB <- c(7.12, 7.82, 7.07, 7.76, 7.59, 7.98, 8.28)
species <- c("H+", "WO4-2", "H2WO4")
coeff <- c(-2, -1, 1)
logB.to.OBIGT(logB, species, coeff, T, P, tolerance = 0.3)
```
After running, `r logB.to.OBIGT_` returns the species indices; the low values for `r HWO4_` (`r info("HWO4-")`) and `r H2WO4` (`r info("H2WO4")`) indicate that the function replaced parameters for these species that were already present in OBIGT.
### Diagram 1: Constant molality of `r F_`
Now we're ready to make a speciation diagram.
Our aim is to reproduce Fig. 7b of @WWH_21, which is made for 300 °C.
A constant molality of `r F_` is based on the assumption of complete dissociation of 0.1 m NaF (we'll change this later).
An ionic strength of 0.9 mol/kg is estimated for a solution with 1.8 m NaCl (use `NaCl(1.8, T = 300)`).
`r NOTE`: because the ionic strength is non-zero, the calculations here refer to molality instead of activity of species (see [An Introduction to CHNOSZ](anintro.html#from-activity-to-molality)).
```{r diagram1, message = FALSE, results = "hide", fig.width = 6, fig.height = 5, out.width = "75%", fig.align = "center", pngquant = pngquant}
basis(c("H+", "WO4-2", "F-", "H2O", "O2"))
basis("F-", log10(0.1))
iaq <- retrieve("W", c("O", "H", "F"), "aq")
species(iaq)
a <- affinity(pH = c(2, 7), T = 300, IS = 0.9)
e <- equilibrate(a)
col <- c(1, 4, 5, 2)
diagram(e, alpha = TRUE, col = col, lty = 1, lwd = 2, ylab = "Fraction total W")
```
This isn't quite the diagram we were looking for.
The published diagram shows a broad region of coexistence of `r H3WO4F2_` and `r HWO4_` at pH < 5 and increasing abundance of `r H2WO4` at lower pH.
### Diagram 2: Variable molality of `r F_`
In reality, the molality of `r F_` depends strongly on pH according to the reaction `r Hplus` + `r F_` = HF.
With a little algebra, we can calculate the molality of `r F_` (`a_F` in the code below) from the equilbrium constant of this reaction for a given total F concentration (`F_tot`).
`r NOTE`: It is important to call `r subcrt_` with a non-zero `IS` so that it returns effective equilibrium constants corrected for ionic strength (try setting `IS = 0` yourself and look at what happens to the diagram).
```{r a_F}
T <- 300
pH <- seq(2, 7, 0.1)
logK_HF <- subcrt(c("H+", "F-", "HF"), c(-1, -1, 1), T = T, IS = 0.9)$out$logK
F_tot <- 0.1
a_F <- F_tot / (1 + 10^(logK_HF - pH))
```
Now that we have the molality of `r F_` as a function of pH, we can provide it in the call to `r affinity_`.
```{r diagram2, message = FALSE, results = "hide", results = "hide", fig.width = 6, fig.height = 5, out.width = "75%", fig.align = "center", pngquant = pngquant}
basis(c("H+", "WO4-2", "F-", "H2O", "O2"))
iaq <- retrieve("W", c("O", "H", "F"), "aq")
species(iaq)
a <- affinity(pH = pH, "F-" = log10(a_F), T = T, IS = 0.9)
e <- equilibrate(a)
diagram(e, alpha = TRUE, col = col, lty = 1, lwd = 2, ylab = "Fraction total W")
```
That's more like it.
We have captured the basic geometry of Fig. 7b in @WWH_21.
For instance, in accord with the published diagram, `r HWO4_` plateaus at around 40% of total W, and `r H2WO4` and `r H3WO4F2_` are nearly equally abundant at pH = 2.
The highest experimental temperature for the formation constants of `r H2WO4` and `r H3WO4F2_` is 250 °C, but this diagram is drawn for 300 °C.
@WWH_21 used the modified Ryzhenko-Bryzgalin (MRB) model to extrapolate to 300 °C.
In contrast, we used a different model but obtained quite similar results.
`r NOTE`: The coefficients in the model used by `r logB.to.OBIGT_` include 25 °C values of `r G_` and `r S_`.
These should be conservatively treated only as *fitting parameters* and should not be used to compute thermodynamic properties close to 25 °C unless they were fit to experimental data in that temperature range.
## References
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/doc/custom_data.Rmd
|
## ----width80, include=FALSE---------------------------------------------------
options(width = 80)
## ----digits6, include=FALSE---------------------------------------------------
options(digits = 6)
## ----HTML, include=FALSE------------------------------------------------------
## Some frequently used HTML expressions
V0 <- "<i>V</i>°"
Cp0 <- "<i>C<sub>P</sub></i>°"
c1 <- "<i>c</i><sub>1</sub>"
c2 <- "<i>c</i><sub>2</sub>"
a1 <- "<i>a</i><sub>1</sub>"
a2 <- "<i>a</i><sub>2</sub>"
a3 <- "<i>a</i><sub>3</sub>"
a4 <- "<i>a</i><sub>4</sub>"
h4sio4 <- "H<sub>4</sub>SiO<sub>4</sub>"
sio2 <- "SiO<sub>2</sub>"
h2o <- "H<sub>2</sub>O"
ch4 <- "CH<sub>4</sub>"
wPrTr <- "ω<sub><i>P<sub>r</sub></i>,<i>T<sub>r</sub></i></sub>"
## ----setup, include=FALSE-----------------------------------------------------
library(knitr)
# Invalidate cache when the tufte version changes
opts_chunk$set(tidy = FALSE, cache.extra = packageVersion('tufte'))
options(htmltools.dir.version = FALSE)
# Adjust plot margins
knit_hooks$set(small.mar = function(before, options, envir) {
if (before) par(mar = c(4.2, 4.2, .3, .3)) # smaller margin on top and right
})
# Use pngquant to optimize PNG images
knit_hooks$set(pngquant = hook_pngquant)
# pngquant isn't available on R-Forge ...
if (!nzchar(Sys.which("pngquant"))) {
pngquant <- NULL
} else {
pngquant <- "--speed=1 --quality=0-50"
}
## Colorize messages 20171031
## Adapted from https://gist.github.com/yihui/2629886#file-knitr-color-msg-rnw
color_block = function(color) {
function(x, options) sprintf('<pre style="color:%s">%s</pre>', color, x)
}
knit_hooks$set(warning = color_block('magenta'), error = color_block('red'), message = color_block('blue'))
# Set dpi 20231129
knitr::opts_chunk$set(
dpi = if(nzchar(Sys.getenv("CHNOSZ_BUILD_LARGE_VIGNETTES"))) 72 else 50
)
## ----library_CHNOSZ-----------------------------------------------------------
library(CHNOSZ)
reset()
## ----Cpdat--------------------------------------------------------------------
file <- system.file("extdata/cpetc/HW97_Cp.csv", package = "CHNOSZ")
Cpdat <- read.csv(file)
# Use data for CH4
Cpdat <- Cpdat[Cpdat$species == "CH4", ]
Cpdat <- Cpdat[, -1]
Cpdat$P <- convert(Cpdat$P, "bar")
## ----EOSregress---------------------------------------------------------------
var <- c("invTTheta2", "TXBorn")
Cplm_high <- EOSregress(Cpdat, var)
Cplm_low <- EOSregress(Cpdat, var, T.max = 600)
Cplm_low$coefficients
## ----EOSplot, fig.margin = TRUE, fig.cap = "Heat capacity of aqueous methane.", fig.width=3.5, fig.height=3.5, cache=TRUE, results="hide", message=FALSE, echo=FALSE, out.width=672, out.height=336, pngquant=pngquant----
EOSplot(Cpdat, coefficients = round(Cplm_low$coefficients, 1))
EOSplot(Cpdat, coeficients = Cplm_high, add = TRUE, lty = 3)
PS01_data <- convert(EOScoeffs("CH4", "Cp"), "J")
EOSplot(Cpdat, coefficients = PS01_data, add = TRUE, lty = 2, col = "blue")
## ----EOSplot, eval=FALSE------------------------------------------------------
# EOSplot(Cpdat, coefficients = round(Cplm_low$coefficients, 1))
# EOSplot(Cpdat, coeficients = Cplm_high, add = TRUE, lty = 3)
# PS01_data <- convert(EOScoeffs("CH4", "Cp"), "J")
# EOSplot(Cpdat, coefficients = PS01_data, add = TRUE, lty = 2, col = "blue")
## ----Cpcoeffs, message=FALSE--------------------------------------------------
convert(EOScoeffs("CH4", "Cp"), "J")
## ----Vdat---------------------------------------------------------------------
file <- system.file("extdata/cpetc/HWM96_V.csv", package = "CHNOSZ")
Vdat <- read.csv(file)
# Use data for CH4 near 280 bar
Vdat <- Vdat[Vdat$species == "CH4", ]
Vdat <- Vdat[abs(Vdat$P - 28) < 0.1, ]
Vdat <- Vdat[, -1]
Vdat$P <- convert(Vdat$P, "bar")
## ----Vdat_non-----------------------------------------------------------------
QBorn <- EOSvar("QBorn", T = Vdat$T, P = Vdat$P)
Vomega <- convert(Cplm_low$coefficients[["TXBorn"]], "cm3bar")
V_sol <- Vomega * QBorn
V_non <- Vdat$V - V_sol
Vdat_non <- data.frame(T = Vdat$T, P = Vdat$P, V = V_non)
## ----Vdat_non_regress, message=FALSE------------------------------------------
var <- "invTTheta"
Vnonlm <- EOSregress(Vdat_non, var, T.max = 450)
Vcoeffs <- round(c(Vnonlm$coefficients, QBorn = Vomega), 1)
Vcoeffs_database <- convert(EOScoeffs("CH4", "V"), "J")
## ----Vplot, fig.margin=TRUE, results="hide", message=FALSE, echo=FALSE, fig.width=3.5, fig.height=7, fig.cap="Volume of aqueous methane.", out.width=672, out.height=672, pngquant=pngquant----
par(mfrow = c(2, 1))
# plot 1
EOSplot(Vdat, coefficients = Vcoeffs)
EOSplot(Vdat, coefficients = Vcoeffs_database, add = TRUE, lty = 2)
# plot 2
EOSplot(Vdat, coefficients = Vcoeffs_database, T.plot = 600, lty = 2)
EOSplot(Vdat, coefficients = Vcoeffs, add = TRUE)
## ----Vplot, eval=FALSE--------------------------------------------------------
# par(mfrow = c(2, 1))
# # plot 1
# EOSplot(Vdat, coefficients = Vcoeffs)
# EOSplot(Vdat, coefficients = Vcoeffs_database, add = TRUE, lty = 2)
# # plot 2
# EOSplot(Vdat, coefficients = Vcoeffs_database, T.plot = 600, lty = 2)
# EOSplot(Vdat, coefficients = Vcoeffs, add = TRUE)
## ----Nadat--------------------------------------------------------------------
T <- convert(seq(0, 600, 50), "K")
P <- 1000
prop.PT <- subcrt("Na+", T = T, P = P, grid = "T", convert = FALSE)$out[[1]]
Nadat <- prop.PT[, c("T", "P", "Cp")]
## ----Nalm, fig.margin=TRUE, fig.width=3.5, fig.height=3.5, fig.cap="Heat capacity of Na<sup>+</sup> (inapplicable: constant ω).", out.width=672, out.height=336, pngquant=pngquant----
var <- c("invTTheta2", "TXBorn")
Nalm <- EOSregress(Nadat, var, T.max = 600)
EOSplot(Nadat, coefficients = Nalm$coefficients, fun.legend = NULL)
EOSplot(Nadat, add = TRUE, lty = 3)
## ----Navars1------------------------------------------------------------------
var1 <- c("invTTheta2", "Cp_s_var")
omega.guess <- coef(Nalm)[3]
## ----Nawhile, fig.margin=TRUE, fig.width=3.5, fig.height=3.5, fig.cap="Heat capacity of Na<sup>+</sup> (variable ω).", out.width=672, out.height=336, pngquant=pngquant----
diff.omega <- 999
while(abs(diff.omega) > 1) {
Nalm1 <- EOSregress(Nadat, var1, omega.PrTr = tail(omega.guess, 1), Z = 1)
omega.guess <- c(omega.guess, coef(Nalm1)[3])
diff.omega <- tail(diff(omega.guess), 1)
}
EOSplot(Nadat, coefficients = signif(coef(Nalm1), 6),
omega.PrTr = tail(omega.guess, 1), Z = 1)
convert(EOScoeffs("Na+", "Cp"), "J")
## ----NaVolume, fig.margin=TRUE, fig.width=3.5, fig.height=3.5, fig.cap="Volume of Na<sup>+</sup> (variable ω).", results="hide", message=FALSE, echo=FALSE, out.width=672, out.height=336, pngquant=pngquant----
T <- convert(seq(0, 600, 25), "K")
P <- 1000
prop.PT <- subcrt("Na+", T = T, P = P, grid = "T", convert = FALSE)$out[[1]]
NaVdat <- prop.PT[, c("T", "P", "V")]
var1 <- c("invTTheta", "V_s_var")
omega.guess <- 1400000
diff.omega <- 999
while(abs(diff.omega) > 1) {
NaVlm1 <- EOSregress(NaVdat, var1,
omega.PrTr = tail(convert(omega.guess, "joules"), 1), Z = 1)
omega.guess <- c(omega.guess, coef(NaVlm1)[3])
diff.omega <- tail(diff(omega.guess), 1)
}
EOSplot(NaVdat, coefficients = signif(coef(NaVlm1), 6),
omega.PrTr = tail(convert(omega.guess, "joules"), 1), Z = 1,
fun.legend = "bottomleft")
coefficients <- convert(EOScoeffs("Na+", "V", P = 1000), "J")
names(coefficients)[3] <- "V_s_var"
EOSplot(NaVdat, coefficients = coefficients, Z = 1, add = TRUE, lty = 2,
omega.PrTr = convert(coefficients["V_s_var"], "joules"))
## ----NaVolume, eval=FALSE-----------------------------------------------------
# T <- convert(seq(0, 600, 25), "K")
# P <- 1000
# prop.PT <- subcrt("Na+", T = T, P = P, grid = "T", convert = FALSE)$out[[1]]
# NaVdat <- prop.PT[, c("T", "P", "V")]
# var1 <- c("invTTheta", "V_s_var")
# omega.guess <- 1400000
# diff.omega <- 999
# while(abs(diff.omega) > 1) {
# NaVlm1 <- EOSregress(NaVdat, var1,
# omega.PrTr = tail(convert(omega.guess, "joules"), 1), Z = 1)
# omega.guess <- c(omega.guess, coef(NaVlm1)[3])
# diff.omega <- tail(diff(omega.guess), 1)
# }
# EOSplot(NaVdat, coefficients = signif(coef(NaVlm1), 6),
# omega.PrTr = tail(convert(omega.guess, "joules"), 1), Z = 1,
# fun.legend = "bottomleft")
# coefficients <- convert(EOScoeffs("Na+", "V", P = 1000), "J")
# names(coefficients)[3] <- "V_s_var"
# EOSplot(NaVdat, coefficients = coefficients, Z = 1, add = TRUE, lty = 2,
# omega.PrTr = convert(coefficients["V_s_var"], "joules"))
## ----AS04, message=FALSE------------------------------------------------------
add.OBIGT("AS04")
## ----SiO2_2H2O, message=FALSE-------------------------------------------------
s_25C <- subcrt(c("SiO2", "H2O"), c(1, 2), T = 25)$out
s_near25 <- subcrt(c("SiO2", "H2O"), c(1, 2), T = seq(20, 30, length.out=50))$out
s_lowT <- subcrt(c("SiO2", "H2O"), c(1, 2), T = seq(0, 100, 10))$out
s_Psat <- subcrt(c("SiO2", "H2O"), c(1, 2))$out
s_P500 <- subcrt(c("SiO2", "H2O"), c(1, 2), T = seq(0, 1000, 100), P = 500)$out
s_P1000 <- subcrt(c("SiO2", "H2O"), c(1, 2), T = seq(0, 1000, 100), P = 1000)$out
## ----new_H4SiO4---------------------------------------------------------------
mod.OBIGT("calc-H4SiO4", formula = "H4SiO4", ref1 = "this_vignette",
date = as.character(Sys.Date()), G = s_25C$G, H = s_25C$H, S = s_25C$S,
Cp = s_25C$Cp, V = s_25C$V, z = 0)
## ----substuff-----------------------------------------------------------------
substuff <- rbind(s_near25, s_lowT, s_Psat, s_P500, s_P1000)
substuff$T <- convert(substuff$T, "K")
## ----Cp_H4SiO4, results="hide"------------------------------------------------
Cpdat <- substuff[, c("T", "P", "Cp")]
var <- c("invTTheta2", "TXBorn")
Cplm <- EOSregress(Cpdat, var)
Cpcoeffs <- Cplm$coefficients
mod.OBIGT("calc-H4SiO4", c1 = Cpcoeffs[1],
c2 = Cpcoeffs[2]/10000, omega = Cpcoeffs[3]/100000)
## ----V_H4SiO4_nonsolvation----------------------------------------------------
Vdat <- substuff[, c("T", "P", "V")]
QBorn <- EOSvar("QBorn", T = Vdat$T, P = Vdat$P)
Vomega <- convert(Cplm$coefficients[["TXBorn"]], "cm3bar")
V_sol <- Vomega * QBorn
V_non <- Vdat$V - V_sol
Vdat$V <- V_non
## ----V_H4SiO4, results="hide"-------------------------------------------------
var <- c("invPPsi", "invTTheta", "invPPsiTTheta")
Vlm <- EOSregress(Vdat, var)
Vcoeffs <- convert(Vlm$coefficients, "joules")
mod.OBIGT("calc-H4SiO4", a1 = Vcoeffs[1]*10, a2 = Vcoeffs[2]/100,
a3 = Vcoeffs[3], a4 = Vcoeffs[4]/10000)
## ----width180, include=FALSE------------------------------------------------------------------------------------------------------------------------------------------------------
options(width = 180)
## ----info_H4SiO4, message=FALSE---------------------------------------------------------------------------------------------------------------------------------------------------
info(info(c("calc-H4SiO4", "H4SiO4")))
## ----width80, include=FALSE---------------------------------------------------
options(width = 80)
## ----subcrt_H4SiO4, fig.margin=TRUE, fig.width=4, fig.height=4, small.mar=TRUE, echo=FALSE, results="hide", message=FALSE, out.width="100%", cache=TRUE, fig.cap="Comparison of H<sub>4</sub>SiO<sub>4</sub> pseudospecies.", pngquant=pngquant----
s1 <- subcrt(c("calc-H4SiO4", "SiO2", "H2O"), c(-1, 1, 2))
plot(s1$out$T, s1$out$G, type = "l", ylim = c(-500, 2000),
xlab = axis.label("T"), ylab = axis.label("DG0"))
s2 <- subcrt(c("H4SiO4", "SiO2", "H2O"), c(-1, 1, 2))
lines(s2$out$T, s2$out$G, lty = 2)
abline(h = 0, lty = 3)
legend("topright", legend = c("calc-H4SiO4 (this vignette)",
"H4SiO4 (Stef\u00e1nsson, 2001)"), lty = c(1, 2), bty = "n")
text(225, 1000, describe.reaction(s1$reaction))
## ----subcrt_H4SiO4, eval=FALSE------------------------------------------------
# s1 <- subcrt(c("calc-H4SiO4", "SiO2", "H2O"), c(-1, 1, 2))
# plot(s1$out$T, s1$out$G, type = "l", ylim = c(-500, 2000),
# xlab = axis.label("T"), ylab = axis.label("DG0"))
# s2 <- subcrt(c("H4SiO4", "SiO2", "H2O"), c(-1, 1, 2))
# lines(s2$out$T, s2$out$G, lty = 2)
# abline(h = 0, lty = 3)
# legend("topright", legend = c("calc-H4SiO4 (this vignette)",
# "H4SiO4 (Stef\u00e1nsson, 2001)"), lty = c(1, 2), bty = "n")
# text(225, 1000, describe.reaction(s1$reaction))
## ----activity_diagram, fig.margin=TRUE, fig.width=4, fig.height=4, small.mar=TRUE, echo=TRUE, results="hide", message=FALSE, out.width="100%", cache=TRUE, fig.cap="Activity diagram for K<sub>2</sub>O-Al<sub>2</sub>O<sub>3</sub>-SiO<sub>2</sub>-H<sub>2</sub>O.", pngquant=pngquant----
basis(c("Al+3", "H4SiO4", "K+", "H2O", "H+", "O2"))
species(c("gibbsite", "muscovite", "kaolinite", "pyrophyllite", "K-feldspar"))
a <- affinity(H4SiO4 = c(-8, 0, 300), `K+` = c(-1, 8, 300))
diagram(a, ylab = ratlab("K+"), fill = "terrain", yline = 1.7)
legend("bottomleft", describe.property(c("T", "P"), c(25, 1)), bty = "n")
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/doc/eos-regress.R
|
---
title: "Regressing thermodynamic data"
subtitle: "EOSregress in CHNOSZ"
author: "Jeffrey M. Dick"
date: "`r Sys.Date()`"
output:
tufte::tufte_html:
tufte_features: ["background"]
toc: true
mathjax: null
highlight: null
tufte::tufte_handout:
citation_package: natbib
latex_engine: xelatex
tufte::tufte_book:
citation_package: natbib
latex_engine: xelatex
vignette: >
%\VignetteIndexEntry{Regressing thermodynamic data}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
bibliography: vig.bib
link-citations: yes
csl: elementa.csl
---
<style>
html {
font-size: 14px;
}
body {
font-family: ‘Times New Roman’, Times, serif;
}
li {
padding: 0.25rem 0;
}
/* Zero margin around pre blocks (looks more like R console output) */
pre {
margin-top: 0;
margin-bottom: 0;
}
</style>
```{r width80, include=FALSE}
options(width = 80)
```
```{r digits6, include=FALSE}
options(digits = 6)
```
```{r HTML, include=FALSE}
## Some frequently used HTML expressions
V0 <- "<i>V</i>°"
Cp0 <- "<i>C<sub>P</sub></i>°"
c1 <- "<i>c</i><sub>1</sub>"
c2 <- "<i>c</i><sub>2</sub>"
a1 <- "<i>a</i><sub>1</sub>"
a2 <- "<i>a</i><sub>2</sub>"
a3 <- "<i>a</i><sub>3</sub>"
a4 <- "<i>a</i><sub>4</sub>"
h4sio4 <- "H<sub>4</sub>SiO<sub>4</sub>"
sio2 <- "SiO<sub>2</sub>"
h2o <- "H<sub>2</sub>O"
ch4 <- "CH<sub>4</sub>"
wPrTr <- "ω<sub><i>P<sub>r</sub></i>,<i>T<sub>r</sub></i></sub>"
```
```{r setup, include=FALSE}
library(knitr)
# Invalidate cache when the tufte version changes
opts_chunk$set(tidy = FALSE, cache.extra = packageVersion('tufte'))
options(htmltools.dir.version = FALSE)
# Adjust plot margins
knit_hooks$set(small.mar = function(before, options, envir) {
if (before) par(mar = c(4.2, 4.2, .3, .3)) # smaller margin on top and right
})
# Use pngquant to optimize PNG images
knit_hooks$set(pngquant = hook_pngquant)
# pngquant isn't available on R-Forge ...
if (!nzchar(Sys.which("pngquant"))) {
pngquant <- NULL
} else {
pngquant <- "--speed=1 --quality=0-50"
}
## Colorize messages 20171031
## Adapted from https://gist.github.com/yihui/2629886#file-knitr-color-msg-rnw
color_block = function(color) {
function(x, options) sprintf('<pre style="color:%s">%s</pre>', color, x)
}
knit_hooks$set(warning = color_block('magenta'), error = color_block('red'), message = color_block('blue'))
# Set dpi 20231129
knitr::opts_chunk$set(
dpi = if(nzchar(Sys.getenv("CHNOSZ_BUILD_LARGE_VIGNETTES"))) 72 else 50
)
```
This [vignette](index.html) demonstrates <span style="color:blue">`EOSregress()`</span> and related functions for the regression of heat capacity and volumetric data to obtain "equations of state" coefficients.
# A note on the equations
The CHNOSZ thermodynamic database uses the revised Helgeson-Kirkham-Flowers equations of state (EOS) for aqueous species.
Different terms in these equations give the "non-solvation" and "solvation" contributions to the standard molal heat capacity (`r Cp0`) and volume (`r V0`) as a function of temperature (*T*) and pressure (*P*).
The equations were originally described by @HKF81; for `r Cp0` the equation is
> `r Cp0` = `r c1` + `r c2` / (*T* - θ)<sup>2</sup> + ω*TX*
Here, `r c1` and `r c2` are the non-solvation parameters, and ω is the solvation parameter.
θ is equal to 228 K, and *X* is one of the "Born functions" that relates the solvation process to the dielectric properties of water.
For neutral species, all of the parameters, including the "effective" value of ω, are constant.
However, **for charged species, ω has non-zero derivatives at *T* > 100 °C, increasing with temperature**, that depend on the charge and ionic radius.
Revisions by @TH88 and @SOJSH92 refined the equations to improve their high-*T* and *P* behavior.
# A note on the algorithms
The regression functions are essentially a wrapper around the <span style="color:green">`water()`</span>-related functions in CHNOSZ and `lm()` in R.
The former provide values of the Born functions.
Accordingly, numerical values for all of the *variables* in the equations (e.g. 1/(*T* - θ)<sup>2</sup> and *TX*) can be calculated at each experimental *T* and *P*.
Applying a linear model (`lm`), the *coefficients* in the model can be obtained.
In this case, they correspond to the HKF parameters, e.g. `c1` (the intercept), `c2` and ω.
The coefficients **in this model** are constants, restricing application of the model to neutral (uncharged) species, for which the high-temperature derivatives of ω are 0.
Further below, a procedure is described to iteratively solve the equations for charged species.
# An example for neutral species
This is from the first example from <span style="color:green">`EOSregress()`</span>.
```{marginfigure}
The `?` indicates a documentation topic in R. To view it, type <span style="color:blue">`?EOSregress`</span> or <span style="color:blue">`help(EOSregress)`</span> at the R prompt.
```
Here, we regress experimental heat capacities of aqueous methane (`r ch4`) using the revised HKF equations.
First, load CHNOSZ and its database:
```{r library_CHNOSZ}
library(CHNOSZ)
reset()
```
Now, read a data file with experimental measurements from @HW97 and convert pressures in MPa to bar (the values of `r Cp0` in Joules will be used as-is):
```{r Cpdat}
file <- system.file("extdata/cpetc/HW97_Cp.csv", package = "CHNOSZ")
Cpdat <- read.csv(file)
# Use data for CH4
Cpdat <- Cpdat[Cpdat$species == "CH4", ]
Cpdat <- Cpdat[, -1]
Cpdat$P <- convert(Cpdat$P, "bar")
```
Next, we specify the terms in the HKF equations and perform the regression using <span style="color:green">`EOSregress()`</span>.
In the second call to <span style="color:green">`EOSregress()`</span> below, only for *T* < 600 K are included in the regression.
The coefficients here correspond to `r c1`, `r c2` and ω in the HKF equations.
```{r EOSregress}
var <- c("invTTheta2", "TXBorn")
Cplm_high <- EOSregress(Cpdat, var)
Cplm_low <- EOSregress(Cpdat, var, T.max = 600)
Cplm_low$coefficients
```
```{r EOSplot, fig.margin = TRUE, fig.cap = "Heat capacity of aqueous methane.", fig.width=3.5, fig.height=3.5, cache=TRUE, results="hide", message=FALSE, echo=FALSE, out.width=672, out.height=336, pngquant=pngquant}
EOSplot(Cpdat, coefficients = round(Cplm_low$coefficients, 1))
EOSplot(Cpdat, coeficients = Cplm_high, add = TRUE, lty = 3)
PS01_data <- convert(EOScoeffs("CH4", "Cp"), "J")
EOSplot(Cpdat, coefficients = PS01_data, add = TRUE, lty = 2, col = "blue")
```
We can use <span style="color:green">`EOSplot()`</span> to plot the data and fitted lines and show the coefficients in the legend.
The solid line shows the fit to the lower-temperature data.
The fit to all data, represented by the dotted line, doesn't capture the low-temperature trends in the data.
```{r EOSplot, eval=FALSE}
```
```{marginfigure}
Be aware that the lines shown by <span style="color:green">`EOSplot()`</span> are calculated for a single pressure only, despite the temperature- and pressure-dependence of the data and regressions.
```
<span style="color:green">`EOScoeffs()`</span> is a small function that is used to retrieve the HKF parameters in the database in CHNOSZ.
*For species in the database with `E_units` set to `cal` for calories (i.e., most HKF species), the coefficients need to be converted to Joules here.*
The dashed blue line shows calculated values for methane using these parameters, which are from @PS01.
Compare the database values with the regressed values shown in the legend of figure above.
Some differences are expected as the values in the database are derived from different regression techniques applied to different sets of data:
```{r Cpcoeffs, message=FALSE}
convert(EOScoeffs("CH4", "Cp"), "J")
```
## Setting the value of omega
Given both high-temperature volumetric and calorimetric data for neutral species, the effective value of ω is most reliably regressed from the latter [@SSW01].
Let's regress volumetric data using a value of omega taken from the heat capacity regression.
First, read the data from @HWM96.
```{r Vdat}
file <- system.file("extdata/cpetc/HWM96_V.csv", package = "CHNOSZ")
Vdat <- read.csv(file)
# Use data for CH4 near 280 bar
Vdat <- Vdat[Vdat$species == "CH4", ]
Vdat <- Vdat[abs(Vdat$P - 28) < 0.1, ]
Vdat <- Vdat[, -1]
Vdat$P <- convert(Vdat$P, "bar")
```
Compressibilities of species (measured or estimated) are implied by the full set of HKF volumetric parameters (`r a1`, `r a2`, `r a3`, `r a4`).
In this example we model volumes at nearly constant *P*.
Therefore, we can use a simpler equation for `r V0` written in terms of the "isobaric fit parameters" (Tanger and Helgeson 1988, p. 35) σ and ξ, together with the solvation contribution that depends on the *Q* Born function:
> `r V0` = σ + ξ / (*T* - θ) - ω*Q*
```{marginfigure}
<span style="color:green">`EOSvar()`</span> actually returns the negative of *Q*, so the omega symbol here carries no negative sign.
```
Now we calculate the *Q* Born function using <span style="color:green">`EOSvar()`</span> and multiply by ω (from the heat capacity regression) to get the solvation volume at each experimental temperature and pressure.
Subtract the solvation volume from the experimental volumes and create a new data frame holding the calculated "non-solvation" volume.
```{marginfigure}
Because we are dealing with volumes, the units of ω are converted according to 1 J = 10 cm<sup>3</sup> bar.
```
```{r Vdat_non}
QBorn <- EOSvar("QBorn", T = Vdat$T, P = Vdat$P)
Vomega <- convert(Cplm_low$coefficients[["TXBorn"]], "cm3bar")
V_sol <- Vomega * QBorn
V_non <- Vdat$V - V_sol
Vdat_non <- data.frame(T = Vdat$T, P = Vdat$P, V = V_non)
```
Next, regress the non-solvation volume using the non-solvation terms in the HKF model.
As with `r Cp0`, also get the values of the parameters from the database for comparison with the regression results.
```{r Vdat_non_regress, message=FALSE}
var <- "invTTheta"
Vnonlm <- EOSregress(Vdat_non, var, T.max = 450)
Vcoeffs <- round(c(Vnonlm$coefficients, QBorn = Vomega), 1)
Vcoeffs_database <- convert(EOScoeffs("CH4", "V"), "J")
```
```{r Vplot, fig.margin=TRUE, results="hide", message=FALSE, echo=FALSE, fig.width=3.5, fig.height=7, fig.cap="Volume of aqueous methane.", out.width=672, out.height=672, pngquant=pngquant}
par(mfrow = c(2, 1))
# plot 1
EOSplot(Vdat, coefficients = Vcoeffs)
EOSplot(Vdat, coefficients = Vcoeffs_database, add = TRUE, lty = 2)
# plot 2
EOSplot(Vdat, coefficients = Vcoeffs_database, T.plot = 600, lty = 2)
EOSplot(Vdat, coefficients = Vcoeffs, add = TRUE)
```
Finally, plot the data and regressions.
The first plot shows all the data, and the second the low-temperature subset (*T* < 600 K).
The solid line is the two-term fit for σ and ξ (using ω from the heat capacity regression), and the dashed line shows the volumes calculated using the parameters in the database.
The plot legends give the parameters from the two-term fit (first plot), or from the database (second plot).
```{r Vplot, eval=FALSE}
```
The equation for `r V0` provides a reasonable approximation of the trend of lowest-temperature data (*T* < 450 K).
However, the equation does not closely reproduce the trend of higher-temperature `r V0` data (*T* < 600 K), nor behavior in the critical region.
Because of these issues, some researchers are exploring alternatives to the HKF model for aqueous nonelectrolytes.
(See also an example in <span style="color:blue">`?EOSregress`</span>.)
# An example for charged species
For this example, let's generate synthetic data for Na<sup>+</sup> using its parameters in the database.
In the call to <span style="color:green">`subcrt()`</span> below, `convert = FALSE` means to take *T* in units of K.
```{r Nadat}
T <- convert(seq(0, 600, 50), "K")
P <- 1000
prop.PT <- subcrt("Na+", T = T, P = P, grid = "T", convert = FALSE)$out[[1]]
Nadat <- prop.PT[, c("T", "P", "Cp")]
```
As noted above, ω for electrolytes is not a constant.
What happens if we apply the constant-ω model anyway, knowing it's not applicable (especially at high temperature)?
```{r Nalm, fig.margin=TRUE, fig.width=3.5, fig.height=3.5, fig.cap="Heat capacity of Na<sup>+</sup> (inapplicable: constant ω).", out.width=672, out.height=336, pngquant=pngquant}
var <- c("invTTheta2", "TXBorn")
Nalm <- EOSregress(Nadat, var, T.max = 600)
EOSplot(Nadat, coefficients = Nalm$coefficients, fun.legend = NULL)
EOSplot(Nadat, add = TRUE, lty = 3)
```
As before, the solid line is a fit to relatively low-temperature (*T* < 600 K) data, and the dotted line a fit to the entire temperature range of the data.
The fits using constant ω are clearly not acceptable.
There is, however, a way out.
A different variable, `Cp_s_var`, can be used to specify the calculation of the "solvation" heat capacity in the HKF equations using the temperature- and pressure-dependent corrections for charged species.
To use this variable, the values of `r wPrTr` (omega at the reference temperature and pressure) and *Z* (charge) must be given, in addition to *T* and *P*.
Of course, right now we *don't know* the value of `r wPrTr`---it is the purpose of the regression to find it!
But we can make a first guess using the value of ω found above.
```{r Navars1}
var1 <- c("invTTheta2", "Cp_s_var")
omega.guess <- coef(Nalm)[3]
```
Then, we can use an iterative procedure that refines successive guesses of `r wPrTr`.
The convergence criterion is measured by the difference in sequential regressed values of ω.
```{r Nawhile, fig.margin=TRUE, fig.width=3.5, fig.height=3.5, fig.cap="Heat capacity of Na<sup>+</sup> (variable ω).", out.width=672, out.height=336, pngquant=pngquant}
diff.omega <- 999
while(abs(diff.omega) > 1) {
Nalm1 <- EOSregress(Nadat, var1, omega.PrTr = tail(omega.guess, 1), Z = 1)
omega.guess <- c(omega.guess, coef(Nalm1)[3])
diff.omega <- tail(diff(omega.guess), 1)
}
EOSplot(Nadat, coefficients = signif(coef(Nalm1), 6),
omega.PrTr = tail(omega.guess, 1), Z = 1)
convert(EOScoeffs("Na+", "Cp"), "J")
```
Alrighty! We managed to obtain HKF coefficients from synthetic data for Na<sup>+</sup>.
The regressed values of the HKF coefficients (shown in the plot legend) are very close to the database values (printed by the call to <span style="color:green">`EOScoeffs()`</span>) used to generate the synthetic data.
## Doing it for volume
Just like above, but using synthetic `r V0` data.
Note that the regressed value of ω has volumetric units (cm<sup>3</sup> bar/mol), while `omega.PrTr` is in energetic units (J/mol).
Compared to `r Cp0`, the regression of `r V0` is very finicky.
Given a starting guess of `r wPrTr` of 1400000 cm<sup>3</sup> bar/mol, the iteration converges on 1394890 instead of the "true" database value of 1383230 (represented by dashed line in the plot).
```{r NaVolume, fig.margin=TRUE, fig.width=3.5, fig.height=3.5, fig.cap="Volume of Na<sup>+</sup> (variable ω).", results="hide", message=FALSE, echo=FALSE, out.width=672, out.height=336, pngquant=pngquant}
T <- convert(seq(0, 600, 25), "K")
P <- 1000
prop.PT <- subcrt("Na+", T = T, P = P, grid = "T", convert = FALSE)$out[[1]]
NaVdat <- prop.PT[, c("T", "P", "V")]
var1 <- c("invTTheta", "V_s_var")
omega.guess <- 1400000
diff.omega <- 999
while(abs(diff.omega) > 1) {
NaVlm1 <- EOSregress(NaVdat, var1,
omega.PrTr = tail(convert(omega.guess, "joules"), 1), Z = 1)
omega.guess <- c(omega.guess, coef(NaVlm1)[3])
diff.omega <- tail(diff(omega.guess), 1)
}
EOSplot(NaVdat, coefficients = signif(coef(NaVlm1), 6),
omega.PrTr = tail(convert(omega.guess, "joules"), 1), Z = 1,
fun.legend = "bottomleft")
coefficients <- convert(EOScoeffs("Na+", "V", P = 1000), "J")
names(coefficients)[3] <- "V_s_var"
EOSplot(NaVdat, coefficients = coefficients, Z = 1, add = TRUE, lty = 2,
omega.PrTr = convert(coefficients["V_s_var"], "joules"))
```
```{r NaVolume, eval=FALSE}
```
# Making a pseudospecies: `r h4sio4`
Some mineral stability diagrams use the activity of `r h4sio4` as a variable.
However, the primary species for dissolved silica in CHNOSZ is `r sio2`(aq).
As recommended by @WJ17, let us use data for `r sio2`(aq) from @AS04, which gives a higher solubility of quartz compared to values from @SHS89 that are loaded by default in the package:
```{r AS04, message=FALSE}
add.OBIGT("AS04")
```
The pseudo-reaction with zero properties, `r h4sio4` = `r sio2` + 2 `r h2o`, defines the properties of the pseudospecies `r h4sio4`.
First we go about calculating the properties of `r sio2` + 2 `r h2o`.
We do this over a range of *T* and *P*, but include many points near 25 °C to improve the fit of the regression in that region:
`r op <- options(warn = -1)`
```{r SiO2_2H2O, message=FALSE}
s_25C <- subcrt(c("SiO2", "H2O"), c(1, 2), T = 25)$out
s_near25 <- subcrt(c("SiO2", "H2O"), c(1, 2), T = seq(20, 30, length.out=50))$out
s_lowT <- subcrt(c("SiO2", "H2O"), c(1, 2), T = seq(0, 100, 10))$out
s_Psat <- subcrt(c("SiO2", "H2O"), c(1, 2))$out
s_P500 <- subcrt(c("SiO2", "H2O"), c(1, 2), T = seq(0, 1000, 100), P = 500)$out
s_P1000 <- subcrt(c("SiO2", "H2O"), c(1, 2), T = seq(0, 1000, 100), P = 1000)$out
```
`r options(op)`
Now we can start making the new species, with thermodynamic properties calculated at 25 °C:
```{r new_H4SiO4}
mod.OBIGT("calc-H4SiO4", formula = "H4SiO4", ref1 = "this_vignette",
date = as.character(Sys.Date()), G = s_25C$G, H = s_25C$H, S = s_25C$S,
Cp = s_25C$Cp, V = s_25C$V, z = 0)
```
To prepare for the regression, combine the calculated data and convert °C to K:
```{r substuff}
substuff <- rbind(s_near25, s_lowT, s_Psat, s_P500, s_P1000)
substuff$T <- convert(substuff$T, "K")
```
Now let's run a `r Cp0` regression and update the new species with the regressed HKF coefficients.
Note that we apply order-of-magnitude scaling to the coefficients (see <span style="color:blue">`?thermo`</span>):
```{r Cp_H4SiO4, results="hide"}
Cpdat <- substuff[, c("T", "P", "Cp")]
var <- c("invTTheta2", "TXBorn")
Cplm <- EOSregress(Cpdat, var)
Cpcoeffs <- Cplm$coefficients
mod.OBIGT("calc-H4SiO4", c1 = Cpcoeffs[1],
c2 = Cpcoeffs[2]/10000, omega = Cpcoeffs[3]/100000)
```
Let's get ready to regress `r V0` data.
We use the strategy shown above to calculate non-solvation volume using ω from the `r Cp0` regression:
```{r V_H4SiO4_nonsolvation}
Vdat <- substuff[, c("T", "P", "V")]
QBorn <- EOSvar("QBorn", T = Vdat$T, P = Vdat$P)
Vomega <- convert(Cplm$coefficients[["TXBorn"]], "cm3bar")
V_sol <- Vomega * QBorn
V_non <- Vdat$V - V_sol
Vdat$V <- V_non
```
Here's the `r V0` regression for the pseudospecies.
We specify the variables for the `r a1`, `r a2`, `r a3`, and `r a4` terms in the HKF equations.
```{r V_H4SiO4, results="hide"}
var <- c("invPPsi", "invTTheta", "invPPsiTTheta")
Vlm <- EOSregress(Vdat, var)
Vcoeffs <- convert(Vlm$coefficients, "joules")
mod.OBIGT("calc-H4SiO4", a1 = Vcoeffs[1]*10, a2 = Vcoeffs[2]/100,
a3 = Vcoeffs[3], a4 = Vcoeffs[4]/10000)
```
We just calculated the properties of the `r h4sio4` pseudospecies.
For comparison, the OBIGT database in CHNOSZ contains `H4SiO4` with parameters from @Ste01:
```{r width180, include=FALSE}
options(width = 180)
```
```{r info_H4SiO4, message=FALSE}
info(info(c("calc-H4SiO4", "H4SiO4")))
```
```{r width80, include=FALSE}
```
```{r subcrt_H4SiO4, fig.margin=TRUE, fig.width=4, fig.height=4, small.mar=TRUE, echo=FALSE, results="hide", message=FALSE, out.width="100%", cache=TRUE, fig.cap="Comparison of H<sub>4</sub>SiO<sub>4</sub> pseudospecies.", pngquant=pngquant}
s1 <- subcrt(c("calc-H4SiO4", "SiO2", "H2O"), c(-1, 1, 2))
plot(s1$out$T, s1$out$G, type = "l", ylim = c(-500, 2000),
xlab = axis.label("T"), ylab = axis.label("DG0"))
s2 <- subcrt(c("H4SiO4", "SiO2", "H2O"), c(-1, 1, 2))
lines(s2$out$T, s2$out$G, lty = 2)
abline(h = 0, lty = 3)
legend("topright", legend = c("calc-H4SiO4 (this vignette)",
"H4SiO4 (Stef\u00e1nsson, 2001)"), lty = c(1, 2), bty = "n")
text(225, 1000, describe.reaction(s1$reaction))
```
Let's compare `H4SiO4` from Stefánsson (2001) and the `calc-H4SiO4` we just made with the calculated properties of `r sio2` + 2 `r h2o` as a function of temperature:
```{r subcrt_H4SiO4, eval=FALSE}
```
Ideally, the lines would be horizontal with a _y_-interecept of 0.
However, both the `calc-H4SiO4` we made here and the `H4SiO4` from Stefánsson (2001) show deviations that increase at higher temperatures.
While they are not quite negligible, these deviations are comparatively small.
For example, the almost 800 J/mol offset in Δ<i>G</i>° at 350 °C corresponds to a difference in log<i>K</i> of only -0.07.
The following example uses the `H4SiO4` from Stefánsson (2001) to make an activity diagram for the K<sub>2</sub>O-Al<sub>2</sub>O<sub>3</sub>-SiO<sub>2</sub>-H<sub>2</sub>O system.
This is similar to the diagram on p. 361 of [Garrels and Christ, 1965](https://www.worldcat.org/oclc/517586), but is quantitatively a closer match to the diagram in the [User's Guide to PHREEQC](https://wwwbrr.cr.usgs.gov/projects/GWC_coupled/phreeqc/html/final-75.html).
```{r activity_diagram, fig.margin=TRUE, fig.width=4, fig.height=4, small.mar=TRUE, echo=TRUE, results="hide", message=FALSE, out.width="100%", cache=TRUE, fig.cap="Activity diagram for K<sub>2</sub>O-Al<sub>2</sub>O<sub>3</sub>-SiO<sub>2</sub>-H<sub>2</sub>O.", pngquant=pngquant}
basis(c("Al+3", "H4SiO4", "K+", "H2O", "H+", "O2"))
species(c("gibbsite", "muscovite", "kaolinite", "pyrophyllite", "K-feldspar"))
a <- affinity(H4SiO4 = c(-8, 0, 300), `K+` = c(-1, 8, 300))
diagram(a, ylab = ratlab("K+"), fill = "terrain", yline = 1.7)
legend("bottomleft", describe.property(c("T", "P"), c(25, 1)), bty = "n")
```
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/doc/eos-regress.Rmd
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.