---
title: "grid function"
author: "cgmguru Developers"
date: "`r Sys.Date()`"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{grid function}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r setup, include=FALSE}
knitr::opts_chunk$set(collapse = TRUE, comment = "#>")
library(cgmguru)
library(iglu)
```

# Introduction

The GRID (Glucose Rate Increase Detector) algorithm is designed to automatically detect rapid increases in continuous glucose monitoring (CGM) data. This is frequently used for meal detection and evaluating time periods of significant glucose change.

This vignette demonstrates how to use the `grid` function from the `cgmguru` package with real CGM data examples.

`grid()` operates on the timestamps and glucose values supplied in `df`. It does not automatically call `interpolate_cgm()` and does not use the full-day event preprocessing grid unless you explicitly pass interpolated data to `grid()`.

# Example Data

The `iglu` package provides example multi-subject and single-subject datasets that we use here.

```{r data-load}
data(example_data_5_subject)
data(example_data_hall)
```

# Basic GRID Analysis

We'll run the GRID algorithm on a 5-subject CGM dataset, using default parameter values (`gap = 15` minutes, `threshold = 130 mg/dL/h`).

```{r grid-analysis}
grid_result <- grid(example_data_5_subject, gap = 15, threshold = 130)

# View the number of GRID events detected per subject
print(grid_result$episode_counts)

# View the start points of GRID events
print(head(grid_result$episode_start))

# See the identified points in the time series
grid_points <- head(grid_result$grid_vector)
print(grid_points)
```

# Parameter Sensitivity

You can adjust the `gap` and `threshold` for more or less sensitive detection. For example, lowering the threshold detects less pronounced glucose rises.

```{r grid-sensitive}
sensitive_result <- grid(example_data_5_subject, gap = 10, threshold = 120)

print(head(sensitive_result$episode_counts))
```

# Larger Dataset Example

Apply GRID analysis to a larger CGM dataset:

```{r grid-large}
large_grid <- grid(example_data_hall, gap = 15, threshold = 130)
print(paste("Detected", sum(large_grid$episode_counts$episode_counts), "episodes"))
```

# Plotting GRID Events Over Time

Here is how you might visualize GRID event starts against glucose time series for one subject:

```{r plot-grid, fig.height=4}
library(ggplot2)
subid <- example_data_5_subject$id[1]
subdata <- example_data_5_subject[example_data_5_subject$id == subid, ]
substarts <- grid_result$episode_start[grid_result$episode_start$id == subid, ]

plot <- ggplot(subdata, aes(x = time, y = gl)) +
  geom_line() +
  geom_point(data = substarts, aes(x = time, y = gl), color = 'red', size = 2) +
  labs(title = paste("GRID Events for Subject", subid), y = "Glucose (mg/dL)")
plot
```

# Conclusion

The GRID function automates the detection of rapid glycemic events in CGM data, supporting clinical research and personalized diabetes care.

For further exploration, see function reference or try out other algorithms and parameters in `cgmguru`.

# How to Open this Vignette in RStudio

You can open this vignette in the RStudio Help tab at any time with the following command:

```r
browseVignettes("cgmguru")
```

This command will list all vignettes for the `cgmguru` package; click on "grid" to view this vignette in the Help panel.
