| Title: | Stochastic Blockmodels |
|---|---|
| Description: | A collection of tools and functions to adjust a variety of stochastic blockmodels (SBM). Supports at the moment Simple, Bipartite, 'Multipartite' and Multiplex SBM (undirected or directed with Bernoulli, Poisson or Gaussian emission laws on the edges, and possibly covariate for Simple and Bipartite SBM). See Léger (2016) <doi:10.48550/arXiv.1602.07587>, 'Barbillon et al.' (2020) <doi:10.1111/rssa.12193> and 'Bar-Hen et al.' (2020) <doi:10.48550/arXiv.1807.10138>. |
| Authors: | Julien Chiquet [aut, cre] (ORCID: <https://orcid.org/0000-0002-3629-3429>), Sophie Donnet [aut] (ORCID: <https://orcid.org/0000-0003-4370-7316>), großBM team [ctb], Pierre Barbillon [aut] (ORCID: <https://orcid.org/0000-0002-7766-7693>) |
| Maintainer: | Julien Chiquet <[email protected]> |
| License: | GPL (>= 3) |
| Version: | 1.0.0 |
| Built: | 2026-11-06 21:05:05 UTC |
| Source: | https://github.com/grosssbm/sbm |
R6 class for Bipartite SBM
SBM -> BipartiteSBM
dimLabelsvector of two characters giving the label of each connected dimension (row, col)
blockProplist of two vectors of block proportions (aka prior probabilities of each block)
connectParamparameters associated to the connectivity of the SBM, e.g. matrix of inter/inter block probabilities when model is Bernoulli
probMembershipsmatrix of estimated probabilities for block memberships for all nodes
nbBlocksvector of size 2: number of blocks (rows, columns)
maskMask for the (potential) NAs in the adjacency matrix
nbDyadsnumber of dyads (potential edges in the network)
nbConnectParamnumber of parameter used for the connectivity
membershipslist of size 2: vector of memberships in row, in column.
indMembershipsmatrix for clustering memberships
BipartiteSBM$new()constructor for SBM
BipartiteSBM$new(
model,
nbNodes,
blockProp = vector("list", 2),
connectParam = list(mean = matrix(0, 0, 0)),
dimLabels = c(row = "row", col = "col"),
covarParam = numeric(length(covarList)),
covarList = list(),
nodesCovarList = vector("list", 2),
nodesCovarParam = vector("list", 2)
)
modelcharacter describing the type of model
nbNodesnumber of nodes in each dimension of the network
blockPropparameters for block proportions (vector of list of vectors)
connectParamlist of parameters for connectivity with a matrix of means 'mean' and an optional scalar for the variance 'var'. The dimensions of mu must match blockProp lengths
dimLabelsoptional labels of each dimension (in row, in column)
covarParamoptional vector of covariates effect
covarListoptional list of covariates data
nodesCovarListoptional list of two matrices with nodes covariates
nodesCovarParamoptional list of two matrices of parameters of effects of nodes covariates on clustering
BipartiteSBM$rMemberships()a method to sample new block memberships for the current SBM
BipartiteSBM$rMemberships(store = FALSE)
storeshould the sampled blocks be stored (and overwrite the existing data)? Default to FALSE
the sampled blocks
BipartiteSBM$rEdges()a method to sample a network data (edges) for the current SBM
BipartiteSBM$rEdges(store = FALSE)
storeshould the sampled edges be stored (and overwrite the existing data)? Default to FALSE
the sampled network
BipartiteSBM$predict()prediction under the current parameters
BipartiteSBM$predict(covarList = self$covarList, theta_p0 = 0)
covarLista list of covariates. By default, we use the covariates with which the model was estimated.
theta_p0double for thresholding...
BipartiteSBM$show()show method
BipartiteSBM$show(type = "Bipartite Stochastic Block Model")
typecharacter used to specify the type of SBM
BipartiteSBM$plot()basic matrix plot method for BipartiteSBM object or mesoscopic plot
BipartiteSBM$plot(
type = c("data", "expected", "graphon", "meso"),
ordered = TRUE,
plotOptions = list()
)
typecharacter for the type of plot: either 'data' (true connection), 'expected' (fitted connection), 'graphon' (block connectivity on the unit square, blocks sized by the block proportions) or 'meso' (mesoscopic view). Default to 'data'.
orderedlogical: should the rows and columns be reordered according to the clustering? Default to TRUE.
plotOptionslist with the parameters for the plot. See help of the corresponding S3 method for details.
a ggplot2 object
BipartiteSBM$clone()The objects of this class are cloneable with this method.
BipartiteSBM$clone(deep = FALSE)
deepWhether to make a deep clone.
This class is designed to give a representation and adjust an LBM fitted with blockmodels.
The list of parameters estimOptions essentially tunes the optimization process and the variational EM algorithm, with the following parameters
"nbCores integer for number of cores used. Default is 2 (1 under Positron, which does not allow forking)
"verbosity" integer for verbosity (0, 1). Default is 1
"plot" boolean, should the ICL be dynamically plotted or not. Default is TRUE, FALSE when "verbosity" is 0
"exploreFactor" control the exploration of the number of groups
"exploreMin" explore at least until exploreMin even if the exploration factor rule is achieved. Default 4. See the package blockmodels for details.
"exploreMax" Stop exploration at exploreMax even if the exploration factor rule is not achieved. Default Inf. See the package blockmodels for details.
"nbBlocksRange" minimal and maximal number or blocks explored
"fast" logical: should approximation be used for Bernoulli model with covariates. Default to TRUE
SBM -> BipartiteSBM -> BipartiteSBM_fit
loglikdouble: approximation of the log-likelihood (variational lower bound) reached
ICLdouble: value of the integrated classification log-likelihood
penaltydouble, value of the penalty term in ICL
entropydouble, value of the entropy due to the clustering distribution
storedModelsdata.frame of all models fitted (and stored) during the optimization
BipartiteSBM_fit$new()constructor for a Bipartite SBM fit
BipartiteSBM_fit$new(
incidenceMatrix,
model,
dimLabels = c(row = "row", col = "col"),
covarList = list(),
nodesCovarList = vector("list", 2)
)
incidenceMatrixrectangular (weighted) matrix
modelcharacter ('bernoulli', 'poisson', 'gaussian')
dimLabelslabels of each dimension (in row, in columns)
covarListan optional list of covariates, each of whom must have the same dimension as incidenceMatrix
nodesCovarListan optional list of two matrices of covariates, each of whom must have the same dimension as incidenceMatrix
BipartiteSBM_fit$optimize()function to perform optimization
BipartiteSBM_fit$optimize(estimOptions = list())
estimOptionsa list of parameters controlling the inference algorithm and model selection. See details.
BipartiteSBM_fit$setModel()method to select a specific model among the ones fitted during the optimization. Fields of the current SBM_fit will be updated accordingly.
BipartiteSBM_fit$setModel(index)
indexinteger, the index of the model to be selected (row number in storedModels)
BipartiteSBM_fit$reorder()permute group labels by order of decreasing probability
BipartiteSBM_fit$reorder()
BipartiteSBM_fit$show()show method
BipartiteSBM_fit$show(type = "Fit of a Bipartite Stochastic Block Model")
typecharacter used to specify the type of SBM
BipartiteSBM_fit$clone()The objects of this class are cloneable with this method.
BipartiteSBM_fit$clone(deep = FALSE)
deepWhether to make a deep clone.
Extracts model coefficients from objects with class SBM and children (SimpleSBM_fit,
BipartiteSBM_fit)
## S3 method for class 'SBM' coef(object, type = c("connectivity", "block", "covariates"), ...)## S3 method for class 'SBM' coef(object, type = c("connectivity", "block", "covariates"), ...)
object |
an R6 object inheriting from class SBM_fit (like SimpleSBM_fit or BipartiteSBM_fit) |
type |
type of parameter that should be extracted. Either 'block' for
, 'connectivity' for
, or "covariates" for
. Default is 'connectivity'. |
... |
additional parameters for S3 compatibility. Not used |
vector or list of parameters.
Define a network
defineSBM( netMat, model = "bernoulli", type = ifelse(ncol(netMat) == nrow(netMat), "simple", "bipartite"), directed = !isSymmetric(netMat), dimLabels = c(row = "row", col = "col"), covariates = list() )defineSBM( netMat, model = "bernoulli", type = ifelse(ncol(netMat) == nrow(netMat), "simple", "bipartite"), directed = !isSymmetric(netMat), dimLabels = c(row = "row", col = "col"), covariates = list() )
netMat |
a matrix describing the network: either an adjacency (square) or incidence matrix with possibly weighted entries. |
model |
character describing the model for the relation between nodes ( |
type |
Type of the matrix, choice between 'simple' and 'bipartite' |
directed |
logical: is the network directed or not? Only relevant when |
dimLabels |
an optional vector of labels for each dimension (in row, in column). Default value = c('row' = row,'col'= col) |
covariates |
a list of matrices with same dimension as mat describing covariates at the edge level. No covariate per Default. |
an object SimpleSBM or BipartiteSBM with the informations required to define a future multipartite network
A <- matrix(rbinom(100,1,.2), 10, 10) myNet <- defineSBM(A, "bernoulli", "simple", TRUE, "Actor")A <- matrix(rbinom(100,1,.2), 10, 10) myNet <- defineSBM(A, "bernoulli", "simple", TRUE, "Actor")
This function performs variational inference of bipartite Stochastic Block Models, with various model for the distribution of the edges: Bernoulli, Poisson, or Gaussian models.
estimateBipartiteSBM( netMat, model = "bernoulli", dimLabels = c(row = "row", col = "col"), covariates = list(), nodesCovariates = vector("list", 2), estimOptions = list() )estimateBipartiteSBM( netMat, model = "bernoulli", dimLabels = c(row = "row", col = "col"), covariates = list(), nodesCovariates = vector("list", 2), estimOptions = list() )
netMat |
a matrix describing the network: either an adjacency (square) or incidence matrix with possibly weighted entries. |
model |
character describing the model for the relation between nodes ( |
dimLabels |
an optional vector of labels for each dimension (in row, in column) |
covariates |
a list of matrices with same dimension as mat describing covariates at the edge level. No covariate per Default. |
nodesCovariates |
a list of two matrices with the same number of rows as the number of nodes in rows and cols in the network, describing the nodes covariates for each type of nodes. No nodes covariates per default. |
estimOptions |
a list of parameters controlling the inference algorithm and model selection. See details. |
The list of parameters estimOptions essentially tunes the optimization process and the variational EM algorithm, with the following parameters
"nbCores integer for number of cores used. Default is 2 (1 under Positron, which does not allow forking)
"verbosity" integer for verbosity (0, 1). Default is 1
"plot" boolean, should the ICL be dynamically plotted or not. Default is TRUE, FALSE when "verbosity" is 0
"exploreFactor" control the exploration of the number of groups
"exploreMin" explore at least until exploreMin even if the exploration factor rule is achieved. Default 4. See the package blockmodels for details.
"exploreMax" Stop exploration at exploreMax even if the exploration factor rule is not achieved. Default Inf. See the package blockmodels for details.
"nbBlocksRange" minimal and maximal number or blocks explored
"fast" logical: should approximation be used for Bernoulli model with covariates. Default to TRUE
a list with the estimated parameters. See details...
### ======================================= ### BIPARTITE BINARY SBM (Bernoulli model) ## Graph parameters and Sampling nbNodes <- c(60, 80) blockProp <- list(c(.5, .5), c(1/3, 1/3, 1/3)) # group proportions means <- matrix(runif(6), 2, 3) # connectivity matrix # In Bernoulli SBM, parameters is a list with a # matrix of means 'mean' which are probabilities of connection connectParam <- list(mean = means) mySampler <- sampleBipartiteSBM(nbNodes, blockProp, connectParam, model = 'bernoulli') ## Estimation myBipartiteSBM <- estimateBipartiteSBM(mySampler$networkData, estimOptions = list(plot = FALSE)) plot(myBipartiteSBM, 'expected') ### ======================================= ### BIPARTITE POISSON SBM ## Graph parameters & Sampling nbNodes <- c(60, 80) blockProp <- list(c(.5, .5), c(1/3, 1/3, 1/3)) # group proportions means <- matrix(rbinom(6, 30, 0.25), 2, 3) # connectivity matrix connectParam <- list(mean = means) mySampler <- sampleBipartiteSBM(nbNodes, blockProp, connectParam, model = 'poisson') ## Estimation myBipartiteSBM <- estimateBipartiteSBM(mySampler$networkData, 'poisson', estimOptions = list(plot = FALSE)) plot(myBipartiteSBM, 'expected') ### ======================================= ### BIPARTITE GAUSSIAN SBM ## Graph parameters & sampling nbNodes <- c(60, 80) blockProp <- list(c(.5, .5), c(1/3, 1/3, 1/3)) # group proportions means <- 20 * matrix(runif(6), 2, 3) # connectivity matrix connectParam <- list(mean = means, var = 1) mySampler <- sampleBipartiteSBM(nbNodes, blockProp, connectParam, model = 'gaussian') ## Estimation myBipartiteSBM <- estimateBipartiteSBM(mySampler$networkData, 'gaussian', estimOptions = list(plot = FALSE)) plot(myBipartiteSBM, 'expected')### ======================================= ### BIPARTITE BINARY SBM (Bernoulli model) ## Graph parameters and Sampling nbNodes <- c(60, 80) blockProp <- list(c(.5, .5), c(1/3, 1/3, 1/3)) # group proportions means <- matrix(runif(6), 2, 3) # connectivity matrix # In Bernoulli SBM, parameters is a list with a # matrix of means 'mean' which are probabilities of connection connectParam <- list(mean = means) mySampler <- sampleBipartiteSBM(nbNodes, blockProp, connectParam, model = 'bernoulli') ## Estimation myBipartiteSBM <- estimateBipartiteSBM(mySampler$networkData, estimOptions = list(plot = FALSE)) plot(myBipartiteSBM, 'expected') ### ======================================= ### BIPARTITE POISSON SBM ## Graph parameters & Sampling nbNodes <- c(60, 80) blockProp <- list(c(.5, .5), c(1/3, 1/3, 1/3)) # group proportions means <- matrix(rbinom(6, 30, 0.25), 2, 3) # connectivity matrix connectParam <- list(mean = means) mySampler <- sampleBipartiteSBM(nbNodes, blockProp, connectParam, model = 'poisson') ## Estimation myBipartiteSBM <- estimateBipartiteSBM(mySampler$networkData, 'poisson', estimOptions = list(plot = FALSE)) plot(myBipartiteSBM, 'expected') ### ======================================= ### BIPARTITE GAUSSIAN SBM ## Graph parameters & sampling nbNodes <- c(60, 80) blockProp <- list(c(.5, .5), c(1/3, 1/3, 1/3)) # group proportions means <- 20 * matrix(runif(6), 2, 3) # connectivity matrix connectParam <- list(mean = means, var = 1) mySampler <- sampleBipartiteSBM(nbNodes, blockProp, connectParam, model = 'gaussian') ## Estimation myBipartiteSBM <- estimateBipartiteSBM(mySampler$networkData, 'gaussian', estimOptions = list(plot = FALSE)) plot(myBipartiteSBM, 'expected')
Estimation for multipartite SBM
estimateMultipartiteSBM(listSBM, estimOptions = list())estimateMultipartiteSBM(listSBM, estimOptions = list())
listSBM |
list of networks that were defined by the |
estimOptions |
options for the inference procedure |
The list of parameters estimOptions essentially tunes the optimization process and the variational EM algorithm, with the following parameters
"nbCores" integer for number of cores used. Default is 2 (1 under Positron, which does not allow forking)
"verbosity" integer for verbosity (0, 1). Default is 1
"nbBlocksRange" List of length the number of functional groups, each element supplying the minimal and maximal number of blocks to be explored. The names of the list must be the names of the functional groups. Default value is from 1 to 10)
"initBM" Boolean. True if using simple and bipartite SBM as initialisations. Default value = TRUE
"maxiterVEM" Number of max. number of iterations in the VEM. Default value = 100
"maxiterVE" Number of max. number of iterations in the VE. Default value = 100
a MultipartiteSBM_fit object with the estimated parameters and the blocks in each Functional Group
## Not run: ## About the Parts/Functional Groups (FG) blockProp <- list(c(0.16 ,0.40 ,0.44),c(0.3,0.7)) # prop of blocks in each FG archiMultipartite <- rbind(c(1,2),c(2,2),c(1,1)) # architecture of the multipartite net. nbNodes <- c(60,50) ## About the connection matrices directed <- c(NA, TRUE, FALSE) # type of each network model <- c('gaussian','bernoulli','poisson') C1 <- list(mean = matrix(c(6.1, 8.9, 6.6, 9.8, 2.6, 1.0), 3, 2), var = matrix(c(1.6, 1.6, 1.8, 1.7 ,2.3, 1.5),3, 2)) C2 <- list(mean = matrix(c(0.7,1.0, 0.4, 0.6),2, 2)) m3 <- matrix(c(2.5, 2.6 ,2.2 ,2.2, 2.7 ,3.0 ,3.6, 3.5, 3.3),3,3 ) C3 <- list(mean = .5 * (m3 + t(m3))) connectParam <- list(C1, C2, C3) ## Graph Sampling mySampleMSBM <- sampleMultipartiteSBM(nbNodes, blockProp, archiMultipartite, connectParam, model, directed, dimLabels = c('A','B'), seed = 2) listSBM <- mySampleMSBM$listSBM estimOptions <- list(initBM = FALSE, nbCores = 2) myMSBM <- estimateMultipartiteSBM(listSBM, estimOptions) plot(myMSBM, type = "data") plot(myMSBM, type = "expected") plot(myMSBM, type = "meso") ## End(Not run)## Not run: ## About the Parts/Functional Groups (FG) blockProp <- list(c(0.16 ,0.40 ,0.44),c(0.3,0.7)) # prop of blocks in each FG archiMultipartite <- rbind(c(1,2),c(2,2),c(1,1)) # architecture of the multipartite net. nbNodes <- c(60,50) ## About the connection matrices directed <- c(NA, TRUE, FALSE) # type of each network model <- c('gaussian','bernoulli','poisson') C1 <- list(mean = matrix(c(6.1, 8.9, 6.6, 9.8, 2.6, 1.0), 3, 2), var = matrix(c(1.6, 1.6, 1.8, 1.7 ,2.3, 1.5),3, 2)) C2 <- list(mean = matrix(c(0.7,1.0, 0.4, 0.6),2, 2)) m3 <- matrix(c(2.5, 2.6 ,2.2 ,2.2, 2.7 ,3.0 ,3.6, 3.5, 3.3),3,3 ) C3 <- list(mean = .5 * (m3 + t(m3))) connectParam <- list(C1, C2, C3) ## Graph Sampling mySampleMSBM <- sampleMultipartiteSBM(nbNodes, blockProp, archiMultipartite, connectParam, model, directed, dimLabels = c('A','B'), seed = 2) listSBM <- mySampleMSBM$listSBM estimOptions <- list(initBM = FALSE, nbCores = 2) myMSBM <- estimateMultipartiteSBM(listSBM, estimOptions) plot(myMSBM, type = "data") plot(myMSBM, type = "expected") plot(myMSBM, type = "meso") ## End(Not run)
Estimation for Multiplex SBM
estimateMultiplexSBM(listSBM, dependent = FALSE, estimOptions = list())estimateMultiplexSBM(listSBM, dependent = FALSE, estimOptions = list())
listSBM |
list of networks that were defined by the |
dependent |
logical parameter indicating whether the networks in the multiplex structure are dependent beyond the latent variables, |
estimOptions |
options for the inference procedure |
The list of parameters estimOptions essentially tunes the optimization process and the variational EM algorithm, with the following parameters
"nbCores" integer for number of cores used. Default is 2 (1 under Positron, which does not allow forking)
"verbosity" integer for verbosity (0, 1). Default is 1
"nbBlocksRange" List of length the number of functional groups, each element supplying the minimal and maximal number of blocks to be explored. The names of the list must be the names of the functional groups. Default value is from 1 to 10)
"initBM" Boolean. True if using simple and bipartite SBM as initialisations. Default value = TRUE
"maxiterVEM" Number of max. number of iterations in the VEM. Default value = 100
"maxiterVE" Number of max. number of iterations in the VE. Default value = 100
"plot" boolean, should the ICL be dynamically plotted or not. Default is TRUE, FALSE when "verbosity" is 0. For dependent networks
"exploreFactor" control the exploration of the number of groups. For dependent networks
"exploreMin" explore at least until exploreMin even if the exploration factor rule is achieved. Default 4. See the package blockmodels for details. For dependent networks
"exploreMax" Stop exploration at exploreMax even if the exploration factor rule is not achieved. Default Inf. See the package blockmodels for details. For dependent networks
"nbBlocksRange" minimal and maximal number or blocks explored. For dependent networks
"fast" logical: should approximation be used for Bernoulli model with covariates. Default to TRUE. For dependent networks
a MultiplexSBM_fit object with the estimated parameters and the blocks
## Not run: ### ======================================= ### MULTIPLEX SBM without dependence between layers ## Nnodes <- 40 blockProp <- c(.4,.6) nbLayers <- 2 connectParam <- list(list(mean=matrix(rbeta(4,.5,.5),2,2)),list(mean=matrix(rexp(4,.5),2,2))) model <- c("bernoulli","poisson") type <- "directed" mySampleMultiplexSBM <- sampleMultiplexSBM( nbNodes = Nnodes, blockProp = blockProp, nbLayers = nbLayers, connectParam = connectParam, model=model, type=type) listSBM <- mySampleMultiplexSBM$listSBM estimOptions <- list(initBM = FALSE, nbCores = 2) myMultiplexSBM <- estimateMultiplexSBM(listSBM,estimOptions,dependent=FALSE) ### ======================================= ### MULTIPLEX SBM Gaussian with dependence ## Q <- 3 nbLayers <- 2 connectParam <- list() connectParam$mu <- vector("list",nbLayers) connectParam$mu[[1]] <- matrix(.1,Q,Q) + diag(1:Q) connectParam$mu[[2]] <- matrix(-2,Q,Q) + diag(rev(Q:1)) connectParam$Sigma <- matrix(c(2,1,1,4),nbLayers,nbLayers) model <- rep("gaussian",2) type <- "directed" Nnodes <- 80 blockProp <- c(.3,.3,.4) mySampleMultiplexSBM <- sampleMultiplexSBM( nbNodes = Nnodes, blockProp = blockProp, nbLayers = nbLayers, connectParam = connectParam, model=model, type="undirected", dependent=TRUE) listSBM <- mySampleMultiplexSBM$listSBM myMultiplexSBM <- estimateMultiplexSBM(listSBM,estimOptions,dependent=TRUE) ## MultiplexSBM Bernoulli with dependence Q <- 2 P00<-matrix(runif(Q*Q),Q,Q) P10<-matrix(runif(Q*Q),Q,Q) P01<-matrix(runif(Q*Q),Q,Q) P11<-matrix(runif(Q*Q),Q,Q) SumP<-P00+P10+P01+P11 P00<-P00/SumP P01<-P01/SumP P10<-P10/SumP P11<-P11/SumP connectParam <- list() connectParam$prob00 <- P00 connectParam$prob01 <- P01 connectParam$prob10 <- P10 connectParam$prob11 <- P11 model <- rep("bernoulli",2) type <- "directed" nbLayers <- 2 Nnodes <- 40 blockProp <- c(.6,.4) mySampleMultiplexSBM <- sampleMultiplexSBM( nbNodes = Nnodes, blockProp = blockProp, nbLayers = nbLayers, connectParam = connectParam, model=model, type=type, dependent=TRUE) listSBM <- mySampleMultiplexSBM$listSBM myMultiplexSBM <- estimateMultiplexSBM(listSBM,estimOptions,dependent=TRUE) ## End(Not run)## Not run: ### ======================================= ### MULTIPLEX SBM without dependence between layers ## Nnodes <- 40 blockProp <- c(.4,.6) nbLayers <- 2 connectParam <- list(list(mean=matrix(rbeta(4,.5,.5),2,2)),list(mean=matrix(rexp(4,.5),2,2))) model <- c("bernoulli","poisson") type <- "directed" mySampleMultiplexSBM <- sampleMultiplexSBM( nbNodes = Nnodes, blockProp = blockProp, nbLayers = nbLayers, connectParam = connectParam, model=model, type=type) listSBM <- mySampleMultiplexSBM$listSBM estimOptions <- list(initBM = FALSE, nbCores = 2) myMultiplexSBM <- estimateMultiplexSBM(listSBM,estimOptions,dependent=FALSE) ### ======================================= ### MULTIPLEX SBM Gaussian with dependence ## Q <- 3 nbLayers <- 2 connectParam <- list() connectParam$mu <- vector("list",nbLayers) connectParam$mu[[1]] <- matrix(.1,Q,Q) + diag(1:Q) connectParam$mu[[2]] <- matrix(-2,Q,Q) + diag(rev(Q:1)) connectParam$Sigma <- matrix(c(2,1,1,4),nbLayers,nbLayers) model <- rep("gaussian",2) type <- "directed" Nnodes <- 80 blockProp <- c(.3,.3,.4) mySampleMultiplexSBM <- sampleMultiplexSBM( nbNodes = Nnodes, blockProp = blockProp, nbLayers = nbLayers, connectParam = connectParam, model=model, type="undirected", dependent=TRUE) listSBM <- mySampleMultiplexSBM$listSBM myMultiplexSBM <- estimateMultiplexSBM(listSBM,estimOptions,dependent=TRUE) ## MultiplexSBM Bernoulli with dependence Q <- 2 P00<-matrix(runif(Q*Q),Q,Q) P10<-matrix(runif(Q*Q),Q,Q) P01<-matrix(runif(Q*Q),Q,Q) P11<-matrix(runif(Q*Q),Q,Q) SumP<-P00+P10+P01+P11 P00<-P00/SumP P01<-P01/SumP P10<-P10/SumP P11<-P11/SumP connectParam <- list() connectParam$prob00 <- P00 connectParam$prob01 <- P01 connectParam$prob10 <- P10 connectParam$prob11 <- P11 model <- rep("bernoulli",2) type <- "directed" nbLayers <- 2 Nnodes <- 40 blockProp <- c(.6,.4) mySampleMultiplexSBM <- sampleMultiplexSBM( nbNodes = Nnodes, blockProp = blockProp, nbLayers = nbLayers, connectParam = connectParam, model=model, type=type, dependent=TRUE) listSBM <- mySampleMultiplexSBM$listSBM myMultiplexSBM <- estimateMultiplexSBM(listSBM,estimOptions,dependent=TRUE) ## End(Not run)
This function performs variational inference of simple Stochastic Block Models, with various model for the distribution of the edges: Bernoulli, Poisson, or Gaussian models.
estimateSimpleSBM( netMat, model = "bernoulli", directed = !isSymmetric(netMat), dimLabels = c("node"), covariates = list(), nodesCovariates = matrix(0, 0, 0), estimOptions = list() )estimateSimpleSBM( netMat, model = "bernoulli", directed = !isSymmetric(netMat), dimLabels = c("node"), covariates = list(), nodesCovariates = matrix(0, 0, 0), estimOptions = list() )
netMat |
a matrix describing the network: either an adjacency (square) or incidence matrix with possibly weighted entries. |
model |
character describing the model for the relation between nodes ( |
directed |
logical: is the network directed or not? Only relevant when |
dimLabels |
an optional label for referring to the nodes |
covariates |
a list of matrices with same dimension as mat describing covariates at the edge level. No covariate per Default. |
nodesCovariates |
a matrix with the same number of rows as the number of nodes in the network, describing the nodes covariates. No nodes covariates per default. |
estimOptions |
a list of parameters controlling the inference algorithm and model selection. See details. |
The list of parameters estimOptions essentially tunes the optimization process and the variational EM algorithm, with the following parameters
"nbCores integer for number of cores used. Default is 2 (1 under Positron, which does not allow forking)
"verbosity" integer for verbosity (0, 1). Default is 1
"plot" boolean, should the ICL be dynamically plotted or not. Default is TRUE, FALSE when "verbosity" is 0
"exploreFactor" control the exploration of the number of groups
"exploreMin" explore at least until exploreMin even if the exploration factor rule is achieved. Default 4. See the package blockmodels for details.
"exploreMax" Stop exploration at exploreMax even if the exploration factor rule is not achieved. Default Inf. See the package blockmodels for details.
"nbBlocksRange" minimal and maximal number or blocks explored
"fast" logical: should approximation be used for Bernoulli model with covariates. Default to TRUE
a list with the estimated parameters. See details...
### ======================================= ### SIMPLE BINARY SBM (Bernoulli model) ## Graph parameters & Sampling nbNodes <- 60 blockProp <- c(.5, .25, .25) # group proportions means <- diag(.4, 3) + 0.05 # connectivity matrix: affiliation network connectParam <- list(mean = means) mySampler <- sampleSimpleSBM(nbNodes, blockProp, connectParam) adjacencyMatrix <- mySampler$networkData ## Estimation mySimpleSBM <- estimateSimpleSBM(adjacencyMatrix, 'bernoulli', estimOptions = list(plot = FALSE)) plot(mySimpleSBM, 'data', ordered = FALSE) plot(mySimpleSBM, 'data') plot(mySimpleSBM, 'expected', ordered = FALSE) plot(mySimpleSBM, 'expected') plot(mySimpleSBM, 'meso') ### ======================================= ### SIMPLE POISSON SBM ## Graph parameters & Sampling nbNodes <- 60 blockProp <- c(.5, .25, .25) # group proportions means <- diag(15., 3) + 5 # connectivity matrix: affiliation network connectParam <- list(mean = means) mySampler <- sampleSimpleSBM(nbNodes, blockProp, list(mean = means), model = "poisson") adjacencyMatrix <- mySampler$networkData ## Estimation mySimpleSBM <- estimateSimpleSBM(adjacencyMatrix, 'poisson', estimOptions = list(plot = FALSE)) plot(mySimpleSBM, 'data', ordered = FALSE) plot(mySimpleSBM, 'data') plot(mySimpleSBM, 'expected', ordered = FALSE) plot(mySimpleSBM, 'expected') ### ======================================= ### SIMPLE GAUSSIAN SBM ## Graph parameters & Sampling nbNodes <- 60 blockProp <- c(.5, .25, .25) # group proportions means <- diag(15., 3) + 5 # connectivity matrix: affiliation network connectParam <- list(mean = means, var = 2) mySampler <- sampleSimpleSBM(nbNodes, blockProp, connectParam, model = "gaussian") ## Estimation mySimpleSBM <- estimateSimpleSBM(mySampler$networkData, 'gaussian', estimOptions = list(plot = FALSE)) plot(mySimpleSBM, 'data', ordered = FALSE) plot(mySimpleSBM, 'data') plot(mySimpleSBM, 'expected', ordered = FALSE) plot(mySimpleSBM, 'expected')### ======================================= ### SIMPLE BINARY SBM (Bernoulli model) ## Graph parameters & Sampling nbNodes <- 60 blockProp <- c(.5, .25, .25) # group proportions means <- diag(.4, 3) + 0.05 # connectivity matrix: affiliation network connectParam <- list(mean = means) mySampler <- sampleSimpleSBM(nbNodes, blockProp, connectParam) adjacencyMatrix <- mySampler$networkData ## Estimation mySimpleSBM <- estimateSimpleSBM(adjacencyMatrix, 'bernoulli', estimOptions = list(plot = FALSE)) plot(mySimpleSBM, 'data', ordered = FALSE) plot(mySimpleSBM, 'data') plot(mySimpleSBM, 'expected', ordered = FALSE) plot(mySimpleSBM, 'expected') plot(mySimpleSBM, 'meso') ### ======================================= ### SIMPLE POISSON SBM ## Graph parameters & Sampling nbNodes <- 60 blockProp <- c(.5, .25, .25) # group proportions means <- diag(15., 3) + 5 # connectivity matrix: affiliation network connectParam <- list(mean = means) mySampler <- sampleSimpleSBM(nbNodes, blockProp, list(mean = means), model = "poisson") adjacencyMatrix <- mySampler$networkData ## Estimation mySimpleSBM <- estimateSimpleSBM(adjacencyMatrix, 'poisson', estimOptions = list(plot = FALSE)) plot(mySimpleSBM, 'data', ordered = FALSE) plot(mySimpleSBM, 'data') plot(mySimpleSBM, 'expected', ordered = FALSE) plot(mySimpleSBM, 'expected') ### ======================================= ### SIMPLE GAUSSIAN SBM ## Graph parameters & Sampling nbNodes <- 60 blockProp <- c(.5, .25, .25) # group proportions means <- diag(15., 3) + 5 # connectivity matrix: affiliation network connectParam <- list(mean = means, var = 2) mySampler <- sampleSimpleSBM(nbNodes, blockProp, connectParam, model = "gaussian") ## Estimation mySimpleSBM <- estimateSimpleSBM(mySampler$networkData, 'gaussian', estimOptions = list(plot = FALSE)) plot(mySimpleSBM, 'data', ordered = FALSE) plot(mySimpleSBM, 'data') plot(mySimpleSBM, 'expected', ordered = FALSE) plot(mySimpleSBM, 'expected')
Extracts fitted values for object with class (SimpleSBM_fit,
BipartiteSBM_fit) or multipartitepartiteSBM_fit)
## S3 method for class 'SBM' fitted(object, ...)## S3 method for class 'SBM' fitted(object, ...)
object |
an R6 object inheriting from SimpleSBM_fit, BipartiteSBM_fit or MultipartiteSBM_fit |
... |
additional parameters for S3 compatibility. Not used |
a matrix of expected fitted values for each dyad
This data set provides information about $154$ fungi sampled on $51$ tree species.
fungusTreeNetworkfungusTreeNetwork
A list with the following entries:
fungi_list list of the fungus species names
tree_list list of the tree species names
fungus_tree binary fungus-tree interactions
tree_tree weighted tree-tree interactions (number of common fungal species two tree species host)
covar_tree covariates associated to pairs of trees (namely genetic, taxonomic and geographic distances)
Vacher, Corinne, Dominique Piou, and Marie-Laure Desprez-Loustau. "Architecture of an antagonistic tree/fungus network: the asymmetric influence of past evolutionary history." PloS one 3.3 (2008): e1740.
Auxiliary function to check the given class of an object
is_SBM(Robject)is_SBM(Robject)
Robject |
an R6 object inheriting from class SBM |
TRUE or FALSE
Multipartite network of mutualistic interactions between plants and pollinators, plants and birds and plants and ants.
multipartiteEcologicalNetworkmultipartiteEcologicalNetwork
A list a 3 binary incidence matrices
Inc_plant_ant Interactions between plants (rows) and ants (cols). Matrix with 141 rows and 30 columns
Inc_plant_bird Interactions between plants (rows) and birds (cols). Matrix with141 rows and 46 columns
Inc_plant_flovis Interactions between plants (rows) and pollinators (cols). Matrix with 141 rows and 173 columns
Dataset compiled and conducted at Centro de Investigaciones Costeras La Mancha (CICOLMA), located on the central coast of the Gulf of Mexico, Veracruz, Mexico. see doi:10.1098/rspb.2016.1564 and https://github.com/lucaspdmedeiros/multi-network_core_removal/tree/master/data
R6 Class definition of a Multipartite SBM
SBM -> MultipartiteSBM
dimLabelsvector of characters giving the label of each connected dimension
blockProplist of two vectors of block proportions (aka prior probabilities of each block)
connectParamparameters associated to the connectivity of the SBM, e.g. matrix of inter/inter block probabilities when model is Bernoulli
probMembershipsmatrix of estimated probabilities for block memberships for all nodes
nbBlocks: vector with the number of blocks in each FG
nbConnectParamnumber of parameter used for the connectivity
architectureorganization of the multipartite network
nbNetworksnumber of networks in the multipartite network
membershipslist of size 2: vector of memberships in all parts of the network
indMembershipsmatrix for clustering memberships
MultipartiteSBM$new()constructor for Multipartite SBM
MultipartiteSBM$new( model = character(0), architecture = matrix(NA, 0, 2), directed = logical(0), nbNodes = numeric(0), dimLabels = character(0), blockProp = list(), connectParam = list() )
modelcharacter describing the type of model
architecturea 2-column matrix describing interactions between the networks
directedvector of logical: are the network directed or not?
nbNodesnumber of nodes in each dimension/part of the network
dimLabelslabels of each par of the network
blockPropparameters for block proportions (vector of list of vectors)
connectParamparameters of connectivity (vector of list of vectors)
MultipartiteSBM$show()print method
MultipartiteSBM$show(type = "Multipartite Stochastic Block Model")
typecharacter to tune the displayed name
MultipartiteSBM$print()print method
MultipartiteSBM$print()
MultipartiteSBM$plot()plot Multipartite Network
MultipartiteSBM$plot(
type = c("data", "expected", "meso"),
ordered = TRUE,
plotOptions = list()
)
typecharacter for the type of plot: either 'data' (true connection), 'expected' (fitted connection) or 'meso' (mesoscopic view). Default to 'data'.
orderedTRUE is the matrices are plotted after reorganization with the blocks. Default value = TRUE
plotOptionslist of plot options for the mesoscopic view or matrix view
MultipartiteSBM$clone()The objects of this class are cloneable with this method.
MultipartiteSBM$clone(deep = FALSE)
deepWhether to make a deep clone.
This class is designed to give a representation and adjust a Multipartite SBM fitted with GREMLIN.
The list of parameters estimOptions essentially tunes the optimization process and the variational EM algorithm, with the following parameters
"nbCores integer for number of cores used. Default is 2 (1 under Positron, which does not allow forking)
"verbosity" integer for verbosity (0, 1). Default is 1
"plot" boolean, should the ICL be dynamically plotted or not. Default is TRUE, FALSE when "verbosity" is 0
"exploreFactor" control the exploration of the number of groups
"exploreMin" explore at least until exploreMin even if the exploration factor rule is achieved. Default 4. See the package blockmodels for details.
"exploreMax" Stop exploration at exploreMax even if the exploration factor rule is not achieved. Default Inf. See the package blockmodels for details.
"nbBlocksRange" minimal and maximal number or blocks explored
"fast" logical: should approximation be used for Bernoulli model with covariates. Default to TRUE
SBM -> MultipartiteSBM -> MultipartiteSBM_fit
loglikdouble: approximation of the log-likelihood (variational lower bound) reached
ICLdouble: value of the integrated classification log-likelihood
storedModelsdata.frame of all models fitted (and stored) during the optimization
MultipartiteSBM_fit$new()constructor for Multipartite SBM
MultipartiteSBM_fit$new(netList)
netListlist of SBM objects
MultipartiteSBM_fit$optimize()estimation of multipartiteSBM via GREMLINS
MultipartiteSBM_fit$optimize(estimOptions)
estimOptionsoptions for MultipartiteBM
MultipartiteSBM_fit$predict()prediction under the currently estimated model
MultipartiteSBM_fit$predict()
a list of matrices matrix of expected values for each dyad
MultipartiteSBM_fit$setModel()method to select a specific model among the ones fitted during the optimization. Fields of the current MultipartiteSBM_fit will be updated accordingly.
MultipartiteSBM_fit$setModel(index)
indexinteger, the index of the model to be selected (row number in storedModels)
MultipartiteSBM_fit$show()show method
MultipartiteSBM_fit$show(type = "Fit of a Multipartite Stochastic Block Model")
typecharacter used to specify the type of SBM
MultipartiteSBM_fit$clone()The objects of this class are cloneable with this method.
MultipartiteSBM_fit$clone(deep = FALSE)
deepWhether to make a deep clone.
This class is designed to give a representation and adjust a Multiplex SBM fitted with GREMLIN.
The list of parameters estimOptions essentially tunes the optimization process and the variational EM algorithm, with the following parameters
"nbCores" integer for number of cores used. Default is 2 (1 under Positron, which does not allow forking)
"verbosity" integer for verbosity (0, 1). Default is 1
"nbBlocksRange" List of length the number of functional groups, each element supplying the minimal and maximal number of blocks to be explored. The names of the list must be the names of the functional groups. Default value is from 1 to 10)
"initBM" Boolean. True if using simple and bipartite SBM as initialisations. Default value = TRUE
"maxiterVEM" Number of max. number of iterations in the VEM. Default value = 100
"maxiterVE" Number of max. number of iterations in the VE. Default value = 100
SBM -> MultipartiteSBM -> MultipartiteSBM_fit -> MultiplexSBM_fit
nbBlocksvector of size 2: number of blocks (rows, columns)
dependentNetwork: connection parameters in each network
storedModelsdata.frame of all models fitted (and stored) during the optimization
namesLayers: names of the various Networks
MultiplexSBM_fit$new()constructor for Multiplex SBM
MultiplexSBM_fit$new(netList, dependentNet = FALSE)
netListlist of SBM object with
dependentNetboolean indicating whether dependence is assumed between networks beyond the common dependence on the latent variables
MultiplexSBM_fit$optimize()estimation of multipartiteSBM via GREMLINS
MultiplexSBM_fit$optimize(estimOptions)
estimOptionsoptions for MultipartiteBM
MultiplexSBM_fit$plot()plot Multiplex Network
MultiplexSBM_fit$plot(
type = c("data", "expected", "graphon"),
ordered = TRUE,
plotOptions = list()
)
typecharacter for the type of plot: either 'data' (true connection), 'expected' (fitted connection) or 'graphon' (block connectivity of each layer on the unit square, blocks sized by the block proportions; the marginal connectivity of each layer in the dependent case). Default to 'data'.
orderedTRUE is the matrices are plotted after reorganization with the blocks. Default value = TRUE
plotOptionslist of plot options for the matrix view
MultiplexSBM_fit$show()show method
MultiplexSBM_fit$show(type = "Fit of a Multiplex Stochastic Block Model")
typecharacter used to specify the type of SBM
MultiplexSBM_fit$predict()prediction under the currently estimated model
MultiplexSBM_fit$predict()
a list of matrices matrix of expected values for each dyad
MultiplexSBM_fit$clone()The objects of this class are cloneable with this method.
MultiplexSBM_fit$clone(deep = FALSE)
deepWhether to make a deep clone.
Basic matrix plot method for SBM object or mesoscopic view
## S3 method for class 'SBM' plot( x, type = c("data", "expected", "graphon", "meso"), ordered = TRUE, plotOptions = list(), ... )## S3 method for class 'SBM' plot( x, type = c("data", "expected", "graphon", "meso"), ordered = TRUE, plotOptions = list(), ... )
x |
an object inheriting from class SBM |
type |
character for the type of plot: either 'data' (true connection), 'expected' (fitted connection), 'graphon' (block connectivity on the unit square, blocks sized by the block proportions) or 'meso' (mesoscopic). Default to 'data'. 'graphon' is available for simple, bipartite and multiplex SBM (one panel per layer). |
ordered |
logical: should the rows and columns be ordered according to the clustering? Default to |
plotOptions |
list with parameters for 'meso' type plot and data type plot. Details are given below |
... |
additional parameters for S3 compatibility. Not used |
For simple and bipartite SBM, the mesoscopic view draws the graphon as a network: each block is a node whose area is
proportional to the block proportion (the largest block of each type of nodes having the same size), and the connectivity between two blocks is an edge whose width and color grow with the
connectivity, with the colors of the graphon. The connectivity within a block is drawn as a loop. Edges are curved arrows for directed networks.
The list of parameters plotOptions for this mesoscopic plot is:
seed to control the layout (free layout). Default value is NULL
character string for the title. Default value is NULL
"free" (force-directed: the blocks are placed according to their connectivities), "groups" (one line of blocks per type of nodes, for bipartite SBM) or a matrix with the coordinates of the blocks (one row per block, rows then columns for the bipartite SBM). Default value is NULL: "free" for simple SBM, "groups" for bipartite SBM
Color of the blocks, one per type of nodes. Default values are taken in a hue palette without the reds of the connectivities
Color of the border of the blocks. Default value is NA (no border)
"circle", "square", "diamond" or "triangle", one per type of nodes. Default value is "circle": the types of nodes are distinguished by their colors
Factor multiplying the size of the blocks, one per type of nodes. Default value is 1
Prefix of the labels of the blocks, one per type of nodes. Default value is NULL: the number of the block for a simple SBM, the shortest prefixes of the labels of the dimensions which distinguish them for a bipartite SBM
Default value is "black"
Size of the labels. Default value is 3.5
The label of a block is drawn inside it when its radius is at least this fraction of the radius of the largest block (for a label of 2 characters, the fraction being proportional to the number of characters), outside it otherwise. Default value is 0.5. Set it to 0 to draw all the labels inside the blocks
Representation of the connectivity within the blocks for simple SBM: "loop" (a loop, as the other connections) or "fill" (the color of the block). Default value is "loop"
Threshold under which the connectivity is not plotted. Default value is -Inf
Factor multiplying the width of the edges. Default value is 1
Curvature of the edges for directed networks. Default value is 0.2
Factor multiplying the size of the arrows for directed networks. Default value is 1
Colors of the connectivities, as for the graphon (see below)
For multipartite SBM, the list of parameters plotOptions for the mesoscopic plot (drawn with ggplot2, the free layout being computed with igraph) is:
seed to control the free layout. Default value is NULL
character string for the title. Default value is NULL
"free" (the blocks are placed according to their connectivities, whatever their functional group), "groups" (one row of blocks per functional group) or a matrix with the coordinates of the blocks (one row per block, in the order of the functional groups). Default value is "free"
Colors of the functional groups. Default values are taken in a hue palette without the reds of the connectivities
Color of the border of the blocks. Default value is NA (no border)
"circle", "square", "diamond" or "triangle", one per functional group. Default value is "circle": the functional groups are distinguished by their colors
Size of the node (default is 1)
The second size of the node (e.g. for a rectangle)
Names of the vertices. Default value is the label of the nodes
Default value is "black"
Default value is 2. Font: 1 plain, 2 bold, 3, italic, 4 bold italic, 5 symbol
Font size (multiplication factor, device-dependent).Default value is 0.9.
Distance between the label and the vertex. Default value is 0
The position of the label in relation to the vertex. default value is 0
The label of a block is drawn inside it when its radius is at least this fraction of the radius of the largest block (for a label of 2 characters, the fraction being proportional to the number of characters), outside it otherwise. Default value is 0.5
Threshold under which the edge is not plotted. Default value is = -Inf
Default value is "gray"
Factor parameter. Default value is 1
Default value is 1
Default value is 1
Line type, could be 0 or "blank", 1 or "solid", 2 or "dashed", 3 or "dotted", 4 or "dotdash", 5 or "longdash", 6 or "twodash". Default value is "solid"
Default value is = 0.3.
For type = 'data' or 'expected plot', the list of parameters plotOptions is
Boolean. Set TRUE if you want to see the legend. Default value is FALSE
Boolean. Set TRUE if you want to print the title of the legend. Default value is FALSE
Position of the legend. Possible values are 'bottom', 'top','left,'right'. Default value is 'bottom'
Set true if the rownames must be plotted. Default value is FALSE
Set true if the colNames must be plotted. Default value is FALSE
Numeric. Size (in pts) of the row and column names. Default value is NULL: the size decreases with the number of nodes, so that the names do not overlap on a 5 inches plot
Chain of character. The color of the lines to separate groups if a clustering is provided. Default value is red
Numeric. Width of the lines to separate groups. Default value is NULL, automatically chosen
Chain of character. Title of the plot. Default value is NULL
Boolean. Color the background of each block (when ordered = TRUE), with an opacity growing with the mean value of the entries in the block. Default value is TRUE for type = 'data' and FALSE for type = 'expected'
Boolean. Color the entries with the colors of the graphon (see below) instead of gray levels. Default value is TRUE for type = 'expected' and FALSE for type = 'data'
Chain of character. The color of the block background. Default value is red
Numeric. Opacity of the least and most dense blocks. Default values are 0.1 and 0.6
For type = 'graphon', the blocks are drawn with the colors of the block background of the data plot.
The axes are in number of nodes, so that the aspect ratio of the plot reflects the dimensions of the network.
The list of parameters plotOptions is
As for the 'data' plot
As for the 'data' plot
Numeric vector of length 2. Range of the connectivity values mapped to the colors. Default value is NULL: from 0 to the maximal value (or the range for negative values). Set it to compare several graphons on the same color scale, for instance c(0, 1) for Bernoulli models
The graphon is drawn from the connectivity parameters only, without the effect of the covariates.
a ggplot2 object for the 'data', 'expected' and 'graphon', and 'meso'. For 'meso', the coordinates of the blocks are in the attribute "blockLayout" of the plot (a matrix with one row per block, named by the labels of the blocks): they can be modified and given back in plotOptions$layout, for instance lay <- attr(plot(mySBM, type = "meso"), "blockLayout"), then lay["P1", ] <- c(0, 2) and plot(mySBM, type = "meso", plotOptions = list(layout = lay))
Plot an alluvial plot between clusterings
plotAlluvial(listMemberships, plotOptions = list())plotAlluvial(listMemberships, plotOptions = list())
listMemberships |
: a list vectors containing the memberships |
plotOptions |
: a list containing the options for Alluvial plots |
The list of parameters plotOptions provides the following options
"curvy" numeric, controls the curvature of the alluvial. Default value = 0.3
"alpha numeric, vector of transparency of the stripes. Default value = 0.8
"gap.width" numeric, relative width of inter-category gaps. Default value = 0.1
"col" vector of colors of the stripes. Default value is NULL: the stripes are colored according to the clusters of the first clustering
"border" vector of border colors for the stripes. Default is white
"reorder" boolean. If TRUE, the clusters of each clustering are stacked so as to follow the clusters of the previous one, which limits the crossings of the stripes. The labels of the clusters are not changed. Default value = TRUE
display the alluvial plot, returns invisibly a list with the plotOptions and the table of frequencies
listMemberships <- list(C1 = rep(c('A','B','C'),each=10),C2 = rep(c(1,2,4),10)) plotAlluvial(listMemberships)listMemberships <- list(C1 = rep(c('A','B','C'),each=10),C2 = rep(c(1,2,4),10)) plotAlluvial(listMemberships)
Draws the block connectivity of a simple or bipartite SBM on the unit square, each block being sized by its proportion. The axes are in number of nodes, so that the aspect ratio of the plot reflects the dimensions of the network.
plotMyGraphon( connectParam, blockProp, nbNodes = 1, dimLabels = c(row = "row", col = "col"), plotOptions = list() )plotMyGraphon( connectParam, blockProp, nbNodes = 1, dimLabels = c(row = "row", col = "col"), plotOptions = list() )
connectParam |
: a matrix of connectivity parameters (one row per row block, one column per column block), or a list with a |
blockProp |
: the block proportions. A vector for a simple SBM, a list of two vectors (row and col) for a bipartite SBM |
nbNodes |
: a vector of length 1 or 2 giving the number of nodes in row and col. Default is 1 |
dimLabels |
: a vector of length 1 or 2 specifying the types of nodes in row and col (functional group) |
plotOptions |
: a list providing options. See details below. |
The graphon of an SBM is the piecewise constant function on whose value on the
rectangle of row block and column block is the connectivity parameter
; the sides of the rectangle are the proportions and
of the blocks. Contrary to the matrix plots (type = 'data' or
'expected' in plot.SBM), it does not depend on the nodes nor on
their memberships, only on the parameters of the model.
The blocks are drawn with the colors of the block background of the matrix plot
(plotMyMatrix), so that both plots can be put side by side.
For an SBM object (sampled or estimated), plot(x, type = 'graphon') gives the same plot.
The list of parameters plotOptions for the graphon plot is
"legend": Boolean. Set TRUE if you want to see the legend. Default value is FALSE
"legend.title": Boolean. Set TRUE if you want to print the title of the legend. Default value is FALSE
"legend.position": Position of the legend. Possible values are 'bottom', 'top','left,'right'. Default value is 'bottom'
"line.color": Chain of character. The color of the lines to separate blocks. Default value is red
"line.width": Numeric. Width of the lines to separate blocks. Default value is NULL, automatically chosen
"title": Chain of character. Title of the plot. Default value is NULL
"block.color": Chain of character. The color of the blocks. Default value is red
"blockAlpha.min", "blockAlpha.max": Numeric. Opacity of the blocks with the lowest and highest connectivity. Default values are 0.1 and 0.6
"limits": Numeric vector of length 2. Range of the connectivity values mapped to the colors. Default value is NULL: from 0 to the maximal value (or the range for negative values). Set it to compare several graphons on the same color scale, for instance c(0, 1) for Bernoulli models
a ggplot object corresponding to the plot
## simple SBM plotMyGraphon(matrix(c(0.8, 0.1, 0.1, 0.4), 2, 2), blockProp = c(0.3, 0.7), nbNodes = 50, dimLabels = 'individuals') ## bipartite SBM plotMyGraphon(matrix(c(0.7, 0.4, 0.1, 0.4, 0.15, 0.03), 2, 3, byrow = TRUE), blockProp = list(row = c(0.2, 0.8), col = c(0.1, 0.3, 0.6)), nbNodes = c(90, 120), dimLabels = c(row = 'Pollinators', col = 'Plants'), plotOptions = list(legend = TRUE, limits = c(0, 1))) ## from an SBM object: the parameters of a sampled network mySampler <- sampleSimpleSBM(nbNodes = 60, blockProp = c(0.5, 0.5), connectParam = list(mean = matrix(c(0.6, 0.1, 0.1, 0.3), 2, 2))) plotMyGraphon(mySampler$connectParam, mySampler$blockProp, mySampler$nbNodes, dimLabels = 'node', plotOptions = list(title = 'Graphon')) ## same plot plot(mySampler, type = 'graphon')## simple SBM plotMyGraphon(matrix(c(0.8, 0.1, 0.1, 0.4), 2, 2), blockProp = c(0.3, 0.7), nbNodes = 50, dimLabels = 'individuals') ## bipartite SBM plotMyGraphon(matrix(c(0.7, 0.4, 0.1, 0.4, 0.15, 0.03), 2, 3, byrow = TRUE), blockProp = list(row = c(0.2, 0.8), col = c(0.1, 0.3, 0.6)), nbNodes = c(90, 120), dimLabels = c(row = 'Pollinators', col = 'Plants'), plotOptions = list(legend = TRUE, limits = c(0, 1))) ## from an SBM object: the parameters of a sampled network mySampler <- sampleSimpleSBM(nbNodes = 60, blockProp = c(0.5, 0.5), connectParam = list(mean = matrix(c(0.6, 0.1, 0.1, 0.3), 2, 2))) plotMyGraphon(mySampler$connectParam, mySampler$blockProp, mySampler$nbNodes, dimLabels = 'node', plotOptions = list(title = 'Graphon')) ## same plot plot(mySampler, type = 'graphon')
Plot an adjacency or incidence Matrix
plotMyMatrix( Mat, dimLabels = c(row = "row", col = "col"), clustering = NULL, plotOptions = NULL )plotMyMatrix( Mat, dimLabels = c(row = "row", col = "col"), clustering = NULL, plotOptions = NULL )
Mat |
: a matrix representing the network |
dimLabels |
: a vector of length 1 or 2 specifying the types of nodes in row and col (functional group) (Default is |
clustering |
: a list of length 2 specifying a clustering on row and col |
plotOptions |
: a list providing options. See details below. |
The list of parameters plotOptions for the matrix plot is
"legend": Boolean. Set TRUE if you want to see the legend. Default value is FALSE
"legend.title": Boolean. Set TRUE if you want to print the title of the legend. Default value is FALSE
"legend.position": Position of the legend. Possible values are 'bottom', 'top','left,'right'. Default value is 'bottom'
"rowNames": Set true if the rownames must be plotted. Default value is FALSE
"colNames": Set true if the colNames must be plotted. Default value is FALSE
"names.size": Numeric. Size (in pts) of the row and column names. Default value is NULL: the size decreases with the number of nodes, so that the names do not overlap on a 5 inches plot
"line.color": Chain of character. The color of the lines to separate groups if a clustering is provided. Default value is red
"line.width": Numeric. Width of the lines to separate groups. Default value is NULL, automatically chosen
"title": Chain of character. Title of the plot. Default value is NULL
"blockBackground": Boolean. Color the background of each block, with an opacity growing with the mean value of the entries in the block. Only used when a clustering is provided. Default value is TRUE
"block.color": Chain of character. The color of the block background. Default value is red
"blockAlpha.min", "blockAlpha.max": Numeric. Opacity of the least and most dense blocks. Default values are 0.1 and 0.6
a ggplot object corresponding to the plot
M <- matrix(sample(c(0,1),900,replace=TRUE),30,30) plotMyMatrix(M, dimLabels = c('individulals'), plotOptions= list(legend = FALSE)) M2 <- matrix( rpois(800,10),40,20) plotMyMatrix(M2, dimLabels = c(row = 'reader',col = 'book'), plotOptions = list(legend = TRUE))M <- matrix(sample(c(0,1),900,replace=TRUE),30,30) plotMyMatrix(M, dimLabels = c('individulals'), plotOptions= list(legend = FALSE)) M2 <- matrix( rpois(800,10),40,20) plotMyMatrix(M2, dimLabels = c(row = 'reader',col = 'book'), plotOptions = list(legend = TRUE))
Plot the matrices corresponding to a Multipartite Network
plotMyMultipartiteMatrix(listSBM, memberships = NULL, plotOptions = list())plotMyMultipartiteMatrix(listSBM, memberships = NULL, plotOptions = list())
listSBM |
: a list of objects representing the multipartite network (see) |
memberships |
: a list of length equal to the number of Functional Groups providing the clusterings inside each group. |
plotOptions |
: a list containing the options. See details. |
plotOptions is a list containing the following items
"normalized": Boolean. TRUE if the various matrices are presented in the same scale (between O and 1). FALSE otherwise. Default value FALSE
"compact": Boolean. Default value is TRUE if you ask for the matrices to be transposed to have a more compact view
"legend": Boolean. Set TRUE if you want to see the legend. Default value is FALSE
"legend.title": Boolean. Set TRUE if you want to print the title of the legend. Default value is FALSE
"legend.position": Position of the legend. Possible values are 'bottom', 'top','left,'right'. Default value is 'bottom'
"nodeNames": Set true if the node Names must be plotted. Default value is FALSE
"line.color": The color of the lines to separate groups. Default value is red
"line.width": Width of the lines to separate groups. Default value is NULL, automatically chosen
"title": Title of the plot. Default value is NULL
"names.size": Numeric. Size (in pts) of the node names. Default value is NULL: the size decreases with the number of nodes
"blockBackground": Boolean. Color the background of each block, with an opacity growing with the mean value of the entries in the block. Only used when a clustering is provided. Default value is TRUE
"graphonColors": Boolean. Color the entries with the colors of the graphon (from blockAlpha.min to blockAlpha.max opacity of block.color) instead of white to black. Ignored for binary matrices. Default value is FALSE
"block.color": Chain of character. The color of the block background. Default value is red
"blockAlpha.min", "blockAlpha.max": Numeric. Opacity of the least and most dense blocks. Default values are 0.1 and 0.6
a ggplot object corresponding to the plot
data("multipartiteEcologicalNetwork") Net <- multipartiteEcologicalNetwork type='bipartite' model = 'bernoulli' directed = FALSE listNet <- list() listNet[[1]] = defineSBM(Net$Inc_plant_ant, model,type,directed, dimLabels = c(row = "Plants", col = "Ants")) listNet[[2]] = defineSBM(Net$Inc_plant_bird,model,type,directed, dimLabels =c(row = "Plants",col = "Birds")) plotMyMultipartiteMatrix(listNet,plotOptions=list(legend = TRUE,title='Ecology')) listNet <- list() listNet[[1]] <- defineSBM(matrix(rbinom(1000,1,0.5),20,50), model = 'bernoulli', type ='bipartite', directed = NA, dimLabels = c(row="Questions",col="Students")) listNet[[2]] <- defineSBM(matrix(rpois(20*30,8),30,20), model = 'poisson', type ='bipartite',directed = NA, dimLabels = c(row="Competences",col="Questions")) plotMyMultipartiteMatrix(listNet,plotOptions=list(legend = TRUE,compact = FALSE)) plotMyMultipartiteMatrix(listNet,plotOptions=list(legend = TRUE,normalized = TRUE))data("multipartiteEcologicalNetwork") Net <- multipartiteEcologicalNetwork type='bipartite' model = 'bernoulli' directed = FALSE listNet <- list() listNet[[1]] = defineSBM(Net$Inc_plant_ant, model,type,directed, dimLabels = c(row = "Plants", col = "Ants")) listNet[[2]] = defineSBM(Net$Inc_plant_bird,model,type,directed, dimLabels =c(row = "Plants",col = "Birds")) plotMyMultipartiteMatrix(listNet,plotOptions=list(legend = TRUE,title='Ecology')) listNet <- list() listNet[[1]] <- defineSBM(matrix(rbinom(1000,1,0.5),20,50), model = 'bernoulli', type ='bipartite', directed = NA, dimLabels = c(row="Questions",col="Students")) listNet[[2]] <- defineSBM(matrix(rpois(20*30,8),30,20), model = 'poisson', type ='bipartite',directed = NA, dimLabels = c(row="Competences",col="Questions")) plotMyMultipartiteMatrix(listNet,plotOptions=list(legend = TRUE,compact = FALSE)) plotMyMultipartiteMatrix(listNet,plotOptions=list(legend = TRUE,normalized = TRUE))
Plot the matrices corresponding to a Multiplex Network
plotMyMultiplexMatrix(listSBM, memberships = NULL, plotOptions = list())plotMyMultiplexMatrix(listSBM, memberships = NULL, plotOptions = list())
listSBM |
: a list of objects representing the multiplex network (see) |
memberships |
: a list of length equal to the number of Functional Groups providing the clusterings inside each group. |
plotOptions |
: a list containing the options. See details. |
plotOptions is a list containing the following items
"normalized": Boolean. TRUE if the various matrices are presented in the same scale (between O and 1). FALSE otherwise. Default value FALSE
"compact": Boolean. Default value is TRUE if you ask for the matrices to be transposed to have a more compact view
"legend": Boolean. Set TRUE if you want to see the legend. Default value is FALSE
"legend.title": Boolean. Set TRUE if you want to print the title of the legend. Default value is FALSE
"legend.position": Position of the legend. Possible values are 'bottom', 'top','left,'right'. Default value is 'bottom'
"nodeNames": Set true if the node Names must be plotted. Default value is FALSE
"line.color": The color of the lines to separate groups. Default value is red
"line.width": Width of the lines to separate groups. Default value is NULL, automatically chosen
"title": Title of the plot. Default value is NULL
"names.size": Numeric. Size (in pts) of the node names. Default value is NULL: the size decreases with the number of nodes
"blockBackground": Boolean. Color the background of each block, with an opacity growing with the mean value of the entries in the block. Only used when a clustering is provided. Default value is TRUE
"graphonColors": Boolean. Color the entries with the colors of the graphon (from blockAlpha.min to blockAlpha.max opacity of block.color) instead of white to black. Ignored for binary matrices. Default value is FALSE
"block.color": Chain of character. The color of the block background. Default value is red
"blockAlpha.min", "blockAlpha.max": Numeric. Opacity of the least and most dense blocks. Default values are 0.1 and 0.6
a ggplot object corresponding to the plot
Nnodes <- c(40,30) blockProp <- list(c(.4,.6),c(0.5,0.5)) nbLayers <- 2 connectParam <- list(list(mean=matrix(rbeta(4,.5,.5),2,2)),list(mean=matrix(rexp(4,.5),2,2))) names(connectParam) <- c('Read','Score') model <- c("bernoulli","poisson") type <- "bipartite" mySampleMultiplexSBM <- sampleMultiplexSBM( nbNodes = Nnodes, blockProp = blockProp, nbLayers = nbLayers, connectParam = connectParam, model=model, dimLabels = c('readers','books'), type=type) listNet <- mySampleMultiplexSBM$listSBM names(listNet) <- c("Read","Affinity") plotMyMultiplexMatrix(listNet,plotOptions=list(legend = TRUE))Nnodes <- c(40,30) blockProp <- list(c(.4,.6),c(0.5,0.5)) nbLayers <- 2 connectParam <- list(list(mean=matrix(rbeta(4,.5,.5),2,2)),list(mean=matrix(rexp(4,.5),2,2))) names(connectParam) <- c('Read','Score') model <- c("bernoulli","poisson") type <- "bipartite" mySampleMultiplexSBM <- sampleMultiplexSBM( nbNodes = Nnodes, blockProp = blockProp, nbLayers = nbLayers, connectParam = connectParam, model=model, dimLabels = c('readers','books'), type=type) listNet <- mySampleMultiplexSBM$listSBM names(listNet) <- c("Read","Affinity") plotMyMultiplexMatrix(listNet,plotOptions=list(legend = TRUE))
Make predictions from an SBM.
## S3 method for class 'SBM' predict(object, covarList = object$covarList, theta_p0 = 0, ...)## S3 method for class 'SBM' predict(object, covarList = object$covarList, theta_p0 = 0, ...)
object |
an R6 object inheriting from class SBM_fit (like SimpleSBM_fit or BipartiteSBM_fit) |
covarList |
a list of covariates. By default, we use the covariates associated with the model. |
theta_p0 |
a threshold... |
... |
additional parameters for S3 compatibility. Not used |
a matrix of expected values for each dyad
This function samples a simple Stochastic Block Models, with various model for the distribution of the edges: Bernoulli, Poisson, or Gaussian models, and possibly with covariates
sampleBipartiteSBM( nbNodes, blockProp = vector("list", 2), connectParam, model = "bernoulli", dimLabels = c(row = "row", col = "col"), covariates = list(), covariatesParam = numeric(0), nodesCovariates = vector("list", 2), nodesCovariatesParam = vector("list", 2) )sampleBipartiteSBM( nbNodes, blockProp = vector("list", 2), connectParam, model = "bernoulli", dimLabels = c(row = "row", col = "col"), covariates = list(), covariatesParam = numeric(0), nodesCovariates = vector("list", 2), nodesCovariatesParam = vector("list", 2) )
nbNodes |
number of nodes in the network |
blockProp |
parameters for block proportions: list of size two with row and column block proportions |
connectParam |
list of parameters for connectivity with a matrix of means 'mean' and an optional matrix of variances 'var', the sizes of which must match |
model |
character describing the model for the relation between nodes ( |
dimLabels |
an optional list of labels for each dimension (in row, in column) |
covariates |
a list of matrices with same dimension as mat describing covariates at the edge level. No covariate per Default. |
covariatesParam |
optional vector of covariates effect. A zero length numeric vector by default. |
nodesCovariates |
a list of two matrices with |
nodesCovariatesParam |
a list of two matrices of dimension |
an object with class BipartiteSBM
### ======================================= ### BIPARTITE BERNOULLI SBM ## Graph parameters nbNodes <- c(100, 120) blockProp <- list(c(.5, .5), c(1/3, 1/3, 1/3)) # group proportions means <- matrix(runif(6), 2, 3) # connectivity matrix # In Bernoulli SBM, parameters is a list with # a matrix of means 'mean' which are probabilities of connection connectParam <- list(mean = means) ## Graph Sampling dimLabels = c(row='Reader',col='Book') mySampler <- sampleBipartiteSBM(nbNodes, blockProp, connectParam, model = 'bernoulli',dimLabels) plot(mySampler) plot(mySampler,type='meso',plotOptions = list(vertex.label.name=list(row='Reader',col='Book'))) plot(mySampler,type='meso',plotOptions = list(vertex.label.name=c('A','B'),vertex.size = 1.4)) mySampler$rMemberships() # sample new memberships mySampler$rEdges() # sample new edges mySampler$rNetwork() # sample a new networrk (blocks and edges) ### ======================================= ### BIPARTITE POISSON SBM ## Graph parameters nbNodes <- c(100, 120) blockProp <- list(c(.5, .5), c(1/3, 1/3, 1/3)) # group proportions means <- matrix(rbinom(6, 30, 0.25), 2, 3) # connectivity matrix # In Poisson SBM, parameters is a list with a matrix of # means 'mean' which are a mean integer value taken by edges connectParam <- list(mean = means) ## Graph Sampling dimLabels = c(row = 'Ind', col = 'Service') mySampler <- sampleBipartiteSBM(nbNodes, blockProp, connectParam, model = 'poisson', dimLabels) plot(mySampler,type='expected') plotOptions = list(vertex.label.name=c('U','V'),vertex.size = c(1.4,1.3)) plot(mySampler, type='meso', plotOptions = plotOptions) hist(mySampler$networkData) ### ======================================= ### BIPARTITE GAUSSIAN SBM ## Graph parameters nbNodes <- c(100, 120) blockProp <- list(c(.5, .5), c(1/3, 1/3, 1/3)) # group proportions means <- 20 * matrix(runif(6), 2, 3) # connectivity matrix # In Gaussian SBM, parameters is a list with a matrix # of means 'mean' and a matrix of variances 'var' connectParam <- list(mean = means, var = 1) ## Graph Sampling mySampler <- sampleBipartiteSBM(nbNodes, blockProp, connectParam, model = 'gaussian') plot(mySampler) hist(mySampler$networkData)### ======================================= ### BIPARTITE BERNOULLI SBM ## Graph parameters nbNodes <- c(100, 120) blockProp <- list(c(.5, .5), c(1/3, 1/3, 1/3)) # group proportions means <- matrix(runif(6), 2, 3) # connectivity matrix # In Bernoulli SBM, parameters is a list with # a matrix of means 'mean' which are probabilities of connection connectParam <- list(mean = means) ## Graph Sampling dimLabels = c(row='Reader',col='Book') mySampler <- sampleBipartiteSBM(nbNodes, blockProp, connectParam, model = 'bernoulli',dimLabels) plot(mySampler) plot(mySampler,type='meso',plotOptions = list(vertex.label.name=list(row='Reader',col='Book'))) plot(mySampler,type='meso',plotOptions = list(vertex.label.name=c('A','B'),vertex.size = 1.4)) mySampler$rMemberships() # sample new memberships mySampler$rEdges() # sample new edges mySampler$rNetwork() # sample a new networrk (blocks and edges) ### ======================================= ### BIPARTITE POISSON SBM ## Graph parameters nbNodes <- c(100, 120) blockProp <- list(c(.5, .5), c(1/3, 1/3, 1/3)) # group proportions means <- matrix(rbinom(6, 30, 0.25), 2, 3) # connectivity matrix # In Poisson SBM, parameters is a list with a matrix of # means 'mean' which are a mean integer value taken by edges connectParam <- list(mean = means) ## Graph Sampling dimLabels = c(row = 'Ind', col = 'Service') mySampler <- sampleBipartiteSBM(nbNodes, blockProp, connectParam, model = 'poisson', dimLabels) plot(mySampler,type='expected') plotOptions = list(vertex.label.name=c('U','V'),vertex.size = c(1.4,1.3)) plot(mySampler, type='meso', plotOptions = plotOptions) hist(mySampler$networkData) ### ======================================= ### BIPARTITE GAUSSIAN SBM ## Graph parameters nbNodes <- c(100, 120) blockProp <- list(c(.5, .5), c(1/3, 1/3, 1/3)) # group proportions means <- 20 * matrix(runif(6), 2, 3) # connectivity matrix # In Gaussian SBM, parameters is a list with a matrix # of means 'mean' and a matrix of variances 'var' connectParam <- list(mean = means, var = 1) ## Graph Sampling mySampler <- sampleBipartiteSBM(nbNodes, blockProp, connectParam, model = 'gaussian') plot(mySampler) hist(mySampler$networkData)
This function samples a Multipartite Stochastic Block Models, with various model for the distribution of the edges: Bernoulli, Poisson, or Gaussian models
sampleMultipartiteSBM( nbNodes, blockProp, archiMultipartite, connectParam, model, directed, dimLabels = NULL, seed = NULL )sampleMultipartiteSBM( nbNodes, blockProp, archiMultipartite, connectParam, model, directed, dimLabels = NULL, seed = NULL )
nbNodes |
number of nodes in each functional group involved in the multipartite network |
blockProp |
a list of parameters for block proportions in each functional group |
archiMultipartite |
a matrix with two columns and nbNetworks lines, each line specifying the index of the functional groups in interaction. |
connectParam |
list of parameters for connectivity (of length nbNetworks). Each element is a list of one or two elements: a matrix of means 'mean' and an optional matrix of variances 'var', the sizes of which must match |
model |
a vector of characters describing the model for each network of the Multipartite relation between nodes ( |
directed |
a vector of logical, directed network or not for each network. Default is |
dimLabels |
an optional list of labels for functional group involved in the network |
seed |
numeric to set the seed. |
a list of two elements : simulatedMemberships are the clustering of each node in each Functional Group,
multipartiteNetwork is the list of the simulated networks (each one being a simple or bipartite network)
### ======================================= ### MULTIPARTITE SBM : 4 networks between 3 Functional Groups ## Graph parameters # About the Functional Groups (FG) nbNodes <- c(100,50,40) blockProp <- vector("list", 3) # parameters of clustering in each functional group blockProp[[1]] <- c(0.4,0.3,0.3) # in Functional Group 1 blockProp[[2]] <- c(0.6,0.4) # in Functional Group 2 blockProp[[3]] <- c(0.6,0.4) # in Functional Group 3 # About the interactions between the FG archiMultipartite <- rbind(c(1,2),c(2,3),c(2,2),c(1,3)) # model <- c('bernoulli','poisson','gaussian','gaussian') # type of distribution in each network # for each network : directed or not (not required for an interaction between two different FG) directed <- c( NA, NA , FALSE , NA) connectParam <- list() connectParam[[1]] <- list(mean = matrix(c(0.3, 0.3, 0.5, 0.2, 0.6, 0.6),3,2)) connectParam[[2]] <- list(mean = matrix(c(1000 , 500, 400 , 950),2,2)) connectParam[[3]] <- list(mean = matrix(c(10, 0, -10, 20), 2,2), var = matrix(1,2,2)) connectParam[[4]] <- list(mean = matrix(c(3, 23 ,11 ,16 , 2 ,25), 3,2)) connectParam[[4]]$var <- matrix(c(10,20,1,5,0.1,10), 3,2) dimLabels <- c('A','B','C') ## Graph Sampling mySampleMBM <- sampleMultipartiteSBM(nbNodes, blockProp, archiMultipartite, connectParam, model, directed, dimLabels,seed = 3) listSBM <- mySampleMBM$listSBM memberships <- mySampleMBM$memberships plotMyMultipartiteMatrix(listSBM) plotMyMultipartiteMatrix(listSBM,plotOptions = list(normalized = TRUE)) plotMyMultipartiteMatrix(listSBM,memberships = memberships,plotOptions = list(normalized = TRUE))### ======================================= ### MULTIPARTITE SBM : 4 networks between 3 Functional Groups ## Graph parameters # About the Functional Groups (FG) nbNodes <- c(100,50,40) blockProp <- vector("list", 3) # parameters of clustering in each functional group blockProp[[1]] <- c(0.4,0.3,0.3) # in Functional Group 1 blockProp[[2]] <- c(0.6,0.4) # in Functional Group 2 blockProp[[3]] <- c(0.6,0.4) # in Functional Group 3 # About the interactions between the FG archiMultipartite <- rbind(c(1,2),c(2,3),c(2,2),c(1,3)) # model <- c('bernoulli','poisson','gaussian','gaussian') # type of distribution in each network # for each network : directed or not (not required for an interaction between two different FG) directed <- c( NA, NA , FALSE , NA) connectParam <- list() connectParam[[1]] <- list(mean = matrix(c(0.3, 0.3, 0.5, 0.2, 0.6, 0.6),3,2)) connectParam[[2]] <- list(mean = matrix(c(1000 , 500, 400 , 950),2,2)) connectParam[[3]] <- list(mean = matrix(c(10, 0, -10, 20), 2,2), var = matrix(1,2,2)) connectParam[[4]] <- list(mean = matrix(c(3, 23 ,11 ,16 , 2 ,25), 3,2)) connectParam[[4]]$var <- matrix(c(10,20,1,5,0.1,10), 3,2) dimLabels <- c('A','B','C') ## Graph Sampling mySampleMBM <- sampleMultipartiteSBM(nbNodes, blockProp, archiMultipartite, connectParam, model, directed, dimLabels,seed = 3) listSBM <- mySampleMBM$listSBM memberships <- mySampleMBM$memberships plotMyMultipartiteMatrix(listSBM) plotMyMultipartiteMatrix(listSBM,plotOptions = list(normalized = TRUE)) plotMyMultipartiteMatrix(listSBM,memberships = memberships,plotOptions = list(normalized = TRUE))
This function samples a Multiplex Stochastic Block Models, with various model for the distribution of the edges: Bernoulli, Poisson, or Gaussian models
sampleMultiplexSBM( nbNodes, blockProp, nbLayers, connectParam, model, type = c("directed", "undirected", "bipartite"), dependent = FALSE, dimLabels = NULL, seed = NULL )sampleMultiplexSBM( nbNodes, blockProp, nbLayers, connectParam, model, type = c("directed", "undirected", "bipartite"), dependent = FALSE, dimLabels = NULL, seed = NULL )
nbNodes |
number of nodes in each functional group involved in the Multiplex network |
blockProp |
a vector for block proportion if the networks are simple, a list of parameters for block proportions for both functional groups if the networks are bipartite |
nbLayers |
a matrix with two columns and nbNetworks lines, each line specifying the index of the functional groups in interaction. |
connectParam |
list of parameters for connectivity (of length nbNetworks). Each element is a list of one or two elements: a matrix of means 'mean' and an optional matrix of variances 'var', the sizes of which must match |
model |
a vector of characters describing the model for each network of the Multiplex relation between nodes ( |
type |
a string of character indicating whether the networks are directed, undirected or bipartite |
dependent |
connection parameters in each network |
dimLabels |
an optional list of labels for functional group involved in the network |
seed |
numeric to set the seed. |
a list of two elements : simulatedMemberships are the clustering of each node in each Functional Group, MultiplexNetwork is the list of the simulated networks (each one being a simple or bipartite network)
nbLayers <- 2 ## MultiplexSBM without dependence between layers Nnodes <- 40 blockProp <- c(.4,.6) connectParam <- list(list(mean=matrix(rbeta(4,.5,.5),2,2)),list(mean=matrix(rexp(4,.5),2,2))) model <- c("bernoulli","poisson") type <- "directed" mySampleMultiplexSBM <- sampleMultiplexSBM( nbNodes = Nnodes, blockProp = blockProp, nbLayers = nbLayers, connectParam = connectParam, model=model, type=type) listSBM <- mySampleMultiplexSBM$listSBM ## MultiplexSBM Gaussian with dependence Q <- 3 nbLayers <- 2 connectParam <- list() connectParam$mu <- vector("list",nbLayers) connectParam$mu[[1]] <- matrix(.1,Q,Q) + diag(1:Q) connectParam$mu[[2]] <- matrix(-2,Q,Q) + diag(rev(Q:1)) connectParam$Sigma <- matrix(c(2,1,1,4),nbLayers,nbLayers) model <- rep("gaussian",2) type <- "directed" Nnodes <- 80 blockProp <- c(.3,.3,.4) mySampleMultiplexSBM <- sampleMultiplexSBM( nbNodes = Nnodes, blockProp = blockProp, nbLayers = nbLayers, connectParam = connectParam, model=model, type="undirected", dependent=TRUE) listSBM <- mySampleMultiplexSBM$listSBM ## MultiplexSBM Bernoulli with dependence Q <- 2 P00<-matrix(runif(Q*Q),Q,Q) P10<-matrix(runif(Q*Q),Q,Q) P01<-matrix(runif(Q*Q),Q,Q) P11<-matrix(runif(Q*Q),Q,Q) SumP<-P00+P10+P01+P11 P00<-P00/SumP P01<-P01/SumP P10<-P10/SumP P11<-P11/SumP connectParam <- list() connectParam$prob00 <- P00 connectParam$prob01 <- P01 connectParam$prob10 <- P10 connectParam$prob11 <- P11 model <- rep("bernoulli",2) type <- "directed" nbLayers <- 2 Nnodes <- 40 blockProp <- c(.6,.4) mySampleMultiplexSBM <- sampleMultiplexSBM( nbNodes = Nnodes, blockProp = blockProp, nbLayers = nbLayers, connectParam = connectParam, model=model, type=type, dependent=TRUE) listSBM_BB <- mySampleMultiplexSBM$listSBMnbLayers <- 2 ## MultiplexSBM without dependence between layers Nnodes <- 40 blockProp <- c(.4,.6) connectParam <- list(list(mean=matrix(rbeta(4,.5,.5),2,2)),list(mean=matrix(rexp(4,.5),2,2))) model <- c("bernoulli","poisson") type <- "directed" mySampleMultiplexSBM <- sampleMultiplexSBM( nbNodes = Nnodes, blockProp = blockProp, nbLayers = nbLayers, connectParam = connectParam, model=model, type=type) listSBM <- mySampleMultiplexSBM$listSBM ## MultiplexSBM Gaussian with dependence Q <- 3 nbLayers <- 2 connectParam <- list() connectParam$mu <- vector("list",nbLayers) connectParam$mu[[1]] <- matrix(.1,Q,Q) + diag(1:Q) connectParam$mu[[2]] <- matrix(-2,Q,Q) + diag(rev(Q:1)) connectParam$Sigma <- matrix(c(2,1,1,4),nbLayers,nbLayers) model <- rep("gaussian",2) type <- "directed" Nnodes <- 80 blockProp <- c(.3,.3,.4) mySampleMultiplexSBM <- sampleMultiplexSBM( nbNodes = Nnodes, blockProp = blockProp, nbLayers = nbLayers, connectParam = connectParam, model=model, type="undirected", dependent=TRUE) listSBM <- mySampleMultiplexSBM$listSBM ## MultiplexSBM Bernoulli with dependence Q <- 2 P00<-matrix(runif(Q*Q),Q,Q) P10<-matrix(runif(Q*Q),Q,Q) P01<-matrix(runif(Q*Q),Q,Q) P11<-matrix(runif(Q*Q),Q,Q) SumP<-P00+P10+P01+P11 P00<-P00/SumP P01<-P01/SumP P10<-P10/SumP P11<-P11/SumP connectParam <- list() connectParam$prob00 <- P00 connectParam$prob01 <- P01 connectParam$prob10 <- P10 connectParam$prob11 <- P11 model <- rep("bernoulli",2) type <- "directed" nbLayers <- 2 Nnodes <- 40 blockProp <- c(.6,.4) mySampleMultiplexSBM <- sampleMultiplexSBM( nbNodes = Nnodes, blockProp = blockProp, nbLayers = nbLayers, connectParam = connectParam, model=model, type=type, dependent=TRUE) listSBM_BB <- mySampleMultiplexSBM$listSBM
This function samples a simple Stochastic Block Models, with various model for the distribution of the edges: Bernoulli, Poisson, or Gaussian models, and possibly with covariates
sampleSimpleSBM( nbNodes, blockProp = numeric(0), connectParam, model = "bernoulli", directed = FALSE, dimLabels = c("node"), covariates = list(), covariatesParam = numeric(0), nodesCovariates = matrix(0, 0, 0), nodesCovariatesParam = matrix(0, 0, 0) )sampleSimpleSBM( nbNodes, blockProp = numeric(0), connectParam, model = "bernoulli", directed = FALSE, dimLabels = c("node"), covariates = list(), covariatesParam = numeric(0), nodesCovariates = matrix(0, 0, 0), nodesCovariatesParam = matrix(0, 0, 0) )
nbNodes |
number of nodes in the network |
blockProp |
parameters for block proportions. Possibly null if the nodes affectation is driven by |
connectParam |
list of parameters for connectivity with a matrix of means 'mean' and an optional matrix of variances 'var', the sizes of which must match |
model |
character describing the model for the relation between nodes ( |
directed |
logical, directed network or not. Default is |
dimLabels |
an optional list of labels for each dimension (in row, in column) |
covariates |
a list of matrices with same dimension as mat describing covariates at the edge level. No covariate per Default. |
covariatesParam |
optional vector of covariates effect. A zero length numeric vector by default. |
nodesCovariates |
an optional matrix with |
nodesCovariatesParam |
an optional matrix of dimension |
an object with class SimpleSBM
### ======================================= ### SIMPLE BINARY SBM (Bernoulli model) ## Graph parameters nbNodes <- 90 blockProp <- c(.5, .25, .25) # group proportions means <- diag(.4, 3) + 0.05 # connectivity matrix: affiliation network # In Bernoulli SBM, parameters is a list with a # matrix of means 'mean' which are probabilities of connection connectParam <- list(mean = means) ## Graph Sampling mySampler <- sampleSimpleSBM(nbNodes, blockProp, connectParam, model = 'bernoulli') plot(mySampler) plot(mySampler) plot(mySampler,type='meso') hist(mySampler$networkData) ### ======================================= ### SIMPLE POISSON SBM ## Graph parameters nbNodes <- 90 blockProp <- c(.5, .25, .25) # group proportions means <- diag(15., 3) + 5 # connectivity matrix: affiliation network # In Poisson SBM, parameters is a list with # a matrix of means 'mean' which are a mean integer value taken by edges connectParam <- list(mean = means) ## Graph Sampling mySampler <- sampleSimpleSBM(nbNodes, blockProp, list(mean = means), model = "poisson") plot(mySampler) plot(mySampler,type='meso') hist(mySampler$networkData) ### ======================================= ### SIMPLE GAUSSIAN SBM ## Graph parameters nbNodes <- 90 blockProp <- c(.5, .25, .25) # group proportions means <- diag(15., 3) + 5 # connectivity matrix: affiliation network # In Gaussian SBM, parameters is a list with # a matrix of means 'mean' and a matrix of variances 'var' connectParam <- list(mean = means, var = 2) ## Graph Sampling mySampler <- sampleSimpleSBM(nbNodes, blockProp, connectParam, model = "gaussian",dimLabels='Tree') plot(mySampler) plot(mySampler,type='meso') hist(mySampler$networkData)### ======================================= ### SIMPLE BINARY SBM (Bernoulli model) ## Graph parameters nbNodes <- 90 blockProp <- c(.5, .25, .25) # group proportions means <- diag(.4, 3) + 0.05 # connectivity matrix: affiliation network # In Bernoulli SBM, parameters is a list with a # matrix of means 'mean' which are probabilities of connection connectParam <- list(mean = means) ## Graph Sampling mySampler <- sampleSimpleSBM(nbNodes, blockProp, connectParam, model = 'bernoulli') plot(mySampler) plot(mySampler) plot(mySampler,type='meso') hist(mySampler$networkData) ### ======================================= ### SIMPLE POISSON SBM ## Graph parameters nbNodes <- 90 blockProp <- c(.5, .25, .25) # group proportions means <- diag(15., 3) + 5 # connectivity matrix: affiliation network # In Poisson SBM, parameters is a list with # a matrix of means 'mean' which are a mean integer value taken by edges connectParam <- list(mean = means) ## Graph Sampling mySampler <- sampleSimpleSBM(nbNodes, blockProp, list(mean = means), model = "poisson") plot(mySampler) plot(mySampler,type='meso') hist(mySampler$networkData) ### ======================================= ### SIMPLE GAUSSIAN SBM ## Graph parameters nbNodes <- 90 blockProp <- c(.5, .25, .25) # group proportions means <- diag(15., 3) + 5 # connectivity matrix: affiliation network # In Gaussian SBM, parameters is a list with # a matrix of means 'mean' and a matrix of variances 'var' connectParam <- list(mean = means, var = 2) ## Graph Sampling mySampler <- sampleSimpleSBM(nbNodes, blockProp, connectParam, model = "gaussian",dimLabels='Tree') plot(mySampler) plot(mySampler,type='meso') hist(mySampler$networkData)
R6 virtual class for SBM representation (mother class of SimpleSBM, BipartiteSBM, MultipartiteSBM)
modelNamecharacter, the family of model for the distribution of the edges
directedmode of the network data (directed or not or not applicable)
dimLabelsvector or list of characters, the label of each dimension
nbNodesvector describing the number of the successive elements connecting the network
nbCovariatesinteger, the number of covariates
connectParamparameters associated to the connectivity of the SBM, e.g. matrix of inter/inter block probabilities when model is Bernoulli
covarParamvector of regression parameters associated with the covariates.
covarListlist of matrices of covariates
covarArraythe array of covariates
covarEffecteffect of covariates
nbNodesCovariatesthe dimension of the nodes covariates
nodesCovariatesthe list of nodes covariates
nodesCovariatesParamthe list of nodes covariates parameters
networkDatathe network data (adjacency or incidence matrix or list of such object)
expectationexpected values of connection under the current model
SBM$new()constructor for SBM
SBM$new(
model = vector("character", 0),
directed = vector("logical", 0),
dimension = vector("numeric", 0),
dimLabels = vector("character", 0),
blockProp = vector("numeric", 0),
connectParam = vector("list", 0),
covarParam = numeric(length(covarList)),
covarList = list(),
nodesCovarList = list(),
nodesCovarParam = list()
)
modelcharacter describing the type of model
directedlogical describing if the network data is directed or not
dimensiondimension of the network data
dimLabelslabels of each dimension
blockPropparameters for block proportions (vector or list of vectors)
connectParamlist of parameters for connectivity
covarParamoptional vector of covariates effect
covarListoptional list of covariates data
nodesCovarListoptional list of covariates on nodes (rows and cols),
nodesCovarParamoptional list of vector of node covariates effects on the clustering
SBM$rNetwork()a method to sample a network data for the current SBM (blocks and edges)
SBM$rNetwork(store = FALSE)
storeshould the sampled network be stored (and overwrite the existing data)? Default to FALSE
a list with the sampled block and network
SBM$show()print method
SBM$show(type = "Stochastic Block Model")
typecharacter to tune the displayed name
SBM$print()print method
SBM$print()
SBM$clone()The objects of this class are cloneable with this method.
SBM$clone(deep = FALSE)
deepWhether to make a deep clone.
R6 class for Simple SBM
SBM -> SimpleSBM
dimLabelsa single character giving the label of the nodes
blockPropvector of block proportions (aka prior probabilities of each block)
connectParamparameters associated to the connectivity of the SBM, e.g. matrix of inter/inter block probabilities when model is Bernoulli
probMembershipsmatrix of estimated probabilities for block memberships for all nodes
maskMask for the (potential) NAs in the adjacency matrix
nbBlocksnumber of blocks
nbDyadsnumber of dyads (potential edges in the network)
nbConnectParamnumber of parameter used for the connectivity
nodesCovariatesmatrix of covariates on nodes
nodesCovariatesParamthe matrix of nodes covariates parameters
nbNodesCovariatesnumber of covariates on nodes
membershipsvector of clustering
indMembershipsmatrix for clustering memberships
SimpleSBM$new()constructor for SBM
SimpleSBM$new(
model,
nbNodes,
directed,
blockProp,
connectParam,
dimLabels = c("node"),
covarParam = numeric(length(covarList)),
covarList = list(),
nodesCovarList = list(node = matrix(0, 0, 0)),
nodesCovarParam = list(node = matrix(0, 0, 0))
)
modelcharacter describing the type of model
nbNodesnumber of nodes in the network
directedlogical, directed network or not.
blockPropparameters for block proportions (vector of list of vectors)
connectParamlist of parameters for connectivity with a matrix of means 'mean' and an optional scalar for the variance 'var'. The size of mu must match blockProp length
dimLabelsoptional label for the node (default is "nodeName")
covarParamoptional vector of covariates effect
covarListoptional list of covariates data
nodesCovarListoptional list of one matrix with nodes covariates
nodesCovarParamoptional list of one matrix of parameters of effects of nodes covariates on clustering
SimpleSBM$rMemberships()a method to sample new block memberships for the current SBM
SimpleSBM$rMemberships(store = FALSE)
storeshould the sampled blocks be stored (and overwrite the existing data)? Default to FALSE
the sampled blocks
SimpleSBM$rEdges()a method to sample a network data (edges) for the current SBM
SimpleSBM$rEdges(store = FALSE)
storeshould the sampled edges be stored (and overwrite the existing data)? Default to FALSE
the sampled network
SimpleSBM$predict()prediction under the currently parameters
SimpleSBM$predict(covarList = self$covarList, theta_p0 = 0)
covarLista list of covariates. By default, we use the covariates with which the model was estimated
theta_p0a threshold...
a matrix of expected values for each dyad
SimpleSBM$show()show method
SimpleSBM$show(type = "Simple Stochastic Block Model")
typecharacter used to specify the type of SBM
SimpleSBM$plot()basic matrix plot method for SimpleSBM object or mesoscopic plot
SimpleSBM$plot(
type = c("data", "expected", "graphon", "meso"),
ordered = TRUE,
plotOptions = list()
)
typecharacter for the type of plot: either 'data' (true connection), 'expected' (fitted connection), 'graphon' (block connectivity on the unit square, blocks sized by the block proportions) or 'meso' (mesoscopic view). Default to 'data'.
orderedlogical: should the rows and columns be reordered according to the clustering? Default to TRUE.
plotOptionslist with the parameters for the plot. See help of the corresponding S3 method for details.
a ggplot2 object
SimpleSBM$clone()The objects of this class are cloneable with this method.
SimpleSBM$clone(deep = FALSE)
deepWhether to make a deep clone.
This class is designed to give a representation and adjust an SBM fitted with blockmodels.
The list of parameters estimOptions essentially tunes the optimization process and the variational EM algorithm, with the following parameters
"nbCores integer for number of cores used. Default is 2 (1 under Positron, which does not allow forking)
"verbosity" integer for verbosity (0, 1). Default is 1
"plot" boolean, should the ICL be dynamically plotted or not. Default is TRUE, FALSE when "verbosity" is 0
"exploreFactor" control the exploration of the number of groups
"exploreMin" explore at least until exploreMin even if the exploration factor rule is achieved. Default 4. See the package blockmodels for details.
"exploreMax" Stop exploration at exploreMax even if the exploration factor rule is not achieved. Default Inf. See the package blockmodels for details.
"nbBlocksRange" minimal and maximal number or blocks explored
"fast" logical: should approximation be used for Bernoulli model with covariates. Default to TRUE
SBM -> SimpleSBM -> SimpleSBM_fit
loglikdouble: approximation of the log-likelihood (variational lower bound) reached
ICLdouble: value of the integrated classification log-likelihood
penaltydouble, value of the penalty term in ICL
entropydouble, value of the entropy due to the clustering distribution
storedModelsdata.frame of all models fitted (and stored) during the optimization
SimpleSBM_fit$new()constructor for a Simple SBM fit
SimpleSBM_fit$new( adjacencyMatrix, model, directed, dimLabels = c(node = "nodeName"), covarList = list(), nodesCovarList = list(matrix(nrow = 0, ncol = 0)) )
adjacencyMatrixsquare (weighted) matrix
modelcharacter ('bernoulli', 'poisson', 'gaussian')
directedlogical, directed network or not. In not, adjacencyMatrix must be symmetric.
dimLabelslist of labels of each dimension (in row, in columns)
covarListand optional list of covariates, each of whom must have the same dimension as adjacencyMatrix
nodesCovarListoptional list of one matrix with nodes covariates
SimpleSBM_fit$optimize()function to perform optimization
SimpleSBM_fit$optimize(estimOptions = list())
estimOptionsa list of parameters controlling the inference algorithm and model selection. See details.
SimpleSBM_fit$setModel()method to select a specific model among the ones fitted during the optimization. Fields of the current SBM_fit will be updated accordingly.
SimpleSBM_fit$setModel(index)
indexinteger, the index of the model to be selected (row number in storedModels)
SimpleSBM_fit$reorder()permute group labels by order of decreasing probability
SimpleSBM_fit$reorder()
SimpleSBM_fit$show()show method
SimpleSBM_fit$show(type = "Fit of a Simple Stochastic Block Model")
typecharacter used to specify the type of SBM
SimpleSBM_fit$clone()The objects of this class are cloneable with this method.
SimpleSBM_fit$clone(deep = FALSE)
deepWhether to make a deep clone.
This dataset contains two networks where the nodes are countries and an
edge in network "belligerent" means that the two countries have been at
least once at war between years 1816 to 2007 while an edge in network "alliance"
means that the two countries have had a formal alliance between years 1816 to 2012.
The network belligerent have less nodes since countries which have not been at
war are not considered.
warwar
A list with 2 two igraph objects, alliance and belligerent.
Each graph have three attributes: 'name' (the country name), 'power' (a score related to military power: the higher, the better) and
'trade' (a score related to the trade effort between pairs of countries).
networks were extracted from https://correlatesofwar.org/
Sarkees, Meredith Reid and Frank Wayman (2010). Resort to War: 1816 - 2007. Washington DC: CQ Press.
Gibler, Douglas M. 2009. International military alliances, 1648-2008. CQ Press
data(war) class(war$belligerent) igraph::gorder(war$alliance) igraph::gorder(war$belligerent) igraph::edges(war$alliance) igraph::get.graph.attribute(war$alliance)data(war) class(war$belligerent) igraph::gorder(war$alliance) igraph::gorder(war$belligerent) igraph::edges(war$alliance) igraph::get.graph.attribute(war$alliance)