---
title: >
  Configuring iSEE apps
author:
- name: Kevin Rue-Albrecht
  affiliation: 
  - &id4 MRC WIMM Centre for Computational Biology, University of Oxford, Oxford, OX3 9DS, UK
  email: kevinrue67@gmail.com
- 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 Friedrich Miescher Institute for Biomedical Research, Basel, Switzerland
  - SIB Swiss Institute of Bioinformatics
  email: charlottesoneson@gmail.com
- name: Aaron Lun
  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**: 2020-04-20

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

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

```{r, eval=!exists("SCREENSHOT"), include=FALSE}
SCREENSHOT <- function(x, ...) knitr::include_graphics(x, dpi = NA)
```

# 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)
app <- iSEE(sce, initial=list(
    FeatureAssayPlot(PanelWidth=6L),
    FeatureAssayPlot(PanelWidth=6L)
))
```

```{r, echo=FALSE}
SCREENSHOT("screenshots/configure-FAP-basic.png")
```

The genes to show on the Y-axis in the two plots can be specified via the `YAxisFeatureName` argument to the respective panels in `iSEE`. 

```{r fexArg}
app <- iSEE(sce, initial=list(
    FeatureAssayPlot(YAxisFeatureName="0610009L18Rik"),
    FeatureAssayPlot(YAxisFeatureName="0610009B22Rik")
)) 
```

```{r, echo=FALSE}
SCREENSHOT("screenshots/configure-FAP-preset-genes.png")
```

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 export 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}
app <- iSEE(sce, initial=list(
    ColumnDataPlot(YAxis="NREADS", PanelWidth=6L, DataBoxOpen=TRUE),
    ColumnDataPlot(YAxis="TOTAL_DUP", PanelWidth=6L, DataBoxOpen=TRUE)
))
```

```{r, echo=FALSE}
SCREENSHOT("screenshots/configure-CDP-basic.png")
```

## Setting the X-axis {#xaxis}

The X-axis can be set to different types of variables.
The type of variable is generally set in the `XAxis` slot, while the name of the variable is stored in a different slot depending on the value of `XAxis`.
At runtime, this allows the app to remember the last selected variable of each type.

For instance, the `XAxis` slot of the _feature assay plot_ 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 `XAxisColumnData` to be set to a column name in the `colData(sce)`.
3. `"Feature name"`: requires either
    a. `XAxisFeatureName` to be set to a feature name (or positional index) in `rownames(sce)`.
    b. `XAxisFeatureSource` to be set to the name of a _Row data table_ panel with an active selection set in its own `Selected` column.

Each of these scenarios is demonstrated below:

```{r xaxis}
fex <- FeatureAssayPlot(DataBoxOpen=TRUE, PanelWidth=6L)

# Example 1
fex1 <- fex
fex1[["XAxis"]] <- "None"

# Example 2
fex2 <- fex
fex2[["XAxis"]] <- "Column data"
fex2[["XAxisColumnData"]] <- "Core.Type"

# Example 3a
fex3 <- fex
fex3[["XAxis"]] <- "Feature name"
fex3[["XAxisFeatureName"]] <- "Zyx"

# Example 4 (also requires a row statistic table)
fex4 <- fex
fex4[["XAxis"]] <- "Feature name"
fex4[["XAxisFeatureSource"]] <- "RowDataTable1"
rex <- RowDataTable(Selected="Ints2", Search="Ints", PanelWidth=12L)

# Initialisation
app <- iSEE(sce, initial=list(fex1, fex2, fex3, fex4, rex))
```

```{r, echo=FALSE}
SCREENSHOT("screenshots/configure-FAP-xaxis.png")
```

Note how _Example 3b_ requires an active _row data 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` slot:

```{r redDimPlotDefaults-type}
app <- iSEE(sce, initial=list(
    ReducedDimensionPlot(DataBoxOpen=TRUE, Type="TSNE", 
        XAxis=2L, YAxis=1L, PanelWidth=6L)
))
```

```{r, echo=FALSE}
SCREENSHOT("screenshots/configure-ReDP-basic.png")
```

## 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` argument:

```{r featAssayPlotDefaults-assay}
app <- iSEE(sce, initial=list(
    FeatureAssayPlot(DataBoxOpen=TRUE, Assay="logcounts", PanelWidth=6L),
    FeatureAssayPlot(DataBoxOpen=TRUE, Assay="tophat_counts", PanelWidth=6L)
))
```

```{r, echo=FALSE}
SCREENSHOT("screenshots/configure-FAP-assay.png")
```

# 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` slot,
while the default transparency value is controlled through the `PointAlpha` slot
Here, we alter several default visual parameters in the second panel:

```{r ColorByDefaultColor}
cdp <- ColumnDataPlot(VisualBoxOpen=TRUE, 
    VisualChoices=c("Color", "Size", "Point", "Text"))

cdp2 <- cdp
cdp2[["ColorByDefaultColor"]] <- "chocolate3"
cdp2[["PointAlpha"]] <- 0.2
cdp2[["PointSize"]] <- 2
cdp2[["Downsample"]] <- TRUE
cdp2[["DownsampleResolution"]] <- 150
cdp2[["FontSize"]] <- 2

app <- iSEE(sce, initial=list(cdp, cdp2))
```

```{r, echo=FALSE}
SCREENSHOT("screenshots/configure-CDP-visual.png")
```

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 `ColorByColumnData` value to the desired column name:

```{r aesthetic-covariate}
cdp <- ColumnDataPlot(VisualBoxOpen=TRUE, VisualChoices=c("Color", "Shape"),
    ColorByColumnData="Core.Type", ShapeByColumnData="Core.Type",
    ColorBy="Column data", ShapeBy="Column data")

cdp2 <- cdp
cdp2[["ColorByColumnData"]] <- "TOTAL_DUP"
cdp2[["ShapeByColumnData"]] <- "driver_1_s"

app <- iSEE(sce, initial=list(cdp, cdp2))
```

```{r, echo=FALSE}
SCREENSHOT("screenshots/configure-CDP-linked-visual.png")
```

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)`.
We demonstrate below how faceting may be enabled by row, column, or both:

```{r facet}
cdp <- ColumnDataPlot(VisualBoxOpen=TRUE, VisualChoices=c("Facet"),
    FacetRowBy="Column data", FacetRowByColData="driver_1_s", 
    FacetColumnBy="Column data", FacetColumnByColData="Core.Type", PanelWidth=4L)

cdp2 <- cdp
cdp2[["FacetRowBy"]] <- "None"

cdp3 <- cdp
cdp3[["FacetColumnBy"]] <- "None" 

app <- iSEE(sce, initial=list(cdp, cdp2, cdp3))
```

```{r, echo=FALSE}
SCREENSHOT("screenshots/configure-CDP-facets.png")
```

# Selection parameters

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 `ColumnSelectionSource` 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` slot.

The simplest way to obtain a valid `BrushData` value 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 <- ColumnDataPlot(
    XAxis="Column data",
    XAxisColumnData="driver_1_s",

    # Configuring the selection parameters.
    SelectionBoxOpen=TRUE,
    ColumnSelectionSource="ReducedDimensionPlot1",
    ColorBy="Column selection", 

    # Throwing in some parameters for aesthetic reasons.
    ColorByDefaultColor="#BDB3B3", 
    PointSize=2,
    PanelWidth=6L)

# Preconfigure the sender panel, including the point selection.
# NOTE: You don't actually have to write this from scratch! Just
# open an iSEE instance, make a brush and then look at the 'BrushData'
# entry when you click on the 'Display panel settings' button.
rdArgs <- ReducedDimensionPlot(
    BrushData = list(
        xmin = 13.7, xmax = 53.5, ymin = -36.5, ymax = 37.2, 
        coords_css = list(xmin = 413.2, xmax = 650.2, ymin = 83.0, ymax = 344.0), 
        coords_img = list(xmin = 537.2, xmax = 845.3, ymin = 107.9, ymax = 447.2), 
        img_css_ratio = list(x = 1.3, y = 1.3), 
        mapping = list(x = "X", y = "Y"), 
        domain = list(left = -49.1, right = 57.2, bottom = -70.4, top = 53.5), 
        range = list(left = 50.9, right = 873.9, bottom = 603.0, top = 33.1), 
        log = list(x = NULL, y = NULL), 
        direction = "xy", 
        brushId = "ReducedDimensionPlot1_Brush", 
        outputId = "ReducedDimensionPlot1"
    ),
    PanelWidth=6L
)    

app <- iSEE(sce, initial=list(cdArgs, rdArgs))
```

```{r, echo=FALSE}
SCREENSHOT("screenshots/configure-ReDP-select.png")
```

Note that in the example above, we color selected data points in the receiver panel by setting the `ColorBy` argument to `"Column selection"`.
The default is to increase the transparency of unselected data points;
another option is to set `ColumnSelectionRestrict` to `TRUE` to show only the selected data points.

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

```{r select-lasso}
# Preconfigure the sender panel, including the point selection.
# NOTE: again, you shouldn't try writing this from scratch! Just
# make a lasso and then copy the panel settings in 'BrushData'.
rdArgs[["BrushData"]] <- list(
    lasso = NULL, closed = TRUE, panelvar1 = NULL, panelvar2 = NULL, 
    mapping = list(x = "X", y = "Y"), 
    coord = structure(c(18.4, 
        18.5, 26.1, 39.9, 
        55.2, 50.3, 54.3, 
        33.3, 18.4, 35.5, 
        -4.2, -21.2, -46.1, 
        -43.5, -18.1, 7.3, 
        19.7, 35.5), .Dim = c(9L, 2L)
    )
)

app <- iSEE(sce, initial=list(cdArgs, rdArgs))
```

```{r, echo=FALSE}
SCREENSHOT("screenshots/configure-ReDP-lasso.png")
```

# 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 <- defaultTour()
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., `#ComplexHeatmapPlot1_ColumnData + .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`:

- `?ReducedDimensionPlot`
- `?ColumnDataPlot`
- `?ColumnDataTable`
- `?FeatureAssayPlot`
- `?RowDataPlot`
- `?RowDataTable`
- `?SampleAssayPlot`
- `?ComplexHeatmapPlot`

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

# Session Info {.unnumbered}

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

# References {.unnumbered}
