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.

Pass the `Network`, never `net.graph`

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 networkon floon flo.graph
core_number1, 2, 2, … (max 2)2, 4, 4, … (doubled)
maximum degree612
global_clustering_coefficient0.19150.0395
maximal_cliquesworksMethodError (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 trap

Basic Properties

nv

Graphs.nv — Function
nv(net::Network) -> Int

Return the number of vertices in the network (R's network.size).

Example

net = network(5)
nv(net)    # 5
source

ne

Graphs.ne — Function
ne(net::Network) -> Int

Return 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)                 # 1
source

vertices

Graphs.vertices — Function
vertices(net::Network) -> iterator

Return an iterator over all vertices, 1:nv(net).

Example

net = network(3)
collect(vertices(net))    # [1, 2, 3]
source

edges

Graphs.edges — Function
edges(net::Network) -> iterator

Return 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))                        # 2
source
Graphs.src — Function
src(e) -> Int

Source (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)
source
Graphs.dst — Function
dst(e) -> Int

Destination (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)
source

has_vertex

Graphs.has_vertex — Function
has_vertex(net::Network, v) -> Bool

Check 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)    # false
source

has_edge

Graphs.has_edge — Function
has_edge(net::Network, i, j) -> Bool

Check 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 — directed
source

degree, 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]
source
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)    # 0
source
Graphs.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)   # 0
source

is_directed

Graphs.is_directed — Function
is_directed(net::Network) -> Bool

Check 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))    # false
source

is_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) -> Bool

Check 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.

source

is_two_mode

NetworkCore.is_two_mode — Function
is_two_mode(net) -> Bool

Return 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))                 # false
source

zero

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.

source
zero(net::Network) -> Network

Return an empty network with the same eltype, directedness, and loops setting as net.

source

Vertex Modification

add_vertex!

Graphs.SimpleGraphs.add_vertex! — Function
add_vertex!(net::Network) -> Bool

Add 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)             # 4
source

add_vertices!

Graphs.add_vertices! — Function
add_vertices!(net::Network, n::Int) -> Int

Add n new vertices to the network. Returns the number of vertices added.

Example

net = network(3)
add_vertices!(net, 2)    # 2
nv(net)                  # 5
source

rem_vertex!

Graphs.SimpleGraphs.rem_vertex! — Function
rem_vertex!(net::Network, v) -> Bool

Remove 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)
source

rem_vertices!

Graphs.SimpleGraphs.rem_vertices! — Method
rem_vertices!(net::Network, vs) -> Vector

Remove 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)
source

Edge Modification

add_edge!

Graphs.SimpleGraphs.add_edge! — Function
add_edge!(net::Network, i, j) -> Bool

Add 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)     # true
source
add_edge!(net::Network, i, j, attrs::Dict) -> Bool

Add 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.5
source

add_edges!

NetworkCore.add_edges! — Function
add_edges!(net::Network, edges) -> Int

Add 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:4
source

rem_edge!

Graphs.SimpleGraphs.rem_edge! — Function
rem_edge!(net::Network, i, j) -> Bool

Remove 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 absent
source

Neighbors

neighbors

Graphs.neighbors — Function
neighbors(net::Network, v) -> iterator

Return 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]
source

inneighbors

Graphs.inneighbors — Function
inneighbors(net::Network, v) -> iterator

Return 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]
source

outneighbors

Graphs.outneighbors — Function
outneighbors(net::Network, v) -> iterator

Return 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]
source

Utility Functions

network_size

NetworkCore.network_size — Function
network_size(net::Network) -> Int

Return the number of vertices. Alias for nv() to match R's network.size().

Example

network_size(network(7))    # 7
source

network_edgecount

NetworkCore.network_edgecount — Function
network_edgecount(net::Network) -> Int

Return 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)    # 2
source

network_density

NetworkCore.network_density — Function
network_density(net; missing=:error, diag=net.loops, discount_bipartite=false) -> Float64

Network 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:

Networkdiag=falsediag=true
Directedn (n - 1)n²
Undirectedn (n - 1) / 2n (n + 1) / 2
Two-mode, discount_bipartite=true, undirectedn₁ n₂n₁ n₂
Two-mode, discount_bipartite=true, directed2 n₁ n₂2 n₁ n₂

Keywords

  • missing::Symbol=:error — the missing-dyad policy (see require_observed). By default a network with masked (unobserved) dyads is refused; missing=:face counts every edge at its stored face value, over a denominator that still contains every dyad. This is R's network.density(x, na.omit=FALSE). R's default na.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's loops flag, exactly as R keys the denominator on has.loops(x), so an existing call gives the same value it always did. diag=false on a loops-allowed network mirrors sna::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 writing

See also missing_policies (this routine declares (:error, :face)), is_two_mode.

source

get_neighborhood

NetworkCore.get_neighborhood — Function
get_neighborhood(net::Network, v, order::Int=1) -> Set

Get 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])
source

get_induced_subgraph

NetworkCore.get_induced_subgraph — Function
get_induced_subgraph(net::Network, vlist) -> Network

Create 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)      # true
source

permute_vertices

NetworkCore.permute_vertices — Function
permute_vertices(net::Network, perm::Vector) -> Network

Create 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"
source

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])
source

complement

Graphs.complement — Method
complement(net::Network) -> Network

Graphs.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)
source