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

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

```{r setup}
library(RGDrivers)
library(terra)
```

## Introduction

`RGDrivers` provides tools for analyzing stream networks, including the
construction of directed graphs from stream reaches, the calculation of
Link Magnitude (Shreve stream order) and D-LINK (downstream reach order),
and the export of results back to a spatial file.

This vignette uses the small sample set of stream reaches included in the
package (`inst/extdata/rede_exemplo.gpkg`).

## Loading the sample data

```{r}
network <- vect(system.file("extdata", "rede_exemplo.gpkg", package = "RGDrivers"))
network
```

## Creating the directed graph

```{r}
g <- create_network_graph(network, col_id = "id", col_downstream = "jus")
g
```

## Calculating the Link Magnitude (Shreve)

```{r}
lm <- calculate_link_magnitude(g)
lm
```

## Calculating the D-LINK

```{r}
df <- as.data.frame(network)
df$link_mag <- lm[as.character(df$id)]
df <- calculate_dlink(df, col_id = "id", col_downstream = "jus", col_order = "link_mag")
df
```

## Writing the result to a new spatial vector

```{r}
network$link_mag <- df$link_mag
network$D_LINK <- df$D_LINK

output <- tempfile(fileext = ".gpkg")
write_network_with_orders(
  original_vector = network,
  updated_df = df,
  col_id = "id",
  additional_cols = c("link_mag", "D_LINK"),
  output_path = output
)
file.exists(output)
```
