Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Generating a weighted and directed network form adjacency matrix in Julia

I want to generate a weighted and directed network from an adjacency matrix in Julia (v0.7).

So far I've tried:

using LightGraphs
using SimpleWeightedGraphs

A = rand(100, 100)
G = Graph(A)

but I get error:

ERROR: ArgumentError: Adjacency / distance matrices must be symmetric
Stacktrace:
 [1] SimpleGraph{Int64}(::Array{Float64,2}) at /home/user/.julia/packages/LightGraphs/PPsyP/src/SimpleGraphs/simplegraph.jl:78
 [2] SimpleGraph(::Array{Float64,2}) at /home/user/.julia/packages/LightGraphs/PPsyP/src/SimpleGraphs/simplegraph.jl:72
 [3] top-level scope at none:0

So far I have only seen the example on the github (https://github.com/JuliaGraphs/SimpleWeightedGraphs.jl) page which generates the weighted graph from and edgelist. However, I would prefer if I could generate the graph directly from an adjacency matrix.

like image 294
RM- Avatar asked Nov 05 '25 02:11

RM-


1 Answers

Building off crstnbr's answer, a Graph is an unweighted undirected, so the adjacency matrix is ideally symmetric with values in [0, 1].
Feeding the Graph constructor any symmetric matrix creates edges for every non-zero element:

A = rand(3,3);
Graph(A+A');
println.(edges(G));
 Edge 1 => 1
 Edge 1 => 2
 Edge 1 => 3
 Edge 2 => 2
 Edge 2 => 3
 Edge 3 => 3

The SimpleWeightedDiGraph has several constructors that can take a dense or SparseMatrixCSC adjacency matrix:

SimpleWeightedDiGraph(rand(4,4))
 {4, 16} directed simple Int64 graph with Float64 weights

SimpleWeightedDiGraph(rand([0,1], 3, 3))
 {3, 5} directed simple Int64 graph with Int64 weights

using SparseArrays
SimpleWeightedDiGraph( sprand(3, 3, 0.5) )
 {3, 5} directed simple Int64 graph with Float64 weights
like image 193
stillearningsomething Avatar answered Nov 07 '25 12:11

stillearningsomething



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!