---
title: "cyjShiny Introduction"
author: "Paul Shannon and Augustin Luna"
package: cyjShiny
date: "`r Sys.Date()`"
output:
  html_document:
    toc: yes
vignette: >
  %\VignetteIndexEntry{"cyjShiny Introduction: a simple demo"}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

<style>
.main-container { width: 1200px; max-width:2800px;}
</style>


```{r setup, include = FALSE}
options(width=120)
knitr::opts_chunk$set(
   collapse = TRUE,
   eval=interactive(),
   echo=TRUE,
   comment = "#>"
)
```

# Introduction 

cyjShiny is a Shiny widget based on [htmlWidgets](http://www.htmlwidgets.org/index.html) for network visualization using [cytoscape.js](https://js.cytoscape.org/).


# Installation

```
install.packages("cyjShiny") 
```

# Demo Files 

Demo files are files in `inst/demos` folder of the project code repository: https://github.com/cytoscape/cyjShiny

# Quick Start Example 

* Running the following code in RStudio will produce output in the Viewer panel
* Running this code as an RMarkdown chunk will embed the cyjShiny network visualization into the document

```{r}
library(cyjShiny)

# NETWORK DATA ----
tbl_nodes <- data.frame(id=c("A", "B", "C"), 
                        size=c(10, 20, 30),
                        stringsAsFactors=FALSE)

# Must have the interaction column 
tbl_edges <- data.frame(source=c("A", "B", "C"),
                        target=c("B", "C", "A"),
                        interaction=c("inhibit", "stimulate", "inhibit"),
                        stringsAsFactors=FALSE)

graph_json <- toJSON(dataFramesToJSON(tbl_edges, tbl_nodes), auto_unbox=TRUE)

# graph_json is a string with JSON content that is input to cytoscape.js
print(graph_json)

cyjShiny(graph=graph_json, layoutName="cola")
```
# Styling 

Many of the visual properties of a network can be stylized. 

* [Styling Documentation](https://js.cytoscape.org/#style)
* Example Styling (`data()` maps data dynamically to specify a property value from the input data.frame):

```{}
[
  {"selector":"node", "css": {
    "border-width": "2px",
    "width": "data(size)",
    "height": "data(size)", 
    "content": "data(id)"
  }},
  {"selector": "edge[interaction='stimulate']", "css": {
    "line-color": "green"
  }},
  {"selector": "edge[interaction='inhibit']", "css": {
    "line-color": "red"
  }}
]
```

## Styling Usage with Quick Start Example: 

Save the example styling to a file `style.js` in the current working directory and replace `cyjShiny()` in the Quick Start example as shown below:

```{r}
style_file <- system.file(file.path("demos", "rmarkdownDemo", "style.js"), package="cyjShiny")
cyjShiny(graph_json, layoutName="cola", styleFile=style_file)
```

# Layouts 

[Cytoscape.js](https://js.cytoscape.org/) includes many layouts by default, including: cola, cose, circle, concentric, grid, breadthfirst, random, fcose, spread, preset


```{r}
yeast_galactose_style_file <- system.file(file.path("demos", "rmarkdownDemo", "yeastGalactoseStyle.js"), package="cyjShiny")
yeast_galactose_graph <- readLines(system.file(file.path("demos", "rmarkdownDemo", "yeastGalactose.cyjs"), package="cyjShiny"))

cyjShiny(yeast_galactose_graph, layoutName="fcose", styleFile=yeast_galactose_style_file)
```

## Preset Layout

The `preset` layout can be used to retain a layout 

```{r}
style_file <- system.file(file.path("demos", "rmarkdownDemo", "preset_style.js"), package="cyjShiny")
graph_json <- readLines(system.file(file.path("demos", "rmarkdownDemo", "preset_graph.js"), package="cyjShiny"))
cyjShiny(graph_json, layoutName="preset", styleFile=style_file)
```

# cyjShiny and Cytoscape Desktop

Networks from the [Cytoscape Desktop](https://cytoscape.org/) can also be visualized within cyjShiny. Users can export the network for use with cytoscape.js (cyjShiny-compatible) format in this way: 

`File -> Export -> Network to File -> Export File Format: "Cytoscape.js JSON (*.js)"`

Any layouts generated in Cytoscape Desktop can be retained in cyjShiny by using the `preset` layout as shown in the example.

```{r}
preset_graph_file <- system.file(file.path("demos", "fromCytoscapeDesktop", "small", "cyjshiny.cyjs"), package="cyjShiny")
graph_json <- readAndStandardizeJSONNetworkFile(preset_graph_file)
writeLines(graph_json, "cyjshiny_cytoscape_desktop.cyjs")

cyjShiny(graph_json, layoutName="preset")
```


# cyjShiny as Part of Shiny Applications

The following code create a minimal R Shiny application with network visualization using cyjShiny and cytoscape.js. 

```{r app, prompt=TRUE, message=TRUE, results="hold", eval=FALSE}
library(shiny)
library(cyjShiny)
library(graph)
library(jsonlite)

# NETWORK DATA ----
tbl_nodes <- data.frame(id=c("A", "B", "C"), 
                        size=c(10, 20, 30),
                        stringsAsFactors=FALSE)

# Must have the interaction column 
tbl_edges <- data.frame(source=c("A", "B", "C"),
                        target=c("B", "C", "A"),
                        interaction=c("inhibit", "stimulate", "inhibit"),
                        stringsAsFactors=FALSE)

graph_json <- toJSON(dataFramesToJSON(tbl_edges, tbl_nodes), auto_unbox=TRUE)

# UI ----
ui <- fluidPage(cyjShinyOutput('cyjShiny'))

# SERVER ----
server <- function(input, output, session) {
  output$cyjShiny <- renderCyjShiny({
    # Layouts (see js.cytoscape.org): cola, cose, circle, concentric, grid, breadthfirst, random, fcose, spread
    cyjShiny(graph_json, layoutName="cola")
  })
}

# RUN ----
shinyApp(ui=ui, server=server)
```
