Skip to content

Commit

Permalink
On #62 and #60.
Browse files Browse the repository at this point in the history
Switch default method to Nelder-Mead in optim.
Document fitFOM arguments and tweak example.
  • Loading branch information
sashahafner committed Nov 30, 2024
1 parent 1b765a3 commit 495f657
Show file tree
Hide file tree
Showing 3 changed files with 115 additions and 21 deletions.
24 changes: 16 additions & 8 deletions DESCRIPTION
Original file line number Diff line number Diff line change
@@ -1,13 +1,21 @@
Package: biogas
Type: Package
Title: Process Biogas Data and Predict Biogas Production
Version: 1.45
Date: 2024-11-29
Authors@R: c(person("Sasha D.", "Hafner", role = c("aut", "cre"), email = "[email protected]"), person("Charlotte", "Rennuit", role = "aut"), person("Camilla", "Justesen", role = "aut"), person("Nanna", "Lojborg", role = "aut"), person("Jacob", "Mortensen", role = "aut"), person("Jonas", "Ohlsson", role = "aut"), person("Sergi", "Astals", role = "ctb"), person("Konrad", "Koch", role = "ctb"), person("Soeren", "Weinrich", role = "ctb"), person("Jin Mi", "Triolo", role = "ctb"), person("Ali", "Heidarzadeh Vazifehkhoran", role = "ctb"))
Author: Sasha D. Hafner [aut, cre], Charlotte Rennuit [aut], Camilla Justesen [aut], Nanna Lojborg [aut], Jacob Mortensen [aut], Jonas Ohlsson [aut], Sergi Astals [ctb], Konrad Koch [ctb], Soeren Weinrich [ctb], Jin Mi Triolo [ctb], Ali Heidarzadeh Vazifehkhoran [ctb]
Maintainer: Sasha D. Hafner <[email protected]>
Version: 1.46
Date: 2024-11-30
Authors@R: c(person("Sasha D.", "Hafner", role = c("aut", "cre"), email = "[email protected]", comment = c(ORCID = "0000-0003-0955-0327")),
person("Charlotte", "Rennuit", role = "aut"),
person("Camilla", "Justesen", role = "aut"),
person("Nanna", "Lojborg", role = "aut"),
person("Jacob", "Mortensen", role = "aut"),
person("Jonas", "Ohlsson", role = "aut"),
person("Sergi", "Astals", role = "ctb"),
person("Konrad", "Koch", role = "ctb"),
person("Soeren", "Weinrich", role = "ctb"),
person("Jin Mi", "Triolo", role = "ctb"),
person("Ali", "Heidarzadeh Vazifehkhoran", role = "ctb"))
Maintainer: Sasha D. Hafner <[email protected]>
VignetteBuilder: knitr
Imports: minpack.lm
Suggests: knitr, ggplot2, testthat
Description: High- and low-level functions for processing biogas data and predicting biogas production. Molar mass and calculated oxygen demand (COD') can be determined from a chemical formula. Measured gas volume can be corrected for water vapor and to (possibly user-defined) standard temperature and pressure. Gas quantity can be converted between volume, mass, and moles. Gas composition, cumulative production, or other variables can be interpolated to a specified time. Cumulative biogas and methane production (and rates) can be calculated using volumetric, manometric, gravimetric, or gas density methods for any number of bottles. With cumulative methane production data and data on bottle contents, biochemical methane potential (BMP) can be calculated and summarized, including subtraction of the inoculum contribution and normalization by substrate mass. Cumulative production and production rates can be summarized in several different ways (e.g., omitting normalization) using the same function. Biogas quantity and composition can be predicted from substrate composition and additional, optional data. Lastly, inoculum and substrate mass can be determined for planning BMP experiments.
Suggests: minpack.lm, knitr, ggplot2, testthat
Description: High- and low-level functions for processing biogas data and predicting biogas production. Molar mass and calculated oxygen demand (COD') can be determined from a chemical formula. Measured gas volume can be corrected for water vapor and to (possibly user-defined) standard temperature and pressure. Gas quantity can be converted between volume, mass, and moles. Gas composition, cumulative production, or other variables can be interpolated to a specified time. Cumulative biogas and methane production (and rates) can be calculated from raw data obtained using volumetric, manometric, gravimetric, or gas density methods for any number of bottles. With cumulative methane production data and data on bottle contents, biochemical methane potential (BMP) or specific methane production (SMP) can be calculated and summarized, including subtraction of the inoculum contribution and normalization by substrate mass. Cumulative production and production rates can be summarized in several different ways (e.g., omitting normalization) using the same function. Biogas quantity and composition can be predicted from substrate composition and additional, optional data. Inoculum and substrate mass can be determined for planning BMP experiments. Finally, first-order models can be fit to measurements in order to extract estimate of ultimate yield and kinetic constants.
License: GPL-2
8 changes: 7 additions & 1 deletion R/FOM.R
Original file line number Diff line number Diff line change
Expand Up @@ -125,7 +125,7 @@ FO2pObj <- function(x, t, y, fit.to = 'yield', t.shift = 0, y.shift = 0, SS = TR

fitFOM <- function(dat, n.pool = 1,
time.name = 'time.d', resp.name = 'cvCH4',
fit.to = 'yield', method = 'LM', abs.err = FALSE, trans = TRUE,
fit.to = 'yield', method = 'Nelder-Mead', abs.err = FALSE, trans = TRUE,
init = if (n.pool == 1) c(B = 'yield', k = 0.5) else c(B = 'yield', f = 0.5, k1 = 0.01, k2 = 0.5),
fixed = NULL, fit.last = FALSE, lower = NULL, upper = NULL,
lag.phase = FALSE) {
Expand Down Expand Up @@ -209,6 +209,10 @@ fitFOM <- function(dat, n.pool = 1,

if (method == 'LM') {

if (!requireNamespace('minpack.lm')) {
stop('You selected method = \'LM\' but the manpack.lm packge is not installed.\nPlease install minpack.lm in order to use this method.')
}

if (n.pool == 1) {

mod <- minpack.lm::nls.lm(par = init,
Expand Down Expand Up @@ -249,6 +253,8 @@ fitFOM <- function(dat, n.pool = 1,

mod <- optim(par = init, fn = FO1pObj, resids = FALSE,
t = t, y = y, t.shift = t.shift, y.shift = y.shift, SS = !abs.err,
fixed = fixed,
fit.last = fit.last,
fit.to = fit.to,
trans = trans,
method = method,
Expand Down
104 changes: 92 additions & 12 deletions man/fitFOM.Rd
Original file line number Diff line number Diff line change
Expand Up @@ -8,25 +8,91 @@
\code{fitFOM} (FOM is for \emph{f}irst \emph{o}rder \emph{m}odel) is a flexible function for fitting first-order models to batch biogas production data, typically from a biochemical methane potential (BMP) test.
}
\usage{
firFOM(dat, n.pool = 1, time.name = 'time.d', resp.name = 'cvCH4',
fit.to = 'yield', method = 'LM', abs.err = FALSE, trans = TRUE,
fitFOM(dat, n.pool = 1, time.name = 'time.d', resp.name = 'cvCH4',
fit.to = 'yield', method = 'Nelder-Mead', abs.err = FALSE, trans = TRUE,
init = if (n.pool == 1) c(B = 'yield', k = 0.5) else c(B = 'yield', f = 0.5, k1 = 0.01, k2 = 0.5),
fixed = NULL, fit.last = FALSE, lower = NULL, upper = NULL, lag.phase = FALSE)
}

%- maybe also "usage" for other objects documented here.
\arguments{
\item{dat}{
a data frame with a column for elapsed time and cumulative response variable.
\item{dat}{
a data frame with columns for elapsed time and cumulative methane yield ("specific methane production" SMP) or another response variable.
}
\item{n.pool}{
Number of substrate pools to include in the model.
1 or 2.
Length-one numeric vector.
}
\item{time.name}{
Name of the column in \code{dat} that has elapsed time.
Length-one character vector.
}
\item{resp.name}{
Name of the column in \code{dat} that has response variable, typically cumulative methane yield ("specific methane production" SMP).
Length-one character vector.
}
\item{fit.to}{
Should fitting be to cumulative yield (\code{'yield'}, default) or the average production rate (\code{'rate*}, calculated as its difference over time)?
Length-one character vector.
}
\item{method}{
Method used to fit the model, i.e., to estimate best-fit parameter values.
Default of \code{'Nelder-Mead'} uses that method via the \code{\link{optim}} function.
The other \code{method}s available for \code{link{optim}} are alternatives.
If \code{'LM'} is used, the \code{nls.lm} function from the minpack.lm package is used.
Length-one character vector.
}
\item{abs.error}{
Should fitting be based on mean absolute error (\code{TRUE}) or sum of squares (\code{FALSE}, default).
Length-one logical vector.
}
\item{trans}{
Should parameter values be transformed for fitting?
If \code{TRUE}, the \code{k} parameter(s) are log10-transformed and (if relevant) \code{f} is transformed with the standard logistic function.
This ensures logical values (positive \code{k}, \code{f} between 0 and 1) and may result in better estimates.
Default is \code{FALSE}.
Length-one logical vector.
}
\item{init}{
Vector of initial parameter estimates.
See defaults for elements.
Length-two or -four named numeric vector.
}
\item{fixed}{
Fixed parameters that should be excluded from optimization.
Named numeric vector.
}
\item{fit.last}{
Set to \code{TRUE} to force fit exactly through final measured observation.
Not recommended.
Length-one logical vector.
}
\item{lwr}{
Optional lower parameter value limits.
Only available with some \code{method}s.
Named numeric vector.
}
\item{upr}{
Optional upper parameter value limits.
Only available with some \code{method}s.
Named numeric vector.
}
\item{lag.phase}{
Should the "lag phase" be excluded from fitting?
This period is defined as all observations prior to maximum average production rate.
Default of \code{FALSE}.
Length-one logical vector.
}
}
\details{
Use for fitting first-order model. See examples.

Use for fitting a first-order model (estimation of best-fit parameter values).
Intended for extracting kinetic constants and maximum methane potential from biochemical methane potential (BMP) test measurements.
}
\value{
A list.
A list with parameter estimates and additional information.
Most useful elements are \code{coefs} and \code{coef.tab} (best-fit parameter values), \code{summ} (a summary that includes model efficiency, error, and convergence information), and \code{pred} (model predicted or fitted values).
}
%\references{
Expand All @@ -40,7 +106,7 @@ firFOM(dat, n.pool = 1, time.name = 'time.d', resp.name = 'cvCH4',
%}
\examples{
# Wide data structure
# First use example data to generate a specific methane potential (SMP) curve
library(biogas)
data('feedVol')
data('feedSetup')
Expand Down Expand Up @@ -68,27 +134,41 @@ mod1$summ
# Add model predictions
s9$cvCH4.pred <- mod1$pred
# And plot
plot(cvCH4 ~ time.d, data = s9, type = 'o')
lines(cvCH4.pred ~ time.d, data = s9, col = 'red')
# Fit to rates instead
mod1b <- fitFOM(s9, n.pool = 1, time.name = 'time.d', resp.name = 'cvCH4', fit.to = 'rate')
mod1b$summ
# Try 2 pools
mod2 <- fitFOM(s9, n.pool = 2, time.name = 'time.d', resp.name = 'cvCH4')
mod2$summ
# First pool effectively ignored in the fit
# Try different method (this one required minpack.lm package)
mod2 <- fitFOM(s9, n.pool = 2, time.name = 'time.d', resp.name = 'cvCH4', method = 'LM')
mod2$summ
# Unfortunately, here is a big effect of method on the result!
s9$cvCH4.pred2 <- mod2$pred
plot(cvCH4 ~ time.d, data = s9, type = 'o')
lines(cvCH4.pred ~ time.d, data = s9, col = 'red')
lines(cvCH4.pred2 ~ time.d, data = s9, col = 'blue')
# Drop lag phase
# Drop (exclude) lag phase
mod3 <- fitFOM(s9, n.pool = 2, time.name = 'time.d', resp.name = 'cvCH4', lag.phase = TRUE)
mod3$summ
s9$cvCH4.pred3 <- mod3$pred
lines(cvCH4.pred3 ~ time.d, data = s9, col = 'green')
lines(cvCH4.pred3 ~ time.d, data = s9, col = 'darkgreen')
}
%% Add one or more standard keywords, see file "KEYWORDS" in the
%% R documentation directory.
\keyword{chron}
\keyword{manip}
\keyword{regression}
\concept{biogas}

0 comments on commit 495f657

Please sign in to comment.