# `Networkex.Network`
[🔗](https://github.com/CountlinkX-Solutions/networkex/blob/v0.3.0/lib/networkex/network.ex#L5)

A spatial network built from line geometries, after `spaghetti.Network`.

`new/2` turns every polyline into **arcs** between consecutive vertices. Vertices are
identified by their coordinates rounded to `vertex_sig` significant digits (default 11, as in
spaghetti), so lines that meet at the same rounded point are connected. Vertex ids follow the
order in which vertices first appear.

The result holds:

  * `vertices` - the rounded `{x, y}` of each vertex, by id;
  * `arcs` - `{i, j}` vertex pairs (`i <= j`), unique and sorted; `arc_lengths` aligned with
    them; `adjacency` - the neighbouring vertex ids of each vertex;
  * `network` - the connected components of the arcs: `n_components`, `component_labels` (one
    per arc, numbered by the first arc of each component), `component_lengths`,
    `longest_component`, `largest_component` (most vertices), `component_is_ring`,
    `fully_connected`;
  * `graph` - the network with every chain of degree-2 vertices (outside rings) merged into one
    edge: `edges`, `edge_lengths`, `non_articulation_points` (the merged vertices),
    `arcs_to_edges` and the components of the edges (`n_components`, `component_labels`).

As in spaghetti an arc's length runs from the rounded vertex to the next vertex as given.

## Lines

A list of lines, each a list of points (`{x, y}` or `[x, y]`), or a list of WKB `LineString` /
`MultiLineString` binaries. Every line string is one part: unlike spaghetti, the last vertex of
one part of a `MultiLineString` is not joined to the first vertex of the next.

## Options

  * `:vertex_sig` - significant digits of the vertex coordinates (default `11`; `nil` keeps
    them as given).
  * `:vertex_atol` - decimals the vertex coordinates are rounded to after `:vertex_sig`
    (default `nil`, no rounding), spaghetti's `vertex_atol`. It joins line ends that miss each
    other by less than half a unit of the last decimal, for data with known digitising errors.
    It needs `:vertex_sig`: spaghetti ignores it without, so Networkex refuses that.

## Examples

    iex> ntw = Networkex.Network.new([[{0, 0}, {1, 0}, {3, 0}], [{1, 0}, {1, 2}]])
    iex> {ntw.arcs, ntw.arc_lengths}
    {[{0, 1}, {1, 2}, {1, 3}], [1.0, 2.0, 2.0]}
    iex> ntw.graph.edges
    [{0, 1}, {1, 2}, {1, 3}]

# `link`

```elixir
@type link() :: {non_neg_integer(), non_neg_integer()}
```

# `t`

```elixir
@type t() :: %Networkex.Network{
  adjacency: [[non_neg_integer()]],
  arc_lengths: [float()],
  arcs: [link()],
  graph: map(),
  network: map(),
  ref: reference(),
  vertex_atol: pos_integer() | nil,
  vertex_sig: pos_integer() | nil,
  vertices: [{float(), float()}]
}
```

# `all_neighbor_distances`

```elixir
@spec all_neighbor_distances(
  t(),
  Networkex.PointPattern.t(),
  Networkex.PointPattern.t() | nil,
  keyword()
) :: [[term()]]
```

Network distances between every observation of `source` and of `dest` (rows by source),
after `spaghetti.Network.allneighbordistances`. Without `dest` the pattern is measured against
itself and the diagonal is `:nan` (or `fill_diagonal:`). Two observations on the same arc are
the straight-line distance apart; otherwise the shortest of the four routes through the arcs'
vertices. `snap_dist: true` adds the snapping distances (except on a shared arc, as in
spaghetti).

# `arc_draw_order`

```elixir
@spec arc_draw_order(t()) :: [link()]
```

The arcs in the order simulated observations are drawn along: the order in which they first
appear in the lines (spaghetti's `arc_lengths`), not the sorted order of `arcs`.

# `arcs_at`

```elixir
@spec arcs_at(t(), non_neg_integer()) :: [link()]
```

The arcs that touch `vertex` (an index into `vertices`), after
`spaghetti.Network.enum_links_vertex`. They come sorted; spaghetti lists them in the order it
found the neighbours.

    iex> ntw = Networkex.Network.new([[{0, 0}, {1, 0}, {3, 0}], [{1, 0}, {1, 2}]])
    iex> Networkex.Network.arcs_at(ntw, 1)
    [{0, 1}, {1, 2}, {1, 3}]

# `contiguity_weights`

```elixir
@spec contiguity_weights(t(), keyword()) :: map()
```

Contiguity weights of the arcs (or, with `graph: true`, of the graph edges), after
`spaghetti.Network.contiguityweights`: two links are neighbours when they share a vertex.
`weighting: :lengths` weights each neighbour by its length (spaghetti's `weightings=True`);
the default `:binary` gives 1. `weighting: values`, one number per link (a list, `Nx` tensor or
`Explorer` series, in the order of `arcs` or `graph.edges`), weights each neighbour by its own
value, as spaghetti's `weightings` dict does.

Returns `%{n:, focal:, neighbor:, weight:}` by link index (the order of `arcs` or
`graph.edges`), the arrays `Spatex.Graph.from_arrays/3` takes; links without a neighbour are
islands.

# `counts_per_link`

```elixir
@spec counts_per_link(t(), Networkex.PointPattern.t(), keyword()) :: [
  non_neg_integer()
]
```

The number of observations of `pattern` on each arc (or, with `graph: true`, each graph edge),
aligned with `arcs` (or `graph.edges`), zeros included: the vector spaghetti's `Moran` analyses
(`spaghetti.Network.count_per_link`).

# `distance_band_weights`

```elixir
@spec distance_band_weights(t(), number(), keyword()) :: map()
```

Distance-band weights of the vertices, after `spaghetti.Network.distancebandweights`: two
vertices are neighbours (weight 1) when they are closer than `threshold` along the network.
Unlike spaghetti, vertices without a neighbour stay as islands (spaghetti leaves them out), so
the ids are the vertex ids. Option `:max_cells` bounds the distance matrix (default
25_000_000).

# `distance_matrix`

```elixir
@spec distance_matrix(t(), keyword()) :: [[float() | :infinity]]
```

Shortest-path distances between every pair of vertices (`spaghetti.Network.full_distance_matrix`),
as rows by vertex id; `:infinity` between components. Option `:max_cells` (default
25_000_000) bounds the size of the matrix.

# `extract_component`

```elixir
@spec extract_component(t(), non_neg_integer()) :: {t(), [non_neg_integer()]}
```

One connected component (by its label in `network.component_labels`) as a network of its own,
after `spaghetti.extract_component`. Returns `{component, vertex_ids}`: the component's
vertices are renumbered in the order of their ids in `ntw`, which `vertex_ids` lists (unlike
spaghetti, which keeps the old ids and labels).

# `from_binary`

```elixir
@spec from_binary(binary()) :: {:ok, t()} | {:error, String.t()}
```

A network from a binary of `to_binary/1`, or `{:error, reason}` when the binary is not one
(another format version, truncated, inconsistent).

# `global_auto_k`

```elixir
@spec global_auto_k(t(), Networkex.PointPattern.t(), keyword()) :: map()
```

The global auto K-function of `pattern` along the network with a Monte Carlo envelope, after
`spaghetti.Network.GlobalAutoK`.

At each of `nsteps` distances `r` from 0 to `:upperbound`, `K(r)` counts the ordered pairs of
observations closer than `r` along the network, over `n * lambda`, with `lambda` the
observations per unit of network length. The same curve is computed for each of
`:permutations` patterns of `n` observations simulated as in `simulate_observations/3`.

Returns `%{intensity:, upperbound:, xaxis:, observed:, simulated:, upper_envelope:,
lower_envelope:, seed:}` (`simulated` has one curve per permutation). The envelope is spaghetti's:
the largest simulated value at each step times `1 - threshold / 2` and the smallest times
`threshold / 2`.

## Options

  * `:nsteps` - the number of distances (default 10);
  * `:permutations` - the number of simulations (default 99);
  * `:threshold` - default 0.5;
  * `:upperbound` - the last distance (default the largest distance between two
    observations);
  * `:seed` - an integer seed for the simulations; without one a seed is drawn, and either
    way it is returned as `seed` (`nil` with `:simulations`);
  * `:simulations` - the positions of every simulation (lists of `n` numbers, as
    `simulate_observations/3`'s `:positions`), in place of drawing them.

# `load`

```elixir
@spec load(Path.t()) :: {:ok, t()} | {:error, File.posix() | String.t()}
```

Reads a network written by `save/2`, after `spaghetti.Network.loadnetwork`: `{:error, posix}`
when the file cannot be read, `{:error, reason}` when it is not a network.

# `nearest_neighbor_distances`

```elixir
@spec nearest_neighbor_distances(
  t(),
  Networkex.PointPattern.t(),
  Networkex.PointPattern.t() | nil,
  keyword()
) :: [{[non_neg_integer()], float()}]
```

The nearest observation(s) of `dest` (or of `source` itself) to each observation of `source`,
as `{indices, distance}` (all the indices at the minimum), after
`spaghetti.Network.nearestneighbordistances`. Options `:snap_dist` (default `false`) and
`:keep_zero_dist` (default `true`; with `false` zero distances, such as coincident
observations, are skipped).

# `new`

```elixir
@spec new([term()], keyword()) :: t()
```

Builds a network from `lines`. See the module documentation.

# `regular_lattice`

```elixir
@spec regular_lattice(
  {number(), number(), number(), number()},
  pos_integer(),
  keyword()
) :: [
  [{float(), float()}]
]
```

The lines of a regular lattice inside `bounds` (`{min_x, min_y, max_x, max_y}`), after
`spaghetti.regular_lattice`: `nh` lines across and `nv` (default `nh`) lines down, cut into
segments at every crossing; `exterior: true` adds the border. Returns two-point lines for
`new/2`.

As in spaghetti, the horizontal spacing comes from `nh` and the vertical from `nv`, but the
number of horizontal positions from `nv` and of vertical ones from `nh`: with `nh != nv` the
lattice does not reach every border.

    iex> Networkex.Network.regular_lattice({0, 0, 1, 1}, 1)
    [[{0.0, 0.5}, {0.5, 0.5}], [{0.5, 0.5}, {1.0, 0.5}], [{0.5, 0.0}, {0.5, 0.5}], [{0.5, 0.5}, {0.5, 1.0}]]

# `save`

```elixir
@spec save(t(), Path.t()) :: :ok | {:error, File.posix()}
```

Writes the network to `path` (`to_binary/1`), after `spaghetti.Network.savenetwork`.

# `shortest_paths`

```elixir
@spec shortest_paths(
  t(),
  Networkex.PointPattern.t(),
  Networkex.PointPattern.t() | nil
) :: [map()]
```

The shortest path between observations along the network, after spaghetti's
`allneighbordistances(gen_tree=True)` and `shortest_paths`: every pair `{i, j}` with `i < j` of
`source` without `dest`, otherwise every source with every destination, in that order.

Each path is `%{pair: {i, j}, via: {source_vertex, dest_vertex} | :same_arc, path: [{x, y}]}`:
the vertices of the two observations' arcs it leaves and enters by, and its coordinates from the
snapped source through the network vertices to the snapped destination. Two observations on the
same arc are joined directly. Of two routes of exactly the same length the one through the
vertex settled first (the smaller id among equal distances) is taken, which can differ from
spaghetti's choice.

# `simulate_observations`

```elixir
@spec simulate_observations(t(), pos_integer(), keyword()) ::
  Networkex.PointPattern.t()
```

`count` observations placed uniformly at random along the network, after
`spaghetti.Network.simulate_observations`. Returns a `Networkex.PointPattern` whose points are
on the network (snapping distances 0).

The arcs are laid end to end in `arc_draw_order/1` and each observation goes to a position
drawn uniformly along that length. As in spaghetti, the point sits that position's distance
back from the end of its arc's stretch, measured from the arc's first vertex (on a vertical
arc, from the lower one).

## Options

  * `:seed` - an integer seed for reproducible draws (`:rand`'s `:exsss`); random by default;
  * `:positions` - the positions themselves (`count` numbers from 0 to the network length),
    for example to replay spaghetti's own draws.

# `snap`

```elixir
@spec snap(t(), term()) :: Networkex.PointPattern.t()
```

Snaps `points` (`[{x, y}]`, `[[x, y]]`, an `{n, 2}` tensor or `{xs, ys}`) to the network:
each goes to the nearest point of its nearest arc. On a tie the arc with the smallest vertex
coordinates wins, as in spaghetti. Returns a `Networkex.PointPattern`.

# `spanning_tree`

```elixir
@spec spanning_tree(t(), keyword()) :: t()
```

The minimum spanning tree of the network (`maximum: true` for the maximum one), after
`spaghetti.spanning_tree` with its `"sort"` method: arcs join by increasing length (ties in
`arc_draw_order/1`) unless they close a cycle, and the tree is built anew from them, so its
vertex ids follow that order. A network without cycles is returned as it is.

# `split_arcs`

```elixir
@spec split_arcs(t(), number(), keyword()) :: t()
```

The network with every arc longer than the split cut into pieces, after
`spaghetti.Network.split_arcs`. `by: :distance` (default) cuts pieces of `split` length from
the start of each arc (the last one shorter); `by: :count` cuts each arc into `split` equal
pieces (an integer from 2 to 4_294_967_295).

New vertices get the next ids, arc by arc; a new point exactly on an existing vertex reuses
it. As in spaghetti a vertical arc is walked upwards, and the pieces are placed by adding up
their length, so rounding can leave a last piece of the order of 1e-16 of the arc.
Observations snapped to the original network are not carried over: snap them again with
`snap/2`. Unlike spaghetti's split network, the result also has its `graph`.

## Size and time

Option `:max_arcs` (default 250_000, at most 67_108_864) is a hard limit: a split that
returns has at most that many arcs. The arcs are counted from the arc lengths before anything
is allocated, and a split whose count exceeds `:max_arcs` raises an `ArgumentError`. The
count gives an arc longer than the distance `ceil(length / split)` pieces and an arc split by
count `split` pieces, each plus one for the tiny last piece rounding can leave, and every
other arc 1, so it can exceed the result by up to one arc per arc cut. A split by count whose
pieces would be shorter than the smallest normal float (about 2.2e-308) raises too. Without
the limit, a split distance far below the arc lengths would allocate gigabytes in native
code, which cannot be interrupted. 250_000 arcs take a few hundred megabytes of memory while
the result is built; raise the limit for larger splits.

`:max_arcs` bounds memory, not time. Building the graph of the split network takes time that
grows with the square of its arcs: on a recent x86-64 machine about a third of a second for
25_000 arcs, 3 seconds for 100_000 and nearly 20 seconds at the default limit, during which
a dirty CPU scheduler is busy and the call cannot be interrupted. See "Known limitations" in
the architecture guide.

# `to_binary`

```elixir
@spec to_binary(t()) :: binary()
```

The network as a binary, after `spaghetti.Network.savenetwork`: `from_binary/1` reads it back,
in this or another VM. `:erlang.term_to_binary/1` is not enough, because a network holds a
reference to Rust memory that does not outlive the VM.

The binary is Networkex's own little-endian format (version 1): the vertices, arcs, arc lengths,
the arc order and the rounding options. Adjacency, components and the graph are derived again on
load, as when the network was built. Point patterns (`Networkex.PointPattern`) are plain data:
keep them with `:erlang.term_to_binary/1`.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
