Skip to content

Commit 46f7dfb

Browse files
Merge pull request #107 from ghislainb/matrix2graph_optim
reduce time complexity of matrix2graph
2 parents ddded62 + e66c7ee commit 46f7dfb

File tree

1 file changed

+41
-12
lines changed

1 file changed

+41
-12
lines changed

src/coloring/matrix2graph.jl

Lines changed: 41 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,30 @@
1+
"""
2+
_cols_by_rows(rows_index,cols_index)
3+
4+
Returns a vector of rows where each row contains
5+
a vector of its column indices.
6+
"""
7+
function _cols_by_rows(rows_index,cols_index)
8+
nrows = maximum(rows_index)
9+
cols_by_rows = [eltype(rows_index)[] for _ in 1:nrows]
10+
for (i,j) in zip(rows_index,cols_index)
11+
push!(cols_by_rows[i],j)
12+
end
13+
return cols_by_rows
14+
end
15+
16+
17+
"""
18+
_rows_by_cols(rows_index,cols_index)
19+
20+
Returns a vector of columns where each column contains
21+
a vector of its row indices.
22+
"""
23+
function _rows_by_cols(rows_index,cols_index)
24+
return _cols_by_rows(cols_index,rows_index)
25+
end
26+
27+
128
"""
229
matrix2graph(sparse_matrix, [partition_by_rows::Bool=true])
330
@@ -19,22 +46,24 @@ function matrix2graph(sparse_matrix::SparseMatrixCSC{<:Number, Int}, partition_b
1946
inner = SimpleGraph(num_vtx)
2047

2148
if partition_by_rows
22-
@inbounds for i in eachindex(rows_index)
23-
cur_row = rows_index[i]
24-
for j in 1:(i-1)
25-
next_row = rows_index[j]
26-
if cols_index[i] == cols_index[j] && cur_row != next_row
27-
add_edge!(inner, cur_row, next_row)
49+
rows_by_cols = _rows_by_cols(rows_index,cols_index)
50+
@inbounds for (cur_row,cur_col) in zip(rows_index,cols_index)
51+
if !isempty(rows_by_cols[cur_col])
52+
for next_row in rows_by_cols[cur_col]
53+
if next_row < cur_row
54+
add_edge!(inner, cur_row, next_row)
55+
end
2856
end
2957
end
3058
end
3159
else
32-
@inbounds for i in eachindex(cols_index)
33-
cur_col = cols_index[i]
34-
for j in 1:(i-1)
35-
next_col = cols_index[j]
36-
if rows_index[i] == rows_index[j] && cur_col != next_col
37-
add_edge!(inner, cur_col, next_col)
60+
cols_by_rows = _cols_by_rows(rows_index,cols_index)
61+
@inbounds for (cur_row,cur_col) in zip(rows_index,cols_index)
62+
if !isempty(cols_by_rows[cur_row])
63+
for next_col in cols_by_rows[cur_row]
64+
if next_col < cur_col
65+
add_edge!(inner, cur_col, next_col)
66+
end
3867
end
3968
end
4069
end

0 commit comments

Comments
 (0)