├── .github ├── .gitignore └── ISSUE_TEMPLATE.md ├── .Rinstignore ├── _pkgdown.yml ├── tests ├── testthat │ ├── helper-libs.R │ ├── helper-rmse_DO.R │ ├── test-calc_depth.R │ ├── test-calc_DO.R │ ├── test-distribs.R │ └── test-metab-class.R └── testthat.R ├── docs ├── reference │ └── Rplot001.png ├── articles │ ├── models_mle_files │ │ └── figure-html │ │ │ ├── plot_metab1-1.png │ │ │ └── plot_metab2-1.png │ ├── data_prep_files │ │ └── figure-html │ │ │ ├── viz_inputs_DO-1.png │ │ │ └── viz_inputs_other-1.png │ ├── get_started_files │ │ └── figure-html │ │ │ ├── bayes_pdo_fig-1.png │ │ │ ├── bayes_pred_fig-1.png │ │ │ └── unnamed-chunk-3-1.png │ ├── gpp_er_eqs_files │ │ └── figure-html │ │ │ ├── unnamed-chunk-7-1.png │ │ │ ├── unnamed-chunk-9-1.png │ │ │ └── unnamed-chunk-9-2.png │ ├── ode_methods_files │ │ └── figure-html │ │ │ ├── unnamed-chunk-8-1.png │ │ │ └── unnamed-chunk-9-1.png │ └── simulations_files │ │ └── figure-html │ │ ├── unnamed-chunk-11-1.png │ │ ├── unnamed-chunk-11-2.png │ │ ├── unnamed-chunk-13-1.png │ │ ├── unnamed-chunk-13-2.png │ │ ├── unnamed-chunk-14-1.png │ │ ├── unnamed-chunk-14-2.png │ │ ├── unnamed-chunk-17-1.png │ │ ├── unnamed-chunk-21-1.png │ │ ├── unnamed-chunk-22-1.png │ │ └── unnamed-chunk-27-1.png ├── deps │ └── data-deps.txt ├── pkgdown.yml └── link.svg ├── inst ├── extdata │ ├── brandywine.rds │ ├── b_np_pcpi_eu_ko_v1.stan │ └── KfQ_procobserr.jags ├── CITATION └── doc │ ├── ode_methods.R │ ├── get_started.R │ └── gpp_er_eqs.R ├── .Rbuildignore ├── R ├── deprecated.R ├── mm_locate_filename.R ├── calc_is_daytime.R ├── mm_filter_hours.R ├── streamMetabolizer-deprecated.R ├── calc_sun_rise_set.R ├── revise.R ├── calc_solar_time.R ├── mm_sd_to_ci.R ├── mm_validate_name.R ├── calc_DO_deficit.R ├── metab_inputs.R ├── load_spring_creek.R ├── lookup_usgs_elevation.R ├── convert_PAR_to_SW.R ├── calc_light.R ├── metab_model.predict_DO.R ├── mm_check_mcmc_file.R ├── calc_DO_sat.R ├── calc_depth.R ├── specs-class.R ├── calc_velocity.R ├── mm_filter_dates.R ├── streamMetabolizer.R ├── calc_air_pressure.R └── metab_model.get_param_names.R ├── man ├── zz_build_docs.Rd ├── add_specs_class.Rd ├── show-specs-method.Rd ├── to_degrees.Rd ├── to_radians.Rd ├── zz_tabular.Rd ├── unitted_deprecate_warn.Rd ├── print.specs.Rd ├── show-metab_model-method.Rd ├── pretty_print_ddat.Rd ├── summarize_stopwarn_msgs.Rd ├── print.logs_metab.Rd ├── define_pkg_env.Rd ├── mm_check_mcmc_file.Rd ├── print_specs.Rd ├── load_french_creek.Rd ├── load_spring_creek.Rd ├── metab_sim-class.Rd ├── mm_generate_mcmc_files.Rd ├── metab_bayes-class.Rd ├── metab_night-class.Rd ├── mm_sd_to_ci.Rd ├── format_mcmc_mat_nosplit.Rd ├── convert_localtime_to_UTC.Rd ├── metab_mle-class.Rd ├── lookup_timezone.Rd ├── mm_locate_filename.Rd ├── metab_inputs.Rd ├── convert_date_to_doyhr.Rd ├── format_mcmc_mat_split.Rd ├── convert_k600_to_kGAS.Rd ├── metab_Kmodel-class.Rd ├── revise.Rd ├── convert_kGAS_to_k600.Rd ├── calc_sun_rise_set.Rd ├── get_log.Rd ├── compress_msgs.Rd ├── mm_filter_hours.Rd ├── mm_check_mcmc_files.Rd ├── convert_SW_to_PAR.Rd ├── convert_PAR_to_SW.Rd ├── get_mcmc_data.Rd ├── convert_doyhr_to_date.Rd ├── calc_air_pressure.Rd ├── calc_solar_time.Rd ├── sim_pred_Kb.Rd ├── calc_is_daytime.Rd ├── load_french_creek_std.Rd ├── calc_hour_angle.Rd ├── lookup_usgs_elevation.Rd ├── get_data.Rd ├── streamMetabolizer-deprecated.Rd ├── get_info.Rd ├── Kmodel_aggregate_day.Rd ├── get_data_daily.Rd ├── get_fit.Rd ├── plot_metab_preds.Rd ├── get_version.Rd ├── get_fitting_time.Rd ├── get_specs.Rd ├── metab_model-class.Rd ├── get_mcmc.Rd ├── mm_parse_name.Rd ├── bayes_allply.Rd ├── lookup_google_timezone.Rd ├── calc_declination_angle.Rd ├── mm_validate_data.Rd ├── convert_UTC_to_localtime.Rd ├── mm_valid_names.Rd ├── sim_get_par.Rd ├── convert_solartime_to_UTC.Rd ├── calc_light.Rd ├── calc_DO_sat.Rd ├── calc_depth.Rd ├── convert_UTC_to_solartime.Rd ├── mm_validate_name.Rd ├── sim_Kb.Rd ├── runstan_bayes.Rd ├── calc_velocity.Rd ├── calc_DO_deficit.Rd ├── mm_filter_dates.Rd ├── prepdata_bayes.Rd ├── metab_model_interface.Rd ├── load_french_creek_std_mle.Rd ├── metab_model.Rd ├── calc_zenith_angle.Rd ├── bayes_1ply.Rd ├── mm_predict_DO_1ply.Rd ├── plot_DO_preds.Rd ├── plot_distribs.Rd ├── metab_night_predict_1ply.Rd ├── get_param_names.Rd ├── calc_solar_insolation.Rd ├── mle_1ply.Rd ├── mm_get_timestep.Rd ├── mm_predict_metab_1ply.Rd ├── create_calc_NLL.Rd ├── Kmodel_allply.Rd ├── predict_metab.metab_Kmodel.Rd ├── data_metab.Rd └── metab_night.Rd ├── .gitignore ├── DISCLAIMER.md ├── CONTRIBUTING.md ├── code.json ├── LICENSE.md ├── CODE_OF_CONDUCT.md └── vignettes └── installation.Rmd /.github/.gitignore: -------------------------------------------------------------------------------- 1 | *.html 2 | -------------------------------------------------------------------------------- /.Rinstignore: -------------------------------------------------------------------------------- 1 | ^inst/models/.*\.stanrda$ 2 | ^inst/models/.*\.stanrds$ 3 | -------------------------------------------------------------------------------- /_pkgdown.yml: -------------------------------------------------------------------------------- 1 | url: http://usgs-r.github.io/streamMetabolizer/ 2 | template: 3 | bootstrap: 5 4 | 5 | -------------------------------------------------------------------------------- /tests/testthat/helper-libs.R: -------------------------------------------------------------------------------- 1 | suppressPackageStartupMessages(library(dplyr)) 2 | library(ggplot2) 3 | -------------------------------------------------------------------------------- /docs/reference/Rplot001.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DOI-USGS/streamMetabolizer/HEAD/docs/reference/Rplot001.png -------------------------------------------------------------------------------- /inst/extdata/brandywine.rds: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DOI-USGS/streamMetabolizer/HEAD/inst/extdata/brandywine.rds -------------------------------------------------------------------------------- /tests/testthat.R: -------------------------------------------------------------------------------- 1 | Sys.setenv("R_TESTS" = "") 2 | library(testthat) 3 | test_check('streamMetabolizer', reporter="summary") 4 | -------------------------------------------------------------------------------- /docs/articles/models_mle_files/figure-html/plot_metab1-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DOI-USGS/streamMetabolizer/HEAD/docs/articles/models_mle_files/figure-html/plot_metab1-1.png -------------------------------------------------------------------------------- /docs/articles/models_mle_files/figure-html/plot_metab2-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DOI-USGS/streamMetabolizer/HEAD/docs/articles/models_mle_files/figure-html/plot_metab2-1.png -------------------------------------------------------------------------------- /docs/articles/data_prep_files/figure-html/viz_inputs_DO-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DOI-USGS/streamMetabolizer/HEAD/docs/articles/data_prep_files/figure-html/viz_inputs_DO-1.png -------------------------------------------------------------------------------- /docs/articles/get_started_files/figure-html/bayes_pdo_fig-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DOI-USGS/streamMetabolizer/HEAD/docs/articles/get_started_files/figure-html/bayes_pdo_fig-1.png -------------------------------------------------------------------------------- /docs/articles/data_prep_files/figure-html/viz_inputs_other-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DOI-USGS/streamMetabolizer/HEAD/docs/articles/data_prep_files/figure-html/viz_inputs_other-1.png -------------------------------------------------------------------------------- /docs/articles/get_started_files/figure-html/bayes_pred_fig-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DOI-USGS/streamMetabolizer/HEAD/docs/articles/get_started_files/figure-html/bayes_pred_fig-1.png -------------------------------------------------------------------------------- /docs/articles/get_started_files/figure-html/unnamed-chunk-3-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DOI-USGS/streamMetabolizer/HEAD/docs/articles/get_started_files/figure-html/unnamed-chunk-3-1.png -------------------------------------------------------------------------------- /docs/articles/gpp_er_eqs_files/figure-html/unnamed-chunk-7-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DOI-USGS/streamMetabolizer/HEAD/docs/articles/gpp_er_eqs_files/figure-html/unnamed-chunk-7-1.png -------------------------------------------------------------------------------- /docs/articles/gpp_er_eqs_files/figure-html/unnamed-chunk-9-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DOI-USGS/streamMetabolizer/HEAD/docs/articles/gpp_er_eqs_files/figure-html/unnamed-chunk-9-1.png -------------------------------------------------------------------------------- /docs/articles/gpp_er_eqs_files/figure-html/unnamed-chunk-9-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DOI-USGS/streamMetabolizer/HEAD/docs/articles/gpp_er_eqs_files/figure-html/unnamed-chunk-9-2.png -------------------------------------------------------------------------------- /docs/articles/ode_methods_files/figure-html/unnamed-chunk-8-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DOI-USGS/streamMetabolizer/HEAD/docs/articles/ode_methods_files/figure-html/unnamed-chunk-8-1.png -------------------------------------------------------------------------------- /docs/articles/ode_methods_files/figure-html/unnamed-chunk-9-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DOI-USGS/streamMetabolizer/HEAD/docs/articles/ode_methods_files/figure-html/unnamed-chunk-9-1.png -------------------------------------------------------------------------------- /docs/articles/simulations_files/figure-html/unnamed-chunk-11-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DOI-USGS/streamMetabolizer/HEAD/docs/articles/simulations_files/figure-html/unnamed-chunk-11-1.png -------------------------------------------------------------------------------- /docs/articles/simulations_files/figure-html/unnamed-chunk-11-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DOI-USGS/streamMetabolizer/HEAD/docs/articles/simulations_files/figure-html/unnamed-chunk-11-2.png -------------------------------------------------------------------------------- /docs/articles/simulations_files/figure-html/unnamed-chunk-13-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DOI-USGS/streamMetabolizer/HEAD/docs/articles/simulations_files/figure-html/unnamed-chunk-13-1.png -------------------------------------------------------------------------------- /docs/articles/simulations_files/figure-html/unnamed-chunk-13-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DOI-USGS/streamMetabolizer/HEAD/docs/articles/simulations_files/figure-html/unnamed-chunk-13-2.png -------------------------------------------------------------------------------- /docs/articles/simulations_files/figure-html/unnamed-chunk-14-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DOI-USGS/streamMetabolizer/HEAD/docs/articles/simulations_files/figure-html/unnamed-chunk-14-1.png -------------------------------------------------------------------------------- /docs/articles/simulations_files/figure-html/unnamed-chunk-14-2.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DOI-USGS/streamMetabolizer/HEAD/docs/articles/simulations_files/figure-html/unnamed-chunk-14-2.png -------------------------------------------------------------------------------- /docs/articles/simulations_files/figure-html/unnamed-chunk-17-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DOI-USGS/streamMetabolizer/HEAD/docs/articles/simulations_files/figure-html/unnamed-chunk-17-1.png -------------------------------------------------------------------------------- /docs/articles/simulations_files/figure-html/unnamed-chunk-21-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DOI-USGS/streamMetabolizer/HEAD/docs/articles/simulations_files/figure-html/unnamed-chunk-21-1.png -------------------------------------------------------------------------------- /docs/articles/simulations_files/figure-html/unnamed-chunk-22-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DOI-USGS/streamMetabolizer/HEAD/docs/articles/simulations_files/figure-html/unnamed-chunk-22-1.png -------------------------------------------------------------------------------- /docs/articles/simulations_files/figure-html/unnamed-chunk-27-1.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/DOI-USGS/streamMetabolizer/HEAD/docs/articles/simulations_files/figure-html/unnamed-chunk-27-1.png -------------------------------------------------------------------------------- /tests/testthat/helper-rmse_DO.R: -------------------------------------------------------------------------------- 1 | #' Calculate the RMSE of DO predictions relative to observations 2 | #' 3 | #' @param DO_preds predictions from predict_DO() 4 | rmse_DO <- function(DO_preds) { 5 | sqrt(mean((DO_preds$DO.obs - DO_preds$DO.mod)^2, na.rm=TRUE)) 6 | } -------------------------------------------------------------------------------- /.Rbuildignore: -------------------------------------------------------------------------------- 1 | ^.git$ 2 | ^.github$ 3 | ^.*\.Rproj$ 4 | ^\.Rproj\.user$ 5 | ^\.travis\.yml$ 6 | ^appveyor\.yml$ 7 | man-roxygen 8 | temp 9 | ^doc$ 10 | ^Meta$ 11 | ^_pkgdown\.yml$ 12 | ^docs$ 13 | ^pkgdown$ 14 | ^CONDUCT\.md$ 15 | ^streamMetabolizer\.Rproj$ 16 | ^\.github$ 17 | -------------------------------------------------------------------------------- /docs/deps/data-deps.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | -------------------------------------------------------------------------------- /R/deprecated.R: -------------------------------------------------------------------------------- 1 | #' Warn about deprecation of a units-related argument or function 2 | #' @keywords internal 3 | unitted_deprecate_warn <- function(what) { 4 | deprecate_warn( 5 | what = sprintf('streamMetabolizer::%s', what), 6 | when = "0.12.0", 7 | details = "streamMetabolizer will someday stop using units and the unitted package.") 8 | } 9 | -------------------------------------------------------------------------------- /man/zz_build_docs.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/zz_build_docs.R 3 | \name{zz_build_docs} 4 | \alias{zz_build_docs} 5 | \title{Generate doc text for the `metab()` documentation} 6 | \usage{ 7 | zz_build_docs() 8 | } 9 | \description{ 10 | Results get written to man-roxygen/metab_data.R 11 | } 12 | \keyword{internal} 13 | -------------------------------------------------------------------------------- /man/add_specs_class.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/specs-class.R 3 | \name{add_specs_class} 4 | \alias{add_specs_class} 5 | \title{Add the metabolism model specifications class to a list} 6 | \usage{ 7 | add_specs_class(specs_list) 8 | } 9 | \description{ 10 | Add the metabolism model specifications class to a list 11 | } 12 | \keyword{internal} 13 | -------------------------------------------------------------------------------- /man/show-specs-method.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/specs-class.R 3 | \name{show,specs-method} 4 | \alias{show,specs-method} 5 | \title{Display the specs object} 6 | \usage{ 7 | \S4method{show}{specs}(object) 8 | } 9 | \arguments{ 10 | \item{object}{specs list to be displayed.} 11 | } 12 | \description{ 13 | Print a specs object to the console. 14 | } 15 | -------------------------------------------------------------------------------- /man/to_degrees.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/calc_solar_insolation.R 3 | \name{to_degrees} 4 | \alias{to_degrees} 5 | \title{Convert radians to degrees} 6 | \usage{ 7 | to_degrees(radians) 8 | } 9 | \arguments{ 10 | \item{radians}{angle in radians} 11 | } 12 | \value{ 13 | angle in degrees 14 | } 15 | \description{ 16 | Convert radians to degrees 17 | } 18 | -------------------------------------------------------------------------------- /man/to_radians.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/calc_solar_insolation.R 3 | \name{to_radians} 4 | \alias{to_radians} 5 | \title{Convert degrees to radians} 6 | \usage{ 7 | to_radians(degrees) 8 | } 9 | \arguments{ 10 | \item{degrees}{angle in degrees} 11 | } 12 | \value{ 13 | angle in radians 14 | } 15 | \description{ 16 | Convert degrees to radians 17 | } 18 | -------------------------------------------------------------------------------- /man/zz_tabular.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/zz_build_docs.R 3 | \name{zz_tabular} 4 | \alias{zz_tabular} 5 | \title{Format a data.frame for inclusion in a roxygen header} 6 | \usage{ 7 | zz_tabular(df, bold_headers = TRUE, code = FALSE, ...) 8 | } 9 | \description{ 10 | Modified from Hadley Wickham's function at http://r-pkgs.had.co.nz/man.html 11 | } 12 | \keyword{internal} 13 | -------------------------------------------------------------------------------- /man/unitted_deprecate_warn.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/deprecated.R 3 | \name{unitted_deprecate_warn} 4 | \alias{unitted_deprecate_warn} 5 | \title{Warn about deprecation of a units-related argument or function} 6 | \usage{ 7 | unitted_deprecate_warn(what) 8 | } 9 | \description{ 10 | Warn about deprecation of a units-related argument or function 11 | } 12 | \keyword{internal} 13 | -------------------------------------------------------------------------------- /man/print.specs.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/specs-class.R 3 | \name{print.specs} 4 | \alias{print.specs} 5 | \title{Display the specs object} 6 | \usage{ 7 | \method{print}{specs}(x, ...) 8 | } 9 | \arguments{ 10 | \item{x}{specs list to be displayed.} 11 | 12 | \item{...}{additional arguments passed to inner functions} 13 | } 14 | \description{ 15 | Print a specs object to the console. 16 | } 17 | -------------------------------------------------------------------------------- /man/show-metab_model-method.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_model.show.R 3 | \name{show,metab_model-method} 4 | \alias{show,metab_model-method} 5 | \title{Display the metab_model object} 6 | \usage{ 7 | \S4method{show}{metab_model}(object) 8 | } 9 | \arguments{ 10 | \item{object}{metab_model to be displayed.} 11 | } 12 | \description{ 13 | Print a metab_model object to the console. 14 | } 15 | -------------------------------------------------------------------------------- /man/pretty_print_ddat.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_model.show.R 3 | \name{pretty_print_ddat} 4 | \alias{pretty_print_ddat} 5 | \title{Format and print a summary of data frame of daily values} 6 | \usage{ 7 | pretty_print_ddat(ddat, msg.col) 8 | } 9 | \description{ 10 | Compress error and warning messages into one column and only print the first 11 | few rows of data 12 | } 13 | \keyword{internal} 14 | -------------------------------------------------------------------------------- /man/summarize_stopwarn_msgs.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_model.show.R 3 | \name{summarize_stopwarn_msgs} 4 | \alias{summarize_stopwarn_msgs} 5 | \title{Summarize a vector of warning or error messages} 6 | \usage{ 7 | summarize_stopwarn_msgs(msgs) 8 | } 9 | \description{ 10 | Split ;-separated warning/error messages and condense into counts of each 11 | unique message 12 | } 13 | \keyword{internal} 14 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # History files 2 | .Rhistory 3 | .Rapp.history 4 | # Example code in package build process 5 | *-Ex.R 6 | # RStudio files 7 | .Rproj.user/ 8 | # Produced vignettes 9 | vignettes/*.html 10 | vignettes/*.pdf 11 | .Rproj.user 12 | *.Rproj 13 | *.DS_Store 14 | # Side-effects of tests 15 | tests/testthat/Rplots.pdf 16 | # Temporary files 17 | temp 18 | # Machine-specific files 19 | inst/models/*.stanrda 20 | inst/models/*.stanrds 21 | inst/doc 22 | doc 23 | Meta 24 | -------------------------------------------------------------------------------- /man/print.logs_metab.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_bayes.R 3 | \name{print.logs_metab} 4 | \alias{print.logs_metab} 5 | \title{Print metab logs} 6 | \usage{ 7 | \method{print}{logs_metab}(x, ...) 8 | } 9 | \arguments{ 10 | \item{x}{an object to print} 11 | 12 | \item{...}{ignored; included only for compatibility with `base::print`} 13 | } 14 | \description{ 15 | Print metab model compilation and/or fitting logs 16 | } 17 | -------------------------------------------------------------------------------- /man/define_pkg_env.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/01-onLoad.R 3 | \name{define_pkg_env} 4 | \alias{define_pkg_env} 5 | \title{Define a package environment for storing data specific to a project during an 6 | R session} 7 | \usage{ 8 | define_pkg_env() 9 | } 10 | \value{ 11 | the package environment 12 | } 13 | \description{ 14 | Define a package environment for storing data specific to a project during an 15 | R session 16 | } 17 | \keyword{internal} 18 | -------------------------------------------------------------------------------- /man/mm_check_mcmc_file.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mm_check_mcmc_file.R 3 | \name{mm_check_mcmc_file} 4 | \alias{mm_check_mcmc_file} 5 | \title{Use an engine-specific function to check the model syntax} 6 | \usage{ 7 | mm_check_mcmc_file(model_file) 8 | } 9 | \arguments{ 10 | \item{model_file}{the file path of the model file to check; the extension 11 | will be used to determine which engine to use for checking.} 12 | } 13 | \description{ 14 | Use an engine-specific function to check the model syntax 15 | } 16 | \keyword{internal} 17 | -------------------------------------------------------------------------------- /docs/pkgdown.yml: -------------------------------------------------------------------------------- 1 | pandoc: 3.1.1 2 | pkgdown: 2.0.7 3 | pkgdown_sha: ~ 4 | articles: 5 | data_prep: data_prep.html 6 | get_started: get_started.html 7 | gpp_er_eqs: gpp_er_eqs.html 8 | installation: installation.html 9 | model_structures: model_structures.html 10 | models_bayes: models_bayes.html 11 | models_mle: models_mle.html 12 | ode_methods: ode_methods.html 13 | simulations: simulations.html 14 | last_built: 2023-07-29T16:37Z 15 | urls: 16 | reference: http://usgs-r.github.io/streamMetabolizer/reference 17 | article: http://usgs-r.github.io/streamMetabolizer/articles 18 | 19 | -------------------------------------------------------------------------------- /man/print_specs.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/specs-class.R 3 | \name{print_specs} 4 | \alias{print_specs} 5 | \title{Display the specs object} 6 | \usage{ 7 | print_specs(object, header = "Model specifications:\\n", prefix = " ") 8 | } 9 | \arguments{ 10 | \item{object}{specs list to be displayed.} 11 | 12 | \item{header}{line to be catted at start of printout} 13 | 14 | \item{prefix}{text to prepend to the start of each line that follows the 15 | header} 16 | } 17 | \description{ 18 | Print a specs object to the console. 19 | } 20 | \keyword{internal} 21 | -------------------------------------------------------------------------------- /man/load_french_creek.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/load_french_creek.R 3 | \name{load_french_creek} 4 | \alias{load_french_creek} 5 | \title{Load a short dataset from French Creek} 6 | \usage{ 7 | load_french_creek(attach.units = deprecated()) 8 | } 9 | \arguments{ 10 | \item{attach.units}{(deprecated, effectively FALSE in future) logical, 11 | default TRUE for backward compatibility. Should units be attached to the 12 | data.frame?} 13 | } 14 | \value{ 15 | a data.frame, unitted if attach.units==TRUE 16 | } 17 | \description{ 18 | Load a short dataset from French Creek 19 | } 20 | -------------------------------------------------------------------------------- /man/load_spring_creek.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/load_spring_creek.R 3 | \name{load_spring_creek} 4 | \alias{load_spring_creek} 5 | \title{Load a short dataset from Spring Creek} 6 | \usage{ 7 | load_spring_creek(attach.units = deprecated()) 8 | } 9 | \arguments{ 10 | \item{attach.units}{(deprecated, effectively FALSE in future) logical, 11 | default TRUE for backward compatibility. Should units be attached to the 12 | data.frame?} 13 | } 14 | \value{ 15 | a data.frame, unitted if attach.units==TRUE 16 | } 17 | \description{ 18 | Load a short dataset from Spring Creek 19 | } 20 | -------------------------------------------------------------------------------- /man/metab_sim-class.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_sim.R 3 | \docType{class} 4 | \name{metab_sim-class} 5 | \alias{metab_sim-class} 6 | \title{Data simulator} 7 | \description{ 8 | \code{metab_sim} models generate a DO time series from other input data, 9 | including GPP, ER, and K600 values 10 | } 11 | \seealso{ 12 | Other metab.model.classes: 13 | \code{\link{metab_Kmodel-class}}, 14 | \code{\link{metab_bayes-class}}, 15 | \code{\link{metab_mle-class}}, 16 | \code{\link{metab_model-class}}, 17 | \code{\link{metab_night-class}} 18 | } 19 | \concept{metab.model.classes} 20 | -------------------------------------------------------------------------------- /man/mm_generate_mcmc_files.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mm_generate_mcmc_file.R 3 | \name{mm_generate_mcmc_files} 4 | \alias{mm_generate_mcmc_files} 5 | \title{Generate MCMC code files with all of the desired combinations of features} 6 | \usage{ 7 | mm_generate_mcmc_files() 8 | } 9 | \description{ 10 | This function gets run on package build and creates every model within the 11 | set of factorial combinations of arguments to mm_generate_mcmc_file, with the 12 | exception of the one pair of incompatible arguments (err_obs_iid=F && 13 | deficit_src='DO_mod') 14 | } 15 | \keyword{internal} 16 | -------------------------------------------------------------------------------- /man/metab_bayes-class.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_bayes.R 3 | \docType{class} 4 | \name{metab_bayes-class} 5 | \alias{metab_bayes-class} 6 | \title{Metabolism model fitted by Bayesian MCMC} 7 | \description{ 8 | \code{metab_bayes} models use Bayesian MCMC methods to fit values of GPP, ER, 9 | and K for a given DO curve. 10 | } 11 | \seealso{ 12 | Other metab.model.classes: 13 | \code{\link{metab_Kmodel-class}}, 14 | \code{\link{metab_mle-class}}, 15 | \code{\link{metab_model-class}}, 16 | \code{\link{metab_night-class}}, 17 | \code{\link{metab_sim-class}} 18 | } 19 | \concept{metab.model.classes} 20 | -------------------------------------------------------------------------------- /man/metab_night-class.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_night.R 3 | \docType{class} 4 | \name{metab_night-class} 5 | \alias{metab_night-class} 6 | \title{Reaeration model fitted by nighttime regression} 7 | \description{ 8 | \code{metab_night} models use nighttime regression to fit values of K for a 9 | given DO time series. 10 | } 11 | \seealso{ 12 | Other metab.model.classes: 13 | \code{\link{metab_Kmodel-class}}, 14 | \code{\link{metab_bayes-class}}, 15 | \code{\link{metab_mle-class}}, 16 | \code{\link{metab_model-class}}, 17 | \code{\link{metab_sim-class}} 18 | } 19 | \concept{metab.model.classes} 20 | -------------------------------------------------------------------------------- /man/mm_sd_to_ci.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mm_sd_to_ci.R 3 | \name{mm_sd_to_ci} 4 | \alias{mm_sd_to_ci} 5 | \title{Convert SD columns into CI columns in a data.frame} 6 | \usage{ 7 | mm_sd_to_ci(data, alpha = 0.05) 8 | } 9 | \arguments{ 10 | \item{data}{a data.frame with 1+ pairs of columns named var and var.sd 11 | (where var can be anything)} 12 | 13 | \item{alpha}{the desired significance level described by the confidence 14 | interval} 15 | } 16 | \description{ 17 | Convert data with var and var.sd columns into data with var, var.lower, and 18 | var.upper columns 19 | } 20 | \keyword{internal} 21 | -------------------------------------------------------------------------------- /DISCLAIMER.md: -------------------------------------------------------------------------------- 1 | ## Disclaimer 2 | 3 | This software is preliminary or provisional and is subject to revision. It is 4 | being provided to meet the need for timely best science. The software has not 5 | received final approval by the U.S. Geological Survey (USGS). No warranty, 6 | expressed or implied, is made by the USGS or the U.S. Government as to the 7 | functionality of the software and related material nor shall the fact of release 8 | constitute any such warranty. The software is provided on the condition that 9 | neither the USGS nor the U.S. Government shall be held liable for any damages 10 | resulting from the authorized or unauthorized use of the software. 11 | -------------------------------------------------------------------------------- /man/format_mcmc_mat_nosplit.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_bayes.R 3 | \name{format_mcmc_mat_nosplit} 4 | \alias{format_mcmc_mat_nosplit} 5 | \title{Format MCMC output into a list of data.frames} 6 | \usage{ 7 | format_mcmc_mat_nosplit( 8 | mcmc_mat, 9 | data_list_d, 10 | data_list_n, 11 | model_name, 12 | keep_mcmc, 13 | runmcmc_out 14 | ) 15 | } 16 | \arguments{ 17 | \item{mcmc_mat}{matrix as extracted from Stan} 18 | } 19 | \description{ 20 | For multi-day or unsplit models. Formats output into a list of data.frames, 21 | one per unique number of nodes sharing a variable name 22 | } 23 | \keyword{internal} 24 | -------------------------------------------------------------------------------- /man/convert_localtime_to_UTC.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/convert_UTC_to_localtime.R 3 | \name{convert_localtime_to_UTC} 4 | \alias{convert_localtime_to_UTC} 5 | \title{Convert time from local time to UTC.} 6 | \usage{ 7 | convert_localtime_to_UTC(local.time) 8 | } 9 | \arguments{ 10 | \item{local.time}{POSIXct date+time of interest, already in local time as 11 | specified by the tz attribute} 12 | } 13 | \description{ 14 | Convert time from local time (either standard or with daylight savings) to 15 | UTC. 16 | } 17 | \references{ 18 | https://stackoverflow.com/questions/23414340/convert-to-local-time-zone-using-latitude-and-longitude 19 | } 20 | -------------------------------------------------------------------------------- /man/metab_mle-class.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_mle.R 3 | \docType{class} 4 | \name{metab_mle-class} 5 | \alias{metab_mle-class} 6 | \title{Metabolism model fitted by maximum likelihood estimation} 7 | \description{ 8 | \code{metab_mle} models use non-linear minimization of the negative log 9 | likelihood to fit values of GPP, ER, and K for a given DO curve. 10 | } 11 | \seealso{ 12 | Other metab.model.classes: 13 | \code{\link{metab_Kmodel-class}}, 14 | \code{\link{metab_bayes-class}}, 15 | \code{\link{metab_model-class}}, 16 | \code{\link{metab_night-class}}, 17 | \code{\link{metab_sim-class}} 18 | } 19 | \concept{metab.model.classes} 20 | -------------------------------------------------------------------------------- /CONTRIBUTING.md: -------------------------------------------------------------------------------- 1 | ## Contributing 2 | 3 | Contributions are welcome from the community. Questions can be asked on the 4 | [issues page](https://github.com/USGS-R/streamMetabolizer/issues). 5 | Before creating a new issue, please take a moment to search 6 | and make sure a similar issue does not already exist. If one does exist, you 7 | can comment (most simply even with just a `:+1:`) to show your support for that 8 | issue. 9 | 10 | If you have direct contributions you would like considered for incorporation 11 | into the project, you can 12 | [fork this repository](https://help.github.com/articles/fork-a-repo/) and 13 | [submit a pull request](https://help.github.com/articles/about-pull-requests/) 14 | for review. 15 | -------------------------------------------------------------------------------- /man/lookup_timezone.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/lookup_timezone.R 3 | \name{lookup_timezone} 4 | \alias{lookup_timezone} 5 | \title{Determine the local time zone from the coordinates} 6 | \usage{ 7 | lookup_timezone(latitude, longitude) 8 | } 9 | \arguments{ 10 | \item{latitude}{degrees latitude (positive for north) of the location to look 11 | up.} 12 | 13 | \item{longitude}{degrees longitude (positive for east) of the location to 14 | look up.} 15 | } 16 | \description{ 17 | Uses the Google API (and/or the package cache) to determine the local 18 | timezone name, offset, and DST offset of a site 19 | } 20 | \examples{ 21 | lookup_timezone(41.33, -106.3) 22 | } 23 | -------------------------------------------------------------------------------- /man/mm_locate_filename.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mm_locate_filename.R 3 | \name{mm_locate_filename} 4 | \alias{mm_locate_filename} 5 | \title{Look for a model file} 6 | \usage{ 7 | mm_locate_filename(model_name) 8 | } 9 | \arguments{ 10 | \item{model_name}{a model file in the 'models' folder of the 11 | streamMetabolizer package or a relative or absolute file path of a model 12 | file} 13 | } 14 | \value{ 15 | a file path if the file exists or an error otherwise 16 | } 17 | \description{ 18 | Looks first in the models folder of the streamMetabolizer package, second 19 | along the relative or absolute file path given by model_name 20 | } 21 | \keyword{internal} 22 | -------------------------------------------------------------------------------- /man/metab_inputs.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_inputs.R 3 | \name{metab_inputs} 4 | \alias{metab_inputs} 5 | \title{Describe the requirements for an argument to metab()} 6 | \usage{ 7 | metab_inputs( 8 | type = c("bayes", "mle", "night", "Kmodel", "sim"), 9 | input = c("specs", "data", "data_daily", "info") 10 | ) 11 | } 12 | \arguments{ 13 | \item{type}{the type of model you want to fit} 14 | 15 | \item{input}{the name of an argument to pass into metab()} 16 | } 17 | \description{ 18 | Describe the requirements for an argument to metab() 19 | } 20 | \examples{ 21 | metab_inputs('night','specs') 22 | metab_inputs('bayes','data') 23 | metab_inputs('Kmodel','data_daily') 24 | metab_inputs('mle','info') 25 | } 26 | -------------------------------------------------------------------------------- /man/convert_date_to_doyhr.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/convert_date_to_doyhr.R 3 | \name{convert_date_to_doyhr} 4 | \alias{convert_date_to_doyhr} 5 | \title{Convert a date to a day of year (1-366) with decimal hours} 6 | \usage{ 7 | convert_date_to_doyhr(date) 8 | } 9 | \arguments{ 10 | \item{date}{A datetime object as POSIXct or POSIXt} 11 | } 12 | \value{ 13 | Numeric value expressing the date as the number of days, with decimal 14 | hours, since 00:00 of December 31 of the preceding year (i.e., January 1st 15 | at 00:01 is ~1.01) 16 | } 17 | \description{ 18 | Inspired by / copied from LakeMetabolizer date2doy 19 | } 20 | \examples{ 21 | streamMetabolizer:::convert_date_to_doyhr(as.POSIXct("2015-02-03 12:01:00 UTC")) 22 | } 23 | -------------------------------------------------------------------------------- /man/format_mcmc_mat_split.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_bayes.R 3 | \name{format_mcmc_mat_split} 4 | \alias{format_mcmc_mat_split} 5 | \title{Format MCMC output into a one-row data.frame} 6 | \usage{ 7 | format_mcmc_mat_split( 8 | mcmc_mat, 9 | names_params, 10 | names_stats, 11 | keep_mcmc, 12 | runmcmc_out 13 | ) 14 | } 15 | \arguments{ 16 | \item{mcmc_mat}{matrix as extracted from Stan} 17 | 18 | \item{names_params}{character vector of the names of the parameters} 19 | 20 | \item{names_stats}{character vector of the names of the statistics} 21 | } 22 | \description{ 23 | For split_dates models. Formats output into a one-row data.frame for 24 | row-binding with other such data.frames 25 | } 26 | \keyword{internal} 27 | -------------------------------------------------------------------------------- /man/convert_k600_to_kGAS.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/convert_k600_to_kGAS.R 3 | \name{convert_k600_to_kGAS} 4 | \alias{convert_k600_to_kGAS} 5 | \title{Returns the gas exchange velocity for gas of interest w/ no unit conversions} 6 | \usage{ 7 | convert_k600_to_kGAS(k600, temperature, gas = "O2") 8 | } 9 | \arguments{ 10 | \item{k600}{k600 as vector of numbers or single number} 11 | 12 | \item{temperature}{Water temperature (deg C) as vector array of numbers or single number} 13 | 14 | \item{gas}{gas for conversion, as string (e.g., 'CO2' or 'O2')} 15 | } 16 | \value{ 17 | Numeric value of gas exchange velocity for gas 18 | } 19 | \description{ 20 | Returns the gas exchange velocity for gas of interest w/ no unit conversions 21 | } 22 | -------------------------------------------------------------------------------- /man/metab_Kmodel-class.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_Kmodel.R 3 | \docType{class} 4 | \name{metab_Kmodel-class} 5 | \alias{metab_Kmodel-class} 6 | \title{Interpolation model of daily K for metabolism} 7 | \description{ 8 | \code{metab_Kmodel} models use initial daily estimates of K, along with 9 | predictors such as Q (discharge.daily) or U (velocity.daily) or T (time) to leverage all 10 | available data to reach better, less variable daily estimates of K 11 | } 12 | \seealso{ 13 | Other metab.model.classes: 14 | \code{\link{metab_bayes-class}}, 15 | \code{\link{metab_mle-class}}, 16 | \code{\link{metab_model-class}}, 17 | \code{\link{metab_night-class}}, 18 | \code{\link{metab_sim-class}} 19 | } 20 | \concept{metab.model.classes} 21 | -------------------------------------------------------------------------------- /man/revise.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/revise.R 3 | \name{revise} 4 | \alias{revise} 5 | \title{Change or add named elements of a list} 6 | \usage{ 7 | revise(specs, ..., delete) 8 | } 9 | \arguments{ 10 | \item{specs}{a list of specifications to revise} 11 | 12 | \item{...}{named values to replace in or add to \code{specs}} 13 | 14 | \item{delete}{a vector of names of elements to remove from the specs list} 15 | } 16 | \description{ 17 | Primary use case is for revising a list of specifications as originally 18 | created by specs() 19 | } 20 | \examples{ 21 | sp <- specs(mm_name('bayes')) 22 | sp <- revise(sp, 23 | model_name='b_np_oipi_tr_plrckm_mynewmodel.stan', 24 | params_in=c(params_in,'my_new_param'), my_new_param=4) 25 | } 26 | -------------------------------------------------------------------------------- /man/convert_kGAS_to_k600.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/convert_k600_to_kGAS.R 3 | \name{convert_kGAS_to_k600} 4 | \alias{convert_kGAS_to_k600} 5 | \title{Returns the gas exchange velocity as k600 for gas of interest w/ no unit conversions} 6 | \usage{ 7 | convert_kGAS_to_k600(kGAS, temperature, gas = "O2") 8 | } 9 | \arguments{ 10 | \item{kGAS}{k of gas as vector of numbers or single number} 11 | 12 | \item{temperature}{Water temperature (deg C) as vector array of numbers or single number} 13 | 14 | \item{gas}{gas for conversion, as string (e.g., 'CO2' or 'O2')} 15 | } 16 | \value{ 17 | Numeric value of gas exchange velocity for gas 18 | } 19 | \description{ 20 | Returns the gas exchange velocity as k600 for gas of interest w/ no unit conversions 21 | } 22 | -------------------------------------------------------------------------------- /man/calc_sun_rise_set.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/calc_sun_rise_set.R 3 | \name{calc_sun_rise_set} 4 | \alias{calc_sun_rise_set} 5 | \title{Calculates the time of sunrise and sunset} 6 | \usage{ 7 | calc_sun_rise_set(date, latitude) 8 | } 9 | \arguments{ 10 | \item{date}{Vector of dates in \code{Date} format.} 11 | 12 | \item{latitude}{Single latitude value of site. South should be negative, 13 | North positive} 14 | } 15 | \value{ 16 | data.frame of sunrise and sunset (apparent solar time, nominally UTC) 17 | } 18 | \description{ 19 | Calculates the time of sunrise and sunset based on latitude and date. 20 | } 21 | \examples{ 22 | calc_sun_rise_set(latitude=40.75, 23 | date=as.POSIXlt(c('2013-03-31', '2017-07-01'))) 24 | } 25 | \seealso{ 26 | \link{calc_is_daytime} 27 | } 28 | \keyword{internal} 29 | -------------------------------------------------------------------------------- /docs/link.svg: -------------------------------------------------------------------------------- 1 | 2 | 3 | 5 | 8 | 12 | 13 | -------------------------------------------------------------------------------- /man/get_log.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_bayes.R 3 | \name{get_log} 4 | \alias{get_log} 5 | \alias{get_log.metab_bayes} 6 | \title{Return the log file[s] from a model run} 7 | \usage{ 8 | get_log(metab_model) 9 | 10 | \method{get_log}{metab_bayes}(metab_model) 11 | } 12 | \arguments{ 13 | \item{metab_model}{A Bayesian metabolism model (metab_bayes) from which to 14 | return the log file, if available} 15 | } 16 | \value{ 17 | The MCMC log file[s] lines 18 | } 19 | \description{ 20 | If a log file was created during a model run, this function can retrieve it. 21 | } 22 | \section{Methods (by class)}{ 23 | \itemize{ 24 | \item \code{metab_bayes}: If a log file was created during the Bayesian MCMC run, 25 | metab_bayes() attempted to capture it. Retrieve what was captured with this 26 | function. 27 | }} 28 | 29 | -------------------------------------------------------------------------------- /man/compress_msgs.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_model.show.R 3 | \name{compress_msgs} 4 | \alias{compress_msgs} 5 | \title{Compress warnings and errors in to a single column} 6 | \usage{ 7 | compress_msgs( 8 | ddat, 9 | colname = "messages", 10 | warnings.overall = c(), 11 | errors.overall = c() 12 | ) 13 | } 14 | \arguments{ 15 | \item{ddat}{a data.frame including warnings and errors columns} 16 | 17 | \item{colname}{the name of the column where the summary should be placed} 18 | 19 | \item{warnings.overall}{any general warnings (for the whole model) to be 20 | included in the summary} 21 | 22 | \item{errors.overall}{any general errors (for the whole model) to be included 23 | in the summary} 24 | } 25 | \description{ 26 | Compress two columns of warning and error messages into one short-hand column 27 | } 28 | \keyword{internal} 29 | -------------------------------------------------------------------------------- /man/mm_filter_hours.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mm_filter_hours.R 3 | \name{mm_filter_hours} 4 | \alias{mm_filter_hours} 5 | \title{Limit to a specific time range on each date} 6 | \usage{ 7 | mm_filter_hours(data, day_start, day_end) 8 | } 9 | \arguments{ 10 | \item{data}{a data.frame containing date and solar.time columns (POSIXct)} 11 | 12 | \item{day_start}{the start time of each day, inclusive, in hours} 13 | 14 | \item{day_end}{the end time of each day, exclusive, in hours} 15 | } 16 | \description{ 17 | Within each date (as labeled by the 'date' column of \code{data}, select the 18 | values of solar.time that are within the time range specified by day_start 19 | and day_end). This function only removes rows and cannot add them; to add 20 | overlap starting from a continuous time series, see 21 | \code{\link{mm_model_by_ply}}. 22 | } 23 | \keyword{internal} 24 | -------------------------------------------------------------------------------- /man/mm_check_mcmc_files.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mm_check_mcmc_file.R 3 | \name{mm_check_mcmc_files} 4 | \alias{mm_check_mcmc_files} 5 | \title{Check the syntax of all Bayesian model files in the package} 6 | \usage{ 7 | mm_check_mcmc_files(grep_pattern) 8 | } 9 | \arguments{ 10 | \item{grep_pattern}{string on which to filter the names if only some should 11 | be checked. fixed=FALSE.} 12 | } 13 | \description{ 14 | Check the syntax of all Bayesian model files in the package 15 | } 16 | \examples{ 17 | \dontrun{ 18 | # takes a long time, so run only when needed 19 | checks <- streamMetabolizer:::mm_check_mcmc_files() 20 | saveRDS(checks, file='temp/bayes_model_checks.Rds') 21 | checks <- streamMetabolizer:::mm_check_mcmc_files("*ko\\\\.stan") 22 | checks <- streamMetabolizer:::mm_check_mcmc_files("b_np_.*_ko\\\\.stan") 23 | cat(checks[[7]]) 24 | } 25 | } 26 | \keyword{internal} 27 | -------------------------------------------------------------------------------- /inst/CITATION: -------------------------------------------------------------------------------- 1 | citHeader("To cite streamMetabolizer in publications, please use:") 2 | 3 | bibentry( 4 | bibtype = "Article", 5 | author = personList( 6 | as.person("Alison P. Appling"), 7 | as.person("Robert O. Hall Jr."), 8 | as.person("Charles B. Yackulic"), 9 | as.person("Maite Arroita") 10 | ), 11 | title = "Overcoming Equifinality: Leveraging Long Time Series for Stream Metabolism Estimation", 12 | journal = "Journal of Geophysical Research: Biogeosciences", 13 | year = 2018, 14 | volume = 123, 15 | number = 2, 16 | doi = "10.1002/2017JG004140", 17 | url = "https://github.com/USGS-R/streamMetabolizer", 18 | textVersion = "Appling, Alison P., Robert O. Hall, Charles B. Yackulic, and Maite Arroita. “Overcoming Equifinality: Leveraging Long Time Series for Stream Metabolism Estimation.” Journal of Geophysical Research: Biogeosciences 123, no. 2 (February 2018): 624–45. https://doi.org/10.1002/2017JG004140." 19 | ) 20 | -------------------------------------------------------------------------------- /R/mm_locate_filename.R: -------------------------------------------------------------------------------- 1 | #' Look for a model file 2 | #' 3 | #' Looks first in the models folder of the streamMetabolizer package, second 4 | #' along the relative or absolute file path given by model_name 5 | #' 6 | #' @param model_name a model file in the 'models' folder of the 7 | #' streamMetabolizer package or a relative or absolute file path of a model 8 | #' file 9 | #' @return a file path if the file exists or an error otherwise 10 | #' @keywords internal 11 | mm_locate_filename <- function(model_name) { 12 | 13 | package_dir <- system.file("models", package="streamMetabolizer") 14 | package_path <- system.file(paste0("models/", model_name), package="streamMetabolizer") 15 | other_path <- model_name 16 | 17 | if(file.exists(package_path)) return(package_path) 18 | if(file.exists(other_path)) return(other_path) 19 | 20 | stop("could not locate the model file at ", file.path(package_dir, model_name), " or ", other_path) 21 | } 22 | -------------------------------------------------------------------------------- /man/convert_SW_to_PAR.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/convert_PAR_to_SW.R 3 | \name{convert_SW_to_PAR} 4 | \alias{convert_SW_to_PAR} 5 | \title{Convert from shortwave to photosynthetically active radiation} 6 | \usage{ 7 | convert_SW_to_PAR(sw, coef = 2.114) 8 | } 9 | \arguments{ 10 | \item{sw}{Vector of shortwave radiation (W/m^2)} 11 | 12 | \item{coef}{Numerical coefficient to convert SW (W/m^2) to PAR 13 | (umol/m^2/sec). Defaults to value from Britton and Dodd (1976).} 14 | } 15 | \value{ 16 | Numeric vector of PAR values in units umol/m^2/sec 17 | } 18 | \description{ 19 | Convert shortwave radiation (SW) to photosynthetically active radiation 20 | (PAR). Uses a fixed ratio between SW and PAR, ignoring the minor seasonal 21 | changes in this ratio (see Britton and Dodd (1976)). 22 | } 23 | \examples{ 24 | convert_SW_to_PAR(sw=800) 25 | convert_SW_to_PAR(sw=800, coef=2.1) 26 | convert_SW_to_PAR(unitted::u(473, "W m^-2")) 27 | } 28 | -------------------------------------------------------------------------------- /man/convert_PAR_to_SW.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/convert_PAR_to_SW.R 3 | \name{convert_PAR_to_SW} 4 | \alias{convert_PAR_to_SW} 5 | \title{Convert from photosynthetically active to shortwave radiation} 6 | \usage{ 7 | convert_PAR_to_SW(par, coef = 0.473) 8 | } 9 | \arguments{ 10 | \item{par}{Vector of photosynthetically active radiation (400-700 nm; 11 | umol/m^2/sec)} 12 | 13 | \item{coef}{Numerical coefficient to convert PAR (umol/m^2/sec) to SW 14 | (W/m^2). Defaults to value from Britton and Dodd (1976).} 15 | } 16 | \value{ 17 | Numeric vector of shortwave values with units W/m^2 18 | } 19 | \description{ 20 | Convert photosynthetically active radiation (PAR) to shortwave radiation 21 | (SW). Uses a fixed ratio between PAR and SW, ignoring the minor seasonal 22 | changes in this ratio (see Britton and Dodd (1976)). 23 | } 24 | \examples{ 25 | convert_PAR_to_SW(par=400, coef=0.47) 26 | convert_PAR_to_SW(unitted::u(1000, "umol m^-2 s^-1")) 27 | } 28 | -------------------------------------------------------------------------------- /R/calc_is_daytime.R: -------------------------------------------------------------------------------- 1 | #' Determines if specified datetime is during the daytime 2 | #' Returns T/F indicating whether a datetime occurs during the daytime (sunlight hours) 3 | #' 4 | #' @param datetimes Vector of dates as \code{POSIXct} or \code{POSIXlt} (see \code{\link{DateTimeClasses}}) format, but in SOLAR time 5 | #' @param lat Single latitude value of site. South should be negative, north positive 6 | #' 7 | #' @return a boolean vector of same length as \code{datetimes} 8 | #' 9 | #' @author 10 | #' Luke A. Winslow 11 | #' @seealso 12 | #' \link{calc_sun_rise_set} 13 | #' @importFrom LakeMetabolizer is.day 14 | #' @examples 15 | #' \dontrun{ 16 | #' # Warning: this function is deprecated. 17 | #' calc_is_daytime(datetimes=as.POSIXct(paste('2013-03-31', c('1:00','11:00'))), lat=40.75) 18 | #' } 19 | #' @export 20 | calc_is_daytime <- function(datetimes, lat) { 21 | 22 | .Deprecated() 23 | warning("submit a GitHub issue if you want calc_is_daytime() to stick around") 24 | 25 | LakeMetabolizer::is.day(datetimes, lat) 26 | } 27 | -------------------------------------------------------------------------------- /man/get_mcmc_data.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_bayes.R 3 | \name{get_mcmc_data} 4 | \alias{get_mcmc_data} 5 | \alias{get_mcmc_data.metab_bayes} 6 | \title{Extract any MCMC data list[s] that were stored with the model} 7 | \usage{ 8 | get_mcmc_data(metab_model) 9 | 10 | \method{get_mcmc_data}{metab_bayes}(metab_model) 11 | } 12 | \arguments{ 13 | \item{metab_model}{A Bayesian metabolism model (metab_bayes) from which to 14 | return the data list that was passed to the MCMC} 15 | } 16 | \value{ 17 | The MCMC data list 18 | } 19 | \description{ 20 | A function specific to metab_bayes models. Returns data as formatted to run 21 | through the MCMC process or, for nopool models, a list of data lists. These 22 | lists are not saved by default; see \code{keep_mcmc_data} argument to 23 | \code{\link{specs}} for options. 24 | } 25 | \section{Methods (by class)}{ 26 | \itemize{ 27 | \item \code{metab_bayes}: Retrieve any MCMC data list[s] that were saved with 28 | a metab_bayes model 29 | }} 30 | 31 | -------------------------------------------------------------------------------- /man/convert_doyhr_to_date.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/convert_date_to_doyhr.R 3 | \name{convert_doyhr_to_date} 4 | \alias{convert_doyhr_to_date} 5 | \title{Convert a a day of year (1-366) with decimal hours to a date} 6 | \usage{ 7 | convert_doyhr_to_date( 8 | doyhr, 9 | year, 10 | tz = "UTC", 11 | origin = as.POSIXct("1970-01-01 00:00:00", tz = "UTC"), 12 | ... 13 | ) 14 | } 15 | \arguments{ 16 | \item{doyhr}{Numeric value expressing the date as the number of days, with 17 | decimal hours, since 00:00 of December 31 of the preceding year} 18 | 19 | \item{year}{Numeric 4-digit year} 20 | 21 | \item{tz}{The time zone to pass to as.POSIXct()} 22 | 23 | \item{origin}{The origin to pass to as.POSIXct()} 24 | 25 | \item{...}{Other arguments to pass to as.POSIXct()} 26 | } 27 | \value{ 28 | A datetime object as POSIXct 29 | } 30 | \description{ 31 | Convert a a day of year (1-366) with decimal hours to a date 32 | } 33 | \examples{ 34 | streamMetabolizer:::convert_doyhr_to_date(34.500695, 2015) 35 | } 36 | -------------------------------------------------------------------------------- /tests/testthat/test-calc_depth.R: -------------------------------------------------------------------------------- 1 | context("calc_depth") 2 | 3 | test_that("calc_depth checks & returns values & units as expected", { 4 | # basic numbers, with & without defaults 5 | expect_is(calc_depth(Q=7.3), "numeric") 6 | expect_equal(calc_depth(Q=7.3, c=1, f=0.5), 7.3^0.5) 7 | expect_equal(calc_depth(Q=rep(100, 3), c=seq(0.4, 0.6, 0.1), f=c(0.25, 0.29, 0.33)), c(1.26, 1.9, 2.74), tol=0.1) 8 | 9 | # with units - throws warnings rather than errors in several cases 10 | library(unitted) 11 | expect_error(expect_warning(calc_depth(Q=1:10, f=u(0.36)), "not unitted"), "Unexpected units") 12 | expect_warning(calc_depth(Q=u(1:10, "m^3 s^-1"), c=0.36), "unknown depth units") 13 | expect_warning(calc_depth(Q=u(1:10, "m^3 s^-1"), f=0.36), "not unitted") 14 | 15 | # use units of c, whatever those are, but throw a warning if they're odd 16 | expect_equal(get_units(calc_depth(Q=u(1:10, "m^3 s^-1"), c=u(40,"cm"))), "cm", "retains units of c") 17 | expect_warning(calc_depth(Q=u(1:10, "m^3 s^-1"), c=u(40,"kebabs")), "unknown depth units") 18 | 19 | }) 20 | -------------------------------------------------------------------------------- /R/mm_filter_hours.R: -------------------------------------------------------------------------------- 1 | #' Limit to a specific time range on each date 2 | #' 3 | #' Within each date (as labeled by the 'date' column of \code{data}, select the 4 | #' values of solar.time that are within the time range specified by day_start 5 | #' and day_end). This function only removes rows and cannot add them; to add 6 | #' overlap starting from a continuous time series, see 7 | #' \code{\link{mm_model_by_ply}}. 8 | #' 9 | #' @param data a data.frame containing date and solar.time columns (POSIXct) 10 | #' @param day_start the start time of each day, inclusive, in hours 11 | #' @param day_end the end time of each day, exclusive, in hours 12 | #' @import dplyr 13 | #' @keywords internal 14 | mm_filter_hours <- function(data, day_start, day_end) { 15 | d0 <- ds <- de <- '.dplyr.var' 16 | data %>% 17 | mutate(d0 = with_tz(as.POSIXct(data$date), 'UTC'), 18 | ds = d0 + as.difftime(day_start, units='hours'), 19 | de = d0 + as.difftime(day_end, units='hours')) %>% 20 | filter(solar.time >= ds, solar.time < de) %>% 21 | select(-d0, -ds, -de) 22 | } 23 | -------------------------------------------------------------------------------- /man/calc_air_pressure.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/calc_air_pressure.R 3 | \name{calc_air_pressure} 4 | \alias{calc_air_pressure} 5 | \title{Calculates the average air pressure for a site} 6 | \usage{ 7 | calc_air_pressure( 8 | temp.air = u(15, "degC"), 9 | elevation = u(762, "m"), 10 | attach.units = deprecated() 11 | ) 12 | } 13 | \arguments{ 14 | \item{temp.air}{air temperature in degrees C. Default is 15 degC.} 15 | 16 | \item{elevation}{the site elevation above sea level in m. Default is the 17 | rough mean elevation of the USA at 2500 ft (from 18 | http://www.infoplease.com/ipa/A0001792.html)} 19 | 20 | \item{attach.units}{(deprecated, effectively FALSE in future) logical. Should 21 | the returned vector be a unitted object?} 22 | } 23 | \value{ 24 | a numeric vector of barometric pressures in mb, with units attached 25 | if requested. 26 | } 27 | \description{ 28 | Estimates air pressure from air temperature and elevation 29 | } 30 | \examples{ 31 | calc_air_pressure(15, 762) 32 | calc_air_pressure(15, 100) 33 | } 34 | -------------------------------------------------------------------------------- /man/calc_solar_time.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/calc_solar_time.R 3 | \name{calc_solar_time} 4 | \alias{calc_solar_time} 5 | \title{Calculate solar.time from local.time} 6 | \usage{ 7 | calc_solar_time(local.time, longitude) 8 | } 9 | \arguments{ 10 | \item{local.time}{POSIXct date+time of interest, already in local time as 11 | specified by the tz attribute} 12 | 13 | \item{longitude}{numeric, in degrees, either positive and unitted ("degE" or 14 | "degW") or with sign indicating direction (positive = East)} 15 | } 16 | \description{ 17 | Calculate the appropriate solar.time column for input to metab(). The input 18 | must be POSIXct clock time and should have the correct timezone information 19 | embedded in the object, whether the tz is UTC, local time with daylight 20 | savings, or local standard time. The output is always mean solar time (not 21 | apparent; see \code{convert_UTC_to_solaritme}). 22 | } 23 | \examples{ 24 | local.time <- as.POSIXct('2016-05-27 12:00:00', tz='America/New_York') 25 | solar.time <- calc_solar_time(local.time, longitude=-74) 26 | } 27 | -------------------------------------------------------------------------------- /man/sim_pred_Kb.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_sim.R 3 | \name{sim_pred_Kb} 4 | \alias{sim_pred_Kb} 5 | \title{Predict ln(K600) as Kb-style function of discharge} 6 | \usage{ 7 | sim_pred_Kb(K600_lnQ_nodes_centers, lnK600_lnQ_nodes, lnQ.daily) 8 | } 9 | \arguments{ 10 | \item{K600_lnQ_nodes_centers}{data configuration argument for 11 | pool_K600='binned'. numeric vector giving the natural-log-space centers of 12 | the discharge bins. See also \code{\link{calc_bins}}} 13 | 14 | \item{lnK600_lnQ_nodes}{For a sim model with pool_K600='binned'. The values 15 | of lnK600 at each node. The default value of this spec is a function that 16 | computes lnK600s based on simulated K~Q relationships.} 17 | 18 | \item{lnQ.daily}{vector of daily values of the natural log of discharge, 19 | e.g., \code{log(data_daily$discharge.daily)}} 20 | } 21 | \description{ 22 | Uses linear interpolation among "nodes" (lnQ, lnK points) to predict daily 23 | values of the natural log of K600, based on the lnK ~ lnQ relationship 24 | specified by \code{K600_lnQ_nodes_centers} and \code{lnK600_lnQ_nodes} 25 | } 26 | -------------------------------------------------------------------------------- /R/streamMetabolizer-deprecated.R: -------------------------------------------------------------------------------- 1 | #' Deprecated Functions in package streamMetabolizer 2 | #' 3 | #' These functions are provided for compatibility with older versions of 4 | #' \code{streamMetabolizer} only, and may be defunct as soon as the next 5 | #' release. 6 | #' 7 | #' \itemize{ 8 | #' \item \code{\link{calc_DO_deficit}} - instead, subtract \code{DO.obs} from output of \code{\link{calc_DO_sat}} 9 | #' \item \code{calc_DO_at_sat} - use \code{\link{calc_DO_sat}} instead 10 | #' \item \code{\link{calc_is_daytime}} - if you like and want this function, submit a GitHub issue to keep it 11 | #' \item \code{\link{calc_sun_rise_set}} - if you like and want this function, submit a GitHub issue to keep it 12 | #' } 13 | #' 14 | #' These functions will are currently exported but will soon be internal-only. 15 | #' You are encouraged not to use these. 16 | #' 17 | #' \itemize{ 18 | #' \item \code{\link{convert_date_to_doyhr}} 19 | #' \item \code{\link{convert_doyhr_to_date}} 20 | #' \item \code{\link{lookup_google_timezone}} - use \code{\link{lookup_timezone}} instead 21 | #' } 22 | #' 23 | #' @name streamMetabolizer-deprecated 24 | NULL 25 | -------------------------------------------------------------------------------- /man/calc_is_daytime.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/calc_is_daytime.R 3 | \name{calc_is_daytime} 4 | \alias{calc_is_daytime} 5 | \title{Determines if specified datetime is during the daytime 6 | Returns T/F indicating whether a datetime occurs during the daytime (sunlight hours)} 7 | \usage{ 8 | calc_is_daytime(datetimes, lat) 9 | } 10 | \arguments{ 11 | \item{datetimes}{Vector of dates as \code{POSIXct} or \code{POSIXlt} (see \code{\link{DateTimeClasses}}) format, but in SOLAR time} 12 | 13 | \item{lat}{Single latitude value of site. South should be negative, north positive} 14 | } 15 | \value{ 16 | a boolean vector of same length as \code{datetimes} 17 | } 18 | \description{ 19 | Determines if specified datetime is during the daytime 20 | Returns T/F indicating whether a datetime occurs during the daytime (sunlight hours) 21 | } 22 | \examples{ 23 | \dontrun{ 24 | # Warning: this function is deprecated. 25 | calc_is_daytime(datetimes=as.POSIXct(paste('2013-03-31', c('1:00','11:00'))), lat=40.75) 26 | } 27 | } 28 | \seealso{ 29 | \link{calc_sun_rise_set} 30 | } 31 | \author{ 32 | Luke A. Winslow 33 | } 34 | -------------------------------------------------------------------------------- /tests/testthat/test-calc_DO.R: -------------------------------------------------------------------------------- 1 | context("calc_DO") 2 | 3 | library(unitted) 4 | 5 | DO.obs <<- u(c(7,7.5,7),'mgO2 L^-1') 6 | temp.water <<- u(c(25,24.5,18.9), 'degC') 7 | pressure.air <<- u(c(900,903,910), 'mb') 8 | salinity.water <<- u(2.43, 'PSU') 9 | 10 | test_that("proper units checked and returned for calc_DO_sat", { 11 | expect_equal(calc_DO_sat(temp=u(21,"degC"), press=u(1013.25,"mb"), sal=u(0,"PSU")), u(8.914559, "L^-1 mgO2"), tol=0.0001, info="with units") 12 | expect_equal(calc_DO_sat(temp=21, press=1013.25, sal=0), 8.914559, tol=0.0001, info="with no units") 13 | expect_error(calc_DO_sat(temp=u(77,"degF"), press=u(1.1,"atm"), sal=0), "Unexpected units", info="with wrong units") 14 | }) 15 | 16 | test_that("proper unit failures for DO.deficit", { 17 | expect_error(calc_DO_sat(u(temp.water,'dogs'), pressure.air, salinity.water), 'Unexpected units') 18 | expect_error(expect_warning(calc_DO_sat(v(temp.water), pressure.air, salinity.water), 'not unitted'), 'Unexpected units') 19 | expect_equal(is.numeric(calc_DO_sat(temp=21, press=1.1, sal=0)), TRUE) 20 | expect_equal(get_units(calc_DO_sat(temp=u(4,"degC"), press=u(1100,"mb"), sal=u(0,"PSU"))), "mgO2 L^-1") 21 | }) 22 | -------------------------------------------------------------------------------- /man/load_french_creek_std.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/load_french_creek_std.R 3 | \name{load_french_creek_std} 4 | \alias{load_french_creek_std} 5 | \title{Load a short dataset from French Creek using Bob Hall's code} 6 | \usage{ 7 | load_french_creek_std(attach.units = deprecated()) 8 | } 9 | \arguments{ 10 | \item{attach.units}{(deprecated, effectively FALSE in future) logical, 11 | default TRUE for backward compatibility. Should units be attached to the 12 | data.frame?} 13 | } 14 | \value{ 15 | a data.frame, unitted if attach.units==TRUE 16 | } 17 | \description{ 18 | This function requires \code{chron}, a package that is not formally required 19 | by the \code{streamMetabolizer} package overall. Ensure that you have 20 | \code{chron} installed or install it with \code{install.packages('chron')}. 21 | } 22 | \details{ 23 | This function produces a version of the French Creek dataset that agrees as 24 | much as possible with raw code from Bob Hall, for comparison to functions 25 | written in streamMetabolizer. Line numbers in comments (L22, etc.) refer to 26 | those in 'stream_metab_usa/starter_files/One station metab code.R' 27 | } 28 | -------------------------------------------------------------------------------- /man/calc_hour_angle.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/calc_solar_insolation.R 3 | \name{calc_hour_angle} 4 | \alias{calc_hour_angle} 5 | \title{Calculate hour angle as in 6 | http://education.gsfc.nasa.gov/experimental/July61999siteupdate/inv99Project.Site/Pages/solar.insolation.html.} 7 | \usage{ 8 | calc_hour_angle(hour, format = c("degrees", "radians")) 9 | } 10 | \arguments{ 11 | \item{hour}{numeric value or vector. hour since [solar] midnight as number 12 | between 0 and 23.999} 13 | 14 | \item{format}{The format of both the input and the output. May be "degrees" 15 | or "radians".} 16 | } 17 | \value{ 18 | numeric value or vector, in the units specified by \code{format}, 19 | indicating the angle corresponding to each value supplied in \code{hour}. 20 | } 21 | \description{ 22 | This is an approximation when hour is in clock time; should actually be given 23 | in solar time 24 | } 25 | \examples{ 26 | hourdf <- data.frame(hour=c(0:12,12.5:23.5), 27 | hragl=streamMetabolizer:::calc_hour_angle(c(0:12,12.5:23.5))) 28 | \dontrun{ 29 | library(ggplot2) 30 | ggplot(hourdf, aes(x=hour, y=hragl)) + 31 | geom_hline(yintercept=0, color="gold") + geom_line() 32 | } 33 | } 34 | -------------------------------------------------------------------------------- /man/lookup_usgs_elevation.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/lookup_usgs_elevation.R 3 | \name{lookup_usgs_elevation} 4 | \alias{lookup_usgs_elevation} 5 | \title{Use USGS API (USGS Elevation Point Query Service) to determine approximate 6 | local elevation} 7 | \usage{ 8 | lookup_usgs_elevation(latitude, longitude, units = c("Meters", "Feet")) 9 | } 10 | \arguments{ 11 | \item{latitude}{degrees latitude (positive for north) of the location to look 12 | up.} 13 | 14 | \item{longitude}{degrees longitude (positive for east) of the location to 15 | look up.} 16 | 17 | \item{units}{character, one of Meters or Feet, specifying the units in which 18 | to return the elevation} 19 | } 20 | \description{ 21 | This is meant to supply an APPROXIMATE elevation, with no guarantees on 22 | precision or on the lifetime of the API service used by the function. This 23 | function uses two packages, \code{RCurl} and \code{XML}, that are not 24 | required for the \code{streamMetabolizer} package as a whole. If these are 25 | not already installed, run \code{install.packages(c('RCurl','XML'))} before 26 | calling \code{lookup_usgs_elevation}. 27 | } 28 | \references{ 29 | https://nationalmap.gov/epqs/ 30 | } 31 | -------------------------------------------------------------------------------- /R/calc_sun_rise_set.R: -------------------------------------------------------------------------------- 1 | #' Calculates the time of sunrise and sunset 2 | #' 3 | #' Calculates the time of sunrise and sunset based on latitude and date. 4 | #' 5 | #' @param date Vector of dates in \code{Date} format. 6 | #' @param latitude Single latitude value of site. South should be negative, 7 | #' North positive 8 | #' @return data.frame of sunrise and sunset (apparent solar time, nominally UTC) 9 | #' @importFrom LakeMetabolizer sun.rise.set 10 | #' @importFrom lubridate force_tz 11 | #' @keywords internal 12 | #' @examples 13 | #' calc_sun_rise_set(latitude=40.75, 14 | #' date=as.POSIXlt(c('2013-03-31', '2017-07-01'))) 15 | #' @seealso \link{calc_is_daytime} 16 | #' @export 17 | calc_sun_rise_set <- function(date, latitude) { 18 | 19 | .Deprecated 20 | warning("submit a GitHub issue if you want calc_sun_rise_set() to stick around") 21 | 22 | app.solar.time <- as.POSIXct(strftime(date, "%Y-%m-%d 0"), format="%Y-%m-%d %H") # use local tz, as LakeMetabolizer does 23 | sun.rise.set <- LakeMetabolizer::sun.rise.set(app.solar.time, latitude) 24 | # reformat 25 | data.frame(sunrise=lubridate::force_tz(sun.rise.set[,1], tz="UTC"), 26 | sunset=lubridate::force_tz(sun.rise.set[,2], tz="UTC")) 27 | } 28 | 29 | 30 | 31 | -------------------------------------------------------------------------------- /man/get_data.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_model_interface.R, R/metab_model-class.R 3 | \name{get_data} 4 | \alias{get_data} 5 | \alias{get_data.metab_model} 6 | \title{Extract the fitting data from a metabolism model.} 7 | \usage{ 8 | get_data(metab_model) 9 | 10 | \method{get_data}{metab_model}(metab_model) 11 | } 12 | \arguments{ 13 | \item{metab_model}{A metabolism model, implementing the 14 | metab_model_interface, for which to return the data} 15 | } 16 | \value{ 17 | A data.frame 18 | } 19 | \description{ 20 | A function in the metab_model_interface. Returns the data that were passed to 21 | a metabolism model. 22 | } 23 | \section{Methods (by class)}{ 24 | \itemize{ 25 | \item \code{metab_model}: This implementation is shared by many model types 26 | }} 27 | 28 | \seealso{ 29 | Other metab_model_interface: 30 | \code{\link{get_data_daily}()}, 31 | \code{\link{get_fitting_time}()}, 32 | \code{\link{get_fit}()}, 33 | \code{\link{get_info}()}, 34 | \code{\link{get_param_names}()}, 35 | \code{\link{get_params}()}, 36 | \code{\link{get_specs}()}, 37 | \code{\link{get_version}()}, 38 | \code{\link{predict_DO}()}, 39 | \code{\link{predict_metab}()} 40 | } 41 | \concept{metab_model_interface} 42 | -------------------------------------------------------------------------------- /man/streamMetabolizer-deprecated.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/streamMetabolizer-deprecated.R 3 | \name{streamMetabolizer-deprecated} 4 | \alias{streamMetabolizer-deprecated} 5 | \title{Deprecated Functions in package streamMetabolizer} 6 | \description{ 7 | These functions are provided for compatibility with older versions of 8 | \code{streamMetabolizer} only, and may be defunct as soon as the next 9 | release. 10 | } 11 | \details{ 12 | \itemize{ 13 | \item \code{\link{calc_DO_deficit}} - instead, subtract \code{DO.obs} from output of \code{\link{calc_DO_sat}} 14 | \item \code{calc_DO_at_sat} - use \code{\link{calc_DO_sat}} instead 15 | \item \code{\link{calc_is_daytime}} - if you like and want this function, submit a GitHub issue to keep it 16 | \item \code{\link{calc_sun_rise_set}} - if you like and want this function, submit a GitHub issue to keep it 17 | } 18 | 19 | These functions will are currently exported but will soon be internal-only. 20 | You are encouraged not to use these. 21 | 22 | \itemize{ 23 | \item \code{\link{convert_date_to_doyhr}} 24 | \item \code{\link{convert_doyhr_to_date}} 25 | \item \code{\link{lookup_google_timezone}} - use \code{\link{lookup_timezone}} instead 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /man/get_info.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_model_interface.R, R/metab_model-class.R 3 | \name{get_info} 4 | \alias{get_info} 5 | \alias{get_info.metab_model} 6 | \title{Extract the user-supplied metadata about a metabolism model.} 7 | \usage{ 8 | get_info(metab_model) 9 | 10 | \method{get_info}{metab_model}(metab_model) 11 | } 12 | \arguments{ 13 | \item{metab_model}{A metabolism model, implementing the 14 | metab_model_interface, for which to return the metadata information.} 15 | } 16 | \value{ 17 | The user-supplied metadata in the original format. 18 | } 19 | \description{ 20 | A function in the metab_model_interface. Returns any user-supplied metadata. 21 | } 22 | \section{Methods (by class)}{ 23 | \itemize{ 24 | \item \code{metab_model}: This implementation is shared by many model types 25 | }} 26 | 27 | \seealso{ 28 | Other metab_model_interface: 29 | \code{\link{get_data_daily}()}, 30 | \code{\link{get_data}()}, 31 | \code{\link{get_fitting_time}()}, 32 | \code{\link{get_fit}()}, 33 | \code{\link{get_param_names}()}, 34 | \code{\link{get_params}()}, 35 | \code{\link{get_specs}()}, 36 | \code{\link{get_version}()}, 37 | \code{\link{predict_DO}()}, 38 | \code{\link{predict_metab}()} 39 | } 40 | \concept{metab_model_interface} 41 | -------------------------------------------------------------------------------- /man/Kmodel_aggregate_day.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_Kmodel.R 3 | \name{Kmodel_aggregate_day} 4 | \alias{Kmodel_aggregate_day} 5 | \title{Aggregate unit values to daily values} 6 | \usage{ 7 | Kmodel_aggregate_day( 8 | data_ply, 9 | ply_validity, 10 | ..., 11 | columns = c("discharge", "velocity") 12 | ) 13 | } 14 | \arguments{ 15 | \item{data_ply}{a data.frame containing all relevant, validated modeling data 16 | for a single ply of data. (1 ply ~= 1 date, although the day length has 17 | been specified by day_start and day_end and may not be exactly 24 hours)} 18 | 19 | \item{ply_validity}{the output of \code{mm_is_valid_day} as applied to this 20 | data_ply for those tests specified in \code{day_tests}. Those tests will 21 | have been run before this function is called. The result is TRUE if the ply 22 | is entirely valid, or a character vector containing one or more error 23 | messages if any tests failed.} 24 | 25 | \item{...}{other args that were passed untouched from the function calling 26 | mm_model_by_ply, through mm_model_by_ply, and finally to this function.} 27 | 28 | \item{columns}{character vector of names of columns to aggregate} 29 | } 30 | \description{ 31 | For use in predicting K 32 | } 33 | \keyword{internal} 34 | -------------------------------------------------------------------------------- /man/get_data_daily.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_model_interface.R, R/metab_model-class.R 3 | \name{get_data_daily} 4 | \alias{get_data_daily} 5 | \alias{get_data_daily.metab_model} 6 | \title{Extract the daily fitting data, if any, from a metabolism model.} 7 | \usage{ 8 | get_data_daily(metab_model) 9 | 10 | \method{get_data_daily}{metab_model}(metab_model) 11 | } 12 | \arguments{ 13 | \item{metab_model}{A metabolism model, implementing the 14 | metab_model_interface, for which to return the data_daily} 15 | } 16 | \value{ 17 | A data.frame 18 | } 19 | \description{ 20 | A function in the metab_model_interface. Returns the daily data that were 21 | passed to a metabolism model. 22 | } 23 | \section{Methods (by class)}{ 24 | \itemize{ 25 | \item \code{metab_model}: This implementation is shared by many model types 26 | }} 27 | 28 | \seealso{ 29 | Other metab_model_interface: 30 | \code{\link{get_data}()}, 31 | \code{\link{get_fitting_time}()}, 32 | \code{\link{get_fit}()}, 33 | \code{\link{get_info}()}, 34 | \code{\link{get_param_names}()}, 35 | \code{\link{get_params}()}, 36 | \code{\link{get_specs}()}, 37 | \code{\link{get_version}()}, 38 | \code{\link{predict_DO}()}, 39 | \code{\link{predict_metab}()} 40 | } 41 | \concept{metab_model_interface} 42 | -------------------------------------------------------------------------------- /man/get_fit.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_model_interface.R, R/metab_model-class.R 3 | \name{get_fit} 4 | \alias{get_fit} 5 | \alias{get_fit.metab_model} 6 | \title{Extract the internal model from a metabolism model.} 7 | \usage{ 8 | get_fit(metab_model) 9 | 10 | \method{get_fit}{metab_model}(metab_model) 11 | } 12 | \arguments{ 13 | \item{metab_model}{A metabolism model, implementing the 14 | metab_model_interface, for which to return the data} 15 | } 16 | \value{ 17 | An internal model representation; may have any class 18 | } 19 | \description{ 20 | A function in the metab_model_interface. Returns the internal model 21 | representation as fitted to the supplied data and arguments. 22 | } 23 | \section{Methods (by class)}{ 24 | \itemize{ 25 | \item \code{metab_model}: This implementation is shared by many model types 26 | }} 27 | 28 | \seealso{ 29 | Other metab_model_interface: 30 | \code{\link{get_data_daily}()}, 31 | \code{\link{get_data}()}, 32 | \code{\link{get_fitting_time}()}, 33 | \code{\link{get_info}()}, 34 | \code{\link{get_param_names}()}, 35 | \code{\link{get_params}()}, 36 | \code{\link{get_specs}()}, 37 | \code{\link{get_version}()}, 38 | \code{\link{predict_DO}()}, 39 | \code{\link{predict_metab}()} 40 | } 41 | \concept{metab_model_interface} 42 | -------------------------------------------------------------------------------- /man/plot_metab_preds.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/plot_metab_preds.R 3 | \name{plot_metab_preds} 4 | \alias{plot_metab_preds} 5 | \title{Plot predictions produced with predict_DO} 6 | \usage{ 7 | plot_metab_preds( 8 | metab_preds, 9 | y_var = c("GPP", "ER"), 10 | style = c("ggplot2"), 11 | y_lim = list(GPP = c(NA, NA), ER = c(NA, NA)) 12 | ) 13 | } 14 | \arguments{ 15 | \item{metab_preds}{a data.frame of predictions such as that returned by 16 | predict_metab()} 17 | 18 | \item{y_var}{character. Should the plot display predicted values of GPP 19 | and/or ER? The default is to plot both.} 20 | 21 | \item{style}{character indicating which graphics package to use} 22 | 23 | \item{y_lim}{list of named vectors, each of which has length 2 and is numeric 24 | and has a name in the possible values of y_var. NA within a vector 25 | indicates that the data range should be used. for ggplot2, y_lim is only 26 | used to exclude values outside that range and is ignored if the data span a 27 | narrower range} 28 | } 29 | \description{ 30 | Plots modeled values as lines, observed values as points 31 | } 32 | \examples{ 33 | \dontrun{ 34 | mm <- metab_night(specs(mm_name('night')), data=data_metab('10', day_start=12, day_end=36)) 35 | plot_metab_preds(mm) 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /man/get_version.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_model_interface.R, R/metab_model-class.R 3 | \name{get_version} 4 | \alias{get_version} 5 | \alias{get_version.metab_model} 6 | \title{Extract the version of streamMetabolizer that was used to fit the model.} 7 | \usage{ 8 | get_version(metab_model) 9 | 10 | \method{get_version}{metab_model}(metab_model) 11 | } 12 | \arguments{ 13 | \item{metab_model}{A metabolism model, implementing the 14 | metab_model_interface, for which to return the data} 15 | } 16 | \value{ 17 | character representation of the package version 18 | } 19 | \description{ 20 | A function in the metab_model_interface. Returns the version of 21 | streamMetabolizer that was used to fit the model. 22 | } 23 | \section{Methods (by class)}{ 24 | \itemize{ 25 | \item \code{metab_model}: This implementation is shared by many model types 26 | }} 27 | 28 | \seealso{ 29 | Other metab_model_interface: 30 | \code{\link{get_data_daily}()}, 31 | \code{\link{get_data}()}, 32 | \code{\link{get_fitting_time}()}, 33 | \code{\link{get_fit}()}, 34 | \code{\link{get_info}()}, 35 | \code{\link{get_param_names}()}, 36 | \code{\link{get_params}()}, 37 | \code{\link{get_specs}()}, 38 | \code{\link{predict_DO}()}, 39 | \code{\link{predict_metab}()} 40 | } 41 | \concept{metab_model_interface} 42 | -------------------------------------------------------------------------------- /man/get_fitting_time.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_model_interface.R, R/metab_model-class.R 3 | \name{get_fitting_time} 4 | \alias{get_fitting_time} 5 | \alias{get_fitting_time.metab_model} 6 | \title{Extract the amount of time that was required to fit the metabolism model.} 7 | \usage{ 8 | get_fitting_time(metab_model) 9 | 10 | \method{get_fitting_time}{metab_model}(metab_model) 11 | } 12 | \arguments{ 13 | \item{metab_model}{A metabolism model, implementing the 14 | metab_model_interface, for which to return the time} 15 | } 16 | \value{ 17 | An proc_time object 18 | } 19 | \description{ 20 | A function in the metab_model_interface. Returns the time that was taken to 21 | fit the model; see \code{\link{proc.time}} for details. 22 | } 23 | \section{Methods (by class)}{ 24 | \itemize{ 25 | \item \code{metab_model}: This implementation is shared by many model types 26 | }} 27 | 28 | \seealso{ 29 | Other metab_model_interface: 30 | \code{\link{get_data_daily}()}, 31 | \code{\link{get_data}()}, 32 | \code{\link{get_fit}()}, 33 | \code{\link{get_info}()}, 34 | \code{\link{get_param_names}()}, 35 | \code{\link{get_params}()}, 36 | \code{\link{get_specs}()}, 37 | \code{\link{get_version}()}, 38 | \code{\link{predict_DO}()}, 39 | \code{\link{predict_metab}()} 40 | } 41 | \concept{metab_model_interface} 42 | -------------------------------------------------------------------------------- /man/get_specs.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_model_interface.R, R/metab_model-class.R 3 | \name{get_specs} 4 | \alias{get_specs} 5 | \alias{get_specs.metab_model} 6 | \title{Extract the fitting specifications from a metabolism model.} 7 | \usage{ 8 | get_specs(metab_model) 9 | 10 | \method{get_specs}{metab_model}(metab_model) 11 | } 12 | \arguments{ 13 | \item{metab_model}{A metabolism model, implementing the 14 | metab_model_interface, for which to return the specifications} 15 | } 16 | \value{ 17 | The list of specifications that was passed to \code{\link{metab}()} 18 | } 19 | \description{ 20 | A function in the metab_model_interface. Returns the specifications that were 21 | passed in when fitting the metabolism model. 22 | } 23 | \section{Methods (by class)}{ 24 | \itemize{ 25 | \item \code{metab_model}: This implementation is shared by many model types 26 | }} 27 | 28 | \seealso{ 29 | Other metab_model_interface: 30 | \code{\link{get_data_daily}()}, 31 | \code{\link{get_data}()}, 32 | \code{\link{get_fitting_time}()}, 33 | \code{\link{get_fit}()}, 34 | \code{\link{get_info}()}, 35 | \code{\link{get_param_names}()}, 36 | \code{\link{get_params}()}, 37 | \code{\link{get_version}()}, 38 | \code{\link{predict_DO}()}, 39 | \code{\link{predict_metab}()} 40 | } 41 | \concept{metab_model_interface} 42 | -------------------------------------------------------------------------------- /man/metab_model-class.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_model-class.R 3 | \docType{class} 4 | \name{metab_model-class} 5 | \alias{metab_model-class} 6 | \title{A metabolism model class.} 7 | \description{ 8 | A metabolism model class. 9 | } 10 | \section{Slots}{ 11 | 12 | \describe{ 13 | \item{\code{info}}{Any metadata the user chooses to package with metabolism model.} 14 | 15 | \item{\code{metab_daily}}{A data.frame of daily metabolism predictions.} 16 | 17 | \item{\code{fit}}{An internal representation of a fitted model.} 18 | 19 | \item{\code{fitting_time}}{Usually stored as a proc_time; the time required to fit 20 | the model.} 21 | 22 | \item{\code{pkg_version}}{A string indicating the package version used to create this 23 | metab_model object.} 24 | 25 | \item{\code{specs}}{A list of model specifications that were supplied to the fitting 26 | function.} 27 | 28 | \item{\code{data}}{The data that were used to fit the model.} 29 | 30 | \item{\code{data_daily}}{The daily data, if any, that were used to fit the model.} 31 | }} 32 | 33 | \seealso{ 34 | Other metab.model.classes: 35 | \code{\link{metab_Kmodel-class}}, 36 | \code{\link{metab_bayes-class}}, 37 | \code{\link{metab_mle-class}}, 38 | \code{\link{metab_night-class}}, 39 | \code{\link{metab_sim-class}} 40 | } 41 | \concept{metab.model.classes} 42 | -------------------------------------------------------------------------------- /man/get_mcmc.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_bayes.R 3 | \name{get_mcmc} 4 | \alias{get_mcmc} 5 | \alias{get_mcmc.metab_bayes} 6 | \title{Extract any MCMC model objects that were stored with the model} 7 | \usage{ 8 | get_mcmc(metab_model) 9 | 10 | \method{get_mcmc}{metab_bayes}(metab_model) 11 | } 12 | \arguments{ 13 | \item{metab_model}{A Bayesian metabolism model (metab_bayes) from which to 14 | return the MCMC model object\link{s}} 15 | } 16 | \value{ 17 | The MCMC model object\link{s} 18 | } 19 | \description{ 20 | A function specific to metab_bayes models. Returns an MCMC object of class 21 | \code{stanfit} (\link[rstan:stanfit-class]{rstan::stanfit}), which is saved in the metab_model by 22 | default because you should almost always inspect it; see \code{keep_mcmcs} 23 | argument to \code{\link[=specs]{specs()}} for options for saving space. The \code{rstan} methods 24 | for \link[rstan:stanfit-class]{rstan::stanfit} objects include \code{summary()}, \code{get_stancode()}, 25 | \code{stan_dens()}, \code{stan_diag()}, and many more. See 26 | \code{?'rstan-plotting-functions'}, \link[rstan:stanfit-class]{rstan::stanfit} and the 27 | \href{https://cran.r-project.org/web/packages/rstan/rstan.pdf}{rstan manual}. 28 | } 29 | \section{Methods (by class)}{ 30 | \itemize{ 31 | \item \code{metab_bayes}: Get the Bayesian MCMC model object 32 | }} 33 | 34 | -------------------------------------------------------------------------------- /R/revise.R: -------------------------------------------------------------------------------- 1 | #' Change or add named elements of a list 2 | #' 3 | #' Primary use case is for revising a list of specifications as originally 4 | #' created by specs() 5 | #' 6 | #' @param specs a list of specifications to revise 7 | #' @param ... named values to replace in or add to \code{specs} 8 | #' @param delete a vector of names of elements to remove from the specs list 9 | #' @export 10 | #' @examples 11 | #' sp <- specs(mm_name('bayes')) 12 | #' sp <- revise(sp, 13 | #' model_name='b_np_oipi_tr_plrckm_mynewmodel.stan', 14 | #' params_in=c(params_in,'my_new_param'), my_new_param=4) 15 | revise <- function(specs, ..., delete) { 16 | # evaluate ... in the context of specs 17 | args <- { 18 | # R CMD check gives a note about attach(); I think I've followed the 19 | # recommended best practices of using a distinctive name and immediately 20 | # following attach() with on.exit(detach()) 21 | attach(specs, warn.conflicts=FALSE, name='revisespecstemp') 22 | on.exit(detach('revisespecstemp')) 23 | list(...) 24 | } 25 | 26 | # require names 27 | if(is.null(names(args)) || any(names(args) == '')) { 28 | stop("all arguments in ... must be named") 29 | } 30 | # add/change specs 31 | for(a in names(args)) { 32 | specs[[a]] <- args[[a]] 33 | } 34 | # delete specs 35 | if(!missing(delete)) { 36 | specs[delete] <- NULL 37 | } 38 | # return 39 | specs 40 | } 41 | -------------------------------------------------------------------------------- /man/mm_parse_name.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mm_parse_name.R 3 | \name{mm_parse_name} 4 | \alias{mm_parse_name} 5 | \title{Parse a model name into its features} 6 | \usage{ 7 | mm_parse_name(model_name, expand = FALSE) 8 | } 9 | \arguments{ 10 | \item{model_name}{character: the model name} 11 | 12 | \item{expand}{logical: should additional columns such as model_name and 13 | pool_K600_type be added? If expand=TRUE then the result cannot be passed 14 | directly back into mm_name, but the additional columns may be helpful for 15 | interpreting the model structure.} 16 | } 17 | \description{ 18 | Returns a data.frame with one column per model structure detail and one row 19 | per `model_name` supplied to this function. See \code{?\link{mm_name}} for a 20 | description of each of the data.frame columns that is returned. 21 | } 22 | \details{ 23 | Custom model files (for MCMC) may have additional characters after an 24 | underscore at the end of the name and before the prefix. For example, 25 | 'b_np_pcpi_eu_ko.stan' and 'b_np_pcpi_eu_ko_v2.stan' are parsed the same; the 26 | _v2 is ignored by this function. 27 | } 28 | \examples{ 29 | mm_parse_name(c(mm_name('mle'), mm_name('night'), mm_name('bayes'))) 30 | mm_parse_name(c(mm_name('mle'), mm_name('night'), mm_name('bayes')), expand=TRUE) 31 | } 32 | \seealso{ 33 | The converse of this function is \code{\link{mm_name}}. 34 | } 35 | -------------------------------------------------------------------------------- /man/bayes_allply.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_bayes.R 3 | \name{bayes_allply} 4 | \alias{bayes_allply} 5 | \title{Make daily metabolism estimates from input parameters using a hierarchical 6 | approach.} 7 | \usage{ 8 | bayes_allply(data_all, data_daily_all, removed, specs) 9 | } 10 | \arguments{ 11 | \item{data_all}{data.frame of the form \code{mm_data(solar.time, DO.obs, 12 | DO.sat, depth, temp.water, light)} and containing data for just one 13 | estimation-day (this may be >24 hours but only yields estimates for one 14 | 24-hour period)} 15 | 16 | \item{data_daily_all}{data.frame of daily priors, if appropriate to the given 17 | model_path} 18 | 19 | \item{removed}{data.frame of dates that were removed and why} 20 | 21 | \item{specs}{a list of model specifications and parameters for a model. 22 | Although this may be specified manually (it's just a list), it is easier 23 | and safer to use \code{\link{specs}} to generate the list, because the set 24 | of required parameters and their defaults depends on the model given in the 25 | \code{model_name} argument to \code{specs}. The help file for 26 | \code{\link{specs}} lists the necessary parameters, describes them in 27 | detail, and gives default values.} 28 | } 29 | \value{ 30 | data.frame of estimates and MCMC model diagnostics 31 | } 32 | \description{ 33 | Called from metab_bayes(). 34 | } 35 | \keyword{internal} 36 | -------------------------------------------------------------------------------- /man/lookup_google_timezone.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/lookup_timezone.R 3 | \name{lookup_google_timezone} 4 | \alias{lookup_google_timezone} 5 | \title{Use Google API to determine local time zone} 6 | \usage{ 7 | lookup_google_timezone( 8 | latitude, 9 | longitude, 10 | timestamp = if (unitted::v(latitude) >= 0) as.POSIXct("2015-01-01 00:00:00", tz = 11 | "UTC") else as.POSIXct("2015-07-01 00:00:00", tz = "UTC") 12 | ) 13 | } 14 | \arguments{ 15 | \item{latitude}{degrees latitude (positive for north) of the location to look 16 | up.} 17 | 18 | \item{longitude}{degrees longitude (positive for east) of the location to 19 | look up.} 20 | 21 | \item{timestamp}{POSIXct representation of a time - determines daylight 22 | savings offset, if any. the default is Jan 1 for northern latitudes and 23 | July 1 for southern latitudes, i.e., a time surely not during daylight 24 | savings time.} 25 | } 26 | \description{ 27 | This function uses two packages, \code{RCurl} and \code{XML}, that are not 28 | required for the \code{streamMetabolizer} package as a whole. If these are 29 | not already installed, run \code{install.packages(c('RCurl','XML'))} before 30 | calling \code{lookup_google_timezone}. 31 | } 32 | \details{ 33 | Some parameter definitions below are copied directly from the API webpage. 34 | } 35 | \references{ 36 | https://developers.google.com/maps/documentation/timezone/ 37 | } 38 | -------------------------------------------------------------------------------- /R/calc_solar_time.R: -------------------------------------------------------------------------------- 1 | #' Calculate solar.time from local.time 2 | #' 3 | #' Calculate the appropriate solar.time column for input to metab(). The input 4 | #' must be POSIXct clock time and should have the correct timezone information 5 | #' embedded in the object, whether the tz is UTC, local time with daylight 6 | #' savings, or local standard time. The output is always mean solar time (not 7 | #' apparent; see \code{convert_UTC_to_solaritme}). 8 | #' 9 | #' @inheritParams convert_localtime_to_UTC 10 | #' @inheritParams convert_UTC_to_solartime 11 | #' @import dplyr 12 | #' @examples 13 | #' local.time <- as.POSIXct('2016-05-27 12:00:00', tz='America/New_York') 14 | #' solar.time <- calc_solar_time(local.time, longitude=-74) 15 | #' @export 16 | calc_solar_time <- function(local.time, longitude) { 17 | 18 | # quick check to try to warn users away from using non-solar time 19 | stated_tz <- attr(local.time, 'tz') 20 | if(stated_tz == 'UTC') { 21 | implied_tz <- tryCatch(lookup_timezone(latitude=51.5, longitude), error=function(e) NULL) # london: 51.5N, 0W 22 | if(!is.null(implied_tz) && !implied_tz$std_offset %in% -1:1) # give some buffer. UTC longitudes vary with latitude 23 | warning('found non-UTC longitude for UTC timezone. Are you sure you passed in a local time?') 24 | } 25 | 26 | local.time %>% 27 | convert_localtime_to_UTC() %>% 28 | convert_UTC_to_solartime(longitude=longitude, time.type='mean solar') 29 | } 30 | -------------------------------------------------------------------------------- /.github/ISSUE_TEMPLATE.md: -------------------------------------------------------------------------------- 1 | Thanks for submitting your issue or question. We can address issues fastest if they are: 2 | 3 | * New - search past issues first to see if your question has already been answered. Reopen an old issue if your question was almost but not quite answered. 4 | 5 | * Complete - share all relevant code and console output/errors/warnings, in the order they were run and produced on your computer. Also include the output from a call to `devtools::session_info()` to tell us about your computer's configuration. 6 | 7 | * Reproducible - include all the data and code necessary for us/others to recreate the problem locally. It's fine to make up data if you can't share yours, as long as the problem still comes through. 8 | 9 | * Minimal - what is the smallest amount of data and code you can use to demonstrate the problem? This is less essential than the others but improves communication and our response time. 10 | 11 | Delete these instructions before submitting your issue. 12 | 13 | --- 14 | 15 | ### Brief problem description 16 | 17 | 18 | 19 | ### What you saw on your computer 20 | 21 | Include all code you ran (a minimal example) and all console output, errors, and warnings. Include a data file if needed. 22 | 23 | ```r 24 | 25 | ``` 26 | 27 | ### Session information 28 | 29 | Run the following code line (or `sessionInfo()` if that doesn't work) and paste in your output. 30 | 31 | ```r 32 | > devtools::session_info() 33 | 34 | ``` 35 | -------------------------------------------------------------------------------- /man/calc_declination_angle.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/calc_solar_insolation.R 3 | \name{calc_declination_angle} 4 | \alias{calc_declination_angle} 5 | \title{Calculate declination angle as in Yard et al. (2005)} 6 | \usage{ 7 | calc_declination_angle(jday, format = c("degrees", "radians")) 8 | } 9 | \arguments{ 10 | \item{jday}{The day of year as a number between 0 (Jan 1) and 364 (365 also 11 | OK for leap year)} 12 | 13 | \item{format}{The format of both the input and the output. May be "degrees" 14 | or "radians".} 15 | } 16 | \value{ 17 | numeric value or vector, in the units specified by \code{format}, 18 | indicating the declination angle corresponding to each value supplied in 19 | \code{jday}. 20 | } 21 | \description{ 22 | Calculate declination angle as in Yard et al. (2005) 23 | } 24 | \examples{ 25 | decdf <- data.frame(jday=1:366, 26 | dec=streamMetabolizer:::calc_declination_angle(1:366)) 27 | \dontrun{ 28 | library(ggplot2) 29 | ggplot(unitted::v(decdf), aes(x=jday, y=dec)) + geom_line() 30 | } 31 | } 32 | \references{ 33 | Yard, Michael D., Glenn E. Bennett, Steve N. Mietz, Lewis G. 34 | Coggins Jr., Lawrence E. Stevens, Susan Hueftle, and Dean W. Blinn. 35 | \emph{Influence of Topographic Complexity on Solar Insolation Estimates for 36 | the Colorado River, Grand Canyon, AZ.} Ecological Modelling 183, no. 2-3 37 | (April 25, 2005): 157-72. doi:10.1016/j.ecolmodel.2004.07.027. 38 | } 39 | -------------------------------------------------------------------------------- /man/mm_validate_data.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mm_validate_data.R 3 | \name{mm_validate_data} 4 | \alias{mm_validate_data} 5 | \title{Evaluate whether the data argument is properly formatted.} 6 | \usage{ 7 | mm_validate_data( 8 | data = mm_data(NULL), 9 | data_daily = mm_data(NULL), 10 | metab_class, 11 | data_tests = c("missing_cols", "extra_cols", "na_times", "units") 12 | ) 13 | } 14 | \arguments{ 15 | \item{data}{data.frame (not a tbl_df) of input data at the temporal 16 | resolution of raw observations (unit-value). Columns must have the same 17 | names, units, and format as the default. The solar.time column must also 18 | have a timezone code ('tzone' attribute) of 'UTC'. See the 19 | \strong{'Formatting \code{data}'} section below for a full description.} 20 | 21 | \item{data_daily}{data.frame containing inputs with a daily timestep. See the 22 | \strong{'Formatting \code{data_daily}'} section below for a full 23 | description.} 24 | 25 | \item{metab_class}{character the class name of the metab_model constructor} 26 | 27 | \item{data_tests}{list of tests to conduct to determine whether the input 28 | data.frames are properly formatted to allow modeling to begin} 29 | } 30 | \description{ 31 | Will most often be called from within a metab_model constructor. 32 | } 33 | \examples{ 34 | \dontrun{ 35 | mm_validate_data(dplyr::select(mm_data(),-temp.water), metab_class="metab_mle") 36 | } 37 | } 38 | -------------------------------------------------------------------------------- /man/convert_UTC_to_localtime.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/convert_UTC_to_localtime.R 3 | \name{convert_UTC_to_localtime} 4 | \alias{convert_UTC_to_localtime} 5 | \title{Convert time from UTC to local time.} 6 | \usage{ 7 | convert_UTC_to_localtime( 8 | date.time, 9 | latitude, 10 | longitude, 11 | time.type = c("standard local", "daylight local") 12 | ) 13 | } 14 | \arguments{ 15 | \item{date.time}{POSIXct object the date and time in UTC} 16 | 17 | \item{latitude}{numeric, in degrees, either positive and unitted ("degN" or 18 | "degS") or with sign indicating direction (positive = North)} 19 | 20 | \item{longitude}{numeric, in degrees, either positive and unitted ("degE" or 21 | "degW") or with sign indicating direction (positive = East)} 22 | 23 | \item{time.type}{character. The type of time zone desired - either standard 24 | time without any daylight savings time or daylight time where daylight 25 | savings is on during the appropriate days} 26 | } 27 | \description{ 28 | Convert time from UTC to local time, either standard or with daylight 29 | savings. Recommended for post-analysis visualization only; most functions in 30 | streamMetabolizer use times in UTC. If you know the timezone code for your 31 | local site, use \code{\link[lubridate]{with_tz}} instead. 32 | } 33 | \references{ 34 | https://stackoverflow.com/questions/23414340/convert-to-local-time-zone-using-latitude-and-longitude 35 | } 36 | -------------------------------------------------------------------------------- /man/mm_valid_names.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mm_valid_names.R 3 | \name{mm_valid_names} 4 | \alias{mm_valid_names} 5 | \title{Get the valid names for a given model type or types} 6 | \usage{ 7 | mm_valid_names(type = c("bayes", "mle", "night", "Kmodel", "sim")) 8 | } 9 | \arguments{ 10 | \item{type}{character. The model type. Options: \itemize{ \item \code{mle}: 11 | maximum likelihood estimation (see also \code{\link{metab_mle}}) \item 12 | \code{bayes}: bayesian hierarchical models \code{\link{metab_bayes}} \item 13 | \code{night}: nighttime regression (see also \code{\link{metab_night}}) 14 | \item \code{Kmodel}: regression of \emph{daily} estimates of 15 | \code{K600.daily} versus discharge, time, etc., usually for 3-phase 16 | estimation of K alone (by MLE or nighttime regression), K vs discharge 17 | (using this model), and then GPP and ER with fixed K (by MLE) (see also 18 | \code{\link{metab_Kmodel}}) \item \code{sim}: simulation of \code{DO.obs} 19 | 'data' for testing other models (see also \code{\link{metab_sim}}) }} 20 | } 21 | \description{ 22 | Returns a vector of the \code{model_name}s for the type[s] indicated. If 23 | \code{type} is not supplied, all model types will be included. After being 24 | returned from this function, model names may be translated to something 25 | slightly more readable with \code{\link{mm_parse_name}} if desired. 26 | } 27 | \examples{ 28 | mm_valid_names('mle') 29 | } 30 | -------------------------------------------------------------------------------- /R/mm_sd_to_ci.R: -------------------------------------------------------------------------------- 1 | #' Convert SD columns into CI columns in a data.frame 2 | #' 3 | #' Convert data with var and var.sd columns into data with var, var.lower, and 4 | #' var.upper columns 5 | #' 6 | #' @param data a data.frame with 1+ pairs of columns named var and var.sd 7 | #' (where var can be anything) 8 | #' @param alpha the desired significance level described by the confidence 9 | #' interval 10 | #' @import dplyr 11 | #' @keywords internal 12 | mm_sd_to_ci <- function(data, alpha=0.05) { 13 | 14 | # identify the pairs of columns 15 | . <- '.dplyr.var' 16 | sd.cols <- grep('\\.sd$', names(data), value=TRUE) 17 | var.cols <- substring(sd.cols, 1, nchar(sd.cols)-3) %>% { .[. %in% names(data)] } # could be fewer than sd.cols 18 | if(length(sd.cols) > 0) sd.cols <- paste0(var.cols, '.sd') # only include those cols that both end in '.sd' and have a paired var.cols value 19 | sd.pos <- match(sd.cols, names(data)) 20 | 21 | # replace each var.sd col with var.lower and var.upper cols 22 | crit <- -qnorm(alpha/2) 23 | dat.list <- as.list(data) 24 | for(i in rev(seq_along(var.cols))) { 25 | est <- dat.list[[var.cols[i]]] 26 | sd <- dat.list[[sd.cols[i]]] 27 | dat.list <- append( 28 | dat.list, 29 | setNames(list( 30 | lower = est - crit * sd, 31 | upper = est + crit * sd), paste0(var.cols[i], c('.lower','.upper'))), 32 | after=sd.pos[i]) 33 | dat.list[sd.pos[i]] <- NULL 34 | } 35 | 36 | as.data.frame(dat.list, stringsAsFactors=FALSE) 37 | } 38 | -------------------------------------------------------------------------------- /man/sim_get_par.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_sim.R 3 | \name{sim_get_par} 4 | \alias{sim_get_par} 5 | \title{Get a parameter from data_daily, specs, or both} 6 | \usage{ 7 | sim_get_par(par.name, specs, data_daily, eval_env, required = TRUE) 8 | } 9 | \arguments{ 10 | \item{par.name}{The parameter name. Should be period.separated if that's how 11 | data_daily is. Periods will be converted to underscores when searching 12 | specs for the parameter} 13 | 14 | \item{specs}{a specifications list from which parameter values/functions will 15 | be drawn} 16 | 17 | \item{data_daily}{a data.frame of daily values from which parameter values 18 | will be drawn} 19 | 20 | \item{eval_env}{an environment containing any parameters that have already 21 | been finalized, plus the variable \code{n} containing the number of daily 22 | values required} 23 | 24 | \item{required}{logical. If true and the parameter is unavailable, an error 25 | will be thrown.} 26 | } 27 | \value{ 28 | list containing up to three vectors (or NULLs) named \code{specs}, 29 | \code{data_daily}, and \code{combo} according to the source of the numbers 30 | in each vector. 31 | } 32 | \description{ 33 | Used in get_params.metab_sim. Looks in both data_daily and specs for a daily 34 | paramter, e.g., 'K600.daily'. If it's present in just one place, those values 35 | will be used. If it's present in neither, an error or NULLs will be returned 36 | depending on whether \code{required=TRUE}. 37 | } 38 | \keyword{internal} 39 | -------------------------------------------------------------------------------- /code.json: -------------------------------------------------------------------------------- 1 | [ 2 | { 3 | "name": "streamMetabolizer", 4 | "organization": "U.S. Geological Survey", 5 | "description": "streamMetabolizer uses inverse modeling to estimate aquatic metabolism (photosynthesis and respiration) from time series data on dissolved oxygen, water temperature, depth, and light.", 6 | "version": "main", 7 | "status": "Development", 8 | "permissions": { 9 | "usageType": "openSource", 10 | "licenses": [ 11 | { 12 | "name": "Public Domain, CC0-1.0", 13 | "URL": "https://raw.githubusercontent.com/DOI-USGS/streamMetabolizer/main/LICENSE.md" 14 | } 15 | ] 16 | }, 17 | "homepageURL": "https://github.com/DOI-USGS/streamMetabolizer/", 18 | "downloadURL": "https://github.com/DOI-USGS/streamMetabolizer/archive/refs/heads/main.zip", 19 | "disclaimerURL": "https://raw.githubusercontent.com/DOI-USGS/streamMetabolizer/main/DISCLAIMER.md", 20 | "repositoryURL": "https://github.com/DOI-USGS/streamMetabolizer.git", 21 | "vcs": "git", 22 | "laborHours": 2000, 23 | "tags": [ 24 | "R", 25 | "USGS", 26 | "River", 27 | "Metabolism", 28 | "Photosynthesis", 29 | "Respiration", 30 | "doi|https://doi.org/10.1002/2017JG004140" 31 | ], 32 | "languages": [ 33 | "R", 34 | "Stan" 35 | ], 36 | "contact": { 37 | "name": "Alison Appling", 38 | "email": "aappling@usgs.gov" 39 | }, 40 | "date": { 41 | "metadataLastUpdated": "2023-07-05" 42 | } 43 | } 44 | ] 45 | -------------------------------------------------------------------------------- /inst/extdata/b_np_pcpi_eu_ko_v1.stan: -------------------------------------------------------------------------------- 1 | // This script taken from Bob Hall (email 10/13/15) with modified spacing. He writes, "Warning, 2 | // this failed miserably, ER and K way too low, chains did not converge. I attempted to follow 3 | // Charles’ code, but either I 1. Failed because I did not get the coding translation correct 4 | // between BUGS and Stan, or 2. it failed because of [our current theories on process models]. 5 | // It was quick." 6 | 7 | data { 8 | 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | int T; 24 | 25 | vector [T] y; 26 | vector [T] dodt; 27 | vector [T] oxysat; 28 | vector [T] light; 29 | 30 | 31 | real z; 32 | vector [T] Kc; 33 | 34 | } 35 | 36 | 37 | 38 | 39 | 40 | 41 | 42 | 43 | 44 | 45 | 46 | 47 | parameters { 48 | 49 | real GPP; 50 | real ER; 51 | real K; 52 | real phi; 53 | real sigobs; 54 | real sigproc; 55 | vector[T] eta; 56 | 57 | } 58 | 59 | model { 60 | 61 | vector [T] mdodt; 62 | 63 | for (i in 1:T){ 64 | mdodt[i] <- 65 | eta[i] + 66 | ((GPP/z)*(light[i]/sum(light))) + 67 | (ER*0.006944/z) + 68 | (Kc[i]*K * 0.006944*(oxysat[i]-y[i])); 69 | } 70 | 71 | GPP ~ normal(0, 10); 72 | ER ~ normal(-10, 10); 73 | K ~ normal(10, 10); 74 | 75 | for (i in 1:T){ 76 | dodt[i] ~ normal(mdodt[i], sigobs); 77 | } 78 | 79 | for (i in 2:T){ 80 | eta[i] ~ normal(phi*eta[i-1], sigproc); 81 | } 82 | 83 | } -------------------------------------------------------------------------------- /man/convert_solartime_to_UTC.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/convert_UTC_to_solartime.R 3 | \name{convert_solartime_to_UTC} 4 | \alias{convert_solartime_to_UTC} 5 | \title{Convert DateTime from local solar time to UTC} 6 | \usage{ 7 | convert_solartime_to_UTC( 8 | any.solar.time, 9 | longitude, 10 | time.type = c("apparent solar", "mean solar") 11 | ) 12 | } 13 | \arguments{ 14 | \item{any.solar.time}{either apparent or mean solar time (specified by 15 | time.type); date-time values in POSIXct format. Timezone must be UTC.} 16 | 17 | \item{longitude}{numeric, in degrees, either positive and unitted ("degE" or 18 | "degW") or with sign indicating direction (positive = East), describing 19 | location of the site} 20 | 21 | \item{time.type}{character indicating whether any.solar.time values are in 22 | apparent or mean solar time. "apparent solar", i.e. true solar time, is 23 | noon when the sun is at its zenith. "mean solar" approximates apparent 24 | solar time but with noons exactly 24 hours apart.} 25 | } 26 | \value{ 27 | a POSIXct object in UTC 28 | } 29 | \description{ 30 | Convert DateTime to UTC from local solar time, which may be either apparent 31 | solar (perfect match between noon and solar zenith) or mean solar (exactly 24 32 | hours between solar noons). 33 | } 34 | \references{ 35 | Yard, Bennett, Mietz, Coggins, Stevens, Hueftle, and Blinn. 2005. 36 | Influence of topographic complexity on solar insolation estimates for the 37 | Colorado River, Grand Canyon, AZ. Ecological Modelling. 38 | } 39 | -------------------------------------------------------------------------------- /man/calc_light.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/calc_light.R 3 | \name{calc_light} 4 | \alias{calc_light} 5 | \title{Calculate modeled light from solar.time} 6 | \usage{ 7 | calc_light( 8 | solar.time, 9 | latitude, 10 | longitude, 11 | max.PAR = u(2326, "umol m^-2 s^-1"), 12 | attach.units = deprecated() 13 | ) 14 | } 15 | \arguments{ 16 | \item{solar.time}{mean solar time, as required for input to metabolism 17 | models. See \code{\link{mm_data}} and \code{\link{calc_solar_time}}.} 18 | 19 | \item{latitude}{numeric value or vector indicating the site latitude in 20 | decimal degrees (never radians or deg-min-sec, no matter what \code{format} 21 | is) between -90 (South Pole) and 90 (North Pole).} 22 | 23 | \item{longitude}{numeric, in degrees, either positive and unitted ("degE" or 24 | "degW") or with sign indicating direction (positive = East), describing 25 | location of the site} 26 | 27 | \item{max.PAR}{numeric or unitted_numeric: the PAR (umol m^-2 s^-1) that each 28 | day should reach at peak light} 29 | 30 | \item{attach.units}{(deprecated, effectively FALSE in future) logical. Should 31 | the returned vector be a unitted object?} 32 | } 33 | \description{ 34 | Calculate photosynthetically active radiation (PAR) for a series of 35 | date-times and site coordinates. 36 | } 37 | \examples{ 38 | solar.time <- lubridate::force_tz(as.POSIXct('2016-09-27 12:00'), 'UTC') 39 | calc_light(solar.time, 40, -120) 40 | library(unitted) 41 | calc_light(u(solar.time), u(40, 'degN'), u(-120, 'degE'), u(2315, 'umol m^-2 s^-1')) 42 | } 43 | -------------------------------------------------------------------------------- /man/calc_DO_sat.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/calc_DO_sat.R 3 | \name{calc_DO_sat} 4 | \alias{calc_DO_sat} 5 | \title{Calculates the equilibrium saturation concentration of oxygen in water at the 6 | supplied conditions} 7 | \usage{ 8 | calc_DO_sat( 9 | temp.water, 10 | pressure.air, 11 | salinity.water = u(0, "PSU"), 12 | model = "garcia-benson", 13 | ... 14 | ) 15 | } 16 | \arguments{ 17 | \item{temp.water}{a numeric vector of water temperature in degrees Celsius, 18 | or a \linkS4class{unitted} object of water temperatures.} 19 | 20 | \item{pressure.air}{barometric pressure in millibars, or a 21 | \linkS4class{unitted} object of barometric pressure.} 22 | 23 | \item{salinity.water}{a numeric vector of salinity in PSU, or a 24 | \linkS4class{unitted} object of salinity. Defaults to zero.} 25 | 26 | \item{model}{character. One of 'garcia-benson', 'garcia', 'weiss', or 27 | 'benson', but 'garcia-benson' is recommended.} 28 | 29 | \item{...}{additional parameters passed to 30 | \code{LakeMetabolizer::o2.at.sat.base}} 31 | } 32 | \value{ 33 | a numeric vector of dissolved oxygen equilibrium saturation 34 | concentrations, in mg/L, with units attached if any of the input vectors 35 | are unitted. 36 | } 37 | \description{ 38 | Calculates the equilibrium saturation concentration of oxygen in water at the 39 | supplied conditions 40 | } 41 | \examples{ 42 | calc_DO_sat(temp=21, press=1000.1, sal=0) # no units checking if no units provided 43 | library(unitted) 44 | calc_DO_sat(temp=u(21,"degC"), press=u(1000.1,"mb"), sal=u(0,"PSU")) # units are checked 45 | } 46 | -------------------------------------------------------------------------------- /man/calc_depth.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/calc_depth.R 3 | \name{calc_depth} 4 | \alias{calc_depth} 5 | \title{Estimate depth from discharge and hydraulic geometry coefficients} 6 | \usage{ 7 | calc_depth(Q, c = u(0.409, "m"), f = u(0.294, "")) 8 | } 9 | \arguments{ 10 | \item{Q}{discharge (m^3 s^-1)} 11 | 12 | \item{c}{coefficient representing depth at unit discharge (usually m)} 13 | 14 | \item{f}{exponent in depth-discharge relation (unitless)} 15 | } 16 | \value{ 17 | d, stream depth, in the same units as c 18 | } 19 | \description{ 20 | Uses the relationship \eqn{d=c*Q^f} (parameter names and definitions as in 21 | Leopold and Maddock, 1953; default values for c and f as in Raymond et al. 22 | 2012) 23 | } 24 | \examples{ 25 | Qs <- seq(1,9,2) 26 | calc_depth(Q=Qs) 27 | calc_depth(Q=Qs, f=0.4) 28 | library(unitted) 29 | calc_depth(Q=u(Qs, "m^3 s^-1"), c=u(40,"cm")) 30 | calc_depth(Q=u(Qs, "m^3 s^-1"), f=u(0.36)) 31 | } 32 | \references{ 33 | Raymond, Peter A., Christopher J. Zappa, David Butman, Thomas L. 34 | Bott, Jody Potter, Patrick Mulholland, Andrew E. Laursen, William H. 35 | McDowell, and Denis Newbold. \emph{Scaling the gas transfer velocity and 36 | hydraulic geometry in streams and small rivers}. Limnology & Oceanography: 37 | Fluids & Environments 2 (2012): 41-53. 38 | 39 | Leopold, L.B., and Thomas Maddock Jr. \emph{The Hydraulic Geometry of 40 | Stream Channels and Some Physiographic Implications}. Report. Professional 41 | Paper, 1953. USGS Publications Warehouse. 42 | https://pubs.er.usgs.gov/publication/pp252. 43 | } 44 | -------------------------------------------------------------------------------- /man/convert_UTC_to_solartime.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/convert_UTC_to_solartime.R 3 | \name{convert_UTC_to_solartime} 4 | \alias{convert_UTC_to_solartime} 5 | \title{Convert DateTime from UTC to local solar time} 6 | \usage{ 7 | convert_UTC_to_solartime( 8 | date.time, 9 | longitude, 10 | time.type = c("apparent solar", "mean solar") 11 | ) 12 | } 13 | \arguments{ 14 | \item{date.time}{date-time values in POSIXct format and UTC timezone.} 15 | 16 | \item{longitude}{numeric, in degrees, either positive and unitted ("degE" or 17 | "degW") or with sign indicating direction (positive = East)} 18 | 19 | \item{time.type}{character. "apparent solar", i.e. true solar time, is noon 20 | when the sun is at its zenith. "mean solar" approximates apparent solar 21 | time but with noons exactly 24 hours apart. Elsewhere in this package, 22 | variables named "solar.time" are mean solar time, whereas "app.solar.time" 23 | is apparent solar and "any.solar.time" is either.} 24 | } 25 | \value{ 26 | a POSIXct object that says it's in tz="UTC" but that's actually in 27 | solar time, with noon being very close to solar noon 28 | } 29 | \description{ 30 | Convert DateTime from UTC to local solar time, which may be either apparent 31 | solar (perfect match between noon and solar zenith) or mean solar (exactly 24 32 | hours between solar noons). 33 | } 34 | \references{ 35 | Yard, Bennett, Mietz, Coggins, Stevens, Hueftle, and Blinn. 2005. 36 | Influence of topographic complexity on solar insolation estimates for the 37 | Colorado River, Grand Canyon, AZ. Ecological Modelling. 38 | } 39 | -------------------------------------------------------------------------------- /man/mm_validate_name.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mm_validate_name.R 3 | \name{mm_validate_name} 4 | \alias{mm_validate_name} 5 | \title{Check the validity of a model name} 6 | \usage{ 7 | mm_validate_name(model_name) 8 | } 9 | \arguments{ 10 | \item{model_name}{character string identifying the model features. Use 11 | \code{\link{mm_name}} to create a valid name based on desired attributes, 12 | or \code{\link{mm_valid_names}} to see all valid names. Two alternatives to 13 | the names given by \code{mm_valid_names()} are also accepted: (1) a model 14 | type as accepted by the \code{type} argument to \code{mm_name}, which will 15 | be used to create the default model name for that model type, or (2) a full 16 | model file path for custom Bayesian models, as long as basename(model_name) 17 | can still be parsed correctly with \code{mm_parse_name()} and the file 18 | exists. In that case the file may be specified either as a file path 19 | relative to the streamMetabolizer models directory (the first assumption; 20 | this directory can be found with \code{system.file("models", 21 | package="streamMetabolizer")}) or as an absolute path or a path relative to 22 | the current working directory (the second assumption, if the first 23 | assumption turns up no files of the given name).} 24 | } 25 | \description{ 26 | Check the syntactic & scientific validity of a model name. Returns the model 27 | name if it's valid, otherwise gives an error 28 | } 29 | \examples{ 30 | mm_validate_name("b_np_oipi_tr_plrckm.stan") 31 | \dontrun{ 32 | mm_validate_name("b_np_oipn") # throws error 33 | } 34 | } 35 | -------------------------------------------------------------------------------- /man/sim_Kb.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_sim.R 3 | \name{sim_Kb} 4 | \alias{sim_Kb} 5 | \title{Simulate a lnK ~ lnQ relationship in the Kb format} 6 | \usage{ 7 | sim_Kb( 8 | K600_lnQ_nodes_centers, 9 | K600_lnQ_cnode_meanlog, 10 | K600_lnQ_cnode_sdlog, 11 | K600_lnQ_nodediffs_meanlog, 12 | K600_lnQ_nodediffs_sdlog 13 | ) 14 | } 15 | \arguments{ 16 | \item{K600_lnQ_nodes_centers}{data configuration argument for 17 | pool_K600='binned'. numeric vector giving the natural-log-space centers of 18 | the discharge bins. See also \code{\link{calc_bins}}} 19 | 20 | \item{K600_lnQ_cnode_meanlog}{For a sim model with pool_K600='binned'. The 21 | mean of a lognormal distribution describing the y=K600 value of the middle 22 | (or just past middle) node in the piecewise lnK ~ lnQ relationship} 23 | 24 | \item{K600_lnQ_cnode_sdlog}{For a sim model with pool_K600='binned'. The sd 25 | of a lognormal distribution describing the y=K600 value of the middle (or 26 | just past middle) node in the piecewise lnK ~ lnQ relationship} 27 | 28 | \item{K600_lnQ_nodediffs_meanlog}{For a sim model with pool_K600='binned'. 29 | The average (in log space) difference between ln(K) values of successive 30 | nodes. A non-zero value introduces a trend in K ~ Q.} 31 | 32 | \item{K600_lnQ_nodediffs_sdlog}{hyperparameter for pool_K600='binned'. The 33 | standard deviations of the differences in estimated K600 between successive 34 | lnQ_nodes (bins), where the means of those differences are always zero} 35 | } 36 | \description{ 37 | Uses linear interpolation among "nodes" (lnQ, lnK points) to describe the lnK 38 | ~ lnQ relationship 39 | } 40 | -------------------------------------------------------------------------------- /man/runstan_bayes.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_bayes.R 3 | \name{runstan_bayes} 4 | \alias{runstan_bayes} 5 | \title{Run Stan on a formatted data ply} 6 | \usage{ 7 | runstan_bayes( 8 | data_list, 9 | model_path, 10 | model_name, 11 | params_out, 12 | split_dates, 13 | keep_mcmc = FALSE, 14 | n_chains = 4, 15 | n_cores = 4, 16 | burnin_steps = 1000, 17 | saved_steps = 1000, 18 | thin_steps = 1, 19 | verbose = FALSE, 20 | ... 21 | ) 22 | } 23 | \arguments{ 24 | \item{data_list}{a formatted list of inputs to the Stan model} 25 | 26 | \item{model_path}{the Stan model file to use, as a full file path} 27 | 28 | \item{model_name}{the coded model name, as from mm_name, giving the model 29 | structure} 30 | 31 | \item{params_out}{a character vector of parameters whose values in the MCMC 32 | runs should be recorded and summarized} 33 | 34 | \item{keep_mcmc}{logical. If TRUE, the Stan output object will be saved. Be 35 | careful; these can be big, and a run with many models might overwhelm R's 36 | memory.} 37 | 38 | \item{n_chains}{the number of chains to run} 39 | 40 | \item{n_cores}{the number of cores to apply to this run} 41 | 42 | \item{burnin_steps}{the number of steps per chain to run and ignore before 43 | starting to collect MCMC 'data'} 44 | 45 | \item{saved_steps}{the number of MCMC steps per chain to save} 46 | 47 | \item{thin_steps}{the number of steps to move before saving another step. 1 48 | means save all steps.} 49 | 50 | \item{verbose}{logical. give status messages?} 51 | 52 | \item{...}{ignored arguments} 53 | } 54 | \description{ 55 | Run Stan on a formatted data ply 56 | } 57 | \keyword{internal} 58 | -------------------------------------------------------------------------------- /man/calc_velocity.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/calc_velocity.R 3 | \name{calc_velocity} 4 | \alias{calc_velocity} 5 | \title{Estimate velocity from discharge and hydraulic geometry coefficients} 6 | \usage{ 7 | calc_velocity(Q, k = u(0.194, "m s^-1"), m = u(0.285, "")) 8 | } 9 | \arguments{ 10 | \item{Q}{discharge (m^3 s^-1)} 11 | 12 | \item{k}{coefficient representing velocity at unit discharge (usually m/s; e in Raymond et al.)} 13 | 14 | \item{m}{exponent in velocity-discharge relation (unitless; f in Raymond et al.)} 15 | } 16 | \value{ 17 | v (= V = U), stream flow velcoity, in the same units as k 18 | } 19 | \description{ 20 | Uses the relationship \eqn{U=k*Q^m} (parameter names and definitions as in 21 | Leopold and Maddock, 1953; default values for k and m as in Raymond et al. 22 | 2012) 23 | } 24 | \examples{ 25 | Qs <- seq(1,9,2) 26 | calc_velocity(Q=Qs) 27 | calc_velocity(Q=Qs, k=0.4) 28 | library(unitted) 29 | calc_velocity(Q=u(Qs, "m^3 s^-1"), m=u(40)) 30 | calc_velocity(Q=u(Qs, "m^3 s^-1"), k=u(0.36, "m s^-1")) 31 | } 32 | \references{ 33 | Raymond, Peter A., Christopher J. Zappa, David Butman, Thomas L. 34 | Bott, Jody Potter, Patrick Mulholland, Andrew E. Laursen, William H. 35 | McDowell, and Denis Newbold. \emph{Scaling the gas transfer velocity and 36 | hydraulic geometry in streams and small rivers}. Limnology & Oceanography: 37 | Fluids & Environments 2 (2012): 41-53. 38 | 39 | Leopold, L.B., and Thomas Maddock Jr. \emph{The Hydraulic Geometry of 40 | Stream Channels and Some Physiographic Implications}. Report. Professional 41 | Paper, 1953. USGS Publications Warehouse. 42 | https://pubs.er.usgs.gov/publication/pp252. 43 | } 44 | -------------------------------------------------------------------------------- /man/calc_DO_deficit.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/calc_DO_deficit.R 3 | \name{calc_DO_deficit} 4 | \alias{calc_DO_deficit} 5 | \title{Deprecated: Calculate a vector of dissolved oxygen deficits} 6 | \usage{ 7 | calc_DO_deficit(DO.obs, temp.water, pressure.air, salinity.water = 0, ...) 8 | } 9 | \arguments{ 10 | \item{DO.obs}{a numeric vector of dissolved oxygen concentration 11 | observations, mgO2 L^-1, or a \linkS4class{unitted} object of dissolved 12 | oxygen concentrations.} 13 | 14 | \item{temp.water}{a numeric vector of water temperature in degrees Celsius, 15 | or a \linkS4class{unitted} object of water temperatures.} 16 | 17 | \item{pressure.air}{barometric pressure in millibars, or a 18 | \linkS4class{unitted} object of barometric pressure.} 19 | 20 | \item{salinity.water}{a numeric vector of salinity in PSU, or a 21 | \linkS4class{unitted} object of salinity. Defaults to zero. Length must be 22 | one or equal to length of \code{temp.water}.} 23 | 24 | \item{...}{additional parameters passed to 25 | \code{LakeMetabolizer::o2.at.sat.base}} 26 | } 27 | \value{ 28 | a vector of DO.deficit values 29 | } 30 | \description{ 31 | Deprecated: Submit a GitHub issue if you want calc_DO_deficit() to stick 32 | around. Creates a DO.deficit vector for input into metabolism models. 33 | } 34 | \examples{ 35 | \dontrun{ 36 | # Warning: this function is deprecated. 37 | calc_DO_deficit(DO.obs=7, temp.water=25, pressure.air=900, salinity.water=2.43) 38 | library(unitted) 39 | calc_DO_deficit( 40 | DO.obs = u(c(7,7.5,7),'mgO2 L^-1'), 41 | temp.water = u(c(25,24.5,18.9), 'degC'), 42 | pressure.air = u(c(900,903,910), 'mb'), 43 | salinity.water = u(2.43, 'PSU')) 44 | } 45 | } 46 | -------------------------------------------------------------------------------- /R/mm_validate_name.R: -------------------------------------------------------------------------------- 1 | #' Check the validity of a model name 2 | #' 3 | #' Check the syntactic & scientific validity of a model name. Returns the model 4 | #' name if it's valid, otherwise gives an error 5 | #' 6 | #' @inheritParams specs 7 | #' @examples 8 | #' mm_validate_name("b_np_oipi_tr_plrckm.stan") 9 | #' \dontrun{ 10 | #' mm_validate_name("b_np_oipn") # throws error 11 | #' } 12 | #' @export 13 | mm_validate_name <- function(model_name) { 14 | 15 | # under lazy eval, model_name might not break until here (e.g., 16 | # mm_validate_name(mm_name('mle', badarg=4))). force it here to give mm_name a 17 | # chance to throw its own errors. 18 | model_name <- force(model_name) 19 | 20 | # require parseable name 21 | parse_problem <- c() 22 | parsed <- tryCatch( 23 | mm_parse_name(model_name), 24 | error=function(e) { 25 | parse_problem <<- "could not parse model name. try constructing with mm_name()" 26 | }) 27 | if(length(parse_problem) > 0) { 28 | stop(parse_problem) 29 | } 30 | 31 | # require valid type 32 | type <- parsed$type 33 | valid_types <- eval(formals(mm_name)$type) 34 | if(is.na(type) || !(type %in% valid_types)) { 35 | stop('model name implies unknown model type (', type, '). try constructing with mm_name()') 36 | } 37 | 38 | # check against known or findable valid names 39 | valid_names <- mm_valid_names(type) 40 | if(basename(model_name) != model_name) { 41 | mm_locate_filename(model_name) 42 | } else if(!(model_name %in% valid_names)) { 43 | stop("model_name (", model_name, ") is not among valid ", type, 44 | sprintf(" model_names (see mm_valid_names('%s'))", type)) 45 | } 46 | 47 | # return the model name 48 | model_name 49 | } 50 | -------------------------------------------------------------------------------- /tests/testthat/test-distribs.R: -------------------------------------------------------------------------------- 1 | context('distribs') 2 | # this file is really just to help me wrap my head around parameter 3 | # distributions and parameter scaling. 4 | 5 | library(ggplot2) 6 | 7 | # variable description convention in notes: 8 | # stan.and.SM.arg = symbol = r.arg 9 | 10 | explore_scaling <- function() { 11 | #skip('tests are for developer understanding, not code performance') 12 | 13 | # location = mu = meanlog; scale = sigma = sdlog 14 | location <- 0 15 | scale <- 1 16 | n <- 10000 17 | 18 | # desired 19 | desired <- rlnorm(n, meanlog=location, sdlog=scale) 20 | expect_equal(mean(log(desired)), location, tol=0.5) 21 | expect_equal(sd(log(desired)), scale, tol=0.2) 22 | expect_gt(min(desired), 0) 23 | expect_equal(min(desired), 0, tol=0.1) 24 | ggplot(tibble::tibble(desired), aes(x=log(desired))) + geom_histogram() 25 | ggplot(tibble::tibble(desired), aes(x=desired)) + geom_histogram() + xlim(-1, 5) 26 | 27 | # scaled 28 | scaled <- rnorm(n, mean=0, sd=1) 29 | ggplot(tibble::tibble(scaled), aes(x=scaled)) + geom_histogram() 30 | final <- exp(location)*(exp(scaled)^scale) 31 | ggplot(tibble::tibble(final), aes(x=log(final))) + geom_histogram() 32 | ggplot(tibble::tibble(final), aes(x=final)) + geom_histogram() + xlim(-5, 100) 33 | 34 | # comparison 35 | comp <- dplyr::bind_rows( 36 | tibble::tibble(value=desired, type='desired'), 37 | tibble::tibble(value=scaled, type='scaled'), 38 | tibble::tibble(value=final, type='final')) 39 | ggplot(comp) + geom_histogram(aes(x=log(value), fill=type), alpha=0.5, binwidth=1, position='identity') 40 | ggplot(dplyr::filter(comp, type != 'scaled')) + geom_histogram(aes(x=value, fill=type), alpha=0.5, binwidth=1, position='identity') + xlim(-5, 100) 41 | } 42 | -------------------------------------------------------------------------------- /man/mm_filter_dates.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mm_filter_dates.R 3 | \name{mm_filter_dates} 4 | \alias{mm_filter_dates} 5 | \title{Filter unit or daily data by inclusive start & end dates} 6 | \usage{ 7 | mm_filter_dates( 8 | data, 9 | date_start = NA, 10 | date_end = NA, 11 | day_start = 4, 12 | day_end = 28, 13 | date_format = "\%Y-\%m-\%d" 14 | ) 15 | } 16 | \arguments{ 17 | \item{data}{either instantaneous/unit or daily data, having columns for 18 | solar.time or date, respectively, to filter} 19 | 20 | \item{date_start}{Date or a class convertible with as.Date. The first date 21 | (inclusive) for which to report DO predictions. If NA, no filtering is 22 | done.} 23 | 24 | \item{date_end}{Date or a class convertible with as.Date. The last date 25 | (inclusive) for which to report DO predictions. If NA, no filtering is 26 | done.} 27 | } 28 | \description{ 29 | Filter unit or daily data by inclusive start & end dates 30 | } 31 | \examples{ 32 | tm <- as.POSIXct("2017-10-02 00:00:00 UTC") 33 | dt <- as.Date("2017-10-02") 34 | udat <- data.frame(solar.time=tm + as.difftime(1:100, units='hours'), value=1:100) 35 | udat1 <- streamMetabolizer:::mm_filter_dates(udat) 36 | udat2 <- streamMetabolizer:::mm_filter_dates(udat, date_start=dt, date_end=dt) 37 | udat3 <- streamMetabolizer:::mm_filter_dates(udat, date_start=dt, date_end=dt, 38 | day_start=12, day_end=14) 39 | c(nrow(udat), nrow(udat1), nrow(udat2), nrow(udat3)) 40 | ddat <- data.frame(date=dt + as.difftime(1:100, units='days'), value=1:100) 41 | ddat1 <- streamMetabolizer:::mm_filter_dates(ddat) 42 | ddat2 <- streamMetabolizer:::mm_filter_dates(ddat, date_start=dt+10, date_end=dt+20) 43 | c(nrow(ddat), nrow(ddat1), nrow(ddat2)) 44 | } 45 | \keyword{internal} 46 | -------------------------------------------------------------------------------- /man/prepdata_bayes.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_bayes.R 3 | \name{prepdata_bayes} 4 | \alias{prepdata_bayes} 5 | \title{Prepare data for passing to Stan} 6 | \usage{ 7 | prepdata_bayes(data, data_daily, ply_date = NA, specs) 8 | } 9 | \arguments{ 10 | \item{data}{data.frame (not a tbl_df) of input data at the temporal 11 | resolution of raw observations (unit-value). Columns must have the same 12 | names, units, and format as the default. The solar.time column must also 13 | have a timezone code ('tzone' attribute) of 'UTC'. See the 14 | \strong{'Formatting \code{data}'} section below for a full description.} 15 | 16 | \item{data_daily}{data.frame containing inputs with a daily timestep. See the 17 | \strong{'Formatting \code{data_daily}'} section below for a full 18 | description.} 19 | 20 | \item{ply_date}{the modal date of this ply of data and data_daily, and the 21 | date by which this ply should be referred topresent.} 22 | 23 | \item{specs}{a list of model specifications and parameters for a model. 24 | Although this may be specified manually (it's just a list), it is easier 25 | and safer to use \code{\link{specs}} to generate the list, because the set 26 | of required parameters and their defaults depends on the model given in the 27 | \code{model_name} argument to \code{specs}. The help file for 28 | \code{\link{specs}} lists the necessary parameters, describes them in 29 | detail, and gives default values.} 30 | } 31 | \value{ 32 | list of data for input to runstan_bayes 33 | } 34 | \description{ 35 | This function accepts pre-validated data (though more problems may be 36 | discovered here). It prepares the data needed to run a Bayesian MCMC method 37 | to estimate GPP, ER, and K600. 38 | } 39 | \keyword{internal} 40 | -------------------------------------------------------------------------------- /LICENSE.md: -------------------------------------------------------------------------------- 1 | ## License 2 | 3 | Unless otherwise noted, This project is in the public domain in the United 4 | States because it contains materials that originally came from the United 5 | States Geological Survey, an agency of the United States Department of 6 | Interior. For more information, see the official USGS copyright policy at 7 | https://www.usgs.gov/information-policies-and-instructions/copyrights-and-credits 8 | 9 | Additionally, we waive copyright and related rights in the work 10 | worldwide through the CC0 1.0 Universal public domain dedication. 11 | 12 | 13 | ### CC0 1.0 Universal Summary 14 | 15 | This is a human-readable summary of the 16 | [Legal Code (read the full text)][1]. 17 | 18 | 19 | #### No Copyright 20 | 21 | The person who associated a work with this deed has dedicated the work to 22 | the public domain by waiving all of his or her rights to the work worldwide 23 | under copyright law, including all related and neighboring rights, to the 24 | extent allowed by law. 25 | 26 | You can copy, modify, distribute and perform the work, even for commercial 27 | purposes, all without asking permission. 28 | 29 | 30 | #### Other Information 31 | 32 | In no way are the patent or trademark rights of any person affected by CC0, 33 | nor are the rights that other persons may have in the work or in how the 34 | work is used, such as publicity or privacy rights. 35 | 36 | Unless expressly stated otherwise, the person who associated a work with 37 | this deed makes no warranties about the work, and disclaims liability for 38 | all uses of the work, to the fullest extent permitted by applicable law. 39 | When using or citing the work, you should not imply endorsement by the 40 | author or the affirmer. 41 | 42 | 43 | [1]: https://creativecommons.org/publicdomain/zero/1.0/legalcode 44 | -------------------------------------------------------------------------------- /man/metab_model_interface.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_model_interface.R 3 | \docType{data} 4 | \name{metab_model_interface} 5 | \alias{metab_model_interface} 6 | \title{Functions implemented by any \code{streamMetabolizer}-compatible metabolism 7 | model.} 8 | \format{ 9 | A collection of functions which any metabolism model in 10 | \code{streamMetabolizer} should implement. 11 | } 12 | \description{ 13 | Metabolism models in the \code{streamMetabolizer} package all implement a 14 | common set of core functions. These functions are conceptually packaged as 15 | the \code{metab_model_interface} defined here. 16 | } 17 | \section{Functions in the interface}{ 18 | 19 | 20 | \itemize{ 21 | 22 | \item \code{\link{show}(metab_model) \{ display(metab_model) \}} 23 | 24 | \item \code{\link{get_params}(metab_model, ...) \{ return(data.frame) \}} 25 | 26 | \item \code{\link{get_param_names}(metab_model, ...) \{ return(list) \}} 27 | 28 | \item \code{\link{predict_metab}(metab_model, ...) \{ return(data.frame) 29 | \}} 30 | 31 | \item \code{\link{predict_DO}(metab_model, ...) \{ return(data.frame) \}} 32 | 33 | \item \code{\link{get_fit}(metab_model) \{ return(fitted.model) \}} 34 | 35 | \item \code{\link{get_fitting_time}(metab_model) \{ return(proc_time) \}} 36 | 37 | \item \code{\link{get_info}(metab_model) \{ return(info) \}} 38 | 39 | \item \code{\link{get_specs}(metab_model) \{ return(specs.list) \}} 40 | 41 | \item \code{\link{get_data}(metab_model) \{ return(data.frame) \}} 42 | 43 | \item \code{\link{get_data_daily}(metab_model) \{ return(data.frame) \}} 44 | 45 | \item \code{\link{get_version}(metab_model) \{ return(version.string) \}} 46 | 47 | } 48 | } 49 | 50 | \examples{ 51 | methods(class="metab_model") 52 | } 53 | -------------------------------------------------------------------------------- /man/load_french_creek_std_mle.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/load_french_creek_std.R 3 | \name{load_french_creek_std_mle} 4 | \alias{load_french_creek_std_mle} 5 | \title{Generate outputs using Bob's code for comparison} 6 | \usage{ 7 | load_french_creek_std_mle( 8 | french, 9 | K = 35, 10 | estimate = c("PRK", "K", "PR"), 11 | start = c(dates = "08/23/12", times = "22:00:00"), 12 | end = c(dates = "08/25/12", times = "06:00:00"), 13 | plot = FALSE 14 | ) 15 | } 16 | \arguments{ 17 | \item{french}{the French Creek dataset} 18 | 19 | \item{K}{optional. If specified, a number for the K600 to assume (units of 20 | 1/d)} 21 | 22 | \item{estimate}{character indicating the type of model to fit} 23 | 24 | \item{start}{a character vector specifying the time at which the 'day' (the 25 | time period to use in producing an estimate for a single date) begins. The 26 | vector should have 2 elements, dates and times, to pass to chron()} 27 | 28 | \item{end}{a character vector specifying the time at which the 'day' ends. 29 | The vector should have 2 elements, dates and times, to pass to chron()} 30 | 31 | \item{plot}{logical - should plots be produced?} 32 | } 33 | \description{ 34 | Bob's code includes MLE and nighttime regression models. This function 35 | generates the output from those models, keeping the code as much intact as 36 | possible. The exception is that we're using solar.time rather than 37 | local.time, for consistency with streamMetabolizer's recommendations 38 | } 39 | \details{ 40 | This function requires the \code{chron} package, which is only suggested 41 | rather than required for the \code{streamMetabolizer} package. If you wish to 42 | run this function, ensure that \code{chron} is installed or install it with 43 | \code{install.packages('chron')}. 44 | } 45 | -------------------------------------------------------------------------------- /CODE_OF_CONDUCT.md: -------------------------------------------------------------------------------- 1 | ## Code of Conduct 2 | 3 | ### Contributor Code of Conduct 4 | 5 | As contributors and maintainers of this project, we pledge to respect all people who contribute through reporting issues, posting feature requests, updating documentation, submitting pull requests or patches, and other activities. 6 | 7 | We are committed to making participation in this project a harassment-free experience for everyone, regardless of level of experience, gender, gender identity and expression, sexual orientation, disability, personal appearance, body size, race, ethnicity, age, or religion. 8 | 9 | Examples of unacceptable behavior by participants include the use of sexual language or imagery, derogatory comments or personal attacks, trolling, public or private harassment, insults, or other unprofessional conduct. 10 | 11 | Project maintainers have the right and responsibility to remove, edit, or reject comments, commits, code, wiki edits, issues, and other contributions that are not aligned to this Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed from the project team. 12 | 13 | Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by opening an issue or contacting one or more of the project maintainers. 14 | 15 | This Code of Conduct is adapted from the 16 | [Contributor Covenant, version 1.0.0](https://www.contributor-covenant.org/version/1/0/0/code-of-conduct.html). 17 | 18 | 19 | ### USGS Code of Scientific Conduct 20 | 21 | Additionally, all contributions to -- and interactions surrounding -- this project will abide by 22 | the 23 | [USGS Code of Scientific Conduct](https://www.usgs.gov/office-of-science-quality-and-integrity/fundamental-science-practices) 24 | and the 25 | [DOI Code of Development Conduct](https://github.com/DOI-BLM/01-guidance/blob/master/CODE_OF_CONDUCT.md). 26 | -------------------------------------------------------------------------------- /vignettes/installation.Rmd: -------------------------------------------------------------------------------- 1 | --- 2 | title: "Installation" 3 | author: "Alison Appling" 4 | date: "`r Sys.Date()`" 5 | output: 6 | # rmarkdown::github_document 7 | rmarkdown::html_vignette: 8 | keep_md: true 9 | vignette: > 10 | %\VignetteIndexEntry{Installation} 11 | %\VignetteEngine{knitr::rmarkdown} 12 | %\VignetteEncoding{UTF-8} 13 | --- 14 | 15 | ```{r knitr_init, echo=FALSE, cache=FALSE} 16 | knitr::opts_chunk$set(echo = TRUE) 17 | options(width=100) 18 | ``` 19 | 20 | # Installing streamMetabolizer 21 | 22 | To install the `streamMetabolizer` package, use the `remotes` package (running `install.packages('remotes')` first if needed). To use `remotes::install_github()` it is convenient to set a [GitHub Personal Access Token (PAT)](https://docs.github.com/en/authentication/keeping-your-account-and-data-secure/managing-your-personal-access-tokens). There are [several methods](https://usethis.r-lib.org/articles/git-credentials.html) for setting your PATs within R; the simplest is to call `Sys.setenv(GITHUB_PAT="yyyy"), 23 | replacing yyyy with the PAT you established on the GitHub website. 24 | 25 | You may first need to install the `unitted` dependency: 26 | ```{r, eval=FALSE} 27 | remotes::install_github('appling/unitted') 28 | ``` 29 | 30 | You can then install the most cutting edge version of streamMetabolizer with this command: 31 | ```{r, eval=FALSE} 32 | remotes::install_github( 33 | "USGS-R/streamMetabolizer", # soon to be "DOI-USGS/streamMetabolizer" 34 | build_vignettes = TRUE) 35 | ``` 36 | 37 | ## Software dependencies for Bayesian models 38 | 39 | The major dependency for Bayesian models is the `rstan` package, and installation of that package is rarely as simple as a call to `install.packages()`. Start at the [rstan wiki page](https://github.com/stan-dev/rstan/wiki) for the most up-to-date installation instructions, which differ by operating system. 40 | -------------------------------------------------------------------------------- /man/metab_model.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_model-class.R 3 | \name{metab_model} 4 | \alias{metab_model} 5 | \title{Create a metab_model object.} 6 | \usage{ 7 | metab_model( 8 | model_class = "metab_model", 9 | info = "user metadata goes here", 10 | metab_daily = NULL, 11 | fit = "generic metab_model class; no actual fit", 12 | fitting_time = system.time({ }), 13 | specs = list(), 14 | data = mm_data(solar.time, DO.obs, DO.sat, depth, temp.water, light), 15 | data_daily = mm_data(date, optional = "all"), 16 | pkg_version = as.character(packageVersion("streamMetabolizer")), 17 | ... 18 | ) 19 | } 20 | \arguments{ 21 | \item{model_class}{character name of a class inheriting from metab_model - 22 | the type of object to create} 23 | 24 | \item{info}{User-supplied metadata of any form.} 25 | 26 | \item{metab_daily}{a data.frame of daily metabolism estimates produced from 27 | the fit.} 28 | 29 | \item{fit}{An internal representation of a fitted model.} 30 | 31 | \item{fitting_time}{A proc_time object giving the time taken to fit the 32 | model.} 33 | 34 | \item{specs}{A list of model specifications that were supplied to the fitting 35 | function.} 36 | 37 | \item{data}{The data that were used to fit the model.} 38 | 39 | \item{data_daily}{The data_daily that were used to fit the model. May be 40 | NULL.} 41 | 42 | \item{pkg_version}{A string indicating the package version used to create 43 | this metab_model object. The default should almost always be appropriate.} 44 | 45 | \item{...}{other arguments passed to new() for this particular model_class} 46 | } 47 | \value{ 48 | A metab_model object. 49 | } 50 | \description{ 51 | Generates a new model of class metab_model (\code{\link{metab_model-class}}). 52 | } 53 | \examples{ 54 | metab_model() 55 | metab_model("metab_mle", fit=1:5, specs=list(length=5)) 56 | } 57 | -------------------------------------------------------------------------------- /man/calc_zenith_angle.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/calc_solar_insolation.R 3 | \name{calc_zenith_angle} 4 | \alias{calc_zenith_angle} 5 | \title{Calculate zenith angle as in 6 | http://education.gsfc.nasa.gov/experimental/July61999siteupdate/inv99Project.Site/Pages/solar.insolation.html} 7 | \usage{ 8 | calc_zenith_angle( 9 | latitude, 10 | declination.angle, 11 | hour.angle, 12 | format = c("degrees", "radians") 13 | ) 14 | } 15 | \arguments{ 16 | \item{latitude}{numeric value or vector indicating the site latitude in 17 | decimal degrees (never radians or deg-min-sec, no matter what \code{format} 18 | is) between -90 (South Pole) and 90 (North Pole).} 19 | 20 | \item{declination.angle}{numeric value or vector, in the units specified by 21 | \code{format}, indicating the declination angle.} 22 | 23 | \item{hour.angle}{numeric value or vector, in the units specified by 24 | \code{format}, indicating the angle.} 25 | 26 | \item{format}{The format of both the output. May be "degrees" or "radians".} 27 | } 28 | \description{ 29 | Calculate zenith angle as in 30 | http://education.gsfc.nasa.gov/experimental/July61999siteupdate/inv99Project.Site/Pages/solar.insolation.html 31 | } 32 | \examples{ 33 | zendf <- data.frame( 34 | lat=rep(c(0,20,40,60), each=24*4), 35 | jday=rep(rep(c(1,101,201,301), each=24), times=4), 36 | hour=rep(c(0:12,13.5:23.5), times=4*4)) 37 | zendf <- transform(zendf, 38 | dec=streamMetabolizer:::calc_declination_angle(jday), 39 | hragl=streamMetabolizer:::calc_hour_angle(hour)) 40 | zendf <- transform(zendf, 41 | zen=streamMetabolizer:::calc_zenith_angle(lat, dec, hragl)) 42 | \dontrun{ 43 | library(ggplot2) 44 | ggplot(unitted::v(zendf), aes(x=hour, y=zen, color=jday, group=jday)) + 45 | geom_line() + facet_wrap(~lat) + 46 | ggtitle('zenith angles by latitude (panels) and day of year (colors)') 47 | } 48 | } 49 | -------------------------------------------------------------------------------- /R/calc_DO_deficit.R: -------------------------------------------------------------------------------- 1 | #' Deprecated: Calculate a vector of dissolved oxygen deficits 2 | #' 3 | #' Deprecated: Submit a GitHub issue if you want calc_DO_deficit() to stick 4 | #' around. Creates a DO.deficit vector for input into metabolism models. 5 | #' 6 | #' @md 7 | #' @param DO.obs a numeric vector of dissolved oxygen concentration 8 | #' observations, mgO2 L^-1, or a \linkS4class{unitted} object of dissolved 9 | #' oxygen concentrations. 10 | #' @param temp.water a numeric vector of water temperature in degrees Celsius, 11 | #' or a \linkS4class{unitted} object of water temperatures. 12 | #' @param pressure.air barometric pressure in millibars, or a 13 | #' \linkS4class{unitted} object of barometric pressure. 14 | #' @param salinity.water a numeric vector of salinity in PSU, or a 15 | #' \linkS4class{unitted} object of salinity. Defaults to zero. Length must be 16 | #' one or equal to length of \code{temp.water}. 17 | #' @param ... additional parameters passed to 18 | #' `LakeMetabolizer::o2.at.sat.base` 19 | #' @return a vector of DO.deficit values 20 | #' @examples 21 | #' \dontrun{ 22 | #' # Warning: this function is deprecated. 23 | #' calc_DO_deficit(DO.obs=7, temp.water=25, pressure.air=900, salinity.water=2.43) 24 | #' library(unitted) 25 | #' calc_DO_deficit( 26 | #' DO.obs = u(c(7,7.5,7),'mgO2 L^-1'), 27 | #' temp.water = u(c(25,24.5,18.9), 'degC'), 28 | #' pressure.air = u(c(900,903,910), 'mb'), 29 | #' salinity.water = u(2.43, 'PSU')) 30 | #' } 31 | #' @export 32 | calc_DO_deficit <- function(DO.obs, temp.water, pressure.air, salinity.water = 0, ...){ 33 | 34 | .Deprecated() 35 | warning("submit a GitHub issue if you want calc_DO_deficit() to stick around") 36 | 37 | DO.equil <- calc_DO_sat(temp.water, pressure.air, salinity.water, ...) 38 | 39 | # to do: verify incoming units (convert if needed?) and set DO.equil units to mgO2 L^-1 40 | DO.deficit <- DO.equil-DO.obs 41 | 42 | return(DO.deficit) 43 | } 44 | -------------------------------------------------------------------------------- /man/bayes_1ply.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_bayes.R 3 | \name{bayes_1ply} 4 | \alias{bayes_1ply} 5 | \title{Make daily metabolism estimates from input parameters} 6 | \usage{ 7 | bayes_1ply(data_ply, data_daily_ply, ply_date, ply_validity, ..., specs) 8 | } 9 | \arguments{ 10 | \item{data_ply}{a data.frame containing all relevant, validated modeling data 11 | for a single ply of data. (1 ply ~= 1 date, although the day length has 12 | been specified by day_start and day_end and may not be exactly 24 hours)} 13 | 14 | \item{data_daily_ply}{NULL or a data.frame containing inputs with a daily 15 | timestep.} 16 | 17 | \item{ply_date}{the modal date of this ply of data and data_daily, and the 18 | date by which this ply should be referred topresent.} 19 | 20 | \item{ply_validity}{the output of \code{mm_is_valid_day} as applied to this 21 | data_ply for those tests specified in \code{day_tests}. Those tests will 22 | have been run before this function is called. The result is TRUE if the ply 23 | is entirely valid, or a character vector containing one or more error 24 | messages if any tests failed.} 25 | 26 | \item{...}{other args that were passed untouched from the function calling 27 | mm_model_by_ply, through mm_model_by_ply, and finally to this function.} 28 | 29 | \item{specs}{a list of model specifications and parameters for a model. 30 | Although this may be specified manually (it's just a list), it is easier 31 | and safer to use \code{\link{specs}} to generate the list, because the set 32 | of required parameters and their defaults depends on the model given in the 33 | \code{model_name} argument to \code{specs}. The help file for 34 | \code{\link{specs}} lists the necessary parameters, describes them in 35 | detail, and gives default values.} 36 | } 37 | \value{ 38 | data.frame of estimates and MCMC model diagnostics 39 | } 40 | \description{ 41 | Called from metab_bayes(). 42 | } 43 | \keyword{internal} 44 | -------------------------------------------------------------------------------- /man/mm_predict_DO_1ply.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mm_predict_DO_1ply.R 3 | \name{mm_predict_DO_1ply} 4 | \alias{mm_predict_DO_1ply} 5 | \title{Helper to predict_DO.metab_model} 6 | \usage{ 7 | mm_predict_DO_1ply( 8 | data_ply, 9 | data_daily_ply, 10 | day_start, 11 | day_end, 12 | ply_date, 13 | ..., 14 | model_name 15 | ) 16 | } 17 | \arguments{ 18 | \item{data_ply}{a data.frame containing all relevant, validated modeling data 19 | for a single ply of data. (1 ply ~= 1 date, although the day length has 20 | been specified by day_start and day_end and may not be exactly 24 hours)} 21 | 22 | \item{data_daily_ply}{NULL or a data.frame containing inputs with a daily 23 | timestep.} 24 | 25 | \item{day_start}{start time (inclusive) of a day's data in number of hours 26 | from the midnight that begins the date. For example, day_start=-1.5 27 | indicates that data describing 2006-06-26 begin at 2006-06-25 22:30, or at 28 | the first observation time that occurs after that time if day_start doesn't 29 | fall exactly on an observation time.} 30 | 31 | \item{day_end}{end time (exclusive) of a day's data in number of hours from 32 | the midnight that begins the date. For example, day_end=30 indicates that 33 | data describing 2006-06-26 end at the last observation time that occurs 34 | before 2006-06-27 06:00.} 35 | 36 | \item{ply_date}{the modal date of this ply of data and data_daily, and the 37 | date by which this ply should be referred topresent.} 38 | 39 | \item{...}{other args that were passed untouched from the function calling 40 | mm_model_by_ply, through mm_model_by_ply, and finally to this function.} 41 | 42 | \item{model_name}{the coded model name that will determine the GPP_fun, 43 | ER_fun, deficit_src, and ode_method to use in prediction} 44 | } 45 | \value{ 46 | a data.frame of predictions 47 | } 48 | \description{ 49 | Usually assigned to model_fun within mm_model_by_ply, called from there 50 | } 51 | -------------------------------------------------------------------------------- /man/plot_DO_preds.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/plot_DO_preds.R 3 | \name{plot_DO_preds} 4 | \alias{plot_DO_preds} 5 | \title{Plot predictions produced with predict_DO} 6 | \usage{ 7 | plot_DO_preds( 8 | DO_preds, 9 | y_var = c("conc", "pctsat", "ddodt"), 10 | style = c("ggplot2", "dygraphs"), 11 | y_lim = list(conc = c(NA, NA), pctsat = c(NA, NA), ddodt = c(NA, NA)), 12 | date_start = NA, 13 | date_end = NA, 14 | use_saved = TRUE 15 | ) 16 | } 17 | \arguments{ 18 | \item{DO_preds}{a data.frame of predictions such as that returned by 19 | predict_DO()} 20 | 21 | \item{y_var}{character. Should the plot display predicted & observed values 22 | in concentration (conc) or as percent of saturation (pctsat)? The default 23 | is to plot both.} 24 | 25 | \item{style}{character indicating which graphics package to use} 26 | 27 | \item{y_lim}{list of named vectors, each of which has length 2 and is numeric 28 | and has a name in the possible values of y_var. NA within a vector 29 | indicates that the data range should be used. for ggplot2, y_lim is only 30 | used to exclude values outside that range and is ignored if the data span a 31 | narrower range} 32 | 33 | \item{date_start}{Date or a class convertible with as.Date. The first date 34 | (inclusive) for which to report DO predictions. If NA, no filtering is 35 | done.} 36 | 37 | \item{date_end}{Date or a class convertible with as.Date. The last date 38 | (inclusive) for which to report DO predictions. If NA, no filtering is 39 | done.} 40 | 41 | \item{use_saved}{logical. Is it OK to use predictions that were saved with 42 | the model?} 43 | } 44 | \description{ 45 | Plots modeled values as lines, observed values as points 46 | } 47 | \examples{ 48 | \dontrun{ 49 | mm <- metab_night(specs(mm_name('night')), data=data_metab('3', day_start=12, day_end=36)) 50 | plot_DO_preds(mm) 51 | plot_DO_preds(mm, date_start='2012-09-19', date_end='2012-09-19') 52 | plot_DO_preds(mm, style='dygraphs', y_var='pctsat') 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /tests/testthat/test-metab-class.R: -------------------------------------------------------------------------------- 1 | context("metab_model class and inheriting classes") 2 | 3 | test_that("metab_model objects can be created and accessed", { 4 | 5 | # basic structure of metab_model parent class 6 | mm <- metab_model() 7 | expect_output(print(slot(mm, "fit")), "generic metab_model class; no actual fit") 8 | expect_true(all(names(formals(metab)) %in% names(getSlots('metab_model'))), info="slots should match args to metab()") 9 | expect_is(slot(mm, "fitting_time"), "proc_time", info="time should be recorded") 10 | expect_is(slot(mm, "data"), "data.frame", info="default should populate with example data") 11 | expect_is(slot(mm, "pkg_version"), "character", info="pkg version should be autopopulated") 12 | 13 | # display 14 | expect_output(print(mm), "metab_model", info="model type should be shown") 15 | 16 | # accessors 17 | expect_equal(slot(mm, "fit"), get_fit(mm)) 18 | expect_equal(slot(mm, "specs"), get_specs(mm)) 19 | expect_equal(slot(mm, "data"), get_data(mm)) 20 | expect_equal(slot(mm, "pkg_version"), get_version(mm)) 21 | expect_equal(slot(mm, "info"), get_info(mm)) 22 | }) 23 | 24 | test_that("metab_models have default predict_metab and predict_DO methods", { 25 | 26 | mm <- metab_model() 27 | expect_null(get_params(mm)) 28 | expect_null(predict_metab(mm)) 29 | expect_null(predict_DO(mm)) 30 | 31 | }) 32 | 33 | # slow, therefore manual 34 | manual_test <- function() { 35 | test_that("metab_models can be saved & reloaded (see helper-save_load.R)", { 36 | 37 | # save and reload 38 | mm <- metab_model() 39 | 40 | # see if saveRDS with gzfile, compression=9 works well 41 | rdstimes <- save_load_timing(mm, reps=1) # autoloaded b/c script begins with 'helper' and is in this directory 42 | expect_true('gz6' %in% rdstimes$typelevel[1:3], info="gz6 is reasonably efficient for saveRDS") 43 | plot_save_load_timing(rdstimes) 44 | 45 | # save and load the mm, make sure it stays the same 46 | test_save_load_recovery(mm) 47 | 48 | }) 49 | } 50 | -------------------------------------------------------------------------------- /R/metab_inputs.R: -------------------------------------------------------------------------------- 1 | #' Describe the requirements for an argument to metab() 2 | #' 3 | #' @param type the type of model you want to fit 4 | #' @param input the name of an argument to pass into metab() 5 | #' @import dplyr 6 | #' @importFrom unitted v u get_units 7 | #' @examples 8 | #' metab_inputs('night','specs') 9 | #' metab_inputs('bayes','data') 10 | #' metab_inputs('Kmodel','data_daily') 11 | #' metab_inputs('mle','info') 12 | #' @export 13 | metab_inputs <- function(type=c('bayes','mle','night','Kmodel','sim'), input=c('specs','data','data_daily','info')) { 14 | 15 | # check inputs 16 | type <- match.arg(type) 17 | input <- match.arg(input) 18 | 19 | if(input == 'specs') { 20 | paste0("specs(mm_name('",type,"'))", 21 | " # see ?mm_name, ?mm_specs for more options") 22 | } else if(input %in% c('data','data_daily')) { 23 | mfun <- paste0('metab_',type) 24 | eg <- eval(formals(mfun)[[input]]) 25 | # reformat so there's a row each for units, format, example, and optional-T/F 26 | if(is.null(v(eg))) { 27 | 'NULL' 28 | } else { 29 | . <- 'dplyr.var' 30 | data.frame( 31 | colname = { 32 | names(eg) 33 | }, 34 | class = { 35 | sapply(unname(v(eg)), function(col) paste0(class(col), collapse=',')) 36 | }, 37 | units = { 38 | get_units(eg) %>% 39 | unname() 40 | }, 41 | need = { 42 | opt <- attr(eg, 'optional') 43 | opt_vec <- if(opt[1]=='all') { 44 | rep('optional', length(eg)) 45 | } else if(opt[1]=='none') { 46 | rep('required', length(eg)) 47 | } else { 48 | ifelse(names(eg) %in% opt, 'optional', 'required') 49 | } 50 | }, 51 | stringsAsFactors=FALSE) 52 | } 53 | # bind_rows %>% 54 | # u(c(type=NA, get_units(mm_data(everything())))[names(.)]) 55 | } else if(input == 'info') { 56 | "info may be NULL, a list, or any other data you want to attach to the output of metab()" 57 | } 58 | } 59 | -------------------------------------------------------------------------------- /man/plot_distribs.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/plot_distribs.R 3 | \name{plot_distribs} 4 | \alias{plot_distribs} 5 | \title{Plot the prior/posterior distributions of a parameter} 6 | \usage{ 7 | plot_distribs( 8 | dist_data, 9 | parname = c("GPP_daily", "alpha", "Pmax", "ER_daily", "K600_daily", 10 | "K600_daily_meanlog", "lnK600_lnQ_intercept", "lnK600_lnQ_slope", "K600_lnQ_nodes", 11 | "K600_daily_sdlog", "K600_daily_sigma", "err_obs_iid_sigma", "err_proc_acor_phi", 12 | "err_proc_acor_sigma", "err_proc_iid_sigma", "err_mult_GPP_sdlog"), 13 | index = TRUE, 14 | style = c("dygraphs", "ggplot2") 15 | ) 16 | } 17 | \arguments{ 18 | \item{dist_data}{Either a specs list (for priors only) or a metab_model 19 | object (for both priors and posteriors).} 20 | 21 | \item{parname}{character. the name of the parameter whose distribution[s] you 22 | wish to plot} 23 | 24 | \item{index}{integer or logical. Applicable only if plotting posteriors, and 25 | useful only if the parname is for a parameter having multiple (e.g., daily) 26 | instances. In this case, the index selects the instance and corresponds to 27 | the row number in the data.frame element of \code{get_fit(metab_model)} 28 | that contains the parameter, e.g. \code{get_fit(metab_model)$daily} for 29 | \code{'GPP_daily'}. The default, TRUE, selects and pools all instances of 30 | the parameter.} 31 | 32 | \item{style}{character indicating which graphics package to use} 33 | } 34 | \description{ 35 | Plot the prior and/or posterior disitrubtions as implied by the 36 | hyperparameters in a specs list and/or the 37 | } 38 | \examples{ 39 | \dontrun{ 40 | # priors only 41 | plot_distribs(specs('bayes', K600_daily_mu=30), 'K600_daily') 42 | 43 | # posteriors, too 44 | mm <- metab(specs(mm_name('bayes')), data=data_metab('1', res='30')) 45 | plot_distribs(mm, 'GPP_daily', 1) 46 | 47 | # with modifications 48 | plot_distribs(mm, 'err_proc_iid_sigma') \%>\% 49 | dygraphs::dyRangeSelector(dateWindow=c(-0.1,1.3)) \%>\% 50 | dygraphs::dyAxis(name='y', valueRange=c(0,15)) 51 | } 52 | } 53 | -------------------------------------------------------------------------------- /R/load_spring_creek.R: -------------------------------------------------------------------------------- 1 | #' Load a short dataset from Spring Creek 2 | #' 3 | #' @import dplyr 4 | #' @importFrom unitted u 5 | #' @importFrom utils read.csv 6 | #' @importFrom lubridate with_tz 7 | #' @importFrom lifecycle deprecated is_present 8 | #' @param attach.units (deprecated, effectively FALSE in future) logical, 9 | #' default TRUE for backward compatibility. Should units be attached to the 10 | #' data.frame? 11 | #' @return a data.frame, unitted if attach.units==TRUE 12 | load_spring_creek <- function(attach.units=deprecated()) { 13 | # check units arguments 14 | if (lifecycle::is_present(attach.units)) { 15 | # only warn if it's TRUE 16 | if(isTRUE(attach.units)) unitted_deprecate_warn("load_spring_creek(attach.units)") 17 | } else { 18 | attach.units <- TRUE 19 | } 20 | 21 | # load the file 22 | file.name <- system.file("extdata", "spring14.csv", package="streamMetabolizer") # data from Spring Creek, Laramie, WY 23 | time <- utc.time <- oxy <- temp <- solar.time <- app.solar.time <- ".dplyr.var" 24 | spring <- read.csv(file.name, stringsAsFactors=FALSE, header=TRUE) %>% 25 | transmute( 26 | utc.time = as.POSIXct(time, origin="1970-01-01", tz="UTC"), 27 | local.time = with_tz(utc.time, "America/Denver"), 28 | DO.obs = u(oxy, 'mgO2 L^-1'), 29 | temp.water = u(temp, 'degC')) %>% 30 | u() %>% 31 | mutate( 32 | DO.sat = calc_DO_sat(temp.water=temp.water, pressure.air=u(595, "mmHg")*unitted::u(1.33322368, "mb mmHg^-1")), 33 | depth = u(rep(0.18, length(temp.water)), "m"), 34 | solar.time = convert_UTC_to_solartime(utc.time, longitude=-105.6, time.type='mean solar'), 35 | app.solar.time = convert_UTC_to_solartime(utc.time, longitude=-105.6, time.type='apparent solar'), 36 | light = convert_SW_to_PAR(calc_solar_insolation(app.solar.time=v(app.solar.time), latitude=41.33, max.insolation=convert_PAR_to_SW(2326), attach.units=TRUE)) 37 | ) 38 | 39 | # return w/ proper units & columns 40 | spring <- if(attach.units) spring else v(spring) 41 | spring[c("solar.time","DO.obs","DO.sat","depth","temp.water","light")] 42 | } 43 | -------------------------------------------------------------------------------- /R/lookup_usgs_elevation.R: -------------------------------------------------------------------------------- 1 | #' Use USGS API (USGS Elevation Point Query Service) to determine approximate 2 | #' local elevation 3 | #' 4 | #' This is meant to supply an APPROXIMATE elevation, with no guarantees on 5 | #' precision or on the lifetime of the API service used by the function. This 6 | #' function uses two packages, \code{RCurl} and \code{XML}, that are not 7 | #' required for the \code{streamMetabolizer} package as a whole. If these are 8 | #' not already installed, run \code{install.packages(c('RCurl','XML'))} before 9 | #' calling \code{lookup_usgs_elevation}. 10 | #' 11 | #' @param latitude degrees latitude (positive for north) of the location to look 12 | #' up. 13 | #' @param longitude degrees longitude (positive for east) of the location to 14 | #' look up. 15 | #' @param units character, one of Meters or Feet, specifying the units in which 16 | #' to return the elevation 17 | #' @references https://nationalmap.gov/epqs/ 18 | #' @importFrom unitted u 19 | #' @export 20 | lookup_usgs_elevation <- function( 21 | latitude, longitude, units=c("Meters","Feet")) { 22 | 23 | # confirm that units are among the accepted values for ned.usgs.gov 24 | units <- match.arg(units) 25 | 26 | # check for required packages specific to this function 27 | if(!requireNamespace("RCurl", quietly = TRUE)) { 28 | stop("the RCurl package must be installed to use this function") 29 | } 30 | if(!requireNamespace("XML", quietly = TRUE)) { 31 | stop("the XML package must be installed to use this function") 32 | } 33 | 34 | # ask the USGS 35 | api.url <- sprintf("https://nationalmap.gov/epqs/pqs.php?x=%f&y=%f&units=%s&output=xml", 36 | longitude, latitude, units) 37 | api.out <- RCurl::getURL(api.url, .opts = list(ssl.verifypeer = FALSE)) 38 | out.parsed <- XML::xmlParse(api.out) 39 | out.units <- switch( 40 | out.parsed[["string(//Units)"]], 41 | "Feet"="ft", 42 | "Meters"="m") 43 | return(list( 44 | data_source = out.parsed[["string(//Data_Source)"]], 45 | elevation = u(as.numeric(out.parsed[["string(//Elevation)"]]), out.units) 46 | )) 47 | } 48 | -------------------------------------------------------------------------------- /inst/extdata/KfQ_procobserr.jags: -------------------------------------------------------------------------------- 1 | model { 2 | 3 | # DAY-SPECIFIC PARAMETERS 4 | for(d in 1:nday) { 5 | 6 | # Daily mean values of GPP and ER (gO2 m^-2 d^-1) 7 | GPP_daily[d] ~ dnorm(GPP_daily_mu, pow(GPP_daily_sigma, -2)) 8 | ER_daily[d] ~ dnorm(ER_daily_mu, pow(ER_daily_sigma, -2)) 9 | 10 | # Linear relationship between K600 (m d^-1) and daily, standardized, centered, logged Q 11 | K600_daily[d] ~ dnorm(KQ_icpt + KQ_slope*log(standardize(center(Q))), K600_daily_tau) 12 | 13 | # Convert daily rates to per-observation rates 14 | for(i in 1:n[d]) { 15 | GPP[i,d] <- GPP_daily[d] * frac_GPP[i,d] / depth[i,d] 16 | ER[i,d] <- ER_daily[d] * frac_ER[i,d] / depth[i,d] 17 | K[i,d] <- K600_daily[d] * KO2_conv[i,d] * frac_D[i,d] 18 | } 19 | 20 | # Set up initial DO_mod and err_proc_acor for the day 21 | DO_mod[1,d] <- DO_obs[1,d] 22 | err_proc_acor[1,d] <- 0 23 | 24 | # TIMESTEP-SPECIFIC PARAMETERS 25 | for(i in 2:n[d]) { 26 | # Model DO changes as in Hotchkiss & Hall 2014, eq. 2 27 | DO_mod[i,d] <- DO_mod[i-1,d] + 28 | GPP[i,d] + 29 | ER[i,d] + 30 | K[i,d] * (DO_sat[i,d] - DO_mod[i-1,d]) + 31 | err_proc_acor[i,d] 32 | 33 | # Process error: Build an error timeseries with a fitted autocorrelation structure 34 | err_proc_acor[i,d] ~ dnorm(err_proc_acor_phi*err_proc_acor[i-1,d], pow(err_proc_acor_sigma, -2)) 35 | 36 | # Observation error: Compare all the DO predictions to their observations 37 | DO_obs[i,d] ~ dnorm(DO_mod[i,d], pow(err_obs_iid_sigma, -2)) 38 | 39 | } 40 | } 41 | 42 | # TIME-INDEPENDENT PARAMETERS 43 | 44 | # Prior on the sd of the errors between modeled and observed DO 45 | err_obs_iid_sigma ~ dunif(0, 0.5) 46 | 47 | # Prior on the autocorrelation & sd of the process errors 48 | err_proc_acor_phi <- 1 49 | err_proc_acor_sigma ~ dunif(0, 0.5) 50 | 51 | # Priors on the intercept and slope of the K ~ Q relationshipo 52 | KQ_icpt ~ dnorm(3, 1) 53 | KQ_slope ~ dnorm(0, 1) 54 | 55 | # Supplied by the input 56 | # GPP_daily_mu, GPP_daily_sigma 57 | # ER_daily_mu, ER_daily_sigma 58 | 59 | } 60 | -------------------------------------------------------------------------------- /R/convert_PAR_to_SW.R: -------------------------------------------------------------------------------- 1 | #' Convert from photosynthetically active to shortwave radiation 2 | #' 3 | #' Convert photosynthetically active radiation (PAR) to shortwave radiation 4 | #' (SW). Uses a fixed ratio between PAR and SW, ignoring the minor seasonal 5 | #' changes in this ratio (see Britton and Dodd (1976)). 6 | #' 7 | #' @param par Vector of photosynthetically active radiation (400-700 nm; 8 | #' umol/m^2/sec) 9 | #' @param coef Numerical coefficient to convert PAR (umol/m^2/sec) to SW 10 | #' (W/m^2). Defaults to value from Britton and Dodd (1976). 11 | #' @return Numeric vector of shortwave values with units W/m^2 12 | #' 13 | #' @examples 14 | #' convert_PAR_to_SW(par=400, coef=0.47) 15 | #' convert_PAR_to_SW(unitted::u(1000, "umol m^-2 s^-1")) 16 | #' @importFrom LakeMetabolizer par.to.sw.base 17 | #' @importFrom unitted is.unitted verify_units 18 | #' @export 19 | convert_PAR_to_SW <- function(par, coef=0.473) { 20 | if(is.unitted(par)) { 21 | verify_units(par, "umol m^-2 s^-1") 22 | coef <- u(coef, "W umol^-1 s") 23 | } 24 | (LakeMetabolizer::par.to.sw.base(par, coef)) # parentheses to return value as visible 25 | } 26 | 27 | #' Convert from shortwave to photosynthetically active radiation 28 | #' 29 | #' Convert shortwave radiation (SW) to photosynthetically active radiation 30 | #' (PAR). Uses a fixed ratio between SW and PAR, ignoring the minor seasonal 31 | #' changes in this ratio (see Britton and Dodd (1976)). 32 | #' 33 | #' @param sw Vector of shortwave radiation (W/m^2) 34 | #' @param coef Numerical coefficient to convert SW (W/m^2) to PAR 35 | #' (umol/m^2/sec). Defaults to value from Britton and Dodd (1976). 36 | #' @return Numeric vector of PAR values in units umol/m^2/sec 37 | #' 38 | #' @examples 39 | #' convert_SW_to_PAR(sw=800) 40 | #' convert_SW_to_PAR(sw=800, coef=2.1) 41 | #' convert_SW_to_PAR(unitted::u(473, "W m^-2")) 42 | #' @importFrom LakeMetabolizer sw.to.par.base 43 | #' @export 44 | convert_SW_to_PAR <- function(sw, coef=2.114) { 45 | if(is.unitted(sw)) { 46 | verify_units(sw, "W m^-2") 47 | coef <- u(coef, "umol s^-1 W^-1") 48 | } 49 | (LakeMetabolizer::sw.to.par.base(sw, coef)) # parentheses to return value as visible 50 | } 51 | -------------------------------------------------------------------------------- /R/calc_light.R: -------------------------------------------------------------------------------- 1 | #' Calculate modeled light from solar.time 2 | #' 3 | #' Calculate photosynthetically active radiation (PAR) for a series of 4 | #' date-times and site coordinates. 5 | #' 6 | #' @param solar.time mean solar time, as required for input to metabolism 7 | #' models. See \code{\link{mm_data}} and \code{\link{calc_solar_time}}. 8 | #' @inheritParams calc_zenith_angle 9 | #' @inheritParams convert_solartime_to_UTC 10 | #' @param max.PAR numeric or unitted_numeric: the PAR (umol m^-2 s^-1) that each 11 | #' day should reach at peak light 12 | #' @inheritParams calc_solar_insolation 13 | #' @import dplyr 14 | #' @importFrom lifecycle deprecated is_present 15 | #' @examples 16 | #' solar.time <- lubridate::force_tz(as.POSIXct('2016-09-27 12:00'), 'UTC') 17 | #' calc_light(solar.time, 40, -120) 18 | #' library(unitted) 19 | #' calc_light(u(solar.time), u(40, 'degN'), u(-120, 'degE'), u(2315, 'umol m^-2 s^-1')) 20 | #' @export 21 | calc_light <- function( 22 | solar.time, latitude, longitude, max.PAR=u(2326, 'umol m^-2 s^-1'), 23 | attach.units=deprecated()) { 24 | 25 | # check units-related arguments. old default was attach.units=is.unitted(solar.time) 26 | if (lifecycle::is_present(attach.units)) { 27 | # only warn if it's TRUE 28 | if(isTRUE(attach.units)) unitted_deprecate_warn("calc_light(attach.units)") 29 | } else if (is.unitted(solar.time)) { 30 | unitted_deprecate_warn("calc_light(solar.time.unitted)") 31 | message('in calc_light, setting attach.units=TRUE because is.unitted(solar.time)') 32 | attach.units <- TRUE 33 | } else { 34 | attach.units <- FALSE 35 | } 36 | 37 | coef.SW.to.PAR <- formals(convert_SW_to_PAR)$coef # shouldn't really matter what is b/c we convert out and back 38 | app.solar.time <- v(solar.time) %>% 39 | convert_solartime_to_UTC(longitude=longitude, time.type='mean solar') %>% 40 | convert_UTC_to_solartime(longitude=longitude, time.type='apparent solar') 41 | sw <- calc_solar_insolation( 42 | app.solar.time, latitude=latitude, 43 | max.insolation=convert_PAR_to_SW(max.PAR, coef=1/coef.SW.to.PAR), 44 | format=c("degrees", "radians"), attach.units=attach.units) 45 | par <- convert_SW_to_PAR(sw, coef=coef.SW.to.PAR) 46 | 47 | par 48 | } 49 | -------------------------------------------------------------------------------- /man/metab_night_predict_1ply.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_night.R 3 | \name{metab_night_predict_1ply} 4 | \alias{metab_night_predict_1ply} 5 | \title{Helper to predict_DO.metab_model} 6 | \usage{ 7 | metab_night_predict_1ply( 8 | data_ply, 9 | data_daily_ply, 10 | day_start, 11 | day_end, 12 | ply_date, 13 | timestep_days, 14 | ..., 15 | model_name 16 | ) 17 | } 18 | \arguments{ 19 | \item{data_ply}{a data.frame containing all relevant, validated modeling data 20 | for a single ply of data. (1 ply ~= 1 date, although the day length has 21 | been specified by day_start and day_end and may not be exactly 24 hours)} 22 | 23 | \item{data_daily_ply}{NULL or a data.frame containing inputs with a daily 24 | timestep.} 25 | 26 | \item{day_start}{start time (inclusive) of a day's data in number of hours 27 | from the midnight that begins the date. For example, day_start=-1.5 28 | indicates that data describing 2006-06-26 begin at 2006-06-25 22:30, or at 29 | the first observation time that occurs after that time if day_start doesn't 30 | fall exactly on an observation time.} 31 | 32 | \item{day_end}{end time (exclusive) of a day's data in number of hours from 33 | the midnight that begins the date. For example, day_end=30 indicates that 34 | data describing 2006-06-26 end at the last observation time that occurs 35 | before 2006-06-27 06:00.} 36 | 37 | \item{ply_date}{the modal date of this ply of data and data_daily, and the 38 | date by which this ply should be referred topresent.} 39 | 40 | \item{timestep_days}{numeric length of the mean timestep for this day, if 41 | requested by setting \code{timestep_days} to \code{TRUE} or a numeric value 42 | in the call to \code{\link{mm_model_by_ply}}} 43 | 44 | \item{...}{other args that were passed untouched from the function calling 45 | mm_model_by_ply, through mm_model_by_ply, and finally to this function.} 46 | 47 | \item{model_name}{the coded model name that will determine the GPP_fun, 48 | ER_fun, deficit_src, and ode_method to use in prediction} 49 | } 50 | \value{ 51 | a data.frame of predictions 52 | } 53 | \description{ 54 | Usually assigned to model_fun within mm_model_by_ply, called from there 55 | } 56 | -------------------------------------------------------------------------------- /R/metab_model.predict_DO.R: -------------------------------------------------------------------------------- 1 | #' @include metab_model-class.R 2 | NULL 3 | 4 | #' @describeIn predict_DO This implementation is shared by many model types 5 | #' @export 6 | #' @import dplyr 7 | #' @importFrom lubridate tz 8 | #' @importFrom unitted u v get_units 9 | #' @importFrom lifecycle deprecated is_present 10 | predict_DO.metab_model <- function( 11 | metab_model, date_start=NA, date_end=NA, 12 | ..., attach.units=deprecated(), use_saved=TRUE) { 13 | 14 | # check units-related arguments 15 | if (lifecycle::is_present(attach.units)) { 16 | unitted_deprecate_warn("predict_DO(attach.units)") 17 | } else { 18 | attach.units <- FALSE 19 | } 20 | 21 | # pull args from the model 22 | specs <- get_specs(metab_model) 23 | day_start <- specs$day_start 24 | day_end <- specs$day_end 25 | 26 | # get the input data; filter if requested 27 | data <- get_data(metab_model) %>% 28 | v() %>% # units are discarded here. someday we'll get them worked through the whole system. 29 | mm_filter_dates(date_start=date_start, date_end=date_end, day_start=day_start, day_end=day_end) 30 | 31 | # if allowed and available, use previously stored values for DO.mod rather than re-predicting them now 32 | if(isTRUE(use_saved) && !is.null(data) && "DO.mod" %in% names(data)) { 33 | return(data) 34 | } 35 | 36 | # get the metabolism estimates; filter as we did for data 37 | metab_ests <- get_params(metab_model, date_start=date_start, date_end=date_end, uncertainty='none', messages=FALSE) 38 | 39 | # if we lack the data or params to predict, return NULL now 40 | if(is.null(data) || nrow(data) == 0 || is.null(metab_ests)) 41 | return(NULL) 42 | 43 | # re-process the input data with the metabolism estimates to predict DO 44 | preds <- mm_model_by_ply( 45 | mm_predict_DO_1ply, data=data, data_daily=metab_ests, # for mm_model_by_ply 46 | day_start=day_start, day_end=day_end, day_tests=c(), timestep_days=FALSE, required_timestep=NA, # for mm_model_by_ply 47 | model_name=specs$model_name) %>% # for mm_predict_DO_1ply 48 | mm_filter_dates(date_start=date_start, date_end=date_end) # trim off the extra 49 | 50 | if(attach.units) preds <- u(preds, get_units(mm_data())[gsub('DO.mod','DO.obs',names(preds))]) 51 | preds 52 | } 53 | -------------------------------------------------------------------------------- /R/mm_check_mcmc_file.R: -------------------------------------------------------------------------------- 1 | #' Use an engine-specific function to check the model syntax 2 | #' 3 | #' @param model_file the file path of the model file to check; the extension 4 | #' will be used to determine which engine to use for checking. 5 | #' @keywords internal 6 | mm_check_mcmc_file <- function(model_file) { 7 | engine <- mm_parse_name(model_file)$engine 8 | if(!file.exists(model_file)) model_file <- paste0('inst/models/', model_file) 9 | if(engine != 'stan') stop('need to add handling for engines other than stan') 10 | 11 | # stan() can't find its own function cpp_object_initializer() unless the 12 | # namespace is loaded. requireNamespace is somehow not doing this. Thoughts 13 | # (not solution): 14 | # https://stat.ethz.ch/pipermail/r-devel/2014-September/069803.html 15 | if(!suppressPackageStartupMessages(require(rstan))) { 16 | stop("the rstan package is required to check Stan MCMC models") 17 | } 18 | model_status <- tryCatch({ 19 | rstan::stan_model(file=model_file) 20 | return("correct") 21 | }, error=function(e) { 22 | e$message 23 | }) 24 | model_status 25 | } 26 | 27 | #' Check the syntax of all Bayesian model files in the package 28 | #' 29 | #' @param grep_pattern string on which to filter the names if only some should 30 | #' be checked. fixed=FALSE. 31 | #' @examples 32 | #' \dontrun{ 33 | #' # takes a long time, so run only when needed 34 | #' checks <- streamMetabolizer:::mm_check_mcmc_files() 35 | #' saveRDS(checks, file='temp/bayes_model_checks.Rds') 36 | #' checks <- streamMetabolizer:::mm_check_mcmc_files("*ko\\.stan") 37 | #' checks <- streamMetabolizer:::mm_check_mcmc_files("b_np_.*_ko\\.stan") 38 | #' cat(checks[[7]]) 39 | #' } 40 | #' @keywords internal 41 | mm_check_mcmc_files <- function(grep_pattern) { 42 | model_files <- mm_valid_names(type='bayes') 43 | if(!missing(grep_pattern)) { 44 | model_files <- grep(grep_pattern, model_files, value=TRUE) 45 | } 46 | sapply(setNames(model_files, model_files), function(m) { 47 | message("checking ", m, "...", appendLF=FALSE) 48 | model_status <- mm_check_mcmc_file(m) 49 | if(model_status != "correct") { 50 | message("found a problem.") 51 | } else { 52 | message("OK!") 53 | } 54 | model_status 55 | }) 56 | } 57 | -------------------------------------------------------------------------------- /man/get_param_names.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_model_interface.R, 3 | % R/metab_model.get_param_names.R 4 | \name{get_param_names} 5 | \alias{get_param_names} 6 | \alias{get_param_names.character} 7 | \alias{get_param_names.metab_model} 8 | \title{Extract the daily parameter names from a metabolism model.} 9 | \usage{ 10 | get_param_names(metab_model, ...) 11 | 12 | \method{get_param_names}{character}(metab_model, ...) 13 | 14 | \method{get_param_names}{metab_model}(metab_model, ...) 15 | } 16 | \arguments{ 17 | \item{metab_model}{A metabolism model object or model name for which to 18 | return the list of required and optional metabolism parameters.} 19 | 20 | \item{...}{Placeholder for future arguments} 21 | } 22 | \value{ 23 | Returns a list of two vectors, the names of the required and optional 24 | daily metabolism parameters, respectively. 25 | } 26 | \description{ 27 | A function in the metab_model_interface. Returns vectors of the required and 28 | optional daily metabolism parameters for the model. 29 | } 30 | \section{Methods (by class)}{ 31 | \itemize{ 32 | \item \code{character}: This implementation is shared by many model types 33 | 34 | \item \code{metab_model}: Lets you pass in a model object rather than a 35 | character string 36 | }} 37 | 38 | \examples{ 39 | 40 | # pass in a character string: 41 | get_param_names(mm_name('mle', GPP_fun='satlight')) 42 | get_param_names(mm_name('bayes')) 43 | get_param_names(mm_name('Kmodel')) 44 | get_param_names(mm_name('night')) 45 | get_param_names(mm_name('sim')) 46 | 47 | # or pass in a metab_model object: 48 | dat <- data_metab('1','30') 49 | get_param_names(metab(specs(mm_name('mle', ER_fun='q10temp')), data=dat)) 50 | get_param_names(metab(specs('night'), data=dat)) 51 | get_param_names(metab(specs('sim'), data=dat)) 52 | } 53 | \seealso{ 54 | Other metab_model_interface: 55 | \code{\link{get_data_daily}()}, 56 | \code{\link{get_data}()}, 57 | \code{\link{get_fitting_time}()}, 58 | \code{\link{get_fit}()}, 59 | \code{\link{get_info}()}, 60 | \code{\link{get_params}()}, 61 | \code{\link{get_specs}()}, 62 | \code{\link{get_version}()}, 63 | \code{\link{predict_DO}()}, 64 | \code{\link{predict_metab}()} 65 | } 66 | \concept{metab_model_interface} 67 | -------------------------------------------------------------------------------- /man/calc_solar_insolation.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/calc_solar_insolation.R 3 | \name{calc_solar_insolation} 4 | \alias{calc_solar_insolation} 5 | \title{Model solar insolation on a horizontal surface (W/m2 == J/s/m2) as in 6 | http://education.gsfc.nasa.gov/experimental/July61999siteupdate/inv99Project.Site/Pages/solar.insolation.html} 7 | \usage{ 8 | calc_solar_insolation( 9 | app.solar.time, 10 | latitude, 11 | max.insolation = convert_PAR_to_SW(2326), 12 | format = c("degrees", "radians"), 13 | attach.units = deprecated() 14 | ) 15 | } 16 | \arguments{ 17 | \item{app.solar.time}{POSIXct vector of date-time values in apparent solar 18 | time, e.g., as returned by \code{convert_UTC_to_solartime(..., 19 | time.type="apparent solar")}} 20 | 21 | \item{latitude}{numeric value or vector indicating the site latitude in 22 | decimal degrees (never radians or deg-min-sec, no matter what \code{format} 23 | is) between -90 (South Pole) and 90 (North Pole).} 24 | 25 | \item{max.insolation}{insolation rate at solar noon, W/m2 == J/s/m2. varies 26 | greatly with atmospheric conditions} 27 | 28 | \item{format}{The format of both the input and the output. May be "degrees" 29 | or "radians".} 30 | 31 | \item{attach.units}{(deprecated, effectively FALSE in future) logical. Should 32 | the returned vector be a unitted object?} 33 | } 34 | \description{ 35 | Model solar insolation on a horizontal surface (W/m2 == J/s/m2) as in 36 | http://education.gsfc.nasa.gov/experimental/July61999siteupdate/inv99Project.Site/Pages/solar.insolation.html 37 | } 38 | \examples{ 39 | insdf <- data.frame( 40 | lat=rep(c(0,20,40,60), each=48*4), 41 | date=rep(as.Date(sprintf('2004-\%d-15', rep(c(1,4,7,10), each=48)), tz='UTC'), times=4), 42 | hour=rep(seq(0,23.5,0.5), times=4*4) 43 | ) 44 | insdf <- transform(insdf, datetime=lubridate::with_tz(as.POSIXct(date), 'UTC') + 45 | as.difftime(hour, units='hours')) 46 | insdf <- transform(insdf, date=as.character(date)) 47 | insdf <- transform(insdf, ins=calc_solar_insolation(datetime, lat)) 48 | \dontrun{ 49 | library(ggplot2) 50 | ggplot(insdf, aes(color=date, y=ins, x=hour)) + 51 | geom_line() + facet_wrap(~lat) + 52 | ggtitle('solar insolation by latitude (panels) and day of year (colors)') 53 | } 54 | } 55 | -------------------------------------------------------------------------------- /man/mle_1ply.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_mle.R 3 | \name{mle_1ply} 4 | \alias{mle_1ply} 5 | \title{Make daily metabolism estimates from input parameters} 6 | \usage{ 7 | mle_1ply( 8 | data_ply, 9 | data_daily_ply, 10 | ply_date, 11 | ply_validity, 12 | timestep_days, 13 | ..., 14 | specs = specs("m_np_oi_tr_km.nlm") 15 | ) 16 | } 17 | \arguments{ 18 | \item{data_ply}{a data.frame containing all relevant, validated modeling data 19 | for a single ply of data. (1 ply ~= 1 date, although the day length has 20 | been specified by day_start and day_end and may not be exactly 24 hours)} 21 | 22 | \item{data_daily_ply}{NULL or a data.frame containing inputs with a daily 23 | timestep.} 24 | 25 | \item{ply_date}{the modal date of this ply of data and data_daily, and the 26 | date by which this ply should be referred topresent.} 27 | 28 | \item{ply_validity}{the output of \code{mm_is_valid_day} as applied to this 29 | data_ply for those tests specified in \code{day_tests}. Those tests will 30 | have been run before this function is called. The result is TRUE if the ply 31 | is entirely valid, or a character vector containing one or more error 32 | messages if any tests failed.} 33 | 34 | \item{timestep_days}{numeric length of the mean timestep for this day, if 35 | requested by setting \code{timestep_days} to \code{TRUE} or a numeric value 36 | in the call to \code{\link{mm_model_by_ply}}} 37 | 38 | \item{...}{other args that were passed untouched from the function calling 39 | mm_model_by_ply, through mm_model_by_ply, and finally to this function.} 40 | 41 | \item{specs}{a list of model specifications and parameters for a model. 42 | Although this may be specified manually (it's just a list), it is easier 43 | and safer to use \code{\link{specs}} to generate the list, because the set 44 | of required parameters and their defaults depends on the model given in the 45 | \code{model_name} argument to \code{specs}. The help file for 46 | \code{\link{specs}} lists the necessary parameters, describes them in 47 | detail, and gives default values.} 48 | } 49 | \value{ 50 | data.frame of estimates and \code{\link[stats]{nlm}} model 51 | diagnostics 52 | } 53 | \description{ 54 | Called from metab_mle(). 55 | } 56 | \keyword{internal} 57 | -------------------------------------------------------------------------------- /man/mm_get_timestep.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mm_get_timestep.R 3 | \name{mm_get_timestep} 4 | \alias{mm_get_timestep} 5 | \title{Return the average timestep in days} 6 | \usage{ 7 | mm_get_timestep( 8 | datetimes, 9 | format = c("mean", "unique", "modal"), 10 | require_unique = FALSE, 11 | tol = 60/(24 * 60 * 60) 12 | ) 13 | } 14 | \arguments{ 15 | \item{datetimes}{a vector of date-times in POSIXct format from which to 16 | compute the average timestep} 17 | 18 | \item{format}{the format in which to return the timestep. 'mean' always 19 | returns one value; 'unique' may return more than one depending on the 20 | variation in timesteps and the value of \code{digits}.} 21 | 22 | \item{require_unique}{logical. should it be required that there is exactly 23 | one unique timestep (within the given tolerance \code{tol})?} 24 | 25 | \item{tol}{if \code{format == 'unique'}, unique values are first calculated 26 | to machine precision, but then subsetted to those that differ from one 27 | another by at least tol, where tol is a time difference in units of days 28 | (and thus 1/(24*60*60) is one second).} 29 | } 30 | \description{ 31 | Return the average timestep in days 32 | } 33 | \examples{ 34 | { 35 | datetimes <- Sys.time()+ as.difftime(c(0,304,600,900.2,1200,1500,1800), units='secs') 36 | mm_get_timestep(datetimes, 'unique', tol=1/(24*60*60)) 37 | mm_get_timestep(datetimes, 'unique', tol=5/(24*60*60)) 38 | mm_get_timestep(datetimes, 'unique', tol=10/(24*60*60)) 39 | mm_get_timestep(datetimes, 'unique', tol=300/(24*60*60)) 40 | mm_get_timestep(datetimes, 'mean') 41 | mm_get_timestep(datetimes, 'mean', require_unique=TRUE, tol=300/(24*60*60)) 42 | datetimes <- Sys.time()+ as.difftime(c(-1,0,2,4,5,6,8,10), units='days') 43 | mm_get_timestep(datetimes, 'modal') 44 | mm_get_timestep(c(), 'mean') 45 | mm_get_timestep(c(), 'unique') 46 | mm_get_timestep(c(), 'modal') 47 | \dontrun{ 48 | # all of these should and do give errors: 49 | mm_get_timestep(datetimes, 'mean', require_unique=TRUE, tol=1/(24*60*60)) 50 | mm_get_timestep(datetimes, 'unique', tol=5/(24*60*60), require_unique=TRUE) 51 | mm_get_timestep(c(), 'mean', require_unique=TRUE) 52 | mm_get_timestep(c(), 'unique', require_unique=TRUE) 53 | mm_get_timestep(c(), 'modal', require_unique=TRUE) 54 | } 55 | } 56 | } 57 | -------------------------------------------------------------------------------- /inst/doc/ode_methods.R: -------------------------------------------------------------------------------- 1 | ## ----knitr_init, echo=FALSE, cache=FALSE---------------------------------------------------------- 2 | knitr::opts_chunk$set(echo = TRUE) 3 | options(width=100) 4 | 5 | ## ---- message=FALSE------------------------------------------------------------------------------- 6 | library(streamMetabolizer) 7 | library(dplyr) 8 | library(ggplot2) 9 | 10 | ## ------------------------------------------------------------------------------------------------- 11 | dat <- data_metab('3','30') 12 | 13 | ## ------------------------------------------------------------------------------------------------- 14 | mm_euler <- metab(specs(mm_name('mle', ode_method='euler')), dat) 15 | 16 | ## ------------------------------------------------------------------------------------------------- 17 | mm_trapezoid <- metab(specs(mm_name('mle', ode_method='trapezoid')), dat) 18 | 19 | ## ------------------------------------------------------------------------------------------------- 20 | mm_rk4 <- metab(specs(mm_name('mle', ode_method='rk4')), dat) 21 | 22 | ## ------------------------------------------------------------------------------------------------- 23 | mm_lsoda <- metab(specs(mm_name('mle', ode_method='lsoda')), dat) 24 | 25 | ## ------------------------------------------------------------------------------------------------- 26 | DO.standard <- rep(predict_DO(mm_rk4)$'DO.mod', times=4) 27 | ode_preds <- bind_rows( 28 | mutate(predict_DO(mm_euler), method='euler'), 29 | mutate(predict_DO(mm_trapezoid), method='trapezoid'), 30 | mutate(predict_DO(mm_rk4), method='rk4'), 31 | mutate(predict_DO(mm_lsoda), method='lsoda')) %>% 32 | mutate(DO.mod.diffeuler = DO.mod - DO.standard) 33 | 34 | ## ---- fig.width=6--------------------------------------------------------------------------------- 35 | ggplot(ode_preds, aes(x=solar.time)) + 36 | geom_point(aes(y=DO.obs), color='grey', alpha=0.3) + 37 | geom_line(aes(y=DO.mod, color=method), size=1) + 38 | theme_bw() 39 | 40 | ## ---- fig.width=6--------------------------------------------------------------------------------- 41 | ggplot(ode_preds, aes(x=solar.time)) + 42 | geom_point(aes(y=pmax(-0.2, pmin(0.2, DO.mod.diffeuler)), color=method), size=1, alpha=0.8) + 43 | scale_y_continuous(limits=c(-0.2,0.2)) + 44 | ylab("Deviations from rk4 (capped at +/- 0.2)") + 45 | theme_bw() 46 | 47 | -------------------------------------------------------------------------------- /man/mm_predict_metab_1ply.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/mm_predict_metab_1ply.R 3 | \name{mm_predict_metab_1ply} 4 | \alias{mm_predict_metab_1ply} 5 | \title{Helper to predict_metab.metab_model} 6 | \usage{ 7 | mm_predict_metab_1ply( 8 | data_ply, 9 | data_daily_ply, 10 | day_start, 11 | day_end, 12 | ply_date, 13 | ply_validity, 14 | ..., 15 | model_name 16 | ) 17 | } 18 | \arguments{ 19 | \item{data_ply}{a data.frame containing all relevant, validated modeling data 20 | for a single ply of data. (1 ply ~= 1 date, although the day length has 21 | been specified by day_start and day_end and may not be exactly 24 hours)} 22 | 23 | \item{data_daily_ply}{NULL or a data.frame containing inputs with a daily 24 | timestep.} 25 | 26 | \item{day_start}{start time (inclusive) of a day's data in number of hours 27 | from the midnight that begins the date. For example, day_start=-1.5 28 | indicates that data describing 2006-06-26 begin at 2006-06-25 22:30, or at 29 | the first observation time that occurs after that time if day_start doesn't 30 | fall exactly on an observation time.} 31 | 32 | \item{day_end}{end time (exclusive) of a day's data in number of hours from 33 | the midnight that begins the date. For example, day_end=30 indicates that 34 | data describing 2006-06-26 end at the last observation time that occurs 35 | before 2006-06-27 06:00.} 36 | 37 | \item{ply_date}{the modal date of this ply of data and data_daily, and the 38 | date by which this ply should be referred topresent.} 39 | 40 | \item{ply_validity}{the output of \code{mm_is_valid_day} as applied to this 41 | data_ply for those tests specified in \code{day_tests}. Those tests will 42 | have been run before this function is called. The result is TRUE if the ply 43 | is entirely valid, or a character vector containing one or more error 44 | messages if any tests failed.} 45 | 46 | \item{...}{other args that were passed untouched from the function calling 47 | mm_model_by_ply, through mm_model_by_ply, and finally to this function.} 48 | 49 | \item{model_name}{the coded model name that will determine the GPP_fun, 50 | ER_fun, deficit_src, and ode_method to use in prediction} 51 | } 52 | \value{ 53 | a data.frame of predictions 54 | } 55 | \description{ 56 | Usually assigned to model_fun within mm_model_by_ply, called from there 57 | } 58 | -------------------------------------------------------------------------------- /R/calc_DO_sat.R: -------------------------------------------------------------------------------- 1 | #' Calculates the equilibrium saturation concentration of oxygen in water at the 2 | #' supplied conditions 3 | #' 4 | #' @md 5 | #' @param temp.water a numeric vector of water temperature in degrees Celsius, 6 | #' or a \linkS4class{unitted} object of water temperatures. 7 | #' @param pressure.air barometric pressure in millibars, or a 8 | #' \linkS4class{unitted} object of barometric pressure. 9 | #' @param salinity.water a numeric vector of salinity in PSU, or a 10 | #' \linkS4class{unitted} object of salinity. Defaults to zero. 11 | #' @param model character. One of 'garcia-benson', 'garcia', 'weiss', or 12 | #' 'benson', but 'garcia-benson' is recommended. 13 | #' @param ... additional parameters passed to 14 | #' `LakeMetabolizer::o2.at.sat.base` 15 | #' @return a numeric vector of dissolved oxygen equilibrium saturation 16 | #' concentrations, in mg/L, with units attached if any of the input vectors 17 | #' are unitted. 18 | #' 19 | #' @importFrom LakeMetabolizer o2.at.sat.base 20 | #' @importFrom unitted u v get_units verify_units is.unitted 21 | #' @examples 22 | #' calc_DO_sat(temp=21, press=1000.1, sal=0) # no units checking if no units provided 23 | #' library(unitted) 24 | #' calc_DO_sat(temp=u(21,"degC"), press=u(1000.1,"mb"), sal=u(0,"PSU")) # units are checked 25 | #' @export 26 | calc_DO_sat <- calc_DO_at_sat <- function(temp.water, pressure.air, salinity.water = u(0,'PSU'), model='garcia-benson', ...){ 27 | 28 | if(as.character(sys.call()[[1]]) == 'calc_DO_at_sat') { 29 | .Deprecated('calc_DO_sat') 30 | } 31 | 32 | with.units <- any(sapply(list(temp.water, pressure.air), is.unitted)) || (if(!missing(salinity.water)) is.unitted(salinity.water) else FALSE) 33 | 34 | if (with.units){ 35 | # if any units are set, they all must be set and must be correct 36 | verify_units(temp.water, "degC") 37 | verify_units(pressure.air, "mb") 38 | verify_units(salinity.water, "PSU") 39 | } 40 | 41 | # units are stripped regardless 42 | temp.water <- v(temp.water) 43 | pressure.air <- v(pressure.air) 44 | salinity.water <- v(salinity.water) 45 | 46 | o2.at.sat <- LakeMetabolizer::o2.at.sat.base(temp = temp.water, baro = pressure.air, salinity = salinity.water, model = model, ...) 47 | 48 | if (with.units) { 49 | return(u(o2.at.sat, 'mgO2 L^-1')) 50 | } else { 51 | return(o2.at.sat) 52 | } 53 | 54 | } 55 | -------------------------------------------------------------------------------- /R/calc_depth.R: -------------------------------------------------------------------------------- 1 | #' Estimate depth from discharge and hydraulic geometry coefficients 2 | #' 3 | #' Uses the relationship \eqn{d=c*Q^f} (parameter names and definitions as in 4 | #' Leopold and Maddock, 1953; default values for c and f as in Raymond et al. 5 | #' 2012) 6 | #' 7 | #' @param Q discharge (m^3 s^-1) 8 | #' @param c coefficient representing depth at unit discharge (usually m) 9 | #' @param f exponent in depth-discharge relation (unitless) 10 | #' @return d, stream depth, in the same units as c 11 | #' @examples 12 | #' Qs <- seq(1,9,2) 13 | #' calc_depth(Q=Qs) 14 | #' calc_depth(Q=Qs, f=0.4) 15 | #' library(unitted) 16 | #' calc_depth(Q=u(Qs, "m^3 s^-1"), c=u(40,"cm")) 17 | #' calc_depth(Q=u(Qs, "m^3 s^-1"), f=u(0.36)) 18 | #' @references Raymond, Peter A., Christopher J. Zappa, David Butman, Thomas L. 19 | #' Bott, Jody Potter, Patrick Mulholland, Andrew E. Laursen, William H. 20 | #' McDowell, and Denis Newbold. \emph{Scaling the gas transfer velocity and 21 | #' hydraulic geometry in streams and small rivers}. Limnology & Oceanography: 22 | #' Fluids & Environments 2 (2012): 41-53. 23 | #' 24 | #' Leopold, L.B., and Thomas Maddock Jr. \emph{The Hydraulic Geometry of 25 | #' Stream Channels and Some Physiographic Implications}. Report. Professional 26 | #' Paper, 1953. USGS Publications Warehouse. 27 | #' https://pubs.er.usgs.gov/publication/pp252. 28 | #' 29 | #' @importFrom unitted u v verify_units 30 | #' @export 31 | calc_depth <- function(Q, c=u(0.409,"m"), f=u(0.294,"")) { 32 | 33 | with.units <- is.unitted(Q) || (if(!missing(c)) is.unitted(c) else FALSE) || (if(!missing(f)) is.unitted(f) else FALSE) 34 | 35 | if(with.units) { 36 | # if any units are set, they all must be set and must be correct 37 | verify_units(Q, "m^3 s^-1") 38 | if(!(get_units(c) %in% c("m","cm","mm","ft","in"))) warning("c has unknown depth units (",get_units(c),")") 39 | verify_units(f, "") 40 | } else { 41 | # if no units are explicitly set, then make sure c and f aren't using their unitted defaults 42 | c <- v(c) 43 | f <- v(f) 44 | } 45 | 46 | # The exponential form (below) is equivalent to this log-log form: 47 | # d <- exp(log(v(c)) + log(v(Q)) * f) 48 | # if(with.units) d <- u(d, get_units(c)) 49 | 50 | # Do the calculation, overriding the Q units (if any) for this empirical 51 | # equation. If c is unitted, units will be carried through. 52 | c * v(Q) ^ f 53 | } 54 | -------------------------------------------------------------------------------- /inst/doc/get_started.R: -------------------------------------------------------------------------------- 1 | ## ----knitr_init, echo=FALSE, cache=FALSE-------------------------------------- 2 | knitr::opts_chunk$set(echo = TRUE) 3 | options(width=80) 4 | 5 | ## ----libs, warning=FALSE, message=FALSE--------------------------------------- 6 | library(streamMetabolizer) 7 | library(dplyr) 8 | 9 | ## ----data--------------------------------------------------------------------- 10 | dat <- data_metab(num_days='3', res='15', day_start=4, day_end=28) 11 | 12 | ## ----bayes_name--------------------------------------------------------------- 13 | bayes_name <- mm_name(type='bayes', pool_K600='none', err_obs_iid=TRUE, err_proc_iid=TRUE) 14 | bayes_name 15 | 16 | ## ----bayes_specs-------------------------------------------------------------- 17 | bayes_specs <- specs(bayes_name) 18 | bayes_specs 19 | 20 | ## ----bayes_specs2------------------------------------------------------------- 21 | # one way to alter specifications: call specs() again 22 | bayes_specs <- specs(bayes_name, burnin_steps=100, saved_steps=200, n_cores=1, GPP_daily_mu=3, GPP_daily_sigma=2) 23 | # another way: use revise() 24 | bayes_specs <- revise(bayes_specs, burnin_steps=100, saved_steps=200, n_cores=1, GPP_daily_mu=3, GPP_daily_sigma=2) 25 | 26 | ## ----bayes_fit---------------------------------------------------------------- 27 | mm <- metab(bayes_specs, data=dat) 28 | 29 | ## ----------------------------------------------------------------------------- 30 | mm 31 | 32 | ## ----bayes_pred_tbl----------------------------------------------------------- 33 | predict_metab(mm) 34 | 35 | ## ----bayes_pred_fig, fig.width=5, fig.height=5-------------------------------- 36 | plot_metab_preds(mm) 37 | 38 | ## ----------------------------------------------------------------------------- 39 | get_params(mm) 40 | 41 | ## ----bayes_pdo_tbl, results='asis'-------------------------------------------- 42 | predict_DO(mm) %>% head() 43 | 44 | ## ----bayes_pdo_fig, fig.width=5, fig.height=5--------------------------------- 45 | plot_DO_preds(mm) 46 | 47 | ## ---- fig.width=5, fig.height=5----------------------------------------------- 48 | mcmc <- get_mcmc(mm) 49 | rstan::traceplot(mcmc, pars='K600_daily', nrow=3) 50 | 51 | ## ----------------------------------------------------------------------------- 52 | get_fit(mm)$overall %>% 53 | select(ends_with('Rhat')) 54 | 55 | ## ----------------------------------------------------------------------------- 56 | get_fit(mm) %>% 57 | lapply(names) 58 | 59 | -------------------------------------------------------------------------------- /man/create_calc_NLL.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/create_calc_NLL.R 3 | \name{create_calc_NLL} 4 | \alias{create_calc_NLL} 5 | \title{Create a function to compute the negative log likelihood of a set of 6 | metabolism parameter values} 7 | \usage{ 8 | create_calc_NLL( 9 | calc_DO, 10 | par.names = environment(environment(calc_DO)$calc_dDOdt)$metab.needs, 11 | err_obs_iid = FALSE, 12 | err_proc_iid = FALSE 13 | ) 14 | } 15 | \arguments{ 16 | \item{calc_DO}{a function as from \code{create_calc_DO}} 17 | 18 | \item{par.names}{vector of names of parameters that can be expected in calls 19 | to the function created by this one (the calc_NLL function)} 20 | 21 | \item{err_obs_iid}{logical. Should IID observation error be included? If not, 22 | the model will be fit to the differences in successive DO measurements, 23 | rather than to the DO measurements themselves.} 24 | 25 | \item{err_proc_iid}{logical. Should IID process error be included?} 26 | } 27 | \value{ 28 | a function that will return a negative log likelihood of the data 29 | given a set of metab.pars. metab.pars is the first argument of the returned 30 | function; its names are defined in \code{par.names}. 31 | } 32 | \description{ 33 | Produces a function that can be given to nlm(). K600.daily may be passed to 34 | that function within the p vector (for fitting K600.daily) or as an 35 | additional argument (for fixing it). 36 | } 37 | \examples{ 38 | data <- data_metab('1','30')[seq(1,48,by=2),] 39 | dDOdt <- create_calc_dDOdt(data, ode_method='trapezoid', GPP_fun='linlight', 40 | ER_fun='constant', deficit_src='DO_mod') 41 | DO <- create_calc_DO(dDOdt) 42 | NLL <- create_calc_NLL(DO, err_obs_iid=TRUE) 43 | NLL(metab.pars=c(GPP.daily=2, ER.daily=-2, K600.daily=25)) 44 | NLL(metab.pars=c(GPP.daily=2, ER.daily=-2, K600.daily=25), DO.mod.1=8) 45 | NLL(metab.pars=c(GPP.daily=4, ER.daily=-7, K600.daily=15)) 46 | NLL2 <- create_calc_NLL(DO, par.names=c('GPP.daily','ER.daily'), err_obs_iid=TRUE) 47 | NLL2(metab.pars=c(GPP.daily=2, ER.daily=-2), K600.daily=25) 48 | NLL3 <- create_calc_NLL(DO, 49 | par.names=c('GPP.daily','ER.daily','K600.daily','DO.mod.1'), err_obs_iid=TRUE) 50 | NLL3(metab.pars=c(GPP.daily=2, ER.daily=-2, K600.daily=25, DO.mod.1=9)) 51 | nlm(NLL, p=c(GPP.daily=2, ER.daily=-2, K600.daily=25)) 52 | nlm(NLL2, p=c(GPP.daily=2, ER.daily=-2), K600.daily=31.265) 53 | nlm(NLL3, p=c(GPP.daily=2, ER.daily=-2, K600.daily=25, DO.mod.1=9)) 54 | } 55 | -------------------------------------------------------------------------------- /man/Kmodel_allply.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_Kmodel.R 3 | \name{Kmodel_allply} 4 | \alias{Kmodel_allply} 5 | \title{Fit a K model} 6 | \usage{ 7 | Kmodel_allply( 8 | data_daily_all, 9 | engine, 10 | weights, 11 | predictors, 12 | transforms, 13 | other_args 14 | ) 15 | } 16 | \arguments{ 17 | \item{data_daily_all}{data to use as input, with columns including K600.daily.obs, 18 | weight, and any predictors} 19 | 20 | \item{engine}{The software or function to use in fitting the model. Should be 21 | specified via \code{mm_name} rather than here. For \code{type='bayes'}, 22 | always \code{'stan'} indicating the software package to use for the MCMC 23 | process (see http://mc-stan.org/). For types in 24 | \code{c('mle','night','sim')} there's again only one option per model (R 25 | functions; these need not be named here but will be noted in the suffix of 26 | the model name, e.g., \code{"m_np_oi_tr_plrckm.nlm"} uses \code{nlm()} for 27 | model fitting). For type='Kmodel', the name of an interpolation or 28 | regression method relating K to the predictor[s] of choice. One of 29 | \code{c("mean", "lm", "loess")}.} 30 | 31 | \item{weights}{For Kmodel, character vector indicating the type of weighting 32 | to use. Set to c() for no weights. One of c("1/CI", "K600/CI", c()).} 33 | 34 | \item{predictors}{For Kmodel, character vector of variables (column names in 35 | data or data_daily) to use in predicting K. Leave blank or set to c() for 36 | no predictors. Otherwise, one or more of these may be included: c("date", 37 | "velocity.daily", "discharge.daily").} 38 | 39 | \item{transforms}{For Kmodel, a named character vector of names of functions 40 | (probably 'log' or NA) to apply to K600.daily and/or the predictors. K600.daily should 41 | probably be logged. The vector names must match the values of 42 | \code{predictors}, although not all elements of \code{predictors} must be 43 | included in \code{transforms}. Recommended transforms include 44 | \code{c(K600.daily='log', date=NA, velocity.daily="log", discharge.daily="log")}} 45 | 46 | \item{other_args}{Other arguments passed to the fitting function given by 47 | \code{specs$engine}. \code{na.rm=TRUE} is already passed to 48 | \code{mean} (which is actually implemented as \code{sum}, anyway).} 49 | } 50 | \description{ 51 | The model will predict daily K estimates from preliminary daily K estimates. 52 | Called from metab_Kmodel(). 53 | } 54 | \keyword{internal} 55 | -------------------------------------------------------------------------------- /R/specs-class.R: -------------------------------------------------------------------------------- 1 | #### initialize #### 2 | 3 | setOldClass('specs') 4 | 5 | #' Add the metabolism model specifications class to a list 6 | #' 7 | #' @keywords internal 8 | add_specs_class <- function(specs_list) { 9 | class(specs_list) <- c("specs", class(specs_list)) 10 | specs_list 11 | } 12 | 13 | #### display #### 14 | 15 | #' Display the specs object 16 | #' 17 | #' Print a specs object to the console. 18 | #' 19 | #' @param object specs list to be displayed. 20 | setMethod( 21 | "show", "specs", 22 | function(object) { 23 | print_specs(object) 24 | } 25 | ) 26 | 27 | #' Display the specs object 28 | #' 29 | #' Print a specs object to the console. 30 | #' 31 | #' @param x specs list to be displayed. 32 | #' @param ... additional arguments passed to inner functions 33 | #' @export 34 | print.specs <- function(x, ...) { 35 | print_specs(x, ...) 36 | } 37 | 38 | #' Display the specs object 39 | #' 40 | #' Print a specs object to the console. 41 | #' 42 | #' @param object specs list to be displayed. 43 | #' @param header line to be catted at start of printout 44 | #' @param prefix text to prepend to the start of each line that follows the 45 | #' header 46 | #' @import dplyr 47 | #' @importFrom utils capture.output 48 | #' @keywords internal 49 | print_specs <- function(object, header="Model specifications:\n", prefix=" ") { 50 | # create a data.frame with a concise 1-line description of each specs element 51 | max_value_width <- if(length(object) > 0) { 52 | max(10, getOption('width') - nchar(prefix) - max(nchar(names(object))) - 1) 53 | } else { 54 | 10 55 | } 56 | specs_df <- data.frame(value=sapply(names(object), function(spec) { 57 | spec_char <- tryCatch( 58 | if(is.null(object[[spec]])) { 59 | 'NULL' 60 | } else { 61 | paste0(as.character(object[[spec]]), collapse=", ") 62 | }, 63 | error=function(e) { 64 | paste0(paste0(class(object[[spec]]), collapse=","),"; see element [['",spec,"']] for details") 65 | }) 66 | if(nchar(spec_char) > max_value_width) { 67 | spec_char <- paste0(substr(spec_char, 1, max_value_width-3), "...") 68 | } 69 | spec_char 70 | })) 71 | 72 | # format into a character vector, one string per row; omit the df header 73 | specs_printed <- capture.output(print(specs_df, right=FALSE))[-1] 74 | 75 | # print the specs header and df rows 76 | cat(header) 77 | cat(paste0(prefix, specs_printed, "\n"), sep='') 78 | 79 | invisible(object) 80 | } 81 | -------------------------------------------------------------------------------- /man/predict_metab.metab_Kmodel.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_Kmodel.R 3 | \name{predict_metab.metab_Kmodel} 4 | \alias{predict_metab.metab_Kmodel} 5 | \title{Override generic predict_metab for metab_Kmodel, which can't predict metab} 6 | \usage{ 7 | \method{predict_metab}{metab_Kmodel}( 8 | metab_model, 9 | date_start = NA, 10 | date_end = NA, 11 | day_start = NA, 12 | day_end = NA, 13 | ..., 14 | attach.units = deprecated(), 15 | use_saved = TRUE 16 | ) 17 | } 18 | \arguments{ 19 | \item{metab_model}{A metabolism model, implementing the 20 | metab_model_interface, to use in predicting metabolism} 21 | 22 | \item{date_start}{Date or a class convertible with as.Date. The first date 23 | (inclusive) for which to report metabolism predictions. If NA, no filtering 24 | is done.} 25 | 26 | \item{date_end}{Date or a class convertible with as.Date. The last date 27 | (inclusive) for which to report metabolism predictions. If NA, no filtering 28 | is done.} 29 | 30 | \item{day_start}{start time (inclusive) of a day's data in number of hours 31 | from the midnight that begins the date. For example, day_start=-1.5 32 | indicates that data describing 2006-06-26 begin at 2006-06-25 22:30, or at 33 | the first observation time that occurs after that time if day_start doesn't 34 | fall exactly on an observation time. For daily metabolism predictions, 35 | day_end - day_start should probably equal 24 so that each day's estimate is 36 | representative of a 24-hour period.} 37 | 38 | \item{day_end}{end time (exclusive) of a day's data in number of hours from 39 | the midnight that begins the date. For example, day_end=30 indicates that 40 | data describing 2006-06-26 end at the last observation time that occurs 41 | before 2006-06-27 06:00. For daily metabolism predictions, day_end - 42 | day_start should probably equal 24 so that each day's estimate is 43 | representative of a 24-hour period.} 44 | 45 | \item{...}{Other arguments passed to class-specific implementations of 46 | \code{predict_metab}} 47 | 48 | \item{attach.units}{(deprecated, effectively FALSE in future) logical. Should 49 | units be attached to the output?} 50 | 51 | \item{use_saved}{logical. Is it OK to use predictions that were saved with 52 | the model?} 53 | } 54 | \description{ 55 | metab_Kmodel predicts K (only) at daily timesteps and usually knows nothing 56 | about GPP or ER. So it's not possible to predict metabolism from this model. 57 | Try get_params() to retrieve the predicted values of K600.daily. 58 | } 59 | -------------------------------------------------------------------------------- /R/calc_velocity.R: -------------------------------------------------------------------------------- 1 | #' Estimate velocity from discharge and hydraulic geometry coefficients 2 | #' 3 | #' Uses the relationship \eqn{U=k*Q^m} (parameter names and definitions as in 4 | #' Leopold and Maddock, 1953; default values for k and m as in Raymond et al. 5 | #' 2012) 6 | #' 7 | #' @param Q discharge (m^3 s^-1) 8 | #' @param k coefficient representing velocity at unit discharge (usually m/s; e in Raymond et al.) 9 | #' @param m exponent in velocity-discharge relation (unitless; f in Raymond et al.) 10 | #' @return v (= V = U), stream flow velcoity, in the same units as k 11 | #' @examples 12 | #' Qs <- seq(1,9,2) 13 | #' calc_velocity(Q=Qs) 14 | #' calc_velocity(Q=Qs, k=0.4) 15 | #' library(unitted) 16 | #' calc_velocity(Q=u(Qs, "m^3 s^-1"), m=u(40)) 17 | #' calc_velocity(Q=u(Qs, "m^3 s^-1"), k=u(0.36, "m s^-1")) 18 | #' @references Raymond, Peter A., Christopher J. Zappa, David Butman, Thomas L. 19 | #' Bott, Jody Potter, Patrick Mulholland, Andrew E. Laursen, William H. 20 | #' McDowell, and Denis Newbold. \emph{Scaling the gas transfer velocity and 21 | #' hydraulic geometry in streams and small rivers}. Limnology & Oceanography: 22 | #' Fluids & Environments 2 (2012): 41-53. 23 | #' 24 | #' Leopold, L.B., and Thomas Maddock Jr. \emph{The Hydraulic Geometry of 25 | #' Stream Channels and Some Physiographic Implications}. Report. Professional 26 | #' Paper, 1953. USGS Publications Warehouse. 27 | #' https://pubs.er.usgs.gov/publication/pp252. 28 | #' 29 | #' @importFrom unitted u v verify_units 30 | #' @export 31 | calc_velocity <- function(Q, k=u(0.194,"m s^-1"), m=u(0.285,"")) { 32 | 33 | with.units <- is.unitted(Q) || (if(!missing(k)) is.unitted(k) else FALSE) || (if(!missing(m)) is.unitted(m) else FALSE) 34 | 35 | if(with.units) { 36 | # if any units are set, they all must be set and must be correct 37 | verify_units(Q, "m^3 s^-1") 38 | if(!(get_units(k) %in% paste0(c("m","cm","mm","ft","in"), " s^-1"))) warning("c has unknown depth units (",get_units(k),")") 39 | verify_units(m, "") 40 | } else { 41 | # if no units are explicitly set, then make sure c and f aren't using their unitted defaults 42 | k <- v(k) 43 | m <- v(m) 44 | } 45 | 46 | # The exponential form (below) is equivalent to this log-log form: 47 | # U <- exp(log(v(k)) + log(v(Q)) * m) 48 | # if(with.units) U <- u(U, get_units(k)) 49 | 50 | # Do the calculation, overriding the Q units (if any) for this empirical 51 | # equation. If k is unitted, units will be carried through. 52 | k * v(Q) ^ m 53 | } 54 | -------------------------------------------------------------------------------- /R/mm_filter_dates.R: -------------------------------------------------------------------------------- 1 | #' Filter unit or daily data by inclusive start & end dates 2 | #' 3 | #' @param data either instantaneous/unit or daily data, having columns for 4 | #' solar.time or date, respectively, to filter 5 | #' @inheritParams predict_DO 6 | #' @importFrom lubridate tz floor_date 7 | #' @keywords internal 8 | #' @examples 9 | #' tm <- as.POSIXct("2017-10-02 00:00:00 UTC") 10 | #' dt <- as.Date("2017-10-02") 11 | #' udat <- data.frame(solar.time=tm + as.difftime(1:100, units='hours'), value=1:100) 12 | #' udat1 <- streamMetabolizer:::mm_filter_dates(udat) 13 | #' udat2 <- streamMetabolizer:::mm_filter_dates(udat, date_start=dt, date_end=dt) 14 | #' udat3 <- streamMetabolizer:::mm_filter_dates(udat, date_start=dt, date_end=dt, 15 | #' day_start=12, day_end=14) 16 | #' c(nrow(udat), nrow(udat1), nrow(udat2), nrow(udat3)) 17 | #' ddat <- data.frame(date=dt + as.difftime(1:100, units='days'), value=1:100) 18 | #' ddat1 <- streamMetabolizer:::mm_filter_dates(ddat) 19 | #' ddat2 <- streamMetabolizer:::mm_filter_dates(ddat, date_start=dt+10, date_end=dt+20) 20 | #' c(nrow(ddat), nrow(ddat1), nrow(ddat2)) 21 | mm_filter_dates <- function(data, date_start=NA, date_end=NA, day_start=4, day_end=28, date_format="%Y-%m-%d") { 22 | 23 | if(is.null(data) || nrow(data) == 0 || (is.character(data) && data == "generic metab_model class; no actual fit")) return(data) 24 | date_col <- unlist(sapply(c('solar.time','date'), grep, names(data), fixed=TRUE, value=TRUE, USE.NAMES = FALSE))[1] 25 | data <- data[!is.na(data[[date_col]]),] 26 | # format dates 27 | tidy_date <- function(date) { 28 | local.tz <- if(date_col=='solar.time') tz(data$solar.time) else 'UTC' 29 | loc.date <- as.Date(date, format=date_format, tz=local.tz) 30 | switch( 31 | date_col, 32 | 'solar.time' = as.POSIXct(format(loc.date, date_format), format=date_format, tz=local.tz), 33 | 'date' = loc.date 34 | ) 35 | } 36 | date_start <- tidy_date(date_start) 37 | date_end <- tidy_date(date_end) 38 | # filter 39 | switch( 40 | date_col, 41 | 'solar.time' = { 42 | # format dates 43 | data %>% dplyr::filter( 44 | if(!is.na(date_start)) solar.time >= (date_start + as.difftime(day_start, units="hours")) else TRUE, 45 | if(!is.na(date_end)) solar.time <= (date_end + as.difftime(day_end, units="hours")) else TRUE) 46 | }, 47 | 'date' = { 48 | data %>% dplyr::filter( 49 | if(!is.na(date_start)) date >= date_start else TRUE, 50 | if(!is.na(date_end)) date <= date_end else TRUE) 51 | } 52 | ) 53 | } 54 | -------------------------------------------------------------------------------- /inst/doc/gpp_er_eqs.R: -------------------------------------------------------------------------------- 1 | ## ----knitr_init, echo=FALSE, cache=FALSE---------------------------------------------------------- 2 | knitr::opts_chunk$set(echo = TRUE) 3 | options(width=100) 4 | 5 | ## ---- message=FALSE------------------------------------------------------------------------------- 6 | library(streamMetabolizer) 7 | library(dplyr) 8 | 9 | ## ------------------------------------------------------------------------------------------------- 10 | dat <- data_metab('3', '15') 11 | 12 | ## ------------------------------------------------------------------------------------------------- 13 | # the Classic: linear GPP, constant ER (also the default) 14 | mm_classic <- 15 | mm_name('mle', GPP_fun='linlight', ER_fun='constant') %>% 16 | specs() %>% 17 | metab(dat) 18 | mm_classic 19 | 20 | ## ------------------------------------------------------------------------------------------------- 21 | # the Saturator: GPP saturating with light, constant ER 22 | mm_saturator <- 23 | mm_name('mle', GPP_fun='satlight', ER_fun='constant') %>% 24 | specs() %>% 25 | metab(dat) 26 | mm_saturator 27 | 28 | ## ------------------------------------------------------------------------------------------------- 29 | get_params(mm_saturator) %>% select(date, warnings, errors) 30 | 31 | ## ------------------------------------------------------------------------------------------------- 32 | predict_metab(mm_saturator) %>% select(date, warnings, errors) 33 | 34 | ## ------------------------------------------------------------------------------------------------- 35 | predict_DO(mm_saturator) %>% head 36 | plot_DO_preds(mm_saturator) 37 | 38 | ## ------------------------------------------------------------------------------------------------- 39 | mm_saturator2 <- 40 | mm_name('mle', GPP_fun='satlight', ER_fun='constant') %>% 41 | specs() %>% 42 | metab(dat, data_daily=select(get_params(mm_saturator), date, init.Pmax=Pmax, init.alpha=alpha)) 43 | get_params(mm_saturator2) 44 | mm_saturator3 <- 45 | mm_name('mle', GPP_fun='satlight', ER_fun='constant') %>% 46 | specs(init.Pmax=6.2, init.alpha=0.008) %>% 47 | metab(dat) 48 | get_params(mm_saturator3) 49 | mm_saturator4 <- 50 | mm_name('mle', GPP_fun='satlight', ER_fun='constant') %>% 51 | specs(init.Pmax=6.2, init.alpha=0.008) %>% 52 | metab(dat, transmute(get_params(mm_saturator), date, init.Pmax=Pmax[1], init.alpha=alpha[1])[2,]) 53 | get_params(mm_saturator4) 54 | 55 | ## ------------------------------------------------------------------------------------------------- 56 | plot_DO_preds(mm_classic) 57 | plot_DO_preds(mm_saturator4) 58 | 59 | -------------------------------------------------------------------------------- /R/streamMetabolizer.R: -------------------------------------------------------------------------------- 1 | #' Functions for calculating ecosystem metabolism in streams 2 | #' 3 | #' This package uses inverse modeling to estimate aquatic photosynthesis and 4 | #' respiration (collectively, metabolism) from time series data on dissolved 5 | #' oxygen, water temperature, depth, and light. The package assists with data 6 | #' preparation, handles data gaps during modeling, and provides tabular and 7 | #' graphical reports of model outputs. Several time-honored methods are 8 | #' implemented along with many promising new variants that produce more accurate 9 | #' and precise metabolism estimates. 10 | #' 11 | #' See http://usgs-r.github.io/streamMetabolizer for vignettes on the web. 12 | #' 13 | #' @section Calculate new input variables: 14 | #' 15 | #' \itemize{ 16 | #' 17 | #' \item \code{\link{calc_depth}} 18 | #' 19 | #' \item \code{\link{calc_DO_sat}} 20 | #' 21 | #' \item \code{\link{calc_light}} 22 | #' 23 | #' } 24 | #' 25 | #' @section Convert existing input variables: 26 | #' 27 | #' \itemize{ 28 | #' 29 | #' \item \code{\link{convert_date_to_doyhr}} 30 | #' 31 | #' \item \code{\link{convert_localtime_to_UTC}} 32 | #' 33 | #' \item \code{\link{convert_UTC_to_solartime}} 34 | #' 35 | #' \item \code{\link{convert_k600_to_kGAS}} 36 | #' 37 | #' \item \code{\link{convert_PAR_to_SW}} 38 | #' 39 | #' } 40 | #' 41 | #' @section Model metabolism: 42 | #' 43 | #' \itemize{ 44 | #' 45 | #' \item \code{\link{mm_name}} 1. Choose a model structure 46 | #' 47 | #' \item \code{\link{specs}} 2. Set the specifications 48 | #' 49 | #' \item \code{\link{metab}} 3. Fit the model 50 | #' 51 | #' } 52 | #' 53 | #' @section Inspect model results: 54 | #' 55 | #' \itemize{ 56 | #' 57 | #' \item \code{\link{predict_metab}} 58 | #' 59 | #' \item \code{\link{predict_DO}} 60 | #' 61 | #' \item \code{\link{plot_metab_preds}} 62 | #' 63 | #' \item \code{\link{plot_DO_preds}} 64 | #' 65 | #' \item \code{\link{get_params}} 66 | #' 67 | #' \item \code{\link{get_fit}} 68 | #' 69 | #' \item \code{\link{get_mcmc}} (Bayesian models only) 70 | #' 71 | #' \item \code{\link{get_fitting_time}} 72 | #' 73 | #' 74 | #' } 75 | #' 76 | #' @section Inspect model inputs/properties: 77 | #' 78 | #' \itemize{ 79 | #' 80 | #' \item \code{\link{get_specs}} 81 | #' 82 | #' \item \code{\link{get_data}} 83 | #' 84 | #' \item \code{\link{get_data_daily}} 85 | #' 86 | #' \item \code{\link{get_info}} 87 | #' 88 | #' \item \code{\link{get_version}} 89 | #' 90 | #' } 91 | #' 92 | #' @docType package 93 | #' @name streamMetabolizer 94 | #' @aliases streamMetabolizer-package 95 | NULL 96 | -------------------------------------------------------------------------------- /man/data_metab.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/data_metab.R 3 | \name{data_metab} 4 | \alias{data_metab} 5 | \title{Get a demo dataset for modeling metabolism} 6 | \usage{ 7 | data_metab( 8 | num_days = c("1", "3", "10"), 9 | res = c("5", "10", "15", "30"), 10 | flaws = c("missing middle", "missing start", "missing end", "missorted", 11 | "duplicated"), 12 | day_start = 4, 13 | day_end = 28, 14 | attach.units = deprecated() 15 | ) 16 | } 17 | \arguments{ 18 | \item{num_days}{the number of days to include in the data. character format 19 | because only certain numbers of days are permitted (see defaults in Usage 20 | for the accepted options)} 21 | 22 | \item{res}{character specifying the desired resolution of the data in minutes 23 | (character; see defaults in Usage for the accepted options)} 24 | 25 | \item{flaws}{character specifying one or more flaws to include in the data, 26 | or empty (\code{c()}) for no flaws. default is no flaws.} 27 | 28 | \item{day_start}{start time (inclusive) of a day's data in number of hours 29 | from the midnight that begins the date. For example, day_start=-1.5 30 | indicates that data describing 2006-06-26 begin at 2006-06-25 22:30, or at 31 | the first observation time that occurs after that time if day_start doesn't 32 | fall exactly on an observation time. For metabolism models working with 33 | single days of input data, it is conventional/useful to begin the day the 34 | evening before, e.g., -1.5, and to end just before the next sunrise, e.g., 35 | 30. For multiple consecutive days, it may make the most sense to start just 36 | before sunrise (e.g., 4) and to end 24 hours later. For nighttime 37 | regression, the date assigned to a chunk of data should be the date whose 38 | evening contains the data. The default is therefore 12 to 36 for 39 | metab_night, of which the times of darkness will be used.} 40 | 41 | \item{day_end}{end time (exclusive) of a day's data in number of hours from 42 | the midnight that begins the date. For example, day_end=30 indicates that 43 | data describing 2006-06-26 end at the last observation time that occurs 44 | before 2006-06-27 06:00. See day_start for recommended start and end times.} 45 | 46 | \item{attach.units}{(deprecated, effectively FALSE in future) logical, 47 | default TRUE for backward compatibility. Should units be attached to the 48 | data.frame?} 49 | } 50 | \description{ 51 | Get a formatted data.frame of inputs from which metabolism can be modeled. 52 | These test data were provided by Bob Hall. 53 | } 54 | \examples{ 55 | head(data_metab()) 56 | head(data_metab(res='30')) 57 | } 58 | -------------------------------------------------------------------------------- /man/metab_night.Rd: -------------------------------------------------------------------------------- 1 | % Generated by roxygen2: do not edit by hand 2 | % Please edit documentation in R/metab_night.R 3 | \name{metab_night} 4 | \alias{metab_night} 5 | \title{Nighttime regression for K estimation} 6 | \usage{ 7 | metab_night( 8 | specs = specs(mm_name("night")), 9 | data = mm_data(solar.time, DO.obs, DO.sat, depth, temp.water, light, discharge, 10 | optional = "discharge"), 11 | data_daily = mm_data(NULL), 12 | info = NULL 13 | ) 14 | } 15 | \arguments{ 16 | \item{specs}{a list of model specifications and parameters for a model. 17 | Although this may be specified manually (it's just a list), it is easier 18 | and safer to use \code{\link{specs}} to generate the list, because the set 19 | of required parameters and their defaults depends on the model given in the 20 | \code{model_name} argument to \code{specs}. The help file for 21 | \code{\link{specs}} lists the necessary parameters, describes them in 22 | detail, and gives default values.} 23 | 24 | \item{data}{data.frame (not a tbl_df) of input data at the temporal 25 | resolution of raw observations (unit-value). Columns must have the same 26 | names, units, and format as the default. The solar.time column must also 27 | have a timezone code ('tzone' attribute) of 'UTC'. See the 28 | \strong{'Formatting \code{data}'} section below for a full description.} 29 | 30 | \item{data_daily}{data.frame containing inputs with a daily timestep. See the 31 | \strong{'Formatting \code{data_daily}'} section below for a full 32 | description.} 33 | 34 | \item{info}{any information, in any format, that you would like to store 35 | within the metab_model object} 36 | } 37 | \value{ 38 | A metab_night object containing the fitted model. This object can be 39 | inspected with the functions in the \code{\link{metab_model_interface}}. 40 | } 41 | \description{ 42 | Fits a model to estimate K from nighttime input data on DO, temperature, 43 | light, etc. The default day start & end are 12 noon on the preceding to 44 | present day; the algorithm then filters the data to just those time points 45 | for which light is very low. Discharge is only used, if at all, to identify 46 | and exclude days with any negative discharge. 47 | } 48 | \examples{ 49 | dat <- data_metab('3', day_start=12, day_end=35) 50 | mm <- metab_night(data=dat) 51 | predict_metab(mm) 52 | \dontrun{ 53 | plot_DO_preds(predict_DO(mm)) 54 | } 55 | } 56 | \seealso{ 57 | Other metab_model: 58 | \code{\link{metab_Kmodel}}, 59 | \code{\link{metab_bayes}}, 60 | \code{\link{metab_mle}}, 61 | \code{\link{metab_sim}} 62 | } 63 | \author{ 64 | Alison Appling, Maite Arroita, Bob Hall 65 | } 66 | \concept{metab_model} 67 | -------------------------------------------------------------------------------- /R/calc_air_pressure.R: -------------------------------------------------------------------------------- 1 | #' Calculates the average air pressure for a site 2 | #' 3 | #' Estimates air pressure from air temperature and elevation 4 | #' 5 | #' @param temp.air air temperature in degrees C. Default is 15 degC. 6 | #' @param elevation the site elevation above sea level in m. Default is the 7 | #' rough mean elevation of the USA at 2500 ft (from 8 | #' http://www.infoplease.com/ipa/A0001792.html) 9 | #' @param attach.units (deprecated, effectively FALSE in future) logical. Should 10 | #' the returned vector be a unitted object? 11 | #' @return a numeric vector of barometric pressures in mb, with units attached 12 | #' if requested. 13 | #' @importFrom lifecycle deprecated is_present 14 | #' @importFrom unitted u v get_units verify_units is.unitted 15 | #' @examples 16 | #' calc_air_pressure(15, 762) 17 | #' calc_air_pressure(15, 100) 18 | #' @export 19 | calc_air_pressure <- function(temp.air=u(15, "degC"), elevation=u(762, "m"), attach.units=deprecated()) { 20 | 21 | # check units-related arguments 22 | if (lifecycle::is_present(attach.units)) { 23 | unitted_deprecate_warn("calc_air_pressure(attach.units)") 24 | } else { 25 | attach.units <- FALSE 26 | } 27 | 28 | # Bob's code: 29 | # ###Estimate barometric pressure as a function of altitude and standard BP 30 | # # since we will not correct for dail change in BP use 29.92 (=760 mm) 31 | # ##this is based on the barometric formula 32 | # ###temp is degC, alt is m, and bpst is in mm of Hg. Temp is usually relative to a standard, 15 degC. This is from Colt's book 33 | # bpcalc<- function(bpst, alt, temp) { 34 | # bpst*exp((-9.80665*0.0289644*alt)/(8.31447*(273.15+temp))) 35 | # } 36 | # ##call as 37 | # bpcalc(bpst=760,alt=2400,temp=15) 38 | 39 | # assume units if not provided 40 | if(!is.unitted(temp.air)) temp.air <- u(temp.air, "degC") 41 | if(!is.unitted(elevation)) elevation <- u(elevation, "m") 42 | 43 | # check units 44 | verify_units(temp.air, "degC") 45 | verify_units(elevation, "m") 46 | 47 | # compute pressure. eqn also at https://en.wikipedia.org/wiki/Barometric_formula 48 | Pb <- u(760, "mmHg") # standard pressure 49 | g0 <- u(9.80665, "m s^-2") # gravitational acceleration 50 | M <- u(0.0289644, "kg mol^-1") # molar mass of Earth's air 51 | Rst <- u(8.31447, "N m mol^-1 K^-1") * u(1, "kg m s^-2 N^-1") # universal gas constant for air: 8.31432 N*m /(mol*K) 52 | Ta <- u(273.15, "K") + temp.air*u(1, "K degC^-1") # actual temperature in Kelvins 53 | baro <- Pb * exp((-1 * g0 * M * elevation)/(Rst * Ta)) * u(1.33322368, "mb mmHg^-1") 54 | 55 | # return 56 | if(attach.units) baro else v(baro) 57 | } 58 | -------------------------------------------------------------------------------- /R/metab_model.get_param_names.R: -------------------------------------------------------------------------------- 1 | #' @describeIn get_param_names This implementation is shared by many model types 2 | #' @export 3 | #' @examples 4 | #' 5 | #' # pass in a character string: 6 | #' get_param_names(mm_name('mle', GPP_fun='satlight')) 7 | #' get_param_names(mm_name('bayes')) 8 | #' get_param_names(mm_name('Kmodel')) 9 | #' get_param_names(mm_name('night')) 10 | #' get_param_names(mm_name('sim')) 11 | get_param_names.character <- function(metab_model, ...) { 12 | # parse the model features 13 | features <- mm_parse_name(metab_model) 14 | 15 | # build the dDOdt function in order to pull out the metab.needs 16 | if(features$type == 'Kmodel') { 17 | metab.needs <- c('K600.daily') 18 | metab.optional <- c() 19 | } else { 20 | . <- '.dplyr.var' 21 | egdat <- unitted::v(eval(formals(paste0("metab_", features$type))$data)) %>% 22 | bind_rows(.,.) 23 | dDOdt <- create_calc_dDOdt( 24 | egdat, ode_method=features$ode_method, GPP_fun=features$GPP_fun, 25 | ER_fun=features$ER_fun, deficit_src=features$deficit_src) 26 | metab.needs <- environment(dDOdt)$metab.needs 27 | metab.optional <- c('DO.mod.1') # maybe should embed this in create_calc_DO? 28 | 29 | # special treatment for sim models - need discharge and specially sorted args 30 | if(features$type == 'sim') { 31 | metab.needs <- c(metab.needs, 'err.obs.sigma', 'err.obs.phi', 'err.proc.sigma', 'err.proc.phi') 32 | if(features$pool_K600 %in% c('linear','binned')) { 33 | metab.needs <- c(metab.needs, 'discharge.daily') 34 | } else { 35 | metab.optional <- c(metab.optional, 'discharge.daily') 36 | } 37 | # sort needs to match data_daily default order, which is the order of 38 | # operations we want to support when generating params 39 | ops.order <- names(eval(formals('metab_sim')$data_daily)) 40 | metab.needs <- metab.needs[na.omit(match(ops.order, metab.needs))] 41 | metab.optional <- metab.optional[na.omit(match(ops.order, metab.optional))] 42 | } 43 | } 44 | list(required=metab.needs, optional=metab.optional) 45 | } 46 | 47 | #' @describeIn get_param_names Lets you pass in a model object rather than a 48 | #' character string 49 | #' @export 50 | #' @examples 51 | #' 52 | #' # or pass in a metab_model object: 53 | #' dat <- data_metab('1','30') 54 | #' get_param_names(metab(specs(mm_name('mle', ER_fun='q10temp')), data=dat)) 55 | #' get_param_names(metab(specs('night'), data=dat)) 56 | #' get_param_names(metab(specs('sim'), data=dat)) 57 | get_param_names.metab_model <- function(metab_model, ...) { 58 | get_param_names(get_specs(metab_model)$model_name) 59 | } 60 | --------------------------------------------------------------------------------