forked from JuliaGraphs/GraphIO.jl
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNet.jl
More file actions
79 lines (70 loc) · 2.28 KB
/
Copy pathNet.jl
File metadata and controls
79 lines (70 loc) · 2.28 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
module NET
using Graphs: Graphs
using Graphs
using Graphs: AbstractGraphFormat
import Graphs: loadgraph, loadgraphs, savegraph
export NETFormat
struct NETFormat <: AbstractGraphFormat end
"""
savenet(io, g, gname="g")
Write a graph `g` to an IO stream `io` in the [Pajek NET](https://docs.gephi.org/desktop/User_Manual/Import/Pajek_NET_Format)
format. Return 1 (number of graphs written).
"""
function savenet(io::IO, g::Graphs.AbstractGraph, gname::String="g")
println(io, "*Vertices $(nv(g))")
# write edges
if is_directed(g)
println(io, "*Arcs")
else
println(io, "*Edges")
end
for e in Graphs.edges(g)
println(io, "$(src(e)) $(dst(e))")
end
return 1
end
"""
loadnet(io::IO, gname="graph")
Read a graph from IO stream `io` in the [Pajek NET](https://docs.gephi.org/desktop/User_Manual/Import/Pajek_NET_Format)
format. Return the graph.
"""
function loadnet(io::IO, gname::String="graph")
line = readline(io)
# skip comments
while startswith(line, "%")
line = readline(io)
end
n = parse(Int, match(r"\d+", line).match)
for ioline in eachline(io)
line = ioline
(occursin(r"^\*[Aa]rcs", line) || occursin(r"^\*[Ee]dges", line)) && break
end
if occursin(r"^\*[Aa]rcs", line)
g = Graphs.DiGraph(n)
else
g = Graphs.Graph(n)
end
while occursin(r"^\*[Aa]rcs", line)
for ioline in eachline(io)
line = ioline
ms = collect(m.match for m in eachmatch(r"\d+", line; overlap=false))
length(ms) < 2 && break
add_edge!(g, parse(Int, ms[1]), parse(Int, ms[2]))
end
end
while occursin(r"^\*[Ee]dges", line) # add edges in both directions
for ioline in eachline(io)
line = ioline
ms = collect(m.match for m in eachmatch(r"\d+", line; overlap=false))
length(ms) < 2 && break
i1, i2 = parse(Int, ms[1]), parse(Int, ms[2])
add_edge!(g, i1, i2)
add_edge!(g, i2, i1)
end
end
return g
end
loadgraph(io::IO, gname::String, ::NETFormat) = loadnet(io, gname)
loadgraphs(io::IO, ::NETFormat) = Dict("graph" => loadnet(io, "graph"))
savegraph(io::IO, g::AbstractGraph, gname::String, ::NETFormat) = savenet(io, g, gname)
end # module