Graph Interface API Reference
This page documents the Graphs.jl AbstractGraph interface methods implemented by NetworkCore.jl. These functions let a Network be passed to Graphs.jl algorithms (Graphs.core_number(net), Graphs.betweenness_centrality(net), Graphs.connected_components(net), …), which then see the network's true directedness.
An undirected Network is stored as a SimpleDiGraph holding both arcs of every edge (the field net.graph). The interface methods below account for that; Graphs.jl itself does not. A Graphs.jl algorithm called on net.graph therefore sees a directed graph with every tie twice:
| Florentine marriage network | on flo | on flo.graph |
|---|---|---|
core_number | 1, 2, 2, … (max 2) | 2, 4, 4, … (doubled) |
maximum degree | 6 | 12 |
global_clustering_coefficient | 0.1915 | 0.0395 |
maximal_cliques | works | MethodError (directed) |
Always call Graphs.jl on the Network itself. When an algorithm needs a concrete Graphs.jl type, convert explicitly: Graphs.SimpleGraph(net) is an undirected copy (each edge once) and Graphs.SimpleDiGraph(net) a directed copy of the storage. Never mutate net.graph either — the mutators keep edge attributes, the missing-dyad mask, the two-mode partition and the cached self-loop count in step with it.
using NetworkCore, Graphs
flo = load_dataset(:florentine_marriage)
core_number(flo) == core_number(SimpleGraph(flo)) # true — the right answer
core_number(flo.graph) == 2 .* core_number(flo) # true — the trapBasic Properties
nv
ne
Graphs.ne — Function
ne(net::Network) -> IntReturn the number of edges in the network (R's network.edgecount). For undirected networks, each edge is counted once (including self-loops).
Example
net = network(3; directed=false)
add_edge!(net, 1, 2)
add_edge!(net, 2, 1) # false — already present (undirected)
ne(net) # 1vertices
Graphs.vertices — Function
vertices(net::Network) -> iteratorReturn an iterator over all vertices, 1:nv(net).
Example
net = network(3)
collect(vertices(net)) # [1, 2, 3]edges
Graphs.edges — Function
edges(net::Network) -> iteratorReturn an iterator over all edges. For undirected networks each edge is yielded exactly once (canonical src <= dst orientation) even though the backing digraph stores both arc directions; the iterator has a correct length and eltype.
Example
net = network(3; directed=false)
add_edges!(net, [(2, 1), (2, 3)])
[(src(e), dst(e)) for e in edges(net)] # [(1, 2), (2, 3)]
length(edges(net)) # 2Graphs.src — Function
src(e) -> IntSource (first endpoint) of an edge yielded by edges — the Graphs.jl accessor, re-exported with the iterator so that for e in edges(net); src(e) … works after a plain using NetworkCore (or using ERGM). On an undirected network the edge is yielded in canonical orientation, so src(e) <= dst(e).
Example
net = network(3; directed=true)
add_edge!(net, 3, 1)
e = first(edges(net))
src(e), dst(e) # (3, 1)Graphs.dst — Function
dst(e) -> IntDestination (second endpoint) of an edge yielded by edges — the Graphs.jl accessor, re-exported with the iterator; see src.
Example
net = network(3; directed=false)
add_edge!(net, 3, 1)
dst(first(edges(net))) # 3 — canonical orientation (1, 3)has_vertex
Graphs.has_vertex — Function
has_vertex(net::Network, v) -> BoolCheck if vertex v exists in the network, i.e. 1 <= v <= nv(net).
Example
net = network(3)
has_vertex(net, 3) # true
has_vertex(net, 4) # falsehas_edge
Graphs.has_edge — Function
has_edge(net::Network, i, j) -> BoolCheck if edge (i, j) exists in the network (R's is.adjacent). Symmetric for undirected networks. Reads the face value: a masked (unobserved) dyad reports its stored tie status — see is_missing_dyad.
Example
net = network(3)
add_edge!(net, 1, 2)
has_edge(net, 1, 2) # true
has_edge(net, 2, 1) # false — directeddegree, indegree, outdegree
The Graphs.jl degree family, re-exported so that using NetworkCore alone answers the first descriptive question a user asks. On an undirected network all three agree; on a directed one degree is indegree + outdegree. A self-loop counts once on an undirected network and twice (one in, one out) on a directed one, as in Graphs.jl.
Graphs.degree — Function
degree(net::Network, v) -> Int
degree(net::Network) -> Vector{Int}Degree of vertex v (or of every vertex), the Graphs.jl generic re-exported by NetworkCore.jl. On a directed network degree(net, v) == indegree(net, v) + outdegree(net, v); on an undirected network all three agree. A self-loop counts once on an undirected network and twice (one in, one out) on a directed one, as in Graphs.jl.
Reads face values: a masked (unobserved) dyad contributes its stored tie status. For a degree that honours the missing-data contract use SNA.degree_centrality(net; missing=...).
Example
net = Network(3)
add_edge!(net, 1, 2)
add_edge!(net, 3, 1)
degree(net, 1) # 2
degree(net) # [2, 1, 1]Graphs.indegree — Function
indegree(net::Network, v) -> Int
indegree(net::Network) -> Vector{Int}Number of edges pointing into v (Graphs.jl generic, re-exported). Equal to degree on an undirected network. Reads face values at masked dyads.
Example
net = Network(3)
add_edge!(net, 1, 2)
indegree(net, 2) # 1
indegree(net, 1) # 0Graphs.outdegree — Function
outdegree(net::Network, v) -> Int
outdegree(net::Network) -> Vector{Int}Number of edges leaving v (Graphs.jl generic, re-exported). Equal to degree on an undirected network. Reads face values at masked dyads.
Example
net = Network(3)
add_edge!(net, 1, 2)
outdegree(net, 1) # 1
outdegree(net, 2) # 0is_directed
Graphs.is_directed — Function
is_directed(net::Network) -> BoolCheck if the network is directed.
Directedness is a type parameter of Network{T,D}, so the type-level trait Graphs.is_directed(typeof(net)) is truthful and Graphs.jl generics that dispatch on it use the correct (un)directed semantics.
Example
is_directed(network(3)) # true (the default)
is_directed(network(3; directed=false)) # falseis_bipartite
is_bipartite is Graphs.jl's graph-theoretic two-colourability test, which NetworkCore.jl extends for Network. It is not the statnet two-mode metadata flag — for that, see is_two_mode below.
Graphs.is_bipartite — Function
is_bipartite(net::Network) -> BoolCheck whether the network is bipartite in the graph-theoretic sense, i.e. whether its vertices can be two-colored so that every edge joins the two color classes (computed by Graphs.jl's algorithm on the underlying graph).
This is not the two-mode metadata flag set via network(n; bipartite=k); use is_two_mode for that.
is_two_mode
NetworkCore.is_two_mode — Function
is_two_mode(net) -> BoolReturn whether the network is flagged as a two-mode (bipartite) network, i.e. whether it carries the statnet-style bipartite metadata giving the size of the first vertex mode (network(n; bipartite=k) or BipartiteNetwork). This is pure metadata about how the vertex set is partitioned; for the graph-theoretic property use Graphs.is_bipartite.
Example
is_two_mode(network(5; bipartite=2)) # true
is_two_mode(BipartiteNetwork(2, 3)) # true
is_two_mode(network(5)) # falsezero
Base.zero — Function
zero(::Type{Network{T,D}}) -> Network{T,D}Return an empty network of the given type, as required by the Graphs.jl interface. Directedness is encoded in the type parameter D and is preserved. For the one-parameter form zero(Network{T}) (directedness unspecified) an empty directed network is returned, matching the constructor default; use zero(net) on an instance to match its directedness.
zero(net::Network) -> NetworkReturn an empty network with the same eltype, directedness, and loops setting as net.
Vertex Modification
add_vertex!
Graphs.SimpleGraphs.add_vertex! — Function
add_vertex!(net::Network) -> BoolAdd a new vertex to the network (as vertex nv(net) + 1). Returns true if successful.
Example
net = network(3)
add_vertex!(net) # true
nv(net) # 4add_vertices!
Graphs.add_vertices! — Function
add_vertices!(net::Network, n::Int) -> IntAdd n new vertices to the network. Returns the number of vertices added.
Example
net = network(3)
add_vertices!(net, 2) # 2
nv(net) # 5rem_vertex!
Graphs.SimpleGraphs.rem_vertex! — Function
rem_vertex!(net::Network, v) -> BoolRemove vertex v from the network. Returns true if successful.
All edges incident to v and their attributes are removed. On a one-mode network, following the Graphs.jl swap-and-pop convention, the last vertex is renumbered to v; its vertex attributes and the attributes of its incident edges are remapped to the new ID, so attribute data stays attached to the right vertices.
On a two-mode network swap-and-pop would move the last (mode-2) vertex into a mode-1 slot and turn its edges into within-mode pairs, so the vertices are instead renumbered stably — every vertex after v moves down by one — and the mode-1 size bipartite drops by one when v is a mode-1 vertex. This is R's delete.vertices; attributes and missing-dyad marks move with their vertices. Use Graphs.rem_vertices!(net, vs) to delete several vertices at once with the same stable renumbering.
Example
net = network(3)
set_vertex_attribute!(net, :name, ["a", "b", "c"])
rem_vertex!(net, 1) # true; vertex 3 ("c") is renumbered to 1
nv(net) # 2
get_vertex_attribute(net, :name, 1) # "c"
b = network(5; bipartite=2, directed=false)
add_edges!(b, [(1, 3), (2, 5)])
rem_vertex!(b, 1) # stable: old 2..5 become 1..4
b.bipartite # 1
has_edge(b, 1, 4) # true — old edge (2, 5)rem_vertices!
Graphs.SimpleGraphs.rem_vertices! — Method
rem_vertices!(net::Network, vs) -> VectorRemove the vertices vs (any iterable of vertex IDs; repeats are ignored) from the network, with R's delete.vertices semantics: the remaining vertices keep their relative order and are renumbered 1, 2, … (stable renumbering, never swap-and-pop), every edge incident to a removed vertex goes with its attributes and missing-dyad marks, and on a two-mode network bipartite drops by the number of removed mode-1 vertices. Returns vmap, the original ID of each remaining vertex (vmap[new] == old), as Graphs.jl's rem_vertices! does. A vertex outside 1:nv(net) is an ArgumentError and leaves the network untouched.
This is a method of Graphs.jl's rem_vertices! (not exported by NetworkCore.jl: call it as Graphs.rem_vertices! or after using Graphs).
Example
using Graphs: rem_vertices!
net = network(5; bipartite=2, directed=false)
add_edges!(net, [(1, 3), (2, 4), (2, 5)])
set_vertex_attribute!(net, :name, ["a", "b", "c", "d", "e"])
vmap = rem_vertices!(net, [1, 4]) # [2, 3, 5]
net.bipartite # 1
vertex_attribute_vector(net, :name, String) # ["b", "c", "e"]
has_edge(net, 1, 3) # true — old edge (2, 5)Edge Modification
add_edge!
Graphs.SimpleGraphs.add_edge! — Function
add_edge!(net::Network, i, j) -> BoolAdd edge (i, j) to the network. Returns true if successful. For undirected networks, also adds (j, i). For bipartite networks, edges must connect the two modes; within-mode edges are rejected (returns false).
The other half of the sampler toggle (see rem_edge!, which is 0 B). Adds no allocation over Graphs.jl's own add_edge! on the wrapped SimpleDiGraph: the edge is handed over as a concrete SimpleEdge{T} rather than through the generic add_edge!(g, x, y), whose edgetype(g)(x, y) construction allocates, and the attribute store is skipped when empty. The wrapped graph itself may allocate a few dozen bytes on alternate toggles after a removal (a Base insert! regrowing the adjacency list after deleteat!), and this method allocates exactly as much — the "allocation-free" testset pins equality with the bare SimpleDiGraph, not zero.
Example
net = network(3)
add_edge!(net, 1, 2) # true
add_edge!(net, 1, 2) # false — already present
add_edge!(net, 1, 1) # false — loops=false
has_edge(net, 1, 2) # trueadd_edge!(net::Network, i, j, attrs::Dict) -> BoolAdd edge (i, j) and, if it was added, store each attr => value pair of attrs on it. Returns whether the edge was added.
Example
net = network(3)
add_edge!(net, 1, 2, Dict(:weight => 2.5)) # true
get_edge_attribute(net, :weight, 1, 2) # 2.5add_edges!
NetworkCore.add_edges! — Function
add_edges!(net::Network, edges) -> IntAdd multiple edges from an iterable of (i, j) pairs (R's add.edges). Returns the number of edges newly added — an edge already present counts as zero and is not an error.
Every listed edge ends up in the network or the call throws. An endpoint outside 1:nv(net) (an undersized network(n), a mistyped ID), a self-loop when loops=false, and a within-mode pair on a two-mode network are ArgumentErrors naming the offending edge, as R's add.edges errors on an illegal vertex reference — never a silently smaller network. (The single add_edge! keeps Graphs.jl's convention of returning false.)
Example
net = network(4)
add_edges!(net, [(1, 2), (2, 3), (1, 2)]) # 2 — the repeat is not re-added
ne(net) # 2
try add_edges!(net, [(3, 4), (1, 99)]) catch err; err end # ArgumentError: edge (1, 99) references a vertex outside 1:4rem_edge!
Graphs.SimpleGraphs.rem_edge! — Function
rem_edge!(net::Network, i, j) -> BoolRemove edge (i, j) from the network, together with every edge attribute stored on it. Returns true if the edge existed and was removed, false (and touches nothing) if it did not.
This is the toggle half of every Metropolis–Hastings sampler in the ecosystem, so it is allocation-free: on a network with no edge attributes it never looks at the attribute store, and on one with attributes it walks the attribute dictionaries by value (one delete! per attribute, no key lookup). Pinned by the "remedge!/addedge! are allocation-free" testset.
Example
net = network(3)
add_edge!(net, 1, 2)
set_edge_attribute!(net, :weight, 1, 2, 2.5)
rem_edge!(net, 1, 2) # true
has_edge(net, 1, 2) # false
get_edge_attribute(net, :weight, 1, 2) === nothing # attribute went with it
rem_edge!(net, 1, 2) # false — already absentNeighbors
neighbors
Graphs.neighbors — Function
neighbors(net::Network, v) -> iteratorReturn neighbors of vertex v. For directed networks, returns outgoing neighbors.
Example
net = network(4)
add_edges!(net, [(1, 2), (1, 3), (4, 1)])
neighbors(net, 1) # [2, 3]inneighbors
Graphs.inneighbors — Function
inneighbors(net::Network, v) -> iteratorReturn incoming neighbors of vertex v (all neighbors on an undirected network).
Example
net = network(4)
add_edges!(net, [(1, 2), (1, 3), (4, 1)])
inneighbors(net, 1) # [4]outneighbors
Graphs.outneighbors — Function
outneighbors(net::Network, v) -> iteratorReturn outgoing neighbors of vertex v (all neighbors on an undirected network).
Example
net = network(4)
add_edges!(net, [(1, 2), (1, 3), (4, 1)])
outneighbors(net, 1) # [2, 3]Utility Functions
network_size
NetworkCore.network_size — Function
network_size(net::Network) -> IntReturn the number of vertices. Alias for nv() to match R's network.size().
Example
network_size(network(7)) # 7network_edgecount
NetworkCore.network_edgecount — Function
network_edgecount(net::Network) -> IntReturn the number of edges. Alias for ne() to match R's network.edgecount().
Example
net = network(3)
add_edges!(net, [(1, 2), (2, 3)])
network_edgecount(net) # 2network_density
NetworkCore.network_density — Function
network_density(net; missing=:error, diag=net.loops, discount_bipartite=false) -> Float64Network density: the number of edges divided by the number of dyads that could carry one, following R's network.density. Returns NaN for networks with fewer than two vertices (R does the same).
The denominator is chosen from the network's directedness and the diag and discount_bipartite keywords:
| Network | diag=false | diag=true |
|---|---|---|
| Directed | n (n - 1) | n² |
| Undirected | n (n - 1) / 2 | n (n + 1) / 2 |
Two-mode, discount_bipartite=true, undirected | n₁ n₂ | n₁ n₂ |
Two-mode, discount_bipartite=true, directed | 2 n₁ n₂ | 2 n₁ n₂ |
Keywords
missing::Symbol=:error— the missing-dyad policy (seerequire_observed). By default a network with masked (unobserved) dyads is refused;missing=:facecounts every edge at its stored face value, over a denominator that still contains every dyad. This is R'snetwork.density(x, na.omit=FALSE). R's defaultna.omit=TRUE— drop the NA edges from the numerator but keep the denominator — is deliberately not offered: it reads an unobserved tie as absent, which is the silent data-invention the missing-data contract exists to stop.diag::Bool=net.loops— whether self-loops count as possible dyads. Defaults to the network'sloopsflag, exactly as R keys the denominator onhas.loops(x), so an existing call gives the same value it always did.diag=falseon a loops-allowed network mirrorssna::gden(diag=FALSE): self-loops are dropped from both the numerator and the denominator.discount_bipartite::Bool=false— see below.
Two-mode networks
A two-mode network (network(n; bipartite=n₁) or a BipartiteNetwork) is measured by default over all n (n - 1) (or n (n - 1) / 2) dyads, including the within-mode dyads that can never carry a tie — this is R's default, discount.bipartite=FALSE. Pass discount_bipartite=true to use only the n₁ n₂ cross-mode dyads (2 n₁ n₂ for a directed two-mode network, one per direction), which is the "density of the incidence matrix" most two-mode analyses mean. The keyword is a no-op on a one-mode network. Both the flagged Network and the BipartiteNetwork wrapper give the same answer for the same edge set and keyword.
Example
net = network(4; directed=false)
add_edges!(net, [(1, 2), (2, 3), (3, 4)])
network_density(net) # 0.5 == 3 / 6
b = network(5; bipartite=2, directed=false)
add_edges!(b, [(1, 3), (1, 4), (2, 5)])
network_density(b) # 0.3 — over all 10 dyads (R default)
network_density(b; discount_bipartite=true) # 0.5 — over the 2·3 cross-mode dyads
l = network(3; loops=true)
add_edges!(l, [(1, 1), (1, 2)])
network_density(l) # 2/9 — loops count (diag=true)
network_density(l; diag=false) # 1/6 — self-loop dropped, sna::gden(diag=FALSE)
set_missing_dyad!(net, 1, 4)
try network_density(net) catch err; err end # ArgumentError: masked dyad
network_density(net; missing=:face) # 0.5 — face value, in writingSee also missing_policies (this routine declares (:error, :face)), is_two_mode.
get_neighborhood
NetworkCore.get_neighborhood — Function
get_neighborhood(net::Network, v, order::Int=1) -> SetGet the neighborhood of vertex v up to the specified order (distance), following out-neighbors on a directed network: the set of vertices reachable from v in at most order steps, including v itself (R's get.neighborhood returns the order-1 neighbors without v).
Example
net = network(5)
add_edges!(net, [(1, 2), (2, 3), (3, 4)])
get_neighborhood(net, 1) # Set([1, 2])
get_neighborhood(net, 1, 2) # Set([1, 2, 3])get_induced_subgraph
NetworkCore.get_induced_subgraph — Function
get_induced_subgraph(net::Network, vlist) -> NetworkCreate a new network containing only the specified vertices and the edges between them (R's get.inducedSubgraph). Vertex vlist[i] becomes vertex i of the result; vertex, edge and network attributes and missing-dyad marks between retained vertices are carried over. vlist must be distinct vertices of net (ArgumentError naming the offending entry otherwise, as R's "Illegal vertex selection").
On a two-mode network the result is two-mode too, with bipartite equal to the number of selected mode-1 vertices (R's get.inducedSubgraph keeps the partition the same way). Because vertex vlist[i] becomes vertex i, the selected mode-1 vertices must come before the selected mode-2 ones in vlist — otherwise the result could not be a contiguous two-mode network, and an ArgumentError says so (sort(vlist) always qualifies) instead of silently returning a one-mode network.
Example
net = network(5)
add_edges!(net, [(1, 2), (2, 3), (3, 4)])
sub = get_induced_subgraph(net, [2, 3, 5])
nv(sub), ne(sub) # (3, 1) — only 2→3 survives, as 1→2
has_edge(sub, 1, 2) # truepermute_vertices
NetworkCore.permute_vertices — Function
permute_vertices(net::Network, perm::Vector) -> NetworkCreate a new network with vertices permuted according to the given permutation (R's permute.vertexIDs): old vertex perm[i] becomes new vertex i, and every attribute and missing-dyad mark moves with its vertex. perm must be a permutation of 1:nv(net) (ArgumentError otherwise, as R's "Invalid permutation vector").
On a two-mode network the permutation must map each mode onto itself (perm[1:n₁] a permutation of 1:n₁): a vertex moved across the mode boundary would turn its cross-mode edges into impossible within-mode pairs. Such a permutation is an ArgumentError (R's permute.vertexIDs only warns and returns a network that violates its own partition).
Example
net = network(3)
add_edge!(net, 1, 2)
set_vertex_attribute!(net, :name, ["a", "b", "c"])
p = permute_vertices(net, [3, 1, 2]) # old 3 → new 1, old 1 → new 2, old 2 → new 3
has_edge(p, 2, 3) # true
get_vertex_attribute(p, :name, 1) # "c"Graphs.jl constructions
Graphs.jl generics that build a new graph from a Network. NetworkCore.jl adds methods so the result is a Network with its attributes, missing-dyad mask, loops flag and two-mode partition — not a bare graph.
induced_subgraph
Graphs.induced_subgraph — Method
induced_subgraph(net::Network, vlist) -> (Network, vmap)Graphs.jl's induced_subgraph on a Network: returns the subgraph built by get_induced_subgraph — attributes, missing-dyad marks, loops and the two-mode partition carried over — together with vmap, the original ID of each vertex of the subgraph (vmap[i] == vlist[i]), as Graphs.jl returns it. vlist may also be a Bool mask of length nv(net). The Graphs.jl fallback would build a bare network without any of the attributes.
Example
using Graphs: induced_subgraph
net = network(5)
add_edges!(net, [(1, 2), (2, 3), (3, 4)])
sub, vmap = induced_subgraph(net, [2, 3, 5])
ne(sub), vmap # (1, [2, 3, 5])complement
Graphs.complement — Method
complement(net::Network) -> NetworkGraphs.jl's complement on a Network: the network with the same vertices in which every possible dyad is a tie exactly when it is not one in net (R's !net). "Possible" follows the network's own rules: self-loops are part of the complement only when loops=true, and on a two-mode network only cross-mode dyads are (within-mode pairs can never carry a tie, so the complement stays two-mode with the same bipartite). Directedness, loops, bipartite, the vertex and network attributes and the missing-dyad mask are kept — an unobserved dyad stays unobserved, with its face value complemented — while edge attributes are dropped, since the complement's edges are the original's non-edges.
Example
using Graphs: complement
net = network(3; directed=false)
add_edge!(net, 1, 2)
c = complement(net)
ne(c), has_edge(c, 1, 2), has_edge(c, 1, 3) # (2, false, true)