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

```{r setup, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
skip_vignette <- !reticulate::py_module_available("kuzu")
```

## Introduction

This vignette demonstrates how to convert Kuzu query results into various R graph library objects, including `igraph`, `tidygraph`, and `g6R`. It showcases the seamless integration of `kuzuR` with popular R packages for graph analysis and visualization.

## Converting to `igraph`

The `igraph` package is a powerful tool for graph manipulation and analysis in R. `kuzuR` provides a direct conversion function `as_igraph()` to transform Kuzu query results into `igraph` objects.

### Example: Loading and Converting Graph Data

First, let's set up a Kuzu database and load some sample graph data.

```{r, eval=!skip_vignette}
library(kuzuR)
library(igraph)

# Create a connection
db_path <- tempfile()
con <- kuzu_connection(db_path)

# Create schema for nodes and relationships
kuzu_execute(con, paste("CREATE NODE TABLE Person(name STRING, age INT64,",
                        "PRIMARY KEY (name))"))
kuzu_execute(con, "CREATE REL TABLE Knows(FROM Person TO Person, since INT64)")

# Prepare data frames
persons_data <- data.frame(
  name = c("Alice", "Bob", "Carol"),
  age = c(35, 45, 25)
)

knows_data <- data.frame(
  from_person = c("Alice", "Bob"),
  to_person = c("Bob", "Carol"),
  since = c(2010, 2015)
)

# Load data into Kuzu
kuzu_copy_from_df(con, persons_data, "Person")
kuzu_copy_from_df(con, knows_data, "Knows")
```

Now, let's execute a query that returns graph data and convert it to an `igraph` object.

```{r, eval=!skip_vignette}
# Query to get all persons and their relationships
graph_query_result <- kuzu_execute(con, paste("MATCH (p1:Person)-[k:Knows]->",
                                              "(p2:Person) RETURN p1, p2, k"))

# Convert the Kuzu result to an igraph object
igraph_graph <- as_igraph(graph_query_result)

# Print the igraph object summary
print(igraph_graph)

V(igraph_graph)$label <- igraph::V(igraph_graph)$name
E(igraph_graph)$label <- "knows"
plot(igraph_graph)
```

You can now perform standard `igraph` operations on `igraph_graph`.

## Converting to `tidygraph`

The `tidygraph` package offers a tidy data approach to graph manipulation, integrating seamlessly with the tidyverse. `kuzuR` supports conversion to `tidygraph` objects via `as_tidygraph()`.

### Example: Converting to `tidygraph`

Using the same Kuzu query result, we can convert it to a `tidygraph` object.

```{r, eval=!skip_vignette}
# Convert the Kuzu result to a tidygraph object
tidygraph_graph <- as_tidygraph(graph_query_result)

# Print the tidygraph object summary
print(tidygraph_graph)
plot(tidygraph_graph)
```

## Interactive Visualization with `g6R`

The `g6R` package provides an R interface to the G6 JavaScript graph visualization library, enabling rich, interactive visualizations directly within R environments. Since `g6R` has built-in support for `igraph` objects, you can easily create interactive visualizations by first converting your Kuzu query result to an `igraph` object.

### Example: Creating an Interactive `g6R` Graph

Building on the previous examples, we can convert the Kuzu query result into a `g6R` object. We can then customize the appearance of the nodes and edges for a more informative visualization.

```{r, eval=!skip_vignette}
library(g6R)
graph_query_result <- kuzu_execute(con, paste("MATCH (p1:Person)-[k:Knows]->",
                                              "(p2:Person) RETURN p1, p2, k"))
# Convert the Kuzu result to a g6R-compatible list
igraph_graph <- as_igraph(graph_query_result)

g6 <- g6_igraph(igraph_graph) |>
  g6_layout(d3_force_layout()) |>
  g6_options(
    animation = FALSE,
    node = list(
      style = list(
        labelText = JS("(d) => d.name")
      )
    ),
    edge = list(
      style = list(
        endArrow = TRUE,
        labelText = JS("(d) => d.data.label")
      )
    )
  ) |>
  g6_behaviors(
    zoom_canvas(),
    collapse_expand(),
    drag_canvas(),
    drag_element()
  ) |>
  g6_plugins("toolbar")


# Display the graph
g6
```
