Package: networkqit
Networkqit: spectral entropies of complex networksAn information theoretic approach inspired by quantum statistical mechanics was recently proposed as a means to optimize network models and to assess their likelihood against synthetic and real-world networks.
Importantly, this method does not rely on specific topological features or network descriptors, but leverages entropy-based measures of network distance.
Entertaining the analogy with thermodynamics,networkqitprovides a computational tool for the estimate of spectral entropy and fitting of model parameters.
These results enable the practical application of this novel and powerful framework to network model inference.DocumentationThe full documentation for this package under development and is currently being written, its current version is available at:https://networkqit.github.io/InstallationTo use thenetworkqitpackage we suggest to usevirtualenv.
Thenetworkqitpackage is pure Python, so it should work on Linux, Mac OSX and Windows.
Here we report instructions for usage in a standard Ubuntu linux installation.How to install on LinuxOpen a terminal, installpipandvirtualenvand clone this repositorysudoapt-getinstallpython3-pip
sudopip3installvirtualenv
virtualenvworkspacecdworkspace
gitclonehttps://github.com/carlonicolini/networkqitYou cloned the repository. Now start the virtualenv session.sourcebin/activateIf you are inside thevirtualenvsession, check that the Python version you are using is the one provided byvirtualenv.whichpython3Now install the networkqit package within thevirtualenvenvironment.cdnetworkqit
python3setup.pysdistNow install the created Python package, that should come with all its dependenciesmatplotlib,numpy,networkx,pandas,numdifftools,bctpycd..
pip3installnetworkqit/dist/networkqit-0.1.tar.gzGetting startedHere we discuss how to usenetworkqit.Computing the spectral entropy of a networkLet us start by studying the spectral entropy of the density matrix of the famous karate club graph.
This example shows how to generate the spectral entropy plots shown in our main paper.importnetworkxasnxG=nx.karate_club_graph()A=nx.to_numpy_array(G)importnetworkqitasnqimportnumpyasnpimportmatplotlib.pyplotaspltplt.style.use('ggplot')beta_range=np.logspace(-3,3,200)Sbeta=nq.batch_compute_vonneumann_entropy(L=nq.graph_Laplacian(A),beta_range=beta_range)plt.semilogx(beta_range,Sbeta)plt.xlabel('$\\beta$')plt.ylabel('$S$')plt.title('Unnormalized spectral entropy')plt.show()The spectral entropy is always in the range[0, log(N)], so if we simply divide bylog Nwhere $N$ is the number
of nodes, we renormalize it in the[0,1]range.Generative network modelsnetworkqitfeatures a large number of network models, mainly those obtained from within the Maximum Entropy
framework. You can create a number of models and call methods on them by a consistent nomenclature:
Here we create an instance of the Undirected Binary Configuration model (UBCM), and sample 10 random networks from this
ensemble, based on the fitness parametersx_icreated at random in the[0,1]domain.importnetworkqitasnqN=10model=nq.UBCM(N=10)xi=np.random.random([N,])adj_graphs=model.sample_adjacency(xi,batch_size=5)print(adj_graphs.shape)The call returns a[5,N,N]numpy array, where the last two dimensions embed with the adjacency matrix of the 5 random graphs.
The methodsample_adjacencyis available for every generative model implemented innetworkqitand is at the base  of themaximize and sampleapproach used for the optimization of the spectral entropy.Classical optimization of spectral entropiesNetworkqit can also work with network model fitting. The utilities to define model optimization are defined in thealgorithmspackage, and here we describe how to run model optimization in the non-sparse limit (the one discussed in the PRE paper).The following lines describe an example of optimization of the expected Laplacian model.
We first create the object ErdosRenyi that describes the expected Laplacian, adjacency and Laplacian gradient with
respect to the only continuous parameters $p$.importnetworkxasnximportnetworkqitasnqimportnumpyasnpG=nx.karate_club_graph()A=nx.to_numpy_array(G)L=nq.graph_Laplacian(A)beta_range=np.logspace(-3,3,20)ermodel=nq.ErdosRenyi(N=len(A))We can call theermodelas if it is a simple function:print(ermodel([0.5]))This returns the expected adjacency matrix, a34x34matrix with0.5off diagonal and0on diagonal.
Theermodelalso allows to call methods like the expected Laplacian or the expected Laplacian gradients:print(ermodel.expected_Laplacian_grad([0.5]))Otherwise we can sample 10 independent networks from the Erdos-Renyi model, with the methodsample_adjacency:print(ermodel.sample_adjacency([0.5]),batch_size=10)Once theermodelobject is defined, we can optimize its parameters in the spectral entropies framework with the help of the classContinuousOptimizer.
We initialize the observed adjacency matrix asAand the initial solutionx0=np.array([0.2]). It is important to definex0as a numpy array.
Finally thebeta_rangeis a numpy array with the range ofbetaover which to optimize the model.solver=nq.ContinuousOptimizer(A=A,x0=np.array([0.2]),beta_range=beta_range)solver.setup(ermodel,ermodel.expected_Laplacian_grad,step_callback=None)sol=solver.run()print(sol)Stochastic optimization of spectral entropyMost of the models do not allow an analytical treatment of their spectral likelihood.
This involves knowing exact analytical formulations of the Laplacian eigenvalues spectral density and this is still an unsolved problem for most of the useful network models.
To perform spectral likelihood optimization we can do stochastic optimization and find the parameters of the empirical graph such that the expected relative entropy averaged over the model ensemble
is minimized.
Doing this innetworkqitis simple, as the library relies on theautogradpackage for the automatic calculation of complicated gradients of stochastic functions.With the optimization methodAdamwhich is borrowed from machine learning, we can optimize the expected relative entropy of the Erdos-Renyi model with respect to our model karate-club network,represented byAand see the effects of changing the inverse temperature parameterbetaon the optimization process.At every iteration, abatch_sizenumber of random networks are sampled from the model, and their average spectral properties are used to compute an approximation to the expected relative entropy.
In this example we see how to optimze a model withN (N-1)free Bernoulli random variables that describe links in a graph.
At each stage in theforloop we replot the result, compared with the original network. We sample at each iteration of Adam a number of 32 independent networks, in order to form a good statistic for the calculation of the Laplacian spectrum.This is the result of this optimization loop. Look how the spectral entropies of the model approximates the one of the empirical network.importmatplotlib.pyplotaspltfromautogradimportnumpyasnpimportnetworkqitasnqfromnetworkqitimportAdamA=nq.ring_of_custom_cliques([24,12,8])N=len(A)M=nq.IsingModel(N=N)L=nq.graph_Laplacian(A)beta=1opt=Adam(G=A,L=L,x0=np.random.random([N*N,]),model=M)rho=nq.compute_vonneuman_density(L=L,beta=beta)forrepinrange(10):sol=opt.run(beta,learning_rate=1E-3,batch_size=32,maxiter=1000)nq.plot_mle(A,M.expected_adjacency(sol['x']))plt.show()Classical maximum likelihood estimationnetworkqitis also featuring a number of Maximum Entropy random graph models, from the soft-configuration model, to the Erdos-Renyi, the Weighted Random graph model and the Enhanced Configuration model.
You can simply fit these models onto empirical data, with a few calls.
For example here we fit the Lagrange multipliers of the Undirected Configuration Model onto an empirical networkAand then sample 100 networks from the optimal values of this model:importnetworkqitasnqA=nq.ring_of_custom_cliques([24,12,8])M=nq.UBCM(N=len(A))# defines the model classsol=M.fit(G=A,ftol=1E-9)M.sample_adjacency(theta=sol['x'],batch_size=100)In this case we don't plot the expected weights, as this model supports only binary networks, but if you prefer, we can fit the Undirected Enhanced Configuration Model:importnetworkqitasnqA=nq.ring_of_custom_cliques([24,12,8])M=nq.UECM3(N=len(A))# defines the model classsol=M.fit(G=A,ftol=1E-9)M.sample_adjacency(theta=sol['x'],batch_size=100)As you can see using the Enhanced Configuration model, both the weights and the link probabilities are correctly fitted in the model, even if this network is unweighted.CitingTo citenetworkqitplease include the following publication in BibTeX format:@article{PhysRevE.98.022322,
  title = {Thermodynamics of network model fitting with spectral entropies},
  author = {Nicolini, Carlo and Vlasov, Vladimir and Bifone, Angelo},
  journal = {Phys. Rev. E},
  volume = {98},
  issue = {2},
  pages = {022322},
  numpages = {10},
  year = {2018},
  month = {Aug},
  publisher = {American Physical Society},
  doi = {10.1103/PhysRevE.98.022322},
  url = {https://link.aps.org/doi/10.1103/PhysRevE.98.022322}
}It is also vailableat this linkTODOI would like to find someone helping in implementing XLA instead of autograd as the basic package for automatic differentiation. Indeed XLA has the possibility to extend calculations on the GPU and (in future) on MultiGPU or TPU systems, effortlessly. It would be possible to scale to much larger problems.