From noreply at r-forge.r-project.org Thu Nov 5 06:18:37 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 5 Nov 2015 06:18:37 +0100 (CET) Subject: [CHNOSZ-commits] r95 - in pkg/CHNOSZ: . R demo inst man Message-ID: <20151105051837.8A4EC187178@r-forge.r-project.org> Author: jedick Date: 2015-11-05 06:18:37 +0100 (Thu, 05 Nov 2015) New Revision: 95 Added: pkg/CHNOSZ/demo/copper.R Modified: pkg/CHNOSZ/DESCRIPTION pkg/CHNOSZ/NAMESPACE pkg/CHNOSZ/R/diagram.R pkg/CHNOSZ/R/equilibrate.R pkg/CHNOSZ/R/examples.R pkg/CHNOSZ/R/mosaic.R pkg/CHNOSZ/R/swap.basis.R pkg/CHNOSZ/R/util.plot.R pkg/CHNOSZ/demo/00Index pkg/CHNOSZ/inst/NEWS pkg/CHNOSZ/man/diagram.Rd pkg/CHNOSZ/man/equilibrate.Rd pkg/CHNOSZ/man/examples.Rd pkg/CHNOSZ/man/swap.basis.Rd pkg/CHNOSZ/man/util.plot.Rd Log: add demo copper.R Modified: pkg/CHNOSZ/DESCRIPTION =================================================================== --- pkg/CHNOSZ/DESCRIPTION 2015-10-19 18:37:20 UTC (rev 94) +++ pkg/CHNOSZ/DESCRIPTION 2015-11-05 05:18:37 UTC (rev 95) @@ -1,6 +1,6 @@ -Date: 2015-10-19 +Date: 2015-11-05 Package: CHNOSZ -Version: 1.0.6 +Version: 1.0.6-1 Title: Chemical Thermodynamics and Activity Diagrams Author: Jeffrey Dick Maintainer: Jeffrey Dick Modified: pkg/CHNOSZ/NAMESPACE =================================================================== --- pkg/CHNOSZ/NAMESPACE 2015-10-19 18:37:20 UTC (rev 94) +++ pkg/CHNOSZ/NAMESPACE 2015-11-05 05:18:37 UTC (rev 95) @@ -11,7 +11,8 @@ "contour", "image", "legend", "lines", "mtext", "par", "plot", "plot.new", "plot.window", "points", "rect", "text", "title") importFrom("stats", "D", "as.formula", "cor", "lm", "loess.smooth", - "na.omit", "qqline", "qqnorm", "sd", "splinefun", "uniroot") + "na.omit", "predict.lm", "qqline", "qqnorm", "sd", "splinefun", + "uniroot") importFrom("utils", "browseURL", "capture.output", "combn", "demo", "example", "head", "installed.packages", "read.csv", "tail", "write.csv", "write.table") Modified: pkg/CHNOSZ/R/diagram.R =================================================================== --- pkg/CHNOSZ/R/diagram.R 2015-10-19 18:37:20 UTC (rev 94) +++ pkg/CHNOSZ/R/diagram.R 2015-11-05 05:18:37 UTC (rev 95) @@ -24,7 +24,7 @@ # labels names=NULL, main=NULL, legend.x="topright", # plotting controls - add=FALSE, plot.it=TRUE, tplot=TRUE + add=FALSE, plot.it=TRUE, tplot=TRUE, ... ) { ### argument handling ### @@ -203,7 +203,7 @@ ### 0-D diagram - bar graph of properties of species or reactions # plot setup if(missing(ylab)) ylab <- axis.label(plotvar, units="") - barplot(unlist(plotvals), names.arg=names, ylab=ylab, cex.names=cex.names, col=col) + 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) { @@ -223,7 +223,7 @@ 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) + else plot(0, 0, type="n", xlim=xlim, ylim=ylim, xlab=xlab, ylab=ylab, ...) } # draw the lines for(i in 1:length(plotvals)) lines(xvalues, plotvals[[i]], col=col[i], lty=lty[i], lwd=lwd[i]) @@ -406,7 +406,7 @@ if(is.null(ylab)) ylab <- axis.label(eout$vars[2], basis=eout$basis) 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) + else plot(0, 0, type="n", xlim=xlim, ylim=ylim, xlab=xlab, ylab=ylab, ...) # add a title if(!is.null(main)) title(main=main) } Modified: pkg/CHNOSZ/R/equilibrate.R =================================================================== --- pkg/CHNOSZ/R/equilibrate.R 2015-10-19 18:37:20 UTC (rev 94) +++ pkg/CHNOSZ/R/equilibrate.R 2015-11-05 05:18:37 UTC (rev 95) @@ -64,7 +64,8 @@ }) } ## put together the output - out <- c(aout, list(balance=balance, m.balance=m.balance, n.balance=n.balance, Astar=Astar, loga.equil=loga.equil)) + 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) } Modified: pkg/CHNOSZ/R/examples.R =================================================================== --- pkg/CHNOSZ/R/examples.R 2015-10-19 18:37:20 UTC (rev 94) +++ pkg/CHNOSZ/R/examples.R 2015-11-05 05:18:37 UTC (rev 95) @@ -32,7 +32,7 @@ demos <- function(which=c("sources", "NaCl", "density", "phosphate", "nucleobase", "ORP", "diagram", "revisit", "findit", "CO2Ac", "nonideal", "ionize", "buffer", "yeastgfp", "mosaic", - "solubility", "wjd"), do.png=FALSE) { + "copper", "solubility", "wjd"), do.png=FALSE) { # run one or more demos from CHNOSZ with ask=FALSE, and return the value of the last one for(i in 1:length(which)) { # say something so the user sees where we are Modified: pkg/CHNOSZ/R/mosaic.R =================================================================== --- pkg/CHNOSZ/R/mosaic.R 2015-10-19 18:37:20 UTC (rev 94) +++ pkg/CHNOSZ/R/mosaic.R 2015-11-05 05:18:37 UTC (rev 95) @@ -17,7 +17,7 @@ # (the first one should be present in the starting basis set) iswap <- match(bases[1], names(myargs)) # the log activity of the starting basis species - logact.swap <- basis()$logact[match(bases[1], row.names(basis()))] + logact.swap <- basis()$logact[ibasis(bases[1])] # a list where we'll keep the affinity calculations affs <- list() for(i in seq_along(bases)) { @@ -35,11 +35,14 @@ # change the basis species; restore the original at the end of the loop if(i < length(bases)) { swap.basis(bases[i], bases[i+1]) - basis(bases[i+1], logact.swap) + # TODO: basis() requires the formula to identify the basis species, + # would be nicer to just use the ibasis here + bformula <- rownames(basis())[ibasis(bases[i+1])] + basis(bformula, logact.swap) } else { swap.basis(bases[i], bases[1]) - basis(bases[1], logact.swap) - names <- row.names(basis()) + bformula <- rownames(basis())[ibasis(bases[1])] + basis(bformula, logact.swap) } } # calculate affinities of formation of basis species Modified: pkg/CHNOSZ/R/swap.basis.R =================================================================== --- pkg/CHNOSZ/R/swap.basis.R 2015-10-19 18:37:20 UTC (rev 94) +++ pkg/CHNOSZ/R/swap.basis.R 2015-11-05 05:18:37 UTC (rev 95) @@ -47,6 +47,19 @@ 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")$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 definition @@ -63,8 +76,7 @@ if(length(species) > 1 | length(species2) > 2) stop("can only swap one species for one species") # arguments are good, now find the basis species to swap out - if(is.numeric(species)) ib <- match(species, oldbasis$ispecies) - else ib <- match(species, rownames(oldbasis)) + 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 Modified: pkg/CHNOSZ/R/util.plot.R =================================================================== --- pkg/CHNOSZ/R/util.plot.R 2015-10-19 18:37:20 UTC (rev 94) +++ pkg/CHNOSZ/R/util.plot.R 2015-11-05 05:18:37 UTC (rev 95) @@ -103,16 +103,41 @@ if(!is.null(T)) par(opar) } -label.plot <- function(x,xfrac=0.95,yfrac=0.9,cex=1,paren=TRUE,adj=1) { +label.plot <- function(x, xfrac=0.05, yfrac=0.95, 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(paren) x <- as.expression(substitute(group('(',italic(a),')'),list(a=x))) + 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, cex=cex , adj=adj) + 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=TRUE 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(xaxis='pH', yaxis='Eh', T=298.15, P='Psat', which=c('oxidation','reduction'), logaH2O=0, lty=2, lwd=1, col=par('fg'), xpoints=NULL, O2state="gas") { # draw water stability limits Modified: pkg/CHNOSZ/demo/00Index =================================================================== --- pkg/CHNOSZ/demo/00Index 2015-10-19 18:37:20 UTC (rev 94) +++ pkg/CHNOSZ/demo/00Index 2015-11-05 05:18:37 UTC (rev 95) @@ -13,5 +13,6 @@ buffer ionized proteins as a chemical activity buffer (1. thiol peroxidases 2. sigma factors) yeastgfp logfO2-logaH2O diagrams for model proteins based on YeastGFP localizations mosaic Eh-pH diagram for iron oxides, sulfides and carbonate with two sets of changing basis species +copper another example of mosaic(): complexation of copper with glycine species solubility solubility of calicite or CO2(gas) as a function of pH wjd run.wjd() with proteins: cell periphery of yeast Added: pkg/CHNOSZ/demo/copper.R =================================================================== --- pkg/CHNOSZ/demo/copper.R (rev 0) +++ pkg/CHNOSZ/demo/copper.R 2015-11-05 05:18:37 UTC (rev 95) @@ -0,0 +1,68 @@ +## 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) + +# 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)) +# Gibbs energies from A&D's 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( + convert(c(0, -146, -129.7, + -384.061, -370.647, -314.833, + 49.98, 65.49, -183.6, -258.5, -298.2)*1000, "cal"), + 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)+") + mod.obigt(names[i], G=myG) +} + +# 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) +names <- c(Cu_s, Cu_aq, CuGly) +# mosaic diagram with to speciate glycine as a function of pH +m <- mosaic(bases=Gly, pH=c(0, 16, 300), Eh=c(-0.6, 1.0, 300)) +fill <- c(rep("lightgrey", 3), rep("white", 4), rep("lightblue", 4)) +d <- diagram(m$A.species, fill=fill, names=NULL, tplot=FALSE, xaxs="i", yaxs="i") +# to make the labels look nicer +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(d$lx[i]+dx, d$ly[i]+dy, lab, srt=srt) +} + +# add glycine ionization lines +d <- diagram(m$A.bases, add=TRUE, col="darkblue", dotted=c(2, 3), names=NULL) +text(d$lx, -0.5, Gly, col="darkblue") + +# add water lines and title and re-draw a box around the plot +# because the filling of fields masks it +water.lines() +box() +title(main=paste("Aqueous Copper + Glycine, 25 deg C, 1 bar", + "After Aksu and Doyle, 2001 Fig. 2b",sep="\n")) + +# done! +data(thermo) Modified: pkg/CHNOSZ/inst/NEWS =================================================================== --- pkg/CHNOSZ/inst/NEWS 2015-10-19 18:37:20 UTC (rev 94) +++ pkg/CHNOSZ/inst/NEWS 2015-11-05 05:18:37 UTC (rev 95) @@ -1,6 +1,25 @@ -CHANGES IN CHNOSZ 1.0.6 (2015-10-19) +CHANGES IN CHNOSZ 1.0.6-1 (2015-11-05) -------------------------------------- +- Add functions usrfig() (get figure limits in user coordinates) and + label.figure() (add label to figure outside of plot region). + +- Add copper.R demo (complexation of copper with glycine, uses + mosaic()). + +- Using new supporting function ibasis(), swap.basis() and mosaic() + now allow basis species to be specified by name, not just formula. + +- diagram() now has '...' argument to pass additional options to + plot() (useful with diagram(tplot=FALSE, ...)). + +- TODO: Update vignette 'equilibrium.Rnw' with better definitions of + concepts, organization of functions, and amino acid and protein + examples. + +CHANGES IN CHNOSZ 1.0.6 (2015-10-19) +------------------------------------ + - Rewrite rho.IAPWS95() to be able to invert density from IAPWS-95 equations for a more extensive range of T,P values. Modified: pkg/CHNOSZ/man/diagram.Rd =================================================================== --- pkg/CHNOSZ/man/diagram.Rd 2015-10-19 18:37:20 UTC (rev 94) +++ pkg/CHNOSZ/man/diagram.Rd 2015-11-05 05:18:37 UTC (rev 95) @@ -16,7 +16,7 @@ lty=NULL, lwd=par("lwd"), dotted=0, bg=par("bg"), col=par("col"), col.names=par("col"), fill=NULL, names=NULL, main=NULL, legend.x="topright", add=FALSE, plot.it=TRUE, - tplot=TRUE) + tplot=TRUE, ...) strip(affinity, ispecies = NULL, col = NULL, ns = NULL, xticks = NULL, ymin = -0.2, xpad = 1, cex.names = 0.7) find.tp(x) @@ -62,12 +62,13 @@ \item{ymin}{numeric, lower limit of y-axis} \item{xpad}{numeric, amount to extend x-axis on each side} \item{x}{matrix, value of the \code{predominant} list element from \code{diagram}} + \item{...}{additional arguments passed to \code{\link{plot}} or \code{\link{barplot}}} } \details{ \code{diagram} takes as its primary input the results from \code{\link{equilibrate}} and displays diagrams representing the equilibrium chemical activities of the species. -0-D diagrams, at a single point, are shown as barcharts. +0-D diagrams, at a single point, are shown as \code{\link{barplot}}s. 1-D diagrams, for a single variable on the x-axis, are plotted as lines. 2-D diagrams, for two variables, are plotted as predominance fields. The allowed variables are any that \code{\link{affinity}} accepts: temperature, pressure, or the chemical activities of the basis species Modified: pkg/CHNOSZ/man/equilibrate.Rd =================================================================== --- pkg/CHNOSZ/man/equilibrate.Rd 2015-10-19 18:37:20 UTC (rev 94) +++ pkg/CHNOSZ/man/equilibrate.Rd 2015-11-05 05:18:37 UTC (rev 95) @@ -86,7 +86,7 @@ \value{ \code{equil.reaction} and \code{equil.boltzmann} each return a list with dimensions and length equal to those of \code{Astar}, giving the \code{\link{log10}} of the equilibrium activities of the species of interest. -\code{equilibrate} returns a list, containing first the values in \code{aout}, to which are appended \code{m.balance} (the balancing coefficients if \code{normalize} is TRUE, a vector of \samp{1}s otherwise), \code{n.balance} (the balancing coefficients if \code{normalize} is FALSE, a vector of \samp{1}s otherwise) and \code{loga.equil} (the calculated equilibrium activities of the species). +\code{equilibrate} returns a list, containing first the values in \code{aout}, to which are appended \code{m.balance} (the balancing coefficients if \code{normalize} is TRUE, a vector of \samp{1}s otherwise), \code{n.balance} (the balancing coefficients if \code{normalize} is FALSE, a vector of \samp{1}s otherwise), \code{loga.balance}, \code{Astar}, and \code{loga.equil} (the calculated equilibrium activities of the species). \code{balance} returns a list containing the balancing coefficients (\code{n}) and a textual description (\code{description}). } Modified: pkg/CHNOSZ/man/examples.Rd =================================================================== --- pkg/CHNOSZ/man/examples.Rd 2015-10-19 18:37:20 UTC (rev 94) +++ pkg/CHNOSZ/man/examples.Rd 2015-11-05 05:18:37 UTC (rev 95) @@ -16,7 +16,7 @@ demos(which = c("sources", "NaCl", "density", "phosphate", "nucleobase", "ORP", "diagram", "revisit", "findit", "CO2Ac", "nonideal", "ionize", "buffer", "yeastgfp", "mosaic", - "solubility", "wjd"), do.png=FALSE) + "copper", "solubility", "wjd"), do.png=FALSE) } \details{ @@ -46,6 +46,7 @@ \code{buffer} \tab ionized proteins as a chemical activity buffer (1. thiol peroxidases 2. sigma factors) \cr \code{yeastgfp} \tab logfO2-logaH2O diagrams for model proteins based on YeastGFP localizations (Dick, 2009) \cr \code{mosaic} \tab Eh-pH diagram with two sets of changing basis species (Garrels and Christ, 1965) \cr + \code{copper} \tab another example of \code{\link{mosaic}}: complexation of Cu with glycine (Aksu and Doyle, 2001) \cr \code{solubility} \tab solubility of calcite (cf. Manning et al., 2013) or CO2(gas) (cf. Stumm and Morgan, 1996) \cr \code{wjd} \tab run.wjd() with proteins: cell periphery of yeast \cr } @@ -53,6 +54,8 @@ } \references{ + Aksu, S. and Doyle, F. M. (2001) Electrochemistry of copper in aqueous glycine solutions. \emph{J. Electrochem. Soc.} \bold{148}, B51--B57. \url{http://dx.doi.org/10.1149/1.1344532} + Alberty, R. A. (2003) \emph{Thermodynamics of Biochemical Reactions}, John Wiley & Sons, Hoboken, New Jersey, 397 p. \url{http://www.worldcat.org/oclc/51242181} Dick, J. M. (2009) Calculation of the relative metastabilities of proteins in subcellular compartments of \emph{Saccharomyces cerevisiae}. \emph{BMC Syst. Biol.} \bold{3}:75. \url{http://dx.doi.org/10.1186/1752-0509-3-75} Modified: pkg/CHNOSZ/man/swap.basis.Rd =================================================================== --- pkg/CHNOSZ/man/swap.basis.Rd 2015-10-19 18:37:20 UTC (rev 94) +++ pkg/CHNOSZ/man/swap.basis.Rd 2015-11-05 05:18:37 UTC (rev 95) @@ -4,16 +4,18 @@ \alias{element.mu} \alias{basis.logact} \alias{swap.basis} +\alias{ibasis} \title{Swap Basis Species} \description{ Swap the basis species defining a chemical system. One basis species is replaced by a new one with a different chemical formula. } \usage{ + swap.basis(species, species2, T = 25) basis.matrix(basis = get("thermo")$basis) element.mu(basis = get("thermo")$basis, T = 25) basis.logact(emu, basis = get("thermo")$basis, T = 25) - swap.basis(species, species2, T = 25) + ibasis(species) } \arguments{ @@ -25,12 +27,17 @@ } \details{ - To change the basis definition, specify the names or formulas of the new basis species in the first argument. When the basis definition is changed, any species of interest that were present are deleted, unless the new basis definition has exactly the same elements as before. In that case, the species are kept and the activities of the new basis species are set so that the chemical potentials of the elements at 25 \eqn{^{\circ}}{?}C and 1 bar are unchanged. +\code{swap.basis} allows to change the basis definition by swapping out a basis species for a new one. +Specify the names or formulas of the old and replacement basis species in the first argument. +When the basis definition is changed, any species of interest that were present are deleted, unless the new basis definition has exactly the same elements as before. +In that case, the species are kept; also, the activities of the new basis species are set in order to maintain the chemical potentials of the elements at \code{T} \eqn{^{\circ}}{?}C and 1 bar. +The other functions are supporting functions: \code{basis.matrix} returns the stoichiometric matrix for the current basis definition, \code{element.mu} calculates the chemical potentials of elements corresponding to the activities of the basis species, \code{basis.logact} does the inverse operation, and \code{ibasis} returns the index in the basis set for a given species index (in \code{\link{thermo}$obigt}), name or formula. + } \seealso{ - \code{\link{basis}} for defining the basis species, a prerequisite for swapping. Tests (using \code{\link[testthat]{test_that}}) showing common error conditions are in \samp{inst/tests}. + \code{\link{basis}} for defining the basis species, a prerequisite for swapping, and \code{\link{mosaic}}, which swaps basis species in order to calculate affinities and make diagrams with changing basis species. } \examples{ Modified: pkg/CHNOSZ/man/util.plot.Rd =================================================================== --- pkg/CHNOSZ/man/util.plot.Rd 2015-10-19 18:37:20 UTC (rev 94) +++ pkg/CHNOSZ/man/util.plot.Rd 2015-11-05 05:18:37 UTC (rev 95) @@ -3,6 +3,8 @@ \alias{thermo.plot.new} \alias{thermo.axis} \alias{label.plot} +\alias{usrfig} +\alias{label.figure} \alias{water.lines} \alias{mtitle} \alias{residualsplot} @@ -21,8 +23,11 @@ xline = NULL) thermo.axis(lab = "x-axis", side = 1, line = 1.5, cex = par("cex"), lwd = par("lwd"), T = NULL, col = par("col")) - label.plot(x, xfrac = 0.95, yfrac = 0.9, cex = 1, paren = TRUE, - adj = 1) + label.plot(x, xfrac = 0.05, yfrac = 0.95, paren = FALSE, + italic = FALSE, ...) + usrfig() + label.figure(x, xfrac = 0.05, yfrac = 0.95, paren = FALSE, + italic = FALSE, ...) water.lines(xaxis = "pH", yaxis = "Eh", T = 298.15, P = "Psat", which = c("oxidation","reduction"), logaH2O = 0, lty = 2, lwd=1, col = par("fg"), xpoints = NULL, O2state="gas") @@ -55,7 +60,7 @@ \item{xfrac}{numeric, fractional location on \eqn{x}{x}-axis for placement of label} \item{yfrac}{numeric, fractional location on \eqn{y}{y}-axis for placement of label} \item{paren}{logical, add parentheses around label text?} - \item{adj}{numeric, parameter for text alignment} + \item{italic}{logical, italicize label text?} \item{xaxis}{character, description of \eqn{x}{x}-axis} \item{yaxis}{character, description of \eqn{y}{y}-axis} \item{P}{numeric, pressure (bar)} @@ -82,8 +87,13 @@ Change this to \samp{aq} to plot the logarithm of oxygen activity (do not change it if plotting \samp{Eh}). \code{xpoints} is an optional list of points on the x axis to which to restrict the plotting (default of \code{NULL} refers to the axis limits). - \code{label.plot} adds identifying text to the plot; the value given for \code{x} is made into a label like \eqn{(a)}{(a)}. The location of the label is controlled by \code{xfrac} and \code{yfrac} (the fractional locations along the respective axes) as well as \code{adj} (the text alignment parameter, see \code{\link{text}}). +\code{label.plot} and \code{label.figure} add identifying text within the plot region and figure region. +The value given for \code{x} is made into a label, optionally italicized and with parentheses (like \ifelse{latex}{\eqn{(a)}}{\ifelse{html}{\out{(a)}}{(a)}}). +The location of the label is controlled by \code{xfrac} and \code{yfrac} (the fractional coordinates of either the plot or figure region), and \code{...} can include other parameters such as \code{cex} and \code{adj} that are passed to \code{\link{text}}. +\code{usrfig} returns the limits of the figure region in \dQuote{user} coordinates (i.e. the limits of the plot region, from \code{\link{par}("usr")}). +It is a supporting function for \code{label.figure} but is also useful for other circumstances where information must be added at a particular location in a figure. + \code{thermo.axis} is used to add axes and axis labels to plots, with some default style settings (rotation of numeric labels) and conversions between oxidation-reduction scales (called by \code{thermo.plot.new}). It also adds minor tick marks. \code{mtitle} can be used to add a multi-line title to a plot. It loops over each element of \code{main} and places it on a separate margin line using \code{\link{mtext}}. This function exists to facilitate using \code{\link{expression}}s in multiline titles (see \code{\link{revisit}} for an example.) From noreply at r-forge.r-project.org Sat Nov 7 09:53:26 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Sat, 7 Nov 2015 09:53:26 +0100 (CET) Subject: [CHNOSZ-commits] r96 - in pkg/CHNOSZ: . R data demo inst man tests/testthat Message-ID: <20151107085326.CFD201875A9@r-forge.r-project.org> Author: jedick Date: 2015-11-07 09:53:26 +0100 (Sat, 07 Nov 2015) New Revision: 96 Added: pkg/CHNOSZ/R/nonideal.R pkg/CHNOSZ/man/nonideal.Rd Removed: pkg/CHNOSZ/demo/CO2Ac.R pkg/CHNOSZ/demo/diagram.R pkg/CHNOSZ/demo/nonideal.R pkg/CHNOSZ/demo/phosphate.R Modified: pkg/CHNOSZ/DESCRIPTION pkg/CHNOSZ/R/diagram.R pkg/CHNOSZ/R/equilibrate.R pkg/CHNOSZ/R/examples.R pkg/CHNOSZ/R/protein.info.R pkg/CHNOSZ/R/species.R pkg/CHNOSZ/R/swap.basis.R pkg/CHNOSZ/R/util.expression.R pkg/CHNOSZ/R/util.misc.R pkg/CHNOSZ/R/util.plot.R pkg/CHNOSZ/R/util.program.R pkg/CHNOSZ/R/water.R pkg/CHNOSZ/data/opt.csv pkg/CHNOSZ/demo/00Index pkg/CHNOSZ/demo/buffer.R pkg/CHNOSZ/demo/copper.R pkg/CHNOSZ/demo/nucleobase.R pkg/CHNOSZ/demo/solubility.R pkg/CHNOSZ/demo/wjd.R pkg/CHNOSZ/inst/NEWS pkg/CHNOSZ/man/CHNOSZ-package.Rd pkg/CHNOSZ/man/buffer.Rd pkg/CHNOSZ/man/data.Rd pkg/CHNOSZ/man/examples.Rd pkg/CHNOSZ/man/species.Rd pkg/CHNOSZ/man/swap.basis.Rd pkg/CHNOSZ/man/util.misc.Rd pkg/CHNOSZ/man/util.plot.Rd pkg/CHNOSZ/man/util.water.Rd pkg/CHNOSZ/man/water.Rd pkg/CHNOSZ/tests/testthat/test-makeup.R Log: create separate help page for nonideal() Modified: pkg/CHNOSZ/DESCRIPTION =================================================================== --- pkg/CHNOSZ/DESCRIPTION 2015-11-05 05:18:37 UTC (rev 95) +++ pkg/CHNOSZ/DESCRIPTION 2015-11-07 08:53:26 UTC (rev 96) @@ -1,6 +1,6 @@ -Date: 2015-11-05 +Date: 2015-11-07 Package: CHNOSZ -Version: 1.0.6-1 +Version: 1.0.6-2 Title: Chemical Thermodynamics and Activity Diagrams Author: Jeffrey Dick Maintainer: Jeffrey Dick Modified: pkg/CHNOSZ/R/diagram.R =================================================================== --- pkg/CHNOSZ/R/diagram.R 2015-11-05 05:18:37 UTC (rev 95) +++ pkg/CHNOSZ/R/diagram.R 2015-11-07 08:53:26 UTC (rev 96) @@ -222,7 +222,7 @@ 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) + 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 Modified: pkg/CHNOSZ/R/equilibrate.R =================================================================== --- pkg/CHNOSZ/R/equilibrate.R 2015-11-05 05:18:37 UTC (rev 95) +++ pkg/CHNOSZ/R/equilibrate.R 2015-11-07 08:53:26 UTC (rev 96) @@ -172,28 +172,24 @@ logadiff.max <- logadiff(Abar.range[2], i) if(is.infinite(logadiff.max)) stop("FIXME: the second initial guess for Abar.max failed") } - # 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 in revisit.Rd) - logadiff.min <- logadiff(Abar.range[1], i) - logadiff.max <- logadiff(Abar.range[2], i) - if(logadiff.min > 0 | logadiff.max < 0) { - # do again what we did above + 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 in revisit.Rd) logadiff.min <- logadiff(Abar.range[1], i) logadiff.max <- logadiff(Abar.range[2], i) - if(logadiff.min > 0 | logadiff.max < 0) { - stop("FIXME: make this function (Abarrange() in equil.reaction()) - iterate again to find a range of Abar such that the differences in - logarithm of activity of the conserved component cross zero") + 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) Modified: pkg/CHNOSZ/R/examples.R =================================================================== --- pkg/CHNOSZ/R/examples.R 2015-11-05 05:18:37 UTC (rev 95) +++ pkg/CHNOSZ/R/examples.R 2015-11-07 08:53:26 UTC (rev 96) @@ -30,8 +30,8 @@ } demos <- function(which=c("sources", "NaCl", "density", - "phosphate", "nucleobase", "ORP", "diagram", "revisit", "findit", - "CO2Ac", "nonideal", "ionize", "buffer", "yeastgfp", "mosaic", + "nucleobase", "ORP", "revisit", "findit", + "ionize", "buffer", "yeastgfp", "mosaic", "copper", "solubility", "wjd"), do.png=FALSE) { # run one or more demos from CHNOSZ with ask=FALSE, and return the value of the last one for(i in 1:length(which)) { Added: pkg/CHNOSZ/R/nonideal.R =================================================================== --- pkg/CHNOSZ/R/nonideal.R (rev 0) +++ pkg/CHNOSZ/R/nonideal.R 2015-11-07 08:53:26 UTC (rev 96) @@ -0,0 +1,68 @@ +# CHNOSZ/nonideal.R +# first version of function: 20080308 jmd +# moved to nonideal.R from util.misc.R 20151107 + +nonideal <- function(species,proptable,IS,T) { + thermo <- get("thermo") + # generate nonideal contributions to thermodynamic properties + # number of species, same length as proptable list + # T in Kelvin, same length as nrows of proptables + # a function that does a lot of the work + loggamma2 <- function(Z,I,T,prop='log') { + # extended Debye-Huckel equation ('log') + # and its partial derivatives ('G','H','S','Cp') + # T in Kelvin + B <- 1.6 + # 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) + # equation for alpha from Alberty, 2003 p. 48 + A <- 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 + loggamma <- function(a,Z,I,B) { - a * Z^2 * I^(1/2) / (1 + B * I^(1/2)) } + # XXX check the following equations 20080208 jmd + if(prop=='log') return(loggamma(eval(A),Z,I,B)) + else if(prop=='G') return(thermo$opt$R * T * loggamma(eval(A),Z,I,B)) + else if(prop=='H') return(thermo$opt$R * T^2 * loggamma(eval(DD(A,'T',1)),Z,I,B)) + else if(prop=='S') return(- thermo$opt$R * T * loggamma(eval(DD(A,'T',1)),Z,I,B)) + else if(prop=='Cp') return(thermo$opt$R * T^2 *loggamma(eval(DD(A,'T',2)),Z,I,B)) + } + if(!is.numeric(species[[1]])) species <- info(species,'aq') + proptable <- as.list(proptable) + # which gamma function to use + #mlg <- get(paste('loggamma',which,sep='')) + ndid <- 0 + for(i in 1:length(species)) { + myprops <- proptable[[i]] + # get the charge from the chemical formula + # force a charge count even if it's zero + mkp <- makeup(c("Z0", species[i]), sum=TRUE) + Z <- mkp[grep("Z", names(mkp))] + # don't do anything for neutral species + if(Z==0) next + # to keep unit activity coefficients of the proton and electron + if(species[i] == info("H+") & thermo$opt$ideal.H) next + if(species[i] == info("e-") & thermo$opt$ideal.e) next + didit <- FALSE + for(j in 1:ncol(myprops)) { + #if(colnames(myprops)[j]=='G') myprops[,j] <- myprops[,j] + thermo$opt$R * T * mlg(Z,IS,convert(T,'C')) + cname <- colnames(myprops)[j] + if(cname %in% c('G','H','S','Cp')) { + myprops[,j] <- myprops[,j] + loggamma2(Z,IS,T,cname) + didit <- TRUE + } + } + # append a loggam column if we did any nonideal calculations of thermodynamic properties + if(didit) myprops <- cbind(myprops,loggam=loggamma2(Z,IS,T)) + proptable[[i]] <- myprops + if(didit) ndid <- ndid + 1 + } + if(ndid > 0) msgout(paste('nonideal:',ndid,'species were nonideal\n')) + return(proptable) +} + Modified: pkg/CHNOSZ/R/protein.info.R =================================================================== --- pkg/CHNOSZ/R/protein.info.R 2015-11-05 05:18:37 UTC (rev 95) +++ pkg/CHNOSZ/R/protein.info.R 2015-11-07 08:53:26 UTC (rev 96) @@ -174,7 +174,7 @@ thermo <- get("thermo") ionize.it <- FALSE iword <- "nonionized" - bmat <- basis.matrix() + bmat <- basis.elements() if("H+" %in% rownames(bmat)) { ionize.it <- TRUE iword <- "ionized" Modified: pkg/CHNOSZ/R/species.R =================================================================== --- pkg/CHNOSZ/R/species.R 2015-11-05 05:18:37 UTC (rev 95) +++ pkg/CHNOSZ/R/species.R 2015-11-07 08:53:26 UTC (rev 96) @@ -2,9 +2,9 @@ # define species of interest # to retrieve the coefficients of reactions to form the species from the basis species -species.basis <- function(species) { - # current basis matrix - bmat <- basis.matrix() +species.basis <- function(species=get("thermo")$species$ispecies) { + # current basis elements + bmat <- basis.elements() tbmat <- t(bmat) # what are the elements? belem <- rownames(tbmat) Modified: pkg/CHNOSZ/R/swap.basis.R =================================================================== --- pkg/CHNOSZ/R/swap.basis.R 2015-11-05 05:18:37 UTC (rev 95) +++ pkg/CHNOSZ/R/swap.basis.R 2015-11-07 08:53:26 UTC (rev 96) @@ -2,8 +2,8 @@ # functions related to swapping basis species # extracted from basis() 20120114 jmd -# return the current basis matrix -basis.matrix <- function(basis = get("thermo")$basis) { +# return the current basis elements +basis.elements <- function(basis = get("thermo")$basis) { if(is.null(basis)) stop("basis species are not defined") return(as.matrix(basis[, 1:nrow(basis), drop=FALSE])) } @@ -11,7 +11,7 @@ # calculate chemical potentials of elements from logarithms of activity of basis species element.mu <- function(basis = get("thermo")$basis, T = 25) { # matrix part of the basis definition - basis.mat <- basis.matrix(basis) + basis.mat <- basis.elements(basis) # the standard Gibbs energies of the basis species if(T==25) G <- get("thermo")$obigt$G[basis$ispecies] else G <- unlist(subcrt(basis$ispecies, T=T, property="G")$out) @@ -27,7 +27,7 @@ # calculate logarithms of activity of basis species from chemical potentials of elements basis.logact <- function(emu, basis = get("thermo")$basis, T = 25) { # matrix part of the basis definition - basis.mat <- basis.matrix(basis) + 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 Modified: pkg/CHNOSZ/R/util.expression.R =================================================================== --- pkg/CHNOSZ/R/util.expression.R 2015-11-05 05:18:37 UTC (rev 95) +++ pkg/CHNOSZ/R/util.expression.R 2015-11-07 08:53:26 UTC (rev 96) @@ -1,4 +1,4 @@ -# CHNOSZ/describe.R +# CHNOSZ/util.expression.R # write descriptions of chemical species, properties, reactions, conditions # modified from describe(), axis.label() 20120121 jmd @@ -7,8 +7,10 @@ # that include subscripts, superscripts (if charged) # and optionally designations of states +/- loga or logf prefix if(length(species) > 1) (stop("more than one species")) - # the counts of elements in the species - elements <- makeup(species) + # 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(makeup(species)) # where we'll put the expression expr <- "" # loop over elements Modified: pkg/CHNOSZ/R/util.misc.R =================================================================== --- pkg/CHNOSZ/R/util.misc.R 2015-11-05 05:18:37 UTC (rev 95) +++ pkg/CHNOSZ/R/util.misc.R 2015-11-07 08:53:26 UTC (rev 96) @@ -25,69 +25,6 @@ return(T + P / dPdT) } -nonideal <- function(species,proptable,IS,T) { - thermo <- get("thermo") - # generate nonideal contributions to thermodynamic properties - # number of species, same length as proptable list - # T in Kelvin, same length as nrows of proptables - # a function that does a lot of the work - loggamma2 <- function(Z,I,T,prop='log') { - # extended Debye-Huckel equation ('log') - # and its partial derivatives ('G','H','S','Cp') - # T in Kelvin - B <- 1.6 - # 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) - # equation for alpha from Alberty, 2003 p. 48 - A <- 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 - loggamma <- function(a,Z,I,B) { - a * Z^2 * I^(1/2) / (1 + B * I^(1/2)) } - # XXX check the following equations 20080208 jmd @@@ - if(prop=='log') return(loggamma(eval(A),Z,I,B)) - else if(prop=='G') return(thermo$opt$R * T * loggamma(eval(A),Z,I,B)) - else if(prop=='H') return(thermo$opt$R * T^2 * loggamma(eval(DD(A,'T',1)),Z,I,B)) - else if(prop=='S') return(- thermo$opt$R * T * loggamma(eval(DD(A,'T',1)),Z,I,B)) - else if(prop=='Cp') return(thermo$opt$R * T^2 *loggamma(eval(DD(A,'T',2)),Z,I,B)) - } - if(!is.numeric(species[[1]])) species <- info(species,'aq') - proptable <- as.list(proptable) - # which gamma function to use - #mlg <- get(paste('loggamma',which,sep='')) - ndid <- 0 - for(i in 1:length(species)) { - myprops <- proptable[[i]] - # get the charge from the chemical formula - # force a charge count even if it's zero - mkp <- makeup(c("Z0", species[i]), sum=TRUE) - Z <- mkp[grep("Z", names(mkp))] - # don't do anything for neutral species - if(Z==0) next - # this keeps unit activity coefficient of the proton and electron - if(species[i] %in% c(info("H+"), info("e-"))) next - didit <- FALSE - for(j in 1:ncol(myprops)) { - #if(colnames(myprops)[j]=='G') myprops[,j] <- myprops[,j] + thermo$opt$R * T * mlg(Z,IS,convert(T,'C')) - cname <- colnames(myprops)[j] - if(cname %in% c('G','H','S','Cp')) { - myprops[,j] <- myprops[,j] + loggamma2(Z,IS,T,cname) - didit <- TRUE - } - } - # append a loggam column if we did any nonideal calculations of thermodynamic properties - if(didit) myprops <- cbind(myprops,loggam=loggamma2(Z,IS,T)) - proptable[[i]] <- myprops - if(didit) ndid <- ndid + 1 - } - if(ndid > 0) msgout(paste('nonideal:',ndid,'species were nonideal\n')) - return(proptable) -} - # which.balance is used by transfer(), # keep it as a global function which.balance <- function(species) { Modified: pkg/CHNOSZ/R/util.plot.R =================================================================== --- pkg/CHNOSZ/R/util.plot.R 2015-11-05 05:18:37 UTC (rev 95) +++ pkg/CHNOSZ/R/util.plot.R 2015-11-07 08:53:26 UTC (rev 96) @@ -200,11 +200,12 @@ } } -mtitle <- function(main,...) { +mtitle <- function(main, line=0, ...) { # 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 l <- length(main) - for(i in 1:l) mtext(main[i],line=l-i,...) + for(i in 1:l) mtext(main[i], line=line+l-i, ...) } Modified: pkg/CHNOSZ/R/util.program.R =================================================================== --- pkg/CHNOSZ/R/util.program.R 2015-11-05 05:18:37 UTC (rev 95) +++ pkg/CHNOSZ/R/util.program.R 2015-11-07 08:53:26 UTC (rev 96) @@ -27,9 +27,14 @@ # 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) - msgout(paste("palply:", caller.name(4), "running", length(X), "calculations on", - nCores, "cores with variable(s)", paste(varlist, collapse=", "), "\n")) + if(! "" %in% varlist) { + parallel::clusterExport(cl, varlist) + msgout(paste("palply:", caller.name(4), "running", length(X), "calculations on", + nCores, "cores with variable(s)", paste(varlist, collapse=", "), "\n")) + } else { + msgout(paste("palply:", caller.name(4), "running", length(X), "calculations on", + nCores, "cores\n")) + } # run the calculations out <- parallel::parLapply(cl, X, FUN, ...) parallel::stopCluster(cl) Modified: pkg/CHNOSZ/R/water.R =================================================================== --- pkg/CHNOSZ/R/water.R 2015-11-05 05:18:37 UTC (rev 95) +++ pkg/CHNOSZ/R/water.R 2015-11-07 08:53:26 UTC (rev 96) @@ -285,7 +285,7 @@ # calculate values of P for Psat if(identical(P, "Psat")) P <- psat() msgout(" rho") - my.rho <- rho.IAPWS95(T, P, get("thermo")$opt$IAPWS95.Psat.state) + my.rho <- rho.IAPWS95(T, P, get("thermo")$opt$IAPWS.sat) rho <- function() my.rho } for(i in 1:length(property)) { Modified: pkg/CHNOSZ/data/opt.csv =================================================================== --- pkg/CHNOSZ/data/opt.csv 2015-11-05 05:18:37 UTC (rev 95) +++ pkg/CHNOSZ/data/opt.csv 2015-11-07 08:53:26 UTC (rev 96) @@ -1,2 +1,2 @@ -Tr,Pr,Theta,Psi,R,cutoff,E.units,T.units,P.units,state,water,G.tol,Cp.tol,V.tol,varP,IAPWS95.Psat.state,paramin -298.15,1,228,2600,1.9872,1e-10,cal,C,bar,aq,SUPCRT92,100,1,1,FALSE,liquid,1000 +Tr,Pr,Theta,Psi,R,cutoff,E.units,T.units,P.units,state,water,G.tol,Cp.tol,V.tol,varP,IAPWS.sat,paramin,ideal.H,ideal.e +298.15,1,228,2600,1.9872,1e-10,cal,C,bar,aq,SUPCRT92,100,1,1,FALSE,liquid,1000,TRUE,TRUE Modified: pkg/CHNOSZ/demo/00Index =================================================================== --- pkg/CHNOSZ/demo/00Index 2015-11-05 05:18:37 UTC (rev 95) +++ pkg/CHNOSZ/demo/00Index 2015-11-07 08:53:26 UTC (rev 96) @@ -1,14 +1,10 @@ sources cross-check the reference list with the thermodynamic database NaCl equilibrium constant for aqueous NaCl dissociation density density of H2O, inverted from IAPWS-95 equations -phosphate phosphate speciation with pH, temperature and ionic strength nucleobase relative stabilities of nucleobases and some amino acids ORP oxidation-reduction potential of redox standards as a function of temperature -diagram comparison of methods for calculating stability fields revisit detailed example of usage of revisit() findit detailed example of usage of findit() -CO2Ac activity of CO2 buffered by acetic acid; comparing affinity(return.buffer=TRUE) with diagram(what="CO2") -nonideal activity coefficient of charged species, using the IS argument of subcrt ionize ionize.aa(): contour plots of net charge and ionization properties of LYSC_CHICK buffer ionized proteins as a chemical activity buffer (1. thiol peroxidases 2. sigma factors) yeastgfp logfO2-logaH2O diagrams for model proteins based on YeastGFP localizations Deleted: pkg/CHNOSZ/demo/CO2Ac.R =================================================================== --- pkg/CHNOSZ/demo/CO2Ac.R 2015-11-05 05:18:37 UTC (rev 95) +++ pkg/CHNOSZ/demo/CO2Ac.R 2015-11-07 08:53:26 UTC (rev 96) @@ -1,26 +0,0 @@ -# one can solve for the logarithm of activity of a -# basis species using the 'what' argument of diagram -basis("CHNOS") -basis("CO2", 999) -species("acetic acid", -3) -a <- affinity(O2=c(-85, -70, 4), T=c(25, 100, 4)) -# hacking to write a title with formulas and subscripts -lCO2 <- axis.label("CO2") -main <- substitute(a~~b~~c,list(a=lCO2, b="buffered by", - c="acetic acid")) -d <- diagram(a, what="CO2", main=main) -species(1, -10) -a <- affinity(O2=c(-85, -70, 4), T=c(25, 100, 4)) -d <- diagram(a, what="CO2", add=TRUE, lty=2) -# add a legend -lAC <- expr.species("CH3COOH", log="aq") -ltext <- c(as.expression(lAC), -3, -10) -lty <- c(NA, 1, 2) -legend("topright", legend=ltext, lty=lty, bg="white") -# do return.buffer and diagram(what) give the same results? -and <- as.numeric(d$plotvals[[1]]) -basis("CO2", "AC") -mod.buffer("AC", logact=-10) -a.buffer <- affinity(O2=c(-85, -70, 4), T=c(25, 100, 4), return.buffer=TRUE) -ana <- as.numeric(unlist(a.buffer[[1]])) -stopifnot(all.equal(ana, and)) Modified: pkg/CHNOSZ/demo/buffer.R =================================================================== --- pkg/CHNOSZ/demo/buffer.R 2015-11-05 05:18:37 UTC (rev 95) +++ pkg/CHNOSZ/demo/buffer.R 2015-11-07 08:53:26 UTC (rev 96) @@ -11,11 +11,11 @@ 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(0, 14, 200), T=c(25, 70, 200)) +a <- affinity(pH=c(4, 10, 300), T=c(40, 60, 300)) e <- equilibrate(a, normalize=TRUE) diagram(e, fill=NULL) title(main="Thiol peroxidases from bacteria") -text(0.5, 66, describe.basis(thermo$basis[-6,], oneline=TRUE), adj=0) +legend("topleft", describe.basis(thermo$basis[-6,])) ## Buffer + ionization: relative stabilities ## of E. coli sigma factors on a T-pH diagram Modified: pkg/CHNOSZ/demo/copper.R =================================================================== --- pkg/CHNOSZ/demo/copper.R 2015-11-05 05:18:37 UTC (rev 95) +++ pkg/CHNOSZ/demo/copper.R 2015-11-07 08:53:26 UTC (rev 96) @@ -61,8 +61,8 @@ # because the filling of fields masks it water.lines() box() -title(main=paste("Aqueous Copper + Glycine, 25 deg C, 1 bar", - "After Aksu and Doyle, 2001 Fig. 2b",sep="\n")) +mtitle(expression("Copper-water-glycine at 25"~degree*"C and 1 bar", + "After Aksu and Doyle, 2001 (Fig. 2b)"), line=0.5) # done! data(thermo) Deleted: pkg/CHNOSZ/demo/diagram.R =================================================================== --- pkg/CHNOSZ/demo/diagram.R 2015-11-05 05:18:37 UTC (rev 95) +++ pkg/CHNOSZ/demo/diagram.R 2015-11-07 08:53:26 UTC (rev 96) @@ -1,17 +0,0 @@ -## a case where the maximum affinity method doesn't -## reproduce an equilibrium predominance diagram -basis("CHNOS+") -# this adds data for some metabolites in the TCA cycle -# from Dalla-Betta and Schulte, 2010 -add.obigt() -species(c("oxaloacetate-2", "malate-2", "fumarate-2", - "a-ketoglutarate-2", "citrate-3")) -a <- affinity(O2=c(-80, -60), H2O=c(-5, 5)) -diagram(a, dotted=1, fill="heat") -e <- equilibrate(a) -diagram(e, add=TRUE, names=NULL, col="purple") -e <- equilibrate(a, normalize=TRUE) -diagram(e, add=TRUE, names=NULL) -title(main=paste("maximum affinity method (fields)\n", - "equilibrium calculations (lines)")) -data(thermo) Deleted: pkg/CHNOSZ/demo/nonideal.R =================================================================== --- pkg/CHNOSZ/demo/nonideal.R 2015-11-05 05:18:37 UTC (rev 95) +++ pkg/CHNOSZ/demo/nonideal.R 2015-11-07 08:53:26 UTC (rev 96) @@ -1,40 +0,0 @@ -### non-ideality calculations -- activity coefficients of -### aqueous species as a function of charge, temperature, -### and ionic strength -- after Alberty, 2003 -## p. 16 Table 1.3 apparent pKa of acetic acid with -## changing ionic strength -subcrt(c("acetic acid","acetate","H+"),c(-1,1,1), - IS=c(0,0.1,0.25),T=25,property="logK") -# note that these *apparent* values of G and logK approach -# their *standard* counterparts as IS goes to zero. -## p. 95: basis and elemental stoichiometries of species -## (a digression here from the nonideality calculations) -# note coefficient of O2 and NH3 will be zero for these species -basis(c("ATP-4","H+","H2O","HPO4-2","O2","NH3")) -# cf Eq. 5.1-33: (basis composition) -species(c("ATP-4","H+","H2O","HPO4-2","ADP-3","HATP-3","HADP-2","H2PO4-")) -lb <- nrow(basis()) -# cf Eq. 5.1-32: (elemental composition) -as.matrix(species()[,1:lb]) %*% as.matrix(basis()[,1:lb]) -## p. 273-275: activity coefficient (gamma) -## as a function of ionic strength and temperature -## (as of 20080304, these do look quantitatively different -## from the plots in Alberty's book.) -iplotfun <- function(T,col,add=TRUE) { - IS <- seq(0,0.25,0.0025) - s <- subcrt(c("H2PO4-","HADP-2","HATP-3","ATP-4"),IS=IS,grid="IS",T=T) - if(!add) thermo.plot.new(xlim=range(IS),ylim=c(0,1), - xlab=axis.label("IS"),ylab="gamma") - for(i in 1:4) lines(IS,10^s$out[[i]]$loggam,col=col) -} -iplotfun(0,"blue",add=FALSE) -text(0.1, 0.62, "Z = -1") -iplotfun(25,"black") -text(0.075, 0.18, "Z = -2") -iplotfun(40,"red") -text(0.05, 0.06, "Z = -3") -title(main=paste("activity coefficient (gamma) of -1,-2,-3,-4", - "charged species at 0, 25, 40 deg C, after Alberty, 2003", - sep="\n"),cex.main=0.95) -legend("topright", lty=c(NA, 1, 1, 1), col=c(NA, "blue", "black", "red"), - legend=c(as.expression(axis.label("T")), 0, 25, 40)) Modified: pkg/CHNOSZ/demo/nucleobase.R =================================================================== --- pkg/CHNOSZ/demo/nucleobase.R 2015-11-05 05:18:37 UTC (rev 95) +++ pkg/CHNOSZ/demo/nucleobase.R 2015-11-07 08:53:26 UTC (rev 96) @@ -1,21 +1,22 @@ ## Nucleobase - Amino Acid Interaction Eh-H2O -# for this example we try a unique basis definition -basis(c("CO2","H2O","glutamine","e-","H+"),c(-3,0,-3,0,-7)) -species(c("uracil","cytosine","adenine","guanine", - "phenylalanine","proline","lysine","glycine"),"aq") +# for this example we try a custom basis set +basis(c("CO2", "H2O", "glutamine", "e-", "H+"), c(-3, 0, -3, 0, -7)) +species(c("uracil", "cytosine", "adenine", "guanine", + "phenylalanine", "proline", "lysine", "glycine"), "aq") # this loaded four nucleobases and four related amino acids # (coded for by the homocodon triplets) # check out the predominance diagrams -a.1 <- affinity(H2O=c(-5,0),Eh=c(-0.5,0)) -diagram(a.1,fill=NULL) +a.1 <- affinity(H2O=c(-5, 0, 300), Eh=c(-0.5, 0, 300)) +diagram(a.1, fill=NULL) # overlay a different temperature -a.2 <- affinity(H2O=c(-5,0),Eh=c(-0.5,0),T=100) -diagram(a.2,col="red",add=TRUE,names=NULL) -# start make a title for the plot -tb <- thermo$basis # includes activities of basis species +a.2 <- affinity(H2O=c(-5, 0, 300), Eh=c(-0.5, 0, 300), T=100) +diagram(a.2, col="red", add=TRUE, names=NULL) +# add title and legend +title(main="Nucleobases and amino acids; P=Psat") +# includes activities of basis species +tb <- thermo$basis # exclude those that are on the axes -tb <- tb[!((rownames(tb) %in% c("e-","H2O"))),] -title(main="Nucleobases and amino acids; P=Psat") +tb <- tb[!((rownames(tb) %in% c("e-", "H2O"))),] dp <- describe.property(c("T", "T"), c(25, 100)) db <- describe.basis(tb) -legend("bottomleft", lty=c(1, 1, NA, NA, NA), col=c("black","red"), legend=c(dp, db)) +legend("bottomleft", lty=c(1, 1, NA, NA, NA), col=c("black", "red"), legend=c(dp, db)) Deleted: pkg/CHNOSZ/demo/phosphate.R =================================================================== --- pkg/CHNOSZ/demo/phosphate.R 2015-11-05 05:18:37 UTC (rev 95) +++ pkg/CHNOSZ/demo/phosphate.R 2015-11-07 08:53:26 UTC (rev 96) @@ -1,32 +0,0 @@ -## speciation of phosphate as a function of ionic strength -opar <- par(mfrow=c(2, 1)) -basis("CHNOPS+") -T <- c(25, 100) -species(c("PO4-3", "HPO4-2", "H2PO4-")) -a25 <- affinity(IS=c(0, 0.14), T=T[1]) -e25 <- equilibrate(a25) -d25 <- diagram(e25, ylim=c(-3.0, -2.6), legend.x=NULL) -a100 <- affinity(IS=c(0, 0.14), T=T[2]) -e100 <- equilibrate(a100) -d100 <- diagram(e100, ylim=c(-3.0, -2.6), add=TRUE, col="red") -title(main="Non-ideality model for phosphate species") -dp <- describe.property(c("pH", "T", "T"), c(7, T)) -legend("topright", lty=c(NA, 1, 1), col=c(NA, "black", "red"), legend=dp) -text(0.07, -2.76, expr.species("HPO4-2")) -text(0.07, -2.90, expr.species("H2PO4-")) -# the crossing points of the logarithms of activity at the two temperatures -# (it's higher IS at higher temperature) -x25 <- which.min(abs(d25$loga.equil[[3]] - d25$loga.equil[[2]])) -stopifnot(all.equal(x25, 27)) -x100 <- which.min(abs(d100$loga.equil[[3]] - d100$loga.equil[[2]])) -stopifnot(all.equal(x100, 45)) -## phosphate predominance f(IS,pH) -a <- affinity(IS=c(0, 0.14), pH=c(6, 13), T=T[1]) -d <- diagram(a, fill=NULL) -a <- affinity(IS=c(0, 0.14), pH=c(6, 13), T=T[2]) -d <- diagram(a, add=TRUE, names=NULL, col="red") -par(opar) -# the most stable species are PO4-3, HPO4-2, H2PO4- with decreasing pH, -# at any ionic strength (in the range used here) -stopifnot(all.equal(unique(d$predominant[1, 1:128]), 3:1)) -stopifnot(all.equal(unique(d$predominant[128, 1:128]), 3:1)) Modified: pkg/CHNOSZ/demo/solubility.R =================================================================== --- pkg/CHNOSZ/demo/solubility.R 2015-11-05 05:18:37 UTC (rev 95) +++ pkg/CHNOSZ/demo/solubility.R 2015-11-07 08:53:26 UTC (rev 96) @@ -74,10 +74,10 @@ # make plot ylim <- c(-10, 4) thermo.plot.new(xlim=range(pHs), ylim=ylim, xlab="pH", ylab="log a") -lines(pHs, loga.tot, lwd=3) +lines(pHs, loga.tot, lwd=4, col="green2") lines(pHs, loga.CO2, lwd=2) lines(pHs, loga.HCO3, lty=2, lwd=2) lines(pHs, loga.CO3, lty=3, lwd=2) -legend(ifelse(what=="calcite", "topright", "topleft"), lty=c(1, 1:3), lwd=c(3, 2, 2, 2), +legend(ifelse(what=="calcite", "topright", "topleft"), lty=c(1, 1:3), lwd=c(4, 2, 2, 2), col=c("green2", rep("black", 3)), legend=as.expression(c("total", expr.species("CO2", state="aq"), expr.species("HCO3-"), expr.species("CO3-2")))) title(main=substitute(what~"solubility at"~T~degree*"C", list(what=what, T=T))) Modified: pkg/CHNOSZ/demo/wjd.R =================================================================== --- pkg/CHNOSZ/demo/wjd.R 2015-11-05 05:18:37 UTC (rev 95) +++ pkg/CHNOSZ/demo/wjd.R 2015-11-07 08:53:26 UTC (rev 96) @@ -19,13 +19,15 @@ # run the Gibbs energy minimization w <- run.wjd(iobigt, Y=Y, imax=100) # make a log-log plot -plot(log10(y$abundance[!ina]), log10(w$X), xlim=c(1.5, 5), ylim=c(1.5, 5)) +plot(log10(y$abundance[!ina]), log10(w$X), xlim=c(1.5, 5), ylim=c(1.5, 5), + xlab="log10(abundance) reported in YeastGFP study", + ylab="log10(abundance) calculated using Gibbs energy minimization") # get the element potentials (tolerating "close enough" to equilibrium) emu <- equil.potentials(w, tol=1e7) # then the logarithms of activities of the basis species basis("CHNOS") bl <- basis.logact(emu) # make a title and legend -title(main="calculated vs observed abundances: yeast cell periphery") +title(main="relative abundances of proteins: yeast cell periphery") basis(names(bl), bl) legend("topleft", describe.basis(digits=2)) Modified: pkg/CHNOSZ/inst/NEWS =================================================================== --- pkg/CHNOSZ/inst/NEWS 2015-11-05 05:18:37 UTC (rev 95) +++ pkg/CHNOSZ/inst/NEWS 2015-11-07 08:53:26 UTC (rev 96) @@ -1,10 +1,10 @@ -CHANGES IN CHNOSZ 1.0.6-1 (2015-11-05) +CHANGES IN CHNOSZ 1.0.6-2 (2015-11-07) -------------------------------------- - Add functions usrfig() (get figure limits in user coordinates) and label.figure() (add label to figure outside of plot region). -- Add copper.R demo (complexation of copper with glycine, uses +- Add demo copper.R (complexation of copper with glycine, uses mosaic()). - Using new supporting function ibasis(), swap.basis() and mosaic() @@ -17,6 +17,20 @@ concepts, organization of functions, and amino acid and protein examples. +- Remove demo diagram.R (concepts better shown in equilibrium.Rnw). + +- Rename basis.matrix() to basis.elements(). + +- Argument of species.basis() defaults to current species indices. + ( species.basis() %*% basis.elements() returns elemental composition + of currently defined species.) + +- Move demos phosphate.R and nonideal.R to help page nonideal.Rd. + +- Add options to thermo$opt: 'ideal.H' and 'ideal.e'. Default TRUE tells + nonideal() to set activity coefficients of proton and electron to + zero. + CHANGES IN CHNOSZ 1.0.6 (2015-10-19) ------------------------------------ @@ -54,7 +68,7 @@ add specific importsFrom lines in NAMESPACE. - Fix incorrect entry for entropy of aqueous methionine and [Met] in - OBIGT.csv. Thanks to Apar Prasad for spotting this. + OBIGT.csv. Thanks to Apar Prasad for reporting this. - Some fixes for compatibility with new version of testthat (increase tolerance for one test in test-eos.R because of corrected alignment Modified: pkg/CHNOSZ/man/CHNOSZ-package.Rd =================================================================== --- pkg/CHNOSZ/man/CHNOSZ-package.Rd 2015-11-05 05:18:37 UTC (rev 95) +++ pkg/CHNOSZ/man/CHNOSZ-package.Rd 2015-11-07 08:53:26 UTC (rev 96) @@ -103,6 +103,8 @@ The values generated by \code{\link{buffer}} may not be applied correctly by \code{\link{affinity}} in calculating the affinities of the formation reactions. (The values returned by \code{affinity(..., return.buffer=TRUE)} do appear to be correct in the examples). There is an unidentified inconsistency in \code{\link{transfer}} causing the reaction boundaries in one of the examples (\code{apc("closed")}) to be offset from the stability diagram. OTOH, \code{feldspar("closed")} appears to work correctly. + + Values of activity coefficients may be affected by an unidentified bug in \code{\link{nonideal}}. } \examples{ Modified: pkg/CHNOSZ/man/buffer.Rd =================================================================== --- pkg/CHNOSZ/man/buffer.Rd 2015-11-05 05:18:37 UTC (rev 95) +++ pkg/CHNOSZ/man/buffer.Rd 2015-11-07 08:53:26 UTC (rev 96) @@ -73,7 +73,7 @@ # change the activity of species in the buffer mod.buffer("AC",logact=-10) affinity(O2=c(-85,-70,4),T=c(25,100,4),return.buffer=TRUE) -# see demo('CO2Ac') for a different strategy using the +# see below for a different strategy using the # 'what' argument of diagram [TRUNCATED] To get the complete diff run: svnlook diff /svnroot/chnosz -r 96 From noreply at r-forge.r-project.org Sun Nov 8 11:54:56 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Sun, 8 Nov 2015 11:54:56 +0100 (CET) Subject: [CHNOSZ-commits] r97 - in pkg/CHNOSZ: . R inst man vignettes Message-ID: <20151108105456.135B6187171@r-forge.r-project.org> Author: jedick Date: 2015-11-08 11:54:55 +0100 (Sun, 08 Nov 2015) New Revision: 97 Modified: pkg/CHNOSZ/DESCRIPTION pkg/CHNOSZ/R/protein.info.R pkg/CHNOSZ/R/util.plot.R pkg/CHNOSZ/inst/NEWS pkg/CHNOSZ/man/protein.info.Rd pkg/CHNOSZ/vignettes/equilibrium.Rnw pkg/CHNOSZ/vignettes/equilibrium.lyx pkg/CHNOSZ/vignettes/vig.bib Log: update vignette equilibrium.Rnw Modified: pkg/CHNOSZ/DESCRIPTION =================================================================== --- pkg/CHNOSZ/DESCRIPTION 2015-11-07 08:53:26 UTC (rev 96) +++ pkg/CHNOSZ/DESCRIPTION 2015-11-08 10:54:55 UTC (rev 97) @@ -1,6 +1,6 @@ -Date: 2015-11-07 +Date: 2015-11-08 Package: CHNOSZ -Version: 1.0.6-2 +Version: 1.0.6-3 Title: Chemical Thermodynamics and Activity Diagrams Author: Jeffrey Dick Maintainer: Jeffrey Dick Modified: pkg/CHNOSZ/R/protein.info.R =================================================================== --- pkg/CHNOSZ/R/protein.info.R 2015-11-07 08:53:26 UTC (rev 96) +++ pkg/CHNOSZ/R/protein.info.R 2015-11-08 10:54:55 UTC (rev 97) @@ -121,7 +121,7 @@ if(round.it) pf <- round(pf, 3) } # convert each protein formula to a single line - formula <- as.chemical.formula(pf) + formula <- as.chemical.formula(round(pf, 3)) if(round.it) { length <- round(length, 1) G <- round(G, 3) @@ -161,7 +161,7 @@ return(sb) } -protein.equil <- function(protein, T=25, loga.protein=0) { +protein.equil <- function(protein, T=25, loga.protein=0, digits=4) { # show the individual steps in calculating metastable equilibrium among proteins msgout("protein.equil: temperature from argument is ", T, " degrees C\n") TK <- convert(T, "K") @@ -196,30 +196,30 @@ G0prot <- unlist(suppressMessages(subcrt(pname, T=T, property="G")$out)) # standard Gibbs energy of formation reaction of nonionized protein, cal/mol G0protform <- G0prot - G0basissum - msgout("protein.equil [1]: reaction to form nonionized protein from basis species has G0(cal/mol) of ", G0protform[1], "\n") + msgout("protein.equil [1]: reaction to form nonionized protein from basis species has G0(cal/mol) of ", signif(G0protform[1], digits), "\n") if(ionize.it) { # standard Gibbs energy of ionization of protein, cal/mol G0ionization <- suppressMessages(ionize.aa(aa, property="G", T=T, pH=pH))[1, ] - msgout("protein.equil [1]: ionization reaction of protein has G0(cal/mol) of ", G0ionization[1], "\n") + msgout("protein.equil [1]: ionization reaction of protein has G0(cal/mol) of ", signif(G0ionization[1], digits), "\n") # standard Gibbs energy of formation reaction of ionized protein, cal/mol G0protform <- G0protform + G0ionization } # standard Gibbs energy of formation reaction of non/ionized residue equivalents, dimensionless G0res.RT <- G0protform/thermo$opt$R/TK/plength - msgout("protein.equil [1]: per residue, reaction to form ", iword, " protein from basis species has G0/RT of ", G0res.RT[1], "\n") + msgout("protein.equil [1]: per residue, reaction to form ", iword, " protein from basis species has G0/RT of ", signif(G0res.RT[1], digits), "\n") # 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) - msgout("protein.equil [1]: per residue, logQstar is ", logQstar[1], "\n") + msgout("protein.equil [1]: per residue, logQstar is ", signif(logQstar[1], digits), "\n") Astar.RT <- -G0res.RT - log(10)*logQstar - msgout("protein.equil [1]: per residue, Astar/RT = -G0/RT - 2.303logQstar is ", Astar.RT[1], "\n") + msgout("protein.equil [1]: per residue, Astar/RT = -G0/RT - 2.303logQstar is ", signif(Astar.RT[1], digits), "\n") if(!is.numeric(protein)) msgout("protein.equil [1]: not comparing calculations with affinity() because 'protein' is not numeric\n") 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 - msgout("check it! per residue, Astar/RT calculated using affinity() is ", aAstar.RT[1], "\n") + msgout("check it! per residue, Astar/RT calculated using affinity() is ", signif(aAstar.RT[1], digits), "\n") 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()") } @@ -227,36 +227,36 @@ else { ## next set of output: equilibrium calculations msgout("protein.equil [all]: lengths of all proteins are ", paste(plength, collapse=" "), "\n") - msgout("protein.equil [all]: Astar/RT of all residue equivalents are ", paste(Astar.RT, collapse=" "), "\n") + msgout("protein.equil [all]: Astar/RT of all residue equivalents are ", paste(signif(Astar.RT, digits), collapse=" "), "\n") expAstar.RT <- exp(Astar.RT) sumexpAstar.RT <- sum(expAstar.RT) - msgout("protein.equil [all]: sum of exp(Astar/RT) of all residue equivalents is ", sumexpAstar.RT, "\n") + msgout("protein.equil [all]: sum of exp(Astar/RT) of all residue equivalents is ", signif(sumexpAstar.RT, digits), "\n") # boltzmann distribution alpha <- expAstar.RT / sumexpAstar.RT - msgout("protein.equil [all]: equilibrium degrees of formation (alphas) of residue equivalents are ", paste(alpha, collapse=" "), "\n") + msgout("protein.equil [all]: equilibrium degrees of formation (alphas) of residue equivalents are ", paste(signif(alpha, digits), collapse=" "), "\n") # 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) - msgout("check it! alphas of residue equivalents from equilibrate() are ", paste(ealpha, collapse=" "), "\n") + msgout("check it! alphas of residue equivalents from equilibrate() are ", paste(signif(ealpha, digits), collapse=" "), "\n") 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)) - msgout("protein.equil [all]: for activity of proteins equal to 10^", loga.protein, ", total activity of residues is 10^", loga.residue, "\n") + msgout("protein.equil [all]: for activity of proteins equal to 10^", signif(loga.protein, digits), ", total activity of residues is 10^", signif(loga.residue, digits), "\n") # equilibrium activities of residues loga.residue.equil <- log10(alpha*10^loga.residue) - msgout("protein.equil [all]: log10 equilibrium activities of residue equivalents are ", paste(loga.residue.equil, collapse=" "), "\n") + msgout("protein.equil [all]: log10 equilibrium activities of residue equivalents are ", paste(signif(loga.residue.equil, digits), collapse=" "), "\n") # equilibrium activities of proteins loga.protein.equil <- log10(10^loga.residue.equil/plength) - msgout("protein.equil [all]: log10 equilibrium activities of proteins are ", paste(loga.protein.equil, collapse=" "), "\n") + msgout("protein.equil [all]: log10 equilibrium activities of proteins are ", paste(signif(loga.protein.equil, digits), collapse=" "), "\n") # check with equilibrate() if(is.numeric(protein)) { eloga.protein.equil <- unlist(suppressMessages(equilibrate(a, loga.balance=loga.residue, normalize=TRUE))$loga.equil) - msgout("check it! log10 eq'm activities of proteins from equilibrate() are ", paste(eloga.protein.equil, collapse=" "), "\n") + msgout("check it! log10 eq'm activities of proteins from equilibrate() are ", paste(signif(eloga.protein.equil, digits), collapse=" "), "\n") 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()") } Modified: pkg/CHNOSZ/R/util.plot.R =================================================================== --- pkg/CHNOSZ/R/util.plot.R 2015-11-07 08:53:26 UTC (rev 96) +++ pkg/CHNOSZ/R/util.plot.R 2015-11-08 10:54:55 UTC (rev 97) @@ -152,13 +152,14 @@ ylim <- pu[3:4] # exact lines # warning: Eh calculations are reliable only at a single T - if(xaxis=='pH' & (yaxis=='Eh' | yaxis=='O2' | yaxis=="pe")) { + if(xaxis=="O2" | (xaxis=='pH' & (yaxis=='Eh' | yaxis=='O2' | yaxis=="pe"))) { if('reduction' %in% which) { logfH2 <- 0 logK <- 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 + 2 * logaH2O - if(yaxis=='O2') abline(h=logfO2,lty=lty,lwd=lwd,col=col) + if(xaxis=='O2') abline(v=logfO2,lty=lty,lwd=lwd,col=col) + else if(yaxis=='O2') abline(h=logfO2,lty=lty,lwd=lwd,col=col) else if(yaxis=="Eh") lines(xlim,convert(logfO2,'E0',T=T,P=P,pH=xlim),lty=lty,lwd=lwd,col=col) else if(yaxis=="pe") lines(xlim,convert(convert(logfO2,'E0',T=T,P=P,pH=xlim),"pe",T=T),lty=lty,lwd=lwd,col=col) } @@ -167,6 +168,7 @@ logK <- 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(xaxis=='O2') abline(v=logfO2,lty=lty,lwd=lwd,col=col) if(yaxis=='O2') abline(h=logfO2,lty=lty,lwd=lwd,col=col) else if(yaxis=="Eh") lines(xlim,convert(logfO2,'E0',T=T,P=P,pH=xlim),lty=lty,lwd=lwd,col=col) else if(yaxis=="pe") lines(xlim,convert(convert(logfO2,'E0',T=T,P=P,pH=xlim),"pe",T=T),lty=lty,lwd=lwd,col=col) Modified: pkg/CHNOSZ/inst/NEWS =================================================================== --- pkg/CHNOSZ/inst/NEWS 2015-11-07 08:53:26 UTC (rev 96) +++ pkg/CHNOSZ/inst/NEWS 2015-11-08 10:54:55 UTC (rev 97) @@ -1,4 +1,4 @@ -CHANGES IN CHNOSZ 1.0.6-2 (2015-11-07) +CHANGES IN CHNOSZ 1.0.6-3 (2015-11-08) -------------------------------------- - Add functions usrfig() (get figure limits in user coordinates) and @@ -13,9 +13,9 @@ - diagram() now has '...' argument to pass additional options to plot() (useful with diagram(tplot=FALSE, ...)). -- TODO: Update vignette 'equilibrium.Rnw' with better definitions of - concepts, organization of functions, and amino acid and protein - examples. +- Update vignette 'equilibrium.Rnw' with better definitions of concepts, + organization of functions, and examples and applications. Now uses + knitr. - Remove demo diagram.R (concepts better shown in equilibrium.Rnw). Modified: pkg/CHNOSZ/man/protein.info.Rd =================================================================== --- pkg/CHNOSZ/man/protein.info.Rd 2015-11-07 08:53:26 UTC (rev 96) +++ pkg/CHNOSZ/man/protein.info.Rd 2015-11-08 10:54:55 UTC (rev 97) @@ -18,7 +18,7 @@ protein.length(protein, organism = NULL) protein.info(protein, T = 25, residue = FALSE, round.it = FALSE) protein.basis(protein, T = 25, normalize = FALSE) - protein.equil(protein, T=25, loga.protein = 0) + protein.equil(protein, T=25, loga.protein = 0, digits = 4) MP90.cp(protein, T) group.formulas() } @@ -31,6 +31,7 @@ \item{T}{numeric, temperature in \eqn{^{\circ}}{?}C} \item{round.it}{logical, round the values in the output?} \item{loga.protein}{numeric, decimal logarithms of reference activities of proteins} + \item{digits}{integer, number of significant digits (see \code{\link{signif}})} } \details{ Modified: pkg/CHNOSZ/vignettes/equilibrium.Rnw =================================================================== --- pkg/CHNOSZ/vignettes/equilibrium.Rnw 2015-11-07 08:53:26 UTC (rev 96) +++ pkg/CHNOSZ/vignettes/equilibrium.Rnw 2015-11-08 10:54:55 UTC (rev 97) @@ -1,32 +1,30 @@ -%% LyX 2.1.3 created this file. For more info, see http://www.lyx.org/. +%% LyX 2.1.4 created this file. For more info, see http://www.lyx.org/. %% Do not edit unless you really know what you are doing. -\documentclass[english,noae]{article} +\documentclass[english,round]{article} \usepackage{mathpazo} +\renewcommand{\sfdefault}{lmss} +\renewcommand{\ttdefault}{lmtt} \usepackage[T1]{fontenc} \usepackage[latin9]{inputenc} -\usepackage[letterpaper]{geometry} +\usepackage{geometry} \geometry{verbose,tmargin=2.5cm,bmargin=2.5cm,lmargin=2.5cm,rmargin=2.5cm} \usepackage{color} \usepackage{babel} \usepackage{amsbsy} \usepackage{amssymb} -\usepackage[numbers]{natbib} +\usepackage[authoryear]{natbib} \usepackage[unicode=true,pdfusetitle, bookmarks=true,bookmarksnumbered=false,bookmarksopen=false, - breaklinks=false,pdfborder={0 0 1},backref=false,colorlinks=true] + breaklinks=false,pdfborder={0 0 0},backref=false,colorlinks=true] {hyperref} \hypersetup{ - citecolor=black, linkcolor=black} + citecolor=magenta, urlcolor=blue} \usepackage{breakurl} \makeatletter -%%%%%%%%%%%%%%%%%%%%%%%%%%%%%% Textclass specific LaTeX commands. -<>= - if(exists(".orig.enc")) options(encoding = .orig.enc) -@ - %%%%%%%%%%%%%%%%%%%%%%%%%%%%%% User specified LaTeX commands. %\VignetteIndexEntry{Equilibrium in CHNOSZ} +%\VignetteEngine{knitr::knitr} % so DOIs in bibliography show up as hyperlinks \newcommand*{\doi}[1]{\href{http://dx.doi.org/#1}{doi: #1}} @@ -34,62 +32,683 @@ \makeatother \begin{document} +<>= +library(knitr) +## set global chunk options +opts_chunk$set(fig.align='center') +opts_chunk$set(tidy=TRUE) +## set code/output width +options(width=85) +## set number of digits +options(digits=3) +@ + \title{Equilibrium in CHNOSZ} \author{Jeffrey M. Dick} \maketitle +This document defines the concepts, explains the organization of functions, +and provides examples of calculating equilibrium in CHNOSZ. It also +highlights some applications of the methods (i.e. to reproduce published +diagrams) and includes an Appendix on details of the equilibration +calculations. -\section{Background; terminology} -\emph{Species of interest} (or simply \emph{species}) are chosen by -the user to represent the possible species in a chemical system. \emph{Basis -species} combine linearly to make up the species of interest. Basis -species are analogous to thermodynamic components in that they are -the minimum number to describe the compositional variation, but unlike -components basis species can be charged. +\section{Concepts} +\begin{description} +\item [{Species~of~interest}] Chemical species for which you want to +calculate relative stabilities. +\item [{Basis~species}] Species in terms of which you want to write all +formation reactions of species of interest. +\item [{Formation~reactions}] Stoichiometric chemical reactions showing +the mass requirements for formation of 1 mole of each species of interest +from the basis species. +\item [{Chemical~affinity}] Change in Gibbs energy per increment of reaction +progress; the negative of the overall Gibbs energy of reaction; $\boldsymbol{A}=2.303RT\log(K/Q)$, +where $K$ is the equilibrium constant and $Q$ is the reaction activity +quotient ($\log$ here is used for base-10 logarithms). +\item [{(1)~Reference~activity}] User-defined (usually equal) activities +of species of interest. +\item [{(1)~Reference~affinity}] ($\boldsymbol{A}_{{\it ref}}$) Chemical +affinity of formation reaction with a reference activity of the species +of interest. +\item [{(1)~Maximum~affinity~method}] Comparison of reference affinities +for given balance coefficients in order to calculate stability regions +on a predominance diagram. +\item [{Balance~coefficients}] ($n_{balance}$) The number of moles of +a basis species present in the formation reaction of each of the species +of interest. Reactions between any two species of interest then are +``balanced'' on this basis species. Can be a quantity other than +basis species (e.g., balance = 1, or length of amino acid sequence +of protein). +\item [{Predominance~diagram}] Diagram showing fields of maximal stability +(i.e. greatest activity at equilibrium) for species of interest as +a function of two variables (aka equal activity diagram). +\item [{(2)~Starred~affinity}] ($\boldsymbol{A}^{*}$) Chemical affinity +of formation reaction with unit activity of the species of interest +(aka ``starved'' affinity because the activity of the species of +interest drops out of $Q$). +\item [{(2)~Total~balance~activity}] The sum of activities of this basis +species contributed by each of the species of interest. (In Appendix: +activity of the immobile or conserved component; $a_{\mathrm{ic}}$.) +\item [{(2)~Equilibration~method}] Comparison of starred affinities in +order to calculate activities of species of interest for given balance +coefficients and total balance activity. +\item [{Speciation~diagram}] Diagram showing the activities of species +of interest, usually as a function of 1 variable (aka activity diagram). +\item [{Boltzmann~distribution}] Algorithm used for the equilibration +method when the balance coefficients are 1. +\item [{Reaction~matrix}] Algorithm used for the equilibration method +when the balance coefficients are not all 1. +\item [{Normalization}] Algorithm used for large molecules such as proteins; +chemical formulas and affinities are scaled to an equal size (e.g. +a single residue; ``residue equivalent'' in Appendix), activities +are calculated using balance = 1, and formulas and activities are +rescaled to the original size of the molecule. +\item [{Mosaic}] Calculations of chemical affinities for making diagrams +where the speciation of basis species depends on the variables. +\end{description} +The numbered groups above are connected with two distinct approaches +to generating diagrams: +\begin{enumerate} +\item With the \textbf{maximum affinity method} for creating predominance +diagrams, the user sets the reference activities of the species of +interest; the program compares the reference affinities at these conditions +to determine the most stable species (highest activity, i.e. predominant +at equilibrium). +\item With the \textbf{equilibration method} for creating predominance or +activity diagrams, the user explicitly sets the total balance activity +or the program takes it from the reference activities of the species. +The starred affinities are used to calculate equilibrium activities +using one of two techniques (Boltzmann distribution for balance = +1, reaction matrix for balance $\ne$ 1). +\end{enumerate} +The affinities used in these calculations can be calculated using +\texttt{affinity()}, which works with a single basis set, or with +\texttt{mosaic()}, which uses multiple basis sets to account for basis +species that themselves may change as a function of the variables +of interest (e.g. ionization of carbonic acid as a function of pH). +This document focuses primarily on the \texttt{affinity()} function; +for more information on mosaic diagrams see the help page (type \texttt{?mosaic} +at the R command line). -The calculations of chemical equilibrium in CHNOSZ are formulated -for a system that is open with respect to the basis species. Therefore, -the natural variables are temperature, pressure and chemical potentials -of the basis species. +Step-by-step examples of some of the calculations, particularly the +reaction matrix algorithm, are provided in the Appendix. For further +description of the equilibration method applied to proteins see \citet{DS13} +(also with a derivation of energetic distance from equilibrium using +the \textbf{starred affinity}). -To calculate the equilibrium distribution of species in a given system, -a single linear balancing constraint must be specified. Therefore, -we say things like ``the reactions are balanced on $\mathrm{CO_{2}}$'' -or ``the reactions are balanced on protein length''. The \emph{balancing -coefficients} describe these constraints. At different times in the -documentation of CHNOSZ, the balancing constraint has been associated -with the conserved component, immobile component, or conserved basis -species, all with the same meaning. -The ``reactions'' in the preceding statements refer to \emph{transformations} -between species. The actual calculations, however, start with the -definitions of the formation reactions. The \emph{formation reaction} -for any species has one mole of the species as a product, and the -mass balance is made up of the basis species. +\section{Organization} -By definition, the formation reaction is written to form one mole -of a species. For many systems, the extent of the molar formula of -the species is not a matter of concern. However, for systems made -of polymers, such as proteins, it is often desirable to normalize -the molar formula by the balancing coefficients. This normalization -has been referred to previously as using the residue equivalents of -proteins \citep{Dic08}; here the terminology of \emph{normalize} -will be used preferentially\footnote{The older style of function call using \texttt{diagram(..., residue=TRUE)} -has been replaced by \texttt{equilibrate(..., normalize=TRUE)} or -\texttt{diagram(..., normalize=TRUE)} starting with version 0.9-9 -of CHNOSZ.}. +The function sequences below assume you have already defined the basis +species and species of interest using \texttt{basis(...)} and \texttt{species(...)} +(ellipses here and below indicate system-specific input). +Note that if \texttt{equilibrate()} or \texttt{diagram()} is called +without an explicit \texttt{balance} argument, the balance coefficients +will be taken from the first basis species (in the current basis definition) +that is present in all of the species. Depending on the system, this +may coincide either with balance = 1 or with balance $\ne$ 1. In +the case of \texttt{normalize = TRUE} or \texttt{as.residue = TRUE}, +the balance coefficients (for the purposes of the equilibration step) +are temporarily set to 1. +\begin{enumerate} +\item Maximum affinity method, balance = 1 + +\begin{enumerate} +\item Typical use: simple mineral/aqueous species stability comparisons +\item Function sequence:\\ +\texttt{a <- affinity(...)}\\ +\texttt{diagram(a, balance = 1)} +\item Algorithm: $\max\left\{ \boldsymbol{A}_{{\it ref}}\right\} $ +\end{enumerate} +\item Equilibration method, balance = 1 + +\begin{enumerate} +\item Typical use: simple aqueous species activity comparisons +\item Function sequence:\\ +\texttt{a <- affinity(...)}\\ +\texttt{e <- equilibrate(e, balance = 1)}\\ +\texttt{diagram(e)} +\item Algorithm: Boltzmann distribution +\end{enumerate} +\item Maximum affinity method, balance $\ne$ 1 + +\begin{enumerate} +\item Typical use: mineral/aqueous species stability comparisons +\item Function sequence:\\ +\texttt{a <- affinity(...)}~\\ +\texttt{diagram(a, balance = ...)} +\item Algorithm: $\max\left\{ \boldsymbol{A}_{{\it ref}}/n_{balance}\right\} $ +\end{enumerate} +\item Equilibration method, balance $\ne$ 1 + +\begin{enumerate} +\item Typical use: aqueous species activity comparisons +\item Function sequence:\\ +\texttt{a <- affinity(...)}~\\ +\texttt{e <- equilibrate(a, balance = ...)}~\\ +\texttt{diagram(e)} +\item Algorithm: Reaction matrix +\end{enumerate} +\item Maximum affinity method, normalize = TRUE + +\begin{enumerate} +\item Typical use: protein/polymer stability comparisons +\item Function sequence:\\ +\texttt{a <- affinity(...)}~\\ +\texttt{diagram(a, normalize = TRUE)} +\item Algorithm: $\max\left\{ \boldsymbol{A}^{*}/n_{balance}-\log n_{balance}\right\} $ +\end{enumerate} +\item Equilibration method, normalize = TRUE + +\begin{enumerate} +\item Typical use: protein/polymer activity comparisons +\item Function sequence:\\ +\texttt{a <- affinity(...)}~\\ +\texttt{e <- equilibrate(a, normalize = TRUE)}~\\ +\texttt{diagram(e)} +\item Algorithm: Scale formulas and affinities to residues; Boltzmann distribution +(balance = 1); Scale activities to proteins +\end{enumerate} +\end{enumerate} + +\section{Examples} + + +\subsection{Amino acids} + +Basis species: $\mathrm{CO_{2}}$, $\mathrm{H_{2}O}$, $\mathrm{NH_{3}}$, +$\mathrm{H_{2}S}$, $\mathrm{O_{2}}$. Species of interest: 20 amino +acids. (Only the first few lines of the data frame of amino acid species +are shown.) + +<>= +library(CHNOSZ) +data(thermo) +basis("CHNOS") +species(aminoacids(""))[1:5, ] +@ + +Code for figures. Function names are keyed to the subfigures. + +<>= +res <- 200 +aa <- aminoacids() + +aaA <- function() { + a <- affinity(O2=c(-90, -70, res), H2O=c(-20, 10, res)) + diagram(a, balance=1, names=aa) +} + +aaB <- function() { + a <- affinity(O2=c(-90, -70, res), H2O=c(-20, 10, res)) + e <- equilibrate(a, balance=1) + diagram(e, names=aa) +} + +aaC <- function() { + a <- affinity(O2=c(-71, -66, res), H2O=c(-8, 4, res)) + diagram(a, balance="CO2", names=aa) +} + +aaD <- function() { + a <- affinity(O2=c(-71, -66), H2O=c(-8, 4)) + e <- equilibrate(a, balance="CO2") + diagram(e, names=aa) +} + +aaE <- function() { + basis("O2", -66) + a <- affinity(H2O=c(-8, 4)) + e <- equilibrate(a, balance="CO2") + diagram(e, ylim=c(-5, -1), names=aa) +} + +aaF <- function() { + species(1:20, -4) + a <- affinity(H2O=c(-8, 4)) + e <- equilibrate(a, balance="CO2") + diagram(e, ylim=c(-5, -1), names=aa) +} +@ + +Note that for the plot we use the 1-letter abbreviations of the amino +acids, unlike the full species names (\texttt{aminoacids()} is a function +in CHNOSZ that returns their names or abbreviations). + +<>= +AA <- aminoacids("") +names(AA) <- aa +AA +@ + +The annotated figure is shown next. The actual code used to set up +the plots, add labels, etc. is in the source of this vignette (not +shown in the PDF). + +<>= +showtime <- function(st) { + # plot time in lower-right of figure region + f <- usrfig() + par(xpd=TRUE) + if(st[3] > 2) col <- "red" else col <- "black" + text(f$x[2], f$y[1], paste(round(st[3], 1), "s\n"), adj=1, col=col) + par(xpd=FALSE) +} +@ + +<>= +layout(t(matrix(c(1:7, 11, 8:10, 12), nrow=4)), widths=c(1, 4, 4, 4), heights=c(1, 4, 4)) + +## row 0 (column titles) +opar <- par(mar=c(0, 0, 0, 0)) +plot.new() +plot.new() +text(0.5, 0.5, "maximum affinity", cex=1.4) +plot.new() +text(0.5, 0.5, "equilibration", cex=1.4) +plot.new() +text(0.5, 0.5, "equilibration", cex=1.4) +par(opar) + +## row 1 (balance = 1) +opar <- par(mar=c(0, 0, 0, 0)) +plot.new() +text(0.5, 0.5, "balance = 1", srt=90, cex=1.4) +par(opar) +# figure A +st <- system.time(dA <- aaA()) +showtime(st) +title(main="loga(species) = -3", cex.main=1) +label.figure("A", col="blue", yfrac=0.9, xfrac=0.1) +# figure B +st <- system.time(dB <- aaB()) +showtime(st) +title(main=paste("loga(total species) =", round(dB$loga.balance, 2)), cex.main=1) +label.figure("B", col="blue", yfrac=0.9, xfrac=0.1) + +## row 2 (balance = nCO2) +opar <- par(mar=c(0, 0, 0, 0)) +plot.new() +text(0.5, 0.5, 'balance = "CO2"', srt=90, cex=1.4) +par(opar) +# figure C +st <- system.time(dC <- aaC()) +showtime(st) +title(main="loga(species) = -3", cex.main=1) +label.figure("C", col="blue", yfrac=0.9, xfrac=0.1) +# figure D +st <- system.time(dD <- aaD()) +showtime(st) +title(main=paste("loga(total CO2) =", round(dD$loga.balance, 2)), cex.main=1) +label.figure("D", col="blue", yfrac=0.9, xfrac=0.1) + +## right (speciation at different total activity of CO2) +par(xpd=NA) +lines(c(-66, -64.5), c(4, 9), lty=2) +lines(c(-66, -64.5), c(-8, -8.5), lty=2) +par(xpd=FALSE) +# figure E +st <- system.time(dE <- aaE()) +showtime(st) +title(main=paste("loga(total CO2) =", round(dE$loga.balance, 2)), cex.main=1) +label.figure("E", col="blue", yfrac=0.9, xfrac=0.1) +# figure F +st <- system.time(dF <- aaF()) +showtime(st) +title(main=paste("loga(total CO2) =", round(dF$loga.balance, 2)), cex.main=1) +label.figure("F", col="blue", yfrac=0.9, xfrac=0.1) + +@ + +Comments on the plots: +\begin{itemize} +\item The equal-activity lines in Figures \textcolor{blue}{A} and \textcolor{blue}{B} +are \emph{identical}. For balance = 1, the maximum affinity method +and the equilibration method should produce the same predominance +diagrams. (More precisely, because balance = 1, the conditions of +equal activity of any species of interest \textbf{are independent +of} the actual value of that activity.) +\item Figures \textcolor{blue}{C} and \textcolor{blue}{D} are \emph{different}. +For balance $\ne$ 1, the maximum affinity method and the equilibration +method will generally produce difference predominance diagrams. (Because +balance $\ne$ 1, the conditions of equal activity of any species +of interest \textbf{depend on} the actual value of that activity.) +\item Both Figures \textcolor{blue}{E} and \textcolor{blue}{F} are constructed +using the equilibration method, to calculate activities of species +as a function of $\log a_{\mathrm{H_{2}O}}$ at $\log f_{\mathrm{O_{2}}}=-66$. +Figure \textcolor{blue}{E} shows the results for the default settings +($a_{\mathrm{CO_{2}}}$ is the sum of activities present in all species, +taken from initial species activity of $10^{-3}$) and the crossing +lines indicating equal activities \emph{are identical to the positions +in Figure }\textcolor{blue}{\emph{D}} at $\log f_{\mathrm{O_{2}}}=-66$. +\item Figure \textcolor{blue}{F} shows the results for a lower total activity +of $\mathrm{CO_{2}}$. Consequently, the activities of the predominant +species decrease from ca. $10^{-2}$ in Figure \textcolor{blue}{E} +to ca. $10^{-3}$ in Figure \textcolor{blue}{F}. Also, the stability +region of the smaller glycine has grown at the expense of the neighboring +bigger amino acids, so that the crossing lines indicating equal activities +in Figure \textcolor{blue}{F} \emph{are closer to those shown in Figure +}\textcolor{blue}{\emph{C}} at $\log f_{\mathrm{O_{2}}}=-66$. +\item In other words, a lower equal-activity value causes the stability +region of the species with the smaller balance coefficient to invade +that of the species with the larger balance coefficient. +\item Figures \textcolor{blue}{A}, \textcolor{blue}{B}, \textcolor{blue}{C}, +and \textcolor{blue}{D} are all equal activity diagrams, but have +different constraints on the activities: + +\begin{itemize} +\item Maximum affinity method (Figures \textcolor{blue}{A}, \textcolor{blue}{C}): +Equal activities of species set to a constant value. +\item Equilibration method (Figures \textcolor{blue}{B}, \textcolor{blue}{D}): +Equal activities of species determined by overall speciation of the +system. +\end{itemize} +\end{itemize} + +\subsection{Proteins} + +Basis species: $\mathrm{CO_{2}}$, $\mathrm{H_{2}O}$, $\mathrm{NH_{3}}$, +$\mathrm{H_{2}S}$, $\mathrm{O_{2}}$, $\mathrm{H^{+}}$. Species +of interest: 6 proteins from the set of archaeal and bacterial surface +layer proteins considered by \citet{Dic08}. + +<>= +basis("CHNOS+") +organisms <- c("METJA", "HALJP", "METVO", "ACEKI", "GEOSE", "BACLI") +proteins <- c(rep("CSG", 3), rep("SLAP", 3)) +species(proteins, organisms) +@ + +Code for the figures. + +<>= +prA <- function() { + a <- affinity(O2=c(-90, -70, res), H2O=c(-20, 0, res)) + e <- equilibrate(a, balance="length", loga.balance=0) + diagram(e, names=organisms) +} + +prB <- function() { + a <- affinity(O2=c(-90, -70)) + e <- equilibrate(a, balance="length", loga.balance=0) + diagram(e, names=organisms, ylim=c(-5, -1), legend.x=NA) +} + +prC <- function() { + a <- affinity(O2=c(-90, -70, res), H2O=c(-20, 0, res)) + e <- equilibrate(a, normalize=TRUE, loga.balance=0) + diagram(e, names=organisms) +} + +prD <- function() { + a <- affinity(O2=c(-90, -70)) + e <- equilibrate(a, normalize=TRUE, loga.balance=0) + diagram(e, names=organisms, ylim=c(-5, -1), legend.x=NA) +} + +prE <- function() { + a <- affinity(O2=c(-90, -70, res), H2O=c(-20, 0, res)) + e <- equilibrate(a, as.residue=TRUE, loga.balance=0) + diagram(e, names=organisms) +} + +prF <- function() { + a <- affinity(O2=c(-90, -70)) + e <- equilibrate(a, as.residue=TRUE, loga.balance=0) + diagram(e, names=organisms, ylim=c(-3, 1), legend.x=NA) +} +@ + +The plots follow. As before, the code used to layout the figure and +label the plots is not shown in the PDF. + +<>= +layout(t(matrix(1:12, nrow=4)), widths=c(1, 4, 4, 4), heights=c(1, 4, 4)) + +## row 0 (column titles) +opar <- par(mar=c(0, 0, 0, 0)) +plot.new() +plot.new() +text(0.5, 0.5, 'balance = "length"', cex=1.4) +plot.new() +text(0.5, 0.5, "normalize = TRUE\n(balance = 1)", cex=1.4) +plot.new() +text(0.5, 0.5, "as.residue = TRUE\n(balance = 1)", cex=1.4) +par(opar) + +## row 1 (equilibrate 2D) +opar <- par(mar=c(0, 0, 0, 0)) +plot.new() +text(0.5, 0.5, "equilibration", srt=90, cex=1.4) +par(opar) +# figure A (balance = "length") +st <- system.time(dA <- prA()) +showtime(st) +label.figure("A", col="blue", yfrac=0.9, xfrac=0.1) +# figure C (normalize = TRUE) +st <- system.time(dC <- prC()) +showtime(st) +label.figure("C", col="blue", yfrac=0.9, xfrac=0.1) +# figure E (as.residue = TRUE) +st <- system.time(dE <- prE()) +showtime(st) +label.figure("E", col="blue", yfrac=0.9, xfrac=0.1) + [TRUNCATED] To get the complete diff run: svnlook diff /svnroot/chnosz -r 97 From noreply at r-forge.r-project.org Mon Nov 9 05:45:01 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 9 Nov 2015 05:45:01 +0100 (CET) Subject: [CHNOSZ-commits] r98 - in pkg/CHNOSZ: . R inst man tests/testthat vignettes Message-ID: <20151109044501.71D27186FB1@r-forge.r-project.org> Author: jedick Date: 2015-11-09 05:45:00 +0100 (Mon, 09 Nov 2015) New Revision: 98 Added: pkg/CHNOSZ/inst/tests/ Removed: pkg/CHNOSZ/inst/tests/ Modified: pkg/CHNOSZ/DESCRIPTION pkg/CHNOSZ/R/diagram.R pkg/CHNOSZ/R/equilibrate.R pkg/CHNOSZ/inst/NEWS pkg/CHNOSZ/man/equilibrate.Rd pkg/CHNOSZ/tests/testthat/test-diagram.R pkg/CHNOSZ/tests/testthat/test-equilibrate.R pkg/CHNOSZ/vignettes/equilibrium.Rnw pkg/CHNOSZ/vignettes/equilibrium.lyx Log: add 'method' argument to equilibrate() Modified: pkg/CHNOSZ/DESCRIPTION =================================================================== --- pkg/CHNOSZ/DESCRIPTION 2015-11-08 10:54:55 UTC (rev 97) +++ pkg/CHNOSZ/DESCRIPTION 2015-11-09 04:45:00 UTC (rev 98) @@ -1,6 +1,6 @@ -Date: 2015-11-08 +Date: 2015-11-09 Package: CHNOSZ -Version: 1.0.6-3 +Version: 1.0.6-4 Title: Chemical Thermodynamics and Activity Diagrams Author: Jeffrey Dick Maintainer: Jeffrey Dick Modified: pkg/CHNOSZ/R/diagram.R =================================================================== --- pkg/CHNOSZ/R/diagram.R 2015-11-08 10:54:55 UTC (rev 97) +++ pkg/CHNOSZ/R/diagram.R 2015-11-09 04:45:00 UTC (rev 98) @@ -42,7 +42,7 @@ if(!"loga.equil" %in% names(eout)) { eout.is.aout <- TRUE # get the balancing coefficients - n.balance <- balance(eout, balance)$n + n.balance <- balance(eout, balance) } } else if(what %in% rownames(eout$basis)) { # to calculate the loga of basis species at equilibrium Modified: pkg/CHNOSZ/R/equilibrate.R =================================================================== --- pkg/CHNOSZ/R/equilibrate.R 2015-11-08 10:54:55 UTC (rev 97) +++ pkg/CHNOSZ/R/equilibrate.R 2015-11-09 04:45:00 UTC (rev 98) @@ -3,15 +3,15 @@ # of species in (metastable) equilibrium equilibrate <- function(aout, balance=NULL, loga.balance=NULL, - ispecies=1:length(aout$values), normalize=FALSE, as.residue=FALSE) { + ispecies=1:length(aout$values), normalize=FALSE, as.residue=FALSE, + method=c("boltzmann", "reaction")) { ### set up calculation of equilibrium activities of species from the affinities ### of their formation reactions from basis species at known activities ### split from diagram() 20120925 jmd ## number of possible species nspecies <- length(aout$values) ## get the balancing coefficients - balance <- balance(aout, balance) - n.balance <- balance$n + n.balance <- balance(aout, balance) ## take selected species in 'ispecies' if(length(ispecies)==0) stop("the length of ispecies is zero") # take out species that have NA affinities @@ -27,17 +27,15 @@ ## number of species that are left nspecies <- length(aout$values) ## say what the balancing coefficients are - if(length(n.balance) < 100) msgout(paste("equilibrate: balancing coefficients are", c2s(n.balance), "\n")) + if(length(n.balance) < 100) msgout(paste("equilibrate: n.balance is", c2s(n.balance), "\n")) ## logarithm of total activity of the balance - if(is.numeric(loga.balance)) - msgout(paste("equilibrate: logarithm of total", balance$description, "(from loga.balance) is", loga.balance, "\n")) - else { + 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) - msgout(paste("equilibrate: logarithm of total", balance$description, "is", loga.balance, "\n")) } + msgout(paste0("equilibrate: loga.balance is ", loga.balance, "\n")) ## normalize -- normalize the molar formula by the balance coefficients m.balance <- n.balance isprotein <- grepl("_", as.character(aout$species$name)) @@ -54,9 +52,14 @@ # and normalize the value by the nor-molar ratio (aout$values[[i]] + aout$species$logact[i]) / m.balance[i] }) - ## compute the equilibrium activities of species - if(all(n.balance==1)) loga.equil <- equil.boltzmann(Astar, n.balance, loga.balance) - else loga.equil <- equil.reaction(Astar, n.balance, loga.balance) + ## 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] + } + msgout(paste("equilibrate: using", method[1], "method\n")) + 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) ## if we normalized the formulas, get back to activities to species if(normalize & !as.residue) { loga.equil <- lapply(1:nspecies, function(i) { @@ -83,7 +86,7 @@ # 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) @@ -150,6 +153,11 @@ 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) @@ -161,7 +169,6 @@ # if one of them is infinite we might have a chance if(is.infinite(logadiff.min)) { # decrease the Abar range by increasing the minimum - # the 0.99 is necessary at least for the residue=FALSE plot in protactiv.Rnw; 0.9 isn't enough! 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") @@ -246,21 +253,16 @@ if(is.numeric(balance[1])) { # a numeric vector n.balance <- rep(balance, length.out=length(aout$values)) - if(all(n.balance==1)) msgout("balance: coefficients are unity\n") - # use 'balance' below as a name - if(all(n.balance==1)) balance.description <- "moles of species" - else balance <- "moles of user-specified coefficients" + msgout("balance: from numeric argument value\n") } 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) - balance.description <- "protein length" - msgout(paste("balance: coefficients are", balance.description, "\n")) + msgout("balance: from protein length\n") } else if(identical(balance, "volume")) { n.balance <- info(aout$species$ispecies, check.it=FALSE)$V - balance.description <- "volume" - msgout(paste("balance: coefficients are", balance.description, "\n")) + msgout("balance: from volume") } else { # is the balance the name of a basis species? if(length(ibalance)==0) { @@ -269,13 +271,12 @@ } # the name of the basis species (need this if we got ibalance which which.balance, above) balance <- colnames(aout$species)[ibalance[1]] - balance.description <- paste("moles of", balance) - msgout(paste("balance: coefficients are", balance.description, "in formation reactions\n")) + msgout(paste("balance: from moles of", balance, "in formation reactions\n")) # the balance vector 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=n.balance, description=balance.description)) + return(n.balance) } Modified: pkg/CHNOSZ/inst/NEWS =================================================================== --- pkg/CHNOSZ/inst/NEWS 2015-11-08 10:54:55 UTC (rev 97) +++ pkg/CHNOSZ/inst/NEWS 2015-11-09 04:45:00 UTC (rev 98) @@ -1,4 +1,4 @@ -CHANGES IN CHNOSZ 1.0.6-3 (2015-11-08) +CHANGES IN CHNOSZ 1.0.6-4 (2015-11-09) -------------------------------------- - Add functions usrfig() (get figure limits in user coordinates) and @@ -31,6 +31,8 @@ nonideal() to set activity coefficients of proton and electron to zero. +- Add 'method' argument to equilibrate(). + CHANGES IN CHNOSZ 1.0.6 (2015-10-19) ------------------------------------ Modified: pkg/CHNOSZ/man/equilibrate.Rd =================================================================== --- pkg/CHNOSZ/man/equilibrate.Rd 2015-11-08 10:54:55 UTC (rev 97) +++ pkg/CHNOSZ/man/equilibrate.Rd 2015-11-09 04:45:00 UTC (rev 98) @@ -10,7 +10,8 @@ \usage{ equilibrate(aout, balance=NULL, loga.balance=NULL, - ispecies=1:length(aout$values), normalize=FALSE, as.residue=FALSE) + ispecies=1:length(aout$values), normalize=FALSE, as.residue=FALSE, + method=c("boltzmann", "reaction")) balance(aout, balance=NULL) equil.boltzmann(Astar, n.balance, loga.balance) equil.reaction(Astar, n.balance, loga.balance) @@ -25,6 +26,7 @@ \item{Astar}{numeric, affinities of formation reactions excluding species contribution} \item{n.balance}{numeric, number of moles of conserved component in the formation reactions of the species of interest} \item{loga.balance}{numeric, logarithm of total activity of balanced quantity} + \item{method}{character, equilibration method to use} } \details{ @@ -58,7 +60,9 @@ \code{ispecies} can be supplied to identify a subset of the species to include in the calculation. -\code{equil.boltzmann} is used to calculate the equilibrium activities if \code{balance} is \samp{1} (including the normalized result when \code{normalize} is TRUE), otherwise \code{equil.reaction} is called. +\code{equil.boltzmann} is used to calculate the equilibrium activities if \code{balance} is \samp{1} (or when \code{normalize} or \code{as.residue} is TRUE), otherwise \code{equil.reaction} is called. +The default behavior can be overriden by specifying either \samp{boltzmann} or \samp{reaction} in \code{method}. +Using \code{equil.reaction} may be needed for systems with huge (negative or positive) affinities, where \code{equil.boltzmann} produces a NaN result. } @@ -76,6 +80,7 @@ In \code{equil.boltzmann} (algorithm available beginning with CHNOSZ-0.8), the chemical activities of species are calculated using the Boltzmann distribution. This calculation is faster than the algorithm of \code{equil.reaction}, but is limited to systems where the transformations are all balanced on one mole of species. +If \code{equil.boltzmann} is called with \code{balance} other than \samp{1}, it stops with an error. } Modified: pkg/CHNOSZ/tests/testthat/test-diagram.R =================================================================== --- pkg/CHNOSZ/tests/testthat/test-diagram.R 2015-11-08 10:54:55 UTC (rev 97) +++ pkg/CHNOSZ/tests/testthat/test-diagram.R 2015-11-09 04:45:00 UTC (rev 98) @@ -5,7 +5,7 @@ basis("CHNOS") species(c("glycine", "alanine")) a <- affinity() - expect_message(diagram(a, plot.it=FALSE), "coefficients are moles of CO2 in formation reactions") + expect_message(diagram(a, plot.it=FALSE), "balance: from moles of CO2 in formation reactions") e <- equilibrate(a) expect_error(diagram(e, "Z"), "Z is not a basis species") }) @@ -22,7 +22,7 @@ # we can't calculate the equilibrium activity of a basis species if it's externally buffered expect_error(diagram(a, "O2"), "is not numeric - was a buffer selected\\?") # this one works - a barplot of A/2.303RT - expect_message(diagram(a, plot.it=FALSE), "coefficients are moles of CO2 in formation reactions") + expect_message(diagram(a, plot.it=FALSE), "balance: from moles of CO2 in formation reactions") # if we're plotting A/2.303RT the values can be divided by balancing coefficient or not d.1 <- diagram(a, balance=1, plot.it=FALSE) d.CO2 <- diagram(a, plot.it=FALSE) Modified: pkg/CHNOSZ/tests/testthat/test-equilibrate.R =================================================================== --- pkg/CHNOSZ/tests/testthat/test-equilibrate.R 2015-11-08 10:54:55 UTC (rev 97) +++ pkg/CHNOSZ/tests/testthat/test-equilibrate.R 2015-11-09 04:45:00 UTC (rev 98) @@ -19,18 +19,18 @@ test_that("equilibrate() gives expected messages and errors for balance calculation", { # the following error is triggered by equil.react, not equil.boltzmann expect_error(equilibrate(aone), "at least two species needed") - expect_message(equilibrate(aacid), "coefficients are moles of CO2") - expect_message(equilibrate(aacid), "balancing coefficients are 2 1 1 2 ") - expect_message(equilibrate(aacid), "logarithm of total moles of CO2 is -2.221848") - expect_message(equilibrate(aacid, loga.balance=-3), "logarithm of total moles of CO2 \\(from loga.balance\\) is -3") + expect_message(equilibrate(aacid), "balance: from moles of CO2") + expect_message(equilibrate(aacid), "n.balance is 2 1 1 2 ") + expect_message(equilibrate(aacid), "loga.balance is -2.221848") + expect_message(equilibrate(aacid, loga.balance=-3), "loga.balance is -3") expect_error(equilibrate(aacid, balance="length"), "some species are not proteins") - expect_message(equilibrate(aacidS), "coefficients are unity") - expect_message(equilibrate(aacidS), "balancing coefficients are 1 1 1 1 1") - expect_message(equilibrate(aacidS), "logarithm of total moles of species is -2.301029") + expect_message(equilibrate(aacidS), "balance: from numeric argument value") + expect_message(equilibrate(aacidS), "n.balance is 1 1 1 1 1") + expect_message(equilibrate(aacidS), "loga.balance is -2.301029") expect_error(equilibrate(aacidS, balance="CO2"), "some species have no CO2 in the formation reaction") - expect_message(equilibrate(aprot), "coefficients are protein length") - expect_message(equilibrate(aprot), "balancing coefficients are 129 153 124 104") - expect_message(equilibrate(aprot), "logarithm of total protein length is -0.292429") + expect_message(equilibrate(aprot), "balance: from protein length") + expect_message(equilibrate(aprot), "n.balance is 129 153 124 104") + expect_message(equilibrate(aprot), "loga.balance is -0.292429") expect_message(equilibrate(aprot, normalize=TRUE), "using 'normalize' for molar formulas") }) @@ -78,8 +78,51 @@ expect_true(all(abs(loga.equil-loga.ref) < 0.36)) }) -#} +test_that("equilibrate() can be used for huge values of Astar", { + ## working out some bugs and testing new 'method' argument 20151109 + ## first, demonstrate that equil.reaction works where equil.boltzmann doesn't + # minimal example: Astar=c(0, 0), n.balance=c(1, 1), loga.balance=0 + # results in equal activities of two species + eb0 <- equil.boltzmann(c(0, 0), c(1, 1), 0) + expect_equal(unlist(eb0), rep(log10(0.5), 2)) + # Astar=c(-330, -330) + # result is NaN (we probably get an Inf-Inf somewhere) + eb330 <- equil.boltzmann(c(-330, -330), c(1, 1), 0) + expect_equal(unlist(eb330), rep(NaN, 2)) + # (fixed bug: while loop in equil.reaction tested a NaN value) + # (dlogadiff.dAbar <- 0 / 0) + er330 <- equil.reaction(c(-330, -330), c(1, 1), 0) + expect_equal(er330, eb0) + + ## second, set up extreme test case and show boltzmann method produces NaN (is.na) + basis("CHNOS") + basis("O2", 200) + species(c("glycine", "alanine", "proline")) + a <- affinity() + expect_message(eb <- equilibrate(a, balance=1), "using boltzmann method") + expect_true(all(is.na(unlist(eb$loga.equil)))) + + ## third, check we can use method="reaction" + expect_message(er1 <- equilibrate(a, balance=1, method="reaction"), "using reaction method") + expect_false(any(is.na(unlist(er1$loga.equil)))) + # is it an equilibrium solution? + species(1:3, unlist(er1$loga.equil)) + a1 <- affinity() + expect_equal(diff(range(unlist(a1$values))), 0) + + ## third, check that we can use arbitrary numeric balance specification + # (balance <> 1 here means equilibrate will call equil.reaction) + expect_message(er11 <- equilibrate(a, balance=1.000001), "using reaction method") + species(1:3, unlist(er11$loga.equil)) + a11 <- affinity() + expect_equal(unlist(a1$values), unlist(a11$values)) + + ## fourth, check that equil.boltzmann won't run for balance <> 1 + expect_error(equilibrate(a, balance=1.000001, method="boltzmann"), "won't run equil.boltzmann") +}) + + # references # Seewald, J. S. (2001) Modified: pkg/CHNOSZ/vignettes/equilibrium.Rnw =================================================================== --- pkg/CHNOSZ/vignettes/equilibrium.Rnw 2015-11-08 10:54:55 UTC (rev 97) +++ pkg/CHNOSZ/vignettes/equilibrium.Rnw 2015-11-09 04:45:00 UTC (rev 98) @@ -610,7 +610,7 @@ if(loga==-1) d <- diagram(a) else d <- diagram(a, add=TRUE, names=NULL) iCu <- which(d$predominant == 1, arr.ind=TRUE) - text(a$vals[[1]][max(iCu[, 1])] - 0.2, a$vals[[2]][min(iCu[, 2])] + 0.2, loga) + text(a$vals[[1]][max(iCu[, 1])] - 0.03, a$vals[[2]][min(iCu[, 2])] + 0.2, adj=1, loga) } water.lines() @@ -679,7 +679,7 @@ equilibrate the basis species rather than compose the diagram using the predominant basis species). \begin{itemize} -\item See the examples in \texttt{?mosaic} and \texttt{demo(``mosaic'')} +\item See the examples in \texttt{?mosaic} and \texttt{demo(\textquotedbl{}mosaic\textquotedbl{})} for calculations of mineral stabilities in the Fe-S-O-$\mathrm{H_{2}O}$ system (after \citealp{GC65}). \item A calculation of copper solubility limits and speciation with aqueous Modified: pkg/CHNOSZ/vignettes/equilibrium.lyx =================================================================== --- pkg/CHNOSZ/vignettes/equilibrium.lyx 2015-11-08 10:54:55 UTC (rev 97) +++ pkg/CHNOSZ/vignettes/equilibrium.lyx 2015-11-09 04:45:00 UTC (rev 98) @@ -2638,8 +2638,8 @@ \begin_layout Plain Layout - text(a$vals[[1]][max(iCu[, 1])] - 0.2, a$vals[[2]][min(iCu[, 2])] + 0.2, - loga) + text(a$vals[[1]][max(iCu[, 1])] - 0.03, a$vals[[2]][min(iCu[, 2])] + 0.2, + adj=1, loga) \end_layout \begin_layout Plain Layout @@ -2919,15 +2919,7 @@ \family default and \family typewriter -demo( -\begin_inset Quotes eld -\end_inset - -mosaic -\begin_inset Quotes erd -\end_inset - -) +demo("mosaic") \family default for calculations of mineral stabilities in the Fe-S-O- \begin_inset Formula $\mathrm{H_{2}O}$ From noreply at r-forge.r-project.org Mon Nov 9 05:45:35 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Mon, 9 Nov 2015 05:45:35 +0100 (CET) Subject: [CHNOSZ-commits] r99 - pkg/CHNOSZ/inst Message-ID: <20151109044535.260E71875E9@r-forge.r-project.org> Author: jedick Date: 2015-11-09 05:45:34 +0100 (Mon, 09 Nov 2015) New Revision: 99 Removed: pkg/CHNOSZ/inst/tests/ Log: remove inst/tests From noreply at r-forge.r-project.org Tue Nov 10 19:16:47 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Tue, 10 Nov 2015 19:16:47 +0100 (CET) Subject: [CHNOSZ-commits] r100 - in pkg/CHNOSZ: . R inst vignettes Message-ID: <20151110181647.2FA43187C16@r-forge.r-project.org> Author: jedick Date: 2015-11-10 19:16:46 +0100 (Tue, 10 Nov 2015) New Revision: 100 Modified: pkg/CHNOSZ/DESCRIPTION pkg/CHNOSZ/R/EOSregress.R pkg/CHNOSZ/inst/NEWS pkg/CHNOSZ/vignettes/equilibrium.Rnw pkg/CHNOSZ/vignettes/equilibrium.lyx pkg/CHNOSZ/vignettes/vig.bib Log: minor edits of equilibrium.Rnw Modified: pkg/CHNOSZ/DESCRIPTION =================================================================== --- pkg/CHNOSZ/DESCRIPTION 2015-11-09 04:45:34 UTC (rev 99) +++ pkg/CHNOSZ/DESCRIPTION 2015-11-10 18:16:46 UTC (rev 100) @@ -1,6 +1,6 @@ -Date: 2015-11-09 +Date: 2015-11-10 Package: CHNOSZ -Version: 1.0.6-4 +Version: 1.0.6-5 Title: Chemical Thermodynamics and Activity Diagrams Author: Jeffrey Dick Maintainer: Jeffrey Dick Modified: pkg/CHNOSZ/R/EOSregress.R =================================================================== --- pkg/CHNOSZ/R/EOSregress.R 2015-11-09 04:45:34 UTC (rev 99) +++ pkg/CHNOSZ/R/EOSregress.R 2015-11-10 18:16:46 UTC (rev 100) @@ -177,10 +177,12 @@ names(out) <- c("(Intercept)", "invTTheta2", "TXBorn") } else if(property=="V") { iis <- iis[,c("a1", "a2", "a3", "a4", "omega")] - sigma <- ( iis$a1 + iis$a2 / (2600 + 1) ) * 41.84 - xi <- ( iis$a3 + iis$a4 / (2600 + 1) ) * 41.84 + # calculate sigma and xi and convert to volumetric units: 1 cal = 41.84 cm^3 bar + sigma <- convert( iis$a1 + iis$a2 / (2600 + 1), "cm3bar" ) + xi <- convert( iis$a3 + iis$a4 / (2600 + 1), "cm3bar" ) + omega <- convert( iis$omega, "cm3bar" ) # watch for the negative sign on omega here! - out <- data.frame(sigma, xi, -iis$omega) + out <- data.frame(sigma, xi, -omega) names(out) <- c("(Intercept)", "invTTheta", "QBorn") } return(out) Modified: pkg/CHNOSZ/inst/NEWS =================================================================== --- pkg/CHNOSZ/inst/NEWS 2015-11-09 04:45:34 UTC (rev 99) +++ pkg/CHNOSZ/inst/NEWS 2015-11-10 18:16:46 UTC (rev 100) @@ -1,4 +1,4 @@ -CHANGES IN CHNOSZ 1.0.6-4 (2015-11-09) +CHANGES IN CHNOSZ 1.0.6-5 (2015-11-10) -------------------------------------- - Add functions usrfig() (get figure limits in user coordinates) and Modified: pkg/CHNOSZ/vignettes/equilibrium.Rnw =================================================================== --- pkg/CHNOSZ/vignettes/equilibrium.Rnw 2015-11-09 04:45:34 UTC (rev 99) +++ pkg/CHNOSZ/vignettes/equilibrium.Rnw 2015-11-10 18:16:46 UTC (rev 100) @@ -64,12 +64,14 @@ \item [{Basis~species}] Species in terms of which you want to write all formation reactions of species of interest. \item [{Formation~reactions}] Stoichiometric chemical reactions showing -the mass requirements for formation of 1 mole of each species of interest -from the basis species. -\item [{Chemical~affinity}] Change in Gibbs energy per increment of reaction -progress; the negative of the overall Gibbs energy of reaction; $\boldsymbol{A}=2.303RT\log(K/Q)$, -where $K$ is the equilibrium constant and $Q$ is the reaction activity -quotient ($\log$ here is used for base-10 logarithms). +the mass balance requirements for formation of 1 mole of each species +of interest from the basis species. +\item [{Chemical~affinity}] Negative of the differential of Gibbs energy +of a system with respect to reaction progress. For a given reaction, +chemical affinity is the negative of Gibbs energy of reaction; $\boldsymbol{A}=2.303RT\log(K/Q)$, +where $K$ is the equilibrium constant and $Q$ is the activity quotient +of species in the reaction ($\log$ in this text denotes base-10 logarithms, +i.e. \texttt{log10} in R). \item [{(1)~Reference~activity}] User-defined (usually equal) activities of species of interest. \item [{(1)~Reference~affinity}] ($\boldsymbol{A}_{{\it ref}}$) Chemical @@ -104,10 +106,10 @@ \item [{Reaction~matrix}] Algorithm used for the equilibration method when the balance coefficients are not all 1. \item [{Normalization}] Algorithm used for large molecules such as proteins; -chemical formulas and affinities are scaled to an equal size (e.g. -a single residue; ``residue equivalent'' in Appendix), activities -are calculated using balance = 1, and formulas and activities are -rescaled to the original size of the molecule. +chemical formulas and affinities are scaled to a similar molecular +size (e.g. a single residue; ``residue equivalent'' in Appendix), +activities are calculated using balance = 1, and formulas and activities +are rescaled to the original size of the molecule. \item [{Mosaic}] Calculations of chemical affinities for making diagrams where the speciation of basis species depends on the variables. \end{description} @@ -172,7 +174,7 @@ \item Typical use: simple aqueous species activity comparisons \item Function sequence:\\ \texttt{a <- affinity(...)}\\ -\texttt{e <- equilibrate(e, balance = 1)}\\ +\texttt{e <- equilibrate(a, balance = 1)}\\ \texttt{diagram(e)} \item Algorithm: Boltzmann distribution \end{enumerate} @@ -575,11 +577,11 @@ disappears while that of the smaller protein from METJA grows. Because of the drastic activity changes at the stability transitions (see Figure \textcolor{blue}{B} above), a large change in equal activities -(to an infinitesimally small activity = $10^{-111}$) is used here -to demonstrate this effect, and even then the visual impact on the -predominance diagram is subtle. Therefore, naturally occurring relative -abundances of proteins are better modeled using the \texttt{normalize} -or \texttt{as.residue} approaches. +(to a minuscule activity = $10^{-111}$) is used here to demonstrate +this effect, and even then the visual impact on the predominance diagram +is subtle. Therefore, naturally occurring relative abundances of proteins +are better modeled using the \texttt{normalize} or \texttt{as.residue} +approaches. \clearpage @@ -588,7 +590,7 @@ Many of the help-page examples and demos in CHNOSZ use these methods to reproduce (or closely emulate) published figures. Below is not -a comprehensive list, but just some highlights: +a comprehensive list, but just some highlights. \subsection{Maximum affinity method} @@ -1048,9 +1050,9 @@ \subsection{Visualizing the effects of normalization} -A comparison of the outcomes of equilibrium calculations that do and -do not use the normalized formulas for proteins was given in a publication -\citet{Dic08}. A diagram like Figure 5 in that paper is shown below. +A comparison of equilibrium calculations that do and do not use normalized +formulas for proteins was presented by \citet{Dic08}. A diagram like +Figure 5 in that paper is shown below. <>= organisms <- c("METSC", "METJA", "METFE", "HALJP", "METVO", "METBU", "ACEKI", "GEOSE", "BACLI", "AERSA") @@ -1071,8 +1073,8 @@ Although it is well below the stability limit of $\mathrm{H_{2}O}$ (vertical dashed line), there is an interesting convergence of the -activities of some proteins at low $\log f_{\mathrm{O_{2}}}$; this -is likely a consequence of compositional similarities. +activities of some proteins at low $\log f_{\mathrm{O_{2}}}$, due +most likely to compositional similarity of the amino acid sequences. The reaction-matrix approach can also be applied to systems having conservation coefficients that differ from unity, such as many mineral Modified: pkg/CHNOSZ/vignettes/equilibrium.lyx =================================================================== --- pkg/CHNOSZ/vignettes/equilibrium.lyx 2015-11-09 04:45:34 UTC (rev 99) +++ pkg/CHNOSZ/vignettes/equilibrium.lyx 2015-11-10 18:16:46 UTC (rev 100) @@ -200,8 +200,8 @@ \begin_inset space ~ \end_inset -reactions Stoichiometric chemical reactions showing the mass requirements - for formation of 1 mole of each species of interest from the basis species. +reactions Stoichiometric chemical reactions showing the mass balance requirement +s for formation of 1 mole of each species of interest from the basis species. \end_layout \begin_layout Description @@ -209,8 +209,10 @@ \begin_inset space ~ \end_inset -affinity Change in Gibbs energy per increment of reaction progress; the - negative of the overall Gibbs energy of reaction; +affinity Negative of the differential of Gibbs energy of a system with respect + to reaction progress. + For a given reaction, chemical affinity is the negative of Gibbs energy + of reaction; \begin_inset Formula $\boldsymbol{A}=2.303RT\log(K/Q)$ \end_inset @@ -222,11 +224,16 @@ \begin_inset Formula $Q$ \end_inset - is the reaction activity quotient ( + is the activity quotient of species in the reaction ( \begin_inset Formula $\log$ \end_inset - here is used for base-10 logarithms). + in this text denotes base-10 logarithms, i.e. + +\family typewriter +log10 +\family default + in R). \end_layout \begin_layout Description @@ -403,7 +410,7 @@ \begin_layout Description Normalization Algorithm used for large molecules such as proteins; chemical - formulas and affinities are scaled to an equal size (e.g. + formulas and affinities are scaled to a similar molecular size (e.g. a single residue; \begin_inset Quotes eld \end_inset @@ -608,7 +615,7 @@ \family typewriter -e <- equilibrate(e, balance = 1) +e <- equilibrate(a, balance = 1) \family default \begin_inset Newline newline @@ -2470,8 +2477,7 @@ \color blue B \color inherit - above), a large change in equal activities (to an infinitesimally small - activity = + above), a large change in equal activities (to a minuscule activity = \begin_inset Formula $10^{-111}$ \end_inset @@ -2512,7 +2518,7 @@ \begin_layout Standard Many of the help-page examples and demos in CHNOSZ use these methods to reproduce (or closely emulate) published figures. - Below is not a comprehensive list, but just some highlights: + Below is not a comprehensive list, but just some highlights. \end_layout \begin_layout Subsection @@ -4261,9 +4267,8 @@ \end_layout \begin_layout Standard -A comparison of the outcomes of equilibrium calculations that do and do - not use the normalized formulas for proteins was given in a publication - +A comparison of equilibrium calculations that do and do not use normalized + formulas for proteins was presented by \begin_inset CommandInset citation LatexCommand cite key "Dic08" @@ -4374,7 +4379,7 @@ \begin_inset Formula $\log f_{\mathrm{O_{2}}}$ \end_inset -; this is likely a consequence of compositional similarities. +, due most likely to compositional similarity of the amino acid sequences. \end_layout \begin_layout Standard Modified: pkg/CHNOSZ/vignettes/vig.bib =================================================================== --- pkg/CHNOSZ/vignettes/vig.bib 2015-11-09 04:45:34 UTC (rev 99) +++ pkg/CHNOSZ/vignettes/vig.bib 2015-11-10 18:16:46 UTC (rev 100) @@ -194,7 +194,7 @@ } @Article{DLH06, - Title = {{T}emperature, pressure, and electrochemical constraints on protein speciation: group additivity calculation of the standard molal thermodynamic properties of ionized unfolded proteins}, + Title = {{T}emperature, pressure, and electrochemical constraints on protein speciation: {G}roup additivity calculation of the standard molal thermodynamic properties of ionized unfolded proteins}, Author = {Dick, Jeffrey M. and LaRowe, Douglas E. and Helgeson, Harold C.}, Journal = {Biogeosciences}, Year = {2006}, @@ -315,12 +315,13 @@ @Incollection{Hel70c, Title = {{A} chemical and thermodynamic model of ore deposition in hydrothermal systems}, Author = {Helgeson, Harold C.}, - Booktitle = {Mineralogical Society of America, Fiftieth Anniversary Symposium}, + Booktitle = {Fiftieth Anniversary Symposia}, Publisher = {Mineralogical Society of America}, Year = {1970}, - Editor = {Morgan, B. A.}, + Editor = {Morgan, Benjamin A.}, Pages = {155--186}, - Volume = {Special Paper \#3}, + Series = {Mineralogical Society of America, Special Paper}, + Volume = {3}, Url = {http://www.worldcat.org/oclc/583263} } @@ -577,7 +578,6 @@ Number = {21}, Pages = {3965--3992}, Volume = {65}, - __markedentry = {}, Abstract = {Aluminum speciation in crustal fluids is assessed by means of standard thermodynamic properties at 25 degreesC, 1 bar, and revised Helgeson-Kirkham-Flowers (HKF) (Tanger J. C. IV and Helgeson H. C., "Calculation of the thermodynamic and transport properties of aqueous species at high pressures and temperatures: Revised equations of state for the standard partial molal properties of ions and electrolytes," Ain. J. Sci. 288, 19-98, 1988) equations of state parameters for aqueous species in the system Al-O-H-Na-Si-Cl-F-SO4 derived from recent experimental data with the help of isocoulombic reactions and correlations among parameters in the HKF model. In acidic to neutral hydrothermal. solutions and for fluorine concentrations in excess of 1 ppm, the fluoride complexes AlFn3-n dominate Al speciation at temperature (T) < 100 degreesC, whereas the hydroxide fluoride species Al(OH)(2)F-(aq)(0) and AlOHF2(aq)0 are dominant up to similar to 400 degreesC. In high-temperature (T > 300 degreesC) hydrothermal and metamorphic fluids, aluminum mobility is considerably 0 enhanced by formation of NaAl(OH)(3)F-(aq)(0) and NaAl(OH)(2)F-2((aq))0 ion paired mixed species. NaAl(OH)(2)F-2((aq))0 controls Al transport in granite-derived fluids and during greisenization. At alkaline PH, Al(OH)(4)(-), Al(OH)(3)H3SiO4-, and the NaAl(OH)(4)(0)((aq)) ion-pair are the dominant Al species. Thermodynamic calculations show that as a result of strong interactions of Al(aq) with NaOH, NaF, HF, and SiO2(aq) present in crustal fluids, the concentrations of aluminum in equilibrium with Al-bearing minerals can be several orders of magnitude higher than those calculated assuming that only Al hydroxyde complexes are formed. Interactions with these components are likely to be responsible for aluminum mobility during hydrothermal and metamorphic reactions. Copyright (C) 2001 Elsevier Science Ltd.}, Doi = {10.1016/S0016-7037(01)00705-0}, } From noreply at r-forge.r-project.org Thu Nov 19 14:15:23 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 19 Nov 2015 14:15:23 +0100 (CET) Subject: [CHNOSZ-commits] r101 - in pkg/CHNOSZ: . R inst man tests/testthat vignettes Message-ID: <20151119131523.9DDAB187BA2@r-forge.r-project.org> Author: jedick Date: 2015-11-19 14:15:23 +0100 (Thu, 19 Nov 2015) New Revision: 101 Modified: pkg/CHNOSZ/DESCRIPTION pkg/CHNOSZ/R/util.affinity.R pkg/CHNOSZ/inst/NEWS pkg/CHNOSZ/man/util.water.Rd pkg/CHNOSZ/tests/testthat/test-affinity.R pkg/CHNOSZ/tests/testthat/test-diagram.R pkg/CHNOSZ/tests/testthat/test-util.affinity.R pkg/CHNOSZ/vignettes/equilibrium.Rnw pkg/CHNOSZ/vignettes/equilibrium.lyx Log: fixes for changed aperm() behavior in R-devel Modified: pkg/CHNOSZ/DESCRIPTION =================================================================== --- pkg/CHNOSZ/DESCRIPTION 2015-11-10 18:16:46 UTC (rev 100) +++ pkg/CHNOSZ/DESCRIPTION 2015-11-19 13:15:23 UTC (rev 101) @@ -1,6 +1,6 @@ -Date: 2015-11-10 +Date: 2015-11-19 Package: CHNOSZ -Version: 1.0.6-5 +Version: 1.0.6-6 Title: Chemical Thermodynamics and Activity Diagrams Author: Jeffrey Dick Maintainer: Jeffrey Dick Modified: pkg/CHNOSZ/R/util.affinity.R =================================================================== --- pkg/CHNOSZ/R/util.affinity.R 2015-11-10 18:16:46 UTC (rev 100) +++ pkg/CHNOSZ/R/util.affinity.R 2015-11-19 13:15:23 UTC (rev 101) @@ -359,7 +359,12 @@ # 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) } Modified: pkg/CHNOSZ/inst/NEWS =================================================================== --- pkg/CHNOSZ/inst/NEWS 2015-11-10 18:16:46 UTC (rev 100) +++ pkg/CHNOSZ/inst/NEWS 2015-11-19 13:15:23 UTC (rev 101) @@ -1,4 +1,4 @@ -CHANGES IN CHNOSZ 1.0.6-5 (2015-11-10) +CHANGES IN CHNOSZ 1.0.6-6 (2015-11-19) -------------------------------------- - Add functions usrfig() (get figure limits in user coordinates) and @@ -8,7 +8,7 @@ mosaic()). - Using new supporting function ibasis(), swap.basis() and mosaic() - now allow basis species to be specified by name, not just formula. + now allow basis species to be specified by name, not only formula. - diagram() now has '...' argument to pass additional options to plot() (useful with diagram(tplot=FALSE, ...)). @@ -31,8 +31,14 @@ nonideal() to set activity coefficients of proton and electron to zero. -- Add 'method' argument to equilibrate(). +- Add 'method' argument to equilibrate() (can be 'reaction' or + 'boltzmann'). +- For compatibility with a change in R-devel ("aperm(a, *) now preserves + names(dim(a))"), modify slice.affinity() to preserve names of + dimensions, and use check.attributes=FALSE or check.names=FALSE in + some tests. + CHANGES IN CHNOSZ 1.0.6 (2015-10-19) ------------------------------------ Modified: pkg/CHNOSZ/man/util.water.Rd =================================================================== --- pkg/CHNOSZ/man/util.water.Rd 2015-11-10 18:16:46 UTC (rev 100) +++ pkg/CHNOSZ/man/util.water.Rd 2015-11-19 13:15:23 UTC (rev 101) @@ -4,7 +4,7 @@ \alias{WP02.auxiliary} \alias{rho.IAPWS95} \alias{water.AW90} -\title{Functions to assist in calculating properties of water and steam} +\title{Functions for Properties of Water and Steam} \description{ Utility functions for properties of water and steam. } Modified: pkg/CHNOSZ/tests/testthat/test-affinity.R =================================================================== --- pkg/CHNOSZ/tests/testthat/test-affinity.R 2015-11-10 18:16:46 UTC (rev 100) +++ pkg/CHNOSZ/tests/testthat/test-affinity.R 2015-11-19 13:15:23 UTC (rev 101) @@ -31,7 +31,8 @@ a.Eh <- affinity(Eh=Eh, T=100) a.pe <- affinity(pe=pe, T=100) # they should give the same result - expect_equal(a.Eh$values, a.pe$values) + # ... except for names(dim(.)), so set check.attributes=FALSE + expect_equal(a.Eh$values, a.pe$values, check.attributes=FALSE) # the variables should have the right names expect_equal(c(a.Eh$vars, a.pe$vars), c("Eh", "pe")) # now for an Eh-pH example @@ -72,7 +73,7 @@ # log_a(O2) = -20, -15, -10, -5, 0 # first test: the dimensions are correct a.logK <- affinity(T=c(0, 125, 6), H2=c(-20, 0, 5), O2=c(-20, 0, 5), property="logK") - expect_equal(dim(a.logK$values[[1]]), c(6, 5, 5)) + expect_equal(dim(a.logK$values[[1]]), c(6, 5, 5), check.names=FALSE) # second and third tests: the logK values used by affinity() are correct expect_equal(a.logK$values[[1]][2, 3, 3], logK.25) expect_equal(a.logK$values[[1]][5, 4, 3], logK.100) Modified: pkg/CHNOSZ/tests/testthat/test-diagram.R =================================================================== --- pkg/CHNOSZ/tests/testthat/test-diagram.R 2015-11-10 18:16:46 UTC (rev 100) +++ pkg/CHNOSZ/tests/testthat/test-diagram.R 2015-11-19 13:15:23 UTC (rev 101) @@ -54,7 +54,7 @@ # ask for degrees of formation instead of logarithms of activities d <- diagram(e, alpha=TRUE, plot.it=FALSE) # we should find that the sum of alphas is one - expect_equal(Reduce("+", d$plotvals), array(rep(1, 128))) + expect_equal(Reduce("+", d$plotvals), array(rep(1, 128)), check.attributes=FALSE) }) test_that("'normalize' and 'as.residue' work as expected", { Modified: pkg/CHNOSZ/tests/testthat/test-util.affinity.R =================================================================== --- pkg/CHNOSZ/tests/testthat/test-util.affinity.R 2015-11-10 18:16:46 UTC (rev 100) +++ pkg/CHNOSZ/tests/testthat/test-util.affinity.R 2015-11-19 13:15:23 UTC (rev 101) @@ -8,7 +8,7 @@ # for two proteins, a list of length 2 expect_equal(length(A), 2) # for 3 variables with the values given to energy.args() - expect_equal(dim(A[[1]]), c(3, 2, 4)) + expect_equal(dim(A[[1]]), c(3, 2, 4), check.names=FALSE) }) test_that("A.ionization() handles arguments generated by energy.args()", { Modified: pkg/CHNOSZ/vignettes/equilibrium.Rnw =================================================================== --- pkg/CHNOSZ/vignettes/equilibrium.Rnw 2015-11-10 18:16:46 UTC (rev 100) +++ pkg/CHNOSZ/vignettes/equilibrium.Rnw 2015-11-19 13:15:23 UTC (rev 101) @@ -600,8 +600,9 @@ \item The ``Fe-S-O'' example in \texttt{?diagram} shows stability fields for minerals (balance $\ne$ 1, after \citealp{Hel70c}). \item Next is an example of using \emph{unequal activities} of species (mineral -activity = 1; variable aqueous species activity) to plot aqueous species --- mineral stability boundaries (balance = 1, after Figure 14 of \citealp{Pou49}). +activity = 1; variable aqueous species activity indicated by the contours +(logarithm of activity)) to plot aqueous species -- mineral stability +boundaries (balance = 1, after Figure 14 of \citealp{Pou49}). \end{itemize} <>= basis(c("Cu+2", "H2O", "H+", "e-")) @@ -633,12 +634,12 @@ This total activity is the initial concentration of GSH that will be speciated among GSH and GSSG. If the aqueous species have equal concentrations (or activities), the fraction of GSH that has been -oxidized is actually 2/3, because the formation of GSSG takes two -moles of GSH. This is why the blue lines (fraction of starting GSH -that is oxidized) are higher than the black lines (aqueous species -distribution). Although the caption to Fig. 3 of \citet{SB01} reads -``percent GSH that has been oxidized to GSSG'', the lines in their -figure are closer to the black lines in the figure below. +oxidized is actually 2/3, because the formation of one mole of GSSG +consumes two moles of GSH. That is why the blue lines (fraction of +starting GSH that is oxidized) are higher than the black lines (aqueous +species distribution). Although the caption to Fig. 3 of \citet{SB01} +reads ``percent GSH that has been oxidized to GSSG'', the lines +in their figure are closer to the black lines in the figure below. \end{itemize} <>= basis(c("GSH", "NH3", "H2S", "H2O", "H+", "e-")) @@ -905,7 +906,7 @@ (e.g., for systems of proteins where the backbone group is conserved, $n_{\mathrm{ic},i}$ is the same as $n_{i}$ in Eq. \ref{eq:a_residue_i}). Calculate values for each of the $\boldsymbol{A}_{i}^{*}$. Metastable -equilibrium is implied by the identity of $\boldsymbol{A}$ in all +equilibrium is implied by the equality of $\boldsymbol{A}$ in all of the equations. \item Write a function for the total activity of the immobile component: $a_{\mathrm{ic}}^{'}=\sum n_{\mathrm{ic},i}a_{i}$. @@ -1080,7 +1081,7 @@ conservation coefficients that differ from unity, such as many mineral and inorganic systems, where the immobile component has different molar coefficients in the formulas. For example, consider a system -like one described by \citealp{See96}: +like one described by \citet{See96}: <>= basis("CHNOS+") Modified: pkg/CHNOSZ/vignettes/equilibrium.lyx =================================================================== --- pkg/CHNOSZ/vignettes/equilibrium.lyx 2015-11-10 18:16:46 UTC (rev 100) +++ pkg/CHNOSZ/vignettes/equilibrium.lyx 2015-11-19 13:15:23 UTC (rev 101) @@ -2580,9 +2580,9 @@ \emph on unequal activities \emph default - of species (mineral activity = 1; variable aqueous species activity) to - plot aqueous species -- mineral stability boundaries (balance = 1, after - Figure 14 of + of species (mineral activity = 1; variable aqueous species activity indicated + by the contours (logarithm of activity)) to plot aqueous species -- mineral + stability boundaries (balance = 1, after Figure 14 of \begin_inset CommandInset citation LatexCommand citealp key "Pou49" @@ -2704,8 +2704,8 @@ among GSH and GSSG. If the aqueous species have equal concentrations (or activities), the fraction of GSH that has been oxidized is actually 2/3, because the formation of - GSSG takes two moles of GSH. - This is why the blue lines (fraction of starting GSH that is oxidized) + one mole of GSSG consumes two moles of GSH. + That is why the blue lines (fraction of starting GSH that is oxidized) are higher than the black lines (aqueous species distribution). Although the caption to Fig. 3 of @@ -3740,7 +3740,7 @@ \end_inset . - Metastable equilibrium is implied by the identity of + Metastable equilibrium is implied by the equality of \begin_inset Formula $\boldsymbol{A}$ \end_inset @@ -4389,7 +4389,7 @@ in the formulas. For example, consider a system like one described by \begin_inset CommandInset citation -LatexCommand citealp +LatexCommand citet key "See96" \end_inset From noreply at r-forge.r-project.org Thu Nov 19 17:53:20 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Thu, 19 Nov 2015 17:53:20 +0100 (CET) Subject: [CHNOSZ-commits] r102 - in pkg/CHNOSZ: . demo inst vignettes Message-ID: <20151119165320.59329187B8D@r-forge.r-project.org> Author: jedick Date: 2015-11-19 17:53:20 +0100 (Thu, 19 Nov 2015) New Revision: 102 Modified: pkg/CHNOSZ/DESCRIPTION pkg/CHNOSZ/demo/yeastgfp.R pkg/CHNOSZ/inst/NEWS pkg/CHNOSZ/vignettes/equilibrium.Rnw pkg/CHNOSZ/vignettes/equilibrium.lyx Log: prepare version 1.0.7 for submission to CRAN Modified: pkg/CHNOSZ/DESCRIPTION =================================================================== --- pkg/CHNOSZ/DESCRIPTION 2015-11-19 13:15:23 UTC (rev 101) +++ pkg/CHNOSZ/DESCRIPTION 2015-11-19 16:53:20 UTC (rev 102) @@ -1,6 +1,6 @@ Date: 2015-11-19 Package: CHNOSZ -Version: 1.0.6-6 +Version: 1.0.7 Title: Chemical Thermodynamics and Activity Diagrams Author: Jeffrey Dick Maintainer: Jeffrey Dick Modified: pkg/CHNOSZ/demo/yeastgfp.R =================================================================== --- pkg/CHNOSZ/demo/yeastgfp.R 2015-11-19 13:15:23 UTC (rev 101) +++ pkg/CHNOSZ/demo/yeastgfp.R 2015-11-19 16:53:20 UTC (rev 102) @@ -39,7 +39,7 @@ for(i in 1:length(nloc)) { diagram(a, normalize=TRUE, names=names[inames], groups=as.list(inames), fill=fill[inames], cex.axis=0.75, cex.names=1) - label.plot(letters[i]) + label.plot(letters[i], xfrac=0.95, yfrac=0.9, paren=TRUE, italic=TRUE) title(main=paste(length(inames), "locations")) # take out the stable species inames <- inames[-(1:nloc[i])] Modified: pkg/CHNOSZ/inst/NEWS =================================================================== --- pkg/CHNOSZ/inst/NEWS 2015-11-19 13:15:23 UTC (rev 101) +++ pkg/CHNOSZ/inst/NEWS 2015-11-19 16:53:20 UTC (rev 102) @@ -1,4 +1,4 @@ -CHANGES IN CHNOSZ 1.0.6-6 (2015-11-19) +CHANGES IN CHNOSZ 1.0.7 (2015-11-19) -------------------------------------- - Add functions usrfig() (get figure limits in user coordinates) and Modified: pkg/CHNOSZ/vignettes/equilibrium.Rnw =================================================================== --- pkg/CHNOSZ/vignettes/equilibrium.Rnw 2015-11-19 13:15:23 UTC (rev 101) +++ pkg/CHNOSZ/vignettes/equilibrium.Rnw 2015-11-19 16:53:20 UTC (rev 102) @@ -236,7 +236,8 @@ species(aminoacids(""))[1:5, ] @ -Code for figures. Function names are keyed to the subfigures. +Code for making the diagrams. Function names refer to the subfigure +labels. <>= res <- 200 @@ -608,7 +609,7 @@ basis(c("Cu+2", "H2O", "H+", "e-")) species(c("Cu+2", "copper", "cuprite", "tenorite")) for(loga in c(-1, 0, -2, -3)) { - species(c("Cu+2"), loga) + species("Cu+2", loga) a <- affinity(pH=c(1.6, 7.6, 400), Eh=c(-0.2, 1, 400)) if(loga==-1) d <- diagram(a) else d <- diagram(a, add=TRUE, names=NULL) Modified: pkg/CHNOSZ/vignettes/equilibrium.lyx =================================================================== --- pkg/CHNOSZ/vignettes/equilibrium.lyx 2015-11-19 13:15:23 UTC (rev 101) +++ pkg/CHNOSZ/vignettes/equilibrium.lyx 2015-11-19 16:53:20 UTC (rev 102) @@ -842,8 +842,8 @@ \end_layout \begin_layout Standard -Code for figures. - Function names are keyed to the subfigures. +Code for making the diagrams. + Function names refer to the subfigure labels. \end_layout \begin_layout Standard @@ -2619,7 +2619,7 @@ \begin_layout Plain Layout - species(c("Cu+2"), loga) + species("Cu+2", loga) \end_layout \begin_layout Plain Layout From noreply at r-forge.r-project.org Wed Nov 25 05:43:03 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Wed, 25 Nov 2015 05:43:03 +0100 (CET) Subject: [CHNOSZ-commits] r103 - in pkg/CHNOSZ: . R data demo inst inst/extdata/thermo man Message-ID: <20151125044303.D4438186F1F@r-forge.r-project.org> Author: jedick Date: 2015-11-25 05:43:03 +0100 (Wed, 25 Nov 2015) New Revision: 103 Added: pkg/CHNOSZ/demo/dehydration.R Modified: pkg/CHNOSZ/DESCRIPTION pkg/CHNOSZ/R/examples.R pkg/CHNOSZ/data/OBIGT.csv pkg/CHNOSZ/data/refs.csv pkg/CHNOSZ/demo/00Index pkg/CHNOSZ/inst/NEWS pkg/CHNOSZ/inst/extdata/thermo/OBIGT-2.csv pkg/CHNOSZ/man/examples.Rd Log: add demo dehydration.R Modified: pkg/CHNOSZ/DESCRIPTION =================================================================== --- pkg/CHNOSZ/DESCRIPTION 2015-11-19 16:53:20 UTC (rev 102) +++ pkg/CHNOSZ/DESCRIPTION 2015-11-25 04:43:03 UTC (rev 103) @@ -1,6 +1,6 @@ -Date: 2015-11-19 +Date: 2015-11-25 Package: CHNOSZ -Version: 1.0.7 +Version: 1.0.7-1 Title: Chemical Thermodynamics and Activity Diagrams Author: Jeffrey Dick Maintainer: Jeffrey Dick Modified: pkg/CHNOSZ/R/examples.R =================================================================== --- pkg/CHNOSZ/R/examples.R 2015-11-19 16:53:20 UTC (rev 102) +++ pkg/CHNOSZ/R/examples.R 2015-11-25 04:43:03 UTC (rev 103) @@ -32,15 +32,18 @@ demos <- function(which=c("sources", "NaCl", "density", "nucleobase", "ORP", "revisit", "findit", "ionize", "buffer", "yeastgfp", "mosaic", - "copper", "solubility", "wjd"), do.png=FALSE) { + "copper", "solubility", "wjd", "dehydration"), to.file=FALSE) { # run one or more demos from CHNOSZ with ask=FALSE, and return the value of the last one for(i in 1:length(which)) { # say something so the user sees where we are msgout("------------\n") - msgout(paste("demos: running '", which[i], "'\n", sep="")) - if(do.png) png(paste(which[i],"%d.png",sep=""),width=500,height=500,pointsize=12) + if(which[i]=="dehydration" & !to.file) { + msgout("demos: skipping dehydration demo as to.file is FALSE\n") + next + } else msgout(paste("demos: running '", which[i], "'\n", sep="")) + if(to.file & !which[i]=="dehydration") png(paste(which[i],"%d.png",sep=""),width=500,height=500,pointsize=12) out <- demo(which[i], package="CHNOSZ", character.only=TRUE, echo=FALSE, ask=FALSE) - if(do.png) dev.off() + if(to.file & !which[i]=="dehydration") dev.off() } return(invisible(out)) } Modified: pkg/CHNOSZ/data/OBIGT.csv =================================================================== --- pkg/CHNOSZ/data/OBIGT.csv 2015-11-19 16:53:20 UTC (rev 102) +++ pkg/CHNOSZ/data/OBIGT.csv 2015-11-25 04:43:03 UTC (rev 103) @@ -2551,6 +2551,7 @@ "2-iodobenzoic acid",NA,C7H5IO2,cr,RG11,NA,07.Jan.12,-41260.994,-70602.294,52.187,40.17,110.2,-1.828,133.724,1.892,0,0,0,0,435.02 "3-iodobenzoic acid",NA,C7H5IO2,cr,RG11,NA,07.Jan.12,-46041.109,-75382.409,52.187,40.17,114.8,-1.828,133.724,1.892,0,0,0,0,460.3 "4-iodobenzoic acid",NA,C7H5IO2,cr,RG11,NA,07.Jan.12,-45921.606,-75262.906,52.187,40.17,115.5,-1.828,133.724,1.892,0,0,0,0,543.7 +gypsum,NA,CaSO4*2H2O,cr,RH95,Kel60,22.Nov.15,-429493,-483509,46.32,NA,74.69,21.84,76,0,0,0,0,0,400 pyridine,NA,C5H5N,liq,LH06b,NA,11.Jul.03,43370,23890,42.52,31.72,80.86,10.24,64.34,2.042,0,0,0,0,1000 piperidine,NA,C5H11N,liq,LH06b,NA,16.Jul.03,24270,-20860,50.18,42.95,99.4,2.42,98.88,9.831,0,0,0,0,1000 methane,NA,CH4,liq,HOK+98,NA,30.Aug.06,-8976,-18895,30.57,14.68,58.2,-1.55,47.6,1.81,0,0,0,0,111.64 Modified: pkg/CHNOSZ/data/refs.csv =================================================================== --- pkg/CHNOSZ/data/refs.csv 2015-11-19 16:53:20 UTC (rev 102) +++ pkg/CHNOSZ/data/refs.csv 2015-11-25 04:43:03 UTC (rev 103) @@ -28,8 +28,9 @@ FDK+04,"P. M. B. Fernandes, T. Domitrovic et al.",2004,"FEBS Lett. 556, 153-160",http://dx.doi.org/10.1016/S0014-5793(03)01396-6 FPC+04,"D. Fenclova, S. Perez-Casas, M. Costas, and V. Dohnal",2004,"J. Chem. Eng. Data 49, 1833-1838",http://dx.doi.org/10.1021/je049738c GLL+98,"C. Godon, G. Lagniel et al.",1998,"J. Biol. Chem. 273, 22480-22489",http://dx.doi.org/10.1074/jbc.273.35.22480 +GM09,"K.-D. Grevel and J. Majzlan",2009,"Geochim. Cosmochim. Acta 73, 6805 - 6815",http://dx.doi.org/10.1016/j.gca.2009.08.005 Gur96,"S. Gurrieri",1996,"personal communication", -HDN+78,"H. C. Helgeson, J. M. Delany et al.",1978,"Am. J. Sci. 278A, 1-229",http://www.worldcatlibraries.org/oclc/13594862 +HDN+78,"H. C. Helgeson, J. M. Delany et al.",1978,"Am. J. Sci. 278A, 1-229",http://www.worldcat.org/oclc/13594862 Hel85b,"H. C. Helgeson",1985,"Am. J. Sci. 285, 845-855",http://dx.doi.org/10.2475/ajs.285.9.845 HOK+98,"H. C. Helgeson, C. E. Owens et al.",1998,"Geochim. Cosmochim. Acta 62, 985-1081",http://dx.doi.org/10.1016/S0016-7037(97)00219-6 HPT06,"B. Hawrylak, R. Palepu and P. R. Tremaine",2006,"J. Chem. Thermodynamics 38, 988-1007",http://dx.doi.org.ezproxy1.lib.asu.edu/10.1016/j.jct.2005.10.013 @@ -49,8 +50,8 @@ LLD+99,"J. J. M. ter Linde, H. Liang et al.",1999,"J. Bacteriol. 181, 7409-7413",http://jb.asm.org/cgi/content/abstract/181/24/7409 MA07,"L. Marini and M. Accornero",2007,"Environ. Geol. 52, 1343-1363",http://dx.doi.org/10.1007/s00254-006-0578-5 MA10,"L. Marini and M. Accornero",2010,"Environ. Earth Sci. 59, 1601-1606",http://dx.doi.org/10.1007/s12665-009-0369-x -MGN03,"J. Majzlan, K. D. Grevel and A. Navrotsky",2003,"Am. Mineral. 88, 855-859",http://ammin.geoscienceworld.org/cgi/content/abstract/88/5-6/855 -MLS+03,"J. Majzlan, B. E. Lang et al.",2003,"Am. Mineral. 88, 846-854",http://ammin.geoscienceworld.org/cgi/content/abstract/88/5-6/846 +MGN03,"J. Majzlan, K.-D. Grevel and A. Navrotsky",2003,"Am. Mineral. 88, 855-859",http://dx.doi.org/10.2138/am-2003-5-614 +MLS+03,"J. Majzlan, B. E. Lang et al.",2003,"Am. Mineral. 88, 846-854",http://dx.doi.org/10.2138/am-2003-5-613 MNM+06,"J. Majzlan, A. Navrotsky et al.",2006,"Eur. J. Mineral. 18, 175-186",http://dx.doi.org/10.1127/0935-1221/2006/0018-0175 MS97,"T. M. McCollom and E. L. Shock",1997,"Geochim. Cosmochim. Acta 61, 4375-4391",http://dx.doi.org/10.1016/S0016-7037(97)00241-X MSB+04,"J. Majzlan, R. Stevens et al.",2004,"Phys. Chem. Mineral. 31, 518-531",http://dx.doi.org/10.1007/s00269-004-0405-z Modified: pkg/CHNOSZ/demo/00Index =================================================================== --- pkg/CHNOSZ/demo/00Index 2015-11-19 16:53:20 UTC (rev 102) +++ pkg/CHNOSZ/demo/00Index 2015-11-25 04:43:03 UTC (rev 103) @@ -12,3 +12,4 @@ copper another example of mosaic(): complexation of copper with glycine species solubility solubility of calicite or CO2(gas) as a function of pH wjd run.wjd() with proteins: cell periphery of yeast +dehydration log K of dehydration reactions; SVG file contains tooltips and links Added: pkg/CHNOSZ/demo/dehydration.R =================================================================== --- pkg/CHNOSZ/demo/dehydration.R (rev 0) +++ pkg/CHNOSZ/demo/dehydration.R 2015-11-25 04:43:03 UTC (rev 103) @@ -0,0 +1,83 @@ +# plot temperature dependence of log K for some dehydration reactions + +# the RSVGTipsDevice packages 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") + +# add.obigt is needed to add malate and fumarate, +# and epsomite and hexahydrite to thermo$obigt +add.obigt() +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", "cr1", "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("http://dx.doi.org/", ex.doi[i]) + setSVGShapeURL(URL, target="_blank") + setSVGShapeContents(paste0("", ex.txt[i], "")) + # 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]] + ikey1 <- which(thermo$refs$key==key1) + URL1 <- thermo$refs$URL[ikey1] + setSVGShapeURL(URL1, target="_blank") + setSVGShapeContents(paste0("", paste(formula, s$reaction$state[j]), "")) + 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("2nd reference") + 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() + +} Modified: pkg/CHNOSZ/inst/NEWS =================================================================== --- pkg/CHNOSZ/inst/NEWS 2015-11-19 16:53:20 UTC (rev 102) +++ pkg/CHNOSZ/inst/NEWS 2015-11-25 04:43:03 UTC (rev 103) @@ -1,6 +1,18 @@ -CHANGES IN CHNOSZ 1.0.7 (2015-11-19) +CHANGES IN CHNOSZ 1.0.7-1 (2015-11-25) -------------------------------------- +- Add gypsum to OBIGT.csv. + +- Add MgSO4 and hydrated Mg sulfate minerals to OBIGT-2.csv (kieserite, + starkeyite, hexahydrite and epsomite from Grevel and Majzlan, 2009). + +- Add demo dehydration.R. This demo requires the RSVGTipsDevice package, + which is currently unavailable on Windows. + + +CHANGES IN CHNOSZ 1.0.7 (2015-11-19) +------------------------------------ + - Add functions usrfig() (get figure limits in user coordinates) and label.figure() (add label to figure outside of plot region). Modified: pkg/CHNOSZ/inst/extdata/thermo/OBIGT-2.csv =================================================================== --- pkg/CHNOSZ/inst/extdata/thermo/OBIGT-2.csv 2015-11-19 16:53:20 UTC (rev 102) +++ pkg/CHNOSZ/inst/extdata/thermo/OBIGT-2.csv 2015-11-25 04:43:03 UTC (rev 103) @@ -304,3 +304,8 @@ goethite,NA,FeOOH,cr,MGN03,MLS+03,13.Apr.09,-117065,-134010.5,14.269,17.7724665391969,20.881,0.298,55.736,0.75,0,0,0,0,375 lepidocrocite,NA,FeOOH,cr,MGN03,MLS+03,13.Apr.09,-114746.7,-131309.8,15.559,16.5248565965583,22.395,14.283,14.465,-1.847,0,0,0,0,390 maghemite,NA,Fe2O3,cr,MGN03,MLS+03,13.Apr.09,-173972.3,-193140.5,22.228,25.0215105162524,32.779,25.526,15.557,-4.508,0,0,0,0,760 +MgSO4,NA,MgSO4,cr,WEP+82,NA,24.Nov.15,-279780,-307100,21.89,NA,NA,23.06,0,0,0,0,0,0,NA +kieserite,NA,MgSO4.H2O,cr,GM09,NA,24.Nov.15,-343670,-385160,30.11,NA,NA,24.65,0.41,-4.29,0,0,0,0,400 +starkeyite,NA,MgSO4*4H2O,cr,GM09,NA,24.Nov.15,-514770,-596580,62.12,NA,NA,0,0,0,0,0,0,0,400 +hexahydrite,NA,MgSO4*6H2O,cr,GM09,NA,24.Nov.15,-629130,-737880,83.29,NA,NA,48.56,1.6,-10.68,0,0,0,0,400 +epsomite,NA,MgSO4*7H2O,cr,GM09,NA,24.Nov.15,-686190,-809920,88.74,NA,NA,52.29,1.78,-11.67,0,0,0,0,400 Modified: pkg/CHNOSZ/man/examples.Rd =================================================================== --- pkg/CHNOSZ/man/examples.Rd 2015-11-19 16:53:20 UTC (rev 102) +++ pkg/CHNOSZ/man/examples.Rd 2015-11-25 04:43:03 UTC (rev 103) @@ -9,6 +9,7 @@ \arguments{ \item{do.png}{logical, generate PNG files for the plots?} \item{which}{character, which example to run} + \item{to.file}{logical, generate image files for the plots?} } \usage{ @@ -16,7 +17,7 @@ demos(which = c("sources", "NaCl", "density", "nucleobase", "ORP", "revisit", "findit", "ionize", "buffer", "yeastgfp", "mosaic", - "copper", "solubility", "wjd"), do.png=FALSE) + "copper", "solubility", "wjd", "dehydration"), to.file=FALSE) } \details{ @@ -45,6 +46,7 @@ \code{copper} \tab another example of \code{\link{mosaic}}: complexation of Cu with glycine (Aksu and Doyle, 2001) \cr \code{solubility} \tab solubility of calcite (cf. Manning et al., 2013) or CO2(gas) (cf. Stumm and Morgan, 1996) \cr \code{wjd} \tab run.wjd() with proteins: cell periphery of yeast \cr + \code{dehydration} \tab log K of dehydration reactions; SVG file contains tooltips and links \cr } } From noreply at r-forge.r-project.org Fri Nov 27 15:15:54 2015 From: noreply at r-forge.r-project.org (noreply at r-forge.r-project.org) Date: Fri, 27 Nov 2015 15:15:54 +0100 (CET) Subject: [CHNOSZ-commits] r104 - in pkg/CHNOSZ: . R demo inst man tests/testthat Message-ID: <20151127141554.F07E718742B@r-forge.r-project.org> Author: jedick Date: 2015-11-27 15:15:54 +0100 (Fri, 27 Nov 2015) New Revision: 104 Modified: pkg/CHNOSZ/DESCRIPTION pkg/CHNOSZ/R/EOSregress.R pkg/CHNOSZ/R/hkf.R pkg/CHNOSZ/demo/dehydration.R pkg/CHNOSZ/inst/NEWS pkg/CHNOSZ/man/EOSregress.Rd pkg/CHNOSZ/tests/testthat/test-EOSregress.R Log: add ... argument to EOSvar() and EOSregress() Modified: pkg/CHNOSZ/DESCRIPTION =================================================================== --- pkg/CHNOSZ/DESCRIPTION 2015-11-25 04:43:03 UTC (rev 103) +++ pkg/CHNOSZ/DESCRIPTION 2015-11-27 14:15:54 UTC (rev 104) @@ -1,6 +1,6 @@ -Date: 2015-11-25 +Date: 2015-11-27 Package: CHNOSZ -Version: 1.0.7-1 +Version: 1.0.7-2 Title: Chemical Thermodynamics and Activity Diagrams Author: Jeffrey Dick Maintainer: Jeffrey Dick Modified: pkg/CHNOSZ/R/EOSregress.R =================================================================== --- pkg/CHNOSZ/R/EOSregress.R 2015-11-25 04:43:03 UTC (rev 103) +++ pkg/CHNOSZ/R/EOSregress.R 2015-11-27 14:15:54 UTC (rev 104) @@ -3,7 +3,7 @@ # 20091105 first version # 20110429 revise and merge with CHNOSZ package -EOSvar <- function(var, T, P) { +EOSvar <- function(var, T, P, ...) { # get the variables of a term in a regression equation # T (K), P (bar) opt <- get("thermo")$opt @@ -25,14 +25,17 @@ ( if(var %in% water.props()) water(var, T, P)[, 1] else if(exists(var)) { if(is.function(get(var))) { - if(identical(names(formals(get(var))), c("T", "P"))) get(var)(T, P) - else stop(paste("the arguments of ", var, "() are not T, P", sep="")) + 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) } @@ -79,21 +82,21 @@ return(lab) } -EOSregress <- function(exptdata,var="",T.max=9999) { +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,] + 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] + X <- exptdata[, 3] # now build a regression formula if(length(var) == 0) stop("var is missing") - fmla <- as.formula(paste("X ~ ",paste(var,collapse="+"))) + 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)) + for(i in seq_along(var)) assign(var[i], EOSvar(var[i], T=T, P=P, ...)) # now regress away! EOSlm <- lm(fmla) return(EOSlm) @@ -169,20 +172,21 @@ return(invisible(list(xlim=range(exptdata$T[iexpt])))) } -EOScoeffs <- function(species, property) { +EOScoeffs <- function(species, property, P=1) { # get the HKF coefficients for species in the database iis <- info(info(species, "aq")) if(property=="Cp") { - out <- iis[,c("c1", "c2", "omega")] + 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 cal = 41.84 cm^3 bar - sigma <- convert( iis$a1 + iis$a2 / (2600 + 1), "cm3bar" ) - xi <- convert( iis$a3 + iis$a4 / (2600 + 1), "cm3bar" ) + sigma <- convert( iis$a1 + iis$a2 / (2600 + P), "cm3bar" ) + xi <- convert( iis$a3 + iis$a4 / (2600 + P), "cm3bar" ) omega <- convert( iis$omega, "cm3bar" ) - # watch for the negative sign on omega here! - out <- data.frame(sigma, xi, -omega) + # 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) Modified: pkg/CHNOSZ/R/hkf.R =================================================================== --- pkg/CHNOSZ/R/hkf.R 2015-11-25 04:43:03 UTC (rev 103) +++ pkg/CHNOSZ/R/hkf.R 2015-11-27 14:15:54 UTC (rev 104) @@ -17,7 +17,7 @@ property <- eargs$prop props <- eargs$props Prop <- eargs$Prop - domega <- rep(domega,length.out=nrow(ghs)) + domega <- rep(domega,length.out=nrow(eos)) # nonsolvation, solvation, and origination contribution contribs <- c('n','s','o') notcontrib <- ! contrib %in% contribs @@ -29,8 +29,8 @@ # only take these ones if we're in SUPCRT92 compatibility mode dosupcrt <- thermo$opt$water != "IAPWS95" if(dosupcrt) { - # (E, daldT, V - for partial derivatives of omega (g function)) - H2O.props <- c(H2O.props,'E','daldT','kT','ZBorn') + # (rho, alpha, daldT, beta - for partial derivatives of omega (g function)) + H2O.props <- c(H2O.props, "rho", "alpha", "daldT", "beta") } else { # (NBorn, UBorn - for compressibility, expansibility) H2O.props <- c(H2O.props,'NBorn','UBorn') @@ -42,20 +42,26 @@ } # a list to store the result x <- list() - for(k in 1:nrow(ghs)) { + nspecies <- nrow(ghs) + # we can be called with NULL ghs (by Cp_s_var, V_s_var) + if(is.null(nspecies)) nspecies <- nrow(eos) + for(k in 1:nspecies) { # loop over each species GHS <- ghs[k,] EOS <- eos[k,] # substitute Cp and V for missing EoS parameters # here we assume that the parameters are in the same position as in thermo$obigt - # put the heat capacity in for c1 if both c1 and c2 are missing - if(all(is.na(EOS[, 17:18]))) EOS[, 17] <- EOS$Cp - # put the volume in for a1 if a1, a2, a3 and a4 are missing - if(all(is.na(EOS[, 13:16]))) EOS[, 13] <- convert(EOS$V, "calories") - # test for availability of the EoS parameters - hasEOS <- any(!is.na(EOS[, 13:20])) - # if at least one of the EoS parameters is available, zero out any NA's in the rest - if(hasEOS) EOS[, 13:20][, is.na(EOS[, 13:20])] <- 0 + # 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(EOS[, 17:18]))) EOS[, 17] <- EOS$Cp + # put the volume in for a1 if a1, a2, a3 and a4 are missing + if(all(is.na(EOS[, 13:16]))) EOS[, 13] <- convert(EOS$V, "calories") + # test for availability of the EoS parameters + hasEOS <- any(!is.na(EOS[, 13:20])) + # if at least one of the EoS parameters is available, zero out any NA's in the rest + if(hasEOS) EOS[, 13:20][, is.na(EOS[, 13:20])] <- 0 + } # compute values of omega(P,T) from those of omega(Pr,Tr) # using g function etc. (Shock et al., 1992 and others) omega <- EOS$omega # omega.PrTr Modified: pkg/CHNOSZ/demo/dehydration.R =================================================================== --- pkg/CHNOSZ/demo/dehydration.R 2015-11-25 04:43:03 UTC (rev 103) +++ pkg/CHNOSZ/demo/dehydration.R 2015-11-27 14:15:54 UTC (rev 104) @@ -1,6 +1,6 @@ # plot temperature dependence of log K for some dehydration reactions -# the RSVGTipsDevice packages allows us to create an SVG file with +# the RSVGTipsDevice package allows us to create an SVG file with # tooltips and hyperlinks if(require("RSVGTipsDevice")) { @@ -14,7 +14,7 @@ plot(range(T), c(-2, 1), type="n", xlab="T, °C", ylab="log K") title(main="Dehydration reactions") -# add.obigt is needed to add malate and fumarate, +# add.obigt is used to add malate and fumarate, # and epsomite and hexahydrite to thermo$obigt add.obigt() reactants <- c("[AABB]", "[AABB]", "malate-2", "goethite", "gypsum", "epsomite", "ethanol") Modified: pkg/CHNOSZ/inst/NEWS =================================================================== --- pkg/CHNOSZ/inst/NEWS 2015-11-25 04:43:03 UTC (rev 103) +++ pkg/CHNOSZ/inst/NEWS 2015-11-27 14:15:54 UTC (rev 104) @@ -1,4 +1,4 @@ -CHANGES IN CHNOSZ 1.0.7-1 (2015-11-25) +CHANGES IN CHNOSZ 1.0.7-2 (2015-11-27) -------------------------------------- - Add gypsum to OBIGT.csv. @@ -9,7 +9,14 @@ - Add demo dehydration.R. This demo requires the RSVGTipsDevice package, which is currently unavailable on Windows. +- Add ... argument to EOSvar() and EOSregress(). Allows specifying new + variables that are written as a function of arbitrary properties + (regression variables still must be a function of at least T and P). +- EOSvar() now returns the negative of the 'QBorn' variable so that + values of omega obtained from regressions of volume data have the + correct sign in the HKF equations. + CHANGES IN CHNOSZ 1.0.7 (2015-11-19) ------------------------------------ Modified: pkg/CHNOSZ/man/EOSregress.Rd =================================================================== --- pkg/CHNOSZ/man/EOSregress.Rd 2015-11-25 04:43:03 UTC (rev 103) +++ pkg/CHNOSZ/man/EOSregress.Rd 2015-11-27 14:15:54 UTC (rev 104) @@ -13,13 +13,13 @@ } \usage{ - EOSregress(exptdata, var = "", T.max = 9999) - EOSvar(var, T, P) + EOSregress(exptdata, var = "", T.max = 9999, ...) + EOSvar(var, T, P, ...) EOScalc(coefficients, T, P) EOSplot(exptdata, var = NULL, T.max = 9999, T.plot = NULL, fun.legend = "topleft", coefficients = NULL) EOSlab(var, coeff = "") - EOScoeffs(species, property) + EOScoeffs(species, property, P=1) } \arguments{ @@ -28,6 +28,7 @@ \item{T.max}{numeric, maximum temperature for regression, in degrees Kelvin} \item{T}{numeric, temperature in degrees Kelvin} \item{P}{numeric, pressure in bars} + \item{...}{arguments defining additional properties which variables are a function of} \item{T.plot}{numeric, upper limit of temperature range to plot} \item{fun.legend}{character, where to place legend on plot} \item{coefficients}{dataframe, coefficients to use to make line on plot} @@ -74,6 +75,7 @@ \code{EOScoeffs} retrieves coefficients in the Helgeson-Kirkham-Flowers equations from the thermodynamic database (\code{\link{thermo}$obigt}) for the given aqueous \code{species}. If the \code{property} is \samp{Cp}, the resulting data frame has column names of \samp{(Intercept)}, \samp{invTTheta2} and \samp{TX}, respectively holding the coefficients \eqn{c_1}{c1}, \eqn{c_2}{c2} and \eqn{\omega}{omega} in the equation \eqn{Cp^\circ = c_1 + c_2/(T-\Theta)^2 + {\omega}TX}{Cp = c1 + c2/(T-Theta)^2 + omega*TX}. If the \code{property} is \samp{V}, the data frame has column names of \samp{(Intercept)}, \samp{invTTheta} and \samp{Q}, respectively holding the coefficients \eqn{\sigma}{sigma}, \eqn{\xi}{xi} and \eqn{-\omega}{-omega} in \eqn{V^\circ = \sigma + \xi/(T-\Theta) - {\omega}Q}{V = sigma + xi/(T-Theta) - omega*Q}. +Here, \eqn{\sigma}{sigma} and \eqn{\xi}{xi} are calculated from a1, a2, a3 and a4 in \code{thermo$obigt} at the pressure indicated by \code{P} (default 1 bar). The motivation for writing these functions is to explore alternatives or possible modifications to the revised Helgeson-Kirkham-Flowers equations applied to aqueous nonelectrolytes. As pointed out by Schulte et al., 2001, the functional forms of the equations do not permit retrieving values of the solvation parameter (\eqn{\omega}{omega}) that closely represent the observed trends in both heat capacity and volume at high temperatures (above ca. 200 \eqn{^{\circ}}{?}C). Modified: pkg/CHNOSZ/tests/testthat/test-EOSregress.R =================================================================== --- pkg/CHNOSZ/tests/testthat/test-EOSregress.R 2015-11-25 04:43:03 UTC (rev 103) +++ pkg/CHNOSZ/tests/testthat/test-EOSregress.R 2015-11-27 14:15:54 UTC (rev 104) @@ -13,7 +13,7 @@ #expect_error(EOSvar("TX", T=25, P=1), "the arguments of TX\\(\\) are not T, P") }) -test_that("regressions return known HKF parameters", { +test_that("regressions return known HKF parameters (neutral species)", { # regress computed values of heat capacity and volume of CH4(aq) # calculated from HKF parameters on a T-P grid T <- convert(seq(0, 350, 25), "K") @@ -34,15 +34,15 @@ ## the tests: did we get the HKF parameters that are in the database? CH4.par <- info(info("CH4")) # c1 and c2 - expect_equal(Cp.coeff[1], CH4.par$c1, check.attributes=FALSE) - expect_equal(Cp.coeff[2], CH4.par$c2, check.attributes=FALSE) + expect_equivalent(Cp.coeff[1], CH4.par$c1) + expect_equivalent(Cp.coeff[2], CH4.par$c2) # omega (from Cp) - expect_equal(Cp.coeff[3], CH4.par$omega, check.attributes=FALSE) + expect_equivalent(Cp.coeff[3], CH4.par$omega) # a1, a2, a3 and a4 - expect_equal(V.coeff[1], CH4.par$a1, check.attributes=FALSE) - expect_equal(V.coeff[2], CH4.par$a2, check.attributes=FALSE) - expect_equal(V.coeff[3], CH4.par$a3, check.attributes=FALSE) - expect_equal(V.coeff[4], CH4.par$a4, check.attributes=FALSE) - # omega (from V) - note negative sign - expect_equal(-V.coeff[5], CH4.par$omega, check.attributes=FALSE) + expect_equivalent(V.coeff[1], CH4.par$a1) + expect_equivalent(V.coeff[2], CH4.par$a2) + expect_equivalent(V.coeff[3], CH4.par$a3) + expect_equivalent(V.coeff[4], CH4.par$a4) + # omega (from V) + expect_equivalent(V.coeff[5], CH4.par$omega) })