---
title: >
  Configuring `r Biocpkg("iSEE")` apps
author:
- name: Kevin Rue-Albrecht
  affiliation: 
  - &id4 Kennedy Institute of Rheumatology, University of Oxford,
    Headington, Oxford OX3 7FY, UK.
  email: kevin.rue-albrecht@kennedy.ox.ac.uk
- name: Federico Marini
  affiliation: 
  - &id1 Institute of Medical Biostatistics, Epidemiology and Informatics (IMBEI), Mainz
  - Center for Thrombosis and Hemostasis (CTH), Mainz
  email: marinif@uni-mainz.de
- name: Charlotte Soneson
  affiliation: 
  - &id3 Institute of Molecular Life Sciences, University of Zurich
  - SIB Swiss Institute of Bioinformatics
  email: charlottesoneson@gmail.com
- name: Aaron Lun
  affiliation: 
  - &id2 Cancer Research UK Cambridge Institute, University of Cambridge
  email: infinite.monkeys.with.keyboards@gmail.com 
date: "`r BiocStyle::doc_date()`"
package: "`r BiocStyle::pkg_ver('iSEE')`"
output: 
  BiocStyle::html_document:
    toc_float: true
vignette: >
  %\VignetteIndexEntry{3. Configuring iSEE apps}
  %\VignetteEncoding{UTF-8}  
  %\VignettePackage{iSEE}
  %\VignetteKeywords{GeneExpression, RNASeq, Sequencing, Visualization, QualityControl, GUI}
  %\VignetteEngine{knitr::rmarkdown}
editor_options: 
  chunk_output_type: console
bibliography: iSEE.bib
---

**Compiled date**: `r Sys.Date()`

**Last edited**: 2018-03-08

**License**: `r packageDescription("iSEE")[["License"]]`

```{r setup, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>",
  error = FALSE,
  warning = FALSE,
  message = FALSE
)
stopifnot(requireNamespace("htmltools"))
htmltools::tagList(rmarkdown::html_dependency_font_awesome())
sce <- readRDS("sce.rds")    
```

# Changing the default start configuration

The default start configuration with one plot of each type may not always be the most appropriate.
`iSEE` allows the user to programmatically modify the initial settings [@kra2018iSEE], avoiding the need to click through the choices to obtain the desired panel setup.
Almost every aspect of the initial app state can be customized, down to whether or not the parameter boxes are open or closed!

To demonstrate this feature, let's assume that we are only interested in _feature assay plot_ panels.
The default set of panels can be changed via the `initialPanels` argument of the `iSEE` function call.
Given a `SingleCellExperiment` or `SummarizedExperiment` object named `sce`^[We'll re-use the example from the `r Biocpkg("iSEE", vignette="basic.html", label="previous workflow")`.], the following code opens an app with two adjacent feature assay plots.
Note that each panel is set to occupy half the width of the application window, which is set to 12 units by the `r CRANpkg("shiny")` package.

```{r init}
library(iSEE)
init <- DataFrame(
    Name = c("Feature assay plot 1", "Feature assay plot 2"),
    Width = c(6, 6)
)
app <- iSEE(sce, initialPanels = init)
```

The genes to show on the Y-axis in the two plots can be specified via the `featAssayArgs` argument to `iSEE`. This is a `DataFrame`, specifying the initial parameters for each plot.
In this case, we want to modify the `YAxis` and `YAxisFeatName` defaults for the two plots:

```{r fexArg}
fexArg <- featAssayPlotDefaults(sce, 2)
fexArg$YAxisFeatName <- c("0610009L18Rik", "0610009B22Rik")
app <- iSEE(sce, initialPanels = init, featAssayArgs = fexArg)
```

This will open the app with two feature assay plots, showing the selected genes.
Of course, from this starting point, all the interactive functionality is still available, and new panels can be added, modified and linked via point selection.

# Data parameters

## Overview

The _data parameters_ control the source of the information represented on the X-axis and Y-axis of each plot.
Those parameters are accessible at runtime in the eponymous collapsible box.

We refer users to the individual help page of each panel type listed [below](#further) to learn more about the choices of X-axis variables for each type of panel.

From a running `iSEE` application, you can also display all the R code that is required to set up the current configuration by clicking on `Display panel settings` under the wrench icon in the top-right corner. 

## Setting the Y-axis

The nature of the Y-axis is defined by the type of panel.
For instance, _column data plot_ panels require the name of a column in the `colData(sce)`.
Users can preconfigure the Y-axis of individual _column data plot_ panels as follows:

```{r yaxis}
cdArgs <- colDataPlotDefaults(sce, 2)
cdArgs$DataBoxOpen <- TRUE
cdArgs$YAxis <- c("NREADS", "TOTAL_DUP")
init <- DataFrame(
    Name = c("Column data plot 1", "Column data plot 2"),
    Width = c(6, 6)
)
app <- iSEE(sce, initialPanels = init, colDataArgs = cdArgs)
```

## Setting the X-axis {#xaxis}

The X-axis can be set to different types of variables, which generally requires setting at least two columns in the `DataFrame` of arguments.
The type of variable is generally set in the `XAxis` column, while the name of the variable is stored in a different column for each type of variable.
At runtime, this allows the app to remember the last selected variable of each type.

For instance, the `XAxis` column of _feature assay plot_ arguments can have up to four different values:

1. `"None"`: does not require any addition input (draws a single violin for all features)
2. `"Column data"`: requires `XAxisColData` to be set to a column name in the `colData(sce)`
3. `"Feature name"`: requires either
    a. `XAxisFeatName` to be set to a feature name (or positional index) in `rownames(sce)`
    b. `XAxisRowTable` to be set to the name of a _Row statistics table_ panel with an active selection set in its own `Selected` column

Each of these scenarios is demonstrated below:

```{r xaxis}
fexArg <- featAssayPlotDefaults(sce, 4)
fexArg$DataBoxOpen <- TRUE

# Example 1
fexArg[1, "XAxis"] <- "None"

# Example 2
fexArg[2, "XAxis"] <- "Column data"
fexArg[2, "XAxisColData"] <- "Core.Type"

# Example 3a
fexArg[3, "XAxis"] <- "Feature name"
fexArg[3, "XAxisFeatName"] <- "Zyx"

# Example 3b (also requires a row statistic table)
fexArg[4, "XAxis"] <- "Feature name"
fexArg[4, "XAxisRowTable"] <- "Row statistics table 1"
rowData(sce)[, "gene_id"] <- rownames(sce)
rsArg <- rowStatTableDefaults(sce, 1)
rsArg$Selected <- "Ints2"
rsArg$SearchColumns <- list(gene_id="Ints")

# Initialisation
init <- DataFrame(
    Name = c(
        paste("Feature assay plot", 1:4),
        "Row statistics table 1"),
    Width = c(rep(6, 4), 12)
)
app <- iSEE(sce, initialPanels = init, featAssayArgs = fexArg, rowStatArgs = rsArg)
```

Note how _Example 3b_ requires an active _row statistics table_ as a source of selection.
To facilitate visualisation, we added the features identifiers as the `gene_id` column in `rowData(sce)`,
we preselected the feature `"Ints2"`, and we prefiltered the table using the pattern `"Ints"` on the `gene_id` column to show this active selection.

## Configuring the type of dimensionality reduction

In the case of reduced dimension plots, _data parameters_  include the name of the reduced dimension slot from which to fetch coordinates.
This information is stored in the `Type` column:

```{r redDimPlotDefaults-type}
rdArgs <- redDimPlotDefaults(sce, 1)
rdArgs$DataBoxOpen <- TRUE
rdArgs$Type <- "TSNE"
rdArgs$XAxis <- 2
rdArgs$YAxis <- 1
init <- DataFrame(
    Name = c("Reduced dimension plot 1"),
    Width = c(6)
)
app <- iSEE(sce, initialPanels = init, redDimArgs = rdArgs)
```

We refer users to the `?redDimPlotDefaults` help page to learn more about the choices of default parameters for _reduced dimension plot_ panels.

## Configuring the type of assay data {#assay}

For axes linked to an assay, such as the Y-axis of _feature assay plot_ panels, the assay to display can be set through the `Assay` column of the arguments:

```{r featAssayPlotDefaults-assay}
fexArg <- featAssayPlotDefaults(sce, 2)
fexArg$DataBoxOpen <- TRUE
fexArg$Assay <- c("rsem_counts", "tophat_counts")
init <- DataFrame(
    Name = paste("Feature assay plot", 1:2),
    Width = c(6, 6)
)
app <- iSEE(sce, initialPanels = init, featAssayArgs = fexArg)
```

# Visual parameters

## Overview

The _visual parameters_ control the appearance of data points.
Those parameters include: color, shape, size, opacity, facet, as well as font size and legend position.
Some visual parameters can be associated to variables and controlled through `r CRANpkg("ggplot2")` aesthetics, while others can be set to constant user-defined values.
All those parameters are accessible at runtime in the eponymous collapsible box.

We refer users to the `?"iSEE point parameters"`  help page to learn more about the visual parameters variables configurable for each type of panel;
and to the `?"iSEE selection parameters"` help page to learn more about the choices of parameters that control the appearance of point selections in receiver plot panels.

## Configuring default visual parameters

Certain visual parameters can be set to a constant user-defined value.
Those include: color, transparency (i.e., alpha), downsampling resolution, as well as text font size and legend position.

For instance, the default color of data points in _column data plot_ panels can be set to
a value different than the default `"black"` through the `ColorByDefaultColor` column,
while the default transparency value is controlled through the `PointAlpha` column.
Here, we alter several default visual parameters in the second panel:

```{r ColorByDefaultColor}
cdArgs <- colDataPlotDefaults(sce, 2)
cdArgs$VisualBoxOpen <- TRUE
cdArgs$VisualChoices <- list(c("Color", "Points", "Other"), c("Color", "Points", "Other"))
cdArgs$ColorByDefaultColor[2] <- c("chocolate3")
cdArgs$PointAlpha[2] <- 0.2
cdArgs$PointSize[2] <- 2
cdArgs$Downsample[2] <- TRUE
cdArgs$SampleRes[2] <- 150
cdArgs$FontSize[2] <- 2

init <- DataFrame(
    Name = c("Column data plot 1", "Column data plot 2"),
    Width = c(6, 6)
)
app <- iSEE(sce, initialPanels = init, colDataArgs = cdArgs)
```

Note that for this demonstration, we facilitate visualization of the preconfigured arguments by setting `VisualChoices` to display both the `"Color"` and `"Shape"` UI panels.

## Linking point aesthetics to variables

The color and point of data points can be linked to variables in a manner similar to the X-axis parameters demonstrated [above](#xaxis).

For instance, the color of data points in _column data plot_ panels can be set to a variable in `colData(sce)` by setting the `ColorBy` value to `"Column data"`, and the `ColorByColData` value to the desired coloumn name:

```{r aesthetic-covariate}
cdArgs <- colDataPlotDefaults(sce, 2)
cdArgs$VisualBoxOpen <- TRUE
cdArgs$VisualChoices <- list(c("Color", "Shape"), c("Color", "Shape"))
cdArgs$ColorBy <- "Column data"
cdArgs$ShapeBy <- "Column data"
cdArgs$ColorByColData <- c("Core.Type", "TOTAL_DUP")
cdArgs$ShapeByColData <- c("Core.Type", "driver_1_s")

init <- DataFrame(
    Name = c("Column data plot 1", "Column data plot 2"),
    Width = c(6, 6)
)
app <- iSEE(sce, initialPanels = init, colDataArgs = cdArgs)
```

Note that points may only be shaped by a categorical variable.

## Configuring plot facets

Categorical variables may also be used to facet plots by row and column.

For instance, _column data plot_ panels can be facet by variables stored in the columns of `colData(sce)`.
Users can enable faceting by setting `FacetByRow` and/or `FacetByColumn` columns to `TRUE`, and set `RowFacetByColData` and `ColumnFacetByColData` to the appropriate column name in `colData(sce)`.
We demonstrate below how faceting may be enable by row, column, or both:

```{r facet}
cdArgs <- colDataPlotDefaults(sce, 3)
cdArgs$VisualBoxOpen <- TRUE
cdArgs$VisualChoices <- list("Facets", "Facets", "Facets")
cdArgs$FacetByRow <- c(TRUE, FALSE, TRUE)
cdArgs$FacetByColumn <- c(FALSE, TRUE, TRUE)
cdArgs$RowFacetByColData <- "driver_1_s"
cdArgs$ColumnFacetByColData <- "Core.Type"
init <- DataFrame(
    Name = paste("Column data plot", 1:3),
    Width = c(4, 4, 4)
)
app <- iSEE(sce, initialPanels = init, colDataArgs = cdArgs)
```

# Selection parameters

## Shiny brush

The initial state of _iSEE_ applications can be configured all the way down to point selections and links between panels.
For instance, in the example below, we preconfigure the `SelectByPlot` column of a _column data plot_ panel to receive a point selection from a _reduced dimension plot_ panel.
This requires an active selection in the _reduced dimension plot_ panel, which is achieved by preconfiguring the `BrushData` column of the arguments.

The simplest way to obtain a valid input for the `BrushData` column is to launch an _iSEE_ application, make the desired selection using a Shiny brush, open the _iSEE_ code tracker, and copy paste the relevant point selection data.
The result should look as below:

```{r select-brish}
# Preconfigure the receiver panel
cdArgs <- colDataPlotDefaults(sce, 1)
cdArgs$SelectBoxOpen <- TRUE
cdArgs$SelectByPlot <- "Reduced dimension plot 1"
cdArgs$SelectEffect <- "Color"
cdArgs$SelectColor <- "darkgoldenrod1"

# Preconfigure the sender panel, including the point selection
rdArgs <- redDimPlotDefaults(sce, 1)
rdArgs$BrushData <- list(
        list(xmin = 2.8, xmax = 10.4, ymin = 0.6, ymax = 13.2, 
        mapping = list(x = "X", y = "Y"), domain = list(left = -14.0, right = 10.9, 
            bottom = -12.0, top = 16.4), range = list(left = 38.7, 
            right = 541.5, bottom = 466.0, top = 23.7), 
        log = list(x = NULL, y = NULL), direction = "xy", brushId = "redDimPlot1_Brush", 
        outputId = "redDimPlot1")
    )

init <- DataFrame(
    Name = c("Reduced dimension plot 1", "Column data plot 1"),
    Width = c(6, 6)
)
app <- iSEE(sce, initialPanels = init, redDimArgs = rdArgs, colDataArgs = cdArgs)
```

Note that in the example above, we chose to color selected data points in the receiver panel, by setting the `SelectEffect` argument to `"Color"`,
and the color of selected data points to `"darkgoldenrod1"`.
Other choices include `"Restrict"`, to show only the selected data points;
and `"Transparent"` (the default), to increase the transparency of unselected data points.

## Lasso selection

An identical process can be followed to preconfigure a lasso point selection:

```{r select-lasso}
# Preconfigure the receiver panel
cdArgs <- colDataPlotDefaults(sce, 1)
cdArgs$SelectBoxOpen <- TRUE
cdArgs$SelectByPlot <- "Reduced dimension plot 1"
cdArgs$SelectEffect <- "Color"
cdArgs$SelectColor <- "darkgoldenrod1"

# Preconfigure the sender panel, including the point selection
rdArgs <- redDimPlotDefaults(sce, 1)
rdArgs$LassoData <- list(
    list(lasso = NULL, closed = TRUE, panelvar1 = NULL, panelvar2 = NULL, mapping = list(
        x = "X", y = "Y"), coord = structure(c(9.7, 4.0, 2.0, 
        8.2, 10.5, 9.7, 9.0, 12.8, 7.9, 0.9, 2.1, 9.0), .Dim = c(6L, 
        2L)))
    )

init <- DataFrame(
    Name = c("Reduced dimension plot 1", "Column data plot 1"),
    Width = c(6, 6)
)
app <- iSEE(sce, initialPanels = init, redDimArgs = rdArgs, colDataArgs = cdArgs)
```

# Parameter fields accepting both integer/character

As we mentioned [earlier](#assay), certain parameters such as assay types may be set to either character or integer values.
Those include parameters referring to assays `*Assay`, features `*FeatName`, and samples `*Sample`.

We generally recommend to set those parameters using integer values; those are used internally and will always work even in the presence of unnamed assays, for instance:

```{r integer}
fexArg <- featAssayPlotDefaults(sce, 2)
fexArg$DataBoxOpen <- TRUE
fexArg$Assay <- c(6, 6)
fexArg$YAxisFeatName <- c(10, 11)
fexArg$XAxis <- "Feature name"
fexArg$XAxisFeatName <- c(12, 13)
init <- DataFrame(
    Name = paste("Feature assay plot", 1:2),
    Width = c(6, 6)
)
app <- iSEE(sce, initialPanels = init, featAssayArgs = fexArg)
```

Alternatively, users may refer to assays, features, and samples by their character name, if any.
However, users are advised against mixing character and integer values, as this will cause integer values to be converted to the character type.

For instance, the example below will fail to find an assay called `"6"` for the first panel, and it will instead fall back to using the first assay (`"tophat_counts`):

```{r character-integer}
fexArg <- featAssayPlotDefaults(sce, 2)
fexArg$DataBoxOpen <- TRUE
fexArg$Assay <- c(6, "counts")
init <- DataFrame(
    Name = paste("Feature assay plot", 1:2),
    Width = c(6, 6)
)
app <- iSEE(sce, initialPanels = init, featAssayArgs = fexArg)
```

We provide below an example where all parameters are defined as character values:

```{r character}
fexArg <- featAssayPlotDefaults(sce, 2)
fexArg$DataBoxOpen <- TRUE
fexArg$Assay <- c("logcounts", "counts")
fexArg$YAxisFeatName <- c("A3galt2", "A4galt")
fexArg$XAxis <- "Feature name"
fexArg$XAxisFeatName <- c("L3mbtl1", "L3mbtl2")
init <- DataFrame(
    Name = paste("Feature assay plot", 1:2),
    Width = c(6, 6)
)
app <- iSEE(sce, initialPanels = init, featAssayArgs = fexArg)
```

We refer users to the individual help page of each panel type listed [below](#further) to learn more about the parameters of each type of panel that accept integer and character values.

# Writing your own tour

By providing a data frame to the `tour` argument of `iSEE`, you can create your own tour that will start when the app is launched^[In theory. On servers, sometimes the tour does not recognize the UI elements at start-up and needs to be restarted via the "Click me for quick tour" button to work properly.]. 
The data frame should have two columns, `element` and `intro`:

```{r}
introtour <- read.delim(
	system.file("extdata/intro_firststeps.txt", package = "iSEE"), 
    sep = ";", header = TRUE)
head(introtour)
```

Each entry of the `element` column contains the name of a UI element in the application, prefixed by a hash sign (`#`).
The `intro` column contains the corresponding text (or basic HTML) that is to be shown at each step.

The simplest way to get started is to copy the `intro_firststeps.txt` file from the `inst/extdata` folder and edit it for your specific data set. 
More customized tours require some knowledge of the names of the UI elements to put in the `element` column.
We recommend one of the following options:

- If using Firefox, open the `Tools` menu. 
Select `Web Developer`, and in the submenu, select `Inspector`. 
This will toggle a toolbar, and you will be able to read out the name of the element of interest when you hover and click on it. 
If you want to select another element, you might need to re-click on the icon in the upper left corner of the toolbox, `Pick an element from the page`.
- If using Safari, open the `Develop` menu and select `Show Web Inspector`. 
To toggle the selection of elements, you need to click on the crosshair icon in the top part of the toolbox, then again, explore the desired element by clicking or hovering on it.
- If using Chrome, from the `View` menu, select first `Developer` and then `Developer Tools`. 
Click then on the selecting arrow in the top left corner, and similarly to the other browsers, hover or click on the element of interest to obtain its name.
- Alternatively, the [SelectorGadget](https://selectorgadget.com) browser extension can be used.

Most elements can be identified using the above strategies.
Selectize widgets are trickier but can be handled with, e.g., `#heatMapPlot1_ColData + .selectize-control`.
Please see the `intro_firststeps.txt` file in the `inst/extdata` folder for more of these examples.

Sometimes it is useful to place one step of the tour in the center. 
To do so, simply put a hash sign before a word which does not link directly to any CSS selector (e.g., as we do for `#Welcome`) in the corresponding `element` column.

# Further reading {#further}

Users should refer to the following help pages for the full list of values that can be specified in `iSEE`:

- `?redDimPlotDefaults`
- `?colDataPlotDefaults`
- `?featAssayPlotDefaults`
- `?rowDataPlotDefaults,`
- `?rowStatTableDefaults`
- `?sampAssayPlotDefaults`
- `?heatMapPlotDefaults`
- `?"iSEE point parameters"`
- `?"iSEE selection parameters"`

Some fairly complex configurations for a variety of data sets can be found at https://github.com/LTLA/iSEE2018.
These may serve as useful examples for setting up your own configurations.

# Session Info {.unnumbered}

```{r sessioninfo}
sessionInfo()
# devtools::session_info()
```

# References {.unnumbered}

