---
title: "Multilayer networks"
author: "Alejandro Espinosa-Rada"
output: rmarkdown::html_vignette
vignette: >
  %\VignetteIndexEntry{Multilayer networks}
  %\VignetteEngine{knitr::rmarkdown}
  %\VignetteEncoding{UTF-8}
---

```{r, include = FALSE}
knitr::opts_chunk$set(
  collapse = TRUE,
  comment = "#>"
)
```

-----

## Installation

You can install the released version from CRAN, or the development version from
[github/anespinosa](https://github.com/anespinosa/netmem):

```{r inst, eval=FALSE}
install.packages("netmem")
# install.packages("devtools")
devtools::install_github("anespinosa/netmem")
```

```{r setup}
library(netmem)
```

-----

### Multilayers

*Multilayer networks* is a framework that considers complex patterns of
relationships between the same and/or different nodes. However, from a social
network and sociological perspective, different types of multilayer structures
are often referred to as *multiplex networks* (or *multi-relational*),
*multilevel networks*, *network of networks* [Kivelä et al.
(2014)](https://doi.org/10.1093/comnet/cnu016), *two-mode networks*, among
others. Furthermore, and from a matrix perspective, the 'backbone' of these
complex structures are mainly represented through the comfortable combination of
different types of matrices. The primary matrix used in social network analysis
is the adjacency matrix or sociomatrix and the incidence matrix.

-----

### Two-mode networks

There are different ways of referring to incidence matrices. From the social
network perspective is often considered as *affiliation network*, which consist
of a set of binary relationships between members of two sets of items (i.e., "is
a member of" or "is a participant in" or "has") ([Borgatti and Halgin,
2011](https://methods.sagepub.com/book/the-sage-handbook-of-social-network-analysis/n28.xml)).
In general, these networks have a bipartite property in which there are two
classes such that all ties occur only between classes and never within classes.

For example, in this section we will use the classical example of the Southern
Woman extracted from the `R` package
[classicnets](https://github.com/anespinosa/classicnets):

```{r}
A <- matrix(
  c(
    1, 1, 1, 1, 1, 1, 0, 1, 1, 0, 0, 0, 0, 0,
    1, 1, 1, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
    0, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0,
    1, 0, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
    0, 0, 1, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 1, 0, 1, 1, 0, 1, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 1, 0, 1, 1, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 1, 0, 1, 1, 1, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 0, 1, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 0, 1, 1, 1,
    0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 0, 1, 1, 1,
    0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 1, 1, 1,
    0, 0, 0, 0, 0, 0, 1, 1, 0, 1, 1, 1, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 1, 1, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 1, 0, 1, 0, 0, 0
  ),
  byrow = TRUE, ncol = 14
)
```

As a common practice, an incidence matrix is often converted to adjacent
matrices. These are given by the matrix product $AA^T$ and $A^TA$, where $A$ is
the incidence matrix and matrix $A^T$ is the transpose of $A$. The relationship
between these matrices in the context of social networks was explored by
[Breiger (1974)](https://doi.org/10.2307/2576011).

```{r}
matrix_projection(A)
```
Another concept often used is *bipartite network*, which means that the graph's nodes can be partitioned into two classes. While in some cases, these classes can be different entities (e.g., actors participating in activities or belonging to clubs), this assumption is not always clear. For example, dichotomic attributes of ascribed characteristics also have a bipartite property.

An approach that was devised specifically for affiliation data, was provided by
[Bonacich (1972)](https://doi.org/10.1080/0022250X.1972.9989806):

```{r}
bonacich_norm(A)
```

The difference between *affiliation networks* and *bipartite networks* allowed
us to avoid confounding the concept of social proximity (e.g., being part of the
same laboratory) with social similarity (e.g., having an ascribed gender)
([Rivera et al., 2010](https://doi.org/10.1146/annurev.soc.34.040507.134743)).
In addition, this distinction is important because these mechanisms are often
considered competing alternatives to understanding social relationships.

*Two-mode networks* is a broader concept that emphasizes the difference between
entities of different levels. Therefore, these entities are likewise
differentiated as rows and columns in the incidence matrix.

Some researchers differentiate between the informational or socio-cognitive
dimensions and social networks of concrete relations - or proxies - between
agents ([Leydesdorff, 2008](https://doi.org/10.1002/asi.20732)). For example,
informational or socio-cognitive networks can be an incidence matrix of actors
and survey's items, citation networks or a tweet message. Therefore, the
incidence matrix of socio-cognitive networks are often called *occurrence
networks*.

For example, in scientometric, information is often explored using co-occurrence
of overlapping ties:

```{r}
minmax_overlap(A, row = TRUE, min = TRUE)
minmax_overlap(A, row = FALSE, min = TRUE)

co_occurrence(A, similarity = c("ochiai"), occurrence = TRUE, projection = FALSE)
```

-----

## Multilevel Networks

Connections between individuals are often embedded in complex structures, which
shape actors’ expectations, behaviours and outcomes over time. These structures
can themselves be interdependent and exist at different levels. Multilevel
networks are a means by which we can represent this complex system by using
nodes and edges of different types ([Lazega and Snijders,
2016](https://link.springer.com/book/10.1007/978-3-319-24520-1), [Knoke et al.,
2021](https://doi.org/10.1017/9781108985000)).

For multilevel structures, we tend to collect the data in different matrices
representing the variation of ties within and between levels. Often, we describe
the connection between actors as an adjacency matrix and the relations between
levels through incidence matrices. The comfortable combination of these matrices
into a common structure would represent the multilevel network that could be
highly complex.

### Example

<div class="alert alert-info"> Let's assume that we have a multilevel network
with two adjacency matrices, one valued matrix and two incidence matrices
between them.

- `A1`: Adjacency Matrix of the level 1

- `B1`: incidence Matrix between level 1 and level 2

- `A2`: Adjacency Matrix of the level 2

- `B2`: incidence Matrix between level 2 and level 3

- `A3`: Valued Matrix of the level 3

</div>

Create the data

```{r multilevel_example}
A1 <- matrix(c(
  0, 1, 0, 0, 1,
  1, 0, 0, 1, 1,
  0, 0, 0, 1, 1,
  0, 1, 1, 0, 1,
  1, 1, 1, 1, 0
), byrow = TRUE, ncol = 5)

B1 <- matrix(c(
  1, 0, 0,
  1, 1, 0,
  0, 1, 0,
  0, 1, 0,
  0, 1, 1
), byrow = TRUE, ncol = 3)

A2 <- matrix(c(
  0, 1, 1,
  1, 0, 0,
  1, 0, 0
), byrow = TRUE, nrow = 3)

B2 <- matrix(c(
  1, 1, 0, 0,
  0, 0, 1, 0,
  0, 0, 1, 1
), byrow = TRUE, ncol = 4)

A3 <- matrix(c(
  0, 1, 3, 1,
  1, 0, 0, 0,
  3, 0, 0, 5,
  1, 0, 5, 0
), byrow = TRUE, ncol = 4)

rownames(A1) <- letters[1:nrow(A1)]
colnames(A1) <- rownames(A1)
rownames(A2) <- letters[nrow(A1) + 1:nrow(A2)]
colnames(A2) <- rownames(A2)
rownames(B1) <- rownames(A1)
colnames(B1) <- colnames(A2)
rownames(A3) <- letters[nrow(A1) + nrow(A2) + 1:nrow(A3)]
colnames(A3) <- rownames(A3)
rownames(B2) <- rownames(A2)
colnames(B2) <- colnames(A3)
```

We will start with a report of the matrices:

```{r}
matrix_report(A1)
matrix_report(B1)
matrix_report(A2)
matrix_report(B2)
matrix_report(A3)
```

-----

### Ties within and between modes

In some cases we have an incidence matrix and also the relationships of the node
of the same class. In which case, we can use the *'meta-matrix'* ([Krackhardt &
Carley,
1998](https://www.andrew.cmu.edu/user/krack/documents/pubs/1998/1998%20PCANS%20Model%20Structure%20in%20Organizations.pdf);
Carley, 2002) to represent a
multilevel network.

```{r meta_matrix, message=FALSE}
meta_matrix(A1, B1, A2, B2, A3)
meta_matrix(A1, B1, A2, B2)
```

`netmem` works with matrices and does not depend on other packages to draw
them. When `igraph` is installed, it can be used to plot the meta-matrix:

```{r meta_matrix_plot, message=FALSE, eval=requireNamespace("igraph", quietly = TRUE)}
plot(igraph::graph_from_adjacency_matrix(meta_matrix(A1, B1, A2, B2, A3), mode = "directed"))
```

What is the density of some of the matrices?

```{r multilevel_example2}
matrices <- list(A1, B1, A2, B2)
gen_density(matrices, multilayer = TRUE)
```

How about the degree centrality of the entire structure?

```{r multil}
multilevel_degree(A1, B1, A2, B2, complete = TRUE)
```

Besides, we can perform a *k*-core analysis of one of the levels using the
information of an incidence matrix

```{r multil2}
k_core(A1, B1, multilevel = TRUE)
```

This package also allows performing complex census for multilevel networks

```{r multil3}
mixed_census(A2, t(B1), B2, quad = TRUE)
```

Also, there are some functions that allowed performing the zone-2 sampling from
second-mode (2-path distance from an ego in the second level)

```{r zone_sample}
two_mode_sam <- zone_sample(A1, B1, ego = TRUE)
two_mode_sam
```

Each subgraph is an adjacency matrix, which can be plotted with `igraph`, with
the nodes of the second level in blue:

```{r zone_sample_plot, message=FALSE, eval=requireNamespace("igraph", quietly = TRUE)}
m <- meta_matrix(A1, B1)
g <- igraph::graph_from_adjacency_matrix(m, mode = "max")
plot(g, vertex.color = ifelse(igraph::V(g)$name %in% colnames(B1), "blue", "red"))

for (i in 1:ncol(B1)) {
  g <- igraph::graph_from_adjacency_matrix(two_mode_sam[[i]], mode = "max")
  plot(g,
    vertex.color = ifelse(igraph::V(g)$name %in% colnames(B1), "blue", "red"),
    main = names(two_mode_sam)[i]
  )
}
```

Willing to create a multilevel network? We can simulate a multilevel network
with 30 actors in the first level and 20 nodes in the second level.

```{r}
set.seed(26091949)
ind_rand_matrix(n = 30, m = 20, type = "probability", p = 0.2, multilevel = TRUE)
```

-----

## Multiplex networks

In multiplex networks, interlayer edges can only connect nodes that represent
the same actor in different layer ([Kinsley et al.,
2020](https://www.frontiersin.org/articles/10.3389/fvets.2020.00596/full))

As mentioned by [Gluckman (1955:
19)](https://books.google.ch/books/about/The_Judicial_Process_Among_the_Barotse_o.html?id=Eja8AAAAIAAJ&redir_esc=y):

"As we shall have constantly to refer to the consistency of Lozi law with these
relationships which serve many interests, I propose, for brevity, to call them
*multiplex* relationships. I require also a term to cover the structure of
relationships in which a person tends to occupy the same position relative to
the same set of other persons in all networks of purposive ties - economic,
political, procreative, religious, educational."

To explore some of the functions available in `netmem` we will use data from
[Lazega
(2001)](https://books.google.ch/books/about/The_Collegial_Phenomenon.html?id=zRNaURgLOhYC&redir_esc=y)

```{r}
data("lazega_lawfirm")
rownames(lazega_lawfirm$advice) <- as.character(1:ncol(lazega_lawfirm$advice))
colnames(lazega_lawfirm$advice) <- rownames(lazega_lawfirm$advice)

colnames(lazega_lawfirm$friends) <- rownames(lazega_lawfirm$advice)
rownames(lazega_lawfirm$friends) <- colnames(lazega_lawfirm$friends)
```

Which are the densities of the networks?

```{r}
gen_density(list(
  lazega_lawfirm$cowork, lazega_lawfirm$advice,
  lazega_lawfirm$friends
), multilayer = TRUE)
```

How about computing the Jaccard index between matrices?

```{r}
jaccard(lazega_lawfirm$cowork, lazega_lawfirm$advice)

jaccard(lazega_lawfirm$cowork, lazega_lawfirm$friends)

jaccard(lazega_lawfirm$advice, lazega_lawfirm$friends)
```

Finally, we can conduct a multiplex triad census between a directed and an
undirected relation among the same people (Espinosa-Rada, 2021; Espinosa-Rada
et al., 2024). Each triple of people is classified by its triad of the directed
relation (Holland and Leinhardt, 1976) and its triad of the undirected
relation, together with how the two overlap, which gives 104 types of triads.
Here the advice is directed, and the friendship is treated as undirected:

```{r}
advice <- lazega_lawfirm$advice
friends <- pmax(lazega_lawfirm$friends, t(lazega_lawfirm$friends))
census <- multiplex_census(advice, friends)
length(census)
head(sort(census, decreasing = TRUE), 10)
```

The name of each type joins the triad of advice and the triad of friendship,
and the letters locate the friendship ties on the advice triad. Every triple is
counted once:

```{r}
sum(census) == choose(nrow(advice), 3)
```

With `merge = "overlap"`, the types that give the same combined triad are
merged:

```{r}
length(multiplex_census(advice, friends, merge = "overlap"))
```

### The layers in a single matrix

The layers of a multiplex network can be arranged in a supra-adjacency matrix,
with one row and one column for each actor in each layer ([De Domenico et al.,
2013](https://doi.org/10.1103/PhysRevX.3.041022); [Kivelä et al.,
2014](https://doi.org/10.1093/comnet/cnu016)). The blocks of the diagonal are
the layers, and the blocks outside it join the copies of the same actor:

```{r supra}
layers <- list(
  cowork = lazega_lawfirm$cowork,
  advice = lazega_lawfirm$advice,
  friends = lazega_lawfirm$friends
)
S <- supra_adjacency(layers)
dim(S)
S[1:4, c(1:2, 72:73, 143:144)]
```

The coupling can join every pair of layers (`categorical`, the default), only
the layers that follow each other (`ordinal`, for layers ordered in time), or
nothing (`none`).

The other way of putting the layers together is to aggregate them, so a tie
counts the layers in which two people are connected ([Battiston et al.,
2014](https://doi.org/10.1103/PhysRevE.89.032804)):

```{r aggregate}
A <- aggregate_layers(layers)
table(layers_with_a_tie = A[upper.tri(A)])
gen_density(aggregate_layers(layers, method = "binary"), directed = TRUE)
```

Aggregating is convenient, but it loses which layer each tie belongs to, and
the measures of the aggregated network can differ from those of the layers
([De Domenico et al., 2015](https://doi.org/10.1038/ncomms7864)).

-----

Note: the temporal networks are a special case of a multiplex network. Links are
dynamic, and nodes can join or leave at different stages of the network
evolution. For example, in this `toy example`, maybe two authors are no longer
available. In this case, we might prefer maintaining their name in the matrix
and assign a `NA` in their row and/or column:

```{r}
A <- matrix(c(
  0, 1, 1,
  1, 0, 1,
  0, 0, 0
), byrow = TRUE, ncol = 3)
colnames(A) <- c("A", "C", "D")
rownames(A) <- c("A", "C", "D")

# complete list of actors
label <- c("A", "B", "C", "D", "E")

structural_na(A, label)
```

-----

## References

Battiston, F., Nicosia, V. and Latora, V. (2014). Structural measures for multiplex networks. *Physical Review E*, 89(3), 032804. <https://doi.org/10.1103/PhysRevE.89.032804>

Bonacich, P. (1972). Factoring and weighting approaches to status scores and clique identification. *Journal of Mathematical Sociology*, 2(1), 113–120. <https://doi.org/10.1080/0022250X.1972.9989806>

Borgatti, S. P., & Halgin, D. S. (2011). Analyzing affiliation networks. In J. Scott & P. J. Carrington (Eds.), *The Sage Handbook of Social Network Analysis* (pp. 417–433). Sage.

Breiger, R. L. (1974). The duality of persons and groups. *Social Forces*, 53(2), 181–190. <https://doi.org/10.2307/2576011>

Carley, K. M. (2002). Smart agents and organizations of the future. In L. Lievrouw & S. Livingstone (Eds.), *The Handbook of New Media* (pp. 206–220). Sage.

De Domenico, M., Solé-Ribalta, A., Cozzo, E., Kivelä, M., Moreno, Y., Porter, M. A., Gómez, S. and Arenas, A. (2013). Mathematical formulation of multilayer networks. *Physical Review X*, 3(4), 041022. <https://doi.org/10.1103/PhysRevX.3.041022>

De Domenico, M., Nicosia, V., Arenas, A. and Latora, V. (2015). Structural reducibility of multilayer networks. *Nature Communications*, 6, 6864. <https://doi.org/10.1038/ncomms7864>

Espinosa-Rada, A. (2021). *A Network Approach for the Sociological Study of Science: Modelling Dynamic Multilevel Networks*. PhD thesis, The University of Manchester.

Espinosa-Rada, A., Bellotti, E., Everett, M. and Stadtfeld, C. (2024). Co-evolution of a socio-cognitive scientific network: A case study of citation dynamics among astronomers. *Social Networks*, 78, 92–108. <https://doi.org/10.1016/j.socnet.2023.11.008>

Gluckman, M. (1955). *The Judicial Process Among the Barotse of Northern Rhodesia*. Manchester University Press.

Holland, P. W. and Leinhardt, S. (1976). Local structure in social networks. *Sociological Methodology*, 7, 1–45. <https://doi.org/10.2307/270703>

Kinsley, A. C., Rossi, G., Silk, M. J. and VanderWaal, K. (2020). Multilayer and multiplex networks: An introduction to their use in veterinary epidemiology. *Frontiers in Veterinary Science*, 7, 596. <https://doi.org/10.3389/fvets.2020.00596>

Kivelä, M., Arenas, A., Barthelemy, M., Gleeson, J. P., Moreno, Y., & Porter, M. A. (2014). Multilayer networks. *Journal of Complex Networks*, 2(3), 203–271. <https://doi.org/10.1093/comnet/cnu016>

Knoke, D., Diani, M., Hollway, J., & Christopoulos, D. (2021). *Multimodal Political Networks*. Cambridge University Press. <https://doi.org/10.1017/9781108985000>

Krackhardt, D., & Carley, K. M. (1998). *A PCANS model of structure in organizations*. Carnegie Mellon University. <https://www.andrew.cmu.edu/user/krack/documents/pubs/1998/1998%20PCANS%20Model%20Structure%20in%20Organizations.pdf>

Lazega, E. (2001). *The Collegial Phenomenon: The Social Mechanisms of Cooperation Among Peers in a Corporate Law Partnership*. Oxford University Press.

Lazega, E., & Snijders, T. A. B. (Eds.). (2016). *Multilevel Network Analysis for the Social Sciences*. Springer. <https://doi.org/10.1007/978-3-319-24520-1>

Leydesdorff, L. (2008). On the normalization and visualization of author co-citation data: Salton's Cosine versus the Jaccard index. *Journal of the American Society for Information Science and Technology*, 59(1), 77–85. <https://doi.org/10.1002/asi.20732>

Rivera, M. T., Soderstrom, S. B., & Uzzi, B. (2010). Dynamics of dyads in social networks: Assortative, relational, and proximity mechanisms. *Annual Review of Sociology*, 36, 91–115. <https://doi.org/10.1146/annurev.soc.34.040507.134743>
