Skip to content

Commit 5f824bc

Browse files
bubblingoaksbromberger
authored andcommitted
cartesian_product override (#40)
* add override for cartesian_product * add import of cartesian_product for new override * add missing comma * add tests for cartesian_product
1 parent d72b698 commit 5f824bc

File tree

3 files changed

+27
-1
lines changed

3 files changed

+27
-1
lines changed

src/SimpleWeightedGraphs.jl

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -15,7 +15,7 @@ import LightGraphs:
1515
has_vertex, has_edge, inneighbors, outneighbors,
1616
indegree, outdegree, degree, has_self_loops, num_self_loops,
1717

18-
add_vertices!, adjacency_matrix, weights, connected_components,
18+
add_vertices!, adjacency_matrix, weights, connected_components, cartesian_product,
1919

2020
AbstractGraphFormat, loadgraph, loadgraphs, savegraph,
2121
pagerank, induced_subgraph

src/overrides.jl

Lines changed: 20 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -59,6 +59,26 @@ savegraph(fn::AbstractString, g::AbstractSimpleWeightedGraph, gname::AbstractStr
5959
savegraph(fn::AbstractString, d::Dict{T, U}; compress=true) where T <: AbstractString where U <: AbstractSimpleWeightedGraph =
6060
savegraph(fn, d, SWGFormat(), compress=compress)
6161

62+
# It is possible that this is suboptimal, but it is the most trivial extension of the implementation used in LightGraphs
63+
function cartesian_product(g::G, h::G) where G <: AbstractSimpleWeightedGraph
64+
z = G(nv(g) * nv(h))
65+
id(i, j) = (i - 1) * nv(h) + j
66+
for e in edges(g)
67+
i1, i2 = Tuple(e)
68+
for j = 1:nv(h)
69+
add_edge!(z, id(i1, j), id(i2, j), weight(e))
70+
end
71+
end
72+
73+
for e in edges(h)
74+
j1, j2 = Tuple(e)
75+
for i in vertices(g)
76+
add_edge!(z, id(i, j1), id(i, j2), weight(e))
77+
end
78+
end
79+
return z
80+
end
81+
6282
# Connected Components on a Sparse Matrix
6383

6484
function _cc(g::SimpleWeightedGraph{T,U}) where T where U

test/overrides.jl

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -13,6 +13,12 @@
1313
gi = gx[2:4]
1414
@test weights(gi)[1, 2] == 99
1515

16+
h = @inferred(cartesian_product(g, g))
17+
@test nv(h) == 25
18+
@test ne(h) == 40
19+
gz = g3[1:4]
20+
add_edge!(gz, 3, 4, 87)
21+
@test weights(cartesian_product(g3,gz))[11,12]==weights(gz)[3,4]
1622
end
1723

1824
add_edge!(g5, 1, 2, 2); add_edge!(g5, 2, 3, 2); add_edge!(g5, 1, 3, 1); add_edge!(g5, 3, 4, 5)

0 commit comments

Comments
 (0)