3

我想从 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 ) 页面上看到了从边列表生成加权图的示例。但是,如果我可以直接从邻接矩阵生成图形,我会更喜欢。

4

3 回答 3

2

绝不是 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)
于 2018-09-18T19:02:21.593 回答
2

根据 crstnbr 的答案, aGraph是未加权的无向矩阵,因此邻接矩阵理想地与 中的值对称[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
于 2018-09-18T23:22:04.327 回答
2

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

其次,如果你想要一个加权图,你会想要使用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
于 2018-09-18T23:44:26.993 回答