content
stringlengths 0
14.9M
| filename
stringlengths 44
136
|
---|---|
## ----setup, include=FALSE-----------------------------------------------------
## Use pngquant to optimize PNG images
library(knitr)
knit_hooks$set(pngquant = hook_pngquant)
pngquant <- "--speed=1 --quality=0-25"
if (!nzchar(Sys.which("pngquant"))) pngquant <- NULL
# Set dpi 20231129
knitr::opts_chunk$set(
dpi = if(nzchar(Sys.getenv("CHNOSZ_BUILD_LARGE_VIGNETTES"))) 100 else 72
)
## ----CHNOSZ_reset, include=FALSE----------------------------------------------
library(CHNOSZ)
reset()
## ----AAsetup, results = "hide", message = FALSE-------------------------------
library(CHNOSZ)
reset()
basis("CHNOS")
species(aminoacids(""))
## ----AAfunctions--------------------------------------------------------------
aaA <- function() {
a <- affinity(O2 = c(-90, -70), H2O = c(-20, 10))
diagram(a, balance = 1, names = aa)
}
aaB <- function() {
a <- affinity(O2 = c(-90, -70), H2O = c(-20, 10))
e <- equilibrate(a, balance = 1)
diagram(e, names = aa)
}
aaC <- function() {
a <- affinity(O2 = c(-71, -66), H2O = c(-8, 4))
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, -7)
a <- affinity(H2O = c(-8, 4))
e <- equilibrate(a, balance = "CO2")
diagram(e, ylim = c(-8, -4), names = aa)
}
## ----AAabbrv------------------------------------------------------------------
aa <- aminoacids()
aa
## ----AAplot, eval = FALSE-----------------------------------------------------
# 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(0.7, 4, 4))
#
# ## Row 0 (column titles)
# opar <- par(mar=c(0, 0, 0, 0))
# plot.new()
# plot.new()
# text(0.58, 0.5, "maximum affinity", cex=1.4)
# plot.new()
# text(0.58, 0.5, "equilibration", cex=1.4)
# plot.new()
# text(0.58, 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", yfrac=0.92, xfrac=0.1, font = 2)
# # Figure B
# st <- system.time(dB <- aaB())
# showtime(st)
# title(main=paste("loga(total species) =", round(dB$loga.balance[1], 2)), cex.main=1)
# label.figure("C", yfrac=0.92, xfrac=0.1, font = 2)
#
# ## 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("B", yfrac=0.92, xfrac=0.1, font = 2)
# # Figure D
# st <- system.time(dD <- aaD())
# showtime(st)
# title(main=paste("loga(total CO2) =", round(dD$loga.balance[1], 2)), cex.main=1)
# label.figure("D", yfrac=0.92, xfrac=0.1, font = 2)
#
# ## Right column (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[1], 2)), cex.main=1)
# label.figure("E", yfrac=0.92, xfrac=0.1, font = 2)
# # Figure F
# st <- system.time(dF <- aaF())
# showtime(st)
# title(main=paste("loga(total CO2) =", round(dF$loga.balance[1], 2)), cex.main=1)
# label.figure("F", yfrac=0.92, xfrac=0.1, font = 2)
## ----AAplot, echo = FALSE, results = "hide", message = FALSE, fig.width = 13/2, fig.height = 8.7/2, out.width = "100%", pngquant = pngquant----
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(0.7, 4, 4))
## Row 0 (column titles)
opar <- par(mar=c(0, 0, 0, 0))
plot.new()
plot.new()
text(0.58, 0.5, "maximum affinity", cex=1.4)
plot.new()
text(0.58, 0.5, "equilibration", cex=1.4)
plot.new()
text(0.58, 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", yfrac=0.92, xfrac=0.1, font = 2)
# Figure B
st <- system.time(dB <- aaB())
showtime(st)
title(main=paste("loga(total species) =", round(dB$loga.balance[1], 2)), cex.main=1)
label.figure("C", yfrac=0.92, xfrac=0.1, font = 2)
## 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("B", yfrac=0.92, xfrac=0.1, font = 2)
# Figure D
st <- system.time(dD <- aaD())
showtime(st)
title(main=paste("loga(total CO2) =", round(dD$loga.balance[1], 2)), cex.main=1)
label.figure("D", yfrac=0.92, xfrac=0.1, font = 2)
## Right column (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[1], 2)), cex.main=1)
label.figure("E", yfrac=0.92, xfrac=0.1, font = 2)
# Figure F
st <- system.time(dF <- aaF())
showtime(st)
title(main=paste("loga(total CO2) =", round(dF$loga.balance[1], 2)), cex.main=1)
label.figure("F", yfrac=0.92, xfrac=0.1, font = 2)
## ----PRsetup, results = "hide", message = FALSE-------------------------------
basis("CHNOS+")
organisms <- c("METJA", "HALJP", "METVO", "ACEKI", "GEOSE", "BACLI")
proteins <- c(rep("CSG", 3), rep("SLAP", 3))
species(proteins, organisms)
## ----PRlength-----------------------------------------------------------------
protein.length(species()$name)
## ----PRfunctions--------------------------------------------------------------
prA <- function() {
a <- affinity(O2 = c(-90, -70), H2O = c(-20, 0))
diagram(a, balance = "length", names = organisms)
}
prB <- function() {
a <- affinity(O2 = c(-90, -70))
e <- equilibrate(a, balance = "length")
ylab <- quote(log~italic(a)~protein)
diagram(e, names = organisms, ylim = c(-5, -1), ylab = ylab)
}
prC <- function() {
a <- affinity(O2 = c(-90, -70), H2O = c(-20, 0))
diagram(a, normalize = TRUE, names = organisms)
}
prD <- function() {
a <- affinity(O2 = c(-90, -70))
e <- equilibrate(a, normalize = TRUE)
ylab <- quote(log~italic(a)~protein)
diagram(e, names = organisms, ylim = c(-5, -1), ylab = ylab)
}
prE <- function() {
a <- affinity(O2 = c(-90, -70), H2O = c(-20, 0))
diagram(a, as.residue = TRUE, names = organisms)
}
prF <- function() {
a <- affinity(O2 = c(-90, -70))
e <- equilibrate(a, as.residue = TRUE, loga.balance = 0)
ylab <- quote(log~italic(a)~residue)
diagram(e, names = organisms, ylim = c(-3, 1), ylab = ylab)
}
## ----PRplot, eval = FALSE-----------------------------------------------------
# layout(t(matrix(1:12, nrow=4)), widths=c(1, 4, 4, 4), heights=c(0.7, 4, 4))
#
# ## Row 0 (column titles)
# opar <- par(mar=c(0, 0, 0, 0))
# plot.new()
# plot.new()
# text(0.58, 0.5, 'balance = "length"', cex=1.4)
# plot.new()
# text(0.58, 0.5, "normalize = TRUE\n(balance = 1)", cex=1.4)
# plot.new()
# text(0.58, 0.5, "as.residue = TRUE\n(balance = 1)", cex=1.4)
# par(opar)
#
# ## Row 1 (maximum affinity 2D)
# opar <- par(mar=c(0, 0, 0, 0))
# plot.new()
# text(0.5, 0.5, "maximum affinity", srt=90, cex=1.4)
# par(opar)
# # Figure A (balance = "length")
# st <- system.time(dA <- prA())
# showtime(st)
# label.figure("A", yfrac=0.9, xfrac=0.1, font = 2)
# # Figure C (normalize = TRUE)
# st <- system.time(dC <- prC())
# showtime(st)
# label.figure("C", yfrac=0.9, xfrac=0.1, font = 2)
# # Figure E (as.residue = TRUE)
# st <- system.time(dE <- prE())
# showtime(st)
# label.figure("E", yfrac=0.9, xfrac=0.1, font = 2)
#
# ## Row 2 (equilibrate 1D)
# opar <- par(mar=c(0, 0, 0, 0))
# plot.new()
# text(0.5, 0.5, "equilibration", srt=90, cex=1.4)
# par(opar)
# # Figure B (balance = "length")
# st <- system.time(prB())
# showtime(st)
# label.figure("B", yfrac=0.9, xfrac=0.1, font = 2)
# # Figure D (normalize = TRUE)
# st <- system.time(prD())
# showtime(st)
# label.figure("D", yfrac=0.9, xfrac=0.1, font = 2)
# # Figure F (as.residue = TRUE)
# st <- system.time(prF())
# showtime(st)
# label.figure("F", yfrac=0.9, xfrac=0.1, font = 2)
## ----PRplot, echo = FALSE, results = "hide", message = FALSE, fig.width = 13/2, fig.height = 8.7/2, out.width = "100%", pngquant = pngquant----
layout(t(matrix(1:12, nrow=4)), widths=c(1, 4, 4, 4), heights=c(0.7, 4, 4))
## Row 0 (column titles)
opar <- par(mar=c(0, 0, 0, 0))
plot.new()
plot.new()
text(0.58, 0.5, 'balance = "length"', cex=1.4)
plot.new()
text(0.58, 0.5, "normalize = TRUE\n(balance = 1)", cex=1.4)
plot.new()
text(0.58, 0.5, "as.residue = TRUE\n(balance = 1)", cex=1.4)
par(opar)
## Row 1 (maximum affinity 2D)
opar <- par(mar=c(0, 0, 0, 0))
plot.new()
text(0.5, 0.5, "maximum affinity", srt=90, cex=1.4)
par(opar)
# Figure A (balance = "length")
st <- system.time(dA <- prA())
showtime(st)
label.figure("A", yfrac=0.9, xfrac=0.1, font = 2)
# Figure C (normalize = TRUE)
st <- system.time(dC <- prC())
showtime(st)
label.figure("C", yfrac=0.9, xfrac=0.1, font = 2)
# Figure E (as.residue = TRUE)
st <- system.time(dE <- prE())
showtime(st)
label.figure("E", yfrac=0.9, xfrac=0.1, font = 2)
## Row 2 (equilibrate 1D)
opar <- par(mar=c(0, 0, 0, 0))
plot.new()
text(0.5, 0.5, "equilibration", srt=90, cex=1.4)
par(opar)
# Figure B (balance = "length")
st <- system.time(prB())
showtime(st)
label.figure("B", yfrac=0.9, xfrac=0.1, font = 2)
# Figure D (normalize = TRUE)
st <- system.time(prD())
showtime(st)
label.figure("D", yfrac=0.9, xfrac=0.1, font = 2)
# Figure F (as.residue = TRUE)
st <- system.time(prF())
showtime(st)
label.figure("F", yfrac=0.9, xfrac=0.1, font = 2)
## ----ProteinSpeciation, results = "hide", message = FALSE, fig.width = 8, fig.height = 5.5, out.width = "100%", pngquant = pngquant----
organisms <- c("METSC", "METJA", "METFE", "METVO", "METBU",
"HALJP", "ACEKI", "GEOSE", "BACLI", "AERSA")
proteins <- c(rep("CSG", 6), rep("SLAP", 4))
# Use red for Methano* genera
col <- c(rep(2, 5), rep(1, 5))
basis("CHNOS+")
species(proteins, organisms)
a <- affinity(O2 = c(-100, -65))
layout(matrix(1:2), heights = c(1, 2))
e <- equilibrate(a)
diagram(e, ylim = c(-2.8, -1.6), names = organisms, col = col)
water.lines(e, col = 4)
title(main="Equilibrium activities of proteins, normalize = FALSE")
e <- equilibrate(a, normalize = TRUE)
diagram(e, ylim = c(-4, -2), names = organisms, col = col)
water.lines(e, col = 4)
title(main = "Equilibrium activities of proteins, normalize = TRUE")
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/doc/equilibrium.R
|
---
title: "Equilibrium in CHNOSZ"
author: "Jeffrey M. Dick"
output:
html_vignette:
mathjax: null
vignette: >
%\VignetteIndexEntry{Equilibrium in CHNOSZ}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
bibliography: vig.bib
csl: elementa.csl
link-citations: true
---
<style>
/* https://gomakethings.com/how-to-break-an-image-out-of-its-parent-container-with-css/ */
@media (min-width: 700px) {
.full-width {
left: 50%;
margin-left: -50vw;
margin-right: -50vw;
max-width: 100vw;
position: relative;
right: 50%;
width: 100vw;
}
}
@media (min-width: 1020px) {
.full-width {
left: 50vw; /* fallback if needed */
left: calc(50vw - 160px);
width: 1000px;
position: relative;
background-color: #9ecff7;
padding:10px;
}
}
/* Zero margin around pre blocks (looks more like R console output) */
pre {
margin-top: 0;
margin-bottom: 0;
}
</style>
<script>
function ToggleDiv(ID) {
var D = document.getElementById("D-" + ID);
var B = document.getElementById("B-" + ID);
if (D.style.display === "none") {
// open the div and change button text
D.style.display = "block";
B.innerText = "Hide code";
} else {
// close the div and change button text
D.style.display = "none";
B.innerText = "Show code";
}
}
</script>
```{r setup, include=FALSE}
## Use pngquant to optimize PNG images
library(knitr)
knit_hooks$set(pngquant = hook_pngquant)
pngquant <- "--speed=1 --quality=0-25"
if (!nzchar(Sys.which("pngquant"))) pngquant <- NULL
# Set dpi 20231129
knitr::opts_chunk$set(
dpi = if(nzchar(Sys.getenv("CHNOSZ_BUILD_LARGE_VIGNETTES"))) 100 else 72
)
```
```{r CHNOSZ_reset, include=FALSE}
library(CHNOSZ)
reset()
```
This vignette was compiled on `r Sys.Date()` with CHNOSZ version `r sessionInfo()$otherPkgs$CHNOSZ$Version`.
This document defines the concepts and provides examples of equilibrium calculations in CHNOSZ.
First, some limitations.
CHNOSZ is not a general-purpose speciation code.
The types of equilibrium calculations it can handle are restricted to those systems that can be described as *balanced on an element*.
For example, we can predict the speciation of Au in complexes with chloride, hydroxide, and sulfide all with specified activities.
But we can not at the same time predict the formation of species such as NaCl(aq), which is required for a complete equilibrium model.
## Concepts
System
: Chemical system defined by formed species (referred to simply as species) and basis species, which are analogous to thermodynamic components.
The possible species are any that are available in the [OBIGT thermodynamic database](OBIGT.html).
Species
: Selection of possible chemical species for which you want to calculate relative stabilities.
Basis species
: Any minimal set of possible species that can be used to balance the formation reactions of the species.
Additionally, in CHNOSZ the number of basis species must be equal to the number of elements.
Formation reaction
: Chemical reaction giving the stoichiometry of basis species combined to make 1 mole of a species.
Transformation reaction
: Any combination of two formation reactions in opposite directions (1 mole of a species reacts to form 1 mole of another species).
Balancing coefficients
: (*n*~balance~) For a system that is balanced on one of the basis species,
the number of moles of that basis species in the formation reaction of each of the species.
The number can be positive or negative but not zero.
Can also represent a virtual quantity, such as 1 (balance on moles of species) or number of amino acids in a protein sequence (balance on protein length).
Speciation diagram
: Diagram showing the equilibrium activities of species as a function of one variable.
Predominance diagram
: Diagram variables showing fields for species with highest equilibrium activity as a function of two variables.
Also known as an equal activity diagram for aqueous species or stability diagram for minerals.
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: *A* = 2.303*RT*log(*K*/*Q*),
where *K* is the equilibrium constant and *Q* is the activity quotient of species in the reaction
(log here denotes base-10 logarithms, i.e. `log10` in R).
Maximum affinity method
: Approach used to construct predominance diagrams not by finding the highest activity at equilibrium but by finding the highest affinity at a **reference activity**.
The reference activities are user-defined equal activities of species (e.g. unit activity for minerals and 10^-3^ for aqueous species).
Equilibration method
: Calculations of the activities of species in equilibrium.
Metastable equilibrium
: The condition that the affinities of all *transformation* reactions are zero.
Implemented with the `equilibrate()` function in CHNOSZ, which is used below.
Total equilibrium
: The condition that the affinities of all *formation* reactions are zero.
Implemented with the `solubility()` function in CHNOSZ, which is not described here.
## Example 1: Amino acids
In this sytem the basis species are CO~2~, H~2~O, NH~3~, H~2~S, and O~2~ and the formed species are 20 amino acids.
```{r AAsetup, results = "hide", message = FALSE}
library(CHNOSZ)
reset()
basis("CHNOS")
species(aminoacids(""))
```
These functions are used for the different diagrams in the figure.
```{r AAfunctions}
aaA <- function() {
a <- affinity(O2 = c(-90, -70), H2O = c(-20, 10))
diagram(a, balance = 1, names = aa)
}
aaB <- function() {
a <- affinity(O2 = c(-90, -70), H2O = c(-20, 10))
e <- equilibrate(a, balance = 1)
diagram(e, names = aa)
}
aaC <- function() {
a <- affinity(O2 = c(-71, -66), H2O = c(-8, 4))
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, -7)
a <- affinity(H2O = c(-8, 4))
e <- equilibrate(a, balance = "CO2")
diagram(e, ylim = c(-8, -4), names = aa)
}
```
The labels used for the diagrams are the one-letter abbreviations for the amino acids.
```{r AAabbrv}
aa <- aminoacids()
aa
```
Press the button to show all of the code for making the figure.
<button id="B-AAplot" onclick="ToggleDiv('AAplot')">Show code</button>
<div id="D-AAplot" style="display: none">
```{r AAplot, eval = FALSE}
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(0.7, 4, 4))
## Row 0 (column titles)
opar <- par(mar=c(0, 0, 0, 0))
plot.new()
plot.new()
text(0.58, 0.5, "maximum affinity", cex=1.4)
plot.new()
text(0.58, 0.5, "equilibration", cex=1.4)
plot.new()
text(0.58, 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", yfrac=0.92, xfrac=0.1, font = 2)
# Figure B
st <- system.time(dB <- aaB())
showtime(st)
title(main=paste("loga(total species) =", round(dB$loga.balance[1], 2)), cex.main=1)
label.figure("C", yfrac=0.92, xfrac=0.1, font = 2)
## 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("B", yfrac=0.92, xfrac=0.1, font = 2)
# Figure D
st <- system.time(dD <- aaD())
showtime(st)
title(main=paste("loga(total CO2) =", round(dD$loga.balance[1], 2)), cex.main=1)
label.figure("D", yfrac=0.92, xfrac=0.1, font = 2)
## Right column (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[1], 2)), cex.main=1)
label.figure("E", yfrac=0.92, xfrac=0.1, font = 2)
# Figure F
st <- system.time(dF <- aaF())
showtime(st)
title(main=paste("loga(total CO2) =", round(dF$loga.balance[1], 2)), cex.main=1)
label.figure("F", yfrac=0.92, xfrac=0.1, font = 2)
```
</div>
```{r AAplot, echo = FALSE, results = "hide", message = FALSE, fig.width = 13/2, fig.height = 8.7/2, out.width = "100%", pngquant = pngquant}
```
Diagrams **A** and **B** use the *maximum affinity method*, where the reference
activities of species are set to a single value. Diagrams **C** and **D** use
the *equilibration method*, where the activities of species change across the
diagram and the lines are drawn at equal activity. Other comments on the
figure:
* The equal-activity lines in Diagrams **A** and **C** are the same. That is,
with the setting `balance = 1`, the conditions for equal activity of two
species do not depend on the actual value of that activity.
* Diagrams **B** and **D** are different. Because balance ≠ 1 (in this case,
the reactions are balanced on CO~2~), the conditions for equal activity of
species depend on the actual value of that activity. In particular, with the
equilibration method, the lines are curved due to the distribution of more
than two species.
* Diagrams **E** and **F** both use the equilibration method to calculate
activities of species as a function of log*a*~H2O~ at log*f*~O2~ = -66.
Diagram **F** shows the default setting, where *a*~CO2~ is taken from the sum
of initial activities of species (each 10^-3^). The positions of equal
activities (where the lines cross) are the same as in Diagram **D** at
log*f*~O2~ = -66.
* Diagram **F** is drawn for a lower total activity of *a*~CO2~. Not only are
the activities of all amino acids decreased, but glycine starts to become
predominant at some conditions. This is because, compared to other amino
acids, it is smaller and has a lower coefficient on CO~2~ in its formation
reaction.
## Example 2: Proteins
In this sytem the basis species are CO~2~, H~2~O, NH~3~, H~2~S, O~2~, and H^+^ and the
formed species are 6 proteins from the set of archaeal and bacterial surface
layer proteins considered by @Dic08.
The inclusion of charge in the basis species (with H^+^) allows ionization of
proteins to be calculated [@DLH06].
```{r PRsetup, results = "hide", message = FALSE}
basis("CHNOS+")
organisms <- c("METJA", "HALJP", "METVO", "ACEKI", "GEOSE", "BACLI")
proteins <- c(rep("CSG", 3), rep("SLAP", 3))
species(proteins, organisms)
```
Here are the lengths of the proteins.
```{r PRlength}
protein.length(species()$name)
```
These functions are used for the different diagrams in the figure.
```{r PRfunctions}
prA <- function() {
a <- affinity(O2 = c(-90, -70), H2O = c(-20, 0))
diagram(a, balance = "length", names = organisms)
}
prB <- function() {
a <- affinity(O2 = c(-90, -70))
e <- equilibrate(a, balance = "length")
ylab <- quote(log~italic(a)~protein)
diagram(e, names = organisms, ylim = c(-5, -1), ylab = ylab)
}
prC <- function() {
a <- affinity(O2 = c(-90, -70), H2O = c(-20, 0))
diagram(a, normalize = TRUE, names = organisms)
}
prD <- function() {
a <- affinity(O2 = c(-90, -70))
e <- equilibrate(a, normalize = TRUE)
ylab <- quote(log~italic(a)~protein)
diagram(e, names = organisms, ylim = c(-5, -1), ylab = ylab)
}
prE <- function() {
a <- affinity(O2 = c(-90, -70), H2O = c(-20, 0))
diagram(a, as.residue = TRUE, names = organisms)
}
prF <- function() {
a <- affinity(O2 = c(-90, -70))
e <- equilibrate(a, as.residue = TRUE, loga.balance = 0)
ylab <- quote(log~italic(a)~residue)
diagram(e, names = organisms, ylim = c(-3, 1), ylab = ylab)
}
```
<button id="B-PRplot" onclick="ToggleDiv('PRplot')">Show code</button>
<div id="D-PRplot" style="display: none">
```{r PRplot, eval = FALSE}
```
</div>
```{r PRplot, echo = FALSE, results = "hide", message = FALSE, fig.width = 13/2, fig.height = 8.7/2, out.width = "100%", pngquant = pngquant}
layout(t(matrix(1:12, nrow=4)), widths=c(1, 4, 4, 4), heights=c(0.7, 4, 4))
## Row 0 (column titles)
opar <- par(mar=c(0, 0, 0, 0))
plot.new()
plot.new()
text(0.58, 0.5, 'balance = "length"', cex=1.4)
plot.new()
text(0.58, 0.5, "normalize = TRUE\n(balance = 1)", cex=1.4)
plot.new()
text(0.58, 0.5, "as.residue = TRUE\n(balance = 1)", cex=1.4)
par(opar)
## Row 1 (maximum affinity 2D)
opar <- par(mar=c(0, 0, 0, 0))
plot.new()
text(0.5, 0.5, "maximum affinity", srt=90, cex=1.4)
par(opar)
# Figure A (balance = "length")
st <- system.time(dA <- prA())
showtime(st)
label.figure("A", yfrac=0.9, xfrac=0.1, font = 2)
# Figure C (normalize = TRUE)
st <- system.time(dC <- prC())
showtime(st)
label.figure("C", yfrac=0.9, xfrac=0.1, font = 2)
# Figure E (as.residue = TRUE)
st <- system.time(dE <- prE())
showtime(st)
label.figure("E", yfrac=0.9, xfrac=0.1, font = 2)
## Row 2 (equilibrate 1D)
opar <- par(mar=c(0, 0, 0, 0))
plot.new()
text(0.5, 0.5, "equilibration", srt=90, cex=1.4)
par(opar)
# Figure B (balance = "length")
st <- system.time(prB())
showtime(st)
label.figure("B", yfrac=0.9, xfrac=0.1, font = 2)
# Figure D (normalize = TRUE)
st <- system.time(prD())
showtime(st)
label.figure("D", yfrac=0.9, xfrac=0.1, font = 2)
# Figure F (as.residue = TRUE)
st <- system.time(prF())
showtime(st)
label.figure("F", yfrac=0.9, xfrac=0.1, font = 2)
```
Diagrams **A**, **C**, and **E** are predominance (equal-activity) diagrams
made with different balancing constraints. Diagrams **B**, **D**, and **F**
show a cross-section of the same system at log*a*~H2O~ = 0.
* In Diagrams **A** and **B**, the reactions are balanced on protein length.
The drastic transitions between proteins in **B** result from the large
balancing coefficients, which become exponents on activities in the
expression for the activity quotient (*Q*).
* In Diagrams **C** and **D**, the chemical formulas of the proteins are
*normalized*, or divided by the protein length, before the equilibration or
maximum affinity calculation. However, the final diagram is not drawn for
activities of these "residue equivalents", but for rescaled activities of
whole proteins. Because of the rescaling, the fields of the shorter METJA and
METVO proteins grow at the expense of the longer BACLI protein.
* Diagrams **E** and **F** are like the normalization calculation, except that
the final diagram is drawn for the residue equivalents and not the whole
proteins. The predominance diagram is the same as that for non-normalized
reactions (**A**), but the equilibrium activities of residues are higher than
those of the proteins.
## Example 3: Normalization
Here is another figure showing the effects of normalization.
This is like Figure 5 of @Dic08, extended to more extreme conditions.
If you wish to reproduce the diagram from the 2008 paper more closely, uncomment the `add.OBIGT()` command.
```{r ProteinSpeciation, results = "hide", message = FALSE, fig.width = 8, fig.height = 5.5, out.width = "100%", pngquant = pngquant}
organisms <- c("METSC", "METJA", "METFE", "METVO", "METBU",
"HALJP", "ACEKI", "GEOSE", "BACLI", "AERSA")
proteins <- c(rep("CSG", 6), rep("SLAP", 4))
# Use red for Methano* genera
col <- c(rep(2, 5), rep(1, 5))
basis("CHNOS+")
species(proteins, organisms)
a <- affinity(O2 = c(-100, -65))
layout(matrix(1:2), heights = c(1, 2))
e <- equilibrate(a)
diagram(e, ylim = c(-2.8, -1.6), names = organisms, col = col)
water.lines(e, col = 4)
title(main="Equilibrium activities of proteins, normalize = FALSE")
e <- equilibrate(a, normalize = TRUE)
diagram(e, ylim = c(-4, -2), names = organisms, col = col)
water.lines(e, col = 4)
title(main = "Equilibrium activities of proteins, normalize = TRUE")
```
Although it is below the stability limit of H~2~O (vertical dashed line), there
is an interesting convergence of the metastable equilibrium activities of some
proteins at low log *f*~O2~.
## Document history
* 2009-11-29 Initial version with CSG example, titled "Calculating relative abundances of proteins"
* 2012-09-30 Renamed to "Equilibrium in CHNOSZ"; remove activity comparisons and add maximum affinity method.
* 2015-11-08 Move previous material to Appendix and add sections on concepts, organization, examples, and applications; use knitr vignette engine.
* 2020-07-10 Simplify to concepts and examples (amino acids, proteins, normalization); convert document from LaTeX (Rnw) to R Markdown (Rmd).
## References
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/doc/equilibrium.Rmd
|
## ----setup, include=FALSE-----------------------------------------------------
options(width = 80)
## Use pngquant to optimize PNG images
library(knitr)
knit_hooks$set(pngquant = hook_pngquant)
pngquant <- "--speed=1 --quality=0-25"
if (!nzchar(Sys.which("pngquant"))) pngquant <- NULL
## Resolution settings
# Change this to TRUE to make high-resolution plots
# (default is FALSE to save time in CRAN checks)
hires <- nzchar(Sys.getenv("CHNOSZ_BUILD_LARGE_VIGNETTES"))
res1.lo <- 150
res1.hi <- 256
res1 <- if(hires) res1.hi else res1.lo
res2.lo <- 200
res2.hi <- 400
res2 <- if(hires) res2.hi else res2.lo
## logK with a thin space 20200627
logK <- "log <i>K</i>"
## Set dpi 20231129
knitr::opts_chunk$set(
dpi = if(nzchar(Sys.getenv("CHNOSZ_BUILD_LARGE_VIGNETTES"))) 100 else 72
)
## ----CHNOSZ_reset, include=FALSE----------------------------------------------
library(CHNOSZ)
reset()
## ----res, results = "asis", echo = FALSE--------------------------------------
cat("```")
cat("\n")
cat(paste0(if(hires) "# " else "", "res1 <- ", res1.lo))
cat("\n")
cat(paste0(if(hires) "" else "# ", "res1 <- ", res1.hi))
cat("\n")
cat(paste0(if(hires) "# " else "", "res2 <- ", res2.lo))
cat("\n")
cat(paste0(if(hires) "" else "# ", "res2 <- ", res2.hi))
cat("\n")
cat("```")
## ----mash, echo = 1:8, eval = FALSE-------------------------------------------
# par(mfrow = c(1, 2))
# basis("CHNOS+")
# species(c("CH4", "CO2", "HCO3-", "CO3-2"))
# aC <- affinity(pH = c(0, 14), O2 = c(-75, -60))
# dC <- diagram(aC, dx = c(0, 1, 0, 0), dy = c(0, 1, 0, 0))
# species(c("H2S", "HS-", "HSO4-", "SO4-2"))
# aS <- affinity(aC) # argument recall
# dS <- diagram(aS, add = TRUE, col = 4, col.names = 4, dx = c(0, -0.5, 0, 0))
# aCS <- mash(dC, dS)
# srt <- c(0, 0, 90, 0, 0, 0, 90, 0, 0, 0)
# cex.names <- c(1, 1, 0.8, 1, 1, 1, 1, 1, 1, 1)
# dy <- c(0, 0, 0, -0.2, 0, 0, 0, 0, 0, 0)
# diagram(aCS, srt = srt, cex.names = cex.names, dy = dy)
# legend("topright", legend = lTP(25, 1), bty = "n")
## ----mash, echo = 9:14, results = "hide", message = FALSE, fig.width = 10, fig.height = 5, out.width = "100%"----
par(mfrow = c(1, 2))
basis("CHNOS+")
species(c("CH4", "CO2", "HCO3-", "CO3-2"))
aC <- affinity(pH = c(0, 14), O2 = c(-75, -60))
dC <- diagram(aC, dx = c(0, 1, 0, 0), dy = c(0, 1, 0, 0))
species(c("H2S", "HS-", "HSO4-", "SO4-2"))
aS <- affinity(aC) # argument recall
dS <- diagram(aS, add = TRUE, col = 4, col.names = 4, dx = c(0, -0.5, 0, 0))
aCS <- mash(dC, dS)
srt <- c(0, 0, 90, 0, 0, 0, 90, 0, 0, 0)
cex.names <- c(1, 1, 0.8, 1, 1, 1, 1, 1, 1, 1)
dy <- c(0, 0, 0, -0.2, 0, 0, 0, 0, 0, 0)
diagram(aCS, srt = srt, cex.names = cex.names, dy = dy)
legend("topright", legend = lTP(25, 1), bty = "n")
## ----materials, message = FALSE, results = "hide"-----------------------------
## Formation energies (eV / atom) for solids from Materials API, e.g.
# from pymatgen import MPRester
# m = MPRester("USER_API_KEY")
# m.query(criteria={"task_id": "mp-1279742"}, properties=["formation_energy_per_atom"])
# mp-13, mp-1279742, mp-19306, mp-19770
#Fe.cr <- c(Fe = 0, FeO = -1.72803, Fe3O4 = -1.85868, Fe2O3 = -1.90736) # 20201109
Fe.cr <- c(Fe = 0, FeO = -1.72768, Fe3O4 = -1.85838, Fe2O3 = -1.90708) # 20210219
# mp-146, mp-18937, mp-1275946, mp-19094, mp-756395, mp-25279
#V.cr <- c(V = 0, V2O3 = -2.52849, V3O5 = -2.52574, VO2 = -2.48496, V3O7 = -2.32836, V2O5 = -2.29524) # 20201109
V.cr <- c(V = 0, V2O3 = -2.52787, V3O5 = -2.52516, VO2 = -2.48447, V3O7 = -2.32789, V2O5 = -2.29480) # 20210219
# Convert formation energies from eV / atom to eV / molecule
natom.Fe <- sapply(makeup(names(Fe.cr)), sum)
Fe.cr <- Fe.cr * natom.Fe
natom.V <- sapply(makeup(names(V.cr)), sum)
V.cr <- V.cr * natom.V
# Convert formation energies from eV / molecule to J / mol
eVtoJ <- function(eV) eV * 1.602176634e-19 * 6.02214076e23
Fe.cr <- eVtoJ(Fe.cr)
V.cr <- eVtoJ(V.cr)
# Gibbs energies of formation (J / mol) for aqueous species
# Most are from Wagman et al., 1982
Fe.aq <- 1000 * c("Fe+2" = -78.90, "Fe+3" = -4.7, "FeO2-2" = -295.3,
"FeOH+" = -277.4, "FeOH+2" = -229.41, "HFeO2-" = -377.7,
"Fe(OH)2+" = -438.0, "Fe(OH)3" = -659.3,
"FeO2-" = -368.2, # SSWS97
"FeO4-2" = -322.2 # Mis73
)
V.aq <- 1000 * c("VO+2" = -446.4, "VO2+" = -587.0, "VO3-" = -783.6, "VO4-3" = -899.0,
"V2O7-4" = -1719, "HVO4" = -745.1, "HVO4-2" = -974.8,
"VOH2O2+3" = -523.4, "VO2H2O2+" = -746.3, "V2HO7-3" = 1792.2, "V2H3O7-" = -1863.8,
"HV10O28-5" = -7702, "H2V10O28-4" = -7723
)
# Gibbs energies of formation (J / mol) for solids from Wagman et al., 1982
Fe3O4 <- 1000 * -1015.4 # magnetite
V3O5 <- 1000 * -1803
# Calculate correction for difference between reference and DFT energies (Persson et al., 2012)
Fe.corr <- (Fe.cr["Fe3O4"] - Fe3O4) / 3
V.corr <- (V.cr["V3O5"] - V3O5) / 2
# Apply correction to standard Gibbs energies of aqueous species (Persson et al., 2012)
nFe <- sapply(makeup(names(Fe.aq)), "[", "Fe")
Fe.aq <- Fe.aq + nFe * Fe.corr
nV <- sapply(makeup(names(V.aq)), "[", "V")
V.aq <- V.aq + nV * V.corr
# Add energies to OBIGT
# This function modifies OBIGT and returns the species indices of the affected species
modfun <- function(x, state, model = NULL) sapply(seq_along(x), function(i) {
# We explicitly set the units to Joules (this is the default as of CHNOSZ 2.0.0)
if(is.null(model)) mod.OBIGT(names(x)[i], formula = names(x)[i], state = state, E_units = "J", G = x[i])
else mod.OBIGT(names(x)[i], formula = names(x)[i], state = state, model = model, E_units = "J", G = x[i])
})
# We need model = "CGL" to override the Berman model for some minerals 20220919
iFe.cr <- modfun(Fe.cr, "cr", model = "CGL")
iFe.aq <- modfun(Fe.aq, "aq")
iV.cr <- modfun(V.cr, "cr", model = "CGL")
iV.aq <- modfun(V.aq, "aq")
# Formation energies (eV / atom) for bimetallic solids from Materials API
# mp-1335, mp-1079399, mp-866134, mp-558525, mp-504509 (triclinic FeVO4)
#FeV.cr <- c(FeV = -0.12928, FeV3 = -0.17128, Fe3V = -0.12854, Fe2V4O13 = -2.23833, FeVO4 = -1.75611) # 20201109
FeV.cr <- c(FeV = -0.12815, FeV3 = -0.17114, Fe3V = -0.12832, Fe2V4O13 = -2.23967, FeVO4 = -1.75573) # 20210219
# Convert energies and add to OBIGT
natom.FeV <- sapply(makeup(names(FeV.cr)), sum)
FeV.cr <- FeV.cr * natom.FeV
FeV.cr <- eVtoJ(FeV.cr)
iFeV.cr <- modfun(FeV.cr, "cr")
## ----mixing1, eval = FALSE, echo = 1:14---------------------------------------
# par(mfrow = c(1, 3))
# loga.Fe <- -5
# loga.V <- -5
# # Fe-O-H diagram
# basis(c("VO+2", "Fe+2", "H2O", "e-", "H+"))
# species(c(iFe.aq, iFe.cr))
# species(1:length(iFe.aq), loga.Fe)
# aFe <- affinity(pH = c(4, 10, res1), Eh = c(-1.5, 0, res1))
# dFe <- diagram(aFe, plot.it = FALSE)
# # V-O-H diagram
# species(c(iV.aq, iV.cr))
# species(1:length(iV.aq), loga.V)
# aV <- affinity(aFe) # argument recall
# dV <- diagram(aV, plot.it = FALSE)
#
# # Calculate affinities for bimetallic species
# species(iFeV.cr)
# aFeV <- affinity(aFe) # argument recall
# dFeV <- diagram(aFeV, plot.it = FALSE, bold = TRUE)
# # 1:1 mixture (Fe:V)
# a11 <- mix(dFe, dV, dFeV, c(1, 1))
# # Adjust labels 20210219
# iV2O3 <- info("V2O3")
# iFeO <- info("FeO", "cr")
# iFe3V <- info("Fe3V")
# srt <- rep(0, nrow(a11$species))
# srt[a11$species$ispecies == paste(iFeO, iV2O3, sep = ",")] <- 90
# srt[a11$species$ispecies == paste(iV2O3, iFe3V, sep = ",")] <- -13
# diagram(a11, min.area = 0.01, srt = srt)
# title("Fe:V = 1:1")
# label.figure(lTP(25, 1), xfrac = 0.12)
# # 1:3 mixture
# a13 <- mix(dFe, dV, dFeV, c(1, 3))
# srt <- rep(0, nrow(a13$species))
# srt[a13$species$ispecies == paste(iFeO, iV2O3, sep = ",")] <- 90
# srt[a13$species$ispecies == paste(iV2O3, iFe3V, sep = ",")] <- -13
# diagram(a13, min.area = 0.01, srt = srt)
# title("Fe:V = 1:3")
# # 1:5 mixture
# a15 <- mix(dFe, dV, dFeV, c(1, 5))
# iFeV3 <- info("FeV3")
# srt <- rep(0, nrow(a15$species))
# srt[a15$species$ispecies == paste(iFeO, iV2O3, sep = ",")] <- 90
# srt[a15$species$ispecies == paste(iV2O3, iFe3V, sep = ",")] <- -13
# srt[a15$species$ispecies == paste(iV2O3, iFeV3, sep = ",")] <- -13
# diagram(a15, min.area = 0.01, srt = srt)
# title("Fe:V = 1:5")
## ----mixing1, echo = 16:47, message = FALSE, results = "hide", fig.width = 9, fig.height = 3, out.width = "100%", out.extra='class="full-width"', pngquant = pngquant----
par(mfrow = c(1, 3))
loga.Fe <- -5
loga.V <- -5
# Fe-O-H diagram
basis(c("VO+2", "Fe+2", "H2O", "e-", "H+"))
species(c(iFe.aq, iFe.cr))
species(1:length(iFe.aq), loga.Fe)
aFe <- affinity(pH = c(4, 10, res1), Eh = c(-1.5, 0, res1))
dFe <- diagram(aFe, plot.it = FALSE)
# V-O-H diagram
species(c(iV.aq, iV.cr))
species(1:length(iV.aq), loga.V)
aV <- affinity(aFe) # argument recall
dV <- diagram(aV, plot.it = FALSE)
# Calculate affinities for bimetallic species
species(iFeV.cr)
aFeV <- affinity(aFe) # argument recall
dFeV <- diagram(aFeV, plot.it = FALSE, bold = TRUE)
# 1:1 mixture (Fe:V)
a11 <- mix(dFe, dV, dFeV, c(1, 1))
# Adjust labels 20210219
iV2O3 <- info("V2O3")
iFeO <- info("FeO", "cr")
iFe3V <- info("Fe3V")
srt <- rep(0, nrow(a11$species))
srt[a11$species$ispecies == paste(iFeO, iV2O3, sep = ",")] <- 90
srt[a11$species$ispecies == paste(iV2O3, iFe3V, sep = ",")] <- -13
diagram(a11, min.area = 0.01, srt = srt)
title("Fe:V = 1:1")
label.figure(lTP(25, 1), xfrac = 0.12)
# 1:3 mixture
a13 <- mix(dFe, dV, dFeV, c(1, 3))
srt <- rep(0, nrow(a13$species))
srt[a13$species$ispecies == paste(iFeO, iV2O3, sep = ",")] <- 90
srt[a13$species$ispecies == paste(iV2O3, iFe3V, sep = ",")] <- -13
diagram(a13, min.area = 0.01, srt = srt)
title("Fe:V = 1:3")
# 1:5 mixture
a15 <- mix(dFe, dV, dFeV, c(1, 5))
iFeV3 <- info("FeV3")
srt <- rep(0, nrow(a15$species))
srt[a15$species$ispecies == paste(iFeO, iV2O3, sep = ",")] <- 90
srt[a15$species$ispecies == paste(iV2O3, iFe3V, sep = ",")] <- -13
srt[a15$species$ispecies == paste(iV2O3, iFeV3, sep = ",")] <- -13
diagram(a15, min.area = 0.01, srt = srt)
title("Fe:V = 1:5")
## ----FeVO4, eval = FALSE, echo = 1:29-----------------------------------------
# layout(t(matrix(1:3)), widths = c(1, 1, 0.2))
# par(cex = 1)
# # Fe-bearing species
# basis(c("VO+2", "Fe+2", "H2O", "e-", "H+"))
# species(c(iFe.aq, iFe.cr))$name
# species(1:length(iFe.aq), loga.Fe)
# aFe <- affinity(pH = c(0, 14, res2), Eh = c(-1.5, 2, res2))
# dFe <- diagram(aFe, plot.it = FALSE)
# # V-bearing species
# species(c(iV.aq, iV.cr))$name
# species(1:length(iV.aq), loga.V)
# aV <- affinity(aFe) # argument recall
# dV <- diagram(aV, plot.it = FALSE)
# # Bimetallic species
# species(iFeV.cr)
# aFeV <- affinity(aFe) # argument recall
# dFeV <- diagram(aFeV, plot.it = FALSE, bold = TRUE)
# # 1:1 mixture (Fe:V)
# a11 <- mix(dFe, dV, dFeV, c(1, 1))
# # Adjust labels 20210219
# iV2O3 <- info("V2O3")
# iFe3V <- info("Fe3V")
# iVO4m3 <- info("VO4-3")
# iFe2O3 <- info("Fe2O3")
# srt <- rep(0, nrow(a11$species))
# srt[a11$species$ispecies == paste(iV2O3, iFe3V, sep = ",")] <- -13
# srt[a11$species$ispecies == paste(iFe2O3, iVO4m3, sep = ",")] <- 90
# d11 <- diagram(a11, min.area = 0.01, srt = srt)
# water.lines(d11, col = "orangered")
#
# # Calculate affinity of FeVO4
# species("FeVO4")
# aFeVO4 <- affinity(aFe) # argument recall
# # Calculate difference from stable species
# aFeVO4_vs_stable <- aFeVO4$values[[1]] - d11$predominant.values
# # Overlay lines from diagram on color map
# diagram(a11, fill = NA, names = FALSE, limit.water = FALSE)
# opar <- par(usr = c(0, 1, 0, 1))
# col <- rev(topo.colors(128)) # No hcl.colors() in R < 3.6.0
# if(getRversion() >= "3.6.0") col <- rev(hcl.colors(128, palette = "YlGnBu", alpha = 0.8))
# image(aFeVO4_vs_stable, col = col, add = TRUE)
# par(opar)
# diagram(a11, fill = NA, add = TRUE, names = FALSE)
# water.lines(d11, col = "orangered")
# thermo.axis()
#
# imax <- arrayInd(which.max(aFeVO4_vs_stable), dim(aFeVO4_vs_stable))
# pH <- d11$vals$pH[imax[1]]
# Eh <- d11$vals$Eh[imax[2]]
# points(pH, Eh, pch = 10, cex = 2, lwd = 2, col = "gold")
# stable <- d11$names[d11$predominant[imax]]
# text(pH, Eh, stable, adj = c(0.5, -1), cex = 1.2, col = "gold")
#
# # Make color scale 20210228
# par(mar = c(3, 0, 2.5, 2.7))
# plot.new()
# levels <- 1:length(col)
# plot.window(xlim = c(0, 1), ylim = range(levels), xaxs = "i", yaxs = "i")
# rect(0, levels[-length(levels)], 1, levels[-1L], col = rev(col), border = NA)
# box()
# # To get the limits, convert range of affinities to eV/atom
# arange <- rev(range(aFeVO4_vs_stable))
# # This gets us to J/mol
# Jrange <- convert(arange, "G")
# # And to eV/atom
# eVrange <- Jrange / 1.602176634e-19 / 6.02214076e23 / 6
# ylim <- formatC(eVrange, digits = 3, format = "f")
# axis(4, at = range(levels), labels = ylim)
# mtext(quote(Delta*italic(G)[pbx]*", eV/atom"), side = 4, las = 0, line = 1)
## ----FeVO4, echo = 31:44, message = FALSE, results = "hide", fig.width = 11, fig.height = 5, out.width = "100%", pngquant = pngquant----
layout(t(matrix(1:3)), widths = c(1, 1, 0.2))
par(cex = 1)
# Fe-bearing species
basis(c("VO+2", "Fe+2", "H2O", "e-", "H+"))
species(c(iFe.aq, iFe.cr))$name
species(1:length(iFe.aq), loga.Fe)
aFe <- affinity(pH = c(0, 14, res2), Eh = c(-1.5, 2, res2))
dFe <- diagram(aFe, plot.it = FALSE)
# V-bearing species
species(c(iV.aq, iV.cr))$name
species(1:length(iV.aq), loga.V)
aV <- affinity(aFe) # argument recall
dV <- diagram(aV, plot.it = FALSE)
# Bimetallic species
species(iFeV.cr)
aFeV <- affinity(aFe) # argument recall
dFeV <- diagram(aFeV, plot.it = FALSE, bold = TRUE)
# 1:1 mixture (Fe:V)
a11 <- mix(dFe, dV, dFeV, c(1, 1))
# Adjust labels 20210219
iV2O3 <- info("V2O3")
iFe3V <- info("Fe3V")
iVO4m3 <- info("VO4-3")
iFe2O3 <- info("Fe2O3")
srt <- rep(0, nrow(a11$species))
srt[a11$species$ispecies == paste(iV2O3, iFe3V, sep = ",")] <- -13
srt[a11$species$ispecies == paste(iFe2O3, iVO4m3, sep = ",")] <- 90
d11 <- diagram(a11, min.area = 0.01, srt = srt)
water.lines(d11, col = "orangered")
# Calculate affinity of FeVO4
species("FeVO4")
aFeVO4 <- affinity(aFe) # argument recall
# Calculate difference from stable species
aFeVO4_vs_stable <- aFeVO4$values[[1]] - d11$predominant.values
# Overlay lines from diagram on color map
diagram(a11, fill = NA, names = FALSE, limit.water = FALSE)
opar <- par(usr = c(0, 1, 0, 1))
col <- rev(topo.colors(128)) # No hcl.colors() in R < 3.6.0
if(getRversion() >= "3.6.0") col <- rev(hcl.colors(128, palette = "YlGnBu", alpha = 0.8))
image(aFeVO4_vs_stable, col = col, add = TRUE)
par(opar)
diagram(a11, fill = NA, add = TRUE, names = FALSE)
water.lines(d11, col = "orangered")
thermo.axis()
imax <- arrayInd(which.max(aFeVO4_vs_stable), dim(aFeVO4_vs_stable))
pH <- d11$vals$pH[imax[1]]
Eh <- d11$vals$Eh[imax[2]]
points(pH, Eh, pch = 10, cex = 2, lwd = 2, col = "gold")
stable <- d11$names[d11$predominant[imax]]
text(pH, Eh, stable, adj = c(0.5, -1), cex = 1.2, col = "gold")
# Make color scale 20210228
par(mar = c(3, 0, 2.5, 2.7))
plot.new()
levels <- 1:length(col)
plot.window(xlim = c(0, 1), ylim = range(levels), xaxs = "i", yaxs = "i")
rect(0, levels[-length(levels)], 1, levels[-1L], col = rev(col), border = NA)
box()
# To get the limits, convert range of affinities to eV/atom
arange <- rev(range(aFeVO4_vs_stable))
# This gets us to J/mol
Jrange <- convert(arange, "G")
# And to eV/atom
eVrange <- Jrange / 1.602176634e-19 / 6.02214076e23 / 6
ylim <- formatC(eVrange, digits = 3, format = "f")
axis(4, at = range(levels), labels = ylim)
mtext(quote(Delta*italic(G)[pbx]*", eV/atom"), side = 4, las = 0, line = 1)
## ----Gpbx_min, echo = 2:8, message = FALSE, fig.keep = "none"-----------------
plot(1:10) # so we can run "points" in this chunk
imax <- arrayInd(which.max(aFeVO4_vs_stable), dim(aFeVO4_vs_stable))
pH <- d11$vals$pH[imax[1]]
Eh <- d11$vals$Eh[imax[2]]
points(pH, Eh, pch = 10, cex = 2, lwd = 2, col = "gold")
stable <- d11$names[d11$predominant[imax]]
text(pH, Eh, stable, adj = c(0.3, 2), cex = 1.2, col = "gold")
(Apbx <- range(aFeVO4_vs_stable[d11$predominant == d11$predominant[imax]]))
## ----hull, message = FALSE----------------------------------------------------
b <- basis(c("Fe2O3", "Fe2V4O13", "O2"))
J_mol <- subcrt("FeVO4", 1, T = 25)$out$G
stopifnot(all.equal(rep(convert(J_mol, "logK"), 2), Apbx))
eV_mol <- J_mol / 1.602176634e-19
eV_atom <- eV_mol / 6.02214076e23 / 6
round(eV_atom, 3)
stopifnot(round(eV_atom, 3) == 0.415)
## ----reset, message = FALSE---------------------------------------------------
reset()
## ----stack1_1, results = "hide", message = FALSE------------------------------
logaH2S <- -2
T <- 200
pH <- c(0, 14, res2)
O2 <- c(-48, -33, res2)
basis(c("Cu+", "pyrite", "H2S", "oxygen", "H2O", "H+"))
basis("H2S", logaH2S)
S.aq <- c("H2S", "HS-", "HSO4-", "SO4-2")
Fe.cr <- c("pyrite", "pyrrhotite", "magnetite", "hematite")
Fe.abbrv <- c("Py", "Po", "Mag", "Hem")
## ----stack1_2, eval = FALSE, echo = 1:4---------------------------------------
# species(Fe.cr)
# mFe <- mosaic(S.aq, pH = pH, O2 = O2, T = T)
# diagram(mFe$A.bases, lty = 2, col = 4, col.names = 4, italic = TRUE, dx = c(0, 1, 0, 0), dy = c(-1.5, 0, 1, 0))
# dFe <- diagram(mFe$A.species, add = TRUE, lwd = 2, names = Fe.abbrv, dx = c(0, 0.5, 0, 0), dy = c(-1, 0, 0.5, 0))
# FeCu.cr <- c("chalcopyrite", "bornite")
# Cu.cr <- c("copper", "cuprite", "tenorite", "chalcocite", "covellite")
# FeCu.abbrv <- c("Ccp", "Bn", "Cu", "Cpr", "Tnr", "Cct", "Cv")
# species(c(FeCu.cr, Cu.cr))
# mFeCu <- mosaic(list(S.aq, Fe.cr), pH = pH, O2 = O2,
# T = T, stable = list(NULL, dFe$predominant))
# col <- c("#FF8C00", rep(2, 6))
# lwd <- c(2, 1, 1, 1, 1, 1, 1)
# dy = c(0, 0, 0, 0, 0, 1, 0)
# diagram(mFeCu$A.species, add = TRUE, col = col, lwd = lwd, col.names = col, bold = TRUE, names = FeCu.abbrv, dy = dy)
# TPS <- c(describe.property(c("T", "P"), c(T, "Psat")), expression(sum(S) == 0.01*m))
# legend("topright", TPS, bty = "n")
# title("Cu-Fe-S-O-H (minerals only)", font.main = 1)
## ----stack1_2, echo=5:17, results = "hide", message = FALSE, fig.width = 6, fig.height = 5, out.width = "75%", fig.align = "center", pngquant = pngquant----
species(Fe.cr)
mFe <- mosaic(S.aq, pH = pH, O2 = O2, T = T)
diagram(mFe$A.bases, lty = 2, col = 4, col.names = 4, italic = TRUE, dx = c(0, 1, 0, 0), dy = c(-1.5, 0, 1, 0))
dFe <- diagram(mFe$A.species, add = TRUE, lwd = 2, names = Fe.abbrv, dx = c(0, 0.5, 0, 0), dy = c(-1, 0, 0.5, 0))
FeCu.cr <- c("chalcopyrite", "bornite")
Cu.cr <- c("copper", "cuprite", "tenorite", "chalcocite", "covellite")
FeCu.abbrv <- c("Ccp", "Bn", "Cu", "Cpr", "Tnr", "Cct", "Cv")
species(c(FeCu.cr, Cu.cr))
mFeCu <- mosaic(list(S.aq, Fe.cr), pH = pH, O2 = O2,
T = T, stable = list(NULL, dFe$predominant))
col <- c("#FF8C00", rep(2, 6))
lwd <- c(2, 1, 1, 1, 1, 1, 1)
dy = c(0, 0, 0, 0, 0, 1, 0)
diagram(mFeCu$A.species, add = TRUE, col = col, lwd = lwd, col.names = col, bold = TRUE, names = FeCu.abbrv, dy = dy)
TPS <- c(describe.property(c("T", "P"), c(T, "Psat")), expression(sum(S) == 0.01*m))
legend("topright", TPS, bty = "n")
title("Cu-Fe-S-O-H (minerals only)", font.main = 1)
## ----stack2, eval = FALSE-----------------------------------------------------
# # Define system
# pH <- c(0, 14, res2)
# O2 <- c(-48, -33, res2)
# T <- 200
# logmS <- -2
# m_NaCl <- 0.1
# logm_aq <- -6 # for both Fe- and Cu-bearing aq species
# # Basis species
# S.aq <- c("H2S", "HS-", "HSO4-", "SO4-2")
# # Minerals
# Fe.cr <- c("pyrite", "pyrrhotite", "magnetite", "hematite")
# Fe.abbrv <- c("Py", "Po", "Mag", "Hem")
# FeCu.cr <- c("chalcopyrite", "bornite")
# Cu.cr <- c("copper", "cuprite", "tenorite", "chalcocite", "covellite")
# FeCu.abbrv <- c("Ccp", "Bn", "Cu", "Cpr", "Tnr", "Cct", "Cv")
# # Aqueous species
# iFe.aq <- retrieve("Fe", c("S", "O", "H", "Cl"), "aq")
# Fe.aq <- info(iFe.aq)$name
# iCu.aq <- retrieve("Cu", c("S", "O", "H", "Cl"), "aq")
# Cu.aq <- info(iCu.aq)$name
# # Expressions for making the legend
# TPexpr <- describe.property(c("T", "P"), c(T, "Psat"))
# Sexpr <- as.expression(bquote(sum(S) == .(10^logmS)*m))
# NaClexpr <- as.expression(bquote(NaCl == .(m_NaCl)*m))
# aqexpr <- as.expression(bquote("("*aq*")"[italic(i)] == 10^.(logm_aq)*m))
#
# # Setup basis species
# basis(c("Cu+", "pyrite", "H2S", "oxygen", "H2O", "H+", "Cl-"))
# basis("H2S", logmS)
# nacl <- NaCl(m_tot = m_NaCl, T = T, P = "Psat")
# basis("Cl-", log10(nacl$m_Cl))
# # Fe-bearing minerals
# species(Fe.cr)
# # Add aqueous species 20210220
# species(iFe.aq, logm_aq, add = TRUE)
# mFe <- mosaic(S.aq, pH = pH, O2 = O2, T = T, IS = nacl$IS)
# # Start plot with just the fields for transparency effect
# dFe <- diagram(mFe$A.species, lwd = 0, names = FALSE)
#
# # Cu-bearing minerals
# species(c(FeCu.cr, Cu.cr))
# # Add aqueous species 20210220
# species(iCu.aq, logm_aq, add = TRUE)
#
# ## Mosaic with all Fe species as basis species
# #mFeCu <- mosaic(list(S.aq, c(Fe.cr, Fe.aq)), pH = pH, O2 = O2, T = T, stable = list(NULL, dFe$predominant))
# # Use only predominant Fe species as basis species (to speed up calculation) 20210224
# predom <- dFe$predominant
# ipredom <- sort(unique(as.numeric(predom)))
# for(i in seq_along(ipredom)) predom[dFe$predominant == ipredom[i]] <- i
# Fe.predom <- c(Fe.cr, Fe.aq)[ipredom]
# # Use loga_aq argument to control the activity of aqueous species in mosaic calculation 20220722
# # c(NA, logm_aq) means to use:
# # basis()'s value for logact of aqueous S species
# # logm_aq for logact of aqueous Fe species
# mFeCu <- mosaic(list(S.aq, Fe.predom), pH = pH, O2 = O2, T = T, stable = list(NULL, predom), IS = nacl$IS, loga_aq = c(NA, logm_aq))
#
# # Adjust labels
# bold <- c(rep(TRUE, length(FeCu.abbrv)), rep(FALSE, length(Cu.aq)))
# names <- c(FeCu.abbrv, Cu.aq)
# srt <- dx <- dy <- rep(0, length(names))
# cex <- rep(1, length(names))
# dx[names == "Cu"] <- -1.5
# dx[names == "Bn"] <- 1.4
# dx[names == "CuHS"] <- 1
# dx[names == "Cu+"] <- -0.5
# dy[names == "Cu"] <- 3
# dx[names == "Cct"] <- -2
# dy[names == "Cct"] <- 4
# dy[names == "CuHS"] <- 1
# dy[names == "Bn"] <- -0.9
# dx[names == "CuCl2-"] <- -1
# dy[names == "CuCl2-"] <- 2
# cex[names == "Bn"] <- 0.8
# srt[names == "Bn"] <- 85
# # Highlight Ccp field
# col.names <- col <- rep(2, nrow(mFeCu$A.species$species))
# col[1] <- "#FF8C00"
# col.names[1] <- "#FF8C00"
# lwd <- rep(1, nrow(mFeCu$A.species$species))
# lwd[1] <- 2
# diagram(mFeCu$A.species, add = TRUE, lwd = lwd, col = col, col.names = col.names, names = names, bold = bold, dx = dx, dy = dy, cex.names = cex, srt = srt)
# # Add second Cu label
# text(12.3, -47, "Cu", col = 2, font = 2)
#
# # Plot the Fe-system lines and names "on top" so they are not covered by fill colors
# diagram(mFe$A.bases, add = TRUE, lty = 2, col = 4, names = FALSE, fill = NA)
# bold <- c(rep(TRUE, length(Fe.abbrv)), rep(FALSE, length(Fe.aq)))
# names <- c(Fe.abbrv, Fe.aq)
# srt <- dx <- dy <- rep(0, length(names))
# cex <- rep(1, length(names))
# dy[names == "Hem"] <- 0.5
# dy[names == "Mag"] <- -0.8
# dx[names == "Hem"] <- -0.5
# dx[names == "Mag"] <- 0.25
# dx[names == "Fe+2"] <- 0.5
# dx[names == "FeO2-"] <- 1
# dy[names == "FeO2-"] <- -3
# dx[names == "HFeO2-"] <- -0.5
# dy[names == "HFeO2-"] <- 1
# srt[names == "Mag"] <- 83
# srt[names == "FeSO4"] <- 90
# diagram(mFe$A.species, add = TRUE, lwd = 2, names = names, bold = bold, dx = dx, dy = dy, cex.names = cex, srt = srt, fill = NA)
# legend("topright", c(TPexpr, Sexpr, NaClexpr, aqexpr), bty = "n")
# title("Cu-Fe-S-O-H-Cl (minerals and aqueous species)", font.main = 1)
#
# # Restore default OBIGT database
# OBIGT()
## ----stack2, echo = FALSE, results = "hide", message = FALSE, fig.width = 6, fig.height = 5, out.width = "75%", fig.align = "center", pngquant = pngquant----
# Define system
pH <- c(0, 14, res2)
O2 <- c(-48, -33, res2)
T <- 200
logmS <- -2
m_NaCl <- 0.1
logm_aq <- -6 # for both Fe- and Cu-bearing aq species
# Basis species
S.aq <- c("H2S", "HS-", "HSO4-", "SO4-2")
# Minerals
Fe.cr <- c("pyrite", "pyrrhotite", "magnetite", "hematite")
Fe.abbrv <- c("Py", "Po", "Mag", "Hem")
FeCu.cr <- c("chalcopyrite", "bornite")
Cu.cr <- c("copper", "cuprite", "tenorite", "chalcocite", "covellite")
FeCu.abbrv <- c("Ccp", "Bn", "Cu", "Cpr", "Tnr", "Cct", "Cv")
# Aqueous species
iFe.aq <- retrieve("Fe", c("S", "O", "H", "Cl"), "aq")
Fe.aq <- info(iFe.aq)$name
iCu.aq <- retrieve("Cu", c("S", "O", "H", "Cl"), "aq")
Cu.aq <- info(iCu.aq)$name
# Expressions for making the legend
TPexpr <- describe.property(c("T", "P"), c(T, "Psat"))
Sexpr <- as.expression(bquote(sum(S) == .(10^logmS)*m))
NaClexpr <- as.expression(bquote(NaCl == .(m_NaCl)*m))
aqexpr <- as.expression(bquote("("*aq*")"[italic(i)] == 10^.(logm_aq)*m))
# Setup basis species
basis(c("Cu+", "pyrite", "H2S", "oxygen", "H2O", "H+", "Cl-"))
basis("H2S", logmS)
nacl <- NaCl(m_tot = m_NaCl, T = T, P = "Psat")
basis("Cl-", log10(nacl$m_Cl))
# Fe-bearing minerals
species(Fe.cr)
# Add aqueous species 20210220
species(iFe.aq, logm_aq, add = TRUE)
mFe <- mosaic(S.aq, pH = pH, O2 = O2, T = T, IS = nacl$IS)
# Start plot with just the fields for transparency effect
dFe <- diagram(mFe$A.species, lwd = 0, names = FALSE)
# Cu-bearing minerals
species(c(FeCu.cr, Cu.cr))
# Add aqueous species 20210220
species(iCu.aq, logm_aq, add = TRUE)
## Mosaic with all Fe species as basis species
#mFeCu <- mosaic(list(S.aq, c(Fe.cr, Fe.aq)), pH = pH, O2 = O2, T = T, stable = list(NULL, dFe$predominant))
# Use only predominant Fe species as basis species (to speed up calculation) 20210224
predom <- dFe$predominant
ipredom <- sort(unique(as.numeric(predom)))
for(i in seq_along(ipredom)) predom[dFe$predominant == ipredom[i]] <- i
Fe.predom <- c(Fe.cr, Fe.aq)[ipredom]
# Use loga_aq argument to control the activity of aqueous species in mosaic calculation 20220722
# c(NA, logm_aq) means to use:
# basis()'s value for logact of aqueous S species
# logm_aq for logact of aqueous Fe species
mFeCu <- mosaic(list(S.aq, Fe.predom), pH = pH, O2 = O2, T = T, stable = list(NULL, predom), IS = nacl$IS, loga_aq = c(NA, logm_aq))
# Adjust labels
bold <- c(rep(TRUE, length(FeCu.abbrv)), rep(FALSE, length(Cu.aq)))
names <- c(FeCu.abbrv, Cu.aq)
srt <- dx <- dy <- rep(0, length(names))
cex <- rep(1, length(names))
dx[names == "Cu"] <- -1.5
dx[names == "Bn"] <- 1.4
dx[names == "CuHS"] <- 1
dx[names == "Cu+"] <- -0.5
dy[names == "Cu"] <- 3
dx[names == "Cct"] <- -2
dy[names == "Cct"] <- 4
dy[names == "CuHS"] <- 1
dy[names == "Bn"] <- -0.9
dx[names == "CuCl2-"] <- -1
dy[names == "CuCl2-"] <- 2
cex[names == "Bn"] <- 0.8
srt[names == "Bn"] <- 85
# Highlight Ccp field
col.names <- col <- rep(2, nrow(mFeCu$A.species$species))
col[1] <- "#FF8C00"
col.names[1] <- "#FF8C00"
lwd <- rep(1, nrow(mFeCu$A.species$species))
lwd[1] <- 2
diagram(mFeCu$A.species, add = TRUE, lwd = lwd, col = col, col.names = col.names, names = names, bold = bold, dx = dx, dy = dy, cex.names = cex, srt = srt)
# Add second Cu label
text(12.3, -47, "Cu", col = 2, font = 2)
# Plot the Fe-system lines and names "on top" so they are not covered by fill colors
diagram(mFe$A.bases, add = TRUE, lty = 2, col = 4, names = FALSE, fill = NA)
bold <- c(rep(TRUE, length(Fe.abbrv)), rep(FALSE, length(Fe.aq)))
names <- c(Fe.abbrv, Fe.aq)
srt <- dx <- dy <- rep(0, length(names))
cex <- rep(1, length(names))
dy[names == "Hem"] <- 0.5
dy[names == "Mag"] <- -0.8
dx[names == "Hem"] <- -0.5
dx[names == "Mag"] <- 0.25
dx[names == "Fe+2"] <- 0.5
dx[names == "FeO2-"] <- 1
dy[names == "FeO2-"] <- -3
dx[names == "HFeO2-"] <- -0.5
dy[names == "HFeO2-"] <- 1
srt[names == "Mag"] <- 83
srt[names == "FeSO4"] <- 90
diagram(mFe$A.species, add = TRUE, lwd = 2, names = names, bold = bold, dx = dx, dy = dy, cex.names = cex, srt = srt, fill = NA)
legend("topright", c(TPexpr, Sexpr, NaClexpr, aqexpr), bty = "n")
title("Cu-Fe-S-O-H-Cl (minerals and aqueous species)", font.main = 1)
# Restore default OBIGT database
OBIGT()
## ----stack2.refs, message = FALSE---------------------------------------------
minerals <- list(Fe.cr = Fe.cr, Cu.cr = Cu.cr, FeCu.cr = FeCu.cr)
aqueous <- list(S.aq = S.aq, Fe.aq = Fe.aq, Cu.aq = Cu.aq)
allspecies <- c(minerals, aqueous)
iall <- lapply(allspecies, info)
allkeys <- lapply(iall, function(x) thermo.refs(x)$key)
allkeys
## ----stack2.cite, results = "asis"--------------------------------------------
allyears <- lapply(iall, function(x) thermo.refs(x)$year)
o <- order(unlist(allyears))
keys <- gsub("\\..*", "", unique(unlist(allkeys)[o]))
cat(paste(paste0("@", keys), collapse = "; "))
## ----mixing2, eval = FALSE----------------------------------------------------
# par(mfrow = c(2, 2))
#
# logaH2S <- -2
# T <- 200
# pH <- c(0, 14)
# O2 <- c(-60, -25)
# basis(c("Cu+", "Fe+2", "H2S", "oxygen", "H2O", "H+"))
# basis("H2S", logaH2S)
#
# S.aq <- c("H2S", "HS-", "HSO4-", "SO4-2")
# Fe.cr <- c("pyrite", "pyrrhotite", "magnetite", "hematite")
# Cu.cr <- c("copper", "cuprite", "tenorite", "chalcocite", "covellite")
# FeCu.cr <- c("chalcopyrite", "bornite")
#
# species(Fe.cr)
# mFe <- mosaic(S.aq, pH = pH, O2 = O2, T = T)
# diagram(mFe$A.bases, lty = 2, col = 4, col.names = 4, italic = TRUE, dx = c(0, 1, 0, 0), dy = c(-1, 0, -2, 0))
# names <- info(info(Fe.cr))$abbrv
# dFe <- diagram(mFe$A.species, add = TRUE, names = names)
#
# species(Cu.cr)
# mCu <- mosaic(S.aq, pH = pH, O2 = O2, T = T)
# names <- info(info(Cu.cr))$abbrv
# col.names <- rep(2, length(names))
# col.names[1] <- 0
# dCu <- diagram(mCu$A.species, add = TRUE, col = 2, col.names = col.names, names = names)
# text(12, -55, "Cu", col = 2)
# legend("topright", legend = lTP(T, "Psat"), bty = "n")
# title(paste("Fe-S-O-H and Cu-S-O-H; Total S =", 10^logaH2S, "m"))
#
# species(FeCu.cr)
# mFeCu <- mosaic(S.aq, pH = pH, O2 = O2, T = T)
# names <- info(info(FeCu.cr))$abbrv
# dFeCu <- diagram(mFeCu$A.species, plot.it = FALSE, names = names)
#
# fill <- function(a) {
# ifelse(grepl("Ccp", a$species$name), "#FF8C0088",
# ifelse(grepl("Bn", a$species$name), "#DC143C88", NA)
# )}
# srt <- function(a) ifelse(a$species$name %in% c("Mag+Bn", "Mag+Ccp"), 80, 0)
# cex.names <- function(a) ifelse(a$species$name %in% c("Mag+Bn", "Mag+Ccp", "Mag+Cct"), 0.8, 1)
# dx <- function(a) sapply(a$species$name, switch, "Mag+Bn" = 0.15, "Mag+Cct" = 0.5, 0)
# dy <- function(a) sapply(a$species$name, switch, "Py+Bn" = -1, "Po+Bn" = -0.8, "Po+Cu" = -0.8, "Mag+Ccp" = -1, 0)
#
# a11 <- mix(dFe, dCu, dFeCu)
# diagram(a11, fill = fill(a11), srt = srt(a11), min.area = 0.01, dx = dx(a11), dy = dy(a11), cex.names = cex.names(a11))
# title("Fe:Cu = 1:1")
#
# a21 <- mix(dFe, dCu, dFeCu, c(2, 1))
# diagram(a21, fill = fill(a21), srt = srt(a21), min.area = 0.01, dx = dx(a21), dy = dy(a21), cex.names = cex.names(a21))
# title("Fe:Cu = 2:1")
#
# a12 <- mix(dFe, dCu, dFeCu, c(1, 2))
# diagram(a12, fill = fill(a12), srt = srt(a12), min.area = 0.01, dx = dx(a12), dy = dy(a12), cex.names = cex.names(a12))
# title("Fe:Cu = 1:2")
## ----mixing2, echo = FALSE, results = "hide", message = FALSE, fig.width = 8, fig.height = 6.5, out.width = "100%", pngquant = pngquant----
par(mfrow = c(2, 2))
logaH2S <- -2
T <- 200
pH <- c(0, 14)
O2 <- c(-60, -25)
basis(c("Cu+", "Fe+2", "H2S", "oxygen", "H2O", "H+"))
basis("H2S", logaH2S)
S.aq <- c("H2S", "HS-", "HSO4-", "SO4-2")
Fe.cr <- c("pyrite", "pyrrhotite", "magnetite", "hematite")
Cu.cr <- c("copper", "cuprite", "tenorite", "chalcocite", "covellite")
FeCu.cr <- c("chalcopyrite", "bornite")
species(Fe.cr)
mFe <- mosaic(S.aq, pH = pH, O2 = O2, T = T)
diagram(mFe$A.bases, lty = 2, col = 4, col.names = 4, italic = TRUE, dx = c(0, 1, 0, 0), dy = c(-1, 0, -2, 0))
names <- info(info(Fe.cr))$abbrv
dFe <- diagram(mFe$A.species, add = TRUE, names = names)
species(Cu.cr)
mCu <- mosaic(S.aq, pH = pH, O2 = O2, T = T)
names <- info(info(Cu.cr))$abbrv
col.names <- rep(2, length(names))
col.names[1] <- 0
dCu <- diagram(mCu$A.species, add = TRUE, col = 2, col.names = col.names, names = names)
text(12, -55, "Cu", col = 2)
legend("topright", legend = lTP(T, "Psat"), bty = "n")
title(paste("Fe-S-O-H and Cu-S-O-H; Total S =", 10^logaH2S, "m"))
species(FeCu.cr)
mFeCu <- mosaic(S.aq, pH = pH, O2 = O2, T = T)
names <- info(info(FeCu.cr))$abbrv
dFeCu <- diagram(mFeCu$A.species, plot.it = FALSE, names = names)
fill <- function(a) {
ifelse(grepl("Ccp", a$species$name), "#FF8C0088",
ifelse(grepl("Bn", a$species$name), "#DC143C88", NA)
)}
srt <- function(a) ifelse(a$species$name %in% c("Mag+Bn", "Mag+Ccp"), 80, 0)
cex.names <- function(a) ifelse(a$species$name %in% c("Mag+Bn", "Mag+Ccp", "Mag+Cct"), 0.8, 1)
dx <- function(a) sapply(a$species$name, switch, "Mag+Bn" = 0.15, "Mag+Cct" = 0.5, 0)
dy <- function(a) sapply(a$species$name, switch, "Py+Bn" = -1, "Po+Bn" = -0.8, "Po+Cu" = -0.8, "Mag+Ccp" = -1, 0)
a11 <- mix(dFe, dCu, dFeCu)
diagram(a11, fill = fill(a11), srt = srt(a11), min.area = 0.01, dx = dx(a11), dy = dy(a11), cex.names = cex.names(a11))
title("Fe:Cu = 1:1")
a21 <- mix(dFe, dCu, dFeCu, c(2, 1))
diagram(a21, fill = fill(a21), srt = srt(a21), min.area = 0.01, dx = dx(a21), dy = dy(a21), cex.names = cex.names(a21))
title("Fe:Cu = 2:1")
a12 <- mix(dFe, dCu, dFeCu, c(1, 2))
diagram(a12, fill = fill(a12), srt = srt(a12), min.area = 0.01, dx = dx(a12), dy = dy(a12), cex.names = cex.names(a12))
title("Fe:Cu = 1:2")
## ----stack3, eval = FALSE-----------------------------------------------------
# T <- 125
# layout(matrix(c(1, 2, 3, 3), nrow = 2), widths = c(1, 1.5))
#
# # Fe-S-O-H diagram
# basis(c("copper", "hematite", "S2", "oxygen", "H2O", "H+", "Cl-"))
# bFe <- species(c("hematite", "magnetite", "pyrite"))$name
# aFe <- affinity(S2 = c(-34, -10, res1), O2 = c(-55, -40, res1), T = T)
# # Order species by a function of composition to make colors
# oFe <- order(aFe$species$S2 - aFe$species$O2)
# fill <- terrain.colors(length(oFe), alpha = 0.2)[oFe]
# abbrv <- info(aFe$species$ispecies)$abbrv
# dFe <- diagram(aFe, names = abbrv, fill = fill)
# title("Fe-S-O-H")
#
# # Cu-Fe-S-O-H diagram based on reactions with the
# # stable Fe-bearing minerals (mosaic stack)
# bCu <- species(c("copper", "chalcocite", "covellite", "chalcopyrite", "bornite"))$name
# mCu <- mosaic(bFe, S2 = c(-34, -10, res1), O2 = c(-55, -40, res1),
# T = T, stable = list(dFe$predominant))
# oCu <- order(mCu$A.species$species$S2 - mCu$A.species$species$O2)
# fill <- terrain.colors(length(oCu), alpha = 0.2)[oCu]
# abbrv <- info(mCu$A.species$species$ispecies)$abbrv
# dCu <- diagram(mCu$A.species, names = abbrv, fill = fill, dx = c(0, 0, 0, 0, 1.8))
# title("Cu-Fe-S-O-H")
#
# # Mash the diagrams and adjust labels
# aFeCu <- mash(dFe, dCu)
# names <- aFeCu$species$name
# dx <- dy <- srt <- rep(0, length(names))
# cex <- rep(1, length(names))
# cex[names %in% c("Hem+Ccp", "Hem+Cv")] <- 0.8
# srt[names %in% c("Mag+Cu", "Hem+Cu")] <- 90
# srt[names %in% c("Mag+Bn", "Hem+Bn")] <- 63
# srt[names %in% c("Mag+Ccp", "Hem+Ccp")] <- 68
# srt[names %in% c("Py+Bn", "Py+Cv")] <- 90
# dx[names == "Hem+Ccp"] <- -0.4
# dy[names == "Hem+Ccp"] <- -0.5
# oFeCu <- order(aFeCu$species$S2 - aFeCu$species$O2)
# fill <- terrain.colors(length(oFeCu), alpha = 0.2)[oFeCu]
# diagram(aFeCu, cex.names = cex, srt = srt, dx = dx, dy = dy, fill = fill)
# legend("topleft", legend = lTP(T, "Psat"), bg = "white")
# title("Cu-Fe-S-O-H")
## ----stack3, echo = FALSE, results = "hide", message = FALSE, fig.width = 6, fig.height = 4, out.width = "100%", pngquant = pngquant----
T <- 125
layout(matrix(c(1, 2, 3, 3), nrow = 2), widths = c(1, 1.5))
# Fe-S-O-H diagram
basis(c("copper", "hematite", "S2", "oxygen", "H2O", "H+", "Cl-"))
bFe <- species(c("hematite", "magnetite", "pyrite"))$name
aFe <- affinity(S2 = c(-34, -10, res1), O2 = c(-55, -40, res1), T = T)
# Order species by a function of composition to make colors
oFe <- order(aFe$species$S2 - aFe$species$O2)
fill <- terrain.colors(length(oFe), alpha = 0.2)[oFe]
abbrv <- info(aFe$species$ispecies)$abbrv
dFe <- diagram(aFe, names = abbrv, fill = fill)
title("Fe-S-O-H")
# Cu-Fe-S-O-H diagram based on reactions with the
# stable Fe-bearing minerals (mosaic stack)
bCu <- species(c("copper", "chalcocite", "covellite", "chalcopyrite", "bornite"))$name
mCu <- mosaic(bFe, S2 = c(-34, -10, res1), O2 = c(-55, -40, res1),
T = T, stable = list(dFe$predominant))
oCu <- order(mCu$A.species$species$S2 - mCu$A.species$species$O2)
fill <- terrain.colors(length(oCu), alpha = 0.2)[oCu]
abbrv <- info(mCu$A.species$species$ispecies)$abbrv
dCu <- diagram(mCu$A.species, names = abbrv, fill = fill, dx = c(0, 0, 0, 0, 1.8))
title("Cu-Fe-S-O-H")
# Mash the diagrams and adjust labels
aFeCu <- mash(dFe, dCu)
names <- aFeCu$species$name
dx <- dy <- srt <- rep(0, length(names))
cex <- rep(1, length(names))
cex[names %in% c("Hem+Ccp", "Hem+Cv")] <- 0.8
srt[names %in% c("Mag+Cu", "Hem+Cu")] <- 90
srt[names %in% c("Mag+Bn", "Hem+Bn")] <- 63
srt[names %in% c("Mag+Ccp", "Hem+Ccp")] <- 68
srt[names %in% c("Py+Bn", "Py+Cv")] <- 90
dx[names == "Hem+Ccp"] <- -0.4
dy[names == "Hem+Ccp"] <- -0.5
oFeCu <- order(aFeCu$species$S2 - aFeCu$species$O2)
fill <- terrain.colors(length(oFeCu), alpha = 0.2)[oFeCu]
diagram(aFeCu, cex.names = cex, srt = srt, dx = dx, dy = dy, fill = fill)
legend("topleft", legend = lTP(T, "Psat"), bg = "white")
title("Cu-Fe-S-O-H")
## ----solubility, eval = FALSE-------------------------------------------------
# par(mfrow = c(1, 3))
# basis("pH", 6)
# # Estimate the molality of Cl for ca. 80,000 mg/kg solution (Table 2 of Sverjensky, 1987)
# m_tot <- 80000 / mass("Cl") / 1000
# calc <- NaCl(T = T, m_tot = m_tot)
# # Use log molality here, not log activity, because
# # activity coefficients are calculated by setting IS below
# basis("Cl-", log10(calc$m_Cl))
# # Initial setup: dissolve a single mineral to form aqueous Cu complexes
# species("copper")
# iaq <- retrieve("Cu", c("O", "H", "Cl", "S"), "aq")
#
# # Function to calculate solubility of Cu for stable assemblages of Fe and Cu minerals
# # (i.e. equilibrium is imposed with all of these minerals, not only Cu(s))
# mfun <- function() {
# s <- solubility(iaq, bases = list(bFe, bCu), S2 = c(-34, -10, res1), O2 = c(-55, -40, res1),
# T = T, IS = calc$IS, stable = list(dFe$predominant, dCu$predominant))
# s <- convert(s, "ppm")
# diagram(aFeCu, names = NA, col = "gray", fill = fill)
# diagram(s, type = "loga.balance", levels = 10^(-3:3), add = TRUE)
# diagram(s, type = "loga.balance", levels = 35, add = TRUE, lwd = 3, col = 6, contour.method = NA)
# }
# # DIAGRAM 1
# mfun()
# title("Cu (ppm)")
#
# # Calculate logK for CuCl2- dissociation at 125 °C
# logK <- subcrt(c("CuCl2-", "Cu+", "Cl-"), c(-1, 1, 2), T = T)$out$logK
# # Sverjensky (1987) used Helgeson (1969) value, which is ca. -5.2
# dlogK <- logK - -5.2
# # Calculate the difference in ΔG° corresponding to this logK difference
# dG_J <- convert(dlogK, "G", T = convert(T, "K"))
# # We should use calories here because the database values are in calories 20220604
# stopifnot(info(info("CuCl2-"))$E_units == "cal")
# dG_cal <- convert(dG_J, "cal")
# # Apply this difference to the CuCl2- entry in OBIGT
# newG <- info(info("CuCl2-"))$G + dG_cal
# mod.OBIGT("CuCl2-", G = newG)
#
# # Do the same thing for CuCl3-2
# logK <- subcrt(c("CuCl3-2", "Cu+", "Cl-"), c(-1, 1, 3), T = T)$out$logK
# dlogK <- logK - -5.6
# dG_J <- convert(dlogK, "G", T = convert(T, "K"))
# stopifnot(info(info("CuCl3-2"))$E_units == "cal")
# dG_cal <- convert(dG_J, "cal")
# newG <- info(info("CuCl3-2"))$G + dG_cal
# mod.OBIGT("CuCl3-2", G = newG)
#
# # DIAGRAM 2
# mfun()
# title("Cu (ppm)", line = 1.7)
# CuCl2 <- expr.species("CuCl2-")
# CuCl3 <- expr.species("CuCl3-2")
# title(bquote("Helgeson (1969)"~.(CuCl2)~and~.(CuCl3)), line = 0.9)
#
# # Set up system to dissolve S2(gas)
# basis(c("S2", "copper", "hematite", "oxygen", "H2O", "H+", "Cl-"))
# basis("pH", 6)
# species("S2")
# # Calculate concentration of SO4-2
# iaq <- info("SO4-2")
# s <- solubility(iaq, S2 = c(-34, -10, res1), O2 = c(-55, -40, res1), T = T, IS = calc$IS, in.terms.of = "SO4-2")
# s <- convert(s, "ppm")
# # DIAGRAM 3
# diagram(aFeCu, names = NA, col = "gray", fill = fill)
# diagram(s, type = "loga.balance", levels = 10^(-3:3), add = TRUE)
# diagram(s, type = "loga.balance", levels = 35, add = TRUE, lwd = 3, col = 6, contour.method = NA)
# title(bquote(bold(.(expr.species("SO4-2"))~"(ppm)")))
## ----solubility, echo = FALSE, results = "hide", message = FALSE, fig.width = 7, fig.height = 3, out.width = "100%", fig.align = "center", pngquant = pngquant----
par(mfrow = c(1, 3))
basis("pH", 6)
# Estimate the molality of Cl for ca. 80,000 mg/kg solution (Table 2 of Sverjensky, 1987)
m_tot <- 80000 / mass("Cl") / 1000
calc <- NaCl(T = T, m_tot = m_tot)
# Use log molality here, not log activity, because
# activity coefficients are calculated by setting IS below
basis("Cl-", log10(calc$m_Cl))
# Initial setup: dissolve a single mineral to form aqueous Cu complexes
species("copper")
iaq <- retrieve("Cu", c("O", "H", "Cl", "S"), "aq")
# Function to calculate solubility of Cu for stable assemblages of Fe and Cu minerals
# (i.e. equilibrium is imposed with all of these minerals, not only Cu(s))
mfun <- function() {
s <- solubility(iaq, bases = list(bFe, bCu), S2 = c(-34, -10, res1), O2 = c(-55, -40, res1),
T = T, IS = calc$IS, stable = list(dFe$predominant, dCu$predominant))
s <- convert(s, "ppm")
diagram(aFeCu, names = NA, col = "gray", fill = fill)
diagram(s, type = "loga.balance", levels = 10^(-3:3), add = TRUE)
diagram(s, type = "loga.balance", levels = 35, add = TRUE, lwd = 3, col = 6, contour.method = NA)
}
# DIAGRAM 1
mfun()
title("Cu (ppm)")
# Calculate logK for CuCl2- dissociation at 125 °C
logK <- subcrt(c("CuCl2-", "Cu+", "Cl-"), c(-1, 1, 2), T = T)$out$logK
# Sverjensky (1987) used Helgeson (1969) value, which is ca. -5.2
dlogK <- logK - -5.2
# Calculate the difference in ΔG° corresponding to this logK difference
dG_J <- convert(dlogK, "G", T = convert(T, "K"))
# We should use calories here because the database values are in calories 20220604
stopifnot(info(info("CuCl2-"))$E_units == "cal")
dG_cal <- convert(dG_J, "cal")
# Apply this difference to the CuCl2- entry in OBIGT
newG <- info(info("CuCl2-"))$G + dG_cal
mod.OBIGT("CuCl2-", G = newG)
# Do the same thing for CuCl3-2
logK <- subcrt(c("CuCl3-2", "Cu+", "Cl-"), c(-1, 1, 3), T = T)$out$logK
dlogK <- logK - -5.6
dG_J <- convert(dlogK, "G", T = convert(T, "K"))
stopifnot(info(info("CuCl3-2"))$E_units == "cal")
dG_cal <- convert(dG_J, "cal")
newG <- info(info("CuCl3-2"))$G + dG_cal
mod.OBIGT("CuCl3-2", G = newG)
# DIAGRAM 2
mfun()
title("Cu (ppm)", line = 1.7)
CuCl2 <- expr.species("CuCl2-")
CuCl3 <- expr.species("CuCl3-2")
title(bquote("Helgeson (1969)"~.(CuCl2)~and~.(CuCl3)), line = 0.9)
# Set up system to dissolve S2(gas)
basis(c("S2", "copper", "hematite", "oxygen", "H2O", "H+", "Cl-"))
basis("pH", 6)
species("S2")
# Calculate concentration of SO4-2
iaq <- info("SO4-2")
s <- solubility(iaq, S2 = c(-34, -10, res1), O2 = c(-55, -40, res1), T = T, IS = calc$IS, in.terms.of = "SO4-2")
s <- convert(s, "ppm")
# DIAGRAM 3
diagram(aFeCu, names = NA, col = "gray", fill = fill)
diagram(s, type = "loga.balance", levels = 10^(-3:3), add = TRUE)
diagram(s, type = "loga.balance", levels = 35, add = TRUE, lwd = 3, col = 6, contour.method = NA)
title(bquote(bold(.(expr.species("SO4-2"))~"(ppm)")))
## ----NaCl---------------------------------------------------------------------
# Ionic strength
calc$IS
# Logarithm of activity of Cl-
log10(calc$m_Cl * calc$gam_Cl)
## ----logK, message = FALSE----------------------------------------------------
# logK values interpolated from Table 5 of Helgeson (1969)
subcrt(c("CuCl2-", "Cu+", "Cl-"), c(-1, 1, 2), T = T)$out$logK
subcrt(c("CuCl3-2", "Cu+", "Cl-"), c(-1, 1, 3), T = T)$out$logK
# Default OBIGT database
reset()
subcrt(c("CuCl2-", "Cu+", "Cl-"), c(-1, 1, 2), T = T)$out$logK
subcrt(c("CuCl3-2", "Cu+", "Cl-"), c(-1, 1, 3), T = T)$out$logK
## ----iCu.aq-------------------------------------------------------------------
names(iCu.aq)
## ----rebalance, eval = FALSE--------------------------------------------------
# mat <- matrix(c(1, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5), byrow = TRUE, nrow = 2)
# layout(mat)
# par(font.main = 1)
#
# basis(c("Fe+2", "Cu+", "hydrogen sulfide", "oxygen", "H2O", "H+"))
# xlab <- ratlab("Fe+2", "Cu+")
#
# ### PRIMARY balancing
#
# # Only Fe-bearing minerals
# species(c("pyrite", "pyrrhotite", "magnetite", "hematite"))
# aFe <- affinity("Fe+2" = c(0, 12), O2 = c(-40, -16), T = 400, P = 2000)
# names <- info(aFe$species$ispecies)$abbrv
# dFe <- diagram(aFe, xlab = xlab, names = names)
# title(bquote("Only Fe; 1° balance:" ~ .(expr.species(dFe$balance))))
# label.plot("A")
#
# # Only Cu-bearing minerals
# species(c("covellite", "chalcocite", "tenorite", "cuprite"))
# aCu <- affinity(aFe) # argument recall
# names <- info(aCu$species$ispecies)$abbrv
# dCu <- diagram(aCu, xlab = xlab, names = names)
# title(bquote("Only Cu; 1° balance:" ~ .(expr.species(dCu$balance))))
# label.plot("B")
#
# # Only Fe- AND Cu-bearing minerals
# species(c("chalcopyrite", "bornite"))
# aFeCu <- affinity(aFe)
# names <- info(aFeCu$species$ispecies)$abbrv
# dFeCu <- diagram(aFeCu, xlab = xlab, balance = "H+", names = names)
# title(bquote("Only Fe+Cu; 1° balance:" ~ .(expr.species(dFeCu$balance))))
# label.plot("C")
#
# ### SECONDARY balancing
#
# # Fe- or Cu-bearing minerals
# ad1 <- rebalance(dFe, dCu, balance = "H+")
# names <- info(ad1$species$ispecies)$abbrv
# d1 <- diagram(ad1, xlab = xlab, balance = 1, names = names)
# title(bquote("Only Fe or Cu; 2° balance:" ~ .(expr.species("H+"))))
# label.plot("D")
#
# # All minerals
# d1$values <- c(dFe$values, dCu$values)
# ad2 <- rebalance(d1, dFeCu, balance = "H+")
# names <- info(ad2$species$ispecies)$abbrv
# diagram(ad2, xlab = xlab, balance = 1, names = names)
# title(bquote("Fe and/or Cu; 2° balance:" ~ .(expr.species("H+"))))
# label.plot("E")
#
# db <- describe.basis(3)
# leg <- lex(lTP(400, 2000), db)
# legend("bottomleft", legend = leg, bty = "n")
## ----rebalance, eval = FALSE, echo = 5:6--------------------------------------
# mat <- matrix(c(1, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5), byrow = TRUE, nrow = 2)
# layout(mat)
# par(font.main = 1)
#
# basis(c("Fe+2", "Cu+", "hydrogen sulfide", "oxygen", "H2O", "H+"))
# xlab <- ratlab("Fe+2", "Cu+")
#
# ### PRIMARY balancing
#
# # Only Fe-bearing minerals
# species(c("pyrite", "pyrrhotite", "magnetite", "hematite"))
# aFe <- affinity("Fe+2" = c(0, 12), O2 = c(-40, -16), T = 400, P = 2000)
# names <- info(aFe$species$ispecies)$abbrv
# dFe <- diagram(aFe, xlab = xlab, names = names)
# title(bquote("Only Fe; 1° balance:" ~ .(expr.species(dFe$balance))))
# label.plot("A")
#
# # Only Cu-bearing minerals
# species(c("covellite", "chalcocite", "tenorite", "cuprite"))
# aCu <- affinity(aFe) # argument recall
# names <- info(aCu$species$ispecies)$abbrv
# dCu <- diagram(aCu, xlab = xlab, names = names)
# title(bquote("Only Cu; 1° balance:" ~ .(expr.species(dCu$balance))))
# label.plot("B")
#
# # Only Fe- AND Cu-bearing minerals
# species(c("chalcopyrite", "bornite"))
# aFeCu <- affinity(aFe)
# names <- info(aFeCu$species$ispecies)$abbrv
# dFeCu <- diagram(aFeCu, xlab = xlab, balance = "H+", names = names)
# title(bquote("Only Fe+Cu; 1° balance:" ~ .(expr.species(dFeCu$balance))))
# label.plot("C")
#
# ### SECONDARY balancing
#
# # Fe- or Cu-bearing minerals
# ad1 <- rebalance(dFe, dCu, balance = "H+")
# names <- info(ad1$species$ispecies)$abbrv
# d1 <- diagram(ad1, xlab = xlab, balance = 1, names = names)
# title(bquote("Only Fe or Cu; 2° balance:" ~ .(expr.species("H+"))))
# label.plot("D")
#
# # All minerals
# d1$values <- c(dFe$values, dCu$values)
# ad2 <- rebalance(d1, dFeCu, balance = "H+")
# names <- info(ad2$species$ispecies)$abbrv
# diagram(ad2, xlab = xlab, balance = 1, names = names)
# title(bquote("Fe and/or Cu; 2° balance:" ~ .(expr.species("H+"))))
# label.plot("E")
#
# db <- describe.basis(3)
# leg <- lex(lTP(400, 2000), db)
# legend("bottomleft", legend = leg, bty = "n")
## ----rebalance, eval = FALSE, echo = 10:33------------------------------------
# mat <- matrix(c(1, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5), byrow = TRUE, nrow = 2)
# layout(mat)
# par(font.main = 1)
#
# basis(c("Fe+2", "Cu+", "hydrogen sulfide", "oxygen", "H2O", "H+"))
# xlab <- ratlab("Fe+2", "Cu+")
#
# ### PRIMARY balancing
#
# # Only Fe-bearing minerals
# species(c("pyrite", "pyrrhotite", "magnetite", "hematite"))
# aFe <- affinity("Fe+2" = c(0, 12), O2 = c(-40, -16), T = 400, P = 2000)
# names <- info(aFe$species$ispecies)$abbrv
# dFe <- diagram(aFe, xlab = xlab, names = names)
# title(bquote("Only Fe; 1° balance:" ~ .(expr.species(dFe$balance))))
# label.plot("A")
#
# # Only Cu-bearing minerals
# species(c("covellite", "chalcocite", "tenorite", "cuprite"))
# aCu <- affinity(aFe) # argument recall
# names <- info(aCu$species$ispecies)$abbrv
# dCu <- diagram(aCu, xlab = xlab, names = names)
# title(bquote("Only Cu; 1° balance:" ~ .(expr.species(dCu$balance))))
# label.plot("B")
#
# # Only Fe- AND Cu-bearing minerals
# species(c("chalcopyrite", "bornite"))
# aFeCu <- affinity(aFe)
# names <- info(aFeCu$species$ispecies)$abbrv
# dFeCu <- diagram(aFeCu, xlab = xlab, balance = "H+", names = names)
# title(bquote("Only Fe+Cu; 1° balance:" ~ .(expr.species(dFeCu$balance))))
# label.plot("C")
#
# ### SECONDARY balancing
#
# # Fe- or Cu-bearing minerals
# ad1 <- rebalance(dFe, dCu, balance = "H+")
# names <- info(ad1$species$ispecies)$abbrv
# d1 <- diagram(ad1, xlab = xlab, balance = 1, names = names)
# title(bquote("Only Fe or Cu; 2° balance:" ~ .(expr.species("H+"))))
# label.plot("D")
#
# # All minerals
# d1$values <- c(dFe$values, dCu$values)
# ad2 <- rebalance(d1, dFeCu, balance = "H+")
# names <- info(ad2$species$ispecies)$abbrv
# diagram(ad2, xlab = xlab, balance = 1, names = names)
# title(bquote("Fe and/or Cu; 2° balance:" ~ .(expr.species("H+"))))
# label.plot("E")
#
# db <- describe.basis(3)
# leg <- lex(lTP(400, 2000), db)
# legend("bottomleft", legend = leg, bty = "n")
## ----rebalance, eval = FALSE, echo = 36:49------------------------------------
# mat <- matrix(c(1, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5), byrow = TRUE, nrow = 2)
# layout(mat)
# par(font.main = 1)
#
# basis(c("Fe+2", "Cu+", "hydrogen sulfide", "oxygen", "H2O", "H+"))
# xlab <- ratlab("Fe+2", "Cu+")
#
# ### PRIMARY balancing
#
# # Only Fe-bearing minerals
# species(c("pyrite", "pyrrhotite", "magnetite", "hematite"))
# aFe <- affinity("Fe+2" = c(0, 12), O2 = c(-40, -16), T = 400, P = 2000)
# names <- info(aFe$species$ispecies)$abbrv
# dFe <- diagram(aFe, xlab = xlab, names = names)
# title(bquote("Only Fe; 1° balance:" ~ .(expr.species(dFe$balance))))
# label.plot("A")
#
# # Only Cu-bearing minerals
# species(c("covellite", "chalcocite", "tenorite", "cuprite"))
# aCu <- affinity(aFe) # argument recall
# names <- info(aCu$species$ispecies)$abbrv
# dCu <- diagram(aCu, xlab = xlab, names = names)
# title(bquote("Only Cu; 1° balance:" ~ .(expr.species(dCu$balance))))
# label.plot("B")
#
# # Only Fe- AND Cu-bearing minerals
# species(c("chalcopyrite", "bornite"))
# aFeCu <- affinity(aFe)
# names <- info(aFeCu$species$ispecies)$abbrv
# dFeCu <- diagram(aFeCu, xlab = xlab, balance = "H+", names = names)
# title(bquote("Only Fe+Cu; 1° balance:" ~ .(expr.species(dFeCu$balance))))
# label.plot("C")
#
# ### SECONDARY balancing
#
# # Fe- or Cu-bearing minerals
# ad1 <- rebalance(dFe, dCu, balance = "H+")
# names <- info(ad1$species$ispecies)$abbrv
# d1 <- diagram(ad1, xlab = xlab, balance = 1, names = names)
# title(bquote("Only Fe or Cu; 2° balance:" ~ .(expr.species("H+"))))
# label.plot("D")
#
# # All minerals
# d1$values <- c(dFe$values, dCu$values)
# ad2 <- rebalance(d1, dFeCu, balance = "H+")
# names <- info(ad2$species$ispecies)$abbrv
# diagram(ad2, xlab = xlab, balance = 1, names = names)
# title(bquote("Fe and/or Cu; 2° balance:" ~ .(expr.species("H+"))))
# label.plot("E")
#
# db <- describe.basis(3)
# leg <- lex(lTP(400, 2000), db)
# legend("bottomleft", legend = leg, bty = "n")
## ----rebalance, echo = FALSE, results = "hide", message = FALSE, fig.width = 6.5, fig.height = 5, out.width = "100%", fig.align = "center", pngquant = pngquant----
mat <- matrix(c(1, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5), byrow = TRUE, nrow = 2)
layout(mat)
par(font.main = 1)
basis(c("Fe+2", "Cu+", "hydrogen sulfide", "oxygen", "H2O", "H+"))
xlab <- ratlab("Fe+2", "Cu+")
### PRIMARY balancing
# Only Fe-bearing minerals
species(c("pyrite", "pyrrhotite", "magnetite", "hematite"))
aFe <- affinity("Fe+2" = c(0, 12), O2 = c(-40, -16), T = 400, P = 2000)
names <- info(aFe$species$ispecies)$abbrv
dFe <- diagram(aFe, xlab = xlab, names = names)
title(bquote("Only Fe; 1° balance:" ~ .(expr.species(dFe$balance))))
label.plot("A")
# Only Cu-bearing minerals
species(c("covellite", "chalcocite", "tenorite", "cuprite"))
aCu <- affinity(aFe) # argument recall
names <- info(aCu$species$ispecies)$abbrv
dCu <- diagram(aCu, xlab = xlab, names = names)
title(bquote("Only Cu; 1° balance:" ~ .(expr.species(dCu$balance))))
label.plot("B")
# Only Fe- AND Cu-bearing minerals
species(c("chalcopyrite", "bornite"))
aFeCu <- affinity(aFe)
names <- info(aFeCu$species$ispecies)$abbrv
dFeCu <- diagram(aFeCu, xlab = xlab, balance = "H+", names = names)
title(bquote("Only Fe+Cu; 1° balance:" ~ .(expr.species(dFeCu$balance))))
label.plot("C")
### SECONDARY balancing
# Fe- or Cu-bearing minerals
ad1 <- rebalance(dFe, dCu, balance = "H+")
names <- info(ad1$species$ispecies)$abbrv
d1 <- diagram(ad1, xlab = xlab, balance = 1, names = names)
title(bquote("Only Fe or Cu; 2° balance:" ~ .(expr.species("H+"))))
label.plot("D")
# All minerals
d1$values <- c(dFe$values, dCu$values)
ad2 <- rebalance(d1, dFeCu, balance = "H+")
names <- info(ad2$species$ispecies)$abbrv
diagram(ad2, xlab = xlab, balance = 1, names = names)
title(bquote("Fe and/or Cu; 2° balance:" ~ .(expr.species("H+"))))
label.plot("E")
db <- describe.basis(3)
leg <- lex(lTP(400, 2000), db)
legend("bottomleft", legend = leg, bty = "n")
## ----non-metal, results = "hide", message = FALSE, fig.width = 6, fig.height = 5, out.width = "80%", fig.align = "center", pngquant = pngquant----
basis(c("Fe+2", "Cu+", "hydrogen sulfide", "oxygen", "H2O", "H+"))
basis("H2S", 2)
species(c("pyrite", "magnetite", "hematite", "covellite", "tenorite",
"chalcopyrite", "bornite"))
a <- affinity("Cu+" = c(-8, 2, 500), "Fe+2" = c(-4, 12, 500), T = 400, P = 2000)
names <- info(a$species$ispecies)$abbrv
d <- diagram(a, xlab = ratlab("Cu+"), ylab = ratlab("Fe+2"), balance = "O2", names = names)
title(bquote("Cu-Fe-S-O-H; 1° balance:" ~ .(expr.species(d$balance))))
# Add saturation lines
species(c("pyrrhotite", "ferrous-oxide", "chalcocite", "cuprite"))
asat <- affinity(a) # argument recall
names <- asat$species$name
names[2] <- "ferrous oxide"
diagram(asat, type = "saturation", add = TRUE, lty = 2, col = 4, names = names)
legend("topleft", legend = lTP(400, 2000), bty = "n")
## ----mosaic-combo, eval = FALSE-----------------------------------------------
# ## METHOD 1: Keff equation (Robinson et al., 2021)
#
# # A function to calculate Keff for any combination of T and pH
# Keff <- function(T = 25, pH = 7) {
# # Make T and pH the same length
# len <- max(length(T), length(pH))
# T <- rep(T, length.out = len)
# pH <- rep(pH, length.out = len)
# # Calculate activity of H+
# aH <- 10^(-pH)
# # Calculate logKs
# logK1 <- subcrt(c("acetic acid", "NH3", "acetamide", "H2O"), c(-1, -1, 1, 1), T = T)$out$logK
# logK2 <- subcrt(c("acetic acid", "acetate", "H+"), c(-1, 1, 1), T = T)$out$logK
# logK3 <- subcrt(c("NH3", "H+", "NH4+"), c(-1, -1, 1), T = T)$out$logK
# # Calculate Ks
# K1 <- 10^logK1
# K2 <- 10^logK2
# K3 <- 10^logK3
# # Calculate Keff (Eq. 7)
# Keff <- K1 * (1 + K2 / aH) ^ -1 * (1 + K3 * aH) ^ -1
# Keff
# }
#
# # Calculate logKeff as a function of pH at 100 °C
# res <- 128
# pH <- seq(0, 14, length.out = res)
# T <- 100
# logKeff <- log10(Keff(pH = pH, T = T))
#
# # Calculate activity of acetamide for
# # acetic acid + acetate = 0.01 m
# # ammonia + ammonium = 0.001 m
# logAc <- log10(0.01)
# logAm <- log10(0.001)
# logAcAm <- logKeff + logAc + logAm
#
# ## METHOD 2: Mosaic combo
#
# # Define total activities
# a_N <- 0.001
# # This is 2 * 0.01 because acetic acid has 2 carbons
# a_C <- 2 * 0.01
# loga_N <- log10(a_N)
# loga_C <- log10(a_C)
# # Setup basis species
# basis(c("CO2", "NH3", "O2", "H2O", "H+"))
# basis("NH3", loga_N)
# # Load all C-bearing species (including acetamide)
# species(c("acetamide", "acetic acid", "acetate"))
# # Calculate distribution of C-bearing species accounting for ammonia/ammonium speciation
# m <- mosaic(c("NH3", "NH4+"), pH = c(0, 14, res), T = T)
# e <- equilibrate(m, loga.balance = loga_C)
#
# # Plot and label diagram
# # Start with empty diagram
# diagram(e, ylim = c(-8, -0), lty = 0, names = FALSE)
# # Add pH = 6 line
# abline(v = 6, col = "gray60", lty = 5)
# # Add line for acetamide activity calculated with Keff
# lines(pH, logAcAm, col = 4, lwd = 6, lty = 2)
# # Add lines from CHNOSZ calculations
# diagram(e, add = TRUE, lty = c(2, 3, 1, 2, 3), lwd = c(1, 1, 2, 1, 1), dx = c(-0.2, 0.2, -2.5, 0, 0), dy = c(0.1, 0.1, -1, 0.1, 0.1), srt = c(0, 0, 52, 0, 0))
# tN <- paste("Total N in basis species =", format(a_N, scientific = FALSE), "m")
# tC <- paste("Total C in formed species =", format(a_C, scientific = FALSE), "m")
# title(main = paste(tN, tC, sep = "\n"), font.main = 1)
# legend("topright", legend = lTP(T, "Psat"), bty = "n")
# # Check that we got equal values
# stopifnot(all.equal(as.numeric(e$loga.equil[[3]]), logAcAm, tol = 1e-3, scale = 1))
## ----mosaic-combo, echo = FALSE, results = "hide", message = FALSE, fig.width = 6, fig.height = 5, out.width = "80%", fig.align = "center", pngquant = pngquant----
## METHOD 1: Keff equation (Robinson et al., 2021)
# A function to calculate Keff for any combination of T and pH
Keff <- function(T = 25, pH = 7) {
# Make T and pH the same length
len <- max(length(T), length(pH))
T <- rep(T, length.out = len)
pH <- rep(pH, length.out = len)
# Calculate activity of H+
aH <- 10^(-pH)
# Calculate logKs
logK1 <- subcrt(c("acetic acid", "NH3", "acetamide", "H2O"), c(-1, -1, 1, 1), T = T)$out$logK
logK2 <- subcrt(c("acetic acid", "acetate", "H+"), c(-1, 1, 1), T = T)$out$logK
logK3 <- subcrt(c("NH3", "H+", "NH4+"), c(-1, -1, 1), T = T)$out$logK
# Calculate Ks
K1 <- 10^logK1
K2 <- 10^logK2
K3 <- 10^logK3
# Calculate Keff (Eq. 7)
Keff <- K1 * (1 + K2 / aH) ^ -1 * (1 + K3 * aH) ^ -1
Keff
}
# Calculate logKeff as a function of pH at 100 °C
res <- 128
pH <- seq(0, 14, length.out = res)
T <- 100
logKeff <- log10(Keff(pH = pH, T = T))
# Calculate activity of acetamide for
# acetic acid + acetate = 0.01 m
# ammonia + ammonium = 0.001 m
logAc <- log10(0.01)
logAm <- log10(0.001)
logAcAm <- logKeff + logAc + logAm
## METHOD 2: Mosaic combo
# Define total activities
a_N <- 0.001
# This is 2 * 0.01 because acetic acid has 2 carbons
a_C <- 2 * 0.01
loga_N <- log10(a_N)
loga_C <- log10(a_C)
# Setup basis species
basis(c("CO2", "NH3", "O2", "H2O", "H+"))
basis("NH3", loga_N)
# Load all C-bearing species (including acetamide)
species(c("acetamide", "acetic acid", "acetate"))
# Calculate distribution of C-bearing species accounting for ammonia/ammonium speciation
m <- mosaic(c("NH3", "NH4+"), pH = c(0, 14, res), T = T)
e <- equilibrate(m, loga.balance = loga_C)
# Plot and label diagram
# Start with empty diagram
diagram(e, ylim = c(-8, -0), lty = 0, names = FALSE)
# Add pH = 6 line
abline(v = 6, col = "gray60", lty = 5)
# Add line for acetamide activity calculated with Keff
lines(pH, logAcAm, col = 4, lwd = 6, lty = 2)
# Add lines from CHNOSZ calculations
diagram(e, add = TRUE, lty = c(2, 3, 1, 2, 3), lwd = c(1, 1, 2, 1, 1), dx = c(-0.2, 0.2, -2.5, 0, 0), dy = c(0.1, 0.1, -1, 0.1, 0.1), srt = c(0, 0, 52, 0, 0))
tN <- paste("Total N in basis species =", format(a_N, scientific = FALSE), "m")
tC <- paste("Total C in formed species =", format(a_C, scientific = FALSE), "m")
title(main = paste(tN, tC, sep = "\n"), font.main = 1)
legend("topright", legend = lTP(T, "Psat"), bty = "n")
# Check that we got equal values
stopifnot(all.equal(as.numeric(e$loga.equil[[3]]), logAcAm, tol = 1e-3, scale = 1))
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/doc/multi-metal.R
|
---
title: "Diagrams with multiple metals"
author: "Jeffrey M. Dick"
output:
html_vignette:
mathjax: null
vignette: >
%\VignetteIndexEntry{Diagrams with multiple metals}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
bibliography: [vig.bib, OBIGT.bib]
csl: elementa.csl
link-citations: true
---
<style>
/* https://gomakethings.com/how-to-break-an-image-out-of-its-parent-container-with-css/ */
@media (min-width: 700px) {
.full-width {
left: 50%;
margin-left: -50vw;
margin-right: -50vw;
max-width: 100vw;
position: relative;
right: 50%;
width: 100vw;
}
}
@media (min-width: 1020px) {
.full-width {
left: 50vw; /* fallback if needed */
left: calc(50vw - 160px);
width: 1000px;
position: relative;
background-color: #9ecff7;
padding:10px;
}
}
/* Zero margin around pre blocks (looks more like R console output) */
pre {
margin-top: 0;
margin-bottom: 0;
}
</style>
<script>
function ToggleDiv(ID) {
var D = document.getElementById("D-" + ID);
var B = document.getElementById("B-" + ID);
if (D.style.display === "none") {
// open the div and change button text
D.style.display = "block";
B.innerText = "Hide code";
} else {
// close the div and change button text
D.style.display = "none";
B.innerText = "Show code";
}
}
</script>
```{r setup, include=FALSE}
options(width = 80)
## Use pngquant to optimize PNG images
library(knitr)
knit_hooks$set(pngquant = hook_pngquant)
pngquant <- "--speed=1 --quality=0-25"
if (!nzchar(Sys.which("pngquant"))) pngquant <- NULL
## Resolution settings
# Change this to TRUE to make high-resolution plots
# (default is FALSE to save time in CRAN checks)
hires <- nzchar(Sys.getenv("CHNOSZ_BUILD_LARGE_VIGNETTES"))
res1.lo <- 150
res1.hi <- 256
res1 <- if(hires) res1.hi else res1.lo
res2.lo <- 200
res2.hi <- 400
res2 <- if(hires) res2.hi else res2.lo
## logK with a thin space 20200627
logK <- "log <i>K</i>"
## Set dpi 20231129
knitr::opts_chunk$set(
dpi = if(nzchar(Sys.getenv("CHNOSZ_BUILD_LARGE_VIGNETTES"))) 100 else 72
)
```
```{r CHNOSZ_reset, include=FALSE}
library(CHNOSZ)
reset()
```
This vignette was compiled on `r Sys.Date()` with CHNOSZ version `r sessionInfo()$otherPkgs$CHNOSZ$Version`.
This vignette is associated with a paper that has been published in *Applied Computing and Geosciences* ([Dick, 2021](https://doi.org/10.1016/j.acags.2021.100059 "Diagrams with multiple metals in CHNOSZ")).
Please consider citing that paper if you use the functions or diagrams described here.
The plots in this vignette were made using the following resolution settings.
Low resolutions are used for submitting the package to CRAN.
High resolutions are used if the `CHNOSZ_BUILD_LARGE_VIGNETTES` environment variable is set.
```{r res, results = "asis", echo = FALSE}
cat("```")
cat("\n")
cat(paste0(if(hires) "# " else "", "res1 <- ", res1.lo))
cat("\n")
cat(paste0(if(hires) "" else "# ", "res1 <- ", res1.hi))
cat("\n")
cat(paste0(if(hires) "# " else "", "res2 <- ", res2.lo))
cat("\n")
cat(paste0(if(hires) "" else "# ", "res2 <- ", res2.hi))
cat("\n")
cat("```")
```
Basic diagrams in CHNOSZ are made for reactions that are *balanced on an element* (see [Equilibrium in CHNOSZ](equilibrium.html)) and therefore represent minerals or aqueous species that all have one element, often a metal, in common.
The package documentation has many examples of diagrams for a single metal appearing in different minerals or complexed with different ligands, but a common request is to make diagrams for multiple metals.
This vignette describes some methods for constructing diagrams for multi-metal minerals and other multi-element systems.
The methods are **mashing**, **mixing**, **mosaic stacking**, and **secondary balancing**.
## Mashing
Mashing or simple overlay refers to independent calculations for two different systems that are displayed on the same diagram.
This example starts with a log*f*~O<sub>2</sub>~--pH base diagram for the C-O-H system then overlays a diagram for S-O-H.
The second call to `affinity()` uses the argument recall feature, where the arguments after the first are taken from the previous command.
This allows calculations to be run at the same conditions for a different system.
This feature is also used in other examples in this vignette.
```{r mash, echo = 1:8, eval = FALSE}
par(mfrow = c(1, 2))
basis("CHNOS+")
species(c("CH4", "CO2", "HCO3-", "CO3-2"))
aC <- affinity(pH = c(0, 14), O2 = c(-75, -60))
dC <- diagram(aC, dx = c(0, 1, 0, 0), dy = c(0, 1, 0, 0))
species(c("H2S", "HS-", "HSO4-", "SO4-2"))
aS <- affinity(aC) # argument recall
dS <- diagram(aS, add = TRUE, col = 4, col.names = 4, dx = c(0, -0.5, 0, 0))
aCS <- mash(dC, dS)
srt <- c(0, 0, 90, 0, 0, 0, 90, 0, 0, 0)
cex.names <- c(1, 1, 0.8, 1, 1, 1, 1, 1, 1, 1)
dy <- c(0, 0, 0, -0.2, 0, 0, 0, 0, 0, 0)
diagram(aCS, srt = srt, cex.names = cex.names, dy = dy)
legend("topright", legend = lTP(25, 1), bty = "n")
```
The second diagram is just like the first, except the function `mash()` is used to label the fields with names of species from both systems, and a legend is added to indicate the temperature and pressure.
```{r mash, echo = 9:14, results = "hide", message = FALSE, fig.width = 10, fig.height = 5, out.width = "100%"}
```
Note that these are predominance diagrams, so they show only the species with highest activity; there is in fact a distribution of activities of aqueous species that is not visible here.
Tip: the names of the fields in the second diagram come from `aCS$species$name`, which are expressions made by combining `aC$names` and `aS$names`.
If you prefer plain text names without formatting, add `format.names = FALSE` to all of the `diagram()` calls.
## Mixing 1
As shown above, mashing two diagrams is essentially a simple combination of the two systems.
Although it is easy to make such a diagram, there is no interaction between the systems.
If there is a possibility of forming bimetallic species, then additional considerations are needed to account for the stoichiometry of the mixture.
The stoichiometry can be given as a fixed composition of both metals; then, all combinations of (mono- and/or bimetallic) species that satisfy this compositional constraint are used as the candidate "species" in the system.
This is the same type of calculation as that described for [binary Pourbaix diagrams in the Materials Project](https://matgenb.materialsvirtuallab.org/2017/12/15/Plotting-a-Pourbaix-Diagram.html#Plotting-k-nary-systems).
This example makes a Pourbaix diagram for the Fe-V-O-H system that is similar to Figure 1 of @SZS_17.
Before getting started, it may be helpful to clarify some terminology.
In the materials science community, materials are characterized by several energies (among others): 1) the formation energy from the elements in their reference state, 2) the energy above the convex hull, which is zero for stable materials, and greater than zero for metastable materials, and 3) the Pourbaix energy difference (Δ*G*~pbx~), which refers to the energy of a given material with respect to the stable solids and aqueous species as a function of pH and Eh.
The parallel terminology used in CHNOSZ is that aqueous species or minerals have a 1) standard Gibbs energy of formation from the elements, Δ*G*° = *f*(*T*, *P*), which is available from the [OBIGT database](OBIGT.html), 2) standard Gibbs energy of reaction from the stable species, and 3) affinity of formation from the basis species, *A* = -Δ*G* = *f*(*T*, *P*, and activities of all species).
As used in CHNOSZ, "formation reaction" refers to formation from the basis species, not from the elements.
The basis species **are not** in general the stable species, so we begin by identifying the stable species in the system; the difference between *their* affinities and the affinity of any other species corresponds to -Δ*G*~pbx~.
First we need to assemble the standard Gibbs energies of the solids and aqueous species.
For solids, values of formation energy from the elements (in eV/atom) computed using density functional theory (DFT) were retrieved from the [Materials API](https://github.com/materialsproject/mapidoc) [@OCJ_15] and are converted to units of J/mol.
The Materials Project (MP) website also provides these values, but with fewer decimal places, which would lead to a small rounding error in the comparison of energy above the hull at the end of this example.
For aqueous species, values of standard Gibbs energy of formation from the elements at 25 °C (in J/mol) are taken mostly from @WEP_82 augmented with data for FeO~2~^-^ from @SSWS97 and FeO~4~^-2^ from @Mis73.
Adapting the method described by @PWLC12, a correction for each metal is calculated from the difference between the DFT-based formation energy and the standard Gibbs energy of a representative material; here we use values for Fe~3~O~4~ (magnetite) and V~3~O~5~ from @WEP_82.
This correction is then applied to all of the aqueous species that have that metal.
Finally, `mod.OBIGT()` is used to add the obtained energies to the OBIGT database in CHNOSZ.
<button id="B-materials" onclick="ToggleDiv('materials')">Show code</button>
<div id="D-materials" style="display: none">
```{r materials, message = FALSE, results = "hide"}
## Formation energies (eV / atom) for solids from Materials API, e.g.
# from pymatgen import MPRester
# m = MPRester("USER_API_KEY")
# m.query(criteria={"task_id": "mp-1279742"}, properties=["formation_energy_per_atom"])
# mp-13, mp-1279742, mp-19306, mp-19770
#Fe.cr <- c(Fe = 0, FeO = -1.72803, Fe3O4 = -1.85868, Fe2O3 = -1.90736) # 20201109
Fe.cr <- c(Fe = 0, FeO = -1.72768, Fe3O4 = -1.85838, Fe2O3 = -1.90708) # 20210219
# mp-146, mp-18937, mp-1275946, mp-19094, mp-756395, mp-25279
#V.cr <- c(V = 0, V2O3 = -2.52849, V3O5 = -2.52574, VO2 = -2.48496, V3O7 = -2.32836, V2O5 = -2.29524) # 20201109
V.cr <- c(V = 0, V2O3 = -2.52787, V3O5 = -2.52516, VO2 = -2.48447, V3O7 = -2.32789, V2O5 = -2.29480) # 20210219
# Convert formation energies from eV / atom to eV / molecule
natom.Fe <- sapply(makeup(names(Fe.cr)), sum)
Fe.cr <- Fe.cr * natom.Fe
natom.V <- sapply(makeup(names(V.cr)), sum)
V.cr <- V.cr * natom.V
# Convert formation energies from eV / molecule to J / mol
eVtoJ <- function(eV) eV * 1.602176634e-19 * 6.02214076e23
Fe.cr <- eVtoJ(Fe.cr)
V.cr <- eVtoJ(V.cr)
# Gibbs energies of formation (J / mol) for aqueous species
# Most are from Wagman et al., 1982
Fe.aq <- 1000 * c("Fe+2" = -78.90, "Fe+3" = -4.7, "FeO2-2" = -295.3,
"FeOH+" = -277.4, "FeOH+2" = -229.41, "HFeO2-" = -377.7,
"Fe(OH)2+" = -438.0, "Fe(OH)3" = -659.3,
"FeO2-" = -368.2, # SSWS97
"FeO4-2" = -322.2 # Mis73
)
V.aq <- 1000 * c("VO+2" = -446.4, "VO2+" = -587.0, "VO3-" = -783.6, "VO4-3" = -899.0,
"V2O7-4" = -1719, "HVO4" = -745.1, "HVO4-2" = -974.8,
"VOH2O2+3" = -523.4, "VO2H2O2+" = -746.3, "V2HO7-3" = 1792.2, "V2H3O7-" = -1863.8,
"HV10O28-5" = -7702, "H2V10O28-4" = -7723
)
# Gibbs energies of formation (J / mol) for solids from Wagman et al., 1982
Fe3O4 <- 1000 * -1015.4 # magnetite
V3O5 <- 1000 * -1803
# Calculate correction for difference between reference and DFT energies (Persson et al., 2012)
Fe.corr <- (Fe.cr["Fe3O4"] - Fe3O4) / 3
V.corr <- (V.cr["V3O5"] - V3O5) / 2
# Apply correction to standard Gibbs energies of aqueous species (Persson et al., 2012)
nFe <- sapply(makeup(names(Fe.aq)), "[", "Fe")
Fe.aq <- Fe.aq + nFe * Fe.corr
nV <- sapply(makeup(names(V.aq)), "[", "V")
V.aq <- V.aq + nV * V.corr
# Add energies to OBIGT
# This function modifies OBIGT and returns the species indices of the affected species
modfun <- function(x, state, model = NULL) sapply(seq_along(x), function(i) {
# We explicitly set the units to Joules (this is the default as of CHNOSZ 2.0.0)
if(is.null(model)) mod.OBIGT(names(x)[i], formula = names(x)[i], state = state, E_units = "J", G = x[i])
else mod.OBIGT(names(x)[i], formula = names(x)[i], state = state, model = model, E_units = "J", G = x[i])
})
# We need model = "CGL" to override the Berman model for some minerals 20220919
iFe.cr <- modfun(Fe.cr, "cr", model = "CGL")
iFe.aq <- modfun(Fe.aq, "aq")
iV.cr <- modfun(V.cr, "cr", model = "CGL")
iV.aq <- modfun(V.aq, "aq")
# Formation energies (eV / atom) for bimetallic solids from Materials API
# mp-1335, mp-1079399, mp-866134, mp-558525, mp-504509 (triclinic FeVO4)
#FeV.cr <- c(FeV = -0.12928, FeV3 = -0.17128, Fe3V = -0.12854, Fe2V4O13 = -2.23833, FeVO4 = -1.75611) # 20201109
FeV.cr <- c(FeV = -0.12815, FeV3 = -0.17114, Fe3V = -0.12832, Fe2V4O13 = -2.23967, FeVO4 = -1.75573) # 20210219
# Convert energies and add to OBIGT
natom.FeV <- sapply(makeup(names(FeV.cr)), sum)
FeV.cr <- FeV.cr * natom.FeV
FeV.cr <- eVtoJ(FeV.cr)
iFeV.cr <- modfun(FeV.cr, "cr")
```
</div>
This code produces species indices in the OBIGT database for Fe- and V-bearing aqueous species (`iFe.aq`, `iV.aq`), solids (`iFe.cr`, `iV.cr`), and bimetallic solids (`iFeV.cr`), which are used in the following diagrams.
Now we set up the plot area and assign activities of aqueous species to 10^-5^, which is the default value for diagrams on the MP website (from the page for a material: "Generate Phase Diagram" -- "Aqueous Stability (Pourbaix)").
The following commands compute Eh-pH diagrams for the single-metal systems Fe-O-H and V-O-H.
The pH and Eh ranges are made relatively small in order to show just a part of the diagram.
The diagrams are not plotted, but the output of `diagram()` is saved in `dFe` and `dV` for later use.
```{r mixing1, eval = FALSE, echo = 1:14}
par(mfrow = c(1, 3))
loga.Fe <- -5
loga.V <- -5
# Fe-O-H diagram
basis(c("VO+2", "Fe+2", "H2O", "e-", "H+"))
species(c(iFe.aq, iFe.cr))
species(1:length(iFe.aq), loga.Fe)
aFe <- affinity(pH = c(4, 10, res1), Eh = c(-1.5, 0, res1))
dFe <- diagram(aFe, plot.it = FALSE)
# V-O-H diagram
species(c(iV.aq, iV.cr))
species(1:length(iV.aq), loga.V)
aV <- affinity(aFe) # argument recall
dV <- diagram(aV, plot.it = FALSE)
# Calculate affinities for bimetallic species
species(iFeV.cr)
aFeV <- affinity(aFe) # argument recall
dFeV <- diagram(aFeV, plot.it = FALSE, bold = TRUE)
# 1:1 mixture (Fe:V)
a11 <- mix(dFe, dV, dFeV, c(1, 1))
# Adjust labels 20210219
iV2O3 <- info("V2O3")
iFeO <- info("FeO", "cr")
iFe3V <- info("Fe3V")
srt <- rep(0, nrow(a11$species))
srt[a11$species$ispecies == paste(iFeO, iV2O3, sep = ",")] <- 90
srt[a11$species$ispecies == paste(iV2O3, iFe3V, sep = ",")] <- -13
diagram(a11, min.area = 0.01, srt = srt)
title("Fe:V = 1:1")
label.figure(lTP(25, 1), xfrac = 0.12)
# 1:3 mixture
a13 <- mix(dFe, dV, dFeV, c(1, 3))
srt <- rep(0, nrow(a13$species))
srt[a13$species$ispecies == paste(iFeO, iV2O3, sep = ",")] <- 90
srt[a13$species$ispecies == paste(iV2O3, iFe3V, sep = ",")] <- -13
diagram(a13, min.area = 0.01, srt = srt)
title("Fe:V = 1:3")
# 1:5 mixture
a15 <- mix(dFe, dV, dFeV, c(1, 5))
iFeV3 <- info("FeV3")
srt <- rep(0, nrow(a15$species))
srt[a15$species$ispecies == paste(iFeO, iV2O3, sep = ",")] <- 90
srt[a15$species$ispecies == paste(iV2O3, iFe3V, sep = ",")] <- -13
srt[a15$species$ispecies == paste(iV2O3, iFeV3, sep = ",")] <- -13
diagram(a15, min.area = 0.01, srt = srt)
title("Fe:V = 1:5")
```
Then we calculate the affinities for the bimetallic species and save the output of `diagram()` in `dFeV`, again without making a plot, but formatting the names in bold.
Note that `diagram()` uses different colors for regions with two solids, one solid, and no solids, including some transparency to show the underlying water stability region that is plotted first.
Now we have all the ingredients needed to combine the Fe-bearing, V-bearing, and bimetallic species to generate a given composition.
The `mix()` function is used to calculate the affinities of formation from basis species for all combinations of aqueous species and minerals that satisfy each of three different compositions.
Finally, the `diagram()`s are plotted; the `min.area` argument is used to remove labels for very small fields.
Regarding the legend, it should be noted that although the DFT calculations for solids are made for zero temperature and zero pressure [@SZS_17], the standard Gibbs energies of aqueous species [e.g. @WEP_82] are modified by a correction term so that they can be combined with DFT energies to reproduce the experimental energy for dissolution of a representative material for each metal at 25 °C and 1 bar [@PWLC12].
```{r mixing1, echo = 16:47, message = FALSE, results = "hide", fig.width = 9, fig.height = 3, out.width = "100%", out.extra='class="full-width"', pngquant = pngquant}
```
In these diagrams, changing the Fe:V ratio affects the fully reduced metallic species.
In the 1:1 mixture, the FeV~3~ + Fe~3~V assemblage is predicted to be stable instead of FeV.
This result is unlike Figure 1 of @SZS_17 but is consistent with the [MP page for FeV](https://doi.org/10.17188/1189535) where it is shown to decompose to this assemblage.
On the other hand, [FeV~3~ is stable](https://next-gen.materialsproject.org/materials/mp-1079399/) in the 1:3 mixture.
For an even higher proportion of V, the V + FeV~3~ assemblage is stable, which can be seen for instance in the Pourbaix diagram linked from the [MP page for FeV~5~O~12~](https://doi.org/10.17188/1305091).
Let's make another diagram for the 1:1 Fe:V composition over a broader range of Eh and pH.
The diagram shows a stable assemblage of Fe~2~O~3~ with an oxidized bimetallic material, [Fe~2~V~4~O~13~](https://next-gen.materialsproject.org/materials/mp-1200054/).
```{r FeVO4, eval = FALSE, echo = 1:29}
layout(t(matrix(1:3)), widths = c(1, 1, 0.2))
par(cex = 1)
# Fe-bearing species
basis(c("VO+2", "Fe+2", "H2O", "e-", "H+"))
species(c(iFe.aq, iFe.cr))$name
species(1:length(iFe.aq), loga.Fe)
aFe <- affinity(pH = c(0, 14, res2), Eh = c(-1.5, 2, res2))
dFe <- diagram(aFe, plot.it = FALSE)
# V-bearing species
species(c(iV.aq, iV.cr))$name
species(1:length(iV.aq), loga.V)
aV <- affinity(aFe) # argument recall
dV <- diagram(aV, plot.it = FALSE)
# Bimetallic species
species(iFeV.cr)
aFeV <- affinity(aFe) # argument recall
dFeV <- diagram(aFeV, plot.it = FALSE, bold = TRUE)
# 1:1 mixture (Fe:V)
a11 <- mix(dFe, dV, dFeV, c(1, 1))
# Adjust labels 20210219
iV2O3 <- info("V2O3")
iFe3V <- info("Fe3V")
iVO4m3 <- info("VO4-3")
iFe2O3 <- info("Fe2O3")
srt <- rep(0, nrow(a11$species))
srt[a11$species$ispecies == paste(iV2O3, iFe3V, sep = ",")] <- -13
srt[a11$species$ispecies == paste(iFe2O3, iVO4m3, sep = ",")] <- 90
d11 <- diagram(a11, min.area = 0.01, srt = srt)
water.lines(d11, col = "orangered")
# Calculate affinity of FeVO4
species("FeVO4")
aFeVO4 <- affinity(aFe) # argument recall
# Calculate difference from stable species
aFeVO4_vs_stable <- aFeVO4$values[[1]] - d11$predominant.values
# Overlay lines from diagram on color map
diagram(a11, fill = NA, names = FALSE, limit.water = FALSE)
opar <- par(usr = c(0, 1, 0, 1))
col <- rev(topo.colors(128)) # No hcl.colors() in R < 3.6.0
if(getRversion() >= "3.6.0") col <- rev(hcl.colors(128, palette = "YlGnBu", alpha = 0.8))
image(aFeVO4_vs_stable, col = col, add = TRUE)
par(opar)
diagram(a11, fill = NA, add = TRUE, names = FALSE)
water.lines(d11, col = "orangered")
thermo.axis()
imax <- arrayInd(which.max(aFeVO4_vs_stable), dim(aFeVO4_vs_stable))
pH <- d11$vals$pH[imax[1]]
Eh <- d11$vals$Eh[imax[2]]
points(pH, Eh, pch = 10, cex = 2, lwd = 2, col = "gold")
stable <- d11$names[d11$predominant[imax]]
text(pH, Eh, stable, adj = c(0.5, -1), cex = 1.2, col = "gold")
# Make color scale 20210228
par(mar = c(3, 0, 2.5, 2.7))
plot.new()
levels <- 1:length(col)
plot.window(xlim = c(0, 1), ylim = range(levels), xaxs = "i", yaxs = "i")
rect(0, levels[-length(levels)], 1, levels[-1L], col = rev(col), border = NA)
box()
# To get the limits, convert range of affinities to eV/atom
arange <- rev(range(aFeVO4_vs_stable))
# This gets us to J/mol
Jrange <- convert(arange, "G")
# And to eV/atom
eVrange <- Jrange / 1.602176634e-19 / 6.02214076e23 / 6
ylim <- formatC(eVrange, digits = 3, format = "f")
axis(4, at = range(levels), labels = ylim)
mtext(quote(Delta*italic(G)[pbx]*", eV/atom"), side = 4, las = 0, line = 1)
```
We then compute the affinity for formation of a metastable material, in this case triclinic FeVO~4~, from the same basis species used to make the previous diagrams.
Given the diagram for the stable Fe-, V- and bimetallic materials *mixed with the same stoichiometry* as FeVO~4~ (1:1 Fe:V), the difference between their affinities of formation and that of FeVO~4~ corresponds to the Pourbaix energy difference (-Δ*G*~pbx~).
This is plotted as a color map in the second diagram.
(See the source of this vignette for the code used to make the scale bar.)
```{r FeVO4, echo = 31:44, message = FALSE, results = "hide", fig.width = 11, fig.height = 5, out.width = "100%", pngquant = pngquant}
```
Now we locate the pH and Eh that maximize the affinity (that is, minimize Δ*G*~pbx~) of FeVO~4~ compared to the stable species.
In agreement with @SZS_17, this is in the stability field of Fe~2~O~3~ + Fe~2~V~4~O~13~.
```{r Gpbx_min, echo = 2:8, message = FALSE, fig.keep = "none"}
plot(1:10) # so we can run "points" in this chunk
imax <- arrayInd(which.max(aFeVO4_vs_stable), dim(aFeVO4_vs_stable))
pH <- d11$vals$pH[imax[1]]
Eh <- d11$vals$Eh[imax[2]]
points(pH, Eh, pch = 10, cex = 2, lwd = 2, col = "gold")
stable <- d11$names[d11$predominant[imax]]
text(pH, Eh, stable, adj = c(0.3, 2), cex = 1.2, col = "gold")
(Apbx <- range(aFeVO4_vs_stable[d11$predominant == d11$predominant[imax]]))
```
Although one point is drawn on the diagram, FeVO~4~ has the same Pourbaix energy difference with respect to the entire Fe~2~O~3~ + Fe~2~V~4~O~13~ field, as shown by the `range()` command (the values are dimensionless values of affinity, *A*/(*RT*) = -Δ*G*~pbx~/(*RT*)).
This can occur only if the decomposition reaction has no free O~2~ or H~2~, and means that in this case Δ*G*~pbx~ in the Fe~2~O~3~ + Fe~2~V~4~O~13~ field is equal to the energy above the hull.
To calculate the energy above the hull "by hand", let's set up the basis species to be the stable decomposition products we just found.
O~2~ is also needed to make a square stoichiometric matrix (i.e. same number of elements and basis species), but it does not appear in the reaction to form FeVO~4~ from the basis species.
`subcrt()` is used to automatically balance the formation reaction for 1 mole of FeVO~4~ and calculate the standard Gibbs energy of the reaction.
We first test that `r logK` of the reaction (calculated with `convert()`, which divides Δ*G*° by *-RT*) is the same as the dimensionless affinity for FeVO~4~ calculated above.
Then, the value of Δ*G*° in J/mol is converted to eV/mol, and finally eV/atom.
```{r hull, message = FALSE}
b <- basis(c("Fe2O3", "Fe2V4O13", "O2"))
J_mol <- subcrt("FeVO4", 1, T = 25)$out$G
stopifnot(all.equal(rep(convert(J_mol, "logK"), 2), Apbx))
eV_mol <- J_mol / 1.602176634e-19
eV_atom <- eV_mol / 6.02214076e23 / 6
round(eV_atom, 3)
stopifnot(round(eV_atom, 3) == 0.415)
```
This is equal to the value for the energy above the hull / atom for [triclinic FeVO~4~ on the MP website](https://next-gen.materialsproject.org/materials/mp-504509/) (0.415 eV, accessed on 2020-11-09 and 2021-02-19).
This shows that we successfully made a round trip starting with the input formation energies (eV/atom) from the Materials API, to standard Gibbs energy (J/mol) in the OBIGT database, and back out to energy above the hull (eV/atom).
The concept of using the stable minerals and aqueous species to calculate reaction energetics is formalized in the `mosaic()` function, which is described next.
Because this example modified the thermodynamic data for some minerals that are used below, we should restore the default OBIGT database before proceeding to the next section.
```{r reset, message = FALSE}
reset()
```
## Mosaic Stacking 1
*For a function that implements the workflow described below, see `stack_mosaic()` (added in CHNOSZ 2.0.0).*
A mosaic diagram shows the effects of changing basis species on the stabilities of minerals.
The Fe-S-O-H system is a common example: the speciation of aqueous sulfur species affects the stabilities of iron oxides and sulfides.
Examples of mosaic diagrams with Fe or other single metals are given elsewhere.
A mosaic stack is when predominance fields for minerals calculated in one mosaic diagram are used as input to a second mosaic diagram, where the minerals are now themselves basis species.
The example here shows the construction of a Cu-Fe-S-O-H diagram.
First we define the conditions and basis species.
It is important to put Cu^+^ first so that it will be used as the balance for the reactions with Cu-bearing minerals (which also have Fe).
Pyrite is chosen as the starting Fe-bearing basis species, which will be changed as indicated in `Fe.cr`.
```{r stack1_1, results = "hide", message = FALSE}
logaH2S <- -2
T <- 200
pH <- c(0, 14, res2)
O2 <- c(-48, -33, res2)
basis(c("Cu+", "pyrite", "H2S", "oxygen", "H2O", "H+"))
basis("H2S", logaH2S)
S.aq <- c("H2S", "HS-", "HSO4-", "SO4-2")
Fe.cr <- c("pyrite", "pyrrhotite", "magnetite", "hematite")
Fe.abbrv <- c("Py", "Po", "Mag", "Hem")
```
Now we calculate affinities for minerals in the Fe-S-O-H system that take account of the changing aqueous sulfur species in `S.aq`.
The result is used to make different layers of the diagram (1 and 2 are both made by the first call to `diagram()`):
1. Water stability region (gray shading)
2. Predominance fields for the aqueous S species (blue text and dashed lines)
3. Stability areas for the Fe-bearing minerals (black text and lines)
```{r stack1_2, eval = FALSE, echo = 1:4}
species(Fe.cr)
mFe <- mosaic(S.aq, pH = pH, O2 = O2, T = T)
diagram(mFe$A.bases, lty = 2, col = 4, col.names = 4, italic = TRUE, dx = c(0, 1, 0, 0), dy = c(-1.5, 0, 1, 0))
dFe <- diagram(mFe$A.species, add = TRUE, lwd = 2, names = Fe.abbrv, dx = c(0, 0.5, 0, 0), dy = c(-1, 0, 0.5, 0))
FeCu.cr <- c("chalcopyrite", "bornite")
Cu.cr <- c("copper", "cuprite", "tenorite", "chalcocite", "covellite")
FeCu.abbrv <- c("Ccp", "Bn", "Cu", "Cpr", "Tnr", "Cct", "Cv")
species(c(FeCu.cr, Cu.cr))
mFeCu <- mosaic(list(S.aq, Fe.cr), pH = pH, O2 = O2,
T = T, stable = list(NULL, dFe$predominant))
col <- c("#FF8C00", rep(2, 6))
lwd <- c(2, 1, 1, 1, 1, 1, 1)
dy = c(0, 0, 0, 0, 0, 1, 0)
diagram(mFeCu$A.species, add = TRUE, col = col, lwd = lwd, col.names = col, bold = TRUE, names = FeCu.abbrv, dy = dy)
TPS <- c(describe.property(c("T", "P"), c(T, "Psat")), expression(sum(S) == 0.01*m))
legend("topright", TPS, bty = "n")
title("Cu-Fe-S-O-H (minerals only)", font.main = 1)
```
Next we load the Cu-bearing minerals and calculate their affinities while changing *both* the aqueous sulfur species and the Fe-bearing minerals whose stability fields were just calculated.
The latter step is the key to the mosaic stack and is activated by supplying the calculated stabilities of the Fe-bearing minerals in the `stable` argument.
This is a list whose elements correspond to each group of changing basis species given in the first argument.
The NULL means that the abundances of S-bearing aqueous species are calculated according to the default in `mosaic()`, which uses `equilibrate()` to compute the continuous transition between them ("blending").
Because the Fe-bearing minerals are the second group of changing basis species (`Fe.cr`), their stabilities are given in the second position of the `stable` list.
The result is used to plot the last layer of the diagram:
4. Stability areas for Cu-bearing minerals (red text and lines; orange for chalcopyrite)
After that we add the legend and title.
```{r stack1_2, echo=5:17, results = "hide", message = FALSE, fig.width = 6, fig.height = 5, out.width = "75%", fig.align = "center", pngquant = pngquant}
```
This diagram has a distinctive chalcopyrite "hook" surrounded by a thin bornite field.
Only the chalcopyrite-bornite reaction in the pyrite field is shown in some published diagrams [e.g. @And75;@Gio02], but diagrams with a similar chalcopyrite wedge or hook geometry can be seen in @BBR77 and @Bri80.
## Mosaic Stacking 2
The previous diagram shows the relative stabilities of minerals only.
The next diagram adds aqueous species to the system.
The position of the boundaries between the stability fields for minerals and aqueous species are calculated for a given activity for the latter, in this case 10^-6^.
<button id="B-stack2" onclick="ToggleDiv('stack2')">Show code</button>
<div id="D-stack2" style="display: none">
```{r stack2, eval = FALSE}
# Define system
pH <- c(0, 14, res2)
O2 <- c(-48, -33, res2)
T <- 200
logmS <- -2
m_NaCl <- 0.1
logm_aq <- -6 # for both Fe- and Cu-bearing aq species
# Basis species
S.aq <- c("H2S", "HS-", "HSO4-", "SO4-2")
# Minerals
Fe.cr <- c("pyrite", "pyrrhotite", "magnetite", "hematite")
Fe.abbrv <- c("Py", "Po", "Mag", "Hem")
FeCu.cr <- c("chalcopyrite", "bornite")
Cu.cr <- c("copper", "cuprite", "tenorite", "chalcocite", "covellite")
FeCu.abbrv <- c("Ccp", "Bn", "Cu", "Cpr", "Tnr", "Cct", "Cv")
# Aqueous species
iFe.aq <- retrieve("Fe", c("S", "O", "H", "Cl"), "aq")
Fe.aq <- info(iFe.aq)$name
iCu.aq <- retrieve("Cu", c("S", "O", "H", "Cl"), "aq")
Cu.aq <- info(iCu.aq)$name
# Expressions for making the legend
TPexpr <- describe.property(c("T", "P"), c(T, "Psat"))
Sexpr <- as.expression(bquote(sum(S) == .(10^logmS)*m))
NaClexpr <- as.expression(bquote(NaCl == .(m_NaCl)*m))
aqexpr <- as.expression(bquote("("*aq*")"[italic(i)] == 10^.(logm_aq)*m))
# Setup basis species
basis(c("Cu+", "pyrite", "H2S", "oxygen", "H2O", "H+", "Cl-"))
basis("H2S", logmS)
nacl <- NaCl(m_tot = m_NaCl, T = T, P = "Psat")
basis("Cl-", log10(nacl$m_Cl))
# Fe-bearing minerals
species(Fe.cr)
# Add aqueous species 20210220
species(iFe.aq, logm_aq, add = TRUE)
mFe <- mosaic(S.aq, pH = pH, O2 = O2, T = T, IS = nacl$IS)
# Start plot with just the fields for transparency effect
dFe <- diagram(mFe$A.species, lwd = 0, names = FALSE)
# Cu-bearing minerals
species(c(FeCu.cr, Cu.cr))
# Add aqueous species 20210220
species(iCu.aq, logm_aq, add = TRUE)
## Mosaic with all Fe species as basis species
#mFeCu <- mosaic(list(S.aq, c(Fe.cr, Fe.aq)), pH = pH, O2 = O2, T = T, stable = list(NULL, dFe$predominant))
# Use only predominant Fe species as basis species (to speed up calculation) 20210224
predom <- dFe$predominant
ipredom <- sort(unique(as.numeric(predom)))
for(i in seq_along(ipredom)) predom[dFe$predominant == ipredom[i]] <- i
Fe.predom <- c(Fe.cr, Fe.aq)[ipredom]
# Use loga_aq argument to control the activity of aqueous species in mosaic calculation 20220722
# c(NA, logm_aq) means to use:
# basis()'s value for logact of aqueous S species
# logm_aq for logact of aqueous Fe species
mFeCu <- mosaic(list(S.aq, Fe.predom), pH = pH, O2 = O2, T = T, stable = list(NULL, predom), IS = nacl$IS, loga_aq = c(NA, logm_aq))
# Adjust labels
bold <- c(rep(TRUE, length(FeCu.abbrv)), rep(FALSE, length(Cu.aq)))
names <- c(FeCu.abbrv, Cu.aq)
srt <- dx <- dy <- rep(0, length(names))
cex <- rep(1, length(names))
dx[names == "Cu"] <- -1.5
dx[names == "Bn"] <- 1.4
dx[names == "CuHS"] <- 1
dx[names == "Cu+"] <- -0.5
dy[names == "Cu"] <- 3
dx[names == "Cct"] <- -2
dy[names == "Cct"] <- 4
dy[names == "CuHS"] <- 1
dy[names == "Bn"] <- -0.9
dx[names == "CuCl2-"] <- -1
dy[names == "CuCl2-"] <- 2
cex[names == "Bn"] <- 0.8
srt[names == "Bn"] <- 85
# Highlight Ccp field
col.names <- col <- rep(2, nrow(mFeCu$A.species$species))
col[1] <- "#FF8C00"
col.names[1] <- "#FF8C00"
lwd <- rep(1, nrow(mFeCu$A.species$species))
lwd[1] <- 2
diagram(mFeCu$A.species, add = TRUE, lwd = lwd, col = col, col.names = col.names, names = names, bold = bold, dx = dx, dy = dy, cex.names = cex, srt = srt)
# Add second Cu label
text(12.3, -47, "Cu", col = 2, font = 2)
# Plot the Fe-system lines and names "on top" so they are not covered by fill colors
diagram(mFe$A.bases, add = TRUE, lty = 2, col = 4, names = FALSE, fill = NA)
bold <- c(rep(TRUE, length(Fe.abbrv)), rep(FALSE, length(Fe.aq)))
names <- c(Fe.abbrv, Fe.aq)
srt <- dx <- dy <- rep(0, length(names))
cex <- rep(1, length(names))
dy[names == "Hem"] <- 0.5
dy[names == "Mag"] <- -0.8
dx[names == "Hem"] <- -0.5
dx[names == "Mag"] <- 0.25
dx[names == "Fe+2"] <- 0.5
dx[names == "FeO2-"] <- 1
dy[names == "FeO2-"] <- -3
dx[names == "HFeO2-"] <- -0.5
dy[names == "HFeO2-"] <- 1
srt[names == "Mag"] <- 83
srt[names == "FeSO4"] <- 90
diagram(mFe$A.species, add = TRUE, lwd = 2, names = names, bold = bold, dx = dx, dy = dy, cex.names = cex, srt = srt, fill = NA)
legend("topright", c(TPexpr, Sexpr, NaClexpr, aqexpr), bty = "n")
title("Cu-Fe-S-O-H-Cl (minerals and aqueous species)", font.main = 1)
# Restore default OBIGT database
OBIGT()
```
</div>
```{r stack2, echo = FALSE, results = "hide", message = FALSE, fig.width = 6, fig.height = 5, out.width = "75%", fig.align = "center", pngquant = pngquant}
```
After running the code to make this diagram, we can list the reference keys for the minerals and aqueous species.
```{r stack2.refs, message = FALSE}
minerals <- list(Fe.cr = Fe.cr, Cu.cr = Cu.cr, FeCu.cr = FeCu.cr)
aqueous <- list(S.aq = S.aq, Fe.aq = Fe.aq, Cu.aq = Cu.aq)
allspecies <- c(minerals, aqueous)
iall <- lapply(allspecies, info)
allkeys <- lapply(iall, function(x) thermo.refs(x)$key)
allkeys
```
The next code chunk prepends `@` to the reference keys and uses the chunk option [`results = 'asis'`](https://bookdown.org/yihui/rmarkdown-cookbook/results-asis.html) to insert the citations into the R Markdown document in chronological order.
```{r stack2.cite, results = "asis"}
allyears <- lapply(iall, function(x) thermo.refs(x)$year)
o <- order(unlist(allyears))
keys <- gsub("\\..*", "", unique(unlist(allkeys)[o]))
cat(paste(paste0("@", keys), collapse = "; "))
```
## Mixing 2
The previous diagram shows a stability boundary between chalcopyrite and bornite but does not identify the stable *assemblages* that contain these minerals.
This is where `mix()` can help.
Following the workflow described in **Mixing 1**, we first calculate individual diagrams for Fe-S-O-H and Cu-S-O-H, which are overlaid on the first plot and saved in `dFe` and `dCu`.
We then calculate the affinities for the bimetallic Cu and Fe minerals and run them through `diagram()` without actually making a plot, but save the result in `dFeCu`.
Then, we combine the results using `mix()` to define different proportions of Fe and Cu.
<button id="B-mixing2" onclick="ToggleDiv('mixing2')">Show code</button>
<div id="D-mixing2" style="display: none">
```{r mixing2, eval = FALSE}
par(mfrow = c(2, 2))
logaH2S <- -2
T <- 200
pH <- c(0, 14)
O2 <- c(-60, -25)
basis(c("Cu+", "Fe+2", "H2S", "oxygen", "H2O", "H+"))
basis("H2S", logaH2S)
S.aq <- c("H2S", "HS-", "HSO4-", "SO4-2")
Fe.cr <- c("pyrite", "pyrrhotite", "magnetite", "hematite")
Cu.cr <- c("copper", "cuprite", "tenorite", "chalcocite", "covellite")
FeCu.cr <- c("chalcopyrite", "bornite")
species(Fe.cr)
mFe <- mosaic(S.aq, pH = pH, O2 = O2, T = T)
diagram(mFe$A.bases, lty = 2, col = 4, col.names = 4, italic = TRUE, dx = c(0, 1, 0, 0), dy = c(-1, 0, -2, 0))
names <- info(info(Fe.cr))$abbrv
dFe <- diagram(mFe$A.species, add = TRUE, names = names)
species(Cu.cr)
mCu <- mosaic(S.aq, pH = pH, O2 = O2, T = T)
names <- info(info(Cu.cr))$abbrv
col.names <- rep(2, length(names))
col.names[1] <- 0
dCu <- diagram(mCu$A.species, add = TRUE, col = 2, col.names = col.names, names = names)
text(12, -55, "Cu", col = 2)
legend("topright", legend = lTP(T, "Psat"), bty = "n")
title(paste("Fe-S-O-H and Cu-S-O-H; Total S =", 10^logaH2S, "m"))
species(FeCu.cr)
mFeCu <- mosaic(S.aq, pH = pH, O2 = O2, T = T)
names <- info(info(FeCu.cr))$abbrv
dFeCu <- diagram(mFeCu$A.species, plot.it = FALSE, names = names)
fill <- function(a) {
ifelse(grepl("Ccp", a$species$name), "#FF8C0088",
ifelse(grepl("Bn", a$species$name), "#DC143C88", NA)
)}
srt <- function(a) ifelse(a$species$name %in% c("Mag+Bn", "Mag+Ccp"), 80, 0)
cex.names <- function(a) ifelse(a$species$name %in% c("Mag+Bn", "Mag+Ccp", "Mag+Cct"), 0.8, 1)
dx <- function(a) sapply(a$species$name, switch, "Mag+Bn" = 0.15, "Mag+Cct" = 0.5, 0)
dy <- function(a) sapply(a$species$name, switch, "Py+Bn" = -1, "Po+Bn" = -0.8, "Po+Cu" = -0.8, "Mag+Ccp" = -1, 0)
a11 <- mix(dFe, dCu, dFeCu)
diagram(a11, fill = fill(a11), srt = srt(a11), min.area = 0.01, dx = dx(a11), dy = dy(a11), cex.names = cex.names(a11))
title("Fe:Cu = 1:1")
a21 <- mix(dFe, dCu, dFeCu, c(2, 1))
diagram(a21, fill = fill(a21), srt = srt(a21), min.area = 0.01, dx = dx(a21), dy = dy(a21), cex.names = cex.names(a21))
title("Fe:Cu = 2:1")
a12 <- mix(dFe, dCu, dFeCu, c(1, 2))
diagram(a12, fill = fill(a12), srt = srt(a12), min.area = 0.01, dx = dx(a12), dy = dy(a12), cex.names = cex.names(a12))
title("Fe:Cu = 1:2")
```
</div>
```{r mixing2, echo = FALSE, results = "hide", message = FALSE, fig.width = 8, fig.height = 6.5, out.width = "100%", pngquant = pngquant}
```
These diagrams show that changing the amounts of the metals affects the stability of minerals involved in reactions with chalcopyrite.
At a 1:1 ratio of Fe:Cu, chalcopyrite is a stable single-mineral assemblage.
At a 2:1 ratio, pyrite, pyrrhotite, or magnetite can coexist in a two-phase assemblage with chalcopyrite.
At a 1:2 ratio, an assemblage consisting of the two bimetallic minerals (chalcopyrite and bornite) is stable.
## Mosaic Stacking 3
The results of a mosaic stack can also be processed with `mash()` to label each region with the minerals from both systems.
For this example, the speciation of aqueous sulfur is not considered; instead, the fugacity of S~2~ is a plotting variable.
The stable Fe-bearing minerals (Fe-S-O-H) are used as the changing basis species to make the diagram for Cu-bearing minerals (Cu-Fe-S-O-H).
Then, the two diagrams are mashed to show all minerals in a single diagram.
Greener colors are used to indicate minerals with less S~2~ and more O~2~ in their formation reactions.
<button id="B-stack3" onclick="ToggleDiv('stack3')">Show code</button>
<div id="D-stack3" style="display: none">
```{r stack3, eval = FALSE}
T <- 125
layout(matrix(c(1, 2, 3, 3), nrow = 2), widths = c(1, 1.5))
# Fe-S-O-H diagram
basis(c("copper", "hematite", "S2", "oxygen", "H2O", "H+", "Cl-"))
bFe <- species(c("hematite", "magnetite", "pyrite"))$name
aFe <- affinity(S2 = c(-34, -10, res1), O2 = c(-55, -40, res1), T = T)
# Order species by a function of composition to make colors
oFe <- order(aFe$species$S2 - aFe$species$O2)
fill <- terrain.colors(length(oFe), alpha = 0.2)[oFe]
abbrv <- info(aFe$species$ispecies)$abbrv
dFe <- diagram(aFe, names = abbrv, fill = fill)
title("Fe-S-O-H")
# Cu-Fe-S-O-H diagram based on reactions with the
# stable Fe-bearing minerals (mosaic stack)
bCu <- species(c("copper", "chalcocite", "covellite", "chalcopyrite", "bornite"))$name
mCu <- mosaic(bFe, S2 = c(-34, -10, res1), O2 = c(-55, -40, res1),
T = T, stable = list(dFe$predominant))
oCu <- order(mCu$A.species$species$S2 - mCu$A.species$species$O2)
fill <- terrain.colors(length(oCu), alpha = 0.2)[oCu]
abbrv <- info(mCu$A.species$species$ispecies)$abbrv
dCu <- diagram(mCu$A.species, names = abbrv, fill = fill, dx = c(0, 0, 0, 0, 1.8))
title("Cu-Fe-S-O-H")
# Mash the diagrams and adjust labels
aFeCu <- mash(dFe, dCu)
names <- aFeCu$species$name
dx <- dy <- srt <- rep(0, length(names))
cex <- rep(1, length(names))
cex[names %in% c("Hem+Ccp", "Hem+Cv")] <- 0.8
srt[names %in% c("Mag+Cu", "Hem+Cu")] <- 90
srt[names %in% c("Mag+Bn", "Hem+Bn")] <- 63
srt[names %in% c("Mag+Ccp", "Hem+Ccp")] <- 68
srt[names %in% c("Py+Bn", "Py+Cv")] <- 90
dx[names == "Hem+Ccp"] <- -0.4
dy[names == "Hem+Ccp"] <- -0.5
oFeCu <- order(aFeCu$species$S2 - aFeCu$species$O2)
fill <- terrain.colors(length(oFeCu), alpha = 0.2)[oFeCu]
diagram(aFeCu, cex.names = cex, srt = srt, dx = dx, dy = dy, fill = fill)
legend("topleft", legend = lTP(T, "Psat"), bg = "white")
title("Cu-Fe-S-O-H")
```
</div>
```{r stack3, echo = FALSE, results = "hide", message = FALSE, fig.width = 6, fig.height = 4, out.width = "100%", pngquant = pngquant}
```
The resulting diagram is similar to Figure 2 of @Sve87; that diagram also shows calculations of the solubility of Cu and concentration of SO~4~^-2^ in model Cu ore-forming fluids.
The `solubility()` function can be used to calculate the total concentration of Cu in different complexes in solution (listed in the `iaq` argument).
The `bases` argument triggers a `mosaic()` calculation, so that the solubility corresponds that that of stable minerals at each point on the diagram.
The pH for these calculations is set to 6, and the molality of free Cl^-^, which affects the formation of the Cu chloride complexes, is estimated based on the composition of fluids from Table 2 of @Sve87 (ca. 80000 mg Cl / kg H~2~O) and the `NaCl()` function in CHNOSZ.
This also gives an estimated ionic strength, which is used in the following `mosaic()` and `affinity()` calls to calculate activity coefficients.
<button id="B-solubility" onclick="ToggleDiv('solubility')">Show code</button>
<div id="D-solubility" style="display: none">
```{r solubility, eval = FALSE}
par(mfrow = c(1, 3))
basis("pH", 6)
# Estimate the molality of Cl for ca. 80,000 mg/kg solution (Table 2 of Sverjensky, 1987)
m_tot <- 80000 / mass("Cl") / 1000
calc <- NaCl(T = T, m_tot = m_tot)
# Use log molality here, not log activity, because
# activity coefficients are calculated by setting IS below
basis("Cl-", log10(calc$m_Cl))
# Initial setup: dissolve a single mineral to form aqueous Cu complexes
species("copper")
iaq <- retrieve("Cu", c("O", "H", "Cl", "S"), "aq")
# Function to calculate solubility of Cu for stable assemblages of Fe and Cu minerals
# (i.e. equilibrium is imposed with all of these minerals, not only Cu(s))
mfun <- function() {
s <- solubility(iaq, bases = list(bFe, bCu), S2 = c(-34, -10, res1), O2 = c(-55, -40, res1),
T = T, IS = calc$IS, stable = list(dFe$predominant, dCu$predominant))
s <- convert(s, "ppm")
diagram(aFeCu, names = NA, col = "gray", fill = fill)
diagram(s, type = "loga.balance", levels = 10^(-3:3), add = TRUE)
diagram(s, type = "loga.balance", levels = 35, add = TRUE, lwd = 3, col = 6, contour.method = NA)
}
# DIAGRAM 1
mfun()
title("Cu (ppm)")
# Calculate logK for CuCl2- dissociation at 125 °C
logK <- subcrt(c("CuCl2-", "Cu+", "Cl-"), c(-1, 1, 2), T = T)$out$logK
# Sverjensky (1987) used Helgeson (1969) value, which is ca. -5.2
dlogK <- logK - -5.2
# Calculate the difference in ΔG° corresponding to this logK difference
dG_J <- convert(dlogK, "G", T = convert(T, "K"))
# We should use calories here because the database values are in calories 20220604
stopifnot(info(info("CuCl2-"))$E_units == "cal")
dG_cal <- convert(dG_J, "cal")
# Apply this difference to the CuCl2- entry in OBIGT
newG <- info(info("CuCl2-"))$G + dG_cal
mod.OBIGT("CuCl2-", G = newG)
# Do the same thing for CuCl3-2
logK <- subcrt(c("CuCl3-2", "Cu+", "Cl-"), c(-1, 1, 3), T = T)$out$logK
dlogK <- logK - -5.6
dG_J <- convert(dlogK, "G", T = convert(T, "K"))
stopifnot(info(info("CuCl3-2"))$E_units == "cal")
dG_cal <- convert(dG_J, "cal")
newG <- info(info("CuCl3-2"))$G + dG_cal
mod.OBIGT("CuCl3-2", G = newG)
# DIAGRAM 2
mfun()
title("Cu (ppm)", line = 1.7)
CuCl2 <- expr.species("CuCl2-")
CuCl3 <- expr.species("CuCl3-2")
title(bquote("Helgeson (1969)"~.(CuCl2)~and~.(CuCl3)), line = 0.9)
# Set up system to dissolve S2(gas)
basis(c("S2", "copper", "hematite", "oxygen", "H2O", "H+", "Cl-"))
basis("pH", 6)
species("S2")
# Calculate concentration of SO4-2
iaq <- info("SO4-2")
s <- solubility(iaq, S2 = c(-34, -10, res1), O2 = c(-55, -40, res1), T = T, IS = calc$IS, in.terms.of = "SO4-2")
s <- convert(s, "ppm")
# DIAGRAM 3
diagram(aFeCu, names = NA, col = "gray", fill = fill)
diagram(s, type = "loga.balance", levels = 10^(-3:3), add = TRUE)
diagram(s, type = "loga.balance", levels = 35, add = TRUE, lwd = 3, col = 6, contour.method = NA)
title(bquote(bold(.(expr.species("SO4-2"))~"(ppm)")))
```
</div>
```{r solubility, echo = FALSE, results = "hide", message = FALSE, fig.width = 7, fig.height = 3, out.width = "100%", fig.align = "center", pngquant = pngquant}
```
After running the code above, we can inspect the value of `calc` to show the estimated ionic strength and activity of Cl^-^; the latter is very close to unity.
```{r NaCl}
# Ionic strength
calc$IS
# Logarithm of activity of Cl-
log10(calc$m_Cl * calc$gam_Cl)
```
The thick magenta lines indicate the 35 ppm contour for Cu and SO~4~^-2^.
The first plot shows a lower Cu solubility in this region compared to Figure 2 of @Sve87.
The difference is likely due to lower stabilities of Cu(I) chloride complexes in the default OBIGT database, compared to those available at the time [@Hel69].
For the second plot, the standard Gibbs energies of CuCl~2~^-^ and CuCl~3~^-2^ are adjusted so that the `logK` for their dissociation reactions at 125 °C matches values interpolated from Table 5 of @Hel69.
Here are the `logK` values after the adjustment, followed a `reset()` call to compare the values with the default database, which is also used for later examples in this vignette.
(`T` was set to 125 above.)
```{r logK, message = FALSE}
# logK values interpolated from Table 5 of Helgeson (1969)
subcrt(c("CuCl2-", "Cu+", "Cl-"), c(-1, 1, 2), T = T)$out$logK
subcrt(c("CuCl3-2", "Cu+", "Cl-"), c(-1, 1, 3), T = T)$out$logK
# Default OBIGT database
reset()
subcrt(c("CuCl2-", "Cu+", "Cl-"), c(-1, 1, 2), T = T)$out$logK
subcrt(c("CuCl3-2", "Cu+", "Cl-"), c(-1, 1, 3), T = T)$out$logK
```
The higher stability of these complexes from @Hel69 causes the 35 ppm contour to move closer to the position shown by @Sve87.
Interestingly, the calculation here also predict substantial increases of Cu concentration of Cu at high *f*~S<sub>2</sub>~ and low *f*~O<sub>2</sub>~, due to the formation of bisulfide complexes with Cu.
The aqueous species considered in the calculation can be seen like this:
```{r iCu.aq}
names(iCu.aq)
```
CuHS and Cu(HS)~2~^-^ can be excluded by removing S from the `retrieve()` call above (i.e. only `c("O", "H", "Cl")` as the elements in possible ligands); doing so precludes a high concentration of aqueous Cu in the highly reduced, sulfidic region.
The third plot for the concentation of SO~4~^-2^ is simply made by using `affinity()` to calculate the affinity of its formation reaction as a function of *f*~S<sub>2</sub>~ and *f*~O<sub>2</sub>~ at pH 6 and 125 °C, then using `solubility()` to calculate the solubility of S~2~(gas), expressed in terms of moles of SO~4~^-2^ in order to calculate parts per million (ppm) by weight.
## Secondary Balancing
Predominance diagrams in CHNOSZ are made using the maximum affinity method, where the affinities of formation reactions of species are divided by the *balancing coefficients* [@Dic19].
Usually, these balancing coefficients are taken from the formation reactions themselves; for example, if they are the coefficients on the Fe-bearing basis species, then the reactions are said to be "balanced on Fe".
Some diagrams in the literature are made with secondary balancing constraints in addition to the primary ones.
For example, reactions of Fe-bearing minerals are balanced on Fe, and reactions of Cu-bearing minerals are balanced on Cu; these are both primary balancing coefficients.
Then, reactions between all minerals are balanced on H^+^ as the secondary balancing coefficients.
The core concept is to apply the secondary balance while also maintaining the primary balance; a method to do this has been implemented in the `rebalance()` function.
Different parts of the script to make the diagrams are described below; press the button to show the entire script.
<button id="B-rebalance" onclick="ToggleDiv('rebalance')">Show code</button>
<div id="D-rebalance" style="display: none">
```{r rebalance, eval = FALSE}
mat <- matrix(c(1, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5), byrow = TRUE, nrow = 2)
layout(mat)
par(font.main = 1)
basis(c("Fe+2", "Cu+", "hydrogen sulfide", "oxygen", "H2O", "H+"))
xlab <- ratlab("Fe+2", "Cu+")
### PRIMARY balancing
# Only Fe-bearing minerals
species(c("pyrite", "pyrrhotite", "magnetite", "hematite"))
aFe <- affinity("Fe+2" = c(0, 12), O2 = c(-40, -16), T = 400, P = 2000)
names <- info(aFe$species$ispecies)$abbrv
dFe <- diagram(aFe, xlab = xlab, names = names)
title(bquote("Only Fe; 1° balance:" ~ .(expr.species(dFe$balance))))
label.plot("A")
# Only Cu-bearing minerals
species(c("covellite", "chalcocite", "tenorite", "cuprite"))
aCu <- affinity(aFe) # argument recall
names <- info(aCu$species$ispecies)$abbrv
dCu <- diagram(aCu, xlab = xlab, names = names)
title(bquote("Only Cu; 1° balance:" ~ .(expr.species(dCu$balance))))
label.plot("B")
# Only Fe- AND Cu-bearing minerals
species(c("chalcopyrite", "bornite"))
aFeCu <- affinity(aFe)
names <- info(aFeCu$species$ispecies)$abbrv
dFeCu <- diagram(aFeCu, xlab = xlab, balance = "H+", names = names)
title(bquote("Only Fe+Cu; 1° balance:" ~ .(expr.species(dFeCu$balance))))
label.plot("C")
### SECONDARY balancing
# Fe- or Cu-bearing minerals
ad1 <- rebalance(dFe, dCu, balance = "H+")
names <- info(ad1$species$ispecies)$abbrv
d1 <- diagram(ad1, xlab = xlab, balance = 1, names = names)
title(bquote("Only Fe or Cu; 2° balance:" ~ .(expr.species("H+"))))
label.plot("D")
# All minerals
d1$values <- c(dFe$values, dCu$values)
ad2 <- rebalance(d1, dFeCu, balance = "H+")
names <- info(ad2$species$ispecies)$abbrv
diagram(ad2, xlab = xlab, balance = 1, names = names)
title(bquote("Fe and/or Cu; 2° balance:" ~ .(expr.species("H+"))))
label.plot("E")
db <- describe.basis(3)
leg <- lex(lTP(400, 2000), db)
legend("bottomleft", legend = leg, bty = "n")
```
</div>
We first define basis species to contain both Cu- and Fe-bearing species.
The \emph{x} axis is the ratio of activities of Fe^+2^ and Cu^+^; the label is made with `ratlab()`.
```{r rebalance, eval = FALSE, echo = 5:6}
```
We then calculate the diagrams for the primary balancing coefficients, for the groups of only Fe-, only Cu-, and only Fe+Cu-bearing minerals.
It is obvious that the first two systems are balanced on Fe and Cu, respectively, but the third has a somewhat unusual balance: H^+^.
See Reaction 4 of @MH85 for an example.
```{r rebalance, eval = FALSE, echo = 10:33}
```
Now comes the secondary balancing, where all reactions, not only that between bornite and chalcopyrite, are balanced on H^+^.
We first rebalance the diagrams for the Fe- or Cu-bearing minerals to make diagram D.
Note that after secondary balancing with `rebalance()`, the argument `balance = 1` should be used in `diagram()` to prevent further balancing.
This is because `rebalance()` preserves the primary balancing for Fe- and Cu-bearing minerals (internally the "plotvals" components of `dFe` and `dCu`).
Then we rebalance diagrams D and C to make the final diagram in E.
The fields in this diagram are labeled with mineral abbreviations from the OBIGT database.
```{r rebalance, eval = FALSE, echo = 36:49}
```
```{r rebalance, echo = FALSE, results = "hide", message = FALSE, fig.width = 6.5, fig.height = 5, out.width = "100%", fig.align = "center", pngquant = pngquant}
```
The final diagram is like one shown in Figure 5 of @Bri80 and Figure 5 of @MH85.
*Challenge*: Although the diagram here is drawn only for H~2~S in the basis species, take it a step further and make a mosaic diagram to account for the stability of HSO~4~^-^ at high oxygen fugacity.
## Other Possibilities
Conceptually, the methods described above treat different metal-bearing elements as parts of distinct chemical systems that are then joined together.
Other methods may be more suitable for considering multiple metals (or other elements) in one system.
### Balancing on a Non-Metal
As shown in the **secondary balancing** example, there is no requirement that the balancing coefficients come from a metal-bearing species.
It is possible to make diagrams for minerals with different metallic elements simply by using a non-metallic element as the primary balance.
Here is an example for the Cu-Fe-S-O-H system.
The reactions are balanced on O~2~, which means that no O~2~ appears in the reaction between any two minerals, but Fe^+2^ and/or Cu^+^ can be present, depending on the chemical composition.
Saturation limits are shown for species that have no O~2~ in their formation reactions.
```{r non-metal, results = "hide", message = FALSE, fig.width = 6, fig.height = 5, out.width = "80%", fig.align = "center", pngquant = pngquant}
basis(c("Fe+2", "Cu+", "hydrogen sulfide", "oxygen", "H2O", "H+"))
basis("H2S", 2)
species(c("pyrite", "magnetite", "hematite", "covellite", "tenorite",
"chalcopyrite", "bornite"))
a <- affinity("Cu+" = c(-8, 2, 500), "Fe+2" = c(-4, 12, 500), T = 400, P = 2000)
names <- info(a$species$ispecies)$abbrv
d <- diagram(a, xlab = ratlab("Cu+"), ylab = ratlab("Fe+2"), balance = "O2", names = names)
title(bquote("Cu-Fe-S-O-H; 1° balance:" ~ .(expr.species(d$balance))))
# Add saturation lines
species(c("pyrrhotite", "ferrous-oxide", "chalcocite", "cuprite"))
asat <- affinity(a) # argument recall
names <- asat$species$name
names[2] <- "ferrous oxide"
diagram(asat, type = "saturation", add = TRUE, lty = 2, col = 4, names = names)
legend("topleft", legend = lTP(400, 2000), bty = "n")
```
This example was prompted by Figure 3 of @MH85; earlier versions of the diagram are in @HBL69 and @Hel70a.
In some ways this is like the inverse of the **mosaic stacking** example.
There, reactions were balanced on Fe or Cu, and *f*~O<sub>2</sub>~ and pH were used as plotting variables.
Here, the reactions are balanced on O~2~ and implicitly on H^+^ through the activity ratios with *a*~Fe^+2^~ and *a*~Cu^+^~, which are the plotting variables.
More common diagrams of this type are balanced on Si or Al.
See `demo(saturation)` for an example in the H~2~O-CO~2~-CaO-MgO-SiO~2~ system.
### Mosaic Combo
Instead of adding minerals with different metals by stacking mosaic diagrams, it may be possible to include two different metals in the basis species and formed species.
The `mosaic()` and `equilibrate()` functions can be combined to balance on two different elements.
The example here compares two methods applied to N-, C-, and N+C-bearing species because bimetallic aqueous species are not currently available in the OBIGT database.
The total activities used here are modified from the example for sedimentary basin brines described by @Sho93, which is also the source of the thermodynamic parameters for acetamide.
1. The "effective equilibrium constant" (*K*^eff^) method [@RBG_21] is used to calculate the activity of acetamide for a total activities of neutral and ionized species, i.e. ∑(ammonia and ammonium) and ∑(acetic acid and acetate).
2. Using the mosaic combo method, the `mosaic()` command calculates equilibrium activities of NH~3~ and NH~4~^+^ for a given total activity of N in the basis species, and calculates the corresponding affinities of the formed species.
Then, the `equilibrate()` command calculates equilibrium activities of the formed species for given total activity of C, and combines them with the activities of the changing basis species (NH~3~ and NH~4~^+^).
The mosaic combo method (solid black line) produces results equivalent to those of the *K*^eff^ method (dashed blue line).
<button id="B-mosaic-combo" onclick="ToggleDiv('mosaic-combo')">Show code</button>
<div id="D-mosaic-combo" style="display: none">
```{r mosaic-combo, eval = FALSE}
## METHOD 1: Keff equation (Robinson et al., 2021)
# A function to calculate Keff for any combination of T and pH
Keff <- function(T = 25, pH = 7) {
# Make T and pH the same length
len <- max(length(T), length(pH))
T <- rep(T, length.out = len)
pH <- rep(pH, length.out = len)
# Calculate activity of H+
aH <- 10^(-pH)
# Calculate logKs
logK1 <- subcrt(c("acetic acid", "NH3", "acetamide", "H2O"), c(-1, -1, 1, 1), T = T)$out$logK
logK2 <- subcrt(c("acetic acid", "acetate", "H+"), c(-1, 1, 1), T = T)$out$logK
logK3 <- subcrt(c("NH3", "H+", "NH4+"), c(-1, -1, 1), T = T)$out$logK
# Calculate Ks
K1 <- 10^logK1
K2 <- 10^logK2
K3 <- 10^logK3
# Calculate Keff (Eq. 7)
Keff <- K1 * (1 + K2 / aH) ^ -1 * (1 + K3 * aH) ^ -1
Keff
}
# Calculate logKeff as a function of pH at 100 °C
res <- 128
pH <- seq(0, 14, length.out = res)
T <- 100
logKeff <- log10(Keff(pH = pH, T = T))
# Calculate activity of acetamide for
# acetic acid + acetate = 0.01 m
# ammonia + ammonium = 0.001 m
logAc <- log10(0.01)
logAm <- log10(0.001)
logAcAm <- logKeff + logAc + logAm
## METHOD 2: Mosaic combo
# Define total activities
a_N <- 0.001
# This is 2 * 0.01 because acetic acid has 2 carbons
a_C <- 2 * 0.01
loga_N <- log10(a_N)
loga_C <- log10(a_C)
# Setup basis species
basis(c("CO2", "NH3", "O2", "H2O", "H+"))
basis("NH3", loga_N)
# Load all C-bearing species (including acetamide)
species(c("acetamide", "acetic acid", "acetate"))
# Calculate distribution of C-bearing species accounting for ammonia/ammonium speciation
m <- mosaic(c("NH3", "NH4+"), pH = c(0, 14, res), T = T)
e <- equilibrate(m, loga.balance = loga_C)
# Plot and label diagram
# Start with empty diagram
diagram(e, ylim = c(-8, -0), lty = 0, names = FALSE)
# Add pH = 6 line
abline(v = 6, col = "gray60", lty = 5)
# Add line for acetamide activity calculated with Keff
lines(pH, logAcAm, col = 4, lwd = 6, lty = 2)
# Add lines from CHNOSZ calculations
diagram(e, add = TRUE, lty = c(2, 3, 1, 2, 3), lwd = c(1, 1, 2, 1, 1), dx = c(-0.2, 0.2, -2.5, 0, 0), dy = c(0.1, 0.1, -1, 0.1, 0.1), srt = c(0, 0, 52, 0, 0))
tN <- paste("Total N in basis species =", format(a_N, scientific = FALSE), "m")
tC <- paste("Total C in formed species =", format(a_C, scientific = FALSE), "m")
title(main = paste(tN, tC, sep = "\n"), font.main = 1)
legend("topright", legend = lTP(T, "Psat"), bty = "n")
# Check that we got equal values
stopifnot(all.equal(as.numeric(e$loga.equil[[3]]), logAcAm, tol = 1e-3, scale = 1))
```
</div>
```{r mosaic-combo, echo = FALSE, results = "hide", message = FALSE, fig.width = 6, fig.height = 5, out.width = "80%", fig.align = "center", pngquant = pngquant}
```
The diagram shows the ionization of acetic acid and NH~3~ at different pHs.
The predicted appearance of acetamide (CH~3~CONH~2~) is a consequence of the interaction between the N-bearing and C-bearing species, and is analogous to the formation of a bimetallic complex.
*Thanks to Kirt Robinson for the feature request and test case used in this example.*
## Document History
* 2020-07-15 First version.
* 2021-03-01 Improve mineral abbreviations and placement of labels; use updated DFT energies from Materials Project; add Mosaic Stacking 2 (minerals and aqueous species); add *K*~eff~ calculation; add Δ*G*~pbx~ color scale.
## References
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/doc/multi-metal.Rmd
|
# integrate Berman's equations using sympy 20170930
# add k4, k5, k6 20180328
library(rSymPy)
# create SymPy variables called T and P
sympy("var('T')")
sympy("var('P')")
sympy("k0 = Symbol('k0', real=True)")
sympy("k1 = Symbol('k1', real=True)")
sympy("k2 = Symbol('k2', real=True)")
sympy("k3 = Symbol('k3', real=True)")
sympy("k4 = Symbol('k4', real=True)")
sympy("k5 = Symbol('k5', real=True)")
sympy("k6 = Symbol('k6', real=True)")
sympy("v1 = Symbol('v1', real=True)")
sympy("v2 = Symbol('v2', real=True)")
sympy("v3 = Symbol('v3', real=True)")
sympy("v4 = Symbol('v4', real=True)")
sympy("Tr = Symbol('Tr', real=True)")
sympy("Pr = Symbol('Pr', real=True)")
sympy("VPrTr = Symbol('VPrTr', real=True)")
sympy("HPrTr = Symbol('HPrTr', real=True)")
sympy("SPrTr = Symbol('SPrTr', real=True)")
# Cp and its integrals
Cp <- "k0 + k1*T**-0.5 + k2*T**-2 + k3*T**-3 + k4*T**-1 + k5*T + k6*T**2"
intCp <- sympy(paste("integrate(", Cp,", (T, Tr, T))"))
message("intCp = ", intCp)
Cp_T <- "k0*T**-1 + k1*T**-1.5 + k2*T**-3 + k3*T**-4 + k4*T**-2 + k5 + k6*T"
intCp_T <- sympy(paste("integrate(", Cp_T,", (T, Tr, T))"))
message("intCp_T = ", intCp_T)
# V and its integrals
# as written in Berman, 1988
#V <- "VPrTr * (1 + v1*(P - Pr) + v2*(P - Pr)**2 + v3*(T- Tr) + v4*(T - Tr)**2)"
# simplified version with Pr==1 (Anderson and Crerar, 1993, p. 175)
V <- "VPrTr * (1 + v1*(P - 1) + v2*(P - 1)**2 + v3*(T - Tr) + v4*(T - Tr)**2)"
intV <- sympy(paste("integrate(", V,", (P, 1, P))"))
# check that intV is equal to the expression in Berman, 1988 and Anderson, 2005 eq. 5.36
#refintV <- "VPrTr * ( (v1/2 - v2) * (P**2 - Pr**2) + v2/3 * (P**3 - Pr**3) + (1 - v1 + v2 + v3*(T-Tr) + v4*(T-Tr)**2) * (P - Pr) )"
# simplified version with Pr==1
refintV <- "VPrTr * ( (v1 / 2 - v2) * (P**2 - 1) + v2 / 3 * (P**3 - 1) + (1 - v1 + v2 + v3*(T-Tr) + v4*(T-Tr)**2) * (P - 1) )"
# this doesn't collect and cancel terms, so we have to expand the expressions
#sympy(paste(intV, "- (", refintV, ")"))
expintV <- sympy(paste("expand (", intV, ")"))
exprefintV <- sympy(paste("expand (", refintV, ")"))
# the difference is zero!
diffintV <- sympy(paste(expintV, "- (", exprefintV, ")"))
message("diffintV = ", diffintV, " (should be 0)")
# another way to check that the expressions are equal
# a function to separate the terms of an expression
septerms <- function(x) {
x <- paste("+", x)
x <- gsub("+ ", "+", x, fixed=TRUE)
x <- gsub("- ", "-", x, fixed=TRUE)
strsplit(x, " ")[[1]]
}
intVterms <- septerms(expintV)
refintVterms <- septerms(exprefintV)
equalintVterms <- setequal(intVterms, refintVterms)
message("equalintVterms is ", equalintVterms, " (should be TRUE)")
# continuing with V integrals for S and H
dVdT <- sympy(paste("diff(", V, ", T, 1)"))
# again, integrate using Pr==1
intdVdT <- sympy(paste("integrate(", dVdT,", (P, 1, P))")) # for S
message("intdVdT = ", intdVdT)
minusintdVdT <- sympy(paste("- (", intdVdT, ")")) # apply minus sign!
V_TdVdT <- sympy(paste(V, " - T * (", dVdT, ")"))
intV_TdVdT <- sympy(paste("integrate(", V_TdVdT,", (P, 1, P))")) # for H
message("intV_TdVdT = ", intV_TdVdT)
# check that intV_TdVdT - T * minusintdVdT is equal to intV (for G)
intV2 <- sympy(paste(intV_TdVdT, "- T * (", minusintdVdT, ")") )
expintV2 <- sympy(paste("expand (", intV2, ")"))
## maybe we need to expand the terms first...
#expintV_TdVdT <- sympy(paste("expand (", intV_TdVdT, ")"))
#TintdVdT <- sympy(paste("T * (", intdVdT, ")") )
#expTintdVdT <- sympy(paste("expand (", TintdVdT, ")"))
#expintV3 <- sympy(paste(expintV_TdVdT, "- (", expTintdVdT, ")"))
# this is zero!
diffexpintV <- sympy(paste(expintV2, "- (", expintV, ")"))
message("diffexpintV = ", diffexpintV, " (should be 0)")
# H, S and G
#HCp <- sympy(paste("HPrTr +", intCp, "+", intV_TdVdT))
#SCp <- sympy(paste("SPrTr +", intCp_T, "- (", intdVdT, ")"))
#GCp <- sympy(paste(HCp, "- T * (", SCp, ")"))
#G <- sympy(paste(GCp, "+", intV))
# References
# Anderson, G. M. (2005) \emph{Thermodynamics of Natural Systems}, 2nd ed., Cambridge University Press, 648 p. \url{http://www.worldcat.org/oclc/474880901}
# Anderson, G. M. and Crerar, D. A. (1993) \emph{Thermodynamics in Geochemistry: The Equilibrium Model}, Oxford University Press. \url{http://www.worldcat.org/oclc/803272549}
# Berman, R. G. (1988) Internally-consistent thermodynamic data for minerals in the system Na{\s2}O-K{\s2}O-CaO-MgO-FeO-Fe{\s2}O{\s3}-Al{\s2}O{\s3}-SiO{\s2}-TiO{\s2}-H{\s2}O-CO{\s2}. \emph{J. Petrol.} \bold{29}, 445-522. \url{https://doi.org/10.1093/petrology/29.2.445}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/extdata/Berman/sympy.R
|
# Load default settings for CHNOSZ
reset()
# 20220206
info <- "Database is set up correctly"
# Activate the AD model for aqueous nonelectrolytes
iAD <- add.OBIGT("AD")
# Get the indices of the modified aqueous species
iaq <- iAD[info(iAD)$state == "aq"]
# Each aqueous species should be associated with the AD model
expect_equal(unique(info(iaq)$model), "AD", info = info)
# Each aqueous species should have a gaseous counterpart
igas <- info(info(iAD)$name, "gas")
expect_true(!any(is.na(igas)), info = info)
# First version of tests used a circular reference (values previously calculated in CHNOSZ) 20190220
# Tests now use values calculated with the AD_full program provided by N. Akinfiev and E. Bastrakov 20210206
info <- "AD produces correct values for CO2 along saturation curve"
P <- "Psat"
T <- c(50, 150, 250, 350)
# J mol-1
G_ref1 <- c(-389128.8, -405167.1, -425423.6, -450572.9)
# J K-1 mol-1
S_ref1 <- c(135.082, 183.295, 226.32, 366.626)
Cp_ref1 <- c(189.791, 178.452, 273.662, 7231.723)
V_ref1 <- c(32.57, 38.125, 58.269, 298.659)
# Calculate values using AD model in CHNOSZ
sout1 <- subcrt("CO2", T = T, P = P)$out[[1]]
expect_equal(sout1$G, G_ref1, tolerance = 13, scale = 1, info = info)
expect_equal(sout1$S, S_ref1, tolerance = 0.8, scale = 1, info = info)
expect_equal(sout1$V[1:3], V_ref1[1:3], tolerance = 0.11, scale = 1, info = info)
# Cp and V get much larger, and so do the differences, near the critical point
expect_equal(sout1$V[4], V_ref1[4], tolerance = 24, scale = 1, info = info)
info <- "AD produces correct values for CO2 at 1000 bar"
P <- 1000
T <- c(300, 400, 500, 600)
G_ref2 <- c(-431672.1, -455065.1, -480692, -507005.3)
S_ref2 <- c(221.255, 246.139, 263.759, 259.812)
Cp_ref2 <- c(150.613, 157.014, 54.489, -76.384)
V_ref2 <- c(45.831, 67.408, 107.656, 129.264)
# Calculate values using AD model in CHNOSZ
sout2 <- subcrt("CO2", T = T, P = P)$out[[1]]
expect_equal(sout2$G, G_ref2, tolerance = 11, scale = 1, info = info)
expect_equal(sout2$S, S_ref2, tolerance = 0.1, scale = 1, info = info)
expect_equal(sout2$V, V_ref2, tolerance = 0.4, scale = 1, info = info)
info <- "AD gives consistent values of G, H, and S"
T_in_Kelvin <- convert(T, "K")
S_of_elements_in_Joules <- entropy("CO2")
expect_equal(sout2$H - T_in_Kelvin * sout2$S + 298.15 * S_of_elements_in_Joules, sout2$G, info = info)
# 20220206
info <- "Fugacity, density, and density derivatives of H2O are close to values in Akinfiev and Diamond (2003)"
# This is the value of fugacity given in the paper
expect_equal(log(CHNOSZ:::.f1(298.15, 1, TRUE)), -3.4773, tolerance = 0.026, scale = 1, info = info)
# This is the value of fugacity output by AD_full
expect_equal(log(CHNOSZ:::.f1(298.15, 1, TRUE)), -3.4524, tolerance = 0.0007, scale = 1, info = info)
# The following values are from the paper
# g / cm3
expect_equal(CHNOSZ:::.rho1(298.15, 1), 0.9970, tolerance = 0.0001, scale = 1, info = info)
# g / cm3 / K
expect_equal(CHNOSZ:::.drho1_dT(298.15, 1, FALSE), -0.0002571, tolerance = 0.000002, scale = 1, info = info)
# g / cm3 / bar
expect_equal(CHNOSZ:::.drho1_dP(298.15, 1, FALSE), 0.00004511, tolerance = 0.0000001, scale = 1, info = info)
# 20190220 Compare Gibbs energies at 25 degrees calculated with AD model to default OBIGT database
info <- "Gibbs energies at 25 degree C are comparable between AD and default OBIGT database"
# Remove some hydroxides that aren't in the default database
iaq <- iaq[!info(iaq)$name %in% c("Si(OH)4", "As(OH)3")]
# This would produce an error if any calculations failed
# (e.g. because gases corresponding to any aqueous species were unavailable)
sAD <- subcrt(iaq, T = 25)
GAD <- do.call(rbind, sAD$out)$G
# Now calculate the parameters using default OBIGT database
OBIGT()
sOBIGT <- subcrt(iaq, T = 25)
GOBIGT <- do.call(rbind, sOBIGT$out)$G
# Mean absolute differences are less than 280 J / mol
expect_equal(GAD, GOBIGT, tolerance = 280, scale = 1, info = info)
# The largest differences are for HCl, ethane, and B(OH)3
expect_equal(sort(info(iaq[abs(GAD - GOBIGT) > 900])$name), sort(c("HCl", "ethane", "B(OH)3")))
## This line should be commented for a released package
#exit_file("Skipping tests so development builds on R-Forge work")
## The following tests work on JMD's Linux machine "at home" but not on some CRAN machines 20220210
if(!at_home()) exit_file("Skipping tests on CRAN")
# This one fails on Windows (tolerance = 9 works) 20220208
expect_equal(sout1$Cp[1:3], Cp_ref1[1:3], tolerance = 3, scale = 1, info = "AD produces correct values for CO2 along saturation curve")
# This one fails on ATLAS and M1mac on CRAN 20220210
expect_equal(sout1$Cp[4], Cp_ref1[4], tolerance = 800, scale = 1, info = "AD produces correct values for CO2 along saturation curve")
# This one fails on ATLAS
expect_equal(sout2$Cp, Cp_ref2, tolerance = 14, scale = 1, info = "AD produces correct values for CO2 at 1000 bar")
# This one fails on M1mac
# g / cm3 / K^2
expect_equal(CHNOSZ:::.d2rho1_dT2(298.15, 1, FALSE), -0.000009503, tolerance = 0.000007, scale = 1,
info = "Fugacity, density, and density derivatives of H2O are close to values in Akinfiev and Diamond (2003)")
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-AD.R
|
# test-Berman.R 20171001
# Load default settings for CHNOSZ
reset()
# Make sure all Berman minerals are listed with units of J in OBIGT 20220203
info <- "Berman minerals are listed with units of J in OBIGT"
file <- system.file("extdata/OBIGT/Berman_cr.csv", package = "CHNOSZ")
dat <- read.csv(file)
expect_true(all(dat$E_units == "J"), info = info)
# The maximum absolute pairwise difference between x and y
maxdiff <- function(x, y) max(abs(y - x))
info <- "high-T,P calculated properties are similar to precalculated ones"
# Reference values for G (cal/mol) were taken from the spreadsheet Berman_Gibbs_Free_Energies.xlsx
# (http://www.dewcommunity.org/uploads/4/1/7/6/41765907/sunday_afternoon_sessions__1_.zip accessed on 2017-10-03)
T <- c(100, 100, 1000, 1000)
P <- c(5000, 50000, 5000, 50000)
# anadalusite: an uncomplicated mineral (no transitions)
And_G <- convert(c(-579368, -524987, -632421, -576834), "J")
And <- subcrt("andalusite", T = T, P = P)$out[[1]]
expect_true(maxdiff(And$G, And_G) < 32, info = info)
# quartz: a mineral with polymorphic transitions
aQz_G <- convert(c(-202800, -179757, -223864, -200109), "J")
aQz <- subcrt("quartz", T = T, P = P)$out[[1]]
expect_true(maxdiff(aQz$G[-2], aQz_G[-2]) < 5, info = info)
# The high-P, low-T point suffers
expect_true(maxdiff(aQz$G[2], aQz_G[2]) < 5200, info = info)
# K-feldspar: this one has disordering effects
Kfs_G <- convert(c(-888115, -776324, -988950, -874777), "J")
Kfs <- subcrt("K-feldspar", T = T, P = P)$out[[1]]
expect_true(maxdiff(Kfs$G[1:2], Kfs_G[1:2]) < 20, info = info)
# we are less consistent with the reference values at high T
expect_true(maxdiff(Kfs$G[3:4], Kfs_G[3:4]) < 1500, info = info)
info <- "Nonexistent or incomplete user data file is handled properly"
thermo("opt$Berman" = "XxXxXx.csv")
expect_error(Berman("calcite"), "the file named in thermo\\(\\)\\$opt\\$Berman \\(XxXxXx.csv\\) does not exist", info = info)
thermo("opt$Berman" = system.file("extdata/Berman/testing/BA96_Berman.csv", package = "CHNOSZ"))
expect_error(Berman("xxx"), "Data for xxx not available. Please add it to", info = info)
thermo("opt$Berman" = NA)
expect_error(Berman("xxx"), "Data for xxx not available. Please add it to your_data_file.csv", info = info)
info <- "NA values of P are handled"
sresult <- suppressWarnings(subcrt("H2O", T = seq(0, 500, 100)))
T <- sresult$out$water$T
P <- sresult$out$water$P
# This stopped with a error prior to version 1.1.3-37
bresult <- Berman("quartz", T = convert(T, "K"), P = P)
expect_equal(sum(is.na(bresult$G)), 2, info = info)
# This also now works (producing the same NA values)
#subcrt("quartz", T = seq(0, 500, 100))
info <- "NAs don't creep into calculations below 298.15 K for minerals with disorder parameters"
# 20191116
expect_false(any(is.na(subcrt("K-feldspar", P = 1, T = seq(273.15, 303.15, 5), convert = FALSE)$out[[1]]$G)), info = info)
# Get parameters for all available minerals
dat <- Berman()
mineral <- unique(dat$name)
info <- "Properties of all minerals are computed without errors"
# Running this without error means that:
# - formulas for the minerals are found in thermo()$OBIGT
# - warning is produced for flourtremolite (GfPrTr(calc) >= 1000 J/mol different from GfPrTr(table))
expect_warning(properties <- lapply(mineral, Berman, check.G = TRUE), "fluortremolite", info = info)
# Save the results so we can use them in the next tests
Berman <- do.call(rbind, properties)
# Convert to calories for comparison with Helgeson minerals below
Berman[, c("G", "H", "S", "Cp")] <- convert(Berman[, c("G", "H", "S", "Cp")], "cal")
# Find the mineral data using Helgeson formulation
icr <- suppressMessages(info(mineral, "cr"))
add.OBIGT("SUPCRT92")
# NOTE: with check.it = TRUE (the default), this calculates Cp from the tabulated Maier-Kelley parameters
#Helgeson <- suppressMessages(info(icr, check.it = FALSE))
Helgeson <- suppressMessages(info(icr))
# Get the minerals that are present in *both* Berman and Helgeson versions
# All of these except rutile (Robie et al., 1978) reference Helgeson et al., 1978
iboth <- Helgeson$ref1 %in% c("HDNB78", "RHF78.4")
mineral <- mineral[iboth]
Berman <- Berman[iboth, ]
Helgeson <- Helgeson[iboth, ]
# Now we can compare Berman and Helgeson G, H, S, Cp, V
# Minerals with missing properties are not matched here
# (i.e. fluortremolite: no G and H in Helgeson data)
info <- "Berman and Helgeson tabulated properties have large differences for few minerals"
# Which minerals differ in DGf by more than 4 kcal/mol?
idiffG <- which(abs(Berman$G - Helgeson$G) > 4000)
DGf.list <- c("paragonite", "anthophyllite", "antigorite", "Ca-Al-pyroxene", "lawsonite", "margarite", "merwinite", "fluorphlogopite")
expect_true(identical(sort(mineral[idiffG]), sort(DGf.list)), info = info)
# Which minerals differ in DHf by more than 4 kcal/mol?
idiffH <- which(abs(Berman$H - Helgeson$H) > 4000)
DHf.list <- c("paragonite", "anthophyllite", "antigorite", "Ca-Al-pyroxene", "lawsonite", "margarite", "merwinite", "fluorphlogopite")
expect_true(identical(sort(mineral[idiffH]), sort(DHf.list)), info = info)
# Which minerals differ in S by more than 4 cal/K/mol?
idiffS <- which(abs(Berman$S - Helgeson$S) > 4)
DS.list <- c("epidote", "annite", "fluortremolite", "andradite")
expect_true(identical(sort(mineral[idiffS]), sort(DS.list)), info = info)
# Which minerals differ in Cp by more than 4 cal/K/mol?
idiffCp <- which(abs(Berman$Cp - Helgeson$Cp) > 4)
DCp.list <- c("glaucophane", "antigorite", "cristobalite,beta", "K-feldspar", "fluortremolite")
expect_true(identical(sort(mineral[idiffCp]), sort(DCp.list)), info = info)
# Which minerals differ in V by more than 1 cm^3/mol?
idiffV <- which(abs(Berman$V - Helgeson$V) > 1)
DV.list <- c("glaucophane", "anthophyllite", "antigorite", "chrysotile", "merwinite", "grunerite")
expect_true(identical(sort(mineral[idiffV]), sort(DV.list)), info = info)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-Berman.R
|
# Tests for DEW implementation in CHNOSZ
# First version 20170925
# Load default settings for CHNOSZ
reset()
# Get properties of water from DEW implementation in CHNOSZ
water("DEW")
# Use DEW species parameters in OBIGT database
add.OBIGT("DEW")
info <- "Density of water is calculated correctly"
pressure <- c(5000, 5000, 10000, 10000, 20000, 20000, 50000, 50000)
temperature <- c(100, 1000, 100, 1000, 100, 1000, 100, 1000)
# Density from R translation of DEW macro functions
RDensity <- calculateDensity(pressure, temperature)
# Density from DEW spreadsheet
DEWDensity <- c(1.108200, 0.597623, 1.196591, 0.798331, 1.321050, 1.000735, 1.578116, 1.287663)
expect_equal(RDensity, DEWDensity, tolerance = 1e-6, info = info)
info <- "Gibbs energy of water is calculated correctly"
pressure <- c(5000, 5000, 10000, 10000, 20000, 20000, 50000, 50000)
temperature <- c(100, 1000, 100, 1000, 100, 1000, 100, 1000)
# Gibbs energies from R translation of DEW macro functions
RGibbs <- calculateGibbsOfWater(pressure, temperature)
# Gibbs energies from DEW spreadsheet
DEWGibbs <- c(-56019.85419280258, -84262.028821198, -54155.004480575895, -81210.38766217149,
-50735.122222685815, -76433.07602205424, -41823.26077175943, -65187.48113532527)
expect_equal(RGibbs, DEWGibbs, info = info)
info <- "Dielectric constant of water is calculated correctly"
pressure <- c(5000, 5000, 10000, 10000, 20000, 20000, 50000, 50000)
temperature <- c(100, 1000, 100, 1000, 100, 1000, 100, 1000)
# epsilon from R translation of DEW macro functions
Repsilon <- calculateEpsilon(calculateDensity(pressure, temperature), temperature)
# epsilon from DEW spreadsheet
DEWepsilon <- c(65.63571, 6.10465, 72.40050, 8.97800, 82.16244, 12.13131, 103.12897, 16.97266)
expect_equal(Repsilon, DEWepsilon, tolerance = 1e-7, info = info)
info <- "Born coefficient Q is calculated correctly"
pressure <- c(5000, 5000, 10000, 10000, 20000, 20000, 50000, 50000)
temperature <- c(100, 1000, 100, 1000, 100, 1000, 100, 1000)
# Q from R translation of DEW macro functions
RQ <- calculateQ(calculateDensity(pressure, temperature), temperature)
# Q from DEW spreadsheet
DEWQ <- c(0.32319817, 14.50286092, 0.19453478, 3.12650897,
0.10918151, 0.87729257, 0.05068788, 0.20640645) / 1e6
expect_equal(RQ, DEWQ, info = info)
info <- "g function is calculated correctly"
pressure <- c(1000, 1000, 5000, 5000, 10000)
temperature <- c(100, 1000, 100, 1000, 100)
# note that values returned for alpha, daldT, beta are NA
w <- water(c("rho", "alpha", "daldT", "beta", "Psat"), T=convert(temperature, "K"), P=pressure)
# g from CHNOSZ functions
Rg <- CHNOSZ:::gfun(w$rho/1000, temperature, pressure, w$alpha, w$daldT, w$beta)$g
# g from R translation of DEW macro functions (not used in CHNOSZ)
DEWg <- CHNOSZ:::calculateG(pressure, temperature, w$rho/1000)
expect_equal(Rg, DEWg, info = info)
## The following tests use reference values in calories
E.units("cal")
info <- "Gibbs energies of species are calculated correctly"
P <- c(5000, 5000, 10000, 10000, 20000, 20000, 50000, 50000)
T <- c(100, 1000, 100, 1000, 100, 1000, 100, 1000)
RG_HCl <- subcrt("HCl", P=P, T=T)$out[[1]]$G
DEWG_HCl <- c(-28784.99, -58496.85, -26520.94, -55276.92, -21928.89, -50337.19, -8014.34, -36746.87)
expect_equal(RG_HCl, DEWG_HCl, tolerance = 1e-5, info = info)
RG_Cl <- subcrt("Cl-", P=P, T=T)$out[[1]]$G
DEWG_Cl <- c(-30054.59, -22839.35, -27910.68, -28094.07, -23568.45, -27959.67, -10443.07, -18744.93)
expect_equal(RG_Cl, DEWG_Cl, tolerance = 1e-7, info = info)
info <- "Delta G, logK, and Delta V of reactions are calculated correctly"
# These are reactions corresponding to Fig. 1b of Sverjensky et al., 2014 (Nat. Geosci.).
# The properties are calculated using parameters from the DEW spreadsheet,
# which are not necessarily identical those that were used for the paper.
T <- 600
P <- c(5000, 50000)
R1 <- subcrt(c("H2O", "CO2", "HCO3-", "H+"), c(-1, -1, 1, 1), T=T, P=P)$out
R2 <- subcrt(c("HCO3-", "CO3-2", "H+"), c(-1, 1, 1), T=T, P=P)$out
R3 <- subcrt(c("acetic acid", "acetate", "H+"), c(-1, 1, 1), T=T, P=P)$out
R4 <- subcrt(c("H2O", "CO2", "acetic acid", "oxygen"), c(-2, -2, 1, 2), T=T, P=P)$out
R5 <- subcrt(c("oxygen", "CH4", "acetic acid", "H2O"), c(-2, -2, 1, 2), T=T, P=P)$out
# Delta G values calculated using the DEW spreadsheet (May 2017 version)
DEW_DG <- c(38267.404507442814, 14893.170655988564, # R1
41407.05995898576, 21347.599525026497, # R2
28109.598104640143, 16112.928184675075, # R3
186960.22705581048, 133640.9631638353, # R4
-141552.60059404257, -134279.54670605875) # R5
# the aqueous-only reactions
expect_equal(c(R1$G, R2$G, R3$G), DEW_DG[1:6], tolerance = 1e-7, info = info)
# note that there is a small error for oxygen in the DEW spreadsheet (wrong c parameter),
# but even so, these tests have a lower tolerance because of the larger magnitude of the difference
expect_equal(c(R4$G, R5$G), DEW_DG[7:10], tolerance = 1e-9, info = info)
# logK values calculated using the DEW spreadsheet
DEW_logK <- c(-9.58455651110442, -3.7301833667366027,
-10.370923015131565, -5.346776889042665,
-7.040405143911882, -4.035687100632826,
-46.826558649850625, -33.47207316851283,
35.45364304557209, 33.632014510923746)
expect_equal(c(R1$logK, R2$logK, R3$logK, R4$logK, R5$logK), DEW_logK, tolerance = 1e-3, info = info)
# Delta V values calculated using the DEW spreadsheet
DEW_DV <- c(-45.26925983499276, -14.640599169742725,
-47.95180846799733, -9.469432706749927,
-27.042087540311922, -6.836267057722694,
-18.1550937649195, 5.513800665649967,
-37.37077435045512, -45.08570662275889)
# for the aqueous species we're getting very close results
# (at P=5000 bar this depends on calculating drhodP -> beta -> dgdP -> dwdP -> V correctly, which is not tested above)
expect_equal(c(R1$V, R2$V, R3$V), DEW_DV[1:6], tolerance = 1e-15, info = info)
# TODO: why does DEW spreadsheet use V (O2,g) == 24.465?
#expect_equal(c(R4$V, R5$V), DEW_DV[7:10], info = info)
info <- "Calculated logK values are consistent with Extended Deep Earth Water paper"
# Reference logK values are from Appendix D of Huang and Sverjensky, 2019 (doi:10.1016/j.gca.2019.03.027)
# Select T and P for comparisons
T <- c(300, 1100)
P <- c(10000, 60000)
# Adjust calculated logKs for different values of the
# gas constant used in the DEW spreadsheet and CHNOSZ
#RoverR <- 1.9858775 / 1.9872 # 20170925
RoverR <- 1.9858775 / (8.314463 / 4.184) # 20230630
# Calculate logK for each reaction
logK1 <- subcrt(c("H2O", "CO2", "H2CO3"), c(-1, -1, 1), T = T, P = P)$out$logK / RoverR
logK2 <- subcrt(c("AlO2(SiO2)-", "H+", "Al+3", "H2O", "SiO2"), c(-1, -4, 1, 2, 1), T = T, P = P)$out$logK / RoverR
logK3 <- subcrt(c("Ca(HCO3)+", "Ca+2", "HCO3-"), c(-1, 1, 1), T = T, P = P)$out$logK / RoverR
logK4 <- subcrt(c("Ca(HCOO)+", "Ca+2", "HCOO-"), c(-1, 1, 1), T = T, P = P)$out$logK / RoverR
logK5 <- subcrt(c("Ca(HSiO3)+", "H+", "Ca+2", "H2O", "SiO2"), c(-1, -1, 1, 1, 1), T = T, P = P)$out$logK / RoverR
logK6 <- subcrt(c("Fe(HCOO)+", "Fe+2", "HCOO-"), c(-1, 1, 1), T = T, P = P)$out$logK / RoverR
logK7 <- subcrt(c("Fe(HSiO3)+", "H+", "Fe+2", "H2O", "SiO2"), c(-1, -1, 1, 1, 1), T = T, P = P)$out$logK / RoverR
logK8 <- subcrt(c("H2O", "SiO2", "HSiO3-", "H+"), c(-1, -1, 1, 1), T = T, P = P)$out$logK / RoverR
logK9 <- subcrt(c("MgO", "H+", "Mg+2", "H2O"), c(-1, -2, 1, 1), T = T, P = P)$out$logK / RoverR
logK10 <- subcrt(c("Mg(SiO2)(HCO3)+", "Mg+2", "SiO2", "HCO3-"), c(-1, 1, 1, 1), T = T, P = P)$out$logK / RoverR
logK11 <- subcrt(c("NaHCO3", "Na+", "HCO3-"), c(-1, 1, 1), T = T, P = P)$out$logK / RoverR
logK12 <- subcrt(c("Si3O6", "SiO2"), c(-1, 3), T = T, P = P)$out$logK / RoverR
# Make the comparisons:
# - Reference logK values are from Appendix D of Huang and Sverjensky, 2019 (doi:10.1016/j.gca.2019.03.027)
# - Tolerance (tol) is added if there are differences between the reference and calculated values after rounding
# (scale = 1 is used to compare absolute differences)
expect_equal(round(logK1, 2), c(-0.76, 1.34), info = info)
expect_equal(round(logK2, 4), c( 6.7755, 0.9413), tol = 0.003, scale = 1, info = info)
expect_equal(round(logK3, 4), c(-2.3759, -5.6840), info = info)
expect_equal(round(logK4, 4), c(-2.2837, -5.5822), tol = 0.0001, scale = 1, info = info)
expect_equal(round(logK5, 4), c( 4.0349, 0.1797), tol = 0.002, scale = 1, info = info)
expect_equal(round(logK6, 4), c(-7.5354, -8.0238), info = info)
expect_equal(round(logK7, 4), c(-0.6883, -1.6363), tol = 0.002, scale = 1, info = info)
expect_equal(round(logK8, 4), c(-7.0651, -5.5067), tol = 0.002, scale = 1, info = info)
expect_equal(round(logK9, 4), c( 8.2759, 4.3493), tol = 0.002, scale = 1, info = info)
expect_equal(round(logK10, 4), c(-6.8106, -8.5888), tol = 0.0001, scale = 1, info = info)
expect_equal(round(logK11, 4), c(-0.2447, -2.9235), info = info)
expect_equal(round(logK12, 4), c( 3.3283, 0.4527), info = info)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-DEW.R
|
# Load default settings for CHNOSZ
reset()
info <- "EOSvar stops with unknown variables"
expect_error(EOSvar("TX", T = 25, P = 1), "can't find a variable named TX", info = info)
# Why can't the test find these?
#TX <- 2
#expect_error(EOSvar("TX", T = 25, P = 1), "an object named TX is not a function")
#TX <- function(T) 2
#expect_error(EOSvar("TX", T = 25, P = 1), "the arguments of TX\\(\\) are not T, P")
info <- "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")
P <- seq(200, 1000, 100)
# We use calories to compare with OBIGT data for CH4(aq) 20220325
T.units("K")
E.units("cal")
CH4.prop <- subcrt("CH4", T = T, P = P, grid = "T")$out[[1]]
# Terms in the HKF equations for Cp
Cp.var <- c("invTTheta2", "TXBorn")
# Get coefficients in Cp regression
Cp.lm <- EOSregress(CH4.prop[, c("T", "P", "Cp")], Cp.var)
Cp.coeff <- Cp.lm$coefficients
# Terms in the HKF equations for V
V.var <- c("invPPsi", "invTTheta", "invPPsiTTheta", "QBorn")
# Get coefficients in V regression
V.lm <- EOSregress(CH4.prop[, c("T", "P", "V")], V.var)
# Use same units as HKF: convert from cm3.bar to joules (divide by 10) then to calories
V.coeff <- convert(convert(V.lm$coefficients, "joules"), "cal")
## The tests: did we get the HKF parameters that are in the database?
CH4.par <- info(info("CH4"))
# c1 and c2
expect_equivalent(Cp.coeff[1], CH4.par$c1, info = info)
expect_equivalent(Cp.coeff[2], CH4.par$c2, info = info)
# omega (from Cp)
expect_equivalent(Cp.coeff[3], CH4.par$omega, info = info)
# a1, a2, a3 and a4
expect_equivalent(V.coeff[1], CH4.par$a1, info = info)
expect_equivalent(V.coeff[2], CH4.par$a2, info = info)
expect_equivalent(V.coeff[3], CH4.par$a3, info = info)
expect_equivalent(V.coeff[4], CH4.par$a4, info = info)
# omega (from V)
expect_equivalent(V.coeff[5], CH4.par$omega, info = info)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-EOSregress.R
|
# Load default settings for CHNOSZ
reset()
info <- "Calculations of Helmholtz free energy and its derivatives are consistent with reference cases"
## Reference values of these terms are listed Table 6.6 of Wagner and Pruss, 2002
p <- c("phi", "phi.delta", "phi.delta.delta", "phi.tau", "phi.tau.tau", "phi.delta.tau")
# Reference values for case 1: T=500 K, rho=838.025 kg m-3
idealgas.ref.1 <- c(0.204797734e1, 0.384236747, -0.147637878, 0.904611106e1, -0.193249185e1, 0)
residual.ref.1 <- c(-0.342693206e1, -0.364366650, 0.856063701, -0.581403435e1, -0.223440737e1, -0.112176915e1)
# Reference values for case 1: T=647 K, rho=358 kg m-3
idealgas.ref.2 <- c(-0.156319605e1, 0.899441341, -0.808994726, 0.980343918e1, -0.343316334e1, 0)
residual.ref.2 <- c(-0.121202657e1, -0.714012024, 0.475730696, -0.321722501e1, -0.996029507e1, -0.133214720e1)
## Set up the problem
# Critical point constants
T.critical <- 647.096 # K
rho.critical <- 322 # kg m-3
# T and rho for cases 1 and 2
T <- c(500, 647)
rho <- c(838.025, 358)
# delta and tau for cases 1 and 2
delta <- rho / rho.critical
tau <- T.critical / T
# Dalculated ideal gas and residual parts for case 1
idealgas.calc.1 <- sapply(p, CHNOSZ:::IAPWS95.idealgas, delta[1], tau[1])
residual.calc.1 <- sapply(p, CHNOSZ:::IAPWS95.residual, delta[1], tau[1])
# Calculated ideal gas and residual parts for case 2
idealgas.calc.2 <- sapply(p, CHNOSZ:::IAPWS95.idealgas, delta[2], tau[2])
residual.calc.2 <- sapply(p, CHNOSZ:::IAPWS95.residual, delta[2], tau[2])
## Perform the tests
# We almost get away without increasing the tolerance in any test ...
expect_equal(idealgas.calc.1, idealgas.ref.1, check.attributes = FALSE, info = info)
expect_equal(residual.calc.1, residual.ref.1, check.attributes = FALSE, info = info)
expect_equal(idealgas.calc.2, idealgas.ref.2, check.attributes = FALSE, info = info)
# ... however an offset is apparent in the value of the residual phi.delta.delta for case 2
expect_equal(residual.calc.2, residual.ref.2, check.attributes = FALSE, tolerance = 1e-5, info = info)
info <- "Calculations of thermodynamic properties are consistent with reference values"
## These are the properties we test - from Table 13.1 of Wagner and Pruss, 2002
## (speed of sound omitted as it's not currently implemented)
p <- c("P", "H", "S", "Cv", "Cp")
## A selection of T and rho at vapor-liquid boundary
## (NOTE: excluding triple and critical points; we have some unresolved issues there)
T <- c(274, 320, 368, 416, 464, 512, 560, 608, 647)
rho.liquid <- c(999.843, 989.387, 961.984, 923.577, 875.125, 814.982, 737.831, 626.74, 357.34)
rho.vapor <- c(0.00514, 0.07166, 0.50231, 2.1203, 6.5107, 16.409, 37.147, 84.173, 286.51)
## Reference values
P.ref <- c(0.000650, 0.010546, 0.084142, 0.39166, 1.2788, 3.2798, 7.1062, 13.681, 22.038)
H.liquid.ref <- c(3.544, 196.170, 397.457, 601.396, 811.225, 1032.06, 1273.11, 1558.42, 2029.44)
H.vapor.ref <- c(2502.46, 2585.71, 2667.37, 2737.09, 2785.91, 2803.05, 2771.24, 2646.01, 2148.56)
S.liquid.ref <- c(0.0130, 0.6629, 1.2487, 1.7687, 2.2436, 2.6914, 3.1319, 3.6034, 4.3224)
S.vapor.ref <- c(9.1331, 8.1302, 7.4169, 6.9025, 6.4994, 6.1504, 5.8071, 5.3922, 4.5065)
cv.liquid.ref <- c(4.2156, 4.0416, 3.7950, 3.5560, 3.3523, 3.1884, 3.0722, 3.0617, 6.2344)
cv.vapor.ref <- c(1.4191, 1.4627, 1.5428, 1.7138, 2.0015, 2.3697, 2.8225, 3.4538, 6.2740)
cp.liquid.ref <- c(4.2171, 4.1807, 4.2101, 4.2892, 4.4513, 4.7616, 5.4239, 7.6169, 3905.2)
cp.vapor.ref <- c(1.8852, 1.9417, 2.0601, 2.3334, 2.8561, 3.7263, 5.4099, 10.805, 5334.1)
## Calculated values
liquid.calc <- IAPWS95(p, T, rho.liquid)
vapor.calc <- IAPWS95(p, T, rho.vapor)
## The tests
# Take P to 5 significant digits but not more than 6 decimals
expect_equal(round(signif(liquid.calc$p, 5), 6), P.ref, tolerance = 1e-3, info = info)
expect_equal(round(signif(vapor.calc$p, 5), 6), P.ref, tolerance = 1e-4, info = info)
# Take H to 6 significant digits but not more than 3 decimals
expect_equal(round(signif(liquid.calc$h, 6), 3), H.liquid.ref, tolerance = 1e-5, info = info)
expect_equal(round(signif(vapor.calc$h, 6), 3), H.vapor.ref, info = info) # spot on!
# Round S to 4 decimals
expect_equal(round(liquid.calc$s, 4), S.liquid.ref, info = info) # spot on!
expect_equal(round(vapor.calc$s, 4), S.vapor.ref, tolerance = 1e-4, info = info)
# Round cv to 4 decimals
expect_equal(round(liquid.calc$cv, 4), cv.liquid.ref, tolerance = 1e-4, info = info)
expect_equal(round(vapor.calc$cv, 4), cv.vapor.ref, tolerance = 1e-4, info = info)
# Take cp to 5 significant digits but not more than 4 decimals
# Note high tolerance setting: the highest temperature is the challenge
expect_equal(round(signif(liquid.calc$cp, 5), 4), cp.liquid.ref, tolerance = 1e0, info = info)
expect_equal(round(signif(vapor.calc$cp, 5), 4), cp.vapor.ref, tolerance = 1e-1, info = info)
info <- "Calculations are possible at low temperatures"
# The sequences start at the lowest whole-number temperature (K)
# Where the function returns a value of density at the given pressure
expect_false(any(is.na(water.IAPWS95("rho", T = seq(234, 274, 3), P = rep(1, 14)))), info = info)
expect_false(any(is.na(water.IAPWS95("rho", T = seq(227, 272, 3), P = rep(1000, 16)))), info = info)
# Reference
# Wagner, W. and Pruss, A. (2002)
# The IAPWS formulation 1995 for the thermodynamic properties of
# ordinary water substance for general and scientific use
# J. Phys. Chem. Ref. Data 31, 387--535. https://doi.org/10.1063/1.1461829
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-IAPWS95.R
|
# Load default settings for CHNOSZ
reset()
info <- "add.protein works as expected"
# Factors causing problems again ...
f <- system.file("extdata/protein/POLG.csv", package = "CHNOSZ")
aa <- read.csv(f, as.is = TRUE)
# This adds the proteins
ip1 <- add.protein(aa)
# This replaces the proteins (with the same ones)
ip2 <- add.protein(aa)
expect_equal(ip1, ip2, info = info)
info <- "Errors and messages occur in some circumstances"
expect_error(add.protein(count.aa("AAA")), "does not have the same columns as thermo\\(\\)\\$protein", info = info)
expect_message(add.protein(pinfo(pinfo("CYC_BOVIN"))), "replaced 1 existing protein\\(s\\)", info = info)
info <- "group additivity for proteins gives expected values"
# Values for chicken lysozyme calculated using group additivity values
# from Dick et al., 2006 [DLH06] (Biogeosciences 3, 311-336)
G <- -4206050
Cp <- 6415.5
V <- 10421
formula <- "C613H959N193O185S10"
# To reproduce, use superseded properties of [Met], [Gly], and [UPBB] (Dick et al., 2006)
mod.OBIGT("[Met]", G = -35245, H = -59310, S = 40.38)
mod.OBIGT("[Gly]", G = -6075, H = -5570, S = 17.31)
mod.OBIGT("[UPBB]", G = -21436, H = -45220, S = 1.62)
lprop <- info(info("LYSC_CHICK"))
expect_equal(G, lprop$G, info = info)
expect_equal(Cp, lprop$Cp, tolerance = 1e-5, info = info)
expect_equal(V, lprop$V, tolerance = 1e-4, info = info)
expect_equal(formula, lprop$formula, info = info)
info <- "read.fasta() identifies sequences correctly and gives amino acid compositions in the correct format"
ffile <- system.file("extdata/protein/EF-Tu.aln", package = "CHNOSZ")
aa <- read.fasta(ffile)
expect_equal(aa[1, ], read.fasta(ffile, 1), info = info)
# Use unlist here so that different row names are not compared
expect_equal(unlist(aa[8, ]), unlist(read.fasta(ffile, 8)), info = info)
expect_message(ip1 <- add.protein(aa), "added 8 new protein\\(s\\)", info = info)
expect_message(ip2 <- add.protein(aa), "replaced 8 existing protein\\(s\\)", info = info)
# add.protein should return the correct indices for existing proteins
expect_equal(ip1, ip2, info = info)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-add.protein.R
|
# This is a long test ... only run it "at home" 20220129
if(!at_home()) exit_file("Skipping long test")
# Load default settings for CHNOSZ
reset()
info <- "Errors come as expected"
expect_error(affinity(iprotein = 7), "basis species are not defined", info = info)
expect_error(affinity(iprotein = NA), "has some NA values", info = info)
expect_error(affinity(iprotein = 0), "are not rownumbers", info = info)
basis("CHNOS")
expect_error(affinity(), "species have not been defined", info = info)
species("CO2")
expect_error(affinity(pe = c(-10, 10), pH = c(0, 14)), "pe.*does not match any basis species", info = info)
expect_error(affinity(O2 = c(-80, -60), pH = c(0, 14)), "pH.*does not match any basis species", info = info)
info <- "Output gives T and P in user's units"
basis("CHNOS")
species("5a(H),14b(H)-cholestane")
a.C_bar <- affinity(T = c(0, 100, 10), P = c(10, 1000, 10))
expect_equal(range(a.C_bar$vals[[1]]), c(0, 100), info = info)
expect_equal(range(a.C_bar$vals[[2]]), c(10, 1000), info = info)
T.units("K")
P.units("MPa")
a.K_MPa <- affinity(T = c(273.15, 373.15, 10), P = c(1, 100, 10))
expect_equal(range(a.K_MPa$vals[[1]]), c(273.15, 373.15), info = info)
expect_equal(range(a.K_MPa$vals[[2]]), c(1, 100), info = info)
# different units, same T,P ... same affinities
expect_equal(a.C_bar$values, a.K_MPa$values, info = info)
# Go back to original units for the remaining tests
T.units("C")
P.units("bar")
info <- "pe, pH and Eh are correctly handled"
basis("CHNOSe")
species(c("HS-", "H2S", "SO4-2"))
Eh <- c(-1, 1)
pe <- convert(Eh, "pe", T = convert(100, "K"))
a.Eh <- affinity(Eh = Eh, T = 100)
a.pe <- affinity(pe = pe, T = 100)
# They should give the same result
# ... except for names(dim(.)), so set check.attributes = FALSE
expect_equal(a.Eh$values, a.pe$values, check.attributes = FALSE, info = info)
# The variables should have the right names
expect_equal(c(a.Eh$vars, a.pe$vars), c("Eh", "pe"), info = info)
# Now for an Eh-pH example
pH <- c(0, 14)
a <- affinity(pH = pH, Eh = Eh)
expect_equal(a$vars, c("pH", "Eh"), info = info)
expect_equal(range(a$vals[[1]]), pH, info = info)
expect_equal(range(a$vals[[2]]), Eh, info = info)
expect_equal(length(a$vals[[2]]), 256, info = info)
# Since Eh has to be reconstructed, check it's done correctly
a129 <- affinity(pH = pH, Eh = c(Eh, 129))
expect_equal(length(a129$vals[[2]]), 129, info = info)
## TODO: a transect of hotter, more oxidizing and more acidic
## has not been working since at least 0.9-7
##T <- c(25, 50, 100, 125, 150)
##Eh <- c(-1, -0.5, 0, 0.5, 1)
##pH <- c(10, 8, 6, 4, 2)
##a <- affinity(T = T, Eh = Eh, pH = pH)
info <- "affinity() in 3D returns values consistent with manual calculation"
# Our "manual" calculation will be for H2(aq) + 0.5O2(aq) = H2O(l)
# The equilibrium constants at 25 and 100 degrees C
# (the logK are tested against literature values in test-subcrt.R)
logK.25 <- subcrt(c("H2", "O2", "H2O"), "aq", c(-1, -0.5, 1), T = 25)$out$logK
logK.100 <- subcrt(c("H2", "O2", "H2O"), "aq", c(-1, -0.5, 1), T = 100)$out$logK
# The value of A/2.303RT at 25 degrees and logaH2 = -10, logaO2 = -10 and logaH2O = 0
A.2303RT.25.10.10 <- logK.25 - ( (-1)*(-10) + (-0.5)*(-10) )
# The value of A/2.303RT at 100 degrees and logaH2 = -5, logaO2 = -10 and logaH2O = 0
A.2303RT.100.5.10 <- logK.100 - ( (-1)*(-5) + (-0.5)*(-10) )
# Set up basis and species
basis(c("H2", "O2"), "aq")
species("H2O")
# We will run affinity() in 3D
# T = 0, 25, 50, 75, 100, 125 degrees
# log_a(H2) = -20, -15, -10, -5, 0
# 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), check.names = FALSE, info = info)
# Second and third tests: the logK values used by affinity() are correct
expect_equal(a.logK$values[[1]][2, 3, 3], logK.25, info = info)
expect_equal(a.logK$values[[1]][5, 4, 3], logK.100, info = info)
# Fourth and fifth tests: the A/2.303RT values returned by affinity() are correct
a.A <- affinity(T = c(0, 125, 6), H2 = c(-20, 0, 5), O2 = c(-20, 0, 5))
expect_equal(a.A$values[[1]][2, 3, 3], A.2303RT.25.10.10, info = info)
expect_equal(a.A$values[[1]][5, 4, 3], A.2303RT.100.5.10, info = info)
info <- "'iprotein' gives consistent results on a transect"
# From Dick and Shock, 2011, values of A/2.303RT for the per-residue
# formation reactions of overall model proteins at five sampling sites
# at Bison Pool, with different temperature, pH and log_a(H2)
# These are the maximum values for each site from Table 5 in the paper
A.2303RT_ref <- c(-18.720, -27.894, -35.276, -36.657, -41.888)
# The measured temperatures and pHs
T <- c(93.3, 79.4, 67.5, 65.3, 57.1)
pH <- c(7.350, 7.678, 7.933, 7.995, 8.257)
# Eq. 24 of the paper
H2 <- -11+T*3/40
# Remove "RESIDUE" entries in thermo()$OBIGT (clutter from first test)
reset()
basis(c("HCO3-", "H2O", "NH3", "HS-", "H2", "H+"),
"aq", c(-3, 0, -4, -7, 999, 999))
sites <- c("N", "S", "R", "Q", "P")
ip <- pinfo("overall", c("bisonN", "bisonS", "bisonR", "bisonQ", "bisonP"))
# To reproduce, use superseded properties of [Met], [Gly], and [UPBB] (Dick et al., 2006)
mod.OBIGT("[Met]", G = -35245, H = -59310, S = 40.38)
mod.OBIGT("[Gly]", G = -6075, H = -5570, S = 17.31)
mod.OBIGT("[UPBB]", G = -21436, H = -45220, S = 1.62)
a <- affinity(T = T, pH = pH, H2 = H2, iprotein = ip)
# Divide A/2.303RT by protein length
pl <- protein.length(ip)
A.2303RT <- t(sapply(a$values, c)) / pl
# Find the maximum for each site
A.2303RT_max <- apply(A.2303RT, 2, max)
# We're off a bit in the second decimal ...
# maybe becuase of rounding of the aa composition?
expect_equal(A.2303RT_max, A.2303RT_ref, tolerance = 1e-3, info = info)
# TODO: add comparison with results from loading proteins via species()
info <- "affinity() for proteins (with/without 'iprotein') returns same value as in previous package versions"
## These values were calculated using versions 0.6, 0.8 and 0.9-7 (25 degrees C, 1 bar, basis species "CHNOS" or "CHNOS+")
#A.2303RT.nonionized <- -3795.297
#A.2303RT.ionized <- -3075.222
## Calculated with version 2.0.0 (util.units() has R = 8.314445)
#A.2303RT.nonionized <- -3795.291
#A.2303RT.ionized <- -3075.215
# Calculated with version 2.0.0-16 (util.units() has R = 8.314463)
A.2303RT.nonionized <- -3794.69
A.2303RT.ionized <- -3074.613
# First for nonionized protein
basis("CHNOS")
# Try it with iprotein
ip <- pinfo("CSG_HALJP")
expect_equal(affinity(iprotein = ip, loga.protein = -3)$values[[1]][1], A.2303RT.nonionized, tolerance = 1e-5, info = info)
# Then with the protein loaded as a species
species("CSG_HALJP")
expect_equal(affinity()$values[[1]][1], A.2303RT.nonionized, tolerance = 1e-5, info = info)
# Now for ionized protein
basis("CHNOS+")
expect_equal(affinity(iprotein = ip, loga.protein = -3)$values[[1]][1], A.2303RT.ionized, tolerance = 1e-5, info = info)
species("CSG_HALJP")
expect_equal(affinity()$values[[1]][1], A.2303RT.ionized, tolerance = 1e-5, info = info)
info <- "affinity() for proteins keeps track of pH on 2-D calculations"
# (relates to the "thisperm" construction in A.ionization() )
basis("CHNOS+")
species("LYSC_CHICK")
a1 <- affinity(pH = c(6, 8, 3))
a2 <- affinity(pH = c(6, 8, 3), T = c(0, 75, 4))
expect_equal(as.numeric(a1$values[[1]]), a2$values[[1]][, 2], info = info)
info <- "IS can be constant or variable"
# Inspired by an error from demo("phosphate")
# > a25 <- affinity(IS = c(0, 0.14), T = T[1])
# ...
# Error in subcrt(species = c(1017L, 20L, 19L), property = "logK", T = 298.15, :
# formal argument "IS" matched by multiple actual arguments
oldnon <- nonideal("Alberty")
basis("CHNOPS+")
species(c("PO4-3", "HPO4-2", "H2PO4-"))
a0 <- affinity()
a1 <- affinity(IS = 0.14)
a2 <- affinity(IS = c(0, 0.14))
expect_equal(unlist(lapply(a2$values, head, 1)), unlist(a0$values), info = info)
expect_equal(unlist(lapply(a2$values, tail, 1)), unlist(a1$values), info = info)
nonideal(oldnon)
info <- "Argument recall is usable"
# 20190127
basis("CHNOS")
species(c("CO2", "CH4"))
a0 <- affinity(O2 = c(-80, -60))
a1 <- affinity(O2 = c(-80, -60), T = 100)
a2 <- affinity(a0, T = 100)
a3 <- affinity(a1, T = 25)
expect_identical(a1, a2, info = info)
# We don't test entire output here becuase a0 doesn't have a "T" argument
expect_identical(a0$values, a3$values, info = info)
info <- "sout is processed correctly"
# 20190201
basis("CHNOS+")
# Previously, this test would fail when sout has
# more species than are used in the calculation
species(c("H2S", "CO2", "CH4"))
a0 <- affinity(T = c(0, 100))
sout <- a0$sout
# Test the calculation with just CH4
species(1:2, delete = TRUE)
a1 <- affinity(T = c(0, 100))
a2 <- affinity(T = c(0, 100), sout = a0$sout)
expect_equal(a1$values, a2$values, info = info)
info <- "return.sout = TRUE returns output of subcrt()"
# 20240206
# Caught by Mosaic Stacking 2 in multi-metal.Rmd
# (returned value was NULL in CHNOSZ_2.0.0-43,
# creating weirdness in mineral-aqueous boundaries on diagram)
basis("CHNOS+")
species("CO2")
a <- affinity(return.sout = TRUE)
expect_equal(names(a), c("species", "out"), info = info)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-affinity.R
|
# Load default settings for CHNOSZ
reset()
info <- "Invalid basis definitions cause an error"
expect_error(basis(character()), "argument is empty", info = info)
expect_error(basis(c("CO2", "CO2")), "names are not unique", info = info)
expect_error(basis(c("CO2", "H2O")), "the number of basis species is less than the number of elements", info = info)
expect_error(basis(c("H2O", "O2", "H2")), "the number of basis species is greater than the number of elements", info = info)
expect_error(basis(c("HCN", "H2O", "O2", "H2")), "singular", info = info)
expect_error(basis(c("CN", "H2O", "O2", "H2")), "species not available", info = info)
expect_error(basis(c("CN")), "species not available", info = info)
ina <- nrow(thermo()$OBIGT) + 1
expect_error(basis(ina), "species not available", info = info)
expect_error(CHNOSZ:::preset.basis(c("CN")), "is not a keyword", info = info)
# After all that, the basis should still be undefined
expect_null(basis(), info = info)
info <- "Invalid basis modification requests cause an error"
basis(delete = TRUE)
expect_error(CHNOSZ:::mod.basis("CH4", "gas"), "basis is not defined", info = info)
b <- basis("CHNOS+")
expect_error(CHNOSZ:::mod.basis("CH4", "gas"), "is not a formula of one of the basis species", info = info)
iCH4 <- info("CH4")
expect_error(CHNOSZ:::mod.basis(iCH4, "gas"), "is not a species index of one of the basis species", info = info)
expect_error(CHNOSZ:::mod.basis("CO2", "PPM"), "the elements .* in buffer .* are not in the basis", info = info)
expect_error(CHNOSZ:::mod.basis("CO2", "liq"), "state .* not found", info = info)
# After all that, the basis should be unchanged
expect_equal(basis(), b, info = info)
info <- "Modifying states of basis species is possible"
b1 <- basis(c("copper", "chalcocite"))
b2 <- basis("Cu2S", "cr2")
# We went from chalcocite cr to cr2, which is the next row in the database
expect_equal(sum(b2$ispecies - b1$ispecies), 1, info = info)
expect_error(basis("Cu2S", "cr4"), "state or buffer 'cr4' not found for chalcocite", info = info)
# Can we go from CO2(aq) to CO2(gas) back to CO2(aq)?
basis("CHNOS+") # first basis species is CO2(aq)
expect_equal(basis("CO2", "gas")$state[1], "gas", info = info)
expect_equal(basis("CO2", "aq")$state[1], "aq", info = info)
# 20220208
info <- "Adding basis species to an existing definition works"
basis(c("iron", "oxygen", "H2O", "H+"), c(0, -80, 1, -7))
species(c("Fe", "Fe+2", "Fe+2"), c(0, -6, -6))
a1 <- affinity(pH = c(0, 14))
expect_error(basis(c("iron"), add = TRUE), "this species is already in the basis definition", info = info)
expect_error(basis(c("iron", "oxygen", "H2O", "H+"), add = TRUE), "these species are already in the basis definition", info = info)
expect_error(basis("Fe+2", add = TRUE), "the number of basis species is greater than the number of elements and charge", info = info)
expect_silent(newbasis <- basis(c("H2S", "Cl-"), c(-5, -3), add = TRUE), info = info)
expect_equal(newbasis$logact[5:6], c(-5, -3), info = info)
newspecies <- species()
expect_equal(colnames(newspecies)[5:6], c("H2S", "Cl-"), info = info)
expect_equal(newspecies$H2S, numeric(3), info = info)
a2 <- affinity(pH = c(0, 14))
expect_identical(a1$values, a2$values, info = info)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-basis.R
|
# Load default settings for CHNOSZ
reset()
info <- "Simple buffer works in 0, 1, and 2 dimensions"
add.OBIGT("SUPCRT92")
# Define 4 temperatures
T <- c(200, 300, 400, 500)
# calculate SiO2 activity buffered by quartz at 1000 bar
logaSiO2 <- subcrt(c("quartz", "SiO2"), c(-1, 1), T = T, P = 1000)$out$logK
# Set up system
basis(c("Al+3", "SiO2", "Na+", "K+", "H2O", "O2", "H+"))
species(c("K-feldspar", "albite", "paragonite", "dickite", "muscovite"))
# Calculate logact(SiO2) with quartz buffer
basis("SiO2", "quartz")
# 0 dimensions: constant T
a0 <- affinity(T = 200, P = 1000)
expect_equal(a0$buffer[[1]], logaSiO2[1], info = info)
# 1 dimension: variable T
a1 <- affinity(T = T, P = 1000)
expect_equal(a1$buffer[[1]], logaSiO2, info = info)
# 2 dimensions: variable T and Na+ activity (affinity errored in version <= 1.3.6)
a2 <- affinity(T = c(200, 500, 4), "Na+" = c(1, 5, 5), P = 1000)
expect_equivalent(a2$buffer[[1]][, 1], logaSiO2, info = info)
# 2 dimensions: variable K+ and Na+ activity (diagram errored in version <= 1.3.6)
A2 <- affinity("K+" = c(1, 5, 5), "Na+" = c(1, 5, 5), T = 200, P = 1000)
#D2 <- diagram(A2)
expect_equivalent(unique(as.vector(A2$buffer[[1]])), logaSiO2[1], info = info)
# A test for 0 dimensions with a two-mineral buffer 20201103
info <- "2-mineral buffer at a single point"
# (buffer errored trying to index columns of non-matrix prior to 1.3.6-85)
T <- 400
P <- 1000
basis(c("Fe", "O2"), c("cr", "gas"))
basis("O2", "HM")
O2_HM <- affinity(T = T, P = P, return.buffer = TRUE)$O2
logfO2 <- subcrt(c("hematite", "magnetite"), c(-6, 4), T = T, P = P)$out$logK
expect_equal(O2_HM, logfO2, info = info)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-buffer.R
|
# Load default settings for CHNOSZ
reset()
info <- "Expected errors are produced for inconsistent arguments"
expect_error(diagram(list()), "'eout' is not the output from", info = info)
basis("CHNOS")
species(c("glycine", "alanine"))
a <- affinity()
expect_message(diagram(a, plot.it = FALSE), "balance: on moles of CO2 in formation reactions", info = info)
e <- equilibrate(a)
expect_error(diagram(e, "Z"), "Z is not a valid diagram type", info = info)
info <- "Expected messages, errors and results arise using output from affinity()"
basis("CHNOS+")
# Fugacity of O2 is buffered here
basis("O2", "CO2-AC")
species(c("formic acid", "formate", "acetic acid", "acetate"))
# 0-D
a <- affinity()
# Equilibrium activities are not possible here
expect_error(diagram(a, "loga.equil"), "'eout' is not the output from equil\\(\\)", info = info)
# 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\\?", info = info)
# This one works - a barplot of A/2.303RT
expect_message(diagram(a, plot.it = FALSE), "balance: on moles of CO2 in formation reactions", info = info)
# 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)
expect_equal(as.numeric(d.CO2$plotvals), as.numeric(d.1$plotvals)/c(1, 1, 2, 2), info = info)
# Now run the calculation over a range of O2
basis("O2", -90)
# 1-D
a <- affinity(O2 = c(-80, -70))
# Ask for the equilibrium activity of CO2
expect_error(diagram(a, "CO2", groups = list(1:2, 3:4)), "can't plot equilibrium activities of basis species for grouped species", info = info)
expect_error(diagram(a, "CO2", alpha = TRUE), "equilibrium activities of basis species not available with alpha = TRUE", info = info)
d <- diagram(a, "CO2", plot.it = FALSE)
# Test that the result does in fact correspond to zero affinity of formation, how about for acetate?
a <- affinity(O2 = d$vals[[1]], CO2 = d$plotvals[[4]])
expect_equal(a$values[[4]], array(numeric(256)), info = info)
info <- "'groups' and 'alpha' work as expected"
basis("CHNOS+")
species(c("formic acid", "formate", "acetic acid", "acetate"))
# 1-D
a <- affinity(O2 = c(-80, -60))
e <- equilibrate(a)
# Group the species together
d <- diagram(e, groups = list(1:2, 3:4), plot.it = FALSE)
# We should find that their activities have been multiplied by the balance coefficients and summed
n.balance <- CHNOSZ:::balance(a)$n.balance
expect_equal(d$plotvals[[1]], log10(n.balance[1]*10^e$loga.equil[[1]] + n.balance[2]*10^e$loga.equil[[2]]), info = info)
expect_equal(d$plotvals[[2]], log10(n.balance[3]*10^e$loga.equil[[3]] + n.balance[4]*10^e$loga.equil[[4]]), info = info)
# 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, 256)), check.attributes = FALSE, info = info)
info <- "'normalize' and 'as.residue' work as expected"
basis("CHNOS")
species(c("LYSC_CHICK", "MYG_PHYCA", "RNAS1_BOVIN", "CYC_BOVIN"))
# 1-D
a <- affinity(O2 = c(-80, -70))
expect_error(diagram(a, normalize = TRUE), "can be TRUE only for a 2-D \\(predominance\\) diagram", info = info)
# 2-D
a <- affinity(H2O = c(-10, 0), O2 = c(-80, -70))
d1 <- diagram(a, normalize = TRUE, plot.it = FALSE)
e <- equilibrate(a, normalize = TRUE)
d2 <- diagram(e, plot.it = FALSE)
expect_equal(d1$predominant, d2$predominant, info = info)
expect_error(diagram(e, normalize = TRUE), "can be TRUE only if 'eout' is the output from affinity\\(\\)", info = info)
d3 <- diagram(a, as.residue = TRUE, plot.it = FALSE)
e <- equilibrate(a, as.residue = TRUE)
d4 <- diagram(e, plot.it = FALSE)
expect_equal(d3$predominant, d4$predominant, info = info)
info <- "NaN values from equilibrate() are preserved (as NA in predominance calculation)"
# Example provided by Grayson Boyer 20170411
basis(c("H2", "O2", "CO2"), c(-7.19, -60, -2.65))
species(c("n-hexadecanol", "n-hexadecanoic acid", "n-octadecanol", "n-octadecanoic acid"), c("liq", "liq", "liq", "liq"))
a <- affinity("H2" = c(-12, 0), "O2" = c(-90, -50), T = 30)
e <- equilibrate(a, balance = 1)
d <- diagram(e, plot.it = FALSE)
# equilibrate() here with default "boltzmann" method produces
# NaN at very high O2 + low H2 or very low O2 + high H2
expect_equal(d$predominant[1, 256], as.numeric(NA), info = info)
expect_equal(d$predominant[256, 1], as.numeric(NA), info = info)
## TODO: Exclude this test for now because plot.it = FALSE doesn't produce values for namesx 20190223
#info <- "labels are dropped outside of xlim and ylim ranges"
#basis(c("Fe", "O2", "S2"))
#species(c("iron", "ferrous-oxide", "magnetite",
# "hematite", "pyrite", "pyrrhotite"))
#a <- affinity(S2 = c(-50, 0), O2 = c(-90, -10), T = 200)
## total range: all species are present
#d <- diagram(a, fill = "heat", xlim = NULL, ylim = NULL, plot.it = FALSE)
#expect_equal(sum(is.na(d$namesx)), 0, info = info)
## reduce y-range to exclude hematite
#d <- diagram(a, fill = "heat", xlim = NULL, ylim = c(-90, -50), plot.it = FALSE)
#expect_equal(sum(is.na(d$namesx)), 1, info = info)
## reduce x-range to exclude pyrite
#d <- diagram(a, fill = "heat", xlim = c(-50, -20), ylim = c(-90, -50), plot.it = FALSE)
#expect_equal(sum(is.na(d$namesx)), 2, info = info)
info <- "P-T diagram has expected geometry"
# Modified from kayanite-sillimanite-andalusite example in ?diagram 20200811
basis(c("corundum", "quartz", "oxygen"))
species(c("kyanite", "sillimanite", "andalusite"))
a <- affinity(T = c(200, 900, 50), P = c(0, 9000, 51), exceed.Ttr = TRUE)
d <- diagram(a, plot.it = FALSE)
expect_equal(species()$name[d$predominant[1, 1]], "andalusite", info = info)
expect_equal(species()$name[d$predominant[1, 51]], "kyanite", info = info)
expect_equal(species()$name[d$predominant[50, 51]], "sillimanite", info = info)
info <- "diagram(type = .) and affinity(return.buffer = TRUE) give the same results"
# Extracted from ?buffer 20200811
O2 <- c(-85, -70, 4)
T <- c(25, 100, 4)
basis("CHNOS")
basis("CO2", 999)
species("acetic acid", -3)
species(1, -10)
a <- affinity(O2 = O2, T = T)
d <- diagram(a, type = "CO2", plot.it = FALSE)
and <- as.numeric(d$plotvals[[1]])
# Now do the calculation with affinity(return.buffer = TRUE)
basis("CO2", "AC")
mod.buffer("AC", logact = -10)
a.buffer <- affinity(O2 = O2, T = T, return.buffer = TRUE)
ana <- as.numeric(unlist(a.buffer[[1]]))
expect_equal(ana, and, info = info)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-diagram.R
|
# Load default settings for CHNOSZ
reset()
info <- "CGL species with NA volume produces reasonable results"
# 20171006: After rewriting much of the code in cgl(), melanterite and hydronium jarosite
# disappeared from the example diagram after Majzlan et al., 2006.
# Because the volumes are NA, the integral properties became NA,
# but it makes more sense to set them to zero.
ispecies <- info("melanterite")
expect_equal(info(ispecies)$V, NA_real_, info = info)
sout <- subcrt(ispecies, T = c(25, 25, 100, 100), P = c(1, 100, 1, 100))$out[[1]]
expect_false(any(is.na(sout$H)), info = info)
# For melanterite, which is listed in the database with zero heat capacity,
# all Cp and V integrals evaluate to zero
expect_true(length(unique(sout$H)) == 1, info = info)
info <- "gfun() gives expected results"
# Calculate values of g and its derivatives up to350 degrees C at Psat
Tc <- c(0, 25, 50, 100, 150, 200, 250, 300, 350)
# Get the required properties of water
w <- water(c("rho", "alpha", "daldT", "beta", "Psat"), T = convert(Tc, "K"), P = "Psat")
# Calculate g and its derivatives
gfun.Psat <- CHNOSZ:::gfun(w$rho/1000, Tc, w$Psat, w$alpha, w$daldT, w$beta)
# Up to 450 degrees C at 500 bar
Tc <- c(Tc, 400, 450)
w <- water(c("rho", "alpha", "daldT", "beta"), T = convert(Tc, "K"), P = 500)
gfun.500 <- CHNOSZ:::gfun(w$rho/1000, Tc, rep(500, length(Tc)), w$alpha, w$daldT, w$beta)
# Up to 600 degrees C at 1000 bar
Tc <- c(Tc, 500, 550, 600)
w <- water(c("rho", "alpha", "daldT", "beta"), T = convert(Tc, "K"), P = 1000)
gfun.1000 <- CHNOSZ:::gfun(w$rho/1000, Tc, rep(1000, length(Tc)), w$alpha, w$daldT, w$beta)
# Up to 1000 degrees C at 4000 bar
Tc <- c(Tc, 700, 800, 900, 1000)
w <- water(c("rho", "alpha", "daldT", "beta"), T = convert(Tc, "K"), P = 4000)
gfun.4000 <- CHNOSZ:::gfun(w$rho/1000, Tc, rep(4000, length(Tc)), w$alpha, w$daldT, w$beta)
# Values from table 5 of Shock et al., 1992
g.Psat.ref <- c(0, 0, 0, 0, -0.09, -1.40, -8.05, -35.23, -192.05)
g.500.ref <- c(0, 0, 0, 0, -0.02, -0.43, -3.55, -16.81, -56.78, -287.16, -1079.75)
g.1000.ref <- c(0, 0, 0, 0, 0, -0.12, -1.49, -8.44, -30.59, -85.09, -201.70, -427.17, -803.53, -1312.67)
g.4000.ref <- c(0, 0, 0, 0, 0, 0, 0, -0.01, -0.20, -1.14, -3.52, -7.84, -14.19, -22.21, -40.15, -54.28, -59.35, -55.17)
# Compare the calculations with the reference values
# Note: tolerance is set as low as possible (order of magnitude) for successful tests
expect_equal(gfun.Psat$g * 1e4, g.Psat.ref, tolerance = 1e-4, info = info)
expect_equal(gfun.500$g * 1e4, g.500.ref, tolerance = 1e-4, info = info)
expect_equal(gfun.1000$g * 1e4, g.1000.ref, tolerance = 1e-5, info = info)
expect_equal(gfun.4000$g * 1e4, g.4000.ref, tolerance = 1e-4, info = info)
# Values from table 6 of Shock et al., 1992
dgdT.Psat.ref <- c(0, 0, 0, -0.01, -0.62, -6.13, -25.33, -123.20, -1230.59)
dgdT.500.ref <- c(0, 0, 0, 0, -0.13, -2.21, -12.54, -46.50, -110.45, -734.92, -2691.41)
dgdT.1000.ref <- c(0, 0, 0, 0, -0.02, -0.75, -6.12, -24.83, -69.29, -158.38, -324.13, -594.43, -904.41, -1107.84)
dgdT.4000.ref <- c(0, 0, 0, 0, 0, 0, 0, -0.08, -0.89, -3.09, -6.60, -10.72, -14.55, -17.29, -17.26, -10.06, -0.08, 7.82)
expect_equal(gfun.Psat$dgdT * 1e6, dgdT.Psat.ref, tolerance = 1e-2, info = info)
expect_equal(gfun.500$dgdT * 1e6, dgdT.500.ref, tolerance = 1e-2, info = info)
expect_equal(gfun.1000$dgdT * 1e6, dgdT.1000.ref, tolerance = 1e-5, info = info)
expect_equal(gfun.4000$dgdT * 1e6, dgdT.4000.ref, tolerance = 1e-3, info = info)
# Values from table 7 of Shock et al., 1992
d2gdT2.Psat.ref <- c(0, 0, 0, -0.1, -3.7, -20.7, -74.3, -527.8, -15210.4)
d2gdT2.500.ref <- c(0, 0, 0, 0, -1.0, -9.3, -36.8, -109.4, -26.3, -2043.5, -4063.1)
d2gdT2.1000.ref <- c(0, 0, 0, 0, -0.2, -4.0, -20.5, -58.4, -125.4, -241.8, -433.9, -628.0, -550.0, -265.2)
d2gdT2.4000.ref <- c(0, 0, 0, 0, 0, 0, 0, -0.6, -2.9, -5.9, -7.9, -8.2, -6.8, -3.9, 4.0, 9.5, 9.6, 5.9)
expect_equal(gfun.Psat$d2gdT2 * 1e8, d2gdT2.Psat.ref, tolerance = 1e-5, info = info)
expect_equal(gfun.500$d2gdT2 * 1e8, d2gdT2.500.ref, tolerance = 1e-4, info = info)
expect_equal(gfun.1000$d2gdT2 * 1e8, d2gdT2.1000.ref, tolerance = 1e-4, info = info)
expect_equal(gfun.4000$d2gdT2 * 1e8, d2gdT2.4000.ref, tolerance = 1e-2, info = info)
# Values from table 8 of Shock et al., 1992
dgdP.Psat.ref <- c(0, 0, 0, 0, 0.03, 0.36, 1.92, 12.27, 227.21)
dgdP.500.ref <- c(0, 0, 0, 0, 0.01, 0.53, 1.75, 5.69, 107.61, 704.88, 1110.20)
dgdP.1000.ref <- c(0, 0, 0, 0, 0, 0.03, 0.31, 1.50, 5.25, 15.53, 4.78, 101.39, 202.25, 313.90)
dgdP.4000.ref <- c(0, 0, 0, 0, 0, 0, 0, 0, 0.05, 0.18, 0.46, 0.91, 1.54, 2.34, 4.26, 6.12, 7.29, 7.47)
expect_equal(gfun.Psat$dgdP * 1e6, dgdP.Psat.ref, tolerance = 1e-0, info = info)
expect_equal(gfun.500$dgdP * 1e6, dgdP.500.ref, tolerance = 1e+1, info = info)
expect_equal(gfun.1000$dgdP * 1e6, dgdP.1000.ref, tolerance = 1e-1, info = info)
expect_equal(gfun.4000$dgdP * 1e6, dgdP.4000.ref, tolerance = 1e-3, info = info)
info <- "hkf() and subcrt() give consistent values for non-solvation volume"
# Added on 20220326 to check usage of subcrt() with omega = 0
# in demo/DEW.R (b/c hkf() is no longer exported)
# Load SiO2 and Si2O4 data taken from DEW spreadsheet
iSi <- add.OBIGT("DEW", c("SiO2", "Si2O4"))
# Override check for DEW water model 20220920
mod.OBIGT(iSi, model = rep("HKF", 2))
Vn1 <- Vn2 <- numeric()
species <- c("CO3-2", "BO2-", "MgCl+", "SiO2", "HCO3-", "Si2O4")
# First method: use hkf() function
for(i in 1:length(species)) {
# Get HKF parameters
par <- info(info(species[i]), check.it = FALSE)
# Get the nonsolvation volume from hkf()
Vn1 <- c(Vn1, CHNOSZ:::hkf("V", par, contrib="n")$aq[[1]]$V)
}
# In CHNOSZ 2.0.0, hkf() assumes the parameters are Joules,
# but we gave it calorie-based parameters, so we need to convert to Joules
Vn1 <- convert(Vn1, "J")
# Second method: subcrt() with omega = 0
for(i in 1:length(species)) {
mod.OBIGT(species[i], omega = 0)
Vn2 <- c(Vn2, subcrt(species[i], T = 25)$out[[1]]$V)
}
expect_equal(Vn1, Vn2, info = info)
# Reference
# Shock, E. L., Oelkers, E. H., Johnson, J. W., Sverjensky, D. A. and Helgeson, H. C. (1992)
# Calculation of the thermodynamic properties of aqueous species at high pressures and temperatures:
# Effective electrostatic radii, dissociation constants and standard partial molal properties to 1000 degrees C and 5 kbar.
# J. Chem. Soc. Faraday Trans. 88, 803--826. https://doi.org/10.1039/FT9928800803
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-eos.R
|
# Load default settings for CHNOSZ
reset()
# Set up some simple systems
# One acid
basis("CHNOS+")
species("acetic acid")
aone <- suppressMessages(affinity())
# Acids
species(c("formic acid", "formate", "acetate"), add = TRUE)
aacid <- suppressMessages(affinity())
# Acids plus a sulfur species
species("H2S", add = TRUE)
aacidS <- suppressMessages(affinity())
# Proteins
species(c("LYSC_CHICK", "MYG_PHYCA", "RNAS1_BOVIN", "CYC_BOVIN"))
aprot <- suppressMessages(affinity())
info <- "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", info = info)
expect_message(equilibrate(aacid), "balance: on moles of CO2", info = info)
expect_message(equilibrate(aacid), "n.balance is 2 1 1 2", info = info)
expect_message(equilibrate(aacid), "loga.balance is -2.221848", info = info)
expect_message(equilibrate(aacid, loga.balance = -3), "loga.balance is -3", info = info)
expect_error(equilibrate(aacid, balance = "length"), "some species are not proteins", info = info)
expect_error(equilibrate(aacidS), "no basis species is present in all formation reactions", info = info)
expect_message(equilibrate(aacidS, balance = 1), "balance: on supplied numeric argument", info = info)
expect_message(equilibrate(aacidS, balance = 1), "n.balance is 1 1 1 1 1", info = info)
expect_message(equilibrate(aacidS, balance = 1), "loga.balance is -2.301029", info = info)
expect_error(equilibrate(aacidS, balance = "CO2"), "some species have no CO2 in the formation reaction", info = info)
expect_message(equilibrate(aprot), "balance: on protein length", info = info)
expect_message(equilibrate(aprot), "n.balance is 129 153 124 104", info = info)
expect_message(equilibrate(aprot), "loga.balance is -0.292429", info = info)
expect_message(equilibrate(aprot, normalize = TRUE), "using 'normalize' for molar formulas", info = info)
info <- "equilibrate() gives expected messages and errors for species selection"
# An error if we select no species
expect_error(equilibrate(aacid, ispecies = numeric()), "the length of ispecies is zero", info = info)
# An error if all affinities are NA
aNA <- aacid
aNA$values[1:2] <- NA
expect_error(equilibrate(aNA, ispecies = 1:2), "all species have NA affinities", info = info)
# A message if we select only certain of the species
expect_message(equilibrate(aacid, ispecies = 1:2), "using 2 of 4 species", info = info)
info <- "equilibrate() keeps the same total loga.balance for normalize = TRUE or FALSE"
# Use the proteins
e.norm <- equilibrate(aprot, normalize = TRUE)
e <- equilibrate(aprot)
# The total activity of the balance in the two cases
sumact.balance.norm <- sum(10^unlist(e.norm$loga.equil)*e.norm$m.balance)
sumact.balance <- sum(10^unlist(e$loga.equil)*e$n.balance)
expect_equal(sumact.balance.norm, sumact.balance, info = info)
info <- "equilibrate() reproduces an example from the literature"
# The reference values are the equilibrium logarithms of activities
# of sulfur species at logfO2 = -30 from Seewald, 2001
# We name them here because S5O6-2 isn't on the plot at logfO2 = -30,
# and to get them in order
species.ref <- c("S3O6-2", "S2O6-2", "S2O4-2", "S3-2", "S2-2", "S2O3-2", "HSO3-", "SO2", "HSO4-", "H2S")
# These values were read from the plot using g3data
loga.ref <- c(-28.82, -24.70, -22.10, -14.19, -12.12, -11.86, -8.40, -7.40, -6.54, -1.95)
# Set up the system - see ?diagram for an example showing the entire plot
basis("CHNOS+")
basis(c("pH", "O2"), c(5, -30))
# We include here all the species shown by Seewald, 2001
species(c("H2S", "S2-2", "S3-2", "S2O3-2", "S2O4-2", "S3O6-2", "S5O6-2", "S2O6-2", "HSO3-", "SO2", "HSO4-"))
a <- affinity(T = 325, P = 350)
# loga.balance = -2 signifies 10 mmolal total sulfur
e <- equilibrate(a, loga.balance = -2)
# Get the calculated activities of the reference species
loga.equil <- unlist(e$loga.equil[match(species.ref, e$species$name)])
# The test... the tolerance may seem high, but consider that the reference values
# were read from a plot with 30 logfO2 units spanning 4 inches
expect_true(all(abs(loga.equil-loga.ref) < 0.36), info = info)
info <- "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), info = info)
# 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), info = info)
# (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, info = info)
## 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", info = info)
expect_true(all(is.na(unlist(eb$loga.equil))), info = info)
## Third, check we can use method = "reaction"
expect_message(er1 <- equilibrate(a, balance = 1, method = "reaction"), "using reaction method", info = info)
expect_false(any(is.na(unlist(er1$loga.equil))), info = info)
# Is it an equilibrium solution?
species(1:3, unlist(er1$loga.equil))
a1 <- affinity()
expect_equal(diff(range(unlist(a1$values))), 0, info = info)
## Fourth, 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", info = info)
species(1:3, unlist(er11$loga.equil))
a11 <- affinity()
expect_equal(unlist(a1$values), unlist(a11$values), info = info)
## Fifth, check that equil.boltzmann won't run for balance <> 1
expect_error(equilibrate(a, balance = 1.000001, method = "boltzmann"), "won't run equil.boltzmann", info = info)
info <- "equilibrate() can be used with a vector of loga.balance values"
# System is balanced on CO2; species have different number of C, so loga.balance affects the equilibrium activities
basis("CHNOS")
species(c("formic acid", "acetic acid", "propanoic acid"))
# Calculate reference values at logfO2 = -80, log(aCO2tot) = -6
basis("O2", -80)
a <- affinity()
e80.6 <- unlist(equilibrate(a, loga.balance = -6)$loga.equil)
# Calculate reference values at logfO2 = -60, log(aCO2tot) = -8
basis("O2", -60)
a <- affinity()
e60.8 <- unlist(equilibrate(a, loga.balance = -8)$loga.equil)
# Calculate affinity on a transect: logfO2 from -80 to -60
O2 <- seq(-80, -60)
aO2 <- affinity(O2 = O2)
# Values calculated at the ends of the transect should be the same as above
eO2.6 <- equilibrate(aO2, loga.balance = -6)$loga.equil
expect_equal(list2array(eO2.6)[1, ], e80.6, info = info)
eO2.8 <- equilibrate(aO2, loga.balance = -8)$loga.equil
expect_equal(list2array(eO2.8)[21, ], e60.8, info = info)
# Make an vector of loga.balance to go with the logfO2 transect
# First we make a vector with non-matching length, and get an error
logaCO2.wronglen <- seq(-6, -8)
expect_error(equilibrate(aO2, loga.balance = logaCO2.wronglen), "length of loga.balance \\(3) doesn't match the affinity values \\(21)", info = info)
# Now do it with the correct length
logaCO2 <- seq(-6, -8, length.out = length(O2))
eO2 <- equilibrate(aO2, loga.balance = logaCO2)
# Now the first set of conditions is logfO2 = -80, log(aCO2tot) = -6
expect_equal(list2array(eO2$loga.equil)[1, ], e80.6, info = info)
# and the final set is logfO2 = -80, log(aCO2tot) = -6
expect_equal(list2array(eO2$loga.equil)[21, ], e60.8, info = info)
info <- "normalizing formulas of only selected species works as expected"
iC6 <- info("hexane", "liq")
iC12 <- info("dodecane", "liq")
`n-alkane` <- iC6:iC12
i2C6 <- info("2-methylpentane", "liq")
i2C9 <- info("2-methyloctane", "liq")
`2-isoalkane` <- i2C6:i2C9
basis("CHNOS")
basis("O2", -49.5)
species(`n-alkane`)
species(`2-isoalkane`, add = TRUE)
# Approximate conditions of Computer Experiment 27 (Helgeson et al., 2009, GCA)
a <- affinity(T = 150, P = 830, exceed.Ttr = TRUE)
# Using full chemical formulas
efull <- equilibrate(a)
dloga_isoalkane_full <- diff(unlist(efull$loga.equil[c(8, 11)]))
# Normalize all the formulas
enorm <- equilibrate(a, normalize = TRUE)
dloga_nalkane_norm <- diff(unlist(enorm$loga.equil[c(1, 7)]))
dloga_isoalkane_norm <- diff(unlist(enorm$loga.equil[c(8, 11)]))
# Normalize only the n-alkane formulas
isalk <- species()$ispecies %in% `n-alkane`
emix <- equilibrate(a, normalize = isalk)
# The activity ratios for the normalized formulas should be the same in both calculations
dloga_nalkane_mix <- diff(unlist(emix$loga.equil[c(1, 7)]))
expect_equal(dloga_nalkane_mix, dloga_nalkane_norm, info = info)
# The actvitity ratios for the not-normalized formulas should be similar in both calculations
# (not identical becuase they are affected by total activity, unlike normalized formulas)
dloga_isoalkane_mix <- diff(unlist(emix$loga.equil[c(8, 11)]))
maxdiff <- function(x, y) max(abs(y - x))
expect_true(maxdiff(dloga_isoalkane_mix, dloga_isoalkane_full) < 0.07, info = info)
# However, the difference between normalized and not-normalized formulas is much greater
expect_true(maxdiff(dloga_isoalkane_mix, dloga_isoalkane_norm) > maxdiff(dloga_isoalkane_mix, dloga_isoalkane_full), info = info)
info <- "solids are not equilibrated, but their stability fields are calculated"
# Added 20191111; based on an example sent by Feng Lai on 20191020
Cu_aq <- c("CuCl", "CuCl2-", "CuCl3-2", "CuHS", "Cu(HS)2-", "CuOH", "Cu(OH)2-")
Cu_cr <- c("copper", "chalcocite")
basis(c("Cu+", "HS-", "Cl-", "H2O", "H+", "oxygen"))
basis("O2", -35)
basis("H+", -5)
species(Cu_aq, -3)
species(Cu_cr, add = TRUE)
a <- affinity("Cl-" = c(-3, 0, 200), "HS-" = c(-10, 0, 200), T = 325, P = 500)
apredom <- diagram(a, plot.it = FALSE)$predominant
e <- equilibrate(a)
epredom <- diagram(e, plot.it = FALSE)$predominant
expect_equal(apredom, epredom, info = info)
# Also test that equilibrate() works with *only* solids 20200715
species(Cu_cr)
acr <- affinity(a)
ecr <- equilibrate(acr)
expect_identical(e$values[8:9], ecr$values, info = info)
# Reference
# Seewald, J. S. (2001)
# Aqueous geochemistry of low molecular weight hydrocarbons at elevated temperatures and
# pressures: Constraints from mineral buffered laboratory experiments
# Geochim. Cosmochim. Acta 65, 1641--1664. https://doi.org/10.1016/S0016-7037(01)00544-0
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-equilibrate.R
|
# Load default settings for CHNOSZ
reset()
info <- "info.character() produces expected results and messages"
expect_equal(CHNOSZ:::info.character("acetate", "cr"), NA, info = info)
expect_message(CHNOSZ:::info.character("acetate", "cr"), "only 'aq' is available", info = info)
expect_message(CHNOSZ:::info.character("methane", "cr"), "only 'gas' 'liq' are available", info = info)
expect_message(CHNOSZ:::info.character("methane"), "also available in liq", info = info)
expect_message(CHNOSZ:::info.character("SiO2", "cr"), "also available in.*quartz", info = info)
expect_message(CHNOSZ:::info.character("chalcocite"), "found chalcocite\\(cr\\) with 2 polymorphic transitions", info = info)
# H2O is a special case
expect_equal(CHNOSZ:::info.character("H2O", "aq"), CHNOSZ:::info.character("H2O", "liq"), info = info)
info <- "info.numeric() produces expected errors and messages"
expect_error(CHNOSZ:::info.numeric(9999), "species index 9999 not found in thermo\\(\\)\\$OBIGT", info = info)
iargon <- info("argon", "gas")
expect_message(CHNOSZ:::info.numeric(iargon), "Cp° of argon\\(gas\\) is NA; set by EOS parameters to 4.97", info = info)
iMgSO4 <- info("MgSO4")
expect_message(CHNOSZ:::info.numeric(iMgSO4), "V° of MgSO4\\(aq\\) is NA; set by EOS parameters to 1.34", info = info)
info <- "info.approx() produces expected messages"
expect_message(CHNOSZ:::info.approx("lactic"), "is similar to lactic acid", info = info)
expect_message(CHNOSZ:::info.approx("lactic acid"), "is ambiguous", info = info)
# Note though that info("lactic acid") finds a match because info.character is used first...
expect_equal(info("lactic acid"), grep("lactic acid", thermo()$OBIGT$name), info = info)
# Looking in optional databases 20190127
expect_message(info("dickite"), "is in an optional database", info = info)
info <- "info() can be used for cr and aq descriptions of the same species and proteins"
i2 <- info("LYSC_CHICK", c("cr", "aq"))
expect_equal(thermo()$OBIGT$state[i2], c("cr", "aq"), info = info)
expect_equal(info(i2)[1, ], info(i2[1]), check.attributes = FALSE, info = info)
info <- "info() gives correct column names for species using the AD model"
# Add an aqueous species conforming to the AD model
iCO2 <- mod.OBIGT("CO2", model = "AD", a = -8.8321, b = 11.2684, c = -0.0850)
params <- info(iCO2)
expect_equal(params$a, -8.8321, info = info)
expect_equal(params$b, 11.2684, info = info)
expect_equal(params$xi, -0.0850, info = info)
# 20220208
info <- "info() and subcrt() report consistent values for thermodynamic properties of Berman minerals"
sout <- subcrt("K-feldspar", T = 25)$out[[1]]
iout <- info(info("K-feldspar"))
expect_equal(sout$G, iout$G, tolerance = 13, scale = 1)
expect_equal(sout$H, iout$H)
expect_equal(sout$S, iout$S, tolerance = 0.00009, scale = 1)
expect_equal(sout$Cp, iout$Cp)
expect_equal(sout$V, iout$V)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-info.R
|
# Load default settings for CHNOSZ
reset()
info <- "Handling of repeated T, P, pH values is correct"
expect_message(expect_error(ionize.aa(T = c(25, 25, 100, 100, 100), P = c(100, 1000, 1000, 1000, 1000))),
"18 species at 3 values of T \\(\u00BAC\\) and P \\(bar\\) \\(wet\\)", info = info)
expect_message(ia.25x10 <- ionize.aa(T = rep(25,10), ret.val = "pK"), "18 species at 25 \u00BAC and 1 bar \\(wet\\)", info = info)
# We have ten rows of the same values
expect_identical(ia.25x10[1, ], apply(ia.25x10, 2, unique), info = info)
# also ten rows of the same values for same pH
ia.7x10 <- ionize.aa(pH = rep(7, 10), ret.val = "pK")
expect_identical(ia.7x10[1, ], apply(ia.7x10, 2, unique), info = info)
# Same behaviour with alpha and aavals
ia.7x10 <- ionize.aa(pH = rep(7, 10), ret.val = "alpha")
expect_identical(ia.7x10[1, ], apply(ia.7x10, 2, unique), info = info)
ia.7x10 <- ionize.aa(pH = rep(7, 10), ret.val = "aavals")
expect_identical(ia.7x10[1, ], apply(ia.7x10, 2, unique), info = info)
info <- "Charge summations for aa compositions are internally consistent"
# One pH value should give the same results as two of the same value
expect_equal(ionize.aa(thermo()$protein[1:10,], pH = 7),
ionize.aa(thermo()$protein[1:10,], pH = c(7,7))[1, , drop = FALSE], check.attributes = FALSE, info = info)
# At pH extremes we should be fully ionized
iplus <- match(c("His", "Lys", "Arg", "chains"), colnames(thermo()$protein))
iminus <- match(c("Cys", "Asp", "Glu", "Tyr", "chains"), colnames(thermo()$protein))
ia520 <- ionize.aa(thermo()$protein[1:10,], pH = c(-5, 20))
expect_equal(ia520[1, ], rowSums(thermo()$protein[1:10, iplus]), info = info)
expect_equal(ia520[2, ], -rowSums(thermo()$protein[1:10, iminus]), info = info)
info <- "Charge summations for aa compositions are consistent with literature"
# Comparison with values for LYSC_CHICK digitized from Fig. 10 of Dick et al., 2006
# charge at 25, 100, 150 degrees and at 25 degrees with cysteine suppressed (oxidized)
# at pH 4, 6, 8, 10, 12, 14
Z.LYSC_CHICK.25 <- c(13.3, 8.5, 5.1, -6.2, -14, -20.6)
Z.LYSC_CHICK.100 <- c(13.3, 7.8, -3.4, -15.2, -20.9, -20.9)
Z.LYSC_CHICK.150 <- c(13.3, 7.1, -8.0, -20.0, -20.9, -20.9)
Z.LYSC_CHICK.25_oxid <- c(13.5, 8.7, 7.6, 1.6, -6.2, -12.9)
aa <- pinfo(pinfo("LYSC_CHICK"))
pH <- c(4, 6, 8, 10, 12, 14)
# The literature values are significantly different at this tolerance (the following is not TRUE)
# expect_equal(Z.LYSC_CHICK.25, Z.LYSC_CHICK.100, 1e-1, info = info)
expect_equal(ionize.aa(aa, pH = pH, T = 25)[, 1], Z.LYSC_CHICK.25, tolerance = 1e-1, check.attributes = FALSE, info = info)
expect_equal(ionize.aa(aa, pH = pH, T = 100)[, 1], Z.LYSC_CHICK.100, tolerance = 1e-1, check.attributes = FALSE, info = info)
expect_equal(ionize.aa(aa, pH = pH, T = 150)[, 1], Z.LYSC_CHICK.150, tolerance = 1e-1, check.attributes = FALSE, info = info)
expect_equal(ionize.aa(aa, pH = pH, T = 25, suppress.Cys = TRUE)[, 1], Z.LYSC_CHICK.25_oxid, tolerance = 1e-2, check.attributes = FALSE, info = info)
info <- "Heat capacity of ionization is consistent with literature"
# Heat capacity (kcal mol-1 K-1) of AMYA_PYRFU at 60, 80, 100, 120, 140 degrees
# for nonionzed protein and ionized protein at pH 6 and 12
# digitized from Fig. 11 of Dick et al., 2006
Cp.AMYA_PYRFU.nonion <- convert(c(41.26, 42.22, 42.85, 43.33, 43.74), "J")
Cp.AMYA_PYRFU.pH6 <- convert(c(37.44, 37.81, 37.78, 37.41, 36.70), "J")
Cp.AMYA_PYRFU.pH12 <- convert(c(36.19, 36.59, 36.52, 36.11, 35.30), "J")
aa <- pinfo(pinfo("AMYA_PYRFU"))
Cp.ionization.pH6 <- ionize.aa(aa, "Cp", T = c(60, 80, 100, 120, 140), pH = 6)
Cp.ionization.pH12 <- ionize.aa(aa, "Cp", T = c(60, 80, 100, 120, 140), pH = 12)
# The literature values are significantly different at this tolerance (the following is not TRUE)
# expect_equal(Cp.AMYA_PYRFU.pH6 - Cp.AMYA_PYRFU.nonion, Cp.AMYA_PYRFU.pH12 - Cp.AMYA_PYRFU.nonion, 1e-2, info = info)
expect_equal(Cp.ionization.pH6[,1], (Cp.AMYA_PYRFU.pH6 - Cp.AMYA_PYRFU.nonion)*1000, tolerance = 1e-2, check.attributes = FALSE, info = info)
expect_equal(Cp.ionization.pH12[,1], (Cp.AMYA_PYRFU.pH12 - Cp.AMYA_PYRFU.nonion)*1000, tolerance = 1e-2, check.attributes = FALSE, info = info)
info <- "Gibbs energy of ionization is consistent with literature"
# Gibbs energy (Mcal mol-1) of AMY_BACSU at pH 0, 2, 4, 6, 8, 10, 12, 14 at 25 and 100 degrees
# digitized from Fig. 12 of Dick et al., 2006
G.AMY_BACSU.25 <- convert(c(-24.9, -24.9, -24.7, -24.5, -24.4, -23.9, -23.5, -23.2), "J")
G.AMY_BACSU.100 <- convert(c(-26.7, -26.7, -26.4, -26.1, -25.7, -25.1, -24.9, -24.9), "J")
# To reproduce the calculations in the paper, use superseded properties of [Met], [Gly], and [UPBB]
mod.OBIGT("[Met]", G = -35245, H = -59310, S = 40.38, E_units = "cal")
mod.OBIGT("[Gly]", G = -6075, H = -5570, S = 17.31, E_units = "cal")
mod.OBIGT("[UPBB]", G = -21436, H = -45220, S = 1.62, E_units = "cal")
G.nonionized <- subcrt("AMY_BACSU", T = c(25, 100))$out[[1]]$G
aa <- pinfo(pinfo("AMY_BACSU"))
G.ionization.25 <- ionize.aa(aa, "G", T = 25, pH = seq(0, 14, 2))[,1]
G.ionization.100 <- ionize.aa(aa, "G", T = 100, pH = seq(0, 14, 2))[,1]
expect_equal(G.nonionized[1] + G.ionization.25, G.AMY_BACSU.25 * 1e6, tolerance = 1e-3, check.attributes = FALSE, info = info)
expect_equal(G.nonionized[2] + G.ionization.100, G.AMY_BACSU.100 * 1e6, tolerance = 1e-3, check.attributes = FALSE, info = info)
info <- "Affinity of ionization is consistent with manual calculations"
# Equilibrium constant of ionization of [Cys] at 25 and 100 degres C
logK.Cys <- subcrt(c("[Cys]", "[Cys-]", "H+"), c(-1, 1, 1), T = c(25, 100))$out$logK
# Affinity (A/2.303RT) of ionization of [Cys] at pH 7
A.2303RT.Cys.pH7 <- logK.Cys + 7
# Equilibrium constant of ionization of [His] at 25 degrees C
logK.His <- subcrt(c("[His]", "H+", "[His+]"), c(-1, -1, 1), T = 25)$out$logK
# Affinity (A/2.303RT) of ionization of [His] at pH 7 and 14
A.2303RT.His.pH7_14 <- logK.His - c(7, 14)
# Calculate the affinities at pH 7 at 25 and 100 degrees C using ionize()
A.ionization.pH7 <- ionize.aa(property = "A", T = c(25, 100), ret.val = "aavals")
iCys <- match("[Cys-]", colnames(A.ionization.pH7))
expect_equal(A.2303RT.Cys.pH7, A.ionization.pH7[, iCys], check.attributes = FALSE, info = info)
# Calculate the affinities at pH 7 and 14 at 25 degrees C using ionize()
A.ionization.pH7_14 <- ionize.aa(property = "A", pH = c(7, 14), ret.val = "aavals")
iHis <- match("[His+]", colnames(A.ionization.pH7_14))
expect_equal(A.2303RT.His.pH7_14, A.ionization.pH7_14[, iHis], check.attributes = FALSE, info = info)
# Test whether the additive value for a protein is internally consistent
alpha <- ionize.aa(ret.val = "alpha")
affinity <- ionize.aa(property = "A", ret.val = "aavals")
aa <- pinfo(pinfo("LYSC_CHICK"))
iionize <- match(c("Cys", "Asp", "Glu", "His", "Lys", "Arg", "Tyr", "chains", "chains"), colnames(aa))
# Sum of the affinities of ionization of each ionizable group mutiplied by
# their degree of formation and by their frequency in the protein
A.protein <- sum(alpha * affinity * aa[, iionize])
expect_equal(ionize.aa(aa, property = "A")[1, ], A.protein, check.attributes = FALSE, info = info)
# Test added 20210407
info <- "Protein ionization calculations are not affected by E.units()"
E.units("cal")
basis(c("CO2", "H2", "NH4+", "H2O", "H2S", "H+"))
a1 <- affinity(iprotein = 1)
E.units("J")
a2 <- affinity(iprotein = 1)
expect_equal(a1$values, a2$values, info = info)
# Test added 20220621
info <- "Messages indicate status of ionization calculations"
basis("CHNOS+")
expect_message(a <- affinity(iprotein = 1), "affinity: ionizing proteins ...", info = info)
thermo("opt$ionize.aa" = FALSE)
expect_message(a <- affinity(iprotein = 1), "affinity: NOT ionizing proteins because thermo()$opt$ionize.aa is FALSE", fixed = TRUE, info = info)
# Reference
# Dick, J. M., LaRowe, D. E. and Helgeson, H. C. (2006)
# Temperature, pressure, and electrochemical constraints on protein speciation:
# Group additivity calculation of the standard molal thermodynamic properties of ionized unfolded proteins.
# Biogeosciences 3, 311--336. https://doi.org/10.5194/bg-3-311-2006
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-ionize.aa.R
|
# Load default settings for CHNOSZ
reset()
info <- "pK values as a function of temperature are consistent with literature values"
# pK at 0, 100, 200, 300 degrees C digitized from Fig. 4 of Dick et al., 2006
DLH06.pK <- list(`[Cys-]` = c(8.82, 7.44, 7.14, 7.90),
`[Asp-]` = c(4.06, 3.80, 4.17, 5.30),
`[Glu-]` = c(4.36, 4.39, 5.11, 6.68),
`[His+]` = c(6.44, 4.91, 3.92, 3.17),
`[Lys+]` = c(10.92,8.02, 6.27, 4.75),
`[Arg+]` = c(13.38,10.02,8.11, 6.56),
`[Tyr-]` = c(9.68, 8.02, 7.59, 8.33),
`[AABB+]`= c(2.34, 2.36, 2.62, 2.81),
`[AABB-]`= c(10.16,7.85, 6.51, 6.28))
this.pK <- ionize.aa(T = c(0, 100, 200, 300), ret.val = "pK")
# Ionization of [Cys] and [His] is off more than the others
expect_equal(this.pK[, 1], DLH06.pK$`[Cys-]`, tolerance = 1e-1, check.attributes = FALSE, info = info)
expect_equal(this.pK[, 2], DLH06.pK$`[Asp-]`, tolerance = 1e-2, check.attributes = FALSE, info = info)
expect_equal(this.pK[, 3], DLH06.pK$`[Glu-]`, tolerance = 1e-2, check.attributes = FALSE, info = info)
expect_equal(this.pK[, 4], DLH06.pK$`[His+]`, tolerance = 1e-1, check.attributes = FALSE, info = info)
expect_equal(this.pK[, 5], DLH06.pK$`[Lys+]`, tolerance = 1e-2, check.attributes = FALSE, info = info)
expect_equal(this.pK[, 6], DLH06.pK$`[Arg+]`, tolerance = 1e-2, check.attributes = FALSE, info = info)
expect_equal(this.pK[, 7], DLH06.pK$`[Tyr-]`, tolerance = 1e-2, check.attributes = FALSE, info = info)
expect_equal(this.pK[, 8], DLH06.pK$`[AABB+]`,tolerance = 1e-2, check.attributes = FALSE, info = info)
expect_equal(this.pK[, 9], DLH06.pK$`[AABB-]`,tolerance = 1e-2, check.attributes = FALSE, info = info)
info <- "there is one pK value for each ionizable group at each temperature"
pH <- seq(0, 14, 2)
T <- seq(0, 150, 15)
val <- expand.grid(pH = pH, T = T)
Z <- ionize.aa(pH = val$pH, T = val$T, ret.val = "pK")
expect_equal(length(unique(Z)), 99, info = info)
# Reference
# Dick, J. M., LaRowe, D. E. and Helgeson, H. C. (2006)
# Temperature, pressure, and electrochemical constraints on protein speciation:
# Group additivity calculation of the standard molal thermodynamic properties of ionized unfolded proteins.
# Biogeosciences 3, 311--336. https://doi.org/10.5194/bg-3-311-2006
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-ionize.aa_pK.R
|
# Load default settings for CHNOSZ
reset()
info <- "Non-zero ionic strength transforms variables from activity to molality"
# What happens with activity coefficients when using subcrt() to calculate affinity,
# and in the rest of the main workflow of CHNOSZ?
# 20171025 first version
# 20181106 include non-zero activity coefficient of CO2(aq)
# The maximum absolute pairwise difference between x and y
maxdiff <- function(x, y) max(abs(y - x))
### First get the activity coefficients of H+ and HCO3-
## The long way...
wprop <- water(c("A_DH", "B_DH"), P = 1)
speciesprops <- subcrt(c("H+", "HCO3-", "CO2"), T = 25)$out
nonid <- nonideal(c("H+", "HCO3-", "CO2"), speciesprops, IS = 1, T = 298.15, P = 1, A_DH = wprop$A_DH, B_DH = wprop$B_DH)
# Compare with a precalculated value:
expect_true(maxdiff(nonid[[2]]$loggam, -0.1868168) < 1e-7, info = info)
## The short way...
out1 <- subcrt(c("H+", "HCO3-", "CO2"), T = 25, IS = 1)$out
loggam_HCO3 <- out1[[2]]$loggam
loggam_CO2 <- out1[[3]]$loggam
expect_equal(nonid[[2]]$loggam, loggam_HCO3, info = info)
expect_equal(nonid[[3]]$loggam, loggam_CO2, info = info)
## Take-home message -1: with default settings, the activity coefficient of H+ is always 1
### How do activity coefficient affect the value of G?
# Let's step back and look at the *standard Gibbs energy* at IS = 0
out0 <- subcrt(c("H+", "HCO3-", "CO2"), T = 25)$out
# The adjusted standard Gibbs energy is less than the standard Gibbs energy
# by an amount determined by the activity coefficient
expect_equal(out1[[2]]$G - out0[[2]]$G, -convert(loggam_HCO3, "G"), info = info)
expect_equal(out1[[3]]$G - out0[[3]]$G, -convert(loggam_CO2, "G"), info = info)
## Take-home message 0: setting IS in subcrt() gives adjusted standard Gibbs energy
# What is the equilibrium constant for the reaction CO2 + H2O = H+ + HCO3-?
# (this is the standard state property at IS = 0)
logK <- subcrt(c("CO2", "H2O", "H+", "HCO3-"), c(-1, -1, 1, 1), T = 25)$out$logK
# We get logK = -6.34468 (rounded)
expect_true(maxdiff(logK, -6.34468) < 1e-6, info = info)
### What is the affinity of the reaction at pH=7 and molalities of HCO3- and CO2 = 10^-3?
## Case 1: ionic strength = 0, so gamma = 0 and activity = molality
# First calculate it by hand from 2.303RTlog(K/Q)
# logQ = (logaH+ + logaHCO3-) - (logaH2O + logaCO2)
logQ0 <- (-7 + -3) - (0 + -3) # i.e. 7
# Convert logs to energy according to G = -2.303RTlogK
# (we negate that to get affinity)
A0manual <- -convert(logK - logQ0, "G")
# Now the run calculation with subcrt
A0subcrt <- subcrt(c("CO2", "H2O", "H+", "HCO3-"), c(-1, -1, 1, 1), T = 25, logact = c(-3, 0, -7, -3))$out$A
# We get the same affinity!
expect_equal(A0subcrt, A0manual, info = info)
## Case 2: ionic strength = 1, so activity = molality * gamma
logaHCO3 <- -3 + loggam_HCO3
logaCO2 <- -3 + loggam_CO2
logQ1 <- (-7 + logaHCO3) - (0 + logaCO2)
A1manual <- -convert(logK - logQ1, "G")
A1subcrt <- subcrt(c("CO2", "H2O", "H+", "HCO3-"), c(-1, -1, 1, 1), T = 25, logact = c(-3, 0, -7, -3), IS = 1)$out$A
expect_equal(A1subcrt, A1manual, info = info)
## Take-home message 1: using subcrt with IS not equal to zero, the "logact"
## argument is logmolal in affinity calculations for charged aqueous species
### Now calculate the affinities using affinity()
basis("CHNOS+") # pH = 7, logaCO2 = -3
species(c("CO2", "HCO3-")) # logactivities = -3
## Case 1: IS = 0
a0 <- affinity()
# That gives us values in log units; convert to energy
# (HCO3- is species #2)
A0affinity <- -convert(a0$values[[2]], "G")
expect_equal(A0affinity[[1]], A0subcrt, info = info)
## Case 2: IS = 1
a1 <- affinity(IS = 1)
A1affinity <- -convert(a1$values[[2]], "G")
expect_equal(A1affinity[[1]], A1subcrt, info = info)
## Take-home message 2: using affinity() with IS not equal to zero, the "logact"
## set by species() is logmolal in affinity calculations for charged aqueous species
### Now, swap HCO3- for CO2 in the basis
swap.basis("CO2", "HCO3-")
basis("HCO3-", -3)
a0 <- affinity()
a1 <- affinity(IS = 1)
# Look at HCO3 formation affinity:
# they're both zero at IS = 0 or 1
expect_equal(a0$values[[2]][1], 0, info = info)
expect_equal(a1$values[[2]][1], 0, info = info)
# Look at CO2 formation affinity:
ACO2_0affinity <- -convert(a0$values[[1]], "G")
ACO2_1affinity <- -convert(a1$values[[1]], "G")
# What's that?? we're looking at the reverse of the above
# reaction, i.e. H+ + HCO3- = CO2 + H2O
# so, logK = 6.345
logKrev <- -logK
logQrev0 <- -logQ0
logQrev1 <- -logQ1
ACO2_0manual <- -convert(logKrev - logQrev0, "G")
ACO2_1manual <- -convert(logKrev - logQrev1, "G")
expect_equal(ACO2_0manual, ACO2_0affinity[[1]], info = info)
expect_equal(ACO2_1manual, ACO2_1affinity[[1]], info = info)
## Take-home message 3: using affinity() with IS not equal to zero, the "logact"
## set by basis() is logmolal in affinity calculations for charged aqueous species
### Now look at equilibrate()
e0 <- equilibrate(a0)
e1 <- equilibrate(a1)
# Using the equilibrated values, calculate affinity of the reaction CO2 + H2O = H+ + HCO3-
# Case 1: IS = 0
logact_HCO3 <- e0$loga.equil[[2]]
logact_CO2 <- e0$loga.equil[[1]]
logQeq0 <- (-7 + logact_HCO3) - (logact_CO2 + 0)
Aeq0 <- -convert(logK - logQeq0, "G") # zero!
expect_equal(Aeq0[[1]], 0, info = info)
# Case 2: IS = 1
logact_HCO3 <- e1$loga.equil[[2]]
logact_CO2 <- e1$loga.equil[[1]]
# Here, loga.equil is the *molality*, so we must multiply by loggam
logQeq1 <- (-7 + logact_HCO3 + loggam_HCO3) - (logact_CO2 + loggam_CO2 + 0)
Aeq1 <- -convert(logK - logQeq1, "G") # zero!
expect_equal(Aeq1[[1]], 0, info = info)
## Take-home message 4: using affinity() with IS not equal to zero, the "loga.equil"
## returned by equilibrate() is logmolal for speciation calculations with charged aqueous species
# Finally, what is loga.balance?
a.balance <- 10^e1$loga.balance
m.total <- sum(10^unlist(e1$loga.equil))
expect_equal(a.balance, m.total, info = info)
## Take-home message 5: using affinity() with IS not equal to zero, the "loga.balance"
## used by equilibrate() is the logarithm of total molality of the balancing basis species
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-logmolality.R
|
# Load default settings for CHNOSZ
reset()
info <- "Chemical formulas with unknown elements cause a warning"
expect_warning(makeup("X"), "element\\(s\\) not in thermo\\(\\)\\$element", info = info)
info <- "Unparseable chemical formulas cause an error"
expect_error(makeup("h"), "is not a simple chemical formula", info = info)
expect_error(makeup("1H"), "is not a simple chemical formula", info = info)
expect_error(makeup("(H2O"), "has unpaired parentheses", info = info)
expect_error(makeup("H)2O"), "has unpaired parentheses", info = info)
info <- "Numeric species indices, and coefficients indicating charge can be parsed"
# these are all equivalent formulas for the electron
expect_equal(makeup("-1"), makeup("Z0-1"), info = info)
expect_equal(makeup("-1"), makeup("(Z-1)"), info = info)
expect_equal(makeup("-1"), makeup("Z-1+0"), info = info)
# The species index of the electron in thermo()$OBIGT
ie <- info("e-")
expect_equal(makeup("-1"), makeup(ie), info = info)
info <- "Signed and fractional coefficients can be parsed"
expect_equal(10*makeup("C10.6N1.6P0.1"), makeup("C106N16P1"), info = info)
expect_equal(as.numeric(makeup("C-1.567")), c(1, -1.567), info = info)
expect_equal(as.numeric(makeup("C-1.567+0")), -1.567, info = info)
info <- "Parenthetical and suffixed subformulas can be parsed"
expect_equal(makeup("(H)2O"), makeup("H2O"), info = info)
info <- "Summing and multiply formulas works as expected"
ispecies <- info(c("B(OH)3", "gypsum", "lysine:HCl"))
# The elemental composition all of those, added together
msaved <- as.array(c(B = 1, C = 6, Ca = 1, Cl = 1, H = 22, N = 2, O = 11, S = 1))
expect_equal(makeup(ispecies, sum = TRUE), msaved, info = info)
# The elemental composition in a 1:2:-1 ratio
msaved121 <- as.array(c(B = 1, C = -6, Ca = 2, Cl = -1, H = -4, N = -2, O = 13, S = 2))
expect_equal(makeup(ispecies, c(1,2,-1), sum = TRUE), msaved121, info = info)
expect_error(makeup(ispecies, c(1,2), sum = TRUE), "multiplier does not have .* length = number of formulas", info = info)
info <- "makeup() has a fall-through mechanism for matrices and named objects"
# This series of tests mimics situations encountered in residue.info() via species.basis()
# Ultimately we want to be able to use species.basis() for species indices, formulas or makeups
expect_equal(makeup(makeup("CH4")), makeup("CH4"), info = info)
expect_equal(makeup(list(makeup("CH4"))), list(makeup("CH4")), info = info)
basis("CHNOS")
# We turn the result into a vector using [1, ] so as to drop row names conditionally placed by species.basis
expect_equal(CHNOSZ:::species.basis("CH4")[1, ], CHNOSZ:::species.basis(info("CH4"))[1, ], info = info)
expect_equal(CHNOSZ:::species.basis(makeup("CH4"))[1, ], CHNOSZ:::species.basis("CH4")[1, ], info = info)
# A matrix should be turned into a list
protein <- c("LYSC_CHICK", "RNAS1_BOVIN", "CYC_BOVIN", "MYG_PHYCA", "MYG_HORSE")
pf <- protein.formula(protein) # a matrix with elements on the columns
basis(protein) # yup, a basis set made of proteins, just for fun
bmat <- basis.elements() # a matrix with elements on the columns
expect_equal(makeup(pf)[[1]], makeup(as.chemical.formula(pf)[1]), info = info)
expect_equal(makeup(pf), makeup(bmat), info = info)
info <- "as.chemical.formula() moves charge to the end"
mkp <- makeup("Z-1HCO3")
expect_equal(as.chemical.formula(mkp), "HCO3-1", info = info) # i.e. not -1HCO3
# TODO: Commented this test because detaching the package isn't always possible 20220131
#info <- "makeup() can process formulas if the package is not attached"
## test added 20200727
#CHNOSZattached <- "CHNOSZ" %in% (.packages())
#if(CHNOSZattached) detach("package:CHNOSZ", unload = TRUE)
#mH2O <- CHNOSZ::makeup("H2O")
#expect_identical(mH2O, c(H = 2, O = 1), info = info)
#if(CHNOSZattached) library(CHNOSZ)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-makeup.R
|
# Load default settings for CHNOSZ
reset()
info <- "mix() and mosaic() yield same affinities for a bimetallic mineral"
# Test that we get the same values for affinity of a bimetallic mineral formed from different single-metal basis species using:
# 1. affinity() of the bimetallic mineral minus mix() for two single-metal systems in correct proportions
# 2. mosaic() with two sets of changing basis species corresponding to the single-metal systems
# 20200724
plot.it <- FALSE
res <- 50
## Uncomment to show plots
#plot.it <- TRUE
#par(mfrow = c(2, 2))
# Set up system
pH <- c(0, 7, res)
Eh <- c(-1, 1, res)
basis(c("copper", "iron", "H2S", "H2O", "e-", "H+"))
iFe.cr <- info(c("iron", "ferrous-oxide", "magnetite", "hematite"))
iFe.aq <- info(c("Fe+2", "FeOH+"))
iCu.cr <- info(c("copper", "cuprite", "tenorite"))
iCu.aq <- info(c("Cu+", "CuOH"))
# METHOD 1 (mix)
# Fe-O-H diagram
# Use logact = 0 for everything so we can compare results with mosaic()
species(c(iFe.aq, iFe.cr), 0)
# Increase the temperature so we get a ferrous oxide field
aFe <- affinity(pH = pH, Eh = Eh, T = 300)
dFe <- diagram(aFe, fill = fill(aFe), plot.it = plot.it)
# Cu-O-H diagram
species(c(iCu.aq, iCu.cr), 0)
aCu <- affinity(aFe) # argument recall
dCu <- diagram(aCu, fill = fill(aCu), plot.it = plot.it)
# Combine the diagrams for a 1:5 mixture of Fe:Cu
aFeCu15 <- mix(dFe, dCu, parts = c(1, 5))
dFeCu15 <- diagram(aFeCu15, fill = fill(aFeCu15), min.area = 0.01, plot.it = FALSE)
# Calculate affinity of bornite (Cu5FeS4)
species("bornite")
abornite <- affinity(aFe) # argument recall
# Because of the 1) equal stoichiometry and 2) same basis species
# used for bornite and the mix() diagram, subtracting these makes sense
# 20201221 But now we have to multiply by 5 because predominant.values is divided by the balancing coefficients
abornite_vs_predominant.values <- abornite$values[[1]] - 5 * dFeCu15$predominant.values
if(plot.it) image(abornite_vs_predominant.values)
# METHOD 2 (mosaic)
# Make a mosaic diagram to calculate affinity of bornite with changing basis species
# (which correspond to the Fe-O-H and Cu-O-H diagrams)
iFe <- c(iFe.cr, iFe.aq)
iCu <- c(iCu.cr, iCu.aq)
# TODO: allow numeric values for bases in mosaic()
#mbornite <- mosaic(list(iFe, iCu), pH = pH, Eh = Eh, T = 300, predominant = list(dFe$predominant, dCu$predominant))
Fe <- info(iFe, check.it = FALSE)$name
Cu <- info(iCu, check.it = FALSE)$name
mbornite <- mosaic(list(Fe, Cu), pH = pH, Eh = Eh, T = 300, blend = FALSE)
if(plot.it) image(mbornite$A.species$values[[1]])
# The test: values calculated both ways should be equal
expect_equal(abornite_vs_predominant.values, mbornite$A.species$values[[1]], tol = 1e-5, scale = 1, info = info)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-mix.R
|
# Load default settings for CHNOSZ
reset()
info <- "minimal usage of mod.OBIGT() creates usable data entries"
# We need at least a name and some property
expect_error(mod.OBIGT("test"), "species name and a property", info = info)
# A valid formula is needed
expect_warning(expect_error(mod.OBIGT("test", date = as.character(Sys.Date())), "is not a simple chemical formula", info = info),
"please supply a valid chemical formula", info = info)
# The default state is aq
expect_message(itest <- mod.OBIGT("test", formula = "Z0", date = as.character(Sys.Date())), "added test\\(aq\\)", info = info)
# We should get NA values of G for a species with NA properties
expect_true(all(is.na(subcrt(itest)$out[[1]]$G)), info = info)
# A single value of G comes through to subcrt
mod.OBIGT("test", G = 100)
expect_equal(subcrt("test", T = 25, P = 1)$out[[1]]$G, 100, info = info)
# Values for Cp and c1 integrate to the same values of G
G.Cp <- subcrt(mod.OBIGT(list(name = "test", S = 0, Cp = 100)))$out[[1]]$G
G.c1 <- subcrt(mod.OBIGT(list(name = "test", S = 0, c1 = 100)))$out[[1]]$G
expect_equal(G.Cp, G.c1, info = info)
info <- "mod.OBIGT() works with numeric argument (species index)"
# Test added 20200707
i1 <- info("CH4")
# Previously this failed with an error
i2 <- mod.OBIGT(i1, name = "methane")
expect_identical(i1, i2, info = info)
expect_identical(info(i2)$name, "methane", info = info)
# Test added 20220920
info <- "Can add > 1 species; different states get different default models; info() works after mod.OBIGT"
iC12C13 <- mod.OBIGT(c("X", "Y"), formula = c("C12", "C13"), state = c("aq", "cr"))
expect_identical(info(iC12C13)$model, c("HKF", "CGL"))
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-mod.OBIGT.R
|
# This is a long test ... only run it "at home" 20220129
if(!at_home()) exit_file("Skipping long test")
# Load default settings for CHNOSZ
reset()
info <- "results are consistent with affinity()"
basis(c("CO2", "H2O", "NH3", "O2"), c(0, 0, 0, 0))
species(c("alanine", "glycine"))
a25 <- affinity()
# This is a no-op case because we only allow NH3 to swap for NH3, and CO2 for CO2;
# however it still exercises the affinity scaling and summing code
m1_25 <- mosaic(list("NH3", "CO2"))
# This failed before we divided by loga.tot to get _relative_ abundances of basis species in mosaic.R
expect_equal(a25$values, m1_25$A.species$values, info = info)
# The next call failed when which.pmax(), called by diagram(), choked on a list of length one
m2_25 <- mosaic(list("NH3", "CO2"), blend = FALSE)
expect_equal(a25$values, m2_25$A.species$values, info = info)
# Make sure the function works when all affinities are NA
a500 <- suppressWarnings(affinity(T = 500))
# Using blend = TRUE was failing prior to version 1.1.3-37
m1_500 <- suppressWarnings(mosaic(list("NH3", "CO2"), T = 500))
expect_equal(a500$values, m1_500$A.species$values, info = info)
m2_500 <- suppressWarnings(mosaic(list("NH3", "CO2"), blend = FALSE, T = 500))
expect_equal(a500$values, m2_500$A.species$values, info = info)
info <- "blend = TRUE produces reasonable values"
# A more rigorous test than above. this was failing because loga.tot (actually, a.tot)
# was computed incorrectly, by sum()ing an unlist()ed list (the affinities of basis species)
# to produce a single value; corrected by using Reduce for addition of vectors/arrays in the list.
# Example adapted from ?mosaic
basis(c("FeO", "SO4-2", "H2O", "H+", "e-"))
basis("SO4-2", -6)
basis("Eh", -0.15)
species(c("hematite", "magnetite"))
# The basis species we'll swap through
bases <- c("SO4-2", "HSO4-", "HS-", "H2S")
# Calculate affinities using the predominant basis species
pH <- c(0, 14, 29)
m1 <- mosaic(bases, pH = pH, blend = FALSE)
# Calculate affinities with smooth transitions between basis species
m2 <- mosaic(bases, pH = pH)
# These species have no S so the results should be similar,
expect_equivalent(m2$A.species$values[[1]], m1$A.species$values[[1]], info = info)
# Now with S-bearing species ...
species(c("pyrrhotite", "pyrite"))
m3 <- mosaic(bases, pH = pH, blend = FALSE)
m4 <- mosaic(bases, pH = pH)
# The results are different ...
expect_equal(sapply(m3$A.species$values, "[", 13), sapply(m4$A.species$values, "[", 13), tol = 1e-1, info = info)
# But more similar at extreme pH values
expect_equal(sapply(m3$A.species$values, "[", 1), sapply(m4$A.species$values, "[", 1), tol = 1e-7, info = info)
expect_equal(sapply(m3$A.species$values, "[", 29), sapply(m4$A.species$values, "[", 29), tol = 1e-13, info = info)
info <- "mosaic() - equilibrate() produces equilibrium activities"
# Test added 20190505, based on a calculation sent by Kirt Robinson
basis(c("CO2", "NH3", "O2", "H2O", "H+"))
species(c("acetamide", "acetic acid", "acetate"))
m <- mosaic(c("NH3", "NH4+"), pH = c(0, 14))
e <- equilibrate(m$A.species)
# Calculate logK for form acetamide from predominant species at low pH
s1 <- subcrt(c("acetic acid", "NH4+", "acetamide", "water", "H+"), c(-1, -1, 1, 1, 1), T = 25)
logK1 <- s1$out$logK
# Values of activities
loga_acetic <- e$loga.equil[[2]]
loga_NH4 <- m$E.bases[[1]]$loga.equil[[2]]
loga_acetamide <- e$loga.equil[[1]]
loga_H2O <- m$E.bases[[1]]$basis$logact[[4]]
loga_Hplus <- - m$E.bases[[1]]$vals$pH
logQ1 <- - loga_acetic - loga_NH4 + loga_acetamide + loga_H2O + loga_Hplus
A1 <- logQ1 - logK1
## In CHNOSZ versions before 1.3.2-5 (20190505), the affinity was zero at the pH extremes,
## but peaked with a value of 0.3 (log10(2)) at pH 9.2 (equal activities of NH3 and NH4+)
#plot(m$E.bases[[1]]$vals$pH, A1, type = "l")
#title(main = describe.reaction(s1$reaction))
expect_equivalent(as.numeric(A1), rep(0, length(A1)), info = info)
info <- "mosaic() - solubility() produces equilibrium activities"
# Test added 20190505, simplified from demo/contour.R with varying pH at constant logfO2
# Define temperature and pressure
T <- 250
P <- 500
# Set up system
basis(c("Au", "Cl-", "H2S", "H2O", "oxygen", "H+"))
species(c("Au(HS)2-", "AuHS", "AuOH", "AuCl2-"))
# This get us close to total S = 0.01 m
basis("H2S", -2)
# Set a low logfO2 to get into H2S - HS- fields
basis("O2", -40)
# Calculate solution composition for 1 mol/kg NaCl
NaCl <- NaCl(T = T, P = P, m_tot = 1)
basis("Cl-", log10(NaCl$m_Cl))
# Calculate affinity with changing basis species
bases <- c("H2S", "HS-", "HSO4-", "SO4-2")
m <- mosaic(bases, pH = c(2, 10), T = 250, P = 500, IS = NaCl$IS)
# Calculate solubility
s <- solubility(m$A.species)
# Calculate logK to form Au(HS)2- in H2S stability region
# Include IS here to compute adjusted logK
s1 <- subcrt(c("Au", "H2S", "oxygen", "Au(HS)2-", "H2O", "H+"), c(-1, -2, -0.25, 1, 0.5, 1), T = T, P = P, IS = NaCl$IS)
logK1 <- s1$out$logK
# Calculate logQ with the given or computed activities
loga_Au <- m$A.bases$basis$logact[[1]]
loga_H2S <- m$E.bases[[1]]$loga.equil[[1]]
logf_O2 <- m$A.bases$basis$logact[[5]]
loga_AuHS2minus <- s$loga.equil[[1]]
loga_H2O <- m$A.bases$basis$logact[[4]]
loga_Hplus <- - m$A.bases$vals$pH
logQ1 <- - 1 * loga_Au - 2 * loga_H2S - 0.25 * logf_O2 + 1 * loga_AuHS2minus + 0.5 * loga_H2O + 1 * loga_Hplus
# Calculate affinity - should be zero!
A1 <- logQ1 - logK1
#plot(m$A.bases$vals$pH, A1, type = "l")
#title(main = describe.reaction(s1$reaction))
expect_equivalent(as.numeric(A1), rep(0, length(A1)), info = info)
info <- "mosaic() - equilibrate() produces equilibrium activities that are consistent with
stability differences of minerals and multiple groups of changing basis species"
# Test added 20190505, adapted from demo/mosaic.R:
# select a constant pH close to equal activities of CO2 - HCO3-,
# and a range of Eh that crosses the upper and lower boundaries
# of pyrite with siderite (including the H2S - SO4-2 transition)
basis(c("FeO", "SO4-2", "H2O", "H+", "e-", "CO3-2"))
basis("SO4-2", -6)
basis("CO3-2", 0)
basis("pH", 6.3)
species(c("pyrrhotite", "pyrite", "hematite", "magnetite", "siderite"))
# Two sets of changing basis species:
# speciate SO4-2, HSO4-, HS-, H2S as a function of Eh and pH
# speciate CO3-2, HCO3-, CO2 as a function of pH
bases <- list(c("SO4-2", "HSO4-", "HS-", "H2S"),
c("CO3-2", "HCO3-", "CO2"))
# Calculate affinities using the relative abundances of different basis species
m <- mosaic(bases, Eh = c(-0.5, 0))
# Calculate logK for pyrite-siderite reaction using arbitrarily chosen basis species
s1 <- subcrt(c("pyrite", "CO2", "H2O", "H+", "e-", "siderite", "H2S"), c(-1, -1, -1, -2, -2, 1, 2), T = 25)
logK <- s1$out$logK
# Get activities of minerals, water, and H+
loga_pyrite <- loga_siderite <- loga_H2O <- 0
loga_Hplus <- m$A.bases[[1]]$basis$logact[[4]]
# Get activities of basis species
loga_eminus <- - convert(m$A.bases[[1]]$vals$Eh, "pe")
loga_H2S <- m$E.bases[[1]]$loga.equil[[4]]
loga_CO2 <- m$E.bases[[2]]$loga.equil[[3]]
# Calculate affinity
logQ <- -1 * loga_pyrite - 1 * loga_CO2 - 1 * loga_H2O - 2 * loga_Hplus - 2 * loga_eminus + 1 * loga_siderite + 2 * loga_H2S
A <- logQ - logK
# The "hand-calculated" value and the affinity calculated by the function should be equal
Adiff <- A - (m$A.species$values[[2]] - m$A.species$values[[5]])
#par(mfrow = c(2, 1))
#diagram(m$A.species)
#plot(m$A.bases[[1]]$vals$Eh, Adiff, type = "l")
#title(main = "A(single basis species) - A(all basis species)")
#legend("topleft", legend = describe.reaction(s1$reaction))
expect_equivalent(as.numeric(Adiff), rep(0, length(Adiff)), info = info)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-mosaic.R
|
# Load default settings for CHNOSZ
reset()
# 20161219
info <- "loggam and logK values are consistent"
oldnon <- nonideal("Alberty")
rxn1 <- subcrt(c("anhydrite", "Ca+2", "SO4-2"), c(-1, 1, 1), P = 1, T = 25, I = 0)
rxn2 <- subcrt(c("anhydrite", "Ca+2", "SO4-2"), c(-1, 1, 1), P = 1, T = 25, I = 0.7)
expect_equal(rxn1$out$logK, rxn2$out$loggam + rxn2$out$logK, info = info)
nonideal(oldnon)
# The maximum absolute pairwise difference between x and y
maxdiff <- function(x, y) max(abs(y - x))
# 20171011
info <- "A and B parameters are calculated correctly"
## Psat
# Values from Helgeson, 1967 "Solution chemistry and metamorphism"
# (chapter in http://www.worldcat.org/oclc/152725534)
T <- c(25, 50, 100, 200, 300, 350)
A <- c(0.5095, 0.5354, 0.6019, 0.8127, 1.2979, 1.9936)
B <- c(0.3284, 0.3329, 0.3425, 0.3659, 0.4010, 0.4300)
SUP <- water.SUPCRT92(c("A_DH", "B_DH"), T = convert(T, "K"), P = "Psat")
IAP <- water.IAPWS95(c("A_DH", "B_DH"), T = convert(T, "K"), P = "Psat")
expect_true(maxdiff(SUP$A_DH, A) < 0.18, info = info)
expect_true(maxdiff(IAP$A_DH, A) < 0.11, info = info)
expect_true(maxdiff(SUP$B_DH / 1e8, B) < 0.012, info = info)
expect_true(maxdiff(IAP$B_DH / 1e8, B) < 0.008, info = info)
# Values digitized from Fig. 10 of Manning et al., 2013
# doi: 10.2138/rmg.2013.75.5
## 5 kbar
T5 <- c(25, seq(100, 1000, 100))
A5 <- c(0.441, 0.49, 0.583, 0.685, 0.817, 0.983, 1.164, 1.409, 1.673, 1.938, 2.187)
B5 <- c(0.328, 0.336, 0.350, 0.363, 0.377, 0.391, 0.405, 0.421, 0.434, 0.445, 0.453)
SUP5 <- water.SUPCRT92(c("A_DH", "B_DH"), T = convert(T5, "K"), P = rep(5000, 11))
IAP5 <- water.IAPWS95(c("A_DH", "B_DH"), T = convert(T5, "K"), P = rep(5000, 11))
DEW5 <- water.DEW(c("A_DH", "B_DH"), T = convert(T5, "K"), P = rep(5000, 11))
# DEW is the winner here
expect_true(maxdiff(SUP5$A_DH, A5) < 0.47, info = info)
expect_true(maxdiff(IAP5$A_DH, A5) < 0.26, info = info)
expect_true(maxdiff(DEW5$A_DH, A5) < 0.14, info = info)
expect_true(maxdiff(SUP5$B_DH / 1e8, B5) < 0.036, info = info)
expect_true(maxdiff(IAP5$B_DH / 1e8, B5) < 0.021, info = info)
expect_true(maxdiff(DEW5$B_DH / 1e8, B5) < 0.013, info = info)
## 30 kbar
T30 <- seq(700, 1000, 100)
A30 <- c(0.625, 0.703, 0.766, 0.815)
B30 <- c(0.386, 0.400, 0.409, 0.416)
DEW30 <- water.DEW(c("A_DH", "B_DH"), T = convert(T30, "K"), P = rep(30000, 4))
expect_true(maxdiff(DEW30$A_DH, A30) < 0.06, info = info)
expect_true(maxdiff(DEW30$B_DH / 1e8, B30) < 0.024, info = info)
info <- "Affinity transect incorporates IS correctly"
basis("CHNOS+")
species("acetate")
# Calculations at single combinations of logfO2 and IS
basis("O2", -80); a80_0 <- affinity()
basis("O2", -60); a60_1 <- affinity(IS = 1)
# Calculations on a transect with those endpoints
a <- affinity(O2 = seq(-80, -60, length.out = 4), IS = seq(0, 1, length.out = 4))
expect_equal(a$values[[1]][1], a80_0$values[[1]][1], info = info)
expect_equal(a$values[[1]][4], a60_1$values[[1]][1], info = info)
# 20171013: that was working fine, but how about a more complicated case involving T?
a25_0 <- affinity()
a50_1 <- affinity(T = 50, IS = 1)
a <- affinity(T = seq(25, 50, length.out = 4), IS = seq(0, 1, length.out = 4))
expect_equal(a$values[[1]][1], a25_0$values[[1]][1], info = info)
expect_equal(a$values[[1]][4], a50_1$values[[1]][1], info = info)
# 20171221
info <- "Nonideality calculations work for Zn"
# nonideal() had a bug where both Z and Zn were identified as the charge
# in the species formula, producing an error in this calculation
expect_true(is.list(subcrt(c("Zn+2", "Cl-", "ZnCl+"), c(-1, -1, 1), T = 200, P = 16, IS = 0.05)), info = info)
# 20181105
info <- "Activity coefficients are similar to those from HCh"
# Ionic strength of solution and activity coefficients of Na+ and Cl-
# calculated with HCh version 3.7 (Shvarov and Bastrakov, 1999) at 1000 bar,
# 100, 200, and 300 degress C, and 1 to 6 molal NaCl,
# using the default "B-dot" activity coefficient model (Helgeson, 1969)
# and the default setting for the Setchenow equation,
# for which the only non-zero term is the mole fraction to molality conversion factor
IS.HCh <- list(`100` = c(0.992, 1.969, 2.926, 3.858, 4.758, 5.619),
`300` = c(0.807, 1.499, 2.136, 2.739, 3.317, 3.875),
`500` = c(0.311, 0.590, 0.861, 1.125, 1.385, 1.642))
gamCl.HCh <- list(`100` = c(0.565, 0.545, 0.551, 0.567, 0.589, 0.615),
`300` = c(0.366, 0.307, 0.275, 0.254, 0.238, 0.224),
`500` = c(0.19, 0.137, 0.111, 0.096, 0.085, 0.077))
gamNa.HCh <- list(`100` = c(0.620, 0.616, 0.635, 0.662, 0.695, 0.730),
`300` = c(0.421, 0.368, 0.339, 0.318, 0.302, 0.288),
`500` = c(0.233, 0.180, 0.155, 0.138, 0.126, 0.117))
gamNaCl.HCh <- list(`100` = c(0.965, 0.933, 0.904, 0.876, 0.850, 0.827),
`300` = c(0.968, 0.941, 0.915, 0.892, 0.870, 0.849),
`500` = c(0.977, 0.955, 0.935, 0.915, 0.897, 0.879))
# Calculate activity coefficent of Cl- at each temperature
gamCl.100 <- 10^subcrt("Cl-", T = 100, P = 1000, IS = IS.HCh$`100`)$out$`Cl-`$loggam
gamCl.300 <- 10^subcrt("Cl-", T = 300, P = 1000, IS = IS.HCh$`300`)$out$`Cl-`$loggam
gamCl.500 <- 10^subcrt("Cl-", T = 500, P = 1000, IS = IS.HCh$`500`)$out$`Cl-`$loggam
expect_true(maxdiff(gamCl.100, gamCl.HCh$`100`) < 0.07, info = info)
expect_true(maxdiff(gamCl.300, gamCl.HCh$`300`) < 0.03, info = info)
expect_true(maxdiff(gamCl.500, gamCl.HCh$`500`) < 0.009, info = info)
# Calculate activity coefficent of Na+ at each temperature
gamNa.100 <- 10^subcrt("Na+", T = 100, P = 1000, IS = IS.HCh$`100`)$out$`Na+`$loggam
gamNa.300 <- 10^subcrt("Na+", T = 300, P = 1000, IS = IS.HCh$`300`)$out$`Na+`$loggam
gamNa.500 <- 10^subcrt("Na+", T = 500, P = 1000, IS = IS.HCh$`500`)$out$`Na+`$loggam
expect_true(maxdiff(gamNa.100, gamNa.HCh$`100`) < 0.08, info = info)
expect_true(maxdiff(gamNa.300, gamNa.HCh$`300`) < 0.03, info = info)
expect_true(maxdiff(gamNa.500, gamNa.HCh$`500`) < 0.013, info = info)
# Calculate activity coefficent of NaCl at each temperature
gamNaCl.100 <- 10^subcrt("NaCl", T = 100, P = 1000, IS = IS.HCh$`100`)$out$`NaCl`$loggam
gamNaCl.300 <- 10^subcrt("NaCl", T = 300, P = 1000, IS = IS.HCh$`300`)$out$`NaCl`$loggam
gamNaCl.500 <- 10^subcrt("NaCl", T = 500, P = 1000, IS = IS.HCh$`500`)$out$`NaCl`$loggam
expect_true(maxdiff(gamNaCl.100, gamNaCl.HCh$`100`) < 0.09, info = info)
expect_true(maxdiff(gamNaCl.300, gamNaCl.HCh$`300`) < 0.09, info = info)
expect_true(maxdiff(gamNaCl.500, gamNaCl.HCh$`500`) < 0.10, info = info)
# 20190603
info <- "G, H, S, and Cp corrections are calculated consistently"
nonideal("Alberty")
# First test: DG = DH - T * DS
T <- seq(25, 100, 25)
GHSstd <- subcrt("Na+", T = T)$out[[1]][, c("G", "H", "S")]
GHSadj <- subcrt("Na+", T = T, IS = 0.25)$out[[1]][, c("G", "H", "S")]
D <- GHSadj - GHSstd
TK <- convert(T, "K")
expect_equal(D$G, D$H - TK * D$S, info = info)
# Second test: Cp = dH/dT
# Calculate the derivative numerically at 50 degC
T <- c(49.9, 50.1)
# First do it for standard properties (at I = 0) to make sure the test is set up correctly
Cpstd <- subcrt("Na+", T = 50)$out[[1]][, "Cp"]
Hstd <- subcrt("Na+", T = T)$out[[1]][, "H"]
expect_equal(Cpstd, diff(Hstd) / diff(T), tol = 1e-6, info = info)
# Now at I = 0.25 mol kg-1
Cpadj <- subcrt("Na+", T = 50, IS = 0.25)$out[[1]][, "Cp"]
Hadj <- subcrt("Na+", T = T, IS = 0.25)$out[[1]][, "H"]
expect_equal(Cpadj, diff(Hadj) / diff(T), tol = 1e-6, info = info)
# Another way to test things: compare our calculations with values of the Debye-Huckel limiting slopes (Alberty, 2001, Table 1)
Glim <- c(2.56494, 2.70073, 2.84196, 2.91482, 2.98934, 3.14349)
Hlim <- c(1.075, 1.213, 1.3845, 1.4775, 1.5775, 1.800)
Cplim <- c(13.255, 15.41, 17.90, 19.27, 20.725, 23.885)
T <- c(0, 10, 20, 25, 30, 40)
IS <- 0.25
GHSCpstd <- subcrt("Na+", T = T)$out[[1]][, c("G", "H", "S", "Cp")]
GHSCpadj <- subcrt("Na+", T = T, IS = IS)$out[[1]][, c("G", "H", "S", "Cp")]
D <- GHSCpadj - GHSCpstd
# Now make the checks
IBterm <- IS ^ 0.5 / (1 + 1.6 * IS ^ 0.5)
expect_equal(Glim * 1000, - D$G / IBterm, tol = 1e-4, info = info)
expect_equal(Hlim * 1000, D$H / IBterm, tol = 1e-3, info = info)
expect_equal(Cplim, D$Cp / IBterm, tol = 1e-4, info = info)
info <- "Affinity has IS-T and T-IS calculations"
basis("CHNOS+")
species(c("H2S", "HS-", "HSO4-", "SO4-2", "SO2"))
# Reference values: affinity as a function of IS at T = 250 degC
a250 <- affinity(IS = seq(0, 1, 0.2), T = 250)
# Increasing ionic strength should raise the affinity of HS-
expect_true(all(diff(a250$values[[2]]) > 0), info = info)
# T-IS grid; use different resolutions to help identify indexing bugs
a_T.IS <- affinity(IS = c(0, 1, 6), T = c(190, 310, 5))
expect_equivalent(a_T.IS$values[[2]][, 3], as.numeric(a250$values[[2]]), info = info)
# IS-T grid
a_IS.T <- affinity(T = c(190, 310, 5), IS = c(0, 1, 6))
expect_equivalent(a_IS.T$values[[2]][3, ], as.numeric(a250$values[[2]]), info = info)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-nonideal.R
|
# Load default settings for CHNOSZ
reset()
info <- "pinfo() deals with underscore in first argument"
expect_equal(pinfo("LYSC_CHICK"), 6, info = info)
info <- "pinfo() returns NA for unmatched protein_organism pairs"
expect_equal(pinfo(c("LYSC", "zzzz"), "CHICK"), c(6, NA), info = info)
info <- "pinfo() returns NA if no organism is given"
expect_equal(pinfo(c("LYSC_CHICK", "MYGPHYCA")), c(6, NA), info = info)
info <- "protein.equil() reports values consistent with Dick and Shock (2011)"
protein <- pinfo(c("CSG_METVO", "CSG_METJA"))
# To reproduce the calculations in the paper, use superseded properties of [Met], [Gly], and [UPBB]
mod.OBIGT("[Met]", G = -35245, H = -59310, S = 40.38, E_units = "cal")
mod.OBIGT("[Gly]", G = -6075, H = -5570, S = 17.31, E_units = "cal")
mod.OBIGT("[UPBB]", G = -21436, H = -45220, S = 1.62, E_units = "cal")
basis("CHNOS+")
suppressMessages(swap.basis("O2", "H2"))
pequil <- protein.equil(protein, loga.protein=-3)
# Before 20230630:
# With R = 8.314445 (= 1.9872 * 4.184) in util.units(), ionize.aa(pinfo(protein)) gives:
# 20 18
#[1,] -56.06509 -55.87025
# Astar/RT in the paragraph following Eq. 23, p. 6 of DS11
# (truncated because of rounding)
# expect_true(any(grepl(c("0\\.435.*1\\.36"), pequil)), info = info)
# After 20230630:
# With R = 8.314463 in util.units(), ionize.aa(pinfo(protein)) gives:
# 20 18
#[1,] -56.06511 -55.87027
# The differences propagate up, so the test was changed on 20230630:
expect_true(any(grepl(c("0\\.437.*1\\.36"), pequil)), info = info)
# log10 activities of the proteins in the left-hand column of the same page
expect_true(any(grepl(c("-3\\.256.*-2\\.834"), pequil)), info = info)
# Reference
# Dick, J. M. and Shock, E. L. (2011) Calculation of the relative chemical stabilities of proteins
# as a function of temperature and redox chemistry in a hot spring.
# PLoS ONE 6, e22782. https://doi.org/10.1371/journal.pone.0022782
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-protein.info.R
|
# Load default settings for CHNOSZ
reset()
# SSH97: Sverjensky et al., 1997
# doi:10.1016/S0016-7037(97)00009-4
info <- "Recalculated values for HSiO3- match those in original reference"
iSiO2 <- info("SiO2")
iHSiO3 <- info("HSiO3-")
# Get values used in OBIGT
SiO2_GHS_OBIGT <- thermo()$OBIGT[iSiO2, c("G", "H", "S")]
HSiO3_GHS_OBIGT <- thermo()$OBIGT[iHSiO3, c("G", "H", "S")]
# Get values from SSH97
add.OBIGT("SLOP98")
SiO2_GHS_SSH97 <- thermo()$OBIGT[iSiO2, c("G", "H", "S")]
HSiO3_GHS_SSH97 <- thermo()$OBIGT[iHSiO3, c("G", "H", "S")]
# Calculate differences
OBIGT_Delta <- HSiO3_GHS_OBIGT - SiO2_GHS_OBIGT
SSH97_Delta <- HSiO3_GHS_SSH97 - SiO2_GHS_SSH97
# Perform test
expect_equal(OBIGT_Delta, SSH97_Delta, info = info)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-recalculate.R
|
# Load default settings for CHNOSZ
reset()
# Test added 20190303
# If this test fails, update extdata/thermo/stoich.csv.xz and rebuild the package:
# reset()
# formula <- thermo()$OBIGT$formula
# stoich <- i2A(formula)
# write.csv(stoich, "stoich.csv")
# system("xz -f stoich.csv")
info <- "Prebuilt stoichiometric matrix is consistent with the default database"
expect_identical(rownames(thermo()$stoich), thermo()$OBIGT$formula, info = info)
info <- "Errors and recalculations produce expected messages"
expect_error(retrieve(c("A", "B", "C")), '"A" is not an element', info = info)
expect_error(retrieve(c("A", "B", "C", "D")), '"A", "D" are not elements', info = info)
add.OBIGT("SUPCRT92")
expect_message(retrieve("Ti"), "updating stoichiometric matrix", info = info)
info <- "retrieve('all') works"
all1 <- sort(retrieve("all"))
all2 <- sort(retrieve(as.list(colnames(thermo()$stoich))))
expect_identical(all1, all2, info = info)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-retrieve.R
|
# Load default settings for CHNOSZ
reset()
info <- "solubility() produces stable conditions (affinity = 0)"
# Set pH range and resolution, constant temperature and ionic strength
pH <- c(0, 14)
res <- 100
T <- 25
IS <- 0
## Start with CO2
basis(c("carbon dioxide", "H2O", "O2", "H+"))
# Use ca. atmospheric PCO2
basis("CO2", -3.5)
species(c("CO2", "HCO3-", "CO3-2"))
a <- affinity(pH = c(pH, res), T = T, IS = IS)
s <- solubility(a)
# A function to check for stable conditions (affinity = 0)
# Do this by setting activities in species() then calculating the affintiy
checkfun <- function(i) {
logact <- sapply(s$loga.equil, "[", i)
species(1:3, logact)
basis("pH", s$vals[[1]][i])
affinity(T = T, IS = IS)
}
# Check any 'i' here - let's just take two
expect_equal(max(abs(unlist(checkfun(33)$values))), 0, info = info)
expect_equal(max(abs(unlist(checkfun(99)$values))), 0, info = info)
# Now do calcite
basis(c("calcite", "Ca+2", "H2O", "O2", "H+"))
species(c("CO2", "HCO3-", "CO3-2"))
a <- affinity(pH = c(pH, res), T = T, IS = IS)
s <- solubility(a, dissociate = TRUE)
# Here we need to also set the activity of Ca+2
checkfun <- function(i) {
logact <- sapply(s$loga.equil, "[", i)
species(1:3, logact)
basis("pH", s$vals[[1]][i])
basis("Ca+2", s$loga.balance[i])
affinity(T = T, IS = IS)
}
expect_equal(max(abs(unlist(checkfun(33)$values))), 0, info = info)
expect_equal(max(abs(unlist(checkfun(99)$values))), 0, info = info)
info <- "Backward compatible and new calling styles produce the same results"
# Test added 20210319
# Calculate solubility of a single substance:
# Gaseous S2 with a given fugacity
# Define basis species (any S-bearing basis species is allowed)
basis(c("HS-", "oxygen", "H2O", "H+"))
basis("pH", 6)
# Load the substances (minerals or gases) to be dissolved
species("S2", -20)
# List the formed aqueous species
i_aq <- info(c("SO4-2", "HS-"))
# Place arguments for affinity() or mosaic() after the first argument of solubility()
s1 <- solubility(i_aq, O2 = c(-55, -40), T = 125, in.terms.of = "SO4-2")
# Backward-compatible method limited to dissolving one species:
# Include S2(g) in the basis species
basis(c("S2", "oxygen", "H2O", "H+"))
basis("pH", 6)
basis("S2", -20)
# Calculate affinities for formation of aqueous species
species(c("SO4-2", "HS-"))
a <- affinity(O2 = c(-55, -40), T = 125)
s_old <- solubility(a, in.terms.of = "SO4-2")
# sout$species (in memoized subcrt() output) have different rownames
s1 <- s1[names(s1) != "sout"]
s_old <- s_old[names(s_old) != "sout"]
expect_identical(s1, s_old, info = info)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-solubility.R
|
# Load default settings for CHNOSZ
reset()
info <- "Species not contained by basis cause errors"
expect_error(species("H2O"), "basis species are not defined", info = info)
expect_error(CHNOSZ:::species.basis("H2O"), "basis species are not defined", info = info)
basis("CHNOS")
expect_error(CHNOSZ:::species.basis("U"), "element\\(s\\) not in the basis\\: U", info = info)
expect_error(species("fayalite"), "element\\(s\\) not in the basis\\: Fe Si", info = info)
info <- "For one or more species, species.basis() keeps track of zeroes and puts elements in order of thermo()$basis"
basis("CHNOS")
test0 <- count.elements("OHN0")
test1 <- count.elements("HN0O")
expect_equal(CHNOSZ:::species.basis(test0), CHNOSZ:::species.basis(test1), info = info)
# We can send multiple species to species.basis() but the argument has to be constructed correctly
expect_equal(unique(as.numeric(CHNOSZ:::species.basis(makeup(c("C", "CCN"))))), 0, info = info)
expect_equal(CHNOSZ:::species.basis(makeup(c("C", "CCN"), count.zero = TRUE))[2, , drop = FALSE], CHNOSZ:::species.basis(makeup("CCN")), info = info)
info <- "Deleting nonexistent species causes error or warning"
expect_error(species("CO2", delete = TRUE), "nonexistent species definition", info = info)
species("H2O")
expect_warning(species("CO2", delete = TRUE), "not present, so can not be deleted", info = info)
expect_null(species("water", delete = TRUE), info = info)
# We should also get NULL if *all* species are deleted
species("H2O")
expect_null(species(delete = TRUE), info = info)
info <- "Non-available species cause error, and species can be added or modified"
basis("CHNOS")
expect_error(species("wate"), "species not available", info = info)
# Add CO2, aq
sdef <- species("CO2")
# We can't add the same species twice
expect_equal(nrow(species("CO2")), 1, info = info)
# Change it to gas
expect_equal(species(1, "gas")$state, "gas", info = info)
# Change its log fugacity to -5
expect_equal(species(1, -5)$logact, -5, info = info)
# Add CO2, aq
expect_equal(nrow(species("CO2", add = TRUE)), 2, info = info)
# Add alanine by index in thermo()$OBIGT
expect_equal(nrow(species(info("alanine"), add = TRUE)), 3, info = info)
# If we just use an index, get only that species
expect_equal(species(3)$name, "alanine", info = info)
# We can add a species with the same name but different state
expect_equal(nrow(species("alanine", "cr", add = TRUE)), 4, info = info)
# We can modify the logact of a named species (only first match)
expect_equal(species("alanine", -7)$logact[3], -7, info = info)
info <- "index_return provides indices for touched species"
basis("CHNOS")
expect_equal(species("CO2", index.return = TRUE), 1, info = info)
# Here it's "touched" (but not added or modified)
expect_equal(species("CO2", index.return = TRUE), 1, info = info)
expect_equal(species(c("H2O", "NH3"), index.return = TRUE, add = TRUE), c(2, 3), info = info)
expect_equal(species(1, "gas", index.return = TRUE), 1, info = info)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-species.R
|
# Load default settings for CHNOSZ
reset()
# The maximum absolute pairwise difference between x and y
maxdiff <- function(x, y) max(abs(y - x))
info <- "Unbalanced reactions give a warning or are balanced given sufficient basis species"
expect_warning(subcrt(c("glucose", "ethanol"), c(-1, 3)), "reaction among glucose,ethanol was unbalanced, missing H-6O3", info = info)
basis("CHNOS")
s <- subcrt(c("malic acid", "citric acid"), c(-1, 1))
expect_equal(s$reaction$coeff, c(-1, 1, -2, -1, 1.5), info = info)
expect_equal(s$reaction$name, c("malic acid", "citric acid", "CO2", "water", "oxygen"), info = info)
info <- "Standard Gibbs energies (kJ/mol) of reactions involving aqueous species are consistent with the literature"
# From Amend and Shock, 2001 [AS01] Table 3
T <- c(2, 18, 25, 37, 45, 55, 70, 85, 100, 115, 150, 200)
# H2O(l) = H+ + OH-
AS01.H2O <- c(78.25, 79.34, 79.89, 80.90, 81.63, 82.59, 84.13, 85.78, 87.55, 89.42, 94.22, 102.21)
sout.H2O <- subcrt(c("H2O", "H+", "OH-"), c(-1, 1, 1), T = T)$out
# Tolerances set to lowest order of magnitute to pass
expect_true(maxdiff(sout.H2O$G/1000, AS01.H2O) < 0.01, info = info)
# AS01 Table 4.3 Reaction A1: H2(aq) + 0.5O2(aq) = H2O(l)
AS01.A1 <- c(-263.94, -263.45, -263.17, -262.62, -262.20, -261.63, -260.67, -259.60, -258.44, -257.18, -253.90, -248.44)
sout.A1 <- subcrt(c("H2", "O2", "H2O"), "aq", c(-1, -0.5, 1), T = T)$out
expect_true(maxdiff(sout.A1$G/1000, AS01.A1) < 0.01, info = info)
# AS01 Table 6.3 Reaction C7: 5S2O3-2 + H2O(l) + 4O2(aq) = 6SO4-2 + 2H+ + 4S(s)
AS01.C7 <- c(-1695.30, -1686.90, -1682.80, -1675.30, -1670.00, -1663.10, -1652.00, -1640.30, -1628.00, -1615.20, -1583.50, -1533.00)
s.C7 <- subcrt(c("S2O3-2", "H2O", "O2", "SO4-2", "H+", "S"), c("aq", "liq", "aq", "aq", "aq", "cr"), c(-5, -1, -4, 6, 2, 4), T = T)
sout.C7 <- s.C7$out
expect_true(maxdiff(sout.C7$G/1000, AS01.C7) < 0.06, info = info)
# We can also check that sulfur has expected polymorphic transitions
expect_equal(s.C7$polymorphs$sulfur, c(1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 3, 3), info = info)
info <- "Calculations using IAPWS-95 are possible"
oldwat <- water("IAPWS95")
# The tests pass if we get numeric values and no error
expect_silent(sb <- subcrt(c("H2O", "Na+"), T = c(-30, -20, 0, 10), P = 1)$out)
expect_true(all(sb$`Na+`$G < sb$water$G), info = info)
# Clean up
water(oldwat)
info <- "Phase stability limits give expected results"
expect_message(subcrt("gold", T = c(1300, 1350), P = 1, convert = FALSE), "subcrt: G is set to NA for gold\\(cr\\)", info = info)
# The reaction coefficients in the output should be unchanged 20171214
expect_equal(subcrt(c("bunsenite", "nickel", "oxygen"), c(-1, 1, 0.5))$reaction$coeff, c(-1, 1, 0.5), info = info)
# Properties are NA only above (not at) the temperature limit for phase stability 20191111
sout <- subcrt("covellite", T = seq(780, 781, 0.5), P = 1, convert = FALSE)$out[[1]]
expect_equal(is.na(sout$G), c(FALSE, FALSE, TRUE), info = info)
# Use calories for comparisons with SUPCRT92
E.units("cal")
info <- "Calculations for K-feldspar are consistent with SUPCRT92"
# Use the superseded Helgeson et al., 1978 data
add.OBIGT("SUPCRT92", "K-feldspar")
T <- c(100, 100, 1000, 1000)
P <- c(5000, 50000, 5000, 50000)
SUPCRT_G <- c(-886628, -769531, -988590, -871493)
SUPCRT_H <- c(-932344, -815247, -865868, -748771)
SUPCRT_S <- c(62.6, 62.6, 150.6, 150.6)
SUPCRT_V <- c(108.9, 108.9, 108.9, 108.9)
SUPCRT_Cp <- c(56.7, 56.7, 80.3, 80.3)
CHNOSZ <- subcrt("K-feldspar", T = T, P = P)$out[[1]]
expect_equal(round(CHNOSZ$G), SUPCRT_G, info = info)
expect_equal(round(CHNOSZ$H), SUPCRT_H, info = info)
expect_equal(round(CHNOSZ$S, 1), SUPCRT_S, info = info)
expect_equal(round(CHNOSZ$V, 1), SUPCRT_V, info = info)
expect_equal(round(CHNOSZ$Cp, 1), SUPCRT_Cp, info = info)
OBIGT()
# Quartz tests re-activated after fixing dPdTtr to use parameters converted to Joules 20240211
info <- "Calculations for quartz are nearly consistent with SUPCRT92"
add.OBIGT("SUPCRT92")
# Using SUPCRT's equations, the alpha-beta transition occurs at
# 705 degC at 5000 bar and 1874 degC at 50000 bar,
# so here beta-quartz is stable only at T = 1000, P = 5000
T <- c(100, 100, 1000, 1000)
P <- c(5000, 50000, 5000, 50000)
SUPCRT_G <- c(-202778, -179719, -223906, -199129)
SUPCRT_H <- c(-214133, -191708, -199359, -177118)
SUPCRT_S <- c(12.3, 10.6, 31.8, 29.8)
SUPCRT_V <- c(22.5, 20.3, 23.7, 21.9)
SUPCRT_Cp <- c(12.3, 12.3, 16.9, 16.9)
CHNOSZ <- subcrt("quartz", T = T, P = P)$out[[1]]
# NOTE: It appears that, where alpha-quartz is stable above Ttr(Pr) but below Ttr(P),
# SUPCRT92 computes the heat capacity and its integrals using parameters of beta-quartz.
# (see e.g. the equation for CprdT under the (Cpreg .EQ. 2) case in the Cptrms subroutine of SUPCRT).
# ... is that incorrect?
# CHNOSZ's behavior is different - it only uses the lower-T polymorph below Ttr(P);
# so we get different values from SUPCRT at T = 1000, P = 50000 (4th condition) where alpha-quartz is stable
# (above Ttr@1 bar (575 degC), but below Ttr@50000 bar)
expect_equal(round(CHNOSZ$G)[-4], SUPCRT_G[-4], info = info)
expect_equal(round(CHNOSZ$H)[-4], SUPCRT_H[-4], info = info)
expect_equal(round(CHNOSZ$S, 1)[-4], SUPCRT_S[-4], info = info)
expect_equal(round(CHNOSZ$Cp, 1)[-4], SUPCRT_Cp[-4], info = info)
expect_equal(round(CHNOSZ$V, 1), SUPCRT_V, info = info)
OBIGT()
info <- "More calculations for quartz are nearly consistent with SUPCRT92"
add.OBIGT("SUPCRT92")
# Output from SUPCRT92 for reaction specified as "1 QUARTZ" run at 1 bar
# (SUPCRT shows polymorphic transition at 574.850 deg C, and does not give Cp values around the transition)
S92_1bar <- read.table(header = TRUE, text = "
T G H S V
573 -214507 -209517 24.7 23.3
574 -214532 -209499 24.8 23.3
575 -214557 -209192 25.1 23.7
576 -214582 -209176 25.1 23.7
")
CHNOSZ_1bar <- subcrt("quartz", T = seq(573, 576), P = 1)$out[[1]]
expect_equal(round(CHNOSZ_1bar$G), S92_1bar$G, info = info)
expect_equal(round(CHNOSZ_1bar$H), S92_1bar$H, info = info)
expect_equal(round(CHNOSZ_1bar$S, 1), S92_1bar$S, info = info)
expect_equal(round(CHNOSZ_1bar$V, 1), S92_1bar$V, info = info)
# 5000 bar: SUPCRT shows polymorphic transition at 704.694 deg C
S92_5000bar <- read.table(header = TRUE, text = "
T G H S V
703 -215044 -204913 26.7 23.3
704 -215071 -204895 26.7 23.3
705 -215142 -204254 27.4 23.7
706 -215170 -204238 27.5 23.7
")
CHNOSZ_5000bar <- subcrt("quartz", T = seq(703, 706), P = 5000)$out[[1]]
# NOTE: calculated values *below* the transition are different
expect_equal(CHNOSZ_5000bar$G, S92_5000bar$G, tolerance = 20, scale = 1, info = info)
expect_equal(CHNOSZ_5000bar$H, S92_5000bar$H, tolerance = 300, scale = 1, info = info)
expect_equal(CHNOSZ_5000bar$S, S92_5000bar$S, tolerance = 0.5, scale = 1, info = info)
expect_equal(CHNOSZ_5000bar$V, S92_5000bar$V, tolerance = 0.05, scale = 1, info = info)
OBIGT()
info <- "Duplicated species yield correct polymorphic transitions"
# If a mineral with polymorphic transitions is in both the basis and species lists,
# energy()'s call to subcrt() will have duplicated species.
# This wasn't working (produced NAs at low T) for a long time prior to 20171003.
s1 <- subcrt("chalcocite", T = c(100, 1000), P = 1000)
s2 <- subcrt(rep("chalcocite", 2), T = c(100, 1000), P = 1000)
expect_equal(s1$out[[1]]$logK, s2$out[[1]]$logK, info = info)
expect_equal(s1$out[[1]]$logK, s2$out[[2]]$logK, info = info)
## Another way to test it ...
basis(c("copper", "chalcocite"))
species("chalcocite")
a <- affinity(T = c(0, 1000, 2), P = 1)
expect_equal(as.numeric(a$values[[1]]), c(0, 0), info = info)
info <- "Reaction coefficients for repeated species are handled correctly"
# These were failing in version 1.1.3
s1 <- subcrt(c("quartz", "SiO2"), c(-1, 1))
expect_equal(s1$reaction$coeff, c(-1, 1), info = info)
s2 <- subcrt(c("pyrrhotite", "pyrrhotite"), c(-1, 1))
expect_equal(s2$reaction$coeff, c(-1, 1), info = info)
# These were failing in version 1.1.3-28
s3 <- subcrt(c("SiO2", "SiO2"), c(-1, 1))
expect_equal(s3$reaction$coeff, c(-1, 1), info = info)
s4 <- subcrt(c("H2O", "H2O", "H2O", "H2O", "H2O"), c(-2, 1, -3, 1, 3))
expect_equal(s4$reaction$coeff, c(-2, 1, -3, 1, 3), info = info)
# The reaction properties here should add up to zero
expect_equal(unique(s4$out$logK), 0, info = info)
info <- "Properties of HKF species below 0.35 g/cm3 are NA and give a warning"
wtext <- "below minimum density for applicability of revised HKF equations \\(2 T,P pairs\\)"
expect_warning(s1 <- subcrt(c("Na+", "quartz"), T = 450, P = c(400, 450, 500)), wtext, info = info)
expect_equal(sum(is.na(s1$out$`Na+`$logK)), 2, info = info)
expect_equal(sum(is.na(s1$out$quartz$logK)), 0, info = info)
# Use exceed.rhomin to go below the minimum density
s2 <- subcrt(c("Na+", "quartz"), T = 450, P = c(400, 450, 500), exceed.rhomin = TRUE)
expect_equal(sum(is.na(s2$out$`Na+`$logK)), 0, info = info)
info <- "Combining minerals with polymorphic transitions and aqueous species with IS > 0 does not mangle output"
# s2 was giving quartz an extraneous loggam column and incorrect G and logK 20181107
add.OBIGT("SUPCRT92")
s1 <- subcrt(c("quartz", "K+"), T = 25, IS = 1)
s2 <- subcrt(c("K+", "quartz"), T = 25, IS = 1)
expect_true(identical(colnames(s1$out[[1]]), c("T", "P", "rho", "logK", "G", "H", "S", "V", "Cp", "polymorph")), info = info)
expect_true(identical(colnames(s2$out[[2]]), c("T", "P", "rho", "logK", "G", "H", "S", "V", "Cp", "polymorph")), info = info)
expect_true(identical(colnames(s1$out[[2]]), c("T", "P", "rho", "logK", "G", "H", "S", "V", "Cp", "loggam", "IS")), info = info)
expect_true(identical(colnames(s2$out[[1]]), c("T", "P", "rho", "logK", "G", "H", "S", "V", "Cp", "loggam", "IS")), info = info)
# Another one ... pyrrhotite was getting a loggam
expect_true(identical(colnames(subcrt(c("iron", "Na+", "Cl-", "OH-", "pyrrhotite"), T = 25, IS = 1)$out$pyrrhotite),
c("T", "P", "rho", "logK", "G", "H", "S", "V", "Cp", "polymorph")), info = info)
info <- "Argument checking handles some types of invalid input"
expect_error(subcrt("H2O", -1, "liq", "xxx"), "invalid property name: xxx", info = info)
# Before version 1.1.3-63, having more than one invalid property gave a mangled error message
expect_error(subcrt("H2O", -1, "liq", c(1, 2)), "invalid property names: 1 2", info = info)
# Added on 20230620
info <- "Polymorphs are used by default"
sres_poly <- subcrt("pyrrhotite")
expect_equal(unique(sres_poly$out[[1]]$polymorph), c(1, 2, 3), info = info)
info <- "Polymorphs work for named species or numeric indices"
iPo <- info("pyrrhotite")
sres_poly1 <- subcrt(iPo)
expect_identical(sres_poly, sres_poly1, info = info)
info <- "Automatic identificatio of polymorphs can be turned off"
sres_nopoly <- subcrt("pyrrhotite", use.polymorphs = FALSE)
expect_null(sres_nopoly$out[[1]]$polymorph, info = info)
info <- "Gibbs energy is NA beyond the transition temperature"
expect_true(anyNA(sres_nopoly$out[[1]]$G))
info <- "Gibbs energy can be extrapolated beyond the transition temperature"
sres_nopoly_extrap <- subcrt("pyrrhotite", use.polymorphs = FALSE, exceed.Ttr = TRUE)
expect_false(anyNA(sres_nopoly_extrap$out[[1]]$G))
# Added on 20230621
info <- "Arguments 2 and 3 can't both be character"
expect_error(subcrt(c("hydrogen", "H2"), c("gas", "aq"), "G"), info = info)
# Added on 20230818
info <- "exceed.Ttr works for basis species in automatically balanced reactions"
basis(c("gypsum", "SO4-2", "H2O", "H+", "O2"))
# Defaults for subcrt() go above the temperature limit for gypsum, so use exceed.Ttr to calculate logK
automatic_reaction <- subcrt("Ca+2", 1, exceed.Ttr = TRUE)$out
expect_false(any(is.na(automatic_reaction$logK)), info = info)
# Check that logK is identical for the reaction entered manually
manual_reaction <- subcrt(c("gypsum", "Ca+2", "SO4-2", "H2O"), c(-1, 1, 1, 2), exceed.Ttr = TRUE)$out
expect_equal(automatic_reaction$logK, manual_reaction$logK, info = info)
# Added on 20231115
info <- "Cp equation limits give expected results"
expect_warning(sout <- subcrt("acanthite", T = 1000:1001, P = 1, convert = FALSE)$out[[1]], "above T limit of 1000 K", info = info)
expect_false(any(is.na(sout$G)))
info <- "exceed.Ttr doesn't interfere with polymorphic transitions"
# Stable polymorphs of pyrrhotite at default T,P conditions of subcrt()
polymorph <- c(1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 2, 2, 2, 3, 3)
s1 <- subcrt("pyrrhotite")$out[[1]]
expect_equal(s1$polymorph, polymorph, info = info)
s2 <- subcrt("pyrrhotite", exceed.Ttr = TRUE)$out[[1]]
expect_equal(s2$polymorph, polymorph, info = info)
# Added on 20231204
info <- "Auto-balanced reactions apply ionic strength correction"
basis("CHNOS+")
sres <- subcrt("acetate", 1, IS = 1)
expect_length(sres$out$loggam, 15)
# Added on 20240206
info <- "High-temperature polymorph is not shown as stable below the transition temperature"
# This checks that the below-transition temperature code in subcrt() is working.
# If not, then cr2 is incorrectly identified as stable at 25 and 103 °C
# (that is, cr2 has a lower ΔG° than cr at those temperatures,
# but should only be shown as stable above the transition temperature of 377 K)
T <- c(25, 50, 103, 104)
sout <- subcrt("carrollite", T = T, P = 1)$out[[1]]
expect_equal(sout$polymorph, c(1, 1, 1, 2), info = info)
info <- "Subzero degree C calculations are possible"
# Set default units
E.units("J")
# Start with H2O
s.H2O <- subcrt("H2O", T = c(-20.1, seq(-20, 0)), P = 1)$out$water
# We should get something at -20 deg C
expect_equal(s.H2O$G[2], convert(-56001, "J"), tolerance = 1, scale = 1, info = info)
# Following SUPCRT92, an input temperature of 0 is converted to 0.01
expect_equal(s.H2O$T[22], 0.01, info = info)
# The following test fails CRAN checks with Intel oneAPI 2023.x compilers
# (Expected TRUE, got FALSE) 20240211
if(!at_home()) exit_file("Skipping tests on CRAN")
# We shouldn't get anything at -20.1 deg C
expect_true(is.na(s.H2O$G[1]), info = info)
# References
# Amend, J. P. and Shock, E. L. (2001)
# Energetics of overall metabolic reactions of thermophilic and hyperthermophilic Archaea and Bacteria.
# FEMS Microbiol. Rev. 25, 175--243. https://doi.org/10.1016/S0168-6445(00)00062-0
# Helgeson, H. C., Delany, J. M., Nesbitt, H. W. and Bird, D. K. (1978)
# Summary and critique of the thermodynamic properties of rock-forming minerals.
# Am. J. Sci. 278-A, 1--229. http://www.worldcat.org/oclc/13594862
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-subcrt.R
|
# Load default settings for CHNOSZ
reset()
info <- "swap.basis raises errors when needed"
expect_error(swap.basis(c("CO2", "H2O")), "requires an existing basis definition", info = info)
basis("CHNOS+")
expect_error(swap.basis(c("CO2", "H2O")), "two species must be identified", info = info)
expect_error(swap.basis(c("CO2", "H2O"), c("HCO3-", "H2O")), "can only swap one species for one species", info = info)
expect_error(swap.basis("CH4", "C2H5OH"), "basis species .* is not defined", info = info)
expect_error(swap.basis("CO2", "C60"), "is not available", info = info)
expect_error(swap.basis("CO2", "H2"), "the number of basis species is greater than the number of elements and charge", info = info)
info <- "basis.logact only accepts defined elements"
# Setup basis species with two elements: C and H
basis(c("graphite", "H2"), c("cr", "gas"))
# We can't get basis activities with one element
expect_error(basis.logact(c(C = 1)), "number of elements in 'emu' is less than those in basis", info = info)
# 20181111
info <- "Swapping works with a buffer (no recalculation of activities)"
basis("FeCHNOS+")
oldb <- basis("O2", "PPM")
# Before version 1.1.3-57, this gave Error in value * (-log(10) * R * T) : non-numeric argument to binary operator
newb <- swap.basis("O2", "hydrogen")
# NOTE: logact includes "PPM" for O2 (old) and H2 (new)
expect_identical(oldb$logact, newb$logact, info = info)
# 20200728 moved from swap-basis.Rd
info <- "Swapping doesn't affect affinities of formation reactions of species"
## Swapping basis species while species are defined
## and using numeric species indices
basis("MgCHNOPS+")
# Load some Mg-ATP species
species(c("MgATP-2", "MgHATP-", "MgH2ATP", "Mg2ATP"))
# Swap in CO2(g) for CO2(aq)
swap.basis("CO2", "carbon dioxide")
a1 <- affinity()
# Swap in CH4(g) for CO2(g)
swap.basis("carbon dioxide", "methane")
a2 <- affinity()
# The equilibrium fugacity of CH4 is *very* low
# Swap in CO2(aq) for CH4(g)
swap.basis("methane", "CO2")
a3 <- affinity()
# Swapping the basis species didn't affect the affinities
# of the formation reactions of the species, since
# the chemical potentials of the elements were unchanged
expect_equal(a1$values, a2$values, info = info)
expect_equal(a1$values, a3$values, info = info)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-swap.basis.R
|
# Load default settings for CHNOSZ
reset()
info <- "NAs in thermo()$OBIGT propagate to subcrt()"
# First of all, water is in thermo()$OBIGT but its properties
# are actually calculated using water() so it has NAs for some parameters
expect_equal(info(1)$a, as.numeric(NA), info = info)
# Get the existing value of c for [Ala](cr) (it's 0)
expect_equal(c.Ala <- info(info("[Ala]", "cr"))$c, 0, info = info)
# When we make a protein, its G depends on temperature
expect_true(all(diff(subcrt("LYSC_CHICK", "cr")$out[[1]]$G) < 0), info = info)
# Turn the values of G and S for [Ala](cr) into NA
mod.OBIGT(name = "[Ala]", state = "cr", G = NA, S = NA)
# Now when we make a protein(cr), its G is NA
expect_true(all(is.na(subcrt("RNAS1_BOVIN", "cr")$out[[1]]$G)), info = info)
# Also check propagation of NA for aqueous species
mod.OBIGT(name = "[Ala]", state = "aq", G = NA, S = NA)
expect_true(all(is.na(subcrt("[Ala]", "aq")$out[[1]]$G)), info = info)
### Tests added 20230310 for changes to thermo() argument handling more like par()
info <- "Alternative indexing styles give the same result"
E1 <- thermo()$opt$E.units # The "old" way
E2 <- thermo("opt$E.units") # The "new" way in CHNOSZ 2.0.0
expect_equal(E2, E1, info = info)
info <- "Value retrieved for opt$E.units is J"
expect_equal(E1, "J", info = info)
## Assign a strange value to opt$E.units
#oldthermo <- thermo("opt$E.units" = 1234)
#info <- "Restoring old parameter values is possible"
#expect_silent(E3 <- thermo(oldthermo), info = info)
#info <- "Old values are restored correctly"
#E4 <- thermo("opt$E.units")
#expect_equal(E4, E1, info = info)
info <- "Parameters can be selected using c() or argument list"
BS1 <- thermo("basis", "species")
BS2 <- thermo(c("basis", "species"))
expect_equal(BS1, BS2, info = info)
info <- "Single parameter gives atomic vector"
expect_null(names(E1), info = info)
info <- "Two more parameters give named list"
expect_equal(names(BS1), c("basis", "species"), info = info)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-thermo.R
|
# Load default settings for CHNOSZ
reset()
info <- "Unavailable elements cause errors in mass() and entropy()"
# The suppressWarnings here refer to the warnings generated by makeup() about the missing elements
expect_error(suppressWarnings(mass("Xxx")), "element\\(s\\) Xxx not available in thermo\\(\\)\\$element", info = info)
# 20130101: The error below was changed to a warning to restore functionality of check.OBIGT()
# (species in the database include those with Am Cm Np Pu, not listed in thermo()$element)
expect_warning(entropy("Xxx"), "element\\(s\\) Xxx not available in thermo\\(\\)\\$element", info = info)
info <- "GHS() and ZC() give warnings and errors in some situation"
expect_error(GHS(c("CO2","H2O"), G = 0, H = 0), "formula, G, H and S arguments are not same length", info = info)
expect_error(ZC("H2O"), "carbon not found in the stoichiometric matrix", info = info)
iATP <- info("ATP-4")
expect_warning(ZC(iATP), "element\\(s\\) P .* not included in this calculation", info = info)
info <- "GHS() and OBIGT2eos() produce expected values"
## A species with missing entropy value
ic <- info("cystine")
icdata <- info(ic)
GHS <- GHS(icdata$formula, G = icdata$G, H = icdata$H, S = icdata$S)
expect_equal(GHS[[3]], 61.8102928143, info = info)
# Done through OBIGT2eos
coe <- CHNOSZ:::OBIGT2eos(thermo()$OBIGT[ic,], "aq", fixGHS = TRUE)
expect_equal(coe$S, GHS[[3]], info = info)
## Mass and entropy of elements in chemical formulas
# The "-1" is a single negative charge, the electron
formula <- c("CH4", "H2O", "-1")
calcmass <- mass(formula)
calcS <- convert(entropy(formula), "cal")
expect_equal(calcmass, c(16.04276, 18.01528, 0), info = info)
expect_equal(calcS, c(63.83843212237, 55.74952198853, 15.61663479924), info = info)
# Another way to calculate the entropy of the elements in H2O
calcGHS <- GHS("H2O", G = 0, H = 0, E_units = "cal")
expect_equal(as.numeric(calcGHS[1, 3]), calcS[2], info = info)
info <- "[P|T|E].units() do not accept invalid units"
expect_error(P.units("X"), "units of pressure must be either bar or MPa", info = info)
expect_error(T.units("X"), "units of temperature must be either C or K", info = info)
expect_error(E.units("X"), "units of energy must be either cal or J", info = info)
info <- "describe.property() does not accept NULL values"
expect_error(describe.property(), "property or value is NULL", info = info)
# Test added on 20240211
# Incorrect result was causing quartz tests in test-subcrt.R to fail
info <- "dPdTtr gives expected result"
add.OBIGT("SUPCRT92")
dPdTtr.calc <- round(dPdTtr(info("quartz", "cr"), info("quartz", "cr2")), 5)
# The reference value was calculated with CHNOSZ_1.4.3
# (prior to bug in dPdTtr introduced by switch to Joules)
expect_equal(dPdTtr.calc, 38.45834, info = info)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-util.R
|
# Load default settings for CHNOSZ
reset()
info <- "A.ionization() builds arrays with correct dimensions"
iprotein <- pinfo(c("LYSC_CHICK", "RNAS1_BOVIN"))
vals <- list(T = convert(c(25, 50, 100), "K"), O2 = c(-80, -70), pH = c(5, 6, 7, 8))
vars <- names(vals)
A <- CHNOSZ:::A.ionization(iprotein, vars, vals)
# For two proteins, a list of length 2
expect_equal(length(A), 2, info = info)
# For 3 variables with the values given to energy.args()
expect_equal(dim(A[[1]]), c(3, 2, 4), check.names = FALSE, info = info)
info <- "A.ionization() handles arguments generated by energy.args()"
# Specifically, when the user asks for Eh, energy.args() produces
# values of pe that are specified in all dimensions
# (because the conversion from Eh is a function of temperature)
# Here, the original length of the Eh variable is 3, so that should be retained by A.ionization
# We need a basis() for the function to poke around in
basis("CHNOSe")
ea <- CHNOSZ:::energy.args(list(CO2 = c(-5, 0, 6), pH = c(0, 14, 2), Eh = c(-1, 0, 3), T = c(25, 28, 4)))
A <- CHNOSZ:::A.ionization(1, ea$vars, ea$vals)
expect_equal(dim(A[[1]]), c(6, 2, 3, 4), info = info)
# A simpler set of arguments, for testing dimensions with identical extents
# (the reason for the "for(dim in c(TPpHdim, otherdim))" in A.ionization())
ea <- CHNOSZ:::energy.args(list(pH = c(0, 14, 2), Eh = c(-1, 0, 2)))
A <- CHNOSZ:::A.ionization(1, ea$vars, ea$vals)
expect_equal(dim(A[[1]]), c(2, 2), info = info)
# An even simpler set of arguments: be able to handle a single point
A <- CHNOSZ:::A.ionization(1, vars = character(), vals = list())
expect_equal(dim(A[[1]]), 1, info = info)
info <- "energy() includes ionization affinities of proteins when needed"
# Get some results for a nonionized protein
basis("CHNOS")
species(c("alanine","LYSC_CHICK"))
# A 2x3 grid
ea <- CHNOSZ:::energy.args(list(T = c(25, 50, 2), O2 = c(-80, -60, 3)))
Anonion <- do.call(CHNOSZ:::energy, ea)
# Get some results for an ionized protein at pH 11
basis("CHNOS+")
basis("pH", 11)
species(c("alanine", "LYSC_CHICK"))
ea <- CHNOSZ:::energy.args(list(T = c(25, 50, 2), O2 = c(-80, -60, 3)))
Aion.pH11 <- do.call(CHNOSZ:::energy, ea)
# Alanine should not change
expect_equal(Anonion$a[[1]], Aion.pH11$a[[1]], info = info)
# What was the difference for LYSC_CHICK
A.ionization.LYSC_CHICK <- Aion.pH11$a[[2]] - Anonion$a[[2]]
# There should be 2 unique values (logfO2 doesn't matter)
# and they should be equal to the "manual" calculation using ionize.aa
A.ionization.2550 <- ionize.aa(pinfo(pinfo("LYSC_CHICK")), property = "A", T = c(25, 50), pH = 11)
expect_equal(A.ionization.LYSC_CHICK[, 1], A.ionization.2550[, 1], check.attributes = FALSE, info = info)
expect_equal(A.ionization.LYSC_CHICK[, 3], A.ionization.2550[, 1], check.attributes = FALSE, info = info)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-util.affinity.R
|
# Load default settings for CHNOSZ
reset()
info <- "reset() and OBIGT() produce the same database"
d1 <- thermo()$OBIGT
OBIGT()
d2 <- thermo()$OBIGT
expect_equal(d1, d2, info = info)
info <- "check.GHS() and check.EOS() (via info()) produce messages"
i1 <- info("S2O3-2")
expect_message(info(i1), "calculated ΔG°f of S2O3-2\\(aq\\) differs by 939 cal mol-1 from database value", info = info)
i2 <- info("Cu+2")
expect_message(info(i2), "calculated Cp° of Cu\\+2\\(aq\\) differs by 3.62 cal K-1 mol-1 from database value", info = info)
info <- "check.GHS() and check.EOS() respond to thermo()$opt$*.tol"
i1 <- info("SO4-2")
thermo("opt$Cp.tol" = 0.5)
expect_message(info(i1), "check.EOS", info = info)
i2 <- info("a,w-dicarboxytetracosane")
thermo("opt$G.tol" = 50)
expect_message(info(i2), "check.GHS", info = info)
info <- "RH2OBIGT() gives group additivity results consistent with database values (from Richard and Helgeson, 1998)"
file <- system.file("extdata/adds/RH98_Table15.csv", package = "CHNOSZ")
dat <- read.csv(file, stringsAsFactors = FALSE)
ispecies <- info(dat$compound, dat$state)
OBIGT.ref <- thermo()$OBIGT[ispecies, ]
OBIGT.calc <- RH2OBIGT(file = file)
# The maximum absolute pairwise difference between x and y
maxdiff <- function(x, y) max(abs(y - x))
# Calculated values of H are spot on; to pass tests, tolerance on
# G is set higher; is there an incorrect group value somewhere?
expect_true(maxdiff(OBIGT.calc$G, OBIGT.ref$G) < 31, info = info)
expect_true(maxdiff(OBIGT.calc$H, OBIGT.ref$H) == 0, info = info)
expect_true(maxdiff(OBIGT.calc$S, OBIGT.ref$S) < 0.02001, info = info)
expect_true(maxdiff(OBIGT.calc$Cp, OBIGT.ref$Cp) < 0.04001, info = info)
expect_true(maxdiff(OBIGT.calc$V, OBIGT.ref$V) < 0.1001, info = info)
expect_true(maxdiff(OBIGT.calc$a1.a, OBIGT.ref$a1.a) < 0.01001, info = info)
expect_true(maxdiff(OBIGT.calc$a2.b, OBIGT.ref$a2.b) < 1e-13, info = info)
expect_true(maxdiff(OBIGT.calc$a3.c, OBIGT.ref$a3.c) < 1e-14, info = info)
info <- "add.OBIGT() replaces existing entries without changing species index"
# Store the original species index of CdCl2
iCdCl2 <- info("CdCl2", "aq")
# Add supplemental database - includes CdCl2
file <- system.file("extdata/adds/BZA10.csv", package = "CHNOSZ")
isp <- add.OBIGT(file)
# Species index of CdCl2 should not have changed
expect_equal(info("CdCl2", "aq"), iCdCl2, info = info)
# Check that names of species modified are same as in file
newdat <- read.csv(file, stringsAsFactors = FALSE)
# The order isn't guaranteed ... just make sure they're all there
expect_true(all(newdat$name %in% thermo()$OBIGT$name[isp]), info = info)
info <- "add.OBIGT() gives an error for an incompatible file"
# Test added 20191210
file <- system.file("extdata/Berman/Ber88_1988.csv", package = "CHNOSZ")
expect_error(add.OBIGT(file), info = info)
info <- "info() gives consistent messages for cal and J"
# Test added 20190529
# Add data for dimethylamine and trimethylamine in different units (cal or J)
expect_message(add.OBIGT(system.file("extdata/adds/LA19_test.csv", package = "CHNOSZ")), "energy units: J and cal", info = info)
expect_message(info(info("DMA_cal")), "-1.92 cal", info = info)
expect_message(info(info("DMA_J")), "-8.02 J", info = info)
# For TMA, only a check.GHS message for the entry in J is produced,
# because it's above the threshold of 100 set in thermo()$opt$G.tol
expect_silent(info(info("TMA_cal")), info = info)
expect_message(info(info("TMA_J")), "-102 J", info = info)
info <- "Missing values for G, Cp, and V are correct in cal and J"
# Test added 20190530
# Add data for dimethylamine and trimethylamine in different units (cal or J)
add.OBIGT(system.file("extdata/adds/LA19_test.csv", package = "CHNOSZ"))
calccal <- info(info("DMA_cal_NA"))
expect_equal(round(calccal$G), 13934, info = info)
expect_equal(round(calccal$Cp, 1), 60.3, info = info)
expect_equal(round(calccal$V, 1), 58.2, info = info)
calcJ <- info(info("DMA_J_NA"))
expect_equal(round(calcJ$G), 58304, info = info)
expect_equal(round(calcJ$Cp, 1), 252.4, info = info)
expect_equal(round(calcJ$V, 1), 58.2, info = info)
info <- "subcrt() gives same results for data entered in cal and J"
# Test added 20190530
# Add data for dimethylamine and trimethylamine in different units (cal or J)
add.OBIGT(system.file("extdata/adds/LA19_test.csv", package = "CHNOSZ"))
E.units("cal")
scal <- subcrt("DMA_cal")
sJ <- subcrt("DMA_J")
expect_true(maxdiff(scal$out[[1]]$G, sJ$out[[1]]$G) < 2, info = info)
expect_true(maxdiff(scal$out[[1]]$H, sJ$out[[1]]$H) < 1, info = info)
expect_true(maxdiff(scal$out[[1]]$S, sJ$out[[1]]$S) < 0.006, info = info)
expect_true(maxdiff(scal$out[[1]]$V, sJ$out[[1]]$V) < 0.011, info = info)
expect_true(maxdiff(scal$out[[1]]$Cp, sJ$out[[1]]$Cp) < 0.16, info = info)
# Now switch output to J (default units)
E.units("J")
calcJ25 <- subcrt("DMA_J", T = 25)$out[[1]]
infoJ25 <- info(info("DMA_J"))
expect_equivalent(calcJ25[, c("G", "H", "S")], calcJ25[, c("G", "H", "S")], info = info)
# In the case of Cp and V, there are bigger difference because they are calculated from the HKF parameters
expect_true(maxdiff(calcJ25$Cp, infoJ25$Cp) < 8.1, info = info)
expect_true(maxdiff(calcJ25$V, infoJ25$V) < 0.55, info = info)
info <- "OBIGT2eos() doesn't convert lambda for cr species"
## Bug visible with change of ferberite data to J:
## lambda (exponent on heat capacity term)
## was incorrectly going through a units conversion 20190903
# This was working
mod.OBIGT("test_cal", formula = "C0", state = "cr", E_units = "cal", a = 10, b = 100, f = 1, lambda = 0)
mod.OBIGT("test_J", formula = "C0", state = "cr", E_units = "J", a = 41.84, b = 418.4, f = 4.184, lambda = 0)
expect_equal(subcrt("test_cal", T = 25)$out[[1]]$Cp, subcrt("test_J", T = 25)$out[[1]]$Cp, info = info)
# This wasn't working
mod.OBIGT("test_cal2", formula = "C0", state = "cr", E_units = "cal", a = 10, b = 100, f = 1, lambda = -1)
mod.OBIGT("test_J2", formula = "C0", state = "cr", E_units = "J", a = 41.84, b = 418.4, f = 4.184, lambda = -1)
expect_equal(subcrt("test_cal2", T = 25)$out[[1]]$Cp, subcrt("test_J2", T = 25)$out[[1]]$Cp, info = info)
info <- "We can define an aqueous species with CGL model"
# Test added 20230220
icr <- mod.OBIGT("fake_cr", formula = "Na2Cl2", state = "cr", model = "CGL", G = -1000, H = -1000, S = 10, Cp = 10, V = 10)
iaq <- mod.OBIGT("fake_aq", formula = "Na2Cl2", state = "aq", model = "CGL", G = -1000, H = -1000, S = 10, Cp = 10, V = 10)
# Make sure info() runs (message is from check.EOS())
expect_message(info(iaq), "differs", info = info)
expect_silent(info(iaq), info = info)
# Make sure subcrt() runs
expect_equal(subcrt(iaq)$G, subcrt(icr)$G, info = info)
# Reference
# Richard, L. and Helgeson, H. C. (1998) Calculation of the thermodynamic properties at elevated
# temperatures and pressures of saturated and aromatic high molecular weight solid and liquid
# hydrocarbons in kerogen, bitumen, petroleum, and other organic matter of biogeochemical interest.
# Geochim. Cosmochim. Acta 62, 3591--3636. https://doi.org/10.1016/S0016-7037(97)00345-1
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-util.data.R
|
# Load default settings for CHNOSZ
reset()
info <- "expr.species() produces expected errors"
expect_error(expr.species(c("H2O", "CO2")), "more than one species", info = info)
# 20220608
info <- "expr.species() handles non-integer coefficients"
es <- expr.species("FeS1.33")
expect_equal(es[[length(es)]], "1.33", info = info)
info <- "expr.species() handles non-integer charge"
es <- expr.species("FeS+1.33")
expect_equal(es[[length(es)]], "+1.33", info = info)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-util.expression.R
|
# Load default settings for CHNOSZ
reset()
info <- "which.pmax() properly applies attributes, and also works for lists of length 1"
x <- list(a = matrix(c(1, 2, 3, 4)), b = matrix(c(4, 3, 2, 1)))
xattr <- attributes(x[[1]])
expect_equal(attributes(which.pmax(x)), xattr, info = info)
expect_equal(as.numeric(which.pmax(x[1])), c(1, 1, 1, 1), info = info)
info <- "which.pmax() can handle NA values"
x <- list(a = matrix(c(1, 2, NA, 4)), b = matrix(c(4, 3, 2, 1)))
expect_equal(as.numeric(which.pmax(x)), c(2, 2, NA, 1), info = info)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-util.list.R
|
# This is a long test ... only run it "at home" 20220131
if(!at_home()) exit_file("Skipping long test")
# Load default settings for CHNOSZ
reset()
# These tests show inefficient uses of parallelization
# (overhead is greater than the savings from multiple cores).
# They are here just to test that the functions are working.
info <- "palply() launches calculations on multiple cores"
if(min(getOption("mc.cores"), 2) > 1 & parallel::detectCores() > 1) {
x <- 1:1001
# for this we don't have to export any variables so varlist == ""
expect_message(palply("", 1:length(x), function(i) i^2), "running 1001 calculations", info = info)
}
info <- "Other functions are calling palply() properly"
if(min(getOption("mc.cores"), 2) > 1 & parallel::detectCores() > 1) {
basis("CHNOS")
ip <- 1:nrow(thermo()$protein)
expect_message(a <- affinity(iprotein = rep(ip, 3)), "affinity running .* calculations", info = info)
expect_message(e <- equilibrate(a, normalize = TRUE), "equil.boltzmann running .* calculations", info = info)
# Test reaction method
species(c("CO2", "acetic acid"))
a <- affinity(O2 = c(-90, -60, 1000))
expect_message(e <- equilibrate(a), "equil.reaction running 1000 calculations", info = info)
}
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-util.program.R
|
# Load default settings for CHNOSZ
reset()
info <- "count.aa() warns about unrecognized amino acids and performs substring operations"
expect_message(count.aa("ABCDEFGHIJ"), "count.aa: unrecognized letter\\(s\\) in protein sequence: B J", info = info)
myseq <- "AAAAAGGGGG"
expect_equal(count.aa(myseq, stop = 5)[, "G"], 0, info = info)
expect_equal(count.aa(myseq, start = 6)[, "A"], 0, info = info)
expect_equal(count.aa(myseq, start = 5, stop = 6)[, c("A", "G")], c(1, 1), check.attributes = FALSE, info = info)
info <- "Nucleobase sequences can be processed with count.aa()"
expect_message(dna <- count.aa("ABCDEFGHIJ", type = "DNA"), "count.aa: unrecognized letter\\(s\\) in DNA sequence: B D E F H I J", info = info)
expect_equal(as.numeric(dna), c(1, 1, 1, 0), info = info)
info <- "count.aa() correctly processes a longer nucleobase sequence"
seq <- "ATGTCCCGTTTCTTAGTTGCATTGGTTGCCGCACTTTTAGGAGTTGCAATTGAGATGTCCCTTCTCGTTCGCGCTCAGGGGCAGCAAACCTTGCTTTTGGCTGAAGAAAGCAAGCATTTGTCGCAATTGCGTCAACTGACTTTTGAAGGCACCAATGCCGAAGCGTATTGGTCGCCTGACGGGAAATGGTTGGTCTTTCAATCCACACGCCCACCTTACAAGGCTGACCAAATCTTCATCATGAGAGCGGATGGCTCGGGAGTTCGTGTCGTCAGCACGGGCAAAGGTCGTTGCACTTGTGCCTATTTCACGCCAGATGGCAAAGGCGTTATCTTTGCTACGACCCACCTTGCTGGACCAGAACCGCCGCAAGTGCCCAAACTGGACATTCCACGCTATGTTTGGGGCGTGTTCCCAAGTTACGAACTTTACCTGCGGCGTTTGGACACGATGGAACTTATCCGCTTGACCGATAACGAAGGCTACGACGCTGAAGCGACCATTTGCTGGAAGACTGGGCGAATTGTCTTCACAAGTTACCGCAATGGCGACCTTGACCTTTACAGCATGAAATTAGACGGCAGCGATTTGAAGCGATTGACGAAAACCATCGGCTACGAGGGCGGAGCGTTCTACTCGCCCGACGGGAAGCGGATTGTCTTCCGAGCCTATTTGCCAAAGACGCCTGACGAAATTGACGAATACAAGCGGTTGCTCCAGTTAGGCGTCATAAGCCCACCAAAGATGGAGTGGGTCGTCATGGACGCCGACGGTCGCAACATGAAGCAAATC"
counts <- data.frame(A = 190, C = 203, G = 211, T = 188)
expect_equal(as.numeric(count.aa(seq, type = "DNA")), as.numeric(counts), info = info)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-util.seq.R
|
# Load default settings for CHNOSZ
reset()
info <- "water.SUPCRT92() gives expected erros and warnings"
expect_error(water.SUPCRT92("X"), "not available: X", info = info)
expect_error(water.SUPCRT92("Psat"), 'please set P = "Psat"', info = info)
info <- "water.SUPCRT92() gives expected values for E and kT"
# E = V * alpha, kT = V * beta
expect_equal(water.SUPCRT92("E"), water.SUPCRT92("V") * water.SUPCRT92("alpha"), check.attributes = FALSE, info = info)
expect_equal(water.SUPCRT92("kT"), water.SUPCRT92("V") * water.SUPCRT92("beta"), check.attributes = FALSE, info = info)
# Now compare with some real data from Tables V and VI of Fine and Millero, 1973
T <- convert(c(25, 100), "K")
P <- c(100, 1000)
expect_equal(water.SUPCRT92("beta", T, P)[, 1] * 1e6, c(44.100, 37.002), tolerance = 1e-2, info = info)
expect_equal(water.SUPCRT92("alpha", T, P)[, 1] * 1e6, c(268.06, 625.55), tolerance = 1e-2, info = info)
info <- "water.DEW() gives expected erros and messages"
expect_error(water.DEW("G", P = "Psat"), "Psat isn\'t supported", info = info)
expect_message(water.DEW("G", T = c(298.15, 373.15), P = c(1, 1000)), "using SUPCRT calculations", info = info)
# Added 20220335
info <- "water.* functions return energies in correct units"
# This is in J / mol calculated with SUPCRT92
G.H.S.Cp_ref <- c(-237181.4, -285837.3, 69.9, 75.4)
expect_equal(round(as.numeric(water.SUPCRT92(c("G", "H", "S", "Cp"))), 1), G.H.S.Cp_ref, info = info)
# Cp from SUPCRT92 and IAPWS95 differ at the tenths place, so round to whole numbers
expect_equal(round(as.numeric(water.IAPWS95(c("G", "H", "S", "Cp")))), round(G.H.S.Cp_ref), info = info)
# We can't do it for DEW because it needs higher pressure
#expect_equal(round(as.numeric(water.DEW(c("G", "H", "S", "Cp")))), round(G.H.S.Cp_ref), info = info)
# Reference
# Fine, R. A. and Millero, F. J. (1973)
# Compressibility of water as a function of temperature and pressure
# J. Chem. Phys. 59, 5529--5536. https://doi.org/10.1063/1.1679903
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-water.R
|
# This is a long test ... only run it "at home" 20220131
if(!at_home()) exit_file("Skipping long test")
# Load default settings for CHNOSZ
reset()
# Testing revised water.lines 2017-06-04
# Change to TRUE to show plots (for additional testing)
plot.it <- FALSE
# Change to FALSE to make base plots (for additional testing)
limit.water <- TRUE
# Function to count the number of species on a diagram (not including NA fields)
nspecies <- function(a) length(na.omit(unique(as.numeric(diagram(a, limit.water = limit.water, plot.it = plot.it, balance = 1)$predominant))))
res <- 25
info <- "water.lines() masks H2 and O2 fields on diagrams with pH as x-axis"
if(plot.it) par(mfrow = c(3, 6))
Ts <- c(25, 100, 25)
logaH2O <- c(0, 0, -5)
for(i in 1:3) {
T <- Ts[i]
basis(c("H2O", "H+", "e-"), c(logaH2O[i], -7, -7))
species(c("H2O", "O2", "H2"), c("liq", "gas", "gas"))
# Eh-pH
n1 <- nspecies(affinity(pH = c(-2, 16, res), Eh = c(-1, 1.5, res), T = T))
# pe-pH
n2 <- nspecies(affinity(pH = c(-2, 16, res), pe = c(-20, 25, res), T = T))
# logfO2-pH
swap.basis("e-", "oxygen")
n3 <- nspecies(affinity(pH = c(-2, 16, res), O2 = c(-90, 10, res), T = T))
# logaO2-pH
swap.basis("oxygen", "O2")
n4 <- nspecies(affinity(pH = c(-2, 16, res), O2 = c(-90, 10, res), T = T))
# logfH2-pH
swap.basis("O2", "hydrogen")
n5 <- nspecies(affinity(pH = c(-2, 16, res), H2 = c(-50, 10, res), T = T))
# logaH2-pH
swap.basis("hydrogen", "H2")
n6 <- nspecies(affinity(pH = c(-2, 16, res), H2 = c(-50, 10, res), T = T))
expect_equal(c(n1, n2, n3, n4, n5, n6), c(1, 1, 1, 1, 1, 1), info = info)
}
if(plot.it) par(mfrow = c(3, 6))
basis(c("H2O", "H+", "e-"), c(0, -7, -7))
species(c("H2O", "O2", "H2"), c("liq", "gas", "gas"))
info <- "water.lines() masks H2 and O2 fields on diagrams with T as x-axis"
n1 <- nspecies(affinity(T = c(0, 200, res), Eh = c(-1, 1.5, res))) # Eh-T
n2 <- nspecies(affinity(T = c(0, 200, res), pe = c(-20, 25, res))) # pe-T
swap.basis("e-", "oxygen"); n3 <- nspecies(affinity(T = c(0, 200, res), O2 = c(-90, 10, res))) # logfO2-T
swap.basis("oxygen", "O2"); n4 <- nspecies(affinity(T = c(0, 200, res), O2 = c(-90, 10, res))) # logaO2-T
swap.basis("O2", "hydrogen"); n5 <- nspecies(affinity(T = c(0, 200, res), H2 = c(-50, 10, res))) # logfH2-T
swap.basis("hydrogen", "H2"); n6 <- nspecies(affinity(T = c(0, 200, res), H2 = c(-50, 10, res))) # logaH2-T
expect_equal(c(n1, n2, n3, n4, n5, n6), c(1, 1, 1, 1, 1, 1), info = info)
info <- "water.lines() masks H2 and O2 fields on diagrams with P as x-axis"
swap.basis("H2", "e-")
n1 <- nspecies(affinity(P = c(1, 5000, res), Eh = c(-1, 1.5, res))) # Eh-P
n2 <- nspecies(affinity(P = c(1, 5000, res), pe = c(-20, 25, res))) # pe-P
swap.basis("e-", "oxygen"); n3 <- nspecies(affinity(P = c(1, 5000, res), O2 = c(-90, 10, res))) # logfO2-P
swap.basis("oxygen", "O2"); n4 <- nspecies(affinity(P = c(1, 5000, res), O2 = c(-90, 10, res))) # logaO2-P
swap.basis("O2", "hydrogen"); n5 <- nspecies(affinity(P = c(1, 5000, res), H2 = c(-50, 10, res))) # logfH2-P
swap.basis("hydrogen", "H2"); n6 <- nspecies(affinity(P = c(1, 5000, res), H2 = c(-50, 10, res))) # logaH2-P
expect_equal(c(n1, n2, n3, n4, n5, n6), c(1, 1, 1, 1, 1, 1), info = info)
info <- "water.lines() masks H2 and O2 fields on diagrams with T as y-axis"
swap.basis("H2", "e-")
n1 <- nspecies(affinity(Eh = c(-1, 1.5, res), T = c(0, 200, res))) # T-Eh
n2 <- nspecies(affinity(pe = c(-20, 25, res), T = c(0, 200, res))) # T-pe
swap.basis("e-", "oxygen"); n3 <- nspecies(affinity(O2 = c(-90, 10, res), T = c(0, 200, res))) # T-logfO2
swap.basis("oxygen", "O2"); n4 <- nspecies(affinity(O2 = c(-90, 10, res), T = c(0, 200, res))) # T-logaO2
swap.basis("O2", "hydrogen"); n5 <- nspecies(affinity(H2 = c(-50, 10, res), T = c(0, 200, res))) # T-logfH2
swap.basis("hydrogen", "H2"); n6 <- nspecies(affinity(H2 = c(-50, 10, res), T = c(0, 200, res))) # T-logaH2
expect_equal(c(n1, n2, n3, n4, n5, n6), c(1, 1, 1, 1, 1, 1), info = info)
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/inst/tinytest/test-water.lines.R
|
---
title: "CHNOSZ FAQ"
author: "Jeffrey M. Dick"
output:
html_vignette:
mathjax: null
toc: true
vignette: >
%\VignetteIndexEntry{CHNOSZ FAQ}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
bibliography: vig.bib
csl: elementa.csl
link-citations: true
---
<style>
/* https://gomakethings.com/how-to-break-an-image-out-of-its-parent-container-with-css/ */
@media (min-width: 700px) {
.full-width {
left: 50%;
margin-left: -50vw;
margin-right: -50vw;
max-width: 100vw;
position: relative;
right: 50%;
width: 100vw;
}
}
@media (min-width: 1100px) {
.full-width {
left: 50vw; /* fallback if needed */
left: calc(50vw - 200px);
width: 1100px;
position: relative;
}
}
/* zero margin around pre blocks (looks more like R console output) */
pre {
margin-top: 0;
margin-bottom: 0;
}
/* CSS snippet from boostrap.css modified by Jeffrey Dick on 2023-11-14 */
/*!
* Bootstrap v5.3.2 (https://getbootstrap.com/)
* Copyright 2011-2023 The Bootstrap Authors
* Licensed under MIT (https://github.com/twbs/bootstrap/blob/main/LICENSE)
*/
:root,
[data-bs-theme=light] {
--bs-info-text-emphasis: #055160;
--bs-warning-text-emphasis: #664d03;
--bs-info-bg-subtle: #cff4fc;
--bs-warning-bg-subtle: #fff3cd;
--bs-info-border-subtle: #9eeaf9;
--bs-warning-border-subtle: #ffe69c;
--bs-border-width: 1px;
--bs-border-radius: 0.375rem;
}
.alert {
--bs-alert-bg: transparent;
--bs-alert-padding-x: 0.5rem;
--bs-alert-padding-y: 0.5rem;
--bs-alert-margin-bottom: 1rem;
--bs-alert-color: inherit;
--bs-alert-border-color: transparent;
--bs-alert-border: var(--bs-border-width) solid var(--bs-alert-border-color);
--bs-alert-border-radius: var(--bs-border-radius);
--bs-alert-link-color: inherit;
position: relative;
padding: var(--bs-alert-padding-y) var(--bs-alert-padding-x);
margin-bottom: var(--bs-alert-margin-bottom);
color: var(--bs-alert-color);
background-color: var(--bs-alert-bg);
border: var(--bs-alert-border);
border-radius: var(--bs-alert-border-radius);
}
.alert-info {
--bs-alert-color: var(--bs-info-text-emphasis);
--bs-alert-bg: var(--bs-info-bg-subtle);
--bs-alert-border-color: var(--bs-info-border-subtle);
--bs-alert-link-color: var(--bs-info-text-emphasis);
}
.alert-warning {
--bs-alert-color: var(--bs-warning-text-emphasis);
--bs-alert-bg: var(--bs-warning-bg-subtle);
--bs-alert-border-color: var(--bs-warning-border-subtle);
--bs-alert-link-color: var(--bs-warning-text-emphasis);
}
</style>
<script>
function ToggleDiv(ID) {
var D = document.getElementById("D-" + ID);
var B = document.getElementById("B-" + ID);
if (D.style.display === "none") {
// open the div and change button text
D.style.display = "block";
B.innerText = "Hide code";
} else {
// close the div and change button text
D.style.display = "none";
B.innerText = "Show code";
}
}
</script>
```{r setup, include = FALSE}
library(CHNOSZ)
options(width = 80)
# Use pngquant to optimize PNG images
library(knitr)
knit_hooks$set(pngquant = hook_pngquant)
pngquant <- "--speed=1 --quality=0-25"
if (!nzchar(Sys.which("pngquant"))) pngquant <- NULL
# To make warnings appear in text box 20230619
# https://selbydavid.com/2017/06/18/rmarkdown-alerts/
knitr::knit_hooks$set(
error = function(x, options) {
paste('\n\n<div class="alert alert-danger">',
gsub('##', '\n', gsub('^##\ Error', '**Error:**', x)),
'</div>', sep = '\n')
},
warning = function(x, options) {
paste('\n\n<div class="alert alert-warning">',
gsub('##', '\n', gsub('^##\ Warning:', '**Warning:**', x)),
'</div>', sep = '\n')
},
message = function(x, options) {
paste('\n\n<div class="alert alert-info">',
gsub('##', '\n', x),
'</div>', sep = '\n')
}
)
# Set dpi 20231129
knitr::opts_chunk$set(
dpi = if(nzchar(Sys.getenv("CHNOSZ_BUILD_LARGE_VIGNETTES"))) 100 else 72
)
```
```{r echo = F, cache = F}
# Merge consecutive messages into a single div 20231114
knitr::knit_hooks$set(document = function(x){
# Not sure why this is needed, but simply computing on 'x' doesn't work
file <- tempfile()
writeLines(x, file)
x <- readLines(file)
# Line numbers of the document with </div>
enddiv <- which(x == "</div>")
# Line numbers with <div class="alert alert-info">
beginalert <- which(x == '<div class="alert alert-info">')
# Find </div> followed <div class="alert alert-info"> (skip empty lines)
removediv <- (enddiv + 2) %in% beginalert
if(any(removediv)) {
# Lines to remove
rmlines1 <- enddiv[removediv]
rmlines2 <- enddiv[removediv] + 1
rmlines3 <- enddiv[removediv] + 2
# Do the removing
x <- x[-c(rmlines1, rmlines2, rmlines3)]
}
x
})
```
```{r HTML, include = FALSE}
NOTE <- '<span style="background-color: yellow;">NOTE</span>'
# CHNOSZ functions
equilibrate_ <- '<code>equilibrate()</code>'
info_ <- '<code>info()</code>'
thermo.refs_ <- '<code>thermo.refs()</code>'
# Math stuff
logK <- "log <i>K</i>"
Hplus <- "H<sup>+</sup>"
HCO2_ <- "HCO<sub>2</sub><sup>−</sup>"
HCO3_ <- "HCO<sub>3</sub><sup>−</sup>"
O2 <- "O<sub>2</sub>"
S2 <- "S<sub>2</sub>"
log <- "log "
aHCO2_ <- "<i>a</i><sub>HCO<sub>2</sub><sup>−</sup></sub>"
aHCO3_ <- "<i>a</i><sub>HCO<sub>3</sub><sup>−</sup></sub>"
logfO2 <- "log <i>f</i><sub>O<sub>2</sub></sub>"
Ctot <- "C<sub>tot</sub>"
C3H5O2_ <- "C<sub>3</sub>H<sub>5</sub>O<sub>2</sub><sup>−</sup>"
a3HCO3_ <- "<i>a</i><sup>3</sup><sub>HCO<sub>3</sub><sup>−</sup></sub>"
aC3H5O2_ <- "<i>a</i><sub>C<sub>3</sub>H<sub>5</sub>O<sub>2</sub><sup>−</sup></sub>"
a2HCO3_ <- "<i>a</i><sup>2</sup><sub>HCO<sub>3</sub><sup>−</sup></sub>"
logCtot <- "log C<sub>tot</sub>"
CO2 <- "CO<sub>2</sub>"
H2O <- "H<sub>2</sub>O"
S3minus <- "S<sub>3</sub><sup>-</sup>"
H2S <- "H<sub>2</sub>S"
SO4__ <- "SO<sub>4</sub><sup>-2</sup>"
Kplus <- "K<sup>+</sup>"
Naplus <- "Na<sup>+</sup>"
Clminus <- "Cl<sup>-</sup>"
H2 <- "H<sub>2</sub>"
```
This vignette was compiled on `r Sys.Date()` with CHNOSZ version `r sessionInfo()$otherPkgs$CHNOSZ$Version`.
## How is 'CHNOSZ' pronounced?
As one syllable that starts with an *sh* sound and [rhymes with *Oz*](https://en.wiktionary.org/wiki/Rhymes:English/%C9%92z).
CHNOSZ and [schnoz](https://en.wiktionary.org/wiki/schnozz) are homophones.
*Added on 2023-05-22.*
## How should CHNOSZ be cited?
* This paper is the general reference for CHNOSZ: @Dic19.
* This paper describes diagrams with multiple metals: @Dic21b.
* This paper describes metastable equilibrium calculations for proteins: @Dic08.
* The [<span style="color:blue">*OBIGT thermodynamic database*</span>](OBIGT.html) represents the work of many researchers.
**If you publish results that depend on any of these data, please cite the primary sources.**
Use `r info_` to show the reference keys for particular species and `r thermo.refs_` to list the bibliographic details.
The following example shows the sources of data for aqueous alanine:
```{r alanine_refs, message = FALSE}
info(info("alanine"))[c("ref1", "ref2")]
thermo.refs(info("alanine"))
```
* Mineral data in OBIGT are based on @Ber88 together with sulfides and other non-conflicting minerals from @HDNB78. For a reaction such as the pyrite-pyrrhotite-magnetite (PPM) oxygen fugacity buffer, all the sources of data can be listed as follows:
```{r PPM_refs, message = FALSE}
basis(c("pyrite", "pyrrhotite", "oxygen"))
sres <- subcrt("magnetite", 1)
info(sres$reaction$ispecies)[, 1:6]
thermo.refs(sres)
reset()
```
* Additional minerals from @HDNB78, that were available in SUPCRT92 but may conflict with the @Ber88 compilation, can be loaded from an optional database with `add.OBIGT("SUPCRT92")`. When using these data, it is appropriate to cite @HDNB78 rather than SUPCRT92.
*Added on 2023-05-27; PPM example added on 2023-11-15.*
## What thermodynamic models are used in CHNOSZ?
* The thermodynamic properties of liquid water are calculated using Fortran code from SUPCRT92 [@JOH92] or optionally an implementation in R of the IAPWS-95 formulation [@WP02].
* Thermodynamic properties of other species are taken from a database for minerals and inorganic and organic aqueous species including biomolecules, or from amino acid group additivity for proteins [@DLH06].
* The corresponding high-temperature properties are calculated using the @BB85 equations for minerals and the revised [@TH88;@SH88] Helgeson-Kirkham-Flowers [@HKF81] equations for aqueous species.
* The revised HKF equations are augmented with the Deep Earth Water (DEW) model [@SHA14] and estimates of parameters in the extended Debye-Hückel equation [@MSS13] to calculate standard-state properties and activity coefficients for given ionic strength at high pressure (to 6 GPa).
* Activity coefficients are implemented via adjusted standard Gibbs energies at specified ionic strength [@Alb96], which converts all activity variables in the workflow to molalities.
* A related adjustment is available to convert standard Gibbs energies for gases from the 1 bar standard state used in SUPCRT92 to a variable-pressure standard state [@AC93,Ch.12].
*Added to <https://chnosz.net/> website on 2018-11-13; moved to FAQ on 2023-05-27; added references for **revised** HKF on 2023-11-17.*
## When and why do equal-activity boundaries depend on total activity?
Short answer: When the species have the same number of the conserved element (let's take C for example),
their activities are raised to the same exponent in reaction quotient, so the activity ratio in the law of mass action becomes unity.
But when the species have different numbers of the conserved element (for example, propanoate with 3 C and bicarbonate with 1 C),
their activities are raised to different exponents, and the activity ratio does not become unity even when the activities are equal
(except for the specific case where the activities themselves are equal to 1).
Therefore, in general, the condition of "equal activity" is not sufficient to define boundaries on a relative stability diagram;
instead, we need to say "activity of each species equal to *x*" or alternatively "total activity equal to *y*".
Long answer: First, consider a reaction between formate and bicarbonate: `r HCO2_` + 0.5 `r O2` $\rightleftharpoons$ `r HCO3_`.
The law of mass action (LMA) is <strong>`r logK` $=$ `r log`(`r aHCO3_` / `r aHCO2_`) $-$ 0.5 `r logfO2`</strong>.
The condition of equal activity is <font color="red">`r aHCO2_` $=$ `r aHCO3_`</font>.
Then, the LMA simplifies to <strong>`r logK` $=$ $-$ 0.5 `r logfO2`</strong>.
The total activity of C is given by <font color="blue">`r Ctot` $=$ `r aHCO2_` $+$ `r aHCO3_`</font>.
According to the LMA, `r logfO2` is a function only of `r logK`, so <font color="green">*d*`r logfO2`/*d*`r logCtot` $=$ 0</font>.
In other words, the position of the equal-activity boundary is independent of the value of `r Ctot`.
Next, consider a reaction between propanoate and bicarbonate: `r C3H5O2_` + <sup>7</sup>⁄<sub>2</sub> `r O2` $\rightleftharpoons$ 3 `r HCO3_` + 2 `r Hplus`.
The LMA is <strong>`r logK` $=$ `r log`(`r a3HCO3_` / `r aC3H5O2_`) $-$ pH $-$ <sup>7</sup>⁄<sub>2</sub> `r logfO2`</strong>.
The condition of equal activity is <font color="red">`r aC3H5O2_` $=$ `r aHCO3_`</font>.
Then, the LMA simplifies to <strong>`r logK` $=$ `r log``r a2HCO3_` $-$ pH $-$ <sup>7</sup>⁄<sub>2</sub> `r logfO2`</strong>.
The total activity of C is given by <font color="blue">`r Ctot` $=$ 3 `r aC3H5O2_` $+$ `r aHCO3_`</font>; combined with the condition of equal activity,
this gives <font color="blue">`r Ctot` $=$ 4 `r aHCO3_`</font>.
Substituting this into the LMA gives <strong>`r logK` $=$ `r log`(`r Ctot` / 4)<sup>2</sup> $-$ pH $-$ <sup>7</sup>⁄<sub>2</sub> `r logfO2`</strong>,
which can be rearranged to write `r logfO2` $=$ <sup>2</sup>⁄<sub>7</sub> (2 `r log``r Ctot` $-$ `r logK` $-$ `r log`16 $-$ pH).
It follows that <font color="green">*d*`r logfO2`/*d*`r logCtot` $=$ <sup>4</sup>⁄<sub>7</sub></font>,
and the position of the equal-activity boundary depends on `r Ctot`.
According to this analysis, increasing `r Ctot` from 0.03 to 3 molal (a 2 log-unit increase)
would have no effect on the location of the formate-bicarbonate equal-activity boundary,
but would raise the propanoate-bicarbonate equal-activity boundary by <sup>8</sup>⁄<sub>7</sub> units on the `r logfO2` scale.
Because the reaction between bicarbonate and `r CO2` does not involve `r O2` (but rather `r H2O` and `r Hplus`),
the same effect should occur on the propanoate-`r CO2` equal-activity boundary.
The plots below, which are made using `r equilibrate_` for species in the Deep Earth Water (DEW) model, illustrate this effect.
<button id="B-DEW_Ctot" onclick="ToggleDiv('DEW_Ctot')">Show code</button>
<div id="D-DEW_Ctot" style="display: none">
```{r DEW_Ctot, eval = FALSE}
### Based on demo/DEW.R in CHNOSZ
# Set up subplots
par(mfrow = c(1, 2), mar = c(3.0, 3.5, 2.5, 1.0), mgp = c(1.7, 0.3, 0), las = 1, tcl = 0.3, xaxs = "i", yaxs = "i")
# Activate DEW model
water("DEW")
###########
## logfO2-pH diagram for aqueous inorganic and organic carbon species at high pressure
## After Figure 1b of Sverjensky et al., 2014b [SSH14]
## (Nature Geoscience, https://doi.org/10.1038/NGEO2291)
###########
# Define system
basis("CHNOS+")
inorganic <- c("CO2", "HCO3-", "CO3-2", "CH4")
organic <- c("formic acid", "formate", "acetic acid", "acetate", "propanoic acid", "propanoate")
species(c(inorganic, organic), 0)
fill <- c(rep("aliceblue", length(inorganic)), rep("aquamarine", length(organic)))
# A function to make the diagrams
dfun <- function(T = 600, P = 50000, res = 200, Ctot = 0.03) {
a <- affinity(pH = c(0, 10, res), O2 = c(-24, -12, res), T = T, P = P)
# Set total C concentration to 0.03 molal
# (from EQ3NR model for eclogite [Supporting Information of SSH14])
e <- equilibrate(a, loga.balance = log10(Ctot))
diagram(e, fill = fill)
dp <- describe.property(c(" T", " P"), c(T, P), digits = 0)
legend("bottomleft", legend = dp, bty = "n")
}
water("DEW")
add.OBIGT("DEW")
dfun(Ctot = 0.03)
mtitle(c("Inorganic and organic species", "C[total] = 0.03 molal"))
dfun(Ctot = 3)
mtitle(c("Inorganic and organic species", "C[total] = 3 molal"))
# Restore default settings for the questions below
reset()
```
</div>
```{r DEW_Ctot, echo = FALSE, message = FALSE, results = "hide", fig.width = 8, fig.height = 4, out.width = "100%", fig.align = "center", pngquant = pngquant, cache = TRUE}
```
*Added on 2023-05-17.*
## How can minerals with polymorphic transitions be added to the database?
The different crystal forms of a mineral are called polymorphs.
Many minerals undergo polymorphic transitions upon heating.
Each polymorph for a given mineral should have its own entry in OBIGT, including values of the standard thermodynamic properties (Δ*G*°~*f*~, Δ*H*°~*f*~, and *S*°) at 25 °C.
The 25 °C (or 298.15 K) values for high-temperature polymorphs are often not listed in thermodynamic tables, but they can be calculated.
This thermodynamic cycle shows how: we calculate the changes of a thermodyamic property (pictured here as `DS1` and `DS2`) between 298.15 K and the transition temperature (`Ttr`) for two polymorphs, then combine those with the property of the polymorphic transition (`DStr`) to obtain the difference of the property between the polymorphs at 298.15 K (`DS298`).
```text
DStr DStr: entropy of transition between polymorphs 1 and 2
Ttr o---------->o Ttr: temperature of transition
^ |
| |
DS1 | | DS2 DS1: entropy change of polymorph 1 from 298.15 K to Ttr
| | DS2: entropy change of polymorph 2 from 298.15 K to Ttr
| v
298.15 K o==========>o DS298: entropy difference between polymorphs 1 and 2 at 298.15 K
DS298 DS298 = DS1 + DStr - DS2
Polymorph 1 2
```
As an example, let's add pyrrhotite (Fe0.877S) from @PMW87.
The formula and thermodynamic properties of this pyrrhotite differ from those of FeS from @HDNB78, which is already in OBIGT.
We begin by defining all the input values in the next code block.
In addition to `G`, `H`, `S`, and the heat capacity coefficients, non-NA values of volume (`V`) must be provided for the polymorph transitions to be calculated correctly by `subcrt()`.
```{r pyrrhotite_values, message = FALSE}
# The formula of the new mineral and literature reference
formula <- "Fe0.877S"
ref1 <- "PMW87"
# Because the properties from Pankratz et al. (1987) are listed in calories,
# we need to change the output of subcrt() to calories (the default is Joules)
E.units("cal")
# Use temperature in Kelvin for the calculations below
T.units("K")
# Thermodynamic properties of polymorph 1 at 25 °C (298.15 K)
G1 <- -25543
H1 <- -25200
S1 <- 14.531
Cp1 <- 11.922
# Heat capacity coefficients for polymorph 1
a1 <- 7.510
b1 <- 0.014798
# For volume, use the value from Helgeson et al. (1978)
V1 <- V2 <- 18.2
# Transition temperature
Ttr <- 598
# Transition enthalpy (cal/mol)
DHtr <- 95
# Heat capacity coefficients for polymorph 2
a2 <- -1.709
b2 <- 0.011746
c2 <- 3073400
# Maximum temperature of polymorph 2
T2 <- 1800
```
Use the temperature (`Ttr`) and enthalpy of transition (`DHtr`) to calculate the entropy of transition (`DStr`).
Note that the Gibbs energy of transition (`DGtr`) is zero at `Ttr`.
```{r pyrrhotite_Ttr, message = FALSE}
DGtr <- 0 # DON'T CHANGE THIS
TDStr <- DHtr - DGtr # TΔS° = ΔH° - ΔG°
DStr <- TDStr / Ttr
```
Start new database entries that include basic information, volume, and heat capacity coefficients for each polymorph.
@PMW87 don't list *C~p~*° of the high-temperature polymorph extrapolated to 298.15 K, so leave it out.
If the properties were in Joules, we would omit `E_units = "cal"` or change it to `E_units = "J"`.
```{r pyrrhotite_Cp, results = "hide", message = FALSE}
mod.OBIGT("pyrrhotite_new", formula = formula, state = "cr", ref1 = ref1,
E_units = "cal", G = 0, H = 0, S = 0, V = V1, Cp = Cp1,
a = a1, b = b1, c = 0, d = 0, e = 0, f = 0, lambda = 0, T = Ttr)
mod.OBIGT("pyrrhotite_new", formula = formula, state = "cr2", ref1 = ref1,
E_units = "cal", G = 0, H = 0, S = 0, V = V2,
a = a2, b = b2, c = c2, d = 0, e = 0, f = 0, lambda = 0, T = T2)
```
For the time being, we set `G`, `H`, and `S` (i.e., the properties at 25 °C) to zero in order to easily calculate the temperature integrals of the properties from 298.15 K to `Ttr`.
Values of zero are placeholders that don't satisfy Δ*G*°~*f*~ = Δ*H*°~*f*~ − *T*Δ*S*°~*f*~ for either polymorph (the subscript *f* represents formation from the elements), as indicated by the following messages.
We will check again for consistency of the thermodynamic parameters at the end of the example.
```{r pyrrhotite_info, results = "hide", collapse = TRUE}
info(info("pyrrhotite_new", "cr"))
info(info("pyrrhotite_new", "cr2"))
```
In order to calculate the temperature integral of Δ*G*°~*f*~, we need not only the heat capacity coefficients but also actual values of *S*°.
Therefore, we start by calculating the entropy changes of each polymorph from 298.15 to `r Ttr` K (`DS1` and `DS2`) and combining those with the entropy of transition to obtain the difference of entropy between the polymorphs at 298.15 K.
For polymorph 1 (with `state = "cr"`) it's advisable to include `use.polymorphs = FALSE` to prevent `subcrt()` from trying to identify the most stable polymorph at the indicated temperature.
```{r pyrrhotite_S, message = FALSE}
DS1 <- subcrt("pyrrhotite_new", "cr", P = 1, T = Ttr, use.polymorphs = FALSE)$out[[1]]$S
DS2 <- subcrt("pyrrhotite_new", "cr2", P = 1, T = Ttr)$out[[1]]$S
DS298 <- DS1 + DStr - DS2
```
Put the values of *S*° at 298.15 into OBIGT, then calculate the changes of all thermodynamic properties of each polymorph between 298.15 K and `Ttr`.
```{r pyrrhotite_D1_D2, message = FALSE, results = "hide"}
mod.OBIGT("pyrrhotite_new", state = "cr", S = S1)
mod.OBIGT("pyrrhotite_new", state = "cr2", S = S1 + DS298)
D1 <- subcrt("pyrrhotite_new", "cr", P = 1, T = Ttr, use.polymorphs = FALSE)$out[[1]]
D2 <- subcrt("pyrrhotite_new", "cr2", P = 1, T = Ttr)$out[[1]]
```
It's a good idea to check that the entropy of transition is calculated correctly.
```{r pyrrhotite_check_S, results = "hide"}
stopifnot(all.equal(D2$S - D1$S, DStr))
```
Now we're ready to add up the contributions to Δ*G*°~*f*~ and Δ*H*°~*f*~ from the left, top, and right sides of the cycle.
This gives us the differences between the polymorphs at 298.15 K, which we use to make the final changes to the database.
```{r pyrrhotite_DG298_DH298, results = "hide", message = FALSE}
DG298 <- D1$G + DGtr - D2$G
DH298 <- D1$H + DHtr - D2$H
mod.OBIGT("pyrrhotite_new", state = "cr", G = G1, H = H1)
mod.OBIGT("pyrrhotite_new", state = "cr2", G = G1 + DG298, H = H1 + DH298)
```
It's a good idea to check that the values of `G`, `H`, and `S` at 25 °C for a given polymorph are consistent with each other.
Here we use `check.GHS()` to calculate the difference between the value given for `G` and the value calculated from `H` and `S`.
The difference of less than 1 `r E.units()`/mol can probably be attributed to small differences in the entropies of the elements used by @PMW87 and in CHNOSZ.
We still get a message that the database value of *C~p~*° at 25 °C for the high-temperature polymorph is NA; this is OK because the (extrapolated) value can be calculated from the heat capacity coefficients.
```{r pyrrhotite_info2, collapse = TRUE}
cr_parameters <- info(info("pyrrhotite_new", "cr"))
stopifnot(abs(check.GHS(cr_parameters)) < 1)
cr2_parameters <- info(info("pyrrhotite_new", "cr2"))
stopifnot(abs(check.GHS(cr2_parameters)) < 1)
```
For the curious, here are the parameter values:
```{r pyrrhotite_parameters}
cr_parameters
cr2_parameters
```
Finally, let's look at the thermodynamic properties of the newly added pyrrhotite as a function of temperature around `Ttr`.
Here, we use the feature of `subcrt()` that identifies the stable polymorph at each temperature.
Note that Δ*G*°~*f*~ is a continuous function -- visual confirmation that the parameters yield zero for `DGtr` -- but Δ*H*°~*f*~, *S*°, and *C~p~*° are discontinuous at the transition temperature.
<button id="B-pyrrhotite_T" onclick="ToggleDiv('pyrrhotite_T')">Show code</button>
<div id="D-pyrrhotite_T" style="display: none">
```{r pyrrhotite_T, eval = FALSE}
T <- seq(550, 650, 1)
sout <- subcrt("pyrrhotite_new", T = T, P = 1)$out[[1]]
par(mfrow = c(1, 4), mar = c(4, 4.2, 1, 1))
labels <- c(G = "DG0f", H = "DH0f", S = "S0", Cp = "Cp0")
for(property in c("G", "H", "S", "Cp")) {
plot(sout$T, sout[, property], col = sout$polymorph,
xlab = axis.label("T"), ylab = axis.label(labels[property])
)
abline(v = Ttr, lty = 3, col = 8)
if(property == "G")
legend("bottomleft", c("1", "2"), pch = 1, col = c(1, 2), title = "Polymorph")
}
# Restore default settings for the questions below
reset()
```
</div>
```{r pyrrhotite_T, echo = FALSE, message = FALSE, results = "hide", fig.width = 8, fig.height = 2.5, out.width = "100%", fig.align = "center", pngquant = pngquant}
```
For additional polymorphs, we could repeat the above procedure using polymorph 2 as the starting point to calculate `G`, `H`, and `S` of polymorph 3, and so on.
*Added on 2023-06-23.*
## How can I make a diagram with the trisulfur radical ion (`r S3minus`)?
A `r logfO2`--pH plot for aqueous sulfur species including `r S3minus` was first presented by @PD11.
Later, @PD15 reported parameters in the revised HKF equations of state for `r S3minus`, which are available in OBIGT.
```{r trisulfur, eval = FALSE, echo = FALSE}
par(mfrow = c(1, 3))
## BLOCK 1
T <- 350
P <- 5000
res <- 200
## BLOCK 2
wt_percent_S <- 10
wt_permil_S <- wt_percent_S * 10
molar_mass_S <- mass("S") # 32.06
moles_S <- wt_permil_S / molar_mass_S
grams_H2O <- 1000 - wt_permil_S
molality_S <- 1000 * moles_S / grams_H2O
logm_S <- log10(molality_S)
## BLOCK 3
basis(c("Ni", "SiO2", "Fe2O3", "H2S", "H2O", "oxygen", "H+"))
species(c("H2S", "HS-", "SO2", "HSO4-", "SO4-2", "S3-"))
a <- affinity(pH = c(2, 10, res), O2 = c(-34, -22, res), T = T, P = P)
e <- equilibrate(a, loga.balance = logm_S)
diagram(e)
## BLOCK 4
mod.buffer("NNO", c("nickel", "bunsenite"), state = "cr", logact = 0)
for(buffer in c("HM", "QFM", "NNO")) {
basis("O2", buffer)
logfO2_ <- affinity(return.buffer = TRUE, T = T, P = P)$O2
abline(h = logfO2_, lty = 3, col = 2)
text(8.5, logfO2_, buffer, adj = c(0, 0), col = 2, cex = 0.9)
}
## BLOCK 5
pH <- subcrt(c("H2O", "H+", "OH-"), c(-1, 1, 1), T = T, P = P)$out$logK / -2
abline(v = pH, lty = 2, col = 4)
## BLOCK 6
lTP <- describe.property(c("T", "P"), c(T, P))
lS <- paste(wt_percent_S, "wt% S(aq)")
ltext <- c(lTP, lS)
legend("topright", ltext, bty = "n", bg = "transparent")
title(quote("Parameters for"~S[3]^"-"~"from Pokrovski and Dubessy (2015)"), xpd = NA)
######## Plot 2: Modify Gibbs energy
oldG <- info(info("S3-"))$G
newG <- oldG - 12548
mod.OBIGT("S3-", G = newG)
a <- affinity(pH = c(2, 10, res), O2 = c(-34, -22, res), T = T, P = P)
e <- equilibrate(a, loga.balance = logm_S)
diagram(e)
legend("topright", ltext, bty = "n", bg = "transparent")
title(quote("Modified"~log*italic(K)~"after Pokrovski and Dubrovinsky (2011)"), xpd = NA)
OBIGT()
######## Plot 3: Do it with DEW
T <- 700
P <- 10000 # 10000 bar = 1 GPa
oldwat <- water("DEW")
add.OBIGT("DEW")
info(species()$ispecies)
a <- affinity(pH = c(2, 10, res), O2 = c(-18, -10, res), T = T, P = P)
e <- equilibrate(a, loga.balance = logm_S)
diagram(e)
lTP <- describe.property(c("T", "P"), c(T, P))
ltext <- c(lTP, lS)
legend("topright", ltext, bty = "n", bg = "transparent")
title(quote("Deep Earth Water (DEW)"~"model"))
water(oldwat)
OBIGT()
```
The blocks of code are commented here:
1. Set temperature, pressure, and resolution.
2. Calculate molality of S from given weight percent [this is rather tedious and could be condensed to fewer lines of code].
- Define the given weight percent (10 wt% S).
- Calculate weight permil S.
- Divide by molar mass to calculate moles of S in 1 kg of solution.
- Calculate grams of `r H2O` in 1 kg of solution.
- Calculate molality (moles of S per kg of `r H2O`, not kg of solution).
- Calculate decimal logarithm of molality.
3. Define the basis species and formed species, calculate affinity, equilibrate activities, and make the diagram.
- If we didn't want to plot the buffer lines, we could just use `basis(c("H2S", "H2O", "oxygen", "H+"))`.
- Basis species with Fe, Si, and Ni are needed for the HM, QFM, and NNO buffers.
- Note that "oxygen" matches `r O2`(gas), not `r O2`(aq), so the variable on the diagram is `r logfO2`.
4. Define Ni-NiO (NNO) buffer and plot buffer lines for HM, QFM, and NNO.
- QFM (quartz-fayalite-magnetite) is also known as FMQ.
5. Calculate and plot pH of neutrality for water.
6. Add a legend and title.
<button id="B-trisulfur-1" onclick="ToggleDiv('trisulfur-1')">Show code</button>
<div id="D-trisulfur-1" style="display: none">
```{r trisulfur, eval = FALSE, echo = 3:43}
```
</div>
### Why does the published diagram have a much larger stability field for `r S3minus`?
Let's calculate `r logK` for the reaction 2 `r H2S`(aq) + `r SO4__` + `r Hplus` = `r S3minus` + 0.75 `r O2`(gas) + 2.5 `r H2O`.
```{r trisulfur_logK, message = FALSE, echo = 1:3}
species <- c("H2S", "SO4-2", "H+", "S3-", "oxygen", "H2O")
coeffs <- c(-2, -1, -1, 1, 0.75, 2.5)
(calclogK <- subcrt(species, coeffs, T = seq(300, 450, 50), P = 5000)$out$logK)
fcalclogK <- formatC(calclogK, format = "f", digits = 1)
reflogK <- -9.6
dlogK <- calclogK[2] - reflogK
# Put in a test so that we don't get surprised by
# future database updates or changes to this vignette
stopifnot(round(dlogK, 4) == -4.4132)
```
By using the thermodynamic parameters for `r S3minus` in OBIGT that are taken from @PD15, `r logK` is calculated to be `r paste(paste(fcalclogK[1:3], collapse = ", "), fcalclogK[4], sep = ", and ")` at 300, 350, 400, and 450 °C and 5000 bar.
In contrast, ref. 22 of @PD11 lists `r reflogK` for `r logK` at 350 °C; this is `r round(-dlogK, 1)` log units higher than the calculated value of `r fcalclogK[2]`.
This corresponds to a difference of Gibbs energy of -2.303 * 1.9872 * (350 + 273.15) * `r round(-dlogK, 1)` = `r formatC(-2.303 * 1.9872 * (350 + 273.15) * -dlogK, format = "f", digits = 0)` cal/mol.
In the code below, we use the difference of Gibbs energy to temporarily update the OBIGT entry for `r S3minus`.
Then, we make a new diagram that is more similar to that from @PD11.
Finally, we reset the OBIGT database so that the temporary parameters don't interfere with later calculations.
<button id="B-trisulfur-2" onclick="ToggleDiv('trisulfur-2')">Show code</button>
<div id="D-trisulfur-2" style="display: none">
```{r trisulfur, eval = FALSE, echo = 46:55}
```
</div>
### Can I make the diagram using the Deep Earth Water (DEW) model?
Yes! Just set a new temperature and pressure and activate the DEW water model and load the DEW aqueous species.
You can also use `r info_` to see which species are affected by loading the DEW parameters; it turns out that `r SO4__` isn't.
Then, use similar commands as above to make the diagram.
At the end, reset the water model and OBIGT database.
<button id="B-trisulfur-DEW" onclick="ToggleDiv('trisulfur-DEW')">Show code</button>
<div id="D-trisulfur-DEW" style="display: none">
```{r trisulfur_DEW, message = FALSE, echo = 8:22, collapse = TRUE, fig.keep = "none"}
# The first four lines are stand-ins to make this block runnable and get the right output from info();
# the diagram actually shown in the vignette is made using the 'trisulfur' block above
b <- basis("CHNOS+")
s <- species(c("H2S", "HS-", "SO2", "HSO4-", "SO4-2", "S3-"))
res <- 10
wt_percent_S <- logm_S <- 0
######## End of stand-in code ########
T <- 700
P <- 10000 # 10000 bar = 1 GPa
oldwat <- water("DEW")
add.OBIGT("DEW")
info(species()$ispecies)[, 1:8]
a <- affinity(pH = c(2, 10, res), O2 = c(-18, -10, res), T = T, P = P)
e <- equilibrate(a, loga.balance = logm_S)
diagram(e)
lTP <- describe.property(c("T", "P"), c(T, P))
lS <- paste(wt_percent_S, "wt% S(aq)")
ltext <- c(lTP, lS)
legend("topright", ltext, bty = "n", bg = "transparent")
title(quote("Deep Earth Water (DEW)"~"model"))
water(oldwat)
OBIGT()
```
</div>
Here are the three plots that we made:
```{r trisulfur, echo = FALSE, message = FALSE, results = "hide", fig.width = 10, fig.height = 3.33, out.width = "100%", out.extra='class="full-width"', pngquant = pngquant, cache = TRUE}
```
*Added on 2023-09-08.*
## In OBIGT, what is the meaning of `T` for solids, liquids, and gases?
The value in this column can be one of the following:
1. The temperature of transition to the next polymorph of a mineral;
2. For the highest-temperature (or only) polymorph, if `T` is positive, it is the phase stability limit (i.e., the temperature of melting or decomposition of a solid or vaporization of a liquid);
3. For the highest-temperature polymorph, if `T` is negative, the opposite (positive) value is the *T* limit for validity of the *C~p~* equation. (*New feature in development version of CHNOSZ*)
These cases are handled by `subcrt()` as follows.
The units of `T` in OBIGT are Kelvin, but `subcrt()` by default uses °C:
**1. For polymorphic transitions, the properties of specific polymorphs are returned:**
```{r pyrrhotite_polymorphs, collapse = TRUE}
subcrt("pyrrhotite", T = c(25, 150, 350), property = "G")$out
```
Note: In both SUPCRT92 and OBIGT, tin, sulfur, and selenium are listed as minerals with one or more polymorphic transitions, but the highest-temperature polymorph actually represents the liquid state.
Furthermore, quicksilver is listed as a mineral whose polymorphs actually correspond to the liquid and gaseous states.
**2. For a phase stability limit, Δ*G*° is set to NA above the temperature limit:**
```{r pyrite_limit}
subcrt("pyrite", T = seq(200, 1000, 200), P = 1)
```
This feature is intended to make it harder to obtain potentially unreliable results at temperatures where a mineral (or an organic solid or liquid) is not stable.
If you want the extrapolated Δ*G*° above the listed phase stability limit, then add `exceed.Ttr = TRUE` to the function call to `subcrt()`.
OBIGT has a non-exhaustive list of temperatures of melting, decomposition, or other phase change, some of which were taken from SUPCRT92 while others were taken from @RH95.
These minerals are listed below:
```{r mineral_Ttr, collapse = TRUE}
file <- system.file("extdata/OBIGT/inorganic_cr.csv", package = "CHNOSZ")
dat <- read.csv(file)
# Reverse rows so highest-T polymorph for each mineral is listed first
dat <- dat[nrow(dat):1, ]
# Remove low-T polymorphs
dat <- dat[!duplicated(dat$name), ]
# Remove minerals with no T limit for phase stability (+ve) or Cp equation (-ve)
dat <- dat[!is.na(dat$z.T), ]
# Keep minerals with phase stability limit
dat <- dat[dat$z.T > 0, ]
# Get names of minerals and put into original order
rev(dat$name)
```
<!--
Use square brackets to suppress parentheses around citation 20231115
https://stackoverflow.com/questions/64209134/r-markdown-suppress-parentheses-in-specific-citations
-->
OBIGT now uses the decomposition temperature of covellite [780.5 K from @RH95] in contrast to the previous Tmax from SUPCRT92 [1273 K, which is referenced to a \Cp equation described as "estimated" on p. 62 of @Kel60].
Selected organic solids and liquids have melting or vaporization temperatures listed as well.
However, no melting temperatures are listed for minerals that use the `Berman` model.
**3. For a *C~p~* equation limit, extrapolated values of Δ*G*° are shown and a warning is produced:**
```{r muscovite_limit, message = FALSE}
add.OBIGT("SUPCRT92")
subcrt("muscovite", T = 850, P = 4500)
reset()
```
The warning is similar to that produced by SUPCRT92 ("CAUTION: BEYOND T LIMIT OF CP COEFFS FOR A MINERAL OR GAS") at temperatures above maximum temperature of validity of the Maier-Kelley equation (Tmax).
Notably, SUPCRT92 outputs Δ*G*° and other standard thermodynamic properties at temperatures higher than Tmax despite the warning.
This is a new feature in CHNOSZ version 2.1.0.
In previous versions of CHNOSZ, values of Δ*G*° above the *C~p~* equation limit were set to NA without a warning, as with the phase stability limit described above.
**4. Finally, if `T` is NA or 0, then no upper temerature limit is imposed by `subcrt()`.**
*Added on 2023-11-15.*
## How can mineral pH buffers be plotted?
Unlike mineral redox buffers, the K-feldspar–muscovite–quartz (KMQ) and muscovite–kaolinite (MC) pH buffers are known as "sliding scale" buffers because they do not determine pH but rather the activity ratio of `r Kplus` to `r Hplus` [@HA05].
To add these buffers to a `r logfO2`–pH diagram in CHNOSZ, choose basis species that include Al<sup>+3</sup> (the least mobile element, which the reactions are balanced on), quartz (this is needed for the KMQ buffer), the mobile ions `r Kplus` and `r Hplus`, and the remaining elements in `r H2O` and `r O2`; `oxygen` denotes the gas in OBIGT.
The formation reactions for these minerals don't involve `r O2`, but it must be present so that the number of basis species equals the number of elements +1 (i.e. elements plus charge).
```{r KMQ_basis_species, message = FALSE}
basis(c("Al+3", "quartz", "K+", "H+", "H2O", "oxygen"))
species(c("kaolinite", "muscovite", "K-feldspar"))
```
We could go right ahead and make a `r logfO2`–pH diagram, but the implied assumption would be that the `r Kplus` activity is unity, which may not be valid.
Instead, we can obtain an independent estimate for `r Kplus` activity based on 1) the activity ratio of `r Naplus` to `r Kplus` for the reaction between albite and K-feldspar and 2) charge balance among `r Naplus`, `r Kplus`, and `r Clminus` for a given activity of the latter [@HC14].
Using the variables defined below, those conditions are expressed as `K_AK = m_Na / m_K` and `m_Na + m_K = m_Cl`, which combine to give `m_K = m_Cl / (K_AK + 1)`.
The reason for writing the equations with molality instead of activity is that ionic strength (`IS`) is provided in the arguments to `subcrt()`, so the function returns a value of `r logK` adjusted for ionic strength.
Furthermore, it is assumed that this is a chloride-dominated solution, so ionic strength is taken to be equal to the molality of `r Clminus`.
```{r KMQ_m_K, message = FALSE}
# Define temperature, pressure, and molality of Cl- (==IS)
T <- 150
P <- 500
IS <- m_Cl <- 1
# Calculate equilibrium constant for Ab-Kfs reaction, corrected for ionic strength
logK_AK <- subcrt(c("albite", "K+", "K-feldspar", "Na+"), c(-1, -1, 1, 1),
T = T, P = P, IS = IS)$out$logK
K_AK <- 10 ^ logK_AK
# Calculate molality of K+
(m_K <- m_Cl / (K_AK + 1))
```
This calculation gives a molality of `r Kplus` that is lower than unity and accordingly makes the buffers less acidic [@HC14].
Now we can apply the calculated molality of `r Kplus` to the basis species and add the buffer lines to the diagram.
The `IS` argument is also used for `affinity()` so that activities are replaced by molalities (that is, affinity is calculated with standard Gibbs energies adjusted for ionic strength; this has the same effect as calculating activity coefficients).
```{r KMQ_diagram, eval = FALSE, echo = 2:10}
par(mfrow = c(1, 2))
basis("K+", log10(m_K))
a <- affinity(pH = c(2, 10), O2 = c(-55, -38), T = T, P = P, IS = IS)
diagram(a, srt = 90)
lTP <- as.expression(c(lT(T), lP(P)))
legend("topleft", legend = lTP, bty = "n", inset = c(-0.05, 0), cex = 0.9)
ltxt <- c(quote("Unit molality of Cl"^"-"), "Quartz saturation")
legend("topright", legend = ltxt, bty = "n", cex = 0.9)
title("Mineral data from Berman (1988)\nand Sverjensky et al. (1991) (OBIGT default)",
font.main = 1, cex.main = 0.9)
add.OBIGT("SUPCRT92")
a <- affinity(pH = c(2, 10), O2 = c(-55, -38), T = T, P = P, IS = IS)
diagram(a, srt = 90)
title("Mineral data from Helgeson et al. (1978)\n(as used in SUPCRT92)",
font.main = 1, cex.main = 0.9)
OBIGT()
```
```{r KMQ_diagram, message = FALSE, fig.width = 8, fig.height = 4, out.width = "100%", results = "hide", echo = FALSE}
```
The gray area, which is automatically drawn by `diagram()`, is below the reducing stability limit of water; that is, this area is where the equilibrium fugacity of `r H2` exceeds unity.
NOTE: Although the muscovite–kaolinite (MC) buffer was mentioned by @HC14 in the context of "clay-rich but feldspar-free sediments", this example uses the feldspathic Ab–Kfs reaction for calculating `r Kplus` molality for both the KMQ and MC buffers.
A more appropriate reaction to constrain the Na/K ratio with the MC buffer may be that between paragonite and muscovite [e.g., @Yar05].
The diagram in Fig. 4 of @HC14 shows the buffer lines at somewhat higher pH values of ca. 5 and 6.
Removing `IS` from the code moves the lines to lower rather than higher pH (*not shown -- try it yourself!*), so the calculation of activity coefficients does not explain the differences.
One possible reason for these differences is the use of different thermodynamic data for the minerals.
The parameters for these minerals in the default OBIGT database come from @Ber88 and @SHD91.
```{r KMQ_refs, message = FALSE}
thermo.refs(species()$ispecies)
```
CHNOSZ doesn't implement the thermodynamic model for minerals from @HP98, which is one of the sources cited by @HC14.
If we use the thermodynamic parameters for minerals from @HDNB78 [these do not include the revisions for aluminosilicates described by @SHD91], we get the lines shown in the second plot above, representing a larger stability field for muscovite.
This moves the KMQ buffer closer to the value shown by @HC14, but the MC buffer further away, so this still doesn't explain why we get a different result.
```{r KMQ_diagram, eval = FALSE, echo = 11:15}
```
*Added on 2023-11-28.*
## References
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/vignettes/FAQ.Rmd
|
---
title: "OBIGT thermodynamic database"
output:
html_vignette:
mathjax: null
vignette: >
%\VignetteIndexEntry{OBIGT thermodynamic database}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
bibliography: OBIGT.bib
# So that these appear in the bibliography
nocite: |
@SPRONS92, @SLOP98, @SLOP07, @SLOP16, @JOH92, @WP02, @CWM89, @PRPG97, @TH88, @Kul06, @Sho09, @HKF81
csl: elementa.csl
link-citations: true
---
<style>
/* https://css-tricks.com/hash-tag-links-padding/ */
a.anchor::before {
display: block;
content: " ";
margin-top: -220px;
height: 220px;
visibility: hidden;
pointer-events: none;
}
</style>
<script>
function ToggleDiv(ID) {
var D = document.getElementById("D-" + ID);
if (D.style.display === "none") {
// close all divs then open this one
CloseAllDivs();
OpenDiv(ID);
} else {
// close all divs
CloseAllDivs();
}
}
function OpenDiv(ID) {
// open the div
var D = document.getElementById("D-" + ID);
D.style.display = "block";
// style the button
var B = document.getElementById("B-" + ID);
var Btext = ID.split("-")[1];
B.innerHTML = "<b>" + Btext + "</b>";
B.style.color = "red";
}
function CloseDiv(ID) {
// close the div
var D = document.getElementById("D-" + ID);
D.style.display = "none";
// style the button
var B = document.getElementById("B-" + ID);
var Btext = ID.split("-")[1];
B.innerHTML = Btext;
B.style.color = "black";
}
function OpenAllDivs() {
OpenDiv("aqueous-H2O");
OpenDiv("aqueous-inorganic");
OpenDiv("aqueous-organic");
OpenDiv("solid-inorganic");
OpenDiv("solid-organic");
OpenDiv("solid-Berman");
OpenDiv("gas-inorganic");
OpenDiv("gas-organic");
OpenDiv("liquid-organic");
OpenDiv("optional-SUPCRT92");
OpenDiv("optional-SLOP98");
OpenDiv("optional-AD");
OpenDiv("optional-AS04");
OpenDiv("optional-DEW");
OpenDiv("optional-GEMSFIT");
// change the footer message
document.getElementById("footer").style.display = "none";
document.getElementById("all-open").style.display = "block";
}
function CloseAllDivs() {
CloseDiv("aqueous-H2O");
CloseDiv("aqueous-inorganic");
CloseDiv("aqueous-organic");
CloseDiv("solid-inorganic");
CloseDiv("solid-organic");
CloseDiv("solid-Berman");
CloseDiv("gas-inorganic");
CloseDiv("gas-organic");
CloseDiv("liquid-organic");
CloseDiv("optional-SUPCRT92");
CloseDiv("optional-SLOP98");
CloseDiv("optional-AD");
CloseDiv("optional-AS04");
CloseDiv("optional-DEW");
CloseDiv("optional-GEMSFIT");
// change the footer message
document.getElementById("footer").style.display = "block";
document.getElementById("all-open").style.display = "none";
}
</script>
```{r CHNOSZ_reset, include=FALSE}
library(CHNOSZ)
reset()
```
```{r setfile, include=FALSE}
# Assign the file name to a variable and print the file name and number of species
setfile <- function(csvfile, dat=NULL) {
# Assign csvfile outside this function
assign("csvfile", csvfile, parent.frame())
file <- system.file(paste0("extdata/OBIGT/", csvfile), package="CHNOSZ")
dat <- read.csv(file, as.is=TRUE)
## Exclude entries for high-T polymorphs
#dat <- dat[!dat$state %in% c("cr2", "cr3", "cr4", "cr5", "cr6", "cr7", "cr8", "cr9"), ]
# The state and class of substance (used as section header), followed by number of species
basename <- gsub(".csv", "", csvfile)
class <- strsplit(basename, "_")[[1]][1]
substr(class, 1, 1) <- toupper(substr(class, 1, 1))
state <- strsplit(basename, "_")[[1]][2]
if(identical(state, "aq")) state <- "Aqueous "
else if(identical(state, "cr")) state <- "Solid "
else if(identical(state, "gas")) state <- "Gas "
else if(identical(state, "liq")) state <- "Liquid "
else state <- "Optional "
paste0(state, class, " (", nrow(dat), " species)")
}
```
```{r filerefs, include=FALSE}
filerefs <- function(csvfile, dat=NULL, message=FALSE) {
# With dat, look for ref2 in dat
whichref <- "ref2"
# Without dat, look for ref1 in csvfile
if(is.null(dat)) {
file <- system.file(paste0("extdata/OBIGT/", csvfile), package="CHNOSZ")
dat <- read.csv(file, as.is=TRUE)
whichref <- "ref1"
}
## Exclude entries for high-T polymorphs
#dat <- dat[!dat$state %in% c("cr2", "cr3", "cr4", "cr5", "cr6", "cr7", "cr8", "cr9"), ]
# Count number of times each reference is used
tab <- table(dat[, whichref])
# In case there are not references (previously for H2O_aq.csv) we return the species here
if(length(tab)==0) return(paste(dat$name, dat$state))
# The reference keys
keys <- names(tab)
# Warn if any keys aren't in thermo()$ref$key
ikey <- match(keys, thermo()$ref$key)
ina <- is.na(ikey)
if(any(ina)) cat(paste("**WARNING: key(s)", paste(names(tab)[ina], collapse=" "), "not found in `thermo()$ref$key`**\n\n"))
# Put the table in chronological order, according to thermo()$ref
ikey <- order(match(keys, thermo()$ref$key))
tab <- tab[ikey]
keys <- keys[ikey]
xxx <- lapply(seq_along(tab), function(i){
thiskey <- keys[i]
# Read thermo()$ref$note
iref <- match(thiskey, thermo()$ref$key)
note <- thermo()$ref$note[iref]
# Show the note in italics
if(!identical(note, "")) note <- paste0(" *", note, "* ")
# Use bullets for ref2
if(whichref=="ref2") bullet <- "- " else bullet <- ""
# Convert key (e.g. LD12.2) to ref in OBIGT.bib (e.g. LD12)
thisref <- gsub("\\..*$", "", thiskey)
# Replace SLOP98 with slop98.dat, etc.
# (we don't actually cite them here to keep the year from showing -- it's annoying to see e.g. "slop98.dat (1998)")
citemark <- "@"
if(thisref=="SLOP16") { thisref <- "slop16.dat"; citemark <- "" }
if(thisref=="SLOP07") { thisref <- "slop07.dat"; citemark <- "" }
if(thisref=="SLOP98") { thisref <- "slop98.dat"; citemark <- "" }
if(thisref=="SPRONS92") { thisref <- "sprons92.dat"; citemark <- "" }
if(thisref=="OBIGT") { thisref <- paste0("OBIGT (", thermo()$ref$year[iref], ")"); citemark <- "" }
cat(bullet, citemark, thisref, " -- ", tab[i], note, "\n\n", sep="")
# Get ref2 if we're in the outer list
if(whichref!="ref2") filerefs(dat=dat[dat$ref1==names(tab)[i], ])
})
# Return all the species listed
paste(dat$name, dat$state)
}
```
```{r used, include=FALSE}
# Initialize the list of used species
used <- character()
# Initialize the list of used optional species
optused <- character()
```
This vignette, produced on `r Sys.Date()`, lists the references for thermodynamic data in the OBIGT database in CHNOSZ version `r sessionInfo()$otherPkgs$CHNOSZ$Version`.
Except for Optional Data, all data are present in the default database, which is loaded when the package is attached, or by running `reset()` or `OBIGT()`.
Each section below corresponds to one of the CSV data files in the `extdata/OBIGT` package directory.
Clicking on a button opens that section, which contains a list of primary references (from column `ref1` in the file) in chronological order.
Any secondary references (`ref2`) are listed with bullet points under the primary reference.
Each citation is followed by the number of species, and a note taken from the file `extdata/OBIGT/refs.csv`.
Additional comments (from this vignette) are present for some sections.
Abbreviations: T (temperature), P (pressure), GHS (standard Gibbs energy, enthalpy, entropy), Cp (heat capacity), V (volume), HKF (<abbr title="Tanger and Helgeson, 1988">revised</abbr> <abbr title="Helgeson et al., 1981">Helgeson-Kirkham-Flowers</abbr> equations).
<!-- All buttons at top -->
### Aqueous Species <button id="B-aqueous-H2O" onclick='ToggleDiv("aqueous-H2O")'>H2O</button> <button id="B-aqueous-inorganic" onclick='ToggleDiv("aqueous-inorganic")'>Inorganic</button> <button id="B-aqueous-organic" onclick='ToggleDiv("aqueous-organic")'>Organic</button>
### Solids <button id="B-solid-inorganic" onclick='ToggleDiv("solid-inorganic")'>Inorganic</button> <button id="B-solid-organic" onclick='ToggleDiv("solid-organic")'>Organic</button> <button id="B-solid-Berman" onclick='ToggleDiv("solid-Berman")'>Berman</button>
### Gases <button id="B-gas-inorganic" onclick='ToggleDiv("gas-inorganic")'>Inorganic</button> <button id="B-gas-organic" onclick='ToggleDiv("gas-organic")'>Organic</button> Liquids <button id="B-liquid-organic" onclick='ToggleDiv("liquid-organic")'>Organic</button>
### Optional Data <button id="B-optional-SUPCRT92" onclick='ToggleDiv("optional-SUPCRT92")'>SUPCRT92</button> <button id="B-optional-SLOP98" onclick='ToggleDiv("optional-SLOP98")'>SLOP98</button> <button id="B-optional-AD" onclick='ToggleDiv("optional-AD")'>AD</button> <button id="B-optional-AS04" onclick='ToggleDiv("optional-AS04")'>AS04</button> <button id="B-optional-DEW" onclick='ToggleDiv("optional-DEW")'>DEW</button> <button id="B-optional-GEMSFIT" onclick='ToggleDiv("optional-GEMSFIT")'>GEMSFIT</button>
<!-- Normal or "all open" footer message -->
<div id="footer" style="display: block">
*Press a button above to show the citations in that data file.*
*Or, <a href = "#showall" onclick='OpenAllDivs()'>click here</a> to show all citations.*
</div>
<div id="all-open" style="display: none">
*Showing citations in all data files.*
*Press any button above to hide them.*
</div>
<!-- Aqueous species divs -->
<div id="D-aqueous-H2O" style="display: none">
## <a id="aqueous-H2O" class="anchor"></a> `r setfile("H2O_aq.csv")`
```{r reflist, results="asis", echo=FALSE}
used <- c(used, filerefs(csvfile))
```
This file contains H<sub>2</sub>O, *e*<sup>-</sup>, and H<sup>+</sup>.
The properties of H<sub>2</sub>O are listed as NA; CHNOSZ calculates its properties using a Fortran subroutine taken from SUPRCT92 ([Johnson et al., 1992](https://doi.org/10.1016/0098-3004(92)90029-Q)) (default) or using the IAPWS-95 equations ([Wagner and Pruß, 2002](https://doi.org/10.1063/1.1461829)) or the Deep Earth Water (DEW) model ([Sverjensky et al., 2014](https://doi.org/10.1016/j.gca.2013.12.019)).
By convention, the standard Gibbs energy of formation, entropy, and heat capacity of the aqueous proton (H<sup>+</sup>) are 0 at all *T* and *P* ([e.g. Cox et al., 1989](https://www.worldcat.org/oclc/18559968)).
The formation reaction of the proton can be expressed as ½H<sub>2,(*g*)</sub> + Z = H<sup>+</sup>, where Z is the "element" of positive charge.
Because the conventional standard Gibbs energy of this reaction is 0 at all *T*, the standard entropy of the reaction is also constrained to be zero (cf. Puigdomenech et al., 1997).
Therefore, the "element" of positive charge (Z) has zero thermodynamic properties except for an entropy, *S*°<sub>*T*<sub>r</sub></sub>, that is negative one-half that of H<sub>2,(*g*)</sub>.
The standard entropy of the aqueous electron, which is a solely a pseudospecies defined by *e*<sup>-</sup> = -Z, is opposite that of Z.
Likewise, [GEM-Selektor](http://gems.web.psi.ch/) defines "independent components" to be stoichiometric units usually consisting of elements and charge; the latter, [which is named Zz](http://gems.web.psi.ch/tests/TestNaCl-dep.html) and has a standard molal entropy of -65.34 J/mol/K and heat capacity of -14.418 J/mol/K (negative one-half those of gaseous hydrogen), is negated in the formula of the fictive "aqueous electron" ([Kulik, 2006](https://doi.org/10.1016/j.chemgeo.2005.08.014)).
Despite these considerations, the final column of the thermodynamic database (`thermo()$OBIGT`) lists a charge of "0" for both the aqueous proton and electron.
Data in this this column are used in CHNOSZ only to specify the charge that is input to the "*g*-function" ([Tanger and Helgeson, 1988](https://doi.org/10.2475/ajs.288.1.19); [Shock and Helgeson, 1988](https://doi.org/10.1016/0016-7037(88)90181-0)).
Setting it to zero prevents activation of the *g*-function, which would result in non-zero contributions to thermodynamic properties, conflicting with the conventions mentioned above.
All other calculations in CHNOSZ obtain the elemental makeup, including the correct charge for the species, by parsing the chemical formulas stored in the database.
</div>
<div id="D-aqueous-inorganic" style="display: none">
## <a id="aqueous-inorganic" class="anchor"></a> `r setfile("inorganic_aq.csv")`
```{r reflist, results="asis", echo=FALSE}
```
</div>
<div id="D-aqueous-organic" style="display: none">
## <a id="aqueous-organic" class="anchor"></a> `r setfile("organic_aq.csv")`
Charged amino acid sidechain groups have a Z parameter that is tabulated as zero; their chemical formulas indicate the correct charge.
Non-zero values of Z would yield derivatives of the omega parameter (ω) in the revised HKF equations of state for the cations and anions *that are not opposites of each other*.
This would be incompatible with group additivity of cations and anions to give a neutral species, for which the derivatives of ω are taken to be zero (cf. [Dick et al., 2006](https://doi.org/10.5194/bg-3-311-2006)).
```{r reflist, results="asis", echo=FALSE}
```
</div>
<!-- Solid species divs -->
<div id="D-solid-inorganic" style="display: none">
## <a id="solid-inorganic" class="anchor"></a> `r setfile("inorganic_cr.csv")`
Chamosite,7A and witherite were present in sprons92.dat but not in slop98.dat or later files, and are not included in CHNOSZ.
The source of parameters used here for goethite is different from that in the slop files ([Shock, 2009](https://doi.org/10.2113/gsecongeo.104.8.1235)).
```{r reflist, results="asis", echo=FALSE}
```
</div>
<div id="D-solid-organic" style="display: none">
## <a id="solid-organic" class="anchor"></a> `r setfile("organic_cr.csv")`
```{r reflist, results="asis", echo=FALSE}
```
</div>
<div id="D-solid-Berman" style="display: none">
## <a id="solid-Berman" class="anchor"></a> `r setfile("Berman_cr.csv")`
This file gives the identifiying information for minerals whose properties are calculated using the formulation of [Berman (1988)](https://doi.org/10.1093/petrology/29.2.445).
Thermodynamic properties for these minerals are listed as NA in `thermo()$OBIGT`; the actual data are stored separately, as CSV files in `extdata/Berman/*.csv`.
```{r reflist, results="asis", echo=FALSE}
```
</div>
<!-- Gas species divs -->
<div id="D-gas-inorganic" style="display: none">
## <a id="gas-inorganic" class="anchor"></a> `r setfile("inorganic_gas.csv")`
```{r reflist, results="asis", echo=FALSE}
```
</div>
<div id="D-gas-organic" style="display: none">
## <a id="gas-organic" class="anchor"></a> `r setfile("organic_gas.csv")`
```{r reflist, results="asis", echo=FALSE}
```
</div>
<!-- Liquid species divs -->
<div id="D-liquid-organic" style="display: none">
## <a id="liquid-organic" class="anchor"></a> `r setfile("organic_liq.csv")`
```{r reflist, results="asis", echo=FALSE}
```
</div>
<!-- Optional species divs -->
<div id="D-optional-SUPCRT92" style="display: none">
## <a id="optional-SUPCRT92" class="anchor"></a> `r setfile("SUPCRT92.csv")`
These minerals and aqueous species, taken from the SUPCRT92 database, were present in earlier versions of CHNOSZ but have since been superseded by @Ber88 (minerals) and @NA03 (H<sub>2</sub>AsO<sub>3</sub><sup>-</sup>).
The thermodynamic properties and parameters are kept here as optional data for reproducing published calculations and making comparisons with newer data.
The minerals here include all of the silicates and Al-bearing minerals from @HDNB78, as well as calcite, dolomite, hematite, and magnetite.
Use `add.OBIGT("SUPCRT92")` to load the data.
**NOTE:** Other minerals from SUPCRT92, including native elements, sulfides, halides, sulfates, and selected carbonates and oxides that do not duplicate those in the Berman dataset, are still present in the default database (**inorganic_cr.csv**).
```{r optreflist, results="asis", echo=FALSE}
```
</div>
<div id="D-optional-SLOP98" style="display: none">
## <a id="optional-SLOP98" class="anchor"></a> `r setfile("SLOP98.csv")`
These species, which were taken from or are linked to slop98.dat (or later versions) and were present in earlier versions of CHNOSZ, have been replaced by or are incompatible with species currently in the default database, including aqueous Al species [@TS01], As species [@NA03], Au, Ag, and Cu species [@AZ01; @AZ10], Pd species [@TBZ+13], Zn species [@AT14], Pt species [@TBB15], Nb species [@AKK+20], and CoCl<sub>2</sub><sup>+</sup> [@LBT+11].
This file also contains aqueous transuranic actinide complexes, for which estimated thermodynamic properties have been reported, but no entropies of the corresponding elements at 298.15 K are available to check the self-consistency of the GHS values for the complexes.
Use `add.OBIGT("SLOP98")` to load the data.
**NOTE:** Many other species found in slop98.dat and later versions are still present in the default database.
```{r optreflist, results="asis", echo=FALSE}
```
</div>
<div id="D-optional-AD" style="display: none">
## <a id="optional-AD" class="anchor"></a> `r setfile("AD.csv")`
This file has parameters for aqueous nonelectrolytes in the Akinfiev-Diamond model [@AD03].
Use `add.OBIGT("AD")` to load the data; see `demo(AD)` for an example.
```{r optreflist, results="asis", echo=FALSE}
```
</div>
<div id="D-optional-AS04" style="display: none">
## <a id="optional-AS04" class="anchor"></a> `r setfile("AS04.csv")`
This file has data for aqueous SiO<sub>2</sub> from @AS04 and a HSiO<sub>3</sub><sup>-</sup> modified to be consistent with the SiO<sub>2</sub> here.
This file also has H<sub>4</sub>SiO<sub>4</sub> from an earlier publication [@Ste01] that is roughly consistent with the SiO<sub>2</sub> here.
Use `add.OBIGT("AS04")` to load the data; see `demo(aluminum)` for an example.
```{r optreflist, results="asis", echo=FALSE}
```
</div>
<div id="D-optional-DEW" style="display: none">
## <a id="optional-DEW" class="anchor"></a> `r setfile("DEW.csv")`
The Deep Earth Water (DEW) model extends the applicability of the revised HKF equations of state to 60 kbar.
Accuracy of the thermodynamic calculations at these conditions is improved by revised correlations for the <i>a</i><sub>1</sub> HKF parameter, as described by [Sverjensky et al. (2014)](https://doi.org/10.1016/j.gca.2013.12.019).
The thermodynamic parameters for species were taken from the May 2017 and January 2019 versions of the DEW spreadsheet.
The following species are present in the spreadsheet, but are not used here because the parameters are unchanged from the default database in CHNOSZ: B(OH)<sub>3</sub>, Br<sup>-</sup>, Ca<sup>+2</sup>, Cl<sup>-</sup>, Cs<sup>+</sup>, F<sup>-</sup>, H<sup>+</sup>, H<sub>2</sub>, He, I<sup>-</sup>, K<sup>+</sup>, Kr, Li<sup>+</sup>, Mg<sup>+2</sup>, Na<sup>+</sup>, Ne, O<sub>2</sub>, Rb<sup>+</sup>, Rn, SO<sub>4</sub><sup>-2</sup>.
Besides using `add.OBIGT("DEW")` to load these data, you should also run `water("DEW")` to activate the DEW equations in CHNOSZ.
See `demo(DEW)` for some examples.
Most of the comments below were transcribed from the DEW spreadsheet. (Comments in parentheses were added by JMD.)
```{r optreflist, results="asis", echo=FALSE}
optused <- c(optused, filerefs(csvfile))
```
</div>
<div id="D-optional-GEMSFIT" style="display: none">
## <a id="optional-GEMSFIT" class="anchor"></a> `r setfile("GEMSFIT.csv")`
[Miron et al. (2016)](https://doi.org/10.1016/j.gca.2016.04.026) and [Miron et al. (2017)](https://doi.org/10.2475/07.2017.01) described an internally consistent thermodynamic dataset for aqueous species in the system Ca-Mg-Na-K-Al-Si-O-H-C-Cl that was obtained by using the [GEMSFIT](https://doi.org/10.1016/j.apgeochem.2014.10.013) package.
Use `add.OBIGT("GEMSFIT")` to load the data.
```{r optreflist, results="asis", echo=FALSE}
```
</div>
<hr>
<b>Total count of species</b>: References were found for `r length(used)` of `r nrow(thermo()$OBIGT)` species in the default OBIGT database and `r length(optused)` optional species.
# References
<script>
// Open button corresponding to hash target in URL 20200703
// Keep this at the end of the body:
// https://stackoverflow.com/questions/9899372/pure-javascript-equivalent-of-jquerys-ready-how-to-call-a-function-when-t
var url = window.location.href;
if (url.indexOf("#") > 0) {
var activeButton = url.substring(url.indexOf("#") + 1);
if(activeButton == "showall") {
OpenAllDivs();
// hide the footer message
document.getElementById("footer").style.display = "none";
} else {
OpenDiv(activeButton);
}
// https://stackoverflow.com/questions/3163615/how-to-scroll-html-page-to-given-anchor
location.hash = "#" + activeButton;
}
</script>
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/vignettes/OBIGT.Rmd
|
---
title: "An Introduction to CHNOSZ"
author: "Jeffrey M. Dick"
date: "`r Sys.Date()`"
output:
tufte::tufte_html:
tufte_features: ["background"]
toc: true
mathjax: null
tufte::tufte_handout:
citation_package: natbib
latex_engine: xelatex
tufte::tufte_book:
citation_package: natbib
latex_engine: xelatex
vignette: >
%\VignetteIndexEntry{An Introduction to CHNOSZ}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
bibliography: vig.bib
link-citations: yes
csl: elementa.csl
---
<style>
html {
font-size: 14px;
}
body {
font-family: ‘Times New Roman’, Times, serif;
}
li {
padding: 0.25rem 0;
}
/* zero margin around pre blocks (looks more like R console output) */
pre {
margin-top: 0;
margin-bottom: 0;
}
</style>
```{r options, include=FALSE}
options(width = 80)
options(digits = 6)
```
```{r HTML, include=FALSE}
## Some frequently used HTML expressions
logfO2 <- "log<i>f</i><sub>O<sub>2</sub></sub>"
# Use lowercase here because these tend to be variable names in the examples
zc <- "<i>Z</i><sub>C</sub>"
o2 <- "O<sub>2</sub>"
h2o <- "H<sub>2</sub>O"
sio2 <- "SiO<sub>2</sub>"
ch4 <- "CH<sub>4</sub>"
```
```{r setup, include=FALSE}
library(knitr)
## From "Tufte Handout" example dated 2016-12-27
# Invalidate cache when the tufte version changes
opts_chunk$set(tidy = FALSE, cache.extra = packageVersion('tufte'))
options(htmltools.dir.version = FALSE)
## Adjust plot margins
## First one from https://yihui.name/knitr/hooks/
knit_hooks$set(small.mar = function(before, options, envir) {
if (before) par(mar = c(4.2, 4.2, .1, .1)) # smaller margin on top and right
})
knit_hooks$set(tiny.mar = function(before, options, envir) {
if (before) par(mar = c(.1, .1, .1, .1)) # tiny margin all around
})
knit_hooks$set(smallish.mar = function(before, options, envir) {
if (before) par(mar = c(4.2, 4.2, 0.9, 0.9)) # smallish margins on top and right
})
## Use pngquant to optimize PNG images
knit_hooks$set(pngquant = hook_pngquant)
pngquant <- "--speed=1 --quality=0-25"
# pngquant isn't available on R-Forge ...
if (!nzchar(Sys.which("pngquant"))) pngquant <- NULL
# Set dpi 20231129
knitr::opts_chunk$set(
dpi = if(nzchar(Sys.getenv("CHNOSZ_BUILD_LARGE_VIGNETTES"))) 72 else 50
)
hidpi = if(nzchar(Sys.getenv("CHNOSZ_BUILD_LARGE_VIGNETTES"))) 100 else 50
## http://stackoverflow.com/questions/23852753/knitr-with-gridsvg
## Set up a chunk hook for manually saved plots.
knit_hooks$set(custom.plot = hook_plot_custom)
## Hook to change <img /> to <embed /> -- required for interactive SVG
hook_plot <- knit_hooks$get("plot")
knit_hooks$set(plot = function(x, options) {
x <- hook_plot(x, options)
if (!is.null(options$embed.tag) && options$embed.tag) x <- gsub("<img ", "<embed ", x)
x
})
## http://stackoverflow.com/questions/30530008/hook-to-time-knitr-chunks
now = Sys.time()
knit_hooks$set(timeit = function(before) {
if (before) { now <<- Sys.time() }
else {
paste("%", sprintf("Chunk rendering time: %s seconds.\n", round(Sys.time() - now, digits = 3)))
}
})
timeit <- NULL
## Colorize messages 20171031
## Adapted from https://gist.github.com/yihui/2629886#file-knitr-color-msg-rnw
color_block = function(color) {
function(x, options) sprintf('<pre style="color:%s">%s</pre>', color, x)
}
knit_hooks$set(warning = color_block('magenta'), error = color_block('red'), message = color_block('blue'))
```
# Overview
This vignette was made for version `r sessionInfo()$otherPkgs$CHNOSZ$Version` of CHNOSZ, a package for the [R software environment](https://www.r-project.org/).
For more information on R, see "[An Introduction to R](https://cran.r-project.org/manuals.html)" and the [contributed documentation](https://cran.r-project.org/other-docs.html) for R.
CHNOSZ has been developed since 2006 as a tool for thermodynamic calculations in geochemistry and compositional biology.
The package provides functions and a thermodynamic database that can be used to calculate the stoichiometric and energetic properties of reactions involving minerals and inorganic and/or organic aqueous species.
These functions also enable calculations of chemical affinities and metastable equilibrium distributions of proteins.
A major feature of the package is the production of diagrams to visualize the effects of changing temperature, pressure, and activities of basis species on the potential for reactions among various species.
## Installing and loading CHNOSZ
After starting R, install CHNOSZ by selecting the "Install packages from CRAN" or similar menu item in the R GUI or by using the following command:
```{r install_CHNOSZ, eval=FALSE}
install.packages("CHNOSZ")
```
Then load the CHNOSZ package to make its data and functions available in your R session:
```{r library_CHNOSZ}
library(CHNOSZ)
```
CHNOSZ is now ready to go with the default thermodynamic database and an empty system definition.
After running some calculations, you may want to "start over" with the default values.
To clear the system settings and restore the default thermodynamic database, use <span style="color:red">`reset()`</span>.
```{r reset}
reset()
```
Note: Throughout this document, syntax highlighting is applied to the *input* of the code chunks.
Double hash marks (`##`) precede the *output*, where black text denotes *results* and blue text is used for *messages*.
## Getting help
After CHNOSZ is installed, type <span style="color:blue">`help.start()`</span> to browse the R help documents, then choose "Packages" followed by "CHNOSZ".
That shows an index of the *manual* (help pages) for each function; many of the help pages include examples.
There are also links to the *demos* (longer examples) and *vignettes* (more in-depth documentation; this document is a vignette).
Suggestions for accessing the documentation are indicated here with <span style="color:blue">blue text</span>.
For example, read <span style="color:blue">``?`CHNOSZ-package` ``</span> to get an overview of the package and a list of features.
```{marginfigure}
"`?`" is a shortcut to R's `help()` function.
The command here is equivalent to <span style="color:blue">`help("CHNOSZ-package")`</span>.
```
## Organization of major functions
CHNOSZ is made up of a set of functions and supporting datasets.
The major components of the package are shown in the figure below, which is an updated version of the diagram in @Dic08.
Rectangles and ellipses represent functions and datasets; bold text indicates primary functions.
<!-- https://stackoverflow.com/questions/14675913/how-to-change-image-size-markdown -->
{ width=75% }
Many functions in CHNOSZ have no side effects.
That is, the function only returns a result; to use the result elsewhere, it can be assigned to a variable with `<-`.
In this document, the names of these functions are shown in <span style="color:green">green text</span> (not applicable to the code chunks).
```{marginfigure}
When they are mentioned, names of functions in the base and recommended packages of R are said to belong to R.
Example: Use R's `plot()` to plot the data.
```
Major functions without side effects in CHNOSZ are:
* <span style="color:green">`info()`</span>: search for species in the thermodynamic database;
* <span style="color:green">`subcrt()`</span>: calculate the thermodynamic properties of species and reactions;
* <span style="color:green">`affinity()`</span>: calculate the affinities of formation reactions using given chemical activities;
* <span style="color:green">`equilibrate()`</span>: calculate the equilibrium chemical activities of the species of interest;
* <span style="color:green">`diagram()`</span>: plot the results.
Some functions in CHNOSZ do have side effects: they modify the `thermo` data object in the current R session.
In this document, the names of these functions are shown in <span style="color:red">red text</span> (but not in the code chunks).
Major functions with side effects are:
* <span style="color:red">`basis()`</span>: set the basis species and their chemical activities;
* <span style="color:red">`species()`</span>: set the species of interest and their (non-equilibrium) chemical activities;
* <span style="color:red">`reset()`</span>: reset the database, restoring all settings to their default values.
The following pseudocode shows a common sequence of commands.
In actual usage, the `...` are replaced by arguments that define the chemical species and variables:
```{r pseudocode, eval=FALSE}
basis(...)
species(...)
a <- affinity(...)
e <- equilibrate(a) ## optional
diagram(e) ## or diagram(a)
reset() ## clear settings for next calculation
```
# Querying the thermodynamic database
## The <span style="color:green">`info()`</span> function
<span style="color:green">`info()`</span> provides an interface to the OBIGT thermodynamic database that is packaged with CHNOSZ.
Suppose you are interested in the thermodynamic properties of aqueous methane.
Because the database is assembled with aqueous species first, they take precedence over other states.
Searching by chemical formula alone gives the first matching species, in this case aqueous methane:
```{r info_CH4}
info("CH4")
```
The number that is returned is the species index in the database.
A second argument can be used to specify a physical state with lower precedence:
```{r info_CH4_gas}
info("CH4", "gas")
```
While some species are identified only by chemical formula, others have distinct names (in English) listed in the database.
For `r ch4` and inorganic substances that are represented by both gaseous and aqueous forms, the name is applied only to the gas.
However, the names of organic substances other than methane are applied to aqueous species, which have precedence, and those in other states.
The following commands get the species indices for some common gases:
```{r info_names_gas}
info("methane")
info("oxygen")
info("carbon dioxide")
```
A special case is sulfur; the name refers to both the native mineral, which has precedence, and the gas.
These two phases can be identifed with the formulas S<sub>2</sub> and S, respectively.
```{r info_S_S2}
info("S")
info("S2")
```
Taking the species number of aqueous methane returned by <span style="color:green">`info()`</span>, use the function again to retrieve the set of standard molal thermodynamic properties and equations of state parameters:
```{r iCH4, message=FALSE}
iCH4 <- info("CH4")
info(iCH4)
```
Liquid water is species number 1; it has NA entries in the database because dedicated functions are used to compute its properties:
```{r info_info_water}
info(info("water"))
```
## Fuzzy searches
Calling <span style="color:green">`info()`</span> with a string that does not exactly match the name of any species invokes a fuzzy search of the database:
```{r width180, include=FALSE}
options(width = 180)
```
```{r info_acid}
info("acid")
```
```{r width80, include=FALSE}
options(width = 80)
```
The message includes e.g. "uracil" and "metacinnabar" because their names have some similarity to the search term.
Since "ribose" is the name of a species in the database, to find species with similar names, add an extra character to the search:
```{r info_ribose}
info(" ribose")
```
The messages may be useful for browsing the database, but owing to their ambiguous results, these fuzzy searches return an `NA` value for the species index.
## Counting elements, chemical formulas, <span style="color:green">`ZC()`</span>
Continuing with the example of aqueous methane, let's look at its chemical formula:
```{r info_CH4_formula, message=FALSE}
info(iCH4)$formula
```
We can use <span style="color:green">`makeup()`</span> to count the elements in the formula, followed by <span style="color:green">`as.chemical.formula()`</span> to rewrite the formula on one line:
```{r makeup_iCH4}
makeup(iCH4)
as.chemical.formula(makeup(iCH4))
```
For organic species, a calculation of the average oxidation state of carbon (`r zc`) is possible given the species index, chemical formula, or elemental count:
```{r ZC_iCH4, message=FALSE}
ZC(iCH4)
ZC(info(iCH4)$formula)
ZC(makeup(iCH4))
```
# Calculating thermodynamic properties
To calculate the standard molal properties of species and reactions, use <span style="color:green">`subcrt()`</span>.
The name of this function is derived from the SUPCRT package [@JOH92], which is also the source of the Fortran subroutine used to calculate the thermodynamic properties of H<sub>2</sub>O.
If no reaction coefficients are given, <span style="color:green">`subcrt()`</span> calculates the standard molal properties of individual species:
```{r subcrt_water}
subcrt("water")
```
That uses the default temperature and pressure settings, i.e. equally spaced temperature intervals from 0 to 350 °C at *P*<sub>sat</sub>, i.e. 1 bar below 100 °C, or the pressure of liquid-vapor saturation (i.e. boiling) at higher temperatures.
The columns in the output are temperature, pressure, density of water, logarithm of the equilibrium constant (only meaningful for reactions; [see below](#properties-of-reactions)), standard molal Gibbs energy and enthalpy of formation from the elements, standard molal entropy, volume, and heat capacity.
```{marginfigure}
The corresponding units are °C (`T`), bar (`P`), g cm<sup>-3</sup> (`rho`), cal mol<sup>-1</sup> (`G` and `H`), cal K<sup>-1</sup> mol<sup>-1</sup> (`S` and `Cp`), and cm<sup>3</sup> mol<sup>-1</sup> (`V`).
```
A custom temperature-pressure grid can be specified.
Here, we calculate the properties of `r h2o` on a *T*, *P* grid in the supercritical region, with conditions grouped by pressure:
```{r subcrt_water_grid}
subcrt("water", T = c(400, 500, 600), P = c(200, 400, 600), grid = "P")$out$water
```
```{r subcrt_water_plot, fig.margin=TRUE, fig.width=4, fig.height=4, small.mar=TRUE, out.width="100%", echo=FALSE, message=FALSE, fig.cap="Isothermal contours of density (g cm<sup>-3</sup>) and pressure (bar) of water.", cache=TRUE, pngquant=pngquant, timeit=timeit}
sres <- subcrt("water", T=seq(0,1000,100), P=c(NA, seq(1,500,1)), grid="T")
water <- sres$out$water
plot(water$P, water$rho, type = "l")
```
The additional operations (`$out$water`) are used to extract a specific part of the results; this can be used with e.g. R's `write.table()` or `plot()` for further processing:
```{r subcrt_water_plot, eval=FALSE}
```
## Changing units
The default units of temperature, pressure, and energy in the input and output of <span style="color:green">`subcrt()`</span> are °C, bar, and Joules.
The functions <span style="color:red">`T.units()`</span>, <span style="color:red">`P.units()`</span>, and <span style="color:red">`E.units()`</span> can be used to change the units used by <span style="color:green">`subcrt()`</span> and some other functions in CHNOSZ.
What is the Gibbs energy in J/mol (the default) and cal/mol of aqueous methane at 298.15 K and 0.1 MPa?
```{r units_CH4}
T.units("K")
P.units("MPa")
subcrt("CH4", T = 298.15, P = 0.1)$out$CH4$G
E.units("cal")
subcrt("CH4", T = 298.15, P = 0.1)$out$CH4$G
```
The parameters for each species in the OBIGT database have the units indicated by the `E_units` column there, which is independent of the setting of <span style="color:red">`E.units()`</span>.
Unlike <span style="color:green">`subcrt()`</span>, <span style="color:green">`info()`</span> always displays the database values in the units given in the database.
A separate function, <span style="color:green">`convert()`</span>, can be used to convert values to selected units.
The following code shows that the database parameters for CH<sub>4</sub>(aq) are in calories, then converts the standard Gibbs energy from cal/mol to J/mol.
```{r convert_G, message=FALSE}
(CH4dat <- info(info("CH4")))
convert(CH4dat$G, "J")
```
Note that converting the database value to J/mol gives the same result as running `subcrt("CH4", T = 25)` with the default <span style="color:red">`E.units()`</span> setting of J.
Use <span style="color:red">`reset()`</span> to restore the units and all other settings for CHNOSZ to their defaults:
```{r reset}
```
# Properties of reactions
## Reaction definitions
To calculate the thermodynamic properties of reactions, give the names of species, the physical states (optional), and reaction coefficients as the arguments to <span style="color:green">`subcrt()`</span>.
Here we calculate properties for the dissolution of CO<sub>2</sub>.
This doesn't correspond to the _solubility_ of CO<sub>2</sub>; see the [solubility section](#complete-equilibrium-solubility) in this vignette and [<span style="color:blue">`demo(solubility)`</span>](../demo) for examples of solubility calculations.
```{r subcrt_CO2}
subcrt(c("CO2", "CO2"), c("gas", "aq"), c(-1, 1), T = seq(0, 250, 50))
```
In order to make a plot like Figure 18 of @MSS13, let's run more calculations and store the results.
In addition to the reaction definition, we specify a greater number of temperature points than the default:
```{r CO2_logK, echo=FALSE, message=FALSE}
T <- seq(0, 350, 10)
CO2 <- subcrt(c("CO2", "CO2"), c("gas", "aq"), c(-1, 1), T = T)$out$logK
CO <- subcrt(c("CO", "CO"), c("gas", "aq"), c(-1, 1), T = T)$out$logK
CH4 <- subcrt(c("CH4", "CH4"), c("gas", "aq"), c(-1, 1), T = T)$out$logK
logK <- data.frame(T, CO2, CO, CH4)
```
```{r CO2_plot, fig.margin=TRUE, fig.width=4, fig.height=4, small.mar=TRUE, out.width="100%", echo=FALSE, message=FALSE, fig.cap="Calculated equilibrium constants for dissolution of CO<sub>2</sub>, CO, and CH<sub>4</sub>.", cache=TRUE, pngquant=pngquant, timeit=timeit}
matplot(logK[, 1], logK[, -1], type = "l", col = 1, lty = 1,
xlab = axis.label("T"), ylab = axis.label("logK"))
text(80, -1.7, expr.species("CO2"))
text(240, -2.37, expr.species("CO"))
text(300, -2.57, expr.species("CH4"))
```
```{r CO2_logK, eval=FALSE}
```
Now we can make the plot, using R's `matplot()`.
Here, <span style="color:green">`axis.label()`</span> and <span style="color:green">`expr.species()`</span> are used to create formatted axis labels and chemical formulas:
```{r CO2_plot, eval=FALSE}
```
## Unbalanced reactions
A balanced chemical reaction conserves mass.
<span style="color:green">`subcrt()`</span> won't stop you from running an unbalanced reaction, but it will give you a warning:
```{r subcrt_unbalanced, results="hide"}
subcrt(c("CO2", "CH4"), c(-1, 1))
```
In other words, to balance the reaction, we should add 4 H to the left and 2 O to the right.
That could be done manually be redefining the reaction with the appropriate species.
There is another option: balancing the reaction automatically using basis species.
## Setting the basis species
_Basis species_ are a minimal number of chemical species that linearly combine to give the composition of any species in the system.
The basis species are similar to thermodynamic components, but can include charged species.
Basis species are used in CHNOSZ to automatically balance reactions; they are also required for making chemical activity diagrams.
Let's start with an example that doesn't work:
```{r basis_singular, error=TRUE}
basis(c("CO2", "H2", "H2CO2"))
```
That set of species has a singular (non-invertible) stoichiometric matrix.
An error would also result from either an underdetermined or overdetermined system.
A valid set of basis species has an invertible stoichiometric matrix and the same number of species as elements:
```{r basis_CHO}
basis(c("CO2", "H2", "H2O"))
```
The composition of any species made up of C, H, and O can be represented by a single linear combination of these basis species.
## Automatically balancing reactions
Methanogenic metabolism in reducing environments may proceed by acetoclastic or hydrogenotrophic processes.
To consider reactions involving a charged species (acetate), let's define a basis with H<sup>+</sup>:
```{r basis_CHOZ}
basis(c("CO2", "H2", "H2O", "H+"))
```
By identifying species *other than* the basis species, the reactions will be automatically balanced.
This produces the balanced reaction for acetoclastic methanogenesis:
```{r subcrt_acetoclastic, message=FALSE}
subcrt(c("acetate", "CH4"), c(-1, 1))$reaction
```
We can similarly consider reactions for hydrogenotrophic methanogenesis as well as acetate oxidation (without production of methane):
```{r subcrt_methanogenesis, message=FALSE}
acetate_oxidation <- subcrt("acetate", -1)
hydrogenotrophic <- subcrt("CH4", 1)
acetoclastic <- subcrt(c("acetate", "CH4"), c(-1, 1))
```
Use <span style="color:green">`describe.reaction()`</span> to write the reactions on a plot:
```{r describe_reaction_plot, fig.margin=TRUE, fig.width=3.5, fig.height=1.8, tiny.mar=TRUE, out.width="100%", pngquant=pngquant, timeit=timeit}
plot(0, 0, type = "n", axes = FALSE, ann=FALSE, xlim=c(0, 5), ylim=c(5.2, -0.2))
text(0, 0, "acetoclastic methanogenesis", adj = 0)
text(5, 1, describe.reaction(acetoclastic$reaction), adj = 1)
text(0, 2, "acetate oxidation", adj = 0)
text(5, 3, describe.reaction(acetate_oxidation$reaction), adj = 1)
text(0, 4, "hydrogenotrophic methanogenesis", adj = 0)
text(5, 5, describe.reaction(hydrogenotrophic$reaction), adj = 1)
```
## Chemical affinity
Usually, <span style="color:green">`subcrt()`</span> returns only standard state thermodynamic properties.
```{marginfigure}
The standard state adopted for H<sub>2</sub>O is unit activity of the pure component at any *T* and *P*.
The standard state for aqueous species is unit activity of a hypothetical one molal solution referenced to infinite dilution at any *T* and *P*.
```
Thermodynamic models often consider a non-standard state (i.e. non-unit activity).
The activities of basis species can be modified with <span style="color:red">`basis()`</span>, and those of the other species using the `logact` argument in <span style="color:green">`subcrt()`</span>.
Let us calculate the chemical affinity of acetoclastic methanogenesis.
```{marginfigure}
The affinity is equal to the negative of the overall (non-standard) Gibbs energy change of the reaction.
```
We change the states of CO<sub>2</sub> and H<sub>2</sub> in the basis from `aq` (aqueous) to `gas`, and set the logarithm of fugacity of gaseous H<sub>2</sub> and the pH, using values from @MDS_13.
The activity of acetate and fugacity of methane, as well as temperature and pressure, are set in the call to <span style="color:green">`subcrt()`</span>:
```{r basis_mayumi, message=FALSE, results="hide"}
basis(c("CO2", "H2", "H2O", "H+"))
basis(c("CO2", "H2"), "gas")
basis(c("H2", "pH"), c(-3.92, 7.3))
```
```{r affinity_acetoclastic, message=FALSE}
subcrt(c("acetate", "CH4"), c(-1, 1),
c("aq", "gas"), logact = c(-3.4, -0.18), T = 55, P = 50)$out
```
The new `A` column shows the affinity; the other columns are unaffected and still show the standard-state properties.
Let's repeat the calculation for hydrogenotrophic methanogenesis.
```{r affinity_hydrogenotrophic, message=FALSE}
subcrt("CH4", 1, "gas", logact = -0.18, T = 55, P = 50)$out
```
Under the specified conditions, the affinities of hydrogenotrophic and acetoclastic methanogenesis are somewhat greater than and less than 20 kJ, respectively.
This result matches Figure 4b in Mayumi et al. (2013) at unit fugacity of CO<sub>2</sub>.
We can go even further and reproduce their plot.
```{marginfigure}
The reproduction is not identical, owing to differences of thermodynamic data and of calculations of the effects of temperature and pressure.
```
To make the code neater, we write a function that can run any of the reactions:
```{r rxnfun, message=FALSE}
rxnfun <- function(coeffs) {
subcrt(c("acetate", "CH4"), coeffs,
c("aq", "gas"), logact = c(-3.4, -0.18), T = 55, P = 50)$out
}
```
Now we're ready to calculate and plot the affinities.
Here, we use R's `lapply()` to list the results at two values of logarithm of fugacity of CO<sub>2</sub>.
We insert an empty reaction to get a line at zero affinity.
R's `do.call()` and `rbind()` are used to turn the list into a data frame that can be plotted with R's `matplot()`.
There, we plot the negative affinities, equal to Gibbs energy, as shown in the plot of Mayumi et al. (2013).
```{r methanogenesis_plot, fig.margin=TRUE, fig.width=4.1, fig.height=4.1, small.mar=TRUE, out.width="100%", echo=FALSE, message=FALSE, fig.cap="Gibbs energies of acetate oxidation and methanogenesis (after Mayumi et al., 2013).", cache=TRUE, pngquant=pngquant, timeit=timeit}
Adat <- lapply(c(-3, 3), function(logfCO2) {
basis("CO2", logfCO2)
data.frame(logfCO2,
rxnfun(c(0, 0))$A,
rxnfun(c(-1, 0))$A,
rxnfun(c(-1, 1))$A,
rxnfun(c(0, 1))$A
)
})
Adat <- do.call(rbind, Adat)
matplot(Adat[, 1], -Adat[, -1]/1000, type = "l", lty = 1, lwd = 2,
xlab = axis.label("CO2"), ylab = axis.label("DG", prefix = "k"))
legend("topleft", c("acetate oxidation", "acetoclastic methanogenesis",
"hydrogenotrophic methanogenesis"), lty = 1, col = 2:4)
```
```{r methanogenesis_plot, eval=FALSE}
```
Let's not forget to clear the system settings, which were modified by <span style="color:red">`basis()`</span>, before running other calculations:
```{r reset, message=FALSE}
```
# Using <span style="color:green">`affinity()`</span>
<span style="color:green">`affinity()`</span> offers calculations of chemical affinity of formation reactions over a configurable range of *T*, *P*, and activities of basis species.
## From affinity to diagrams
By *formation reaction* is meant the stoichiometric requirements for formation of one mole of any species from the basis species.
The <span style="color:red">`species()`</span> function is used to set these *formed species*.
Let's consider the stoichiometry of some aqueous sulfur-bearing species.
Here we use <span style="color:red">`basis()`</span> with a keyword to load a preset basis definition.
To use Eh as a variable, the electron (*e*<sup>-</sup>) should be in the basis, so we use the keyword (<span style="color:red">`basis("CHNOSe")`</span>).
```{marginfigure}
Some available keywords are `CHNOS` (including CO<sub>2</sub>, H<sub>2</sub>O, NH<sub>3</sub>, H<sub>2</sub>S, and O<sub>2</sub>), `CHNOS+` (also including H<sup>+</sup>), and `CHNOSe` (including H<sup>+</sup>, and *e*<sup>-</sup> instead of O<sub>2</sub>).
See <span style="color:blue">`?basis`</span> for more options.
```
```{marginfigure}
What is `SO42-`? Is it 1 S, 4 O, and 2 negative charges, or 1 S, 42 O, and 1 negative charge?
The ambiguity of a digit that could belong to the coefficient for the following charge or to that for the preceding element is why formulas in CHNOSZ are written with the number of charges after the + or - symbol.
`SO4-2` is unambiguously parsed as 1 S, 4 O and 2 negative charges.
```
```{r basis_CHNOSZ, results="hide"}
basis("CHNOSe")
```
```{r species_sulfur}
species(c("H2S", "HS-", "HSO4-", "SO4-2"))
```
Aqueous species are assigned default activities of 10<sup>-3</sup> (`logact` is -3).
Now, we can use <span style="color:green">`affinity()`</span> to calculate the affinities of the formation reactions of each of the species.
R's `unlist()` is used here to turn the list of values of affinity into a numeric object that can be printed in a couple of lines (note that the names correspond to `ispecies` above):
```{r affinity}
unlist(affinity()$values)
```
The values returned by <span style="color:green">`affinity()`</span> are dimensionless, i.e. *A*/(2.303*RT*).
Although <span style="color:green">`subcrt()`</span> can also calculate affinities (in units of cal/mol or J/mol), the main advantage of <span style="color:green">`affinity()`</span> is that it can perform calculations on an arbitrary grid of *T*, *P*, or activities of basis species.
This is the foundation for making many types of diagrams that are useful in geochemistry.
Given the values of affinity, the <span style="color:green">`diagram()`</span> function identifies the species that has the maximum affinity at each grid point.
The result is equivalent to a "predominance diagram" [@Dic19], where the fields represent the predominant aqueous species and the boundaries are equal-activity lines.
If both aqueous species and minerals are present, it is common practice to assign a constant activity to all aqueous species and unit activity (i.e. log activity = 0) for minerals.
More sophisticated diagrams can be made by showing the solubility contours of a metal on the diagram; see [<span style="color:blue">`demo(contour)`</span>](../demo) for an example.
```{r EhpH_plot, fig.margin=TRUE, fig.width=4, fig.height=4, out.width="100%", echo = FALSE, message=FALSE, cache=TRUE, fig.cap="Aqueous sulfur species at 25 °C.", pngquant=pngquant, timeit=timeit}
a <- affinity(pH = c(0, 12), Eh = c(-0.5, 1))
diagram(a, limit.water = TRUE)
```
Let's use <span style="color:green">`diagram()`</span> to make a simple Eh-pH diagram for aqueous species in the system S-O-H.
After running the <span style="color:red">`basis()`</span> and <span style="color:red">`species()`</span> commands above, we can calculate the affinities on an Eh-pH grid.
With the default settings in <span style="color:green">`diagram()`</span>, areas beyond the stability limits of water are colored gray.
This can be changed by setting the `limit.water` argument to FALSE (to not show the stability region of water) or TRUE (to plot the main diagram only in the stable region of water).
The names of species that can be parsed as chemical formulas are formatted with subscripts and superscripts; if this is not desired, set `format.names = FALSE`.
```{r EhpH_plot, echo=TRUE, eval=FALSE}
```
```{r EhpH_plot_color, fig.margin=TRUE, fig.width=4, fig.height=4, smallish.mar=TRUE, out.width="100%", echo=FALSE, message=FALSE, cache=TRUE, fig.cap="The same plot, with different colors and labels.", pngquant=pngquant, timeit=timeit}
diagram(a, fill = "terrain", lwd = 2, lty = 3,
names = c("hydrogen sulfide", "bisulfide", "bisulfate", "sulfate"),
las = 0)
water.lines(a, col = 6, lwd = 2)
```
Other arguments in <span style="color:green">`diagram()`</span> can be used to control the line type (`lty`), width (`lwd`), and color (`col`), field colors (`fill`), and species labels (`name`).
Additional arguments are passed to R's plotting functions; here, we use `las` to change the orientation of axes labels.
Another function, <span style="color:green">`water.lines()`</span>, can be used to draw lines at the water stability limits:
```{r EhpH_plot_color, echo=TRUE, eval=FALSE}
```
See the demos in the package for other examples of Eh-pH diagrams.
In particular, [<span style="color:blue">`demo(Pourbaix)`</span>](../demo) shows how to plot the concentrations of metals as equisolubility (or isosolubility) lines on Eh-pH diagrams [@Pou74].
Mineral stability diagrams often depict activity ratios, e.g. log (*a*<sub>Ca<sup>+2</sup></sub>/*a*<sub>H<sup>+</sup></sub><sup>2</sup>), on one or both axes.
The variables used for potential calculations in CHNOSZ include only a single chemical activity, e.g. log *a*<sub>Ca<sup>+2</sup></sub>.
However, you can set pH = 0 to generate diagrams that are geometrically equivalent to those calculated using activity ratios, and use <span style="color:green">`ratlab()`</span> to make the axes labels for the ratios.
Moreover, <span style="color:green">`diagram()`</span> has a "saturation" option that can be used to draw saturation limits for minerals that do not contain the conserved basis species.
See [<span style="color:blue">`demo(saturation)`</span>](../demo) for an example that uses activity ratios on the axes and plots saturation limits for calcite, magnesite, dolomite, and brucite on a diagram for the H<sub>2</sub>O–CO<sub>2</sub>–CaO–MgO–SiO<sub>2</sub> system.
That demo can be used as a template to produce a wide range of diagrams similar to those in @BJH84.
## Retrieving species in a chemical system
Most of the diagrams in this vignette are made by giving the names of all the species.
However, it can be tedious to find all the species by manually searching the OBIGT database.
The <span style="color:green">`retrieve()`</span> function can be used to identify the available species that contain particular chemical elements.
For example, to get Mn-bearing aqueous species and minerals including the single element, oxides and oxyhydroxides, use this:
```{r retrieve}
retrieve("Mn", c("O", "H"), "aq")
retrieve("Mn", c("O", "H"), "cr")
```
Below, these commands are used to identify the species in an Eh-pH diagram for the Mn-O-H system at 100 °C.
This diagram includes Mn oxides (pyrolusite, bixbyite, hausmannite), Mn(OH)<sub>2</sub>, and aqueous Mn species.
```{r retrieve_diagram, fig.margin=TRUE, fig.width=5, fig.height=5, out.width="100%", message=FALSE, results = "hide", cache=TRUE, fig.cap="Eh-pH diagram for the Mn-O-H system.", pngquant=pngquant, timeit=timeit}
# Set decimal logarithm of activity of aqueous species,
# temperature and plot resolution
logact <- -4
T <- 100
res <- 400
# Start with the aqueous species
basis(c("Mn+2", "H2O", "H+", "e-"))
iaq <- retrieve("Mn", c("O", "H"), "aq")
species(iaq, logact)
aaq <- affinity(pH = c(4, 16, res), Eh = c(-1.5, 1.5, res), T = T)
# Show names for only the metastable species here
names <- names(iaq)
names[!names(iaq) %in% c("MnOH+", "MnO", "HMnO2-")] <- ""
diagram(aaq, lty = 2, col = "#4169E188", names = names, col.names = 4)
# Overlay mineral stability fields
icr <- retrieve("Mn", c("O", "H"), "cr")
species(icr, add = TRUE)
# Supply the previous result from affinity() to use
# argument recall (for plotted variables and T)
acr <- affinity(aaq)
diagram(acr, add = TRUE, bold = acr$species$state=="cr", limit.water = FALSE)
# Add legend
legend <- c(
bquote(log * italic(a)["Mn(aq)"] == .(logact)),
bquote(italic(T) == .(T) ~ degree*C)
)
legend("topright", legend = as.expression(legend), bty = "n")
```
This introductory vignette shows examples for diagrams with a single metal.
Other functions are available to make diagrams for multiple metals; see the vignette [<span style="color:blue">*Diagrams with multiple metals*</span>](multi-metal.html) for more information.
## Mosaic diagrams
If sulfur is an element in the basis species, then we should consider that its speciation is sensitive to Eh and pH, as shown in a previous diagram.
Mosaic diagrams account for speciation of the basis species and are useful for visualizing the stabilities of many types of minerals including oxides, sulfides, and carbonates.
These diagrams are made by constructing individual diagrams for the possible basis species.
The individual diagrams are then combined, each one contributing to the final diagram only in the range of stability of the corresponding basis species.
Let's use <span style="color:green">`mosaic()`</span> to make a diagram for aqueous species and minerals in the Cu-S-Cl-`r h2o` system.
To know what aqueous copper chloride complexes are available in the database, we can use a fuzzy search:
```{r info_CuCl, results="hide"}
info(" CuCl")
```
Next we define the basis, and set the activities of the H<sub>2</sub>S and Cl<sup>-</sup> basis species.
These represent the total activity of S and Cl in the system, which are distributed among the minerals and aqueous species.
Aqueous copper chloride complexes and four minerals are added.
Be sure to include `add = TRUE` in the second call to <span style="color:red">`species()`</span>; otherwise, the minerals would simply replace the previously added aqueous species.
```{r copper_setup, echo=TRUE, results="hide"}
basis(c("Cu", "H2S", "Cl-", "H2O", "H+", "e-"))
basis("H2S", -6)
basis("Cl-", -0.7)
species(c("CuCl", "CuCl2-", "CuCl3-2", "CuCl+", "CuCl2", "CuCl3-", "CuCl4-2"))
species(c("chalcocite", "tenorite", "cuprite", "copper"), add = TRUE)
```
Note that chalcocite (Cu<sub>2</sub>S) undergoes polymorphic transitions.
To get the temperatures of the polymorphic transitions from `thermo()$OBIGT` (in Kelvin, regardless of the <span style="color:red">`T.units()`</span>), we can use <span style="color:green">`info()`</span>.
We see that at 200 °C (473.15 K) the second phase is stable; this one is automatially used by CHNOSZ for this diagram.
```{r info_chalcocite, message=FALSE}
info(info("chalcocite", c("cr", "cr2", "cr3")))$T
```
We use <span style="color:green">`mosaic()`</span> to generate and combine diagrams for each candidate basis species (H<sub>2</sub>S, HS<sup>-</sup>, HSO<sub>4</sub><sup>-</sup>, or SO<sub>4</sub><sup>-2</sup>) as a function of Eh and pH.
The key argument is `bases`, which identifies the candidate basis species, starting with the one in the current basis.
The other arguments, like those of <span style="color:green">`affinity()`</span>, specify the ranges of the variables; `res` indicates the grid resolution to use for each variable (the default is 256).
The first call to <span style="color:green">`diagram()`</span> plots the species of interest; the second adds the predominance fields of the basis species.
We also use <span style="color:green">`water.lines()`</span> to draw dashed blue lines at the water stability limits:
```{r copper_mosaic, fig.margin=TRUE, fig.width=4, fig.height=4, out.width="100%", message=FALSE, cache=TRUE, fig.cap="Copper minerals and aqueous complexes with chloride, 200 °C.", pngquant=pngquant, timeit=timeit}
T <- 200
res <- 200
bases <- c("H2S", "HS-", "HSO4-", "SO4-2")
m1 <- mosaic(bases, pH = c(0, 12, res), Eh=c(-1.2, 0.75, res), T=T)
diagram(m1$A.species, lwd = 2)
diagram(m1$A.bases, add = TRUE, col = 4, col.names = 4, lty = 3,
italic = TRUE)
water.lines(m1$A.species, col = "blue1")
```
The diagrams are combined according to the relative abundances of the different possible basis species listed in `bases` along with a term for the Gibbs energy of mixing (see <span style="color:blue">`?mosaic`</span>).
The smooth transitions between basis species can result in curved field boundaries, in this case around the chalcocite field.
If we added the argument `blend = FALSE`, the diagrams would instead be assembled using the single predominant basis species at any point on the Eh-pH grid, and all of the line segments would be straight.
The reactions used to make this diagram are balanced on Cu, so that no Cu appears in reactions between any two other species (minerals or aqueous species).
If <span style="color:green">`diagram()`</span> is run with `balance = 1`, then the reactions are balanced on formula units.
That is, one mole of the mineral formulas appears on each side of the reaction, with the possibility of Cu appearing as an additional species to conserve the elements.
This may be problematic, as Cu would be be present in some reactions in Eh-pH space where it is not a stable phase.
However, it is common in low-temperature aqueous geochemical calculations to "turn off" particular redox reactions that are not thought to attain equilibrium, so decoupling a species from equilibrium may be justified in some circumstances.
Changing the balance to 1 results in the loss of the tenorite stability field and extension of chalcocite stability to lower pH, as shown in Figure 5a of @CPCC17.
## *T*, *P*, activity transects
Above, we used evenly-spaced grids of chemical activities of basis species; the ranges of variables were given by two or three values (minimum, maximum, and optionally resolution).
<span style="color:green">`affinity()`</span> can also perform calculations along a transect, i.e. a particular path along one or more variables.
A transect is calculated when there are four or more values assigned to the variable(s).
Let's use this feature to calculate affinities (negative Gibbs energies) of methanogenesis and biosynthetic reactions in a hydrothermal system.
Some results of mixing calculations for seawater and vent fluid from the Rainbow hydrothermal field, calculated using EQ3/6 by @SC10, are included in a data file in CHNOSZ.
Reading the file with R's `read.csv()`, we set `check.names = FALSE` to preserve the `NH4+` column name (which is not a syntactically valid variable name):
```{r rainbow_data}
file <- system.file("extdata/cpetc/SC10_Rainbow.csv", package = "CHNOSZ")
rb <- read.csv(file, check.names = FALSE)
```
We take a selection of the species from Shock and Canovas (2010) with activities equal to 10<sup>-6</sup>; aqueous `r ch4` is assigned an activity of 10<sup>-3</sup>.
We will write the synthesis reactions of organic species in terms of these basis species:
```{marginfigure}
The constant activity of CH<sub>4</sub> is a simplification of the calculation reported by Shock and Canovas (2010).
The code here could be expanded to vary the activity of CH<sub>4</sub>.
```
```{r rainbow_species, results="hide"}
basis(c("CO2", "H2", "NH4+", "H2O", "H2S", "H+"))
species("CH4", -3)
species(c("adenine", "cytosine", "aspartic acid", "deoxyribose",
"CH4", "leucine", "tryptophan", "n-nonanoic acid"), -6)
```
Now we can calculate affinities along the transect of changing temperature and activities of five basis species.
Each variable is given as a named argument; `NH4+` must be quoted.
```{marginfigure}
A shorter expression would use R's `do.call()` to construct the function call: `do.call(`<span style="color:green">`affinity`</span>`, as.list(rb))`.
```
```{marginfigure}
The target of the conversion is `G`, or free energy, from `logK`.
That conversion requires temperature in Kelvin, which is obtained by conversion from °C.
We finish with a negation (affinity is negative Gibbs energy) and scaling from cal to kcal.
```
Using R's `lapply()` to run <span style="color:green">`convert()`</span> for each species, we first convert the affinity from dimensionless values (*A*/(2.303*RT*)) to J/mol.
A second call to <span style="color:green">`convert()`</span> is used to obtain energies in cal/mol, and these are finally converted to kcal/mol.
```{r rainbow_affinity, message=FALSE}
a <- affinity(T = rb$T, CO2 = rb$CO2, H2 = rb$H2,
`NH4+` = rb$`NH4+`, H2S = rb$H2S, pH = rb$pH)
T <- convert(a$vals[[1]], "K")
a$values <- lapply(a$values, convert, "G", T)
a$values <- lapply(a$values, convert, "cal")
a$values <- lapply(a$values, `*`, -0.001)
```
```{r rainbow_diagram, fig.margin=TRUE, fig.width=4, fig.height=4, out.width="100%", echo=FALSE, message=FALSE, cache=TRUE, fig.cap="Affinities of organic synthesis in a hydrothermal system, after Shock and Canovas (2010).", pngquant=pngquant, timeit=timeit}
diagram(a, balance = 1, ylim = c(-100, 100), ylab = quote(italic(A)*", kcal/mol"),
col = rainbow(8), lwd = 2, bg = "slategray3")
abline(h = 0, lty = 2, lwd = 2)
```
Finally, we use <span style="color:green">`diagram()`</span> to plot the results.
Although only temperature is shown on the *x* axis, pH and the activities of CO<sub>2</sub>, H<sub>2</sub>, NH<sub>4</sub><sup>+</sup>, and H<sub>2</sub>S are also varied according to the data in `rb`.
By default, <span style="color:green">`diagram()`</span> attempts to scale the affinities by dividing by the reaction coefficients of a shared basis species (in this case, CO<sub>2</sub>).
To override that behavior, we set `balance = 1` to plot the affinities of the formation reactions as written (per mole of the product species).
```{r rainbow_diagram, eval=FALSE}
```
When making line plots, <span style="color:green">`diagram()`</span> automatically places the labels near the lines.
The additional arguments `adj` and `dy` can be used to fine-tune the positions of the labels (they are used in a couple of examples below).
If labeling of the lines is not desired, add e.g. `legend.x = "topright"` to make a legend instead, or `names = FALSE` to prevent any plotting of the names.
## Buffers
There is one other feature of <span style="color:green">`affinity()`</span> that can be mentioned here.
Can we go the other direction: calculate the activities of basis species from the activities of the species of interest?
This question relates to the concept of chemical activity buffers.
In CHNOSZ there are two ways to perform buffer calculations:
1. Assign the name of a buffer (listed in `thermo()$buffer`) to the basis species:
* more versatile (multiple activities can be buffered, e.g. both S<sub>2</sub> and O<sub>2</sub> by pyrite-pyrrhotite-magnetite);
* the buffers are active in calculations of affinity of other species;
* use <span style="color:red">`mod.buffer()`</span> to change or add buffers in `thermo()$buffer`;
* [<span style="color:blue">`demo(buffer)`</span>](../demo) uses it for mineral buffers (solid lines).
2. Use the `type` argument of <span style="color:green">`diagram()`</span> to solve for the activity of the indicated basis species:
* more convenient (the buffers come from the currently defined species of interest), but only a single basis species can be buffered, and it's not used in the calculation of affinity;
* [<span style="color:blue">`demo(buffer)`</span>](../demo) uses it for aqueous organic species as buffers (dotted and dashed lines).
As an example of method 1, let's look at the pyrite-pyrrhotite-magnetite (PPM) buffer at 300 °C.
```{marginfigure}
For other examples, see <span style="color:blue">`?buffer`</span> and [<span style="color:blue">`demo(protbuff)`</span>](../demo) (hypothetical buffer made of proteins).
```
Without the buffer, the basis species have default activities of zero.
Under these conditions, the minerals are not in equilibrium, as shown by their different affinities of formation:
```{r PPM_basis, results="hide", message=FALSE}
basis(c("FeS2", "H2S", "O2", "H2O"))
species(c("pyrite", "magnetite"))
species("pyrrhotite", "cr2", add = TRUE)
```
```{marginfigure}
The affinity of formation of pyrite happens to be zero because it is identical to one of the selected basis species.
```
```{r PPM_affinity, message=FALSE}
unlist(affinity(T = 300, P = 100)$values)
```
We use <span style="color:red">`mod.buffer()`</span> to choose the `cr2` phase of pyrrhotite, which is stable at this temperature ([see above](#mosaic-diagrams) for how to get this information for minerals with polymorphic transitions).
Then, we set up H<sub>2</sub>S and `r o2` to be buffered by PPM, and inspect their buffered activities (logarithmic values):
```{r PPM_setup, results="hide"}
mod.buffer("PPM", "pyrrhotite", "cr2")
basis(c("H2S", "O2"), c("PPM", "PPM"))
```
```{r PPM_activities, message=FALSE}
unlist(affinity(T = 300, P = 100, return.buffer = TRUE)[1:3])
```
<!-- put demo(buffer) here for appealing placement on page -->
```{r demo_buffer_noecho, fig.margin=TRUE, fig.width=4, fig.height=4, out.width="100%", message=FALSE, echo=FALSE, cache=TRUE, fig.cap="Values of log<i>f</i><sub>H<sub>2</sub></sub> corresponding to mineral buffers or to given activities of aqueous species.", pngquant=pngquant, timeit=timeit}
demo(buffer, echo = FALSE)
```
We have found log*a*<sub>H<sub>2</sub>S</sub> and `r logfO2` that are compatible with the coexistence of the three minerals.
Under these conditions, the affinities of formation reactions of the minerals in the buffer are all equal to zero:
<!-- re-run the commands from above because demo(buffer) changes the system -->
```{r PPM_basis, echo = FALSE, results = "hide"}
```
```{r PPM_setup, echo = FALSE, results = "hide", message = FALSE}
```
```{r PPM_affinity, message = FALSE}
```
Another example, based on Figure 6 of @SS95, is given in [<span style="color:blue">`demo(buffer)`</span>](../demo).
Here, values of log*f*<sub>H<sub>2</sub></sub> buffered by minerals or set by equilibrium with given activities of aqueous species are calculated using the two methods:
```{r demo_buffer, eval=FALSE}
demo(buffer)
```
# Equilibrium
Above we considered this question: for equal activities of species, what are the affinities of their formation reactions from basis species?
Turning the question around, we would like to know: for equal affinities of formation reactions, what are the activities of species?
The first question is about non-equilibrium conditions; the second is about equilibrium.
Before presenting some examples, it is helpful to know about the limitations of the functions.
CHNOSZ does not take account of all possible reactions in the speciation of a system.
Instead, it assumes that the total activity of species in the system is set by the activity of *one* basis species.
```{marginfigure}
When activity coefficients are assumed to be zero, activities are equal to concentration and we can refer to "total activity".
If the ionic strength is specified, <span style="color:green">`nonideal()`</span> ([see below](#activity-coefficients)) can be used to calculate activity coefficients.
```
This balanced, or conserved, basis species must be present (with a positive or negative coefficient) in the formation reactions of all species considered.
For a given total activity of the balanced basis species, activities of the species can be found such that the affinities of the formation reactions are all equal.
This is an example of metastable equilibrium.
With additional constraints, the affinities of the formation reactions are not only equal to each other, but equal to zero.
This is total equilibrium.
An example of total equilibrium was given above for the PPM buffer.
In contrast, models for systems of organic and biomolecules often involve metastable equilibrium constraints.
## Equilibration methods
The <span style="color:green">`equilibrate()`</span> function in CHNOSZ automatically chooses between two methods for calculating equilibrium.
The method based on the Boltzmann equation is fast, but is applicable only to systems where the coefficient on the balanced basis species in each of the formation reactions is one.
The reaction-matrix method is slower, but can be applied to systems were the balanced basis species has reaction coefficients other than one.
```{r bjerrum_diagram, fig.margin=TRUE, fig.width=3, fig.height=6, out.width="100%", echo=FALSE, results="hide", message=FALSE, cache=TRUE, fig.cap="Three views of carbonate speciation: affinity, activity, degree of formation.", pngquant=pngquant, timeit=timeit}
par(mfrow = c(3, 1))
basis("CHNOS+")
species(c("CO2", "HCO3-", "CO3-2"))
a25 <- affinity(pH = c(4, 13))
a150 <- affinity(pH = c(4, 13), T = 150)
diagram(a25, dy = 0.4)
diagram(a150, add = TRUE, names = FALSE, col = "red")
e25 <- equilibrate(a25, loga.balance = -3)
e150 <- equilibrate(a150, loga.balance = -3)
diagram(e25, ylim = c(-6, 0), dy = 0.15)
diagram(e150, add = TRUE, names = FALSE, col = "red")
diagram(e25, alpha = TRUE, dy = -0.25)
diagram(e150, alpha = TRUE, add = TRUE, names = FALSE, col = "red")
```
The distribution of aqueous carbonate species as a function of pH (a type of Bjerrum plot) is a classic example of an equilibrium calculation.
We can begin by plotting the affinities of formation, for equal activities of the species, calculated at 25 °C and 150 °C.
Here, CO<sub>2</sub> is in the basis, so it has zero affinity, which is greater than the affinities of HCO<sub>3</sub><sup>-</sup> and CO<sub>3</sub><sup>-2</sup> at low pH.
To avoid overplotting the lines, we offset the species labels in the *y* direction using the `dy` argument:
```{r bjerrum_diagram, echo=1:7, eval=FALSE}
```
Now we use <span style="color:green">`equilibrate()`</span> to calculate the activities of species.
Our balancing constraint is that the total activity of C is 10<sup>-3</sup>.
This shows a hypothetical metastable equilibrium; we know that for true equilibrium the total activity of C is affected by pH.
```{r bjerrum_diagram, echo=8:11, eval=FALSE}
```
To display the species distribution, or degree of formation, add `alpha = TRUE` to the argument list:
```{r bjerrum_diagram, echo=12:13, eval=FALSE}
```
## Complete equilibrium: Solubility
It is important to remember that <span style="color:green">`equilibrate()`</span> calculates an equilibrium distribution of species for a given total activity of the conserved basis species.
For instance, the previous diagram shows the relative abundances of CO<sub>2</sub>, HCO<sub>3</sub><sup>-</sup>, and CO<sub>3</sub><sup>-2</sup> as a function of pH assuming that the possible reactions between species are all balanced on 1 C and the total activity of C is constant.
Although this assumption of metastable equilibrium is useful for making many types of diagrams for aqueous species, the aqueous solutions would not be in equilibrium with other phases, including gases or solids such as carbon dioxide or calcite.
Moving away from metastable equilibrium to complete equilibrium actually involves a simplification of the computations.
Instead of finding the activities of aqueous species where the affinities of formation reactions are equal to each other, equilibrium occurs when the affinities of all formation reactions are equal to zero.
However, the solubility calculation comes with a different constraint: all reactions between the pure substance that is being dissolved and any of the possible formed aqueous species must be able to be balanced on the same element (usually the main metal in the system).
This balancing constraint can be expressed as a conserved basis species, i.e. one that is present in non-zero quantity in the formation reactions of all species considered.
The <span style="color:green">`solubility()`</span> function provides a way to compute activities of aqueous species in equilibrium with one or more minerals or gases.
The following example for corundum (Al<sub>2</sub>O<sub>3</sub>) is based on Figure 15 of @Man13.
To more closely reproduce the diagram, we use superseded thermodynamic data that are kept in the `SLOP98` optional data file.
The basis species are defined with the main element (Al) first.
The mineral we want to dissolve, corundum, is loaded as a formed species.
The aqueous species that can form by dissolution of corundum are listed in the `iaq` argument of <span style="color:green">`solubility()`</span>.
The next arguments describe the variables for the <span style="color:green">`affinity()`</span> calculations.
Note that setting `IS` to 0 has no effect on the calculations, but signals <span style="color:green">`diagram()`</span> to label the *y* axis with logarithm of molality instead of logarithm of activity.
An additional argument, `in.terms.of`, is used to compute the total molality of Al in solution, that is, twice the number of moles of Al<sub>2</sub>O<sub>3</sub> that are dissolved.
<span style="color:green">`diagram()`</span> is used twice, first to plot the total molality of Al, then the concentrations of the individual species, using `adj` and `dy` to adjust the positions of labels in the *x*- and *y*-directions.
At the end of the calculation, we use <span style="color:red">`reset()`</span> to restore the default thermodynamic database.
```{r corundum, fig.margin=TRUE, fig.width=4, fig.height=4, out.width="100%", results="hide", message=FALSE, cache=TRUE, fig.cap="Solubility of corundum (green line) and equilibrium concentrations of aqueous species (black lines).", pngquant=pngquant, timeit=timeit}
add.OBIGT("SLOP98")
basis(c("Al+3", "H2O", "H+", "O2"))
species("corundum")
iaq <- c("Al+3", "AlO2-", "AlOH+2", "AlO+", "HAlO2")
s <- solubility(iaq, pH = c(0, 10), IS = 0, in.terms.of = "Al+3")
diagram(s, type = "loga.balance", ylim = c(-10, 0), lwd = 4, col = "green3")
diagram(s, add = TRUE, adj = c(0, 1, 2.1, -0.2, -1.5), dy = c(0, 0, 4, -0.3, 0.1))
legend("topright", c("25 °C", "1 bar"), text.font = 2, bty = "n")
reset()
```
Other examples of using <span style="color:green">`solubility()`</span> are available in CHNOSZ.
See [<span style="color:blue">`demo(solubility)`</span>](../demo) for calculations of the solubility of CO<sub>2(<i>gas</i>)</sub> and calcite as a function of pH and temperature.
The calculation considers the stoichiometric dissolution of calcite, in which CaCO<sub>3</sub> dissociates to form equal quantities of Ca<sup>+2</sup> and CO<sub>3</sub><sup>-2</sup> ions.
Adding in activity coefficients, an example in <span style="color:blue">`?solubility`</span> uses the `find.IS` option to find the final ionic strength for dissolving calcite into pure water.
[<span style="color:blue">`demo(gold)`</span>](../demo) shows calculations of the solubility of gold as a function of pH and *T* as well as oxygen fugacity set by diferent mineral buffers, and considers ionic strength effects on activity coefficients, so that activities are transformed to molalities ([see below](#from-activity-to-molality)).
# Activity coefficients
For calculating activity coefficients of charged species, <span style="color:green">`nonideal()`</span> uses the extended Debye--Hückel equation as parameterized by @HKF81 for NaCl-dominated solutions to high pressure and temperature, or optionally using parameters described in Chapter 3 of @Alb03, which are applicable to relatively low-temperature biochemical reactions.
The activity coefficients are calculated as a function of ionic strength (*I*), temperature, and charge of each species, without any other species-specific parameters.
Using the default `Helgeson` method, the extended term parameter ("B-dot") is derived from data of @Hel69 and Helgeson et al. (1981), and extrapolations of @MSS13.
## From activity to molality
Following the main workflow of CHNOSZ, <span style="color:green">`nonideal()`</span> normally does not need to be used directly.
Intead, invoke the calculations by setting the `IS` argument in <span style="color:green">`subcrt()`</span> or <span style="color:green">`affinity()`</span>.
There are a few things to remember when using activity coefficients:
* H<sup>+</sup> is assumed to behave ideally, so its activity coefficient is 1 for any ionic strength. You can calculate activity coefficients of H<sup>+</sup> by running `thermo("opt$ideal.H" = FALSE)`.
* Using <span style="color:green">`subcrt()`</span> with `IS` not equal to zero, calculated values of `G` are the **adjusted** Gibbs energy at specified ionic strength [denoted by Δ*G*°(*I*); @Alb96].
* Using <span style="color:green">`subcrt()`</span> with `IS` not equal to zero, values in the `logact` argument stand for **log molality** of aqueous species in affinity calculations.
* Using <span style="color:green">`affinity()`</span> with `IS` not equal to zero, the following values stand for **log molality** of aqueous species:
+ values of `logact` set by <span style="color:green">`basis()`</span>;
+ values of `logact` set by <span style="color:green">`species()`</span>.
* Using <span style="color:green">`equilibrate()`</span> on the output of affinity calculated with `IS` not equal to zero, the following values stand for **log molality** of aqueous species:
+ the value of `loga.balance` used by <span style="color:green">`equilibrate()`</span> (i.e., logarithm of total molality of the balancing basis species);
+ values of `loga.equil` returned by <span style="color:green">`equilibrate()`</span>.
In other words, the activation of activity coefficients effects a transformation from activity to molality in the main workflow.
A simple but comprehensive series of calculations demonstrating these tranformations is in `inst/tinytest/test-logmolality.R`.
Because it is not possible to dynamically change the names of arguments in the functions, the user should be aware of the transformations mentioned above.
However, the labels on diagrams *can* be automatically adjusted; accordingly, activities of aqueous species are relabeled as molalities by <span style="color:green">`diagram()`</span> when `IS` is used in the calculation of <span style="color:green">`affinity()`</span>.
## Biochemical example
For the following calculations, we change the nonideality method to `Alberty`; this is a simpler formulation with parameters that are suitable for biochemical species at relatively low temperatures:
```{r Alberty}
oldnon <- nonideal("Alberty")
```
Let's take a look at calculated activity coefficients at two temperatures and their effect on the standard Gibbs energies of formation (Δ*G*°<sub>*f*</sub>) of species with different charge:
```{r subcrt_IS}
subcrt(c("MgATP-2", "MgHATP-", "MgH2ATP"),
T = c(25, 100), IS = c(0, 0.25), property = "G")$out
```
The logarithms of the activity coefficients (`loggam`) are more negative for the higher-charged species, as well as at higher temperature, and have a stabilizing effect.
That is, the adjusted Gibbs energies at *I* > 0 are less than the standard Gibbs energies at *I* = 0.
We can use these calculations to make some speciation plots, similar to Figures 1.2--1.5 in Alberty (2003).
These figures show the distribution of differently charged species of adenosine triphosphate (ATP) as a function of pH, and the average number of H<sup>+</sup> and Mg<sup>+2</sup> bound to ATP in solution as a function of pH or pMg (-log*a*<sub>Mg<sup>+2</sup></sub>).
Use <span style="color:green">`info()`</span> to see what ATP species are available.
The sources of high-temperature thermodynamic data for these species are two papers by LaRowe and Helgeson [-@LH06a; -@LH06b].
```{r info_ATP, results="hide"}
info(" ATP")
```
The plots for this system in Alberty's book were made for *I* = 0.25 M and *T* = 25 °C.
As a demonstration of CHNOSZ's capabilities, we can assign a temperature of 100 °C.
```{r T_100}
T <- 100
```
Use the following commands to set the basis species, add the variously protonated ATP species, calculate the affinities of the formation reactions, equilibrate the system, and make a degree of formation (α) or mole fraction diagram.
This is similar to Figure 1.3 of Alberty (2003), but is calculated for *I* = 0 M and *T* = 100 °C:
```{marginfigure}
To make the code more readable, commands for plotting titles and legends are not shown.
All of the commands are available in the source of this document.
```
```{r ATP, eval=FALSE, echo=2:6}
par(mfrow = c(1, 4), mar = c(3.1, 3.6, 2.1, 1.6), mgp = c(1.8, 0.5, 0))
basis("MgCHNOPS+")
species(c("ATP-4", "HATP-3", "H2ATP-2", "H3ATP-", "H4ATP"))
a <- affinity(pH = c(3, 9), T = T)
e <- equilibrate(a)
d <- diagram(e, alpha = TRUE, tplot = FALSE)
title(main = describe.property("T", T))
alphas <- do.call(rbind, d$plotvals)
nH <- alphas * 0:4
Hlab <- substitute(italic(N)[H^`+`])
plot(a$vals[[1]], colSums(nH), type = "l", xlab = "pH", ylab=Hlab, lty=2, col=2)
a <- affinity(pH = c(3, 9), IS = 0.25, T = T)
e <- equilibrate(a)
d <- diagram(e, alpha = TRUE, plot.it = FALSE)
alphas <- do.call(rbind, d$plotvals)
nH <- alphas * 0:4
lines(a$vals[[1]], colSums(nH))
legend("topright", legend = c("I = 0 M", "I = 0.25 M"), lty = 2:1, col = 2:1, cex = 0.8)
ATP.H <- substitute("ATP and H"^`+`)
title(main = ATP.H)
species(c("MgATP-2", "MgHATP-", "MgH2ATP", "Mg2ATP"), add = TRUE)
Hplot <- function(pMg, IS = 0.25) {
basis("Mg+2", -pMg)
a <- affinity(pH = c(3, 9), IS = IS, T = T)
e <- equilibrate(a)
d <- diagram(e, alpha = TRUE, plot.it = FALSE)
alphas <- do.call(rbind, d$plotvals)
NH <- alphas * c(0:4, 0, 1, 2, 0)
lines(a$vals[[1]], colSums(NH), lty = 7 - pMg, col = 7 - pMg)
}
plot(c(3, 9), c(0, 2), type = "n", xlab = "pH", ylab = Hlab)
lapply(2:6, Hplot)
legend("topright", legend = paste("pMg = ", 2:6), lty = 5:1, col = 5:1, cex = 0.8)
ATP.H.Mg <- substitute("ATP and H"^`+`~"and Mg"^`+2`)
title(main = ATP.H.Mg)
Mgplot <- function(pH, IS = 0.25) {
basis("pH", pH)
a <- affinity(`Mg+2` = c(-2, -7), IS = IS, T = T)
e <- equilibrate(a)
d <- diagram(e, alpha = TRUE, plot.it = FALSE)
alphas <- do.call(rbind, d$plotvals)
NMg <- alphas * species()$`Mg+`
lines(-a$vals[[1]], colSums(NMg), lty = 10 - pH, col = 10 - pH)
}
Mglab <- substitute(italic(N)[Mg^`+2`])
plot(c(2, 7), c(0, 1.2), type = "n", xlab = "pMg", ylab = Mglab)
lapply(3:9, Mgplot)
legend("topright", legend = paste("pH = ", 3:9), lty = 7:1, col = 7:1, cex = 0.8)
title(main = ATP.H.Mg)
```
Note that we have saved the numeric results of <span style="color:green">`diagram()`</span>, i.e. the degrees of formation of the species (α).
With that, we can calculate and plot the average number of protons bound per ATP molecule.
To do so, we use R's `rbind()` and `do.call()` to turn `alpha` into a matrix, then multiply by the number of protons bound to each species, and sum the columns to get the total (i.e. average proton number, *N*<sub>H<sup>+</sup></sub>):
```{r ATP, eval=FALSE, echo=8:11}
```
Adding the `IS` argument to <span style="color:green">`affinity()`</span>, we can now plot *N*<sub>H<sup>+</sup></sub> at the given ionic strength.
Here we set `plot.it = FALSE` in <span style="color:green">`diagram()`</span> because we use the computed α to make our own plot.
This is similar to Figure 1.3 of Alberty (2003), but at higher temperature:
```{r ATP, eval=FALSE, echo=12:17}
```
Next, we add the Mg<sup>+2</sup>-complexed ATP species:
```{r ATP, eval=FALSE, echo=21}
```
Here is a function to calculate and plot *N*<sub>H<sup>+</sup></sub> for a given pMg:
```{r ATP, eval=FALSE, echo=22:30}
```
With that function in hand, we plot the lines corresponding to pMg = 2 to 6.
This is similar to Figure 1.4 of Alberty (2003):
```{r ATP, eval=FALSE, echo=31:32}
```
The next function calculates and plots the average number of Mg<sup>+2</sup> bound to ATP (*N*<sub>Mg<sup>+2</sup></sub>) for a given pH.
Here we multiply `alpha` by the number of Mg<sup>+2</sup> in each species, and negate log*a*<sub>Mg<sup>+2</sup></sub> (the variable used in <span style="color:green">`affinity()`</span>) to get pMg:
```{r ATP, eval=FALSE, echo=36:44}
```
Using that function, we plot the lines corresponding to pH = 3 to 9.
This is similar to Figure 1.5 of Alberty (2003):
```{r ATP, eval=FALSE, echo=45:47}
```
<p>
```{r ATP, fig.fullwidth=TRUE, fig.width=10, fig.height=2.5, dpi=hidpi, out.width="100%", echo=FALSE, message=FALSE, results="hide", fig.cap="Binding of H<sup>+</sup> and Mg<sup>+2</sup> to ATP at 100 °C and *I* = 0 M (first plot) or *I* = 0.25 M (third and fourth plots).", cache=TRUE, pngquant=pngquant, timeit=timeit}
```
</p>
We have calculated the distribution of ATP species and average binding number of H<sup>+</sup> and Mg<sup>+2</sup> for given pH, pMg, ionic strength, and temperature.
Accounting for the distribution of chemical species lends itself to thermodynamic models for reactions between reactants that have multiple ionized and complexed states.
In contrast, Alberty (2003) and others propose models for biochemical reactions where the ionized and complexed species are combined into a single representation.
Those models invoke Legendre-transformed thermodynamic properties, such as transformed Gibbs energies that are tabulated for specified pH, pMg, and ionic strength.
Although the conceptual pathways are different, the two approaches lead to equivalent results concerning the energetics of the overall reactions and the conditions for equilibrium [@SVI12].
The example here shows how the required calculations can be performed at the species level using conventional standard Gibbs energies for species referenced to infinite dilution (zero ionic strength).
The effects of ionic strength are modeled "on the fly" in CHNOSZ by setting the `IS` argument in <span style="color:green">`subcrt()`</span> or <span style="color:green">`affinity()`</span> to invoke the nonideality model on top of the standard Gibbs energies of species.
Now that we're finished, we can reset the nonideality method to the default.
(This really isn't needed here, because there aren't any nonideality calculations below):
```{r oldnon}
nonideal(oldnon)
```
# Proteins
Proteins in CHNOSZ are handled a little bit differently from other species.
Amino acid group additivity is used to obtain the thermodynamic properties of proteins.
Therefore, CHNOSZ has a data file with amino acid compositions of selected proteins, as well as functions for reading and downloading amino acid sequence data.
When proteins in CHNOSZ are identified by name, they include an underscore, such as in `LYSC_CHICK` (chicken lysozyme C).
Use <span style="color:green">`pinfo()`</span> to search for one or more proteins by name; multiple proteins from the same organism can be specified using the `organism` argument.
The name search returns the rownumbers of `thermo()$protein` (i.e. `iprotein`, the protein indices).
Supply those protein indices to <span style="color:green">`pinfo()`</span> to get the amino acid compositions:
```{r pinfo_LYSC_CHICK}
p1 <- pinfo("LYSC_CHICK")
p2 <- pinfo(c("SHH", "OLIG2"), "HUMAN")
pinfo(c(p1, p2))
```
The length and chemical formula of one or more proteins are returned by <span style="color:green">`protein.length()`</span> and <span style="color:green">`protein.formula()`</span>.
We can calculate the formula of the protein, and the per-residue formula, and show that both have the same average oxidation state of carbon:
```{marginfigure}
These functions accept either names or the protein indices (`iprotein`).
```
```{r formula_LYSC_CHICK}
pl <- protein.length("LYSC_CHICK")
pf <- protein.formula("LYSC_CHICK")
list(length = pl, protein = pf, residue = pf / pl,
ZC_protein = ZC(pf), ZC_residue = ZC(pf / pl))
```
## Group additivity and ionization
The group additivity calculations for proteins are based on equations and data from @AH00, @DLH06, and @LD12.
There are two major options for the calculations: whether to calculate properties for crystalline or aqueous groups, and, for the latter, whether to model the ionization of the sidechain and terminal groups as a function of pH (and *T* and *P*).
By default, additivity of aqueous groups is used, but the ionization calculations are not available in <span style="color:green">`subcrt()`</sub>:
```{r subcrt_LYSC_CHICK, message=FALSE}
subcrt("LYSC_CHICK")$out[[1]][1:6, ]
```
Let's compare experimental values of heat capacity of four proteins, from @PM90, with those calculated using group additivity.
We divide Privalov and Makhatadze's experimental values by the lengths of the proteins to get per-residue values, then plot them.
```{r protein_Cp, fig.margin=TRUE, fig.width=4, fig.height=4, small.mar=TRUE, out.width="100%", echo=FALSE, message=FALSE, fig.cap='The heat capacity calculated by group additivity closely approximates experimental values for aqueous proteins. For a related figure showing the effects of ionization in the calculations, see <span style="color:blue">`?ionize.aa`</span>.', cache=TRUE, pngquant=pngquant, timeit=timeit}
PM90 <- read.csv(system.file("extdata/cpetc/PM90.csv", package = "CHNOSZ"))
plength <- protein.length(colnames(PM90)[2:5])
Cp_expt <- t(t(PM90[, 2:5]) / plength)
matplot(PM90[, 1], Cp_expt, type = "p", pch = 19,
xlab = axis.label("T"), ylab = axis.label("Cp0"), ylim = c(110, 280))
for(i in 1:4) {
pname <- colnames(Cp_expt)[i]
aq <- subcrt(pname, "aq", T = seq(0, 150))$out[[1]]
cr <- subcrt(pname, "cr", T = seq(0, 150))$out[[1]]
lines(aq$T, aq$Cp / plength[i], col = i)
lines(cr$T, cr$Cp / plength[i], col = i, lty = 2)
}
legend("right", legend = colnames(Cp_expt),
col = 1:4, pch = 19, lty = 1, bty = "n", cex = 0.9)
legend("bottomright", legend = c("experimental", "calculated (aq)",
"calculated (cr)"), lty = c(NA, 1, 2), pch = c(19, NA, NA), bty = "n")
```
```{r protein_Cp, eval=FALSE, echo=1:5}
```
The loop calculates the properties of each protein using group additivity with aqueous or crystalline groups, then plots the per-residue values.
```{r protein_Cp, eval=FALSE, echo=-(1:5)}
```
Although <span style="color:green">`subcrt()`</span> has no provision for protein ionization, the properties of ionization can be calculated via <span style="color:green">`affinity()`</span>, which calls <span style="color:green">`ionize.aa()`</span> if a charged species is in the basis.
```{marginfigure}
Whether to calculate properties using aqueous or crystalline groups is determined by the value of `thermo()\$opt\$state`; if it is changed from its default of `aq` to `cr`, no ionization is possible.
```
The following plot shows the calculated affinity of reaction between nonionized proteins and their ionized forms as a function of pH.
Charged and uncharged sets of basis species are used to to activate and suppress the ionization calculations.
The calculation of affinity for the ionized proteins returns multiple values (as a function of pH), but there is only one value of affinity returned for the nonionized proteins, so we need to use R's `as.numeric()` to avoid subtracting nonconformable arrays:
```{r protein_ionization, fig.margin=TRUE, fig.width=4, fig.height=4, small.mar=TRUE, out.width="100%", echo=FALSE, results="hide", message=FALSE, fig.cap='Affinity of ionization of proteins. See [<span style="color:blue">demo(ionize)</span>](../demo) for ionization properties calculated as a function of temperature and pH.', cache=TRUE, pngquant=pngquant, timeit=timeit}
ip <- pinfo(c("CYC_BOVIN", "LYSC_CHICK", "MYG_PHYCA", "RNAS1_BOVIN"))
basis("CHNOS+")
a_ion <- affinity(pH = c(0, 14), iprotein = ip)
basis("CHNOS")
a_nonion <- affinity(iprotein = ip)
plot(c(0, 14), c(50, 300), xlab = "pH", ylab = quote(italic(A/2.303*RT)), type="n")
for(i in 1:4) {
A_ion <- as.numeric(a_ion$values[[i]])
A_nonion <- as.numeric(a_nonion$values[[i]])
lines(a_ion$vals[[1]], A_ion - A_nonion, col=i)
}
legend("topright", legend = a_ion$species$name,
col = 1:4, lty = 1, bty = "n", cex = 0.9)
```
```{r protein_ionization, eval=FALSE}
```
The affinity is always positive, showing the strong energetic drive for ionization of proteins in aqueous solution.
The degrees of ionization of amino and carboxyl groups increase at low and high pH, respectively, giving rise to the U-shaped lines.
There, we used the indices returned by <span style="color:green">`pinfo()`</span> in the `iprotein` argument of <span style="color:green">`affinity()`</span> to specify the proteins in the calculation.
That approach utilizes some optimizations that can be realized due to group additivity, and is useful for calculations involving many proteins.
An alternative, but slower, approach is to identify the proteins to <span style="color:green">`species()`</span>; this produces results that are equivalent to using the `iprotein` argument:
<!-- this is needed because the figure above might be cached, preventing the call to basis() there -->
```{r basis_CHNOS, echo=FALSE, results="hide"}
basis("CHNOS")
```
```{r species_protein, results="hide", message=FALSE, echo=1:2}
species(c("CYC_BOVIN", "LYSC_CHICK", "MYG_PHYCA", "RNAS1_BOVIN"))
a_nonion_species <- affinity()
```
```{r nonion_species_values}
unlist(a_nonion_species$values)
```
```{marginfigure}
The `ispecies` index (top) refers to the rownumber of `thermo()\$species`; that is distinct from the `iprotein` index (bottom, printed as negative integers), which refers to the rownumber of `thermo()\$protein`.
```
```{r nonion_values}
unlist(a_nonion$values)
```
## Chemical analysis of proteins
Functions in CHNOSZ make it easy to get the chemical formulas of proteins from their amino acid compositions.
Calculations based on the formulas, such as the average oxidation state of carbon (`r zc`), and the coefficients of basis species in formation reactions, are also available.
Let's compare the `r zc` of Rubisco with optimal growth temperature of organisms, as shown in Figure 6a of @Dic14.
First we read a CSV file with the IDs of the proteins and the optimal growth temperatures (*T*<sub>opt</sub>); the midpoint of the range of *T*<sub>opt</sub> is used for plotting.
Then we use <span style="color:green">`read.fasta()`</span> to read a FASTA file holding the amino acid sequences of the proteins; the function returns a data frame with the amino acid counts.
To put the proteins in the right order, the IDs in the CSV file are matched to the names of the proteins in the FASTA file.
Then, we calculate `r zc` from the formulas of the proteins.
Next, point symbols are assigned according to domain (Archaea, Bacteria, Eukaryota); numbers inside the symbols show the ordering of *T*<sub>opt</sub> in three temperature ranges (0--35 °C, 37.5--60 °C, and 65--100 °C).
```{r rubisco_svg, echo=FALSE, results="hide", fig.margin=TRUE, fig.width=4, fig.height=4, small.mar=TRUE, out.width="100%", fig.ext='svg', custom.plot=TRUE, embed.tag=TRUE, fig.cap='Average oxidation state of carbon in Rubisco compared with optimal growth temperature of organisms. **This is an interactive image.** Move the mouse over the points to show the names of the organisms, and click to open a reference in a new window. (Made with [**RSVGTipsDevice**](https://cran.r-project.org/package=RSVGTipsDevice) using code that can be found in the source of this document.)'}
## copies the premade SVG image to the knitr figure path
file.copy("rubisco.svg", fig_path(".svg"))
## the code for making the SVG image -- not "live" in the vignette because RSVGTipsDevice isn't available on Windows
#if(require(RSVGTipsDevice)) {
# datfile <- system.file("extdata/cpetc/rubisco.csv", package = "CHNOSZ")
# fastafile <- system.file("extdata/protein/rubisco.fasta", package = "CHNOSZ")
# dat <- read.csv(datfile)
# aa <- read.fasta(fastafile)
# Topt <- (dat$T1 + dat$T2) / 2
# idat <- match(dat$ID, substr(aa$protein, 4, 9))
# aa <- aa[idat, ]
# ZC <- ZC(protein.formula(aa))
# pch <- match(dat$domain, c("E", "B", "A")) - 1
# col <- match(dat$domain, c("A", "B", "E")) + 1
# # because the tooltip titles in the SVG file are shown by recent browsers,
# # we do not need to draw the tooltips explicitly, so set toolTipMode=0
# devSVGTips("rubisco.svg", toolTipMode=0, title="Rubisco")
# par(cex=1.4)
# # unfortunately, plotmath can't be used with devSVGTips,
# # so axis labels here don't contain italics.
# plot(Topt, ZC, type="n", xlab="T, °C", ylab="ZC")
# n <- rep(1:9, 3)
# for(i in seq_along(Topt)) {
# # adjust cex to make the symbols look the same size
# cex <- ifelse(pch[i]==1, 2.5, 3.5)
# points(Topt[i], ZC[i], pch=pch[i], cex=cex, col=col[i])
# URL <- dat$URL[i]
# setSVGShapeURL(URL, target="_blank")
# setSVGShapeContents(paste0("<title>", dat$species[i], "</title>"))
# text(Topt[i], ZC[i], n[i], cex = 1.2)
# }
# abline(v = c(36, 63), lty = 2, col = "grey")
# legend("topright", legend = c("Archaea", "Bacteria", "Eukaryota"),
# pch = c(2, 1, 0), col = 2:4, cex=1.5, pt.cex = c(3, 2.3, 3), bty="n")
# dev.off()
#}
```
```{r rubisco_ZC, fig.keep="none", message=FALSE}
datfile <- system.file("extdata/cpetc/rubisco.csv", package = "CHNOSZ")
fastafile <- system.file("extdata/protein/rubisco.fasta", package = "CHNOSZ")
dat <- read.csv(datfile)
aa <- read.fasta(fastafile)
Topt <- (dat$T1 + dat$T2) / 2
idat <- match(dat$ID, substr(aa$protein, 4, 9))
aa <- aa[idat, ]
ZC <- ZC(protein.formula(aa))
pch <- match(dat$domain, c("E", "B", "A")) - 1
col <- match(dat$domain, c("A", "B", "E")) + 1
plot(Topt, ZC, pch = pch, cex = 2, col = col,
xlab = expression(list(italic(T)[opt], degree*C)),
ylab = expression(italic(Z)[C]))
text(Topt, ZC, rep(1:9, 3), cex = 0.8)
abline(v = c(36, 63), lty = 2, col = "grey")
legend("topright", legend = c("Archaea", "Bacteria", "Eukaryota"),
pch = c(2, 1, 0), col = 2:4, pt.cex = 2)
```
Let's look at the different ways of representing the chemical compositions of the proteins.
<span style="color:green">`protein.basis()`</span> returns the stoichiometry for the formation reaction of each proteins.
Dividing by <span style="color:green">`protein.length()`</span> gives the per-residue reaction coefficients (*n*̅).
Using the set of basis species we have seen before (CO<sub>2</sub>, NH<sub>3</sub>, H<sub>2</sub>S, `r h2o`, `r o2`) there is a noticeable correlation between *n*̅<sub>`r o2`</sub> and `r zc`, but even more so between *n*̅<sub>`r h2o`</sub> and `r zc` (shown in the plots on the left).
```{marginfigure}
The calculation of *Z*<sub>C</sub>, which sums elemental ratios, is not affected by the choice of basis species.
```
The `QEC` keyword to <span style="color:red">`basis()`</span> loads basis species including three amino acids (glutamine, glutamic acid, cysteine, `r h2o`, `r o2`).
This basis strengthens the relationship between `r zc` and *n*̅<sub>`r o2`</sub>, but weakens that between `r zc` and *n*̅<sub>`r h2o`</sub> (shown in the plots on the right).
```{r rubisco_O2, fig.margin=TRUE, fig.width=4, fig.height=4, small.mar=TRUE, out.width="100%", echo=FALSE, results="hide", message=FALSE, fig.cap="Elemental compositions of proteins projected into different sets of basis species.", cache=TRUE, pngquant=pngquant, timeit=timeit}
layout(matrix(1:4, nrow = 2))
par(mgp = c(1.8, 0.5, 0))
pl <- protein.length(aa)
ZClab <- axis.label("ZC")
nO2lab <- expression(bar(italic(n))[O[2]])
nH2Olab <- expression(bar(italic(n))[H[2]*O])
lapply(c("CHNOS", "QEC"), function(thisbasis) {
basis(thisbasis)
pb <- protein.basis(aa)
nO2 <- pb[, "O2"] / pl
plot(ZC, nO2, pch = pch, col = col, xlab = ZClab, ylab = nO2lab)
nH2O <- pb[, "H2O"] / pl
plot(ZC, nH2O, pch = pch, col = col, xlab = ZClab, ylab = nH2Olab)
mtext(thisbasis, font = 2)
})
```
```{r rubisco_O2, eval=FALSE}
```
By projecting the compositions of proteins into the `QEC` set of basis species, *n*̅<sub>`r o2`</sub> emerges as a strong indicator of oxidation state, while *n*̅<sub>`r h2o`</sub> is a relatively uncorrelated (i.e. independent) compositional variable.
These independent variables make it easier to distinguish the effects of oxidation and hydration state in proteomic datasets [@DYT20].
## Normalization to residues
As with other systems, a balance must be chosen for calculations of the metastable equilibrium distribution for proteins.
Balancing on the number of backbone units (the sequence length) seems a reasonable choice given the polymeric structure of proteins.
```{marginfigure}
Balancing on one of the basis species remains a possibility, using the `balance` argument in <span style="color:green">`equilibrate()`</span> or <span style="color:green">`diagram()`</span>.
```
However, there is an additional consideration: owing to the large size of proteins compared to the basis species, the distribution of *proteins* in metastable equilibrium has many orders of magnitude separation between the activities of the dominant and less-dominant proteins.
The metastable coexistence of the *residues* (i.e. per-residue formulas, or residue equivalents) of the same proteins spans a much smaller range of chemical activities.
In CHNOSZ, the calculation of metastable equilibrium activities of the residue equivalents is referred to as *normalization*.
Let's look at the metastable equilibrium distribution of selected proteins in the ER-to-Golgi location of *S. cerevisiae* (yeast) (this example is taken from @Dic09)
Here, we list the names and relative abundances of proteins taken from the YeastGFP study of @GHB_03.
There are six proteins identified in the ER-to-Golgi location; one has NA abundance, so it is excluded from the comparisons:
```{marginfigure}
This can be done programmatically using data from the YeastGFP study that are in the [JMDplots](https://github.com/jedick/JMDplots) package:
<br>
`y <- JMDplots::yeastgfp("ER.to.Golgi")`
<br>
`ina <- is.na(y[["abundance"]])`
<br>
`aa <- JMDplots::yeast.aa(y$protein[!ina])`
<br>
`ip <- add.protein(aa)`
```
```{r yeastgfp}
protein <- c("YDL195W", "YHR098C", "YIL109C", "YLR208W", "YNL049C", "YPL085W")
abundance <- c(1840, 12200, NA, 21400, 1720, 358)
ina <- is.na(abundance)
```
Next, we find the rownumbers of the proteins in `thermo()$protein`:
```{r add_protein_yeast, message=FALSE}
ip <- match(protein[!ina], thermo()$protein$protein)
```
The YeastGFP study reported absolute abundances of molecules, but the thermodynamic calculations give relative chemical activities of the proteins.
In order to make a comparison between them, we use <span style="color:green">`unitize()`</span> to scale the abundances or activities of proteins (in logarithmic units) such that the total abundance or activity of residue equivalents is unity.
To do that, we must have the lengths of the proteins.
Here, the first call to <span style="color:green">`unitize()`</span> generates equal logarithms of activities of proteins for unit total activity of residues; this is used as the reference state for <span style="color:green">`affinity()`</span>.
The second call to <span style="color:green">`unitize()`</span> scales the logarithms of experimental abundances for unit total activity of residues; this is used for comparison with the theoretical results:
```{r unitize}
pl <- protein.length(ip)
logact <- unitize(numeric(5), pl)
logabundance <- unitize(log10(abundance[!ina]), pl)
```
Now we can load the proteins and calculate their activities in metastable equilibrium as a function of `r logfO2`.
The commented line uses <span style="color:red">`add.OBIGT()`</span> to load group additivity parameters that were present in older versions of CHNOSZ (Dick et al., 2006).
The default database contains newer group additivity parameters for the sidechain groups of methionine (LaRowe and Dick, 2012) and glycine and the protein backbone [@Kit14].
```{r yeastplot, eval=FALSE, echo=1:5}
par(mfrow = c(1, 3))
basis("CHNOS+")
a <- affinity(O2 = c(-80, -73), iprotein = ip, loga.protein = logact)
e <- equilibrate(a)
diagram(e, ylim = c(-5, -2), col = 1:5, lwd = 2)
e <- equilibrate(a, normalize = TRUE)
diagram(e, ylim = c(-5, -2.5), col = 1:5, lwd = 2)
abline(h = logabundance, lty = 1:5, col = 1:5)
```
Whoa! The proteins look very non-coexistent in metastable equilibrium.
We get a different view by considering per-residue rather than per-protein reactions, through the `normalize` argument for <span style="color:green">`equilibrate()`</span>:
```{marginfigure}
The normalization step is followed by conversion of activities of residues to activities of proteins; that conversion can be skipped using the `as.residue` argument in <span style="color:green">`equilibrate()`</span>.
```
```{r yeastplot, eval=FALSE, echo=6:8}
```
The experimental relative abundances are plotted as thin horizontal lines with the same style and color as the thicker curved lines calculated for metastable equilibrium.
With the exception of YNL049C, the correspondence between the calculations and experiments looks to be greatest near the middle-left part of the figure.
```{r yeastplot, fig.width=6, fig.height=2.5, dpi=hidpi, out.width="100%", echo=FALSE, message=FALSE, results="hide", cache=TRUE, fig.cap="ER-to-Golgi proteins: calculations without and with length normalization.", pngquant=pngquant, timeit=timeit}
```
## Getting amino acid compositions
In the Rubisco example above, we saw the use of <span style="color:green">`read.fasta()`</span> to read amino acid sequences from a FASTA file.
There are several other methods for inputting amino acid compositions.
R's `read.csv()` can be used to read amino acid compositions from a CSV file with the same columns that are present in `thermo()$protein`.
Note the use of `as.is = TRUE` to prevent reading character data as factors.
The `nrows` argument can be added to read that number of rows:
```{r read_csv}
file <- system.file("extdata/protein/POLG.csv", package = "CHNOSZ")
aa_POLG <- read.csv(file, as.is = TRUE, nrows = 5)
```
<span style="color:green">`read.fasta()`</span> reads a FASTA file and returns the amino acid compositions of the sequences.
The `iseq` argument can be used to read those sequences from the file:
```{r read_fasta, message=FALSE}
file <- system.file("extdata/protein/EF-Tu.aln", package = "CHNOSZ")
aa_Ef <- read.fasta(file, iseq = 1:2)
```
<span style="color:green">`seq2aa()`</span> counts the amino acids in a user-supplied sequence and generates a data frame of the amino acid composition:
```{marginfigure}
See also <span style="color:blue">`?count.aa`</span>, which can process both protein and nucleic acid sequences.
```
```{r seq2aa}
aa_PRIO <- seq2aa("
MANLGCWMLVLFVATWSDLGLCKKRPKPGGWNTGGSRYPGQGSPGGNRYPPQGGGGWGQP
HGGGWGQPHGGGWGQPHGGGWGQPHGGGWGQGGGTHSQWNKPSKPKTNMKHMAGAAAAGA
VVGGLGGYMLGSAMSRPIIHFGSDYEDRYYRENMHRYPNQVYYRPMDEYSNQNNFVHDCV
NITIKQHTVTTTTKGENFTETDVKMMERVVEQMCITQYERESQAYYQRGSSMVLFSSPPV
ILLISFLIFLIVG
", "PRIO_HUMAN")
```
These amino acid compositions can be processed using functions such as <span style="color:green">`protein.length()`</span> and <span style="color:green">`protein.formula()`</span>:
```{r protein_length}
myaa <- rbind(aa_Ef, aa_PRIO)
protein.length(myaa)
```
# Sources of thermodynamic data
An attempt has been made to assemble a default database that has no major inconsistencies between species.
As the database includes thermodynamic data from many sources, it can not be guaranteed to be fully internally consistent.
For crucial problems, check not only the accuracy of entries in the database, but also the *suitability of the data* for your problem.
If there are any doubts, consult the primary sources.
Most of the species in OBIGT have parameters for one of two models for calculating thermodynamic properties.
The coefficients in these models are indicated by the column names with a dot, for example `a1.a`.
Most aqueous species use the revised Helgeson-Kirkham-Flowers (HKF) equations (text before the dot), and crystalline, gas and liquid species other than `r h2o` use a polynomial equation for heat capacity.
See <span style="color:blue">`?hkf`</span> and <span style="color:blue">`?cgl`</span> for information about the equations used for thermodynamic properties.
Besides this vignette, here's where to look for more information about the database:
- Be sure to read the help page at <span style="color:blue">`?thermo`</span> for information about the format of the OBIGT data frame.
- See the vignette [<span style="color:blue">*OBIGT thermodynamic database*</span>](OBIGT.html) for a summary of all sources for the default database and optional data files.
- See the vignette [<span style="color:blue">*Customizing the thermodynamic database*</span>](custom_data.html) for a broader description of the structure of OBIGT, data entry conventions, and examples of adding species to the database.
## Viewing data sources: <span style="color:green">`thermo.refs()`</span>
The OBIGT database lists one or two sources for each entry, and citation information for the sources is listed in `thermo()$refs`.
You can locate and view the references with <span style="color:green">`thermo.refs()`</span>.
Running the function without any arguments opens a browser window with the complete table of references.
```{marginfigure}
See the vignette [<span style="color:blue">*OBIGT thermodynamic database*</span>](OBIGT.html) for a more nicely formatted presentation of the sources of thermodynamic data, along with notes and additional comments.
```
Where available, links to the web page for the articles and books are displayed:
```{r thermo_refs_table, eval=FALSE}
thermo.refs() ## shows table in a browser
```
A numeric argument to <span style="color:green">`thermo.refs()`</span> gives one or more species indices for which to get the references:
```{r width180, include=FALSE}
```
```{r thermo_refs_numeric}
iATP <- info("ATP-4")
iMgATP <- info("MgATP-2")
thermo.refs(c(iATP, iMgATP))
```
A character argument gives the source key(s):
```{r thermo_refs_character}
thermo.refs(c("HDNB78", "MGN03"))
```
If the argument holds the result of <span style="color:green">`subcrt()`</span>, references for all species in the reaction are returned:
```{marginfigure}
The exception is H<sub>2</sub>O.
With the default settings, thermodynamic properties for H<sub>2</sub>O are derived from SUPCRT92 (Johnson et al., 1992).
```
```{r thermo_refs_subcrt, message=FALSE}
sres <- subcrt(c("C2H5OH", "O2", "CO2", "H2O"), c(-1, -3, 2, 3))
thermo.refs(sres)
```
```{r width80, include=FALSE}
```
The URLs of the references can be copied to a browser, or opened using R's `browseURL()`:
```{r thermo_refs_browse, eval=FALSE}
iFo <- info("forsterite")
ref <- thermo.refs(iFo)
browseURL(ref$URL) ## opens a link to worldcat.org
```
## Default database
Thermodynamic properties of minerals in the default database are mostly taken from @Ber88 (including silicates, aluminosilicates, calcite, dolomite, hematite, and magnetite) and @HDNB78 (native elements, sulfides, halides, sulfates, and selected carbonates and oxides that do not duplicate any in the Berman dataset).
Minerals are identified by the state `cr`, and (for the Helgeson dataset) `cr2`, `cr3`, etc. for higher-temperature polymorphs.
Compared to SUPCRT92/SLOP98 (see below), the default database include updates for aqueous Al species [@TS01], Au species [@PAB_14] (see [<span style="color:blue">`demo(gold)`</span>](../demo)), and arsenic-bearing aqueous species and minerals, as compiled in the SUPCRTBL package [@ZZL_16].
This list of updates is incomplete; see the vignette [<span style="color:blue">*OBIGT thermodynamic database*</span>](OBIGT.html) for a detailed list of data sources.
## Optional data files
Some optional datasets can be activated by using <span style="color:red">`add.OBIGT()`</span>. The first couple of these contain data that have been replaced by or are incompatible with later updates; the superseded data are kept here to reproduce published calculations and for comparison with the newer data:
<span style="color:red">`add.OBIGT("SUPCRT92")`</span> -- This file contains data for minerals from SUPCRT92 (mostly Helgeson et al., 1978) that have been replaced by the Berman data set.
<span style="color:red">`add.OBIGT("SLOP98")`</span> -- This file contains data from `slop98.dat` or later slop files, from Everett Shock's GEOPIG group at Arizona State University, that were previously used in CHNOSZ but have been replaced by more recent data updates.
Some calculations using the older data are shown in [this vignette](#complete-equilibrium-solubility).
The updates for these data have been taken from various publications ([LaRowe and Dick, 2012](https://doi.org/10.1016/j.gca.2011.11.041); [Kitadai, 2014](https://doi.org/10.1007/s00239-014-9616-1); [Azadi et al., 2019](https://doi.org/10.1016/j.fluid.2018.10.002))
A comparison of log*K* of metal-glycinate complexes using the updated data is in [<span style="color:blue">`demo(glycinate)`</span>](../demo).
The next three optional datasets are provided to support newer data or models:
<span style="color:red">`add.OBIGT("DEW")`</span> -- These are parameters for aqueous species that are intended for use with the Deep Earth Water (DEW) model [@SHA14].
You should also run <span style="color:red">`water("DEW")`</span> to activate the equations in the model; then, they will be used by <span style="color:green">`subcrt()`</span> and <span style="color:green">`affinity()`</span>.
Examples are in [<span style="color:blue">`demo(DEW)`</span>](../demo).
<span style="color:red">`add.OBIGT("AD")`</span> -- These data are used in the Akinfiev-Diamond model for aqeuous nonelectrolytes [@AD03].
<span style="color:red">`add.OBIGT("GEMSFIT")`</span> -- Thermodynamic data for aqueous species in the system Ca-Mg-Na-K-Al-Si-O-H-C-Cl obtained from global optimization of Gibbs energies with the GEMSFIT package [@MWKL17].
<span style="color:red">`add.OBIGT("AS04")`</span> -- This file has data for aqueous `r sio2` from @AS04 and modified HSiO<sub>3</sub><sup>-</sup>.
These data reflect a revised (higher) solubility of quartz compared to previous compilations, but are not included in the default database in order to maintain compatibility with existing data for minerals that are linked to the older aqueous `r sio2` data.
See [<span style="color:blue">`demo(aluminum)`</span>](../demo) for an example.
## Cross-checking data entries
<span style="color:green">`info()`</span> automatically performs some cross-checks of the thermodynamic data.
```{marginfigure}
This only checks the parameters for individual species, not the internal consistency among different species.
```
Given a numeric species index, it runs <span style="color:green">`check.EOS()`</span>, which compares the given values of *C*<sub>*P*</sub>° and *V*° with those calculated from the HKF or heat capacity parameters.
<span style="color:green">`info()`</span> also runs <span style="color:green">`check.GHS()`</span>, which compares the given value of Δ*G*°<sub>*f*</sub> with that calculated from Δ*H*°<sub>*f*</sub>, *S*°, and the entropy of the elements [@CWM89] in the chemical formula of the species.
If any of the differences is above a certain tolerance (see <span style="color:blue">`?check.GHS`</span> for details), a message to this effect is produced.
Some species in the default and optional databases are known to have inconsistent parameters.
For instance, we can check the data for the trisulfur radical ion (S<sub>3</sub><sup>-</sup>) from @PD15:
```{r info_S3, results="hide"}
info(info("S3-"))
```
The calculated value of Δ*G*°<sub>*f*</sub> is `r round(suppressMessages(check.GHS(info(info("S3-")))))` cal mol<sup>-1</sup> higher than the given value.
After checking for any typographical errors in the entries for Δ*G*°<sub>*f*</sub>, Δ*H*°<sub>*f*</sub>, *S*°, and the chemical formula, the literature may need to be revisited for further clarification.
All of the species with inconsistencies detected in this manner, in both OBIGT and the optional data files, are listed in the file `OBIGT_check.csv`.
```{r check_OBIGT}
file <- system.file("extdata/adds/OBIGT_check.csv", package = "CHNOSZ")
dat <- read.csv(file, as.is = TRUE)
nrow(dat)
```
Without additional information, there is often no clear strategy for "fixing" these inconsistent data, and they are provided as-is.
Users are encouraged to send any corrections to the package maintainer.
## Water: SUPCRT92 or IAPWS-95 or DEW
For calculations of the thermodynamic and dielectric properties of liquid and supercritical H<sub>2</sub>O, CHNOSZ uses a Fortran subroutine (`H2O92`) from SUPCRT92 (Johnson et al., 1992).
Alternatively, the IAPWS-95 formulation for thermodynamic properties [@WP02] can be utilized.
In part because of intrinsic thermodynamic differences between SUPCRT92 and IAPWS-95, as well as different equations used in CHNOSZ for calculating the dielectric constant when the IAPWS-95 option is active, this option could introduce inconsistencies with the data for aqueous species in the database and is not recommended for general use in CHNOSZ.
However, the IAPWS-95 equations are useful for other applications, and may be extrapolated to a greater range of *T* and *P* than SUPCRT.
See <span style="color:blue">`?water`</span> for more information, as well as the last example in <span style="color:blue">`?subcrt`</span>, where uncommenting the line for the `IAPWS95` option allows extrapolation to lower temperatures for supercooled water.
An implementation of the Deep Earth Water (DEW) model is also available; see [Optional data](#optional-data) for more information.
# Functions outside the main workflow
Some functions in CHNOSZ lie outside the main workflow described above.
* <span style="color:green">`RH2OBIGT()`</span> implements a group additivity calculation of standard molal thermodynamic properties and equations of state parameters of crystalline and liquid organic molecules from @RH98.
* <span style="color:green">`EOSregress()`</span> and related functions can be used to regress "equation of state" parameters (e.g. coefficients in the HKF equations) from heat capacity and volumetric data. See <span style="color:blue">`?EOSregress`</span> and the vignette [<span style="color:blue">*Regressing thermodynamic data*</span>](eos-regress.html).
* Some functions are available (see <span style="color:blue">`?taxonomy`</span>) to read data from [NCBI taxonomy files](https://www.ncbi.nlm.nih.gov/taxonomy), traverse taxonomic ranks, and get scientific names of taxonomic nodes.
# Citation and contact information
To cite CHNOSZ, use this reference:
```{r citation_CHNOSZ, results="asis", echo = FALSE}
cref <- citation("CHNOSZ")
print(cref[1], style = "html")
```
For the features described in the [<span style="color:blue">multi-metal vignette</span>](multi-metal.html), use this reference:
```{r citation_multimetal, results="asis", echo = FALSE}
print(cref[2], style = "html")
```
If you found a bug or have questions that aren't answered in the documentation please contact the maintainer:
```{r maintainer_CHNOSZ}
maintainer("CHNOSZ")
```
Thank you for reading, and have fun!
> "The real fun of life is this perpetual testing to realize how far out you can go with any potentialities."
>
> `r tufte::quote_footer('--- Richard P. Feynman')`
# Document history
* 2010-09-30 Initial version, titled "Getting started with CHNOSZ".
<!--
* 2011-08-15 Add <span style="color:green">`browse.refs()`</span>; modifying database hint changed to <span style="color:blue">`help(thermo)`</span>.
```{marginfigure}
<span style="color:green">`browse.refs()`</span> was renamed to <span style="color:green">`thermo.refs()`</span> in 2017.
```
-->
* 2012-06-16 Add "More activity diagrams" (section no longer exists).
* 2015-05-14 Add warning about [internal consistency of thermodynamic data](#thermodynamic-database).
* 2017-02-15 Completely rewritten; switch from Sweave to [knitr](https://yihui.org/knitr/) ([Tufte style](https://rstudio.github.io/tufte/)).
* 2019-01-24 Add [section on solubility calculations](#complete-equilibrium-solubility).
View the R Markdown source of this document [on R-Forge](https://r-forge.r-project.org/scm/viewvc.php/pkg/CHNOSZ/vignettes/anintro.Rmd?view=markup&root=chnosz) or in R:
```{r file_edit_anintro, eval=FALSE}
file.edit(system.file("doc/anintro.Rmd", package = "CHNOSZ"))
```
<p>
```{r the_end}
###### ## ## ## ## ###### ##### #####
## ##===## ## \\## ## ## \\ //
###### ## ## ## ## ###### ##### #####
```
</p>
<!-- for finding what versions of packages are on R-Forge and winbuilder
```{r sessionInfo}
sessionInfo()
```
-->
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/vignettes/anintro.Rmd
|
---
title: "Customizing the thermodynamic database"
author: "Jeffrey M. Dick"
output:
html_vignette:
mathjax: null
toc: true
vignette: >
%\VignetteIndexEntry{Customizing the thermodynamic database}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
bibliography: vig.bib
csl: elementa.csl
link-citations: true
---
```{r setup, include = FALSE}
library(CHNOSZ)
options(width = 80)
## Use pngquant to optimize PNG images
library(knitr)
knit_hooks$set(pngquant = hook_pngquant)
pngquant <- "--speed=1 --quality=0-25"
if (!nzchar(Sys.which("pngquant"))) pngquant <- NULL
# Set dpi 20231129
knitr::opts_chunk$set(
dpi = if(nzchar(Sys.getenv("CHNOSZ_BUILD_LARGE_VIGNETTES"))) 100 else 72
)
```
```{r HTML, include = FALSE}
NOTE <- '<span style="background-color: yellow;">NOTE</span>'
# OBIGT columns
model <- '<span style="color: blue;">model</span>'
name <- '<tt style="color: blue;">name</tt>'
abbrv <- '<tt style="color: blue;">abbrv</tt>'
formula <- '<tt style="color: blue;">formula</tt>'
state <- '<tt style="color: blue;">state</tt>'
ref1 <- '<tt style="color: blue;">ref1</tt>'
ref2 <- '<tt style="color: blue;">ref2</tt>'
date <- '<tt style="color: blue;">date</tt>'
E_units <- '<tt style="color: blue;">E_units</tt>'
b <- '<tt style="color: blue;">b</tt>'
c <- '<tt style="color: blue;">c</tt>'
e <- '<tt style="color: blue;">e</tt>'
f <- '<tt style="color: blue;">f</tt>'
lambda <- '<tt style="color: blue;">lambda</tt>'
c1 <- '<tt style="color: blue;">c1</tt>'
c2 <- '<tt style="color: blue;">c2</tt>'
omega <- '<tt style="color: blue;">omega</tt>'
G_ <- '<tt style="color: blue;">G</tt>'
H_ <- '<tt style="color: blue;">H</tt>'
S_ <- '<tt style="color: blue;">S</tt>'
Cp_ <- '<tt style="color: blue;">Cp</tt>'
V_ <- '<tt style="color: blue;">V</tt>'
T_ <- '<tt style="color: blue;">T</tt>'
# CHNOSZ functions
reset_ <- '<code style="color: red;">reset()</code>'
OBIGT_ <- '<code style="color: red;">OBIGT()</code>'
add.OBIGT_ <- '<code style="color: red;">add.OBIGT()</code>'
mod.OBIGT_ <- '<code style="color: red;">mod.OBIGT()</code>'
logB.to.OBIGT_ <- '<code style="color: red;">logB.to.OBIGT()</code>'
basis_ <- '<code style="color: red;">basis()</code>'
species_ <- '<code style="color: red;">species()</code>'
E.units_ <- '<code style="color: red;">E.units()</code>'
info_ <- '<code style="color: green;">info()</code>'
subcrt_ <- '<code style="color: green;">subcrt()</code>'
affinity_ <- '<code style="color: green;">affinity()</code>'
thermo.refs_ <- '<code style="color: green;">thermo.refs()</code>'
thermo_ <- '<code style="color: green;">thermo()</code>'
check.GHS_ <- '<code style="color: green;">check.GHS()</code>'
check.EOS_ <- '<code style="color: green;">check.EOS()</code>'
# Math stuff
logK <- "log <i>K</i>"
logB <- "log β"
F_ <- "F<sup>-</sup>"
Hplus <- "H<sup>+</sup>"
HWO4_ <- "HWO<sub>4</sub><sup>-</sup>"
H2WO4 <- "H<sub>2</sub>WO<sub>4</sub>"
H3WO4F2_ <- "H<sub>3</sub>WO<sub>4</sub>F<sub>2</sub><sup>-</sup>"
# Thermodynamic properties
Cp_0 <- "<i>C<sub>p</sub></i>°"
DG_0 <- "Δ<i>G</i>°"
```
This vignette was compiled on `r Sys.Date()` with CHNOSZ version `r sessionInfo()$otherPkgs$CHNOSZ$Version`.
This vignette will cover some topics about using custom thermodynamic data in CHNOSZ.
The two main functions to remember are `r add.OBIGT_` to add data from a CSV file and `r mod.OBIGT_` to add or modify data through a function interface.
A third function, `r logB.to.OBIGT_`, is provided to fit thermodynamic parameters to experimental formation constants (`r logB`).
Before describing the methods to add or modify data, some notes on the basic structure of the database and data entry conventions are given.
Column names (or parts thereof) are formatted in blue (e.g. `r formula`), and important notes are highlighted in yellow (`r NOTE`).
Function names in CHNOSZ are colored red for functions that have side effects (including those that modify the database; e.g. `r add.OBIGT_`) and green for functions that don't have side effects.
Note that `r info_` is used for querying the OBIGT thermodynamic database, and `r subcrt_` is the main function in CHNOSZ for calculating standard thermodynamic properties as a function of temperature and pressure from the parameters in the database.
<!-- ######## SECTION MARKER ######## -->
## Basic structure of OBIGT
OBIGT is the name of the thermodynamic database in CHNOSZ.
The data are distributed in CSV files in the `inst/extdata/OBIGT` directory of the CHNOSZ package.
When the package is installed, the files are copied to the `exdata/OBIGT` directory of the installed package location.
To find out where this is on your computer, run the following command.
```{r system.file}
system.file("extdata/OBIGT", package = "CHNOSZ")
```
The directory path on your computer will be different.
Although possible, it is **NOT** recommended to edit the data files at that location.
This is because they will be overwritten by package updates; moreover, it is good practice to keep all the files needed for your project in a project directory.
This lists the files in the installation directory:
```{r dir.system.file}
dir(system.file("extdata/OBIGT", package = "CHNOSZ"))
```
Some of these files are used to build the default OBIGT database that is created when CHNOSZ starts up.
There are also a number of additional data files that have optional datasets.
The [<span style="color:blue">*OBIGT thermodynamic database*</span>](OBIGT.html) vignette summarizes the contents of the default and optional data files.
The files can also be opened by a spreadsheet program and used as templates for adding data yourself.
`thermo()$OBIGT` (hereafter, just OBIGT) is the "live" version of the database that is assembled from the CSV data files when CHNOSZ starts up or by using the `r reset_` or `r OBIGT_` functions.
The OBIGT data frame is stored in an environment named `CHNOSZ` that is part of the namespace of the CHNOSZ package.
More specifically, it is part of a list named `thermo`, which has the OBIGT database and other parameters and settings used by CHNOSZ.
`r reset_` restores the entire `thermo` object to default values; `r OBIGT_` restores just the OBIGT data frame.
The latter is useful for seeing the effects of changing the thermodynamic database on on chemical affinities calculated with `r affinity_`, without changing the chemical species.
OBIGT can be modified during an R session; if it couldn't, some of the examples in this vignette would not be possible!
When you quit R, it offers the option of saving your workspace so it can be reloaded it when R is restarted.
I always say "no" here; my preference is to load data into a fresh session every time I start R.
This "load saved workspace" feature means that OBIGT might not be the default database in any given R session.
To ensure that this vignette is run using the default database, we start by running `r reset_` to reset OBIGT and the other settings used by CHNOSZ.
```{r reset_}
reset()
```
`r thermo_` is a convenience function to access or modify parts of the `thermo` list object.
To see the first few entries in OBIGT, do this:
```{r thermo.OBIGT}
head(thermo()$OBIGT)
```
<!-- ######## SECTION MARKER ######## -->
## Conventions for data entry in OBIGT
The format of OBIGT is described in the CHNOSZ manual: see `r thermo_`.
Next, we point out some particular conventions including types of data, required and optional data, order-of-magnitude scaling.
Here are the numbered column names for reference:
```{r colnames.OBIGT, echo = FALSE}
paste(1:22, colnames(thermo()$OBIGT))
```
### Types of data
- Columns 1--9 have character data.
- Column 8 is named `r model`; here are the two models that are most frequent in the default database:
- `HKF`: Revised Helgeson-Kirkham-Flowers "equation-of-state" parameters for aqueous species
- `CGL`: Heat capacity coefficients for crystalline, gaseous, and liquid species. The first three terms in the CGL heat capacity equation correspond to the Maier-Kelley equation for heat capacity [@MK32]; the additional terms are useful for representing heat capacities of minerals [@RH95] and organic gases and liquids [@HOKR98].
- Columns 10--22 have numeric data.
- Columns 10--14 have standard-state thermodynamic properties at 25 °C and 1 bar.
- Columns 15--21 have parameters for calculating thermodynamic properties at other temperatures and pressures.
- The columns are named by combining the the names of the HKF and CGL coefficients, separated by a dot.
- Column 22 has the charge used in the HKF EOS or the maximum temperature for CGL species.
- `r NOTE`: The value of charge used in the HKF EOS (in particular, the *g* function for the temperature derivatives of the ω parameter [@SOJSH92]) is taken from this column and not from the chemical formula of the species.
### Ranges of HKF and CGL models
To a first approximation, the revised HKF equations of state are applicable within the stability region of liquid water or the supercritical fluid with a density greater than 0.35 g/cm3, and not exceeding the ranges of 0 to 1000 °C and 1 to 5000 bar [see @SOJSH92 for details].
There are two ways in which these limits are enforced in CHNOSZ:
- The default source of water properties (H2O92D Fortran subroutine modified from SUPCRT92) yields NA values beyonds these T and P ranges.
Note that the Deep Earth Water (DEW) model is available to extend the applicable range to pressures of up to 60 kbar (6 GPa) [@SHA14].
- `r subcrt_` generates NA values beyond the density limit; the `exceed.rhomin` argument can be used to enable calculations at lower density in the supercritical region.
The upper temperature limit for validity of the CGL heat-capacity equation is a species-dependent parameter.
This value is stored as a negative value in the `r T_` column of OBIGT and is used by `r subcrt_` to issue a warning at temperatures beyond this limit.
### Required and optional data
REQUIRED:
- All species need a `r name` and a `r state`.
- The state can be one of `aq`, `gas`, or `cr`.
- For minerals with higher-temperature polymorphs, they are named `cr2`, `cr3`, etc.
- `r NOTE`: `cr` stands for "crystalline"; this naming convention (which was inherited from SUPCRT92 data files) refers to any solid phases including amorphous SiO<sub>2</sub> and other minerals.
- A chemical `r formula` is required to do almost anything useful in CHNOSZ (e.g. check reaction balancing with `r subcrt_` and add species with `r basis_` or `r species_`).
- `r NOTE`: The `r name` of *inorganic* aqueous species *and CH<sub>4</sub>* in OBIGT is the same as the chemical formula.
- Most minerals, gases, liquids, and organic aqueous species have a `r name` that is a common name. This permits a shortcut to identify commonly used species in `r subcrt_`.
- For example, `info("O2")` refers to dissolved oxygen, while `info("oxygen")` or `info("O2", "gas")` refers to the gas.
- `E_units` needs to be defined to perform any calculations of thermodynamic properties.
- The value can be `J` for Joules or `cal` for calories.
OPTIONAL: Everything else.
Really, it depends on what you need.
For instance, if you just want to use `r subcrt_` to calculate `r logK` of a reaction from `r DG_0` of species at 25 °C, then `r G_` is the only parameter that is needed.
OPTIONAL but useful:
- `r abbrv` *may be* an abbreviation (e.g. Qtz for quartz). It is used by `r info_` (together with `r name` and `r formula`) to look up species in the database.
- `r date` is a timestamp for the data entry (YYYY-MM-DD format in the default OBIGT database).
- `r ref1` and `r ref2` are bibliographic reference keys. They have matching entries in `extdata/OBIGT/refs.csv`, which is used by `r thermo.refs_` to display references, and in `vignettes/OBIGT.bib`, which is used in the [<span style="color:blue">*OBIGT thermodynamic database*</span>](OBIGT.html) vignette to produce a reference list.
`r NOTE`: Other functions in CHNOSZ do not depend on `r date`, `r ref1`, and `r ref2`, so you can put anything there that is convenient for you.
### NA or 0?
If a character value (in Columns 1--9) or thermodynamic parameter (in Columns 10--14) is unknown, use `NA`.
Note that a missing (blank) value in the file is treated as NA.
- Unknown values for character values (usually `r abbrv`, `r date`, `r ref1`, or `r ref2`) should be NA.
- If you have only two of `r G_`, `r H_`, and `r S_`, then the missing one should be NA.
- Do **NOT** set a missing value of `r G_`, `r H_`, or `r S_` to 0. Zero is a numeric value that is incorrect except for very special cases.
- `r NOTE`: `r info_` -- and, by extension, `r subcrt_` -- "know" about the equation Δ<i>G</i>°<sub><i>f</i></sub> = Δ<i>H</i>°<sub><i>f</i></sub> - <i>T</i>Δ<i>S</i>°<sub><i>f</i></sub> and the entropies of the elements needed to calculate Δ<i>S</i>°<sub><i>f</i></sub> from values of `r S_` in OBIGT. This equation is used to compute a missing value of `r G_`, `r H_`, or `r S_` from the other two, or to cross-check the values if all three are present for any species.
- If you don't have `r Cp_` or `r V_`, then set it to NA.
- If HKF or CGL parameters are present, they will be used to calculate `r Cp_`, so thermodynamic properties *can* be calculated at T > 25 °C.
- If HKF or CGL parameters aren't present, thermodynamic properties *can't* be calculated at T > 25 °C (NAs will propagate to higher T).
If an "equation-of-state" parameter or heat capacity coefficient (Columns 15-21) is unknown, use 0.
- Furthermore, if you would like to assume that `r Cp_` or `r V_` is 0, then set it to 0.
- Then, thermodynamic properties will be extrapolated to T > 25 °C and P > 1 bar assuming that `r Cp_` and `r V_` are 0.
More detail on the inner working of the functions: For both HKF and CGL, if at least one parameter for a species is provided, any NA values of the other parameters are taken to be zero.
If all EOS parameters are NA, but values of `r Cp_` and/or `r V_` are present, they are assumed to be constants for extrapolating thermodynamic properties (e.g. `r DG_0`) as a function of temperature and pressure.
### OOM scaling and `r info_`
HKF parameters in the the CSV files and OBIGT data frame are scaled by order-of-magnitude (OOM) factors.
For these parameters, OOM scaling is nearly always used in published data tables.
See `r thermo_` for details of the OOM scaling.
`r info_` provides a simple user interface to the OBIGT database and is called by other functions in CHNOSZ to retrieve unscaled values from the database.
This is a summary of its main features:
- Remove OOM scaling. This is used primarily by other functions in CHNOSZ to get a set of unscaled `r model` parameters for calculating thermodynamic properties as a function of T and P.
- Extract the HKF or CGL parts of column names (only if all matching species have the same `r model`).
- Calculate a missing one of `r G_`, `r H_`, or `r S_` if two of them are present.
- Cross-check `r G_`, `r H_`, and `r S_` if all of them are present, and print a message if the difference is above a threshold (see `r check.GHS_`).
- Calculate a missing `r Cp_` or `r V_` from the `r model` parameters, if possible.
- Cross-check `r Cp_` or `r V_` (if present) against the `r model` parameters, if possible, and print a message if the difference is above a threshold (see `r check.EOS_`).
`r NOTE`: `r info_` does **NOT** change the units of energy; the values it displays (including possibly calculated ones) correspond to the `r E_units` for that species in OBIGT.
On the other hand, `r subcrt_` outputs values in the units previously selected with the function `r E.units_`.
<!-- ######## SECTION MARKER ######## -->
## Case study: NA and 0 in the default database
Use the `r info_` function to look at the database and `r subcrt_` to calculate thermodynamic properties.
Let's look at some minerals first.
First use `r info_` to get the species indices (i.e. rownumbers) in OBIGT, then pull out the "raw" data (including any NA values).
```{r icr, message = FALSE}
icr <- info(c("orpiment,amorphous", "arsenic,alpha", "tin"))
thermo()$OBIGT[icr, ]
```
Based on the values in the `r Cp_` column, would you predict that thermodynamic properties at T > 25 °C could be calculated for all of these minerals?
Let's see ...
For conciseness we'll consider a relatively small temperature range and display only the `out` part of the `r subcrt_` output.
```{r orpiment}
subcrt("orpiment,amorphous", T = c(25, 50, 75))$out[[1]]
```
That makes sense; integrating NA `r Cp_` to calculate Gibbs energy and other thermodynamic properties would propagate NA, and that is what appears in the output.
Now let's run the calculation for the alpha phase of arsenic.
```{r arsenic}
subcrt("arsenic,alpha", T = c(25, 50, 75))$out[[1]]
```
What happened here?
Even though there are no heat capacity coefficients (see above), there is a non-NA value of `r Cp_`, and that value is used together with the entropy for calculating Gibbs energy at T > 25 °C.
Note that zero for the 25 °C values of G and H in this case is not a placeholder for unknown values (as noted above, unknown values should be represented by NA).
Instaed, this is the reference state for the element, for which G and H are by convention equal to zero.
Let's look at another element in its reference state, tin:
```{r tin}
subcrt("tin", T = c(25, 50, 75))$out[[1]]
```
Are you surprised?
You might be if you only noticed the NA value for `r Cp_` in OBIGT.
However, there are non-NA values for the heat capacity coefficients, which are used to calculate `r Cp_0` as a function of temperature.
When supplied with a numeric argument (a species index), `r info_` actually does this to fill in missing 25 °C values of `r Cp_`, `r V_`, and `r G_`, `r H_`, or `r S_` if possible, in addition to simplifying column names:
```{r info_.tin}
info(info("tin"))
```
## Examples of adding data from a file
Using `r add.OBIGT_` to add data from optional data files for OBIGT or CSV files you make yourself.
### `r add.OBIGT_` with optional data files
The default database has parameters for many minerals from @Ber88; a notable exception is sulfide minerals, which are from @HDNB78.
Besides the different literature sources in `r ref1`, the `r model` column indicates that a different model is used for these minerals (Berman equations or CGL).
```{r Berman}
info(info(c("quartz", "pyrite")))
```
Sometimes it is useful to load mineral data from the SUPCRT92 database, corresponding largely to the compilation by @HDNB78.
This can be done with `r add.OBIGT_`.
In this example we load SUPCRT92 data for just one mineral, quartz.
```{r add.OBIGT_quartz}
add.OBIGT("SUPCRT92", "quartz")
info(info("quartz"))
```
Here we load all minerals available in the optional SUPCRT92 data file and then list the names.
`r NOTE`: `suppressMessages()` is used to suppress messages from `r info_` about missing parameters, and `unique()` is used to list each mineral only once (because each polymorph has a separate entry).
```{r add.OBIGT_SUPCRT92}
iSUPCRT92 <- add.OBIGT("SUPCRT92")
unique(suppressMessages(info(iSUPCRT92))$name)
```
### `r add.OBIGT_` with other CSV files
`r add.OBIGT_` can also be used to add data from a user-specified file to the OBIGT database.
The file must be a CSV (comma separated value) file with column headers that match those in the default database (i.e., `thermo()$OBIGT`).
As an example, here are the contents of `BZA10.csv`, which has parameters taken from @BZA10.
Missing values are indicated by `NA`:
```{r BZA10}
file <- system.file("extdata/adds/BZA10.csv", package = "CHNOSZ")
read.csv(file, as.is = TRUE)
```
Loading the data with `r add.OBIGT_` produces a message that the new data replace existing species.
We can then use `r subcrt_` to calculate the equilibrium constant for a reaction involving the new species.
Note the decrease in the stepwise stability constant for the second cadmium chloride complex with increasing pressure (Bazarkina et al., 2010, Fig. 4).
```{r BZA10_Cd}
iCd <- add.OBIGT(file)
subcrt(c("CdCl+", "Cl-", "CdCl2"), c(-1, -1, 1), T = 25, P = c(1, 2000))
```
After running `r reset_` we can look up the source of data in the default OBIGT database [@SSH97].
Running the reaction with thermodynamic parameters from the default database, we now see that the equilibrium constant is not as sensitive to pressure:
```{r SSH97_subcrt}
reset()
thermo.refs(iCd)[, 1:3]
subcrt(c("CdCl+", "Cl-", "CdCl2"), c(-1, -1, 1), T = 25, P = c(1, 2000))
```
<!-- ######## SECTION MARKER ######## -->
## Examples of adding and modifying data with a function
Use `r mod.OBIGT_` to add or modify the database in the current session.
The function requires the name of a species and one or more properties to change.
### `r mod.OBIGT_` for aqueous species
Let's add data for CoCl<sub>4</sub><sup>-2</sup> from @LBT_11.
The values are taken from Table 5 of that paper; note that they are reported in caloric units, which is rather common for the HKF model.
The entry includes the date in ISO 8601 extended format (e.g. 2020-08-16); `Sys.Date()` is used in this example to get the current date.
```{r mod.OBIGT__CoCl4_ghs}
mod.OBIGT("CoCl4-2", formula = "CoCl4-2", state = "aq", ref1 = "LBT+11", E_units = "cal",
date = as.character(Sys.Date()), G = -134150, H = -171558, S = 19.55, Cp = 72.09, V = 27.74)
```
The function prints a message saying that the species was added and returns the species index of the new species.
Now let's modify the new species by adding the HKF coefficients including the OOM multipliers, as they are usually given in publications.
The `z` at the end refers to the charge of the species, and is used only for calculating the "*g* function" in the revised HKF model, not for balancing reactions.
```{r mod.OBIGT__CoCl4_eos}
mod.OBIGT("CoCl4-2", a1 = 6.5467, a2 = 8.2069, a3 = 2.0130, a4 = -3.1183,
c1 = 76.3357, c2 = 11.6389, omega = 2.9159, z = -2)
```
Let us now calculate the equilibrium constant for the formation of CoCl<sub>4</sub><sup>-2</sup> from Co<sup>+2</sup> and Cl<sup>-</sup>.
```{r CoCl4_reaction, message = FALSE, echo = 1:3}
T <- c(25, seq(50, 350, 50))
sres <- subcrt(c("Co+2", "Cl-", "CoCl4-2"), c(-1, -4, 1), T = T)
round(sres$out$logK, 2)
stopifnot(identical(round(sres$out$logK, 2), c(-3.2, -2.96, -2.02, -0.74, 0.77, 2.5, 4.57, 7.29)))
```
The calculated values of log*K* are identical to those in Table 9 of @LBT_11, which provides a good indication that the thermodynamic parameters were entered correctly.
Nevertheless, this isn't a guarantee that the thermodynamic parameters are consistent with the provided values of *C*<sub>*P*</sub>° and *V*°.
We can see this by running `r info_` to cross-check the parameters for the new CoCl<sub>4</sub><sup>-2</sup> species:
```{r info__CoCl4, results = "hide"}
inew <- info("CoCl4-2")
info(inew)
```
The messages indicate that the given values of *C*<sub>*P*</sub>° and *V*° differ slightly from those calculated using the HKF parameters.
### `r mod.OBIGT_` for minerals
Let's add data for magnesiochromite from @KOSG00.
The parameters in this paper are reported in Joules, so we set the `r E.units_` to J.
The value for volume, in cm<sup>3</sup> mol<sup>-1</sup>, is from @RH95.
```{r mod.OBIGT__magnesiochromite_ghs}
H <- -1762000
S <- 119.6
V <- 43.56
mod.OBIGT("magnesiochromite", formula = "MgCr2O4", state = "cr", ref1 = "KOSG00",
date = as.character(Sys.Date()), E_units = "J", H = H, S = S, V = V)
```
Here are the heat capacity parameters for the Haas-Fisher polynomial equation ($Cp = a + bT + cT^{-2} + dT^{-0.5} + eT^2$).
As of CHNOSZ 2.0.0, OOM multipliers are not used for these coefficients.
1500 K is a generic value for the high-temperature limit; experimental heat capacities were only reported up to 340 K [@KOSG00].
```{r mod.OBIGT__magnesiochromite_eos}
a <- 221.4
b <- -0.00102030
c <- -1757210
d <- -1247.9
mod.OBIGT("magnesiochromite", E_units = "J", a = a, b = b, c = c, d = d,
e = 0, f = 0, lambda = 0, T = 1500)
```
`r NOTE`: An additional `r f` term is available, which can have any exponent given in `r lambda`.
This offers some flexibility for using heat capacity equations that are different from the Haas-Fisher polynomial.
Now we can use `r subcrt_` to calculate the heat capacity of magnesiochromite.
For this calculation, we set the temperature units to Kelvin.
We also specify a pressure of 1 bar because the default setting of *P*<sub>sat</sub> (liquid-vapor saturation) causes an error below the freezing temperature of water.
```{r subcrt__magnesiochromite}
T.units("K")
Tref <- c(250, 300, 340)
(sres <- subcrt("magnesiochromite", property = "Cp", T = Tref, P = 1))
```
Next we check that the calculated values are within 0.3 J K<sup>-1</sup> mol<sup>-1</sup> of reference values taken from Fig. 1 of @KOSG00.
```{r magnesiochromite_check_Cp}
Cpref <- c(114.3, 129.8, 138.4)
stopifnot(max(abs(sres$out[[1]]$Cp - Cpref)) < 0.3)
```
Finally, let's restore the units setting for later calculations with `r subcrt_`.
(Another way would be to run `r reset_`, which also resets the OBIGT database.)
```{r restore_units_magnesiochromite}
T.units("C")
```
<!-- ######## SECTION MARKER ########
## Other models
Here we'll look at how to add minerals that use the Berman equations and aqueous nonelectrolytes that use the Akinfiev-Diamond model.
### Akinfiev-Diamond model
The Akinfiev-Diamond model for aqueous species [@AD03] is activated by setting \code{abbrv = "AD"} in `r thermo_` for a given aqueous species.
The database must also include a corresponding gaseous species with the same name or chemical formula.
TODO
TODO: Add van't Hoff example?
-->
<!-- ######## SECTION MARKER ######## -->
## Case study: Formation constants for aqueous tungsten species
Here we use `r logB.to.OBIGT_` to fit to thermodynamic parameters to experimental formation constants.
Some additional steps are shown to refine a thermodynamic model to generate a speciation diagram as a function of pH.
### Fitting formation constants
`r logB.to.OBIGT_` requires three things:
- Experimental decimal logarithms of formation constants (`r logB`) as a function of temperature;
- The stoichiometry of the formation reaction in terms of known species (the new species must be last);
- The experimental temperature and pressure.
`r logB.to.OBIGT_` does three things:
- Combines the formation constants with standard Gibbs energies (`r DG_0`) of the known species to calculate `r DG_0` of the new species;
- Fits `r DG_0` of the new species using 25 °C thermodynamic properties and selected HKF model parameters (i.e., `r G_`, `r S_`, `r c1`, `r c2`, and `r omega` parameters in OBIGT);
- Adds the parameters to OBIGT for use by other functions in CHNOSZ.
First we set the pressure for all `r logB` data.
```{r Psat}
P <- "Psat"
```
Add first species: `r HWO4_` [@WTW_19].
```{r HWO4_}
T <- c(250, 300, 350)
logB <- c(5.58, 6.51, 7.99)
species <- c("WO4-2", "H+", "HWO4-")
coeff <- c(-1, -1, 1)
logB.to.OBIGT(logB, species, coeff, T, P)
```
Add second species: `r H3WO4F2_` [@WWH_21].
```{r H3WO4F2-}
T <- seq(100, 250, 25)
logB <- c(17.00, 17.11, 17.46, 17.75, 18.17, 18.71, 19.23)
# Species and coefficients in the formation reaction
species <- c("H+", "WO4-2", "F-", "H3WO4F2-")
coeff <- c(-3, -1, -2, 1)
logB.to.OBIGT(logB, species, coeff, T, P)
```
Add third species: `r H2WO4` [@WWH_21].
Here we increase the tolerance because there is considerable scatter in the experimental values.
```{r H2WO4}
logB <- c(7.12, 7.82, 7.07, 7.76, 7.59, 7.98, 8.28)
species <- c("H+", "WO4-2", "H2WO4")
coeff <- c(-2, -1, 1)
logB.to.OBIGT(logB, species, coeff, T, P, tolerance = 0.3)
```
After running, `r logB.to.OBIGT_` returns the species indices; the low values for `r HWO4_` (`r info("HWO4-")`) and `r H2WO4` (`r info("H2WO4")`) indicate that the function replaced parameters for these species that were already present in OBIGT.
### Diagram 1: Constant molality of `r F_`
Now we're ready to make a speciation diagram.
Our aim is to reproduce Fig. 7b of @WWH_21, which is made for 300 °C.
A constant molality of `r F_` is based on the assumption of complete dissociation of 0.1 m NaF (we'll change this later).
An ionic strength of 0.9 mol/kg is estimated for a solution with 1.8 m NaCl (use `NaCl(1.8, T = 300)`).
`r NOTE`: because the ionic strength is non-zero, the calculations here refer to molality instead of activity of species (see [An Introduction to CHNOSZ](anintro.html#from-activity-to-molality)).
```{r diagram1, message = FALSE, results = "hide", fig.width = 6, fig.height = 5, out.width = "75%", fig.align = "center", pngquant = pngquant}
basis(c("H+", "WO4-2", "F-", "H2O", "O2"))
basis("F-", log10(0.1))
iaq <- retrieve("W", c("O", "H", "F"), "aq")
species(iaq)
a <- affinity(pH = c(2, 7), T = 300, IS = 0.9)
e <- equilibrate(a)
col <- c(1, 4, 5, 2)
diagram(e, alpha = TRUE, col = col, lty = 1, lwd = 2, ylab = "Fraction total W")
```
This isn't quite the diagram we were looking for.
The published diagram shows a broad region of coexistence of `r H3WO4F2_` and `r HWO4_` at pH < 5 and increasing abundance of `r H2WO4` at lower pH.
### Diagram 2: Variable molality of `r F_`
In reality, the molality of `r F_` depends strongly on pH according to the reaction `r Hplus` + `r F_` = HF.
With a little algebra, we can calculate the molality of `r F_` (`a_F` in the code below) from the equilbrium constant of this reaction for a given total F concentration (`F_tot`).
`r NOTE`: It is important to call `r subcrt_` with a non-zero `IS` so that it returns effective equilibrium constants corrected for ionic strength (try setting `IS = 0` yourself and look at what happens to the diagram).
```{r a_F}
T <- 300
pH <- seq(2, 7, 0.1)
logK_HF <- subcrt(c("H+", "F-", "HF"), c(-1, -1, 1), T = T, IS = 0.9)$out$logK
F_tot <- 0.1
a_F <- F_tot / (1 + 10^(logK_HF - pH))
```
Now that we have the molality of `r F_` as a function of pH, we can provide it in the call to `r affinity_`.
```{r diagram2, message = FALSE, results = "hide", results = "hide", fig.width = 6, fig.height = 5, out.width = "75%", fig.align = "center", pngquant = pngquant}
basis(c("H+", "WO4-2", "F-", "H2O", "O2"))
iaq <- retrieve("W", c("O", "H", "F"), "aq")
species(iaq)
a <- affinity(pH = pH, "F-" = log10(a_F), T = T, IS = 0.9)
e <- equilibrate(a)
diagram(e, alpha = TRUE, col = col, lty = 1, lwd = 2, ylab = "Fraction total W")
```
That's more like it.
We have captured the basic geometry of Fig. 7b in @WWH_21.
For instance, in accord with the published diagram, `r HWO4_` plateaus at around 40% of total W, and `r H2WO4` and `r H3WO4F2_` are nearly equally abundant at pH = 2.
The highest experimental temperature for the formation constants of `r H2WO4` and `r H3WO4F2_` is 250 °C, but this diagram is drawn for 300 °C.
@WWH_21 used the modified Ryzhenko-Bryzgalin (MRB) model to extrapolate to 300 °C.
In contrast, we used a different model but obtained quite similar results.
`r NOTE`: The coefficients in the model used by `r logB.to.OBIGT_` include 25 °C values of `r G_` and `r S_`.
These should be conservatively treated only as *fitting parameters* and should not be used to compute thermodynamic properties close to 25 °C unless they were fit to experimental data in that temperature range.
## References
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/vignettes/custom_data.Rmd
|
---
title: "Regressing thermodynamic data"
subtitle: "EOSregress in CHNOSZ"
author: "Jeffrey M. Dick"
date: "`r Sys.Date()`"
output:
tufte::tufte_html:
tufte_features: ["background"]
toc: true
mathjax: null
highlight: null
tufte::tufte_handout:
citation_package: natbib
latex_engine: xelatex
tufte::tufte_book:
citation_package: natbib
latex_engine: xelatex
vignette: >
%\VignetteIndexEntry{Regressing thermodynamic data}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
bibliography: vig.bib
link-citations: yes
csl: elementa.csl
---
<style>
html {
font-size: 14px;
}
body {
font-family: ‘Times New Roman’, Times, serif;
}
li {
padding: 0.25rem 0;
}
/* Zero margin around pre blocks (looks more like R console output) */
pre {
margin-top: 0;
margin-bottom: 0;
}
</style>
```{r width80, include=FALSE}
options(width = 80)
```
```{r digits6, include=FALSE}
options(digits = 6)
```
```{r HTML, include=FALSE}
## Some frequently used HTML expressions
V0 <- "<i>V</i>°"
Cp0 <- "<i>C<sub>P</sub></i>°"
c1 <- "<i>c</i><sub>1</sub>"
c2 <- "<i>c</i><sub>2</sub>"
a1 <- "<i>a</i><sub>1</sub>"
a2 <- "<i>a</i><sub>2</sub>"
a3 <- "<i>a</i><sub>3</sub>"
a4 <- "<i>a</i><sub>4</sub>"
h4sio4 <- "H<sub>4</sub>SiO<sub>4</sub>"
sio2 <- "SiO<sub>2</sub>"
h2o <- "H<sub>2</sub>O"
ch4 <- "CH<sub>4</sub>"
wPrTr <- "ω<sub><i>P<sub>r</sub></i>,<i>T<sub>r</sub></i></sub>"
```
```{r setup, include=FALSE}
library(knitr)
# Invalidate cache when the tufte version changes
opts_chunk$set(tidy = FALSE, cache.extra = packageVersion('tufte'))
options(htmltools.dir.version = FALSE)
# Adjust plot margins
knit_hooks$set(small.mar = function(before, options, envir) {
if (before) par(mar = c(4.2, 4.2, .3, .3)) # smaller margin on top and right
})
# Use pngquant to optimize PNG images
knit_hooks$set(pngquant = hook_pngquant)
# pngquant isn't available on R-Forge ...
if (!nzchar(Sys.which("pngquant"))) {
pngquant <- NULL
} else {
pngquant <- "--speed=1 --quality=0-50"
}
## Colorize messages 20171031
## Adapted from https://gist.github.com/yihui/2629886#file-knitr-color-msg-rnw
color_block = function(color) {
function(x, options) sprintf('<pre style="color:%s">%s</pre>', color, x)
}
knit_hooks$set(warning = color_block('magenta'), error = color_block('red'), message = color_block('blue'))
# Set dpi 20231129
knitr::opts_chunk$set(
dpi = if(nzchar(Sys.getenv("CHNOSZ_BUILD_LARGE_VIGNETTES"))) 72 else 50
)
```
This [vignette](index.html) demonstrates <span style="color:blue">`EOSregress()`</span> and related functions for the regression of heat capacity and volumetric data to obtain "equations of state" coefficients.
# A note on the equations
The CHNOSZ thermodynamic database uses the revised Helgeson-Kirkham-Flowers equations of state (EOS) for aqueous species.
Different terms in these equations give the "non-solvation" and "solvation" contributions to the standard molal heat capacity (`r Cp0`) and volume (`r V0`) as a function of temperature (*T*) and pressure (*P*).
The equations were originally described by @HKF81; for `r Cp0` the equation is
> `r Cp0` = `r c1` + `r c2` / (*T* - θ)<sup>2</sup> + ω*TX*
Here, `r c1` and `r c2` are the non-solvation parameters, and ω is the solvation parameter.
θ is equal to 228 K, and *X* is one of the "Born functions" that relates the solvation process to the dielectric properties of water.
For neutral species, all of the parameters, including the "effective" value of ω, are constant.
However, **for charged species, ω has non-zero derivatives at *T* > 100 °C, increasing with temperature**, that depend on the charge and ionic radius.
Revisions by @TH88 and @SOJSH92 refined the equations to improve their high-*T* and *P* behavior.
# A note on the algorithms
The regression functions are essentially a wrapper around the <span style="color:green">`water()`</span>-related functions in CHNOSZ and `lm()` in R.
The former provide values of the Born functions.
Accordingly, numerical values for all of the *variables* in the equations (e.g. 1/(*T* - θ)<sup>2</sup> and *TX*) can be calculated at each experimental *T* and *P*.
Applying a linear model (`lm`), the *coefficients* in the model can be obtained.
In this case, they correspond to the HKF parameters, e.g. `c1` (the intercept), `c2` and ω.
The coefficients **in this model** are constants, restricing application of the model to neutral (uncharged) species, for which the high-temperature derivatives of ω are 0.
Further below, a procedure is described to iteratively solve the equations for charged species.
# An example for neutral species
This is from the first example from <span style="color:green">`EOSregress()`</span>.
```{marginfigure}
The `?` indicates a documentation topic in R. To view it, type <span style="color:blue">`?EOSregress`</span> or <span style="color:blue">`help(EOSregress)`</span> at the R prompt.
```
Here, we regress experimental heat capacities of aqueous methane (`r ch4`) using the revised HKF equations.
First, load CHNOSZ and its database:
```{r library_CHNOSZ}
library(CHNOSZ)
reset()
```
Now, read a data file with experimental measurements from @HW97 and convert pressures in MPa to bar (the values of `r Cp0` in Joules will be used as-is):
```{r Cpdat}
file <- system.file("extdata/cpetc/HW97_Cp.csv", package = "CHNOSZ")
Cpdat <- read.csv(file)
# Use data for CH4
Cpdat <- Cpdat[Cpdat$species == "CH4", ]
Cpdat <- Cpdat[, -1]
Cpdat$P <- convert(Cpdat$P, "bar")
```
Next, we specify the terms in the HKF equations and perform the regression using <span style="color:green">`EOSregress()`</span>.
In the second call to <span style="color:green">`EOSregress()`</span> below, only for *T* < 600 K are included in the regression.
The coefficients here correspond to `r c1`, `r c2` and ω in the HKF equations.
```{r EOSregress}
var <- c("invTTheta2", "TXBorn")
Cplm_high <- EOSregress(Cpdat, var)
Cplm_low <- EOSregress(Cpdat, var, T.max = 600)
Cplm_low$coefficients
```
```{r EOSplot, fig.margin = TRUE, fig.cap = "Heat capacity of aqueous methane.", fig.width=3.5, fig.height=3.5, cache=TRUE, results="hide", message=FALSE, echo=FALSE, out.width=672, out.height=336, pngquant=pngquant}
EOSplot(Cpdat, coefficients = round(Cplm_low$coefficients, 1))
EOSplot(Cpdat, coeficients = Cplm_high, add = TRUE, lty = 3)
PS01_data <- convert(EOScoeffs("CH4", "Cp"), "J")
EOSplot(Cpdat, coefficients = PS01_data, add = TRUE, lty = 2, col = "blue")
```
We can use <span style="color:green">`EOSplot()`</span> to plot the data and fitted lines and show the coefficients in the legend.
The solid line shows the fit to the lower-temperature data.
The fit to all data, represented by the dotted line, doesn't capture the low-temperature trends in the data.
```{r EOSplot, eval=FALSE}
```
```{marginfigure}
Be aware that the lines shown by <span style="color:green">`EOSplot()`</span> are calculated for a single pressure only, despite the temperature- and pressure-dependence of the data and regressions.
```
<span style="color:green">`EOScoeffs()`</span> is a small function that is used to retrieve the HKF parameters in the database in CHNOSZ.
*For species in the database with `E_units` set to `cal` for calories (i.e., most HKF species), the coefficients need to be converted to Joules here.*
The dashed blue line shows calculated values for methane using these parameters, which are from @PS01.
Compare the database values with the regressed values shown in the legend of figure above.
Some differences are expected as the values in the database are derived from different regression techniques applied to different sets of data:
```{r Cpcoeffs, message=FALSE}
convert(EOScoeffs("CH4", "Cp"), "J")
```
## Setting the value of omega
Given both high-temperature volumetric and calorimetric data for neutral species, the effective value of ω is most reliably regressed from the latter [@SSW01].
Let's regress volumetric data using a value of omega taken from the heat capacity regression.
First, read the data from @HWM96.
```{r Vdat}
file <- system.file("extdata/cpetc/HWM96_V.csv", package = "CHNOSZ")
Vdat <- read.csv(file)
# Use data for CH4 near 280 bar
Vdat <- Vdat[Vdat$species == "CH4", ]
Vdat <- Vdat[abs(Vdat$P - 28) < 0.1, ]
Vdat <- Vdat[, -1]
Vdat$P <- convert(Vdat$P, "bar")
```
Compressibilities of species (measured or estimated) are implied by the full set of HKF volumetric parameters (`r a1`, `r a2`, `r a3`, `r a4`).
In this example we model volumes at nearly constant *P*.
Therefore, we can use a simpler equation for `r V0` written in terms of the "isobaric fit parameters" (Tanger and Helgeson 1988, p. 35) σ and ξ, together with the solvation contribution that depends on the *Q* Born function:
> `r V0` = σ + ξ / (*T* - θ) - ω*Q*
```{marginfigure}
<span style="color:green">`EOSvar()`</span> actually returns the negative of *Q*, so the omega symbol here carries no negative sign.
```
Now we calculate the *Q* Born function using <span style="color:green">`EOSvar()`</span> and multiply by ω (from the heat capacity regression) to get the solvation volume at each experimental temperature and pressure.
Subtract the solvation volume from the experimental volumes and create a new data frame holding the calculated "non-solvation" volume.
```{marginfigure}
Because we are dealing with volumes, the units of ω are converted according to 1 J = 10 cm<sup>3</sup> bar.
```
```{r Vdat_non}
QBorn <- EOSvar("QBorn", T = Vdat$T, P = Vdat$P)
Vomega <- convert(Cplm_low$coefficients[["TXBorn"]], "cm3bar")
V_sol <- Vomega * QBorn
V_non <- Vdat$V - V_sol
Vdat_non <- data.frame(T = Vdat$T, P = Vdat$P, V = V_non)
```
Next, regress the non-solvation volume using the non-solvation terms in the HKF model.
As with `r Cp0`, also get the values of the parameters from the database for comparison with the regression results.
```{r Vdat_non_regress, message=FALSE}
var <- "invTTheta"
Vnonlm <- EOSregress(Vdat_non, var, T.max = 450)
Vcoeffs <- round(c(Vnonlm$coefficients, QBorn = Vomega), 1)
Vcoeffs_database <- convert(EOScoeffs("CH4", "V"), "J")
```
```{r Vplot, fig.margin=TRUE, results="hide", message=FALSE, echo=FALSE, fig.width=3.5, fig.height=7, fig.cap="Volume of aqueous methane.", out.width=672, out.height=672, pngquant=pngquant}
par(mfrow = c(2, 1))
# plot 1
EOSplot(Vdat, coefficients = Vcoeffs)
EOSplot(Vdat, coefficients = Vcoeffs_database, add = TRUE, lty = 2)
# plot 2
EOSplot(Vdat, coefficients = Vcoeffs_database, T.plot = 600, lty = 2)
EOSplot(Vdat, coefficients = Vcoeffs, add = TRUE)
```
Finally, plot the data and regressions.
The first plot shows all the data, and the second the low-temperature subset (*T* < 600 K).
The solid line is the two-term fit for σ and ξ (using ω from the heat capacity regression), and the dashed line shows the volumes calculated using the parameters in the database.
The plot legends give the parameters from the two-term fit (first plot), or from the database (second plot).
```{r Vplot, eval=FALSE}
```
The equation for `r V0` provides a reasonable approximation of the trend of lowest-temperature data (*T* < 450 K).
However, the equation does not closely reproduce the trend of higher-temperature `r V0` data (*T* < 600 K), nor behavior in the critical region.
Because of these issues, some researchers are exploring alternatives to the HKF model for aqueous nonelectrolytes.
(See also an example in <span style="color:blue">`?EOSregress`</span>.)
# An example for charged species
For this example, let's generate synthetic data for Na<sup>+</sup> using its parameters in the database.
In the call to <span style="color:green">`subcrt()`</span> below, `convert = FALSE` means to take *T* in units of K.
```{r Nadat}
T <- convert(seq(0, 600, 50), "K")
P <- 1000
prop.PT <- subcrt("Na+", T = T, P = P, grid = "T", convert = FALSE)$out[[1]]
Nadat <- prop.PT[, c("T", "P", "Cp")]
```
As noted above, ω for electrolytes is not a constant.
What happens if we apply the constant-ω model anyway, knowing it's not applicable (especially at high temperature)?
```{r Nalm, fig.margin=TRUE, fig.width=3.5, fig.height=3.5, fig.cap="Heat capacity of Na<sup>+</sup> (inapplicable: constant ω).", out.width=672, out.height=336, pngquant=pngquant}
var <- c("invTTheta2", "TXBorn")
Nalm <- EOSregress(Nadat, var, T.max = 600)
EOSplot(Nadat, coefficients = Nalm$coefficients, fun.legend = NULL)
EOSplot(Nadat, add = TRUE, lty = 3)
```
As before, the solid line is a fit to relatively low-temperature (*T* < 600 K) data, and the dotted line a fit to the entire temperature range of the data.
The fits using constant ω are clearly not acceptable.
There is, however, a way out.
A different variable, `Cp_s_var`, can be used to specify the calculation of the "solvation" heat capacity in the HKF equations using the temperature- and pressure-dependent corrections for charged species.
To use this variable, the values of `r wPrTr` (omega at the reference temperature and pressure) and *Z* (charge) must be given, in addition to *T* and *P*.
Of course, right now we *don't know* the value of `r wPrTr`---it is the purpose of the regression to find it!
But we can make a first guess using the value of ω found above.
```{r Navars1}
var1 <- c("invTTheta2", "Cp_s_var")
omega.guess <- coef(Nalm)[3]
```
Then, we can use an iterative procedure that refines successive guesses of `r wPrTr`.
The convergence criterion is measured by the difference in sequential regressed values of ω.
```{r Nawhile, fig.margin=TRUE, fig.width=3.5, fig.height=3.5, fig.cap="Heat capacity of Na<sup>+</sup> (variable ω).", out.width=672, out.height=336, pngquant=pngquant}
diff.omega <- 999
while(abs(diff.omega) > 1) {
Nalm1 <- EOSregress(Nadat, var1, omega.PrTr = tail(omega.guess, 1), Z = 1)
omega.guess <- c(omega.guess, coef(Nalm1)[3])
diff.omega <- tail(diff(omega.guess), 1)
}
EOSplot(Nadat, coefficients = signif(coef(Nalm1), 6),
omega.PrTr = tail(omega.guess, 1), Z = 1)
convert(EOScoeffs("Na+", "Cp"), "J")
```
Alrighty! We managed to obtain HKF coefficients from synthetic data for Na<sup>+</sup>.
The regressed values of the HKF coefficients (shown in the plot legend) are very close to the database values (printed by the call to <span style="color:green">`EOScoeffs()`</span>) used to generate the synthetic data.
## Doing it for volume
Just like above, but using synthetic `r V0` data.
Note that the regressed value of ω has volumetric units (cm<sup>3</sup> bar/mol), while `omega.PrTr` is in energetic units (J/mol).
Compared to `r Cp0`, the regression of `r V0` is very finicky.
Given a starting guess of `r wPrTr` of 1400000 cm<sup>3</sup> bar/mol, the iteration converges on 1394890 instead of the "true" database value of 1383230 (represented by dashed line in the plot).
```{r NaVolume, fig.margin=TRUE, fig.width=3.5, fig.height=3.5, fig.cap="Volume of Na<sup>+</sup> (variable ω).", results="hide", message=FALSE, echo=FALSE, out.width=672, out.height=336, pngquant=pngquant}
T <- convert(seq(0, 600, 25), "K")
P <- 1000
prop.PT <- subcrt("Na+", T = T, P = P, grid = "T", convert = FALSE)$out[[1]]
NaVdat <- prop.PT[, c("T", "P", "V")]
var1 <- c("invTTheta", "V_s_var")
omega.guess <- 1400000
diff.omega <- 999
while(abs(diff.omega) > 1) {
NaVlm1 <- EOSregress(NaVdat, var1,
omega.PrTr = tail(convert(omega.guess, "joules"), 1), Z = 1)
omega.guess <- c(omega.guess, coef(NaVlm1)[3])
diff.omega <- tail(diff(omega.guess), 1)
}
EOSplot(NaVdat, coefficients = signif(coef(NaVlm1), 6),
omega.PrTr = tail(convert(omega.guess, "joules"), 1), Z = 1,
fun.legend = "bottomleft")
coefficients <- convert(EOScoeffs("Na+", "V", P = 1000), "J")
names(coefficients)[3] <- "V_s_var"
EOSplot(NaVdat, coefficients = coefficients, Z = 1, add = TRUE, lty = 2,
omega.PrTr = convert(coefficients["V_s_var"], "joules"))
```
```{r NaVolume, eval=FALSE}
```
# Making a pseudospecies: `r h4sio4`
Some mineral stability diagrams use the activity of `r h4sio4` as a variable.
However, the primary species for dissolved silica in CHNOSZ is `r sio2`(aq).
As recommended by @WJ17, let us use data for `r sio2`(aq) from @AS04, which gives a higher solubility of quartz compared to values from @SHS89 that are loaded by default in the package:
```{r AS04, message=FALSE}
add.OBIGT("AS04")
```
The pseudo-reaction with zero properties, `r h4sio4` = `r sio2` + 2 `r h2o`, defines the properties of the pseudospecies `r h4sio4`.
First we go about calculating the properties of `r sio2` + 2 `r h2o`.
We do this over a range of *T* and *P*, but include many points near 25 °C to improve the fit of the regression in that region:
`r op <- options(warn = -1)`
```{r SiO2_2H2O, message=FALSE}
s_25C <- subcrt(c("SiO2", "H2O"), c(1, 2), T = 25)$out
s_near25 <- subcrt(c("SiO2", "H2O"), c(1, 2), T = seq(20, 30, length.out=50))$out
s_lowT <- subcrt(c("SiO2", "H2O"), c(1, 2), T = seq(0, 100, 10))$out
s_Psat <- subcrt(c("SiO2", "H2O"), c(1, 2))$out
s_P500 <- subcrt(c("SiO2", "H2O"), c(1, 2), T = seq(0, 1000, 100), P = 500)$out
s_P1000 <- subcrt(c("SiO2", "H2O"), c(1, 2), T = seq(0, 1000, 100), P = 1000)$out
```
`r options(op)`
Now we can start making the new species, with thermodynamic properties calculated at 25 °C:
```{r new_H4SiO4}
mod.OBIGT("calc-H4SiO4", formula = "H4SiO4", ref1 = "this_vignette",
date = as.character(Sys.Date()), G = s_25C$G, H = s_25C$H, S = s_25C$S,
Cp = s_25C$Cp, V = s_25C$V, z = 0)
```
To prepare for the regression, combine the calculated data and convert °C to K:
```{r substuff}
substuff <- rbind(s_near25, s_lowT, s_Psat, s_P500, s_P1000)
substuff$T <- convert(substuff$T, "K")
```
Now let's run a `r Cp0` regression and update the new species with the regressed HKF coefficients.
Note that we apply order-of-magnitude scaling to the coefficients (see <span style="color:blue">`?thermo`</span>):
```{r Cp_H4SiO4, results="hide"}
Cpdat <- substuff[, c("T", "P", "Cp")]
var <- c("invTTheta2", "TXBorn")
Cplm <- EOSregress(Cpdat, var)
Cpcoeffs <- Cplm$coefficients
mod.OBIGT("calc-H4SiO4", c1 = Cpcoeffs[1],
c2 = Cpcoeffs[2]/10000, omega = Cpcoeffs[3]/100000)
```
Let's get ready to regress `r V0` data.
We use the strategy shown above to calculate non-solvation volume using ω from the `r Cp0` regression:
```{r V_H4SiO4_nonsolvation}
Vdat <- substuff[, c("T", "P", "V")]
QBorn <- EOSvar("QBorn", T = Vdat$T, P = Vdat$P)
Vomega <- convert(Cplm$coefficients[["TXBorn"]], "cm3bar")
V_sol <- Vomega * QBorn
V_non <- Vdat$V - V_sol
Vdat$V <- V_non
```
Here's the `r V0` regression for the pseudospecies.
We specify the variables for the `r a1`, `r a2`, `r a3`, and `r a4` terms in the HKF equations.
```{r V_H4SiO4, results="hide"}
var <- c("invPPsi", "invTTheta", "invPPsiTTheta")
Vlm <- EOSregress(Vdat, var)
Vcoeffs <- convert(Vlm$coefficients, "joules")
mod.OBIGT("calc-H4SiO4", a1 = Vcoeffs[1]*10, a2 = Vcoeffs[2]/100,
a3 = Vcoeffs[3], a4 = Vcoeffs[4]/10000)
```
We just calculated the properties of the `r h4sio4` pseudospecies.
For comparison, the OBIGT database in CHNOSZ contains `H4SiO4` with parameters from @Ste01:
```{r width180, include=FALSE}
options(width = 180)
```
```{r info_H4SiO4, message=FALSE}
info(info(c("calc-H4SiO4", "H4SiO4")))
```
```{r width80, include=FALSE}
```
```{r subcrt_H4SiO4, fig.margin=TRUE, fig.width=4, fig.height=4, small.mar=TRUE, echo=FALSE, results="hide", message=FALSE, out.width="100%", cache=TRUE, fig.cap="Comparison of H<sub>4</sub>SiO<sub>4</sub> pseudospecies.", pngquant=pngquant}
s1 <- subcrt(c("calc-H4SiO4", "SiO2", "H2O"), c(-1, 1, 2))
plot(s1$out$T, s1$out$G, type = "l", ylim = c(-500, 2000),
xlab = axis.label("T"), ylab = axis.label("DG0"))
s2 <- subcrt(c("H4SiO4", "SiO2", "H2O"), c(-1, 1, 2))
lines(s2$out$T, s2$out$G, lty = 2)
abline(h = 0, lty = 3)
legend("topright", legend = c("calc-H4SiO4 (this vignette)",
"H4SiO4 (Stef\u00e1nsson, 2001)"), lty = c(1, 2), bty = "n")
text(225, 1000, describe.reaction(s1$reaction))
```
Let's compare `H4SiO4` from Stefánsson (2001) and the `calc-H4SiO4` we just made with the calculated properties of `r sio2` + 2 `r h2o` as a function of temperature:
```{r subcrt_H4SiO4, eval=FALSE}
```
Ideally, the lines would be horizontal with a _y_-interecept of 0.
However, both the `calc-H4SiO4` we made here and the `H4SiO4` from Stefánsson (2001) show deviations that increase at higher temperatures.
While they are not quite negligible, these deviations are comparatively small.
For example, the almost 800 J/mol offset in Δ<i>G</i>° at 350 °C corresponds to a difference in log<i>K</i> of only -0.07.
The following example uses the `H4SiO4` from Stefánsson (2001) to make an activity diagram for the K<sub>2</sub>O-Al<sub>2</sub>O<sub>3</sub>-SiO<sub>2</sub>-H<sub>2</sub>O system.
This is similar to the diagram on p. 361 of [Garrels and Christ, 1965](https://www.worldcat.org/oclc/517586), but is quantitatively a closer match to the diagram in the [User's Guide to PHREEQC](https://wwwbrr.cr.usgs.gov/projects/GWC_coupled/phreeqc/html/final-75.html).
```{r activity_diagram, fig.margin=TRUE, fig.width=4, fig.height=4, small.mar=TRUE, echo=TRUE, results="hide", message=FALSE, out.width="100%", cache=TRUE, fig.cap="Activity diagram for K<sub>2</sub>O-Al<sub>2</sub>O<sub>3</sub>-SiO<sub>2</sub>-H<sub>2</sub>O.", pngquant=pngquant}
basis(c("Al+3", "H4SiO4", "K+", "H2O", "H+", "O2"))
species(c("gibbsite", "muscovite", "kaolinite", "pyrophyllite", "K-feldspar"))
a <- affinity(H4SiO4 = c(-8, 0, 300), `K+` = c(-1, 8, 300))
diagram(a, ylab = ratlab("K+"), fill = "terrain", yline = 1.7)
legend("bottomleft", describe.property(c("T", "P"), c(25, 1)), bty = "n")
```
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/vignettes/eos-regress.Rmd
|
---
title: "Equilibrium in CHNOSZ"
author: "Jeffrey M. Dick"
output:
html_vignette:
mathjax: null
vignette: >
%\VignetteIndexEntry{Equilibrium in CHNOSZ}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
bibliography: vig.bib
csl: elementa.csl
link-citations: true
---
<style>
/* https://gomakethings.com/how-to-break-an-image-out-of-its-parent-container-with-css/ */
@media (min-width: 700px) {
.full-width {
left: 50%;
margin-left: -50vw;
margin-right: -50vw;
max-width: 100vw;
position: relative;
right: 50%;
width: 100vw;
}
}
@media (min-width: 1020px) {
.full-width {
left: 50vw; /* fallback if needed */
left: calc(50vw - 160px);
width: 1000px;
position: relative;
background-color: #9ecff7;
padding:10px;
}
}
/* Zero margin around pre blocks (looks more like R console output) */
pre {
margin-top: 0;
margin-bottom: 0;
}
</style>
<script>
function ToggleDiv(ID) {
var D = document.getElementById("D-" + ID);
var B = document.getElementById("B-" + ID);
if (D.style.display === "none") {
// open the div and change button text
D.style.display = "block";
B.innerText = "Hide code";
} else {
// close the div and change button text
D.style.display = "none";
B.innerText = "Show code";
}
}
</script>
```{r setup, include=FALSE}
## Use pngquant to optimize PNG images
library(knitr)
knit_hooks$set(pngquant = hook_pngquant)
pngquant <- "--speed=1 --quality=0-25"
if (!nzchar(Sys.which("pngquant"))) pngquant <- NULL
# Set dpi 20231129
knitr::opts_chunk$set(
dpi = if(nzchar(Sys.getenv("CHNOSZ_BUILD_LARGE_VIGNETTES"))) 100 else 72
)
```
```{r CHNOSZ_reset, include=FALSE}
library(CHNOSZ)
reset()
```
This vignette was compiled on `r Sys.Date()` with CHNOSZ version `r sessionInfo()$otherPkgs$CHNOSZ$Version`.
This document defines the concepts and provides examples of equilibrium calculations in CHNOSZ.
First, some limitations.
CHNOSZ is not a general-purpose speciation code.
The types of equilibrium calculations it can handle are restricted to those systems that can be described as *balanced on an element*.
For example, we can predict the speciation of Au in complexes with chloride, hydroxide, and sulfide all with specified activities.
But we can not at the same time predict the formation of species such as NaCl(aq), which is required for a complete equilibrium model.
## Concepts
System
: Chemical system defined by formed species (referred to simply as species) and basis species, which are analogous to thermodynamic components.
The possible species are any that are available in the [OBIGT thermodynamic database](OBIGT.html).
Species
: Selection of possible chemical species for which you want to calculate relative stabilities.
Basis species
: Any minimal set of possible species that can be used to balance the formation reactions of the species.
Additionally, in CHNOSZ the number of basis species must be equal to the number of elements.
Formation reaction
: Chemical reaction giving the stoichiometry of basis species combined to make 1 mole of a species.
Transformation reaction
: Any combination of two formation reactions in opposite directions (1 mole of a species reacts to form 1 mole of another species).
Balancing coefficients
: (*n*~balance~) For a system that is balanced on one of the basis species,
the number of moles of that basis species in the formation reaction of each of the species.
The number can be positive or negative but not zero.
Can also represent a virtual quantity, such as 1 (balance on moles of species) or number of amino acids in a protein sequence (balance on protein length).
Speciation diagram
: Diagram showing the equilibrium activities of species as a function of one variable.
Predominance diagram
: Diagram variables showing fields for species with highest equilibrium activity as a function of two variables.
Also known as an equal activity diagram for aqueous species or stability diagram for minerals.
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: *A* = 2.303*RT*log(*K*/*Q*),
where *K* is the equilibrium constant and *Q* is the activity quotient of species in the reaction
(log here denotes base-10 logarithms, i.e. `log10` in R).
Maximum affinity method
: Approach used to construct predominance diagrams not by finding the highest activity at equilibrium but by finding the highest affinity at a **reference activity**.
The reference activities are user-defined equal activities of species (e.g. unit activity for minerals and 10^-3^ for aqueous species).
Equilibration method
: Calculations of the activities of species in equilibrium.
Metastable equilibrium
: The condition that the affinities of all *transformation* reactions are zero.
Implemented with the `equilibrate()` function in CHNOSZ, which is used below.
Total equilibrium
: The condition that the affinities of all *formation* reactions are zero.
Implemented with the `solubility()` function in CHNOSZ, which is not described here.
## Example 1: Amino acids
In this sytem the basis species are CO~2~, H~2~O, NH~3~, H~2~S, and O~2~ and the formed species are 20 amino acids.
```{r AAsetup, results = "hide", message = FALSE}
library(CHNOSZ)
reset()
basis("CHNOS")
species(aminoacids(""))
```
These functions are used for the different diagrams in the figure.
```{r AAfunctions}
aaA <- function() {
a <- affinity(O2 = c(-90, -70), H2O = c(-20, 10))
diagram(a, balance = 1, names = aa)
}
aaB <- function() {
a <- affinity(O2 = c(-90, -70), H2O = c(-20, 10))
e <- equilibrate(a, balance = 1)
diagram(e, names = aa)
}
aaC <- function() {
a <- affinity(O2 = c(-71, -66), H2O = c(-8, 4))
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, -7)
a <- affinity(H2O = c(-8, 4))
e <- equilibrate(a, balance = "CO2")
diagram(e, ylim = c(-8, -4), names = aa)
}
```
The labels used for the diagrams are the one-letter abbreviations for the amino acids.
```{r AAabbrv}
aa <- aminoacids()
aa
```
Press the button to show all of the code for making the figure.
<button id="B-AAplot" onclick="ToggleDiv('AAplot')">Show code</button>
<div id="D-AAplot" style="display: none">
```{r AAplot, eval = FALSE}
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(0.7, 4, 4))
## Row 0 (column titles)
opar <- par(mar=c(0, 0, 0, 0))
plot.new()
plot.new()
text(0.58, 0.5, "maximum affinity", cex=1.4)
plot.new()
text(0.58, 0.5, "equilibration", cex=1.4)
plot.new()
text(0.58, 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", yfrac=0.92, xfrac=0.1, font = 2)
# Figure B
st <- system.time(dB <- aaB())
showtime(st)
title(main=paste("loga(total species) =", round(dB$loga.balance[1], 2)), cex.main=1)
label.figure("C", yfrac=0.92, xfrac=0.1, font = 2)
## 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("B", yfrac=0.92, xfrac=0.1, font = 2)
# Figure D
st <- system.time(dD <- aaD())
showtime(st)
title(main=paste("loga(total CO2) =", round(dD$loga.balance[1], 2)), cex.main=1)
label.figure("D", yfrac=0.92, xfrac=0.1, font = 2)
## Right column (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[1], 2)), cex.main=1)
label.figure("E", yfrac=0.92, xfrac=0.1, font = 2)
# Figure F
st <- system.time(dF <- aaF())
showtime(st)
title(main=paste("loga(total CO2) =", round(dF$loga.balance[1], 2)), cex.main=1)
label.figure("F", yfrac=0.92, xfrac=0.1, font = 2)
```
</div>
```{r AAplot, echo = FALSE, results = "hide", message = FALSE, fig.width = 13/2, fig.height = 8.7/2, out.width = "100%", pngquant = pngquant}
```
Diagrams **A** and **B** use the *maximum affinity method*, where the reference
activities of species are set to a single value. Diagrams **C** and **D** use
the *equilibration method*, where the activities of species change across the
diagram and the lines are drawn at equal activity. Other comments on the
figure:
* The equal-activity lines in Diagrams **A** and **C** are the same. That is,
with the setting `balance = 1`, the conditions for equal activity of two
species do not depend on the actual value of that activity.
* Diagrams **B** and **D** are different. Because balance ≠ 1 (in this case,
the reactions are balanced on CO~2~), the conditions for equal activity of
species depend on the actual value of that activity. In particular, with the
equilibration method, the lines are curved due to the distribution of more
than two species.
* Diagrams **E** and **F** both use the equilibration method to calculate
activities of species as a function of log*a*~H2O~ at log*f*~O2~ = -66.
Diagram **F** shows the default setting, where *a*~CO2~ is taken from the sum
of initial activities of species (each 10^-3^). The positions of equal
activities (where the lines cross) are the same as in Diagram **D** at
log*f*~O2~ = -66.
* Diagram **F** is drawn for a lower total activity of *a*~CO2~. Not only are
the activities of all amino acids decreased, but glycine starts to become
predominant at some conditions. This is because, compared to other amino
acids, it is smaller and has a lower coefficient on CO~2~ in its formation
reaction.
## Example 2: Proteins
In this sytem the basis species are CO~2~, H~2~O, NH~3~, H~2~S, O~2~, and H^+^ and the
formed species are 6 proteins from the set of archaeal and bacterial surface
layer proteins considered by @Dic08.
The inclusion of charge in the basis species (with H^+^) allows ionization of
proteins to be calculated [@DLH06].
```{r PRsetup, results = "hide", message = FALSE}
basis("CHNOS+")
organisms <- c("METJA", "HALJP", "METVO", "ACEKI", "GEOSE", "BACLI")
proteins <- c(rep("CSG", 3), rep("SLAP", 3))
species(proteins, organisms)
```
Here are the lengths of the proteins.
```{r PRlength}
protein.length(species()$name)
```
These functions are used for the different diagrams in the figure.
```{r PRfunctions}
prA <- function() {
a <- affinity(O2 = c(-90, -70), H2O = c(-20, 0))
diagram(a, balance = "length", names = organisms)
}
prB <- function() {
a <- affinity(O2 = c(-90, -70))
e <- equilibrate(a, balance = "length")
ylab <- quote(log~italic(a)~protein)
diagram(e, names = organisms, ylim = c(-5, -1), ylab = ylab)
}
prC <- function() {
a <- affinity(O2 = c(-90, -70), H2O = c(-20, 0))
diagram(a, normalize = TRUE, names = organisms)
}
prD <- function() {
a <- affinity(O2 = c(-90, -70))
e <- equilibrate(a, normalize = TRUE)
ylab <- quote(log~italic(a)~protein)
diagram(e, names = organisms, ylim = c(-5, -1), ylab = ylab)
}
prE <- function() {
a <- affinity(O2 = c(-90, -70), H2O = c(-20, 0))
diagram(a, as.residue = TRUE, names = organisms)
}
prF <- function() {
a <- affinity(O2 = c(-90, -70))
e <- equilibrate(a, as.residue = TRUE, loga.balance = 0)
ylab <- quote(log~italic(a)~residue)
diagram(e, names = organisms, ylim = c(-3, 1), ylab = ylab)
}
```
<button id="B-PRplot" onclick="ToggleDiv('PRplot')">Show code</button>
<div id="D-PRplot" style="display: none">
```{r PRplot, eval = FALSE}
```
</div>
```{r PRplot, echo = FALSE, results = "hide", message = FALSE, fig.width = 13/2, fig.height = 8.7/2, out.width = "100%", pngquant = pngquant}
layout(t(matrix(1:12, nrow=4)), widths=c(1, 4, 4, 4), heights=c(0.7, 4, 4))
## Row 0 (column titles)
opar <- par(mar=c(0, 0, 0, 0))
plot.new()
plot.new()
text(0.58, 0.5, 'balance = "length"', cex=1.4)
plot.new()
text(0.58, 0.5, "normalize = TRUE\n(balance = 1)", cex=1.4)
plot.new()
text(0.58, 0.5, "as.residue = TRUE\n(balance = 1)", cex=1.4)
par(opar)
## Row 1 (maximum affinity 2D)
opar <- par(mar=c(0, 0, 0, 0))
plot.new()
text(0.5, 0.5, "maximum affinity", srt=90, cex=1.4)
par(opar)
# Figure A (balance = "length")
st <- system.time(dA <- prA())
showtime(st)
label.figure("A", yfrac=0.9, xfrac=0.1, font = 2)
# Figure C (normalize = TRUE)
st <- system.time(dC <- prC())
showtime(st)
label.figure("C", yfrac=0.9, xfrac=0.1, font = 2)
# Figure E (as.residue = TRUE)
st <- system.time(dE <- prE())
showtime(st)
label.figure("E", yfrac=0.9, xfrac=0.1, font = 2)
## Row 2 (equilibrate 1D)
opar <- par(mar=c(0, 0, 0, 0))
plot.new()
text(0.5, 0.5, "equilibration", srt=90, cex=1.4)
par(opar)
# Figure B (balance = "length")
st <- system.time(prB())
showtime(st)
label.figure("B", yfrac=0.9, xfrac=0.1, font = 2)
# Figure D (normalize = TRUE)
st <- system.time(prD())
showtime(st)
label.figure("D", yfrac=0.9, xfrac=0.1, font = 2)
# Figure F (as.residue = TRUE)
st <- system.time(prF())
showtime(st)
label.figure("F", yfrac=0.9, xfrac=0.1, font = 2)
```
Diagrams **A**, **C**, and **E** are predominance (equal-activity) diagrams
made with different balancing constraints. Diagrams **B**, **D**, and **F**
show a cross-section of the same system at log*a*~H2O~ = 0.
* In Diagrams **A** and **B**, the reactions are balanced on protein length.
The drastic transitions between proteins in **B** result from the large
balancing coefficients, which become exponents on activities in the
expression for the activity quotient (*Q*).
* In Diagrams **C** and **D**, the chemical formulas of the proteins are
*normalized*, or divided by the protein length, before the equilibration or
maximum affinity calculation. However, the final diagram is not drawn for
activities of these "residue equivalents", but for rescaled activities of
whole proteins. Because of the rescaling, the fields of the shorter METJA and
METVO proteins grow at the expense of the longer BACLI protein.
* Diagrams **E** and **F** are like the normalization calculation, except that
the final diagram is drawn for the residue equivalents and not the whole
proteins. The predominance diagram is the same as that for non-normalized
reactions (**A**), but the equilibrium activities of residues are higher than
those of the proteins.
## Example 3: Normalization
Here is another figure showing the effects of normalization.
This is like Figure 5 of @Dic08, extended to more extreme conditions.
If you wish to reproduce the diagram from the 2008 paper more closely, uncomment the `add.OBIGT()` command.
```{r ProteinSpeciation, results = "hide", message = FALSE, fig.width = 8, fig.height = 5.5, out.width = "100%", pngquant = pngquant}
organisms <- c("METSC", "METJA", "METFE", "METVO", "METBU",
"HALJP", "ACEKI", "GEOSE", "BACLI", "AERSA")
proteins <- c(rep("CSG", 6), rep("SLAP", 4))
# Use red for Methano* genera
col <- c(rep(2, 5), rep(1, 5))
basis("CHNOS+")
species(proteins, organisms)
a <- affinity(O2 = c(-100, -65))
layout(matrix(1:2), heights = c(1, 2))
e <- equilibrate(a)
diagram(e, ylim = c(-2.8, -1.6), names = organisms, col = col)
water.lines(e, col = 4)
title(main="Equilibrium activities of proteins, normalize = FALSE")
e <- equilibrate(a, normalize = TRUE)
diagram(e, ylim = c(-4, -2), names = organisms, col = col)
water.lines(e, col = 4)
title(main = "Equilibrium activities of proteins, normalize = TRUE")
```
Although it is below the stability limit of H~2~O (vertical dashed line), there
is an interesting convergence of the metastable equilibrium activities of some
proteins at low log *f*~O2~.
## Document history
* 2009-11-29 Initial version with CSG example, titled "Calculating relative abundances of proteins"
* 2012-09-30 Renamed to "Equilibrium in CHNOSZ"; remove activity comparisons and add maximum affinity method.
* 2015-11-08 Move previous material to Appendix and add sections on concepts, organization, examples, and applications; use knitr vignette engine.
* 2020-07-10 Simplify to concepts and examples (amino acids, proteins, normalization); convert document from LaTeX (Rnw) to R Markdown (Rmd).
## References
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/vignettes/equilibrium.Rmd
|
---
title: "Diagrams with multiple metals"
author: "Jeffrey M. Dick"
output:
html_vignette:
mathjax: null
vignette: >
%\VignetteIndexEntry{Diagrams with multiple metals}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
bibliography: [vig.bib, OBIGT.bib]
csl: elementa.csl
link-citations: true
---
<style>
/* https://gomakethings.com/how-to-break-an-image-out-of-its-parent-container-with-css/ */
@media (min-width: 700px) {
.full-width {
left: 50%;
margin-left: -50vw;
margin-right: -50vw;
max-width: 100vw;
position: relative;
right: 50%;
width: 100vw;
}
}
@media (min-width: 1020px) {
.full-width {
left: 50vw; /* fallback if needed */
left: calc(50vw - 160px);
width: 1000px;
position: relative;
background-color: #9ecff7;
padding:10px;
}
}
/* Zero margin around pre blocks (looks more like R console output) */
pre {
margin-top: 0;
margin-bottom: 0;
}
</style>
<script>
function ToggleDiv(ID) {
var D = document.getElementById("D-" + ID);
var B = document.getElementById("B-" + ID);
if (D.style.display === "none") {
// open the div and change button text
D.style.display = "block";
B.innerText = "Hide code";
} else {
// close the div and change button text
D.style.display = "none";
B.innerText = "Show code";
}
}
</script>
```{r setup, include=FALSE}
options(width = 80)
## Use pngquant to optimize PNG images
library(knitr)
knit_hooks$set(pngquant = hook_pngquant)
pngquant <- "--speed=1 --quality=0-25"
if (!nzchar(Sys.which("pngquant"))) pngquant <- NULL
## Resolution settings
# Change this to TRUE to make high-resolution plots
# (default is FALSE to save time in CRAN checks)
hires <- nzchar(Sys.getenv("CHNOSZ_BUILD_LARGE_VIGNETTES"))
res1.lo <- 150
res1.hi <- 256
res1 <- if(hires) res1.hi else res1.lo
res2.lo <- 200
res2.hi <- 400
res2 <- if(hires) res2.hi else res2.lo
## logK with a thin space 20200627
logK <- "log <i>K</i>"
## Set dpi 20231129
knitr::opts_chunk$set(
dpi = if(nzchar(Sys.getenv("CHNOSZ_BUILD_LARGE_VIGNETTES"))) 100 else 72
)
```
```{r CHNOSZ_reset, include=FALSE}
library(CHNOSZ)
reset()
```
This vignette was compiled on `r Sys.Date()` with CHNOSZ version `r sessionInfo()$otherPkgs$CHNOSZ$Version`.
This vignette is associated with a paper that has been published in *Applied Computing and Geosciences* ([Dick, 2021](https://doi.org/10.1016/j.acags.2021.100059 "Diagrams with multiple metals in CHNOSZ")).
Please consider citing that paper if you use the functions or diagrams described here.
The plots in this vignette were made using the following resolution settings.
Low resolutions are used for submitting the package to CRAN.
High resolutions are used if the `CHNOSZ_BUILD_LARGE_VIGNETTES` environment variable is set.
```{r res, results = "asis", echo = FALSE}
cat("```")
cat("\n")
cat(paste0(if(hires) "# " else "", "res1 <- ", res1.lo))
cat("\n")
cat(paste0(if(hires) "" else "# ", "res1 <- ", res1.hi))
cat("\n")
cat(paste0(if(hires) "# " else "", "res2 <- ", res2.lo))
cat("\n")
cat(paste0(if(hires) "" else "# ", "res2 <- ", res2.hi))
cat("\n")
cat("```")
```
Basic diagrams in CHNOSZ are made for reactions that are *balanced on an element* (see [Equilibrium in CHNOSZ](equilibrium.html)) and therefore represent minerals or aqueous species that all have one element, often a metal, in common.
The package documentation has many examples of diagrams for a single metal appearing in different minerals or complexed with different ligands, but a common request is to make diagrams for multiple metals.
This vignette describes some methods for constructing diagrams for multi-metal minerals and other multi-element systems.
The methods are **mashing**, **mixing**, **mosaic stacking**, and **secondary balancing**.
## Mashing
Mashing or simple overlay refers to independent calculations for two different systems that are displayed on the same diagram.
This example starts with a log*f*~O<sub>2</sub>~--pH base diagram for the C-O-H system then overlays a diagram for S-O-H.
The second call to `affinity()` uses the argument recall feature, where the arguments after the first are taken from the previous command.
This allows calculations to be run at the same conditions for a different system.
This feature is also used in other examples in this vignette.
```{r mash, echo = 1:8, eval = FALSE}
par(mfrow = c(1, 2))
basis("CHNOS+")
species(c("CH4", "CO2", "HCO3-", "CO3-2"))
aC <- affinity(pH = c(0, 14), O2 = c(-75, -60))
dC <- diagram(aC, dx = c(0, 1, 0, 0), dy = c(0, 1, 0, 0))
species(c("H2S", "HS-", "HSO4-", "SO4-2"))
aS <- affinity(aC) # argument recall
dS <- diagram(aS, add = TRUE, col = 4, col.names = 4, dx = c(0, -0.5, 0, 0))
aCS <- mash(dC, dS)
srt <- c(0, 0, 90, 0, 0, 0, 90, 0, 0, 0)
cex.names <- c(1, 1, 0.8, 1, 1, 1, 1, 1, 1, 1)
dy <- c(0, 0, 0, -0.2, 0, 0, 0, 0, 0, 0)
diagram(aCS, srt = srt, cex.names = cex.names, dy = dy)
legend("topright", legend = lTP(25, 1), bty = "n")
```
The second diagram is just like the first, except the function `mash()` is used to label the fields with names of species from both systems, and a legend is added to indicate the temperature and pressure.
```{r mash, echo = 9:14, results = "hide", message = FALSE, fig.width = 10, fig.height = 5, out.width = "100%"}
```
Note that these are predominance diagrams, so they show only the species with highest activity; there is in fact a distribution of activities of aqueous species that is not visible here.
Tip: the names of the fields in the second diagram come from `aCS$species$name`, which are expressions made by combining `aC$names` and `aS$names`.
If you prefer plain text names without formatting, add `format.names = FALSE` to all of the `diagram()` calls.
## Mixing 1
As shown above, mashing two diagrams is essentially a simple combination of the two systems.
Although it is easy to make such a diagram, there is no interaction between the systems.
If there is a possibility of forming bimetallic species, then additional considerations are needed to account for the stoichiometry of the mixture.
The stoichiometry can be given as a fixed composition of both metals; then, all combinations of (mono- and/or bimetallic) species that satisfy this compositional constraint are used as the candidate "species" in the system.
This is the same type of calculation as that described for [binary Pourbaix diagrams in the Materials Project](https://matgenb.materialsvirtuallab.org/2017/12/15/Plotting-a-Pourbaix-Diagram.html#Plotting-k-nary-systems).
This example makes a Pourbaix diagram for the Fe-V-O-H system that is similar to Figure 1 of @SZS_17.
Before getting started, it may be helpful to clarify some terminology.
In the materials science community, materials are characterized by several energies (among others): 1) the formation energy from the elements in their reference state, 2) the energy above the convex hull, which is zero for stable materials, and greater than zero for metastable materials, and 3) the Pourbaix energy difference (Δ*G*~pbx~), which refers to the energy of a given material with respect to the stable solids and aqueous species as a function of pH and Eh.
The parallel terminology used in CHNOSZ is that aqueous species or minerals have a 1) standard Gibbs energy of formation from the elements, Δ*G*° = *f*(*T*, *P*), which is available from the [OBIGT database](OBIGT.html), 2) standard Gibbs energy of reaction from the stable species, and 3) affinity of formation from the basis species, *A* = -Δ*G* = *f*(*T*, *P*, and activities of all species).
As used in CHNOSZ, "formation reaction" refers to formation from the basis species, not from the elements.
The basis species **are not** in general the stable species, so we begin by identifying the stable species in the system; the difference between *their* affinities and the affinity of any other species corresponds to -Δ*G*~pbx~.
First we need to assemble the standard Gibbs energies of the solids and aqueous species.
For solids, values of formation energy from the elements (in eV/atom) computed using density functional theory (DFT) were retrieved from the [Materials API](https://github.com/materialsproject/mapidoc) [@OCJ_15] and are converted to units of J/mol.
The Materials Project (MP) website also provides these values, but with fewer decimal places, which would lead to a small rounding error in the comparison of energy above the hull at the end of this example.
For aqueous species, values of standard Gibbs energy of formation from the elements at 25 °C (in J/mol) are taken mostly from @WEP_82 augmented with data for FeO~2~^-^ from @SSWS97 and FeO~4~^-2^ from @Mis73.
Adapting the method described by @PWLC12, a correction for each metal is calculated from the difference between the DFT-based formation energy and the standard Gibbs energy of a representative material; here we use values for Fe~3~O~4~ (magnetite) and V~3~O~5~ from @WEP_82.
This correction is then applied to all of the aqueous species that have that metal.
Finally, `mod.OBIGT()` is used to add the obtained energies to the OBIGT database in CHNOSZ.
<button id="B-materials" onclick="ToggleDiv('materials')">Show code</button>
<div id="D-materials" style="display: none">
```{r materials, message = FALSE, results = "hide"}
## Formation energies (eV / atom) for solids from Materials API, e.g.
# from pymatgen import MPRester
# m = MPRester("USER_API_KEY")
# m.query(criteria={"task_id": "mp-1279742"}, properties=["formation_energy_per_atom"])
# mp-13, mp-1279742, mp-19306, mp-19770
#Fe.cr <- c(Fe = 0, FeO = -1.72803, Fe3O4 = -1.85868, Fe2O3 = -1.90736) # 20201109
Fe.cr <- c(Fe = 0, FeO = -1.72768, Fe3O4 = -1.85838, Fe2O3 = -1.90708) # 20210219
# mp-146, mp-18937, mp-1275946, mp-19094, mp-756395, mp-25279
#V.cr <- c(V = 0, V2O3 = -2.52849, V3O5 = -2.52574, VO2 = -2.48496, V3O7 = -2.32836, V2O5 = -2.29524) # 20201109
V.cr <- c(V = 0, V2O3 = -2.52787, V3O5 = -2.52516, VO2 = -2.48447, V3O7 = -2.32789, V2O5 = -2.29480) # 20210219
# Convert formation energies from eV / atom to eV / molecule
natom.Fe <- sapply(makeup(names(Fe.cr)), sum)
Fe.cr <- Fe.cr * natom.Fe
natom.V <- sapply(makeup(names(V.cr)), sum)
V.cr <- V.cr * natom.V
# Convert formation energies from eV / molecule to J / mol
eVtoJ <- function(eV) eV * 1.602176634e-19 * 6.02214076e23
Fe.cr <- eVtoJ(Fe.cr)
V.cr <- eVtoJ(V.cr)
# Gibbs energies of formation (J / mol) for aqueous species
# Most are from Wagman et al., 1982
Fe.aq <- 1000 * c("Fe+2" = -78.90, "Fe+3" = -4.7, "FeO2-2" = -295.3,
"FeOH+" = -277.4, "FeOH+2" = -229.41, "HFeO2-" = -377.7,
"Fe(OH)2+" = -438.0, "Fe(OH)3" = -659.3,
"FeO2-" = -368.2, # SSWS97
"FeO4-2" = -322.2 # Mis73
)
V.aq <- 1000 * c("VO+2" = -446.4, "VO2+" = -587.0, "VO3-" = -783.6, "VO4-3" = -899.0,
"V2O7-4" = -1719, "HVO4" = -745.1, "HVO4-2" = -974.8,
"VOH2O2+3" = -523.4, "VO2H2O2+" = -746.3, "V2HO7-3" = 1792.2, "V2H3O7-" = -1863.8,
"HV10O28-5" = -7702, "H2V10O28-4" = -7723
)
# Gibbs energies of formation (J / mol) for solids from Wagman et al., 1982
Fe3O4 <- 1000 * -1015.4 # magnetite
V3O5 <- 1000 * -1803
# Calculate correction for difference between reference and DFT energies (Persson et al., 2012)
Fe.corr <- (Fe.cr["Fe3O4"] - Fe3O4) / 3
V.corr <- (V.cr["V3O5"] - V3O5) / 2
# Apply correction to standard Gibbs energies of aqueous species (Persson et al., 2012)
nFe <- sapply(makeup(names(Fe.aq)), "[", "Fe")
Fe.aq <- Fe.aq + nFe * Fe.corr
nV <- sapply(makeup(names(V.aq)), "[", "V")
V.aq <- V.aq + nV * V.corr
# Add energies to OBIGT
# This function modifies OBIGT and returns the species indices of the affected species
modfun <- function(x, state, model = NULL) sapply(seq_along(x), function(i) {
# We explicitly set the units to Joules (this is the default as of CHNOSZ 2.0.0)
if(is.null(model)) mod.OBIGT(names(x)[i], formula = names(x)[i], state = state, E_units = "J", G = x[i])
else mod.OBIGT(names(x)[i], formula = names(x)[i], state = state, model = model, E_units = "J", G = x[i])
})
# We need model = "CGL" to override the Berman model for some minerals 20220919
iFe.cr <- modfun(Fe.cr, "cr", model = "CGL")
iFe.aq <- modfun(Fe.aq, "aq")
iV.cr <- modfun(V.cr, "cr", model = "CGL")
iV.aq <- modfun(V.aq, "aq")
# Formation energies (eV / atom) for bimetallic solids from Materials API
# mp-1335, mp-1079399, mp-866134, mp-558525, mp-504509 (triclinic FeVO4)
#FeV.cr <- c(FeV = -0.12928, FeV3 = -0.17128, Fe3V = -0.12854, Fe2V4O13 = -2.23833, FeVO4 = -1.75611) # 20201109
FeV.cr <- c(FeV = -0.12815, FeV3 = -0.17114, Fe3V = -0.12832, Fe2V4O13 = -2.23967, FeVO4 = -1.75573) # 20210219
# Convert energies and add to OBIGT
natom.FeV <- sapply(makeup(names(FeV.cr)), sum)
FeV.cr <- FeV.cr * natom.FeV
FeV.cr <- eVtoJ(FeV.cr)
iFeV.cr <- modfun(FeV.cr, "cr")
```
</div>
This code produces species indices in the OBIGT database for Fe- and V-bearing aqueous species (`iFe.aq`, `iV.aq`), solids (`iFe.cr`, `iV.cr`), and bimetallic solids (`iFeV.cr`), which are used in the following diagrams.
Now we set up the plot area and assign activities of aqueous species to 10^-5^, which is the default value for diagrams on the MP website (from the page for a material: "Generate Phase Diagram" -- "Aqueous Stability (Pourbaix)").
The following commands compute Eh-pH diagrams for the single-metal systems Fe-O-H and V-O-H.
The pH and Eh ranges are made relatively small in order to show just a part of the diagram.
The diagrams are not plotted, but the output of `diagram()` is saved in `dFe` and `dV` for later use.
```{r mixing1, eval = FALSE, echo = 1:14}
par(mfrow = c(1, 3))
loga.Fe <- -5
loga.V <- -5
# Fe-O-H diagram
basis(c("VO+2", "Fe+2", "H2O", "e-", "H+"))
species(c(iFe.aq, iFe.cr))
species(1:length(iFe.aq), loga.Fe)
aFe <- affinity(pH = c(4, 10, res1), Eh = c(-1.5, 0, res1))
dFe <- diagram(aFe, plot.it = FALSE)
# V-O-H diagram
species(c(iV.aq, iV.cr))
species(1:length(iV.aq), loga.V)
aV <- affinity(aFe) # argument recall
dV <- diagram(aV, plot.it = FALSE)
# Calculate affinities for bimetallic species
species(iFeV.cr)
aFeV <- affinity(aFe) # argument recall
dFeV <- diagram(aFeV, plot.it = FALSE, bold = TRUE)
# 1:1 mixture (Fe:V)
a11 <- mix(dFe, dV, dFeV, c(1, 1))
# Adjust labels 20210219
iV2O3 <- info("V2O3")
iFeO <- info("FeO", "cr")
iFe3V <- info("Fe3V")
srt <- rep(0, nrow(a11$species))
srt[a11$species$ispecies == paste(iFeO, iV2O3, sep = ",")] <- 90
srt[a11$species$ispecies == paste(iV2O3, iFe3V, sep = ",")] <- -13
diagram(a11, min.area = 0.01, srt = srt)
title("Fe:V = 1:1")
label.figure(lTP(25, 1), xfrac = 0.12)
# 1:3 mixture
a13 <- mix(dFe, dV, dFeV, c(1, 3))
srt <- rep(0, nrow(a13$species))
srt[a13$species$ispecies == paste(iFeO, iV2O3, sep = ",")] <- 90
srt[a13$species$ispecies == paste(iV2O3, iFe3V, sep = ",")] <- -13
diagram(a13, min.area = 0.01, srt = srt)
title("Fe:V = 1:3")
# 1:5 mixture
a15 <- mix(dFe, dV, dFeV, c(1, 5))
iFeV3 <- info("FeV3")
srt <- rep(0, nrow(a15$species))
srt[a15$species$ispecies == paste(iFeO, iV2O3, sep = ",")] <- 90
srt[a15$species$ispecies == paste(iV2O3, iFe3V, sep = ",")] <- -13
srt[a15$species$ispecies == paste(iV2O3, iFeV3, sep = ",")] <- -13
diagram(a15, min.area = 0.01, srt = srt)
title("Fe:V = 1:5")
```
Then we calculate the affinities for the bimetallic species and save the output of `diagram()` in `dFeV`, again without making a plot, but formatting the names in bold.
Note that `diagram()` uses different colors for regions with two solids, one solid, and no solids, including some transparency to show the underlying water stability region that is plotted first.
Now we have all the ingredients needed to combine the Fe-bearing, V-bearing, and bimetallic species to generate a given composition.
The `mix()` function is used to calculate the affinities of formation from basis species for all combinations of aqueous species and minerals that satisfy each of three different compositions.
Finally, the `diagram()`s are plotted; the `min.area` argument is used to remove labels for very small fields.
Regarding the legend, it should be noted that although the DFT calculations for solids are made for zero temperature and zero pressure [@SZS_17], the standard Gibbs energies of aqueous species [e.g. @WEP_82] are modified by a correction term so that they can be combined with DFT energies to reproduce the experimental energy for dissolution of a representative material for each metal at 25 °C and 1 bar [@PWLC12].
```{r mixing1, echo = 16:47, message = FALSE, results = "hide", fig.width = 9, fig.height = 3, out.width = "100%", out.extra='class="full-width"', pngquant = pngquant}
```
In these diagrams, changing the Fe:V ratio affects the fully reduced metallic species.
In the 1:1 mixture, the FeV~3~ + Fe~3~V assemblage is predicted to be stable instead of FeV.
This result is unlike Figure 1 of @SZS_17 but is consistent with the [MP page for FeV](https://doi.org/10.17188/1189535) where it is shown to decompose to this assemblage.
On the other hand, [FeV~3~ is stable](https://next-gen.materialsproject.org/materials/mp-1079399/) in the 1:3 mixture.
For an even higher proportion of V, the V + FeV~3~ assemblage is stable, which can be seen for instance in the Pourbaix diagram linked from the [MP page for FeV~5~O~12~](https://doi.org/10.17188/1305091).
Let's make another diagram for the 1:1 Fe:V composition over a broader range of Eh and pH.
The diagram shows a stable assemblage of Fe~2~O~3~ with an oxidized bimetallic material, [Fe~2~V~4~O~13~](https://next-gen.materialsproject.org/materials/mp-1200054/).
```{r FeVO4, eval = FALSE, echo = 1:29}
layout(t(matrix(1:3)), widths = c(1, 1, 0.2))
par(cex = 1)
# Fe-bearing species
basis(c("VO+2", "Fe+2", "H2O", "e-", "H+"))
species(c(iFe.aq, iFe.cr))$name
species(1:length(iFe.aq), loga.Fe)
aFe <- affinity(pH = c(0, 14, res2), Eh = c(-1.5, 2, res2))
dFe <- diagram(aFe, plot.it = FALSE)
# V-bearing species
species(c(iV.aq, iV.cr))$name
species(1:length(iV.aq), loga.V)
aV <- affinity(aFe) # argument recall
dV <- diagram(aV, plot.it = FALSE)
# Bimetallic species
species(iFeV.cr)
aFeV <- affinity(aFe) # argument recall
dFeV <- diagram(aFeV, plot.it = FALSE, bold = TRUE)
# 1:1 mixture (Fe:V)
a11 <- mix(dFe, dV, dFeV, c(1, 1))
# Adjust labels 20210219
iV2O3 <- info("V2O3")
iFe3V <- info("Fe3V")
iVO4m3 <- info("VO4-3")
iFe2O3 <- info("Fe2O3")
srt <- rep(0, nrow(a11$species))
srt[a11$species$ispecies == paste(iV2O3, iFe3V, sep = ",")] <- -13
srt[a11$species$ispecies == paste(iFe2O3, iVO4m3, sep = ",")] <- 90
d11 <- diagram(a11, min.area = 0.01, srt = srt)
water.lines(d11, col = "orangered")
# Calculate affinity of FeVO4
species("FeVO4")
aFeVO4 <- affinity(aFe) # argument recall
# Calculate difference from stable species
aFeVO4_vs_stable <- aFeVO4$values[[1]] - d11$predominant.values
# Overlay lines from diagram on color map
diagram(a11, fill = NA, names = FALSE, limit.water = FALSE)
opar <- par(usr = c(0, 1, 0, 1))
col <- rev(topo.colors(128)) # No hcl.colors() in R < 3.6.0
if(getRversion() >= "3.6.0") col <- rev(hcl.colors(128, palette = "YlGnBu", alpha = 0.8))
image(aFeVO4_vs_stable, col = col, add = TRUE)
par(opar)
diagram(a11, fill = NA, add = TRUE, names = FALSE)
water.lines(d11, col = "orangered")
thermo.axis()
imax <- arrayInd(which.max(aFeVO4_vs_stable), dim(aFeVO4_vs_stable))
pH <- d11$vals$pH[imax[1]]
Eh <- d11$vals$Eh[imax[2]]
points(pH, Eh, pch = 10, cex = 2, lwd = 2, col = "gold")
stable <- d11$names[d11$predominant[imax]]
text(pH, Eh, stable, adj = c(0.5, -1), cex = 1.2, col = "gold")
# Make color scale 20210228
par(mar = c(3, 0, 2.5, 2.7))
plot.new()
levels <- 1:length(col)
plot.window(xlim = c(0, 1), ylim = range(levels), xaxs = "i", yaxs = "i")
rect(0, levels[-length(levels)], 1, levels[-1L], col = rev(col), border = NA)
box()
# To get the limits, convert range of affinities to eV/atom
arange <- rev(range(aFeVO4_vs_stable))
# This gets us to J/mol
Jrange <- convert(arange, "G")
# And to eV/atom
eVrange <- Jrange / 1.602176634e-19 / 6.02214076e23 / 6
ylim <- formatC(eVrange, digits = 3, format = "f")
axis(4, at = range(levels), labels = ylim)
mtext(quote(Delta*italic(G)[pbx]*", eV/atom"), side = 4, las = 0, line = 1)
```
We then compute the affinity for formation of a metastable material, in this case triclinic FeVO~4~, from the same basis species used to make the previous diagrams.
Given the diagram for the stable Fe-, V- and bimetallic materials *mixed with the same stoichiometry* as FeVO~4~ (1:1 Fe:V), the difference between their affinities of formation and that of FeVO~4~ corresponds to the Pourbaix energy difference (-Δ*G*~pbx~).
This is plotted as a color map in the second diagram.
(See the source of this vignette for the code used to make the scale bar.)
```{r FeVO4, echo = 31:44, message = FALSE, results = "hide", fig.width = 11, fig.height = 5, out.width = "100%", pngquant = pngquant}
```
Now we locate the pH and Eh that maximize the affinity (that is, minimize Δ*G*~pbx~) of FeVO~4~ compared to the stable species.
In agreement with @SZS_17, this is in the stability field of Fe~2~O~3~ + Fe~2~V~4~O~13~.
```{r Gpbx_min, echo = 2:8, message = FALSE, fig.keep = "none"}
plot(1:10) # so we can run "points" in this chunk
imax <- arrayInd(which.max(aFeVO4_vs_stable), dim(aFeVO4_vs_stable))
pH <- d11$vals$pH[imax[1]]
Eh <- d11$vals$Eh[imax[2]]
points(pH, Eh, pch = 10, cex = 2, lwd = 2, col = "gold")
stable <- d11$names[d11$predominant[imax]]
text(pH, Eh, stable, adj = c(0.3, 2), cex = 1.2, col = "gold")
(Apbx <- range(aFeVO4_vs_stable[d11$predominant == d11$predominant[imax]]))
```
Although one point is drawn on the diagram, FeVO~4~ has the same Pourbaix energy difference with respect to the entire Fe~2~O~3~ + Fe~2~V~4~O~13~ field, as shown by the `range()` command (the values are dimensionless values of affinity, *A*/(*RT*) = -Δ*G*~pbx~/(*RT*)).
This can occur only if the decomposition reaction has no free O~2~ or H~2~, and means that in this case Δ*G*~pbx~ in the Fe~2~O~3~ + Fe~2~V~4~O~13~ field is equal to the energy above the hull.
To calculate the energy above the hull "by hand", let's set up the basis species to be the stable decomposition products we just found.
O~2~ is also needed to make a square stoichiometric matrix (i.e. same number of elements and basis species), but it does not appear in the reaction to form FeVO~4~ from the basis species.
`subcrt()` is used to automatically balance the formation reaction for 1 mole of FeVO~4~ and calculate the standard Gibbs energy of the reaction.
We first test that `r logK` of the reaction (calculated with `convert()`, which divides Δ*G*° by *-RT*) is the same as the dimensionless affinity for FeVO~4~ calculated above.
Then, the value of Δ*G*° in J/mol is converted to eV/mol, and finally eV/atom.
```{r hull, message = FALSE}
b <- basis(c("Fe2O3", "Fe2V4O13", "O2"))
J_mol <- subcrt("FeVO4", 1, T = 25)$out$G
stopifnot(all.equal(rep(convert(J_mol, "logK"), 2), Apbx))
eV_mol <- J_mol / 1.602176634e-19
eV_atom <- eV_mol / 6.02214076e23 / 6
round(eV_atom, 3)
stopifnot(round(eV_atom, 3) == 0.415)
```
This is equal to the value for the energy above the hull / atom for [triclinic FeVO~4~ on the MP website](https://next-gen.materialsproject.org/materials/mp-504509/) (0.415 eV, accessed on 2020-11-09 and 2021-02-19).
This shows that we successfully made a round trip starting with the input formation energies (eV/atom) from the Materials API, to standard Gibbs energy (J/mol) in the OBIGT database, and back out to energy above the hull (eV/atom).
The concept of using the stable minerals and aqueous species to calculate reaction energetics is formalized in the `mosaic()` function, which is described next.
Because this example modified the thermodynamic data for some minerals that are used below, we should restore the default OBIGT database before proceeding to the next section.
```{r reset, message = FALSE}
reset()
```
## Mosaic Stacking 1
*For a function that implements the workflow described below, see `stack_mosaic()` (added in CHNOSZ 2.0.0).*
A mosaic diagram shows the effects of changing basis species on the stabilities of minerals.
The Fe-S-O-H system is a common example: the speciation of aqueous sulfur species affects the stabilities of iron oxides and sulfides.
Examples of mosaic diagrams with Fe or other single metals are given elsewhere.
A mosaic stack is when predominance fields for minerals calculated in one mosaic diagram are used as input to a second mosaic diagram, where the minerals are now themselves basis species.
The example here shows the construction of a Cu-Fe-S-O-H diagram.
First we define the conditions and basis species.
It is important to put Cu^+^ first so that it will be used as the balance for the reactions with Cu-bearing minerals (which also have Fe).
Pyrite is chosen as the starting Fe-bearing basis species, which will be changed as indicated in `Fe.cr`.
```{r stack1_1, results = "hide", message = FALSE}
logaH2S <- -2
T <- 200
pH <- c(0, 14, res2)
O2 <- c(-48, -33, res2)
basis(c("Cu+", "pyrite", "H2S", "oxygen", "H2O", "H+"))
basis("H2S", logaH2S)
S.aq <- c("H2S", "HS-", "HSO4-", "SO4-2")
Fe.cr <- c("pyrite", "pyrrhotite", "magnetite", "hematite")
Fe.abbrv <- c("Py", "Po", "Mag", "Hem")
```
Now we calculate affinities for minerals in the Fe-S-O-H system that take account of the changing aqueous sulfur species in `S.aq`.
The result is used to make different layers of the diagram (1 and 2 are both made by the first call to `diagram()`):
1. Water stability region (gray shading)
2. Predominance fields for the aqueous S species (blue text and dashed lines)
3. Stability areas for the Fe-bearing minerals (black text and lines)
```{r stack1_2, eval = FALSE, echo = 1:4}
species(Fe.cr)
mFe <- mosaic(S.aq, pH = pH, O2 = O2, T = T)
diagram(mFe$A.bases, lty = 2, col = 4, col.names = 4, italic = TRUE, dx = c(0, 1, 0, 0), dy = c(-1.5, 0, 1, 0))
dFe <- diagram(mFe$A.species, add = TRUE, lwd = 2, names = Fe.abbrv, dx = c(0, 0.5, 0, 0), dy = c(-1, 0, 0.5, 0))
FeCu.cr <- c("chalcopyrite", "bornite")
Cu.cr <- c("copper", "cuprite", "tenorite", "chalcocite", "covellite")
FeCu.abbrv <- c("Ccp", "Bn", "Cu", "Cpr", "Tnr", "Cct", "Cv")
species(c(FeCu.cr, Cu.cr))
mFeCu <- mosaic(list(S.aq, Fe.cr), pH = pH, O2 = O2,
T = T, stable = list(NULL, dFe$predominant))
col <- c("#FF8C00", rep(2, 6))
lwd <- c(2, 1, 1, 1, 1, 1, 1)
dy = c(0, 0, 0, 0, 0, 1, 0)
diagram(mFeCu$A.species, add = TRUE, col = col, lwd = lwd, col.names = col, bold = TRUE, names = FeCu.abbrv, dy = dy)
TPS <- c(describe.property(c("T", "P"), c(T, "Psat")), expression(sum(S) == 0.01*m))
legend("topright", TPS, bty = "n")
title("Cu-Fe-S-O-H (minerals only)", font.main = 1)
```
Next we load the Cu-bearing minerals and calculate their affinities while changing *both* the aqueous sulfur species and the Fe-bearing minerals whose stability fields were just calculated.
The latter step is the key to the mosaic stack and is activated by supplying the calculated stabilities of the Fe-bearing minerals in the `stable` argument.
This is a list whose elements correspond to each group of changing basis species given in the first argument.
The NULL means that the abundances of S-bearing aqueous species are calculated according to the default in `mosaic()`, which uses `equilibrate()` to compute the continuous transition between them ("blending").
Because the Fe-bearing minerals are the second group of changing basis species (`Fe.cr`), their stabilities are given in the second position of the `stable` list.
The result is used to plot the last layer of the diagram:
4. Stability areas for Cu-bearing minerals (red text and lines; orange for chalcopyrite)
After that we add the legend and title.
```{r stack1_2, echo=5:17, results = "hide", message = FALSE, fig.width = 6, fig.height = 5, out.width = "75%", fig.align = "center", pngquant = pngquant}
```
This diagram has a distinctive chalcopyrite "hook" surrounded by a thin bornite field.
Only the chalcopyrite-bornite reaction in the pyrite field is shown in some published diagrams [e.g. @And75;@Gio02], but diagrams with a similar chalcopyrite wedge or hook geometry can be seen in @BBR77 and @Bri80.
## Mosaic Stacking 2
The previous diagram shows the relative stabilities of minerals only.
The next diagram adds aqueous species to the system.
The position of the boundaries between the stability fields for minerals and aqueous species are calculated for a given activity for the latter, in this case 10^-6^.
<button id="B-stack2" onclick="ToggleDiv('stack2')">Show code</button>
<div id="D-stack2" style="display: none">
```{r stack2, eval = FALSE}
# Define system
pH <- c(0, 14, res2)
O2 <- c(-48, -33, res2)
T <- 200
logmS <- -2
m_NaCl <- 0.1
logm_aq <- -6 # for both Fe- and Cu-bearing aq species
# Basis species
S.aq <- c("H2S", "HS-", "HSO4-", "SO4-2")
# Minerals
Fe.cr <- c("pyrite", "pyrrhotite", "magnetite", "hematite")
Fe.abbrv <- c("Py", "Po", "Mag", "Hem")
FeCu.cr <- c("chalcopyrite", "bornite")
Cu.cr <- c("copper", "cuprite", "tenorite", "chalcocite", "covellite")
FeCu.abbrv <- c("Ccp", "Bn", "Cu", "Cpr", "Tnr", "Cct", "Cv")
# Aqueous species
iFe.aq <- retrieve("Fe", c("S", "O", "H", "Cl"), "aq")
Fe.aq <- info(iFe.aq)$name
iCu.aq <- retrieve("Cu", c("S", "O", "H", "Cl"), "aq")
Cu.aq <- info(iCu.aq)$name
# Expressions for making the legend
TPexpr <- describe.property(c("T", "P"), c(T, "Psat"))
Sexpr <- as.expression(bquote(sum(S) == .(10^logmS)*m))
NaClexpr <- as.expression(bquote(NaCl == .(m_NaCl)*m))
aqexpr <- as.expression(bquote("("*aq*")"[italic(i)] == 10^.(logm_aq)*m))
# Setup basis species
basis(c("Cu+", "pyrite", "H2S", "oxygen", "H2O", "H+", "Cl-"))
basis("H2S", logmS)
nacl <- NaCl(m_tot = m_NaCl, T = T, P = "Psat")
basis("Cl-", log10(nacl$m_Cl))
# Fe-bearing minerals
species(Fe.cr)
# Add aqueous species 20210220
species(iFe.aq, logm_aq, add = TRUE)
mFe <- mosaic(S.aq, pH = pH, O2 = O2, T = T, IS = nacl$IS)
# Start plot with just the fields for transparency effect
dFe <- diagram(mFe$A.species, lwd = 0, names = FALSE)
# Cu-bearing minerals
species(c(FeCu.cr, Cu.cr))
# Add aqueous species 20210220
species(iCu.aq, logm_aq, add = TRUE)
## Mosaic with all Fe species as basis species
#mFeCu <- mosaic(list(S.aq, c(Fe.cr, Fe.aq)), pH = pH, O2 = O2, T = T, stable = list(NULL, dFe$predominant))
# Use only predominant Fe species as basis species (to speed up calculation) 20210224
predom <- dFe$predominant
ipredom <- sort(unique(as.numeric(predom)))
for(i in seq_along(ipredom)) predom[dFe$predominant == ipredom[i]] <- i
Fe.predom <- c(Fe.cr, Fe.aq)[ipredom]
# Use loga_aq argument to control the activity of aqueous species in mosaic calculation 20220722
# c(NA, logm_aq) means to use:
# basis()'s value for logact of aqueous S species
# logm_aq for logact of aqueous Fe species
mFeCu <- mosaic(list(S.aq, Fe.predom), pH = pH, O2 = O2, T = T, stable = list(NULL, predom), IS = nacl$IS, loga_aq = c(NA, logm_aq))
# Adjust labels
bold <- c(rep(TRUE, length(FeCu.abbrv)), rep(FALSE, length(Cu.aq)))
names <- c(FeCu.abbrv, Cu.aq)
srt <- dx <- dy <- rep(0, length(names))
cex <- rep(1, length(names))
dx[names == "Cu"] <- -1.5
dx[names == "Bn"] <- 1.4
dx[names == "CuHS"] <- 1
dx[names == "Cu+"] <- -0.5
dy[names == "Cu"] <- 3
dx[names == "Cct"] <- -2
dy[names == "Cct"] <- 4
dy[names == "CuHS"] <- 1
dy[names == "Bn"] <- -0.9
dx[names == "CuCl2-"] <- -1
dy[names == "CuCl2-"] <- 2
cex[names == "Bn"] <- 0.8
srt[names == "Bn"] <- 85
# Highlight Ccp field
col.names <- col <- rep(2, nrow(mFeCu$A.species$species))
col[1] <- "#FF8C00"
col.names[1] <- "#FF8C00"
lwd <- rep(1, nrow(mFeCu$A.species$species))
lwd[1] <- 2
diagram(mFeCu$A.species, add = TRUE, lwd = lwd, col = col, col.names = col.names, names = names, bold = bold, dx = dx, dy = dy, cex.names = cex, srt = srt)
# Add second Cu label
text(12.3, -47, "Cu", col = 2, font = 2)
# Plot the Fe-system lines and names "on top" so they are not covered by fill colors
diagram(mFe$A.bases, add = TRUE, lty = 2, col = 4, names = FALSE, fill = NA)
bold <- c(rep(TRUE, length(Fe.abbrv)), rep(FALSE, length(Fe.aq)))
names <- c(Fe.abbrv, Fe.aq)
srt <- dx <- dy <- rep(0, length(names))
cex <- rep(1, length(names))
dy[names == "Hem"] <- 0.5
dy[names == "Mag"] <- -0.8
dx[names == "Hem"] <- -0.5
dx[names == "Mag"] <- 0.25
dx[names == "Fe+2"] <- 0.5
dx[names == "FeO2-"] <- 1
dy[names == "FeO2-"] <- -3
dx[names == "HFeO2-"] <- -0.5
dy[names == "HFeO2-"] <- 1
srt[names == "Mag"] <- 83
srt[names == "FeSO4"] <- 90
diagram(mFe$A.species, add = TRUE, lwd = 2, names = names, bold = bold, dx = dx, dy = dy, cex.names = cex, srt = srt, fill = NA)
legend("topright", c(TPexpr, Sexpr, NaClexpr, aqexpr), bty = "n")
title("Cu-Fe-S-O-H-Cl (minerals and aqueous species)", font.main = 1)
# Restore default OBIGT database
OBIGT()
```
</div>
```{r stack2, echo = FALSE, results = "hide", message = FALSE, fig.width = 6, fig.height = 5, out.width = "75%", fig.align = "center", pngquant = pngquant}
```
After running the code to make this diagram, we can list the reference keys for the minerals and aqueous species.
```{r stack2.refs, message = FALSE}
minerals <- list(Fe.cr = Fe.cr, Cu.cr = Cu.cr, FeCu.cr = FeCu.cr)
aqueous <- list(S.aq = S.aq, Fe.aq = Fe.aq, Cu.aq = Cu.aq)
allspecies <- c(minerals, aqueous)
iall <- lapply(allspecies, info)
allkeys <- lapply(iall, function(x) thermo.refs(x)$key)
allkeys
```
The next code chunk prepends `@` to the reference keys and uses the chunk option [`results = 'asis'`](https://bookdown.org/yihui/rmarkdown-cookbook/results-asis.html) to insert the citations into the R Markdown document in chronological order.
```{r stack2.cite, results = "asis"}
allyears <- lapply(iall, function(x) thermo.refs(x)$year)
o <- order(unlist(allyears))
keys <- gsub("\\..*", "", unique(unlist(allkeys)[o]))
cat(paste(paste0("@", keys), collapse = "; "))
```
## Mixing 2
The previous diagram shows a stability boundary between chalcopyrite and bornite but does not identify the stable *assemblages* that contain these minerals.
This is where `mix()` can help.
Following the workflow described in **Mixing 1**, we first calculate individual diagrams for Fe-S-O-H and Cu-S-O-H, which are overlaid on the first plot and saved in `dFe` and `dCu`.
We then calculate the affinities for the bimetallic Cu and Fe minerals and run them through `diagram()` without actually making a plot, but save the result in `dFeCu`.
Then, we combine the results using `mix()` to define different proportions of Fe and Cu.
<button id="B-mixing2" onclick="ToggleDiv('mixing2')">Show code</button>
<div id="D-mixing2" style="display: none">
```{r mixing2, eval = FALSE}
par(mfrow = c(2, 2))
logaH2S <- -2
T <- 200
pH <- c(0, 14)
O2 <- c(-60, -25)
basis(c("Cu+", "Fe+2", "H2S", "oxygen", "H2O", "H+"))
basis("H2S", logaH2S)
S.aq <- c("H2S", "HS-", "HSO4-", "SO4-2")
Fe.cr <- c("pyrite", "pyrrhotite", "magnetite", "hematite")
Cu.cr <- c("copper", "cuprite", "tenorite", "chalcocite", "covellite")
FeCu.cr <- c("chalcopyrite", "bornite")
species(Fe.cr)
mFe <- mosaic(S.aq, pH = pH, O2 = O2, T = T)
diagram(mFe$A.bases, lty = 2, col = 4, col.names = 4, italic = TRUE, dx = c(0, 1, 0, 0), dy = c(-1, 0, -2, 0))
names <- info(info(Fe.cr))$abbrv
dFe <- diagram(mFe$A.species, add = TRUE, names = names)
species(Cu.cr)
mCu <- mosaic(S.aq, pH = pH, O2 = O2, T = T)
names <- info(info(Cu.cr))$abbrv
col.names <- rep(2, length(names))
col.names[1] <- 0
dCu <- diagram(mCu$A.species, add = TRUE, col = 2, col.names = col.names, names = names)
text(12, -55, "Cu", col = 2)
legend("topright", legend = lTP(T, "Psat"), bty = "n")
title(paste("Fe-S-O-H and Cu-S-O-H; Total S =", 10^logaH2S, "m"))
species(FeCu.cr)
mFeCu <- mosaic(S.aq, pH = pH, O2 = O2, T = T)
names <- info(info(FeCu.cr))$abbrv
dFeCu <- diagram(mFeCu$A.species, plot.it = FALSE, names = names)
fill <- function(a) {
ifelse(grepl("Ccp", a$species$name), "#FF8C0088",
ifelse(grepl("Bn", a$species$name), "#DC143C88", NA)
)}
srt <- function(a) ifelse(a$species$name %in% c("Mag+Bn", "Mag+Ccp"), 80, 0)
cex.names <- function(a) ifelse(a$species$name %in% c("Mag+Bn", "Mag+Ccp", "Mag+Cct"), 0.8, 1)
dx <- function(a) sapply(a$species$name, switch, "Mag+Bn" = 0.15, "Mag+Cct" = 0.5, 0)
dy <- function(a) sapply(a$species$name, switch, "Py+Bn" = -1, "Po+Bn" = -0.8, "Po+Cu" = -0.8, "Mag+Ccp" = -1, 0)
a11 <- mix(dFe, dCu, dFeCu)
diagram(a11, fill = fill(a11), srt = srt(a11), min.area = 0.01, dx = dx(a11), dy = dy(a11), cex.names = cex.names(a11))
title("Fe:Cu = 1:1")
a21 <- mix(dFe, dCu, dFeCu, c(2, 1))
diagram(a21, fill = fill(a21), srt = srt(a21), min.area = 0.01, dx = dx(a21), dy = dy(a21), cex.names = cex.names(a21))
title("Fe:Cu = 2:1")
a12 <- mix(dFe, dCu, dFeCu, c(1, 2))
diagram(a12, fill = fill(a12), srt = srt(a12), min.area = 0.01, dx = dx(a12), dy = dy(a12), cex.names = cex.names(a12))
title("Fe:Cu = 1:2")
```
</div>
```{r mixing2, echo = FALSE, results = "hide", message = FALSE, fig.width = 8, fig.height = 6.5, out.width = "100%", pngquant = pngquant}
```
These diagrams show that changing the amounts of the metals affects the stability of minerals involved in reactions with chalcopyrite.
At a 1:1 ratio of Fe:Cu, chalcopyrite is a stable single-mineral assemblage.
At a 2:1 ratio, pyrite, pyrrhotite, or magnetite can coexist in a two-phase assemblage with chalcopyrite.
At a 1:2 ratio, an assemblage consisting of the two bimetallic minerals (chalcopyrite and bornite) is stable.
## Mosaic Stacking 3
The results of a mosaic stack can also be processed with `mash()` to label each region with the minerals from both systems.
For this example, the speciation of aqueous sulfur is not considered; instead, the fugacity of S~2~ is a plotting variable.
The stable Fe-bearing minerals (Fe-S-O-H) are used as the changing basis species to make the diagram for Cu-bearing minerals (Cu-Fe-S-O-H).
Then, the two diagrams are mashed to show all minerals in a single diagram.
Greener colors are used to indicate minerals with less S~2~ and more O~2~ in their formation reactions.
<button id="B-stack3" onclick="ToggleDiv('stack3')">Show code</button>
<div id="D-stack3" style="display: none">
```{r stack3, eval = FALSE}
T <- 125
layout(matrix(c(1, 2, 3, 3), nrow = 2), widths = c(1, 1.5))
# Fe-S-O-H diagram
basis(c("copper", "hematite", "S2", "oxygen", "H2O", "H+", "Cl-"))
bFe <- species(c("hematite", "magnetite", "pyrite"))$name
aFe <- affinity(S2 = c(-34, -10, res1), O2 = c(-55, -40, res1), T = T)
# Order species by a function of composition to make colors
oFe <- order(aFe$species$S2 - aFe$species$O2)
fill <- terrain.colors(length(oFe), alpha = 0.2)[oFe]
abbrv <- info(aFe$species$ispecies)$abbrv
dFe <- diagram(aFe, names = abbrv, fill = fill)
title("Fe-S-O-H")
# Cu-Fe-S-O-H diagram based on reactions with the
# stable Fe-bearing minerals (mosaic stack)
bCu <- species(c("copper", "chalcocite", "covellite", "chalcopyrite", "bornite"))$name
mCu <- mosaic(bFe, S2 = c(-34, -10, res1), O2 = c(-55, -40, res1),
T = T, stable = list(dFe$predominant))
oCu <- order(mCu$A.species$species$S2 - mCu$A.species$species$O2)
fill <- terrain.colors(length(oCu), alpha = 0.2)[oCu]
abbrv <- info(mCu$A.species$species$ispecies)$abbrv
dCu <- diagram(mCu$A.species, names = abbrv, fill = fill, dx = c(0, 0, 0, 0, 1.8))
title("Cu-Fe-S-O-H")
# Mash the diagrams and adjust labels
aFeCu <- mash(dFe, dCu)
names <- aFeCu$species$name
dx <- dy <- srt <- rep(0, length(names))
cex <- rep(1, length(names))
cex[names %in% c("Hem+Ccp", "Hem+Cv")] <- 0.8
srt[names %in% c("Mag+Cu", "Hem+Cu")] <- 90
srt[names %in% c("Mag+Bn", "Hem+Bn")] <- 63
srt[names %in% c("Mag+Ccp", "Hem+Ccp")] <- 68
srt[names %in% c("Py+Bn", "Py+Cv")] <- 90
dx[names == "Hem+Ccp"] <- -0.4
dy[names == "Hem+Ccp"] <- -0.5
oFeCu <- order(aFeCu$species$S2 - aFeCu$species$O2)
fill <- terrain.colors(length(oFeCu), alpha = 0.2)[oFeCu]
diagram(aFeCu, cex.names = cex, srt = srt, dx = dx, dy = dy, fill = fill)
legend("topleft", legend = lTP(T, "Psat"), bg = "white")
title("Cu-Fe-S-O-H")
```
</div>
```{r stack3, echo = FALSE, results = "hide", message = FALSE, fig.width = 6, fig.height = 4, out.width = "100%", pngquant = pngquant}
```
The resulting diagram is similar to Figure 2 of @Sve87; that diagram also shows calculations of the solubility of Cu and concentration of SO~4~^-2^ in model Cu ore-forming fluids.
The `solubility()` function can be used to calculate the total concentration of Cu in different complexes in solution (listed in the `iaq` argument).
The `bases` argument triggers a `mosaic()` calculation, so that the solubility corresponds that that of stable minerals at each point on the diagram.
The pH for these calculations is set to 6, and the molality of free Cl^-^, which affects the formation of the Cu chloride complexes, is estimated based on the composition of fluids from Table 2 of @Sve87 (ca. 80000 mg Cl / kg H~2~O) and the `NaCl()` function in CHNOSZ.
This also gives an estimated ionic strength, which is used in the following `mosaic()` and `affinity()` calls to calculate activity coefficients.
<button id="B-solubility" onclick="ToggleDiv('solubility')">Show code</button>
<div id="D-solubility" style="display: none">
```{r solubility, eval = FALSE}
par(mfrow = c(1, 3))
basis("pH", 6)
# Estimate the molality of Cl for ca. 80,000 mg/kg solution (Table 2 of Sverjensky, 1987)
m_tot <- 80000 / mass("Cl") / 1000
calc <- NaCl(T = T, m_tot = m_tot)
# Use log molality here, not log activity, because
# activity coefficients are calculated by setting IS below
basis("Cl-", log10(calc$m_Cl))
# Initial setup: dissolve a single mineral to form aqueous Cu complexes
species("copper")
iaq <- retrieve("Cu", c("O", "H", "Cl", "S"), "aq")
# Function to calculate solubility of Cu for stable assemblages of Fe and Cu minerals
# (i.e. equilibrium is imposed with all of these minerals, not only Cu(s))
mfun <- function() {
s <- solubility(iaq, bases = list(bFe, bCu), S2 = c(-34, -10, res1), O2 = c(-55, -40, res1),
T = T, IS = calc$IS, stable = list(dFe$predominant, dCu$predominant))
s <- convert(s, "ppm")
diagram(aFeCu, names = NA, col = "gray", fill = fill)
diagram(s, type = "loga.balance", levels = 10^(-3:3), add = TRUE)
diagram(s, type = "loga.balance", levels = 35, add = TRUE, lwd = 3, col = 6, contour.method = NA)
}
# DIAGRAM 1
mfun()
title("Cu (ppm)")
# Calculate logK for CuCl2- dissociation at 125 °C
logK <- subcrt(c("CuCl2-", "Cu+", "Cl-"), c(-1, 1, 2), T = T)$out$logK
# Sverjensky (1987) used Helgeson (1969) value, which is ca. -5.2
dlogK <- logK - -5.2
# Calculate the difference in ΔG° corresponding to this logK difference
dG_J <- convert(dlogK, "G", T = convert(T, "K"))
# We should use calories here because the database values are in calories 20220604
stopifnot(info(info("CuCl2-"))$E_units == "cal")
dG_cal <- convert(dG_J, "cal")
# Apply this difference to the CuCl2- entry in OBIGT
newG <- info(info("CuCl2-"))$G + dG_cal
mod.OBIGT("CuCl2-", G = newG)
# Do the same thing for CuCl3-2
logK <- subcrt(c("CuCl3-2", "Cu+", "Cl-"), c(-1, 1, 3), T = T)$out$logK
dlogK <- logK - -5.6
dG_J <- convert(dlogK, "G", T = convert(T, "K"))
stopifnot(info(info("CuCl3-2"))$E_units == "cal")
dG_cal <- convert(dG_J, "cal")
newG <- info(info("CuCl3-2"))$G + dG_cal
mod.OBIGT("CuCl3-2", G = newG)
# DIAGRAM 2
mfun()
title("Cu (ppm)", line = 1.7)
CuCl2 <- expr.species("CuCl2-")
CuCl3 <- expr.species("CuCl3-2")
title(bquote("Helgeson (1969)"~.(CuCl2)~and~.(CuCl3)), line = 0.9)
# Set up system to dissolve S2(gas)
basis(c("S2", "copper", "hematite", "oxygen", "H2O", "H+", "Cl-"))
basis("pH", 6)
species("S2")
# Calculate concentration of SO4-2
iaq <- info("SO4-2")
s <- solubility(iaq, S2 = c(-34, -10, res1), O2 = c(-55, -40, res1), T = T, IS = calc$IS, in.terms.of = "SO4-2")
s <- convert(s, "ppm")
# DIAGRAM 3
diagram(aFeCu, names = NA, col = "gray", fill = fill)
diagram(s, type = "loga.balance", levels = 10^(-3:3), add = TRUE)
diagram(s, type = "loga.balance", levels = 35, add = TRUE, lwd = 3, col = 6, contour.method = NA)
title(bquote(bold(.(expr.species("SO4-2"))~"(ppm)")))
```
</div>
```{r solubility, echo = FALSE, results = "hide", message = FALSE, fig.width = 7, fig.height = 3, out.width = "100%", fig.align = "center", pngquant = pngquant}
```
After running the code above, we can inspect the value of `calc` to show the estimated ionic strength and activity of Cl^-^; the latter is very close to unity.
```{r NaCl}
# Ionic strength
calc$IS
# Logarithm of activity of Cl-
log10(calc$m_Cl * calc$gam_Cl)
```
The thick magenta lines indicate the 35 ppm contour for Cu and SO~4~^-2^.
The first plot shows a lower Cu solubility in this region compared to Figure 2 of @Sve87.
The difference is likely due to lower stabilities of Cu(I) chloride complexes in the default OBIGT database, compared to those available at the time [@Hel69].
For the second plot, the standard Gibbs energies of CuCl~2~^-^ and CuCl~3~^-2^ are adjusted so that the `logK` for their dissociation reactions at 125 °C matches values interpolated from Table 5 of @Hel69.
Here are the `logK` values after the adjustment, followed a `reset()` call to compare the values with the default database, which is also used for later examples in this vignette.
(`T` was set to 125 above.)
```{r logK, message = FALSE}
# logK values interpolated from Table 5 of Helgeson (1969)
subcrt(c("CuCl2-", "Cu+", "Cl-"), c(-1, 1, 2), T = T)$out$logK
subcrt(c("CuCl3-2", "Cu+", "Cl-"), c(-1, 1, 3), T = T)$out$logK
# Default OBIGT database
reset()
subcrt(c("CuCl2-", "Cu+", "Cl-"), c(-1, 1, 2), T = T)$out$logK
subcrt(c("CuCl3-2", "Cu+", "Cl-"), c(-1, 1, 3), T = T)$out$logK
```
The higher stability of these complexes from @Hel69 causes the 35 ppm contour to move closer to the position shown by @Sve87.
Interestingly, the calculation here also predict substantial increases of Cu concentration of Cu at high *f*~S<sub>2</sub>~ and low *f*~O<sub>2</sub>~, due to the formation of bisulfide complexes with Cu.
The aqueous species considered in the calculation can be seen like this:
```{r iCu.aq}
names(iCu.aq)
```
CuHS and Cu(HS)~2~^-^ can be excluded by removing S from the `retrieve()` call above (i.e. only `c("O", "H", "Cl")` as the elements in possible ligands); doing so precludes a high concentration of aqueous Cu in the highly reduced, sulfidic region.
The third plot for the concentation of SO~4~^-2^ is simply made by using `affinity()` to calculate the affinity of its formation reaction as a function of *f*~S<sub>2</sub>~ and *f*~O<sub>2</sub>~ at pH 6 and 125 °C, then using `solubility()` to calculate the solubility of S~2~(gas), expressed in terms of moles of SO~4~^-2^ in order to calculate parts per million (ppm) by weight.
## Secondary Balancing
Predominance diagrams in CHNOSZ are made using the maximum affinity method, where the affinities of formation reactions of species are divided by the *balancing coefficients* [@Dic19].
Usually, these balancing coefficients are taken from the formation reactions themselves; for example, if they are the coefficients on the Fe-bearing basis species, then the reactions are said to be "balanced on Fe".
Some diagrams in the literature are made with secondary balancing constraints in addition to the primary ones.
For example, reactions of Fe-bearing minerals are balanced on Fe, and reactions of Cu-bearing minerals are balanced on Cu; these are both primary balancing coefficients.
Then, reactions between all minerals are balanced on H^+^ as the secondary balancing coefficients.
The core concept is to apply the secondary balance while also maintaining the primary balance; a method to do this has been implemented in the `rebalance()` function.
Different parts of the script to make the diagrams are described below; press the button to show the entire script.
<button id="B-rebalance" onclick="ToggleDiv('rebalance')">Show code</button>
<div id="D-rebalance" style="display: none">
```{r rebalance, eval = FALSE}
mat <- matrix(c(1, 1, 2, 2, 3, 3, 4, 4, 4, 5, 5, 5), byrow = TRUE, nrow = 2)
layout(mat)
par(font.main = 1)
basis(c("Fe+2", "Cu+", "hydrogen sulfide", "oxygen", "H2O", "H+"))
xlab <- ratlab("Fe+2", "Cu+")
### PRIMARY balancing
# Only Fe-bearing minerals
species(c("pyrite", "pyrrhotite", "magnetite", "hematite"))
aFe <- affinity("Fe+2" = c(0, 12), O2 = c(-40, -16), T = 400, P = 2000)
names <- info(aFe$species$ispecies)$abbrv
dFe <- diagram(aFe, xlab = xlab, names = names)
title(bquote("Only Fe; 1° balance:" ~ .(expr.species(dFe$balance))))
label.plot("A")
# Only Cu-bearing minerals
species(c("covellite", "chalcocite", "tenorite", "cuprite"))
aCu <- affinity(aFe) # argument recall
names <- info(aCu$species$ispecies)$abbrv
dCu <- diagram(aCu, xlab = xlab, names = names)
title(bquote("Only Cu; 1° balance:" ~ .(expr.species(dCu$balance))))
label.plot("B")
# Only Fe- AND Cu-bearing minerals
species(c("chalcopyrite", "bornite"))
aFeCu <- affinity(aFe)
names <- info(aFeCu$species$ispecies)$abbrv
dFeCu <- diagram(aFeCu, xlab = xlab, balance = "H+", names = names)
title(bquote("Only Fe+Cu; 1° balance:" ~ .(expr.species(dFeCu$balance))))
label.plot("C")
### SECONDARY balancing
# Fe- or Cu-bearing minerals
ad1 <- rebalance(dFe, dCu, balance = "H+")
names <- info(ad1$species$ispecies)$abbrv
d1 <- diagram(ad1, xlab = xlab, balance = 1, names = names)
title(bquote("Only Fe or Cu; 2° balance:" ~ .(expr.species("H+"))))
label.plot("D")
# All minerals
d1$values <- c(dFe$values, dCu$values)
ad2 <- rebalance(d1, dFeCu, balance = "H+")
names <- info(ad2$species$ispecies)$abbrv
diagram(ad2, xlab = xlab, balance = 1, names = names)
title(bquote("Fe and/or Cu; 2° balance:" ~ .(expr.species("H+"))))
label.plot("E")
db <- describe.basis(3)
leg <- lex(lTP(400, 2000), db)
legend("bottomleft", legend = leg, bty = "n")
```
</div>
We first define basis species to contain both Cu- and Fe-bearing species.
The \emph{x} axis is the ratio of activities of Fe^+2^ and Cu^+^; the label is made with `ratlab()`.
```{r rebalance, eval = FALSE, echo = 5:6}
```
We then calculate the diagrams for the primary balancing coefficients, for the groups of only Fe-, only Cu-, and only Fe+Cu-bearing minerals.
It is obvious that the first two systems are balanced on Fe and Cu, respectively, but the third has a somewhat unusual balance: H^+^.
See Reaction 4 of @MH85 for an example.
```{r rebalance, eval = FALSE, echo = 10:33}
```
Now comes the secondary balancing, where all reactions, not only that between bornite and chalcopyrite, are balanced on H^+^.
We first rebalance the diagrams for the Fe- or Cu-bearing minerals to make diagram D.
Note that after secondary balancing with `rebalance()`, the argument `balance = 1` should be used in `diagram()` to prevent further balancing.
This is because `rebalance()` preserves the primary balancing for Fe- and Cu-bearing minerals (internally the "plotvals" components of `dFe` and `dCu`).
Then we rebalance diagrams D and C to make the final diagram in E.
The fields in this diagram are labeled with mineral abbreviations from the OBIGT database.
```{r rebalance, eval = FALSE, echo = 36:49}
```
```{r rebalance, echo = FALSE, results = "hide", message = FALSE, fig.width = 6.5, fig.height = 5, out.width = "100%", fig.align = "center", pngquant = pngquant}
```
The final diagram is like one shown in Figure 5 of @Bri80 and Figure 5 of @MH85.
*Challenge*: Although the diagram here is drawn only for H~2~S in the basis species, take it a step further and make a mosaic diagram to account for the stability of HSO~4~^-^ at high oxygen fugacity.
## Other Possibilities
Conceptually, the methods described above treat different metal-bearing elements as parts of distinct chemical systems that are then joined together.
Other methods may be more suitable for considering multiple metals (or other elements) in one system.
### Balancing on a Non-Metal
As shown in the **secondary balancing** example, there is no requirement that the balancing coefficients come from a metal-bearing species.
It is possible to make diagrams for minerals with different metallic elements simply by using a non-metallic element as the primary balance.
Here is an example for the Cu-Fe-S-O-H system.
The reactions are balanced on O~2~, which means that no O~2~ appears in the reaction between any two minerals, but Fe^+2^ and/or Cu^+^ can be present, depending on the chemical composition.
Saturation limits are shown for species that have no O~2~ in their formation reactions.
```{r non-metal, results = "hide", message = FALSE, fig.width = 6, fig.height = 5, out.width = "80%", fig.align = "center", pngquant = pngquant}
basis(c("Fe+2", "Cu+", "hydrogen sulfide", "oxygen", "H2O", "H+"))
basis("H2S", 2)
species(c("pyrite", "magnetite", "hematite", "covellite", "tenorite",
"chalcopyrite", "bornite"))
a <- affinity("Cu+" = c(-8, 2, 500), "Fe+2" = c(-4, 12, 500), T = 400, P = 2000)
names <- info(a$species$ispecies)$abbrv
d <- diagram(a, xlab = ratlab("Cu+"), ylab = ratlab("Fe+2"), balance = "O2", names = names)
title(bquote("Cu-Fe-S-O-H; 1° balance:" ~ .(expr.species(d$balance))))
# Add saturation lines
species(c("pyrrhotite", "ferrous-oxide", "chalcocite", "cuprite"))
asat <- affinity(a) # argument recall
names <- asat$species$name
names[2] <- "ferrous oxide"
diagram(asat, type = "saturation", add = TRUE, lty = 2, col = 4, names = names)
legend("topleft", legend = lTP(400, 2000), bty = "n")
```
This example was prompted by Figure 3 of @MH85; earlier versions of the diagram are in @HBL69 and @Hel70a.
In some ways this is like the inverse of the **mosaic stacking** example.
There, reactions were balanced on Fe or Cu, and *f*~O<sub>2</sub>~ and pH were used as plotting variables.
Here, the reactions are balanced on O~2~ and implicitly on H^+^ through the activity ratios with *a*~Fe^+2^~ and *a*~Cu^+^~, which are the plotting variables.
More common diagrams of this type are balanced on Si or Al.
See `demo(saturation)` for an example in the H~2~O-CO~2~-CaO-MgO-SiO~2~ system.
### Mosaic Combo
Instead of adding minerals with different metals by stacking mosaic diagrams, it may be possible to include two different metals in the basis species and formed species.
The `mosaic()` and `equilibrate()` functions can be combined to balance on two different elements.
The example here compares two methods applied to N-, C-, and N+C-bearing species because bimetallic aqueous species are not currently available in the OBIGT database.
The total activities used here are modified from the example for sedimentary basin brines described by @Sho93, which is also the source of the thermodynamic parameters for acetamide.
1. The "effective equilibrium constant" (*K*^eff^) method [@RBG_21] is used to calculate the activity of acetamide for a total activities of neutral and ionized species, i.e. ∑(ammonia and ammonium) and ∑(acetic acid and acetate).
2. Using the mosaic combo method, the `mosaic()` command calculates equilibrium activities of NH~3~ and NH~4~^+^ for a given total activity of N in the basis species, and calculates the corresponding affinities of the formed species.
Then, the `equilibrate()` command calculates equilibrium activities of the formed species for given total activity of C, and combines them with the activities of the changing basis species (NH~3~ and NH~4~^+^).
The mosaic combo method (solid black line) produces results equivalent to those of the *K*^eff^ method (dashed blue line).
<button id="B-mosaic-combo" onclick="ToggleDiv('mosaic-combo')">Show code</button>
<div id="D-mosaic-combo" style="display: none">
```{r mosaic-combo, eval = FALSE}
## METHOD 1: Keff equation (Robinson et al., 2021)
# A function to calculate Keff for any combination of T and pH
Keff <- function(T = 25, pH = 7) {
# Make T and pH the same length
len <- max(length(T), length(pH))
T <- rep(T, length.out = len)
pH <- rep(pH, length.out = len)
# Calculate activity of H+
aH <- 10^(-pH)
# Calculate logKs
logK1 <- subcrt(c("acetic acid", "NH3", "acetamide", "H2O"), c(-1, -1, 1, 1), T = T)$out$logK
logK2 <- subcrt(c("acetic acid", "acetate", "H+"), c(-1, 1, 1), T = T)$out$logK
logK3 <- subcrt(c("NH3", "H+", "NH4+"), c(-1, -1, 1), T = T)$out$logK
# Calculate Ks
K1 <- 10^logK1
K2 <- 10^logK2
K3 <- 10^logK3
# Calculate Keff (Eq. 7)
Keff <- K1 * (1 + K2 / aH) ^ -1 * (1 + K3 * aH) ^ -1
Keff
}
# Calculate logKeff as a function of pH at 100 °C
res <- 128
pH <- seq(0, 14, length.out = res)
T <- 100
logKeff <- log10(Keff(pH = pH, T = T))
# Calculate activity of acetamide for
# acetic acid + acetate = 0.01 m
# ammonia + ammonium = 0.001 m
logAc <- log10(0.01)
logAm <- log10(0.001)
logAcAm <- logKeff + logAc + logAm
## METHOD 2: Mosaic combo
# Define total activities
a_N <- 0.001
# This is 2 * 0.01 because acetic acid has 2 carbons
a_C <- 2 * 0.01
loga_N <- log10(a_N)
loga_C <- log10(a_C)
# Setup basis species
basis(c("CO2", "NH3", "O2", "H2O", "H+"))
basis("NH3", loga_N)
# Load all C-bearing species (including acetamide)
species(c("acetamide", "acetic acid", "acetate"))
# Calculate distribution of C-bearing species accounting for ammonia/ammonium speciation
m <- mosaic(c("NH3", "NH4+"), pH = c(0, 14, res), T = T)
e <- equilibrate(m, loga.balance = loga_C)
# Plot and label diagram
# Start with empty diagram
diagram(e, ylim = c(-8, -0), lty = 0, names = FALSE)
# Add pH = 6 line
abline(v = 6, col = "gray60", lty = 5)
# Add line for acetamide activity calculated with Keff
lines(pH, logAcAm, col = 4, lwd = 6, lty = 2)
# Add lines from CHNOSZ calculations
diagram(e, add = TRUE, lty = c(2, 3, 1, 2, 3), lwd = c(1, 1, 2, 1, 1), dx = c(-0.2, 0.2, -2.5, 0, 0), dy = c(0.1, 0.1, -1, 0.1, 0.1), srt = c(0, 0, 52, 0, 0))
tN <- paste("Total N in basis species =", format(a_N, scientific = FALSE), "m")
tC <- paste("Total C in formed species =", format(a_C, scientific = FALSE), "m")
title(main = paste(tN, tC, sep = "\n"), font.main = 1)
legend("topright", legend = lTP(T, "Psat"), bty = "n")
# Check that we got equal values
stopifnot(all.equal(as.numeric(e$loga.equil[[3]]), logAcAm, tol = 1e-3, scale = 1))
```
</div>
```{r mosaic-combo, echo = FALSE, results = "hide", message = FALSE, fig.width = 6, fig.height = 5, out.width = "80%", fig.align = "center", pngquant = pngquant}
```
The diagram shows the ionization of acetic acid and NH~3~ at different pHs.
The predicted appearance of acetamide (CH~3~CONH~2~) is a consequence of the interaction between the N-bearing and C-bearing species, and is analogous to the formation of a bimetallic complex.
*Thanks to Kirt Robinson for the feature request and test case used in this example.*
## Document History
* 2020-07-15 First version.
* 2021-03-01 Improve mineral abbreviations and placement of labels; use updated DFT energies from Materials Project; add Mosaic Stacking 2 (minerals and aqueous species); add *K*~eff~ calculation; add Δ*G*~pbx~ color scale.
## References
|
/scratch/gouwar.j/cran-all/cranData/CHNOSZ/vignettes/multi-metal.Rmd
|
#' @keywords internal
"_PACKAGE"
# The following block is used by usethis to automatically manage
# roxygen namespace tags. Modify with care!
## usethis namespace: start
## usethis namespace: end
NULL
|
/scratch/gouwar.j/cran-all/cranData/CHOIRBM/R/CHOIRBM-package.R
|
#' Generate Simple Example Data
#'
#' Creates a data frame with CHOIR Body Map segment IDs and a randomly
#' associated value. Also adds grouping information for facetting while
#' plotting.
#'
#' @param seed integer to seed the random number generator
#' @return values data.frame
#' @export
#'
#' @examples
#' cbm_df <- gen_example_data()
#' head(cbm_df)
#'
#' @importFrom stats runif
#'
gen_example_data <- function(seed = 123) {
ids <- as.character(c(seq.int(101, 136, 1), seq.int(201, 238, 1)))
set.seed(seed = seed)
values <- data.frame(
id = ids
, value = runif(length(ids))
, group = factor(
ifelse(
as.numeric(ids) < 200
, "Front"
, "Back"
)
, levels = c("Front", "Back")
)
)
return(values)
}
|
/scratch/gouwar.j/cran-all/cranData/CHOIRBM/R/gen_example_data.R
|
utils::globalVariables(c("x", "y"))
|
/scratch/gouwar.j/cran-all/cranData/CHOIRBM/R/globals.R
|
#' Plot the male CHOIR Body Map
#'
#' Creates a new plot of the front and back of the female CHOIR body map.
#'
#' @param df data.frame
#' @param value string
#' @return ggrob
#' @export
#'
#' @examples
#' cbm_df <- gen_example_data()
#' plot_female_choirbm(cbm_df, "value")
#'
#' @importFrom ggplot2 ggplot aes geom_polygon scale_y_reverse facet_wrap
#' @importFrom ggplot2 theme_void theme
#' @importFrom rlang .data
#'
plot_female_choirbm <- function(df, value) {
positions <- rbind(female_front_poly_coords_df, female_back_poly_coords_df)
datapoly <- merge(df, positions, by = "id")
p <- ggplot(datapoly) +
aes(x = x, y = y) +
geom_polygon(
aes(
fill = .data[[value]]
, group = .data[["id"]]
)
, color = "black"
, size = 1.5
) +
scale_y_reverse() +
facet_wrap(~.data[["group"]]) +
theme_void() +
theme(legend.position = "None")
return(p)
}
|
/scratch/gouwar.j/cran-all/cranData/CHOIRBM/R/plot_female_choirbm.R
|
#' Plot the male CHOIR Body Map
#'
#' Creates a new plot of the male CHOIR body map.
#'
#' @param df data.frame
#' @param value string
#' @return ggrob
#' @export
#'
#' @examples
#' cbm_df <- gen_example_data()
#' plot_male_choirbm(cbm_df, "value")
#'
#' @importFrom ggplot2 ggplot aes geom_polygon scale_y_reverse facet_wrap
#' @importFrom ggplot2 theme_void theme
#' @importFrom rlang .data
#'
plot_male_choirbm <- function(df, value) {
positions <- rbind(male_front_poly_coords_df, male_back_poly_coords_df)
datapoly <- merge(df, positions, by = "id")
p <- ggplot(datapoly) +
aes(x = x, y = y) +
geom_polygon(
aes(
fill = .data[[value]]
, group = .data[["id"]]
)
, color = "black", size = 1.5
) +
scale_y_reverse() +
facet_wrap(~.data[["group"]]) +
theme_void() +
theme(legend.position = "None")
return(p)
}
|
/scratch/gouwar.j/cran-all/cranData/CHOIRBM/R/plot_male_choirbm.R
|
#' Converts a comma-separated string to a CHOIR BM
#'
#' Takes a string of IDs that are separated by a comma and converts the
#' information into a data frame with a binary indication of whether or not
#' an ID appeared. Useful for plotting an individual's CHOIR BM or for
#' isolating particular sections to highlight.
#'
#' @param map_str The delimited CBM string.
#' @param delim The delimiter for the CBM string.
#'
#' @return ret_df data.frame with all of the CHOIR BM segment IDs with a 1
#' if the segment was present and 0 otherwise.
#' @export
#'
#' @examples
#' cbm_str <- "101,102,103,104,201,202"
#' cbm_df <- string_to_map(cbm_str)
#' #plot in a male or female bodymap...
#' plot_male_choirbm(cbm_df, "value")
#'
#' @importFrom stringr str_split
#'
string_to_map <- function(map_str = "", delim = ",") {
ids <- as.character(c(seq.int(101, 136, 1), seq.int(201, 238, 1)))
ret_df <- data.frame(
id = ids
, group = ifelse(as.numeric(ids) < 200, "Front", "Back")
, value = as.integer(ids %in% unlist(str_split(map_str, delim)))
)
return(ret_df)
}
|
/scratch/gouwar.j/cran-all/cranData/CHOIRBM/R/string_to_map.R
|
#' CHOIR Body Map data for approximately 7,000 patients
#'
#' A non-identifiable, simulated data set generated by randomly permuting
#' data from the CHOIR Body Map validation study.
#'
#' @docType data
#'
#' @usage data(validation)
#'
#' @format An object of class \code{"data.frame"}
#' \describe{
#' \item{id}{A randomly generated numeric code for each patient.}
#' \item{gender}{The patient's gender.}
#' \item{race}{The patient's race.}
#' \item{age}{The patient's age.}
#' \item{bodymap_regions_csv}{The patient's CHOIR Body Map in a comma
#' separated string.}
#' \item{score}{A simulated pain score for demonstration purposes.}
#' }
#'
#' @references This data set was derived from the data collected during the
#' study validating the CHOIR Body Map as an instrument for recording a
#' patient's anatomical pain location.
#' \doi{10.1097/pr9.0000000000000880}
#'
#' @keywords datasets
#' @examples
#'
#' data(validation)
#' head(validation)
#'
"validation"
|
/scratch/gouwar.j/cran-all/cranData/CHOIRBM/R/validation.R
|
## ---- include = FALSE---------------------------------------------------------
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
## ----setup--------------------------------------------------------------------
library(CHOIRBM)
cbm_str <- "101,102,103,104"
cbm_df <- string_to_map(cbm_str)
head(cbm_df)
## ----plot1--------------------------------------------------------------------
plot_male_choirbm(cbm_df, "value")
|
/scratch/gouwar.j/cran-all/cranData/CHOIRBM/inst/doc/plot-one-patient.R
|
---
title: "Plotting a single patient's CBM"
author: "Eric Cramer"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{plot-one-patient}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
This vignette describes the process of converting a string representation of a CHOIR Body Map (CBM) into a plot.
CBM data for a given patient is often provided in a delimited string similar to this: "101,102,103,104" (these segment identifiers indicate the face and top of the head). If you want to plot the CBM of a single patient (e.g., for a report) or highlight specific segments on a CBM (e.g., in a paper), then you can use the `string_to_map` function to convert this string into an R `data.frame` object ready for the rest of the plotting functions in `CHOIRBM`. Let's take the above string as an example.
## Converting a string map into a CBM-plot-ready data frame
Start with the string representation of a patient's CBM. When it is converted to a data frame, the CBM is represented as a series of segment IDs with a group label (indicating if the segment belongs to the front or back of the body map) and a binary value to indicate whether the segment was present in this patient's CBM string.
```{r setup}
library(CHOIRBM)
cbm_str <- "101,102,103,104"
cbm_df <- string_to_map(cbm_str)
head(cbm_df)
```
The resulting data frame is plot-able:
```{r plot1}
plot_male_choirbm(cbm_df, "value")
```
|
/scratch/gouwar.j/cran-all/cranData/CHOIRBM/inst/doc/plot-one-patient.Rmd
|
---
title: "Plotting a single patient's CBM"
author: "Eric Cramer"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{plot-one-patient}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>"
)
```
This vignette describes the process of converting a string representation of a CHOIR Body Map (CBM) into a plot.
CBM data for a given patient is often provided in a delimited string similar to this: "101,102,103,104" (these segment identifiers indicate the face and top of the head). If you want to plot the CBM of a single patient (e.g., for a report) or highlight specific segments on a CBM (e.g., in a paper), then you can use the `string_to_map` function to convert this string into an R `data.frame` object ready for the rest of the plotting functions in `CHOIRBM`. Let's take the above string as an example.
## Converting a string map into a CBM-plot-ready data frame
Start with the string representation of a patient's CBM. When it is converted to a data frame, the CBM is represented as a series of segment IDs with a group label (indicating if the segment belongs to the front or back of the body map) and a binary value to indicate whether the segment was present in this patient's CBM string.
```{r setup}
library(CHOIRBM)
cbm_str <- "101,102,103,104"
cbm_df <- string_to_map(cbm_str)
head(cbm_df)
```
The resulting data frame is plot-able:
```{r plot1}
plot_male_choirbm(cbm_df, "value")
```
|
/scratch/gouwar.j/cran-all/cranData/CHOIRBM/vignettes/plot-one-patient.Rmd
|
######################################################################
## ciaaw.R
##
## AUTHOR: Juris Meija & Antonio Possolo
## MODIFICATION DATE: 2018 Sep 8
######################################################################
at.weight = function (ratio, ratio.cov, element, ref.isotope, data=NULL)
{
ratio.cov <- as.matrix(ratio.cov)
if(is.null(data)){
e <- new.env(parent = emptyenv())
data(list='ciaaw.mass.2016', envir = e)
data <- e$ciaaw.mass.2016
}
mass.raw = data[which(data$element==element),]
isotope.list = as.vector(mass.raw$isotope)
mass.x = as.numeric(mass.raw$mass)
mass.u = as.numeric(mass.raw$uncertainty)
ref = match(ref.isotope, isotope.list)
p = length(isotope.list) - 1
max.iter = 1e6
mass.sequence = c(ref, seq(from = 1, to = (1 + p))[-ref])
ratios.B = abs(cbind(1, mvtnorm::rmvnorm(max.iter, mean=ratio, sigma=ratio.cov, method = "svd")))
mass.B = mvtnorm::rmvnorm(max.iter, mean=mass.x, sigma=diag(mass.u^2), method="svd")[,mass.sequence]
atomicWeight = rowSums(ratios.B * mass.B)/rowSums(ratios.B)
abundances = ratios.B/rowSums(ratios.B)
colnames(abundances) = mass.x[mass.sequence]
aw.U95 = diff(quantile(atomicWeight, probs = c(0.025, 0.975)))/2
names(aw.U95) = NULL
abundances.U95 = apply(abundances, 2, function(x) diff(quantile(x, probs = c(0.025, 0.975)))/2)
aw.digits = round(2 - log10(sd(atomicWeight)), 0)
x.digits = round(2 - log10(min(apply(abundances, 2, sd))), 0)
x.mean = colMeans(abundances)
x.u = sqrt(diag(cov(abundances)))
cat("\n")
cat("Atomic weight", formatC(mean(atomicWeight), format = "f", digits = aw.digits), "\n")
cat(" u", formatC(sd(atomicWeight), format = "f", digits = aw.digits), "\n")
cat(" U 95%", formatC(aw.U95, format = "f", digits = aw.digits), "\n\n")
cat("Isotopic abundances", "\n")
cat(" mass/Da", colnames(abundances), "\n")
cat("abundance", formatC(x.mean, format = "f", digits = x.digits), "\n")
cat(" u", formatC(x.u, format = "f", digits = x.digits), "\n")
cat(" U 95%", formatC(abundances.U95, format = "f", digits = x.digits), "\n")
result = list(aw = mean(atomicWeight), aw.u = sd(atomicWeight),
aw.U95 = aw.U95, abundances = x.mean,
abundances.cov = cov(abundances),
abundances.u = x.u, abundances.U95 = abundances.U95)
}
## Atomic weight and isotopic abundances of iridium which correspond
## to the isotope ratio 191Ir/193Ir = 0.59471(13)
# at.weight(0.59471, 0.00013^2, "iridium", "193Ir")
## Atomic weight and isotopic abundances of silicon which correspond
## to isotope ratios 28Si/29Si = 1.074(69) and 30Si/29Si = 260(11)
## with a correlation of 0.80 between the two isotope ratios
# ratios = c(1.074,260)
# sigma = matrix(c(0.069^2,0.80*0.069*11,0.80*0.069*11,11^2),ncol=2,byrow=TRUE)
# at.weight(ratios, sigma, "silicon", "29Si")
normalize.ratios = function (dat, element, ref.isotope, expand = FALSE)
{
e <- new.env(parent = emptyenv())
data(list='ciaaw.mass.2016', envir = e)
data <- e$ciaaw.mass.2016
mass.raw = data[which(data$element==element),]
isotope.list = as.vector(mass.raw$isotope)
mass.x = as.numeric(mass.raw$mass)
mass.u = as.numeric(mass.raw$uncertainty)
## helper functions from miscTools
insertRow <- function (m, r, v = NA, rName = "") {
if (r == as.integer(r)) { r <- as.integer(r) }
else { stop("argument 'r' must be an integer") }
nr <- nrow(m)
nc <- ncol(m)
rNames <- rownames(m)
if (is.null(rNames) & rName != "") { rNames <- rep("", nr) }
if (r == 1) { m2 <- rbind(matrix(v, ncol = nc), m)
if (!is.null(rNames)) { rownames(m2) <- c(rName, rNames) } }
else if (r == nr + 1) { m2 <- rbind(m, matrix(v, ncol = nc))
if (!is.null(rNames)) { rownames(m2) <- c(rNames, rName) } }
else { m2 <- rbind(m[1:(r - 1), , drop = FALSE], matrix(v, ncol = nc), m[r:nr, , drop = FALSE])
if (!is.null(rNames)) { rownames(m2) <- c(rNames[1:(r - 1)], rName, rNames[r:nr]) } }
return(m2)
}
insertCol <- function (m, c, v = NA, cName = "") {
if (c == as.integer(c)) {c <- as.integer(c)}
else {stop("argument 'c' must be an integer")}
nr <- nrow(m)
nc <- ncol(m)
cNames <- colnames(m)
if (is.null(cNames) & cName != "") { cNames <- rep("", nc) }
if (c == 1) { m2 <- cbind(matrix(v, nrow = nr), m)
if (!is.null(cNames)) { colnames(m2) <- c(cName, cNames) } }
else if (c == nc + 1) { m2 <- cbind(m, matrix(v, nrow = nr))
if (!is.null(cNames)) {colnames(m2) <- c(cNames, cName) } }
else { m2 <- cbind(m[, 1:(c - 1), drop = FALSE], matrix(v,nrow = nr), m[, c:nc, drop = FALSE])
if (!is.null(cNames)) { colnames(m2) <- c(cNames[1:(c - 1)], cName, cNames[c:nc]) } }
return(m2)
}
###################
isotopes = matrix(unlist(strsplit(as.character(dat$Outcome), "\\/")), ncol = 2, byrow = TRUE)
dat$nominator = isotopes[, 1]
dat$denominator = isotopes[, 2]
ref = match(ref.isotope, isotope.list)
f.J.r.norm = function(x) x/x[ref]
denominator.list = lapply(split(dat$denominator, dat$Study),
function(x) match(unique(x), isotope.list))
r = mapply(function(x, y) append(x, 1, after = y - 1), split(dat$Value,
dat$Study), denominator.list, SIMPLIFY = FALSE)
cov = mapply(function(x, y)
insertCol(insertRow(diag(x, nrow = length(x)), y, 0), y, 0)^2,
split(dat$Unc, dat$Study),
denominator.list, SIMPLIFY = FALSE)
J.r.norm = mapply(function(x) numDeriv::jacobian(f.J.r.norm,
x), r, SIMPLIFY = FALSE)
cov.norm = mapply(function(x, y) x %*% y %*% t(x), J.r.norm,
cov, SIMPLIFY = FALSE)
r.norm = mapply(function(x, y) x/x[y], r, ref, SIMPLIFY = FALSE)
n.studies = length(r)
p = length(r[[1]]) - 1
if (expand) {
cov.norm.red = mapply(function(x, y)
as.matrix(x^2 * y[-ref, -ref]),
lapply(split(dat$k_extra, dat$Study), unique),
cov.norm, SIMPLIFY = FALSE)
} else {
cov.norm.red = mapply(function(y) as.matrix(y[-ref, -ref]),
cov.norm, SIMPLIFY = FALSE) }
cov.norm.red1 = lapply(lapply(cov.norm.red, diag), function(x) diag(x,
nrow = length(x)))
S = cov.norm.red1
R = matrix(do.call(rbind, lapply(r.norm, matrix, ncol = p +
1, byrow = TRUE))[, -ref], nrow = n.studies)
Svars = do.call(rbind, lapply(lapply(S, diag), matrix, ncol = p,
byrow = TRUE))
colnames(R) = colnames(Svars) = paste(isotope.list[-ref],
"/", ref.isotope, sep = "")
rownames(R) = rownames(Svars) = unlist(lapply(split(paste(dat$Year,
"-", dat$Author, sep = ""), dat$Study), head, 1))
names(S) = rownames(Svars)
results = list(R = R, u.R = sqrt(Svars), cov.R = S)
list(R = R, u.R = sqrt(Svars))
}
## Normalize all iridium isotope data to iridium-193
# normalize.ratios(iridium.data, "iridium", "193Ir")
mmm <- function(y, uy, knha=TRUE, verbose=TRUE) {
y.l <- split(y, col(y))
var.l <- split(uy^2, col(uy))
w.l <- split(1/uy^2, col(uy))
n = ncol(y) # no missing outcomes
n.studies = nrow(y)
y.w = mapply(function(w,y) sum(w*y)/sum(w), w.l, y.l)
Q = mapply(function(w,y,mu) sum(w*(y-mu)^2), w.l, y.l, y.w)
tau2 = mapply(function(w,q) max(0, (q - (n.studies-1))/(sum(w)-sum(w^2)/sum(w))), w.l, Q)
w.s = 1/(uy^2 + matrix(rep(tau2, n.studies), ncol=n, byrow=TRUE))
# variance of the consensus values
var.beta = 1/colSums(w.s)
# consensus values
beta = mapply(function(ws, y) sum(ws*y)/sum(ws), split(w.s,col(w.s)), y.l, SIMPLIFY=TRUE)
# covariance estimate
cov.beta = matrix(0, ncol=n, nrow=n)
if (n!=1) {
for (i in 1:n){
for (j in 1:n){
if(i!=j) cov.beta[i,j] <- sum(w.s[,i]*w.s[,j]*(y[,i]-beta[i])*(y[,j]-beta[j])/(sum(w.s[,i])*sum(w.s[,j])))
}}
diag(cov.beta) <- var.beta
} else { cov.beta = as.matrix(unlist(var.beta)) }
# spectral decomposition of cov.beta to avoid possible negative variances
tol=-1e-18
if (min(eigen(cov.beta)$values)<tol){
U = eigen(cov.beta)$vectors
Dpsd = diag(as.vector(eigen(cov.beta)$values), nrow=n)
Dpsd[which(Dpsd<0)] = 0
cov.beta = U %*% Dpsd %*% t(U) }
#Knapp-Hartung adjustment for the variances and covariances of each outcome (Birge ratio)
if(knha==FALSE) H2 <- rep(1, n)
if(knha==TRUE) {H2 <- mapply(function(w,y,mu) sum(w*(y-mu)^2), split(w.s,col(w.s)), y.l, as.list(beta))/(n.studies-1); H2[which(H2 < 1)] <- 1}
# expand uncertainties by H
cov.betaH <- outer(sqrt(H2),sqrt(H2)) * cov.beta
# H-adjusted standard uncertainties
u.betaH = sqrt(diag(cov.betaH))
# correlation matrix
cor.betaH <- if(n==1) as.matrix(1) else {stats::cov2cor(cov.betaH)}
# 95% confidence intervals for isotope ratios based on t-distribution
mt = mvtnorm::qmvt(0.975, corr=cor.betaH, df=(n.studies-1)*n, type="shifted")$quantile
ci.betaH = mt*u.betaH
# Relative total variability due to heterogeneity (in percent)
I2 = round(100*(Q - (n.studies-1))/Q, 1)
I2[which(I2 < 0)] <- 0
# determine the number of decimal digits for printout
d = round(-log10(min(u.betaH))+2,0)
names(beta) <- names(u.betaH) <- names(ci.betaH) <- names(H2) <- names(I2) <- colnames(y)
colnames(cov.betaH) <- rownames(cov.betaH) <- colnames(y)
colnames(cor.betaH) <- rownames(cor.betaH) <- colnames(y)
# annotated summary output
if (verbose ==TRUE) {cat("Multivariate Marginal Method of Moments with working independence assumption", "\n")
cat("Chen et al (2016) DOI: 10.1002/sim.6789", "\n", "\n")
cat("Number of studies: ", n.studies, "\n")
cat("Isotope ratios", "\n", names(beta), "\n", "\n")
cat("Consensus values", "\n", formatC(unlist(beta), format='f', digits=d), "\n", "\n")
cat("Standard uncertainty", "\n", formatC(u.betaH, format='f', digits=d), "\n", "\n")
cat("Expanded uncertainty, 95 %", "\n", formatC(ci.betaH, format='f', digits=d), "\n", "\n")
cat("Birge ratio (Knapp-Hartung adjustment) for each outcome", "\n", formatC(sqrt(H2), format='f', digits=2), "\n", "\n")
cat("Relative total variability due to heterogeneity (%) for each outcome", "\n", formatC(I2, format='f', digits=1), "\n", "\n")
}
# gather the results
result = list( studies=n.studies,
beta=unlist(beta),
beta.u = u.betaH,
beta.U95 = ci.betaH,
beta.cov=cov.betaH,
beta.cor = cor.betaH,
I2 = I2,
H = sqrt(H2),
df=n*(n.studies-1))
}
## Consensus isotope amount ratios for platinum
# df = normalize.ratios(platinum.data, "platinum", "195Pt")
# mmm(df$R, df$u.R)
## A function to convert a given set of isotopic abundances and their uncertainties to the corresponding isotope ratios
abundances2ratios <- function(x,ux,ref=1,iterations=1e4){
n.isotopes = length(x) # number of isotopes
cov.R = list()
u.R = list()
it.n = 0
# setup
cor = diag(1,nrow=n.isotopes) #identity
# assign N random correlations (N = n.isotopes(n.isotopes-3)/2)
z=upper.tri(cor)&!cor[1,]
z[,which(apply(z,2,sum)==1)]<-FALSE
cor[z] <- runif(n.isotopes*(n.isotopes-3)/2,min=-1,max=+1)
cor[lower.tri(cor)] <- t(cor)[lower.tri(cor)]
cov = cor*outer(ux,ux)
# find columns with a single zero entry (and the corresponding rows)
cov1<-cov
# find columns with a single zero entry (and the corresponding rows)
col1=(1:n.isotopes)[apply(cov1==0,2,sum)==1]
row1=apply(as.matrix(col1),1,function(x) which(cov1[,x]==0))
for(i in 1:length(col1)) cov1[row1[i],col1[i]] <- -sum(cov1[,col1[i]])
cov1[lower.tri(cov1)] <- t(cov1)[lower.tri(cov1)]
cov2<-cov1
# find missing covariances and assign a variable symbol to them
for(i in 1:n.isotopes){
for(j in 1:n.isotopes){ifelse(cov1[i,j]==0,cov2[i,j]<-paste("a",min(i,j),max(i,j),sep=""),cov2[i,j]<-"") }
}
variables=unique(c(cov2))[-1]
d<-matrix(0,ncol=length(variables),nrow=length(variables))
# rows in the design matrix for zero-column and zero-row sum
for(i in 1:length(variables)){
d[i,]<-as.numeric(1:length(variables) %in% stats::na.exclude(match(cov2[,i], variables)))
}
# Monte Carlo
for(i in 1:iterations){
cor = diag(1,nrow=n.isotopes) #identity
cor[z] <- runif(n.isotopes*(n.isotopes-3)/2,min=-1,max=+1)
cor[lower.tri(cor)] <- t(cor)[lower.tri(cor)]
cov1 = cor*outer(ux,ux)
for(i in 1:length(col1)) cov1[row1[i],col1[i]] <- -sum(cov1[,col1[i]])
cov1[lower.tri(cov1)] <- t(cov1)[lower.tri(cov1)]
# the corresponding entries in the response vector
y=matrix(-apply(cov1,2,sum))[!apply(cov2=="",2,all),]
# find missing covariances by Gauss elimination
coef<-solve(d)%*%y
for (i in 1:length(variables)){ cov1[cov2==variables[i]]<-coef[i] }
# zero column-sum and zero row-sum covariance matrix: cov1
cor <- stats::cov2cor(cov1)
# rejection of isotopic abundance correlations that are outside [-1,+1]
if(max(abs(cor))<=1){
# jacobian to get isotope ratio uncertainties
J <- diag(x[ref]^(-1), nrow=n.isotopes)
J[,ref] <- -x*x[ref]^(-2)
J[ref,ref] <- 0
cov.Ratios <- J %*% cov1 %*% t(J) # isotope ratio covariance matrix
# further rejection of isotope ratio correlations that are outside [-1,+1]
if (max(abs(stats::cov2cor(cov.Ratios[-ref,-ref])))<=1){
it.n = it.n+1
cov.R[[it.n]] <- cov.Ratios
u.R[[it.n]] <- sqrt(diag(cov.Ratios))
}
else{next}
}
else{next}
}
if(it.n==0) stop("The provided isotopic abundance uncertainties are inconsistent")
# RESULTS
# find the average isotope ratio covariance matrix
cov.R.result <- cov.R[[which.max(unlist(lapply(u.R, mean, na.rm = FALSE)))]]
R <- x[-ref]/x[ref] # output ratios
uR <- sqrt(diag(cov.R.result[-ref,-ref])) # uncertainties
list(R=R, R.u=uR, R.cov = cov.R.result[-ref,-ref], N=it.n)
}
## Example: Convert the isotopic abundances of zinc to the corresponding isotope ratios
# x = c(0.48630, 0.27900, 0.04100, 0.18750, 0.00620)
# ux = c(0.00091, 0.00076, 0.00031, 0.00135, 0.00010)
# z=abundances2ratios(x, ux, ref=2)
# at.weight(z$R, z$R.cov, "zinc", "66Zn")
|
/scratch/gouwar.j/cran-all/cranData/CIAAWconsensus/R/ciaaw.R
|
#' get_background_full
#'
#' @param norm_matrix Norm count matrix (n_genes X n_cells).
#' @param threshold threshold in expression for a given gene
#' @param n_cells_low minimum number of cells where a gene is expressed at a
#' level above threshold
#' @param n_cells_high maximum number of cells where a gene is expressed at a
#' level above threshold
#' @return Character vector with all genes expressed at a level higher than
#' \emph{threshold} in a number of cells between \emph{n_cells} and
#' \emph{n_cells_high}.
#' @author Gabriele Lubatti \email{gabriele.lubatti@@helmholtz-muenchen.de}
#'
#'
#'
#' @export get_background_full
#'
#' @importFrom magrittr %>%
#' @importFrom parallel mclapply
#' @importFrom grDevices hcl
#' @importFrom stats fisher.test
#' @importFrom stats median
get_background_full <- function(norm_matrix, threshold = 1, n_cells_low = 3, n_cells_high = 20) {
genes_filter <- apply(norm_matrix, 1, function(x) {
x <- x[x > threshold]
if (length(x) >= n_cells_low) {
return(TRUE)
}
else{
return(FALSE)
}
})
genes_filter_2 <- apply(norm_matrix, 1, function(x) {
x <- x[x > threshold]
if (length(x) > n_cells_high) {
return(FALSE)
}
else{
return(TRUE)
}
})
genes_important <- row.names(norm_matrix)[genes_filter]
genes_important_2 <- row.names(norm_matrix)[genes_filter_2]
genes_important_final <- intersect(genes_important, genes_important_2)
if (length(genes_important_final) == 0) {
stop("There are not genes that pass the filtering steps")
}
return(genes_important_final)
}
#' CIARA_gene
#'
#' The gene expression is binarized (1/0) if the value in a given cell is
#' above/below the median. Each of cell with its first K nearest neighbors
#' defined a local region. If there are at least \emph{local_region} enriched
#' in 1 according to \emph{fisher.test}, then the gene is defined as highly
#' localized and a final p value is assigned to it. The final p value is the
#' minimum of the p values from all the enriched local regions. If there are no
#' enriched local regions, then the p value by default is set to 1
#'
#' @param knn_matrix K-nearest neighbors matrix (n_cells X n_cells).
#' @param gene_expression numeric vector with the gene expression (length equal
#' to n_cells). The gene expression is binarized (equal to 0/1 in the cells
#' where the value is below/above the median)
#' @param p_value p value returned by the function \emph{fisher.test} with
#' parameter alternative = "g"
#' @param odds_ratio odds_ratio returned by the function \emph{fisher.test}
#' with parameter alternative = "g"
#' @param local_region Integer. Minimum number of local regions (cell with its
#' knn neighbours) where the binarized gene expression is enriched in 1.
#' @param approximation Logical.For a given gene, the fisher test is run in the
#' local regions of only the cells where the binarized gene expression is 1.
#' @inheritParams get_background_full
#' @return List with one element corresponding to the p value of the gene.
#' @author Gabriele Lubatti \email{gabriele.lubatti@@helmholtz-muenchen.de}
#' @seealso \url{https://www.rdocumentation.org/packages/stats/versions/3.6.2/topics/fisher.test}
#' @export CIARA_gene
CIARA_gene <- function(norm_matrix, knn_matrix, gene_expression, p_value = 0.001, odds_ratio = 2, local_region = 1, approximation = FALSE) {
median_genes <- median(gene_expression)
binary_expression <- rep(0, length(gene_expression))
binary_expression[gene_expression > median_genes] <- 1
binary_expression[gene_expression <= median_genes] <- 0
if (approximation == FALSE) {
sub_feature <- colnames(norm_matrix)
message("approximation == FALSE")
}
else {
sub_feature <- colnames(norm_matrix)[which(binary_expression == 1)]
message("approximation == TRUE")
}
if (!all(colnames(norm_matrix)%in%row.names(knn_matrix))) {
stop ("row.names in knn_matrix are not equal to colnames in norm_matrix")
}
knn_matrix_big <- knn_matrix[sub_feature, ]
perform_fisher <- function(j) {
nn_cell <- colnames(norm_matrix)[which(knn_matrix_big[sub_feature[j], ] > 0)]
nn_gene_expression <- binary_expression[colnames(norm_matrix)%in%nn_cell]
if(sum(nn_gene_expression) != 0) {
input_fisher <- matrix(c(sum(nn_gene_expression == 1), sum(binary_expression == 1)-sum(nn_gene_expression == 1), sum(nn_gene_expression == 0), sum(binary_expression == 0)-sum(nn_gene_expression == 0)), nrow = 2, ncol = 2, byrow = T)
test_output <- fisher.test(input_fisher, alternative = "g")
return(test_output$p.value)
}
else{
return(1)
}
}
p_value_gene <- unlist(lapply(seq_len(length(sub_feature)), perform_fisher))
if(sum(p_value_gene < p_value) >= local_region) {
p_value_final <- min(p_value_gene)
}
else {
p_value_final <- 1
}
if (all(p_value_final == 1)){
warning(paste0("There are not genes enriched in ", local_region, " or more local regions"))
}
return((p_value_final))
}
#' CIARA
#'
#' It selects highly localized genes as specified in \emph{CIARA_gene},
#' starting from genes in \emph{background}
#'
#' @param background Vector of genes for which the function \emph{CIARA_gene}
#' is run.
#' @param cores_number Integer.Number of cores to use.
#' @inheritParams CIARA_gene
#' @inheritParams get_background_full
#' @return Dataframe with n_rows equal to the length of
#' \emph{background} . Each row is the output from \emph{CIARA_gene}.
#' @author Gabriele Lubatti \email{gabriele.lubatti@@helmholtz-muenchen.de}
#'
#'
#'
#' @export CIARA
CIARA <- function(norm_matrix, knn_matrix, background, cores_number = 1, p_value = 0.001, odds_ratio = 2, local_region = 1, approximation = FALSE) {
run_loop_genes = function(i) {
if (!all(background %in% row.names(norm_matrix))) {
stop("Some background genes are not present in norm matrix")
}
gene_expression <- as.vector(norm_matrix[background[i],])
message(paste0("Running CIARA on gene:", background[i]))
return(CIARA_gene(norm_matrix, knn_matrix, gene_expression, p_value, odds_ratio, local_region, approximation))
}
result_final <- do.call(rbind, mclapply(seq_len(length(background)),run_loop_genes , mc.cores = cores_number))
row.names(result_final) <- background
return(result_final)
}
|
/scratch/gouwar.j/cran-all/cranData/CIARA/R/CIARA_core_functions.R
|
#' cluster_analysis_integrate_rare
#'
#' @param raw_counts Raw count matrix (n_genes X n_cells).
#' @param project_name Character name of the Seurat project.
#' @param resolution Numeric value specifying the parameter \emph{resolution}
#' used in the Seurat function \emph{FindClusters}.
#' @param neighbors Numeric value specifying the parameter \emph{k.param} in
#' the Seurat function \emph{FindNeighbors}
#' @param max_dimension Numeric value specifying the maximum number of the PCA
#' dimensions used in the parameter \emph{dims} for the Seurat function
#' \emph{FindNeighbors}
#' @param feature_genes vector of features specifying the argument
#' \emph{features} in the Seurat function \emph{RunPCA}.
#' @return Seurat object including raw and normalized counts matrices, UMAP coordinates and cluster result.
#' @author Gabriele Lubatti \email{gabriele.lubatti@@helmholtz-muenchen.de}
#' @seealso
#' \url{https://www.rdocumentation.org/packages/Seurat/versions/4.0.1/topics/FindClusters}
#' \url{https://www.rdocumentation.org/packages/Seurat/versions/4.0.1/topics/FindNeighbors}
#' \url{https://www.rdocumentation.org/packages/Seurat/versions/4.0.1/topics/RunPCA}
#' @export cluster_analysis_integrate_rare
cluster_analysis_integrate_rare <- function(raw_counts, project_name, resolution, neighbors, max_dimension, feature_genes = NULL) {
if (!(requireNamespace("Seurat", quietly = TRUE))) {
stop("Package Seurat needed for this function to work. Please install it: install.packages('Seurat')")
}
nFeature_RNA <- NULL
seurat_object <- Seurat::CreateSeuratObject(counts = raw_counts, project = project_name)
seurat_object <- subset( seurat_object, subset = nFeature_RNA > 0)
seurat_object <- Seurat::NormalizeData( seurat_object, verbose = FALSE)
seurat_object <- Seurat::FindVariableFeatures( seurat_object, selection.method = "vst", nfeatures = 2000)
seurat_object <- Seurat::ScaleData( seurat_object, verbose = FALSE)
seurat_object <- Seurat::RunPCA( seurat_object, npcs = max_dimension, verbose = FALSE, features = feature_genes)
seurat_object <- Seurat::RunUMAP( seurat_object, reduction = "pca", dims = 1:20, set.seed = 42)
seurat_object <- Seurat::FindNeighbors( seurat_object, reduction = "pca", dims = 1:max_dimension, k.param = neighbors)
seurat_object <- Seurat::FindClusters( seurat_object, resolution = resolution)
return(seurat_object)}
#' find_resolution
#'
#' @param seurat_object Seurat object as returned by
#' \emph{cluster_analysis_integrate_rare}
#' @param resolution_vector vector with all values of resolution for which the
#' Seurat function \emph{FindClusters} is run
#' @return Clustree object showing the connection between clusters obtained at different level of resolution as specified in \emph{resolution_vector}.
#' @author Gabriele Lubatti \email{gabriele.lubatti@@helmholtz-muenchen.de}
#' @seealso \url{https://CRAN.R-project.org/package=clustree}
#'
#' @export find_resolution
find_resolution <- function(seurat_object, resolution_vector) {
if (!(requireNamespace("Seurat", quietly = TRUE) & requireNamespace("clustree", quietly = TRUE))) {
stop("Package Seurat and clustree needed for this function to work. Please install them: install.packages('Seurat') and install.packages('clustree')")
}
for (i in resolution_vector) {
seurat_object <- Seurat::FindClusters(seurat_object, resolution = i)
}
clustree::clustree(seurat_object)
}
#' @importFrom ggraph guide_edge_colourbar
#' @export
ggraph::guide_edge_colourbar
#' build_fisher_test
#' @noRd
build_fisher_test <- function(a, b, c) {
matrix_test <- matrix(c(sum(c[c%in%a]%in%c[c%in%b]), sum(c[c%in%a]%in%c[!c%in%b]), sum(c[!c%in%a]%in%c[c%in%b]), sum(c[!c%in%a]%in%c[!c%in%b])), nrow = 2, ncol = 2, byrow = T)
fisher.test(matrix_test)
}
#' de_seurat_cluster
#' @noRd
de_seurat_cluster <- function(seurat_object, cluster, names_cell, max_p_value) {
level <- levels(as.factor(cluster))
final_markers <- vector("list", length(level))
for (i in 1:length(level)) {
markers <- Seurat::FindMarkers(seurat_object, ident.1 = names_cell[cluster == level[i]], ident.2 = names_cell[cluster!=level[i]], only.pos = T)
markers_new <- markers[markers$p_val_adj <= max_p_value, ]
markers_new <- markers_new[order(markers_new$p_val_adj), ]
markers_final <- row.names(markers_new)
final_markers[[i]] <- markers_final
}
return(final_markers)
}
#' merge_cluster
#'
#' @param old_cluster original cluster assignment that need to be updated
#' @param new_cluster new cluster assignment that need to be integrated with
#' \emph{old_cluster}.
#' @param max_number Threshold in size for clusters in \emph{new_cluster}. Only
#' cluster with number of cells smaller than \emph{max_number} will be
#' integrated in \emph{old cluster}. If \emph{max_number} is NULL, then all the clusters in \emph{new_cluster} are integrated in \emph{old cluster}.
#' @return Numeric vector of length equal to \emph{old_cluster} showing the merged cluster assignment between \emph{old cluster} and \emph{new_cluster}.
#' @author Gabriele Lubatti \email{gabriele.lubatti@@helmholtz-muenchen.de}
#'
#' @export merge_cluster
merge_cluster <- function(old_cluster, new_cluster, max_number = NULL) {
if(is.null(max_number)) {
cluster_final <- old_cluster
cluster_final[match(names(new_cluster),names(old_cluster))] <- new_cluster
return(cluster_final)
}
else{
index_small <- which(table(new_cluster)<max_number)
cluster_small <- names(table(new_cluster))[index_small]
if (length(cluster_small) > 0) {
message(paste0("Clusters with number of cells below ", max_number, " in the new partition: ", length(cluster_small)))
cluster_final <- old_cluster
for (i in 1:length(cluster_small)) {
cluster_final[as.vector(new_cluster) == cluster_small[i]] <- paste(cluster_small[i], "step_2", sep = "-")
}
return(cluster_final)
}
else {
warning(paste0("There are not clusters with number of cells below ", max_number))
cluster_final <- old_cluster
return(cluster_final)
}
}
}
#' test_hvg
#'
#' For each cluster in \emph{cluster}, HVGs are defined with
#' Seurat function \emph{FindVariableFeatures}. A Fisher test is performed to
#' see if there is a statistically significant enrichment between the top
#' \emph{number_hvg} and the \emph{localized_genes}
#'
#' @param cluster Vector of length equal to the number of cells, with cluster
#' assignment.
#' @param localized_genes Character vector with localized genes detected by CIARA.
#' @param background Character vector with all the genes names to use as
#' background for the Fisher test.
#' @param number_hvg Integer value. Number of top HVGs provided by the Seurat
#' function \emph{FindVariableFeatures}.
#' @param min_p_value Threshold on p values provided by Fisher test.
#' @inheritParams cluster_analysis_integrate_rare
#' @return A list with two elements. \item{first element}{The first one is a
#' list with length equal to the number of clusters. Each entry is list of
#' three elements. The first two elements contain the p value and the odds
#' ration given by the Fisher test The third is a vector with genes names that
#' are present both in \emph{localized_genes} and in top \emph{number_hvg} HVGs
#' .} \item{second element}{a character vector with the name of the cluster that
#' have a p value smaller than \emph{min_p_value}.}
#' @author Gabriele Lubatti \email{gabriele.lubatti@@helmholtz-muenchen.de}
#' @seealso
#' \url{https://www.rdocumentation.org/packages/stats/versions/3.6.2/topics/fisher.test}
#' @export test_hvg
test_hvg <- function (raw_counts, cluster, localized_genes, background, number_hvg, min_p_value)
{
if (!(requireNamespace("Seurat", quietly = TRUE))) {
stop("Package Seurat needed for this function to work. Please install it: install.packages('Seurat')")
}
nFeature_RNA <- NULL
levels_cluster <- levels(as.factor(cluster))
final_p_value <- rep(list(0), length(levels))
for (i in 1:length(levels_cluster)) {
raw_counts_small <- raw_counts[, cluster == levels_cluster[i]]
seurat_object <- Seurat::CreateSeuratObject(counts = raw_counts_small, project = "sub_cluster")
seurat_object <- subset(seurat_object, subset = nFeature_RNA > 0)
seurat_object <- Seurat::NormalizeData(seurat_object, verbose = FALSE)
seurat_object <- Seurat::FindVariableFeatures(seurat_object, selection.method = "vst", nfeatures = number_hvg)
hvg_genes <- seurat_object@[email protected]
fisher_output <- build_fisher_test(localized_genes, hvg_genes, background)
final_p_value[[i]] <- list(fisher_output[[1]], fisher_output[[3]], localized_genes[localized_genes %in% hvg_genes])
}
names(final_p_value) <- levels_cluster
select_sub <- lapply(final_p_value, function(x) {if(x[[1]]<min_p_value & x[[2]] > 1) {
return(TRUE)}
else{return(FALSE)}
})
final_sub <- names(select_sub)[select_sub == TRUE]
return(list(final_p_value, final_sub))
}
#' cluster_analysis_sub
#'
#' @param name_cluster Character.Name of the original cluster for which the sub
#' clustering is done.
#' @inheritParams cluster_analysis_integrate_rare
#' @return Seurat object including raw and normalized counts matrices and cluster result.
#' @author Gabriele Lubatti \email{gabriele.lubatti@@helmholtz-muenchen.de}
#' @seealso
#' \url{https://www.rdocumentation.org/packages/Seurat/versions/4.0.1/topics/RunPCA}
#' \url{https://www.rdocumentation.org/packages/Seurat/versions/4.0.1/topics/FindVariableFeatures}
#' @export cluster_analysis_sub
cluster_analysis_sub <- function (raw_counts, resolution, neighbors, max_dimension, name_cluster) {
if (!(requireNamespace("Seurat", quietly = TRUE))) {
stop("Package Seurat needed for this function to work. Please install it: install.packages('Seurat')")
}
nFeature_RNA <- NULL
seurat_object <- Seurat::CreateSeuratObject(counts = raw_counts, project = "sub_cluster")
seurat_object <- subset(seurat_object, subset = nFeature_RNA > 0)
seurat_object <- Seurat::NormalizeData(seurat_object, verbose = FALSE)
seurat_object <- Seurat::FindVariableFeatures(seurat_object, selection.method = "vst", nfeatures = 2000)
seurat_object <- Seurat::ScaleData(seurat_object, verbose = FALSE)
hvg_genes <- seurat_object@[email protected]
genes_cluster <- hvg_genes
seurat_object <- Seurat::RunPCA(seurat_object, npcs = max_dimension, verbose = FALSE, features = genes_cluster)
seurat_object <- Seurat::FindNeighbors(seurat_object, reduction = "pca", dims = 1:max_dimension, k.param = neighbors)
seurat_object <- Seurat::FindClusters(seurat_object, resolution = resolution)
new_cluster <- as.vector(seurat_object$seurat_clusters)
for (i in 1:length(levels(seurat_object$seurat_clusters))) {
new_cluster[as.vector(seurat_object$seurat_clusters) == levels(seurat_object$seurat_clusters)[i]] <- paste(name_cluster,
new_cluster[as.vector(seurat_object$seurat_clusters) == levels(seurat_object$seurat_clusters)[i]], sep = "_")
}
names(new_cluster) <- names(seurat_object$seurat_clusters)
seurat_object$seurat_clusters <- new_cluster
return(seurat_object)
}
#' markers_cluster_seurat
#'
#' The Seurat function \emph{FindMarkers} is used to identify general marker
#' for each cluster (specific cluster vs all other cluster). This list of
#' markers is then filtered keeping only the genes that appear as markers in a
#' unique cluster.
#'
#' @param seurat_object Seurat object as returned by
#' \emph{cluster_analysis_sub} or by \emph{cluster_analysis_integrate_rare}.
#' @param cell_names Vector of length equal to the number of cells, with cell
#' names.
#' @param number_top Integer. Number of top marker genes to keep for each
#' cluster.
#' @inheritParams test_hvg
#' @return List of three elements. The first is a vector with \emph{number_top}
#' marker genes for each cluster. The second is a vector with \emph{number_top}
#' marker genes and corresponding cluster. The third element is a vector with
#' all marker genes for each cluster.
#'
#' @author Gabriele Lubatti \email{gabriele.lubatti@@helmholtz-muenchen.de}
#' @seealso \url{https://www.rdocumentation.org/packages/Seurat/versions/4.0.1/topics/FindMarkers}
#'
#' @export markers_cluster_seurat
markers_cluster_seurat <- function(seurat_object, cluster, cell_names, number_top) {
if (!(requireNamespace("Seurat", quietly = TRUE))) {
stop("Package Seurat needed for this function to work. Please install it: install.packages('Seurat')")
}
level <- levels(as.factor(cluster))
marker_cluster <- as.list(rep(0, length(level)))
marker_all <- de_seurat_cluster(seurat_object, cluster, cell_names, 0.05)
for (i in 1:length(level)) {
marker_cluster[[i]] <- marker_all[[i]]
message(paste0("Cluster ", level[i]))
}
marker_all <- unlist(marker_cluster)
marker_all <- marker_all[Biobase::isUnique(marker_all)]
for (i in 1:length(level)) {
marker_cluster[[i]] <- marker_cluster[[i]][marker_cluster[[i]]%in%marker_all]
}
marker_to_see <- as.list(rep(0, length(level)))
marker_complete <- as.list(rep(0, length(level)))
for (i in 1:length(level)) {
if (length(marker_cluster[[i]]) >= number_top) {
marker_to_see[[i]] <- marker_cluster[[i]][1:number_top]
names(marker_to_see[[i]]) <- rep(level[i], length(marker_to_see[[i]]))
marker_complete[[i]] <- marker_cluster[[i]]
names(marker_complete[[i]]) <- rep(level[i], length(marker_complete[[i]]))
}
if ((length(marker_cluster[[i]]) > 0)&(length(marker_cluster[[i]])<number_top)) {
marker_to_see[[i]] <- marker_cluster[[i]][1:length(marker_cluster[[i]])]
names(marker_to_see[[i]]) <- rep(level[i], length(marker_to_see[[i]]))
marker_complete[[i]] <- marker_cluster[[i]]
names(marker_complete[[i]]) <- rep(level[i], length(marker_complete[[i]]))
}
if (length(marker_cluster[[i]]) == 0) {
marker_to_see[[i]] <- NULL
marker_complete[[i]] <- NULL
}
}
marker_top <- unlist(marker_to_see)
marker_top <- marker_top[marker_top!=0]
marker_complete <- unlist(marker_complete)
marker_complete <- marker_complete[marker_complete!=0]
marker_all_cluster_sing <- as.list(rep(0, length(level)))
for (i in 1:length(level)) {
if(sum(names(marker_top) == level[i]) > 0) {
marker_all_cluster_sing[[i]] <- paste(marker_top[names(marker_top) == level[i]], level[i], sep="_")
}
else{}
}
marker_all_cluster <- unlist(marker_all_cluster_sing)
marker_all_cluster <- marker_all_cluster[marker_all_cluster!=0]
return(list(marker_top, marker_all_cluster, marker_complete))}
#' white_black_markers
#'
#' A white-marker is a gene whose median expression across cells belong to
#' \emph{single_cluster} is greater than \emph{threshold} and in all the other
#' clusters is equal to zero.
#'
#' @param single_cluster Character. Label of one specify cluster
#' @param marker_list Third element of the output list as returned by the
#' function \emph{markers_cluster_seurat}
#' @param threshold Numeric. The median of the genes across cells belong to
#' \emph{single_cluster} has to be greater than \emph{threshold} in order to be
#' consider as a white-black marker for \emph{single_cluster}
#' @inheritParams test_hvg
#' @inheritParams cluster_analysis_integrate_rare
#' @inheritParams plot_genes_sum
#' @return Logical vector of length equal to \emph{marker_list}, with
#' TRUE/FALSE if the gene is/is not a white-black marker for
#' \emph{single_cluster}.
#' @author Gabriele Lubatti \email{gabriele.lubatti@@helmholtz-muenchen.de}
#'
#' @export white_black_markers
white_black_markers <- function(cluster, single_cluster, norm_counts, marker_list, threshold = 0) {
white_black <- apply(norm_counts[marker_list[names(marker_list) == single_cluster], ], 1, function(x) {
mean_one <- median(x[cluster == single_cluster])
mean_different <- rep(0, length(levels(factor(cluster[cluster!=single_cluster]))))
for ( i in 1:length(levels(factor(cluster[cluster!=single_cluster])))) {
mean_different[i] <- median(x[cluster == levels(factor(cluster[cluster!=single_cluster]))[i]])}
if (mean_one > threshold&sum(mean_different) == 0) {
return(TRUE)
}
else{
return(FALSE)
}
})
return(white_black)
}
|
/scratch/gouwar.j/cran-all/cranData/CIARA/R/Clustering_functions.R
|
#' plot_umap
#'
#' @param coordinate_umap Data frame with dimensionality reduction coordinates.
#' Number of rows must be equal to the number of cells
#' @inheritParams test_hvg
#' @return ggplot2 object.
#' @author Gabriele Lubatti \email{gabriele.lubatti@@helmholtz-muenchen.de}
#' @seealso \url{https://CRAN.R-project.org/package=ggplot2}
#' @export plot_umap
plot_umap <- function(coordinate_umap, cluster){
umap_plot <- ggplot2::ggplot(coordinate_umap, ggplot2::aes(coordinate_umap[, 1], coordinate_umap[, 2] )) +
ggplot2::geom_point(ggplot2::aes(colour = as.factor(cluster))) + ggplot2::xlab("UMAP 1") + ggplot2::ylab("UMAP 2") + ggplot2::labs(col = "Cluster")
return(list(umap_plot))
}
#' gg_color_hue
#' @noRd
gg_color_hue <- function(n) {
hues <- seq(15, 375, length = n + 1)
hcl(h = hues, l = 65, c = 100)[1:n]
}
#' plot_genes_sum
#'
#' The sum of each gene in \emph{genes_relevant} across all cells is first
#' normalized to 1. Then for each cell, the sum from the (normalized) genes
#' expression is computed and shown in the output plot.
#'
#' @param norm_counts Norm count matrix (genes X cells).
#' @param genes_relevant Vector with gene names for which we want to visualize
#' the sum in each cell.
#' @param name_title Character value.
#' @inheritParams plot_umap
#' @return ggplot2 object.
#' @author Gabriele Lubatti \email{gabriele.lubatti@@helmholtz-muenchen.de}
#' @seealso \url{ https://CRAN.R-project.org/package=ggplot2}
#'
#' @export plot_genes_sum
plot_genes_sum <- function(coordinate_umap, norm_counts, genes_relevant, name_title){
norm_counts_small <- apply(norm_counts[genes_relevant, ], 1, function(x){
y <- x/sum(x)
return(y)
})
gene_sum <- apply(norm_counts_small, 1, sum)
index_sort <- order(gene_sum)
row.names(coordinate_umap) <- colnames(norm_counts)
coordinate_umap <- coordinate_umap[colnames(norm_counts)[index_sort], ]
gene_sum <- sort(gene_sum)
umap_plot <- ggplot2::ggplot(coordinate_umap, ggplot2::aes(coordinate_umap[, 1], coordinate_umap[, 2] )) +
ggplot2::geom_point(ggplot2::aes(colour = (gene_sum))) + ggplot2::xlab("UMAP 1") + ggplot2::ylab("UMAP 2") + ggplot2::labs(col = "Log norm counts") +
ggplot2::scale_colour_gradient(low = "white", high = "blue") +
ggplot2::ggtitle(name_title)
return((umap_plot))
}
#' plot_gene
#'
#' Cells are coloured according to the expression of \emph{gene_id} and plotted
#' according to \emph{coordinate_umap}.
#'
#' @param gene_id Character name of the gene.
#' @param title_name Character name.
#' @inheritParams plot_genes_sum
#' @inheritParams plot_umap
#' @return ggplot2 object.
#' @author Gabriele Lubatti \email{gabriele.lubatti@@helmholtz-muenchen.de}
#' @seealso \url{https://CRAN.R-project.org/package=ggplot2}
#'
#' @export plot_gene
plot_gene <- function(norm_counts, coordinate_umap, gene_id, title_name){
gene_expr <- as.vector(norm_counts[gene_id, ])
index_sort <- order(gene_expr)
row.names(coordinate_umap) <- colnames(norm_counts)
coordinate_umap <- coordinate_umap[colnames(norm_counts)[index_sort], ]
gene_expr <- sort(gene_expr)
umap_plot <- ggplot2::ggplot(coordinate_umap, ggplot2::aes(coordinate_umap[, 1], coordinate_umap[, 2] )) +
ggplot2::geom_point(ggplot2::aes(colour = (gene_expr))) + ggplot2::xlab("UMAP 1") + ggplot2::ylab("UMAP 2") + ggplot2::labs(col = "Log norm counts")+
ggplot2::scale_colour_gradient(low = "white", high = "blue") +
ggplot2::ggtitle(title_name)
return((umap_plot))
}
#' plot_heatmap_marker
#'
#' @param marker_top First element returned by \emph{markers_cluster_seurat}
#' @param marker_all_cluster Second element returned by
#' \emph{markers_cluster_seurat}
#' @param condition Vector or length equal to the number of cells, specifying
#' the condition of the cells (i.e. batch, dataset of origin..)
#' @param text_size Size of the text in the heatmap plot.
#' @inheritParams test_hvg
#' @inheritParams plot_genes_sum
#' @return Heatmap class object.
#' @author Gabriele Lubatti \email{gabriele.lubatti@@helmholtz-muenchen.de}
#' @seealso \url{https://www.rdocumentation.org/packages/ComplexHeatmap/versions/1.10.2/topics/Heatmap}
#'
#' @export plot_heatmap_marker
plot_heatmap_marker <- function(marker_top, marker_all_cluster, cluster, condition, norm_counts, text_size){
if (!(requireNamespace("ComplexHeatmap", quietly = TRUE) & requireNamespace("circlize", quietly = TRUE))) {
stop("Package ComplexHeatmap and circlize needed for this function to work. Please install them: BiocManager::install('ComplexHeatmap') and install.packages('circlize')")
}
cluster_unique <- unique(cluster)
cluster_unique <- sort(cluster_unique, decreasing = F)
index <- as.list(rep(0, length(unique(cluster))))
for (i in 1:length(cluster_unique)){
index[[i]] <- which(cluster==cluster_unique[i])
}
condition_unique <- as.list(rep(0, length(unique(cluster))))
for (i in 1:length(cluster_unique)){
condition_unique[[i]] <- condition[index[[i]]]
}
cell_all_day <- colnames(norm_counts)
cell_unique <- as.list(rep(0, length(unique(cluster))))
for (i in 1:length(cluster_unique)){
cell_unique[[i]] <- cell_all_day[index[[i]]]
}
cluster_unique_2 <- as.list(rep(0, length(unique(cluster))))
for (i in 1:length(cluster_unique)){
cluster_unique_2[[i]] <- cluster[index[[i]]]
}
cluster_finale <- unlist(cluster_unique_2)
good_finale <- unlist(cell_unique)
medium_finale <- unlist(condition_unique)
norm_counts_plot <- norm_counts[marker_top, good_finale]
row.names(norm_counts_plot)<-marker_all_cluster
color_cluster <- rep(0, length(unique(cluster)))
for (i in 1:length(color_cluster) ){
color_cluster[i] <- gg_color_hue(length(color_cluster))[i]
}
names(color_cluster) <- as.character(cluster_unique)
color_condition <- rep(0, length(unique(condition)))
for (i in 1:length(color_condition) ){
color_condition[i] <- gg_color_hue(length(color_condition))[i]
}
names(color_condition) <- as.character(unique(condition))
condition_factor <- factor(condition)
names(color_condition) <- as.character(levels(condition_factor))
data_heatmap <- data.frame(Cluster = cluster_finale
,Condition = medium_finale)
haCol1 <- ComplexHeatmap::HeatmapAnnotation(df = data_heatmap, col = list(Cluster = color_cluster, Condition = color_condition)
, show_legend = T)
ht21 <- ComplexHeatmap::Heatmap(as.matrix(norm_counts_plot)
,cluster_rows = FALSE
, col = circlize::colorRamp2(c(0, round(max(norm_counts_plot))), c("white", "red"))
, name = "log norm counts"
, cluster_columns = F
, top_annotation = haCol1
, row_names_gp = grid::gpar(fontsize = text_size
)
, show_column_names = F
, show_row_names = T)
ComplexHeatmap::draw(ht21)
}
#' plot_interactive
#'
#' It shows in an interactive plot which are the highly localized genes in each
#' cell. It is based on plotly library
#' @param color vector of length equal to n_rows in coordinate_umap.Each cell
#' will be coloured following a gradient according to the corresponding value
#' of this vector.
#' @param text Character vector specifying the highly localized genes in each
#' cell. It is the output from \emph{selection_localized_genes}.
#' @param min_x Set the min limit on the x axis.
#' @param max_x Set the max limit on the x axis.
#' @param min_y Set the min limit on the y axis.
#' @param max_y Set the min limit on the y axis.
#' @inheritParams plot_umap
#' @return plotly object given by \emph{plot_ly function} (from library \emph{plotly}).
#' @author Gabriele Lubatti \email{gabriele.lubatti@@helmholtz-muenchen.de}
#' @seealso \url{https://plotly.com/r/}
#' @export plot_interactive
plot_interactive <- function(coordinate_umap, color, text, min_x = NULL, max_x = NULL, min_y = NULL, max_y = NULL){
if (! requireNamespace("plotly", quietly = TRUE)) {
stop("Package plotly needed for interactive == TRUE. Please install it: install.packages('plotly')")
}
colnames(coordinate_umap) <- c("UMAP_1", "UMAP_2")
fig <- plotly::plot_ly(data = coordinate_umap,
x = ~UMAP_1, y = ~UMAP_2,
color = ~color,
type = "scatter",
mode = "markers",
marker = list(size = 5, width = 2),
text = ~text,
hoverinfo = "text"
)
if(!is.null(min_x)){
fig <- fig %>% plotly::layout(
xaxis = list(range = c(min_x, max_x)),
yaxis = list(range = c(min_y, max_y)))
}
return(fig)
}
#' selection_localized_genes
#'
#' @param localized_genes vector of highly localized genes as provided by the
#' last element of the list given as output from \emph{CIARA_mixing_final}.
#' @param min_number_cells Minimum number of cells where a genes must be
#' expressed (> 0).
#' @param max_number_genes Maximum number of genes to show for each cell in the
#' interactive plot from \emph{plot_interactive}.
#' @inheritParams plot_genes_sum
#' @inheritParams test_hvg
#' @return Character vector where each entry contains the name of the top
#' \emph{max_number_genes} for the corresponding cell.
#' @author Gabriele Lubatti \email{gabriele.lubatti@@helmholtz-muenchen.de}
#'
#' @export selection_localized_genes
selection_localized_genes <- function (norm_counts, localized_genes, min_number_cells = 4,
max_number_genes = 10) {
norm_counts_CIARA <- norm_counts[(localized_genes), ]
logic_CIARA <- apply(norm_counts_CIARA, 1, function(x) {
y = as.list(x)
return(y)
})
logic_CIARA_greater <- lapply(logic_CIARA, function(x) {
y <- x[!all(x == 0)]
if (length(y) > 0) {
return(y)
}
else {
return(NULL)
}
})
index <- rep(0, length(logic_CIARA_greater))
for (i in 1:length(logic_CIARA_greater)) {
index[i] <- sum(logic_CIARA_greater[[i]] > 0)
}
localized_genes <- localized_genes[index > min_number_cells]
top_genes <- apply(norm_counts[localized_genes, ], 2, function(x) {
y <- sort(x, decreasing = T)
if (max_number_genes>length(localized_genes)) {
max_number_genes <- length(localized_genes)
warning("max_number bigger than length of localized_genes. Set max_number_genes = length(localized_genes) ")
}
z <- y[1:max_number_genes]
k <- localized_genes[order(x, decreasing = T)][1:max_number_genes]
return(list(z, k))
})
sum_loc_genes <- rep(0, length(top_genes))
for (i in 1:length(top_genes)) {
sum_loc_genes[i] <- sum(as.numeric(top_genes[[i]][[1]]) > 0)
}
text <- rep("NO", length(colnames(norm_counts)))
for (i in 1:length(top_genes)) {
text[i] <- paste(top_genes[[i]][[2]], collapse = "-")
}
text[sum_loc_genes == 0] <- "No specific genes"
return(text)
}
#' plot_balloon_marker
#'
#' @param marker_complete Third element of the output list as
#' returned by the function \emph{markers_cluster_seurat}
#' @param max_number Integer. Maximum number of markers for each cluster for
#' which we want to plot the expression.
#' @param max_size Integer. Size of the dots to be plotted.
#' @inheritParams plot_genes_sum
#' @inheritParams test_hvg
#' @inheritParams plot_heatmap_marker
#' @return ggplot2 object showing balloon plot.
#' @author Gabriele Lubatti \email{gabriele.lubatti@@helmholtz-muenchen.de}
#' @export plot_balloon_marker
plot_balloon_marker <- function (norm_counts, cluster, marker_complete,
max_number, max_size = 5, text_size = 7) {
livelli <- levels(factor(cluster))
all_markers_plot <- rep(list(0), length(livelli))
all_markers <- rep(list(0), length(livelli))
for (i in 1:length(livelli)) {
genes_4_0 <- marker_complete[(names(marker_complete) == livelli[i])]
if (length(genes_4_0) > 0) {
genes_4_0 <- genes_4_0[1:max_number]
all_markers[[i]] <- genes_4_0
genes_4_0_plot <- paste(livelli[i], genes_4_0, sep = "_")
all_markers_plot[[i]] <- genes_4_0_plot
}
}
all_markers <- lapply(all_markers, function(x) {
x[x != 0]
})
all_markers_plot <- lapply(all_markers_plot, function(x) {
x[x != 0]
})
all_markers_values <- rep(list(0), length(livelli))
for (i in 1:length(livelli)) {
gene_values_0 <- apply(norm_counts[unlist(all_markers, use.names = FALSE), cluster == livelli[i]], 1, mean)
all_markers_values[[i]] <- gene_values_0
}
values <- rep(list(0), length(livelli))
for (i in 1:length(livelli)) {
valore <- apply(norm_counts[unlist(all_markers, use.names = FALSE), cluster == livelli[i]], 1, function(x) {
sum(x > 1)/length(x)
})
values[[i]] <- valore
}
cluster_label_all <- rep(list(0), length(livelli))
for (i in 1:length(livelli)) {
cluster_label_all[[i]] <- rep(livelli[i], length(unlist(all_markers)))
}
all_markers_plot <- unlist(all_markers_plot)
cluster_label_all <- unlist(cluster_label_all)
values <- unlist(values)
all_markers_values <- unlist(all_markers_values)
balloon_melted <- data.frame(all_markers_plot, cluster_label_all, values)
colnames(balloon_melted) <- c("all_markers_plot", "cluster_label_all", "values")
p <- ggplot2::ggplot(balloon_melted, ggplot2::aes(x = cluster_label_all, y = all_markers_plot))
p + ggplot2::geom_point(ggplot2::aes(size = values, colour = as.numeric(all_markers_values))) + ggplot2::theme(panel.background = ggplot2::element_blank(), panel.border = ggplot2::element_rect(colour = "blue", fill = NA, size = 3)) +
ggplot2::scale_size_area(max_size = max_size) + ggplot2::scale_colour_gradient(low = "white", high = "midnight blue", na.value = NA) +
ggplot2::labs(colour = "Mean log2 norm expression", size = "Value (fraction cells above 1 log2 norm counts)") +
ggplot2::xlab("Cluster") + ggplot2::ylab("Markers") + ggplot2::theme(text = ggplot2::element_text(size = text_size), axis.text.x = ggplot2::element_text(angle = 45, vjust = 1, hjust = 1), axis.title.x = ggplot2::element_blank())
}
|
/scratch/gouwar.j/cran-all/cranData/CIARA/R/Plotting_functions.R
|
## ---- include = FALSE---------------------------------------------------------
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
fig.width=7,
fig.height=5
)
## ----setup--------------------------------------------------------------------
library(CIARA)
required <- c("Seurat")
if (!all(unlist(lapply(required, function(pkg) requireNamespace(pkg, quietly = TRUE)))))
knitr::opts_chunk$set(eval = FALSE)
## -----------------------------------------------------------------------------
umap_elmir <- readRDS(system.file("extdata", "annot_umap.rds", package = "CIARA"))
coordinate_umap_human <- umap_elmir[, 2:3]
## ---- eval = FALSE------------------------------------------------------------
# human_data_seurat <- cluster_analysis_integrate_rare(raw_counts_human_data, "Human_data", 0.1, 5, 30)
#
#
## ---- eval = FALSE------------------------------------------------------------
#
# norm_human_data <- as.matrix(Seurat::GetAssayData(human_data_seurat, slot = "data", assay = "RNA"))
#
# knn_human_data <- as.matrix(human_data_seurat@graphs$RNA_nn)
#
#
#
#
## -----------------------------------------------------------------------------
original_cluster_human <- as.vector(umap_elmir$cluster_id)
names(original_cluster_human) <- names(umap_elmir$cell_name)
plot_umap(coordinate_umap_human, original_cluster_human)
## ---- eval = FALSE------------------------------------------------------------
# background <- get_background_full(norm_human_data, threshold = 1, n_cells_low = 3, n_cells_high = 20)
# result <- CIARA(norm_human_data, knn_human_data, background, cores_number = 1, p_value = 0.001, odds_ratio = 2, local_region = 1, approximation = FALSE)
## -----------------------------------------------------------------------------
load(system.file("extdata", "result.Rda", package = "CIARA"))
## -----------------------------------------------------------------------------
ciara_genes <- row.names(result)[result[, 1]<1]
ciara_genes_top <- row.names(result)[order(as.numeric(result[, 1]))]
## ---- eval = FALSE------------------------------------------------------------
# norm_human_data_ciara <- norm_human_data[ciara_genes, ]
## -----------------------------------------------------------------------------
load(system.file("extdata", "norm_human_data_ciara.Rda", package = "CIARA"))
## -----------------------------------------------------------------------------
p <- list()
for(i in (ciara_genes_top)[1:5]) {
q <- plot_gene(norm_human_data_ciara, coordinate_umap_human, i, i)
p <- list(p, q)
}
p
## -----------------------------------------------------------------------------
background <- row.names(result)
## -----------------------------------------------------------------------------
plot_genes_sum(coordinate_umap_human, norm_human_data_ciara, (ciara_genes), "Sum from top CIARA genes")
## -----------------------------------------------------------------------------
norm_counts_small <- apply(norm_human_data_ciara, 1, function(x) {
y <- x/sum(x)
return(y)
})
gene_sum <- apply(norm_counts_small, 1, sum)
genes_name_text <- selection_localized_genes(norm_human_data_ciara, ciara_genes, min_number_cells = 4, max_number_genes = 4)
colnames(coordinate_umap_human) <- c("UMAP_1", "UMAP_2")
if ((requireNamespace("plotly", quietly = TRUE))) {
plot_interactive(coordinate_umap_human, gene_sum, genes_name_text, min_x = NULL, max_x = NULL, min_y = NULL, max_y = NULL)
}
## ---- eval = FALSE------------------------------------------------------------
# human_data_ciara <- cluster_analysis_integrate_rare(raw_counts_human_data, "Elmir data", 0.01, 5, 30, (ciara_genes))
#
## ---- eval = FALSE------------------------------------------------------------
# if ((requireNamespace("clustree", quietly = TRUE))) {
# find_resolution(human_data_ciara, seq(0.01, 1, 0.1))
# }
## ---- eval = FALSE------------------------------------------------------------
# ciara_cluster_human <- human_data_ciara$RNA_snn_res.0.01
## -----------------------------------------------------------------------------
load(system.file("extdata", "ciara_cluster_human.Rda", package = "CIARA"))
## -----------------------------------------------------------------------------
plot_umap(coordinate_umap_human, ciara_cluster_human)
plot_gene(norm_human_data_ciara, coordinate_umap_human, "NANOS3", "NANOS3")
plot_gene(norm_human_data_ciara, coordinate_umap_human, "NANOG", "NANOG")
plot_gene(norm_human_data_ciara, coordinate_umap_human, "DPPA5", "DPPA5")
## -----------------------------------------------------------------------------
final_cluster_human <- merge_cluster(original_cluster_human, ciara_cluster_human, 10)
## -----------------------------------------------------------------------------
final_cluster_human[final_cluster_human == "2-step_2"] <- "PGC"
## -----------------------------------------------------------------------------
plot_umap(coordinate_umap_human, final_cluster_human)
## ---- eval = FALSE------------------------------------------------------------
#
# result_test <- test_hvg(raw_counts_human_data, final_cluster_human, (ciara_genes), background, 100, 0.05)
#
## ---- eval = FALSE------------------------------------------------------------
# result_test[[2]]
## ---- eval = FALSE------------------------------------------------------------
#
# raw_endoderm <- raw_counts_human_data[, as.vector(umap_elmir$cluster_id) == "Endoderm"]
# raw_hemo <- raw_counts_human_data[, as.vector(umap_elmir$cluster_id) == "Hemogenic Endothelial Progenitors"]
# raw_exe_meso <- raw_counts_human_data[, as.vector(umap_elmir$cluster_id) == "ExE Mesoderm"]
#
#
#
# combined_endoderm <- cluster_analysis_sub(raw_endoderm, 0.2, 5, 30, "Endoderm")
#
# combined_hemo <- cluster_analysis_sub(raw_hemo, 0.6, 5, 30, "Hemogenic Endothelial Progenitors")
#
# combined_exe_meso <- cluster_analysis_sub(raw_exe_meso, 0.5, 5, 30, "ExE Mesoderm")
#
#
#
#
#
## ---- eval = FALSE------------------------------------------------------------
#
# all_sub_cluster <- c(combined_endoderm$seurat_clusters, combined_hemo$seurat_clusters, combined_exe_meso$seurat_clusters)
# final_cluster_human_version_sub <- merge_cluster(final_cluster_human, all_sub_cluster)
## -----------------------------------------------------------------------------
load(system.file("extdata", "final_cluster_human_version_sub.Rda", package = "CIARA"))
## -----------------------------------------------------------------------------
plot_umap(coordinate_umap_human, final_cluster_human_version_sub)
## -----------------------------------------------------------------------------
table(as.vector(final_cluster_human_version_sub))
## ---- eval = FALSE------------------------------------------------------------
# Seurat::DefaultAssay(human_data_seurat) <- "RNA"
# markers_human_final <- markers_cluster_seurat(human_data_seurat, final_cluster_human_version_sub, names(human_data_seurat$RNA_snn_res.0.1), 5)
#
# markers_human_top_final <- markers_human_final[[1]]
# markers_human_all_final <- markers_human_final[[3]]
## ---- eval = FALSE------------------------------------------------------------
# white_black_markers <- white_black_markers(final_cluster_human_version_sub, "Hemogenic Endothelial Progenitors_4", norm_human_data, markers_human_all_final, 0)
# sum(white_black_markers)
#
## ---- eval = FALSE------------------------------------------------------------
# white_black_markers <- white_black_markers(final_cluster_human_version_sub, "Endoderm_2", norm_human_data, markers_human_all_final, 0)
# sum(white_black_markers)
## ---- eval = FALSE------------------------------------------------------------
# white_black_markers <- white_black_markers(final_cluster_human_version_sub, "ExE Mesoderm_0", norm_human_data, markers_human_all_final, 0)
# sum(white_black_markers)
## ---- eval = FALSE------------------------------------------------------------
#
# top_endo <- white_black_markers(final_cluster_human_version_sub, "Endoderm_2", norm_human_data, markers_human_all_final, 0)
# top_endo <- names(top_endo)[top_endo]
#
#
# mean_top_endo <- apply(norm_human_data[top_endo, final_cluster_human_version_sub == "Endoderm_2"], 1, mean)
# mean_top_endo <- sort(mean_top_endo, decreasing = T)
#
# top_endo <- names(mean_top_endo)
# names(top_endo) <- rep("Endoderm_2", length(top_endo))
#
## ---- eval = FALSE------------------------------------------------------------
#
# top_hemo <- white_black_markers(final_cluster_human_version_sub, "Hemogenic Endothelial Progenitors_4", norm_human_data, markers_human_all_final, 0)
# top_hemo <- names(top_hemo)[top_hemo]
#
#
# mean_top_hemo <- apply(norm_human_data[top_hemo, final_cluster_human_version_sub == "Hemogenic Endothelial Progenitors_4"], 1, mean)
# mean_top_hemo <- sort(mean_top_hemo, decreasing = T)
#
# top_hemo <- names(mean_top_hemo)
# names(top_hemo) <- rep("Hemogenic Endothelial Progenitors_4", length(top_hemo))
## ---- eval = FALSE------------------------------------------------------------
# top_meso <- white_black_markers(final_cluster_human_version_sub, "ExE Mesoderm_1", norm_human_data, markers_human_all_final, 0)
# top_meso <- names(top_meso)[top_meso]
#
#
# mean_top_meso <- apply(norm_human_data[top_meso, final_cluster_human_version_sub == "ExE Mesoderm_1"], 1, mean)
# mean_top_meso <- sort(mean_top_meso, decreasing = T)
#
# top_meso <- names(mean_top_meso)
# names(top_meso) <- rep("ExE Mesoderm_1", length(top_meso))
#
#
#
## ---- eval = FALSE------------------------------------------------------------
# norm_human_data_plot <- norm_human_data[c(top_endo, top_hemo, top_meso), ]
## -----------------------------------------------------------------------------
load(system.file("extdata", "norm_human_data_plot.Rda", package = "CIARA"))
load(system.file("extdata", "top_meso.Rda", package = "CIARA"))
load(system.file("extdata", "top_endo.Rda", package = "CIARA"))
load(system.file("extdata", "top_hemo.Rda", package = "CIARA"))
## -----------------------------------------------------------------------------
toMatch <- c("Endoderm")
plot_balloon_marker(norm_human_data_plot[, grep(paste(toMatch, collapse="|"), final_cluster_human)], final_cluster_human_version_sub[grep(paste(toMatch, collapse="|"), final_cluster_human)], top_endo, 20, max_size=5, text_size=10)
toMatch <- c("Hemogenic Endothelial Progenitors")
plot_balloon_marker(norm_human_data_plot[, grep(paste(toMatch, collapse = "|"), final_cluster_human)], final_cluster_human_version_sub[grep(paste(toMatch, collapse = "|"), final_cluster_human)], top_hemo, 20, max_size = 5, text_size = 8)
toMatch <- c("ExE Mesoderm")
plot_balloon_marker(norm_human_data_plot[, grep(paste(toMatch, collapse = "|"), final_cluster_human)], final_cluster_human_version_sub[grep(paste(toMatch, collapse = "|"), final_cluster_human)], top_meso, length(top_meso), max_size = 5, text_size = 8)
## -----------------------------------------------------------------------------
plot_gene(norm_human_data_ciara, coordinate_umap_human, "C1R", "C1R")
plot_gene(norm_human_data_ciara, coordinate_umap_human, "NANOS3", "NANOS3")
plot_gene(norm_human_data_ciara, coordinate_umap_human, "NANOG", "NANOG")
plot_gene(norm_human_data_ciara, coordinate_umap_human, "SOX17", "SOX17")
plot_gene(norm_human_data_ciara, coordinate_umap_human, "DPPA5", "DPPA5")
plot_gene(norm_human_data_ciara, coordinate_umap_human, "CSF1", "CSF1")
## -----------------------------------------------------------------------------
utils::sessionInfo()
|
/scratch/gouwar.j/cran-all/cranData/CIARA/inst/doc/CIARA.R
|
---
title: "CIARA"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{CIARA}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
% \VignetteDepends{Seurat}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
fig.width=7,
fig.height=5
)
```
The vignette depends on Seurat package.
```{r setup}
library(CIARA)
required <- c("Seurat")
if (!all(unlist(lapply(required, function(pkg) requireNamespace(pkg, quietly = TRUE)))))
knitr::opts_chunk$set(eval = FALSE)
```
In this vignette it is shown the analysis performed on single cell RNA seq human gastrula data from [Tyser, R.C.V. et al., 2021](https://www.nature.com/articles/s41586-021-04158-y#citeas).
## Load human gastrula data and create norm counts and knn matrices using Seurat
We load the raw count matrix and umap coordinate defined in the original paper.
Raw count matrix can be downloaded [here](http://www.human-gastrula.net)
```{r }
umap_elmir <- readRDS(system.file("extdata", "annot_umap.rds", package = "CIARA"))
coordinate_umap_human <- umap_elmir[, 2:3]
```
Obtain normalized count matrix and knn matrix ( euclidean distance on highly variable genes) using Seurat.
```{r, eval = FALSE }
human_data_seurat <- cluster_analysis_integrate_rare(raw_counts_human_data, "Human_data", 0.1, 5, 30)
```
```{r, eval = FALSE }
norm_human_data <- as.matrix(Seurat::GetAssayData(human_data_seurat, slot = "data", assay = "RNA"))
knn_human_data <- as.matrix(human_data_seurat@graphs$RNA_nn)
```
Cluster annotation provided in the original paper
```{r }
original_cluster_human <- as.vector(umap_elmir$cluster_id)
names(original_cluster_human) <- names(umap_elmir$cell_name)
plot_umap(coordinate_umap_human, original_cluster_human)
```
## Run CIARA
CIARA (Cluster Independent Algorithm for the identification of RAre cell types) is a cluster independent approach that selects genes localized in a small number of neighboring cells from high dimensional PCA space.
We don't execute the CIARA algorithm and we directly load the result
```{r, eval = FALSE}
background <- get_background_full(norm_human_data, threshold = 1, n_cells_low = 3, n_cells_high = 20)
result <- CIARA(norm_human_data, knn_human_data, background, cores_number = 1, p_value = 0.001, odds_ratio = 2, local_region = 1, approximation = FALSE)
```
```{r }
load(system.file("extdata", "result.Rda", package = "CIARA"))
```
## Identifying highly localized genes
```{r }
ciara_genes <- row.names(result)[result[, 1]<1]
ciara_genes_top <- row.names(result)[order(as.numeric(result[, 1]))]
```
```{r, eval = FALSE}
norm_human_data_ciara <- norm_human_data[ciara_genes, ]
```
```{r }
load(system.file("extdata", "norm_human_data_ciara.Rda", package = "CIARA"))
```
```{r }
p <- list()
for(i in (ciara_genes_top)[1:5]) {
q <- plot_gene(norm_human_data_ciara, coordinate_umap_human, i, i)
p <- list(p, q)
}
p
```
```{r }
background <- row.names(result)
```
```{r }
plot_genes_sum(coordinate_umap_human, norm_human_data_ciara, (ciara_genes), "Sum from top CIARA genes")
```
It is also possible to explore wich genes are highly localized in which cells in an interactive way
```{r }
norm_counts_small <- apply(norm_human_data_ciara, 1, function(x) {
y <- x/sum(x)
return(y)
})
gene_sum <- apply(norm_counts_small, 1, sum)
genes_name_text <- selection_localized_genes(norm_human_data_ciara, ciara_genes, min_number_cells = 4, max_number_genes = 4)
colnames(coordinate_umap_human) <- c("UMAP_1", "UMAP_2")
if ((requireNamespace("plotly", quietly = TRUE))) {
plot_interactive(coordinate_umap_human, gene_sum, genes_name_text, min_x = NULL, max_x = NULL, min_y = NULL, max_y = NULL)
}
```
## Cluster analysis using CIARA highly localized genes
We run louvain cluster analysis implemented in Seurat using as features the highly localized genes provided by CIARA
```{r, eval = FALSE}
human_data_ciara <- cluster_analysis_integrate_rare(raw_counts_human_data, "Elmir data", 0.01, 5, 30, (ciara_genes))
```
We can explore how much the number of clusters changes with the resolution. The original cluster 1 and 2 for resolution 0.01 are constantly present for higher values of resolution.
```{r, eval = FALSE }
if ((requireNamespace("clustree", quietly = TRUE))) {
find_resolution(human_data_ciara, seq(0.01, 1, 0.1))
}
```
Cluster 2 (7 cells) is made up by primordial germ cells (PGCs). These cells expressed typical PGCs markers ad NANOS3, NANOG and DPPA5
```{r, eval = FALSE }
ciara_cluster_human <- human_data_ciara$RNA_snn_res.0.01
```
```{r }
load(system.file("extdata", "ciara_cluster_human.Rda", package = "CIARA"))
```
```{r }
plot_umap(coordinate_umap_human, ciara_cluster_human)
plot_gene(norm_human_data_ciara, coordinate_umap_human, "NANOS3", "NANOS3")
plot_gene(norm_human_data_ciara, coordinate_umap_human, "NANOG", "NANOG")
plot_gene(norm_human_data_ciara, coordinate_umap_human, "DPPA5", "DPPA5")
```
`
Merge the original cluster annotation with the one found using CIARA highly localized genes
```{r}
final_cluster_human <- merge_cluster(original_cluster_human, ciara_cluster_human, 10)
```
```{r}
final_cluster_human[final_cluster_human == "2-step_2"] <- "PGC"
```
```{r }
plot_umap(coordinate_umap_human, final_cluster_human)
```
## Sub-cluster analysis using CIARA
Detect the clusters enriched in highly localized genes and then performs on these a sub-cluster analysis (using louvain algorithm implemented in Seurat)
```{r, eval = FALSE }
result_test <- test_hvg(raw_counts_human_data, final_cluster_human, (ciara_genes), background, 100, 0.05)
```
```{r, eval = FALSE }
result_test[[2]]
```
```{r, eval = FALSE }
raw_endoderm <- raw_counts_human_data[, as.vector(umap_elmir$cluster_id) == "Endoderm"]
raw_hemo <- raw_counts_human_data[, as.vector(umap_elmir$cluster_id) == "Hemogenic Endothelial Progenitors"]
raw_exe_meso <- raw_counts_human_data[, as.vector(umap_elmir$cluster_id) == "ExE Mesoderm"]
combined_endoderm <- cluster_analysis_sub(raw_endoderm, 0.2, 5, 30, "Endoderm")
combined_hemo <- cluster_analysis_sub(raw_hemo, 0.6, 5, 30, "Hemogenic Endothelial Progenitors")
combined_exe_meso <- cluster_analysis_sub(raw_exe_meso, 0.5, 5, 30, "ExE Mesoderm")
```
```{r, eval = FALSE }
all_sub_cluster <- c(combined_endoderm$seurat_clusters, combined_hemo$seurat_clusters, combined_exe_meso$seurat_clusters)
final_cluster_human_version_sub <- merge_cluster(final_cluster_human, all_sub_cluster)
```
```{r }
load(system.file("extdata", "final_cluster_human_version_sub.Rda", package = "CIARA"))
```
```{r}
plot_umap(coordinate_umap_human, final_cluster_human_version_sub)
```
```{r}
table(as.vector(final_cluster_human_version_sub))
```
## CIARA identifies three rare population of cells with highly distinctive transcriptional profile
```{r, eval = FALSE}
Seurat::DefaultAssay(human_data_seurat) <- "RNA"
markers_human_final <- markers_cluster_seurat(human_data_seurat, final_cluster_human_version_sub, names(human_data_seurat$RNA_snn_res.0.1), 5)
markers_human_top_final <- markers_human_final[[1]]
markers_human_all_final <- markers_human_final[[3]]
```
```{r, eval = FALSE }
white_black_markers <- white_black_markers(final_cluster_human_version_sub, "Hemogenic Endothelial Progenitors_4", norm_human_data, markers_human_all_final, 0)
sum(white_black_markers)
```
```{r, eval = FALSE}
white_black_markers <- white_black_markers(final_cluster_human_version_sub, "Endoderm_2", norm_human_data, markers_human_all_final, 0)
sum(white_black_markers)
```
```{r, eval = FALSE}
white_black_markers <- white_black_markers(final_cluster_human_version_sub, "ExE Mesoderm_0", norm_human_data, markers_human_all_final, 0)
sum(white_black_markers)
```
```{r, eval = FALSE}
top_endo <- white_black_markers(final_cluster_human_version_sub, "Endoderm_2", norm_human_data, markers_human_all_final, 0)
top_endo <- names(top_endo)[top_endo]
mean_top_endo <- apply(norm_human_data[top_endo, final_cluster_human_version_sub == "Endoderm_2"], 1, mean)
mean_top_endo <- sort(mean_top_endo, decreasing = T)
top_endo <- names(mean_top_endo)
names(top_endo) <- rep("Endoderm_2", length(top_endo))
```
```{r, eval = FALSE}
top_hemo <- white_black_markers(final_cluster_human_version_sub, "Hemogenic Endothelial Progenitors_4", norm_human_data, markers_human_all_final, 0)
top_hemo <- names(top_hemo)[top_hemo]
mean_top_hemo <- apply(norm_human_data[top_hemo, final_cluster_human_version_sub == "Hemogenic Endothelial Progenitors_4"], 1, mean)
mean_top_hemo <- sort(mean_top_hemo, decreasing = T)
top_hemo <- names(mean_top_hemo)
names(top_hemo) <- rep("Hemogenic Endothelial Progenitors_4", length(top_hemo))
```
```{r, eval = FALSE}
top_meso <- white_black_markers(final_cluster_human_version_sub, "ExE Mesoderm_1", norm_human_data, markers_human_all_final, 0)
top_meso <- names(top_meso)[top_meso]
mean_top_meso <- apply(norm_human_data[top_meso, final_cluster_human_version_sub == "ExE Mesoderm_1"], 1, mean)
mean_top_meso <- sort(mean_top_meso, decreasing = T)
top_meso <- names(mean_top_meso)
names(top_meso) <- rep("ExE Mesoderm_1", length(top_meso))
```
```{r, eval = FALSE}
norm_human_data_plot <- norm_human_data[c(top_endo, top_hemo, top_meso), ]
```
```{r }
load(system.file("extdata", "norm_human_data_plot.Rda", package = "CIARA"))
load(system.file("extdata", "top_meso.Rda", package = "CIARA"))
load(system.file("extdata", "top_endo.Rda", package = "CIARA"))
load(system.file("extdata", "top_hemo.Rda", package = "CIARA"))
```
```{r}
toMatch <- c("Endoderm")
plot_balloon_marker(norm_human_data_plot[, grep(paste(toMatch, collapse="|"), final_cluster_human)], final_cluster_human_version_sub[grep(paste(toMatch, collapse="|"), final_cluster_human)], top_endo, 20, max_size=5, text_size=10)
toMatch <- c("Hemogenic Endothelial Progenitors")
plot_balloon_marker(norm_human_data_plot[, grep(paste(toMatch, collapse = "|"), final_cluster_human)], final_cluster_human_version_sub[grep(paste(toMatch, collapse = "|"), final_cluster_human)], top_hemo, 20, max_size = 5, text_size = 8)
toMatch <- c("ExE Mesoderm")
plot_balloon_marker(norm_human_data_plot[, grep(paste(toMatch, collapse = "|"), final_cluster_human)], final_cluster_human_version_sub[grep(paste(toMatch, collapse = "|"), final_cluster_human)], top_meso, length(top_meso), max_size = 5, text_size = 8)
```
Expression of some of the highly localized genes detected by CIARA that are markers of the three rare populations of cells.
```{r }
plot_gene(norm_human_data_ciara, coordinate_umap_human, "C1R", "C1R")
plot_gene(norm_human_data_ciara, coordinate_umap_human, "NANOS3", "NANOS3")
plot_gene(norm_human_data_ciara, coordinate_umap_human, "NANOG", "NANOG")
plot_gene(norm_human_data_ciara, coordinate_umap_human, "SOX17", "SOX17")
plot_gene(norm_human_data_ciara, coordinate_umap_human, "DPPA5", "DPPA5")
plot_gene(norm_human_data_ciara, coordinate_umap_human, "CSF1", "CSF1")
```
```{r}
utils::sessionInfo()
```
|
/scratch/gouwar.j/cran-all/cranData/CIARA/inst/doc/CIARA.Rmd
|
---
title: "CIARA"
output: rmarkdown::html_vignette
vignette: >
%\VignetteIndexEntry{CIARA}
%\VignetteEngine{knitr::rmarkdown}
%\VignetteEncoding{UTF-8}
% \VignetteDepends{Seurat}
---
```{r, include = FALSE}
knitr::opts_chunk$set(
collapse = TRUE,
comment = "#>",
fig.width=7,
fig.height=5
)
```
The vignette depends on Seurat package.
```{r setup}
library(CIARA)
required <- c("Seurat")
if (!all(unlist(lapply(required, function(pkg) requireNamespace(pkg, quietly = TRUE)))))
knitr::opts_chunk$set(eval = FALSE)
```
In this vignette it is shown the analysis performed on single cell RNA seq human gastrula data from [Tyser, R.C.V. et al., 2021](https://www.nature.com/articles/s41586-021-04158-y#citeas).
## Load human gastrula data and create norm counts and knn matrices using Seurat
We load the raw count matrix and umap coordinate defined in the original paper.
Raw count matrix can be downloaded [here](http://www.human-gastrula.net)
```{r }
umap_elmir <- readRDS(system.file("extdata", "annot_umap.rds", package = "CIARA"))
coordinate_umap_human <- umap_elmir[, 2:3]
```
Obtain normalized count matrix and knn matrix ( euclidean distance on highly variable genes) using Seurat.
```{r, eval = FALSE }
human_data_seurat <- cluster_analysis_integrate_rare(raw_counts_human_data, "Human_data", 0.1, 5, 30)
```
```{r, eval = FALSE }
norm_human_data <- as.matrix(Seurat::GetAssayData(human_data_seurat, slot = "data", assay = "RNA"))
knn_human_data <- as.matrix(human_data_seurat@graphs$RNA_nn)
```
Cluster annotation provided in the original paper
```{r }
original_cluster_human <- as.vector(umap_elmir$cluster_id)
names(original_cluster_human) <- names(umap_elmir$cell_name)
plot_umap(coordinate_umap_human, original_cluster_human)
```
## Run CIARA
CIARA (Cluster Independent Algorithm for the identification of RAre cell types) is a cluster independent approach that selects genes localized in a small number of neighboring cells from high dimensional PCA space.
We don't execute the CIARA algorithm and we directly load the result
```{r, eval = FALSE}
background <- get_background_full(norm_human_data, threshold = 1, n_cells_low = 3, n_cells_high = 20)
result <- CIARA(norm_human_data, knn_human_data, background, cores_number = 1, p_value = 0.001, odds_ratio = 2, local_region = 1, approximation = FALSE)
```
```{r }
load(system.file("extdata", "result.Rda", package = "CIARA"))
```
## Identifying highly localized genes
```{r }
ciara_genes <- row.names(result)[result[, 1]<1]
ciara_genes_top <- row.names(result)[order(as.numeric(result[, 1]))]
```
```{r, eval = FALSE}
norm_human_data_ciara <- norm_human_data[ciara_genes, ]
```
```{r }
load(system.file("extdata", "norm_human_data_ciara.Rda", package = "CIARA"))
```
```{r }
p <- list()
for(i in (ciara_genes_top)[1:5]) {
q <- plot_gene(norm_human_data_ciara, coordinate_umap_human, i, i)
p <- list(p, q)
}
p
```
```{r }
background <- row.names(result)
```
```{r }
plot_genes_sum(coordinate_umap_human, norm_human_data_ciara, (ciara_genes), "Sum from top CIARA genes")
```
It is also possible to explore wich genes are highly localized in which cells in an interactive way
```{r }
norm_counts_small <- apply(norm_human_data_ciara, 1, function(x) {
y <- x/sum(x)
return(y)
})
gene_sum <- apply(norm_counts_small, 1, sum)
genes_name_text <- selection_localized_genes(norm_human_data_ciara, ciara_genes, min_number_cells = 4, max_number_genes = 4)
colnames(coordinate_umap_human) <- c("UMAP_1", "UMAP_2")
if ((requireNamespace("plotly", quietly = TRUE))) {
plot_interactive(coordinate_umap_human, gene_sum, genes_name_text, min_x = NULL, max_x = NULL, min_y = NULL, max_y = NULL)
}
```
## Cluster analysis using CIARA highly localized genes
We run louvain cluster analysis implemented in Seurat using as features the highly localized genes provided by CIARA
```{r, eval = FALSE}
human_data_ciara <- cluster_analysis_integrate_rare(raw_counts_human_data, "Elmir data", 0.01, 5, 30, (ciara_genes))
```
We can explore how much the number of clusters changes with the resolution. The original cluster 1 and 2 for resolution 0.01 are constantly present for higher values of resolution.
```{r, eval = FALSE }
if ((requireNamespace("clustree", quietly = TRUE))) {
find_resolution(human_data_ciara, seq(0.01, 1, 0.1))
}
```
Cluster 2 (7 cells) is made up by primordial germ cells (PGCs). These cells expressed typical PGCs markers ad NANOS3, NANOG and DPPA5
```{r, eval = FALSE }
ciara_cluster_human <- human_data_ciara$RNA_snn_res.0.01
```
```{r }
load(system.file("extdata", "ciara_cluster_human.Rda", package = "CIARA"))
```
```{r }
plot_umap(coordinate_umap_human, ciara_cluster_human)
plot_gene(norm_human_data_ciara, coordinate_umap_human, "NANOS3", "NANOS3")
plot_gene(norm_human_data_ciara, coordinate_umap_human, "NANOG", "NANOG")
plot_gene(norm_human_data_ciara, coordinate_umap_human, "DPPA5", "DPPA5")
```
`
Merge the original cluster annotation with the one found using CIARA highly localized genes
```{r}
final_cluster_human <- merge_cluster(original_cluster_human, ciara_cluster_human, 10)
```
```{r}
final_cluster_human[final_cluster_human == "2-step_2"] <- "PGC"
```
```{r }
plot_umap(coordinate_umap_human, final_cluster_human)
```
## Sub-cluster analysis using CIARA
Detect the clusters enriched in highly localized genes and then performs on these a sub-cluster analysis (using louvain algorithm implemented in Seurat)
```{r, eval = FALSE }
result_test <- test_hvg(raw_counts_human_data, final_cluster_human, (ciara_genes), background, 100, 0.05)
```
```{r, eval = FALSE }
result_test[[2]]
```
```{r, eval = FALSE }
raw_endoderm <- raw_counts_human_data[, as.vector(umap_elmir$cluster_id) == "Endoderm"]
raw_hemo <- raw_counts_human_data[, as.vector(umap_elmir$cluster_id) == "Hemogenic Endothelial Progenitors"]
raw_exe_meso <- raw_counts_human_data[, as.vector(umap_elmir$cluster_id) == "ExE Mesoderm"]
combined_endoderm <- cluster_analysis_sub(raw_endoderm, 0.2, 5, 30, "Endoderm")
combined_hemo <- cluster_analysis_sub(raw_hemo, 0.6, 5, 30, "Hemogenic Endothelial Progenitors")
combined_exe_meso <- cluster_analysis_sub(raw_exe_meso, 0.5, 5, 30, "ExE Mesoderm")
```
```{r, eval = FALSE }
all_sub_cluster <- c(combined_endoderm$seurat_clusters, combined_hemo$seurat_clusters, combined_exe_meso$seurat_clusters)
final_cluster_human_version_sub <- merge_cluster(final_cluster_human, all_sub_cluster)
```
```{r }
load(system.file("extdata", "final_cluster_human_version_sub.Rda", package = "CIARA"))
```
```{r}
plot_umap(coordinate_umap_human, final_cluster_human_version_sub)
```
```{r}
table(as.vector(final_cluster_human_version_sub))
```
## CIARA identifies three rare population of cells with highly distinctive transcriptional profile
```{r, eval = FALSE}
Seurat::DefaultAssay(human_data_seurat) <- "RNA"
markers_human_final <- markers_cluster_seurat(human_data_seurat, final_cluster_human_version_sub, names(human_data_seurat$RNA_snn_res.0.1), 5)
markers_human_top_final <- markers_human_final[[1]]
markers_human_all_final <- markers_human_final[[3]]
```
```{r, eval = FALSE }
white_black_markers <- white_black_markers(final_cluster_human_version_sub, "Hemogenic Endothelial Progenitors_4", norm_human_data, markers_human_all_final, 0)
sum(white_black_markers)
```
```{r, eval = FALSE}
white_black_markers <- white_black_markers(final_cluster_human_version_sub, "Endoderm_2", norm_human_data, markers_human_all_final, 0)
sum(white_black_markers)
```
```{r, eval = FALSE}
white_black_markers <- white_black_markers(final_cluster_human_version_sub, "ExE Mesoderm_0", norm_human_data, markers_human_all_final, 0)
sum(white_black_markers)
```
```{r, eval = FALSE}
top_endo <- white_black_markers(final_cluster_human_version_sub, "Endoderm_2", norm_human_data, markers_human_all_final, 0)
top_endo <- names(top_endo)[top_endo]
mean_top_endo <- apply(norm_human_data[top_endo, final_cluster_human_version_sub == "Endoderm_2"], 1, mean)
mean_top_endo <- sort(mean_top_endo, decreasing = T)
top_endo <- names(mean_top_endo)
names(top_endo) <- rep("Endoderm_2", length(top_endo))
```
```{r, eval = FALSE}
top_hemo <- white_black_markers(final_cluster_human_version_sub, "Hemogenic Endothelial Progenitors_4", norm_human_data, markers_human_all_final, 0)
top_hemo <- names(top_hemo)[top_hemo]
mean_top_hemo <- apply(norm_human_data[top_hemo, final_cluster_human_version_sub == "Hemogenic Endothelial Progenitors_4"], 1, mean)
mean_top_hemo <- sort(mean_top_hemo, decreasing = T)
top_hemo <- names(mean_top_hemo)
names(top_hemo) <- rep("Hemogenic Endothelial Progenitors_4", length(top_hemo))
```
```{r, eval = FALSE}
top_meso <- white_black_markers(final_cluster_human_version_sub, "ExE Mesoderm_1", norm_human_data, markers_human_all_final, 0)
top_meso <- names(top_meso)[top_meso]
mean_top_meso <- apply(norm_human_data[top_meso, final_cluster_human_version_sub == "ExE Mesoderm_1"], 1, mean)
mean_top_meso <- sort(mean_top_meso, decreasing = T)
top_meso <- names(mean_top_meso)
names(top_meso) <- rep("ExE Mesoderm_1", length(top_meso))
```
```{r, eval = FALSE}
norm_human_data_plot <- norm_human_data[c(top_endo, top_hemo, top_meso), ]
```
```{r }
load(system.file("extdata", "norm_human_data_plot.Rda", package = "CIARA"))
load(system.file("extdata", "top_meso.Rda", package = "CIARA"))
load(system.file("extdata", "top_endo.Rda", package = "CIARA"))
load(system.file("extdata", "top_hemo.Rda", package = "CIARA"))
```
```{r}
toMatch <- c("Endoderm")
plot_balloon_marker(norm_human_data_plot[, grep(paste(toMatch, collapse="|"), final_cluster_human)], final_cluster_human_version_sub[grep(paste(toMatch, collapse="|"), final_cluster_human)], top_endo, 20, max_size=5, text_size=10)
toMatch <- c("Hemogenic Endothelial Progenitors")
plot_balloon_marker(norm_human_data_plot[, grep(paste(toMatch, collapse = "|"), final_cluster_human)], final_cluster_human_version_sub[grep(paste(toMatch, collapse = "|"), final_cluster_human)], top_hemo, 20, max_size = 5, text_size = 8)
toMatch <- c("ExE Mesoderm")
plot_balloon_marker(norm_human_data_plot[, grep(paste(toMatch, collapse = "|"), final_cluster_human)], final_cluster_human_version_sub[grep(paste(toMatch, collapse = "|"), final_cluster_human)], top_meso, length(top_meso), max_size = 5, text_size = 8)
```
Expression of some of the highly localized genes detected by CIARA that are markers of the three rare populations of cells.
```{r }
plot_gene(norm_human_data_ciara, coordinate_umap_human, "C1R", "C1R")
plot_gene(norm_human_data_ciara, coordinate_umap_human, "NANOS3", "NANOS3")
plot_gene(norm_human_data_ciara, coordinate_umap_human, "NANOG", "NANOG")
plot_gene(norm_human_data_ciara, coordinate_umap_human, "SOX17", "SOX17")
plot_gene(norm_human_data_ciara, coordinate_umap_human, "DPPA5", "DPPA5")
plot_gene(norm_human_data_ciara, coordinate_umap_human, "CSF1", "CSF1")
```
```{r}
utils::sessionInfo()
```
|
/scratch/gouwar.j/cran-all/cranData/CIARA/vignettes/CIARA.Rmd
|
#' AdjustProb
#'
#' @param v a numeric vector of probabilities of length nClust
#' @param MaxElem number of elements
#'
#' @keywords internal
#'
#' @return a numeric vector with adjusted probabilities
AdjustProb <- function(v , MaxElem)
{
# INPUT
# v (1 x nElem): vector
# MaxElem: number of elements
#
# OUTPUT
# v (1 x nElem): vector with 'sum(out)=MaxElem' and no 0-cells
nElem = length(v)
if (any(v < 1))
#add 1 to 0-cells
{
tempv = rep(0,nElem)
tempv[v < 1] = rep(1 , length(which(v < 1)))
v = v + tempv
}#### replace(v,which(v<1),1)
it <- 1
while (!(sum(v) == MaxElem) | it == 500000)
{
if(it == 499999){
stop('No suitable start clustering found, select fewer clusters or select clusters as max number of objects (i.e., length(DataList)')
}
it <- it + 1
diff = sum(v) - MaxElem
if (diff < 0)
#add elements
{
if (abs(diff) < (nElem - sum(v == 1)))
{
for (tel in 1:abs(diff))
{
tempcl = ceiling(runif(1) * nElem)
while (v[tempcl] == 1)
{
tempcl = ceiling(runif(1) * nElem)
}
v[tempcl] = v[tempcl] + 1
}
}
else
{
v[which(!(v == 1))] = v[which(!(v == 1))] + rep(1 , length(which(!(v == 1))))
}
}
else
#delete elements
{
if (abs(diff) < (nElem - sum(v == 1)))
{
for (tel in 1:abs(diff))
{
tempcl = ceiling(runif(1) * nElem)
while (v[tempcl] == 1)
{
tempcl = ceiling(runif(1) * nElem)
}
v[tempcl] = v[tempcl] - 1
}
}
else
{
v[which(!(v == 1))] = v[which(!(v == 1))] - rep(1 , length(which(!(v == 1))))
}
}
}
return(v)
}
|
/scratch/gouwar.j/cran-all/cranData/CICA/R/AdjustProb.R
|
#' CICA: Clusterwise Independent Component Analysis
#'
#'@description Main function to perform Clusterwise Independent Component Analysis
#'
#' @import ica
#' @importFrom plotly plot_ly
#' @import RNifti
#' @importFrom stats as.dist cutree hclust rect.hclust cmdscale cor runif
#' @importFrom utils setTxtProgressBar txtProgressBar combn tail
#' @importFrom mclust adjustedRandIndex
#' @importFrom methods hasArg
#
#' @param DataList a list of matrices
#' @param RanStarts number of random starts
#' @param RatStarts Generate rational starts. Eiter 'all' or a specific linkage method name (e.g., 'complete'). Use NULL to indicate that Rational starts should not be used.
#' @param pseudo percentage value for perturbating rational starts to obtain pseudo rational starts
#' @param pseudoFac factor to multiply the number of rational starts (7 in total) to obtain pseudorational starts
#' @param nComp number or vector of ICA components per cluster
#' @param nClus number or vector of clusters
#' @param userGrid user supplied data.frame for multiple model CICA. First column are the requested components. Second column are the requested clusters
#' @param scalevalue desired sum of squares of the block scaling procedure
#' @param center mean center matrices
#' @param userDef a user-defined starting seed stored in a data.frame, if NULL no userDef starting partition is used
#' @param maxiter maximum number of iterations for each start
#' @param verbose print loss information to console
#' @param ctol tolerance value for convergence criterion
#' @param checks boolean parameter that indicates whether the input checks should be run (TRUE) or not (FALSE).
#'
#' @return \code{CICA} returns an object of \code{\link{class}} "CICA". It contains the estimated clustering, cluster specific component matrices and subject specific time course matrices
#' \item{P}{partitioning vector of size \code{length(DataList)}}
#' \item{Sr}{list of size \code{nClus}, containing cluster specific independent components}
#' \item{Ais}{list of size \code{length(DataList)}, containing subject specific time courses}
#' \item{Loss}{loss function value of the best start}
#' \item{FinalLossDiff}{value of the loss difference between the last two iterations of the algorithm.}
#' \item{IndLoss}{a vector with containing the individual loss function values}
#' \item{LossStarts}{loss function values of all starts}
#' \item{Iterations}{Number of iterations}
#' \item{starts}{dataframe with the used starting partitions}
#'
#'
#'
#' @author Jeffrey Durieux
#'
#'
#' @examples
#' \dontrun{
#' CICA_data <- Sim_CICA(Nr = 15, Q = 5, R = 4, voxels = 100, timepoints = 10,
#' E = 0.4, overlap = .25, externalscore = TRUE)
#'
#' multiple_output = CICA(DataList = CICA_data$X, nComp = 2:6, nClus = 1:5,
#' userGrid = NULL, RanStarts = 30, RatStarts = NULL, pseudo = c(0.1, 0.2),
#' pseudoFac = 2, userDef = NULL, scalevalue = 1000, center = TRUE,
#' maxiter = 100, verbose = TRUE, ctol = .000001)
#'
#' summary(multiple_output$Q_5_R_4)
#'
#' plot(multiple_output$Q_5_R_4)
#' }
#'
#' @export
#'
CICA <- function(DataList, nComp, nClus, RanStarts, RatStarts=NULL, pseudo=NULL, pseudoFac, userDef = NULL, userGrid = NULL, scalevalue = 1000, center = TRUE, maxiter = 100, verbose = TRUE, ctol = .000001, checks = TRUE){
#### input arguments check ####
if(is.null(names(DataList))){
filenames <- 1:length(DataList)
}else{
filenames <- names(DataList)
}
# Feasible randomstart number check (limit is 10% of Stirling number of the 2nd kind)
if(checks==TRUE){
if(RanStarts > 1){
m <- 0
minClus <- min(nClus)
if(minClus == 1){
minClus <- 2
}
for (j in 0:minClus){
m <- m + (-1)^(minClus - j) * choose(minClus, j) * j^length(DataList)
}
stirNum <- m/factorial(minClus)
if(RanStarts >= stirNum*.1){
stop('Too many RanStarts requested, lower the number of RanStarts')
}
}
# if(exists("pseudoFac")){
# if(!is.null(pseudoFac)){
# if(length(pseudoFac)>1){
# stop("pseudoFac must be a unique value, not a vector")
# }
# }
# }
if(!is.null(RatStarts)){
if(length(RatStarts)>1){
stop("Provide a unique method or use 'all' if you want to use all the available methods")
}
METHODS <- c("ward.D", "single", "complete", "average", "mcquitty",
"median", "centroid", "ward.D2", 'all')
i.meth <- pmatch(RatStarts, METHODS)
if(is.na(i.meth)){
stop('Invalid RatStarts argument')
}
}
if(is.null(userGrid)){
if(hasArg(nComp) == FALSE){
stop('nComp or userGrid not provided')
}
if(hasArg(nClus) == FALSE){
stop('nClus or userGrid not provided')
}
}
if (is.list(DataList) == FALSE){
stop('Provided DataList is not a list object')
}
if(!is.null(pseudo)){
if(any(pseudo==0)){#Pseudo==0 does not make sense. Transform it to 0
pseudo<-NULL
warning("0 is not a possible value for pseudo. Pseudo-rational starts are not computed.")
}
if(all(pseudo > 0 & pseudo <=1) == FALSE){
stop('pseudo should be a value between 0 and 1')
}
}
if(!is.null(userDef) && length(nClus)!=1){
stop("User-defined partitions are only allowed when a unique value for the number of clusters is provided")
}
#if( all(sapply(DataList, class)[1,] == 'matrix') == FALSE){
# stop('Please check input DataList, elements are not matrices')
#}
# check if dimensions are equal
if (all( rowSums(sapply(DataList,dim)) == dim(DataList[[1]]) * length(DataList) ) == FALSE ){
stop('Please check input DataList, dimensions are not equal over all matrices')
}
if(!is.null(userDef)){
userDef<-as.matrix(userDef, nrow = NROW(DataList))
for (i in 1:NCOL(userDef)) {
udCluters<-length(unique(userDef[,i]))
if(udCluters!=nClus){
stop(paste0("The number of clusters provided in the user defined partition ", i," is not equal to the number of clusters requested"))
}
}
}
#if( nComp > ncol(DataList[[1]]) ){
# stop('Number of components to extract is larger than the number of variables in each data matrix')
#}
}#end checking input arguments
#### Preprocessing ####
if(center == TRUE){
DataList <- lapply(seq_along(DataList), function(i){
sweep(DataList[[i]], 1, rowMeans( DataList[[i]] ) )
})
}
# scale datamatrices such that they have an equal sum of squares
if(!is.null(scalevalue)){
DataList <- lapply(DataList, FUN = xscale, value = scalevalue)
}
nBlocks <- length(DataList)
##### multiple models part ########
if(!is.null(userGrid) ){
if(!is.data.frame(userGrid)){
stop('Provided userGrid is not a data.frame object')
}
if(ncol(userGrid) != 2){
stop('Structure of provided userGrid is not correct')
}
colnames(userGrid) <- c('nComp', 'nClus')
grid <- userGrid
}else if((length(nComp) != 1 | length(nClus) != 1) & is.null(userGrid) ){
grid <- expand.grid(nComp=nComp, nClus=nClus)
}else{
grid <- data.frame(nComp,nClus)
}
# total loss
Losstotal <- sum( sapply( seq_along(DataList),
function(i) sum( DataList[[i]]^2)) ) + 1
multioutput <- list()
for(ng in 1:nrow(grid)){
LossStarts <- numeric()
FinalLossDiff <- numeric()
TempOutput <- list()
if(grid$nClus[ng]==1){
nS <- 1
startvecs <- matrix(rep(1,length(DataList)))
}else{
startvecs <- NULL
##### define userDef, rational and random starts ####
if(!is.null(userDef)){
startvecs <- userDef
colnames(startvecs)<-paste0("UserDefined",1:NCOL(userDef))
}
if(RanStarts != 0){
randomstarts <- GenRanStarts(RanStarts = RanStarts,
nClus = grid$nClus[ng],
nBlocks = length(DataList),
ARIlim = .2, itmax = 1000,
verbose = verbose)
if(is.null(startvecs)){
startvecs <- randomstarts$rs
}else{
startvecs <- cbind(startvecs, randomstarts$rs)
}
}
if(!is.null(RatStarts)){
rationalstarts <- GenRatStarts(DataList = DataList,RatStarts = RatStarts, nComp = grid$nComp[ng],
nClus = grid$nClus[ng],
scalevalue = scalevalue,
center = center,verbose = verbose,
pseudo = pseudo , pseudoFac = pseudoFac)
if(is.null(startvecs)){
startvecs <- rationalstarts$rat$rationalstarts
}else{
startvecs <- cbind(startvecs, rationalstarts$rat$rationalstarts)
}
}
nS <- ncol(startvecs)
}
for(st in 1:nS){
if(verbose == TRUE){
cat('Computing Q ', grid$nComp[ng], ' and R ', grid$nClus[ng], fill = TRUE)
cat('Start number: ',st, '\n')
}
iter <- 1
#### step 1 initialize P ####
newclus <- startvecs[ ,st]
# if(!is.null(userDef)){
#
# if(class(userDef) == 'rstarts'){
#
# if(st <= dim(userDef$rationalstarts)[2]){
# if(verbose == TRUE){
# cat('Type of start: userDef \n')
# }
# newclus <- userDef$rationalstarts[,st]
# }else{
# if(verbose == TRUE){
# cat('Type of start: Random \n')
# }
# newclus <- clusf(nBlocks, grid$nClus[ng])
# }
# }else{
# if(st == 1){
# if(verbose == TRUE){
# cat('Type of start: Rational \n')
# }
# newclus <- userDef
# }else{
# if(verbose == TRUE){
# cat('Type of start: Random \n')
# }
# newclus <- clusf(nBlocks, grid$nClus[ng])
# }
# }
# }else{
# if(verbose == TRUE){
# cat('Type of start: Random \n')
# }
# newclus <- clusf(nBlocks, grid$nClus[ng])
# }
repeat{
# and concatenate datablocks according to clustering
SortedDataList <- ConcData(DataList = DataList, ClusVec = newclus)
#### Step 2 extract group ICA parameters (only Sr is necessary ####
ICAparams <- ExtractICA(DataList = SortedDataList, nComp = grid$nComp[ng])
#### Step 3 update P ####
UpdatedPInfo <- Reclus(DataList = DataList, SrList = ICAparams$Sr)
# check empty clusters
newclus <- SearchEmptyClusters(nClus = grid$nClus[ng],
newcluster = UpdatedPInfo$newclus,
SSminVec = UpdatedPInfo$SSminVec)
# UpdatedPInfo$Loss <- sum(sapply(seq_along(UpdatedPInfo$SSList), function(i) UpdatedPInfo$SSList[[i]][newclus[i]]))
if(length(unique(newclus)) != grid$nClus[ng] & verbose == TRUE){
cat('empty cluster, checkempties\n')
}
# add new loss to lossvector
if(iter == 1){
Loss <- c(Losstotal, UpdatedPInfo$Loss)
}else{
Loss <- c(Loss, UpdatedPInfo$Loss)
}
if(verbose == TRUE){
cat(Loss[-1],'\n')
}
#### step 4 convergence ####
iter <- iter + 1
if( Loss[iter-1] - Loss[iter] < ctol | iter == maxiter ){
if(verbose == TRUE){
if(iter == maxiter){
cat('Maximum number of iterations reached \n')
cat('\n')
if( Loss[iter-1] - Loss[iter] >= ctol ){
cat('Convergence not reached \n')
cat('\n')
}
}else{
cat('Convergence \n')
cat('\n')
}
}
break()
}
}# end repeat
LossStarts[st] <- Loss[iter]
FinalLossDiff[st] <- Loss[iter-1] - Loss[iter]
# procedure to only save current best start on first position of TempOutput
if(st == 1){
TempOutput$`1`$P <- newclus
TempOutput$`1`$Sr <- ICAparams$Sr
TempOutput$`1`$Loss <- tail(LossStarts, n = 1)
TempOutput$`1`$FinalLossDiff <- tail(FinalLossDiff, n = 1)
TempOutput$`1`$iterations <- iter - 1
TempOutput$`1`$SSmin <- UpdatedPInfo$SSminVec
}else if(st >= 2){
TempOutput$`2`$P <- newclus
TempOutput$`2`$Sr <- ICAparams$Sr
TempOutput$`2`$Loss <- tail(LossStarts, n = 1)
TempOutput$`2`$FinalLossDiff <- tail(FinalLossDiff, n = 1)
TempOutput$`2`$iterations <- iter - 1
TempOutput$`2`$SSmin <- UpdatedPInfo$SSminVec
if(TempOutput$`2`$Loss <= TempOutput$`1`$Loss){
TempOutput$`1`$P <- TempOutput$`2`$P
TempOutput$`1`$Sr <- TempOutput$`2`$Sr
TempOutput$`1`$Loss <- TempOutput$`2`$Loss
TempOutput$`1`$FinalLossDiff <-TempOutput$`2`$FinalLossDiff
TempOutput$`1`$iterations <- iter - 1
TempOutput$`1`$SSmin <- TempOutput$`2`$SSmin
}
}
}# end for nstarts
#### output ####
P <- TempOutput$`1`$P
Sr <- TempOutput$`1`$Sr
Ais <- lapply( seq_along(DataList), function(anom){
crossprod(DataList[[anom]], Sr[[ P[anom] ]]) %*% mpinv( t(Sr[[ P[anom] ]]) %*% Sr[[ P[anom] ]])
})
# if(is.null(names(DataList))){
# names(P) <- 1:length(DataList)
# }else{
# cat('test')
# names(P) <- names(DataList)
# }
names(P) <- filenames
output <- list()
output$P <- P
output$Sr <- Sr
output$Ais <- Ais
output$Loss <- TempOutput$`1`$Loss
output$FinalLossDiff <- TempOutput$`1`$FinalLossDiff
output$IndLoss <- TempOutput$`1`$SSmin
output$LossStarts <- LossStarts
output$iterations <- TempOutput$`1`$iterations
output$starts <- startvecs
class(output) <- 'CICA'
multioutput[[ng]] <- output
}# end for ng - grid
gridnames <- paste('Q_', grid$nComp,'_R_', grid$nClus, sep = '')
names(multioutput) <- gridnames
if(length(multioutput) > 1){
class(multioutput) <- 'MultipleCICA'
}else{
multioutput <- multioutput[[1]]
}
return(multioutput)
}
|
/scratch/gouwar.j/cran-all/cranData/CICA/R/CICA.R
|
#' Concatenate datablocks into list determined by cluster labels
#'@description Internal function for CICA package
#' @param DataList list with datablocks
#' @param ClusVec vector with cluster labels
#'
#' @return list with concatenated datablocks
#'
#' @keywords internal
#'
#'
#' @author Jeffrey Durieux
#'
ConcData <- function(DataList, ClusVec){
ClusL <- length( unique(ClusVec) )
NewList <- list()
for(i in 1:ClusL){
NewList[[i]] <- do.call(cbind, DataList[ClusVec == i])
}
return(NewList)
} # end f_ConcData
|
/scratch/gouwar.j/cran-all/cranData/CICA/R/ConcData.R
|
#' Extract Group ICA parameters
#'@description Internal function for CICA package
#' @param DataList a list object to perform Group ICAs on
#' @param nComp number of ICA components to extract
#' @param svd
#'
#'
#' @keywords internal
#' @return a list with cluster specific independent components
ExtractICA <- function(DataList, nComp, svd = FALSE){
#DataList <- lapply(DataList, FUN = scale, center = T, scale = T)
if(svd == FALSE){
icaListCluster <- lapply(DataList, icafast, nc = nComp)
ICA_S <- lapply(icaListCluster, function(anom) anom$S)
ListRes <- list("Sr" = ICA_S)
}else{
icaListCluster <- lapply(DataList, svd)
ICA_S <- lapply(icaListCluster, function(anom) anom$u[,1:nComp] %*% diag(anom$d[1:nComp]))
ListRes <- list("Sr" = ICA_S)
}
return(ListRes)
}
|
/scratch/gouwar.j/cran-all/cranData/CICA/R/ExtractICA.R
|
#'
#' @param DataList a list of matrices
#' @param RatStarts type of rational start. 'all' computes all types of hclust methods
#' @param nComp number of ICA components to extract
#' @param nClus number of clusters
#' @param scalevalue scale each matrix to have an equal sum of squares
#' @param center mean center matrices
#' @param pseudo percentage value for perturbating rational starts to obtain pseudo rational starts
#' @param pseudoFac how many pseudo starts per rational start
#' @param verbose print output to console
#'
#' @return dataframe with (pseudo-) rational and dist object based on the pairwise modified RV values
#'
#'
#' @examples
#' \dontrun{
#' CICA_data <- Sim_CICA(Nr = 15, Q = 5, R = 4, voxels = 100, timepoints = 10,
#' E = 0.4, overlap = .25, externalscore = TRUE)
#' rats <- FindRationalStarts(DataList = CICA_data$X, nComp = 5, nClus = 4,verbose = TRUE, pseudo = .2)
#' plot(rats, type = 1, method = 'ward.D2')
#' plot(rats, type = 2, method = 'ward.D2')
#' plot(rats, type = 2, method = 'ward.D2', mdsdim = 3)
#' }
#'
#'
#' @export
#' @references Durieux, J., & Wilderjans, T. F. (2019). Partitioning subjects based on high-dimensional fMRI data: comparison of several clustering methods and studying the influence of ICA data reduction in big data. Behaviormetrika, 46(2), 271-311.
#'
FindRationalStarts <- function(DataList, RatStarts = 'all', nComp, nClus, scalevalue = NULL,
center = TRUE, verbose = TRUE, pseudo = NULL, pseudoFac=NULL){
METHODS <- c("ward.D", "single", "complete", "average", "mcquitty",
"median", "centroid", "ward.D2", 'all')
i.meth <- pmatch(RatStarts, METHODS)
if(any(is.na(i.meth))){
stop('Invalid RatStart argument')
}
ICAs <- CICA(DataList = DataList, RanStarts = 1, nComp = nComp,
nClus = length(DataList), scalevalue = scalevalue, center = center, verbose = F)
d <- computeRVmat(DataList = ICAs$Sr, dist = TRUE, verbose = verbose)
if(any(i.meth == 9)){
hcl0 <- hclust(d = d, method = 'ward.D')
hcl1 <- hclust(d = d, method = 'ward.D2')
hcl2 <- hclust(d = d, method = 'complete')
hcl3 <- hclust(d = d, method = 'single')
hcl4 <- hclust(d = d, method = 'average')
hcl5 <- hclust(d = d, method = 'mcquitty')
hcl6 <- hclust(d = d, method = 'median')
hcl7 <- hclust(d = d, method = 'centroid')
p_ward <- cutree(hcl0, k = nClus)
p_ward2 <- cutree(hcl1, k = nClus)
p_comp <- cutree(hcl2, k = nClus)
p_single <- cutree(hcl3, k = nClus)
p_average <- cutree(hcl4, k = nClus)
p_mcquitty <- cutree(hcl5, k = nClus)
p_median <- cutree(hcl6, k = nClus)
p_centroid <- cutree(hcl7, k = nClus)
ps <- data.frame(p_ward, p_ward2, p_comp, p_single, p_average, p_mcquitty,
p_median, p_centroid)
}else{
ps <- matrix(data = NA, nrow = length(DataList), ncol = length(i.meth))
for(i in 1:length(i.meth)){
hcl <- hclust(d = d, method = METHODS[i.meth[i]])
ps[,i] <- cutree(hcl, k = nClus)
}
ps <- data.frame(ps)
colnames(ps) <- METHODS[i.meth]
}
if(!is.null(pseudo)){
if(all(pseudo >= 0 & pseudo <=1) == FALSE){
stop('pseudo should be a value between 0 and 1')
}
if(pseudoFac < 1){
stop('pseudoFac should be an integer larger or equal than 1')
}
#### add loop here to go over pseudo if it is a vector, see issue #4 github
Ppseudo_i <- list()
for(i in 1:pseudoFac){
Ppseudo_j <- list()
for(j in 1:length(pseudo)){
perbs <- matrix(data = NA, nrow = nrow(ps), ncol = ncol(ps))
for(k in 1:ncol(ps)){
perbs[,k] <- perturbation(ps[ ,k], percentage = pseudo[j])
}
colnames(perbs) <- paste(names(ps),'Pseudo',
rep(pseudo[j], times = ncol(ps)), 'Fac',i, sep = '')
Ppseudo_j[[j]] <- data.frame(perbs)
}
Ppseudo_i[[i]] <- data.frame(Ppseudo_j)
}
Ppseudo <- data.frame(Ppseudo_i)
ps <- cbind(ps, Ppseudo)
}
# check if no empty clusters are present
temp <- ps
for(i in 1:ncol(temp)){
temp[,i] <- SearchEmptyClusters(nClus, newcluster = ps[, i])
}
ps <- temp
out <- list()
out$rationalstarts <- ps
out$RVdist <- d
class(out) <- 'rstarts'
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/CICA/R/FindRationalStarts.R
|
#' Generate random starts
#'
#' @param RanStarts number of randomstarts to generate
#' @param nClus number of clusters
#' @param nBlocks number of objects
#' @param ARIlim maximal value of adjusted Rand Index
#' @param itmax maximum number of iterations used to find suitable random starts
#' @param verbose boolean that indicates whether the output should be printed on the console
#'
#' @return a list where the first element is a matrix with random starts, second element all pairwise ARIs
#' #'
GenRanStarts <- function(RanStarts, nClus, nBlocks, ARIlim = 0.2,
itmax = 1000, verbose = FALSE){
# random starts
rs <- matrix(clusf(nBlocks = nBlocks, nClus = nClus) )
it <- 0
while(ncol(rs) != RanStarts & it < itmax){
it <- it + 1
candidate <- clusf(nBlocks = nBlocks, nClus = nClus)
if(all(abs(apply(rs, MARGIN = 2, adjustedRandIndex, y = candidate)) < ARIlim)){
rs <- cbind(rs, candidate)
colnames(rs) <- rep('RandomStart', times = ncol(rs))
}
if(verbose){
cat(ncol(rs), fill = TRUE)
}
}
if(it == itmax){
warning(paste('Not enough random starts found with ARIlimRan of:',ARIlim))
}
# comb <- t(utils::combn(1:ncol(rs), 2))
#
# rsARI <- matrix(data = NA, nrow = ncol(rs) , ncol = ncol(rs))
# rsi <- numeric()
#
# for(i in 1:nrow(comb)){
# idx <- comb[i,]
# rsi<- adjustedRandIndex( rs[,idx[1]], rs[,idx[2]] )
# res <- c(comb[i , ] , rsi)
# rsARI[res[1] , res[2] ] <- res[3]
# }
#
# rsARI[lower.tri(rsARI)] = t(rsARI)[lower.tri(rsARI)]
out <- list()
out$rs <- rs
# out$ARIs <- rsARI
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/CICA/R/GenRanStarts.R
|
#' Title
#'
#' @param DataList DataList
#' @param RatStarts Type of rational start
#' @param nComp number of components
#' @param nClus number of clusters
#' @param scalevalue value for blockscaling procedure
#' @param center center
#' @param verbose verbose
#' @param pseudo percentage used for perturbation rational starts (between 0)
#' @param pseudoFac multiplication factor for pseudo rational starts
#'
#' @return out
#'
GenRatStarts <- function(DataList, RatStarts, nComp, nClus, scalevalue, center, verbose, pseudo, pseudoFac){
rat <- FindRationalStarts(DataList = DataList, RatStarts = RatStarts, nComp = nComp, nClus = nClus,
scalevalue = scalevalue, center = center, verbose = verbose,
pseudo = pseudo, pseudoFac = pseudoFac)
if(NCOL(rat$rationalstarts)>1){
comb <- t(combn(1:NCOL(rat$rationalstarts), 2))
}else{
out <- list()
out$rat <- rat
out$ARIs <- matrix(NA,1,1)
return(out)
}
rsARI <- matrix(data = NA, nrow = NCOL(rat$rationalstarts) , ncol = NCOL(rat$rationalstarts))
rsi <- numeric()
for(i in 1:nrow(comb)){
idx <- comb[i,]
rsi<- adjustedRandIndex( rat$rationalstarts[,idx[1]], rat$rationalstarts[,idx[2]] )
res <- c(comb[i , ] , rsi)
rsARI[res[1] , res[2] ] <- res[3]
}
rsARI
idxdublicate <- which(rsARI == 1, arr.ind = TRUE)
if(nrow(idxdublicate != 0)){
for(i in 1:nrow(idxdublicate)){
rat$rationalstarts[,idxdublicate[i,2]] <- clusf(nBlocks = length(DataList), nClus = nClus)
colnames(rat$rationalstarts)[idxdublicate[i,2]] <- 'ReplacedRandom'
}
}
#rsARI[lower.tri(rsARI)] = t(rsARI)[lower.tri(rsARI)]
out <- list()
out$rat <- rat
out$ARIs <- rsARI
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/CICA/R/GenRatStarts.R
|
#' Generate random clustering
#' @description Internal function for CICA package
#' @param nElement a positive integer number of elements to be clusterd
#' @param nClust a positive integer: Number of clusters
#' @param Prob numeric vector: Portion of elements in each cluster
#'
#'
#'@keywords internal
#'
#' @return a numeric vector indicating the clustering
GenerateRandomClustering <- function(nElement , nClust , Prob = NULL)
{
####GenerateRandomClustering = for Random Starts
# Author: Tom F. Wilderjans
# nElement: number of elements to be clustered
# nClust: number of clusters
# Prob (1 x nClust): proportion of elements in each cluster
# Added by Jeffrey Durieux: default Prob = equal cluster prob
# This done to adjust code later on for potential cluster perbutation
if(is.null(Prob))
{
Prob <- rep(x = (1/nClust) , nClust)
}
BestClust = NULL
ErrorEncountered = F
if (!(length(Prob) == nClust))
{
ErrorEncountered = T
}
if ((abs(sum(Prob) - 1) > .000000001) | (any(Prob < 0)))
{
ErrorEncountered = T
}
if (!(any(nClust == 1:nElement)))
{
ErrorEncountered = T
}
if (!(ErrorEncountered))
{
if (nElement > nClust)
{
if (nClust == 1)
{
BestClust = rep(1 , times = nElement)
}
else
{
ProbVV = round(Prob * nElement)
if (!(sum(ProbVV) == nElement) |
(any(ProbVV < 1)))
#not enough elements, or empty clusters
{
ProbVV = AdjustProb(ProbVV , nElement)
}
tempclus = rep(1:length(ProbVV) , ProbVV)
BestClust = tempclus[sample(1:nElement,size = nElement,replace =
FALSE)]
}
}
else
{
BestClust = 1:nClust
}
}
if (!(length(unique(BestClust)) == nClust))
{
BestClust = NULL
}
return(BestClust)
}
|
/scratch/gouwar.j/cran-all/cranData/CICA/R/GenerateRandomClustering.R
|
# Wed Mar 23 10:39:01 2022
# Author: Jeffrey Durieux, MSc
# What: function to generate a matrix of starts
#nClus = 4; nBlocks = 20;RanStarts = 100; RatStarts = 2;ARIlimRan = 0.2
#DataList=CICA_data$X; scale=T; center=T; pseudo=.2;nComp=5;verbose = T;pseudoFac=5
# GenRanStarts <- function(RanStarts, nClus, nBlocks, ARIlimRan = 0.2,
# itmax = 1000, verbose = FALSE){
# # random starts
# rs <- matrix(CICA:::clusf(nBlocks = nBlocks, nClus = nClus) )
#
# it <- 0
# while(ncol(rs) != RanStarts & it < itmax){
# it <- it + 1
# candidate <- CICA:::clusf(nBlocks = nBlocks, nClus = nClus)
# if(all(abs(apply(rs, MARGIN = 2, adjustedRandIndex, y = candidate)) < ARIlim)){
# rs <- cbind(rs, candidate)
# }
# if(verbose){
# cat(ncol(rs), fill = TRUE)
# }
#
# }
#
# if(it == itmax){
# warning(paste('Not enough random starts found with ARIlimRan of:',ARIlimRan))
# }
#
# # heatmap/image plot option
# comb <- t(utils::combn(1:ncol(rs), 2))
#
# rsARI <- matrix(data = NA, nrow = ncol(rs) , ncol = ncol(rs))
# rsi <- numeric()
#
# for(i in 1:nrow(comb)){
# idx <- comb[i,]
# rsi<- adjustedRandIndex( rs[,idx[1]], rs[,idx[2]] )
# res <- c(comb[i , ] , rsi)
# rsARI[res[1] , res[2] ] <- res[3]
# }
#
# rsARI[lower.tri(rsARI)] = t(rsARI)[lower.tri(rsARI)]
#
# out <- list()
# out$rs <- rs
# out$ARIs <- rsARI
# return(out)
# }
# random <- GenStarts(20, 2, 20)
# m <- random$ARIs
# diag(m) <- 1
# fields::image.plot(m)
# GenRatStarts <- function(DataList, nComp, nClus, scale, center, verbose, pseudo,pseudoFac){
#
#
# rat <- FindRationalStarts(DataList = DataList, nComp = nComp, nClus = nClus,
# scale = scale, center = center, verbose = verbose,
# pseudo = pseudo, pseudoFac = 5)
#
# comb <- t(utils::combn(1:ncol(rat$rationalstarts), 2))
#
# rsARI <- matrix(data = NA, nrow = ncol(rat$rationalstarts) , ncol = ncol(rat$rationalstarts))
# rsi <- numeric()
#
# for(i in 1:nrow(comb)){
# idx <- comb[i,]
# rsi<- adjustedRandIndex( rat$rationalstarts[,idx[1]], rat$rationalstarts[,idx[2]] )
# res <- c(comb[i , ] , rsi)
# rsARI[res[1] , res[2] ] <- res[3]
# }
#
# rsARI[lower.tri(rsARI)] = t(rsARI)[lower.tri(rsARI)]
#
# out <- list()
# out$rat <- rat
# out$ARIs <- rsARI
# return(out)
# }
# res <- GenRatStarts(DataList = CICA_data$X, nComp = 5, nClus = 4, scale = T,
# center = T, verbose = T, pseudo = .05, pseudoFac = 5)
# m <- res$ARIs[-c(1:7),-c(1:7)]
# diag(m) <- 1
# m <- res$ARIs
# diag(m) <- 1
# fields::image.plot(m)
|
/scratch/gouwar.j/cran-all/cranData/CICA/R/GenerateStarts.R
|
# library(clue)
#
# x <- matrix(c(5, 1, 4, 3, 5, 2, 2, 4, 4), nrow = 3)
# x
# solve_LSAP(x)
# solve_LSAP(x, maximum = TRUE)
# ## To get the optimal value (for now):
# y <- solve_LSAP(x)
# sum(x[cbind(seq_along(y), y)])
#
# library(ica)
#
# set.seed(123)
# nobs <- 1000
# Smat <- cbind(icasamp("b","rnd",nobs),icasamp("b","rnd",nobs), icasamp('b','rnd',nobs),
# icasamp("b","rnd",nobs),icasamp("b","rnd",nobs), icasamp('b','rnd',nobs))
# Amat <- matrix(2*runif(6*6),6,6)
# Xmat <- tcrossprod(Smat,Amat)
# Xmat <- aE(Xmat,error = .8)
# # ICA via FastICA with 9 components
# imod <- icafast(Xmat,6)
# Sest <- imod$S
# r <- abs(multiway::congru(Smat,Sest))
# r
# y <- solve_LSAP(r, maximum = TRUE)
# y
#
# diag(cor(Smat,Sest[,y]))
#
# library(microbenchmark)
#
# microbenchmark(solve_LSAP(r, maximum = TRUE), CICA:::modRV(Smat,Sest), times = 20 , unit = 'relative')
|
/scratch/gouwar.j/cran-all/cranData/CICA/R/LSAP_Tucker.R
|
#' Compute loss per data matrix using multivariate regression
#'@description Internal function for CICA package
#' @param Xi datablock
#' @param SkL list with Group ICA parameters
#'
#' @keywords internal
#' @return a numeric vector with loss function values
Lir <- function(Xi, SkL)
{
# compute Ahats
Ah <- lapply(seq_along( SkL), function(i) {
crossprod(Xi, SkL[[i]]) %*% mpinv( t(SkL[[i]]) %*% SkL[[i]])
})
# compute Xhats --> Xhat^r
Xhat <- lapply(seq_along(Ah), function(i) {
tcrossprod( SkL[[i]], Ah[[i]])
})
# loss per data matrix
SS <- sapply(seq_along(Xhat), function(i) {
sum((Xi - Xhat[[i]]) ^ 2)
})
return(SS)
}#function
|
/scratch/gouwar.j/cran-all/cranData/CICA/R/Lir.R
|
#' Sequential Model Selection for Multiple CICA model
#'
#' @param x an object of class MultipleCICA
#'
#' @return a list object
#'
#' @examples
#' \dontrun{
#' CICA_data <- Sim_CICA(Nr = 15, Q = 5, R = 4, voxels = 100, timepoints = 10,
#' E = 0.4, overlap = .25, externalscore = TRUE)
#'
#' multiple_output = CICA(DataList = CICA_data$X, nComp = 2:6, nClus = 1:5,
#' userGrid = NULL, RanStarts = 30, RatStarts = NULL, pseudo = c(0.1, 0.2),
#' pseudoFac = 2, userDef = NULL, scalevalue = 1000, center = TRUE,
#' maxiter = 100, verbose = TRUE, ctol = .000001)
#'
#' ModSelOutput <- SequentialScree(multiple_output)
#'
#' plot(ModSelOutput)
#' }
#'
#' @importFrom methods is
#'
#' @export
#'
SequentialScree <- function(x){
if(xor(is(x,'MultipleCICA'), !is.data.frame(x))){
stop('Input object should be of class MultipleCICA')
}
if(is(x, 'MultipleCICA')){
models <- names(x)
split <- strsplit(models, split = '_')
Q <- as.numeric(sapply(seq_along(split), function(anom) split[[anom]][2]))
R <- as.numeric(sapply(seq_along(split), function(anom) split[[anom]][4]))
Loss <- sapply(seq_along(x), function(anom) x[[anom]]$Loss)
df <- data.frame(Q = Q, R = R, Loss = Loss)
}else{
df <- x
nam <- colnames(df)
if(nam[1] != "Q" & nam[2] != "R"){
stop('Supplied data.frame with complexities and loss function values are not named correctly.
Columnames for components and clusters should be named "Q" and "R" respectively')
}
}
SR_rq <- function(Lq){
Screes <- numeric()
for(i in 1:length(Lq)){
if(i == 1){
Screes[i] <- NA
}
else if(i == length(Lq) ){
Screes[i] <- NA
}else{
Screes[i] <- (Lq[i-1] - Lq[i]) / (Lq[i] - Lq[i+1])
}
}
return(Screes)
}
SR_qR <- function(LqR){
Screes <- numeric()
for(i in 1:length(LqR)){
if(i == 1){
Screes[i] <- NA
}
else if(i == length(LqR) ){
Screes[i] <- NA
}else{
Screes[i] <- (LqR[i-1] - LqR[i]) / (LqR[i] - LqR[i+1])
}
}
return(Screes)
}
# both Q and R
Qu <- unique(df$Q)
Ru <- unique(df$R)
if(length(Qu) > 3 & length(Ru) >3){
Screes <- SR_rq( df[df$Q==Qu[1], ]$Loss )
for(i in 2:length(Qu)){
Screes <- rbind(Screes, SR_rq(df[df$Q==Qu[i], ]$Loss ))
}
ColMeanScrees <- colMeans(Screes, na.rm = TRUE)
Rid <- which.max(ColMeanScrees)
Rselect <- Ru[Rid]
ScreeConditionalonR <- SR_qR(df[df$R==Rselect,]$Loss)
Qid <- which.max(ScreeConditionalonR)
Qselect <- Qu[Qid]
}else if(length(Qu) > 3){ # only Q
Screes <- numeric()
Lq <- df$Loss
for(i in 1:length(Lq)){
if(i == 1){
Screes[i] <- NA
}
else if(i == length(Lq) ){
Screes[i] <- NA
}else{
Screes[i] <- (Lq[i-1] - Lq[i]) / (Lq[i] - Lq[i+1])
}
}
Qselect <- df$Q[which.max(Screes)]
Rselect <- NULL
}else if(length(Ru) > 3){
Screes <- numeric()
Lq <- df$Loss
for(i in 1:length(Lq)){
if(i == 1){
Screes[i] <- NA
}
else if(i == length(Lq) ){
Screes[i] <- NA
}else{
Screes[i] <- (Lq[i-1] - Lq[i]) / (Lq[i] - Lq[i+1])
}
}
Rselect <- df$R[which.max(Screes)]
Qselect <- NULL
}else{
stop('Not enough datapoints to compute scree test values, consider taking a larger number of components and/or clusters')
}
out <- list()
out$optimalQ <- Qselect
out$optimalR <- Rselect
out$df <- df
out$Screes_step1 <- Screes
out$ColMeanScrees <- ColMeanScrees
out$ScreeConditionalonR <- ScreeConditionalonR
class(out) <- 'ModSel'
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/CICA/R/ModelSelection.R
|
#' Recluster based on cluster specific components
#'@description Internal function for CICA package
#' @param DataList list with data matrices
#' @param SrList list with Group ICA RSN parameters
#'
#'
#' @keywords internal
#' @return \item{newclus}{a list object with an updated partitioning}
#' \item{SSminVec}{a numeric vector with the lowest loss function values per data block}
#' \item{Loss}{a numeric indicating the new loss function value}
Reclus <- function(DataList, SrList) {
SSList <- lapply(DataList, FUN = Lir, SkL = SrList)
SSminIndexVec <- sapply(SSList, FUN = which.min)
SSminVec <- sapply(SSList, FUN = min)
Loss <- sum(SSminVec)
ResList <- list("newclus" = SSminIndexVec,'SSminVec' = SSminVec,
"Loss" = Loss, "SSList" = SSList)
return(ResList)
}
|
/scratch/gouwar.j/cran-all/cranData/CICA/R/Reclus.R
|
#' Search for empty clusters
#'@description Internal function for CICA package
#' @param nClus number of clusters
#' @param newcluster newly updated clustering vector P
#' @param SSminVec loss function values per data block
#'
#' @keywords internal
#' @return a numeric vector indicating the new partitioning vector without empty clusters
SearchEmptyClusters <- function(nClus, newcluster, SSminVec = NULL) {
if(is.null(SSminVec)){
SSminVec <- rep(100, length(newcluster))
}
OriCluster <- 1:nClus
test <- sapply(OriCluster, FUN = '%in%', newcluster)
#test result = no empty clusters so return original newcluster
if ( all( test == TRUE) ){
newcluster <- newcluster
}else{
# check singletons, these are not candidates to choose from
EmptyClusters <- which(test == FALSE)
singletonnames <- names(which( (table(newcluster) == 1) == TRUE))
singletons <- as.numeric(singletonnames)
id <- which(newcluster %in% singletons == T)
SSminVec[id] <- 0
worst <- sort( SSminVec, decreasing = TRUE)
#remove worst of singletons, otherwise empties will occur
Index <- sapply( seq_along(EmptyClusters),
function(i) FUN = which( SSminVec == worst[i] ) )
# if ties occur in SSminVec, pick one at random
if( is.null(ncol(Index)) == FALSE ){
Index <- Index[,1]
Index <- sample(Index, size = length(EmptyClusters))
}
for(i in 1:length(Index)){
newcluster <- replace(newcluster, Index[i], EmptyClusters[i])
}
}# else some emptyclusters
if( length(unique(newcluster)) != nClus ){
stop('In function SearchEmptyCluster, empty/ies occurred')
}
# check min number of clusters
# if(!is.null(minclus)){
# test2 <- table(newcluster) < minclus
#
# if ( all( test2 == TRUE) ){
# newcluster <- newcluster
# }else{
# SparseClusters <- which(test2 == TRUE)
#
# worst <- sort( SSminVec, decreasing = TRUE)
#
# Index <- sapply( seq_along(1:minclus),
# function(i) FUN = which( SSminVec == worst[i] ) )
# newcluster[Index] <- SparseClusters
# }
# }
return(newcluster)
}
|
/scratch/gouwar.j/cran-all/cranData/CICA/R/SearchEmptyClusters.R
|
#' Simulate CICA data
#'
#' @param Nr number of subjects per cluster
#' @param Q number of components
#' @param R number of clusters
#' @param voxels number of voxels
#' @param timepoints number of time points
#' @param E proportion of independent gaussian noise
#' @param overlap amount of overlap between S across clusters. Smaller value means more overlap
#' @param externalscore add simulated external score (default is FALSE)
#'
#' @return a list with simulated CICA data
#'
#'
#' @examples
#' \dontrun{
#'
#' #Use set.seed(1) to obtain the dataset used in the article "Clusterwise
#' #Independent Component Analysis (CICA): an R package for clustering subjects
#' #based on ICA patterns underlying three-way (brain) data"
#'
#' Xe <- Sim_CICA(Nr = 15, Q = 5, R = 4, voxels = 100, timepoints = 10,
#' E = 0.4, overlap = .25, externalscore = TRUE)
#' }
#'
#' @importFrom stats rnorm
#'
#' @export
Sim_CICA <- function(Nr, Q, R, voxels, timepoints, E, overlap=NULL, externalscore = FALSE){
if(!is.null(overlap)){
Sbase <- replicate(n = Q, runif(n = voxels, min = -1, max = 1))
S <- lapply(1:R, function(x)
replicate(n = Q, runif(n = voxels, min = -overlap, max = overlap)))
Sr <- lapply(seq_along(S), function(x) Sbase + S[[x]])
RVs <- computeRVmat(DataList = Sr, dist = FALSE, verbose = FALSE)
}else{
Sr <- lapply(1:R, function(x)
replicate(n = Q, icasamp(dname = 'b', nsamp = voxels,query = 'rnd')))
}
Air <- lapply(1:R, FUN = function(x) lapply(1:Nr, function(x)
replicate(n = Q, runif(timepoints, min = -2, max = 2))))
Xs <- list()
for(i in 1:length(Air)){
Xs[[i]] <- lapply(1:length(Air[[i]]), function(x) Sr[[i]] %*% t(Air[[i]][[x]]))
}
X <- do.call(c, Xs)
SSequal <- function(m1,m2){(m1/sqrt(sum(m1^2)) * sqrt(sum(m2^2)))}
addError <- function(datablock, err){
errorM<-replicate(ncol(datablock),rnorm(nrow(datablock)))
errorM<-SSequal(errorM,datablock)
errorlevel<-err/(1-err)
res<-datablock + (errorM * sqrt(errorlevel))
return(res)
}
Xe <- lapply(X, addError, err = E)
P <- rep(1:R, each = Nr)
out <- list()
out$P <- P
out$X <- Xe
out$Sr <- Sr
out$Air <- unlist(Air, recursive = FALSE)
if(!is.null(overlap)){
out$RVs <- RVs
}
if(externalscore == TRUE){
score <- list()
for(i in 1:R){
if((i %% 2) == 0){
score[[i]] <- rnorm(Nr, mean = 25 + runif(1, max=3))
}else{
score[[i]] <- rnorm(Nr, mean = 12 + runif(1, min=-2, max = 2))
}
}
score <- do.call(c, score)
out$externalscore <- score
}
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/CICA/R/Sim_CICA.R
|
#' Convert Cluster specific independent components to NIFTI format
#'
#' @param x an object of \code{class} CICA
#' @param write if TRUE, NIfTI files are written to current working directory
#' @param ... other arguments passed to RNifti::writeNifti
#' @return a list with niftiImage files
#'
#' @examples
#' \dontrun{
#' nifs <- loadNIfTIs('<FolderPath>', toMatrix = T)
#' outnif <- CICA(DataList = nifs, RanStarts = 2, nComp = 10, nClus = 2)
#' test <- Sr_to_nifti(outnif,write = T, datatype = 'int16', version = 2)
#' }
#'
#' @import RNifti
#'
#' @export
#'
Sr_to_nifti <- function(x, write = FALSE, ...){
dims <- dim(x$Sr[[1]])
if(dims[1] == 14812){
img <- readNifti(file = system.file(package = 'CICA', 'extdata', '8mm.nii.gz', mustWork = TRUE) )
}else if(dims[1] == 116380){
img <- readNifti(file = system.file(package = 'CICA', 'extdata', '4mm.nii.gz', mustWork = TRUE) )
}else if(dims[1] == 902629){
img <- readNifti(file = system.file(package = 'CICA', 'extdata', '2mm.nii.gz', mustWork = TRUE) )
}else{
warning('Voxel dimension not equal to a the size of a MNI brain template')
d <- ceiling(dims[1] ^ (1/3))
img <- array(data = 0, dim = c(d,d,d) )
}
dimnif <- dim(img)
dimnif[4] <- dim(x$Sr[[1]])[2]
NIFS <- vector(mode = 'list', length = length(x$Sr))
for(i in 1:length(x$Sr)){
arr <- array(x$Sr[[i]], dim = dimnif)
img <- asNifti(arr, reference = img)
NIFS[[i]] <- img
}
names(NIFS) <- paste('Sr_', 1:length(x$Sr), sep='')
if(write == TRUE){
filenames <- names(NIFS)
lapply(X = seq_along(NIFS), function(i)
writeNifti(NIFS[[i]], file = filenames[i] ,datatype = ...) )
}
return(NIFS)
}
|
/scratch/gouwar.j/cran-all/cranData/CICA/R/Sr_to_nifti.R
|
#' Random clustering generation
#'@description Internal function for CICA package
#' @param nBlocks integer: number of objects
#' @param nClus integer: number of clusters
#'
#'
#'
#' @keywords internal
#' @return a numeric vector indicating the clustering
clusf <- function(nBlocks, nClus) {
#simplyfied cluster generation function using an equal probability
clus <- GenerateRandomClustering(nBlocks, nClus, rep(c(1 / nClus), nClus))
return(clus)
}
|
/scratch/gouwar.j/cran-all/cranData/CICA/R/clusf.R
|
# Thu Jul 1 13:39:33 2021
# Author: Jeffrey Durieux, MSc
#' Compute modified RV matrix
#' @description This function computes a NxN modified RV matrix
#' @param DataList a list with matrices
#' @param dist boolean if TRUE distance object is returned
#' @param verbose boolean if TRUE progressbar is printed to the console
#'
#' @return \item{RVsS}{a square similarity matrix of \code{class} \code{\link{matrix}} or distance object of \code{class} \code{\link{dist}} containing the pairwise modified RV values}
#'
#' @examples
#'
#' \dontrun{
#' CICA_data <- Sim_CICA(Nr = 15, Q = 5, R = 4, voxels = 100, timepoints = 10,
#' E = 0.4, overlap = .25, externalscore = TRUE)
#' #Compute single subject ICAs (nClus equals length(ExampleData))
#' output <- CICA(DataList = CICA_data$X, nStarts = 1,
#' nComp = 5, nClus = 9, verbose = FALSE)
#'
#' RV <- computeRVmat(DataList = output$Sr, dist = TRUE,
#' verbose = FALSE)
#'
#' # apply hierarchical clustering on RV output
#' hcl <- hclust(RV)
#' plot(hcl)
#'
#' # low dimensional visualisation using Classical Multidimensional Scaling
#' mds <- cmdscale(RV)
#' plot(mds)
#' }
#'
#' @importFrom utils combn
#'
#' @export
#'
computeRVmat <- function(DataList = DataList, dist = TRUE, verbose = TRUE){
N <- length(DataList)
comb <- t(combn(1:N, 2))
if(verbose == TRUE){
cat("Computing pairwise modified-RV statistics: \n")
pb <- txtProgressBar(min = 0, max = nrow(comb), initial = 0)
RVsS <- matrix(data = NA, nrow = N , ncol = N)
RVS <- numeric()
for(i in 1:nrow(comb)){
RVS[i] <- modRV( DataList[[ comb[i,1] ]] , DataList[[ comb[i,2] ]])
res <- c(comb[i , ] , RVS[i] )
RVsS[res[1] , res[2] ] <- res[3]
setTxtProgressBar(pb, i)
}
cat('\n')
}else{
RVsS <- matrix(data = NA, nrow = N , ncol = N)
RVS <- numeric()
for(i in 1:nrow(comb)){
RVS[i] <- modRV( DataList[[ comb[i,1] ]] , DataList[[ comb[i,2] ]])
res <- c(comb[i , ] , RVS[i] )
RVsS[res[1] , res[2] ] <- res[3]
}
}
RVsS[lower.tri(RVsS)] = t(RVsS)[lower.tri(RVsS)]
diag(RVsS) <- 1
if(dist == TRUE){
RVsS <- as.dist(sqrt(1-RVsS))
}
return(RVsS)
}
|
/scratch/gouwar.j/cran-all/cranData/CICA/R/computeRVmat.R
|
#' @title Embed images with Papaya
#'
#' @description Writes temporary images out from nifti objects or passes character filenames
#' of images to papaya JS viewer
#' @param images character filenames or \code{nifti} objects to be viewed
#' @param outdir output directory for index and all to go
#' @importFrom neurobase checkimg
#' @importFrom oro.nifti is.nifti nifti
#' @return Output html
#' @import htmltools
#' @export
embed_papaya <- function(
images, # character filenames or \code{nifti} objects to be viewed
outdir = NULL
){
L = get_papaya_version()
build = L$build
# version = L$version
#####################
# Make sure they are nifti
#####################
if (is.nifti(images)){
images = list(images)
}
# images = sapply(images, checkimg, check_type = TRUE)
images = sapply(images, checkimg)
# range
#####################
# Have to copy to temporary directory for js to work it seemed
#####################
if (is.null(outdir)){
outdir = tempfile()
}
if (!file.exists(outdir)){
dir.create(outdir)
}
#####################
# Copying image to output directory
#####################
outfiles = file.path(outdir, basename(images))
file.copy(images, to = outfiles, overwrite = TRUE)
images = basename(outfiles)
images = paste0('"', images, '"')
images = paste(images, collapse = ", ")
L = list()
L$images = images
##################
# Copy over the requirements for papaya
##################
index.file <- system.file("embed.html", package="papayar")
##################
# Reading in the index file to add to
##################
index = readLines(index.file)
line = grep("var params", index)
stopifnot(length(line) == 1)
top = index[seq(line)]
bottom = index[seq(line + 1, length(index))]
nL = names(L)
start = paste0('params["images"] = [')
end = '];'
cmd = ""
if (length(L$images) > 0){
cmd = paste0(start, L$images, end)
}
##################
# Writing out index.html to use
##################
cssfile = system.file("papaya.css", package="papayar")
jsfile = system.file("papaya.js", package="papayar")
outfiles = file.path(outdir, basename(c(cssfile, jsfile)))
file.copy(c(cssfile, jsfile), to = outfiles, overwrite = TRUE)
css = sprintf(
paste0('<link rel="stylesheet" type="text/css" href="%s?build=',
build, '" />\n'),
basename(cssfile))
js = sprintf(
paste0('<script type="text/javascript" src="%s?build=',
build, '"></script>\n'),
basename(jsfile))
index = c(css, js, top, cmd, bottom)
index = HTML(index)
return(index)
}
|
/scratch/gouwar.j/cran-all/cranData/CICA/R/embed_papaya.R
|
#' @title Get Papaya Version
#' @description Reads the papaya.js file installed and determines version and build
#' @return List of build and version, both characters
#' @export
get_papaya_version = function() {
jsfile = system.file("papaya.js",
package = "papayar")
line = readLines(jsfile, n = 1)
separate = strsplit(line, ",")[[1]]
separate = gsub('"', "", separate)
version = grep("PAPAYA_VERSION_ID", separate, value = TRUE)
build = grep("PAPAYA_BUILD_NUM", separate, value = TRUE)
version = gsub(".*=(.*)", "\\1", version)
build = gsub(".*=(.*)", "\\1", build)
L = list(version = version, build = build)
return(L)
}
#' @title Update Papaya build version from GitHub
#' @description Updates the papaya version in the papayar package to the most
#' current on GitHub
#' @param type Type of release. Standard is default
#' @param verbose Should download progress be shown?
#'
#' @return Result of \code{\link{get_papaya_version}} after downloading
#' @export
#' @importFrom utils download.file
update_papaya_build = function(type = c("standard", "minimal", "nodicom",
"nojquery", "standard-with-atlas-local",
"standard-with-atlas"), verbose = TRUE) {
type = match.arg(type)
files = c("index.html", "papaya.css", "papaya.js")
url = paste0(
"http://raw.githubusercontent.com/rii-mango/Papaya/master/release/current/",
type, "/")
dest = system.file(files,
package = "papayar")
bn = basename(dest)
files = intersect(files, bn)
files = paste0(url, files)
ifile = 1
# download the files
for (ifile in seq_along(files)) {
download.file(files[ifile], dest[ifile], quiet = !verbose)
}
L = get_papaya_version()
return(L)
}
|
/scratch/gouwar.j/cran-all/cranData/CICA/R/get_papaya_version.R
|
#' Load Nifti files from directory
#'
#' @param dir Input directory containing nifti files
#' @param toMatrix logical if TRUE nifti's are converted to matrices
#'
#' @return list object containing Voxel by Time course matrices
#'
#' @examples
#' \dontrun{
#' nifs <- loadNIfTIs('<FolderPath>', toMatrix = T)
#' outnif <- CICA(DataList = nifs, RanStarts = 2, nComp = 10, nClus = 2)
#' }
#'
#' @import RNifti
#' @export
#'
loadNIfTIs <- function(dir, toMatrix = TRUE){
fs <- dir(dir, pattern = '.nii.gz')
files <- paste(dir, fs, sep = '/')
NifList <- vector(mode = 'list', length = length(files))
for(nif in 1:length(files) ){
n <- readNifti(files[nif])
if(length(dim(n)) != 4){
stop('Nifti file number ', nif, ' does not have 4 dimensions')
}
# Voxel by Time matrix
if(toMatrix == TRUE){
NifList[[nif]] <- matrix(n, ncol = dim(n)[4])
}else{
NifList[[nif]] <- n
}
}
names(NifList) <- fs
return(NifList)
}
|
/scratch/gouwar.j/cran-all/cranData/CICA/R/loadNiftis.R
|
#' Match components between cluster specific spatial maps
#'
#' @param x object of class CICA
#' @param reference integer cluster index that serves as the reference. If nifti path is supplied, clusters will be matched to this template
#' @param RV compute modified-RV between cluster components
#' @param ... other arguments
#'
#' @return out
#'
#' @examples
#' \dontrun{
#' CICA_data <- Sim_CICA(Nr = 15, Q = 5, R = 4, voxels = 100, timepoints = 10,
#' E = 0.4, overlap = .25, externalscore = TRUE)
#'
#' multiple_output = CICA(DataList = CICA_data$X, nComp = 2:6, nClus = 1:5,
#' userGrid = NULL, RanStarts = 30, RatStarts = NULL, pseudo = c(0.1, 0.2),
#' pseudoFac = 2, userDef = NULL, scalevalue = 1000, center = TRUE,
#' maxiter = 100, verbose = TRUE, ctol = .000001)
#'
#' matcher(multiple_output$Q_5_R_4, reference = 1, RV = TRUE)
#' }
#'
#' @importFrom multiway congru
#' @import RNifti
#'
#' @export
#'
matcher.CICA <- function(x, reference = 1, RV = FALSE, ...){
lsr <- length(x$Sr)
if(class(reference)[1] == 'numeric'){
ncomp <- ncol(x$Sr[[1]])
m <- 1:ncomp
mm <- rep(1, ncomp)
conList <- vector(mode = 'list', length =lsr-1)
toSelect <- 1:lsr
toSelect <- toSelect[-reference]
for(i in 1:length(toSelect)){
#con <- cor(x$Sr[[reference]], x$Sr[[ toSelect[i]]] )
con <- congru(x$Sr[[reference]], x$Sr[[ toSelect[i]]] )
conList[[i]] <- con
Cluster2 <- apply(abs(con) , MARGIN = 1, which.max)
max <- apply(abs(con) , MARGIN = 1, max)
m <- cbind(m, Cluster2)
mm <- cbind(mm, max)
}
names(conList) <- paste('Cluster ', toSelect)
rownames(m) <- paste('Component ', 1:ncomp)
rownames(mm) <- paste('Component ', 1:ncomp)
colnames(m) <- paste('Cluster ', c(reference, toSelect))
colnames(mm) <- paste('Cluster ', c(reference,toSelect))
}else if(class(reference)[1] == 'character'){
nif <- readNifti(reference)
nif <- matrix(nif, ncol = dim(nif)[4])
ncomp <- ncol(nif)
m <- 1:ncomp
mm <- rep(1, ncomp)
conList <- vector(mode = 'list', length = length(x$Sr))
for(i in 1:lsr){
#con <- cor(nif, x$Sr[[ i ]] )
con <- congru(nif, x$Sr[[ i ]] )
conList[[i]] <- con
whichm <- apply(abs(con) , MARGIN = 1, which.max)
max <- apply(abs(con) , MARGIN = 1, max)
m <- cbind(m, whichm)
mm <- cbind(mm, max)
}
names(conList) <- paste('Cluster ', 1:lsr)
rownames(m) <- paste('Component ', 1:ncomp)
rownames(mm) <- paste('Component ', 1:ncomp)
name <- paste('Cluster ', 1:length(x$Sr))
name <- c('Template Nifti', name)
colnames(m) <- name
colnames(mm) <- name
}else if(class(reference)[1] == 'matrix'){
ncomp <- ncol(reference)
m <- 1:ncomp
mm <- rep(1, ncomp)
conList <- vector(mode = 'list', length = length(x$Sr))
for(i in 1:lsr){
con <- cor(reference, x$Sr[[ i ]] )
con <- congru(reference, x$Sr[[ i ]] )
conList[[i]] <- con
whichm <- apply(abs(con) , MARGIN = 1, which.max)
max <- apply(abs(con) , MARGIN = 1, max)
m <- cbind(m, whichm)
mm <- cbind(mm, max)
}
names(conList) <- paste('Cluster ', 1:lsr)
rownames(m) <- paste('Component ', 1:ncomp)
rownames(mm) <- paste('Component ', 1:ncomp)
name <- paste('Cluster ', 1:length(x$Sr))
name <- c('Template ', name)
colnames(m) <- name
colnames(mm) <- name
}
out <- list()
out$matchIndexMatrix <- m
out$matchTuckerMatrix <- round(mm, digits = 3)
out$CongruenceList <- lapply(conList, round, digits = 3)
if(RV == TRUE){
RVs <- computeRVmat(x$Sr, dist = F, verbose = T)
out$RVs <- round(RVs, digits = 3)
}
return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/CICA/R/matcher.CICA.R
|
#' Match components between cluster specific spatial maps
#'
#' @param x object of class CICA
#' @param reference integer cluster index that serves as the reference. If nifti path is supplied, clusters will be matched to this template
#' @param RV compute modified-RV between cluster components
#' @param ... other arguments
#'
#' @return out
#'
#' @examples
#' \dontrun{
#' CICA_data <- Sim_CICA(Nr = 15, Q = 5, R = 4, voxels = 100, timepoints = 10,
#' E = 0.4, overlap = .25, externalscore = TRUE)
#'
#' multiple_output = CICA(DataList = CICA_data$X, nComp = 2:6, nClus = 1:5,
#' userGrid = NULL, RanStarts = 30, RatStarts = NULL, pseudo = c(0.1, 0.2),
#' pseudoFac = 2, userDef = NULL, scalevalue = 1000, center = TRUE,
#' maxiter = 100, verbose = TRUE, ctol = .000001)
#'
#' matcher(multiple_output$Q_5_R_4, reference = 1, RV = TRUE)
#' }
#'
#' @export
#'
#'
matcher <- function(x, reference, RV = FALSE, ...){
UseMethod('matcher')
}
|
/scratch/gouwar.j/cran-all/cranData/CICA/R/matcher.R
|
#' The modified-RV coefficient
#'
#' @param X first matrix, number of rows in X should corresponds to number of rows in Y
#' @param Y second matrix, number of rows in Y should corresponds to number of rows in X
#'
#' @return A single value, indicating the similarity between the two input matrices
#' @keywords internal
#'
#' @author Jeffrey Durieux
#' @references Smilde AK, Kiers HAL, Bijlsma S, Rubingh CM, van Erk MJ (2009) Matrix correlations for high-dimensional data: the modified RV-coefficient. Bioinformatics 25(3):401–405
#'
#' @seealso \code{\link{computeRVmat}}
#'
#' @examples
#' \dontrun{
#' #X1 <- matrix(rnorm(1000), 10)
#' #SVD <- svd(X1)
#' #X2 <- SVD$u[,-5] %*% diag(SVD$d[-5]) %*% t(SVD$v[,-5])
#' #modRV(X1,X2)
#' }
modRV <- function(X, Y){
if(nrow(X) != nrow(Y)){
stop('Number of rows of input matrices are not equal')
}
XXtilde <- ( X %*% t(X) ) - diag (diag( X %*% t(X) ) )
YYtilde <- ( Y %*% t(Y) ) - diag (diag( Y %*% t(Y) ) )
res <- ( t(c(XXtilde)) %*% c(YYtilde) ) /
( sqrt( ( t(c(XXtilde)) %*% c(XXtilde)) * ( t(c(YYtilde)) %*% c(YYtilde)) ) )
return(res)
}
|
/scratch/gouwar.j/cran-all/cranData/CICA/R/modRV.R
|
#' Moore Penrose inverse
#'
#' @param X input matrix
#'
#' @return mp Moore Penrose inverse of matrix X
#'
mpinv <- function (X)
{
#### function from NMFN package but was not maintained any longer
#### original author: Suhai (Timothy) Liu <[email protected]>
Eps <- 100 * .Machine$double.eps
s <- svd(X)
d <- s$d
m <- length(d)
if (!(is.vector(d)))
return(t(s$v %*% (1/d) %*% t(s$u)))
d <- d[d > Eps]
notnull <- length(d)
if (notnull == 1) {
inv <- 1/d
}
else {
inv <- solve(diag(d))
}
if (notnull != m) {
inv <- cbind(inv, matrix(0, nrow = notnull, ncol = (m -
notnull)))
inv <- rbind(inv, matrix(0, nrow = (m - notnull), ncol = m))
}
mp <- s$v %*% inv %*% t(s$u)
mp[abs(mp) < Eps] <- 0
return(mp)
}
|
/scratch/gouwar.j/cran-all/cranData/CICA/R/mpinv.R
|
#' @title View images with Papaya
#'
#' @description Writes temporary images out from nifti objects or passes character filenames
#' of images to papaya JS viewer
#' @param images character filenames or \code{nifti} objects to be viewed
#' @param outdir output directory for index and all to go
#' @param ... Options to be passed to \code{\link{pass_papaya}}
#' @export
#' @importFrom neurobase checkimg
#' @importFrom oro.nifti is.nifti nifti
#' @return Output directory where index.html, js, and copied nii.gz files
#' @examples \dontrun{
#' library(neurobase)
#' x = nifti(img = array(rnorm(100^3), dim= rep(100, 3)), dim=rep(100, 3), datatype=16)
#' thresh = datatyper(x > 1)
#' index.file = papaya(list(x, thresh))
#' }
papaya <- function(
images, # character filenames or \code{nifti} objects to be viewed
outdir = NULL,
...
){
#####################
# Make sure they are nifti
#####################
if (is.nifti(images)){
images = list(images)
}
# images = sapply(images, checkimg, check_type = TRUE)
images = sapply(images, checkimg)
# range
##################
#Create temporary directory for things to go
##################
if (is.null(outdir)){
outdir = tempfile()
}
if (!file.exists(outdir)){
dir.create(outdir)
}
#####################
# Copying image to output directory
#####################
outfiles = file.path(outdir, basename(images))
fc = file.copy(images, to = outfiles, overwrite = TRUE)
if (!all(fc)){
stop("# Some files passed in are not found!")
}
images = basename(outfiles)
images = paste0('"', images, '"')
images = paste(images, collapse = ", ")
L = list()
L$images = images
index.file = pass_papaya(L, outdir = outdir, ...)
return(index.file)
}
|
/scratch/gouwar.j/cran-all/cranData/CICA/R/papaya.R
|
#' @title Papaya Div element output
#' @description Get the necessary div output for embedding a papaya image
#' @return Character string
#' @export
#'
#' @examples
#' papaya_div()
papaya_div = function(){
index.file <- system.file("embed.html", package="papayar")
x = readLines(index.file)
x = x[length(x)]
return(x)
}
|
/scratch/gouwar.j/cran-all/cranData/CICA/R/papaya_div.R
|
#' @title View images with Papaya
#'
#' @description Writes temporary images out from nifti objects or passes character filenames
#' of images to papaya JS viewer
#' @param L list of arguments passed to papaya using params
#' @param outdir output directory for index and all to go
#' @param daemon Argument passed to \code{\link[servr]{server_config}}
#' @param close_on_exit Should the server close once the function finishes?
#' @param sleeper Time in seconds to sleep if \code{close_on_exit = TRUE}.
#' This allows the server to start up.
#' @param version Version of papaya.js and papaya.css to use
#' @param build Build of papaya.js and papaya.css to use
#' @export
#' @importFrom servr httd
#' @return NULL
pass_papaya <- function(
L = NULL,
outdir = NULL,
daemon = FALSE,
close_on_exit = TRUE,
sleeper = 3,
version = "0.8",
build = "982"
){
##################
#Create temporary directory for things to go
##################
if (is.null(outdir)){
outdir = tempfile()
}
if (!file.exists(outdir)){
dir.create(outdir)
}
##################
# Copy over the requirements for papaya
##################
files = c("index.html", "papaya.css", "papaya.js")
files = sapply(files, system.file, package = "papayar")
file.copy(files, to = outdir, overwrite = TRUE)
##################
# Reading in the index file to add to
##################
index.file = file.path(outdir, "index.html")
index = readLines(index.file)
index = gsub("%version%", version, index)
index = gsub("%build%", build, index)
line = grep("var params", index)
stopifnot(length(line) == 1)
top = index[seq(line)]
bottom = index[seq(line + 1, length(index))]
nL = names(L)
start = paste0('params["images"] = [')
end = '];'
cmd = ""
if (length(L$images) > 0){
cmd = paste0(start, L$images, end)
}
##################
# Writing out index.html to use
##################
index = c(top, cmd, bottom)
writeLines(text = index, con = index.file)
# cat(index.file)
##################
# browsing the file
##################
viewer <- getOption("viewer")
# cat(paste0("# Daemon is\n", daemon, "\n"))
daemon_name = httd(outdir, daemon = daemon, browser = TRUE)
if (close_on_exit){
cat(paste0("# Stopping Server ", daemon_name, " \n"))
if (daemon) {
Sys.sleep(sleeper)
}
on.exit({
servr::daemon_stop(daemon_name)
})
}
return(index.file)
}
|
/scratch/gouwar.j/cran-all/cranData/CICA/R/pass_papaya.R
|
#' Perturbate a clustering
#'
#' @param p a clustering vector
#' @param percentage percentage (in proportions)
#'
#' @return peturbated clustering vector
#' @keywords internal
perturbation <- function(p, percentage = 0.1){
clusters <- sort(unique(p))
sel <- ceiling(length(p) * percentage )
selected <- sample(1:length(p), size = sel, replace = F)
if(length(selected) == 1){
# change one cluster
oriclus <- p[selected]
newclus <- which(clusters != oriclus)
if(length(newclus) > 1){
newclus <- sample(newclus, size = 1)
}
np <- replace(p, selected, newclus)
}else{
# change multiple clusters
np <- p
for(i in 1:length(selected)){
oriclus <- p[selected[i]]
newclus <- which(clusters != oriclus)
if(length(newclus) > 1){
newclus <- sample(newclus, size = 1)
}
np <- replace(np, selected[i], newclus)
}
}
return(np)
}
|
/scratch/gouwar.j/cran-all/cranData/CICA/R/perturbation.R
|
#' Plot method for CICA
#' @description Plot method for CICA. This function shows the cluster specific
#' independent components in an interactive viewer using the papayar package
#' @param x Object of \code{class} CICA
#' @param brain auto
#' @param cluster Components of cluster to plot. Only used when non fMRI related data is used
#' @param ... other arguments
#'
#' @examples
#' \dontrun{
#' CICA_data <- Sim_CICA(Nr = 15, Q = 5, R = 4, voxels = 100, timepoints = 10,
#' E = 0.4, overlap = .25, externalscore = TRUE)
#'
#' multiple_output = CICA(DataList = CICA_data$X, nComp = 2:6, nClus = 1:5,
#' userGrid = NULL, RanStarts = 30, RatStarts = NULL, pseudo = c(0.1, 0.2),
#' pseudoFac = 2, userDef = NULL, scalevalue = 1000, center = TRUE,
#' maxiter = 100, verbose = TRUE, ctol = .000001)
#'
#' plot(multiple_output$Q_5_R_4, cluster = 2)
#' }
#'
#' @importFrom plotly plot_ly layout add_histogram
#' @importFrom magrittr %>%
#' @import RNifti
#'
#' @export
#'
#'
plot.CICA <- function(x, brain = 'auto', cluster = 1, ...){
dims <- dim(x$Sr[[1]])
if(dims[1] == 14812){
img <- readNifti(file = system.file(package = 'CICA', 'extdata',
'8mm.nii.gz', mustWork = TRUE) )
papaya( c(list(img), Sr_to_nifti(x) ) )
}else if(dims[1] == 116380){
img <- readNifti(file = system.file(package = 'CICA', 'extdata',
'4mm.nii.gz', mustWork = TRUE) )
papaya( c(list(img), Sr_to_nifti(x) ) )
}else if(dims[1] == 902629){
img <- readNifti(file = system.file(package = 'CICA', 'extdata',
'2mm.nii.gz', mustWork = TRUE) )
papaya( c(list(img), Sr_to_nifti(x) ) )
}else{
create_buttons2 <- function(df, y_axis_var_names) {
lapply(
1:length(y_axis_var_names),
FUN = function(id, y_axis_var_names, df) {
position<-rep(FALSE,length(y_axis_var_names))
position[id]<-TRUE
button <- list(
method = 'update',
args = list(list(visible = position),
list(xaxis = list(title = colnames(y_axis_var_names)[id]))),
label = colnames(y_axis_var_names)[id]
)
},
df
)
}
df <- data.frame(x$Sr[[cluster]])
y_axis_var_names <- paste('Comp' , 1:ncol(x$Sr[[cluster]]), sep = '_')
colnames(df) <- y_axis_var_names
fig<-plot_ly(df, x = ~Comp_1, alpha = 0.3, type = 'histogram')
if(length(y_axis_var_names)>1){
for (i in 2:length(y_axis_var_names)) {
dfi <- data.frame(y=df[y_axis_var_names[i]])
colnames(dfi)<-"y"
fig<-fig %>% add_histogram(x = ~y, data=dfi, visible = FALSE, name = y_axis_var_names[i]) #Something wrong here
}
}
fig<-fig %>% layout(
title = paste('Cluster', cluster),
showlegend = FALSE
,
updatemenus = list(
list(
buttons = create_buttons2(df = df, y_axis_var_names = y_axis_var_names)
)
)
)
fig
}
}
# #warning('Data does not correspond to MNI coordinates, no interactive plot returned')
# df <- data.frame(x$Sr[[cluster]])
# y_axis_var_names <- paste('Comp' , 1:ncol(x$Sr[[cluster]]), sep = '_')
# colnames(df) <- y_axis_var_names
# create_buttons <- function(df, y_axis_var_names) {
# lapply(
# y_axis_var_names,
# FUN = function(var_name, df) {
# button <- list(
# method = 'restyle',
# args = list('x', list(df[, var_name])),
# label = var_name
# )
# },
# df
# )
# }
#
# fig1 <- plot_ly(df, x = ~Comp_1, alpha = 0.3, type = 'histogram') %>%
# layout(title = paste('Cluster', cluster),
# xaxis = list(title = "Component"),
# updatemenus = list(
# list(
# buttons = create_buttons(df = df, y_axis_var_names = y_axis_var_names)
# )
# ))
# fig1
|
/scratch/gouwar.j/cran-all/cranData/CICA/R/plot.CICA.R
|
#' Plot method for sequential model selection
#' @description Plot method for the sequential model selection option for CICA
#' @param x Object of \code{class} ModSel
#' @param ... other arguments
#'
#' @examples
#' \dontrun{
#' CICA_data <- Sim_CICA(Nr = 15, Q = 5, R = 4, voxels = 100, timepoints = 10,
#' E = 0.4, overlap = .25, externalscore = TRUE)
#'
#' multiple_output = CICA(DataList = CICA_data$X, nComp = 2:6, nClus = 1:5,
#' userGrid = NULL, RanStarts = 30, RatStarts = NULL, pseudo = c(0.1, 0.2),
#' pseudoFac = 2, userDef = NULL, scalevalue = 1000, center = TRUE,
#' maxiter = 100, verbose = TRUE, ctol = .000001)
#'
#' ModSelOutput <- SequentialScree(multiple_output)
#'
#' plot(ModSelOutput)
#' }
#'
#' @importFrom plotly plot_ly add_trace
#' @importFrom methods is
#'
#' @export
#'
#'
plot.ModSel <- function(x,...){
if(!is(x,'ModSel')){ #equivalent to if(class(x) != 'ModSel'){
stop('Input object is not of class ModSel')
}
if(length(x$optimalQ)==0 & length(x$optimalR)==0){
stop("Scree values were not computed. Check if you provided at least 3 values for the nComp input argument of CICA")
}
if(length(x$optimalQ)==1 & length(x$optimalR)==1){
xsel <- x$optimalQ
rsel <- x$optimalR
ysel <- x$df[which(x$df$Q == xsel & x$df$R == rsel),]$Loss
plot_ly(data = x$df, x = ~Q, y=~Loss, color = ~as.factor(R), mode='lines+markers',
type = 'scatter') %>%
add_trace(x = ~xsel, y = ~ysel,
marker = list(symbol = 18, size = 10, color = 'darkgreen'), showlegend=F) %>%
layout(
#annotations = list(x = xsel, y = ysel,
# showarrow = TRUE, text = 'selected model',
# arrowhead = 6),
legend = list(title=list(text='Cluster')))
}else if(length(x$optimalQ)==1 & length(x$optimalR)==0){
xsel <- x$optimalQ
ysel <- x$df[which(x$df$Q == xsel),]$Loss
plot_ly(data = x$df, x = ~Q, y=~Loss, mode='lines+markers',
type = 'scatter') %>%
add_trace(x = ~xsel, y = ~ysel,
marker = list(symbol = 18, size = 10, color = 'darkgreen'), showlegend=F)
}else if(length(x$optimalQ)==0 & length(x$optimalR)==1){
xsel <- x$optimalR
ysel <- x$df[which(x$df$R == xsel),]$Loss
plot_ly(data = x$df, x = ~R, y=~Loss, mode='lines+markers',
type = 'scatter') %>%
add_trace(x = ~xsel, y = ~ysel,
marker = list(symbol = 18, size = 10, color = 'darkgreen'), showlegend=F)
}
}
|
/scratch/gouwar.j/cran-all/cranData/CICA/R/plot.ModSel.R
|
#' Plot method for rstarts object
#' @rdname FindRationalStarts
#' @param x an object of \code{class} rstarts
#' @param type type of plot, 1 for a dendrogram, 2 for a multidimensional scaling configuration
#' @param mdsdim 2 for two dimensional mds configuration, 3 for a three dimensional configuration
#' @param nClus Number of clusters for rectangles in dendrogram, default NULL is based on number of clusters present in the object
#' @param ... optional arguments passed to \code{hclust} function
#'
#' @examples
#' \dontrun{
#' CICA_data <- Sim_CICA(Nr = 15, Q = 5, R = 4, voxels = 100, timepoints = 10,
#' E = 0.4, overlap = .25, externalscore = TRUE)
#' Out_starts <- FindRationalStarts(DataList = CICA_data$X,nComp = 5,nClus = 4,scalevalue = 1000)
#' plot(Out_starts)
#' plot(Out_starts, type = 2)
#' plot(Out_starts, type = 2,mdsdim = 3, method = 'ward.D2')
#' }
#'
#'
#' @importFrom plotly plot_ly layout
#' @importFrom magrittr %>%
#' @importFrom stats hclust cutree rect.hclust cmdscale
#' @export
#'
#'
plot.rstarts <- function(x, type = 1, mdsdim = 2, nClus = NULL,...){
if(is.null(nClus)){
nClus <- length( unique( x$rationalstarts[,1]) )
}else{
nClus <- nClus
}
hcl <- hclust(x$RVdist, method = ...)
k <- cutree(hcl, k = nClus)
if(type == 1){
plot(hcl, xlab='')
rect.hclust(hcl, k = nClus)
}else{
dots <- match.call(expand.dots = F)$...
title <- paste('Label method: ', dots[[1]])
mds <- cmdscale(x$RVdist, k = mdsdim)
df <- data.frame(mds, lab = as.factor(k))
hover <- 1:nrow(df)
if(mdsdim == 2){
plot_ly(data = df, x=~X1, y=~X2, color = ~lab, type = 'scatter', mode = 'markers',
text = hover, hoverinfo = 'text') %>%
layout(title = title, yaxis = list(scaleanchor = 'x'))
}else{
plot_ly(data = df, x=~X1, y=~X2, z=~X3, color = ~lab, type = 'scatter3d', mode = 'markers',
text = hover, hoverinfo = 'text', marker = list(size = 5)) %>%
layout(title = title)
}
}
}
|
/scratch/gouwar.j/cran-all/cranData/CICA/R/plot.rstarts.R
|
#' Summary method for class CICA
#' @description Summarize a CICA analysis
#' @param object Object of the type produced by \code{\link{CICA}}
#' @param ... Additional arguments
#'
#' @return \code{summary.CICA} returns an overview of the estimated clustering of a \code{\link{CICA}} analysis
#' \item{PM}{Partitioning matrix}
#' \item{tab}{tabulation of the clustering}
#' \item{Loss}{Loss function value of the solution}
#'
#' @examples
#' \dontrun{
#' CICA_data <- Sim_CICA(Nr = 15, Q = 5, R = 4, voxels = 100, timepoints = 10,
#' E = 0.4, overlap = .25, externalscore = TRUE)
#'
#' multiple_output = CICA(DataList = CICA_data$X, nComp = 2:6, nClus = 1:5,
#' userGrid = NULL, RanStarts = 30, RatStarts = NULL, pseudo = c(0.1, 0.2),
#' pseudoFac = 2, userDef = NULL, scalevalue = 1000, center = TRUE,
#' maxiter = 100, verbose = TRUE, ctol = .000001)
#'
#' summary(multiple_output$Q_5_R_4)
#' }
#'
#'
#' @export
#'
#'
summary.CICA <- function(object, ...){
cat('Partitioning matrix P: \n' )
PB <- matrix(0, nrow = length(object$P), ncol = length(unique(object$P)))
for(i in 1:nrow(PB)){
PB[i, object$P[i]] <- 1
}
colnames(PB) <- paste('Cluster',sort(unique(object$P)))
rownames(PB) <- names(object$P)
cat('\n')
print(PB)
cat('\n')
cat('Tabulation of clustering: \n')
cat('\n')
tab <- table(object$P)
names(tab) <- paste('Cluster',sort(unique(object$P)))
print( tab )
cat('\n')
cat('Loss function value of optimal solution is: ', object$Loss,'\n')
# out <- list()
# out$PM <- PB
# out$tab <- tab
# out$loss <- object$Loss
#
# return(out)
}
|
/scratch/gouwar.j/cran-all/cranData/CICA/R/summary.CICA.R
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.