---
title: "Two-dimensional density estimation"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Two-dimensional density estimation}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
set.seed(2026)
```

This vignette illustrates two-dimensional density estimation and visualization.
It complements the estimator-choice vignette by focusing on the 2D workflow.

```{r}
library(GLBFP)
```

## Simulated example

The example uses a small reproducible mixture so the vignette remains quick to
build.

```{r}
n <- 250
group <- rbinom(n, size = 1, prob = 0.5)

x <- cbind(
  rnorm(n, mean = ifelse(group == 1, -1.2, 1.2), sd = 0.7),
  rnorm(n, mean = ifelse(group == 1, 1.0, -1.0), sd = 0.8)
)

colnames(x) <- c("x1", "x2")

b <- compute_bi_optim(x, m = c(1, 1))
b
```

## Pointwise estimation

```{r}
x0 <- c(0, 0)

ash_fit <- ash(x0, x, b = b, m = c(1, 1))
lbfp_fit <- lbfp(x0, x, b = b)
glbfp_fit <- glbfp(x0, x, b = b, m = c(1, 1))

c(
  ASH = ash_fit$estimation,
  LBFP = lbfp_fit$estimation,
  GLBFP = glbfp_fit$estimation
)
```

## Grid estimation

```{r}
grid_fit <- glbfp_estimate(x, b = b, m = c(1, 1), grid_size = 20)
summary(grid_fit)
head(as.data.frame(grid_fit))
```

## Visualization

For two-dimensional regular grids, `contour = TRUE` returns a static
`ggplot2` contour plot.

```{r}
plot(grid_fit, contour = TRUE)
```

With `contour = FALSE`, the plot method returns an interactive `plotly` surface.
This is useful for exploration. Static contours are usually easier to reproduce
in manuscripts.

```{r}
surface <- plot(grid_fit, contour = FALSE)
surface
```

## Computational note

The number of evaluation points grows quickly with `grid_size` in two
dimensions. For manuscript figures, start with a moderate grid and increase it
only after confirming that the visual conclusions are stable.
