---
title: "Fitting hydraulic vulnerability curves"
author: "Joseph R. Stinziano and Christopher D. Muir"
date: "`r Sys.Date()`"
output: rmarkdown::html_document
vignette: >
 %\VignetteIndexEntry{hydraulic-vulnerability}
 %\VignetteEngine{knitr::rmarkdown}
 %\VignetteEncoding{UTF-8}
---

Current approach fits a sigmoidal model and calculates hydraulic parameters from
the curve fit (Pammenter & Van der Willigen 1998; Ogle *et al*. 2009).

```{r, message = FALSE}

library(dplyr)
library(photosynthesis)

# Read in data
dat = system.file("extdata", "hydraulic_vulnerability.csv", package = "photosynthesis") |>
  read.csv() |>
  mutate(ID = paste(Plot, Tree, sep = "_")) |>
  rename(psi = P)

# Fit hydraulic vulnerability curve
fit = fit_hydra_vuln_curve(
  filter(dat, Tree == 5, Plot == "Irrigation"),
  start_weibull = list(a = 2, b = 1),
  title = "Irrigation 5"
)

# Return Sigmoidal model summary
summary(fit[[1]]) 

# Return Weibull model summary
summary(fit[[4]]) #expecting a = 4.99, b = 3.22

# Return model parameters with 95% confidence intervals
fit[[2]] 

# Return hydraulic parameters
fit[[3]] 

# Return graph
# fit[[5]] 

# Fit many curves
fits = fit_many(
  data = dat,
  group = "ID",
  start_weibull = list(a = 4, b = 2),
  funct = fit_hydra_vuln_curve,
  progress = FALSE
)

# Return model summary
summary(fits[[1]][[1]])

# Return sigmoidal model output
fits[[1]][[2]] 

# Return hydraulic parameters
fits[[1]][[3]] 

# Return graph
# fits[[1]][[5]] 

# Compile parameter outputs
pars = compile_data(data = fits, output_type = "dataframe", list_element = 3)

# Compile graphs
graphs = compile_data(data = fits, output_type = "list", list_element = 5)

```

# References

Ogle K, Barber JJ, Willson C, Thompson B. 2009. Hierarchical statistical modeling of xylem vulnerability to cavitation. *New Phytologist* 182:541-554.

Pammenter NW, Van der Willigen CV. 1998. A mathematical and statistical analysis of the curves illustrating vulnerability of xylem to cavitation. *Tree Physiology* 18:589-593.
