---
title: "fda models"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{fda models}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include = FALSE}
if (requireNamespace("mda", quietly = TRUE)) {
  library(tidypredict)
  library(dplyr)
  eval_code <- TRUE
} else {
  eval_code <- FALSE
}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  eval = eval_code
)
```

| Function                                                      |Works|
|---------------------------------------------------------------|-----|
|`tidypredict_fit()`, `tidypredict_sql()`, `parse_model()`      |  ✔  |
|`tidypredict_to_column()`                                      |  ✗  |
|`tidypredict_test()`                                           |  ✗  |
|`tidypredict_interval()`, `tidypredict_sql_interval()`         |  ✗  |
|`parsnip`                                                      |  ✔  |

`mda::fda()` fits flexible discriminant analysis models. Predicting with such a
model runs the predictors through a regression fit, projects the result onto the
discriminant variates, and turns the distance to each class centroid into a
posterior probability. When the regression fit is linear in the predictors, the
whole path collapses into one linear predictor per outcome class and the
posterior probabilities are the softmax of those linear predictors.

That restricts support to the two linear regression methods: `mda::polyreg()`
(the default) with `degree = 1`, and `mda::gen.ridge()`, which is what
`discrim_linear()` uses. Higher polynomial degrees and the `mda::mars()` and
`mda::bruto()` methods are not supported, and neither are the mixture models
from `mda::mda()`.

Because these models predict one probability per outcome class,
`tidypredict_fit()` returns a *named list* of expressions, one for each class,
rather than a single expression. Since the output is a list,
`tidypredict_to_column()` and `tidypredict_test()` are not supported.

## `tidypredict_` functions

```{r}
model <- mda::fda(Species ~ ., data = iris)
```

- Create the R formulas, one per class
    ```{r}
fit <- tidypredict_fit(model)
names(fit)
fit[["setosa"]]
    ```

- Add the predictions to the original table
    ```{r}
library(dplyr)

iris %>%
  mutate(!!!tidypredict_fit(model)) %>%
  glimpse()
    ```

- Confirm that the results match the model's `predict()` results
    ```{r}
probs <- sapply(fit, \(f) rlang::eval_tidy(f, iris))
all.equal(unname(probs), unname(predict(model, iris, type = "posterior")))
    ```

## parsnip

`parsnip` fitted models are also supported by `tidypredict`:
```{r}
library(parsnip)
library(discrim)

p_model <- discrim_linear(penalty = 1) %>%
  set_engine("mda") %>%
  fit(Species ~ ., data = iris)
```

```{r}
tidypredict_fit(p_model)[["virginica"]]
```

## Parse model spec

Here is an example of the model spec:
```{r}
pm <- parse_model(model)
str(pm, 2)
```
