blvim and the potential view

news
code
R
blvim
Boltzmann–Lotka–Volterra Interaction Model
The development version of blvim maximises a potential: faster equilibria, a meaningful convergence test and a way to compare equilibria
Published

December 5, 2026

Since the first release of blvim on the CRAN, I have been working on its next version, blvim 0.2.0, which is now available in its development version on GitHub. Most of its new features come from a single idea, taken from a recent paper by Osawa, Akamatsu and Kogure: the Boltzmann–Lotka–Volterra (BLV) model, which is defined by a dynamics, can also be seen as the maximisation of a potential. This post explains why this change of point of view is so useful in practice, with a few examples. The development version can be installed from R-universe

install.packages("blvim", repos = "https://fabrice-rossi.r-universe.dev")

or directly from GitHub

remotes::install_github("fabrice-rossi/blvim")

and then loaded as usual (together with ggplot2 for the figures).

library(blvim)
library(ggplot2)

From a dynamics to a landscape

I refer the reader to a previous post for a description of the model. In a nutshell, origin locations \(i\) produce flows \(X_i\) that are shared between destination locations \(j\) according to their attractivenesses \(Z_j\) and to the costs \(c_{ij}\) between locations. The destination \(j\) receives a total flow \(D_j(\mathbf{Z})\) and the BLV model looks for equilibria, that is attractivenesses that match exactly the flows they attract: \(D_j(\mathbf{Z}) = \kappa_j Z_j\) for all \(j\) (the \(\kappa_j\) are conversion factors between attractivenesses and flows, often all equal to 1). In Wilson’s formulation, the equilibria are the fixed points of a dynamical system, in which the attractiveness of a destination grows when it receives more flow than it supports and shrinks otherwise. blvim 0.1.1 computed them by iterating this dynamics until it stopped moving.

Osawa et al. noticed that this dynamics derives from a potential. Using the notations of the package, the potential is \[ f(\mathbf{Z})=\frac{1}{\alpha}\sum_{i=1}^n X_i \log\left(\sum_{j=1}^p Z_j^{\alpha}\exp(-\beta c_{ij})\right)-\sum_{j=1}^p\kappa_jZ_j, \] and its partial derivatives are \[ \frac{\partial f}{\partial Z_j}(\mathbf{Z}) = \frac{D_j(\mathbf{Z}) - \kappa_j Z_j}{Z_j}. \] The gradient of the potential is (up to a positive rescaling) the imbalance between the flows and the attractivenesses. Thus the equilibria of the model are the critical points of the potential (with a little care for the destinations whose attractiveness vanishes) and the BLV updates are gradient steps on \(f\). Moreover, the stable equilibria of the dynamics are the strict local maxima of the potential on the set of admissible attractivenesses (the weighted simplex \(\sum_j\kappa_jZ_j=\sum_iX_i\), \(Z_j\geq 0\)).

In other words, the potential turns the set of possible configurations of the model into a landscape, and its stable equilibria into the peaks of this landscape. Let us illustrate this on a toy model: 121 origins on a regular \(11\times 11\) grid, each producing a unit flow, and three destinations A, B and C, with Euclidean distances as costs.

origins <- expand.grid(x = 0:10, y = 0:10)
destinations <- data.frame(name = c("A", "B", "C"), x = c(2, 8, 4), y = c(2, 3, 8))
costs <- sqrt(outer(origins$x, destinations$x, "-")^2 +
  outer(origins$y, destinations$y, "-")^2)
X <- rep(1, nrow(origins))

We compute equilibria for \(\alpha=1.5\) and three values of the inverse cost scale \(\beta\). Each model is computed from 21 starting points spread regularly over the admissible configurations (one per row of starts), and blvim() keeps all the runs. For this illustration, we use a much shorter step than the default one (rho_init, see below), so that the iterations of the algorithm follow the landscape closely.

alpha <- 1.5
betas <- c(0.3, 0.7, 1)
k <- 8
starts <- subset(expand.grid(a = 1:k, b = 1:k), a + b < k)
starts <- cbind(starts$a, starts$b, k - starts$a - starts$b) / k * sum(X)
short_steps <- blvim_gradient_control(rho_init = 0.001)
models <- lapply(betas, \(beta) {
  blvim(costs, X, alpha, beta, starts, keep_runs = TRUE, control = short_steps)
})

The figure below shows the best equilibrium found for each value of \(\beta\), that is the one with the largest potential. The area of the disks is proportional to the attractiveness of the destinations (a cross marks a destination that has vanished) and each origin has the colour of the destination that receives most of its flow.

Code of the figure
beta_label <- \(beta) sprintf("beta == %s", beta)
origin_data <- do.call(rbind, lapply(seq_along(betas), \(k) {
  data.frame(origins,
    destination = destinations$name[max.col(flows(models[[k]]))],
    label = beta_label(betas[k])
  )
}))
destination_data <- do.call(rbind, lapply(seq_along(betas), \(k) {
  data.frame(destinations,
    share = attractiveness(models[[k]]) / sum(X),
    label = beta_label(betas[k])
  )
}))
ggplot(origin_data, aes(x, y)) +
  geom_point(aes(colour = destination), size = 1, alpha = 0.7) +
  geom_point(data = destination_data, aes(size = share, colour = name)) +
  geom_point(
    data = subset(destination_data, share == 0), aes(colour = name),
    shape = 4, size = 3, stroke = 1
  ) +
  geom_text(
    data = destination_data, aes(label = name),
    nudge_x = 0.6, nudge_y = 0.6, fontface = "bold"
  ) +
  facet_wrap(~label, labeller = label_parsed) +
  scale_size_area(max_size = 8, limits = c(0, 1), guide = "none") +
  guides(colour = "none") +
  coord_equal() +
  theme(
    axis.text = element_blank(), axis.title = element_blank(),
    panel.grid.major = element_blank()
  )

Three maps of the grid of origins and of the three destinations, for beta = 0.3, 0.7 and 1. For beta = 0.3, only destination C remains and receives the flows of all the origins. For beta = 0.7 and 1, the three destinations remain and share the grid in three market areas.

Three maps of the grid of origins and of the three destinations, for beta = 0.3, 0.7 and 1. For beta = 0.3, only destination C remains and receives the flows of all the origins. For beta = 0.7 and 1, the three destinations remain and share the grid in three market areas.

With a large cost scale (\(\beta=0.3\)), the most central destination, C, attracts all the flows. With smaller cost scales, the three destinations share the grid, each with its own market area.

With three destinations, the admissible configurations (the attractivenesses rescaled to sum to one) form a triangle: on a vertex, a single destination receives all the flows; on an edge, one destination has vanished. The landscape can then be drawn on this triangle, as in the figure below, which shows the potential (relative to the best equilibrium) and the paths followed by the algorithm from the 21 starting points to the equilibria they lead to (the circled dots).

Code of the figure
## barycentric coordinates to the plane
to_xy <- \(U) data.frame(x = U[, 2] + U[, 3] / 2, y = U[, 3] * sqrt(3) / 2)
normalise <- \(Z) Z / sum(Z)
## the potential, computed directly from its definition
potential <- function(U, beta) {
  Z <- sum(X) * U
  sum(X * log(exp(-beta * costs) %*% Z^alpha)) / alpha - sum(Z)
}
grid <- expand.grid(
  x = seq(0, 1, by = 0.004),
  y = seq(0, sqrt(3) / 2, by = 0.004)
)
grid$U3 <- 2 * grid$y / sqrt(3)
grid$U2 <- grid$x - grid$U3 / 2
grid$U1 <- 1 - grid$U2 - grid$U3
grid <- subset(grid, U1 >= 0 & U2 >= 0 & U3 >= 0)
landscapes <- do.call(rbind, lapply(seq_along(betas), \(k) {
  values <- apply(grid[, c("U1", "U2", "U3")], 1, potential, beta = betas[k])
  data.frame(grid[, c("x", "y")],
    relative = values - sim_potential(models[[k]]),
    label = beta_label(betas[k])
  )
}))
## the path of a run: the algorithm is deterministic, so that its t-th iterate
## is the result of a run from the same starting point stopped after t
## iterations
path <- function(start, beta) {
  n <- sim_iterations(blvim(costs, X, alpha, beta, start, control = short_steps))
  iterates <- sapply(seq_len(n), \(t) {
    attractiveness(suppressWarnings(blvim(costs, X, alpha, beta, start,
      iter_max = t, control = short_steps
    )))
  })
  to_xy(t(cbind(start, iterates)) / sum(X))
}
paths <- do.call(rbind, lapply(seq_along(betas), \(k) {
  do.call(rbind, lapply(seq_len(nrow(starts)), \(run) {
    data.frame(path(starts[run, ], betas[k]),
      run = run, label = beta_label(betas[k])
    )
  }))
}))
starting_points <- paths[!duplicated(paths[, c("run", "label")]), ]
equilibria <- do.call(rbind, lapply(seq_along(betas), \(k) {
  runs <- sim_runs(models[[k]], unique = TRUE)
  data.frame(to_xy(t(sapply(runs, \(run) normalise(attractiveness(run))))),
    label = beta_label(betas[k])
  )
}))
vertices <- data.frame(to_xy(diag(3)),
  name = destinations$name,
  hjust = c(1.2, -0.2, 0.5), vjust = c(1.3, 1.3, -0.4)
)
## the figure, for some values of beta
landscape_plot <- function(shown = betas) {
  keep <- \(data) data[data$label %in% beta_label(shown), ]
  ggplot(keep(landscapes), aes(x, y)) +
    geom_raster(aes(fill = pmax(relative, -20))) +
    geom_contour(aes(z = relative, colour = from_theme(paper)),
      breaks = seq(-20, 0, by = 2), linewidth = 0.25, alpha = 0.7
    ) +
    ## paths over a halo of the background colour
    geom_path(
      data = keep(paths), aes(group = run, colour = from_theme(paper)),
      linewidth = 1
    ) +
    geom_point(
      data = keep(starting_points), aes(colour = from_theme(paper)),
      size = 1.6
    ) +
    geom_path(data = keep(paths), aes(group = run), linewidth = 0.35) +
    geom_point(data = keep(starting_points), size = 0.6) +
    geom_point(
      data = keep(equilibria), aes(fill = from_theme(paper)),
      shape = 21, size = 2.2, stroke = 0.8
    ) +
    geom_text(
      data = vertices,
      aes(label = name, colour = name, hjust = hjust, vjust = vjust),
      fontface = "bold"
    ) +
    facet_wrap(~label, labeller = label_parsed) +
    labs(fill = "potential\n(relative to\nthe best)") +
    guides(colour = "none") +
    coord_equal(clip = "off") +
    theme(
      axis.text = element_blank(), axis.title = element_blank(),
      panel.grid.major = element_blank(), panel.spacing = unit(1.5, "lines")
    )
}
landscape_plot()

Three triangles coloured by the value of the potential, for beta = 0.3, 0.7 and 1, with the paths of the algorithm from starting points to equilibria. For beta = 0.3, the paths reach an edge and then follow it to one of the three vertices, most of them to C. For beta = 0.7 and 1, all the paths end at a single interior peak.

Three triangles coloured by the value of the potential, for beta = 0.3, 0.7 and 1, with the paths of the algorithm from starting points to equilibria. For beta = 0.3, the paths reach an edge and then follow it to one of the three vertices, most of them to C. For beta = 0.7 and 1, all the paths end at a single interior peak.

The landscape explains the equilibria. With \(\beta=0.3\), it has three peaks, at the vertices: each destination can attract all the flows, but C has the highest peak and the largest basin. The paths first reach an edge, where a destination has vanished, and then follow it to a vertex. With \(\beta=0.7\) and \(\beta=1\), all the paths lead to a single interior peak, where the three destinations coexist. The landscape has more peaks than the figure shows, though: for \(\alpha>1\), a destination that has vanished receives no flow and cannot come back, so each vertex is a local maximum of the potential, as well as each peak of the model restricted to two destinations (for instance on the edge between B and C, for \(\beta=0.7\) and \(\beta=1\)). Their basins of attraction can be tiny.

The short steps used here have a cost: the algorithm needs up to about 100 iterations to converge. With its default step, it converges in at most 14 iterations from the same starting points, but its first steps are long: a step can cross a basin and reach an edge or a vertex, from which a vanished destination never comes back. For \(\beta=0.7\), a few starting points then lead to the edge between B and C or to the vertex C instead of the interior peak. This is one of the reasons why blvim() supports multiple starting points and compares the equilibria they lead to with the potential (see benefit 3 below). All the new features presented below rely on this landscape view.

Benefit 1: faster equilibria

Once the equilibria are seen as the peaks of a landscape, one can climb the landscape with the tools of numerical optimisation rather than by following the dynamics. The new default algorithm of blvim() is a projected gradient ascent: it takes steps in the direction of the gradient of the potential, projects the result back on the admissible set and adapts the length of the steps with a line search. We use the first 15 French cities of the french_cities data set, with unit productions and in a non-bipartite setting (each city is both an origin and a destination), to compare it to the historical BLV updates (algorithm = "linear").

distances <- french_cities_distances[1:15, 1:15] / 1000 ## convert to km
cities <- french_cities$name[1:15]
dimnames(distances) <- list(cities, cities)
production <- rep(1, 15)
start <- rep(1, 15)
gradient_model <- blvim(distances, production, 1.5, 1 / 50, start,
  bipartite = FALSE
)
linear_model <- blvim(distances, production, 1.5, 1 / 50, start,
  bipartite = FALSE, algorithm = "linear",
  control = blvim_gradient_control(history = TRUE)
)
data.frame(
  iterations = c(sim_iterations(gradient_model), sim_iterations(linear_model)),
  potential = c(sim_potential(gradient_model), sim_potential(linear_model)),
  row.names = c("gradient", "linear")
)
         iterations potential
gradient         37 -13.42567
linear         7588 -13.42568

Both algorithms reach the same equilibrium, but the gradient ascent needs 200 times fewer iterations. Moreover, the projection sets the attractivenesses of vanishing destinations exactly to zero, while the BLV updates only make them tend to zero:

rbind(
  gradient = attractiveness(gradient_model),
  linear = attractiveness(linear_model)
)[, c("Lyon", "Toulon")]
                 Lyon       Toulon
gradient 0.000000e+00 0.000000e+00
linear   1.855271e-06 1.452501e-09

Benefit 2: knowing when to stop

An iterative algorithm needs a stopping criterion. blvim 0.1.1 stopped the BLV updates when the attractivenesses barely changed from one iteration to the next. The potential provides a much better criterion, the duality gap, which vanishes exactly at equilibria. It also has a direct interpretation: divided by the total production, it is the largest relative excess of the flow received by a destination over its attractiveness, \(\max_j D_j/(\kappa_jZ_j)-1\). It is now used by all the algorithms of blvim() and reported by sim_diagnostic().

sim_diagnostic(gradient_model)
BLV model obtained with the "gradient" algorithm.
ℹ The algorithm converged after 37 iterations:
• Number of potential evaluations: 52.
• Duality gap: 1.42519e-05.
• Return status: "converged".

The history of the iterations, recorded with blvim_gradient_control(history = TRUE), shows why this matters.

autoplot(sim_history(linear_model), c("gap", "n_active"))

Two panels showing, as functions of the iteration, the duality gap and the number of active destinations of the linear BLV update. The gap first drops, then increases slowly for about 6000 iterations, and finally decreases geometrically. The number of active destinations stays at 15 until about iteration 6400, then drops to 14 and to 13 around iteration 7100.

Two panels showing, as functions of the iteration, the duality gap and the number of active destinations of the linear BLV update. The gap first drops, then increases slowly for about 6000 iterations, and finally decreases geometrically. The number of active destinations stays at 15 until about iteration 6400, then drops to 14 and to 13 around iteration 7100.

During the first 6000 iterations of the BLV updates, two destinations are slowly vanishing: the attractivenesses barely change, but the gap increases, as the configuration moves away from an equilibrium. A criterion based on the size of the steps would have stopped there, far from the equilibrium. The gap decreases only once the two destinations have (almost) vanished.

Benefit 3: comparing equilibria

The potential of the BLV model has in general several local maxima: the equilibrium found by blvim() depends on its starting point. Before the potential view, there was no principled way to choose between equilibria found from different starting points. Now there is one: Osawa et al. show, building on stochastic stability results from evolutionary game theory, that the global maximum of the potential is the most likely configuration when the dynamics is subject to small random perturbations.

blvim() can thus be run from several starting points, specified with blvim_initialise(), and keeps the configuration with the largest potential. sim_logs() summarises all the runs.

set.seed(1)
model <- blvim(distances, production, 1.5, 1 / 50, blvim_initialise(n = 20),
  bipartite = FALSE, keep_runs = TRUE
)
summary(sim_logs(model))

── Summary of 20 runs of blvim ──

• 20 of 20 runs converged.
• Status: converged (20).
• Iterations: median 22, range [16, 68].
• Evaluations: median 34, range [25, 91].
• Largest duality gap of the converged runs: 1.574e-05.

── Final configurations 
16 distinct configurations. The best one (potential -13.42567, 13 active
destinations) was reached by 3 of 20 runs.
The second best potential is -13.42744 (difference 0.001761).
 configuration potential n_active runs share converged
             1  -13.4257       13    3  0.15         3
             2  -13.4274       13    1  0.05         1
             3  -13.4328       13    2  0.10         2
             4  -13.4334       13    1  0.05         1
             5  -13.6183       12    1  0.05         1
... and 11 more.

The 20 runs lead to 16 distinct equilibria. The four best ones have very close potentials, and a look at their attractivenesses explains why:

best <- sim_runs(model, unique = TRUE)[1:4]
t(sapply(best, \(run) attractiveness(run)[c("Marseille", "Toulon", "Lyon", "Saint-Étienne")]))
     Marseille   Toulon     Lyon Saint-Étienne
[1,]  2.088902 0.000000 0.000000      1.995601
[2,]  0.000000 2.113441 0.000000      2.003013
[3,]  2.086246 0.000000 2.001500      0.000000
[4,]  0.000000 2.110818 2.008751      0.000000

In each pair of close cities, Marseille and Toulon on the one hand, Lyon and Saint-Étienne on the other hand, one city absorbs the other, and the four best equilibria are the four possible combinations. They are easy to compare on a map with grid_autoplot() and sim_df_runs(), which collects the distinct equilibria and their summaries, including their potential, in a sim_df.

destination_positions(model) <-
  as.matrix(french_cities[1:15, c("th_longitude", "th_latitude")])
configurations <- sim_df_runs(model, unique = TRUE)[1:4, ]
grid_autoplot(configurations,
  paste0("#", configuration, ": ", round(potential, 4)),
  with_positions = TRUE
) +
  geom_text(
    data = data.frame(
      french_cities[c(2, 12, 3, 14), c("name", "th_longitude", "th_latitude")],
      hjust = c(1.1, -0.1, -0.1, 1.1)
    ),
    aes(th_longitude, th_latitude, label = name, hjust = hjust),
    size = 3, inherit.aes = FALSE
  ) +
  coord_sf(crs = "epsg:4326") +
  scale_linewidth_continuous(range = c(0, 1.5)) +
  labs(x = NULL, y = NULL)

Four maps of the 15 French cities, one per equilibrium, labelled by their rank and potential, showing the flows between the cities. The flows between Marseille and Toulon and between Lyon and Saint-Étienne change direction from one map to another.

Four maps of the 15 French cities, one per equilibrium, labelled by their rank and potential, showing the flows between the cities. The flows between Marseille and Toulon and between Lyon and Saint-Étienne change direction from one map to another.

The potential tells us that the most likely configuration is the one where Marseille and Saint-Étienne survive, but the differences are tiny: an analysis based on a single run could have reported any of these four configurations. The multiple starts and the potential make this kind of ambiguity visible.

Benefit 4: stability for free

Finally, the potential view gives a simple characterisation of the stability of an equilibrium: an equilibrium with no vanished destination is a (linearly) stable fixed point of the BLV dynamics if and only if it is a strict local maximum of the potential. An equilibrium where some destinations have vanished is handled by removing them from the model. In practice, sim_residual_jacobian() computes the Jacobian of the residual map \(D_j(\mathbf{Z})-\kappa_jZ_j\), whose eigenvalues, restricted to the active destinations, are real and negative at a strict local maximum.

active <- attractiveness(model) > 0
jacobian <- sim_residual_jacobian(model)[active, active]
eigen(jacobian, only.values = TRUE)$values
 [1] -1.0000000 -0.9991713 -0.9966107 -0.9890369 -0.9864179 -0.9767000
 [7] -0.9399668 -0.9202801 -0.8480084 -0.7984520 -0.6395746 -0.6300408
[13] -0.4346903

The best equilibrium is a strict local maximum, and therefore a stable configuration of the dynamics.

And more

The new version comes with many other changes, all listed in the NEWS. Note in particular that the change of the default algorithm of blvim() and grid_blvim() is a breaking change: as the potential has several local maxima, the new default can reach a different equilibrium than blvim 0.1.1 from the same starting point (the BLV updates remain available with algorithm = "linear" and algorithm = "quadratic"). The theory behind the potential and the gradient ascent is detailed in a new vignette, Potential Maximisation and Gradient Ascent, while the new tutorial walks through a complete analysis of the retail centres of Île-de-France.