Rphree_DataBase.R 6.15 KB
Newer Older
Marco De Lucia's avatar
Marco De Lucia committed
1
2
##  Functions for manipulating PHREEQC databases

Marco De Lucia's avatar
Marco De Lucia committed
3
4
### Marco De Lucia, delucia@gfz-potsdam.de, 2009-2021
### Time-stamp: "Last modified 2021-04-28 18:39:07 delucia"
Marco De Lucia's avatar
Marco De Lucia committed
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157

##' @title Finds the expression of a logK of a given compound/mineral
##'     in a PHREEQC database
##' @param species name of the species/mineral to search for
##' @param db the buffer containing the database
##' @param type one of c("analytical","logk","equation","lhs","rhs")
##' @return the requested logK
##' @author MDL
##' @export
FindLogK <- function(species, db, type=c("analytical"))
{
    ##  reg <- gsub("\\(","\\\\(",species) ## obsoleted through the fixed=TRUE option
    ##  reg <- gsub("\\)","\\\\)",reg)

    args <- c("analytical","logk","equation","lhs","rhs")
    type <- match.arg(type, args)
    
    pos  <- grep(species,db,fixed=TRUE)
    if (length(pos) > 1) pos <- pos[1] ## just the 1st occurrence
    if (length(pos) == 0) {
        msg("Species \"", species,"\" not found in the DataBase")
        return(NA)
    }
    ## check if analytical expression is present!
    if (type=="analytical") {
        linepos <- grep("anal",db[c(pos:(pos+4))])
        if (length(linepos)==1) {
            
            linepos <- pos + linepos - 1
            line <- TrailSpaces(db[linepos])
            
            parread <- unlist(strsplit(line," +"))[-1]
            len <- length(parread)
            if (len != 5) {
                parread[seq(len+1,5)] <- 0
                msg("Analytical expression for reaction",species,"has only", len, "terms")
            }
            par.anal <- as.numeric(parread)
            attr(par.anal,"line") <- linepos
            attr(par.anal,"type") <- "analytical"
            return(par.anal)
        } 
    }
    if (type=="logk") {
        
        ## if we are here, either there is no analytical, or we want to calculate also the new logK
        linepos <- grep("log",db[c(pos:(pos+3))])
        if (length(linepos)==1) {
            linepos <- pos + linepos - 1
            line <- TrailSpaces(db[linepos])
            
            parread <- unlist(strsplit(line," +"))[2]
            
            par.logk <- as.numeric(parread)
            attr(par.logk,"line") <- linepos
            attr(par.logk,"type") <- "logk"
            
            return(par.logk)
        }
        
    }
    if (type=="equation") {
        return(TrailSpaces(db[pos+1]))
    }
    if (type=="lhs") {
        return(ParseFormula(TrailSpaces(db[pos+1]), type="lhs"))
    }
    if (type=="rhs") {
        return(ParseFormula(TrailSpaces(db[pos+1]), type="rhs"))
    }
    ## if we are here, no matching expression found, returning NA
    return(NA)

}

##' @title Calculates the logK of reaction for a given temperature
##' @param param the vector containing the coefficients of analytical
##'     logK
##' @param Tk temperature in Kelvin
##' @return The logK at wanted temperature
##' @author MDL
##' @export
AnalyticalLogK <- function(param,Tk)
{
  return(param[1]+param[2]*Tk+param[3]/Tk+param[4]*log10(Tk)+param[5]/Tk^2)
}


##' @title Parses a formula as it is written in a PHREEQC database
##' @param line the string containing the reaction
##' @param type one of c("all","lhs","rhs")
##' @return a list containing components and coefficients.
##'     Coefficients of left hand side are negated.
##' @author MDL
##' @export
ParseFormula <- function(line, type="all")
{
    args <- c("all","lhs","rhs")
    type <- match.arg(type, args)

    tsline <- TrailSpaces(line)
    formula <- unlist(strsplit(tsline,"="))
    left <- formula[1]
    right <- formula[2]
  
    lhs <- unlist(strsplit(left," + ", fixed=TRUE))
    rhs <- unlist(strsplit(right," + ", fixed=TRUE))


    if (type=="all" || type=="lhs") {
        ## left hand side
        coeffsl <- rep(1,length(lhs))
        compl <- rep("",length(lhs))
        for (i in seq_along(lhs)) {
            lhs[i] <- sub(' +$', '', lhs[i]) ## remove spaces at the end of string
            spaces <- grep(" ",lhs[i],fixed=TRUE)
            if (length(spaces)==1) {
                tmp <- unlist(strsplit(lhs[i]," ", fixed=TRUE))
                coeffsl[i] <- as.numeric(tmp[1])
                compl[i] <- tmp[2]
            } else {
                compl[i] <- lhs[i]
            }
        }
    }
    
    if (type=="all" || type=="rhs") {
        ## right hand side
        coeffsr <- rep(1,length(rhs))
        compr <- rep("",length(rhs))
        for (i in seq_along(rhs)) {
            rhs[i] <- sub('^ +', '', rhs[i]) ## remove spaces at the beginning
            spaces <- grep(" ",rhs[i],fixed=TRUE)
            if (length(spaces)==1) {
                tmp <- unlist(strsplit(rhs[i]," ", fixed=TRUE))
                coeffsr[i] <- as.numeric(tmp[1])
                compr[i] <- tmp[2]
            } else {
                compr[i] <- rhs[i]
            }
        }
    }

    if (type=="all")
        out <- list(comp=c(compl,compr), coeff=c(-coeffsl,coeffsr))
    if (type=="lhs")
        out <- list(comp=compl, coeff=-coeffsl)
    if (type=="rhs")
        out <- list(comp=compr, coeff=coeffsr)
    
    return(out)
}

Marco De Lucia's avatar
Marco De Lucia committed
158
##' @title Find a PURE_PHASE in a database and parse its formula
Marco De Lucia's avatar
Marco De Lucia committed
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
##' @param species name of phase to search for
##' @param db a PHREEQC database (buffer)
##' @return a list with the components of the formula and the
##'     stoichiometric coefficients, plus the corresponding line in
##'     the db as attr(,"line")
##' @author MDL
##' @export
FindPhase <- function(species,db)
{
  phases <- grep("^PHASES",db)
  pos  <- grep(species, db, fixed=TRUE)
  
  if (length(pos) > 1) pos <- pos[1] ## just the 1st occurrence

  line <- db[pos+1]
  out <- ParseFormula(TrailSpaces(line))

  ## substitute the composition with the mineral name, lower case
  out$comp[1] <- tolower(species)
  attr(out,"line") <- pos+1
  return(out)
}

##' This utility function is not meant to be used directly by the user
##' @title Remove spaces at the end and beginning of a line
##' @param line the string to remove trailing spaces from
##' @return reformatted string without blanks at beginning and end
##' @author MDL
##' @export
TrailSpaces <- function(line)
{
  tmp <- sub(' +$', '', line)  ## remove spaces at the end of the lines
  tmp <- sub('^ +', '', tmp)  ## remove spaces at the beginning
  return(tmp)
}