在Julia中生成加权和有向网络形式邻接矩阵

时间:2018-09-18 18:34:59

标签: julia lightgraphs

我想根据Julia(v0.7)中的邻接矩阵生成加权有向网络。

到目前为止,我已经尝试过:

using LightGraphs
using SimpleWeightedGraphs

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

但我收到错误消息:

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

到目前为止,我只在github(https://github.com/JuliaGraphs/SimpleWeightedGraphs.jl)页面上看到了该示例,该示例从and edgelist生成加权图。但是,如果可以直接从邻接矩阵生成图,我会更喜欢。

3 个答案:

答案 0 :(得分:1)

绝不是Julia图形专家,但我想您想要的是

julia> A = rand(100,100);

julia> G = SimpleWeightedDiGraph(A)
{100, 10000} directed simple Int64 graph with Float64 weights

Graph(a::AbstractMatrix)是无向(单位加权)图的构造函数:

julia> A = A+transpose(A); # making A symmetric

julia> G = Graph(A)
{100, 5050} undirected simple Int64 graph

julia> weights(G)
100 × 100 default distance matrix (value = 1)

答案 1 :(得分:1)

建立在crstnbr答案的基础上,Graph是无权无向的,因此,邻接矩阵理想地与[0, 1]中的值对称。
向任何对称矩阵馈入Graph构造函数,将为每个非零元素创建边:

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

SimpleWeightedDiGraph有多个构造函数,可以采用密集或SparseMatrixCSC邻接矩阵:

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

答案 2 :(得分:1)

您遇到的第一个问题是随机邻接矩阵不对称,这是无向图所必需的。您要创建一个有向图。

第二,如果您想要加权图,则需要使用SimpleWeightedGraphs.jl包,这意味着您可以轻松完成

julia> using LightGraphs, SimpleWeightedGraphs

julia> a = rand(100,100);

julia> g = SimpleWeightedDiGraph(a)
{100, 10000} directed simple Int64 graph with Float64 weights

但是请注意,这是创建随机加权图的一种非常不好的方法,因为rand函数几乎可以保证这将是完整的图。更好的方法是使用sprand

julia> using SparseArrays

julia> a = sprand(100, 100, 0.2);

julia> g = SimpleWeightedDiGraph(a)
{100, 2048} directed simple Int64 graph with Float64 weights