Code for "Reconstruction of plant--pollinator networks from observational data", implemented in Stan, with an emphasis on the pystan
interface.
Pull requests with code for other Stan interfaces are more than welcomed!
The only necessary dependency is stan
.
Our model will of course work with any stan interface, but we provide a number of utilities geared toward its use with pystan
, the main python interface.
We provide support for pystan2 and pystan3, which differ significantly.
To install pystan, simply run:
pip install pystan
Our model takes a matrix of observations M
as input (matrix of non-negative integers, whose entries are number of observed interactions for each pair of plants and pollinators), and outputs a tensor Q
where Q[k,i,j]
, is the probability that the pair (i,j) is connected in sample k
of the posterior distribution. A connection probability for pair (i,j) can be obtained by averaging over all samples. The program also generates samples for non-network quantities such as connectance, species abundances and the strength of the pollination preference.
For those familiar with pystan
, running the model is as simple as:
import pystan
import numpy as np
# Compile the model
model = pystan.StanModel(`model.stan`, model_name="plant_pol")
# Load data matrix
M = np.loadtxt('example_matrix.txt')
# Generate samples
samples = model.sampling(data={'M': M, 'n_p': M.shape[0], 'n_a': M.shape[1]})
# Calculate estimates
print("Connection probability for all pairs:", np.mean(samples['Q'], axis=0)
print("Average posterior connectance:", np.mean(samples['rho'], axis=0)))
In this snippet, n_p
and n_a
are the dimension of the observation matrix M
.
The observation matrix M
is thus a n_p * n_a
numpy array of integers.
For those unfamiliar with Stan, we have written a short tutorial, as well as two python modules that abstract away most of the complexity associated with manipulating samples.
If you use this code, please consider citing:
"Reconstruction of plant–pollinator networks from observational data"
J.-G. Young, F. S. Valdovinos and M.E.J. Newman
Nature Communications 12, 3911 (2021)
Code by Jean-Gabriel Young with pystan3 adaptation by S. Dritz [email protected]. Don't hesitate to get in touch at [email protected] for more information, or via the issues!