introvoyz041 commited on
Commit
c223bdd
·
verified ·
1 Parent(s): fc178f0

Migrated from GitHub

Browse files
This view is limited to 50 files because it contains too many changes.   See raw diff
.gitattributes CHANGED
@@ -57,3 +57,7 @@ saved_model/**/* filter=lfs diff=lfs merge=lfs -text
57
  # Video files - compressed
58
  *.mp4 filter=lfs diff=lfs merge=lfs -text
59
  *.webm filter=lfs diff=lfs merge=lfs -text
 
 
 
 
 
57
  # Video files - compressed
58
  *.mp4 filter=lfs diff=lfs merge=lfs -text
59
  *.webm filter=lfs diff=lfs merge=lfs -text
60
+ data/docs/deps/font-awesome-6.5.2/webfonts/fa-brands-400.ttf filter=lfs diff=lfs merge=lfs -text
61
+ data/docs/deps/font-awesome-6.5.2/webfonts/fa-brands-400.woff2 filter=lfs diff=lfs merge=lfs -text
62
+ data/docs/deps/font-awesome-6.5.2/webfonts/fa-solid-900.ttf filter=lfs diff=lfs merge=lfs -text
63
+ data/docs/deps/font-awesome-6.5.2/webfonts/fa-solid-900.woff2 filter=lfs diff=lfs merge=lfs -text
data/.Rbuildignore ADDED
@@ -0,0 +1,20 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ^Meta$
2
+ ^doc$
3
+ ^docs$
4
+ ^LICENSE\.md$
5
+ ^.*\.Rproj$
6
+ ^\.Rproj\.user$
7
+ ^R/issues\.R$
8
+ CONDUCT.md
9
+ README.Rmd
10
+ README_files/*
11
+ R/scratch.R
12
+ ^cran-comments\.md$
13
+ ^CRAN-RELEASE$
14
+ ^_pkgdown\.yml$
15
+ ^pkgdown$
16
+ ^CRAN-SUBMISSION$
17
+ \.github/*
18
+ ^\.github$
19
+ ^data-raw$
20
+ ^r/photosynthesis-2d\.R$
data/CONDUCT.md ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Contributor Code of Conduct
2
+
3
+ As contributors and maintainers of this project, we pledge to respect all people who
4
+ contribute through reporting issues, posting feature requests, updating documentation,
5
+ submitting pull requests or patches, and other activities.
6
+
7
+ We are committed to making participation in this project a harassment-free experience for
8
+ everyone, regardless of level of experience, gender, gender identity and expression,
9
+ sexual orientation, disability, personal appearance, body size, race, ethnicity, age, or religion.
10
+
11
+ Examples of unacceptable behavior by participants include the use of sexual language or
12
+ imagery, derogatory comments or personal attacks, trolling, public or private harassment,
13
+ insults, or other unprofessional conduct.
14
+
15
+ Project maintainers have the right and responsibility to remove, edit, or reject comments,
16
+ commits, code, wiki edits, issues, and other contributions that are not aligned to this
17
+ Code of Conduct. Project maintainers who do not follow the Code of Conduct may be removed
18
+ from the project team.
19
+
20
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be reported by
21
+ opening an issue or contacting one or more of the project maintainers.
22
+
23
+ This Code of Conduct is adapted from the Contributor Covenant
24
+ (http:contributor-covenant.org), version 1.0.0, available at
25
+ http://contributor-covenant.org/version/1/0/0/
data/DESCRIPTION ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ Package: photosynthesis
2
+ Version: 2.1.5
3
+ Date: 2024-11-23
4
+ Title: Tools for Plant Ecophysiology & Modeling
5
+ Authors@R: c(
6
+ person("Joseph", "Stinziano", email = "[email protected]", role = "aut", comment = c(ORCID = "0000-0002-7628-4201")),
7
+ person("Cassaundra", "Roback", email = "[email protected]", role = "aut"),
8
+ person("Demi", "Sargent", email = "[email protected]", role = "aut"),
9
+ person("Bridget", "Murphy", email = "[email protected]", role = "aut"),
10
+ person("Patrick", "Hudson", email = "[email protected]", role = c("aut", "dtc")),
11
+ person("Chris", "Muir", email = "[email protected]", role = c("aut", "cre"), comment = c(ORCID = "0000-0003-2555-3878"))
12
+ )
13
+ Depends: R (>= 4.0.0),
14
+ ggplot2 (>= 3.4.0),
15
+ minpack.lm (>= 1.2-1),
16
+ units (>= 0.6.6)
17
+ Imports: checkmate (>= 2.0.0),
18
+ crayon (>= 1.3.4),
19
+ dplyr (>= 0.8.5),
20
+ furrr (>= 0.1.0),
21
+ glue (>= 1.4.0),
22
+ graphics (>= 4.0.0),
23
+ grDevices (>= 4.0.0),
24
+ gunit (>= 1.0.2),
25
+ lifecycle (>= 1.0.0),
26
+ magrittr (>= 1.5.0),
27
+ methods (>= 3.5.0),
28
+ nlme (>= 3.1-147),
29
+ progress (>= 1.2.0),
30
+ purrr (>= 0.3.3),
31
+ readr (>= 2.0.0),
32
+ rlang (>= 0.4.6),
33
+ stats (>= 4.0.0),
34
+ stringr (>= 1.4.0),
35
+ tealeaves (>= 1.0.5),
36
+ utils (>= 4.0.0)
37
+ Suggests:
38
+ brms,
39
+ broom,
40
+ future,
41
+ knitr,
42
+ rmarkdown,
43
+ testthat,
44
+ tibble,
45
+ tidyr,
46
+ tidyselect
47
+ Description: Contains modeling and analytical tools for plant ecophysiology.
48
+ MODELING: Simulate C3 photosynthesis using the Farquhar, von Caemmerer,
49
+ Berry (1980) <doi:10.1007/BF00386231> model as described in Buckley and
50
+ Diaz-Espejo (2015) <doi:10.1111/pce.12459>. It uses units to ensure that
51
+ parameters are properly specified and transformed before calculations.
52
+ Temperature response functions get automatically "baked" into all
53
+ parameters based on leaf temperature following Bernacchi et al. (2002)
54
+ <doi:10.1104/pp.008250>. The package includes boundary layer, cuticular,
55
+ stomatal, and mesophyll conductances to CO2, which each can vary on the
56
+ upper and lower portions of the leaf. Use straightforward functions to
57
+ simulate photosynthesis over environmental gradients such as Photosynthetic
58
+ Photon Flux Density (PPFD) and leaf temperature, or over trait gradients
59
+ such as CO2 conductance or photochemistry.
60
+ ANALYTICAL TOOLS: Fit ACi (Farquhar et al. (1980) <doi:10.1007/BF00386231>)
61
+ and AQ curves (Marshall & Biscoe (1980) <doi:10.1093/jxb/31.1.29>),
62
+ temperature responses (Heskel et al. (2016) <doi:10.1073/pnas.1520282113>;
63
+ Kruse et al. (2008) <doi:10.1111/j.1365-3040.2008.01809.x>, Medlyn et al.
64
+ (2002) <doi:10.1046/j.1365-3040.2002.00891.x>, Hobbs et al. (2013)
65
+ <doi:10.1021/cb4005029>), respiration in the light (Kok (1956)
66
+ <doi:10.1016/0006-3002(56)90003-8>, Walker & Ort (2015) <doi:10.1111/pce.12562>,
67
+ Yin et al. (2009) <doi:10.1111/j.1365-3040.2009.01934.x>, Yin et al. (2011)
68
+ <doi:10.1093/jxb/err038>), mesophyll conductance (Harley et al. (1992)
69
+ <doi:10.1104/pp.98.4.1429>), pressure-volume curves (Koide et al. (2000)
70
+ <doi:10.1007/978-94-009-2221-1_9>, Sack et al. (2003)
71
+ <doi:10.1046/j.0016-8025.2003.01058.x>, Tyree et al. (1972)
72
+ <doi:10.1093/jxb/23.1.267>), hydraulic vulnerability curves (Ogle et al. (2009)
73
+ <doi:10.1111/j.1469-8137.2008.02760.x>, Pammenter et al. (1998)
74
+ <doi:10.1093/treephys/18.8-9.589>), and tools for running sensitivity
75
+ analyses particularly for variables with uncertainty (e.g. g_mc(), gamma_star(),
76
+ R_d()).
77
+ License: MIT + file LICENSE
78
+ Encoding: UTF-8
79
+ LazyData: true
80
+ RoxygenNote: 7.3.2
81
+ VignetteBuilder: knitr
82
+ URL: https://github.com/cdmuir/photosynthesis
83
+ BugReports: https://github.com/cdmuir/photosynthesis/issues
84
+ Roxygen: list(markdown = TRUE)
data/LICENSE ADDED
@@ -0,0 +1,2 @@
 
 
 
1
+ YEAR: 2024
2
+ COPYRIGHT HOLDER: Joseph R. Stinziano, Cassaundra Roback, Demi Gamble, Bridget Murphy, Patrick Hudson, & Christopher D. Muir
data/LICENSE.md ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # MIT License
2
+
3
+ Copyright (c) 2024 Joseph R. Stinziano, Cassaundra Roback, Demi Gamble, Bridget Murphy, Patrick Hudson, & Christopher D. Muir
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
data/NAMESPACE ADDED
@@ -0,0 +1,112 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # Generated by roxygen2: do not edit by hand
2
+
3
+ export(A_demand)
4
+ export(A_supply)
5
+ export(FvCB)
6
+ export(J)
7
+ export(W_carbox)
8
+ export(W_regen)
9
+ export(W_tpu)
10
+ export(analyze_sensitivity)
11
+ export(aq_response)
12
+ export(bake)
13
+ export(bake_par)
14
+ export(calculate_j)
15
+ export(calculate_jmax)
16
+ export(compile_data)
17
+ export(compute_sensitivity)
18
+ export(constants)
19
+ export(enviro_par)
20
+ export(fit_PV_curve)
21
+ export(fit_aci_response)
22
+ export(fit_aq_response)
23
+ export(fit_aq_response2)
24
+ export(fit_g_mc_variableJ)
25
+ export(fit_gs_model)
26
+ export(fit_hydra_vuln_curve)
27
+ export(fit_many)
28
+ export(fit_photosynthesis)
29
+ export(fit_r_light2)
30
+ export(fit_r_light_WalkerOrt)
31
+ export(fit_r_light_kok)
32
+ export(fit_r_light_yin)
33
+ export(fit_t_response)
34
+ export(get_all_models)
35
+ export(get_default_model)
36
+ export(gs_mod_ballberry)
37
+ export(gs_mod_leuning)
38
+ export(gs_mod_opti)
39
+ export(gs_mod_optifull)
40
+ export(leaf_par)
41
+ export(make_bakepar)
42
+ export(make_constants)
43
+ export(make_enviropar)
44
+ export(make_leafpar)
45
+ export(marshall_biscoe_1980)
46
+ export(parameter_names)
47
+ export(photo)
48
+ export(photoinhibition)
49
+ export(photosynthesis)
50
+ export(ppm2pa)
51
+ export(print_graphs)
52
+ export(read_li6800)
53
+ export(read_licor)
54
+ export(required_variables)
55
+ export(simulate_error)
56
+ export(t_response_arrhenius)
57
+ export(t_response_arrhenius_kruse)
58
+ export(t_response_arrhenius_medlyn)
59
+ export(t_response_arrhenius_topt)
60
+ export(t_response_calc_dS)
61
+ export(t_response_calc_topt)
62
+ export(t_response_heskel)
63
+ export(t_response_mmrt)
64
+ export(temp_resp1)
65
+ export(temp_resp2)
66
+ importFrom(dplyr,bind_rows)
67
+ importFrom(ggplot2,aes)
68
+ importFrom(ggplot2,annotate)
69
+ importFrom(ggplot2,element_blank)
70
+ importFrom(ggplot2,geom_hline)
71
+ importFrom(ggplot2,geom_line)
72
+ importFrom(ggplot2,geom_point)
73
+ importFrom(ggplot2,geom_smooth)
74
+ importFrom(ggplot2,geom_vline)
75
+ importFrom(ggplot2,ggplot)
76
+ importFrom(ggplot2,ggtitle)
77
+ importFrom(ggplot2,labs)
78
+ importFrom(ggplot2,scale_color_manual)
79
+ importFrom(ggplot2,scale_colour_manual)
80
+ importFrom(ggplot2,scale_y_continuous)
81
+ importFrom(ggplot2,theme)
82
+ importFrom(ggplot2,theme_bw)
83
+ importFrom(grDevices,dev.off)
84
+ importFrom(grDevices,jpeg)
85
+ importFrom(grDevices,pdf)
86
+ importFrom(graphics,par)
87
+ importFrom(graphics,plot)
88
+ importFrom(magrittr,"%<>%")
89
+ importFrom(magrittr,"%>%")
90
+ importFrom(methods,is)
91
+ importFrom(minpack.lm,nls.lm.control)
92
+ importFrom(minpack.lm,nlsLM)
93
+ importFrom(nlme,lmList)
94
+ importFrom(rlang,":=")
95
+ importFrom(rlang,.data)
96
+ importFrom(rlang,exec)
97
+ importFrom(stats,coef)
98
+ importFrom(stats,confint)
99
+ importFrom(stats,deriv)
100
+ importFrom(stats,lm)
101
+ importFrom(stats,nls.control)
102
+ importFrom(stats,optim)
103
+ importFrom(stats,plogis)
104
+ importFrom(stats,resid)
105
+ importFrom(stats,rnorm)
106
+ importFrom(stats,sd)
107
+ importFrom(units,as_units)
108
+ importFrom(units,drop_units)
109
+ importFrom(units,set_units)
110
+ importFrom(utils,read.csv)
111
+ importFrom(utils,setTxtProgressBar)
112
+ importFrom(utils,txtProgressBar)
data/NEWS.md ADDED
@@ -0,0 +1,101 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ # photosynthesis 2.1.5
2
+
3
+ * Added `photoinhibition()` to light response models. This allows users to estimate photoinhibition at high light.
4
+
5
+ # photosynthesis 2.1.4
6
+
7
+ * Removed imports of unexported **tealeaves** functions using `:::` operator
8
+ * `read_licor()` removes lines where parameter settings are changed between logging
9
+
10
+ # photosynthesis 2.1.3
11
+
12
+ * Added example LI6800 data set (inst/extdata/li6800_example) for unit testing `read_licor()`
13
+ * Soft-deprecated `read_li6800()` in favor of `read_licor()`
14
+ * Soft-deprecated `fit_many()` in favor of generic methods like `purrr::map()`
15
+
16
+ # photosynthesis 2.1.2
17
+
18
+ * Updated CITATION using `bibentry()` instead of `citEntry()`
19
+ * Resolved **purrr** deprecations
20
+ * removed `expect_no_condition()` from unit tests to resolved issue #12
21
+ * Replaced `dplyr::progress_estimated()` with `progress::progress_bar()`
22
+ * Fixed error in `photo(..., use_tealeaves = TRUE)`. User-defined changes in stomatal conductance ratio were not being passed to **tealeaves**.
23
+ * Added evaporation (E) to `photo()` and `photosynthesis()` output when `use_tealeaves = TRUE`
24
+ * Fixed issue with **lifecycle** badges
25
+ * Added new function `simulate_error()` to simulate measurement error in gas exchange measurements.
26
+
27
+ # photosynthesis 2.1.1
28
+
29
+ * Added Bayesian options to fit light-response and light respiration models via `fit_photosynthesis(..., .method = "brms")`
30
+ * Preferred method for fitting data to models is `fit_photosynthesis()` which performs all checks and manipulations prior to passing arguments to various `fit_` functions.
31
+ * Deprecated `fit_r_light_kok()`, `fit_r_light_WalkerOrt()`, `fit_r_light_yin()` in favor of `fit_r_light2()`. The new function uses non-standard evaluation to replace variable names as in `dplyr::rename()`. It will also extend functionality to enable Bayesian fitting using **brms** and does not output a plot.
32
+ * Added Bayesian fitting method to `fit_aq_response2()` using **brms** package.
33
+ * Deprecated `fit_aq_response()` in favor of `fit_aq_response2()`. The new function uses non-standard evaluation to replace variable names as in `dplyr::rename()`. It will also extend functionality to enable Bayesian fitting using **brms** and does not output a plot.
34
+ * Fixed bug with setting upper bound for search in `find_A()`
35
+ * Addressed warnings about deprecated arguments in **tidyselect** and **ggplot2**
36
+ * Added `C_i` (intercellular CO2 concentration) to output from `photo()` and `photosynthesis()`
37
+
38
+ # photosynthesis 2.1.0
39
+
40
+ * Commented out examples that took a long time to run
41
+ * Added `progress` option to `fit_many()` to toggle progress bar
42
+ * We removed large files from help subdirectory
43
+ * Divided large vignette into smaller vignettes and removed figures to reduce file size
44
+ * Updated CITATION
45
+ * There is a new vignette on C3 photosynthesis modeling recommendations (modeling-recommendations)
46
+ * Under the hood, many changes to `photosynthesis()`, but performance should be the same
47
+ * Changed default `C_air` from 41 Pa to 420 umol/mol
48
+ * Changed default `O` from 21.27565 kPa to 0.21 mol/mol
49
+ * Added optional feature to calculate mesophyll conductance to CO2 (g_mc) as sum of internal airspace (`g_iasc`) and liquid-phase (`g_liqc`) conductances.
50
+ * To avoid redundancy, `photo_parameters` is single source of truth for all input parameters to `photo()` and `photosynthesis()`.
51
+ * Fixed error in `gc2gw()` and `gw2gc()` and migrated to **gunit** version 1.0.2. Legacy version used version for still air in boundary layer conductance conversions. The corrected version includes modification for laminar flow in the boundary layer. Legacy version can be obtained with option `use_legacy_version = TRUE`.
52
+ * Changed default conductance units from `[umol / m ^ 2 / s / Pa]` to `[mol / m ^ 2 / s]`
53
+ * Changed `<-` to `=` in many instances
54
+ * Changed `%>%` to `|>` in many instances
55
+
56
+ # photosynthesis 2.0.3
57
+
58
+ * In the DESCRIPTION file, rewrote references in the form authors (year) <doi:...>
59
+ * In the DESCRIPTION file, added () behind all function names
60
+ * Added \value to .Rd files regarding exported methods for bake.Rd, bake_par.Rd, constants.Rd, enviro_par.Rd, leaf_par.Rd, parameter_names.Rd
61
+ * Changed print() to stop() or message() in R/compile_data.R; R/fit_gs_model.R; R/fit_t_response.R; R/print_graphs.R
62
+ * In R/print_graphs.R, added code to restore users' option for par()$mfrow
63
+ * Removed "2020" from the field COPYRIGHT HOLDER in the LICENCE file
64
+ * Updated link to Prometheus protocols in vignette
65
+ * Stopped evaluating parallel example in vignette
66
+ * Fixed tests that failed because of update to dependency **units** 0.8-0. (#7)
67
+
68
+ # photosynthesis 2.0.1
69
+
70
+ * for `temp_resp1` and `temp_resp2`, corrected reference. (#6)
71
+
72
+ # photosynthesis 2.0.0
73
+
74
+ * Added analytical tools for plant ecophysiology, including fitting stomatal
75
+ conductance models, photosynthetic responses to light, CO2, and temperature,
76
+ light respiration, as well as tools for performing sensitivity analyses.
77
+
78
+ * Added tests for new functions.
79
+
80
+ * Added new vignette to include examples of new analytical functions.
81
+
82
+ # photosynthesis 1.0.2
83
+
84
+ * Fixed bug with crossing parameters in `photosynthesis()` that was introduced when `use_tealeaves = TRUE` because of changes in the **tealeaves** package. This led to crossing all parameter values with all unique values of calculated `T_sky`, which was incorrect. Added unit tests to ensuring that crossing is done correctly under `tests/test-photosynthesis-crossing.R`
85
+ * Fixed bug in `photosynthesis()` caused by new version of **dplyr**.
86
+ * In `enviro_par()`, "sky" temperature (`T_sky`) can now be provided directly as a values (in K) or as a function (the default).
87
+ * If `parallel = TRUE` in `photosynthesis()`, **future** uses `plan("multisession")` rather than `plan("multiprocess")`.
88
+ * Added full URL for `CONDUCT.md` in README
89
+ * Fixed cross-references in .Rd files
90
+
91
+ # photosynthesis 1.0.1
92
+
93
+ Release to be archived with revision of "Is amphistomy an adaptation to high light? Optimality models of stomatal traits along light gradients."
94
+
95
+ [Blog post.](https://cdmuir.netlify.app/post/2019-05-21-phyteclub/)
96
+
97
+ # photosynthesis 1.0.0
98
+
99
+ Description: Simulate C$_3$ photosynthesis using the Farquhar, von Caemmerer, Berry (1980) model as described in Buckley and Diaz-Espejo (2015). It uses units to ensure that parameters are properly specified and transformed before calculations. Temperature response functions get automatically "baked" into all parameters based on leaf temperature following Bernacchi et al. (2002). The package includes boundary layer, cuticular, stomatal, and mesophyll conductances to CO$_2$, which each can vary on the upper and lower portions of the leaf. Use straightforward functions to simulate photosynthesis over environmental gradients such as Photosynthetic Photon Flux Density (PPFD) and leaf temperature, or over trait gradients such as CO$_2$ conductance or photochemistry.
100
+
101
+ * Added a `NEWS.md` file to track changes to the package.
data/R/FvCB.R ADDED
@@ -0,0 +1,182 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #' Farquhar-von Caemmerer-Berry (FvCB) C3 photosynthesis model
2
+ #'
3
+ #' @inheritParams A_supply
4
+ #'
5
+ #' @return A list of four values with units umol CO2 / (m^2 s) of class `units`:
6
+ #' \cr
7
+ #' - `W_carbox`: Rubisco-limited assimilation rate \cr
8
+ #' - `W_regen`: RuBP regeneration-limited assimilation rate \cr
9
+ #' - `W_tpu`: TPU-limited assimilation rate \cr
10
+ #' - `A`: minimum of W_carbox, W_regen, and W_tpu
11
+ #'
12
+ #' @details
13
+ #'
14
+ #' Equations following Buckley and Diaz-Espejo (2015): \cr
15
+ #' \cr
16
+ #' **Rubisco-limited assimilation rate:** \cr
17
+ #' \cr
18
+ #' \deqn{W_\mathrm{carbox} = V_\mathrm{c,max} C_\mathrm{chl} / (C_\mathrm{chl} + K_\mathrm{m})}{W_carbox = V_cmax C_chl / (C_chl + K_m)}
19
+ #'
20
+ #' where:
21
+ #'
22
+ #' \deqn{K_\mathrm{m} = K_\mathrm{C} (1 + O / K_\mathrm{O})}{K_m = K_c (1 + O / K_o)}
23
+ #'
24
+ #' **RuBP regeneration-limited assimilation rate:** \cr
25
+ #' \cr
26
+ #' \deqn{W_\mathrm{regen} = J C_\mathrm{chl} / (4 C_\mathrm{chl} + 8 \Gamma*)}{W_regen = J C_chl / (4 C_chl + 8 \Gamma*)}
27
+ #'
28
+ #' where \eqn{J} is a function of PPFD, obtained by solving the equation:
29
+ #'
30
+ #' \deqn{0 = \theta_J J ^ 2 - J (J_\mathrm{max} + \phi_J PPFD) + J_\mathrm{max} \phi_J PPFD}{0 = \theta_J J ^ 2 - J (J_max + \phi_J PPFD) + J_max \phi_J PPFD}
31
+ #'
32
+ #' **TPU-limited assimilation rate:** \cr
33
+ #'
34
+ #' \deqn{W_\mathrm{tpu} = 3 V_\mathrm{tpu} C_\mathrm{chl} / (C_\mathrm{chl} - \Gamma*)}{W_tpu = 3 V_tpu C_chl / (C_chl - \Gamma*)}
35
+ #' \cr
36
+ #' \tabular{lllll}{
37
+ #' *Symbol* \tab *R* \tab *Description* \tab *Units* \tab *Default*\cr
38
+ #' \eqn{C_\mathrm{chl}}{C_chl} \tab `C_chl` \tab chloroplastic CO2 concentration \tab Pa \tab input \cr
39
+ #' \eqn{\Gamma*} \tab `gamma_star` \tab chloroplastic CO2 compensation point (T_leaf) \tab Pa \tab [calculated][bake] \cr
40
+ #' \eqn{J_\mathrm{max}}{J_max} \tab `J_max` \tab potential electron transport (T_leaf) \tab \eqn{\mu}mol CO2 / (m\eqn{^2} s) \tab [calculated][bake] \cr
41
+ #' \eqn{K_\mathrm{C}}{K_C} \tab `K_C` \tab Michaelis constant for carboxylation (T_leaf) \tab \eqn{\mu}mol / mol \tab [calculated][bake] \cr
42
+ #' \eqn{K_\mathrm{O}}{K_O} \tab `K_O` \tab Michaelis constant for oxygenation (T_leaf) \tab \eqn{\mu}mol / mol \tab [calculated][bake] \cr
43
+ #' \eqn{O} \tab `O` \tab atmospheric O2 concentration \tab kPa \tab 21.27565 \cr
44
+ #' \eqn{\phi_J} \tab `phi_J` \tab initial slope of the response of J to PPFD \tab none \tab 0.331 \cr
45
+ #' PPFD \tab `PPFD` \tab photosynthetic photon flux density \tab umol quanta / (m^2 s) \tab 1500 \cr
46
+ #' \eqn{R_\mathrm{d}}{R_d} \tab `R_d` \tab nonphotorespiratory CO2 release (T_leaf) \tab \eqn{\mu}mol CO2 / (m\eqn{^2} s) \tab [calculated][bake] \cr
47
+ #' \eqn{\theta_J} \tab `theta_J` \tab curvature factor for light-response curve \tab none \tab 0.825 \cr
48
+ #' \eqn{V_\mathrm{c,max}}{V_c,max} \tab `V_cmax` \tab maximum rate of carboxylation (T_leaf) \tab \eqn{\mu}mol CO2 / (m\eqn{^2} s) \tab [calculated][bake] \cr
49
+ #' \eqn{V_\mathrm{tpu}}{V_tpu} \tab `V_tpu` \tab rate of triose phosphate utilization (T_leaf) \tab \eqn{\mu}mol CO2 / (m\eqn{^2} s) \tab [calculated][bake]
50
+ #' }
51
+ #'
52
+ #' @references
53
+ #'
54
+ #' Buckley TN and Diaz-Espejo A. 2015. Partitioning changes in photosynthetic
55
+ #' rate into contributions from different variables. Plant, Cell & Environment
56
+ #' 38: 1200-11.
57
+ #'
58
+ #' Farquhar GD, Caemmerer S, Berry JA. 1980. A biochemical model of
59
+ #' photosynthetic CO2 assimilation in leaves of C3 species. Planta 149: 78–90.
60
+ #'
61
+ #' @examples
62
+ #' bake_par = make_bakepar()
63
+ #' constants = make_constants(use_tealeaves = FALSE)
64
+ #' enviro_par = make_enviropar(use_tealeaves = FALSE)
65
+ #' leaf_par = make_leafpar(use_tealeaves = FALSE)
66
+ #' leaf_par = bake(leaf_par, enviro_par, bake_par, constants)
67
+ #'
68
+ #' pars = c(leaf_par, enviro_par, constants)
69
+ #' C_chl = set_units(246.0161, umol / mol)
70
+ #' FvCB(C_chl, pars)
71
+ #' @export
72
+ #'
73
+ FvCB = function(C_chl, pars, unitless = FALSE) {
74
+ ret = list(
75
+ W_carbox = W_carbox(C_chl, pars, unitless),
76
+ W_regen = W_regen(C_chl, pars, unitless),
77
+ W_tpu = W_tpu(C_chl, pars, unitless)
78
+ )
79
+
80
+ # Ignore W_tpu if C_chl < gamma_star
81
+ if (C_chl > pars$gamma_star) {
82
+ ret$A = min(ret$W_carbox, ret$W_regen, ret$W_tpu)
83
+ } else {
84
+ ret$A = min(ret$W_carbox, ret$W_regen)
85
+ }
86
+ ret
87
+ }
88
+ #' Rubisco-limited assimilation rate
89
+ #' @rdname FvCB
90
+ #' @export
91
+ W_carbox = function(C_chl, pars, unitless = FALSE) {
92
+ if (unitless) {
93
+ A = pars$V_cmax * C_chl / (C_chl + pars$K_C * (1 + 1e6 * pars$O / pars$K_O))
94
+ } else {
95
+ A = set_units(
96
+ pars$V_cmax * C_chl /
97
+ (C_chl + pars$K_C * (set_units(1) + pars$O / pars$K_O)),
98
+ umol / m^2 / s
99
+ )
100
+ }
101
+ A
102
+ }
103
+ #' RuBP regeneration-limited assimilation rate
104
+ #' @rdname FvCB
105
+ #' @export
106
+ W_regen = function(C_chl, pars, unitless = FALSE) {
107
+ J = J(pars, unitless)
108
+ A = J * C_chl / (4 * C_chl + 8 * pars$gamma_star)
109
+ if (!unitless) A %<>% set_units(umol / m^2 / s)
110
+ A
111
+ }
112
+ #' TPU-limited assimilation rate
113
+ #' @rdname FvCB
114
+ #' @export
115
+ W_tpu = function(C_chl, pars, unitless = FALSE) {
116
+ A = 3 * pars$V_tpu * C_chl / (C_chl - pars$gamma_star)
117
+ if (!unitless) A %<>% set_units(umol / m^2 / s)
118
+ A
119
+ }
120
+ #' J: Rate of electron transport (umol/m^2/s)
121
+ #'
122
+ #' @description Calculate the rate of electron transport as a function of photosynthetic photon flux density (PPFD).
123
+ #'
124
+ #' @inheritParams .get_gtc
125
+ #'
126
+ #' @return Value in \eqn{\mu}mol/ (m^2 s) of class `units`
127
+ #'
128
+ #' @details
129
+ #'
130
+ #' \eqn{J} as a function of PPFD is the solution to the quadratic expression:
131
+ #'
132
+ #' \deqn{0 = \theta_J J ^ 2 - J (J_\mathrm{max} + \phi_J PPFD) + J_\mathrm{max} \phi_J PPFD}{0 = \theta_J J ^ 2 - J (J_max + \phi_J PPFD) + J_max \phi_J PPFD}
133
+ #'
134
+ #' \tabular{lllll}{
135
+ #' *Symbol* \tab *R* \tab *Description* \tab *Units* \tab *Default*\cr
136
+ #' \eqn{J_\mathrm{max}}{J_max} \tab `J_max` \tab potential electron transport (T_leaf) \tab \eqn{\mu}mol CO2 / (m\eqn{^2} s) \tab [calculated][bake] \cr
137
+ #' \eqn{\phi_J} \tab `phi_J` \tab initial slope of the response of J to PPFD \tab none \tab 0.331 \cr
138
+ #' PPFD \tab `PPFD` \tab photosynthetic photon flux density \tab \eqn{\mu}mol quanta / (m^2 s) \tab 1500 \cr
139
+ #' \eqn{\theta_J} \tab `theta_J` \tab curvature factor for light-response curve \tab none \tab 0.825
140
+ #' }
141
+ #'
142
+ #' @examples
143
+ #'
144
+ #' library(magrittr)
145
+ #' library(photosynthesis)
146
+ #'
147
+ #' bake_par = make_bakepar()
148
+ #' constants = make_constants(use_tealeaves = FALSE)
149
+ #' enviro_par = make_enviropar(use_tealeaves = FALSE)
150
+ #' leaf_par = make_leafpar(use_tealeaves = FALSE)
151
+ #' enviro_par$T_air = leaf_par$T_leaf
152
+ #' leaf_par %<>% bake(enviro_par, bake_par, constants)
153
+ #'
154
+ #' pars = c(leaf_par, enviro_par, constants)
155
+ #' J(pars, FALSE)
156
+ #' @export
157
+ #'
158
+ J = function(pars, unitless = FALSE) {
159
+ if (!unitless) {
160
+ # drop units for root finding
161
+ pars$PPFD %<>% set_units(umol / m^2 / s) %>% drop_units()
162
+ pars$J_max %<>% set_units(umol / m^2 / s) %>% drop_units()
163
+ pars$phi_J %<>% drop_units()
164
+ pars$theta_J %<>% drop_units()
165
+ }
166
+
167
+ .f = function(J, PPFD, J_max, phi_J, theta_J) {
168
+ theta_J * J^2 - J * (J_max + phi_J * PPFD) + J_max * phi_J * PPFD
169
+ }
170
+
171
+ J_I = stats::uniroot(.f, c(0, pars$J_max),
172
+ PPFD = pars$PPFD, J_max =
173
+ pars$J_max,
174
+ phi_J = pars$phi_J, theta_J = pars$theta_J
175
+ )
176
+
177
+ J_I %<>% magrittr::use_series("root")
178
+
179
+ if (!unitless) J_I %<>% set_units(umol / m^2 / s)
180
+
181
+ J_I
182
+ }
data/R/analyze_sensitivity.R ADDED
@@ -0,0 +1,148 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #' Running 2-parameter sensitivity analyses
2
+ #'
3
+ #' @param data Dataframe
4
+ #' @param funct Function to use - do not use parentheses
5
+ #' @param test1 Input parameter to vary and test
6
+ #' @param values1 Values of test1 to use
7
+ #' @param test2 Input parameter to vary and test
8
+ #' @param values2 Values of test2 to use
9
+ #' @param element_out List element to compile
10
+ #' @param ... Additional arguments required for the function
11
+ #'
12
+ #' @return analyze_sensitivity runs a 2-parameter sensitivity analysis.
13
+ #' Note that any parameter value combinations that break the input function
14
+ #' WILL break this function. For 1-parameter sensitivity analysis, use test1
15
+ #' only.
16
+ #'
17
+ #' @importFrom rlang exec
18
+ #' @importFrom rlang :=
19
+ #' @export
20
+ #'
21
+ #' @examples
22
+ #' \donttest{
23
+ #' # Read in your data
24
+ #' # Note that this data is coming from data supplied by the package
25
+ #' # hence the complicated argument in read.csv()
26
+ #' # This dataset is a CO2 by light response curve for a single sunflower
27
+ #' data <- read.csv(system.file("extdata", "A_Ci_Q_data_1.csv",
28
+ #' package = "photosynthesis"
29
+ #' ))
30
+ #'
31
+ #' # Define a grouping factor based on light intensity to split the ACi
32
+ #' # curves
33
+ #' data$Q_2 <- as.factor((round(data$Qin, digits = 0)))
34
+ #'
35
+ #' # Convert leaf temperature to K
36
+ #' data$T_leaf <- data$Tleaf + 273.15
37
+ #'
38
+ #' # Run a sensitivity analysis on gamma_star and mesophyll conductance
39
+ #' # at 25 Celsius for one individual curve
40
+ #' # pars <- analyze_sensitivity(
41
+ #' # data = data[data$Q_2 == 1500, ],
42
+ #' # funct = fit_aci_response,
43
+ #' # varnames = list(
44
+ #' # A_net = "A",
45
+ #' # T_leaf = "T_leaf",
46
+ #' # C_i = "Ci",
47
+ #' # PPFD = "Qin"
48
+ #' # ),
49
+ #' # useg_mct = TRUE,
50
+ #' # test1 = "gamma_star25",
51
+ #' # element_out = 1,
52
+ #' # test2 = "g_mc25",
53
+ #' # fitTPU = TRUE,
54
+ #' # Ea_gamma_star = 0,
55
+ #' # Ea_g_mc = 0,
56
+ #' # values1 = seq(
57
+ #' # from = 20,
58
+ #' # to = 40,
59
+ #' # by = 2
60
+ #' # ),
61
+ #' # values2 = seq(
62
+ #' # from = 0.5,
63
+ #' # to = 2,
64
+ #' # by = 0.1
65
+ #' # )
66
+ #' # )
67
+ #'
68
+ #' # Graph V_cmax
69
+ #' # ggplot(pars, aes(x = gamma_star25, y = g_mc25, z = V_cmax)) +
70
+ #' # geom_tile(aes(fill = V_cmax)) +
71
+ #' # labs(
72
+ #' # x = expression(Gamma * "*"[25] ~ "(" * mu * mol ~ mol^
73
+ #' # {
74
+ #' # -1
75
+ #' # } * ")"),
76
+ #' # y = expression(g[m][25] ~ "(" * mu * mol ~ m^{
77
+ #' # -2
78
+ #' # } ~ s^{
79
+ #' # -1
80
+ #' # } ~ Pa^
81
+ #' # {
82
+ #' # -1
83
+ #' # } * ")")
84
+ #' # ) +
85
+ #' # scale_fill_distiller(palette = "Greys") +
86
+ #' # geom_contour(colour = "Black", size = 1) +
87
+ #' # theme_bw()
88
+ #' # }
89
+ #'
90
+ analyze_sensitivity <- function(data,
91
+ funct,
92
+ test1 = NA,
93
+ values1,
94
+ test2 = NA,
95
+ values2,
96
+ element_out = 1,
97
+ ...) {
98
+ # Create an empty list for ACi fits
99
+ fits <- list(NULL)
100
+
101
+ # Next loops through values depending on whether there are
102
+ # two input parameters or one.
103
+ # Note that these loops generalize the arguments and functions
104
+ if (!is.na(test2)) {
105
+ # Start progress bar
106
+ pb <- txtProgressBar(min = 0, max = length(values2) *
107
+ length(values1), style = 3)
108
+ # Loop through values of test1 and test2
109
+ for (j in seq_len(length(values2))) {
110
+ for (i in seq_len(length(values1))) {
111
+ fits[[i + (j - 1) * length(values1)]] <- exec(funct,
112
+ data = data,
113
+ !!test1 := values1[i],
114
+ !!test2 := values2[j],
115
+ ...
116
+ )
117
+ # Set progress bar
118
+ setTxtProgressBar(pb, i + (j - 1) * length(values1))
119
+ }
120
+ }
121
+ } else {
122
+ # Start progress bar
123
+ pb <- txtProgressBar(min = 0, max = length(values1), style = 3)
124
+ for (i in seq_len(length(values1))) {
125
+ fits[[i]] <- exec(funct,
126
+ data = data,
127
+ !!test1 := values1[i],
128
+ ...
129
+ )
130
+ # Set progress bar
131
+ setTxtProgressBar(pb, i)
132
+ }
133
+ }
134
+ # Create empty list for parameter outputs
135
+ pars <- vector("list", length(fits))
136
+
137
+ # Compile parameter outputs
138
+ # Main challenge here when using out-of-package functions:
139
+ # Output style may vary, making this component behave
140
+ # unexpectedly
141
+ for (i in seq_along(fits)) {
142
+ pars[[i]] <- fits[[i]][[element_out]]
143
+ }
144
+ # Convert parameter outputs to dataframe
145
+ pars <- do.call("bind_rows", pars)
146
+ # Return parameters as output
147
+ return(pars)
148
+ }
data/R/aq_response.R ADDED
@@ -0,0 +1,32 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #' Non-rectangular hyperbolic model of light responses
2
+ #'
3
+ #' @description
4
+ #' `r lifecycle::badge("deprecated")`
5
+ #'
6
+ #' Please use `marshall_biscoe_1980()`.
7
+ #'
8
+ #' @param k_sat Light saturated rate of process k
9
+ #' @param phi_J Quantum efficiency of process k
10
+ #' @param Q_abs Absorbed light intensity (umol m-2 s-1)
11
+ #' @param theta_J Curvature of the light response
12
+ #'
13
+ #' @return aq_response is used to describe the response of a process to
14
+ #' absorbed light intensity. Assumes that input is absorbed light. Note
15
+ #' that if absorbed light is not used, then the meaning of phi_J becomes
16
+ #' unclear. This function is designed to be used with fit_aq_response,
17
+ #' however it could easily be fed into a different fitting approach (e.g.
18
+ #' Bayesian approaches). Originally from Marshall et al. 1980.
19
+ #'
20
+ #' @references
21
+ #' Marshall B, Biscoe P. 1980. A model for C3 leaves describing the
22
+ #' dependence of net photosynthesis on irradiance. J Ex Bot 31:29-39
23
+ #' @export
24
+ aq_response = function(k_sat, phi_J, Q_abs, theta_J) {
25
+
26
+ lifecycle::deprecate_warn("2.1.1", "aq_response()", "marshall_biscoe_1980()", always = FALSE)
27
+
28
+ k_net = ((k_sat + phi_J * Q_abs) -
29
+ sqrt((k_sat + phi_J * Q_abs)^2 -
30
+ 4 * k_sat * phi_J * Q_abs * theta_J)) /
31
+ (2 * theta_J)
32
+ }
data/R/bake-par.R ADDED
@@ -0,0 +1,39 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #' S3 class bake_par
2
+ #
3
+
4
+ #' @param .x A list to be constructed into **bake_par**.
5
+ #'
6
+ #' @returns
7
+ #'
8
+ #' Constructor function for bake_par class. This function ensures that leaf
9
+ #' temperature gets properly "baked" into leaf parameters.
10
+ #'
11
+ #' @export
12
+
13
+ bake_par = function(.x) {
14
+
15
+ which = "bake"
16
+
17
+ # Check parameters names ----
18
+ nms = check_parameter_names(.x, which = which, use_tealeaves = FALSE)
19
+ .x = .x[nms]
20
+
21
+ # Set units ----
22
+ .x = .x |>
23
+ set_parameter_units(
24
+ .data$type == which,
25
+ !.data$temperature_response,
26
+ !.data$tealeaves
27
+ )
28
+
29
+ # Assert bounds on values ----
30
+ .x |>
31
+ assert_parameter_bounds(
32
+ .data$type == which,
33
+ !.data$temperature_response,
34
+ !.data$tealeaves
35
+ )
36
+
37
+ structure(.x, class = c(stringr::str_c(which, "_par"), "list"))
38
+
39
+ }
data/R/bake.R ADDED
@@ -0,0 +1,235 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #' S3 class baked
2
+ #' @name baked-class
3
+ #' @description See [bake()]
4
+
5
+ NULL
6
+
7
+ #' Leaf parameter temperature responses
8
+ #'
9
+ #' @description 'bake' leaf parameters using temperature response functions
10
+ #'
11
+ #' @name bake
12
+ #'
13
+ #' @inheritParams photosynthesis
14
+ #' @inheritParams A_supply
15
+ #'
16
+ #' @returns
17
+ #'
18
+ #' Constructor function for `baked` class. This will also inherit class
19
+ #' [leaf_par()] and [list()]. This function ensures that
20
+ #' temperature is "baked in" to leaf parameter calculations `T_leaf` using
21
+ #' temperature response functions detailed below.
22
+ #'
23
+ #' @details
24
+ #'
25
+ #' Several leaf parameters ([leaf_par()]) are temperature sensitive.
26
+ #' Temperature-sensitive parameters are input at a reference temperature of
27
+ #' 25 °C. These parameters are provided as `par_name25` and then "baked"
28
+ #' using the appropriate temperature response function and parameters in
29
+ #' [bake_par()]. The "baked" parameter will have the name without "25"
30
+ #' appended (`par_name`). E.g. `V_cmax25` becomes `V_cmax`. \cr
31
+ #' \cr
32
+ #' Temperature response functions following Buckley and Diaz-Espejo (2015) \cr
33
+ #' \cr
34
+ #' Temperature response function 1 (`temp_response1`): \cr
35
+ #'
36
+ #' \deqn{\mathrm{par}(T_\mathrm{leaf}) = \mathrm{par25}~\mathrm{exp}(E_\mathrm{a} / (R T_\mathrm{ref}) (T_\mathrm{leaf} - 25) / (T_\mathrm{leaf} + 273.15))}{par(T_leaf) = par25 exp(E_a / (R T_ref) (T_leaf - 25) / (T_leaf + 273.15))}
37
+ #'
38
+ #' \eqn{T_\mathrm{ref}}{T_ref} is the reference temperature in K \cr
39
+ #' \eqn{T_\mathrm{leaf}}{T_leaf} is the leaf temperature in °C \cr
40
+ #' \cr
41
+ #' Temperature response function 2 (`temp_response2`) is the above equation multiplied by: \cr
42
+ #'
43
+ #' \deqn{(1 + \mathrm{exp}((D_\mathrm{s} / R - E_\mathrm{d} / (R T_\mathrm{ref})))) / (1 + \mathrm{exp}((D_\mathrm{s} / R) - (E_\mathrm{d} / (R (T_\mathrm{leaf} + 273.15)))))}{(1 + exp((D_s / R - E_d / (R T_ref)))) / (1 + exp((D_s / R) - (E_d / (R (T_leaf + 273.15)))))}
44
+ #'
45
+ #' Function 1 increases exponentially with temperature; Function 2 peaks a particular temperature.
46
+ #'
47
+ #' @encoding UTF-8
48
+ #'
49
+ #' @references
50
+ #'
51
+ #' Buckley TN, Diaz-Espejo A. 2015. Partitioning changes in photosynthetic rate
52
+ #' into contributions from different variables. Plant, Cell and Environment 38:
53
+ #' 1200-1211.
54
+ #'
55
+ #' @examples
56
+ #' bake_par = make_bakepar()
57
+ #' constants = make_constants(use_tealeaves = FALSE)
58
+ #' enviro_par = make_enviropar(use_tealeaves = FALSE)
59
+ #' leaf_par = make_leafpar(
60
+ #' replace = list(T_leaf = set_units(293.15, K)),
61
+ #' use_tealeaves = FALSE
62
+ #' )
63
+ #' baked_leafpar = bake(leaf_par, enviro_par, bake_par, constants)
64
+ #'
65
+ #' baked_leafpar$V_cmax25
66
+ #' baked_leafpar$V_cmax
67
+ #' @encoding UTF-8
68
+ #'
69
+ #' @export
70
+
71
+ bake = function(
72
+ leaf_par,
73
+ enviro_par,
74
+ bake_par,
75
+ constants,
76
+ assert_units = TRUE
77
+ ) {
78
+
79
+ # Assert units before baking ----
80
+ if (assert_units) {
81
+ leaf_par %<>% leaf_par(use_tealeaves = FALSE)
82
+ enviro_par %<>% enviro_par(use_tealeaves = FALSE)
83
+ bake_par %<>% bake_par()
84
+ constants %<>% constants(use_tealeaves = FALSE)
85
+ }
86
+
87
+ # Remove units prior to baking ----
88
+ pars = c(leaf_par, enviro_par, bake_par, constants) |>
89
+ purrr::map_if(~ inherits(.x, "units"), drop_units)
90
+ T_ref = 298.15
91
+
92
+ # Calculate parameters at T_leaf based on temperature response function ----
93
+ # Assumes that g_liqc has same temperature response function as g_mc
94
+ if (length(pars$g_liqc25) != 0) {
95
+ leaf_par$g_liqc = temp_resp2(
96
+ pars$g_liqc25, pars$Ds_gmc, pars$Ea_gmc, pars$Ed_gmc, pars$R, pars$T_leaf,
97
+ T_ref, unitless = TRUE
98
+ )
99
+ }
100
+
101
+ if (length(leaf_par$delta_ias_lower) != 0 & length(leaf_par$delta_ias_upper) != 0) {
102
+ D_c = .get_Dx(pars$D_c0, pars$T_leaf, pars$eT, pars$P, unitless = TRUE)
103
+ leaf_par$g_iasc_lower = 1e9 * D_c / pars$delta_ias_lower *
104
+ pars$P / (pars$R * pars$T_leaf)
105
+ leaf_par$g_iasc_upper = 1e9 * D_c / pars$delta_ias_upper *
106
+ pars$P / (pars$R * pars$T_leaf)
107
+ }
108
+
109
+ if (length(pars$g_mc25) != 0) {
110
+ leaf_par$g_mc = temp_resp2(
111
+ pars$g_mc25, pars$Ds_gmc, pars$Ea_gmc, pars$Ed_gmc, pars$R, pars$T_leaf,
112
+ T_ref, unitless = TRUE
113
+ )
114
+ }
115
+
116
+ leaf_par$gamma_star = temp_resp1(pars$gamma_star25, pars$Ea_gammastar,
117
+ pars$R, pars$T_leaf, T_ref,
118
+ unitless = TRUE
119
+ )
120
+ leaf_par$J_max = temp_resp2(pars$J_max25, pars$Ds_Jmax, pars$Ea_Jmax,
121
+ pars$Ed_Jmax, pars$R, pars$T_leaf, T_ref,
122
+ unitless = TRUE
123
+ )
124
+ leaf_par$K_C = temp_resp1(pars$K_C25, pars$Ea_KC, pars$R, pars$T_leaf,
125
+ T_ref,
126
+ unitless = TRUE
127
+ )
128
+ leaf_par$K_O = temp_resp1(pars$K_O25, pars$Ea_KO, pars$R, pars$T_leaf,
129
+ T_ref,
130
+ unitless = TRUE
131
+ )
132
+ leaf_par$R_d = temp_resp1(pars$R_d25, pars$Ea_Rd, pars$R, pars$T_leaf,
133
+ T_ref,
134
+ unitless = TRUE
135
+ )
136
+ leaf_par$V_cmax = temp_resp1(pars$V_cmax25, pars$Ea_Vcmax, pars$R,
137
+ pars$T_leaf, T_ref,
138
+ unitless = TRUE
139
+ )
140
+ leaf_par$V_tpu = temp_resp1(pars$V_tpu25, pars$Ea_Vtpu, pars$R, pars$T_leaf,
141
+ T_ref,
142
+ unitless = TRUE
143
+ )
144
+
145
+ # Set units ----
146
+ leaf_par = set_parameter_units(leaf_par, .data$R %in% names(leaf_par))
147
+
148
+ # Assert bounds on values ----
149
+ # If !assert_units, no assertion is performed
150
+ if (assert_units) {
151
+ leaf_par |>
152
+ assert_parameter_bounds(
153
+ .data$type == "leaf",
154
+ .data$temperature_response,
155
+ !.data$tealeaves
156
+ )
157
+ }
158
+
159
+ leaf_par %<>% structure(class = c("baked", "leaf_par", "list"))
160
+
161
+ leaf_par
162
+ }
163
+
164
+ #' Temperature response function 1
165
+ #'
166
+ #' @rdname bake
167
+ #'
168
+ #' @param par25 Parameter value at 25 °C of class `units`.
169
+ #' @param E_a Empirical temperature response value in J/mol of class
170
+ #' `units`.
171
+ #' @param R Ideal gas constant in J / (mol K) of class `units`. See
172
+ #' [make_constants()].
173
+ #' @param T_leaf Leaf temperature in K of class `units`. Will be converted
174
+ #' to °C.
175
+ #' @param T_ref Reference temperature in K of class `units`.
176
+ #'
177
+ #' @export
178
+
179
+ temp_resp1 = function(par25, E_a, R, T_leaf, T_ref, unitless) {
180
+ if (unitless) {
181
+ T_leaf %<>% magrittr::subtract(273.15)
182
+ } else {
183
+ pars_unit = units(par25)
184
+ par25 %<>% drop_units()
185
+
186
+ E_a %<>% set_units(J / mol) %>% drop_units()
187
+ R %<>% set_units(J / K / mol) %>% drop_units()
188
+ T_leaf %<>% set_units(degreeC) %>% drop_units()
189
+ T_ref %<>% set_units(K) %>% drop_units()
190
+ }
191
+
192
+ a1 = exp(E_a / (R * T_ref) * ((T_leaf - 25) / (T_leaf + 273.15)))
193
+
194
+ ret = par25 * a1
195
+ if (!unitless) units(ret) = pars_unit
196
+ ret
197
+ }
198
+
199
+ #' Temperature response function 2
200
+ #'
201
+ #' @rdname bake
202
+ #'
203
+ #' @inheritParams temp_resp1
204
+ #' @param D_s Empirical temperature response value in J / (mol K) of class
205
+ #' `units`.
206
+ #' @param E_d Empirical temperature response value in J/mol of class
207
+ #' `units`.
208
+ #'
209
+ #' @export
210
+
211
+ temp_resp2 = function(par25, D_s, E_a, E_d, R, T_leaf, T_ref, unitless) {
212
+ a1 = temp_resp1(par25, E_a, R, T_leaf, T_ref, unitless)
213
+
214
+ if (unitless) {
215
+ T_leaf %<>% magrittr::subtract(273.15)
216
+ } else {
217
+ pars_unit = units(par25)
218
+ par25 %<>% drop_units()
219
+ a1 %<>% drop_units()
220
+
221
+ D_s %<>% set_units(J / mol / K) %>% drop_units()
222
+ E_a %<>% set_units(J / mol) %>% drop_units()
223
+ E_d %<>% set_units(J / mol) %>% drop_units()
224
+ R %<>% set_units(J / K / mol) %>% drop_units()
225
+ T_leaf %<>% set_units(degreeC) %>% drop_units()
226
+ T_ref %<>% set_units(K) %>% drop_units()
227
+ }
228
+
229
+ a2 = (1 + exp((D_s / R - E_d / (R * T_ref)))) /
230
+ (1 + exp((D_s / R) - (E_d / (R * (T_leaf + 273.15)))))
231
+
232
+ ret = a1 * a2
233
+ if (!unitless) units(ret) = pars_unit
234
+ ret
235
+ }
data/R/calculated-parameters.R ADDED
@@ -0,0 +1,58 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #' Get default functions for calculated parameters in [photosynthesis]
2
+ #'
3
+ #' @name calculated-parameters
4
+ #' @param .f_name character string of function
5
+ #' @encoding UTF-8
6
+ get_f_parameter = function(.f_name) {
7
+
8
+ .f_name |>
9
+ match.arg(c("f_nu", "f_sh", "T_sky")) |>
10
+ switch(
11
+
12
+ f_nu = function(Re, type, T_air, T_leaf, surface, unitless) {
13
+ if (!unitless) {
14
+ stopifnot(units(T_air)$numerator == "K" &
15
+ length(units(T_air)$denominator) == 0L)
16
+ stopifnot(units(T_leaf)$numerator == "K" &
17
+ length(units(T_leaf)$denominator) == 0L)
18
+ }
19
+
20
+ type %<>% match.arg(c("free", "forced"))
21
+
22
+ if (identical(type, "forced")) {
23
+ if (unitless) {
24
+ if (Re <= 4000) ret = list(a = 0.6, b = 0.5)
25
+ if (Re > 4000) ret = list(a = 0.032, b = 0.8)
26
+ } else {
27
+ if (Re <= set_units(4000)) ret = list(a = 0.6, b = 0.5)
28
+ if (Re > set_units(4000)) ret = list(a = 0.032, b = 0.8)
29
+ }
30
+ return(ret)
31
+ }
32
+
33
+ if (identical(type, "free")) {
34
+ surface %<>% match.arg(c("lower", "upper"))
35
+ if ((surface == "upper" & T_leaf > T_air) |
36
+ (surface == "lower" & T_leaf < T_air)) {
37
+ ret = list(a = 0.5, b = 0.25)
38
+ } else {
39
+ ret = list(a = 0.23, b = 0.25)
40
+ }
41
+ return(ret)
42
+ }
43
+ },
44
+
45
+ f_sh = function(type, unitless) {
46
+ type |>
47
+ match.arg(c("free", "forced")) |>
48
+ switch(forced = 0.33, free = 0.25)
49
+ },
50
+
51
+ T_sky = function(pars) {
52
+ set_units(pars$T_air, K) - set_units(20, K) *
53
+ set_units(pars$S_sw, W / m^2) / set_units(1000, W / m^2)
54
+ }
55
+
56
+ )
57
+
58
+ }
data/R/compile_data.R ADDED
@@ -0,0 +1,84 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #' Compiling outputs from lists
2
+ #'
3
+ #' @param data List of elements
4
+ #' @param output_type Type of desired output. For graphs or models, use "list",
5
+ #' for parameters, use "dataframe".
6
+ #' @param list_element Which elements of the sublists do you wish to compile?
7
+ #'
8
+ #' @return compile_data converts the outputs of fit_many into a form more
9
+ #' readily usable for analysis. Can be used to create dataframe of all
10
+ #' fitted parameters, a list of model outputs, a list of graphs for plotting.
11
+ #' This function is NOT restricted to compiling outputs from plantecophystools
12
+ #' but could be used to compile elements from ANY list of lists.
13
+ #'
14
+ #' @export
15
+ #'
16
+ #' @examples
17
+ #' \donttest{
18
+ #' # Read in your data
19
+ #' # Note that this data is coming from data supplied by the package
20
+ #' # hence the complicated argument in read.csv()
21
+ #' # This dataset is a CO2 by light response curve for a single sunflower
22
+ #' data <- read.csv(system.file("extdata", "A_Ci_Q_data_1.csv",
23
+ #' package = "photosynthesis"
24
+ #' ))
25
+ #'
26
+ #' # Define a grouping factor based on light intensity to split the ACi
27
+ #' # curves
28
+ #' data$Q_2 <- as.factor((round(data$Qin, digits = 0)))
29
+ #'
30
+ #' # Convert leaf temperature to K
31
+ #' data$T_leaf <- data$Tleaf + 273.15
32
+ #'
33
+ #' # Fit many curves
34
+ #' fits <- fit_many(
35
+ #' data = data,
36
+ #' varnames = list(
37
+ #' A_net = "A",
38
+ #' T_leaf = "T_leaf",
39
+ #' C_i = "Ci",
40
+ #' PPFD = "Qin"
41
+ #' ),
42
+ #' funct = fit_aci_response,
43
+ #' group = "Q_2"
44
+ #' )
45
+ #'
46
+ #' # Compile graphs into a list for plotting
47
+ #' fits_graphs <- compile_data(fits,
48
+ #' list_element = 2
49
+ #' )
50
+ #'
51
+ #' # Plot one graph from the compiled list
52
+ #' plot(fits_graphs[[1]])
53
+ #' }
54
+ compile_data <- function(
55
+ data,
56
+ output_type = "list",
57
+ list_element
58
+ ) {
59
+ # Is output_type compatible with options?
60
+ if (!output_type %in% c("list", "dataframe")) {
61
+ stop("Output type not found. Use list or dataframe.")
62
+ }
63
+ # Create empty list
64
+ output <- vector("list", length(data))
65
+ # Create output list with desired elements
66
+ # Add correct names
67
+ for (i in seq_along(data)) {
68
+ output[[i]] <- data[[i]][[list_element]]
69
+ names(output)[i] <- names(data[i])
70
+ }
71
+ # If desired output is a list, return output list here
72
+ if (output_type == "list") {
73
+ return(output)
74
+ }
75
+ # If desired output is a dataframe, create it from the list here
76
+ # Add ID column to dataframe
77
+ if (output_type == "dataframe") {
78
+ for (i in 1:length(output)) {
79
+ output[[i]]$ID <- names(output)[i]
80
+ }
81
+ output <- do.call("bind_rows", output)
82
+ return(output)
83
+ }
84
+ }
data/R/compute_sensitivity.R ADDED
@@ -0,0 +1,172 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #' Computing measures of sensitivity
2
+ #'
3
+ #' @param data Dataframe with output from sensitivity_analysis()
4
+ #' @param varnames Variable names
5
+ #' @param test1_ref Reference value for parameter
6
+ #' @param test2_ref Reference value for parameter
7
+ #'
8
+ #' @return compute_sensitivity calculates two sets of sensitivity measures:
9
+ #' parameter effect (Bauerle et al., 2014), and control coefficient (Capaldo &
10
+ #' Pandis, 1997). This function is useful in determining how much a given
11
+ #' input (assumed or otherwise) can affect the model output and conclusions.
12
+ #' Particularly useful if a given parameter is unknown during a fitting or
13
+ #' modeling process.
14
+ #'
15
+ #' @references
16
+ #' Bauerle WL, Daniels AB, Barnard DM. 2014. Carbon and water flux responses to
17
+ #' physiology by environment interactions: a sensitivity analysis of variation
18
+ #' in climate on photosynthetic and stomatal parameters. Climate Dynamics 42:
19
+ #' 2539-2554.
20
+ #'
21
+ #' Capaldo KP, Pandis SN 1997. Dimethylsulfide chemistry in the remote marine
22
+ #' atmosphere: evaluation and sensitivity analysis of available mechanisms.
23
+ #' J Geophys Res 102:23251-23267
24
+ #' @importFrom utils setTxtProgressBar
25
+ #' @importFrom utils txtProgressBar
26
+ #' @export
27
+ #'
28
+ #' @examples
29
+ #' \donttest{
30
+ #' # Read in your data
31
+ #' # Note that this data is coming from data supplied by the package
32
+ #' # hence the complicated argument in read.csv()
33
+ #' # This dataset is a CO2 by light response curve for a single sunflower
34
+ #' data <- read.csv(system.file("extdata", "A_Ci_Q_data_1.csv",
35
+ #' package = "photosynthesis"
36
+ #' ))
37
+ #'
38
+ #' # Define a grouping factor based on light intensity to split the ACi
39
+ #' # curves
40
+ #' data$Q_2 <- as.factor((round(data$Qin, digits = 0)))
41
+ #'
42
+ #' # Convert leaf temperature to K
43
+ #' data$T_leaf <- data$Tleaf + 273.15
44
+ #'
45
+ #' # Run a sensitivity analysis on gamma_star and mesophyll conductance
46
+ #' # at 25 Celsius for one individual curve
47
+ #' # pars <- analyze_sensitivity(
48
+ #' # data = data[data$Q_2 == 1500, ],
49
+ #' # funct = fit_aci_response,
50
+ #' # varnames = list(
51
+ #' # A_net = "A",
52
+ #' # T_leaf = "T_leaf",
53
+ #' # C_i = "Ci",
54
+ #' # PPFD = "Qin"
55
+ #' # ),
56
+ #' # useg_mct = TRUE,
57
+ #' # test1 = "gamma_star25",
58
+ #' # element_out = 1,
59
+ #' # test2 = "g_mc25",
60
+ #' # fitTPU = TRUE,
61
+ #' # Ea_gamma_star = 0,
62
+ #' # Ea_g_mc = 0,
63
+ #' # values1 = seq(
64
+ #' # from = 20,
65
+ #' # to = 60,
66
+ #' # by = 2
67
+ #' # ),
68
+ #' # values2 = seq(
69
+ #' # from = 0.2,
70
+ #' # to = 2,
71
+ #' # by = 0.1
72
+ #' # )
73
+ #' # )
74
+ #' # Compute measures of sensitivity
75
+ #' # par2 <- compute_sensitivity(
76
+ #' # data = pars,
77
+ #' # varnames = list(
78
+ #' # Par = "V_cmax",
79
+ #' # test1 = "gamma_star25",
80
+ #' # test2 = "g_mc25"
81
+ #' # ),
82
+ #' # test1_ref = 42,
83
+ #' # test2_ref = 1
84
+ #' # )
85
+ #' # # Plot control coefficients
86
+ #' # ggplot(par2, aes(y = CE_gamma_star25, x = CE_g_mc25, colour = V_cmax)) +
87
+ #' # geom_point() +
88
+ #' # theme_bw()
89
+ #' # # Note that in this case a missing point appears due to an infinity
90
+ #' }
91
+ compute_sensitivity <- function(data,
92
+ varnames = list(
93
+ Par = "Par",
94
+ test1 = "test1",
95
+ test2 = "test2"
96
+ ),
97
+ test1_ref,
98
+ test2_ref) {
99
+ # Set variable names
100
+ data$Par <- data[, varnames$Par]
101
+ data$test1 <- data[, varnames$test1]
102
+ data$test2 <- data[, varnames$test2]
103
+ # Calculate parameter effect (PE) of one input per each instance of
104
+ # the other input. Therefore need to split data relative to one variable,
105
+ # calculate PE, merge data, then split by other variable and repeat
106
+ # Split data by variable 2
107
+ data <- split(data, data$test2)
108
+ # Start progress bar
109
+ pb <- txtProgressBar(min = 0, max = length(data), style = 3)
110
+ # Calculate parameter effect
111
+ for (i in 1:length(data)) {
112
+ data[[i]]$PE_test1 <- abs(data[[i]][data[[i]]$test1 ==
113
+ max(data[[i]]$test1), ]$Par -
114
+ data[[i]][data[[i]]$test1 ==
115
+ min(data[[i]]$test1), ]$Par) /
116
+ mean(data[[i]]$Par) * 100
117
+ # Set progress bar
118
+ setTxtProgressBar(pb, i)
119
+ }
120
+ # Bind back to dataframe
121
+ data <- do.call("rbind", data)
122
+ # Split data by variable 1
123
+ data <- split(data, data$test1)
124
+ # Start progress bar
125
+ pb <- txtProgressBar(min = 0, max = length(data), style = 3)
126
+ # Calculate parameter effect
127
+ for (i in 1:length(data)) {
128
+ data[[i]]$PE_test2 <- abs(data[[i]][data[[i]]$test2 ==
129
+ max(data[[i]]$test2), ]$Par -
130
+ data[[i]][data[[i]]$test2 ==
131
+ min(data[[i]]$test2), ]$Par) /
132
+ mean(data[[i]]$Par) * 100
133
+ # Set progress bar
134
+ setTxtProgressBar(pb, i)
135
+ }
136
+ # Bind back to dataframe
137
+ data <- do.call("rbind", data)
138
+
139
+ # Calculate control coefficients. In this case, we are deriving it numerically
140
+ # Need reference point in the entire parameter space, this is test1_ref and
141
+ # test2_ref. Calculations from Capaldo & Pandis 1997.
142
+ data$CE_test1 <- NA
143
+ data$CE_test2 <- NA
144
+ for (i in 1:nrow(data)) {
145
+ data$CE_test1[i] <- (log(data$Par[i]) - log(data[data$test1 == test1_ref &
146
+ data$test2 == test2_ref, ]$Par)) /
147
+ (log(data$test1[i]) - log(data[data$test1 == test1_ref &
148
+ data$test2 == test2_ref, ]$test1))
149
+ data$CE_test2[i] <- (log(data$Par[i]) - log(data[data$test1 == test1_ref &
150
+ data$test2 == test2_ref, ]$Par)) /
151
+ (log(data$test2[i]) - log(data[data$test1 == test1_ref &
152
+ data$test2 == test2_ref, ]$test2))
153
+ }
154
+
155
+ # Name output columns based on selected variable name
156
+ for (i in 1:ncol(data)) {
157
+ if (colnames(data)[i] == "PE_test1") {
158
+ colnames(data)[i] <- paste0("PE_", varnames$test1)
159
+ }
160
+ if (colnames(data)[i] == "PE_test2") {
161
+ colnames(data)[i] <- paste0("PE_", varnames$test2)
162
+ }
163
+ if (colnames(data)[i] == "CE_test1") {
164
+ colnames(data)[i] <- paste0("CE_", varnames$test1)
165
+ }
166
+ if (colnames(data)[i] == "CE_test2") {
167
+ colnames(data)[i] <- paste0("CE_", varnames$test2)
168
+ }
169
+ }
170
+ # Return dataframe
171
+ return(data)
172
+ }
data/R/conductance.R ADDED
@@ -0,0 +1,307 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #' Conductance to CO2 (mol / m^2 / s)
2
+ #'
3
+ #' @inheritParams A_supply
4
+ #'
5
+ #' @name CO2_conductance
6
+ #'
7
+ #' @details
8
+ #'
9
+ #' **Default conductance model**
10
+ #'
11
+ #' The conductance model described in this section is used by default unless
12
+ #' additional anatomical parameters described in the next section are provided.
13
+ #'
14
+ #' Total conductance to CO2 is the sum of parallel conductances on the lower
15
+ #' (\eqn{g_\mathrm{c,lower}}{gc_lower}) and upper
16
+ #' (\eqn{g_\mathrm{c,upper}}{gc_upper}) leaf portions:
17
+ #'
18
+ #' \deqn{g_\mathrm{c,total} = g_\mathrm{c,lower} + g_\mathrm{c,upper}}{gc_total = gc_lower + gc_upper}
19
+ #'
20
+ #' Each partial conductance consists of two parallel conductances, the
21
+ #' cuticular conductance (\eqn{g_\mathrm{u,c}}{g_uc}) and the in-series
22
+ #' conductances through mesophyll (\eqn{g_\mathrm{m,c}}{g_mc}), stomata (\eqn{g_\mathrm{s,c}}{g_sc}), and boundary layer (\eqn{g_\mathrm{b,c}}{g_bc}). To simplify the formula, I use substitute resistance where \eqn{r_x = 1 / g_x}. For surface \eqn{i}:
23
+ #'
24
+ #' \deqn{g_{\mathrm{c},i} = g_{\mathrm{u},i} + (1 / (r_{\mathrm{m},i} + r_{\mathrm{s},i} + r_{\mathrm{b},i}))}{g_ci = g_ui + (1 / (r_mi + r_si + r_bi))}
25
+ #'
26
+ #' The cuticular, stomatal, and mesophyll conductances can be the same or
27
+ #' different for upper and lower. The partitioning factors (\eqn{k_x}) divide the conductance between surfaces while keeping the total conductance constant:
28
+ #'
29
+ #' \deqn{g_{x,\mathrm{lower}} = g_x (1 / (1 + k_x))}{gx_lower = g_x (1 / (1 + k_x))}
30
+ #' \deqn{g_{x,\mathrm{upper}} = g_x (k_x / (1 + k_x))}{gx_upper = g_x (k_x / (1 + k_x))}
31
+ #' \deqn{g_x = g_{x,\mathrm{lower}} + g_{x,\mathrm{upper}}}{g_x = gx_lower + gx_upper}
32
+ #'
33
+ #' How the partitioning factors work: \cr
34
+ #' \tabular{ll}{
35
+ #' \eqn{k_x} \tab description \cr
36
+ #' 0 \tab all conductance on **lower** surface/portion \cr
37
+ #' 0.5 \tab 2/3 conductance on **lower** surface \cr
38
+ #' 1 \tab conductance evenly divided between surfaces/portions \cr
39
+ #' 2 \tab 2/3 conductance on **upper** surface \cr
40
+ #' Inf \tab all conductance on **upper** surface/portion
41
+ #' }
42
+ #'
43
+ #' The boundary layer conductances for each are calculated on the basis of mass
44
+ #' and heat transfer (see [.get_gbc()]).
45
+ #'
46
+ #' \tabular{lllll}{
47
+ #' *Symbol* \tab *R* \tab *Description* \tab *Units* \tab *Default*\cr
48
+ #' \eqn{g_\mathrm{mc}}{g_mc} \tab `g_mc` \tab mesophyll conductance to CO2 (T_leaf) \tab mol / m\eqn{^2} / s \tab [calculated][bake] \cr
49
+ #' \eqn{g_\mathrm{sc}}{g_sc} \tab `g_sc` \tab stomatal conductance to CO2 \tab mol / m\eqn{^2} / s \tab `r dplyr::pull(photo_parameters[photo_parameters$R == "g_sc","default"])` \cr
50
+ #' \eqn{g_\mathrm{uc}}{g_uc} \tab `g_uc` \tab cuticular conductance to CO2 \tab mol / m\eqn{^2} / s \tab `r dplyr::pull(photo_parameters[photo_parameters$R == "g_uc","default"])` \cr
51
+ #' \eqn{k_\mathrm{mc}}{k_mc} \tab `k_mc` \tab partition of \eqn{g_\mathrm{mc}}{g_mc} to lower mesophyll \tab none \tab `r dplyr::pull(photo_parameters[photo_parameters$R == "k_mc","default"])` \cr
52
+ #' \eqn{k_\mathrm{sc}}{k_sc} \tab `k_sc` \tab partition of \eqn{g_\mathrm{sc}}{g_sc} to lower surface \tab none \tab `r dplyr::pull(photo_parameters[photo_parameters$R == "k_sc","default"])` \cr
53
+ #' \eqn{k_\mathrm{uc}}{k_uc} \tab `k_uc` \tab partition of \eqn{g_\mathrm{uc}}{g_uc} to lower surface \tab none \tab `r dplyr::pull(photo_parameters[photo_parameters$R == "k_uc","default"])` \cr
54
+ #' }
55
+ #'
56
+ #' **New conductance model**
57
+ #'
58
+ #' The conductance model described in this section is implemented in
59
+ #' **photosynthesis** (>= 2.1.0) if parameters to calculate the internal
60
+ #' airspace and liquid-phase conductances (`A_mes_A`, `g_liqc`) are
61
+ #' provided. These parameters are 1) the effective path lengths through the
62
+ #' lower and upper leaf internal airspaces (`delta_ias_lower`,
63
+ #' `delta_ias_upper`) and 2) the mesophyll area per leaf area
64
+ #' (`A_mes_A`) and liquid-phase conductance per mesophyll cell area
65
+ #' (`g_liqc`).
66
+ #'
67
+ #' Two parallel diffusion pathways, one from each leaf surface, converge to a
68
+ #' single CO2 concentration at the mesophyll cell boundary. We use a single
69
+ #' liquid-phase resistance to represent the combined cell wall, plasmalemma, and
70
+ #' chloroplast resistances. The gas-phase resistance through boundary layer,
71
+ #' cuticle/stomata, and internal airspace is \eqn{r_\mathrm{gas,c}}; the
72
+ #' liquid-phase intracellular resistance is \eqn{r_\mathrm{i,c}}.
73
+ #'
74
+ #' \deqn{r_\mathrm{total,c} = r_\mathrm{gas,c} + r_\mathrm{i,c}}{r_total,c = r_gas,c + r_i,c}
75
+ #'
76
+ #' The gas-phase resistance occurs through two parallel pathways, which we refer
77
+ #' to as the 'lower' and 'upper' pathways because horizontally oriented leaves
78
+ #' often have different anatomical properties on each surface. The gas-phase
79
+ #' resistance through pathway \eqn{i \in \{\textrm{lower,upper\}}} is:
80
+ #'
81
+ #' \deqn{r_{\mathrm{gas,c},i} = r_{\mathrm{b,c},i} + r_{\mathrm{u+s,c},i} + r_{\mathrm{ias,c},i}}{r_gas,c,i = r_b,c,i + r_u+s,c,i + r_ias,c,i}
82
+ #'
83
+ #' The subscripts \eqn{_\mathrm{b}}, \eqn{_\mathrm{u+s}}, and \eqn{_\mathrm{ias}}
84
+ #' denote boundary layer, cuticular + stomatal, and internal airspace,
85
+ #' respectively. The subscript \eqn{_\mathrm{c}} indicates we are considering
86
+ #' the conductance to CO2 rather than another molecular species.
87
+ #'
88
+ #' Cuticular and stomatal conductances (1 / resistance) are parallel, so:
89
+ #'
90
+ #' \deqn{1 / r_{\mathrm{u+s,c},i} = g_{\mathrm{u+s,c},i} = g_{\mathrm{u,c},i} + g_{\mathrm{s,c},i}}{1 / r_u+s,c,i = g_u+s,c,i = g_u,c,i + g_s,c,i}
91
+ #'
92
+ #' Substituting the above expression into the equation for \eqn{r_{\mathrm{gas,c},i}}{r_gas,c,i}:
93
+ #'
94
+ #' \deqn{r_{\mathrm{gas,c},i} = r_{\mathrm{b,c},i} + 1 / (g_{\mathrm{u,c},i} = g_{\mathrm{s,c},i}) + r_{\mathrm{ias,c},i}}{r_gas,c,i = r_b,c,i + 1 / (g_u,c,i + g_s,c,i) + r_ias,c,i}
95
+ #'
96
+ #' The total gas-phase resistance is the inverse of the sum of the parallel
97
+ #' lower and upper conductances:
98
+ #'
99
+ #' \deqn{1 / r_{\mathrm{gas,c}} = g_\mathrm{gas,c,lower} + g_\mathrm{gas,c,upper}}{1 / r_gas,c = g_gas,c = g_gas,c,lower + g_gas,c,upper}
100
+ #'
101
+ #' The cuticular, stomatal, and mesophyll conductances can be the same or
102
+ #' different for upper and lower. The partitioning factors \eqn{k_u} and \eqn{k_s}
103
+ #' divide the total cuticular and stomatal conductances, respectively, between
104
+ #' surfaces while keeping the total conductance constant:
105
+ #'
106
+ #' \deqn{g_{x,\mathrm{lower}} = g_x (1 / (1 + k_x))}{gx_lower = g_x (1 / (1 + k_x))}
107
+ #' \deqn{g_{x,\mathrm{upper}} = g_x (k_x / (1 + k_x))}{gx_upper = g_x (k_x / (1 + k_x))}
108
+ #' \deqn{g_x = g_{x,\mathrm{lower}} + g_{x,\mathrm{upper}}}{g_x = gx_lower + gx_upper}
109
+ #'
110
+ #' How the partitioning factors work: \cr
111
+ #' \tabular{ll}{
112
+ #' \eqn{k_x} \tab description \cr
113
+ #' 0 \tab all conductance on **lower** surface/portion \cr
114
+ #' 0.5 \tab 2/3 conductance on **lower** surface \cr
115
+ #' 1 \tab conductance evenly divided between surfaces/portions \cr
116
+ #' 2 \tab 2/3 conductance on **upper** surface \cr
117
+ #' Inf \tab all conductance on **upper** surface/portion
118
+ #' }
119
+ #'
120
+ #' The internal airspace conductance is the diffusivity of CO2 at a given
121
+ #' temperature and pressure divided by the effective path length:
122
+ #'
123
+ #' \deqn{g_\mathrm{ias,c,lower} = D_\mathrm{c} / \delta_\mathrm{ias,lower}}{g_iasc_lower = D_c / delta_ias_lower}
124
+ #' \deqn{g_\mathrm{ias,c,upper} = D_\mathrm{c} / \delta_\mathrm{ias,upper}}{g_iasc_ipper = D_c / delta_ias_upper}
125
+ #'
126
+ #' `g_iasc_lower` and `g_iasc_upper` are calculated in the [bake]
127
+ #' function. See [tealeaves::.get_Dx()] for calculating `D_c`.
128
+ #'
129
+ #' The liquid-phase intracellular resistance is given by:
130
+ #'
131
+ #' \deqn{1 / r_\mathrm{i,c} = g_\mathrm{i,c} = g_\mathrm{liq,c} A_\mathrm{mes} / A}{1 / r_i,c = g_i,c = g_liq,c A_mes / A}
132
+ #'
133
+ #' \eqn{g_\mathrm{liq,c}}{g_liq,c} is temperature sensitive. See [bake()].
134
+ #'
135
+ #' The boundary layer conductances for each are calculated on the basis of mass
136
+ #' and heat transfer (see [.get_gbc()]).
137
+ #'
138
+ #' @encoding UTF-8
139
+ #' @md
140
+
141
+ NULL
142
+
143
+ #' - g_tc: total conductance to CO2
144
+ #'
145
+ #' @rdname CO2_conductance
146
+ .get_gtc = function(pars, unitless, use_legacy_version) {
147
+
148
+ if (check_new_conductance(pars, baked = TRUE)) {
149
+
150
+ gbc_lower = .get_gbc(pars, "lower", unitless, use_legacy_version)
151
+ gsc_lower = .get_gsc(pars, "lower", unitless)
152
+ guc_lower = .get_guc(pars, "lower", unitless)
153
+
154
+ gbc_upper = .get_gbc(pars, "upper", unitless, use_legacy_version)
155
+ gsc_upper = .get_gsc(pars, "upper", unitless)
156
+ guc_upper = .get_guc(pars, "upper", unitless)
157
+
158
+ g_usc_lower = guc_lower + gsc_lower
159
+ g_usc_upper = guc_upper + gsc_upper
160
+ g_gasc_lower = 1 / (1 / gbc_lower + 1 / g_usc_lower + 1 / pars$g_iasc_lower)
161
+ g_gasc_upper = 1 / (1 / gbc_upper + 1 / g_usc_upper + 1 / pars$g_iasc_upper)
162
+ g_gasc = g_gasc_lower + g_gasc_upper
163
+ g_ic = pars$g_liqc * pars$A_mes_A
164
+ g_tc = 1 / (1 / g_gasc + 1 / g_ic)
165
+
166
+ if (!unitless) g_tc %<>% set_units(mol / m^2 / s)
167
+
168
+ return(g_tc)
169
+
170
+ } else {
171
+
172
+ gbc_lower = .get_gbc(pars, "lower", unitless, use_legacy_version)
173
+ gmc_lower = .get_gmc(pars, "lower", unitless)
174
+ gsc_lower = .get_gsc(pars, "lower", unitless)
175
+ guc_lower = .get_guc(pars, "lower", unitless)
176
+
177
+ gbc_upper = .get_gbc(pars, "upper", unitless, use_legacy_version)
178
+ gmc_upper = .get_gmc(pars, "upper", unitless)
179
+ gsc_upper = .get_gsc(pars, "upper", unitless)
180
+ guc_upper = .get_guc(pars, "upper", unitless)
181
+
182
+ rc_lower = 1 / gmc_lower + 1 / gsc_lower + 1 / gbc_lower
183
+ gc_lower = 1 / rc_lower
184
+ gc_lower %<>% magrittr::add(guc_lower)
185
+ rc_upper = 1 / gmc_upper + 1 / gsc_upper + 1 / gbc_upper
186
+ gc_upper = 1 / rc_upper
187
+ gc_upper %<>% magrittr::add(guc_upper)
188
+
189
+ g_tc = gc_lower + gc_upper
190
+
191
+ if (!unitless) g_tc %<>% set_units(mol / m^2 / s)
192
+
193
+ return(g_tc)
194
+
195
+ }
196
+
197
+ }
198
+
199
+ #' - g_uc: cuticular conductance to CO2
200
+ #'
201
+ #' @param surface Leaf surface (lower or upper)
202
+ #'
203
+ #' @rdname CO2_conductance
204
+ .get_guc = function(pars, surface, unitless) {
205
+ surface %<>% match.arg(c("lower", "upper"))
206
+
207
+ if (unitless) {
208
+ g_uc = switch(
209
+ surface,
210
+ lower = pars$g_uc * (1 / (1 + pars$k_uc)),
211
+ upper = pars$g_uc * (pars$k_uc / (1 + pars$k_uc))
212
+ )
213
+ } else {
214
+ g_uc = switch(
215
+ surface,
216
+ lower = pars$g_uc * (set_units(1) / (set_units(1) + pars$k_uc)),
217
+ upper = pars$g_uc * (pars$k_uc / (set_units(1) + pars$k_uc))
218
+ )
219
+ }
220
+
221
+ g_uc
222
+ }
223
+ #' - g_bc: boundary layer conductance to CO2
224
+ #'
225
+ #' @inheritParams .get_guc
226
+ #'
227
+ #' @rdname CO2_conductance
228
+ .get_gbc = function(pars, surface, unitless, use_legacy_version) {
229
+ surface %<>% match.arg(c("lower", "upper"))
230
+
231
+ # Hack because f_sh = sh_constant, f_sh = sh_constant in tealeaves
232
+ # Should update tealeaves to harmonize variable and function names
233
+ pars$sh_constant = pars$f_sh
234
+ pars$nu_constant = pars$f_nu
235
+ ret = .get_gbw(pars$T_leaf, surface, pars, unitless) |>
236
+ set_units(m / s) |>
237
+ gunit::convert_conductance(
238
+ P = set_units(pars$P, kPa),
239
+ R = set_units(pars$R, J / K / mol),
240
+ Temp = set_units((pars$T_air + pars$T_leaf) / 2, K)
241
+ ) |>
242
+ dplyr::pull(.data$`umol/m^2/s/Pa`) |>
243
+ gunit::gw2gc(D_c = pars$D_c0, D_w = pars$D_w0, unitless = unitless,
244
+ a = ifelse(use_legacy_version, 1, 2/3)) |>
245
+ # Convert to mol / m^2 / s
246
+ magrittr::multiply_by(pars$P)
247
+
248
+ # Divide 1e3 because conversion is from umol / kPa -> mol
249
+ # umol / m^2 / s / Pa * 1e3 Pa / kPa * mol / 1e6 umol
250
+ if (unitless) {
251
+ ret = ret / 1e3
252
+ } else {
253
+ ret = set_units(ret, mol/m^2/s)
254
+ }
255
+
256
+ ret
257
+
258
+ }
259
+ #' - g_mc: mesophyll conductance to CO2
260
+ #'
261
+ #' @inheritParams .get_guc
262
+ #'
263
+ #' @rdname CO2_conductance
264
+ .get_gmc = function(pars, surface, unitless) {
265
+
266
+ surface %<>% match.arg(c("lower", "upper"))
267
+
268
+ if (unitless) {
269
+ g_mc = switch(
270
+ surface,
271
+ lower = pars$g_mc * (1 / (1 + pars$k_mc)),
272
+ upper = pars$g_mc * (pars$k_mc / (1 + pars$k_mc))
273
+ )
274
+ } else {
275
+ g_mc = switch(
276
+ surface,
277
+ lower = pars$g_mc * (1 / (set_units(1) + pars$k_mc)),
278
+ upper = pars$g_mc * (pars$k_mc / (set_units(1) + pars$k_mc))
279
+ )
280
+ }
281
+
282
+ g_mc
283
+
284
+ }
285
+ #' - g_sc: stomatal conductance to CO2
286
+ #'
287
+ #' @inheritParams .get_guc
288
+ #'
289
+ #' @rdname CO2_conductance
290
+ .get_gsc = function(pars, surface, unitless) {
291
+ surface %<>% match.arg(c("lower", "upper"))
292
+ if (unitless) {
293
+ g_sc = switch(
294
+ surface,
295
+ lower = pars$g_sc * (1 / (1 + pars$k_sc)),
296
+ upper = pars$g_sc * (pars$k_sc / (1 + pars$k_sc))
297
+ )
298
+ } else {
299
+ g_sc = switch(
300
+ surface,
301
+ lower = pars$g_sc * (set_units(1) / (set_units(1) + pars$k_sc)),
302
+ upper = pars$g_sc * (pars$k_sc / (set_units(1) + pars$k_sc))
303
+ )
304
+ }
305
+
306
+ g_sc
307
+ }
data/R/constants.R ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #' S3 class constants
2
+ #' @inheritParams photosynthesis
3
+ #' @param .x A list to be constructed into **constants**.
4
+ #'
5
+ #' @returns
6
+ #' Constructor function for constants class. This function ensures that
7
+ #' physical constant inputs are properly formatted.
8
+ #'
9
+ #' @export
10
+ constants = function(.x, use_tealeaves) {
11
+
12
+ which = "constants"
13
+
14
+ # Check parameters names ----
15
+ nms = check_parameter_names(.x, which = which, use_tealeaves = use_tealeaves)
16
+ .x = .x |>
17
+ magrittr::extract(nms) |>
18
+ # Set units ----
19
+ set_parameter_units(
20
+ .data$type == which,
21
+ !.data$temperature_response,
22
+ if (!use_tealeaves) {!.data$tealeaves} else TRUE
23
+ )
24
+
25
+ # Assert bounds on values ----
26
+ .x |>
27
+ assert_parameter_bounds(
28
+ .data$type == which,
29
+ !.data$temperature_response,
30
+ if (!use_tealeaves) {!.data$tealeaves} else TRUE
31
+ )
32
+
33
+ structure(.x, class = c(which, "list"))
34
+
35
+ }
data/R/data.R ADDED
@@ -0,0 +1,14 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #' Input parameters to simulate C3 photosynthesis using [photosynthesis()]
2
+ #'
3
+ #' A table of input parameters used in [photosynthesis()]
4
+ #'
5
+ #' @format ## `photo_parameters`
6
+ #' A data frame with `r nrow(photo_parameters)` rows and `r ncol(photo_parameters)` columns:
7
+ #' \describe{
8
+ #' \item{country}{Country name}
9
+ #' \item{iso2, iso3}{2 & 3 letter ISO country codes}
10
+ #' \item{year}{Year}
11
+ #' ...
12
+ #' }
13
+ #' @source <https://www.who.int/teams/global-tuberculosis-programme/data>
14
+ "photo_parameters"
data/R/enviro-par.R ADDED
@@ -0,0 +1,65 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #' S3 class enviro_par
2
+ #
3
+
4
+ #' @inheritParams photosynthesis
5
+ #' @param .x A list to be constructed into **enviro_par**.
6
+ #'
7
+ #' @returns
8
+ #'
9
+ #' Constructor function for enviro_par class. This function ensures that environmental parameter inputs are properly formatted.
10
+ #'
11
+ #' @export
12
+
13
+ enviro_par = function(.x, use_tealeaves) {
14
+
15
+ which = "enviro"
16
+
17
+ # Check parameters names ----
18
+ nms = check_parameter_names(.x, which = which, use_tealeaves = use_tealeaves)
19
+ .x = .x |>
20
+ magrittr::extract(nms) |>
21
+ # Set units ----
22
+ set_parameter_units(
23
+ .data$type == which,
24
+ !.data$temperature_response,
25
+ if (!use_tealeaves) {!.data$tealeaves} else TRUE
26
+ )
27
+
28
+ # Assert bounds on values ----
29
+ .x |>
30
+ assert_parameter_bounds(
31
+ .data$type == which,
32
+ !.data$temperature_response,
33
+ if (!use_tealeaves) {!.data$tealeaves} else TRUE
34
+ )
35
+
36
+ # Notify about T_sky ----
37
+ if (use_tealeaves) {
38
+
39
+ # T_sky can be set or provided as a function ----
40
+ if (is.null(.x$T_sky)) {
41
+ message(
42
+ '\nphotosynthesis (>= 1.0.2) will require users provide a T_sky value or
43
+ function to calculate T_sky from other parameters.
44
+
45
+ For back-compatibility, if T_sky is not provided, this warning will
46
+ appear and the default function used in tealeaves (< 1.0.2) will be
47
+ applied.
48
+
49
+ See more details in vignette("parameter-functions")
50
+ '
51
+ )
52
+
53
+ .x$T_sky = get_f_parameter("T_sky")
54
+
55
+ } else {
56
+ stopifnot(is.function(.x$T_sky) | is.double(.x$T_sky))
57
+
58
+ if (is.double(.x$T_sky)) {
59
+ .x$T_sky %<>% set_units(K)
60
+ }
61
+ }
62
+ }
63
+
64
+ structure(.x, class = c(stringr::str_c(which, "_par"), "list"))
65
+ }
data/R/fit_PV_curve.R ADDED
@@ -0,0 +1,263 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #' Fitting pressure-volume curves
2
+ #'
3
+ #' @param data Dataframe
4
+ #' @param varnames Variable names. varnames = list(psi = "psi", mass =
5
+ #' "mass", leaf_mass = "leaf_mass", bag_mass = "bag_mass", leaf_area =
6
+ #' "leaf_area") where psi is leaf water potential in MPa, mass is the
7
+ #' weighed mass of the bag and leaf in g, leaf_mass is the mass of the
8
+ #' leaf in g, bag_mass is the mass of the bag in g, and leaf_area is
9
+ #' the area of the leaf in cm2.
10
+ #' @param title Graph title
11
+ #'
12
+ #' @return fit_PV_curve fits pressure-volume curve data to determine:
13
+ #' SWC: saturated water content per leaf mass (g H2O g leaf dry mass ^ -1),
14
+ #' PI_o: osmotic potential at full turgor (MPa), psi_TLP: leaf water
15
+ #' potential at turgor loss point (TLP) (MPa), RWC_TLP: relative water
16
+ #' content at TLP (%), eps: modulus of elasticity at full turgor (MPa),
17
+ #' C_FT: relative capacitance at full turgor (MPa ^ -1), C_TLP: relative
18
+ #' capacitance at TLP (MPa ^ -1), and C_FTStar: absolute capacitance per
19
+ #' leaf area (g m ^ -2 MPa ^ -1). Element 1 of the output list contains
20
+ #' the fitted parameters, element 2 contains the water-psi graph, and
21
+ #' element 3 contains the 1/psi-100-RWC graph.
22
+ #'
23
+ #' @references
24
+ #' Koide RT, Robichaux RH, Morse SR, Smith CM. 2000. Plant water status,
25
+ #' hydraulic resistance and capacitance. In: Plant Physiological Ecology:
26
+ #' Field Methods and Instrumentation (eds RW Pearcy, JR Ehleringer, HA
27
+ #' Mooney, PW Rundel), pp. 161-183. Kluwer, Dordrecht, the Netherlands
28
+ #'
29
+ #' Sack L, Cowan PD, Jaikumar N, Holbrook NM. 2003. The 'hydrology' of
30
+ #' leaves: co-ordination of structure and function in temperate woody
31
+ #' species. Plant, Cell and Environment, 26, 1343-1356
32
+ #'
33
+ #' Tyree MT, Hammel HT. 1972. Measurement of turgor pressure and water
34
+ #' relations of plants by pressure bomb technique. Journal of Experimental
35
+ #' Botany, 23, 267
36
+ #'
37
+ #' @importFrom ggplot2 geom_hline
38
+ #' @export
39
+ #'
40
+ #' @examples
41
+ #' \donttest{
42
+ #' # Read in data
43
+ #' data <- read.csv(system.file("extdata", "PV_curve.csv",
44
+ #' package = "photosynthesis"
45
+ #' ))
46
+ #'
47
+ #' # Fit one PV curve
48
+ #' fit <- fit_PV_curve(data[data$ID == "L2", ],
49
+ #' varnames = list(
50
+ #' psi = "psi",
51
+ #' mass = "mass",
52
+ #' leaf_mass = "leaf_mass",
53
+ #' bag_mass = "bag_mass",
54
+ #' leaf_area = "leaf_area"
55
+ #' )
56
+ #' )
57
+ #'
58
+ #' # See fitted parameters
59
+ #' fit[[1]]
60
+ #'
61
+ #' # Plot water mass graph
62
+ #' fit[[2]]
63
+ #'
64
+ #' # Plot PV Curve
65
+ #' fit[[3]]
66
+ #'
67
+ #' # Fit all PV curves in a file
68
+ #' fits <- fit_many(data,
69
+ #' group = "ID",
70
+ #' funct = fit_PV_curve,
71
+ #' varnames = list(
72
+ #' psi = "psi",
73
+ #' mass = "mass",
74
+ #' leaf_mass = "leaf_mass",
75
+ #' bag_mass = "bag_mass",
76
+ #' leaf_area = "leaf_area"
77
+ #' )
78
+ #' )
79
+ #'
80
+ #' # See parameters
81
+ #' fits[[1]][[1]]
82
+ #'
83
+ #' # See water mass - water potential graph
84
+ #' fits[[1]][[2]]
85
+ #'
86
+ #' # See PV curve
87
+ #' fits[[1]][[3]]
88
+ #'
89
+ #' # Compile parameter outputs
90
+ #' pars <- compile_data(
91
+ #' data = fits,
92
+ #' output_type = "dataframe",
93
+ #' list_element = 1
94
+ #' )
95
+ #'
96
+ #' # Compile the water mass - water potential graphs
97
+ #' graphs1 <- compile_data(
98
+ #' data = fits,
99
+ #' output_type = "list",
100
+ #' list_element = 2
101
+ #' )
102
+ #'
103
+ #' # Compile the PV graphs
104
+ #' graphs2 <- compile_data(
105
+ #' data = fits,
106
+ #' output_type = "list",
107
+ #' list_element = 3
108
+ #' )
109
+ #' }
110
+ fit_PV_curve <- function(data,
111
+ varnames = list(
112
+ psi = "psi",
113
+ mass = "mass",
114
+ leaf_mass = "leaf_mass",
115
+ bag_mass = "bag_mass",
116
+ leaf_area = "leaf_area"
117
+ ),
118
+ title = NULL) {
119
+ # Locally bind variables
120
+ inv_psi <- NULL
121
+ inv_psi_pred <- NULL
122
+ leaf_water <- NULL
123
+ psi <- NULL
124
+ psi_pred <- NULL
125
+ `100-RWC` <- NULL
126
+ # Set variable names
127
+ data$psi <- data[, varnames$psi]
128
+ data$mass <- data[, varnames$mass]
129
+ data$leaf_mass <- data[, varnames$leaf_mass]
130
+ data$bag_mass <- data[, varnames$bag_mass]
131
+ data$leaf_area <- data[, varnames$leaf_area]
132
+ # Generate list for outputs
133
+ output <- list(NULL)
134
+ # Generate dataframe for outputs within list
135
+ output[[1]] <- as.data.frame(rbind(1:8))
136
+ colnames(output[[1]]) <- c(
137
+ "SWC",
138
+ "PI_o",
139
+ "psi_TLP",
140
+ "RWC_TLP",
141
+ "eps",
142
+ "C_FT",
143
+ "C_TLP",
144
+ "C_FTStar"
145
+ )
146
+ # Calculate inverse water potential for calculations
147
+ data$inv_psi <- -1 / data$psi
148
+ # Assign single value for leaf mass, bag mass, and leaf area
149
+ # First we assign NULL values to make sure the variable is
150
+ # locally bound to the function and not integrated into the
151
+ # global environment
152
+ leaf_mass <- NULL
153
+ bag_mass <- NULL
154
+ leaf_area <- NULL
155
+ leaf_mass <- data$leaf_mass[1]
156
+ bag_mass <- data$bag_mass[1]
157
+ leaf_area <- data$leaf_area[1]
158
+ # Calculate leaf water
159
+ data$leaf_water <- data$mass - leaf_mass - bag_mass
160
+ # Create empty list for regressions
161
+ water_fit <- list(NULL)
162
+ # Create vector of r-squared values for model selection
163
+ # Length is -2 because regression needs > 2 points
164
+ Rsq <- c(1:(length(data$mass) - 2))
165
+ # This regression needs to be from beginning to end of linear water loss
166
+ # Needs at least 3 points, hence i starting at 3, but cap at 5 to avoid
167
+ # issues if the first three points are not very linear
168
+ for (i in 3:length(data$mass)) {
169
+ water_fit[[i - 2]] <- lm(psi ~ leaf_water, data[1:i, ])
170
+ water_fit[[i - 2]]$Rsq <- summary(water_fit[[i - 2]])$r.squared
171
+ Rsq[i - 2] <- summary(water_fit[[i - 2]])$r.squared
172
+ }
173
+ # Need to select best fit based on r-squared
174
+ for (i in 1:3) {
175
+ if (water_fit[[i]]$Rsq == max(Rsq[1:3])) {
176
+ bestfit <- water_fit[[i]]
177
+ }
178
+ }
179
+ # Calculate saturated water content
180
+ # This is only for calulating other parameters
181
+ SWC <- -coef(bestfit)[1] / coef(bestfit)[2]
182
+ # Calculate saturated water content on leaf mass basis
183
+ output[[1]]$SWC <- SWC / leaf_mass
184
+ # Calculate relative water content
185
+ data$RWC <- data$leaf_water / SWC
186
+ # Convert RWC to percent and 100 - RWC
187
+ data$RWC_percent <- 100 * data$RWC
188
+ data$`100-RWC` <- 100 - data$RWC_percent
189
+ # Generate predicted psi for psi-water plot
190
+ data$psi_pred <- coef(bestfit)[[2]] * data$leaf_water + coef(bestfit)[[1]]
191
+ # Generate psi water plot - lets you see points used for regression
192
+ output[[2]] <- ggplot(data, aes(x = leaf_water, y = psi)) +
193
+ labs(y = expression(Psi[leaf] ~ "(MPa)", x = "Mass of water (g)")) +
194
+ geom_hline(yintercept = 0) +
195
+ geom_line(aes(y = psi_pred), colour = "Grey", linewidth = 2) +
196
+ geom_point(size = 2) +
197
+ theme_bw()
198
+ # Remove bestfit information to avoid code complications
199
+ bestfit <- NULL
200
+ # Generate empty list for predicting turgor loss point
201
+ psi_fit <- list(NULL)
202
+ # Generate r-squared vector
203
+ Rsq <- c(1:(length(data$mass) - 4))
204
+ # Run regressions, ensuring that there is a minimum of 3 points
205
+ # i starts at 3 to avoid first 2 points where large changes in psi
206
+ # can occur. Also finds cutoff observation for other calculations
207
+ for (i in 3:(length(data$inv_psi) - 2)) {
208
+ psi_fit[[i - 2]] <- lm(
209
+ inv_psi ~ `100-RWC`,
210
+ data[(length(data$inv_psi) - i):length(data$inv_psi), ]
211
+ )
212
+ psi_fit[[i - 2]]$Rsq <- summary(psi_fit[[i - 2]])$r.squared
213
+ psi_fit[[i - 2]]$Obs_cut <- i
214
+ Rsq[i - 2] <- summary(psi_fit[[i - 2]])$r.squared
215
+ }
216
+ # Find best model based on r-squared
217
+ for (i in 1:length(psi_fit)) {
218
+ if (psi_fit[[i]]$Rsq == max(Rsq)) {
219
+ bestfit <- psi_fit[[i]]
220
+ }
221
+ }
222
+ # Calculate psi and RWC at turgor loss point
223
+ output[[1]]$psi_TLP <- data[bestfit$Obs_cut, ]$psi
224
+ output[[1]]$RWC_TLP <- data[bestfit$Obs_cut, ]$RWC * 100
225
+ # Calculate osmotic potential at full turgor
226
+ output[[1]]$PI_o <- -1 / coef(bestfit)[1]
227
+ # Caclulate osmotic water potential
228
+ data$psi_o <- -1 / (coef(bestfit)[1] + coef(bestfit)[2] * data$`100-RWC`)
229
+ data$psi_p <- data$psi - data$psi_o
230
+ # Calculate modulus of elasticity at full turgor
231
+ output[[1]]$eps <- coef(lm(psi_p ~ RWC, data[1:bestfit$Obs_cut, ]))[2]
232
+ # Calculate relative capacitance at full turgor
233
+ # Include cutoff observations and points above cutoff
234
+ output[[1]]$C_FT <- coef(lm(RWC ~ psi, data[1:bestfit$Obs_cut, ]))[2]
235
+ # Calculate relative capacitance at turgor loss point
236
+ # Include cutoff observations and points below cutoff
237
+ output[[1]]$C_TLP <- coef(lm(
238
+ RWC ~ psi,
239
+ data[bestfit$Obs_cut:length(data$psi), ]
240
+ ))[2]
241
+ # Calculate absolute capacitance per area at full turgor
242
+ output[[1]]$C_FTStar <- output[[1]]$C_FT * SWC / 18 / (leaf_area / 10000)
243
+ # Calculate predicted inverse psi for graphing
244
+ data$inv_psi_pred <- coef(bestfit)[[2]] * data$`100-RWC` + coef(bestfit)[[1]]
245
+ # Graph the turgor loss point graph
246
+ output[[3]] <- ggplot(data, aes(x = `100-RWC`, y = inv_psi)) +
247
+ ggtitle(label = title) +
248
+ labs(y = expression("1 / " * Psi ~ "(MP" * a^{
249
+ -1
250
+ } * ")")) +
251
+ geom_line(aes(y = inv_psi_pred), linewidth = 3, colour = "Grey") +
252
+ geom_line(linewidth = 1, colour = "Black") +
253
+ geom_point(size = 4) +
254
+ theme_bw()
255
+ # Add names to output list
256
+ names(output) <- c(
257
+ "PV Parameters",
258
+ "Water Mass - Water Potential Graph",
259
+ "TLP Graph"
260
+ )
261
+ # Return output
262
+ return(output)
263
+ }
data/R/fit_aci_response.R ADDED
@@ -0,0 +1,502 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #' Fitting ACi curves
2
+ #'
3
+ #' @param data Dataframe for A-Ci curve fitting
4
+ #' @param varnames List of variable names. varnames = list(A_net = "A_net",
5
+ #' T_leaf = "T_leaf", C_i = "C_i", PPFD = "PPFD", g_mc = "g_mc"), where A_net
6
+ #' is net CO2 assimilation, T_leaf is leaf temperature in Kelvin, C_i is
7
+ #' intercellular CO2 concentration in umol/mol, PPFD is incident irradiance
8
+ #' in umol m-2 s-1 (note that it is ASSUMED to be absorbed irradiance, so be
9
+ #' sure to adjust according to light absorbance and PSI/PSII partitioning
10
+ #' accordingly OR interpret the resultant values of J and J_max with caution),
11
+ #' g_mc is mesophyll conductance to CO2 in mol m-2 s-1 Pa-1.
12
+ #' @param P Atmospheric pressure in kPa
13
+ #' @param fitTPU Should triose phosphate utilization (V_TPU) be fit?
14
+ #' @param alpha_g Fraction of respiratory glycolate carbon that is not returned
15
+ #' to the chloroplast (von Caemmerer, 2000). If ACi curves show high-CO2
16
+ #' decline, then this value should be > 0.
17
+ #' @param R_d_meas Measured value of respiratory CO2 efflux in umol m-2 s-1.
18
+ #' Input value should be positive to work as expected with the equations.
19
+ #' @param useR_d Use a measured value of R_d? Set to TRUE if using R_d_meas.
20
+ #' @param useg_mc Use mesophyll conductance? Set to TRUE if specifying g_mc
21
+ #' in varnames above.
22
+ #' @param useg_mct Use mesophyll conductance temperature response? Set to TRUE
23
+ #' if using a temperature response of mesophyll conductance.
24
+ #' @param usegamma_star Specify gamma_star value? If FALSE, uses a temperature
25
+ #' response function with Nicotiana tabacum defaults from Bernacchi et al.
26
+ #' 2001.
27
+ #' @param useK_M Specify K_M? If FALSE, uses an Arrhenius temperature response
28
+ #' function with Nicotiana tabacum defaults from Bernacchi et al. 2001.
29
+ #' @param useK_C_K_O Use individual carboxylation/oxygenation constants for
30
+ #' rubisco? If TRUE, need to specify values at 25C and activation energy for
31
+ #' the Arrhenius temperature response function.
32
+ #' @param alpha Quantum yield of CO2 assimilation
33
+ #' @param theta_J Curvature of the photosynthetic light response curve
34
+ #' @param gamma_star25 gamma_star at 25C in umol mol-1
35
+ #' @param Ea_gamma_star Activation energy of gamma_star in J mol-1
36
+ #' @param K_M25 Michaelis-Menten constant for rubisco at 25C
37
+ #' @param Ea_K_M Activation energy for K_M in J mol-1
38
+ #' @param g_mc25 Mesophyll conductance at 25C in mol m-2 s-1
39
+ #' @param Ea_g_mc Activation energy of g_mc in J mol-1
40
+ #' @param K_C25 Michaelis-Menten constant for rubisco carboxylation at 25C
41
+ #' @param Ea_K_C Activation energy for K_C in J mol-1
42
+ #' @param K_O25 Michaelis-Menten constant for rubisco oxygenation at 25C
43
+ #' @param Ea_K_O Activation energy for K_O in J mol-2
44
+ #' @param Oconc O2 concentration in %. Used with P to calculate
45
+ #' intracellular O2 when using K_C_K_O
46
+ #' @param gamma_star_set Value of gamma_star to use (in ppm) if
47
+ #' usegamma_star = TRUE
48
+ #' @param K_M_set Value of K_M to use if useK_M = TRUE
49
+ #' @param ... Other arguments to pass on
50
+ #'
51
+ #' @return fit_aci_response fits ACi curves using an approach similar to
52
+ #' Gu et al. 2010. Iterates all possible C_i transition points and checks for
53
+ #' inadmissible curve fits. If no curves are admissible (either due to poor data
54
+ #' or poor assumed parameters), the output will include a dataframe of NA values.
55
+ #' Default parameters are all from Bernacchi et al. 2001, 2002.
56
+ #'
57
+ #' @references
58
+ #' Bernacchi CJ, Singsaas EL, Pimentel C, Portis AR, Long SP. 2001. Improved
59
+ #' temperature response functions for models of rubisco-limited photosynthesis.
60
+ #' Plant Cell Environment 24:253-259.
61
+ #'
62
+ #' Bernacchi CJ, Portis AR, Nakano H, von Caemmerer S, Long SP. 2002. Temperature
63
+ #' response of mesophyll conductance. Implications for the determination of rubisco
64
+ #' enzyme kinetics and for limitations to photosynthesis in vivo. Plant Physiology
65
+ #' 130:1992-1998.
66
+ #'
67
+ #' Gu L, Pallardy SG, Tu K, Law BE, Wullschleger SD. 2010. Reliable estimation
68
+ #' of biochemical parameters from C3 leaf photosynthesis-intercellular carbon
69
+ #' dioxide response curves. Plant Cell Environment 33:1852-1874.
70
+ #'
71
+ #' von Caemmerer S. 2000. Biochemical models of leaf photosynthesis. CSIRO
72
+ #' Publishing, Collingwood.
73
+ #'
74
+ #' @importFrom ggplot2 element_blank
75
+ #' @importFrom ggplot2 geom_line
76
+ #' @importFrom ggplot2 ggplot
77
+ #' @importFrom ggplot2 scale_color_manual
78
+ #' @importFrom ggplot2 scale_y_continuous
79
+ #' @importFrom stats coef
80
+ #' @importFrom stats lm
81
+ #' @importFrom stats sd
82
+ #' @export
83
+ #'
84
+ #' @examples
85
+ #' \donttest{
86
+ #' # Read in your data
87
+ #' # Note that this data is coming from data supplied by the package
88
+ #' # hence the complicated argument in read.csv()
89
+ #' # This dataset is a CO2 by light response curve for a single sunflower
90
+ #' data <- read.csv(system.file("extdata", "A_Ci_Q_data_1.csv",
91
+ #' package = "photosynthesis"
92
+ #' ))
93
+ #'
94
+ #' # Define a grouping factor based on light intensity to split the ACi
95
+ #' # curves
96
+ #' data$Q_2 <- as.factor((round(data$Qin, digits = 0)))
97
+ #'
98
+ #' # Convert leaf temperature to K
99
+ #' data$T_leaf <- data$Tleaf + 273.15
100
+ #'
101
+ #' # Fit ACi curve. Note that we are subsetting the dataframe
102
+ #' # here to fit for a single value of Q_2
103
+ #' fit <- fit_aci_response(data[data$Q_2 == 1500, ],
104
+ #' varnames = list(
105
+ #' A_net = "A",
106
+ #' T_leaf = "T_leaf",
107
+ #' C_i = "Ci",
108
+ #' PPFD = "Qin"
109
+ #' )
110
+ #' )
111
+ #'
112
+ #' # View fitted parameters
113
+ #' fit[[1]]
114
+ #'
115
+ #' # View graph
116
+ #' fit[[2]]
117
+ #'
118
+ #' # View data with modelled parameters attached
119
+ #' fit[[3]]
120
+ #'
121
+ #' # Fit many curves
122
+ #' fits <- fit_many(
123
+ #' data = data,
124
+ #' varnames = list(
125
+ #' A_net = "A",
126
+ #' T_leaf = "T_leaf",
127
+ #' C_i = "Ci",
128
+ #' PPFD = "Qin"
129
+ #' ),
130
+ #' funct = fit_aci_response,
131
+ #' group = "Q_2"
132
+ #' )
133
+ #'
134
+ #' # Print the parameters
135
+ #' # First set of double parentheses selects an individual group value
136
+ #' # Second set selects an element of the sublist
137
+ #' fits[[3]][[1]]
138
+ #'
139
+ #' # Print the graph
140
+ #' fits[[3]][[2]]
141
+ #'
142
+ #' # Compile graphs into a list for plotting
143
+ #' fits_graphs <- compile_data(fits,
144
+ #' list_element = 2
145
+ #' )
146
+ #'
147
+ #' # Compile parameters into dataframe for analysis
148
+ #' fits_pars <- compile_data(fits,
149
+ #' output_type = "dataframe",
150
+ #' list_element = 1
151
+ #' )
152
+ #' }
153
+ fit_aci_response <- function(data,
154
+ varnames = list(
155
+ A_net = "A_net",
156
+ T_leaf = "T_leaf",
157
+ C_i = "C_i",
158
+ PPFD = "PPFD",
159
+ g_mc = "g_mc"
160
+ ),
161
+ P = 100,
162
+ fitTPU = TRUE,
163
+ alpha_g = 0,
164
+ R_d_meas = NULL,
165
+ useR_d = FALSE,
166
+ useg_mc = FALSE,
167
+ useg_mct = FALSE,
168
+ usegamma_star = FALSE,
169
+ useK_M = FALSE,
170
+ useK_C_K_O = FALSE,
171
+ alpha = 0.24,
172
+ theta_J = 0.85,
173
+ gamma_star25 = 42.75,
174
+ Ea_gamma_star = 37830,
175
+ K_M25 = 718.40,
176
+ Ea_K_M = 65508.28,
177
+ g_mc25 = 0.08701,
178
+ Ea_g_mc = 0,
179
+ K_C25 = NULL,
180
+ Ea_K_C = NULL,
181
+ K_O25 = NULL,
182
+ Ea_K_O = NULL,
183
+ Oconc = 21,
184
+ gamma_star_set = NULL,
185
+ K_M_set = NULL,
186
+ ...) {
187
+ # Locally bind variables - avoids notes on check package
188
+ C_i <- NULL
189
+ A_model <- NULL
190
+ A_carbox <- NULL
191
+ A_regen <- NULL
192
+ A_tpu <- NULL
193
+ A_net <- NULL
194
+ PPFD <- NULL
195
+ # Set variable names
196
+ data$C_i <- data[, varnames$C_i]
197
+ data$A_net <- data[, varnames$A_net]
198
+ data$PPFD <- data[, varnames$PPFD]
199
+ data$T_leaf <- data[, varnames$T_leaf]
200
+ outputs <- vector("list", 3)
201
+ # Order data by increasing C_i, avoids calculation issues
202
+ data <- data[order(data$C_i), ]
203
+ # Convert O2 concentration to partial pressure
204
+ O <- Oconc * P / 100
205
+ # Create grid of possible C_i transition points
206
+ ci <- data[order(data$C_i), ]$C_i
207
+ nci <- length(ci)
208
+ citransitions <- diff(ci) / 2 + ci[-nci]
209
+ # Make sure there is a minimum of 3 points for V_cmax fitting
210
+ citransitions1 <- citransitions[3:length(citransitions)]
211
+ if (!fitTPU) {
212
+ citransitions2 <- max(ci) + 1
213
+ } else {
214
+ citransitions2 <- c(max(ci) + 1, rev(citransitions1))
215
+ }
216
+ # Create combinations of ci1 and ci2 to fit
217
+ citransdf <- expand.grid(ci1 = citransitions1, ci2 = citransitions2)
218
+ citransdf <- citransdf[citransdf$ci1 <= citransdf$ci2, ]
219
+ # Mesophyll conductance calculations
220
+ if (!useg_mc) {
221
+ # Assumes g_mc is infinite
222
+ data$C <- data$C_i * P / 100
223
+ } else {
224
+ # Uses measured values of g_mc
225
+ data$g_mc <- data[, varnames$g_mc]
226
+ data$C <- (data$C_i - data$A_net / data$g_mc) * P / 100
227
+ }
228
+ if (useg_mct) {
229
+ # Calculates g_mc based on a specified temperature response
230
+ data$g_mc <- g_mc25 * t_response_arrhenius(
231
+ T_leaf = data$T_leaf,
232
+ Ea = Ea_g_mc
233
+ )
234
+ data$C <- (data$C_i - data$A_net / data$g_mc) * P / 100
235
+ }
236
+ # gamma_star settings
237
+ if (!usegamma_star) {
238
+ # Calculates gamma_star based on temperature response function
239
+ gamma_star <- gamma_star25 * t_response_arrhenius(
240
+ T_leaf = mean(data$T_leaf),
241
+ Ea = Ea_gamma_star
242
+ ) * P / 100
243
+ } else {
244
+ # Uses specified gamma_star, converts to partial pressure
245
+ gamma_star <- gamma_star_set * P / 100
246
+ }
247
+ # K_M settings
248
+ if (!useK_M) {
249
+ # Calculates K_M based on temperature response
250
+ K_M <- K_M25 * t_response_arrhenius(
251
+ T_leaf = mean(data$T_leaf),
252
+ Ea = Ea_K_M
253
+ )
254
+ } else {
255
+ # Uses specified K_M
256
+ K_M <- K_M_set
257
+ }
258
+ if (useK_C_K_O) {
259
+ # Calculates K_M based on temperature responses of K_C and K_O
260
+ K_C <- K_C25 * t_response_arrhenius(
261
+ T_leaf = mean(data$T_leaf),
262
+ Ea = Ea_K_C
263
+ )
264
+ K_O <- K_O25 * t_response_arrhenius(
265
+ T_leaf = mean(data$T_leaf),
266
+ Ea = Ea_K_O
267
+ )
268
+ K_M <- K_C * (1 + O / K_O)
269
+ }
270
+ # Generate x-variables for linearized prediction of V_cmax, J_max, V_TPU
271
+ # Note this is based on the Duursma (2015) approach eto Gu et al. 2010
272
+ data$V_cmax_pred <- (data$C - gamma_star) / (data$C + K_M)
273
+ data$J_max_pred <- (data$C - gamma_star) / (data$C + 2 * gamma_star)
274
+ data$V_TPU_part <- (data$C - gamma_star) / (data$C - (1 + 3 * alpha_g) *
275
+ gamma_star)
276
+ # Create dataframe for all possible curve fits
277
+ poss_fits <- data.frame(matrix(0,
278
+ nrow = nrow(citransdf),
279
+ ncol = 16
280
+ ))
281
+ # Add column names
282
+ colnames(poss_fits) <- c(
283
+ "Num", "V_cmax", "V_cmax_se", "J_max",
284
+ "J", "J_se", "V_TPU", "V_TPU_se", "R_d", "R_d_se",
285
+ "cost", "citransition1", "citransition2",
286
+ "V_cmax_pts", "J_max_pts", "V_TPU_pts"
287
+ )
288
+ # Fit all possible citransition combinations
289
+ for (i in seq_len(nrow(citransdf))) {
290
+ # Locally bind variables
291
+ cost <- NULL
292
+ V_cmax_fit <- NULL
293
+ J_max_fit <- NULL
294
+ V_TPU <- NULL
295
+ datc <- NULL
296
+ datj <- NULL
297
+ datp <- NULL
298
+ datcomp <- NULL
299
+ # CO2-limited points
300
+ datc <- data[data$C_i < citransdf$ci1[i], ]
301
+ # RuBP regeneration-limited points
302
+ datj <- data[data$C_i > citransdf$ci1[i] &
303
+ data$C_i < citransdf$ci2[i], ]
304
+ # V_TPU-limited points
305
+ datp <- data[data$C_i > citransdf$ci2[i], ]
306
+ # Fits V_cmax
307
+ if (!useR_d) {
308
+ # Fit R_d and V_cmax
309
+ fitc <- lm(A_net ~ V_cmax_pred, data = datc)
310
+ R_d_fit <- coef(fitc)[[1]]
311
+ R_d_se <- summary(fitc)$coefficients[1, 2]
312
+ V_cmax_fit <- coef(fitc)[[2]]
313
+ V_cmax_se <- summary(fitc)$coefficients[2, 2]
314
+ datc$A_gross <- datc$A_net - R_d_fit
315
+ } else {
316
+ # Use R_d and fit V_cmax
317
+ R_d_fit <- -R_d_meas
318
+ datc$A_gross <- datc$A_net - R_d_fit
319
+ fitc <- lm(A_gross ~ V_cmax_pred - 1, data = datc)
320
+ V_cmax_fit <- coef(fitc)[[1]]
321
+ V_cmax_se <- summary(fitc)$coefficients[, 2]
322
+ }
323
+ # Fit J and J_max
324
+ if (nrow(datj) > 0) {
325
+ datj$A_gross <- datj$A_net - R_d_fit
326
+ if (nrow(datj) == 1) {
327
+ # Calculates J_max based on one point
328
+ J_fit <- 4 * datj$A_gross / datj$J_max_pred
329
+ J_se <- NA
330
+ J_max_fit <- suppressWarnings(calculate_jmax(mean(data$PPFD),
331
+ alpha,
332
+ J = J_fit, theta_J
333
+ ))
334
+ } else {
335
+ # Calculates J_max based on a linear regression fit
336
+ fitj <- lm(A_gross ~ J_max_pred - 1, data = datj)
337
+ J_fit <- 4 * coef(fitj)[[1]]
338
+ J_se <- summary(fitj)$coefficients[2]
339
+ J_max_fit <- suppressWarnings(calculate_jmax(mean(data$PPFD),
340
+ alpha,
341
+ J = J_fit, theta_J
342
+ ))
343
+ }
344
+ } else {
345
+ # Assign J_max a value of 10 ^ 6 if there's no RuBP limitation
346
+ J_max_fit <- 10^6
347
+ J_max_SS <- 0
348
+ J_se <- NA
349
+ }
350
+ # Calculating V_TPU limitations
351
+ if (nrow(datp) == 1 && nrow(datj) == 0) {
352
+ # Assign V_TPU a value of 1000 if there is only 1 assigned
353
+ # point and no RuBP-limited points
354
+ datp$A_gross <- datp$A_net - R_d_fit
355
+ V_TPU <- 1000
356
+ V_TPU_SS <- 0
357
+ V_TPU_se <- NA
358
+ } else {
359
+ # This section covers if there are no V_TPU-limited points
360
+ datp$A_gross <- datp$A_net - R_d_fit
361
+ V_TPU <- 1000 # same as default in Photosyn
362
+ V_TPU_SS <- 0
363
+ V_TPU_se <- NA
364
+ }
365
+ # Calculates V_TPU limitations if there are at least 3 points
366
+ # to ensure more reliable fit
367
+ if (nrow(datp) > 2) {
368
+ datp$A_gross <- datp$A_net - R_d_fit
369
+ V_TPU_vals <- (1 / 3) * datp$A_gross / datp$V_TPU_part
370
+ V_TPU <- mean(V_TPU_vals)
371
+ V_TPU_se <- sd(V_TPU_vals) / sqrt(length(V_TPU_vals))
372
+ }
373
+ # If V_TPU is fit to be < 0, assign value of 1000. Avoids
374
+ # strange issues.
375
+ if (V_TPU < 0) {
376
+ V_TPU <- 1000
377
+ V_TPU_SS <- 0
378
+ V_TPU_se <- NA
379
+ }
380
+ # Calculate rates of photosynthesis for each limitation state and sums of
381
+ # squares for model-wise cost function
382
+ # CO2 limitations
383
+ datc$A <- V_cmax_fit * (datc$C - gamma_star) / (datc$C + K_M) + R_d_fit
384
+ datc$SS <- (datc$A - datc$A_net)^2
385
+ V_cmax_SS <- sum(datc$SS)
386
+ # RuBP limitations
387
+ datj$A <- J_fit * (datj$C - gamma_star) /
388
+ (4 * datj$C + 8 * gamma_star) + R_d_fit
389
+ datj$SS <- (datj$A - datj$A_net)^2
390
+ J_max_SS <- sum(datj$SS)
391
+ # V_TPU limitations
392
+ datp$A <- 3 * V_TPU * (datp$C - gamma_star) /
393
+ (datp$C - (1 + 3 * alpha_g) * gamma_star / datp$C) + R_d_fit
394
+ datp$SS <- (datp$A - datp$A_net)^2
395
+ V_TPU_SS <- sum(datp$SS)
396
+ # Calculate cost functions
397
+ cost <- 1 / 2 * (V_cmax_SS + J_max_SS + V_TPU_SS)
398
+ # Bind calculated data
399
+ datcomp <- rbind(datc, datj, datp)
400
+ # Add outputs to possible fits
401
+ poss_fits$V_cmax[i] <- V_cmax_fit
402
+ poss_fits$V_cmax_se[i] <- V_cmax_se
403
+ poss_fits$J_max[i] <- J_max_fit
404
+ poss_fits$J[i] <- J_fit
405
+ poss_fits$J_se[i] <- J_se
406
+ poss_fits$V_TPU[i] <- V_TPU
407
+ poss_fits$V_TPU_se[i] <- V_TPU_se
408
+ poss_fits$R_d[i] <- R_d_fit
409
+ poss_fits$R_d_se[i] <- R_d_se
410
+ poss_fits$V_cmax_pts[i] <- nrow(datc)
411
+ poss_fits$J_max_pts[i] <- nrow(datj)
412
+ poss_fits$V_TPU_pts[i] <- nrow(datp)
413
+ poss_fits$cost[i] <- cost
414
+ poss_fits$citransition1[i] <- citransdf$ci1[i]
415
+ poss_fits$citransition2[i] <- citransdf$ci2[i]
416
+ } # End curve fitting of all possible C_i transitions
417
+ # Select fit with minimized cost function
418
+ best_fits <- poss_fits[poss_fits$cost == min(poss_fits$cost), ]
419
+ # New segment for sensitivity analysis
420
+ # Adds values for assumed constants to the output dataframe
421
+ best_fits$alpha <- alpha
422
+ best_fits$alpha_g <- alpha_g
423
+ best_fits$gamma_star25 <- gamma_star25
424
+ best_fits$Ea_gamma_star <- Ea_gamma_star
425
+ best_fits$K_M25 <- K_M25
426
+ best_fits$Ea_K_M <- Ea_K_M
427
+ best_fits$g_mc25 <- g_mc25
428
+ best_fits$Ea_g_mc <- Ea_g_mc
429
+ best_fits$K_C25 <- K_C25
430
+ best_fits$Ea_K_C <- Ea_K_C
431
+ best_fits$K_O25 <- K_O25
432
+ best_fits$Ea_K_O <- Ea_K_O
433
+ best_fits$Oconc <- Oconc
434
+ best_fits$theta_J <- theta_J
435
+ # Calculate net photosynthetic rates
436
+ data$A_carbox <- best_fits$V_cmax * data$C /
437
+ (data$C + K_M) * (1 - gamma_star / data$C) + best_fits$R_d
438
+ data$A_regen <- calculate_j(
439
+ PPFD = mean(data$PPFD), alpha = alpha,
440
+ J_max = best_fits$J_max, theta_J = theta_J
441
+ ) *
442
+ (data$C - gamma_star) / (4 * data$C + 8 * gamma_star) + best_fits$R_d
443
+ data$A_tpu <- 3 * best_fits$V_TPU /
444
+ (1 - 0.5 * (1 + 3 * alpha_g) * (2 * gamma_star / data$C)) *
445
+ (1 - gamma_star / data$C) + best_fits$R_d
446
+ # Calculate gross photosynthetic rates
447
+ data$W_carbox <- data$A_carbox - best_fits$R_d
448
+ data$W_regen <- data$A_regen - best_fits$R_d
449
+ data$W_tpu <- data$A_tpu - best_fits$R_d
450
+ # Create empty variable for modelled CO2 assimilation
451
+ data$A_model <- rep(NA, nrow(data))
452
+ # To avoid issues with graphing and cases where W_j drops below W_c
453
+ # at very low CO2, for the first few points, A_model is calculated
454
+ # with W_c only - plantecophys took an approach where Aj was fixed
455
+ # on the graph until a certain C_i to avoid this same issue.
456
+ for (i in 1:(best_fits$V_cmax_pts - 2)) {
457
+ data$A_model[i] <- data$W_carbox[i] + best_fits$R_d
458
+ }
459
+ if (best_fits$V_TPU == 1000) {
460
+ for (i in (best_fits$V_cmax_pts - 1):nrow(data)) {
461
+ data$A_model[i] <- min(data$W_carbox[i], data$W_regen[i]) + best_fits$R_d
462
+ }
463
+ } else {
464
+ for (i in (best_fits$V_cmax_pts - 1):nrow(data)) {
465
+ data$A_model[i] <- min(
466
+ data$W_carbox[i], data$W_regen[i],
467
+ data$W_tpu[i]
468
+ ) + best_fits$R_d
469
+ }
470
+ }
471
+ # Assign best fit to output element 1
472
+ outputs[[1]] <- best_fits
473
+ # Assign graph to output element 2
474
+ outputs[[2]] <- ggplot(data, aes(x = C_i, y = A_model)) +
475
+ scale_y_continuous(limits = c(
476
+ min(c(data$A_model, data$A_net)) - 3,
477
+ max(c(data$A_model, data$A_net)) + 3
478
+ )) +
479
+ geom_line(aes(color = "black"), linewidth = 4) +
480
+ geom_line(aes(y = A_carbox, color = "blue"), linewidth = 2) +
481
+ geom_line(aes(y = A_regen, color = "orange"), linewidth = 2) +
482
+ geom_line(aes(y = A_tpu, color = "red"), linewidth = 2) +
483
+ geom_point(aes(y = A_net),
484
+ color = "black", fill = "white",
485
+ size = 2, shape = 21
486
+ ) +
487
+ scale_color_manual(
488
+ labels = c("Amod", "Ac", "Aj", "Ap", "Anet"),
489
+ values = c(
490
+ "black", "blue", "orange",
491
+ "red", "white"
492
+ )
493
+ ) +
494
+ theme_bw() +
495
+ theme(legend.title = element_blank())
496
+ # Assign dataframe to output element 3
497
+ outputs[[3]] <- data
498
+ # Add names to list output
499
+ names(outputs) <- c("Fitted Parameters", "Plot", "Data")
500
+ # Return output list
501
+ return(outputs)
502
+ } # End function
data/R/fit_aq_response.R ADDED
@@ -0,0 +1,489 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #' Fit photosynthetic light-response curves
2
+ #'
3
+ #' @description We recommend using [fit_photosynthesis()] with argument `.photo_fun = "aq_response"` rather than calling this function directly.
4
+ #'
5
+ #' @inheritParams fit_photosynthesis
6
+ #' @param usealpha_Q Flag. Should light intensity be multiplied by `alpha_Q` before fitting? Default is FALSE (i.e. assume that '.Q' is absorbed light).
7
+ #' @param alpha_Q Number. Absorbance of incident light. Default value is 0.84. Ignored if `usealpha_Q = FALSE`.
8
+ #'
9
+ #' @return
10
+ #'
11
+ #' * If `.method = 'ls'`: an [stats::nls()] object.
12
+ #' * If `.method = 'brms'`: a [brms::brmsfit()] object.
13
+ #'
14
+ #' @note Rd fitted in this way is essentially the same as the Kok (1956) method, and
15
+ #' represents a respiration value in the light that may not be accurate.
16
+ #' Rd output should thus be interpreted more as a residual parameter to ensure
17
+ #' an accurate fit of the light response parameters. Model originally from
18
+ #' Marshall & Biscoe (1980).
19
+ #'
20
+ #' @references
21
+ #' Marshall B, Biscoe P. 1980. A model for C3 leaves describing the
22
+ #' dependence of net photosynthesis on irradiance. J Ex Bot 31:29-39
23
+ #'
24
+ #' @export
25
+ #'
26
+ #' @examples
27
+ #' \donttest{
28
+ #'
29
+ #' library(broom)
30
+ #' library(dplyr)
31
+ #' library(photosynthesis)
32
+ #'
33
+ #' # Read in your data
34
+ #' dat = system.file("extdata", "A_Ci_Q_data_1.csv", package = "photosynthesis") |>
35
+ #' read.csv() |>
36
+ #' # Set grouping variable
37
+ #' mutate(group = round(CO2_s, digits = 0)) |>
38
+ #' # For this example, round sequentially due to CO2_s set points
39
+ #' mutate(group = as.factor(round(group, digits = -1)))
40
+ #'
41
+ #' # Fit one light-response curve
42
+ #' fit = fit_photosynthesis(
43
+ #' .data = filter(dat, group == 600),
44
+ #' .photo_fun = "aq_response",
45
+ #' .vars = list(.A = A, .Q = Qabs),
46
+ #' )
47
+ #'
48
+ #' # The 'fit' object inherits class 'nls' and many methods can be used
49
+ #'
50
+ #' ## Model summary:
51
+ #' summary(fit)
52
+ #'
53
+ #' ## Estimated parameters:
54
+ #' coef(fit)
55
+ #'
56
+ #' ## 95% confidence intervals:
57
+ #' confint(fit)
58
+ #'
59
+ #' ## Tidy summary table using 'broom::tidy()'
60
+ #' tidy(fit, conf.int = TRUE, conf.level = 0.95)
61
+ #'
62
+ #' # Fit multiple curves with **photosynthesis** and **purrr**
63
+ #'
64
+ #' library(purrr)
65
+ #'
66
+ #' fits = dat |>
67
+ #' split(~ group) |>
68
+ #' map(fit_photosynthesis, .photo_fun = "aq_response", .vars = list(.A = A, .Q = Qabs))
69
+ #'
70
+ #' }
71
+ #'
72
+ #' @md
73
+ fit_aq_response2 = function(
74
+ .data,
75
+ .model = "default",
76
+ .method = "ls",
77
+ usealpha_Q = FALSE,
78
+ alpha_Q = 0.84,
79
+ quiet = FALSE,
80
+ brm_options = NULL
81
+ ) {
82
+
83
+ # Checks
84
+ checkmate::assert_flag(usealpha_Q)
85
+ checkmate::assert_number(alpha_Q, na.ok = !usealpha_Q)
86
+
87
+ # Set light intensity dependent on whether it is incident or
88
+ # absorbed that you want the variables on
89
+ .data = dplyr::mutate(.data, .Qabs = .Q * ifelse(usealpha_Q, alpha_Q, 1)) |>
90
+ dplyr::select(.A, .Q, .Qabs)
91
+
92
+ # Fit AQ response model
93
+ fit = switch(
94
+ .method,
95
+ ls = fit_aq_response2_ls(.data, .model),
96
+ brms = fit_aq_response2_brms(.data, .model, brm_options)
97
+ )
98
+
99
+ fit
100
+
101
+ }
102
+
103
+ #' Fit light response using [minpack.lm::nlsLM()]
104
+ #' @inheritParams fit_aq_response2
105
+ #' @noRd
106
+ fit_aq_response2_ls = function(.data, .model, ...) {
107
+
108
+ requireNamespace("minpack.lm") || stop("Package not loaded: minpack.lm")
109
+
110
+ do.call(
111
+ glue::glue("fit_aq_response2_{.model}_ls"),
112
+ args = list(.data = .data, ...)
113
+ )
114
+
115
+ }
116
+
117
+ #' Fit light response using [brms::brm()]
118
+ #' @noRd
119
+ fit_aq_response2_brms = function(.data, .model, brm_options, ...) {
120
+
121
+ requireNamespace("brms") || stop("Package not loaded: brms")
122
+
123
+ lifecycle::signal_stage("experimental", what = "fit_aq_response2(.method = 'brms')")
124
+
125
+ do.call(
126
+ glue::glue("fit_aq_response2_{.model}_brms"),
127
+ args = list(.data = .data, brm_options = brm_options, ...)
128
+ )
129
+
130
+ }
131
+
132
+ #' Fit photosynthetic nonrectangular hyperbola light-response curves (Marshall & Biscore 1980) using least-squares methods
133
+ #' @inheritParams fit_aq_response2
134
+ #' @noRd
135
+
136
+ fit_aq_response2_marshall_biscoe_1980_ls = function(.data, ...) {
137
+
138
+ minpack.lm::nlsLM(
139
+ data = .data,
140
+ .A ~ marshall_biscoe_1980(Q_abs = .data[[".Qabs"]], k_sat, phi_J, theta_J) - Rd,
141
+ # Attempt to estimate starting parameters
142
+ start = get_init_aq_response(.data),
143
+ # Set lower limits
144
+ lower = c(min(.data[[".A"]]), rep(0, 3)),
145
+ # set upper limits
146
+ upper = c(10 * max(abs(.data[[".A"]])), 0.5, 1, max(.data[[".A"]])),
147
+ # set max iterations for curve fitting
148
+ control = nls.lm.control(maxiter = 100)
149
+ )
150
+
151
+ }
152
+
153
+ #' Fit photosynthetic nonrectangular hyperbola light-response curves (Marshall & Biscore 1980) using Bayesian methods
154
+ #' @inheritParams fit_aq_response2
155
+ #' @noRd
156
+ fit_aq_response2_marshall_biscoe_1980_brms = function(.data, brm_options, ...) {
157
+
158
+ do.call(
159
+ brms::brm,
160
+ args = c(
161
+ brm_options,
162
+ list(
163
+ formula = brms::bf(
164
+ .A ~ ((Asat + inv_logit(logitPhiJ) * .Qabs) -
165
+ sqrt((Asat + inv_logit(logitPhiJ) * .Qabs) ^ 2 -
166
+ 4 * Asat * inv_logit(logitPhiJ) * .Qabs * inv_logit(logitThetaJ))) /
167
+ (2 * inv_logit(logitThetaJ)) - Rd,
168
+ Asat ~ 1,
169
+ logitPhiJ ~ 1,
170
+ logitThetaJ ~ 1,
171
+ Rd ~ 1,
172
+ nl = TRUE
173
+ ),
174
+ data = .data,
175
+ prior = c(
176
+ brms::prior(normal(20, 10), nlpar = "Asat", lb = 0),
177
+ brms::prior(normal(-2.5, 0.5), nlpar = "logitPhiJ"),
178
+ brms::prior(normal(2.5, 0.5), nlpar = "logitThetaJ"),
179
+ brms::prior(normal(2, 1), nlpar = "Rd", lb = 0)
180
+ )
181
+ )
182
+ )
183
+ )
184
+
185
+ }
186
+
187
+ #' Fit photosynthetic nonrectangular hyperbola light-response curves (Marshall & Biscore 1980) and photoinhibition using least-squares methods
188
+ #' @inheritParams fit_aq_response2
189
+ #' @noRd
190
+
191
+ fit_aq_response2_photoinhibition_ls = function(.data, ...) {
192
+
193
+ minpack.lm::nlsLM(
194
+ data = .data,
195
+ .A ~ photoinhibition(Q_abs = .data[[".Qabs"]], k_sat, phi_J, theta_J, b_inh) - Rd,
196
+ # Attempt to estimate starting parameters
197
+ start = c(get_init_aq_response(.data), b_inh = 0),
198
+ # Set lower limits
199
+ lower = c(min(.data[[".A"]]), rep(0, 3), -0.1),
200
+ # set upper limits
201
+ upper = c(10 * max(abs(.data[[".A"]])), 0.5, 1, max(.data[[".A"]]), 0.1),
202
+ # set max iterations for curve fitting
203
+ control = nls.lm.control(maxiter = 100)
204
+ )
205
+
206
+ }
207
+
208
+ #' Fit photosynthetic nonrectangular hyperbola light-response curves (Marshall & Biscore 1980) and photoinhibition using Bayesian methods
209
+ #' @inheritParams fit_aq_response2
210
+ #' @noRd
211
+ fit_aq_response2_photoinhibition_brms = function(.data, brm_options, ...) {
212
+
213
+ do.call(
214
+ brms::brm,
215
+ args = c(
216
+ brm_options,
217
+ list(
218
+ formula = brms::bf(
219
+ .A ~ ((Asat - bInh * .Qabs + inv_logit(logitPhiJ) * .Qabs) -
220
+ sqrt((Asat + inv_logit(logitPhiJ) * .Qabs) ^ 2 -
221
+ 4 * Asat * inv_logit(logitPhiJ) * .Qabs * inv_logit(logitThetaJ))) /
222
+ (2 * inv_logit(logitThetaJ)) - Rd,
223
+ Asat ~ 1,
224
+ bInh ~ 1,
225
+ logitPhiJ ~ 1,
226
+ logitThetaJ ~ 1,
227
+ Rd ~ 1,
228
+ nl = TRUE
229
+ ),
230
+ data = .data,
231
+ prior = c(
232
+ brms::prior(normal(20, 10), nlpar = "Asat", lb = 0),
233
+ brms::prior(normal(0, 0.1), nlpar = "bInh"),
234
+ brms::prior(normal(-2.5, 0.5), nlpar = "logitPhiJ"),
235
+ brms::prior(normal(2.5, 0.5), nlpar = "logitThetaJ"),
236
+ brms::prior(normal(2, 1), nlpar = "Rd", lb = 0)
237
+ )
238
+ )
239
+ )
240
+ )
241
+
242
+ }
243
+
244
+ #' Get list of starting values for `fit_aq_response()`
245
+ #' @noRd
246
+ # Get initial values
247
+ get_init_aq_response = function(.data) {
248
+
249
+ x1 = try({unname(coef(lm(.A ~ .Qabs, dplyr::filter(.data, .Qabs < 300))))}, silent = TRUE)
250
+ if (inherits(x1, "try-error")) x1 = c(0.06, 1)
251
+
252
+ list(
253
+ k_sat = max(.data[[".A"]]),
254
+ phi_J = x1[2],
255
+ theta_J = 0.85,
256
+ Rd = -x1[1]
257
+ )
258
+
259
+ }
260
+
261
+ #' Fitting light responses of net CO2 assimilation
262
+ #'
263
+ #' @description
264
+ #' `r lifecycle::badge("deprecated")`
265
+ #'
266
+ #' Please use `fit_aq_response2()`.
267
+ #'
268
+ #' @param data Dataframe containing CO2 assimilation light response
269
+ #' @param varnames Variable names where varnames = list(A_net = "A_net",
270
+ #' PPFD = "PPFD"). A_net is net CO2 assimilation in umol m-2 s-1, PPFD is
271
+ #' incident irradiance. PPFD can be corrected for light absorbance by using
272
+ #' useapha_Q and setting alpha_Q.
273
+ #' @param usealpha_Q Correct light intensity for absorbance? Default is FALSE.
274
+ #' @param alpha_Q Absorbance of incident light. Default value is 0.84.
275
+ #' @param title Title for graph
276
+ #'
277
+ #' @return fit_aq_response fits the light response of net CO2 assimilation.
278
+ #' Output is a dataframe containing light saturated net CO2 assimilation,
279
+ #' quantum yield of CO2 assimilation (phi_J), curvature of the light response
280
+ #' (theta_J), respiration (Rd), light compensation point (LCP), and residual
281
+ #' sum of squares (resid_SS). Note that Rd fitted in this way is essentially
282
+ #' the same as the Kok method, and represents a respiration value in the
283
+ #' light that may not be accurate. Rd output should thus be interpreted more
284
+ #' as a residual parameter to ensure an accurate fit of the light response
285
+ #' parameters. Model originally from Marshall & Biscoe 1980.
286
+ #'
287
+ #' @references
288
+ #' Marshall B, Biscoe P. 1980. A model for C3 leaves describing the
289
+ #' dependence of net photosynthesis on irradiance. J Ex Bot 31:29-39
290
+ #'
291
+ #' @export
292
+ #'
293
+ #' @examples
294
+ #' \donttest{
295
+ #' # Read in your data
296
+ #' # Note that this data is coming from data supplied by the package
297
+ #' # hence the complicated argument in read.csv()
298
+ #' # This dataset is a CO2 by light response curve for a single sunflower
299
+ #' data = read.csv(system.file("extdata", "A_Ci_Q_data_1.csv",
300
+ #' package = "photosynthesis"
301
+ #' ))
302
+ #'
303
+ #' # Fit many AQ curves
304
+ #' # Set your grouping variable
305
+ #' # Here we are grouping by CO2_s and individual
306
+ #' data$C_s = (round(data$CO2_s, digits = 0))
307
+ #'
308
+ #' # For this example we need to round sequentially due to CO2_s setpoints
309
+ #' data$C_s = as.factor(round(data$C_s, digits = -1))
310
+ #'
311
+ #' # To fit one AQ curve
312
+ #' fit = fit_aq_response(data[data$C_s == 600, ],
313
+ #' varnames = list(
314
+ #' A_net = "A",
315
+ #' PPFD = "Qin"
316
+ #' )
317
+ #' )
318
+ #'
319
+ #' # Print model summary
320
+ #' summary(fit[[1]])
321
+ #'
322
+ #' # Print fitted parameters
323
+ #' fit[[2]]
324
+ #'
325
+ #' # Print graph
326
+ #' fit[[3]]
327
+ #'
328
+ #' # Fit many curves
329
+ #' fits = fit_many(
330
+ #' data = data,
331
+ #' varnames = list(
332
+ #' A_net = "A",
333
+ #' PPFD = "Qin",
334
+ #' group = "C_s"
335
+ #' ),
336
+ #' funct = fit_aq_response,
337
+ #' group = "C_s"
338
+ #' )
339
+ #'
340
+ #' # Look at model summary for a given fit
341
+ #' # First set of double parentheses selects an individual group value
342
+ #' # Second set selects an element of the sublist
343
+ #' summary(fits[[3]][[1]])
344
+ #'
345
+ #' # Print the parameters
346
+ #' fits[[3]][[2]]
347
+ #'
348
+ #' # Print the graph
349
+ #' fits[[3]][[3]]
350
+ #'
351
+ #' # Compile graphs into a list for plotting
352
+ #' fits_graphs = compile_data(fits,
353
+ #' list_element = 3
354
+ #' )
355
+ #'
356
+ #' # Compile parameters into dataframe for analysis
357
+ #' fits_pars = compile_data(fits,
358
+ #' output_type = "dataframe",
359
+ #' list_element = 2
360
+ #' )
361
+ #' }
362
+ #'
363
+ #' @md
364
+ fit_aq_response = function(
365
+ data,
366
+ varnames = list(
367
+ A_net = "A_net",
368
+ PPFD = "PPFD"
369
+ ),
370
+ usealpha_Q = FALSE,
371
+ alpha_Q = 0.84,
372
+ title = NULL
373
+ ) {
374
+
375
+ lifecycle::deprecate_warn(
376
+ "2.1.1", "fit_aq_response()",
377
+ "fit_photosynthesis(.photo_fun = 'aq_response')",
378
+ always = FALSE
379
+ )
380
+
381
+ # Locally bind variables - avoids notes on check package
382
+ A_net = NULL
383
+ Q_abs = NULL
384
+ # Set variable names
385
+ data$A_net = data[, varnames$A_net]
386
+ # Set light intensity dependent on whether it is incident or
387
+ # absorbed that you want the variables on
388
+ if (usealpha_Q) {
389
+ data$Q_abs = data[, varnames$PPFD] * alpha_Q
390
+ } else {
391
+ data$Q_abs = data[, varnames$PPFD]
392
+ }
393
+ # Create empty list for outputs
394
+ output = list(NULL)
395
+ # Fit AQ response model using nlsLM - this function is more
396
+ # robust (i.e. successful) than regular nls
397
+ output[[1]] = nlsLM(
398
+ data = data, A_net ~ aq_response(k_sat,
399
+ phi_J,
400
+ Q_abs = data$Q_abs,
401
+ theta_J
402
+ ) - Rd,
403
+ # Attempt to estimate starting parameters
404
+ start = list(
405
+ k_sat = max(data$A_net),
406
+ phi_J = coef(lm(
407
+ A_net ~ Q_abs,
408
+ data[data$Q_abs <
409
+ 300, ]
410
+ ))[2],
411
+ theta_J = 0.85,
412
+ Rd = -coef(lm(
413
+ A_net ~ Q_abs,
414
+ data[data$Q_abs <
415
+ 300, ]
416
+ ))[1]
417
+ ),
418
+ # Set lower limits
419
+ lower = c(
420
+ min(data$A_net),
421
+ 0,
422
+ 0,
423
+ 0
424
+ ),
425
+ # set upper limits
426
+ upper = c(
427
+ 10 * max(abs(data$A_net)),
428
+ 0.5,
429
+ 1,
430
+ max(abs(data$A_net))
431
+ ),
432
+ # set max iterations for curve fitting
433
+ control = nls.lm.control(maxiter = 100)
434
+ )
435
+ # Prepare output dataframe and extract coefficients
436
+ fitted_pars = NULL
437
+ fitted_pars$A_sat = coef(output[[1]])[1]
438
+ fitted_pars$phi_J = coef(output[[1]])[2]
439
+ fitted_pars$theta_J = coef(output[[1]])[3]
440
+ fitted_pars$Rd = coef(output[[1]])[4]
441
+ fitted_pars$LCP = ((coef(output[[1]])[4]) *
442
+ (coef(output[[1]])[4] * coef(output[[1]])[3] -
443
+ coef(output[[1]])[1]) /
444
+ (coef(output[[1]])[2] * (coef(output[[1]])[4] -
445
+ coef(output[[1]])[1])))
446
+ fitted_pars$resid_SSs = sum(resid(output[[1]])^2)
447
+ # Add fitted parameters to output
448
+ output[[2]] = as.data.frame(do.call("cbind", fitted_pars))
449
+ # Create graph
450
+ output[[3]] = ggplot(data, aes(x = Q_abs, y = A_net)) +
451
+ # Add axis labels
452
+ labs(
453
+ x = expression("Irradiance (" * mu * mol ~ m^{
454
+ -2
455
+ } ~ s^
456
+ {
457
+ -1
458
+ } * ")"),
459
+ y = expression(A[net] ~ "(" * mu * mol ~ m^{
460
+ -2
461
+ } ~ s^
462
+ {
463
+ -1
464
+ } * ")")
465
+ ) +
466
+ # Add title
467
+ ggtitle(label = title) +
468
+ # Add fitted smoothing function
469
+ geom_smooth(
470
+ method = "lm", aes(x = Q_abs, y = A_net),
471
+ show.legend = TRUE,
472
+ formula = y ~ I(aq_response(
473
+ k_sat = output[[2]]$A_sat[1],
474
+ phi_J = output[[2]]$phi_J[1],
475
+ Q_abs = x,
476
+ theta_J = output[[2]]$theta_J[1]
477
+ ) -
478
+ output[[2]]$Rd[1]),
479
+ linewidth = 2
480
+ ) +
481
+ # Add points
482
+ geom_point(size = 2) +
483
+ # Use clean theme
484
+ theme_bw()
485
+ # Name outputs
486
+ names(output) = c("Model", "Parameters", "Graph")
487
+ # Return list of outputs
488
+ return(output)
489
+ }
data/R/fit_g_mc_variableJ.R ADDED
@@ -0,0 +1,151 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #' Fitting mesophyll conductance with the variable J method
2
+ #'
3
+ #' @param data Dataframe
4
+ #' @param varnames Variable names to fit g_mc. varnames = list(A_net = "A_net",
5
+ #' J_etr = "J_etr", C_i = "C_i", PPFD = "PPFD", phi_PSII = "phi_PSII"), where
6
+ #' A_net is net CO2 assimilation in umol m-2 s-1, J_etr is linear electron
7
+ #' transport flux in umol m-2 s-1, C_i is intercellular CO2 concentration in
8
+ #' umol mol-1, PPFD is incident irradiance in umol m-2 s-1, phi_PSII is
9
+ #' the operating efficiency of photosystem II.
10
+ #' @param usealpha_Q Recalculate electron transport with new absorbance value?
11
+ #' @param alpha_Q Absorbance of photosynthetically active radiation
12
+ #' @param beta_Q Partitioning of absorbed light energy between PSI and PSII
13
+ #' @param gamma_star Photorespiratory CO2 compensation point in umol mol-1
14
+ #' @param R_d Respiration rate in umol m-2 s-1
15
+ #' @param P Atmospheric pressure in kPa
16
+ #'
17
+ #' @return fit_g_mc_variableJ fits mesophyll conductance according
18
+ #' to Harley et al. 1992. It also tests the reliability of the
19
+ #' calculation and calculates a mean with only reliable values.
20
+ #' Note that the output is in units of umol m-2 s-1 Pa-1.
21
+ #'
22
+ #' @references
23
+ #' Harley PC, Loreto F, Di Marco G, Sharkey TD. 1992. Theoretical
24
+ #' considerations when estimating mesophyll conductance to CO2 flux
25
+ #' by analysis of the response of photosynthesis to CO2. Plant Physiol
26
+ #' 98:1429 - 1436.
27
+ #' @export
28
+ #'
29
+ #' @examples
30
+ #' \donttest{
31
+ #' # Read in your data
32
+ #' # Note that this data is coming from data supplied by the package
33
+ #' # hence the complicated argument in read.csv()
34
+ #' # This dataset is a CO2 by light response curve for a single sunflower
35
+ #' data <- read.csv(system.file("extdata", "A_Ci_Q_data_1.csv",
36
+ #' package = "photosynthesis"
37
+ #' ))
38
+ #'
39
+ #' # Note: there will be issues here if the alpha value used
40
+ #' # for calculating ETR is off, if gamma_star is incorrect,
41
+ #' # if R_d is incorrect.
42
+ #' data <- fit_g_mc_variableJ(data,
43
+ #' varnames = list(
44
+ #' A_net = "A",
45
+ #' J_etr = "ETR",
46
+ #' C_i = "Ci",
47
+ #' PPFD = "Qin",
48
+ #' phi_PSII = "PhiPS2"
49
+ #' ),
50
+ #' gamma_star = 46,
51
+ #' R_d = 0.153,
52
+ #' usealpha_Q = TRUE,
53
+ #' alpha_Q = 0.84,
54
+ #' beta_Q = 0.5,
55
+ #' P = 84
56
+ #' )
57
+ #'
58
+ #' # Note that many g_mc values from this method can be unreliable
59
+ #' ggplot(data, aes(x = CO2_s, y = g_mc, colour = reliable)) +
60
+ #' labs(
61
+ #' x = expression(CO[2] ~ "(" * mu * mol ~ mol^
62
+ #' {
63
+ #' -1
64
+ #' } * ")"),
65
+ #' y = expression(g[m] ~ "(mol" ~ m^{
66
+ #' -2
67
+ #' } ~ s^{
68
+ #' -1
69
+ #' } ~ Pa^
70
+ #' {
71
+ #' -1
72
+ #' } * ")")
73
+ #' ) +
74
+ #' geom_point(size = 2) +
75
+ #' theme_bw() +
76
+ #' theme(legend.position = "bottom")
77
+ #'
78
+ #' # Plot QAQC graph according to Harley et al. 1992
79
+ #' ggplot(data, aes(x = CO2_s, y = dCcdA, colour = reliable)) +
80
+ #' labs(
81
+ #' x = expression(CO[2] ~ "(" * mu * mol ~ mol^
82
+ #' {
83
+ #' -1
84
+ #' } * ")"),
85
+ #' y = expression(delta * C[chl] * "/" * delta * A)
86
+ #' ) +
87
+ #' geom_hline(yintercept = 10) +
88
+ #' geom_point(size = 2) +
89
+ #' theme_bw() +
90
+ #' theme(legend.position = "bottom")
91
+ #' }
92
+ fit_g_mc_variableJ <- function(data,
93
+ varnames = list(
94
+ A_net = "A_net",
95
+ J_etr = "J_etr",
96
+ C_i = "C_i",
97
+ PPFD = "PPFD",
98
+ phi_PSII = "phi_PSII"
99
+ ),
100
+ usealpha_Q = FALSE,
101
+ alpha_Q = 0.84,
102
+ beta_Q = 0.5,
103
+ gamma_star,
104
+ R_d,
105
+ P = 100) {
106
+ # Set variable names in data if different from defaults
107
+ data$A_net <- data[, varnames$A_net]
108
+ data$J_etr <- data[, varnames$J_etr]
109
+ data$C_i <- data[, varnames$C_i] # In umol / mol
110
+ # If assigning alpha_Q, re-calculate J_etr, otherwise use J_etr
111
+ if (usealpha_Q) {
112
+ data$PPFD <- data[, varnames$PPFD]
113
+ data$phi_PSII <- data[, varnames$phi_PSII]
114
+ data$J_etr <- data$PPFD * alpha_Q * beta_Q * data$phi_PSII
115
+ } else {
116
+ data$J_etr <- data[, varnames$J_etr]
117
+ }
118
+ # Convert C_i and gamma_star into Pa
119
+ data$C_i_pa <- data$C_i / 1000000 * P * 1000
120
+ gamma_star <- gamma_star / 1000000 * P * 1000
121
+ # Calculate g_mc according to Harley et al. 1992
122
+ data$g_mc <- data$A_net /
123
+ (data$C_i_pa - (gamma_star * (data$J_etr + 8 * (data$A_net + R_d)) /
124
+ (data$J_etr - 4 * (data$A_net + R_d))))
125
+
126
+ # According to Harley et al. 1992, if dCc/dA_net is too great
127
+ # g_mc is super sensitive to small errors, while if dCc/dA is too
128
+ # small, the results can be "unbelieveable". They suggested a
129
+ # range of 10 to 50 being acceptable, so the calculations for
130
+ # reliability are based on those. Please note that they may
131
+ # since have been mistaken, so this range is more of a guide
132
+ # rather than a hard and fast rule.
133
+ data$dCcdA <- 12 * gamma_star * data$J_etr /
134
+ (data$J_etr - 4 * (data$A_net + R_d))^2
135
+
136
+ data$reliable_g_mc <- rep(TRUE, length(data$g_mc))
137
+ # for loop to add TRUE/FALSE values to the reliability of the
138
+ # g_mc measurements. Cutoffs based on Harley et al. 1992.
139
+ for (i in 1:length(data$reliable_g_mc)) {
140
+ if (data$dCcdA[i] < 10) {
141
+ data$reliable[i] <- FALSE
142
+ }
143
+ if (data$dCcdA[i] > 50) {
144
+ data$reliable[i] <- FALSE
145
+ }
146
+ }
147
+ # Calculate the mean of reliable g_mc values
148
+ data$mean_g_mc_reliable <- mean(data[data$reliable == TRUE, ]$g_mc)
149
+ # return allows the output to be stored in the global environment
150
+ return(data)
151
+ }
data/R/fit_gs_model.R ADDED
@@ -0,0 +1,346 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #' Fitting stomatal conductance models
2
+ #'
3
+ #' @param data Dataframe
4
+ #' @param varnames Variable names
5
+ #'
6
+ #' For the Ball-Berry model: varnames = list(A_net = "A_net", C_air = "C_air",
7
+ #' g_sw = "g_sw", RH = "RH") where A_net is net CO2 assimilation, C_air is CO2
8
+ #' concentration at the leaf surface in umol mol-1, g_sw is stomatal
9
+ #' conductance to H2O, and RH is relative humidity as a proportion.
10
+ #'
11
+ #' For the Leuning model: varnames = list(A_net = "A_net", C_air = "C_air",
12
+ #' g_sw = "g_sw", VPD = "VPD") where A_net is net CO2 assimilation, C_air is
13
+ #' CO2 concentration at the leaf surface in umol mol-1, g_sw is stomatal
14
+ #' conductance to H2O, and VPD is leaf to air vapor pressure deficit in kPa.
15
+ #'
16
+ #' For the Medlyn et al. 2011 models: varnames = list(A_net = "A_net",
17
+ #' C_air = "C_air", g_sw = "g_sw", VPD = "VPD") where A_net is net CO2
18
+ #' assimilation, C_air is CO2 concentration at the leaf surface in umol mol-1,
19
+ #' g_sw is stomatal conductance to H2O, and VPD is leaf to air vapor pressure
20
+ #' deficit in kPa.
21
+ #' @param model Which model(s) to fit? Defaults to all models. Available
22
+ #' options are "BallBerry", "Leuning", "Medlyn_partial", and "Medlyn_full",
23
+ #' from Ball et al. (1987), Leuning (1995), and Medlyn et al. (2011).
24
+ #' @param D0 Vapor pressure sensitivity of stomata (Leuning 1995)
25
+ #' @param ... Arguments to pass on to the nlsLM() function for the Medlyn
26
+ #' models.
27
+ #'
28
+ #' @references
29
+ #'
30
+ #' Ball JT, Woodrow IE, Berry JA. 1987. A model predicting stomatal
31
+ #' conductance and its contribution to the control of photosynthesis
32
+ #' under different environmental conditions, in Progress in
33
+ #' Photosynthesis Research, Proceedings of the VII International
34
+ #' Congress on Photosynthesis, vol. 4, edited by I. Biggins, pp.
35
+ #' 221–224, Martinus Nijhoff, Dordrecht, Netherlands.
36
+ #'
37
+ #' Leuning R. 1995. A critical appraisal of a coupled stomatal-
38
+ #' photosynthesis model for C3 plants. Plant Cell Environ 18:339-357
39
+ #'
40
+ #' Medlyn BE, Duursma RA, Eamus D, Ellsworth DS, Prentice IC, Barton
41
+ #' CVM, Crous KY, Angelis PD, Freeman M, Wingate L. 2011. Reconciling
42
+ #' the optimal and empirical approaches to modeling stomatal
43
+ #' conductance. Glob Chang Biol 17:2134-2144
44
+ #'
45
+ #' @importFrom minpack.lm nlsLM
46
+ #'
47
+ #' @return fit_gs_model fits one or more stomatal conductance models to the
48
+ #' data. The top level of the output list is named after the fitted model,
49
+ #' while the second level contains the Model, Parameters, and Graph, in that
50
+ #' order.
51
+ #' @export
52
+ #'
53
+ #' @examples
54
+ #' \donttest{
55
+ #' # Read in your data
56
+ #' # Note that this data is coming from data supplied by the package
57
+ #' # hence the complicated argument in read.csv()
58
+ #' # This dataset is a CO2 by light response curve for a single sunflower
59
+ #' data <- read.csv(system.file("extdata", "A_Ci_Q_data_1.csv",
60
+ #' package = "photosynthesis"
61
+ #' ))
62
+ #'
63
+ #' # Convert RH to a proportion
64
+ #' data$RH <- data$RHcham / 100
65
+ #'
66
+ #' # Fit stomatal conductance models
67
+ #' # Can specify a single model, or all as below
68
+ #' fits <- fit_gs_model(
69
+ #' data = data,
70
+ #' varnames = list(
71
+ #' A_net = "A",
72
+ #' C_air = "Ca",
73
+ #' g_sw = "gsw",
74
+ #' RH = "RH",
75
+ #' VPD = "VPDleaf"
76
+ #' ),
77
+ #' model = c(
78
+ #' "BallBerry",
79
+ #' "Leuning",
80
+ #' "Medlyn_partial",
81
+ #' "Medlyn_full"
82
+ #' ),
83
+ #' D0 = 3
84
+ #' )
85
+ #'
86
+ #' # Look at BallBerry model summary:
87
+ #' summary(fits[["BallBerry"]][["Model"]])
88
+ #'
89
+ #' # Look at BallBerry parameters
90
+ #' fits[["BallBerry"]][["Parameters"]]
91
+ #'
92
+ #' # Look at BallBerry plot
93
+ #' fits[["BallBerry"]][["Graph"]]
94
+ #'
95
+ #' # Fit many g_sw models
96
+ #' # Set your grouping variable
97
+ #' # Here we are grouping by Qin and individual
98
+ #' data$Q_2 <- as.factor((round(data$Qin, digits = 0)))
99
+ #'
100
+ #' fits <- fit_many(data,
101
+ #' varnames = list(
102
+ #' A_net = "A",
103
+ #' C_air = "Ca",
104
+ #' g_sw = "gsw",
105
+ #' RH = "RH",
106
+ #' VPD = "VPDleaf"
107
+ #' ),
108
+ #' funct = fit_gs_model,
109
+ #' group = "Q_2"
110
+ #' )
111
+ #'
112
+ #' # Look at the Medlyn_partial outputs at 750 PAR
113
+ #' # Model summary
114
+ #' summary(fits[["750"]][["Medlyn_partial"]][["Model"]])
115
+ #'
116
+ #' # Model parameters
117
+ #' fits[["750"]][["Medlyn_partial"]][["Parameters"]]
118
+ #'
119
+ #' # Graph
120
+ #' fits[["750"]][["Medlyn_partial"]][["Graph"]]
121
+ #'
122
+ #' # Compile parameter outputs for BallBerry model
123
+ #' # Note that it's the first element for each PAR value
124
+ #' # First compile list of BallBerry fits
125
+ #' bbmods <- compile_data(
126
+ #' data = fits,
127
+ #' output_type = "list",
128
+ #' list_element = 1
129
+ #' )
130
+ #' # Now compile the parameters (2nd element) into a dataframe
131
+ #' bbpars <- compile_data(
132
+ #' data = bbmods,
133
+ #' output_type = "dataframe",
134
+ #' list_element = 2
135
+ #' )
136
+ #'
137
+ #' # Convert group variable back to numeric
138
+ #' bbpars$ID <- as.numeric(bbpars$ID)
139
+ #'
140
+ #' # Take quick look at light response of intercept parameters
141
+ #' plot(g0 ~ ID, bbpars)
142
+ #'
143
+ #' # Compile graphs
144
+ #' graphs <- compile_data(
145
+ #' data = bbmods,
146
+ #' output_type = "list",
147
+ #' list_element = 3
148
+ #' )
149
+ #'
150
+ #' # Look at 3rd graph
151
+ #' graphs[[3]]
152
+ #' }
153
+ fit_gs_model <- function(data, varnames = list(
154
+ A_net = "A_net",
155
+ C_air = "C_air",
156
+ g_sw = "g_sw",
157
+ RH = "RH",
158
+ VPD = "VPD"
159
+ ),
160
+ model = c(
161
+ "BallBerry",
162
+ "Leuning",
163
+ "Medlyn_partial",
164
+ "Medlyn_full"
165
+ ),
166
+ D0 = 3,
167
+ ...) {
168
+ # Check: are the models available?
169
+ if (TRUE %in% c(!model %in% c(
170
+ "BallBerry",
171
+ "Leuning",
172
+ "Medlyn_partial",
173
+ "Medlyn_full"
174
+ ))) {
175
+ stop("Specified model is not available. Current supported models are
176
+ BallBerry, Leuning, Medlyn_partial, and Medlyn_full.")
177
+ }
178
+ # Locally bind variables - avoids notes on check package
179
+ A_net <- NULL
180
+ C_air <- NULL
181
+ g_sw <- NULL
182
+ RH <- NULL
183
+ VPD <- NULL
184
+ # Assign variable names
185
+ data$A_net <- data[, varnames$A_net]
186
+ data$C_air <- data[, varnames$C_air]
187
+ data$g_sw <- data[, varnames$g_sw]
188
+ data$RH <- data[, varnames$RH]
189
+ data$VPD <- data[, varnames$VPD]
190
+ # Create empty list for number of output elements
191
+ models <- vector("list", length(model))
192
+ names(models) <- model
193
+ # BallBerry Model
194
+ if ("BallBerry" %in% model) {
195
+ models[["BallBerry"]] <- vector("list", 3)
196
+ # Assign linear regression model to element 1
197
+ models[["BallBerry"]][[1]] <-
198
+ lm(
199
+ data = data,
200
+ g_sw ~ gs_mod_ballberry(
201
+ A_net = A_net,
202
+ C_air = C_air,
203
+ RH = RH
204
+ )
205
+ )
206
+ # Extract coefficients
207
+ g0 <- coef(models[["BallBerry"]][[1]])[[1]]
208
+ g1 <- coef(models[["BallBerry"]][[1]])[[2]]
209
+ # Create list element of coefficients
210
+ models[["BallBerry"]][[2]] <- as.data.frame(cbind(g0, g1))
211
+ # Assign graph to element 3
212
+ models[["BallBerry"]][[3]] <- ggplot(
213
+ data,
214
+ aes(x = I(A_net * C_air * RH), y = g_sw)
215
+ ) +
216
+ geom_smooth(method = "lm", formula = y ~ x) +
217
+ geom_point() +
218
+ theme_bw()
219
+ # Assign names to list
220
+ names(models[["BallBerry"]]) <- c("Model", "Parameters", "Graph")
221
+ }
222
+ if ("Leuning" %in% model) {
223
+ models[["Leuning"]] <- vector("list", 3)
224
+ # Assign regression model to element 1
225
+ models[["Leuning"]][[1]] <- lm(
226
+ data = data,
227
+ g_sw ~ gs_mod_leuning(
228
+ A_net = A_net,
229
+ C_air = C_air,
230
+ D0 = D0,
231
+ VPD = VPD
232
+ )
233
+ )
234
+ # Extract coefficients
235
+ g0 <- coef(models[["Leuning"]][[1]])[[1]]
236
+ g1 <- coef(models[["Leuning"]][[1]])[[2]]
237
+ # Assign coefficients to element 2
238
+ models[["Leuning"]][[2]] <- as.data.frame(cbind(g0, g1))
239
+ # Assign graph to element 3
240
+ models[["Leuning"]][[3]] <- ggplot(
241
+ data,
242
+ aes(
243
+ x = I(A_net /
244
+ (C_air * (1 + VPD * D0))),
245
+ y = g_sw
246
+ )
247
+ ) +
248
+ geom_smooth(method = "lm", formula = y ~ x) +
249
+ geom_point() +
250
+ theme_bw()
251
+ # Assign names to list elements
252
+ names(models[["Leuning"]]) <- c("Model", "Parameters", "Graph")
253
+ }
254
+ if ("Medlyn_partial" %in% model) {
255
+ models[["Medlyn_partial"]] <- vector("list", 3)
256
+ # Fit model, assign to element 1
257
+ try(models[["Medlyn_partial"]][[1]] <- nlsLM(
258
+ data = data,
259
+ g_sw ~ gs_mod_opti(
260
+ A_net = A_net,
261
+ C_air = C_air,
262
+ VPD = VPD,
263
+ g0,
264
+ g1
265
+ ),
266
+ start = list(
267
+ g0 = 0,
268
+ g1 = 1
269
+ ),
270
+ control = nls.control(maxiter = 1000),
271
+ ...
272
+ ))
273
+ # Extract coefficients and make dataframe
274
+ g0 <- coef(models[["Medlyn_partial"]][[1]])[[1]]
275
+ g1 <- coef(models[["Medlyn_partial"]][[1]])[[2]]
276
+
277
+ # Assign coefficients to element 2
278
+ if (is.null(models[["Medlyn_partial"]][[1]]) == TRUE) {
279
+ models[["Medlyn_partial"]][[2]] <- data.frame(cbind("NA", "NA"))
280
+ colnames(models[["Medlyn_partial"]][[2]]) <- c("g0", "g1")
281
+ } else {
282
+ models[["Medlyn_partial"]][[2]] <- as.data.frame(cbind(g0, g1))
283
+ }
284
+ # Create graph, assign to element 3
285
+ models[["Medlyn_partial"]][[3]] <- ggplot(
286
+ data,
287
+ aes(x = I(1.6 / (sqrt(VPD)) *
288
+ (A_net / C_air) + 1.6 *
289
+ (A_net / C_air)), y = g_sw)
290
+ ) +
291
+ geom_smooth(method = "lm", formula = y ~ x) +
292
+ geom_point() +
293
+ theme_bw()
294
+ # Assign names to list elements
295
+ names(models[["Medlyn_partial"]]) <- c("Model", "Parameters", "Graph")
296
+ }
297
+ if ("Medlyn_full" %in% model) {
298
+ models[["Medlyn_full"]] <- vector("list", 3)
299
+ # Fit model, assign to element 1
300
+ try(models[["Medlyn_full"]][[1]] <- nlsLM(
301
+ data = data,
302
+ g_sw ~ gs_mod_optifull(
303
+ A_net = A_net,
304
+ C_air = C_air,
305
+ VPD = VPD,
306
+ g0,
307
+ g1,
308
+ gk
309
+ ),
310
+ start = list(
311
+ g0 = 0,
312
+ g1 = 1,
313
+ gk = 1
314
+ ),
315
+ control = nls.control(maxiter = 1000),
316
+ ...
317
+ ))
318
+ # Extract coefficients and make dataframe
319
+ g0 <- coef(models[["Medlyn_full"]][[1]])[[1]]
320
+ g1 <- coef(models[["Medlyn_full"]][[1]])[[2]]
321
+ gk <- coef(models[["Medlyn_full"]][[1]])[[3]]
322
+ # Assign coefficients to element 2
323
+ if (is.null(models[["Medlyn_full"]][[1]]) == TRUE) {
324
+ models[["Medlyn_full"]][[2]] <- data.frame(cbind("NA", "NA", "NA"))
325
+ colnames(models[["Medlyn_full"]][[2]]) <- c("g0", "g1", "gk")
326
+ } else {
327
+ models[["Medlyn_full"]][[2]] <- as.data.frame(cbind(g0, g1, gk))
328
+ }
329
+ # Create graph, assign to element 3
330
+ models[["Medlyn_full"]][[3]] <- ggplot(
331
+ data,
332
+ aes(x = I(1.6 / ((VPD)^(1 - gk)) *
333
+ (A_net / C_air) + 1.6 *
334
+ (A_net / C_air)), y = g_sw)
335
+ ) +
336
+ geom_smooth(method = "lm", formula = y ~ x) +
337
+ geom_point() +
338
+ theme_bw()
339
+ # Assign names to list elements
340
+ names(models[["Medlyn_full"]]) <- c("Model", "Parameters", "Graph")
341
+ }
342
+ # Add new models here, and make sure their names are available in the model
343
+ # argument at the top.
344
+ # Return list of model outputs
345
+ return(models)
346
+ }
data/R/fit_hyrda_vuln_curve.R ADDED
@@ -0,0 +1,318 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #' Fitting hydraulic vulnerability curves
2
+ #'
3
+ #' @param data Dataframe
4
+ #' @param varnames List of variable names. varnames = list(psi = "psi",
5
+ #' PLC = "PLC") where psi is water potential in MPa, and PLC is percent
6
+ #' loss conductivity.
7
+ #' @param title Title for the output graph
8
+ #' @param start_weibull starting values for the nls fitting routine
9
+ #' for the Weibull curve
10
+ #'
11
+ #' @return fit_hydra_vuln_curve fits a sigmoidal function (Pammenter & Van der
12
+ #' Willigen, 1998) linearized according to Ogle et al. (2009). Output is a list
13
+ #' containing the sigmoidal model in element 1 and Weibull model in element 4,
14
+ #' the fit parameters with 95% confidence interval for both models are in
15
+ #' element 2, and hydraulic parameters in element 3 (including P25, P50, P88,
16
+ #' P95, S50, Pe, Pmax, DSI). Px (25 to 95): water potential at which x% of
17
+ #' conductivity is lost. S50: slope at 50% loss of conductivity. Pe: air
18
+ #' entry point. Pmax: hydraulic failure threshold. DSI: drought stress interval.
19
+ #' Element 5 is a graph showing the fit, P50, Pe, and Pmax.
20
+ #'
21
+ #' @references
22
+ #' Ogle K, Barber JJ, Willson C, Thompson B. 2009. Hierarchical statistical
23
+ #' modeling of xylem vulnerability to cavitation. New Phytologist 182:541-554
24
+ #'
25
+ #' Pammenter NW, Van der Willigen CV. 1998. A mathematical and statistical
26
+ #' analysis of the curves illustrating vulnerability of xylem to cavitation.
27
+ #' Tree Physiology 18:589-593
28
+ #'
29
+ #' @importFrom dplyr bind_rows
30
+ #' @importFrom ggplot2 ggplot
31
+ #' @importFrom ggplot2 aes
32
+ #' @importFrom ggplot2 annotate
33
+ #' @importFrom ggplot2 element_blank
34
+ #' @importFrom ggplot2 labs
35
+ #' @importFrom ggplot2 ggtitle
36
+ #' @importFrom ggplot2 geom_smooth
37
+ #' @importFrom ggplot2 geom_point
38
+ #' @importFrom ggplot2 geom_vline
39
+ #' @importFrom ggplot2 scale_colour_manual
40
+ #' @importFrom ggplot2 theme
41
+ #' @importFrom ggplot2 theme_bw
42
+ #' @importFrom stats confint
43
+ #' @importFrom stats deriv
44
+ #'
45
+ #' @export
46
+ #' @examples
47
+ #' \donttest{
48
+ #' # Read in data
49
+ #' data <- read.csv(system.file("extdata", "hydraulic_vulnerability.csv",
50
+ #' package = "photosynthesis"
51
+ #' ))
52
+ #'
53
+ #' # Fit hydraulic vulnerability curve
54
+ #' fit <- fit_hydra_vuln_curve(data[data$Tree == 4 & data$Plot == "Control", ],
55
+ #' varnames = list(
56
+ #' psi = "P",
57
+ #' PLC = "PLC"
58
+ #' ),
59
+ #' title = "Control 4"
60
+ #' )
61
+ #'
62
+ #' # Return Sigmoidal model summary
63
+ #' summary(fit[[1]])
64
+ #'
65
+ #' # Return Weibull model summary
66
+ #' summary(fit[[4]])
67
+ #'
68
+ #' # Return model parameters with 95\% confidence intervals
69
+ #' fit[[2]]
70
+ #'
71
+ #' # Return hydraulic parameters
72
+ #' fit[[3]]
73
+ #'
74
+ #' # Return graph
75
+ #' fit[[5]]
76
+ #'
77
+ #' # Fit many curves
78
+ #' fits <- fit_many(
79
+ #' data = data,
80
+ #' varnames = list(
81
+ #' psi = "P",
82
+ #' PLC = "PLC"
83
+ #' ),
84
+ #' group = "Tree",
85
+ #' funct = fit_hydra_vuln_curve
86
+ #' )
87
+ #'
88
+ #' # To select individuals from the many fits
89
+ #' # Return model summary
90
+ #' summary(fits[[1]][[1]]) # Returns model summary
91
+ #'
92
+ #' # Return sigmoidal model output
93
+ #' fits[[1]][[2]]
94
+ #'
95
+ #' # Return hydraulic parameters
96
+ #' fits[[1]][[3]]
97
+ #'
98
+ #' # Return graph
99
+ #' fits[[1]][[5]]
100
+ #'
101
+ #' # Compile parameter outputs
102
+ #' pars <- compile_data(
103
+ #' data = fits,
104
+ #' output_type = "dataframe",
105
+ #' list_element = 3
106
+ #' )
107
+ #'
108
+ #' # Compile graphs
109
+ #' graphs <- compile_data(
110
+ #' data = fits,
111
+ #' output_type = "list",
112
+ #' list_element = 5
113
+ #' )
114
+ #' }
115
+ fit_hydra_vuln_curve <- function(data,
116
+ varnames = list(
117
+ psi = "psi",
118
+ PLC = "PLC"
119
+ ),
120
+ start_weibull = list(
121
+ a = 2,
122
+ b = 2
123
+ ),
124
+ title = NULL) {
125
+ # Locally bind variables - avoids notes on check package
126
+ psi <- NULL
127
+ PLC <- NULL
128
+ # Assign variable names
129
+ data$psi <- data[, varnames$psi]
130
+ data$PLC <- data[, varnames$PLC]
131
+ # Prepare y variable for sigmoidal function
132
+ data$H_log <- log(100 / data$PLC - 1)
133
+ # Prepare y variable for Weibull function
134
+ data$K.Kmax <- (1 - data$PLC / 100)
135
+ # Generate empty list for data outputs
136
+ fit_out <- list(NULL)
137
+ # Starting with the sigmoidal model
138
+ # Fit model, remove any infinite values (e.g. at P = 0)
139
+ fit_out[[1]] <- lm(H_log ~ psi, data[data$H_log < Inf, ])
140
+ # Extract model parameter values
141
+ fit_out[[2]] <- data.frame(c(coef(fit_out[[1]])[1], coef(fit_out[[1]])[2]))
142
+ # Note that in model, the intercept is - a * b
143
+ fit_out[[2]][1, ] <- fit_out[[2]][1, ] / -fit_out[[2]][2, ]
144
+ # Assign row names
145
+ rownames(fit_out[[2]]) <- c("b", "a")
146
+ # Assign parameter names
147
+ fit_out[[2]]$Parameter <- rownames(fit_out[[2]])
148
+ # Assign curve name
149
+ fit_out[[2]]$Curve <- "Sigmoidal"
150
+ # Assign column names
151
+ colnames(fit_out[[2]]) <- c(
152
+ "Value",
153
+ "Parameter", "Curve"
154
+ )
155
+ # Create dataframe for calculated parameters
156
+ fit_out[[3]] <- as.data.frame(rbind(1:8))
157
+ # Add column names
158
+ colnames(fit_out[[3]]) <- c(
159
+ "P25", "P50", "P88", "P95",
160
+ "S50", "Pe", "Pmax", "DSI"
161
+ )
162
+ # Assign a and b values to minimize typing
163
+ a <- fit_out[[2]]$Value[2]
164
+ b <- fit_out[[2]]$Value[1]
165
+ # Calculate hydraulic parameters
166
+ fit_out[[3]]$P25 <- log(1 / (0.25) - 1) / (a) + b
167
+ fit_out[[3]]$P50 <- log(1 / (0.5) - 1) / (a) + b
168
+ fit_out[[3]]$P88 <- log(1 / (0.88) - 1) / (a) + b
169
+ fit_out[[3]]$P95 <- log(1 / (0.95) - 1) / (a) + b
170
+ # To get slope, we need to take derivative of model and calculate at P50
171
+ XX <- fit_out[[3]]$P50
172
+ dWpsi <- deriv(~ 100 / (1 + exp(a * (XX - b))), "XX")
173
+ derivSoln <- eval(dWpsi)
174
+ # This extracts the slope at P50
175
+ fit_out[[3]]$S50 <- as.numeric(attributes(derivSoln)$gradient)
176
+ # Next calculate the air entry point
177
+ yint <- 50 - (fit_out[[3]]$S50 * fit_out[[3]]$P50)
178
+ fit_out[[3]]$Pe <- -yint / fit_out[[3]]$S50
179
+ # Calculate the hydraulic failure threshold
180
+ fit_out[[3]]$Pmax <- (100 - yint) / fit_out[[3]]$S50
181
+ # Calculate the drought stress interval
182
+ fit_out[[3]]$DSI <- fit_out[[3]]$Pmax - fit_out[[3]]$Pe
183
+ # Add curve name
184
+ fit_out[[3]]$Curve <- "Sigmoidal"
185
+ # Remove a and b values
186
+ remove(a)
187
+ remove(b)
188
+ # Moving on to Weibull model
189
+ fit_out[[4]] <- nlsLM(
190
+ data = data,
191
+ K.Kmax ~ exp(-((psi / a)^b)),
192
+ start = start_weibull
193
+ )
194
+ # Extract model parameter values
195
+ fit_out[[5]] <- data.frame(c(coef(fit_out[[4]])[2], coef(fit_out[[4]])[1]))
196
+ # Assign parameter names
197
+ fit_out[[5]]$Parameter <- rownames(fit_out[[5]])
198
+ # Assign curve name
199
+ fit_out[[5]]$Curve <- "Weibull"
200
+ # Assign column names
201
+ colnames(fit_out[[5]]) <- c(
202
+ "Value",
203
+ "Parameter", "Curve"
204
+ )
205
+ # Merge model parameters to reduce size of list
206
+ fit_out[[2]] <- bind_rows(fit_out[[2]], fit_out[[5]])
207
+ # Create dataframe for calculated parameters
208
+ fit_out[[5]] <- as.data.frame(rbind(1:8))
209
+ # Add column names
210
+ colnames(fit_out[[5]]) <- c(
211
+ "P25", "P50", "P88", "P95",
212
+ "S50", "Pe", "Pmax", "DSI"
213
+ )
214
+ # Assign a and b values to minimize typing
215
+ a <- fit_out[[2]]$Value[4]
216
+ b <- fit_out[[2]]$Value[3]
217
+ # Calculate hydraulic parameters
218
+ fit_out[[5]]$P25 <- (-log(1 - 25 / 100))^(1 / b) * a
219
+ fit_out[[5]]$P50 <- (-log(1 - 50 / 100))^(1 / b) * a
220
+ fit_out[[5]]$P88 <- (-log(1 - 88 / 100))^(1 / b) * a
221
+ fit_out[[5]]$P95 <- (-log(1 - 95 / 100))^(1 / b) * a
222
+ # To get slope, we need to take derivative of model and calculate at P50
223
+ dWpsi <- deriv(~ (1 - exp(-(XX / a)^b)) * 100, "XX")
224
+ XX <- fit_out[[5]]$P50
225
+ derivSoln <- eval(dWpsi)
226
+ # This extracts the slope at P50
227
+ fit_out[[5]]$S50 <- as.numeric(attributes(derivSoln)$gradient)
228
+ # Next calculate the air entry point
229
+ yint <- 50 - (fit_out[[5]]$S50 * fit_out[[5]]$P50)
230
+ fit_out[[5]]$Pe <- -yint / fit_out[[5]]$S50
231
+ # Calculate the hydraulic failure threshold
232
+ fit_out[[5]]$Pmax <- (100 - yint) / fit_out[[5]]$S50
233
+ # Calculate the drought stress interval
234
+ fit_out[[5]]$DSI <- fit_out[[5]]$Pmax - fit_out[[5]]$Pe
235
+ # Add curve name
236
+ fit_out[[5]]$Curve <- "Weibull"
237
+ # Combine output variables to reduce size of list
238
+ fit_out[[3]] <- rbind(fit_out[[3]], fit_out[[5]])
239
+ # Generates plot of hydraulic vulnerability curve
240
+ fit_out[[5]] <- ggplot(data, aes(x = psi, y = PLC)) +
241
+ ggtitle(label = title) +
242
+ geom_vline(
243
+ xintercept = fit_out[[3]]$P50[1],
244
+ linewidth = 2,
245
+ colour = "Blue"
246
+ ) +
247
+ geom_vline(
248
+ xintercept = fit_out[[3]]$Pe[1],
249
+ linewidth = 2,
250
+ colour = "Blue"
251
+ ) +
252
+ geom_vline(
253
+ xintercept = fit_out[[3]]$Pmax[1],
254
+ linewidth = 2,
255
+ colour = "Blue"
256
+ ) +
257
+ geom_vline(
258
+ xintercept = fit_out[[3]]$P50[2],
259
+ linewidth = 2,
260
+ colour = "Orange",
261
+ linetype = "dashed"
262
+ ) +
263
+ geom_vline(
264
+ xintercept = fit_out[[3]]$Pe[2],
265
+ linewidth = 2,
266
+ colour = "Orange",
267
+ linetype = "dashed"
268
+ ) +
269
+ geom_vline(
270
+ xintercept = fit_out[[3]]$Pmax[2],
271
+ linewidth = 2,
272
+ colour = "Orange",
273
+ linetype = "dashed"
274
+ ) +
275
+ geom_smooth(
276
+ method = "lm", aes(
277
+ x = psi, y = PLC,
278
+ colour = "Blue"
279
+ ), show.legend = TRUE,
280
+ formula = y ~ I(100 /
281
+ (1 + exp(fit_out[[2]]$Value[2] *
282
+ (x - fit_out[[2]]$Value[1])))),
283
+ linewidth = 2
284
+ ) +
285
+ geom_smooth(
286
+ method = "lm", aes(
287
+ x = psi, y = PLC,
288
+ colour = "DarkOrange"
289
+ ), show.legend = TRUE,
290
+ formula = y ~
291
+ I((1 - exp(-((x / fit_out[[2]]$Value[4])^
292
+ fit_out[[2]]$Value[3]))) * 100),
293
+ linewidth = 2
294
+ ) +
295
+ geom_point(size = 2, aes(colour = "Black")) +
296
+ labs(y = "PLC (%)", x = "Water Potential (-MPa)") +
297
+ scale_colour_manual(
298
+ values = c("Black", "Blue", "Orange"),
299
+ labels = c("Data", "Sigmoidal", "Weibull")
300
+ ) +
301
+ annotate("text",
302
+ label = "Left to Right:
303
+ Pe > P50 > Pmax",
304
+ x = 0.5, y = 75
305
+ ) +
306
+ theme_bw() +
307
+ theme(
308
+ legend.position = "bottom",
309
+ legend.title = element_blank()
310
+ )
311
+ # Assign names to elements in the output list
312
+ names(fit_out) <- c(
313
+ "Sig_Model", "Model_Parameters", "Model_Px Values",
314
+ "Wei_Model", "Graph"
315
+ )
316
+ # Return output list
317
+ return(fit_out)
318
+ }
data/R/fit_many.R ADDED
@@ -0,0 +1,106 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #' Fitting many functions across groups
2
+ #'
3
+ #' @description
4
+ #' `r lifecycle::badge("deprecated")`
5
+ #'
6
+ #' We are no longer updating this function. Please use generic methods like \code{\link[purrr]{map}} instead. See `vignette("light-response")` for an example.
7
+ #'
8
+ #' @param data Dataframe
9
+ #' @param funct Function to fit
10
+ #' @param group Grouping variables
11
+ #' @param progress Flag. Show progress bar?
12
+ #' @param ... Arguments for the function to fit. Use ?functionname
13
+ #' to read the help file on available arguments for a given function.
14
+ #'
15
+ #' @return fit_many fits a function across every instance of
16
+ #' a grouping variable.
17
+ #' @importFrom utils setTxtProgressBar
18
+ #' @importFrom utils txtProgressBar
19
+ #' @export
20
+ #'
21
+ #' @examples
22
+ #' \donttest{
23
+ #' # Read in your data
24
+ #' # Note that this data is coming from data supplied by the package
25
+ #' # hence the complicated argument in read.csv()
26
+ #' # This dataset is a CO2 by light response curve for a single sunflower
27
+ #' data = read.csv(system.file("extdata", "A_Ci_Q_data_1.csv",
28
+ #' package = "photosynthesis"
29
+ #' ))
30
+ #'
31
+ #' # Define a grouping factor based on light intensity to split the ACi
32
+ #' # curves
33
+ #' data$Q_2 = as.factor((round(data$Qin, digits = 0)))
34
+ #'
35
+ #' # Convert leaf temperature to K
36
+ #' data$T_leaf = data$Tleaf + 273.15
37
+ #'
38
+ #' # Fit many curves
39
+ #' fits = fit_many(
40
+ #' data = data,
41
+ #' varnames = list(
42
+ #' A_net = "A",
43
+ #' T_leaf = "T_leaf",
44
+ #' C_i = "Ci",
45
+ #' PPFD = "Qin"
46
+ #' ),
47
+ #' funct = fit_aci_response,
48
+ #' group = "Q_2"
49
+ #' )
50
+ #'
51
+ #' # Print the parameters
52
+ #' # First set of double parentheses selects an individual group value
53
+ #' # Second set selects an element of the sublist
54
+ #' fits[[3]][[1]]
55
+ #'
56
+ #' # Print the graph
57
+ #' fits[[3]][[2]]
58
+ #'
59
+ #' # Compile graphs into a list for plotting
60
+ #' fits_graphs = compile_data(fits,
61
+ #' list_element = 2
62
+ #' )
63
+ #'
64
+ #'
65
+ #' # Compile parameters into dataframe for analysis
66
+ #' fits_pars = compile_data(fits,
67
+ #' output_type = "dataframe",
68
+ #' list_element = 1
69
+ #' )
70
+ #' }
71
+ #'
72
+ #' @md
73
+
74
+ fit_many = function(
75
+ data,
76
+ funct,
77
+ group,
78
+ progress = TRUE,
79
+ ...
80
+ ) {
81
+
82
+ lifecycle::deprecate_soft("2.1.3", "fit_many()")
83
+
84
+ checkmate::assert_flag(progress)
85
+
86
+ # Split data into list by group
87
+ data = split(data, data[, group])
88
+
89
+ # Create empty list by group
90
+ fits = list(NULL)
91
+
92
+ # Start progress bar
93
+ if (progress) {
94
+ pb = txtProgressBar(min = 0, max = length(data), style = 3)
95
+ }
96
+
97
+ # Loop through list, fitting the function
98
+ for (i in 1:length(data)) {
99
+ fits[[i]] = funct(data[[i]], ...)
100
+ names(fits)[i] = names(data[i])
101
+ # Set progress bar
102
+ if (progress) setTxtProgressBar(pb, i)
103
+ }
104
+ # Return the list of fits
105
+ return(fits)
106
+ }
data/R/fit_photosynthesis.R ADDED
@@ -0,0 +1,119 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #' Fit photosynthetic models with gas-exchange data
2
+ #'
3
+ #' @param .data A data frame containing plant ecophysiological data. See [required_variables()] for the variables required for each model.
4
+ #' @param .photo_fun A character string of **photosynthesis** function to call. One of: ``r paste0(get_function_types(), collapse = ', ')``.
5
+ #' @param .model A character string of model name to use. See [get_all_models()].
6
+ #' @param .vars A list to rename variables in .data. See [required_variables()] for the accepted variable names.
7
+ #' @param .method A character string of the statistical method to use: 'ls' for least-squares and 'brms' for Bayesian model using [brms::brm()]. Default is 'ls'.
8
+ #' @param ... Additional arguments passed to specific models. See specific help pages for each type of photosynthetic model:
9
+ #'
10
+ #' * Light-response curves [fit_aq_response2()]
11
+ #' * Light respiration [fit_r_light2()]
12
+ #'
13
+ #' @param quiet Flag. Should messages be suppressed? Default is FALSE.
14
+ #' @param brm_options A list of options passed to [brms::brm()] if `.method = "brms"`. Default is NULL.
15
+ #'
16
+ #' @return A fitted model object
17
+ #'
18
+ #' * class 'lm' or 'nls' if `method = 'ls'`
19
+ #' * class 'brmsfit' if `method = 'brms'`
20
+ #'
21
+ #' @note This function will fit models to data but several methods require post-processing to extract meaningful parameter estimates and confidence intervals. See vignettes for further explanation and examples.
22
+ #'
23
+ #' * Light-response curves: `vignette("light-response", package = "photosynthesis")`
24
+ #' * Light respiration: `vignette("light-respiration", package = "photosynthesis")`
25
+ #'
26
+ #' @md
27
+ #' @export
28
+ fit_photosynthesis = function(
29
+ .data,
30
+ .photo_fun,
31
+ .model = "default",
32
+ .vars = NULL,
33
+ .method = "ls",
34
+ ...,
35
+ quiet = FALSE,
36
+ brm_options = NULL
37
+ ) {
38
+
39
+ checkmate::assert_data_frame(.data)
40
+ .photo_fun = match.arg(.photo_fun, choices = get_function_types())
41
+ .model = match.arg(.model, choices = c("default", get_all_models(.photo_fun)))
42
+ if (.model == "default") .model = get_default_model(.photo_fun)
43
+ .vars = substitute(.vars)
44
+ .method = match.arg(.method, choices = c("ls", "brms"))
45
+ checkmate::assert_flag(quiet)
46
+ checkmate::assert_list(brm_options, null.ok = TRUE)
47
+
48
+ # Rename variables
49
+ if (!is.null(.vars)) {
50
+ .data = rename_variables(.data, .vars)
51
+ }
52
+
53
+ assert_required_variables(
54
+ .data = .data,
55
+ .photo_fun = .photo_fun,
56
+ .model = .model,
57
+ .method = .method,
58
+ quiet = quiet
59
+ )
60
+
61
+ do.call(
62
+ glue::glue("fit_{.photo_fun}2"),
63
+ args = list(
64
+ .data = .data,
65
+ .model = .model,
66
+ .method = .method,
67
+ ...,
68
+ quiet = quiet,
69
+ brm_options = brm_options
70
+ )
71
+ )
72
+
73
+ }
74
+
75
+ #' Rename variables in .data based on .vars
76
+ #' @inheritParams fit_photosynthesis
77
+ #' @noRd
78
+ rename_variables = function(.data, .vars) {
79
+
80
+ # I feel like there needs to be a better way to do this
81
+ deparse(.vars) |>
82
+ stringr::str_replace("^list\\(", ".data = dplyr::rename(.data, ") |>
83
+ str2lang() |>
84
+ eval()
85
+
86
+ .data
87
+
88
+ }
89
+
90
+ #' Assert required variables are present in .data
91
+ #' @noRd
92
+ assert_required_variables = function(.data, .photo_fun, .model, .method, quiet) {
93
+
94
+ v = required_variables(.model, quiet = TRUE)
95
+ missing_vars = v[!(v %in% colnames(.data))]
96
+ n_missing_vars = length(missing_vars)
97
+ if (n_missing_vars > 0) {
98
+ if (!quiet) {
99
+ message(paste0(".data is missing required variables: {", paste(missing_vars, collapse = ", "), "}"))
100
+ glue::glue(
101
+ "You may need to revise .vars argument by replacing `var_name1`, etc. with variable name in your_data:
102
+
103
+ fit_photosynthesis(
104
+ .data = your_data,
105
+ .photo_fun = '{.photo_fun}',
106
+ .model = '{.model}',
107
+ .method = '{.method}',
108
+ .vars = list(
109
+ {args}
110
+ ),
111
+ ...
112
+ )\n\n",
113
+ args = stringr::str_c(stringr::str_c(v, " = var_name", seq_len(n_missing_vars)), collapse = ",\n ")
114
+ ) |>
115
+ cat()
116
+ }
117
+ stop(".data is missing variables. fit_photosynthesis() not run.")
118
+ }
119
+ }
data/R/fit_r_light.R ADDED
@@ -0,0 +1,698 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #' Fit models to estimate light respiration (\eqn{R_\mathrm{d}})
2
+ #'
3
+ #' @description We recommend using [fit_photosynthesis()] with argument `.photo_fun = "r_light"` rather than calling this function directly.
4
+ #'
5
+ #' @inheritParams fit_photosynthesis
6
+ #' @param Q_lower Lower light intensity limit for estimating Rd using `kok_1956` and `yin_etal_2011` models.
7
+ #' @param Q_upper Upper light intensity limit for estimating Rd using `kok_1956` and `yin_etal_2011` models
8
+ #' @param Q_levels A numeric vector of light intensity levels (\eqn{\mu}mol / mol) for estimating \eqn{R_\mathrm{d}} from the linear region of the A-C curve using the `walker_ort_2015` model.
9
+ #' @param C_upper Upper C (\eqn{\mu}mol / mol) limit for estimating \eqn{R_\mathrm{d}} from the linear region of the A-C curve using the `walker_ort_2015` model.
10
+ #'
11
+ #' @return
12
+ #'
13
+ #' * If `.method = 'ls'`: an [stats::nls()] or [stats::lm()] object.
14
+ #' * If `.method = 'brms'`: a [brms::brmsfit()] object.
15
+ #'
16
+ #' @note
17
+ #'
18
+ #' Confusingly, \eqn{R_\mathrm{d}} typically denotes respiration in the light, but you might see \eqn{R_\mathrm{day}} or \eqn{R_\mathrm{light}}.
19
+ #'
20
+ #' **Models**
21
+ #'
22
+ #' *Kok (1956)*
23
+ #'
24
+ #' The `kok_1956` model estimates light respiration using the Kok method
25
+ #' (Kok, 1956). The Kok method involves looking for a breakpoint in the
26
+ #' light response of net CO2 assimilation at very low light intensities
27
+ #' and extrapolating from data above the breakpoint to estimate light
28
+ #' respiration as the y-intercept. Rd value should be negative,
29
+ #' denoting an efflux of CO2.
30
+ #'
31
+ #' *Yin et al. (2011)*
32
+ #'
33
+ #' The `yin_etal_2011` model estimates light respiration according
34
+ #' to the Yin *et al.* (2009, 2011) modifications of the Kok
35
+ #' method. The modification uses fluorescence data to get a
36
+ #' better estimate of light respiration. Rd values should be negative here to
37
+ #' denote an efflux of CO2.
38
+ #'
39
+ #' *Walker & Ort (2015)*
40
+ #'
41
+ #' The `walker_ort_2015` model estimates light respiration and
42
+ #' \eqn{\Gamma*} according to Walker & Ort (2015) using a slope-
43
+ #' intercept regression method to find the intercept of multiple
44
+ #' A-C curves run at multiple light intensities. The method estimates
45
+ #' \eqn{\Gamma*} and \eqn{R_\mathrm{d}}. If estimated \eqn{R_\mathrm{d}} is
46
+ #' positive this could indicate issues (i.e. leaks) in the gas exchange
47
+ #' measurements. \eqn{\Gamma*} is in units of umol / mol and \eqn{R_\mathrm{d}}
48
+ #' is in units of \eqn{\mu}mol m\eqn{^{-2}} s\eqn{^{-1}} of respiratory flux.
49
+ #' If using \eqn{C_\mathrm{i}}, the estimated value is technically \eqn{C_\mathrm{i}}*.
50
+ #' You need to use \eqn{C_\mathrm{c}} to get \eqn{\Gamma*} Also note, however,
51
+ #' that the convention in the field is to completely ignore this note.
52
+ #'
53
+ #'
54
+ #' @references
55
+ #' Kok B. 1956. On the inhibition of photosynthesis by intense light.
56
+ #' Biochimica et Biophysica Acta 21: 234–244
57
+ #'
58
+ #' Walker BJ, Ort DR. 2015. Improved method for measuring the apparent
59
+ #' CO2 photocompensation point resolves the impact of multiple internal
60
+ #' conductances to CO2 to net gas exchange. Plant Cell Environ 38:2462-
61
+ #' 2474
62
+ #'
63
+ #' Yin X, Struik PC, Romero P, Harbinson J, Evers JB, van der Putten
64
+ #' PEL, Vos J. 2009. Using combined measurements of gas exchange and
65
+ #' chlorophyll fluorescence to estimate parameters of a biochemical C3
66
+ #' photosynthesis model: a critical appraisal and a new integrated
67
+ #' approach applied to leaves in a wheat (Triticum aestivum) canopy.
68
+ #' Plant Cell Environ 32:448-464
69
+ #'
70
+ #' Yin X, Sun Z, Struik PC, Gu J. 2011. Evaluating a new method to
71
+ #' estimate the rate of leaf respiration in the light by analysis of
72
+ #' combined gas exchange and chlorophyll fluorescence measurements.
73
+ #' Journal of Experimental Botany 62: 3489–3499
74
+ #'
75
+ #' @examples
76
+ #' \donttest{
77
+ #'
78
+ #' # Walker & Ort (2015) model
79
+ #'
80
+ #' library(broom)
81
+ #' library(dplyr)
82
+ #' library(photosynthesis)
83
+ #'
84
+ #' acq_data = system.file("extdata", "A_Ci_Q_data_1.csv", package = "photosynthesis") |>
85
+ #' read.csv()
86
+ #'
87
+ #' fit = fit_photosynthesis(
88
+ #' .data = acq_data,
89
+ #' .photo_fun = "r_light",
90
+ #' .model = "walker_ort_2015",
91
+ #' .vars = list(.A = A, .Q = Qin, .C = Ci),
92
+ #' C_upper = 300,
93
+ #' # Irradiance levels used in experiment
94
+ #' Q_levels = c(1500, 750, 375, 125, 100, 75, 50, 25),
95
+ #' )
96
+ #'
97
+ #' # The 'fit' object inherits class 'lm' and many methods can be used
98
+ #'
99
+ #' ## Model summary:
100
+ #' summary(fit)
101
+ #'
102
+ #' ## Estimated parameters:
103
+ #' coef(fit)
104
+ #'
105
+ #' ## 95% confidence intervals:
106
+ #' ## n.b. these confidence intervals are not correct because the regression is fit
107
+ #' ## sequentially. It ignores the underlying data and uncertainty in estimates of
108
+ #' ## slopes and intercepts with each A-C curve. Use '.method = "brms"' to properly
109
+ #' ## calculate uncertainty.
110
+ #' confint(fit)
111
+ #'
112
+ #' ## Tidy summary table using 'broom::tidy()'
113
+ #' tidy(fit, conf.int = TRUE, conf.level = 0.95)
114
+ #'
115
+ #' ## Calculate residual sum-of-squares
116
+ #' sum(resid(fit)^2)
117
+ #'
118
+ #' # Yin et al. (2011) model
119
+ #'
120
+ #' fit = fit_photosynthesis(
121
+ #' .data = acq_data,
122
+ #' .photo_fun = "r_light",
123
+ #' .model = "yin_etal_2011",
124
+ #' .vars = list(.A = A, .phiPSII = PhiPS2, .Q = Qin),
125
+ #' Q_lower = 20,
126
+ #' Q_upper = 250
127
+ #' )
128
+ #'
129
+ #' # The 'fit' object inherits class 'lm' and many methods can be used
130
+ #'
131
+ #' ## Model summary:
132
+ #' summary(fit)
133
+ #'
134
+ #' ## Estimated parameters:
135
+ #' coef(fit)
136
+ #'
137
+ #' ## 95% confidence intervals:
138
+ #' confint(fit)
139
+ #'
140
+ #' ## Tidy summary table using 'broom::tidy()'
141
+ #' tidy(fit, conf.int = TRUE, conf.level = 0.95)
142
+ #'
143
+ #' ## Calculate residual sum-of-squares
144
+ #' sum(resid(fit)^2)
145
+ #'
146
+ #' # Kok (1956) model
147
+ #'
148
+ #' fit = fit_photosynthesis(
149
+ #' .data = acq_data,
150
+ #' .photo_fun = "r_light",
151
+ #' .model = "kok_1956",
152
+ #' .vars = list(.A = A, .Q = Qin),
153
+ #' Q_lower = 20,
154
+ #' Q_upper = 150
155
+ #' )
156
+ #'
157
+ #' # The 'fit' object inherits class 'lm' and many methods can be used
158
+ #'
159
+ #' ## Model summary:
160
+ #' summary(fit)
161
+ #'
162
+ #' ## Estimated parameters:
163
+ #' coef(fit)
164
+ #'
165
+ #' ## 95% confidence intervals:
166
+ #' confint(fit)
167
+ #'
168
+ #' ## Tidy summary table using 'broom::tidy()'
169
+ #' tidy(fit, conf.int = TRUE, conf.level = 0.95)
170
+ #'
171
+ #' ## Calculate residual sum-of-squares
172
+ #' sum(resid(fit)^2)
173
+ #'
174
+ #' }
175
+ #' @md
176
+ #' @rdname fit_r_light2
177
+ #' @export
178
+ fit_r_light2 = function(
179
+ .data,
180
+ .model = "default",
181
+ .method = "ls",
182
+ Q_lower = NA,
183
+ Q_upper = NA,
184
+ Q_levels = NULL,
185
+ C_upper = NA,
186
+ quiet = FALSE,
187
+ brm_options = NULL
188
+ ) {
189
+
190
+ # Checks
191
+ checkmate::assert_number(
192
+ Q_lower,
193
+ lower = 0,
194
+ na.ok = !(.model %in% c("kok_1956", "yin_etal_2011"))
195
+ )
196
+ checkmate::assert_number(
197
+ Q_upper,
198
+ lower = Q_lower,
199
+ na.ok = !(.model %in% c("kok_1956", "yin_etal_2011"))
200
+ )
201
+ checkmate::assert_numeric(
202
+ Q_levels,
203
+ lower = 0,
204
+ finite = TRUE,
205
+ any.missing = FALSE,
206
+ min.len = 2L,
207
+ null.ok = !(.model %in% c("default", "walker_ort_2015"))
208
+ )
209
+ checkmate::assert_number(
210
+ C_upper,
211
+ lower = 0,
212
+ na.ok = !(.model %in% c("default", "walker_ort_2015"))
213
+ )
214
+
215
+ # Fit model
216
+ fit = switch(
217
+ .method,
218
+ ls = fit_r_light2_ls(.data, .model, Q_lower = Q_lower, Q_upper = Q_upper,
219
+ Q_levels = Q_levels, C_upper = C_upper),
220
+ brms = fit_r_light2_brms(.data, .model, Q_lower = Q_lower, Q_upper = Q_upper,
221
+ Q_levels = Q_levels, C_upper = C_upper,
222
+ brm_options = brm_options)
223
+ )
224
+
225
+ fit
226
+
227
+ }
228
+
229
+ #' Fit models to estimate light respiration (Rd) using least-squares methods
230
+ #' @inheritParams fit_r_light2
231
+ #' @noRd
232
+ fit_r_light2_ls = function(
233
+ .data,
234
+ .model,
235
+ Q_lower,
236
+ Q_upper,
237
+ Q_levels,
238
+ C_upper
239
+ ) {
240
+
241
+ do.call(
242
+ glue::glue("fit_r_light2_{.model}_ls"),
243
+ args = list(
244
+ .data = .data,
245
+ Q_lower = Q_lower,
246
+ Q_upper = Q_upper,
247
+ Q_levels = Q_levels,
248
+ C_upper = C_upper
249
+ )
250
+ )
251
+
252
+ }
253
+
254
+ #' Fit models to estimate light respiration (Rd) using Bayesian methods
255
+ #' @inheritParams fit_r_light2
256
+ #' @noRd
257
+ fit_r_light2_brms = function(
258
+ .data,
259
+ .model,
260
+ Q_lower,
261
+ Q_upper,
262
+ Q_levels,
263
+ C_upper,
264
+ brm_options
265
+ ) {
266
+
267
+ do.call(
268
+ glue::glue("fit_r_light2_{.model}_brms"),
269
+ args = list(
270
+ .data = .data,
271
+ Q_lower = Q_lower,
272
+ Q_upper = Q_upper,
273
+ Q_levels = Q_levels,
274
+ C_upper = C_upper,
275
+ brm_options = brm_options
276
+ )
277
+ )
278
+
279
+ }
280
+
281
+ #' Fit models to estimate light respiration (Rd) with the Walker & Ort (2015) model using least-squares methods
282
+ #' @inheritParams fit_r_light2
283
+ #' @noRd
284
+ fit_r_light2_walker_ort_2015_ls = function(
285
+ .data,
286
+ Q_levels,
287
+ C_upper,
288
+ ...
289
+ ) {
290
+
291
+ .data = .data |>
292
+ dplyr::filter(.C <= C_upper) |>
293
+ dplyr::mutate(
294
+ # Group by Q_level
295
+ .Q_level = round_to_nearest(.Q, Q_levels)
296
+ )
297
+
298
+ nlme::lmList(.A ~ .C | .Q_level, data = .data) |>
299
+ coef() |>
300
+ dplyr::mutate(gamma_star = -.C) %>%
301
+ lm(`(Intercept)` ~ gamma_star, data = .)
302
+
303
+ }
304
+
305
+ #' Fit models to estimate light respiration (Rd) with the Walker & Ort (2015) model using Bayesian methods
306
+ #' @inheritParams fit_r_light2
307
+ #' @noRd
308
+ fit_r_light2_walker_ort_2015_brms = function(
309
+ .data,
310
+ Q_levels,
311
+ C_upper,
312
+ brm_options,
313
+ ...
314
+ ) {
315
+
316
+ .data = .data |>
317
+ dplyr::filter(.C <= C_upper) |>
318
+ dplyr::mutate(
319
+ # Group by Q_level
320
+ .Q_level = as.factor(round_to_nearest(.Q, Q_levels))
321
+ )
322
+
323
+ do.call(
324
+ brms::brm,
325
+ args = c(
326
+ brm_options,
327
+ list(
328
+ formula = .A ~ .C + (1 + .C|.Q_level),
329
+ data = .data
330
+ )
331
+ )
332
+ )
333
+
334
+ }
335
+
336
+ #' Fit models to estimate light respiration (Rd) with the Yin *et al.* (2011) model using least-squares methods
337
+ #' @inheritParams fit_r_light2
338
+ #' @noRd
339
+ fit_r_light2_yin_etal_2011_ls = function(
340
+ .data,
341
+ Q_lower,
342
+ Q_upper,
343
+ ...
344
+ ) {
345
+
346
+ .data |>
347
+ dplyr::filter(.Q >= Q_lower, .Q <= Q_upper) |>
348
+ dplyr::mutate(x_var = .Q * .phiPSII / 4) %>%
349
+ lm(.A ~ x_var, data = .)
350
+
351
+ }
352
+
353
+ #' Fit models to estimate light respiration (Rd) with the Yin *et al.* (2011) model using Bayesian methods
354
+ #' @inheritParams fit_r_light2
355
+ #' @noRd
356
+ fit_r_light2_yin_etal_2011_brms = function(
357
+ .data,
358
+ Q_lower,
359
+ Q_upper,
360
+ brm_options,
361
+ ...
362
+ ) {
363
+
364
+ .data = .data |>
365
+ dplyr::filter(.Q >= Q_lower, .Q <= Q_upper) |>
366
+ dplyr::mutate(x_var = .Q * .phiPSII / 4)
367
+
368
+ do.call(
369
+ brms::brm,
370
+ args = c(
371
+ brm_options,
372
+ list(
373
+ formula = .A ~ x_var,
374
+ data = .data
375
+ )
376
+ )
377
+ )
378
+
379
+ }
380
+
381
+ #' Fit models to estimate light respiration (Rd) with the Kok (1956) model using least-squares methods
382
+ #' @inheritParams fit_r_light2
383
+ #' @noRd
384
+ fit_r_light2_kok_1956_ls = function(
385
+ .data,
386
+ Q_lower,
387
+ Q_upper,
388
+ ...
389
+ ) {
390
+
391
+ .data |>
392
+ dplyr::filter(.Q >= Q_lower, .Q <= Q_upper) %>%
393
+ lm(.A ~ .Q, data = .)
394
+
395
+ }
396
+
397
+ #' Fit models to estimate light respiration (Rd) with the Kok (1956) model using Bayesian methods
398
+ #' @inheritParams fit_r_light2
399
+ #' @noRd
400
+ fit_r_light2_kok_1956_brms = function(
401
+ .data,
402
+ Q_lower,
403
+ Q_upper,
404
+ brm_options,
405
+ ...
406
+ ) {
407
+
408
+ .data = .data |>
409
+ dplyr::filter(.Q >= Q_lower, .Q <= Q_upper)
410
+
411
+ do.call(
412
+ brms::brm,
413
+ args = c(
414
+ brm_options,
415
+ list(
416
+ formula = .A ~ .Q,
417
+ data = .data
418
+ )
419
+ )
420
+ )
421
+
422
+ }
423
+
424
+ #' Estimating light respiration
425
+ #'
426
+ #' @description
427
+ #' `r lifecycle::badge("deprecated")`
428
+ #'
429
+ #' Please use `fit_r_light2()`.
430
+ #'
431
+ #' @param data Dataframe
432
+ #' @param varnames List of variable names
433
+ #' @param PPFD_lower Lower light intensity limit for estimating Rlight
434
+ #' (Kok & Yin)
435
+ #' @param PPFD_upper Upper light intensity limit for estimating Rlight
436
+ #' (Kok & Yin)
437
+ #'
438
+ #' @param P Atmospheric pressure in kPa (Walker & Ort, 2015)
439
+ #' @param C_i_threshold Threshold C_i (in umol / mol) to cut data to
440
+ #' linear region for fitting light respiration and gamma_star
441
+ #' (Walker & Ort, 2015)
442
+ #'
443
+ #' @return fit_r_light_kok estimates light respiration using the Kok method
444
+ #' (Kok, 1956). The Kok method involves looking for a breakpoint in the
445
+ #' light response of net CO2 assimilation at very low light intensities
446
+ #' and extrapolating from data above the breakpoint to estimate light
447
+ #' respiration as the y-intercept. r_light value should be negative,
448
+ #' denoting an efflux of CO2.
449
+ #'
450
+ #' fit_r_light_WalkerOrt estimates light respiration and
451
+ #' GammaStar according to Walk & Ort (2015) using a slope-
452
+ #' intercept regression method to find the intercept of multiple
453
+ #' ACi curves run at multiple light intensities. Output GammaStar and
454
+ #' respiration should be negative If output respiration is positive
455
+ #' this could indicate issues (i.e. leaks) in the gas exchange
456
+ #' measurements. GammaStar is output in umol mol-1, and respiration
457
+ #' is output in umol m-2 s-1 of respiratory flux. Output is a list
458
+ #' containing the slope intercept regression model, a graph of the fit,
459
+ #' and estimates of the coefficients. NOTE: if using C_i, the output value
460
+ #' is technically C_istar. You need to use Cc to get GammaStar. Also note,
461
+ #' however, that the convention in the field is to completely ignore this note.
462
+ #'
463
+ #' fit_r_light_yin estimates light respiration according
464
+ #' to the Yin et al. (2009, 2011) modifications of the Kok
465
+ #' method. The modification uses fluorescence data to get a
466
+ #' better estimate of light respiration. Note that respiration
467
+ #' output should be negative here to denote an efflux of CO2.
468
+ #'
469
+ #' @references
470
+ #' Kok B. 1956. On the inhibition of photosynthesis by intense light.
471
+ #' Biochimica et Biophysica Acta 21: 234–244
472
+ #'
473
+ #' Walker BJ, Ort DR. 2015. Improved method for measuring the apparent
474
+ #' CO2 photocompensation point resolves the impact of multiple internal
475
+ #' conductances to CO2 to net gas exchange. Plant Cell Environ 38:2462-
476
+ #' 2474
477
+ #'
478
+ #' Yin X, Struik PC, Romero P, Harbinson J, Evers JB, van der Putten
479
+ #' PEL, Vos J. 2009. Using combined measurements of gas exchange and
480
+ #' chlorophyll fluorescence to estimate parameters of a biochemical C3
481
+ #' photosynthesis model: a critical appraisal and a new integrated
482
+ #' approach applied to leaves in a wheat (Triticum aestivum) canopy.
483
+ #' Plant Cell Environ 32:448-464
484
+ #'
485
+ #' Yin X, Sun Z, Struik PC, Gu J. 2011. Evaluating a new method to
486
+ #' estimate the rate of leaf respiration in the light by analysis of
487
+ #' combined gas exchange and chlorophyll fluorescence measurements.
488
+ #' Journal of Experimental Botany 62: 3489–3499
489
+ #'
490
+ #' @importFrom nlme lmList
491
+ #' @importFrom stats coef
492
+ #' @importFrom stats lm
493
+ #'
494
+ #' @examples
495
+ #' \donttest{
496
+ #' # FITTING KOK METHOD
497
+ #' # Read in your data
498
+ #' # Note that this data is coming from data supplied by the package
499
+ #' # hence the complicated argument in read.csv()
500
+ #' # This dataset is a CO2 by light response curve for a single sunflower
501
+ #' data = read.csv(system.file("extdata", "A_Ci_Q_data_1.csv",
502
+ #' package = "photosynthesis"
503
+ #' ))
504
+ #'
505
+ #' # Fit light respiration with Kok method
506
+ #' r_light = fit_r_light_kok(
507
+ #' data = data,
508
+ #' varnames = list(
509
+ #' A_net = "A",
510
+ #' PPFD = "Qin"
511
+ #' ),
512
+ #' PPFD_lower = 20,
513
+ #' PPFD_upper = 150
514
+ #' )
515
+ #' # Return r_light
516
+ #' r_light
517
+ #'
518
+ #' # FITTING WALKER-ORT METHOD
519
+ #' # Read in your data
520
+ #' # Note that this data is coming from data supplied by the package
521
+ #' # hence the complicated argument in read.csv()
522
+ #' # This dataset is a CO2 by light response curve for a single sunflower
523
+ #' data = read.csv(system.file("extdata", "A_Ci_Q_data_1.csv",
524
+ #' package = "photosynthesis"
525
+ #' ))
526
+ #'
527
+ #' # Fit the Walker-Ort method for GammaStar and light respiration
528
+ #' walker_ort = fit_r_light_WalkerOrt(data,
529
+ #' varnames = list(
530
+ #' A_net = "A",
531
+ #' C_i = "Ci",
532
+ #' PPFD = "Qin"
533
+ #' )
534
+ #' )
535
+ #' # Extract model
536
+ #' summary(walker_ort[[1]])
537
+ #'
538
+ #' # View graph
539
+ #' walker_ort[[2]]
540
+ #'
541
+ #' # View coefficients
542
+ #' walker_ort[[3]]
543
+ #'
544
+ #' # FITTING THE YIN METHOD
545
+ #' # Read in your data
546
+ #' # Note that this data is coming from data supplied by the package
547
+ #' # hence the complicated argument in read.csv()
548
+ #' # This dataset is a CO2 by light response curve for a single sunflower
549
+ #' data = read.csv(system.file("extdata", "A_Ci_Q_data_1.csv",
550
+ #' package = "photosynthesis"
551
+ #' ))
552
+ #'
553
+ #' # Fit light respiration with Yin method
554
+ #' r_light = fit_r_light_yin(
555
+ #' data = data,
556
+ #' varnames = list(
557
+ #' A_net = "A",
558
+ #' PPFD = "Qin",
559
+ #' phi_PSII = "PhiPS2"
560
+ #' ),
561
+ #' PPFD_lower = 20,
562
+ #' PPFD_upper = 250
563
+ #' )
564
+ #' }
565
+ #'
566
+ #' @rdname fit_r_light
567
+ #' @md
568
+ #' @export
569
+ fit_r_light_kok = function(
570
+ data,
571
+ varnames = list(
572
+ A_net = "A_net",
573
+ PPFD = "PPFD"
574
+ ),
575
+ PPFD_lower = 40,
576
+ PPFD_upper = 100
577
+ ) {
578
+
579
+ lifecycle::deprecate_warn(
580
+ "2.1.1",
581
+ "fit_r_light_kok()",
582
+ "fit_r_light2(.model = 'kok_1956')",
583
+ always = TRUE
584
+ )
585
+
586
+ # Set variable names
587
+ data$A_net = data[, varnames$A_net]
588
+ data$PPFD = data[, varnames$PPFD]
589
+ # Reduce data to within PPFD range
590
+ data_use = data[data$PPFD < PPFD_upper, ]
591
+ data_use = data_use[data_use$PPFD > PPFD_lower, ]
592
+ # Linear regression to estimate r_light (intercept)
593
+ model = lm(A_net ~ PPFD, data = data_use)
594
+ r_light = coef(model)[1]
595
+ # Output light respiration value
596
+ return(r_light)
597
+ }
598
+
599
+ #' @rdname fit_r_light
600
+ #' @export
601
+ fit_r_light_WalkerOrt = function(
602
+ data,
603
+ varnames = list(
604
+ A_net = "A_net",
605
+ C_i = "C_i",
606
+ PPFD = "PPFD"
607
+ ),
608
+ P = 100,
609
+ C_i_threshold = 300
610
+ ) {
611
+
612
+ lifecycle::deprecate_warn(
613
+ "2.1.1",
614
+ "fit_r_light_WalkerOrt()",
615
+ "fit_r_light2(.model = 'walker_ort_2015')",
616
+ always = TRUE
617
+ )
618
+
619
+ # Set variable names
620
+ data$A_net = data[, varnames$A_net]
621
+ data$C_i = data[, varnames$C_i]
622
+ data$PPFD = data[, varnames$PPFD]
623
+
624
+ # Locally define slope and intercept for slope-intercept regression
625
+ # This gets rid of a note in the R CMD CHECK
626
+ Slope = NULL
627
+ Intercept = NULL
628
+
629
+ # Restrict data analysis by a threshold C_i
630
+ data_use = data[data$C_i < C_i_threshold, ]
631
+ # Convert C_i to units of Pa
632
+ data_use$C_i = data_use$C_i / 1000000 * P * 1000
633
+ # Set PPFD as factor for grouping & round
634
+ # PPFD to nearest 10s
635
+ data_use$PPFD = round(data_use$PPFD, digits = -1)
636
+ data_use$PPFD = as.factor(data_use$PPFD)
637
+ # Construct regressions on the pseudolinear portions of
638
+ # the ACi curves
639
+ model = lmList(A_net ~ C_i | PPFD, data = data_use)
640
+ # Extract coefficients
641
+ coefs = coef(model)
642
+ colnames(coefs) = c("Intercept", "Slope")
643
+ coefs$PPFD = rownames(coefs)
644
+ # Create output list
645
+ output = list(NULL)
646
+ # Run slope-intercept regression model, assign to element 1
647
+ output[[1]] = lm(Intercept ~ Slope,
648
+ data = coefs
649
+ )
650
+ # Create graph, assign to element 2
651
+ output[[2]] = ggplot(coefs, aes(x = Slope, y = Intercept)) +
652
+ labs(x = "Slope", y = "Intercept") +
653
+ geom_smooth(method = "lm", linewidth = 2) +
654
+ geom_point(size = 3) +
655
+ theme_bw()
656
+ # Extract coefficients as per Walker and Ort 2015
657
+ # But convert C_istar to umol mol-1
658
+ GammaStar = -coef(output[[1]])[2] / (P * 1000) * 1000000
659
+ r_light = coef(output[[1]])[1]
660
+ output[[3]] = as.data.frame(cbind(GammaStar, r_light))
661
+ # Return output
662
+ return(output)
663
+ }
664
+
665
+ #' @rdname fit_r_light
666
+ #' @export
667
+ fit_r_light_yin = function(
668
+ data,
669
+ varnames = list(
670
+ A_net = "A_net",
671
+ PPFD = "PPFD",
672
+ phi_PSII = "phi_PSII"
673
+ ),
674
+ PPFD_lower = 40,
675
+ PPFD_upper = 100
676
+ ) {
677
+
678
+ lifecycle::deprecate_warn(
679
+ "2.1.1",
680
+ "fit_r_light_yin()",
681
+ "fit_r_light2(.model = 'yin_etal_2011')",
682
+ always = TRUE
683
+ )
684
+
685
+ # Set variable names
686
+ data$A_net = data[, varnames$A_net]
687
+ data$phi_PSII = data[, varnames$phi_PSII]
688
+ data$PPFD = data[, varnames$PPFD]
689
+ # Reduce data to within PPFD range
690
+ data_use = data[data$PPFD < PPFD_upper, ]
691
+ data_use = data_use[data_use$PPFD > PPFD_lower, ]
692
+ # Calculate x-variable for Yin method
693
+ data_use$x_var = data_use$PPFD * data_use$phi_PSII / 4
694
+ # Fit linear model for Yin method
695
+ model = lm(A_net ~ x_var, data = data_use)
696
+ r_light = coef(model)[1]
697
+ return(r_light)
698
+ }
data/R/fit_t_response.R ADDED
@@ -0,0 +1,1016 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #' Fitting temperature responses
2
+ #'
3
+ #' @param data Dataframe with temperature response variables
4
+ #' @param varnames Variable names, where Par is the parameter of interest, and
5
+ #' T_leaf is the leaf temperature in K.
6
+ #' @param model Which temperature response model do you want to use? Defaults
7
+ #' to all: Arrhenius, Heskel, Kruse, Medlyn, MMRT, Quadratic, and Topt.
8
+ #' @param start List of starting parameters for the nls model fits. a, b, and c
9
+ #' are needed for the Heskel model, dEa, Ea_ref, and Par_ref are needed for the
10
+ #' Kruse model, Ea, Par25, and Hd are all needed for the Medlyn and Topt models
11
+ #' while the Medlyn model also requires dS, and dCP, dG, and dH are all for the
12
+ #' MMRT model.
13
+ #' @param setvar Which variable to set as constant for the Medlyn model?
14
+ #' Defaults to "none", while "Hd" and "dS" options are available.
15
+ #' @param hdset Which value should Hd be set to when setvar = "Hd"? Specify
16
+ #' in J/mol.
17
+ #' @param dSset Which value should dS be set to when setvar = "dS"? Specify
18
+ #' in J/mol/K.
19
+ #' @param title Title of output graphs
20
+ #' @param ... Further arguments to pass on to the nlsLM() function
21
+ #'
22
+ #' @return fit_t_response fits one or more temperature response models to a
23
+ #' dataset, returning a list of lists. The parent list contains the models,
24
+ #' while the child list for each model contains the fitted model in element
25
+ #' 1, the coefficients in element 2, and a graph in element 3.
26
+ #' @references
27
+ #' Arrhenius S. 1915. Quantitative laws in biological chemistry. Bell.
28
+ #'
29
+ #' Heskel MA, O'Sullivan OS, Reich PB, Tjoelker MG, Weerasinghe LK,
30
+ #' Penillard A, Egerton JJG, Creek D, Bloomfield KJ, Xiang J, Sinca F,
31
+ #' Stangl ZR, la Torre AM, Griffin KL, Huntingford C, Hurry V, Meir P,
32
+ #' Turnbull MH, Atkin OK. 2016. Convergence in the temperature response
33
+ #' of leaf respiration across biomes and plant functional types. PNAS
34
+ #' 113:3832-3837
35
+ #'
36
+ #' Hobbs JK, Jiao W, Easter AD, Parker EJ, Schipper LA, Arcus VL.
37
+ #' 2013. Change in heat capacity for enzyme catalysis determines
38
+ #' temperature dependence of enzyme catalyzed rates. ACS Chemical
39
+ #' Biology 8:2388-2393.
40
+ #'
41
+ #' Kruse J, Adams MA. 2008. Three parameters comprehensively describe
42
+ #' the temperature response of respiratory oxygen reduction. Plant
43
+ #' Cell Environ 31:954-967
44
+ #'
45
+ #' Liang LL, Arcus VL, Heskel MA, O'Sullivan OS, Weerasinghe LK,
46
+ #' Creek D, Egerton JJG, Tjoelker MG, Atkin OK, Schipper LA. 2018.
47
+ #' Macromolecular rate theory (MMRT) provides a thermodynamics
48
+ #' rationale to underpin the convergent temperature response in
49
+ #' plant leaf respiration. Glob Chang Biol 24:1538-1547
50
+ #'
51
+ #' Medlyn BE, Dreyer E, Ellsworth D, Forstreuter M, Harley PC,
52
+ #' Kirschbaum MUF, Le Roux X, Montpied P, Strassemeyer J, Walcroft A,
53
+ #' Wang K, Loutstau D. 2002. Temperature response of parameters of a
54
+ #' biochemically based model of photosynthesis. II. A review of
55
+ #' experimental data. Plant Cell Environ 25:1167-1179
56
+ #'
57
+ #' @importFrom ggplot2 aes
58
+ #' @importFrom ggplot2 labs
59
+ #' @importFrom ggplot2 ggtitle
60
+ #' @importFrom ggplot2 geom_smooth
61
+ #' @importFrom ggplot2 geom_point
62
+ #' @importFrom ggplot2 theme_bw
63
+ #' @importFrom minpack.lm nlsLM
64
+ #' @importFrom stats nls.control
65
+ #' @export
66
+ #'
67
+ #' @examples
68
+ #' \donttest{
69
+ #' # Read in data
70
+ #' data <- read.csv(system.file("extdata", "A_Ci_T_data.csv",
71
+ #' package = "photosynthesis"
72
+ #' ),
73
+ #' stringsAsFactors = FALSE
74
+ #' )
75
+ #'
76
+ #' library(tidyr)
77
+ #'
78
+ #' # Round temperatures to group them appropriately
79
+ #' # Use sequential rounding
80
+ #' data$T2 <- round(data$Tleaf, 1)
81
+ #' data$T2 <- round(data$Tleaf, 0)
82
+ #'
83
+ #' # Look at unique values to detect rounding issues
84
+ #' unique(data$T2)
85
+ #'
86
+ #' # Some still did not round correctly,
87
+ #' # manually correct
88
+ #' for (i in 1:nrow(data)) {
89
+ #' if (data$T2[i] == 18) {
90
+ #' data$T2[i] <- 17
91
+ #' }
92
+ #' if (data$T2[i] == 23) {
93
+ #' data$T2[i] <- 22
94
+ #' }
95
+ #' if (data$T2[i] == 28) {
96
+ #' data$T2[i] <- 27
97
+ #' }
98
+ #' if (data$T2[i] == 33) {
99
+ #' data$T2[i] <- 32
100
+ #' }
101
+ #' if (data$T2[i] == 38) {
102
+ #' data$T2[i] <- 37
103
+ #' }
104
+ #' }
105
+ #'
106
+ #' # Make sure it is a character string for grouping
107
+ #' data$T2 <- as.character(data$T2)
108
+ #'
109
+ #' # Create grouping variable by ID and measurement temperature
110
+ #' data <- unite(data,
111
+ #' col = "ID2", c("ID", "T2"),
112
+ #' sep = "_"
113
+ #' )
114
+ #'
115
+ #' # Split by temperature group
116
+ #' data <- split(data, data$ID2)
117
+ #'
118
+ #' # Obtain mean temperature for group so temperature
119
+ #' # response fitting is acceptable later, round to
120
+ #' # 2 decimal places
121
+ #' for (i in 1:length(data)) {
122
+ #' data[[i]]$Curve_Tleaf <- round(mean(data[[i]]$Tleaf), 2)
123
+ #' }
124
+ #'
125
+ #' # Convert from list back to dataframe
126
+ #' data <- do.call("rbind", data)
127
+ #'
128
+ #' # Parse grouping variable by ID and measurement temperature
129
+ #' data <- separate(data,
130
+ #' col = "ID2", into = c("ID", "T2"),
131
+ #' sep = "_"
132
+ #' )
133
+ #'
134
+ #' # Make sure number of values matches number of measurement
135
+ #' # temperatures. May vary slightly if plants had slightly
136
+ #' # different leaf temperatures during the measurements
137
+ #' unique(data$Curve_Tleaf)
138
+ #'
139
+ #' # Create ID column to curve fit by ID and temperature
140
+ #' data <- unite(data,
141
+ #' col = "ID2", c("ID", "Curve_Tleaf"),
142
+ #' sep = "_"
143
+ #' )
144
+ #'
145
+ #' # Convert leaf temperature to K
146
+ #' data$T_leaf <- data$Tleaf + 273.15
147
+ #'
148
+ #' # Fit many CO2 response curves
149
+ #' fits2 <- fit_many(
150
+ #' data = data,
151
+ #' group = "ID2",
152
+ #' varnames = list(
153
+ #' A_net = "A",
154
+ #' C_i = "Ci",
155
+ #' T_leaf = "T_leaf",
156
+ #' PPFD = "Qin",
157
+ #' g_mc = "g_mc"
158
+ #' ),
159
+ #' funct = fit_aci_response,
160
+ #' alphag = 0
161
+ #' )
162
+ #'
163
+ #' # Extract ACi parameters
164
+ #' pars <- compile_data(fits2,
165
+ #' output_type = "dataframe",
166
+ #' list_element = 1
167
+ #' )
168
+ #'
169
+ #' # Extract ACi graphs
170
+ #' graphs <- compile_data(fits2,
171
+ #' output_type = "list",
172
+ #' list_element = 2
173
+ #' )
174
+ #'
175
+ #' # Parse the ID variable
176
+ #' pars <- separate(pars, col = "ID", into = c("ID", "Curve_Tleaf"), sep = "_")
177
+ #'
178
+ #' # Make sure curve leaf temperature is numeric
179
+ #' pars$Curve_Tleaf <- as.numeric(pars$Curve_Tleaf)
180
+ #' pars$T_leaf <- pars$Curve_Tleaf + 273.15
181
+ #'
182
+ #' # Fit all models, set Hd to constant in Medlyn model
183
+ #' out <- fit_t_response(
184
+ #' data = pars[pars$ID == "S2", ],
185
+ #' varnames = list(
186
+ #' Par = "V_cmax",
187
+ #' T_leaf = "T_leaf"
188
+ #' ),
189
+ #' setvar = "Hd",
190
+ #' hdset = 200000
191
+ #' )
192
+ #'
193
+ #' out[["Arrhenius"]][["Graph"]]
194
+ #' out[["Heskel"]][["Graph"]]
195
+ #' out[["Kruse"]][["Graph"]]
196
+ #' out[["Medlyn"]][["Graph"]]
197
+ #' out[["MMRT"]][["Graph"]]
198
+ #' out[["Quadratic"]][["Graph"]]
199
+ #' out[["Topt"]][["Graph"]]
200
+ #' }
201
+ fit_t_response <- function(data,
202
+ varnames = list(
203
+ Par = "Par",
204
+ T_leaf = "T_leaf"
205
+ ),
206
+ model = c(
207
+ "Arrhenius",
208
+ "Kruse",
209
+ "Heskel",
210
+ "Medlyn",
211
+ "MMRT",
212
+ "Quadratic",
213
+ "Topt"
214
+ ),
215
+ start = list(
216
+ a = 1,
217
+ b = 1,
218
+ c = 1,
219
+
220
+ dEa = 1,
221
+ Ea_ref = 1,
222
+ Par_ref = 1,
223
+
224
+ Ea = 40000,
225
+ Par25 = 50,
226
+ Hd = 200000,
227
+ dS = 650,
228
+
229
+ dCp = 1,
230
+ dG = 1,
231
+ dH = 1
232
+ ),
233
+ setvar = "none",
234
+ hdset = 200000,
235
+ dSset = 650,
236
+ title = NULL,
237
+ ...) {
238
+ # Check: are the models available?
239
+ if (TRUE %in% c(!model %in% c(
240
+ "Arrhenius",
241
+ "Kruse",
242
+ "Heskel",
243
+ "Medlyn",
244
+ "MMRT",
245
+ "Quadratic",
246
+ "Topt"
247
+ ))) {
248
+ stop("Specified model is not available. Current supported models are
249
+ Arrhenius, Kruse, Heskel, Medlyn, MMRT, Quadratic, and Topt.")
250
+ }
251
+ # Locally bind variables - avoids notes on check package
252
+ Par <- NULL
253
+ T_leaf <- NULL
254
+ # Set variable names
255
+ data$Par <- data[, varnames$Par]
256
+ data$T_leaf <- data[, varnames$T_leaf]
257
+ # Create empty list for number of output elements
258
+ models <- vector("list", length(model))
259
+ names(models) <- model
260
+ # Arrhenius model
261
+ if ("Arrhenius" %in% model) {
262
+ models[["Arrhenius"]] <- vector("list", 3)
263
+ try(models[["Arrhenius"]][[1]] <- nlsLM(
264
+ data = data,
265
+ Par ~ Par25 *
266
+ t_response_arrhenius(Ea,
267
+ T_leaf = T_leaf
268
+ ),
269
+ start = start[c("Ea", "Par25")],
270
+ lower = c(0, 0),
271
+ upper = c(1e10, 10 * max(data$Par)),
272
+ control = nls.control(maxiter = 100),
273
+ ...
274
+ ))
275
+ # Add parameter outputs to output list
276
+ # Assign coefficients to element 2
277
+ if (is.null(models[["Arrhenius"]][[1]]) == TRUE) {
278
+ models[["Arrhenius"]][[2]] <- data.frame(cbind("NA", "NA"))
279
+ colnames(models[["Arrhenius"]][[2]]) <- c("Ea", "Par25")
280
+ } else {
281
+ models[["Arrhenius"]][[2]] <- data.frame(rbind(coef(models[["Arrhenius"]][[1]])))
282
+ }
283
+ # Add graph to output list
284
+ models[["Arrhenius"]][[3]] <- ggplot(data, aes(x = T_leaf, y = Par)) +
285
+ # Add axis labels
286
+ labs(
287
+ x = expression("T_leaf (K)"),
288
+ y = varnames$Par
289
+ ) +
290
+ # Add title
291
+ ggtitle(label = title) +
292
+ # Add fitted smoothing function
293
+ geom_smooth(
294
+ method = "lm",
295
+ formula = y ~ I(models[["Arrhenius"]][[2]]$Par25[1] *
296
+ (t_response_arrhenius(
297
+ T_leaf = x,
298
+ Ea = models[["Arrhenius"]][[2]]$Ea[1]
299
+ ))),
300
+ size = 2
301
+ ) +
302
+ # Add points
303
+ geom_point(size = 2) +
304
+ # Use clean theme
305
+ theme_bw()
306
+ # Name outputs
307
+ names(models[["Arrhenius"]]) <- c("Model", "Parameters", "Graph")
308
+ }
309
+ # Heskel model
310
+ if ("Heskel" %in% model) {
311
+ models[["Heskel"]] <- vector("list", 3)
312
+ try(models[["Heskel"]][[1]] <- nlsLM(
313
+ data = data,
314
+ log(Par) ~
315
+ t_response_heskel(a,
316
+ b,
317
+ c,
318
+ T_leaf = T_leaf
319
+ ),
320
+ start = start[c("a", "b", "c")],
321
+ control =
322
+ nls.control(maxiter = 100),
323
+ ...
324
+ ))
325
+ # Add parameter outputs to output list
326
+ # Assign coefficients to element 2
327
+ if (is.null(models[["Heskel"]][[1]]) == TRUE) {
328
+ models[["Heskel"]][[2]] <- data.frame(cbind("NA", "NA", "NA"))
329
+ colnames(models[["Heskel"]][[2]]) <- c("a", "b", "c")
330
+ } else {
331
+ models[["Heskel"]][[2]] <- data.frame(rbind(coef(models[["Heskel"]][[1]])))
332
+ }
333
+ # Add graph to output list
334
+ models[["Heskel"]][[3]] <- ggplot(data, aes(x = T_leaf, y = Par)) +
335
+ # Add axis labels
336
+ labs(
337
+ x = expression("T_leaf (K)"),
338
+ y = varnames$Par
339
+ ) +
340
+ # Add title
341
+ ggtitle(label = title) +
342
+ # Add fitted smoothing function
343
+ geom_smooth(
344
+ method = "lm",
345
+ formula = y ~ exp(t_response_heskel(
346
+ T_leaf = x,
347
+ a = models[["Heskel"]][[2]]$a[1],
348
+ b = models[["Heskel"]][[2]]$b[1],
349
+ c = models[["Heskel"]][[2]]$c[1]
350
+ )),
351
+ size = 2
352
+ ) +
353
+ # Add points
354
+ geom_point(size = 2) +
355
+ # Use clean theme
356
+ theme_bw()
357
+ # Name outputs
358
+ names(models[["Heskel"]]) <- c("Model", "Parameters", "Graph")
359
+ }
360
+ # Kruse model
361
+ if ("Kruse" %in% model) {
362
+ models[["Kruse"]] <- vector("list", 3)
363
+ data$T2 <- ((data$T_leaf) - 298.15) /
364
+ ((data$T_leaf) * 298.15)
365
+ try(models[["Kruse"]][[1]] <- nlsLM(
366
+ data = data,
367
+ log(Par) ~
368
+ t_response_arrhenius_kruse(dEa,
369
+ Ea_ref,
370
+ Par_ref,
371
+ T2 = T2
372
+ ),
373
+ start = start[c(
374
+ "dEa",
375
+ "Ea_ref",
376
+ "Par_ref"
377
+ )],
378
+ control = nls.control(maxiter = 100),
379
+ ...
380
+ ))
381
+ # Add parameter outputs to output list
382
+ # Assign coefficients to element 2
383
+ if (is.null(models[["Kruse"]][[1]]) == TRUE) {
384
+ models[["Kruse"]][[2]] <- data.frame(cbind("NA", "NA", "NA"))
385
+ colnames(models[["Kruse"]][[2]]) <- c("dEa", "Ea_ref", "Par_ref")
386
+ } else {
387
+ models[["Kruse"]][[2]] <- data.frame(rbind(coef(models[["Kruse"]][[1]])))
388
+ }
389
+ # Add graph to output list
390
+ models[["Kruse"]][[3]] <- ggplot(data, aes(x = T_leaf, y = Par)) +
391
+ # Add axis labels
392
+ labs(
393
+ x = expression("T_leaf (K)"),
394
+ y = varnames$Par
395
+ ) +
396
+ # Add title
397
+ ggtitle(label = title) +
398
+ # Add fitted smoothing function
399
+ geom_smooth(
400
+ method = "lm",
401
+ formula = y ~
402
+ exp(t_response_arrhenius_kruse(
403
+ T2 = ((x) - 298.15) /
404
+ ((x) * 298.15),
405
+ dEa = models[["Kruse"]][[2]]$dEa[1],
406
+ Ea_ref = models[["Kruse"]][[2]]$Ea_ref[1],
407
+ Par_ref = models[["Kruse"]][[2]]$Par_ref[1]
408
+ )),
409
+ size = 2
410
+ ) +
411
+ # Add points
412
+ geom_point(size = 2) +
413
+ # Use clean theme
414
+ theme_bw()
415
+ # Name outputs
416
+ names(models[["Kruse"]]) <- c("Model", "Parameters", "Graph")
417
+ }
418
+ # Medlyn model
419
+ if ("Medlyn" %in% model) {
420
+ models[["Medlyn"]] <- vector("list", 3)
421
+ # Fit both Hd and dS
422
+ if (setvar == "none") {
423
+ # Basically, use Arrhenius curve to feed Ea into Medlyn function start
424
+ # Try approach where you start Hd from 1 to 1000
425
+ # select minimum residual
426
+ modeltest <- nlsLM(
427
+ data = data,
428
+ Par ~ Par25 * t_response_arrhenius(Ea,
429
+ T_leaf = T_leaf
430
+ ),
431
+ start = start[c("Ea", "Par25")],
432
+ lower = c(0, 0),
433
+ upper = c(1e10, 10 * max(data$Par)),
434
+ control = nls.control(maxiter = 100)
435
+ )
436
+ # Create empty dataframe to fill with 1000 curve fits
437
+ model_fm <- as.data.frame(cbind(
438
+ rep(0, 1000),
439
+ rep(0, 1000),
440
+ rep(0, 1000),
441
+ rep(0, 1000),
442
+ rep(0, 1000),
443
+ rep(varnames$Par[[1]], 1000)
444
+ ))
445
+ # Assign column names
446
+ colnames(model_fm) <- c("Ea", "Hd", "Par25", "dS", "residual", "Parameter")
447
+ # Make sure variabel classes are appropriate
448
+ model_fm$Ea <- as.double(model_fm$Ea)
449
+ model_fm$Hd <- as.double(model_fm$Hd)
450
+ model_fm$dS <- as.double(model_fm$dS)
451
+ model_fm$Par25 <- as.double(model_fm$Par25)
452
+ model_fm$residual <- as.double(model_fm$residual)
453
+ model_full <- vector("list", 1000)
454
+ # Run through 1000 instances of the model
455
+ # TryCatch is used to deal with failed fits
456
+ for (i in 1:1000) {
457
+ # Fit model
458
+ model_full[[i]] <- tryCatch(nlsLM(
459
+ data = data,
460
+ Par ~ Par25 *
461
+ t_response_arrhenius_medlyn(Ea,
462
+ Hd,
463
+ dS,
464
+ T_leaf =
465
+ T_leaf
466
+ ),
467
+ start = list(
468
+ Ea = coef(modeltest)[["Ea"]],
469
+ Hd = i * 1000,
470
+ dS = dSset,
471
+ Par25 = coef(modeltest)[["Par25"]]
472
+ ),
473
+ lower = c(0, 0, 0, 0),
474
+ upper = c(
475
+ 1000000, 2000000, 20000,
476
+ 1.5 * max(data$Par)
477
+ ),
478
+ control = nls.control(maxiter = 100)
479
+ ),
480
+ error = function(e) paste(NA)
481
+ )
482
+ # Extract coefficients
483
+ model_fm$Ea[i] <- tryCatch(coef(model_full[[i]])[["Ea"]],
484
+ error = function(e) paste(NA)
485
+ )
486
+ model_fm$Hd[i] <- tryCatch(coef(model_full[[i]])[["Hd"]],
487
+ error = function(e) paste(NA)
488
+ )
489
+ model_fm$dS[i] <- tryCatch(coef(model_full[[i]])[["dS"]],
490
+ error = function(e) paste(NA)
491
+ )
492
+ model_fm$Par25[i] <- tryCatch(coef(model_full[[i]])[["Par25"]],
493
+ error = function(e) paste(NA)
494
+ )
495
+ model_fm$residual[i] <- tryCatch(sum((model_full[[i]]$m$resid())^2),
496
+ error = function(e) paste(NA)
497
+ )
498
+ }
499
+ # Ensure variable classes are appropriate
500
+ model_fm$Ea <- as.double(model_fm$Ea)
501
+ model_fm$Hd <- as.double(model_fm$Hd)
502
+ model_fm$dS <- as.double(model_fm$dS)
503
+ model_fm$Par25 <- as.double(model_fm$Par25)
504
+ model_fm$residual <- as.double(model_fm$residual)
505
+ # Select best model with minimum residuals
506
+ model_fm <- model_fm[is.na(model_fm$residual) == FALSE, ]
507
+ model_fm <- model_fm[model_fm$Ea != 1000000, ]
508
+ model_fm <- model_fm[model_fm$Hd != 2000000, ]
509
+ model_fm <- model_fm[model_fm$dS != 20000, ]
510
+ model_fm <- model_fm[model_fm$residual == min(model_fm$residual), ]
511
+ model_full <- model_full[[as.numeric(rownames(model_fm))]]
512
+ # Add model to output list
513
+ models[["Medlyn"]][[1]] <- model_full
514
+ # Add parameter outputs to output list
515
+ models[["Medlyn"]][[2]] <- data.frame(rbind(coef(model_full)))
516
+ models[["Medlyn"]][[2]]$T_leaf <- mean(data$T_leaf)
517
+ # Add graph to output list
518
+ models[["Medlyn"]][[3]] <- ggplot(data, aes(x = T_leaf, y = Par)) +
519
+ # Add axis labels
520
+ labs(
521
+ x = expression("T_leaf (K)"),
522
+ y = varnames$Par
523
+ ) +
524
+ # Add title
525
+ ggtitle(label = title) +
526
+ # Add fitted smoothing function
527
+ geom_smooth(
528
+ method = "lm",
529
+ formula = y ~ I(models[["Medlyn"]][[2]]$Par25[1] *
530
+ t_response_arrhenius_medlyn(
531
+ T_leaf = x,
532
+ Ea = models[["Medlyn"]][[2]]$Ea[1],
533
+ Hd = models[["Medlyn"]][[2]]$Hd[1],
534
+ dS = models[["Medlyn"]][[2]]$dS[1]
535
+ )),
536
+ size = 2
537
+ ) +
538
+ # Add points
539
+ geom_point(size = 2) +
540
+ # Use clean theme
541
+ theme_bw()
542
+ # Name outputs
543
+ names(models[["Medlyn"]]) <- c("Model", "Parameters", "Graph")
544
+ }
545
+ # Just fit dS
546
+ if (setvar == "Hd") {
547
+ # Basically, use Arrhenius curve to feed Ea into Medlyn function start
548
+ # Try approach where you start Hd from 1 to 1000
549
+ # select minimum residual
550
+ modeltest <- nlsLM(
551
+ data = data,
552
+ Par ~ Par25 * t_response_arrhenius(Ea,
553
+ T_leaf = T_leaf
554
+ ),
555
+ start = start[c("Ea", "Par25")],
556
+ lower = c(0, 0),
557
+ upper = c(1e10, 10 * max(data$Par)),
558
+ control = nls.control(maxiter = 100)
559
+ )
560
+ # Create empty dataframe to fill with 1000 curve fits
561
+ model_fm <- as.data.frame(cbind(
562
+ rep(0, 1000),
563
+ rep(0, 1000),
564
+ rep(0, 1000),
565
+ rep(0, 1000),
566
+ rep(0, 1000),
567
+ rep(varnames$Par[[1]], 1000)
568
+ ))
569
+ # Assign column names
570
+ colnames(model_fm) <- c("Ea", "Hd", "Par25", "dS", "residual", "Parameter")
571
+ # Make sure variabel classes are appropriate
572
+ model_fm$Ea <- as.double(model_fm$Ea)
573
+ model_fm$Hd <- as.double(model_fm$Hd)
574
+ model_fm$dS <- as.double(model_fm$dS)
575
+ model_fm$Par25 <- as.double(model_fm$Par25)
576
+ model_fm$residual <- as.double(model_fm$residual)
577
+ model_full <- vector("list", 1000)
578
+ # Run through 1000 instances of the model
579
+ # TryCatch is used to deal with failed fits
580
+ for (i in 1:1000) {
581
+ # Fit model
582
+ model_full[[i]] <- tryCatch(nlsLM(
583
+ data = data,
584
+ Par ~ Par25 *
585
+ t_response_arrhenius_medlyn(Ea,
586
+ Hd = hdset,
587
+ dS,
588
+ T_leaf =
589
+ T_leaf
590
+ ),
591
+ start = list(
592
+ Ea = coef(modeltest)[["Ea"]],
593
+ dS = i,
594
+ Par25 = coef(modeltest)[["Par25"]]
595
+ ),
596
+ lower = c(0, 0, 0),
597
+ upper = c(
598
+ 1000000, 20000,
599
+ 1.5 * max(data$Par)
600
+ ),
601
+ control = nls.control(maxiter = 100)
602
+ ),
603
+ error = function(e) paste(NA)
604
+ )
605
+ # Extract coefficients
606
+ model_fm$Ea[i] <- tryCatch(coef(model_full[[i]])[["Ea"]],
607
+ error = function(e) paste(NA)
608
+ )
609
+ model_fm$Hd[i] <- hdset
610
+ model_fm$Par25[i] <- tryCatch(coef(model_full[[i]])[["Par25"]],
611
+ error = function(e) paste(NA)
612
+ )
613
+ model_fm$dS[i] <- tryCatch(coef(model_full[[i]])[["dS"]],
614
+ error = function(e) paste(NA)
615
+ )
616
+ model_fm$residual[i] <- tryCatch(sum((model_full[[i]]$m$resid())^2),
617
+ error = function(e) paste(NA)
618
+ )
619
+ }
620
+ # Ensure variable classes are appropriate
621
+ model_fm$Ea <- as.double(model_fm$Ea)
622
+ model_fm$Hd <- as.double(model_fm$Hd)
623
+ model_fm$dS <- as.double(model_fm$dS)
624
+ model_fm$Par25 <- as.double(model_fm$Par25)
625
+ model_fm$residual <- as.double(model_fm$residual)
626
+ # Select best model with minimum residuals
627
+ model_fm <- model_fm[is.na(model_fm$residual) == FALSE, ]
628
+ model_fm <- model_fm[model_fm$Ea != 1000000, ]
629
+ model_fm <- model_fm[model_fm$dS != 20000, ]
630
+ model_fm <- model_fm[model_fm$residual == min(model_fm$residual), ]
631
+ model_full <- model_full[[as.numeric(rownames(model_fm))]]
632
+ # Add model to output list
633
+ models[["Medlyn"]][[1]] <- model_full
634
+ # Add parameter outputs to output list
635
+ models[["Medlyn"]][[2]] <- data.frame(rbind(coef(model_full)))
636
+ models[["Medlyn"]][[2]]$Hd <- hdset
637
+ models[["Medlyn"]][[2]]$T_leaf <- mean(data$T_leaf)
638
+ # Add graph to output list
639
+ models[["Medlyn"]][[3]] <- ggplot(data, aes(x = T_leaf, y = Par)) +
640
+ # Add axis labels
641
+ labs(
642
+ x = expression("T_leaf (K)"),
643
+ y = varnames$Par
644
+ ) +
645
+ # Add title
646
+ ggtitle(label = title) +
647
+ # Add fitted smoothing function
648
+ geom_smooth(
649
+ method = "lm",
650
+ formula = y ~ I(models[["Medlyn"]][[2]]$Par25[1] *
651
+ t_response_arrhenius_medlyn(
652
+ T_leaf = x,
653
+ Ea = models[["Medlyn"]][[2]]$Ea[1],
654
+ Hd = models[["Medlyn"]][[2]]$Hd[1],
655
+ dS = models[["Medlyn"]][[2]]$dS[1]
656
+ )),
657
+ size = 2
658
+ ) +
659
+ # Add points
660
+ geom_point(size = 2) +
661
+ # Use clean theme
662
+ theme_bw()
663
+ # Name outputs
664
+ names(models[["Medlyn"]]) <- c("Model", "Parameters", "Graph")
665
+ }
666
+ # Just fit Hd
667
+ if (setvar == "dS") {
668
+ # Basically, use Arrhenius curve to feed Ea into Medlyn function start
669
+ # Try approach where you start Hd from 1 to 1000
670
+ # select minimum residual
671
+ modeltest <- nlsLM(
672
+ data = data,
673
+ Par ~ Par25 * t_response_arrhenius(Ea,
674
+ T_leaf = T_leaf
675
+ ),
676
+ start = start[c("Ea", "Par25")],
677
+ lower = c(0, 0),
678
+ upper = c(1e10, 10 * max(data$Par)),
679
+ control = nls.control(maxiter = 100)
680
+ )
681
+ # Create empty dataframe to fill with 1000 curve fits
682
+ model_fm <- as.data.frame(cbind(
683
+ rep(0, 1000),
684
+ rep(0, 1000),
685
+ rep(0, 1000),
686
+ rep(0, 1000),
687
+ rep(0, 1000),
688
+ rep(varnames$Par[[1]], 1000)
689
+ ))
690
+ # Assign column names
691
+ colnames(model_fm) <- c("Ea", "Hd", "Par25", "dS", "residual", "Parameter")
692
+ # Make sure variabel classes are appropriate
693
+ model_fm$Ea <- as.double(model_fm$Ea)
694
+ model_fm$Hd <- as.double(model_fm$Hd)
695
+ model_fm$dS <- as.double(model_fm$dS)
696
+ model_fm$Par25 <- as.double(model_fm$Par25)
697
+ model_fm$residual <- as.double(model_fm$residual)
698
+ model_full <- vector("list", 1000)
699
+ # Run through 1000 instances of the model
700
+ # TryCatch is used to deal with failed fits
701
+ for (i in 1:1000) {
702
+ # Fit model
703
+ model_full[[i]] <- tryCatch(nlsLM(
704
+ data = data,
705
+ Par ~ Par25 *
706
+ t_response_arrhenius_medlyn(Ea,
707
+ Hd,
708
+ dS = dSset,
709
+ T_leaf =
710
+ T_leaf
711
+ ),
712
+ start = list(
713
+ Ea = coef(modeltest)[["Ea"]],
714
+ Hd = i * 1000,
715
+ Par25 = coef(modeltest)[["Par25"]]
716
+ ),
717
+ lower = c(0, 0, 0),
718
+ upper = c(
719
+ 1000000, 2000000,
720
+ 1.5 * max(data$Par)
721
+ ),
722
+ control = nls.control(maxiter = 100)
723
+ ),
724
+ error = function(e) paste(NA)
725
+ )
726
+ # Extract coefficients
727
+ model_fm$Ea[i] <- tryCatch(coef(model_full[[i]])[["Ea"]],
728
+ error = function(e) paste(NA)
729
+ )
730
+ model_fm$Hd[i] <- tryCatch(coef(model_full[[i]])[["Hd"]],
731
+ error = function(e) paste(NA)
732
+ )
733
+ model_fm$Par25[i] <- tryCatch(coef(model_full[[i]])[["Par25"]],
734
+ error = function(e) paste(NA)
735
+ )
736
+ model_fm$dS[i] <- dSset
737
+ model_fm$residual[i] <- tryCatch(sum((model_full[[i]]$m$resid())^2),
738
+ error = function(e) paste(NA)
739
+ )
740
+ }
741
+ # Ensure variable classes are appropriate
742
+ model_fm$Ea <- as.double(model_fm$Ea)
743
+ model_fm$Hd <- as.double(model_fm$Hd)
744
+ model_fm$dS <- as.double(model_fm$dS)
745
+ model_fm$Par25 <- as.double(model_fm$Par25)
746
+ model_fm$residual <- as.double(model_fm$residual)
747
+ # Select best model with minimum residuals
748
+ model_fm <- model_fm[is.na(model_fm$residual) == FALSE, ]
749
+ model_fm <- model_fm[model_fm$Ea != 1000000, ]
750
+ model_fm <- model_fm[model_fm$Hd != 2000000, ]
751
+ model_fm <- model_fm[model_fm$residual == min(model_fm$residual), ]
752
+ model_full <- model_full[[as.numeric(rownames(model_fm))]]
753
+ # Add model to output list
754
+ models[["Medlyn"]][[1]] <- model_full
755
+ # Add parameter outputs to output list
756
+ models[["Medlyn"]][[2]] <- data.frame(rbind(coef(model_full)))
757
+ models[["Medlyn"]][[2]]$dS <- dSset
758
+ models[["Medlyn"]][[2]]$T_leaf <- mean(data$T_leaf)
759
+ # Add graph to output list
760
+ models[["Medlyn"]][[3]] <- ggplot(data, aes(x = T_leaf, y = Par)) +
761
+ # Add axis labels
762
+ labs(
763
+ x = expression("T_leaf (K)"),
764
+ y = varnames$Par
765
+ ) +
766
+ # Add title
767
+ ggtitle(label = title) +
768
+ # Add fitted smoothing function
769
+ geom_smooth(
770
+ method = "lm",
771
+ formula = y ~ I(models[["Medlyn"]][[2]]$Par25[1] *
772
+ t_response_arrhenius_medlyn(
773
+ T_leaf = x,
774
+ Ea = models[["Medlyn"]][[2]]$Ea[1],
775
+ Hd = models[["Medlyn"]][[2]]$Hd[1],
776
+ dS = models[["Medlyn"]][[2]]$dS[1]
777
+ )),
778
+ size = 2
779
+ ) +
780
+ # Add points
781
+ geom_point(size = 2) +
782
+ # Use clean theme
783
+ theme_bw()
784
+ # Name outputs
785
+ names(models[["Medlyn"]]) <- c("Model", "Parameters", "Graph")
786
+ }
787
+ }
788
+ # MMRT model
789
+ if ("MMRT" %in% model) {
790
+ models[["MMRT"]] <- vector("list", 3)
791
+ try(models[["MMRT"]][[1]] <- nlsLM(
792
+ data = data,
793
+ log(Par) ~ t_response_mmrt(dCp,
794
+ dG,
795
+ dH,
796
+ T_leaf = T_leaf
797
+ ),
798
+ start = start[c(
799
+ "dCp",
800
+ "dG",
801
+ "dH"
802
+ )],
803
+ control = nls.control(maxiter = 100),
804
+ ...
805
+ ))
806
+ # Add parameter outputs to output list
807
+ # Assign coefficients to element 2
808
+ if (is.null(models[["MMRT"]][[1]]) == TRUE) {
809
+ models[["MMRT"]][[2]] <- data.frame(cbind("NA", "NA", "NA"))
810
+ colnames(models[["MMRT"]][[2]]) <- c("dCp", "dG", "dH")
811
+ } else {
812
+ models[["MMRT"]][[2]] <- data.frame(rbind(coef(models[["MMRT"]][[1]])))
813
+ }
814
+ # Add graph to output list
815
+ models[["MMRT"]][[3]] <- ggplot(data, aes(x = T_leaf, y = Par)) +
816
+ # Add axis labels
817
+ labs(
818
+ x = expression("T_leaf (K)"),
819
+ y = varnames$Par
820
+ ) +
821
+ # Add title
822
+ ggtitle(label = title) +
823
+ # Add fitted smoothing function
824
+ geom_smooth(
825
+ method = "lm",
826
+ formula = y ~ exp(
827
+ t_response_mmrt(
828
+ T_leaf = x,
829
+ dCp = models[["MMRT"]][[2]]$dCp[1],
830
+ dG = models[["MMRT"]][[2]]$dG[1],
831
+ dH = models[["MMRT"]][[2]]$dH[1]
832
+ )
833
+ ),
834
+ size = 2
835
+ ) +
836
+ # Add points
837
+ geom_point(size = 2) +
838
+ # Use clean theme
839
+ theme_bw()
840
+ # Name outputs
841
+ names(models[["MMRT"]]) <- c("Model", "Parameters", "Graph")
842
+ }
843
+ # Quadratic model
844
+ if ("Quadratic" %in% model) {
845
+ models[["Quadratic"]] <- vector("list", 3)
846
+ try(models[["Quadratic"]][[1]] <- nlsLM(
847
+ data = data,
848
+ Par ~ t_response_heskel(a,
849
+ b,
850
+ c,
851
+ T_leaf = T_leaf
852
+ ),
853
+ start = start[c("a", "b", "c")],
854
+ control = nls.control(maxiter = 100),
855
+ ...
856
+ ))
857
+ # Add parameter outputs to output list
858
+ # Assign coefficients to element 2
859
+ if (is.null(models[["Quadratic"]][[1]]) == TRUE) {
860
+ models[["Quadratic"]][[2]] <- data.frame(cbind("NA", "NA", "NA"))
861
+ colnames(models[["Quadratic"]][[2]]) <- c("a", "b", "c")
862
+ } else {
863
+ models[["Quadratic"]][[2]] <- data.frame(rbind(coef(models[["Quadratic"]][[1]])))
864
+ }
865
+ # Add graph to output list
866
+ models[["Quadratic"]][[3]] <- ggplot(data, aes(x = T_leaf, y = Par)) +
867
+ # Add axis labels
868
+ labs(
869
+ x = expression("T_leaf (K)"),
870
+ y = varnames$Par
871
+ ) +
872
+ # Add title
873
+ ggtitle(label = title) +
874
+ # Add fitted smoothing function
875
+ geom_smooth(
876
+ method = "lm",
877
+ formula = y ~ (t_response_heskel(
878
+ T_leaf = x,
879
+ a = models[["Quadratic"]][[2]]$a[1],
880
+ b = models[["Quadratic"]][[2]]$b[1],
881
+ c = models[["Quadratic"]][[2]]$c[1]
882
+ )),
883
+ size = 2
884
+ ) +
885
+ # Add points
886
+ geom_point(size = 2) +
887
+ # Use clean theme
888
+ theme_bw()
889
+ # Name outputs
890
+ names(models[["Quadratic"]]) <- c("Model", "Parameters", "Graph")
891
+ }
892
+ # Topt model
893
+ if ("Topt" %in% model) {
894
+ models[["Topt"]] <- vector("list", 3)
895
+ modeltest <- nlsLM(
896
+ data = data,
897
+ Par ~ Par25 * t_response_arrhenius(Ea,
898
+ T_leaf = T_leaf
899
+ ),
900
+ start = start[c("Ea", "Par25")],
901
+ lower = c(0, 0),
902
+ upper = c(1e10, 10 * max(data$Par)),
903
+ control = nls.control(maxiter = 100)
904
+ )
905
+ # Create empty dataframe to fill with 1000 curve fits
906
+ model_fm <- as.data.frame(cbind(
907
+ rep(0, 1000),
908
+ rep(0, 1000),
909
+ rep(0, 1000),
910
+ rep(0, 1000),
911
+ rep(0, 1000),
912
+ rep(varnames$Par[[1]], 1000)
913
+ ))
914
+ # Assign column names
915
+ colnames(model_fm) <- c(
916
+ "Ea", "Hd", "kopt", "Topt", "residual",
917
+ "Parameter"
918
+ )
919
+ # Make sure variable classes are appropriate
920
+ model_fm$Ea <- as.double(model_fm$Ea)
921
+ model_fm$Hd <- as.double(model_fm$Hd)
922
+ model_fm$kopt <- as.double(model_fm$kopt)
923
+ model_fm$Topt <- as.double(model_fm$Topt)
924
+ model_fm$residual <- as.double(model_fm$residual)
925
+ model_full <- vector("list", 1000)
926
+ # Run through 1000 instances of the model
927
+ # TryCatch is used to deal with failed fits
928
+ for (i in 1:1000) {
929
+ # Fit model
930
+ model_full[[i]] <- tryCatch(nlsLM(
931
+ data = data,
932
+ Par ~ kopt *
933
+ t_response_arrhenius_topt(Ea,
934
+ Hd,
935
+ Topt,
936
+ T_leaf =
937
+ T_leaf
938
+ ),
939
+ start = list(
940
+ Ea = coef(modeltest)[["Ea"]],
941
+ Hd = i * 1000,
942
+ kopt = max(data$Par),
943
+ Topt = max(data$T_leaf)
944
+ ),
945
+ lower = c(0, 0, 0, 0),
946
+ upper = c(
947
+ 1000000, 2000000, max(data$Par) + 1,
948
+ max(data$T_leaf) + 1
949
+ ),
950
+ control = nls.control(maxiter = 100)
951
+ ),
952
+ error = function(e) paste(NA)
953
+ )
954
+ # Extract coefficients
955
+ model_fm$Ea[i] <- tryCatch(coef(model_full[[i]])[["Ea"]],
956
+ error = function(e) paste(NA)
957
+ )
958
+ model_fm$Hd[i] <- tryCatch(coef(model_full[[i]])[["Hd"]],
959
+ error = function(e) paste(NA)
960
+ )
961
+ model_fm$kopt[i] <- tryCatch(coef(model_full[[i]])[["kopt"]],
962
+ error = function(e) paste(NA)
963
+ )
964
+ model_fm$Topt[i] <- tryCatch(coef(model_full[[i]])[["Topt"]],
965
+ error = function(e) paste(NA)
966
+ )
967
+ model_fm$residual[i] <- tryCatch(sum((model_full[[i]]$m$resid())^2),
968
+ error = function(e) paste(NA)
969
+ )
970
+ }
971
+ # Ensure variable classes are appropriate
972
+ model_fm$Ea <- as.double(model_fm$Ea)
973
+ model_fm$Hd <- as.double(model_fm$Hd)
974
+ model_fm$kopt <- as.double(model_fm$kopt)
975
+ model_fm$Topt <- as.double(model_fm$Topt)
976
+ model_fm$residual <- as.double(model_fm$residual)
977
+ # Select best model with minimum residuals
978
+ model_fm <- model_fm[is.na(model_fm$residual) == FALSE, ]
979
+ model_fm <- model_fm[model_fm$Ea != 1000000, ]
980
+ model_fm <- model_fm[model_fm$Hd != 2000000, ]
981
+ model_fm <- model_fm[model_fm$residual == min(model_fm$residual), ]
982
+ model_full <- model_full[[as.numeric(rownames(model_fm))]]
983
+ # Add model to output list
984
+ models[["Topt"]][[1]] <- model_full
985
+ # Add parameter outputs to output list
986
+ models[["Topt"]][[2]] <- data.frame(rbind(coef(model_full)))
987
+ # Add graph to output list
988
+ models[["Topt"]][[3]] <- ggplot(data, aes(x = T_leaf, y = Par)) +
989
+ # Add axis labels
990
+ labs(
991
+ x = expression("T_leaf (K)"),
992
+ y = varnames$Par
993
+ ) +
994
+ # Add title
995
+ ggtitle(label = title) +
996
+ # Add fitted smoothing function
997
+ geom_smooth(
998
+ method = "lm",
999
+ formula = y ~ I(models[["Topt"]][[2]]$kopt[1] *
1000
+ (t_response_arrhenius_topt(
1001
+ T_leaf = x,
1002
+ Ea = models[["Topt"]][[2]]$Ea[1],
1003
+ Hd = models[["Topt"]][[2]]$Hd[1],
1004
+ Topt = models[["Topt"]][[2]]$Topt[1]
1005
+ ))),
1006
+ size = 2
1007
+ ) +
1008
+ # Add points
1009
+ geom_point(size = 2) +
1010
+ # Use clean theme
1011
+ theme_bw()
1012
+ # Name outputs
1013
+ names(models[["Topt"]]) <- c("Model", "Parameters", "Graph")
1014
+ }
1015
+ return(models)
1016
+ }
data/R/gs_models.R ADDED
@@ -0,0 +1,77 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #' Stomatal conductance models
2
+ #'
3
+ #' @param A_net Net CO2 assimilation in umol m-2 s-1
4
+ #' @param C_air CO2 concentration at the leaf surface in umol mol-1
5
+ #' @param RH Relative humidity as a proportion
6
+ #'
7
+ #' @param D0 Vapor pressure sensitivity of stomata (Leuning 1995)
8
+ #' @param VPD Vapor pressure deficit (kPa)
9
+ #'
10
+ #' @param g0 Optimization model intercept term (Medlyn et al. 2011)
11
+ #' @param g1 Optimization model slope term (Medlyn et al. 2011)
12
+ #' @param gk Optimization model root term (Medlyn et al. 2011)
13
+ #'
14
+ #'
15
+ #' @return gs_mod_ballberry is used for fitting the Ball et al. (1987) model
16
+ #' of stomatal conductance
17
+ #'
18
+ #' gs_mod_leuning is used for fitting the Leuning (1995) model
19
+ #' of stomatal conductance
20
+ #'
21
+ #' gs_mod_opti fits the optimal stomatal conductance model according to
22
+ #' Medlyn et al. 2011
23
+ #'
24
+ #' gs_mod_optifull fits the full optimal stomatal conductance model according
25
+ #' to Medlyn et al. 2011
26
+ #'
27
+ #' @references
28
+ #'
29
+ #' Ball JT, Woodrow IE, Berry JA. 1987. A model predicting stomatal
30
+ #' conductance and its contribution to the control of photosynthesis
31
+ #' under different environmental conditions, in Progress in
32
+ #' Photosynthesis Research, Proceedings of the VII International
33
+ #' Congress on Photosynthesis, vol. 4, edited by I. Biggins, pp.
34
+ #' 221–224, Martinus Nijhoff, Dordrecht, Netherlands.
35
+ #'
36
+ #' Leuning R. 1995. A critical appraisal of a coupled stomatal-
37
+ #' photosynthesis model for C3 plants. Plant Cell Environ 18:339-357
38
+ #'
39
+ #' Medlyn BE, Duursma RA, Eamus D, Ellsworth DS, Prentice IC, Barton
40
+ #' CVM, Crous KY, Angelis PD, Freeman M, Wingate L. 2011. Reconciling
41
+ #' the optimal and empirical approaches to modeling stomatal
42
+ #' conductance. Glob Chang Biol 17:2134-2144
43
+ #'
44
+ #' @rdname gs_models
45
+ #' @export
46
+ gs_mod_ballberry <- function(A_net,
47
+ C_air,
48
+ RH) {
49
+ A_net * C_air * RH
50
+ }
51
+ #' @rdname gs_models
52
+ #' @export
53
+ gs_mod_leuning <- function(A_net,
54
+ C_air,
55
+ D0,
56
+ VPD) {
57
+ A_net / (C_air * (1 + VPD * D0))
58
+ }
59
+ #' @rdname gs_models
60
+ #' @export
61
+ gs_mod_opti <- function(g0,
62
+ g1,
63
+ VPD,
64
+ A_net,
65
+ C_air) {
66
+ g0 + 1.6 * (1 + g1 / sqrt(VPD)) * (A_net / C_air)
67
+ }
68
+ #' @rdname gs_models
69
+ #' @export
70
+ gs_mod_optifull <- function(g0,
71
+ g1,
72
+ gk,
73
+ VPD,
74
+ A_net,
75
+ C_air) {
76
+ g0 + 1.6 * (1 + g1 / VPD^(1 - gk)) * (A_net / C_air)
77
+ }
data/R/j_calculations.R ADDED
@@ -0,0 +1,35 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #' Inverse non-rectangular hyperbola for J_max calculation
2
+ #'
3
+ #' @param PPFD light intensity in umol m-2 s-1
4
+ #' @param alpha initial slope of the light response
5
+ #' @param J electron transport rate in umol m-2 s-1
6
+ #' @param J_max maximum rate of electron transport in umol m-2 s-1
7
+ #' @param theta_J curvature of the light response
8
+ #'
9
+ #' @return calculate_jmax calculates J_max given PPFD and J.
10
+ #' It is necessary for the electron transport component of the
11
+ #' fit_aci_response function.
12
+ #'
13
+ #' calculate_j provides a model of the light response of J.
14
+ #' It is necessary for fitting the electron transport component
15
+ #' of the photosynthetic CO2 response curves in fit_aci_response.
16
+ #'
17
+ #' @rdname j_calculations
18
+ #' @export
19
+ calculate_jmax <- function(PPFD,
20
+ alpha,
21
+ J,
22
+ theta_J) {
23
+ J * (J * theta_J - alpha * PPFD) / (J - alpha * PPFD)
24
+ }
25
+
26
+ #' @rdname j_calculations
27
+ #' @export
28
+ calculate_j <- function(PPFD,
29
+ alpha,
30
+ J_max,
31
+ theta_J) {
32
+ (alpha * PPFD + J_max -
33
+ sqrt((alpha * PPFD + J_max)^2 - 4 * alpha * theta_J * PPFD * J_max)) /
34
+ (2 * theta_J)
35
+ }
data/R/leaf-par.R ADDED
@@ -0,0 +1,73 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #' S3 class leaf_par
2
+ #
3
+
4
+ #' @inheritParams photosynthesis
5
+ #' @param .x A list to be constructed into **leaf_par**.
6
+ #'
7
+ #' @returns
8
+ #'
9
+ #' Constructor function for leaf_par class. This function ensures that leaf
10
+ #' parameter inputs are properly formatted.
11
+ #'
12
+ #' @export
13
+ leaf_par = function(.x, use_tealeaves) {
14
+
15
+ which = "leaf"
16
+
17
+ # Message about change of conductance units in version 2.1.0
18
+ check_for_legacy_gunit(.x)
19
+
20
+ # Check parameters names ----
21
+ nms = check_parameter_names(.x, which = which, use_tealeaves = use_tealeaves)
22
+ .x = .x |>
23
+ magrittr::extract(nms) |>
24
+ # Set units ----
25
+ set_parameter_units(
26
+ .data$type == "leaf",
27
+ !.data$temperature_response,
28
+ if (!use_tealeaves) {!.data$tealeaves} else TRUE
29
+ )
30
+
31
+ # Assert bounds on values ----
32
+ .x |>
33
+ assert_parameter_bounds(
34
+ .data$type == which,
35
+ !.data$temperature_response,
36
+ if (!use_tealeaves) {!.data$tealeaves} else TRUE
37
+ )
38
+
39
+ structure(.x, class = c(stringr::str_c(which, "_par"), "list"))
40
+
41
+ }
42
+
43
+ check_for_legacy_gunit = function(pars) {
44
+
45
+ xx = pars |>
46
+ purrr::map(units) |>
47
+ purrr::map_lgl(units::ud_are_convertible, "umol / m^2 / s / Pa") |>
48
+ any()
49
+
50
+ if (xx) {
51
+
52
+ message(
53
+ "
54
+ It looks like one or more of the conductance values is provided in units
55
+ of 'umol / m^2 / s / Pa' or a unit that can be converted to it. This was
56
+ the default in photosynthesis (<= 2.0.3), but we switched to
57
+ 'mol / m^2 / s' because these units are morely widely used in plant
58
+ ecophysiology.
59
+
60
+ To convert, use this code with your desired temperature and pressure:
61
+ g = units::set_units(1, umol / m^2 / s / Pa)
62
+ P = units::set_units(101.3246, kPa)
63
+ Temp = set_units(298.15, K)
64
+ gunit::convert_conductance(g, P = P, Temp = Temp)$`mol/m^2/s`
65
+
66
+ "
67
+ )
68
+ stop("Incorrect conductance units in leaf_par()", call. = FALSE)
69
+ }
70
+
71
+ invisible()
72
+
73
+ }
data/R/make_parameters.R ADDED
@@ -0,0 +1,426 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #' Make lists of parameters for `photosynthesis`
2
+ #'
3
+ #' @param replace A named list of parameters to replace defaults.
4
+ #' If `NULL`, defaults will be used.
5
+ #'
6
+ #' @name make_parameters
7
+ #'
8
+ #' @encoding UTF-8
9
+
10
+ NULL
11
+
12
+ #' make_anypar
13
+ #' @inheritParams make_parameters
14
+ #' @inheritParams parameter_names
15
+ #' @noRd
16
+ make_anypar = function(which, replace, use_tealeaves) {
17
+
18
+ which = match.arg(which, choices = get_par_types())
19
+
20
+ # Message about new conductance model ----
21
+ message_experimental(replace)
22
+
23
+ # Defaults -----
24
+ obj = make_default_parameter_list(
25
+ which = which,
26
+ use_tealeaves = use_tealeaves
27
+ )
28
+
29
+ # Special procedures for constants ---
30
+ if (which == "constants") {
31
+
32
+ if ("f_nu" %in% names(replace)) {
33
+ stopifnot(is.function(replace$f_nu))
34
+ obj$f_nu = replace$f_nu
35
+ replace$f_nu = NULL
36
+ }
37
+
38
+ if ("f_sh" %in% names(replace)) {
39
+ stopifnot(is.function(replace$f_sh))
40
+ obj$f_sh = replace$f_sh
41
+ replace$f_sh = NULL
42
+ }
43
+
44
+ }
45
+
46
+ # Special procedures for enviro_par ----
47
+ if (which == "enviro") {
48
+
49
+ if ("T_sky" %in% names(replace)) {
50
+ if (is.function(replace$T_sky)) {
51
+ obj$T_sky = replace$T_sky
52
+ replace$T_sky = NULL
53
+ }
54
+ }
55
+
56
+ par_equiv = data.frame(
57
+ tl = c("S_sw"),
58
+ ph = c("PPFD")
59
+ )
60
+
61
+ if (any(purrr::map_lgl(replace[par_equiv$tl], ~ !is.null(.x)))) {
62
+ par_equiv %>%
63
+ dplyr::filter(.data$tl %in% names(replace)) %>%
64
+ dplyr::transmute(message = stringr::str_c(
65
+ "\nIn `replace = list(...)`,
66
+ tealeaves parameter ", .data$tl,
67
+ " is not replacable. Use ", .data$ph, " instead."
68
+ )) %>%
69
+ dplyr::pull(.data$message) %>%
70
+ stringr::str_c(collapse = "\n") %>%
71
+ stop(call. = FALSE)
72
+ }
73
+
74
+ }
75
+
76
+ # Special procedures for leaf_par ----
77
+ if (which == "leaf" & use_tealeaves) {
78
+
79
+ par_equiv = get_par_equiv()
80
+
81
+ # Some equivalencies require additional parameters. Therefore leaving
82
+ # those parameter values empty
83
+ tl_placeholders = photosynthesis::photo_parameters |>
84
+ dplyr::filter(.data$R %in% par_equiv$tl) |>
85
+ dplyr::mutate(units = stringr::str_replace(units, "none", "1")) |>
86
+ split(~ R) |>
87
+ purrr::map(function(.y) {
88
+ a = 0
89
+ units(a) = as_units(.y[["units"]])
90
+ a
91
+ })
92
+ obj[names(tl_placeholders)] = tl_placeholders
93
+
94
+ if (!is.null(replace)) {
95
+ if (!is.null(replace$T_leaf)) {
96
+ warning("replace$T_leaf ignored when use_tealeaves is TRUE")
97
+ replace$T_leaf = NULL
98
+ }
99
+
100
+
101
+ if (any(purrr::map_lgl(replace[par_equiv$tl], ~ !is.null(.x)))) {
102
+ par_equiv %>%
103
+ dplyr::filter(.data$tl %in% names(replace)) %>%
104
+ dplyr::transmute(message = stringr::str_c(
105
+ "\nIn `replace = list(...)`,
106
+ tealeaves parameter ", .data$tl, " is not replacable. Use ",
107
+ .data$ph, " instead."
108
+ )) %>%
109
+ dplyr::pull(.data$message) %>%
110
+ stringr::str_c(collapse = "\n") %>%
111
+ stop(call. = FALSE)
112
+ }
113
+ }
114
+ }
115
+
116
+ # Replace defaults ----
117
+ obj %<>% replace_defaults(replace)
118
+
119
+ # Assign class and return ----
120
+ switch(
121
+ which,
122
+ bake = photosynthesis::bake_par(obj),
123
+ constants = photosynthesis::constants(obj, use_tealeaves),
124
+ enviro = photosynthesis::enviro_par(obj, use_tealeaves),
125
+ leaf = photosynthesis::leaf_par(obj, use_tealeaves),
126
+ )
127
+
128
+ }
129
+
130
+ #' make_leafpar
131
+ #' @rdname make_parameters
132
+ #'
133
+ #' @inheritParams photosynthesis
134
+ #'
135
+ #' @return
136
+ #'
137
+ #' `make_leafpar`: An object inheriting from class [leaf_par()]\cr
138
+ #' `make_enviropar`: An object inheriting from class [enviro_par()]\cr
139
+ #' `make_bakepar`: An object inheriting from class [bake_par()]\cr
140
+ #' `make_constants`: An object inheriting from class [constants()]
141
+ #'
142
+ #' @details
143
+ #'
144
+ #' **Constants:**
145
+ #' ```{r, echo=FALSE}
146
+ #' make_photo_parameter_table(type == "constants", !tealeaves)
147
+ #' ```
148
+ #'
149
+ #' **Baking (i.e. temperature response) parameters:**
150
+ #' ```{r, echo=FALSE}
151
+ #' make_photo_parameter_table(type == "bake", !tealeaves)
152
+ #' ```
153
+ #'
154
+ #' **Environment parameters:**
155
+ #' ```{r, echo=FALSE}
156
+ #' make_photo_parameter_table(type == "enviro", !tealeaves)
157
+ #' ```
158
+ #'
159
+ #' **Leaf parameters:**
160
+ #' ```{r, echo=FALSE}
161
+ #' make_photo_parameter_table(type == "leaf", !tealeaves,
162
+ #' is.na(note) | note != "optional")
163
+ #' ```
164
+ #'
165
+ #' If `use_tealeaves = TRUE`, additional parameters are:
166
+ #'
167
+ #' **Constants:**
168
+ #' ```{r, echo=FALSE}
169
+ #' make_photo_parameter_table(type == "constants", tealeaves)
170
+ #' ```
171
+ #'
172
+ #' **Baking (i.e. temperature response) parameters:**
173
+ #' ```{r, echo=FALSE}
174
+ #' make_photo_parameter_table(type == "bake", tealeaves)
175
+ #' ```
176
+ #'
177
+ #' **Environment parameters:**
178
+ #' ```{r, echo=FALSE}
179
+ #' make_photo_parameter_table(type == "enviro", tealeaves)
180
+ #' ```
181
+ #'
182
+ #' **Leaf parameters:**
183
+ #' ```{r, echo=FALSE}
184
+ #' make_photo_parameter_table(type == "leaf", tealeaves)
185
+ #' ```
186
+ #'
187
+ #' **Optional leaf parameters:**
188
+ #'
189
+ #' ```{r, echo=FALSE}
190
+ #' make_photo_parameter_table(type == "leaf", note == "optional")
191
+ #' ```
192
+ #'
193
+ #' @references
194
+ #'
195
+ #' Buckley TN and Diaz-Espejo A. 2015. Partitioning changes in photosynthetic
196
+ #' rate into contributions from different variables. Plant, Cell & Environment
197
+ #' 38: 1200-11.
198
+ #'
199
+ #' @examples
200
+ #' bake_par = make_bakepar()
201
+ #' constants = make_constants(use_tealeaves = FALSE)
202
+ #' enviro_par = make_enviropar(use_tealeaves = FALSE)
203
+ #' leaf_par = make_leafpar(use_tealeaves = FALSE)
204
+ #'
205
+ #' leaf_par = make_leafpar(
206
+ #' replace = list(
207
+ #' g_sc = set_units(0.3, mol / m^2 / s),
208
+ #' V_cmax25 = set_units(100, umol / m^2 / s)
209
+ #' ), use_tealeaves = FALSE
210
+ #' )
211
+ #' @export
212
+ #' @md
213
+
214
+ make_leafpar = function(replace = NULL, use_tealeaves) {
215
+
216
+ make_anypar("leaf", replace = replace, use_tealeaves = use_tealeaves)
217
+
218
+ }
219
+
220
+ #' make_enviropar
221
+ #' @rdname make_parameters
222
+ #' @export
223
+
224
+ make_enviropar = function(replace = NULL, use_tealeaves) {
225
+
226
+ make_anypar("enviro", replace = replace, use_tealeaves = use_tealeaves)
227
+
228
+ }
229
+
230
+ #' make_bakepar
231
+ #' @rdname make_parameters
232
+ #' @export
233
+
234
+ make_bakepar = function(replace = NULL) {
235
+
236
+ make_anypar("bake", replace = replace, use_tealeaves = FALSE)
237
+
238
+ }
239
+
240
+ #' make_constants
241
+ #' @rdname make_parameters
242
+ #' @export
243
+
244
+ make_constants = function(replace = NULL, use_tealeaves) {
245
+
246
+ make_anypar("constants", replace = replace, use_tealeaves = use_tealeaves)
247
+
248
+ }
249
+
250
+ #' Character vector of acceptable parameter types
251
+ #' @noRd
252
+ get_par_types = function() {
253
+ c("bake", "constants", "enviro", "leaf")
254
+ }
255
+
256
+ #' Make default parameter list
257
+ #' @inheritParams parameter_names
258
+ #' @noRd
259
+ make_default_parameter_list = function(which, use_tealeaves) {
260
+
261
+ which = which |>
262
+ match.arg(get_par_types())
263
+
264
+ default_parameter_list = photosynthesis::photo_parameters |>
265
+ dplyr::filter(
266
+ .data$type == which,
267
+ !.data$temperature_response,
268
+ if (!use_tealeaves) {!.data$tealeaves} else TRUE,
269
+ ) |>
270
+ dplyr::mutate(units = stringr::str_replace(units, "none", "1")) |>
271
+ split(~ R) |>
272
+ purrr::map(function(.x) {
273
+ if(is.na(.x$default)) {
274
+ if (.x$note == "optional") {
275
+ a = numeric(0)
276
+ units(a) = as_units(.x$units)
277
+ return(a)
278
+ }
279
+ if (.x$note == "calculated") {
280
+ get_f_parameter(.x$R)
281
+ }
282
+ } else {
283
+ units(.x$default) = as_units(.x$units)
284
+ return(.x$default)
285
+ }
286
+ })
287
+
288
+ default_parameter_list
289
+
290
+ }
291
+
292
+ #' Check parameter names
293
+ #' @inheritParams set_parameter_units
294
+ #' @inheritParams parameter_names
295
+ #' @noRd
296
+ check_parameter_names = function(.x, which, use_tealeaves) {
297
+
298
+ stopifnot(is.list(.x))
299
+
300
+ nms = parameter_names(which, use_tealeaves = use_tealeaves)
301
+
302
+ # Don't fail check if .x is missing tealeaves parameter equivalents
303
+ nms1 = nms[!(nms %in% get_par_equiv()[, "tl"])]
304
+ if (which == "leaf" & use_tealeaves) nms1 = nms1[!(nms1 == "T_leaf")]
305
+
306
+ if (!all(nms1 %in% names(.x))) {
307
+ nms1[!(nms1 %in% names(.x))] |>
308
+ stringr::str_c(collapse = ", ") %>%
309
+ glue::glue("{x} not in parameter names required for {which}",
310
+ x = ., which = which
311
+ ) |>
312
+ stop()
313
+ }
314
+
315
+ nms
316
+
317
+ }
318
+
319
+ #' Set parameter units
320
+ #' @param .x list of parameters to set units
321
+ #' @param ... arguments passed to dplyr::filter()
322
+ #' @noRd
323
+
324
+ set_parameter_units = function(.x, ...) {
325
+
326
+ photosynthesis::photo_parameters |>
327
+ dplyr::filter(...) |>
328
+ dplyr::mutate(units = stringr::str_replace(units, "none", "1")) |>
329
+ split(~ R) |>
330
+ purrr::map(function(.y) {
331
+ v = .x[[.y$R]]
332
+ if (is.function(v)) {
333
+ v
334
+ } else {
335
+ a = if (is.null(v)) {0} else {v}
336
+ units(a) = as_units(.y$units)
337
+ a
338
+ }
339
+ })
340
+
341
+ }
342
+
343
+ #' Assert parameter bounds
344
+ #' @param .x list of parameters
345
+ #' @param ... arguments passed to dplyr::filter()
346
+ #' @noRd
347
+ assert_parameter_bounds = function(.x, ...) {
348
+
349
+ photosynthesis::photo_parameters |>
350
+ dplyr::filter(...) |>
351
+ dplyr::mutate(units = stringr::str_replace(units, "none", "1")) |>
352
+ split(~ R) |>
353
+ purrr::map_lgl(function(.y) {
354
+ if (
355
+ length(.x[[.y$R]]) == 0L |
356
+ is.function(.x[[.y$R]]) |
357
+ is.na(.y$lower) |
358
+ is.na(.y$upper)
359
+ ) {
360
+ TRUE
361
+ } else {
362
+ units(.y$lower) = as_units(.y$units)
363
+ units(.y$upper) = as_units(.y$units)
364
+ all(.x[[.y$R]] >= .y$lower & .x[[.y$R]] <= .y$upper)
365
+ }
366
+ }) |>
367
+ all() |>
368
+ checkmate::assert_true()
369
+
370
+ }
371
+
372
+ #' Message about experimental parameters
373
+ #' @inheritParams replace
374
+ #' @noRd
375
+ message_experimental = function(replace) {
376
+ experimental_leafpar = c(
377
+ "delta_ias_lower",
378
+ "delta_ias_upper",
379
+ "A_mes_A",
380
+ "g_liqc"
381
+ )
382
+ if (any(names(replace) %in% experimental_leafpar)) {
383
+ message(
384
+ "
385
+ It looks like you are using the new CO2 conductance model.
386
+
387
+ As of version 2.1.0, the new CO2 conductance model is experimental and
388
+ may change in new releases. Use with caution.
389
+ ")
390
+ }
391
+ invisible()
392
+ }
393
+
394
+ #' Replace default parameters
395
+ #'
396
+ #' @param obj List of default values
397
+ #' @param replace List of replacement values
398
+ #' @noRd
399
+
400
+ replace_defaults = function(obj, replace) {
401
+ if (!is.null(replace)) {
402
+ stopifnot(is.list(replace))
403
+ stopifnot(all(sapply(replace, inherits, what = "units")))
404
+ stopifnot(all(sapply(replace, is.numeric)))
405
+ x = names(replace)
406
+ if (any(!x %in% names(obj))) {
407
+ warning(sprintf("The following parameters in 'replace' were not
408
+ recognized:\n%s", paste0(x[!x %in% names(obj)],
409
+ collapse = "\n"
410
+ )))
411
+ x %<>% .[. %in% names(obj)]
412
+ }
413
+ obj[x] = replace[x]
414
+ }
415
+
416
+ obj
417
+ }
418
+
419
+ #' Get data.frame of equivalent parameters between tealeaves and photosynthesis
420
+ #' @noRd
421
+ get_par_equiv = function() {
422
+ data.frame(
423
+ tl = c("g_sw", "g_uw", "logit_sr"),
424
+ ph = c("g_sc", "g_uc", "k_sc")
425
+ )
426
+ }
data/R/models.R ADDED
@@ -0,0 +1,109 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #' Get default model
2
+ #'
3
+ #' @rdname models
4
+ #'
5
+ #' @description
6
+ #'
7
+ #' `r lifecycle::badge("experimental")`
8
+ #'
9
+ #' Get the name of the default model used for different plant ecophysiological data analysis methods implemented in **photosynthesis**. Currently only used for [fit_aq_response2()] and [fit_r_light2()].
10
+ #'
11
+ #' @inheritParams fit_photosynthesis
12
+ #'
13
+ #' @return A character string with name of model.
14
+ #'
15
+ #' @examples
16
+ #' get_default_model("aq_response")
17
+ #' get_default_model("r_light")
18
+ #'
19
+ #' @md
20
+ #' @export
21
+ get_default_model = function(.photo_fun) {
22
+ .photo_fun = match.arg(.photo_fun, get_function_types())
23
+ switch(
24
+ .photo_fun,
25
+ aq_response = "marshall_biscoe_1980",
26
+ r_light = "walker_ort_2015"
27
+ )
28
+ }
29
+
30
+ #' @rdname models
31
+ #' @export
32
+ get_all_models = function(method) {
33
+ match.arg(method, get_function_types())
34
+ switch(
35
+ method,
36
+ aq_response = c("marshall_biscoe_1980", "photoinhibition"),
37
+ r_light = c("kok_1956", "walker_ort_2015", "yin_etal_2011")
38
+ )
39
+ }
40
+
41
+ #' @rdname models
42
+ #' @description
43
+ #' **Light response models:**
44
+ #'
45
+ #' * `marshall_biscoe_1980()`: Non-rectangular hyperbolic model of light responses
46
+ #' * `photoinhibition()`: Non-rectangular hyperbolic model of light responses with photoinhibition of `k_sat` at increasing Q_abs
47
+ #'
48
+ #' @param Q_abs Absorbed light intensity (\eqn{\mu}mol m\eqn{^{-2}} s\eqn{^{-1}})
49
+ #' @param k_sat Light saturated rate of process k
50
+ #' @param phi_J Quantum efficiency of process k
51
+ #' @param theta_J Curvature of the light response
52
+ #' @param b_inh Inhibition parameter
53
+ #' @md
54
+ #'
55
+ #' @export
56
+ marshall_biscoe_1980 = function(Q_abs, k_sat, phi_J, theta_J) {
57
+
58
+ ((k_sat + phi_J * Q_abs) -
59
+ sqrt((k_sat + phi_J * Q_abs) ^ 2 - 4 * k_sat * phi_J * Q_abs * theta_J)) /
60
+ (2 * theta_J)
61
+
62
+ }
63
+
64
+ #' @rdname models
65
+ #' @export
66
+ photoinhibition = function(Q_abs, k_sat, phi_J, theta_J, b_inh) {
67
+ k_sat1 = k_sat - b_inh * Q_abs
68
+ marshall_biscoe_1980(Q_abs, k_sat1, phi_J, theta_J)
69
+ }
70
+
71
+ #' Variables required for **photosynthesis** models
72
+ #'
73
+ #' @inheritParams fit_photosynthesis
74
+ #' @export
75
+ required_variables = function(.model, quiet) {
76
+
77
+ .model = match.arg(.model, get_function_types() |>
78
+ purrr::map(get_all_models) |>
79
+ unlist())
80
+ all_vars = list(
81
+ .A = "net CO2 assimilation rate (umol/m^2/s)",
82
+ .C = "intercellular or chloroplastic CO2 concentration (umol/mol)",
83
+ .phiPSII = "quantum efficiency of PSII electron transport (mol / mol)",
84
+ .Q = "irradiance (umol/m^2/s)"
85
+ )
86
+
87
+ model_vars = switch(
88
+ .model,
89
+ kok_1956 = all_vars[c(".A", ".Q")],
90
+ marshall_biscoe_1980 = all_vars[c(".A", ".Q")],
91
+ photoinhibition = all_vars[c(".A", ".Q")],
92
+ walker_ort_2015 = all_vars[c(".A", ".C", ".Q")],
93
+ yin_etal_2011 = all_vars[c(".A", ".phiPSII", ".Q")]
94
+ )
95
+
96
+ if (!quiet) {
97
+ cat(.model, "\n")
98
+ purrr::iwalk(model_vars, ~ {cat(.y, ": ", .x, "\n")})
99
+ }
100
+
101
+ invisible(names(model_vars))
102
+
103
+ }
104
+
105
+ #' Vector of method types
106
+ #' @noRd
107
+ get_function_types = function() {
108
+ c("aq_response", "r_light")
109
+ }
data/R/parameter_names.R ADDED
@@ -0,0 +1,21 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #' Get vector of parameter names
2
+ #'
3
+ #' @inheritParams photosynthesis
4
+ #' @param which A character string indicating which parameter names to retrieve: "leaf", "enviro", "bake", or "constants". Partial matching allowed.
5
+ #'
6
+ #' @returns
7
+ #'
8
+ #' A character vector with parameter names associated with each type, "leaf", "enviro", "bake", or "constants".
9
+ #'
10
+ #' @examples
11
+ #'
12
+ #' parameter_names("leaf", use_tealeaves = FALSE)
13
+ #' @export
14
+ parameter_names = function(which, use_tealeaves) {
15
+
16
+ which |>
17
+ match.arg(get_par_types()) |>
18
+ make_default_parameter_list(use_tealeaves) |>
19
+ names()
20
+
21
+ }
data/R/photosynthesis-package.R ADDED
@@ -0,0 +1,33 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #' `photosynthesis` package
2
+ #'
3
+ #' Tools for Plant Ecophysiology & Modeling
4
+ #'
5
+ #' See the README on
6
+ #' [GitHub](https://github.com/cdmuir/photosynthesis)
7
+ #'
8
+ #' @name photosynthesis-package
9
+ #' @importFrom ggplot2 ggplot
10
+ #' @importFrom magrittr %>% %<>%
11
+ #' @importFrom minpack.lm nlsLM nls.lm.control
12
+ #' @importFrom methods is
13
+ #' @importFrom nlme lmList
14
+ #' @importFrom rlang .data
15
+ #' @importFrom stats coef lm optim plogis resid rnorm
16
+ #' @importFrom units as_units drop_units set_units
17
+ #' @keywords internal
18
+ "_PACKAGE"
19
+ NULL
20
+
21
+ ## quiets concerns of R CMD check re: the .'s that appear in pipelines
22
+ if (getRversion() >= "2.15.1") utils::globalVariables(c("."))
23
+
24
+ ## quiets concerns of R CMD check re: units
25
+ utils::globalVariables(c(
26
+ ".A", ".C", ".phiPSII", ".Q", ".Qabs", "degreeC", "g", "hPa", "J", "K", "kg",
27
+ "kJ", "kPa", "m", "mol", "mmol", "normal", "Pa", "PPFD", "s", "umol", "W"
28
+ ))
29
+
30
+ ## quiets concerns of R CMD check about using ::: operator
31
+ .get_Dx <- utils::getFromNamespace(".get_Dx", "tealeaves")
32
+ .get_gbw <- utils::getFromNamespace(".get_gbw", "tealeaves")
33
+ .get_ps <- utils::getFromNamespace(".get_ps", "tealeaves")
data/R/photosynthesis.R ADDED
@@ -0,0 +1,627 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #' Simulate C3 photosynthesis
2
+ #'
3
+ #' `photosynthesis`: simulate C3 photosynthesis over multiple parameter sets
4
+ #'
5
+ #' @param leaf_par A list of leaf parameters inheriting class `leaf_par`. This can be generated using the `make_leafpar` function.
6
+ #'
7
+ #' @param enviro_par A list of environmental parameters inheriting class `enviro_par`. This can be generated using the `make_enviropar` function.
8
+ #'
9
+ #' @param bake_par A list of temperature response parameters inheriting class `bake_par`. This can be generated using the `make_bakepar` function.
10
+ #'
11
+ #' @param constants A list of physical constants inheriting class `constants`. This can be generated using the `make_constants` function.
12
+ #'
13
+ #' @param use_tealeaves Logical. Should leaf energy balance be used to calculate leaf temperature (T_leaf)? If TRUE, [`tleaf()`][tealeaves::tleaves] calculates T_leaf. If FALSE, user-defined T_leaf is used. Additional parameters and constants are required, see [make_parameters()].
14
+ #'
15
+ #' @param progress Logical. Should a progress bar be displayed?
16
+ #'
17
+ #' @param quiet Logical. Should messages be displayed?
18
+ #'
19
+ #' @param assert_units Logical. Should parameter `units` be checked? The function is faster when FALSE, but input must be in correct units or else results will be incorrect without any warning.
20
+ #'
21
+ #' @param check Logical. Should arguments checks be done? Default is TRUE.
22
+ #'
23
+ #' @param parallel Logical. Should parallel processing be used via [furrr::future_map()]?
24
+ #'
25
+ #' @param use_legacy_version Logical. Should legacy model (<2.1.0) be used? See [NEWS](https://github.com/cdmuir/photosynthesis/blob/master/NEWS.md) for further information. Default is FALSE.
26
+ #'
27
+ #' @return
28
+ #' A data.frame with the following `units` columns \cr
29
+ #'
30
+ #' **Inputs:**
31
+ #' ```{r, echo=FALSE}
32
+ #' make_photo_parameter_table(!temperature_response, !tealeaves)
33
+ #' ```
34
+ #' **Baked Inputs:**
35
+ #' ```{r, echo=FALSE}
36
+ #' make_photo_parameter_table(temperature_response, !tealeaves)
37
+ #' ```
38
+ #'
39
+ #' \tabular{ll}{
40
+ #'
41
+ #' **Output:** \tab \cr
42
+ #' \cr
43
+ #' `A` \tab photosynthetic rate at `C_chl` (\eqn{\mu}mol CO2 / m\eqn{^2} / s) \cr
44
+ #' `C_chl` \tab chloroplastic CO2 concentration where `A_supply` intersects `A_demand` (\eqn{mu}mol / mol) \cr
45
+ #' `C_i` \tab intercellular CO2 concentration where `A_supply` intersects `A_demand` (\eqn{mu}mol / mol) \cr
46
+ #' `g_tc` \tab total conductance to CO2 at `T_leaf` (mol / m\eqn{^2} / s)) \cr
47
+ #' `value` \tab `A_supply` - `A_demand` (\eqn{\mu}mol / (m\eqn{^2} s)) at `C_chl` \cr
48
+ #' `convergence` \tab convergence code (0 = converged)
49
+ #' }
50
+ #'
51
+ #' @details
52
+ #'
53
+ #' `photo`: This function takes simulates photosynthetic rate using the Farquhar-von Caemmerer-Berry ([FvCB()]) model of C3 photosynthesis for single combined set of leaf parameters ([leaf_par()]), environmental parameters ([enviro_par()]), and physical constants ([constants()]). Leaf parameters are provided at reference temperature (25 °C) and then "baked" to the appropriate leaf temperature using temperature response functions (see [bake()]). \cr
54
+ #' \cr
55
+ #' `photosynthesis`: This function uses `photo` to simulate photosynthesis over multiple parameter sets that are generated using [`cross_df()`][purrr::cross]. \cr
56
+ #'
57
+ #' @examples
58
+ #' # Single parameter set with 'photo'
59
+ #'
60
+ #' bake_par = make_bakepar()
61
+ #' constants = make_constants(use_tealeaves = FALSE)
62
+ #' enviro_par = make_enviropar(use_tealeaves = FALSE)
63
+ #' leaf_par = make_leafpar(use_tealeaves = FALSE)
64
+ #' photo(leaf_par, enviro_par, bake_par, constants,
65
+ #' use_tealeaves = FALSE
66
+ #' )
67
+ #'
68
+ #' # Multiple parameter sets with 'photosynthesis'
69
+ #'
70
+ #' leaf_par = make_leafpar(
71
+ #' replace = list(
72
+ #' T_leaf = set_units(c(293.14, 298.15), "K")
73
+ #' ), use_tealeaves = FALSE
74
+ #' )
75
+ #' photosynthesis(leaf_par, enviro_par, bake_par, constants,
76
+ #' use_tealeaves = FALSE
77
+ #' )
78
+ #' @encoding UTF-8
79
+ #'
80
+ #' @export
81
+ #' @md
82
+
83
+ photosynthesis = function(
84
+ leaf_par,
85
+ enviro_par,
86
+ bake_par,
87
+ constants,
88
+ use_tealeaves,
89
+ progress = TRUE,
90
+ quiet = FALSE,
91
+ assert_units = TRUE,
92
+ check = TRUE,
93
+ parallel = FALSE,
94
+ use_legacy_version = FALSE
95
+ ) {
96
+
97
+ # Check arguments ----
98
+ checkmate::assert_flag(check)
99
+
100
+ if (check) {
101
+ checkmate::assert_class(bake_par, "bake_par")
102
+ checkmate::assert_class(constants, "constants")
103
+ checkmate::assert_class(enviro_par, "enviro_par")
104
+ checkmate::assert_class(leaf_par, "leaf_par")
105
+ checkmate::assert_flag(use_tealeaves)
106
+ checkmate::assert_flag(quiet)
107
+ checkmate::assert_flag(assert_units)
108
+ checkmate::assert_flag(parallel)
109
+ checkmate::assert_flag(use_legacy_version)
110
+ }
111
+
112
+ # Message about legacy version ----
113
+ notify_users(quiet = quiet, leaf_par = leaf_par)
114
+
115
+ T_air = NULL
116
+ if (!use_tealeaves && !is.null(enviro_par$T_air)) {
117
+ if (!quiet) {
118
+ message(glue::glue("Both air and leaf temperature are provided and fixed: T_air = {T_air}; T_leaf = {T_leaf}",
119
+ T_air = enviro_par$T_air,
120
+ T_leaf = leaf_par$T_leaf
121
+ ))
122
+ }
123
+ T_air = enviro_par$T_air
124
+ }
125
+
126
+ # Assert units ----
127
+ if (assert_units) {
128
+ bake_par %<>% photosynthesis::bake_par()
129
+ constants %<>% photosynthesis::constants(use_tealeaves)
130
+ enviro_par %<>% photosynthesis::enviro_par(use_tealeaves)
131
+ leaf_par %<>% photosynthesis::leaf_par(use_tealeaves)
132
+ if (!is.null(T_air)) enviro_par$T_air = set_units(T_air, K)
133
+ }
134
+
135
+ # Make parameter sets ----
136
+ pars = make_parameter_sets(leaf_par, enviro_par, bake_par, constants)
137
+
138
+ # Solve ----
139
+ soln = solve_for_photosynthesis(
140
+ pars,
141
+ bake_par,
142
+ constants,
143
+ use_tealeaves,
144
+ progress,
145
+ quiet,
146
+ parallel,
147
+ use_legacy_version
148
+ )
149
+
150
+ # Return ----
151
+ soln
152
+
153
+ }
154
+
155
+ #' Make parameter sets for [photosynthesis()]
156
+ #' @inheritParams photosynthesis
157
+ #' @noRd
158
+ make_parameter_sets = function(
159
+ leaf_par,
160
+ enviro_par,
161
+ bake_par,
162
+ constants
163
+ ) {
164
+
165
+ pars = c(
166
+ purrr::keep(leaf_par, ~ length(.x) > 0),
167
+ purrr::keep(enviro_par, ~ length(.x) > 0)
168
+ ) |>
169
+ purrr::map(~ {if (is.function(.x)) {list(.x)} else {.x}}) |>
170
+ expand.grid()
171
+
172
+ ## Add units back
173
+ # function_pars = apply(pars, 2, function(.x) any(sapply(.x, is.function)))
174
+ # function_par_cols = pars[, function_pars]
175
+ # pars = pars %>%
176
+ # set_parameter_units(.data$R %in% colnames(.)[!function_pars]) |>
177
+ # tibble::as_tibble() |>
178
+ # dplyr::bind_cols(function_par_cols)
179
+
180
+ pars
181
+
182
+ }
183
+
184
+ #' Solve for C_chl and A for each parameter set within [photosynthesis()]
185
+ #' @inheritParams photosynthesis
186
+ #' @noRd
187
+ solve_for_photosynthesis = function(
188
+ pars,
189
+ bake_par,
190
+ constants,
191
+ use_tealeaves,
192
+ progress,
193
+ quiet,
194
+ parallel,
195
+ use_legacy_version
196
+ ) {
197
+
198
+ if (!quiet) {
199
+ glue::glue("\nSolving for photosynthetic rate from {n} parameter set{s} ...",
200
+ n = nrow(pars), s = dplyr::if_else(length(pars) > 1, "s", "")
201
+ ) %>%
202
+ crayon::green() %>%
203
+ message(appendLF = FALSE)
204
+ }
205
+
206
+ if (progress && !parallel) pb = progress::progress_bar$new(total = nrow(pars))
207
+
208
+ soln = if (parallel) {
209
+ pars %>%
210
+ split(~ seq_len(nrow(.))) |>
211
+ furrr::future_map_dfr(
212
+ solve_for_photosynthesis_set,
213
+ bake_par = bake_par,
214
+ constants = constants,
215
+ use_tealeaves = use_tealeaves,
216
+ use_legacy_version = use_legacy_version,
217
+ .progress = progress
218
+ )
219
+ } else {
220
+ pars %>%
221
+ split(~ seq_len(nrow(.))) |>
222
+ purrr::map_dfr(~ {
223
+ ret = solve_for_photosynthesis_set(
224
+ pars = .x,
225
+ bake_par = bake_par,
226
+ constants = constants,
227
+ use_tealeaves = use_tealeaves,
228
+ use_legacy_version = use_legacy_version
229
+ )
230
+ if (progress) pb$tick()
231
+ ret
232
+ })
233
+ }
234
+
235
+ soln
236
+
237
+ }
238
+
239
+ #' Solve for C_chl and A for a single parameter set within [photosynthesis()]
240
+ #' @inheritParams photosynthesis
241
+ #' @noRd
242
+ solve_for_photosynthesis_set = function(
243
+ pars,
244
+ bake_par,
245
+ constants,
246
+ use_tealeaves,
247
+ use_legacy_version
248
+ ) {
249
+
250
+ lx = intersect(
251
+ colnames(pars),
252
+ parameter_names("leaf", use_tealeaves = use_tealeaves)
253
+ )
254
+
255
+ ex = intersect(
256
+ colnames(pars),
257
+ parameter_names("enviro", use_tealeaves = use_tealeaves)
258
+ )
259
+
260
+ # This would cause an error is element was list with multiple elements,
261
+ # but this structure shouldn't occur by this point
262
+ lp = as.list(pars)[lx] |>
263
+ lapply(function(.x) if (is.list(.x)) {.x[[1]]} else .x)
264
+
265
+ ep = as.list(pars)[ex] |>
266
+ lapply(function(.x) if (is.list(.x)) {.x[[1]]} else .x)
267
+
268
+ photo(lp, ep, bake_par, constants, use_tealeaves, quiet = TRUE,
269
+ assert_units = FALSE, check = FALSE,
270
+ use_legacy_version = use_legacy_version)
271
+
272
+ }
273
+
274
+ #' Simulate C3 photosynthesis
275
+ #' @description `photo`: simulate C3 photosynthesis over a single parameter set
276
+ #' @rdname photosynthesis
277
+ #'
278
+ #' @param check Logical. Should arguments checks be done? This is intended to be disabled when [photo()] is called from [photosynthesis()] Default is TRUE.
279
+ #'
280
+ #' @param prepare_for_tleaf Logical. Should arguments additional calculations for [`tleaf()`][tealeaves::tleaves]? This is intended to be disabled when [photo()] is called from [photosynthesis()]. Default is `use_tealeaves`.
281
+ #'
282
+ #' @export
283
+
284
+ photo = function(
285
+ leaf_par,
286
+ enviro_par,
287
+ bake_par,
288
+ constants,
289
+ use_tealeaves,
290
+ quiet = FALSE,
291
+ assert_units = TRUE,
292
+ check = TRUE,
293
+ prepare_for_tleaf = use_tealeaves,
294
+ use_legacy_version = FALSE
295
+ ) {
296
+
297
+ # Check arguments ----
298
+ checkmate::assert_flag(check)
299
+
300
+ if (check) {
301
+ checkmate::assert_class(bake_par, "bake_par")
302
+ checkmate::assert_class(constants, "constants")
303
+ checkmate::assert_class(enviro_par, "enviro_par")
304
+ checkmate::assert_class(leaf_par, "leaf_par")
305
+ checkmate::assert_flag(use_tealeaves)
306
+ checkmate::assert_flag(quiet)
307
+ checkmate::assert_flag(assert_units)
308
+ checkmate::assert_flag(prepare_for_tleaf)
309
+ checkmate::assert_flag(use_legacy_version)
310
+ }
311
+
312
+ # Message about legacy version ----
313
+ notify_users(quiet = quiet, leaf_par = leaf_par)
314
+
315
+ T_air = NULL
316
+ if (!use_tealeaves && !is.null(enviro_par$T_air)) {
317
+ if (!quiet) {
318
+ message(glue::glue("Both air and leaf temperature are provided and fixed: T_air = {T_air}; T_leaf = {T_leaf}",
319
+ T_air = enviro_par$T_air,
320
+ T_leaf = leaf_par$T_leaf
321
+ ))
322
+ }
323
+ T_air = enviro_par$T_air
324
+ }
325
+
326
+ # Set units and bake ----
327
+ if (assert_units) {
328
+ bake_par %<>% photosynthesis::bake_par()
329
+ constants %<>% photosynthesis::constants(use_tealeaves)
330
+ enviro_par %<>% photosynthesis::enviro_par(use_tealeaves)
331
+ leaf_par %<>% photosynthesis::leaf_par(use_tealeaves)
332
+ if (!is.null(T_air)) enviro_par$T_air = set_units(T_air, K)
333
+ }
334
+
335
+ # Calculate T_leaf using energy balance ----
336
+ if (use_tealeaves) {
337
+ leaf_par %<>% add_Tleaf_photo(enviro_par, constants, prepare_for_tleaf)
338
+ # Hack to add E. Should do this better and for all tealeaves calculated
339
+ # values
340
+ E_out = leaf_par$E
341
+ }
342
+
343
+ leaf_par %<>% bake(enviro_par, bake_par, constants, assert_units = FALSE)
344
+
345
+ pars = c(leaf_par, enviro_par, constants) %>%
346
+ purrr::map_if(~ inherits(.x, "units"), drop_units)
347
+ if (!use_tealeaves && is.null(pars$T_air)) pars$T_air = pars$T_leaf
348
+
349
+ # Find intersection between photosynthetic supply and demand curves -----
350
+ soln = find_A(pars, quiet, use_legacy_version)
351
+
352
+ # Check results -----
353
+ if (soln$convergence == 1) {
354
+ "stats::uniroot did not converge, NA returned. Inspect parameters carefully." %>%
355
+ crayon::red() %>%
356
+ message()
357
+ }
358
+
359
+ # Return -----
360
+ # This is a hack needed for `photosynthesis()` because leaf_par and enviro_par
361
+ # are both passed from pars = c(leaf_par, enviro_par), so they have redundant
362
+ # information. This checks that everything is identical, then gets rid of
363
+ # redundant parameters.
364
+ shared_pars = intersect(names(leaf_par), names(enviro_par))
365
+ checkmate::assert_true(all(unlist(leaf_par[shared_pars]) ==
366
+ unlist(enviro_par[shared_pars])))
367
+ leaf_par[shared_pars] = NULL
368
+
369
+ soln = c(
370
+ soln,
371
+ purrr::keep(leaf_par, ~ length(.x) > 0 & !is.function(.x)),
372
+ purrr::keep(enviro_par, ~ length(.x) > 0 & !is.function(.x)),
373
+ purrr::keep(bake_par, ~ length(.x) > 0 & !is.function(.x)),
374
+ purrr::keep(constants, ~ length(.x) > 0 & !is.function(.x))
375
+ ) |>
376
+ as.data.frame()
377
+
378
+ soln$C_chl %<>% set_units(umol / mol)
379
+ soln$g_tc %<>% set_units(mol / m^2 / s)
380
+ soln$A %<>% set_units(umol / m^2 / s)
381
+ soln$C_i = set_units(soln$C_air - soln$A / soln$g_sc, umol/mol)
382
+
383
+ # I should make this for all additional tealeaves calculated value
384
+ if (use_tealeaves) soln$E = E_out
385
+
386
+ soln
387
+
388
+ }
389
+
390
+ #' Calculate leaf temperature using [tealeaves::tleaf()]
391
+ #' @inheritParams photo
392
+ #' @noRd
393
+ add_Tleaf_photo = function(leaf_par, enviro_par, constants, prepare_for_tleaf) {
394
+
395
+ leaf_par1 = leaf_par
396
+ constants1 = constants
397
+
398
+ if (prepare_for_tleaf) {
399
+ enviro_par$S_sw = set_units(enviro_par$E_q * enviro_par$PPFD /
400
+ enviro_par$f_par, W / m^2)
401
+ leaf_par$g_sw = set_units(
402
+ constants$D_w0 / constants$D_c0 * leaf_par$g_sc,
403
+ mol / m^2 / s
404
+ )
405
+ leaf_par$g_uw = set_units(
406
+ constants$D_w0 / constants$D_c0 * leaf_par$g_uc,
407
+ mol / m^2 / s
408
+ )
409
+
410
+ leaf_par1$logit_sr = if (is(leaf_par$k_sc, "units")) {
411
+ stats::qlogis(leaf_par$k_sc / (set_units(1) + leaf_par$k_sc))
412
+ } else {
413
+ stats::qlogis(leaf_par$k_sc / (1 + leaf_par$k_sc))
414
+ }
415
+
416
+ # Need this until tealeaves changes these parameters for consistency
417
+ leaf_par1$g_sw = if (is(leaf_par$g_sw, "units")) {
418
+ leaf_par$g_sw |>
419
+ gunit::convert_conductance(P = enviro_par$P, R = constants$R) |>
420
+ magrittr::extract2("umol/m^2/s/Pa")
421
+ } else {
422
+ leaf_par$g_sw / enviro_par$P * 1000
423
+ }
424
+
425
+ leaf_par1$g_uw = if (is(leaf_par$g_uw, "units")) {
426
+ leaf_par$g_uw |>
427
+ gunit::convert_conductance(P = enviro_par$P, R = constants$R) |>
428
+ magrittr::extract2("umol/m^2/s/Pa")
429
+ } else {
430
+ leaf_par$g_uw / enviro_par$P * 1000
431
+ }
432
+
433
+
434
+ constants1$nu_constant = constants$f_nu
435
+ constants1$sh_constant = constants$f_sh
436
+ constants1$f_nu = constants1$f_sh = NULL
437
+ constants1$s = constants1$sigma
438
+ constants1$sigma = NULL
439
+ }
440
+
441
+ tl = tealeaves::tleaf(
442
+ leaf_par = leaf_par1,
443
+ enviro_par = enviro_par,
444
+ constants = constants1,
445
+ quiet = TRUE,
446
+ set_units = TRUE
447
+ ) %>%
448
+ dplyr::rename(
449
+ tealeaves_convergence = "convergence",
450
+ tealeaves_value = "value"
451
+ )
452
+ leaf_par$T_leaf = tl$T_leaf
453
+ leaf_par$E = tl$E
454
+
455
+ leaf_par
456
+
457
+ }
458
+
459
+ supply_minus_demand = function(C_chl, unitless_pars, use_legacy_version) {
460
+ supply = A_supply(C_chl, unitless_pars, unitless = TRUE, use_legacy_version)
461
+ demand = A_demand(C_chl, unitless_pars, unitless = TRUE)
462
+ supply - demand
463
+ }
464
+
465
+ find_A = function(unitless_pars, quiet, use_legacy_version) {
466
+
467
+ if (!quiet) {
468
+ "\nSolving for C_chl ..." %>%
469
+ crayon::green() %>%
470
+ message(appendLF = FALSE)
471
+ }
472
+
473
+ fit = tryCatch(
474
+ {
475
+ Cchl_upper = max(c(unitless_pars$gamma_star, unitless_pars$C_air))
476
+ while (supply_minus_demand(Cchl_upper, unitless_pars, use_legacy_version) > 0) {
477
+ Cchl_upper = 2 * Cchl_upper
478
+ }
479
+ stats::uniroot(supply_minus_demand,
480
+ unitless_pars = unitless_pars, lower = 0.1,
481
+ upper = Cchl_upper,
482
+ check.conv = TRUE, use_legacy_version = use_legacy_version
483
+ )
484
+ },
485
+ finally = {
486
+ fit = list(root = NA, f.root = NA, convergence = 1)
487
+ }
488
+ )
489
+
490
+ soln = data.frame(
491
+ C_chl = fit$root, value = fit$f.root,
492
+ convergence = dplyr::if_else(is.null(fit$convergence), 0, 1)
493
+ )
494
+
495
+ if (!quiet) {
496
+ " done" %>%
497
+ crayon::green() %>%
498
+ message()
499
+ }
500
+
501
+ soln$g_tc = .get_gtc(unitless_pars, unitless = TRUE, use_legacy_version)
502
+ soln$A = A_supply(soln$C_chl, unitless_pars, unitless = TRUE,
503
+ use_legacy_version)
504
+
505
+ soln
506
+ }
507
+
508
+ #' CO2 supply and demand function (mol / m^2 s)
509
+ #'
510
+ #' This function is not intended to be called by users directly.
511
+ #'
512
+ #' @inheritParams photosynthesis
513
+ #'
514
+ #' @param C_chl Chloroplastic CO2 concentration in Pa of class `units`
515
+ #' @param pars Concatenated parameters (`leaf_par`, `enviro_par`, and `constants`)
516
+ #' @param unitless Logical. Should `units` be set? The function is faster when FALSE, but input must be in correct units or else results will be incorrect without any warning.
517
+ #'
518
+ #' @return Value in mol / (m^2 s) of class `units`
519
+ #'
520
+ #' @details
521
+ #'
522
+ #' **Supply function:**
523
+ #' \cr
524
+ #' \deqn{A = g_\mathrm{tc} (C_\mathrm{air} - C_\mathrm{chl})}{A = g_tc (C_air - C_chl)}
525
+ #'
526
+ #' **Demand function:**
527
+ #' \cr
528
+ #' \deqn{A = (1 - \Gamma* / C_\mathrm{chl}) \mathrm{min}(W_\mathrm{carbox}, W_\mathrm{regen}, W_\mathrm{tpu}) - R_\mathrm{d}}{A = (1 - \Gamma* / C_chl) min(W_carbox, W_regen, W_tpu) - R_d}
529
+ #'
530
+ #' \tabular{lllll}{
531
+ #' *Symbol* \tab *R* \tab *Description* \tab *Units* \tab *Default*\cr
532
+ #' \eqn{A} \tab `A` \tab photosynthetic rate \tab \eqn{\mu}mol CO2 / (m^2 s) \tab calculated \cr
533
+ #' \eqn{g_\mathrm{tc}}{g_tc} \tab `g_tc` \tab total conductance to CO2 \tab \eqn{\mu}mol CO2 / (m\eqn{^2} s Pa) \tab [calculated][.get_gtc] \cr
534
+ #' \eqn{C_\mathrm{air}}{C_air} \tab `C_air` \tab atmospheric CO2 concentration \tab Pa \tab 41 \cr
535
+ #' \eqn{C_\mathrm{chl}}{C_chl} \tab `C_chl` \tab chloroplastic CO2 concentration \tab Pa \tab calculated\cr
536
+ #' \eqn{R_\mathrm{d}}{R_d} \tab `R_d` \tab nonphotorespiratory CO2 release \tab \eqn{\mu}mol CO2 / (m\eqn{^2} s) \tab 2 \cr
537
+ #' \eqn{\Gamma*} \tab `gamma_star` \tab chloroplastic CO2 compensation point \tab Pa \tab 3.743
538
+ #' }
539
+ #'
540
+ #' @examples
541
+ #' bake_par = make_bakepar()
542
+ #' constants = make_constants(use_tealeaves = FALSE)
543
+ #' enviro_par = make_enviropar(use_tealeaves = FALSE)
544
+ #' leaf_par = make_leafpar(use_tealeaves = FALSE)
545
+ #' leaf_par = bake(leaf_par, enviro_par, bake_par, constants)
546
+ #' # Or bake with piping (need library(magrittr))
547
+ #' # leaf_par %<>% bake(enviro_par, bake_par, constants)
548
+ #' enviro_par$T_air = leaf_par$T_leaf
549
+ #'
550
+ #' pars = c(leaf_par, enviro_par, constants)
551
+ #' C_chl = set_units(350, umol/mol)
552
+ #'
553
+ #' A_supply(C_chl, pars)
554
+ #'
555
+ #' A_demand(C_chl, pars)
556
+ #' @export
557
+
558
+ A_supply = function(C_chl, pars, unitless = FALSE, use_legacy_version = FALSE) {
559
+ g_tc = .get_gtc(pars, unitless, use_legacy_version)
560
+
561
+ if (unitless) {
562
+ As = g_tc * (pars$C_air - C_chl)
563
+ } else {
564
+ As = set_units(g_tc * (pars$C_air - C_chl), umol / m^2 / s)
565
+ }
566
+ As
567
+ }
568
+
569
+ #' A_demand
570
+ #' @rdname A_supply
571
+ #' @export
572
+
573
+ A_demand = function(C_chl, pars, unitless = FALSE) {
574
+ if (unitless) {
575
+ Ad = (1 - pars$gamma_star / C_chl) * FvCB(C_chl, pars, unitless)$A - pars$R_d
576
+ } else {
577
+ Ad = set_units((set_units(1) - pars$gamma_star / C_chl) *
578
+ FvCB(C_chl, pars, unitless)$A - pars$R_d, umol / m^2 / s)
579
+ }
580
+
581
+ Ad
582
+ }
583
+
584
+ #' Check whether users supplied parameters to calculate g_ias and g_liq
585
+ #' @noRd
586
+ check_new_conductance = function(pars, baked) {
587
+ checkmate::assert_flag(baked)
588
+ if (baked) {
589
+ c("g_iasc_lower", "g_iasc_upper", "A_mes_A", "g_liqc") |>
590
+ purrr::map_lgl(function(.x, pars) {
591
+ length(pars[[.x]]) > 0 & all(!is.na(pars[[.x]]))
592
+ }, pars = pars) |>
593
+ all()
594
+ } else {
595
+ c("delta_ias_lower", "delta_ias_upper", "A_mes_A", "g_liqc25") |>
596
+ purrr::map_lgl(function(.x, pars) {
597
+ length(pars[[.x]]) > 0 & all(!is.na(pars[[.x]]))
598
+ }, pars = pars) |>
599
+ all()
600
+ }
601
+
602
+ }
603
+
604
+ #' Notify users about important changes in \link[photosyntesis]
605
+ #' @noRd
606
+ notify_users = function(quiet, leaf_par) {
607
+
608
+ if (!quiet) {
609
+ message("
610
+
611
+ As of version 2.1.0, the CO2 conductance model changed slightly.
612
+ To implement legacy version, use:
613
+
614
+ `> photosynthesis(..., use_legacy_version = TRUE)`.")
615
+
616
+ if (check_new_conductance(leaf_par, baked = FALSE)) {
617
+ message("
618
+ It looks like you provided parameters to calculate g_ias and g_liq.
619
+ The parameters g_mc and k_mc will be ignored and calculated from g_ias
620
+ and g_liq. This is a new feature in version 2.1.0 and may change in the
621
+ near future. Inspect results carefully.
622
+ ")
623
+ }
624
+
625
+ }
626
+
627
+ }
data/R/print_graphs.R ADDED
@@ -0,0 +1,132 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #' Printing graphs to system
2
+ #'
3
+ #' @param data List of graphs
4
+ #' @param path File path for printing our graphs. Use "./" to set to current
5
+ #' working directory
6
+ #' @param output_type Type of output file, jpeg or pdf
7
+ #' @param height Height of jpegs
8
+ #' @param width Width of jpegs
9
+ #' @param res Resolution of jpegs
10
+ #' @param units Units of height and width
11
+ #' @param pdf_filename Filename for pdf option
12
+ #' @param ... Further arguments for jpeg() and pdf()
13
+ #'
14
+ #' @return print_graphs creates graph files in current working directory
15
+ #' from a list of graphs
16
+ #' @importFrom grDevices dev.off
17
+ #' @importFrom grDevices jpeg
18
+ #' @importFrom grDevices pdf
19
+ #' @importFrom graphics par
20
+ #' @importFrom graphics plot
21
+ #' @export
22
+ #'
23
+ #' @examples
24
+ #' \donttest{
25
+ #' # Read in your data
26
+ #' # Note that this data is coming from data supplied by the package
27
+ #' # hence the complicated argument in read.csv()
28
+ #' # This dataset is a CO2 by light response curve for a single sunflower
29
+ #' data <- read.csv(system.file("extdata", "A_Ci_Q_data_1.csv",
30
+ #' package = "photosynthesis"
31
+ #' ))
32
+ #'
33
+ #' # Fit many AQ curves
34
+ #' # Set your grouping variable
35
+ #' # Here we are grouping by CO2_s and individual
36
+ #' data$C_s <- (round(data$CO2_s, digits = 0))
37
+ #'
38
+ #' # For this example we need to round sequentially due to CO2_s setpoints
39
+ #' data$C_s <- as.factor(round(data$C_s, digits = -1))
40
+ #'
41
+ #' # To fit one AQ curve
42
+ #' fit <- fit_aq_response(data[data$C_s == 600, ],
43
+ #' varnames = list(
44
+ #' A_net = "A",
45
+ #' PPFD = "Qin"
46
+ #' )
47
+ #' )
48
+ #'
49
+ #' # Print model summary
50
+ #' summary(fit[[1]])
51
+ #'
52
+ #' # Print fitted parameters
53
+ #' fit[[2]]
54
+ #'
55
+ #' # Print graph
56
+ #' fit[[3]]
57
+ #'
58
+ #' # Fit many curves
59
+ #' fits <- fit_many(
60
+ #' data = data,
61
+ #' varnames = list(
62
+ #' A_net = "A",
63
+ #' PPFD = "Qin",
64
+ #' group = "C_s"
65
+ #' ),
66
+ #' funct = fit_aq_response,
67
+ #' group = "C_s"
68
+ #' )
69
+ #'
70
+ #' # Look at model summary for a given fit
71
+ #' # First set of double parentheses selects an individual group value
72
+ #' # Second set selects an element of the sublist
73
+ #' summary(fits[[3]][[1]])
74
+ #'
75
+ #' # Print the parameters
76
+ #' fits[[3]][[2]]
77
+ #'
78
+ #' # Print the graph
79
+ #' fits[[3]][[3]]
80
+ #'
81
+ #' # Compile graphs into a list for plotting
82
+ #' fits_graphs <- compile_data(fits,
83
+ #' list_element = 3
84
+ #' )
85
+ #'
86
+ #' # Print graphs to pdf
87
+ #' # Uncomment to run
88
+ #' # print_graphs(data = fits_graphs,
89
+ #' # output_type = "pdf",
90
+ #' # path = tempdir(),
91
+ #' # pdf_filename = "mygraphs.pdf")
92
+ #' }
93
+ print_graphs <- function(data,
94
+ path,
95
+ output_type = "jpeg",
96
+ height = 5,
97
+ width = 5,
98
+ res = 600,
99
+ units = "in",
100
+ pdf_filename,
101
+ ...) {
102
+ # Is output_type compatible with options?
103
+ if (!output_type %in% c("pdf", "jpeg")) {
104
+ stop("Output type not found. Use pdf or jpeg")
105
+ }
106
+ if (!missing(path)) {
107
+ # Print out individual jpeg files
108
+ if (output_type == "jpeg") {
109
+ for (i in 1:length(data)) {
110
+ jpeg(paste(names(data[i])[1], ".jpeg"),
111
+ height = height, width = width,
112
+ res = res, units = units, ...
113
+ )
114
+ print(data[[i]])
115
+ dev.off()
116
+ }
117
+ }
118
+ # Print out pdf with all graphs
119
+ if (output_type == "pdf") {
120
+ pdf(pdf_filename, ...)
121
+ old_mfrow = par()$mfrow
122
+ par(mfrow = c(2, 2))
123
+ on.exit(par(mfrow = old_mfrow))
124
+ for (i in 1:length(data)) {
125
+ plot(data[[i]], main = names(data[i]))
126
+ }
127
+ dev.off()
128
+ }
129
+ } else {
130
+ message("Graphs not printed. 'path' argument required.")
131
+ }
132
+ }
data/R/read_licor.R ADDED
@@ -0,0 +1,185 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #' Read a LI-COR file
2
+ #'
3
+ #' @description
4
+ #' `r lifecycle::badge("deprecated")`
5
+ #'
6
+ #' We are no longer updating this function. Please use \code{\link{read_licor}} instead.
7
+ #'
8
+ #' @param x File name
9
+ #'
10
+ #' @return Returns a data.frame from raw LI-COR files. Current support
11
+ #' for LI-COR LI-6800 files only.
12
+ #' @importFrom utils read.csv
13
+ #'
14
+ #' @md
15
+ #' @export
16
+ read_li6800 = function(x) {
17
+
18
+ lifecycle::deprecate_soft("2.1.3", "read_li6800()", with = "read_licor()")
19
+
20
+ # Read in header information
21
+ header <- read.csv(
22
+ file = x, header = TRUE, sep = "\t",
23
+ skip = grep(
24
+ pattern = "\\[Data\\]",
25
+ x = readLines(x),
26
+ value = FALSE
27
+ ) + 1,
28
+ nrows = 1
29
+ )
30
+ # Read in data information
31
+ data <- read.csv(
32
+ file = x, header = FALSE, sep = "\t",
33
+ skip = grep(
34
+ pattern = "\\[Data\\]",
35
+ x = readLines(x),
36
+ value = FALSE
37
+ ) + 3
38
+ )
39
+ # Add header to data
40
+ colnames(data) <- colnames(header)
41
+ # Return data
42
+ return(data)
43
+ }
44
+
45
+ #' Read a LI-COR file
46
+ #'
47
+ #' @description
48
+ #' `r lifecycle::badge("experimental")`
49
+ #'
50
+ #' Reads a raw LI-COR LI6800 file, including remarks. This function was
51
+ #' developed using output from Bluestem v.2.0.04 to v.2.1.08. We cannot
52
+ #' guarantee backward compatibility with earlier versions of Bluestem. We will
53
+ #' try to update code when new versions are released, but there maybe a
54
+ #' time-lag, so inspect results carefully.
55
+ #'
56
+ #' @param file Path to a raw LI6800 file
57
+ #' @param bluestem_version Character string of Bluestem software version number. By default, the function will try to pull the version number from file.
58
+ #' @param ... Argument passed to \code{\link[readr]{read_lines}}
59
+ #'
60
+ #' @return Returns a \code{\link[tibble]{tibble}} from raw LI-COR LI6800 files.
61
+ #'
62
+ #' @export
63
+ read_licor = function(
64
+ file,
65
+ bluestem_version = get_bluestem_version(file, n_max = 10L),
66
+ ...
67
+ ) {
68
+
69
+ v1 = "2.0.04"
70
+ v2 = "2.1.08"
71
+ checkmate::assert_string(bluestem_version)
72
+
73
+ if (numeric_version(bluestem_version) < v1) {
74
+ warning(glue::glue("It appears you are using data from Bluestem version {bluestem_version}. `read_licor()` function was developed with versions starting at {v1} and has not been tested with earlier versions. Inspect results carefully."))
75
+ }
76
+
77
+ if (numeric_version(bluestem_version) > v2) {
78
+ warning(glue::glue("It appears you are using data from Bluestem version {bluestem_version}. `read_licor()` function was developed with versions up to {v2} and has not been tested with more recent versions. Inspect results carefully."))
79
+ }
80
+
81
+ # Read lines
82
+ all_lines = readr::read_lines(file, ...)
83
+
84
+ # Extract header information and covert to named list
85
+ header = all_lines |>
86
+ extract_licor_header() |>
87
+ purrr::map(stringr::str_split_1, "\t") |>
88
+ purrr::map(restructure_licor_header_line) %>%
89
+ rlang::set_names(sapply(., `[`, 1L)) |>
90
+ purrr::map(`[`, -1L)
91
+
92
+ # Extract remarks and convert to tibble
93
+ remarks = extract_licor_remarks(all_lines)
94
+
95
+ df_remarks = remarks |>
96
+ tibble::as_tibble() |>
97
+ tidyr::separate(col = "value", into = c("time", "remark"), sep = "\t")
98
+
99
+ # Extract parameter settings
100
+ # Most of these are in header, but this will also remove lines from data when
101
+ # parameter settings are changed between logging
102
+ parameter_settings = names(header) %>%
103
+ magrittr::extract(stringr::str_detect(., "^.*:.*")) |>
104
+ stringr::str_c(collapse = "|") %>%
105
+ paste0("^(", ., ")\\t.*") %>%
106
+ stringr::str_extract(all_lines, .) |>
107
+ stats::na.omit()
108
+
109
+ # Extract data and convert to a tibble
110
+ data_block = setdiff(all_lines, c(remarks, parameter_settings))
111
+ data_start_line = stringr::str_detect(data_block, "\\[Data\\]")
112
+ var_names = stringr::str_split_1(data_block[which(data_start_line) + 2L],
113
+ pattern = "\t")
114
+
115
+ utils::read.table(
116
+ text = data_block[(which(data_start_line) + 4L):length(data_block)],
117
+ sep = "\t"
118
+ ) |>
119
+ magrittr::set_colnames(var_names) |>
120
+ magrittr::set_attr("remarks", df_remarks) |>
121
+ magrittr::set_attr("header", header)
122
+
123
+ }
124
+
125
+ #' Get Bluestem version from LI6800 file
126
+ #'
127
+ #' @inheritParams read_licor
128
+ #' @param ... Argument passed to \code{\link[readr]{read_lines}}
129
+ #' @noRd
130
+ get_bluestem_version = function(file, ...) {
131
+ x1 = readr::read_lines(file, ...)
132
+ ver_number_string = "[0-9]+.[0-9]+.[0-9]+"
133
+ ver_string = paste0("Console ver\tBluestem v.", ver_number_string)
134
+ ver_line = which(stringr::str_detect(x1, ver_string))
135
+ stringr::str_extract(x1[ver_line], ver_number_string)
136
+ }
137
+
138
+ #' Extract header table from a LI6800 raw file
139
+ #' @noRd
140
+ extract_licor_header = function(.x) {
141
+ header_line = "\\[Header\\]"
142
+ data_line = "\\[Data\\]"
143
+ first_line = stringr::str_detect(.x, header_line) |>
144
+ which() |>
145
+ magrittr::add(1L)
146
+ last_line = stringr::str_detect(.x, data_line) |>
147
+ which() |>
148
+ magrittr::subtract(1L)
149
+
150
+ # Remove remarks
151
+ header = .x[first_line:last_line]
152
+ remarks = extract_licor_remarks(header)
153
+
154
+ setdiff(header, remarks)
155
+ }
156
+
157
+ #' Extract remarks from a LI6800 raw file
158
+ #' @noRd
159
+ extract_licor_remarks = function(.x) {
160
+ # Remark lines have time stamp, tab, and no more '\t' in remainder of line
161
+ remark_line = "^[0-2][0-9]:[0-5][0-9]:[0-5][0-9]\t(?!.*(\t))"
162
+ .x[stringr::str_detect(.x, remark_line)]
163
+ }
164
+
165
+ #' Restructure LI6800 header rows
166
+ #' @description
167
+ #' Restructures header rows in raw LI6800 files as needed. Currently, it only alters the row with Stability Definition
168
+ #' @param header_line A character vector from one row in the header after splitting by tabs.
169
+ #' @noRd
170
+ restructure_licor_header_line = function(header_line) {
171
+ checkmate::assert_character(header_line)
172
+
173
+ # Restructure Stability Definition line
174
+ ret = if (
175
+ stringr::str_detect(header_line[1], "^[0-2][0-9]:[0-5][0-9]:[0-5][0-9]$") &
176
+ stringr::str_detect(header_line[2], "^Stability Definition:$")
177
+ ) {
178
+ header_line[2:length(header_line)]
179
+ } else{
180
+ header_line
181
+ }
182
+
183
+ ret
184
+
185
+ }
data/R/simulate_error.R ADDED
@@ -0,0 +1,200 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #' Simulate gas exchange data with measurement error
2
+ #'
3
+ #' @description
4
+ #'
5
+ #' `r lifecycle::badge("experimental")`
6
+ #'
7
+ #' @param ph_out A data frame of output from `photo()` or `photosynthesis()`
8
+ #' with units.
9
+ #' @param chamber_pars A data frame with a single row of chamber parameters.
10
+ #' See Note below for table of required parameters.
11
+ #' @param n Integer. Number of replicated simulations per row of `ph_out`.
12
+ #' @param use_tealeaves Flag. The **tealeaves** package uses a slightly
13
+ #' different equation to calculate the saturating water content of air as a
14
+ #' function temperature and pressure than LI-COR. If FALSE, the function uses
15
+ #' LI-COR's equation in the LI6800 manual. If TRUE, it uses the **tealeaves**
16
+ #' function for internal consistency. The function attempts to guess whether
17
+ #' `ph_out` was run with **tealeaves**, but this can be manually overridden by
18
+ #' providing a value for the argument.
19
+ #'
20
+ #' @return A data frame with `n * nrow(ph_out)` rows. It contains all the
21
+ #' original output in `ph_out` as well as a column `.rep` indicating replicate
22
+ #' number from 1 to `n`. Other new columns are assumed or measured chamber
23
+ #' parameters and 'measured' values estimated from synthetic data with
24
+ #' measurement error:
25
+ #'
26
+ #' | column name | assumed or derived? | description |
27
+ #' |-------------|---------------------|-------------|
28
+ #' | `flow` | assumed | chamber flow rate |
29
+ #' | `leaf_area` | assumed | leaf area in chamber |
30
+ #' | `sigma_CO2_r` | assumed | standard deviation of measurement error in CO2_r |
31
+ #' | `sigma_CO2_s` | assumed | standard deviation of measurement error in CO2_s |
32
+ #' | `sigma_H2O_r` | assumed | standard deviation of measurement error in H2O_r |
33
+ #' | `sigma_H2O_s` | assumed | standard deviation of measurement error in H2O_s |
34
+ #' | `c_0` | derived | CO\eqn{_2} concentration before entering chamber \[\eqn{\mu}mol / mol\] |
35
+ #' | `w_i` | derived | Water vapor concentration within leaf \[mmol / mol\] |
36
+ #' | `w_a` | derived | Water vapor concentration in chamber \[mmol / mol\] |
37
+ #' | `w_0` | derived | Water vapor concentration before entering chamber \[mmol / mol\] |
38
+ #' | `g_tw` | derived | Leaf conductance to water vapor \[mol/m\eqn{^2}/s\] |
39
+ #' | `E_area` | derived | Evaporation rate per area \[mmol/m\eqn{^2}/s\] |
40
+ #' | `E` | derived | Total evaporation rate \[mmol/s\] |
41
+ #' | `CO2_r` | derived | CO\eqn{_2} concentration before entering chamber with measurement error \[\eqn{\mu}mol / mol\] |
42
+ #' | `CO2_s` | derived | CO\eqn{_2} concentration in chamber with measurement error \[\eqn{\mu}mol / mol\] |
43
+ #' | `H2O_s` | derived | Water vapor concentration in chamber with measurement error \[mmol / mol\] |
44
+ #' | `H2O_r` | derived | Water vapor concentration before entering chamber with measurement error \[mmol / mol\] |
45
+ #' | `E_meas` | derived | Total evaporation rate (measured) \[mmol/s\] |
46
+ #' | `E_area_meas` | derived | Evaporation rate per area (measured) \[mmol/m\eqn{^2}/s\] |
47
+ #' | `g_tw_meas` | derived | Leaf conductance to water vapor (measured) \[mol/m\eqn{^2}/s\] |
48
+ #' | `g_sc_meas` | derived | Stomatal conductance to CO\eqn{_2} (measured) \[mol/m\eqn{^2}/s\] |
49
+ #' | `g_tc_meas` | derived | Leaf conductance to CO\eqn{_2} (measured) \[mol/m\eqn{^2}/s\] |
50
+ #' | `A_meas` | derived | Net photosynthetic CO\eqn{_2} assimilation (measured) \[\eqn{\mu}mol/m\eqn{^2}/s\] |
51
+ #' | `C_i` | derived | Intercellular CO\eqn{_2} concentration (measured) \[\eqn{\mu}mol/mol\] |
52
+ #'
53
+ #' @note
54
+ #' The required parameters for the `chamber_pars` argument are:
55
+ #'
56
+ #' * `flow` \[\eqn{\mu}mol / s\]: chamber flow rate
57
+ #' * `leaf_area` \[cm ^ 2\]: leaf area in chamber
58
+ #' * `sigma_CO2_s` \[\eqn{\mu}mol / mol\]: standard deviation of sample \[CO\eqn{_2}\] measurement error
59
+ #' * `sigma_CO2_r` \[\eqn{\mu}mol / mol\]: standard deviation of reference [CO\eqn{_2}\]
60
+ #' * `sigma_H2O_s` \[mmol / mol\]: standard deviation of sample \[H\eqn{_2}O\] measurement error
61
+ #' * `sigma_H2O_r` \[mmol / mol\]: standard deviation of sample \[H\eqn{_2}O\] measurement error
62
+ #'
63
+ #' Units for `flow` and `leaf_area` should be provided; units are implied for sigma's but not necessary to specify because `rnorm()` drop units.
64
+ #'
65
+ #' To evaluate the accuracy and precision of parameter estimation methods, it
66
+ #' may be useful to simulate data with realistic measurement error. This
67
+ #' function takes output from from `photo()` or `photosynthesis()` models, adds
68
+ #' measurement error in CO\eqn{_2} and H\eqn{_2}O concentrations, and calculates
69
+ #' parameter estimates with synthetic data. Currently, the function assumes a
70
+ #' simplified 1-dimensional CO\eqn{_2} and H\eqn{_2}O conductance model: zero
71
+ #' cuticular conductance, infinite boundary layer conductance, and infinite
72
+ #' airspace conductance. Other assumptions include:
73
+ #'
74
+ #' * chamber flow rate, leaf area, leaf temperature, and air pressure are known
75
+ #' without error
76
+ #' * measurement error is normally distributed mean 0 and standard deviation
77
+ #' specified in `chamber_pars`
78
+ #'
79
+ #' This function was designed with the LI-COR LI6800 instrument in mind, but in
80
+ #' principle applies to any open path gas exchange system.
81
+ #'
82
+ #' @examples
83
+ #' library(photosynthesis)
84
+ #'
85
+ #' # Use photosynthesis() to simulate 'real' values
86
+ #' # `replace = ...` sets parameters to meet assumptions of `simulate_error()`
87
+ #' lp = make_leafpar(replace = list(
88
+ #' g_sc = set_units(0.1, mol/m^2/s),
89
+ #' g_uc = set_units(0, mol/m^2/s),
90
+ #' k_mc = set_units(0, 1),
91
+ #' k_sc = set_units(0, 1),
92
+ #' k_uc = set_units(0, 1)
93
+ #' ),
94
+ #' use_tealeaves = FALSE)
95
+ #'
96
+ #' ep = make_enviropar(replace = list(
97
+ #' wind = set_units(Inf, m/s)
98
+ #' ), use_tealeaves = FALSE)
99
+ #' bp = make_bakepar()
100
+ #' cs = make_constants(use_tealeaves = FALSE)
101
+ #'
102
+ #' chamber_pars = data.frame(
103
+ #' flow = set_units(600, umol / s),
104
+ #' leaf_area = set_units(6, cm ^ 2),
105
+ #' sigma_CO2_s = 0.1,
106
+ #' sigma_CO2_r = 0.1,
107
+ #' sigma_H2O_s = 0.1,
108
+ #' sigma_H2O_r = 0.1
109
+ #' )
110
+ #'
111
+ #' ph = photosynthesis(lp, ep, bp, cs, use_tealeaves = FALSE, quiet = TRUE) |>
112
+ #' simulate_error(chamber_pars, n = 1L)
113
+ #'
114
+ #' @md
115
+ #' @export
116
+ simulate_error = function(
117
+ ph_out,
118
+ chamber_pars,
119
+ n = 1L,
120
+ use_tealeaves = ("T_air" %in% colnames(ph_out))
121
+ ) {
122
+
123
+ lifecycle::signal_stage("experimental", what = "simulate_error()")
124
+
125
+ # Check
126
+ checkmate::assert_data_frame(ph_out, any.missing = FALSE, min.rows = 1L)
127
+ c("A", "C_i", "g_sc", "P", "T_leaf") %in% colnames(ph_out) |>
128
+ all() |>
129
+ checkmate::assert_true()
130
+ checkmate::assert_data_frame(chamber_pars, any.missing = FALSE, nrows = 1L)
131
+ c("flow", "leaf_area", "sigma_CO2_r", "sigma_CO2_s", "sigma_H2O_r", "sigma_H2O_s") |>
132
+ magrittr::is_in(colnames(chamber_pars)) |>
133
+ all() |>
134
+ checkmate::assert_true()
135
+ checkmate::assert_number(chamber_pars$flow, lower = 0, finite = TRUE)
136
+ checkmate::assert_number(chamber_pars$leaf_area, lower = 0, finite = TRUE)
137
+ checkmate::assert_number(chamber_pars$sigma_CO2_r, lower = 0, finite = TRUE)
138
+ checkmate::assert_number(chamber_pars$sigma_CO2_s, lower = 0, finite = TRUE)
139
+ checkmate::assert_number(chamber_pars$sigma_H2O_r, lower = 0, finite = TRUE)
140
+ checkmate::assert_number(chamber_pars$sigma_H2O_s, lower = 0, finite = TRUE)
141
+ checkmate::assert_int(n)
142
+ checkmate::assert_flag(use_tealeaves)
143
+
144
+ # Replicate ph_out n times and add chamber parameters
145
+ tidyr::crossing(
146
+ .rep = seq_len(n),
147
+ ph_out,
148
+ chamber_pars
149
+ ) %>%
150
+ dplyr::mutate(
151
+
152
+ # Assume water vapour concentration is saturated within leaf, w_i [mmol/mol]
153
+ w_i = if (use_tealeaves) {
154
+ # Use tealeaves version for internal consistency
155
+ .get_ps(T_leaf, P, FALSE) |>
156
+ magrittr::divide_by(P) |>
157
+ set_units(mmol/mol)
158
+ } else {
159
+ # LI-6800 equation
160
+ T_leaf = set_units(T_leaf, degreeC) |>
161
+ drop_units()
162
+ P = set_units(P, kPa) |>
163
+ drop_units()
164
+ w_i = set_units((1000 * 0.61365 * exp(17.502 * T_leaf / (240.97 + T_leaf)) / P), mmol / mol)
165
+ },
166
+ # Calculate [H2O] in chamber based on RH
167
+ w_a = set_units(.data$RH * w_i, mmol / mol),
168
+ # Assume all g_tw = g_sw (i.e. g_uw = 0; g_bw = Inf
169
+ g_tw = .data$g_sc * 1.6,
170
+ E_area = set_units(.data$g_tw * (w_i - .data$w_a), mmol / m^2 / s),
171
+ E = .data$E_area * .data$leaf_area, # [mmol / s]
172
+ w_0 = set_units(.data$w_a - .data$E * (set_units(1) - .data$w_a) / .data$flow,
173
+ mmol / mol),
174
+ c_0 = set_units(.data$leaf_area * .data$A / .data$flow +
175
+ .data$C_air * (set_units(1) - .data$w_0) /
176
+ (set_units(1) - .data$w_a), umol / mol),
177
+
178
+ # Simulate measurements with error
179
+ H2O_s = .data$w_a + set_units(rnorm(nrow(.), 0, .data$sigma_H2O_s),
180
+ mmol / mol),
181
+ H2O_r = .data$w_0 + set_units(rnorm(nrow(.), 0, .data$sigma_H2O_r),
182
+ mmol / mol),
183
+ CO2_s = .data$C_air + set_units(rnorm(nrow(.), 0, .data$sigma_CO2_s),
184
+ umol / mol),
185
+ CO2_r = .data$c_0 + set_units(rnorm(nrow(.), 0, .data$sigma_CO2_r),
186
+ umol / mol),
187
+
188
+ # Derived estimates with error
189
+ E_meas = set_units(.data$flow * (.data$H2O_s - .data$H2O_r) /
190
+ (set_units(1) - .data$H2O_s), mmol/s),
191
+ E_area_meas = set_units(.data$E_meas / .data$leaf_area, mmol / m^2 / s),
192
+ g_tw_meas = .data$E_area_meas * (set_units(1) - (.data$w_i + .data$H2O_s) / 2) / (.data$w_i - .data$H2O_s),
193
+ g_sc_meas = .data$g_tw_meas / 1.6, # this is only valid if cuticular conductance is 0 and boundary layer conductance is Inf
194
+ g_tc_meas = .data$g_sc_meas, # valid above assumption is true and g_mc is Inf
195
+ A_meas = set_units(.data$flow * (.data$CO2_r - .data$CO2_s * ((set_units(1) - .data$H2O_r) / (set_units(1) - .data$H2O_s))) / .data$leaf_area, umol / m^2 / s),
196
+ C_i_meas = set_units(((.data$g_tc_meas - .data$E_area_meas / 2) * .data$CO2_s - .data$A_meas) / (.data$g_tc_meas + .data$E_area_meas / 2), umol/mol)
197
+
198
+ )
199
+
200
+ }
data/R/t_functions.R ADDED
@@ -0,0 +1,134 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #' Temperature response functions
2
+ #'
3
+ #' @param T_leaf Leaf temperature in K
4
+ #'
5
+ #' @param a Constant to minimize residuals (Heskel et al. 2016)
6
+ #' @param b Linear coefficient to minimize residuals (Heskel et al. 2016)
7
+ #' @param c Quadratic coefficient to minimize residuals (Heskel et al. 2016)
8
+ #'
9
+ #' @param T2 Leaf temperature term (Kruse et al. 2008)
10
+ #' @param dEa Temperature-dependent change in Ea in K^2 (Kruse et al. 2008)
11
+ #' @param Ea_ref Activation energy in J mol-1 (Kruse et al. 2008)
12
+ #' @param Par_ref Parameter at reference temperature of 25 Celsius (Kruse et
13
+ #' al. 2008)
14
+ #'
15
+ #' @param dS Entropy parameter in J mol-1 (Medlyn et al. 2002)
16
+ #' @param Ea Activation energy in J mol-1 (Medlyn et al. 2002)
17
+ #' @param Hd Deactivation energy in J mol-1 (Medlyn et al. 2002)
18
+ #' @param Topt Optimum temperature of the process in K (Medlyn et al.
19
+ #' 2002)
20
+ #'
21
+ #' @param dH Change in enthalpy of the reaction at 25 C in J mol-1 (Hobbs et
22
+ #' al. 2013)
23
+ #' @param dCp Change in heat capacity of the enzyme between the
24
+ #' enzyme-substrate #' and enzyme-transition states in J mol-1 K-1 (Hobbs et
25
+ #' al. 2013)
26
+ #' @param dG Change in Gibbs free energy of the reaction at 25 C in J mol-1
27
+ #' (Hobbs et al. 2013)
28
+ #'
29
+ #' @return t_response_arrhenius calculates the rate of a process based on an
30
+ #' Arrhenius-type curve
31
+ #'
32
+ #' t_response_arrhenius_kruse fits a peaked Arrhenius response according to
33
+ #' Kruse et al. 2008.
34
+ #'
35
+ #' t_response_arrhenius_medlyn is a peaked Arrhenius response as found in
36
+ #' Medlyn et al. 2002.
37
+ #'
38
+ #' t_response_arrhenius_topt is a peaked Arrhenius temperature response
39
+ #' function.
40
+ #'
41
+ #' t_response_calc_dS calculates dS from the fitted Topt model.
42
+ #'
43
+ #' t_response_calc_topt calculates Topt for a process from Arrhenius
44
+ #' parameters.
45
+ #'
46
+ #' t_response_heskel is a quadratic temperature response according to
47
+ #' Heskel et al. 2016.
48
+ #'
49
+ #' t_response_mmrt is a macromolecular rate theory temperature response
50
+ #' according to Hobbs et al. 2013.
51
+ #'
52
+ #' @references
53
+ #'
54
+ #' Arrhenius S. 1915. Quantitative laws in biological chemistry. Bell.
55
+ #'
56
+ #' Heskel et al. 2016. Convergence in the temperature response of leaf
57
+ #' respiration across biomes and plant functional types. PNAS 113:3832-3837
58
+ #'
59
+ #' Hobbs et al. 2013. Change in heat capacity for enzyme catalysis
60
+ #' determines temperature dependence of enzyme catalyzed rates. ACS Chemical
61
+ #' Biology 8:2388-2393
62
+ #'
63
+ #' Kruse J, Adams MA. 2008. Three parameters comprehensively describe
64
+ #' the temperature response of respiratory oxygen reduction. Plant
65
+ #' Cell Environ 31:954-967
66
+ #'
67
+ #' Medlyn BE, Dreyer E, Ellsworth D, Forstreuter M, Harley PC,
68
+ #' Kirschbaum MUF, Le Roux X, Montpied P, Strassemeyer J, Walcroft A,
69
+ #' Wang K, Loutstau D. 2002. Temperature response of parameters of a
70
+ #' biochemically based model of photosynthesis. II. A review of
71
+ #' experimental data. Plant Cell Environ 25:1167-1179
72
+ #'
73
+ #' @rdname t_functions
74
+ #' @export
75
+ t_response_arrhenius <- function(T_leaf, Ea) {
76
+ exp(Ea * ((T_leaf) - 298.15) /
77
+ (298.15 * 8.314 * (T_leaf)))
78
+ }
79
+
80
+ #' @rdname t_functions
81
+ #' @export
82
+ t_response_arrhenius_kruse <- function(dEa, Ea_ref, Par_ref, T2) {
83
+ log(Par_ref) + (Ea_ref / 8.314) * T2 + dEa * T2^2
84
+ }
85
+
86
+ #' @rdname t_functions
87
+ #' @export
88
+ t_response_arrhenius_medlyn <- function(T_leaf, Ea, Hd, dS) {
89
+ exp(Ea * ((T_leaf) - 298.15) /
90
+ (298.15 * 8.314 * (T_leaf))) *
91
+ (1 + exp((298.15 * dS - Hd) / (298.15 * 8.314))) /
92
+ (1 + exp(((T_leaf) * dS - Hd) / ((T_leaf) * 8.314)))
93
+ }
94
+
95
+ #' @rdname t_functions
96
+ #' @export
97
+ t_response_arrhenius_topt <- function(T_leaf, Ea, Hd, Topt) {
98
+ Hd * exp(Ea * ((T_leaf) - (Topt)) /
99
+ ((T_leaf) * (Topt) * 8.314)) /
100
+ (Hd - Ea * (1 - exp(Hd * ((T_leaf) - (Topt)) /
101
+ ((T_leaf) * (Topt) * 8.314))))
102
+ }
103
+
104
+ #' @rdname t_functions
105
+ #' @export
106
+ t_response_calc_dS <- function(Ea,
107
+ Hd,
108
+ Topt) {
109
+ Hd / Topt + 8.314 * log(Ea / (Hd - Ea))
110
+ }
111
+
112
+ #' @rdname t_functions
113
+ #' @export
114
+ t_response_calc_topt <- function(Hd, dS, Ea) {
115
+ Hd / (dS - 8.314 * log(Ea / (Hd - Ea)))
116
+ }
117
+
118
+ #' @rdname t_functions
119
+ #' @export
120
+ t_response_heskel <- function(T_leaf, a, b, c) {
121
+ a + b * (T_leaf - 273.15) + c * (T_leaf - 273.15)^2
122
+ }
123
+
124
+ #' @rdname t_functions
125
+ #' @export
126
+ t_response_mmrt <- function(dCp,
127
+ dG,
128
+ dH,
129
+ T_leaf) {
130
+ (log(1.380649e-23 * (298.15) / 6.62607e-34)) -
131
+ dG / (8.314 * 298.15) +
132
+ (1 / 298.15 + dH / (8.314 * 298.15^2)) * ((T_leaf) - 298.15) +
133
+ (dCp / (2 * 8.314 * 298.15^2)) * ((T_leaf) - 298.15)^2
134
+ }
data/R/utils.R ADDED
@@ -0,0 +1,93 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ #' Convert pressure from PPM to Pascals
2
+ #'
3
+ #' @param ppm Pressure value in umol/mol of class `units`
4
+ #' @param P Atmospheric pressure value in kPa of class `units`
5
+ #'
6
+ #' @return Value in Pa of class `units`
7
+ #'
8
+ #' @details
9
+ #'
10
+ #' \deqn{\mathrm{Press}(kPa) = \mathrm{Press}(ppm) P(kPa)}{Press(kPa) = Press(ppm) P(kPa)}
11
+ #' \deqn{\mathrm{Press}(Pa) = 1000 \mathrm{Press}(kPa)}{Press(Pa) = 1000 Press(kPa)}
12
+ #'
13
+ #' @examples
14
+ #'
15
+ #' ppm = set_units(400, "umol/mol")
16
+ #' P = set_units(101.325, "kPa")
17
+ #' ppm2pa(ppm, P)
18
+ #' @export
19
+ #'
20
+
21
+ ppm2pa = function(ppm, P) {
22
+ set_units(ppm * P, Pa)
23
+ }
24
+
25
+ #' Convert number to scientific notation in LaTeX or R documentation
26
+ #'
27
+ #' @param x vector of numbers to convert
28
+ #' @param .threshold integer threshold for order of magnitude to use scientific notation
29
+ #' @param .digits integer number of significant digits
30
+ #' @param .format character indicating whether to format output for LaTeX "latex" or R documentation "r"
31
+ #'
32
+ #' @noRd
33
+ scientize = function(x, .threshold = -1L, .digits = 2L, .format = "r") {
34
+
35
+ purrr::map_chr(x, function(.x, .threshold, .digits, .format) {
36
+
37
+ if (is.na(.x)) {
38
+ return(NA)
39
+ } else {
40
+ oom = log10(abs(.x))
41
+ if (oom < .threshold) {
42
+ x1 = .x |>
43
+ magrittr::multiply_by(10 ^ -floor(oom)) |>
44
+ round(.digits)
45
+
46
+ x2 = sprintf(glue::glue("%.{.digits}f"), x1) |>
47
+ stringr::str_c("\\times 10^{", floor(oom), "}")
48
+
49
+ if (.format == "r") {
50
+ x2 = glue::glue("\\eqn{<x2>}", .open = "<", .close = ">")
51
+ }
52
+
53
+ return(x2)
54
+ } else {
55
+ x1 = .x |>
56
+ signif(.digits + 1L) |>
57
+ as.character()
58
+ return(x1)
59
+ }
60
+ }
61
+ }, .threshold = .threshold, .digits = .digits, .format = .format)
62
+
63
+ }
64
+
65
+ #' Make table for R documentation on photosynthesis parameters
66
+ #'
67
+ #' @param ... arguments passed to dplyr::filter()
68
+ #'
69
+ #' @noRd
70
+ make_photo_parameter_table = function(...) {
71
+
72
+ photosynthesis::photo_parameters |>
73
+ dplyr::filter(...) |>
74
+ dplyr::mutate(
75
+ Symbol = glue::glue("\\eqn{<symbol>}", .open = "<", .close = ">"),
76
+ R = glue::glue("\\code{<R>}", .open = "<", .close = ">"),
77
+ Units = stringr::str_replace_all(units, "([A-Za-z]+)\\^([0-9]+)",
78
+ "\\1\\\\eqn{^\\2}"),
79
+ Default = scientize(.data$default, .threshold = -2L, .format = "r")
80
+ ) |>
81
+ dplyr::select(.data$Symbol, .data$R, Description = .data$description,
82
+ .data$Units, .data$Default) |>
83
+ knitr::kable()
84
+
85
+ }
86
+
87
+ #' Round a numeric value to nearest element in set of possible values
88
+ #' @noRd
89
+ round_to_nearest = function(x, values) {
90
+ sapply(x, function(y, values) {
91
+ values[which.min(abs(y - values))]
92
+ }, values = values)
93
+ }
data/README.Rmd ADDED
@@ -0,0 +1,103 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ---
2
+ output: github_document
3
+ pagetitle: README
4
+ ---
5
+
6
+ <!-- README.md is generated from README.Rmd. Please edit that file -->
7
+
8
+ ```{r echo=FALSE}
9
+ knitr::opts_chunk$set(
10
+ warning = FALSE,
11
+ message = FALSE,
12
+ collapse = TRUE,
13
+ comment = "#>",
14
+ fig.path = "man/figures/README-",
15
+ out.width = "100%"
16
+ )
17
+ ```
18
+ # photosynthesis <img src="man/figures/logo.png" align="right" height="200" width="200"/>
19
+
20
+ <!-- badges: start -->
21
+ [![CRAN status](https://www.r-pkg.org/badges/version/photosynthesis)](https://cran.r-project.org/package=photosynthesis)
22
+ [![](https://cranlogs.r-pkg.org/badges/photosynthesis)](https://cran.r-project.org/package=photosynthesis)
23
+ [![R-CMD-check](https://github.com/cdmuir/photosynthesis/actions/workflows/R-CMD-check.yaml/badge.svg)](https://github.com/cdmuir/photosynthesis/actions/workflows/R-CMD-check.yaml)
24
+ <!-- badges: end -->
25
+
26
+ ## Model C3 Photosynthesis
27
+
28
+ ## Description
29
+
30
+ **photosynthesis** is an R package with modeling tools for C3 photosynthesis, as well as analytical tools for curve-fitting plant ecophysiology responses. It uses the R package [**units**](https://CRAN.R-project.org/package=units) to ensure that parameters are properly specified and transformed before calculations.
31
+
32
+ ## Get **photosynthesis**
33
+
34
+ From CRAN
35
+
36
+ ```r
37
+ install.packages("photosynthesis")
38
+ ```
39
+
40
+ or from GitHub
41
+
42
+ ```r
43
+ install.packages("remotes")
44
+ remotes::install_github("cdmuir/photosynthesis")
45
+ ```
46
+
47
+ And load `photosynthesis`
48
+
49
+ ```r
50
+ library("photosynthesis")
51
+ ```
52
+
53
+ ## Vignettes
54
+
55
+ See the following vignettes for examples of what **photosynthesis** can do:
56
+
57
+ * [Introduction to the photosynthesis package][photosynthesis-introduction]
58
+ * [Modeling C3 Photosynthesis: recommendations for common scenarios][modeling-recommendations]
59
+ * [Fitting light response curves][light-response]
60
+ * [Fitting CO2 response curves][co2-response]
61
+ * [Fitting temperature response curves][temperature-response]
62
+ * [Fitting stomatal conductance models][stomatal-conductance]
63
+ * [Fitting light respiration][light-respiration]
64
+ * [Fitting mesophyll conductance][mesophyll-conductance]
65
+ * [Fitting pressure-volume curves][pressure-volume]
66
+ * [Fitting hydraulic vulnerability curves][hydraulic-vulnerability]
67
+ * [Sensitivity Analysis][sensitivity-analysis]
68
+
69
+ [photosynthesis-introduction]: https://cdmuir.github.io/photosynthesis/articles/photosynthesis-introduction.html
70
+ [modeling-recommendations]: https://cdmuir.github.io/photosynthesis/articles/modeling-recommendations.html
71
+ [light-response]: https://cdmuir.github.io/photosynthesis/articles/light-response.html
72
+ [co2-response]: https://cdmuir.github.io/photosynthesis/articles/co2-response.html
73
+ [temperature-response]: https://cdmuir.github.io/photosynthesis/articles/temperature-response.html
74
+ [stomatal-conductance]: https://cdmuir.github.io/photosynthesis/articles/stomatal-conductance.html
75
+ [light-respiration]: https://cdmuir.github.io/photosynthesis/articles/light-respiration.html
76
+ [mesophyll-conductance]: https://cdmuir.github.io/photosynthesis/articles/mesophyll-conductance.html
77
+ [pressure-volume]: https://cdmuir.github.io/photosynthesis/articles/pressure-volume.html
78
+ [hydraulic-vulnerability]: https://cdmuir.github.io/photosynthesis/articles/hydraulic-vulnerability.html
79
+ [sensitivity-analysis]: https://cdmuir.github.io/photosynthesis/articles/sensitivity-analysis.html
80
+
81
+ ## Contributors
82
+
83
+ * [Joseph Stinziano](https://github.com/jstinzi)
84
+ * [Chris Muir](https://github.com/cdmuir)
85
+ * Cassaundra Roback
86
+ * Demi Sargent
87
+ * Bridget Murphy
88
+ * Patrick Hudson
89
+
90
+ ## Comments and contributions
91
+
92
+ We welcome comments, criticisms, and especially contributions!
93
+ GitHub issues are the preferred way to report bugs, ask questions, or request new features.
94
+ You can submit issues here:
95
+
96
+ https://github.com/cdmuir/photosynthesis/issues
97
+
98
+ ## Meta
99
+
100
+ * Please [report any issues or bugs](https://github.com/cdmuir/photosynthesis/issues).
101
+ * License: MIT
102
+ * Get citation information for **photosynthesis** in R doing `citation(package = 'photosynthesis')`
103
+ * Please note that this project is released with a [Contributor Code of Conduct](https://github.com/cdmuir/photosynthesis/blob/master/CONDUCT.md). By participating in this project you agree to abide by its terms.
data/_pkgdown.yml ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ url: https://github.com/cdmuir/photosynthesis
2
+
3
+ template:
4
+ bootstrap: 5
data/cran-comments.md ADDED
@@ -0,0 +1,25 @@
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
+ ## Summary of new changes
2
+
3
+ * Fixed broken URL in NEWS.md
4
+ * Added `photoinhibition()` to light response models. This allows users to estimate photoinhibition at high light.
5
+
6
+ ## Test environments
7
+ * local R installation, R 4.4.2
8
+ * ubuntu 22.04.5 (on Github actions), R 4.4.2
9
+ * rhub (version 2):
10
+ - Ubuntu 22.04.5, R-devel, gcc
11
+ - Microsoft Windows Server 2022 10.0.20348, R-devel
12
+ - macOS 13.7.1, R-release, clang
13
+
14
+ ## R CMD check results
15
+
16
+ ❯ checking installed package size ... NOTE
17
+ installed size is 7.4Mb
18
+ sub-directories of 1Mb or more:
19
+ doc 6.2Mb
20
+
21
+ ## rhub results
22
+ Tested using `rhub` version 2. All checks passed successfully on the above platforms.
23
+
24
+ ## Downstream dependencies
25
+ No known issues with downstream dependencies.
data/data-raw/li6800_example.R ADDED
@@ -0,0 +1,8 @@
 
 
 
 
 
 
 
 
 
1
+ ## code to prepare `li6800_example` dataset goes here
2
+
3
+ usethis::use_data(li6800_example, overwrite = TRUE)
4
+
5
+ file.copy(
6
+ "/Users/cdmuir/Library/CloudStorage/[email protected]/Shared drives/muir-lab/adaptive-amphistomy/raw-data/licor/2023-04-23-0804_logdata",
7
+ "inst/extdata/li6800_example"
8
+ )
data/data-raw/photo-2d-parameters.R ADDED
@@ -0,0 +1,7 @@
 
 
 
 
 
 
 
 
1
+ ## code to prepare `photo-2d-parameters` data set goes here
2
+
3
+ # Import shared parameters from photo_parameters
4
+ photo_parameters = readr::read_csv("inst/extdata/photo-parameters.csv")
5
+ photo_2d_parameters = readr::read_csv("inst/extdata/photo-2d-parameters.csv")
6
+
7
+ usethis::use_data(photo_parameters, overwrite = TRUE)
data/data-raw/photo-parameters.R ADDED
@@ -0,0 +1,4 @@
 
 
 
 
 
1
+ ## code to prepare `photo-parameters` data set goes here
2
+ photo_parameters = readr::read_csv("inst/extdata/photo-parameters.csv")
3
+
4
+ usethis::use_data(photo_parameters, overwrite = TRUE)
data/data/photo_parameters.rda ADDED
Binary file (3.02 kB). View file