---
title: "Block feature selection with UBayFS"
author: "Anna Jenul, Stefan Schrunner"
date: "`r Sys.Date()`"
output: 
  prettydoc::html_pretty:
    theme: architect
    toc: TRUE
    hightlight: github
    geometry: width=400cm
bibliography: references.bib
vignette: >
  %\VignetteIndexEntry{UBayFS block feature selection}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

<style>
  body {
  text-align: justify;
  padding: 1em}
  header:after {
    content: "";
    position: absolute;
    top: 55px;
    right: 40px;
    width: 120px;
    height: 120px;
    background-image:url("logo.png");
    background-size:120px;
  }
</style>

```{r set-options, echo=FALSE, cache=FALSE}
options(width = 10000)
```


```{r setup, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
knitr::opts_chunk$set(fig.height = 5)
knitr::opts_chunk$set(fig.width = 8)
knitr::opts_chunk$set(fig.align = 'center')
```

# Introduction
Block feature selection is essential in different fields of application, including treatment outcome prediction in healthcare (for diseases such as cancer). Commonly, data is available from multiple sources, including clinical, genetic, and image data, where measurements from a common source are aggregated into a feature block. In many cases, however, not all data sources are relevant for machine learning models: Suppose we suspected that image data would not contain additional information to the other feature blocks. In that case, it might be easier, in terms of data acquisition and availability, to favor models that do not depend on all data sources at once. In order to detect that a single feature block does not provide any additional information, block feature selection can be deployed. UBayFS is able to cover this scenario by specifying constraints on a block level.

# UBayFS example
At first we load the package and the Breast Cancer Wisconsin (BCW) example dataset, which is described in the main vignette.
```{r, include = TRUE, cache = TRUE}
library(UBayFS)
data(bcw)
```

For block feature selection, it is necessary to define each feature's block affiliation, which is provided either (a) via a block list, or (b) via a block matrix. 

## Version (a): block list
The first example demonstrates how a list of block indices can provide the block structure of the dataset. We define three blocks for the BCW dataset, where the first block contains features with indices 1 to 10, block two features with indices 11 to 20, and block three features with indices 21 to 30.
```{r, include = TRUE}
block_list = list()
block_list[[1]] = 1:10
block_list[[2]] = 11:20
block_list[[3]] = 21:30

block_list
```

For the UBayFS model, we define a max-size block constraint restricting the number of selected blocks to (up to) one. Thus, the `constraint_vars` parameter is set to the maximum number of blocks to be selected, and `num_elements` contains the number of blocks, which equals the number of elements in the block_list.

```{r, include = TRUE}
block_constraints = buildConstraints(constraint_types = c("max_size"), 
                                     constraint_vars = list(1), 
                                     num_elements = length(block_list), 
                                     rho = 1, 
                                     block_list = block_list)

block_constraints
```

## Version (b): block matrix
Assuming the same block structure as for the block list, we demonstrate how to specify the block structure in UBayFS via a block matrix. The block matrix is a binary assignment matrix consisting of rows representing the feature blocks and columns representing the features in the dataset. Note that, in general, a feature may be assigned to an arbitrary number of blocks (i.e., the row and column sums are not restricted), but in practice, a partition of the feature set is sufficient in most cases.

```{r, include = TRUE}
block_matrix = matrix(0, nrow = 3, ncol = ncol(bcw$data))
block_matrix[1, 1:10] = 1
block_matrix[2, 11:20] = 1
block_matrix[3, 21:30] = 1

block_matrix
```

The same block feature constraints as for the block list can be produced using the block matrix. However, note that the  `num_elements` parameter, specifying the number of blocks, has to be set to the number of rows in the block matrix:

```{r, include = TRUE}
block_constraints = buildConstraints(constraint_types = c("max_size", "must_link"), 
                                     constraint_vars = list(1, c(1,2)), 
                                     num_elements = nrow(block_matrix), 
                                     rho = 1, 
                                     block_matrix = block_matrix)

block_constraints
```

## Block-wise prior weights

In addition to block-wise constraints, also prior weights may be specified on block level rather than on feature level. Thus, we define a help function to build the vector of prior block weights. Features from the same block get assigned the same prior weight. In this example, feature weights in block 1 are set to 0.5, feature weights in block 2 are set to 1, and feature weights in block 3 are set to 2.
```{r, include = TRUE}
build_block_weights = function(blocks, weights){
	return(weights[blocks])
}
prior_weights = build_block_weights(blocks = rep(c(1, 2, 3), each = 10), weights = c(0.5, 1, 2))
```

## Evaluation of block feature selection results

After specifying the block constraints, we initialize the UBayFS model. In addition to the block constraints, we require that at most three features are selected in total (max-size constraint).

```{r, include = TRUE}
set.seed(1) # for reproducibility

# define model without block constraints (only feature-wise max-size constraint)
model = build.UBaymodel(data = bcw$data,
                        target = bcw$labels,
                        M = 100, 
                        tt_split = 0.75,
                        nr_features = 10,
                        method = "mRMR",
                        prior_model ="dirichlet",
                        weights = prior_weights,
                        lambda = 1,
                        constraints = buildConstraints(constraint_types = c("max_size"), 
                                                       constraint_vars = list(3), 
                                                       num_elements = ncol(bcw$data), 
                                                       rho = 1),
                        optim_method = "GA",
                        popsize = 100,
                        maxiter = 100,
                        shiny = FALSE
                        )

# add block constraints
model <- setConstraints(model, constraints = block_constraints)
summary(model)
```

We observe, that the ``summary()`` prints additional lines for block constraints. All further steps are similar to the UBayFS variant without block constraints. In this example, three features from the third block are selected. Hence, all constraints are fulfilled.
```{r, include = TRUE}
model = UBayFS::train(model)
summary(model)
plot(model)
```

In the plot, block constraints are shown with dashed lines, while solid lines represent ordinary (feature-)constraints. As demonstrated, blocks 1 and 2 are connected via a must-link constraint (dotted line between features of block 1 and block 2).

Properties of the final feature set(s):
```{r, include = TRUE}
evaluateMultiple(state = model$output$feature_set[1,], model = model)
```

# Conclusion

The specification of block constraints in the UBayFS model follows the same syntax as ordinary feature set constraints. Thus, block constraints can be easily integrated and combined with feature-wise constraints. Further, the framework allows setting arbitrary linear constraints for blocks, as well as for single features.
