## ---- eval=TRUE, echo=TRUE, results='hide', warning=FALSE, error=FALSE, message=FALSE----
require(metavizr)
require(metagenomeSeq)
require(msd16s)

## ---- eval=FALSE, echo=TRUE---------------------------------------------------
#  app <- startMetaviz()
#  

## ---- eval=TRUE, echo=FALSE---------------------------------------------------

app <- startMetaviz(host="http://localhost", http_port=8989, debug=TRUE, open_browser=FALSE, non_interactive=TRUE, try_ports=TRUE)

# register IciclePlot

js_chart_settings <- list(list(id = "title", type = "string", defaultValue = "", label = "Title", possibleValues = NULL), list(id = "marginTop", type = "number", defaultValue = 50, label = "Top margin", possibleValues = NULL), list(id = "marginBottom", type = "number", defaultValue = 23, label = "Bottom margin", possibleValues = NULL), list(id = "marginLeft", type = "number", defaultValue = 20, label = "Left margin", possibleValues = NULL), list(id = "marginRight", type = "number", defaultValue = 10, label = "Right margin", possibleValues = NULL))

js_chart_colors = c("#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf")

app$chart_mgr$register_chart_type("epiviz.ui.charts.tree.Icicle", "epiviz.ui.charts.tree.Icicle", js_chart_settings=js_chart_settings, js_chart_colors=js_chart_colors)


# register HeatpmapPlot

js_chart_settings <- list(list("id"="title","type"="string","defaultValue"="","label"="Title","possibleValues"=NULL),list("id"="marginTop","type"="number","defaultValue"=80,"label"="Top margin","possibleValues"=NULL),list("id"="marginBottom","type"="number","defaultValue"=40,"label"="Bottom margin","possibleValues"=NULL),list("id"="marginLeft","type"="number","defaultValue"=120,"label"="Left margin","possibleValues"=NULL),list("id"="marginRight","type"="number","defaultValue"=40,"label"="Right margin","possibleValues"=NULL),list("id"="measurementGroupsAggregator","type"="categorical","defaultValue"="mean-stdev","label"="Aggregator for measurement groups","possibleValues"=list("mean-stdev","quartiles","count","min","max","sum")),list("id"="colLabel","type"="measurementsMetadata","defaultValue"="colLabel","label"="Columns labels","possibleValues"=NULL),list("id"="rowLabel","type"="measurementsAnnotation","defaultValue"="name","label"="Row labels","possibleValues"=NULL),list("id"="showColorsForRowLabels","type"="boolean","defaultValue"=FALSE,"label"="Row labels as colors","possibleValues"=NULL),list("id"="maxColumns","type"="number","defaultValue"=40,"label"="Max columns","possibleValues"=NULL),list("id"="yMin","type"="number","defaultValue"="default","label"="Min Value","possibleValues"=NULL),list("id"="yMax","type"="number","defaultValue"="default","label"="Max Value","possibleValues"=NULL),list("id"="cluster","type"="categorical","defaultValue"="rows","label"="Cluster","possibleValues"=list("none","rows","columns","both")),list("id"="clusteringAlg","type"="categorical","defaultValue"="none","label"="Clustering Algorithm","possibleValues"=list("none","agglomerative")),list("id"="clusteringMetric","type"="categorical","defaultValue"="euclidean","label"="Clustering Metric","possibleValues"=list("euclidean")),list("id"="clusteringLinkage","type"="categorical","defaultValue"="complete","label"="Clustering Linkage","possibleValues"=list("complete")),list("id"="showDendrogram","type"="boolean","defaultValue"=TRUE,"label"="Show Dendrogram","possibleValues"=NULL))

js_chart_colors = c("#1859a9","#ed2d2e","#008c47","#010101","#f37d22","#662c91","#a11d20","#b33893")

app$chart_mgr$register_chart_type("HeatmapPlot", "epiviz.plugins.charts.HeatmapPlot", js_chart_settings=js_chart_settings, js_chart_colors=js_chart_colors)


# register StackedLinePlot

js_chart_settings <- list(list("id"="title","type"="string","defaultValue"="","label"="Title","possibleValues"=NULL),list("id"="marginTop","type"="number","defaultValue"=30,"label"="Top margin","possibleValues"=NULL),list("id"="marginBottom","type"="number","defaultValue"=50,"label"="Bottom margin","possibleValues"=NULL),list("id"="marginLeft","type"="number","defaultValue"=30,"label"="Left margin","possibleValues"=NULL),list("id"="marginRight","type"="number","defaultValue"=15,"label"="Right margin","possibleValues"=NULL),list("id"="measurementGroupsAggregator","type"="categorical","defaultValue"="mean-stdev","label"="Aggregator for measurement groups","possibleValues"=list("mean-stdev","quartiles","count","min","max","sum")),list("id"="colLabel","type"="measurementsMetadata","defaultValue"="colLabel","label"="Color by","possibleValues"=NULL),list("id"="rowLabel","type"="measurementsAnnotation","defaultValue"="name","label"="Labels","possibleValues"=NULL),list("id"="offset","type"="categorical","defaultValue"="zero","label"="Offset","possibleValues"=list("zero","wiggle")),list("id"="interpolation","type"="categorical","defaultValue"="step-after","label"="Interpolation","possibleValues"=list("linear","step-before","step-after","basis","basis-open","basis-closed","bundle","cardinal","cardinal-open","monotone")),list("id"="scaleToPercent","type"="boolean","defaultValue"=TRUE,"label"="Scale to Percent","possibleValues"=NULL),list("id"="useGroupBy","type"="boolean","defaultValue"=FALSE,"label"="Use Group by","possibleValues"=NULL),list("id"="groupBy","type"="measurementsAnnotation","defaultValue"="name","label"="Group By","possibleValues"=NULL),list("id"="hoverOpacity","type"="number","defaultValue"=0.6,"label"="Hover Opacity","possibleValues"=NULL))

js_chart_colors = c("#393b79","#5254a3","#6b6ecf","#9c9ede","#637939","#8ca252","#b5cf6b","#cedb9c","#8c6d31","#bd9e39","#e7ba52","#e7cb94","#843c39","#ad494a","#d6616b","#e7969c","#7b4173","#a55194","#ce6dbd","#de9ed6")

app$chart_mgr$register_chart_type("StackedLinePlot", "epiviz.plugins.charts.StackedLinePlot", js_chart_settings=js_chart_settings, js_chart_colors=js_chart_colors)

# register LinePlot

js_chart_settings <- list(list("id"="title","type"="string","defaultValue"="","label"="Title","possibleValues"=NULL),list("id"="marginTop","type"="number","defaultValue"=30,"label"="Top margin","possibleValues"=NULL),list("id"="marginBottom","type"="number","defaultValue"=50,"label"="Bottom margin","possibleValues"=NULL),list("id"="marginLeft","type"="number","defaultValue"=30,"label"="Left margin","possibleValues"=NULL),list("id"="marginRight","type"="number","defaultValue"=15,"label"="Right margin","possibleValues"=NULL),list("id"="measurementGroupsAggregator","type"="categorical","defaultValue"="mean-stdev","label"="Aggregator for measurement groups","possibleValues"=list("mean-stdev","quartiles","count","min","max","sum")),list("id"="colLabel","type"="measurementsMetadata","defaultValue"="colLabel","label"="Columns labels","possibleValues"=NULL),list("id"="rowLabel","type"="measurementsAnnotation","defaultValue"="name","label"="Row labels","possibleValues"=NULL),list("id"="showPoints","type"="boolean","defaultValue"=FALSE,"label"="Show points","possibleValues"=NULL),list("id"="showLines","type"="boolean","defaultValue"=TRUE,"label"="Show lines","possibleValues"=NULL),list("id"="showErrorBars","type"="boolean","defaultValue"=TRUE,"label"="Show error bars","possibleValues"=NULL),list("id"="pointRadius","type"="number","defaultValue"=4,"label"="Point radius","possibleValues"=NULL),list("id"="lineThickness","type"="number","defaultValue"=3,"label"="Line thickness","possibleValues"=NULL),list("id"="yMin","type"="number","defaultValue"="default","label"="Min Y","possibleValues"=NULL),list("id"="yMax","type"="number","defaultValue"="default","label"="Max Y","possibleValues"=NULL),list("id"="interpolation","type"="categorical","defaultValue"="basis","label"="Interpolation","possibleValues"=list("linear","step-before","step-after","basis","basis-open","basis-closed","bundle","cardinal","cardinal-open","monotone")))

js_chart_colors = c("#393b79","#5254a3","#6b6ecf","#9c9ede","#637939","#8ca252","#b5cf6b","#cedb9c","#8c6d31","#bd9e39","#e7ba52","#e7cb94","#843c39","#ad494a","#d6616b","#e7969c","#7b4173","#a55194","#ce6dbd","#de9ed6")

app$chart_mgr$register_chart_type("LinePlot", "epiviz.plugins.charts.LinePlot", js_chart_settings=js_chart_settings, js_chart_colors=js_chart_colors)

app$server$start_server()


## ---- eval=FALSE--------------------------------------------------------------
#  app$server$service()

## ---- eval=TRUE---------------------------------------------------------------
feature_order <- c("superkingdom", "phylum", "class", "order", "family", "genus", "species", "OTU")
aggregated_feature_order <- feature_order[1:7]

msd16s_species <- msd16s
fData(msd16s) <- fData(msd16s)[feature_order]
fData(msd16s_species) <- fData(msd16s_species)[aggregated_feature_order]
  
bangladesh <- msd16s[, which(pData(msd16s)$Country == "Bangladesh")]
bangladesh_species <- msd16s_species[, which(pData(msd16s_species)$Country == "Bangladesh")]

aggregated_species <-  cumNorm(aggregateByTaxonomy(bangladesh_species, lvl="species"), p = 0.75)

aggregation_level <- "class"
aggregated_bangladesh <- aggregateByTaxonomy(bangladesh, lvl=aggregation_level)

normed_bangladesh <-  cumNorm(aggregated_bangladesh, p = 0.75)
bangladesh_sample_data <-  pData(normed_bangladesh)
mod <-  model.matrix(~1+Dysentery, data = bangladesh_sample_data)
results_bangladesh <-  fitFeatureModel(normed_bangladesh, mod)
logFC_bangladesh <- MRcoefs(results_bangladesh, number = nrow(normed_bangladesh))

features <- rownames(logFC_bangladesh)
featuresToKeep_names <- features[which(logFC_bangladesh[which(abs(logFC_bangladesh$logFC) > 1),]$adjPvalues < .1)]
featuresToKeep <- rep(2, length(featuresToKeep_names))
names(featuresToKeep) <- featuresToKeep_names

featuresToRemove_names <- features[!(features %in% featuresToKeep_names)]
featuresToRemove <- rep(0, length(featuresToRemove_names))
names(featuresToRemove) <- featuresToRemove_names

## ----eval=TRUE----------------------------------------------------------------
control <- metavizr::metavizControl(featureSelection = c(featuresToKeep, featuresToRemove))

## ----eval=TRUE----------------------------------------------------------------
#specify the feature hierarchy for the dataset
icicle_plot <- app$plot(aggregated_species, datasource_name="mmssdd", type = "LeafCounts", control = control, feature_order = aggregated_feature_order)

## ---- eval=TRUE---------------------------------------------------------------
heatmap <- app$chart_mgr$revisualize(chart_type = "HeatmapPlot", chart = icicle_plot)

## ---- eval=TRUE---------------------------------------------------------------
stackedPlot <- app$chart_mgr$revisualize(chart_type ="StackedLinePlot", chart = icicle_plot)

## ---- eval=TRUE---------------------------------------------------------------

feature_names_update <- rownames(logFC_bangladesh[which(logFC_bangladesh[which(abs(logFC_bangladesh$logFC) > .5),]$adjPvalues < .05),])
fSelection_update <- rep(2, length(feature_names_update))
names(fSelection_update) <- feature_names_update

agg_level = which(feature_order==aggregation_level)
select_value = 2
names(select_value) = agg_level
app$get_ms_object(icicle_plot)$propagateHierarchyChanges(fSelection_update, selectedLevels = select_value, request_with_labels = TRUE)

## ---- eval=TRUE---------------------------------------------------------------
library(etec16s)
data(etec16s)
etec16s <- etec16s[,-which(pData(etec16s)$Day>9)]

## ---- eval=TRUE---------------------------------------------------------------
featureData(etec16s)$Kingdom <- "Bacteria"
feature_order <- c("Kingdom", "Phylum", "Class", "Order", "Family", "Genus", "Species", "OTU.ID")
featureData(etec16s) <- featureData(etec16s)[,feature_order]

## ---- eval=TRUE---------------------------------------------------------------
ic_plot <- app$plot(object = etec16s, type = "TimeSeries", datasource_name = "etec_splines", control = metavizControl(norm=FALSE, aggregateAtDepth = 4), formula = abundance~id + time*class + AntiGiven, class="AnyDayDiarrhea", id="SubjectID", time="Day", lvl="Family", feature_order = feature_order, B=1, seed = 1234, runFitTimeSeries = TRUE, fitThreshold = 2)

splineChart <- app$chart_mgr$revisualize("LinePlot", ic_plot)

## ---- eval=TRUE, echo=FALSE---------------------------------------------------

# list available charts
app$chart_mgr$list_chart_types()

# list available settings for "LinePlot"
app$chart_mgr$list_chart_type_settings("LinePlot")

# update settings on splineChart 
settings <- list(yMin = -10, yMax = 10, colLabel="label")
colors <- c("#1f77b4", "#ff7f0e", "#2ca02c", "#d62728", "#9467bd", "#8c564b", "#e377c2", "#7f7f7f", "#bcbd22", "#17becf")
app$chart_mgr$set_chart_settings(splineChart, settings=settings, colors = colors)

## ---- eval=TRUE, echo=FALSE---------------------------------------------------
app$chart_mgr$rm_all_charts()

## ---- eval=TRUE, echo=FALSE---------------------------------------------------
require(ExperimentHub)
require(tidyr)

EH <-
  ExperimentHub()

ZellerG_2014.metaphlan_bugs_list.stool <-
    EH[["EH1954"]]

relative_abundance <-
  exprs(ZellerG_2014.metaphlan_bugs_list.stool)

number_reads <-
  ZellerG_2014.metaphlan_bugs_list.stool$number_reads

counts <-
  sweep(relative_abundance, 2, number_reads/100, "*")

counts <-
  round(counts)

pheno_data <-
  phenoData(ZellerG_2014.metaphlan_bugs_list.stool)

into_cols <-
  c("Kingdom", "Phylum", "Class", "Order", "Family", "Genus", "Species", "Strain")

taxonomy_data <-
  data.frame(rowname = rownames(counts))

taxonomy_data <-
  separate(taxonomy_data, "rowname", into_cols, sep = "\\|", fill = "right")

rownames(counts) <-
  gsub(".+\\|", "", rownames(counts))

rownames(taxonomy_data) <-
  gsub(".+\\|", "", rownames(counts))

taxonomy_data <-
  apply(taxonomy_data, 2, function(x) {gsub("[a-z]__", "", x)})

taxonomy_data <-
  data.frame(taxonomy_data)

taxonomy_data <-
  AnnotatedDataFrame(taxonomy_data)

zeller_MR_expr <-
    metagenomeSeq::newMRexperiment(
        counts = counts,
        phenoData = pheno_data,
        featureData = taxonomy_data
    )

## ---- eval=TRUE, echo=FALSE---------------------------------------------------
facetZoomWGS <- app$plot(zeller_MR_expr, type = "innerNodeCounts", datasource_name = "zeller", feature_order = colnames(fData(zeller_MR_expr)))

## ---- eval=TRUE, echo=FALSE---------------------------------------------------
heatmap_plot <- app$chart_mgr$revisualize(chart_type = "HeatmapPlot", chart = facetZoomWGS)

## ---- eval=TRUE, echo=FALSE---------------------------------------------------
app$chart_mgr$rm_all_charts()

## ----eval=TRUE----------------------------------------------------------------
app$stop_app()

## ----session-info, cache=FALSE------------------------------------------------
sessionInfo()

