Skip to content
This repository has been archived by the owner on Oct 8, 2021. It is now read-only.

Doubling the weights of self-edges #38

Open
pwl opened this issue Nov 17, 2018 · 3 comments
Open

Doubling the weights of self-edges #38

pwl opened this issue Nov 17, 2018 · 3 comments

Comments

@pwl
Copy link

pwl commented Nov 17, 2018

I'm trying to construct a weighted graph with self-edges using the SimpleWeightedGraph(srcs, dsts, weights) constructor from here but the weights of self-edges seem to be counted twice. For example

> collect(edges(SimpleWeightedGraph([1],[1],[1])))
1-element Array{SimpleWeightedEdge{Int64,Int64},1}:
 Edge 1 => 1 with weight 2

although the edge 1=>1 was specified only once. This is coming from vcat duplicating [1] into [1,1] for source, destination and the weight ending up in a double self-edge. So currently there is no way to use this constructor to get a self-edge with weight 1 (assuming integer input weights).
I don't know if this was intended, if not it could be fixed with the code below.

d=i.!=j
sparse(vcat(i,j[d]), vcat(j,i[d]), vcat(w,w[d]), m, m, combine)
@sbromberger
Copy link
Owner

This is expected (if not explicitly intended) for undirected graphs, as the adjacency matrix of an undirected graph yields 2 for self-loops:

g = Graph(3)
add_edge!(g, 1, 1)
Matrix(adjacency_matrix(g))

gives

2 0 0
0 0 0
0 0 0

@pwl
Copy link
Author

pwl commented Nov 18, 2018

Sorry, I'm at loss as to how the adjacency matrix comes in here, I'm new to the graph terminology. How is the adjacency matrix related to the weights in this context?

Am I on the right track to think that SimpleWeightedGraph(srcs, dsts, weights) is conceptually equivalent to creating a directed graph first and then converting it to an undirected one by summing all the edges, where self edges are counted twice because their adjacency matrix entry is 2?

And a related question, what would be the recommended way to construct a weighted graph that I expected to get in the first place? That is SimpleWeightedGraph(srcs, dsts, weights) without doubling the self-edges? Currently I directly construct the sparse matrix and build a weighted graph with it.

@sbromberger
Copy link
Owner

sbromberger commented Nov 19, 2018

SimpleWeightedGraphs are stored as a sparse matrix with non-zero weights denoting adjacencies. Self-loops are a bit of an afterthought and aren't guaranteed to actually work with all algorithms. However, what you can do is simply iterate over the vertices and divide the weights by two, readding the edges.

A PR would also be welcome, if for nothing else than discussion as to the best way to proceed.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants