---
title: "Getting started with leafareaR"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Getting started with leafareaR}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  warning = FALSE,
  message = FALSE,
  fig.width = 5.8,
  fig.height = 4.0,
  fig.align = "center"
)

library(leafareaR)
library(knitr)

data("leafarea_sample", package = "leafareaR")

dat <- la_validate_input(leafarea_sample)

dat2 <- la_create_derived(
  dat,
  variables = c("LW", "L2", "W2", "L3", "W3", "L_plus_W")
)

desc <- la_descriptive_stats(dat2, variables = c("L", "W", "LA", "LW"))
desc_out <- desc[, c("variable", "mean", "sd", "min", "max")]
names(desc_out) <- c("Variable", "Mean", "SD", "Min", "Max")

fit_linear <- la_fit_linear_models(dat2)
met_linear <- la_evaluate_linear_models(fit_linear)
ranked_linear <- la_rank_models(met_linear)
top_linear <- la_top_models(ranked_linear, n = 3)

top_linear_out <- top_linear[, c("model_id", "RMSE", "MAE", "R2", "AIC")]
names(top_linear_out) <- c("Model", "RMSE", "MAE", "R2", "AIC")

best_id <- ranked_linear$model_id[1]
best_model <- fit_linear$models[[best_id]]
best_equation <- la_build_equation(best_model)

pred <- la_predict_top_ranked(
  ranked_table = ranked_linear,
  fit_object = fit_linear,
  rank_position = 1,
  newdata = dat2[1:10, ]
)

pred_out <- pred[1:6, c("LA", "LA_pred", "residual")]
names(pred_out) <- c("Observed LA", "Predicted LA", "Residual")

vals <- la_linear_fitted_values(fit_linear, best_id)
```

# Overview

`leafareaR` provides a workflow for leaf area analysis based on leaf length
(`L`), leaf width (`W`), and observed leaf area (`LA`). The package includes
tools for input validation, predictor generation, model fitting, model
evaluation and ranking, equation extraction, prediction, graphics, and an
interactive Shiny application.

A typical analysis in `leafareaR` follows six steps:

1. validate the input data;
2. generate derived predictors;
3. fit candidate models;
4. evaluate and rank the fitted models;
5. inspect the selected equation;
6. generate predictions and graphics.

# Example dataset

The package includes a sample dataset named `leafarea_sample`. The example
below shows only the core variables used in most analyses.

```{r}
kable(leafarea_sample[1:6, c("L", "W", "LA")], digits = 3)
```

Additional grouping variables such as `block`, `species`, and `genotype` may
also be present and can be used in mixed-model workflows.

# Data preparation

The first step is to validate the required variables and, when needed, create
derived predictors from `L` and `W`.

```{r, echo=TRUE}
dat <- la_validate_input(leafarea_sample)

dat2 <- la_create_derived(
  dat,
  variables = c("LW", "L2", "W2", "L3", "W3", "L_plus_W")
)
```

A compact descriptive summary of selected variables is shown below.

```{r}
kable(desc_out, digits = 3)
```

# A linear modeling workflow

Linear candidate models can be fitted directly from the prepared data and then
ranked according to the selected evaluation criteria.

```{r, echo=TRUE}
fit_linear <- la_fit_linear_models(dat2)
met_linear <- la_evaluate_linear_models(fit_linear)
ranked_linear <- la_rank_models(met_linear)
```

For illustration, the next table shows only the three best-ranked linear
models.

```{r}
kable(top_linear_out, digits = 4)
```

In this example, the top-ranked model is `r best_id`.

# Equation extraction

A readable equation can be obtained from the selected model.

```{r, results='asis'}
cat(best_equation)
```

This equation can be reported directly or used as the basis for prediction.

# Prediction

Predictions can be generated from the top-ranked model for a new set of
observations.

```{r, echo=TRUE}
pred <- la_predict_top_ranked(
  ranked_table = ranked_linear,
  fit_object = fit_linear,
  rank_position = 1,
  newdata = dat2[1:10, ]
)
```

A small subset of the prediction output is shown below.

```{r}
kable(pred_out, digits = 4)
```

# Graphics

The package also includes simple graphics for exploratory analysis and model
inspection.

## Scatter plot

```{r}
la_plot_scatter(dat2, x = "LW", y = "LA")
```

## Observed versus predicted values

```{r}
la_plot_observed_predicted(
  observed = vals$observed,
  predicted = vals$fitted,
  model_name = best_id
)
```

# Extensions to nonlinear and mixed models

The same general strategy can be extended to nonlinear and mixed models:
fit, evaluate, rank, inspect the selected equation, and predict.

```{r, eval=FALSE}
fit_nonlinear <- la_fit_nonlinear_models(dat2, models = c("power_LW"))
met_nonlinear <- la_evaluate_nonlinear_models(fit_nonlinear)
ranked_nonlinear <- la_rank_models(met_nonlinear)

fit_mixed <- la_fit_mixed_models(dat2, group_var = "species")
met_mixed <- la_evaluate_mixed_models(fit_mixed)
ranked_mixed <- la_rank_models(met_mixed)
```

# Interactive use

`leafareaR` also provides a Shiny application for interactive analysis.

```{r, eval=FALSE}
run_leafareaR_app()
```

The application can be used to load the built-in example dataset
(`leafarea_sample`) or upload your own data, then select predictors, fit and
compare candidate models, inspect equations, and export results and graphics.

# Summary

`leafareaR` provides a reproducible workflow for leaf area analysis, from data
preparation to model comparison, equation reporting, prediction, and
visualization. The package can be used both in script-based analyses and
through its interactive Shiny interface.
