## ----setup, include = FALSE---------------------------------------------------
knitr::opts_chunk$set(
    collapse = TRUE,
    comment = "#>",
    fig.width = 7,
    fig.height = 4.5
)

## ----install, eval = FALSE----------------------------------------------------
# if (!requireNamespace("BiocManager", quietly = TRUE)) {
#     install.packages("BiocManager")
# }
# BiocManager::install("woven")

## ----quick-fit----------------------------------------------------------------
library(woven)
data(woven_example)
fit_ex <- woven(woven_example$X_missing, Y = woven_example$Y, K = 3L)

## ----quick-plots, fig.cap = "Latent space of the example data. Filled points are anchors; open points are subjects scored from a subset of their blocks."----
plot(fit_ex) # latent space by class

## ----quick-features, fig.width = 9, fig.height = 5, fig.cap = "Top features of each block. Bars are coloured by the class in which the feature is highest."----
plot(fit_ex, type = "features", n_top = 10)
woven_top_features(fit_ex, n = 3)

## ----acc-load, message = FALSE, warning = FALSE-------------------------------
library(MultiAssayExperiment)
data(miniACC)

blocks <- c("RNASeq2GeneNorm", "miRNASeqGene", "RPPAArray")
acc <- miniACC[, !is.na(miniACC$C1A.C1B), blocks]

## ----acc-transform------------------------------------------------------------
for (e in c("RNASeq2GeneNorm", "miRNASeqGene")) {
    acc[[e]] <- log2(assay(acc[[e]]) + 1)
}
acc

## ----acc-pattern--------------------------------------------------------------
table(sampleMap(acc)$assay) # samples per block
table(complete_in_all_blocks = complete.cases(acc))
table(acc$C1A.C1B)

## ----acc-fit------------------------------------------------------------------
fit <- woven(acc, Y = "C1A.C1B", K = 2L)
fit

## ----acc-coldata--------------------------------------------------------------
scores <- latent_scores(fit)
identical(rownames(scores), rownames(colData(acc)))
colData(acc)$WOVEN1 <- scores[, 1]
colData(acc)$WOVEN2 <- scores[, 2]
head(as.data.frame(colData(acc))[, c("C1A.C1B", "vital_status", "WOVEN1")])

## ----acc-plot, fig.cap = "WOVEN latent space for the ACC tumours. Filled points are anchors; open points are tumours without RPPA data, scored from RNA-seq and miRNA-seq."----
plot(fit)

## ----acc-coverage-plot, fig.cap = "Tumours by the blocks they have, split by subtype. A complete-case analysis uses only the top bar."----
plot(fit, type = "coverage")

## ----acc-coverage-------------------------------------------------------------
n_total <- nrow(colData(acc))
n_complete <- length(anchor_indices(fit))
n_scored <- sum(!is.na(latent_scores(fit)[, 1]))
data.frame(
    subjects = c(
        "complete-case (what a fully-paired method such as DIABLO uses)",
        "scored by woven"
    ),
    n = c(n_complete, n_scored),
    ESS = c(
        woven_ess_retention(n_complete, n_total),
        woven_ess_retention(n_scored, n_total)
    )
)

## ----acc-holdout--------------------------------------------------------------
set.seed(10)
test_ids <- sample(rownames(colData(acc)), 25)
train <- acc[, setdiff(rownames(colData(acc)), test_ids)]
test <- acc[, test_ids]

fit_train <- woven(train, Y = "C1A.C1B", K = 2L, verbose = FALSE)
pred <- woven_predict(fit_train, test)
head(pred)

truth <- test$C1A.C1B[match(rownames(pred), rownames(colData(test)))]
has_rppa <- rownames(pred) %in%
    sampleMap(test)$primary[sampleMap(test)$assay == "RPPAArray"]
table(
    blocks = ifelse(has_rppa, "all three", "no RPPA"),
    correct = pred$predicted_class == truth
)

## ----acc-top------------------------------------------------------------------
woven_top_features(fit, n = 5, modality = "RNASeq2GeneNorm")

## ----acc-vip, fig.width = 10, fig.height = 5, fig.cap = "Top features of each block by VIP score, coloured by the subtype in which they are highest."----
plot(fit, type = "features", n_top = 10)

## ----acc-loadings, fig.width = 10, fig.height = 5, fig.cap = "Top signed loadings on dimension 1 in each block."----
woven_plot_loadings(fit, dim = 1L, n_top = 8)

## ----list-tables--------------------------------------------------------------
set.seed(1)
tables <- lapply(woven_example$X_missing, function(X) {
    X <- X[!is.na(X[, 1]), ]
    X[sample(nrow(X)), ]
})
vapply(tables, nrow, integer(1))
labels <- setNames(woven_example$Y, rownames(woven_example$X_missing$RNA))
fit_sim <- woven(tables, Y = labels, K = 3L, verbose = FALSE)
fit_sim

## ----list-predict-------------------------------------------------------------
head(woven_predict(fit_sim, list(RNA = woven_example$X_complete$RNA[1:5, ])))

## ----metrics------------------------------------------------------------------
set.seed(1) # NMI uses k-means, which is random
woven_metrics(fit_sim)

## ----nystrom------------------------------------------------------------------
set.seed(1) # the held-out anchors are drawn at random
woven_nystrom_error(fit_ex, woven_example$X_missing, n_loo = 10L)

## ----variance, fig.cap = "Share of the squared canonical correlations per dimension."----
woven_plot_variance(fit_sim)

## ----tune---------------------------------------------------------------------
set.seed(1) # folds are random
tune <- woven_tune(acc, Y = "C1A.C1B", K = 2L, verbose = FALSE)
tune

## ----tune-plot, fig.width = 9, fig.height = 4, fig.cap = "Held-out balanced error rate over the tuning grid for the ACC data. The selected setting is outlined."----
plot(tune)

## ----tune-fit-----------------------------------------------------------------
fit_tuned <- tune$fit
woven_top_features(fit_tuned, n = 3)

## ----precompute---------------------------------------------------------------
pc <- woven_precompute(woven_example$X_missing)
fits <- lapply(c(0.5, 5), function(g) {
    woven(woven_example$X_missing,
        Y = woven_example$Y, K = 3L,
        gamma_y = g, precomp = pc, verbose = FALSE
    )
})
vapply(fits, function(f) singular_values(f)[1], numeric(1))

## ----access-------------------------------------------------------------------
dim(latent_scores(fit))
names(projection_matrices(fit))
dim(projection_matrices(fit)$RNASeq2GeneNorm)
length(anchor_indices(fit))
singular_values(fit)

## ----session------------------------------------------------------------------
sessionInfo()

