Package 'communityhierarchy'

Title: Joint Inference of Communities and Hierarchy in Directed Networks
Description: Fits a joint Bayesian model of community structure and ranking in directed networks of wins, losses and draws, and measures how much of the ranking the communities explain. The undirected network follows a degree-corrected stochastic block model (Peixoto 2017 <doi:10.1103/PhysRevE.95.012317>), each interaction is decided by the Bradley-Terry model, with draws as in Davidson (1970) <doi:10.1080/01621459.1970.10481082>, and a node's score is its group's score plus an individual deviation. The posterior is sampled by Markov chain Monte Carlo with merge-split moves (Peixoto 2020 <doi:10.1103/PhysRevE.102.012305>) in a C++ core shared with the 'Python' package 'community-hierarchy'.
Authors: Maximilian Jerdee [aut, cre, cph]
Maintainer: Maximilian Jerdee <[email protected]>
License: MIT + file LICENSE
Version: 0.5.0.9000
Built: 2026-12-02 06:15:21 UTC
Source: https://github.com/maxjerdee/community-hierarchy

Help Index


Model configuration

Description

Every argument has a default, so ch_config() is the full coupled model with everything inferred. Arguments left out take the value of the hierarchy_model and interaction presets. For the optional numeric parameters, leaving the argument out means "as the preset says", and NULL means "infer it".

Usage

ch_config(
  groups_model = "traditional_SBM",
  hierarchy_model,
  interaction = "coupled",
  assortative,
  mixing_variation,
  variation_in,
  variation_out,
  degree_correction = TRUE,
  individual_depth,
  group_depth,
  draws_parameter,
  num_groups,
  group_attribute = NULL,
  hierarchy_attribute = NULL,
  weighted_SBM,
  weighted_proposals = FALSE
)

Arguments

groups_model

Community-structure model. "traditional_SBM" (default): the stochastic block model, in which each pair of groups has its own rate of connection. "planted_partition": one rate for edges within groups and one for edges between groups (density_in, density_out). Both are degree-corrected unless degree_correction = FALSE.

hierarchy_model

"bradley_terry" (no draws: draws_parameter is fixed at 0, and a graph with neutral edges is an error) or "bradley_terry_draws" (draws as in Davidson 1970). Left out: "bradley_terry_draws" if the graph has a neutral edge, else "bradley_terry".

interaction

"coupled" (default): a score is its group's score plus an individual deviation, and group_depth is inferred. "independent": group_depth is fixed at 0, so the scores do not depend on the groups.

assortative, mixing_variation, variation_in, variation_out

Experimental; leave out.

degree_correction

TRUE (default): degree correction, with a uniform prior over each group's degree sequence. FALSE: none.

individual_depth

Fixed spread of the individual scores about their group's score (sigma_I, > 0); NULL or left out infers it.

group_depth

Fixed spread of the group scores (sigma_G, >= 0); NULL or left out infers it (it is fixed at 0 by interaction = "independent").

draws_parameter

Fixed draw propensity nu (>= 0); NULL or left out infers it (it is fixed at 0 by hierarchy_model = "bradley_terry").

num_groups

Fixed number of groups; NULL or left out infers it.

group_attribute

Name of a node attribute holding known groups. The partition is then fixed and only the hierarchy is inferred.

hierarchy_attribute

Name of a numeric node attribute holding known scores, which are then fixed.

weighted_SBM

TRUE: edge weights are real-valued strengths rather than counts. The binary network follows the SBM, the weights between two groups are uniform on the simplex of their total (Peixoto 2018), and the totals of the group pairs joined by an edge are uniform on the simplex of the overall weight. Left out: TRUE if an edge of the network that drives the communities (group_graph if given, else G) has a weight other than 1.

weighted_proposals

weighted_SBM only: TRUE makes the block-informed partition proposals follow the weights rather than the binary edge counts (experimental). The posterior is the same either way.

Value

An object of class ch_config.

See Also

ch_fit()

Examples

ch_config()
ch_config(interaction = "independent")
ch_config(degree_correction = FALSE)

Fit the community and hierarchy model

Description

Samples the posterior of the joint model of communities and ranking for a directed network by Markov chain Monte Carlo.

Usage

ch_fit(
  G,
  config = ch_config(),
  vertices = NULL,
  group_graph = NULL,
  source_high_rank = TRUE,
  num_chains = 4,
  num_samples = 1000,
  num_warmup = 500,
  sweeps_per_sample = 10,
  num_param_warmup = 0,
  beta = 1,
  num_tempering_chains = 1,
  merge_split_enabled = TRUE,
  initial_partition = NULL,
  initial_scores = NULL,
  initial_individual_depth = NULL,
  initial_group_depth = NULL,
  num_groups_fixed = FALSE,
  seed = NULL,
  timeout = NULL,
  show_progress = interactive()
)

Arguments

G

The interactions: a directed igraph graph, or a data frame of edges whose first two columns are the endpoints (as for igraph::graph_from_data_frame()).

  • Each edge is one interaction, or weight interactions; parallel edges are summed. With weighted_SBM = FALSE, a weight must be a positive whole number.

  • An edge with type = "neutral" is a draw (a tie, or a reciprocated nomination), and its direction is ignored. Any other edge is a decided interaction, read according to source_high_rank. If edges have a type, every edge must be "dominant" or "neutral".

  • Self-loops are not allowed.

  • The order of the vertices is the order of every per-node result.

config

The model, from ch_config().

vertices

With a data frame G: an optional data frame of vertices whose first column is the vertex name (it carries node attributes such as group_attribute, and adds isolated nodes).

group_graph

Two-layer mode: an undirected graph on the same vertex names (an igraph graph or an edge data frame) whose edges drive the communities, while G drives only the scores. Its weights must be finite and positive.

source_high_rank

How to read a decided edge u -> v. TRUE (default): the source wins (a sports result, a dominance interaction). FALSE: the target wins (a citation of v by u, a friendship nomination of v by u). Either way, higher scores mean higher rank.

num_chains, num_samples, num_warmup

The run, named as in PyStan. One iteration is sweeps_per_sample sweeps. Each of num_chains independent chains (run in parallel threads; default 4, so that they can be compared to check convergence) runs num_warmup warm-up iterations, during which the proposal step sizes adapt, then num_samples sampling iterations, recording the state after each one.

sweeps_per_sample

Sweeps (one proposal per node each) per iteration.

num_param_warmup

Iterations before warm-up with the partition and scores frozen, so that the continuous parameters settle first.

beta

Inverse temperature of the likelihood (0 = prior, 1 = posterior).

num_tempering_chains

Parallel-tempering replicas per chain; only the beta replica is recorded.

merge_split_enabled

Merge-split moves for the partition (Peixoto 2020). Without them, single-node moves can converge to a wrong answer without any sign of it within a chain.

initial_partition

Starting groups, one label per node (any labels). Default: greedy modularity on the undirected network, with groups smaller than 5\ by the C++ core, as in the 'Python' package).

initial_scores

Starting scores, one per node. Default: (wins - losses) / (wins + losses + draws) over distinct opponents.

initial_individual_depth, initial_group_depth

Starting values of the inferred sigma_I (> 0) and sigma_G (>= 0).

num_groups_fixed

Hold the number of groups at that of initial_partition.

seed

Random seed in [0, 2^30); chain c uses seed + c. Default: drawn from R's random number generator, so set.seed() makes a fit repeatable. With the same seed, a fit is identical on every platform and to the 'Python' package's (version 0.6.0 or later; earlier versions made their default start in 'Python').

timeout

Wall-clock limit in seconds, or NULL (default) for no limit. When it expires, the fit stops and returns the samples recorded so far, with a warning. Interrupting (Esc or Ctrl-C) stops a fit at any time.

show_progress

Print progress to the console.

Value

An object of class ch_fit. See network_properties(), node_properties(), consensus_partition(), direction_probabilities() and samples().

Examples

# Four players: a beats b and c, b beats c, c and d draw twice.
games <- data.frame(winner = c("a", "a", "b", "c"), loser = c("b", "c", "c", "d"),
                    type = c("dominant", "dominant", "dominant", "neutral"),
                    weight = c(1, 1, 1, 2))
fit <- ch_fit(games, num_chains = 1, num_samples = 50, num_warmup = 20,
              seed = 1, show_progress = FALSE)
network_properties(fit)
node_properties(fit)

Co-membership matrix

Description

Co-membership matrix

Usage

coincidence_matrix(fit)

Arguments

fit

A fit from ch_fit().

Value

An n x n matrix, with rows and columns named by node: the fraction of samples in which two nodes are in the same group.


Point estimate of the partition

Description

Point estimate of the partition

Usage

consensus_partition(
  fit,
  method = c("moc", "moc_modal_k", "binder"),
  refine = TRUE,
  min_samples = 1000
)

Arguments

fit

A fit from ch_fit().

method
  • "moc" (default): the maximum-overlap consensus (Peixoto 2021), the partition, with any number of groups, that agrees with the most node labels across the samples after each sample is optimally relabelled.

    • "moc_modal_k": the same, with the number of groups held at its posterior mode.

    • "binder": the sample, among those with the modal number of groups, whose co-membership is closest to the posterior co-membership matrix (Binder loss), then refined node by node. Its cost grows with the square of the number of nodes.

refine

"binder" only: FALSE returns the best sample unrefined.

min_samples

The samples are thinned, evenly spaced, to the larger of min_samples and the effective sample size of the description length (partition_ess()); 0 turns thinning off.

Value

An integer vector of groups, named by node, numbered from 1 with the group with the lowest mean score first.


MCMC convergence diagnostics

Description

The rank-normalised effective sample sizes and R-hat of Vehtari et al. (2021), as ArviZ's ess(method = "bulk"), ess(method = "tail") and rhat() and the posterior package's ess_bulk(), ess_tail() and rhat(), computed in the C++ core and shared with the Python package.

Usage

diagnostics(fit, scores = FALSE)

Arguments

fit

A fit from ch_fit().

scores

FALSE (default): the network-level parameters. "absolute" or "relative": each node's score, or each score minus the mean score of its sample. The overall level of the scores is pinned only by their prior and wanders slowly; the differences, which every prediction uses, mix faster.

Value

A data frame with columns ess_bulk, ess_tail and rhat, and quantity (the rows of network_properties(), then H_A_b, the description length of the partition, as in partition_ess()) or node. Chains are truncated to the shortest; R-hat needs two chains (NaN otherwise), and a fixed parameter has NaN R-hat.


Leave-one-out cross-validation of the edge directions

Description

Each edge of G in turn has its outcome left out (who won, or that it was a draw); the edge itself stays in the network. The scores and the draw parameter make the outcomes independent, so the leave-one-out posterior is the posterior reweighted by 1 / p(outcome), with the weights Pareto-smoothed (PSIS-LOO, Vehtari, Gelman and Gabry 2017) as in the loo package and ArviZ. The computation is the C++ core's, shared with the Python package.

Usage

direction_loo(fit, r_eff = 1)

Arguments

fit

A fit from ch_fit().

r_eff

Relative efficiency of the samples, which sets the length of the smoothed tail. 1 (default) treats the samples as independent.

Details

An edge of weight w counts w times and is left out whole: give one edge per interaction (a multigraph) for leave-one-interaction-out.

Value

A data frame with one row per edge of G, in edge order:

  • winner, loser: the edge's ends, the winner first (for a draw, as in G);

  • draw, weight;

  • elpd: the leave-one-out log predictive density of the outcome (sum(elpd) is the model's total);

  • pareto_k: above 0.7 that edge's estimate is unreliable;

  • p_win: decided edges, the leave-one-out probability that the winner beats the loser given that the interaction is decided (plain Bradley-Terry); NA for draws.

Two models fitted to the same graph compare edge by edge: the difference of the elpd sums, with standard error sqrt(n) * sd(elpd1 - elpd2).


Predicted outcome of an interaction

Description

The posterior predictive probabilities of the outcome of a new interaction between two nodes, averaged over the samples.

Usage

direction_probabilities(fit, a, b, draws_allowed = TRUE)

Arguments

fit

A fit from ch_fit().

a, b

Two nodes, as named in G.

draws_allowed

TRUE (default): include a draw, with the sampled draws_parameter. FALSE: plain Bradley-Terry, given that the interaction is decided.

Value

A vector named by outcome: a, the probability that a beats b; draw, a draw (only with draws_allowed = TRUE); b, that b beats a. For example c(Spain = 0.62, draw = 0.24, Morocco = 0.14). The values sum to 1. "Beats" is the win of the model, so with source_high_rank = FALSE (for example citations) the a entry is the probability of an edge from b to a.


The sample with the shortest description length

Description

The description length of a sample is H_A_b + H_Adir_G_A_s_nu + H_s_G_b_depths (see samples()): minus the log joint probability of the network, the partition and the scores, given the continuous parameters. It is a by-product of sampling, not a posterior summary.

Usage

mdl_partition(fit)

Arguments

fit

A fit from ch_fit().

Value

A list with value (in nats) and partition (an integer vector named by node, numbered as in consensus_partition()).


Network-level posterior summaries

Description

Network-level posterior summaries

Usage

network_properties(fit, prob = 0.9)

Arguments

fit

A fit from ch_fit().

prob

Probability mass of the highest-density interval, in (0, 1).

Value

A data frame with columns parameter, mean, std, hdi_lo and hdi_hi, one row for each of, in order, num_groups, sigma_T = sqrt(sigma_G^2 + sigma_I^2), alignment = sigma_G^2 / sigma_T^2 (the share of the variance in scores that the groups explain), individual_depth (sigma_I), group_depth (sigma_G), draws_parameter (nu), density_in, density_out, variation_in, variation_out and degree_correction. The interval is the shortest one holding floor(prob * n_samples) samples.


Node-level posterior summaries

Description

Node-level posterior summaries

Usage

node_properties(
  fit,
  partition = c("consensus", "mdl"),
  consensus_method = c("moc", "moc_modal_k", "binder"),
  sort = TRUE
)

Arguments

fit

A fit from ch_fit().

partition

"consensus" (default) for the groups of consensus_partition(), or "mdl" for those of the sample with the shortest description length.

consensus_method

Passed to consensus_partition().

sort

TRUE (default): rows sorted by score_mean, highest first. FALSE: rows in the order of the vertices of G.

Value

A data frame with one row per node (see sort): node, score_mean, score_std, group (numbered from 1, the group with the lowest mean score first) and group_score_mean (the mean of score_mean over the node's group).


Effective sample size of the partition

Description

The rank-normalised split-chain bulk effective sample size (Vehtari et al. 2021) of the description length H_A_b, pooled over chains.

Usage

partition_ess(fit)

Arguments

fit

A fit from ch_fit().

Value

A number.


The recorded samples

Description

The recorded samples

Usage

samples(fit, what = c("parameters", "scores", "groups"))

Arguments

fit

A fit from ch_fit().

what

"parameters" (default): a data frame with one row per sample and the columns

  • chain_id (from 1) and beta, the inverse temperature of the replica;

  • the parameters num_groups, the derived sigma_T and alignment, individual_depth, group_depth, draws_parameter, density_in, density_out, variation_in, variation_out and degree_correction;

  • the description-length terms in nats: H_b (partition prior), H_M, H_k, H_A_G_k_M_b, H_W (weighted_SBM only, else 0), H_A_G_b (undirected network given the partition), H_A_b = H_A_G_b + H_b, H_Adir_G_A_s_nu (edge directions given the scores) and H_s_G_b_depths (scores given the partition).

"scores" or "groups": a samples x nodes matrix of scores or of group labels (the sampler's own labels, from 1, not aligned across samples).

Value

A data frame or a matrix.