# `Spatex.Region`
[🔗](https://github.com/CountlinkX-Solutions/spatex/blob/v0.2.1/lib/spatex/region.ex#L1)

Regionalization after `spopt` 0.8.0: group areas into contiguous regions.

| Function | Method | Parity with spopt |
|---|---|---|
| `skater/3` | SKATER minimum-spanning-forest pruning | exact labels |
| `ward_spatial/3` | Ward clustering constrained by the graph | exact labels and tree |
| `sa3/3` | SA3: spatially constrained Ward tree, HDBSCAN-style (EOM or leaf) extraction, with noise | exact labels and linkage |
| `spenc/3` | Spenc: spatially encouraged spectral clustering | exact affinity, embedding and `:hierarchical` labels; randomized labels statistically |
| `region_kmeans/3` | Region-K-Means (seeded growth, then centroid moves) | exact labels for the same seeds |
| `azp/3` | basic AZP local search | validity and objective, not labels |
| `max_p/3` | Max-p-regions (construction + annealing) | validity and objective, not labels |
| `random_region/2`, `random_regions/2` | random (contiguous) partitions | distributions, not labels |

Helpers: `objective/3`, `contiguous?/2`, `relabel/1`, `standardize/1`.

## Inputs

`attrs` is the attribute table of the areas, in graph order: a list of columns (each a list,
`Nx` vector or `Explorer.Series`), a single column, a map `name => column`, an `{n, m}`
`Nx.Tensor` or an `Explorer.DataFrame` (all its columns). **Attributes are never scaled
implicitly**, exactly like spopt: columns on different scales weigh differently. Call
`standardize/1` first when that is not what you want.

`graph` is a `Spatex.Graph`. Only its pattern of non-self links with non-zero weight matters;
weights are ignored (`spenc/3` is the exception: it multiplies the affinity by them). The pattern must be symmetric, or pass `symmetrize: true` to use
`A or A'` (`ward_spatial/3` always symmetrizes, like scikit-learn). Islands are allowed:
every method defines what it does with several connected components.

Labels are 0-based integers. spopt returns floats for AZP and 1-based labels for Max-p.

## Determinism

`skater/3`, `ward_spatial/3`, `sa3/3` and `region_kmeans/3` (given `seeds:`) are deterministic.
The randomized parts (`azp/3`, `max_p/3`, `random_region/2`, `random_regions/2`,
`region_kmeans/3` with `seed:`, and the label assignment of `spenc/3`) use ChaCha8
streams derived from `seed:`: a seed gives the same result on every run and thread count, but
does not reproduce numpy's generator, so results differ from spopt's for the same seed.

## Memory

No `n x n` matrix is built (spopt builds dense distance matrices for SKATER and Max-p).

# `attrs`

```elixir
@type attrs() :: term()
```

# `labels`

```elixir
@type labels() :: [non_neg_integer()]
```

# `azp`

```elixir
@spec azp(attrs(), Spatex.Graph.t(), keyword()) :: Spatex.Region.AZP.t()
```

AZP (automatic zoning procedure): starting from `initial` or a random contiguous partition,
boundary areas move between neighboring regions to lower the pairwise within-region
dissimilarity.

`:method` selects the local search:

  * `:basic` (default, spopt's `AZP`) - boundary areas move to a randomly chosen neighboring
    region whenever the objective does not increase, until a full pass brings no improvement.
  * `:tabu` (`AZPBasicTabu`) - every iteration makes the best move that is not tabu (even a
    worse one), keeps the last `:tabu_length` (default `10`) reverse moves tabu unless they
    improve the objective (aspiration), and stops once a partition has been visited
    `:repetitions` (default `5`) times; `:max_iterations` defaults to `10 * n` here.
  * `:annealing` (`AZPSimulatedAnnealing`) - basic AZP that also accepts a worse move with
    probability `exp(-diff / T)`; a run ends after `:sa_moves_term` (default `10`) such
    moves. `T` starts at `:init_temperature` (required) and is multiplied by
    `:cooling_factor` (default `0.85`, in `(0, 1)`) each round; the search stops when a
    partition is visited `:repetitions` (default `5`) times or after `:nonmoving_steps`
    (default `3`) rounds without a move.

spopt 0.8.0 crashes on the tabu and annealing classes; they follow the algorithm description
and spopt's intent as summarized above, and return the best partition they visit. For every method
a final deterministic pass makes the result a strict local optimum: no single feasible move
lowers the objective (spopt's loop only approximates this). `n_clusters: 1` returns one
region where spopt crashes.

## Options

  * `:n_clusters` - required; must be at least the number of connected components.
  * `:seed` - integer seed (default `nil`: a random seed, recorded in `seed`).
  * `:initial` - starting labels (any labels; exactly `n_clusters` distinct, each region
    contiguous).
  * `:metric` - `:euclidean` (default, spopt's), `:manhattan` or `:sqeuclidean`.
  * `:max_iterations` - cap on accepted moves (default `1000 * n`; tabu: on iterations,
    default `10 * n`).
  * `:symmetrize` - use `A or A'` for an asymmetric graph.
  * `:method` and its options, see above. Reactive tabu is not provided.

# `contiguous?`

```elixir
@spec contiguous?([term()], Spatex.Graph.t()) :: boolean()
```

True when every region of `labels` induces a connected subgraph of `graph`.

## Examples

    iex> g = Spatex.Graph.from_arrays([0, 1, 1, 2], [1, 0, 2, 1])
    iex> {Spatex.Region.contiguous?([0, 0, 1], g), Spatex.Region.contiguous?([0, 1, 0], g)}
    {true, false}

# `max_p`

```elixir
@spec max_p(attrs(), Spatex.Graph.t(), keyword()) :: Spatex.Region.MaxP.t()
```

Max-p-regions: the largest number `p` of contiguous regions whose total of a spatially
extensive attribute reaches a threshold, then the within-region dissimilarity (cityblock on
`attrs`) is lowered by simulated annealing with a tabu list.

The construction phase grows regions from randomly ordered areas until they reach the
threshold; areas left over are attached by similarity to one of the `top_n` nearest
neighboring areas' regions. The partitions reaching the highest `p` are each annealed
`max_iterations_sa` times and the best result is returned.

## Options

  * `:threshold_variable` - required, the extensive attribute of every area (a column).
  * `:threshold` - required, the minimum total per region.
  * `:top_n` - areas considered for each enclave (default `2`; counts neighboring *areas*,
    so two neighbors in one region take two slots, as in spopt).
  * `:max_iterations_construction` - construction iterations (default `99`).
  * `:max_iterations_sa` - independent annealing runs per candidate (default `10`).
  * `:seed` - integer seed (default `nil`: a random seed, recorded in `seed`).
  * `:policy` - what to do with connected components whose total is below the threshold:
    `:single` (default) links each other component to the largest by one edge between their
    nearest areas, `:multiple` links every area of it to its nearest area in the largest,
    both needing `:coords`; `:drop` removes them (their labels are `nil`); `:keep` raises.
    Joins apply to every non-largest component once any component is infeasible.
  * `:coords` - one `{x, y}` per area, used by `:single` and `:multiple`.
  * `:symmetrize` - use `A or A'` for an asymmetric graph.

Raises when no component reaches the threshold. The annealing parameters (`alpha = 0.998`,
tabu length 10, `n` non-improving moves) are spopt's fixed constants.

# `objective`

```elixir
@spec objective(attrs(), [term()], keyword()) :: float()
```

Within-region heterogeneity of a partition.

## Options

  * `:kind` - `:pairwise` (default): the sum over regions of the distance between every pair
    of areas (spopt's `ObjectiveFunctionPairwise`, used by AZP and Max-p); `:center`: the sum
    of the distances of every area to its region's mean (`ObjectiveFunctionCenter`, SKATER's
    score).
  * `:metric` - `:manhattan` (default), `:euclidean` or `:sqeuclidean`. Use
    `kind: :center, metric: :sqeuclidean` for the within-region sum of squared deviations.

`labels` may use any terms as region ids.

## Examples

    iex> Spatex.Region.objective([[0.0, 1.0, 5.0, 7.0]], [:a, :a, :b, :b])
    3.0

# `random_region`

```elixir
@spec random_region(pos_integer() | Spatex.Graph.t(), keyword()) ::
  Spatex.Region.RandomRegion.t()
```

One random partition of `n` areas into regions, after spopt's `RandomRegion`.

`area` is the number of areas, or a `Spatex.Graph` to require every region to be contiguous
on it. Without a graph, contiguity is ignored: the areas are shuffled and cut at random
breaks. With a graph, regions are grown one at a time (largest cardinality first) from
random areas; when the remaining areas cannot complete a region, an area on the border of an
existing region is swapped out of it (keeping that region connected) and offered again. The
construction is retried up to `:maxiter` times; if it never succeeds the result has
`feasible: false`, as in spopt, instead of raising.

Without `:cardinality` the sizes are random: `:num_regions` regions (drawn between `2` and
`n - 1` when omitted) whose sizes come from `num_regions - 1` distinct random cut points
between `1` and `n - 2`, so the last cut region always holds at least two areas (spopt's
scheme).

## Options

  * `:num_regions` - number of regions. With `:cardinality` it must equal its length. Without
    it, at most `n - 1` (spopt loops forever for more).
  * `:cardinality` - region sizes, positive integers adding up to `n`. The regions are
    built largest first; without a graph they keep the given order.
  * `:maxiter` - attempts at a contiguous solution (default `1000`; only with a graph).
  * `:compact` - grow compact regions by exhausting the current frontier before opening
    a new one (default `false`; only with a graph).
  * `:max_swaps` - cap on swaps per attempt (default `1_000_000`; only with a graph). spopt
    applies the cap between swaps only and can loop forever when no swap is possible; Spatex
    also stops inside a swap search, and then retries.
  * `:seed` - integer seed (default `nil`: a random seed, recorded in `seed`). ChaCha8
    streams: a seed gives the same partition on every run and platform but not numpy's.
  * `:symmetrize` - use `A or A'` for an asymmetric graph.

Labels are 0-based and areas are positions in the graph (or `0..n-1`); spopt takes arbitrary
area ids and requires `area_ids` to equal the weights' `id_order`.

## Examples

    iex> r = Spatex.Region.random_region(6, cardinality: [3, 2, 1], seed: 1)
    iex> {r.feasible, Enum.map(r.regions, &length/1), r.n_regions}
    {true, [3, 2, 1], 3}
    iex> r.labels |> Enum.sort()
    [0, 0, 0, 1, 1, 2]

# `random_regions`

```elixir
@spec random_regions(pos_integer() | Spatex.Graph.t(), keyword()) ::
  Spatex.Region.RandomRegions.t()
```

`:permutations` random partitions, after spopt's `RandomRegions`.

Takes the options of `random_region/2` (with `:maxiter` defaulting to spopt's `100` here)
and `:permutations` (default `99`). Permutation `i` draws from ChaCha8 stream `i` of
`seed:`, so the result does not depend on the thread count, and the first permutation equals
`random_region/2` with the same seed. Returns the solutions and the feasible ones.

## Examples

    iex> r = Spatex.Region.random_regions(8, num_regions: 3, permutations: 4, seed: 7)
    iex> {length(r.solutions), length(r.feasible_solutions)}
    {4, 4}

# `region_kmeans`

```elixir
@spec region_kmeans(attrs(), Spatex.Graph.t(), keyword()) ::
  Spatex.Region.RegionKMeans.t()
```

Region-K-Means: regions grow simultaneously from `n_clusters` seed areas, each step adding to
every region the neighboring area closest to its centroid; then areas move to the nearest
centroid while both regions stay contiguous.

## Options

  * `:seeds` - the seed areas (0-based indices, distinct); region `i` starts at `seeds[i]`.
    With the seeds spopt drew, the labels, centroids and `iters` are identical to its.
  * `:seed` - when `:seeds` is absent, draw the seeds from this integer (default `nil`: a
    random seed, recorded in `seed`), one
    per connected component first. These are not numpy's draws.
  * `:n_clusters` - required unless `:seeds` is given.
  * `:max_iterations` - cap on the improvement loop (default `10 * n * n_clusters`); a
    warning is set when it is hit. spopt has no cap and is not proven to terminate.
  * `:symmetrize` - use `A or A'` for an asymmetric graph.

Raises `ArgumentError` when a connected component contains no seed (spopt loops forever).

## Examples

    iex> g = Spatex.Graph.from_arrays([0, 1, 1, 2, 2, 3], [1, 0, 2, 1, 3, 2])
    iex> r = Spatex.Region.region_kmeans([[1.0, 1.1, 9.0, 9.2]], g, seeds: [0, 3])
    iex> r.labels
    [0, 0, 1, 1]

# `relabel`

```elixir
@spec relabel([term()]) :: labels()
```

Renumbers labels `0..k-1` by order of first appearance, so partitions compare regardless of
numbering.

## Examples

    iex> Spatex.Region.relabel([5, 5, 2, 9, 2])
    [0, 0, 1, 2, 1]

# `sa3`

```elixir
@spec sa3(attrs(), Spatex.Graph.t(), keyword()) :: Spatex.Region.Sa3.t()
```

SA3 (spatial adaptive agglomerative aggregation): spatially constrained Ward clustering
whose merge tree is cut with HDBSCAN's cluster extraction, giving multiscale contiguous
clusters and noise.

Every connected component of the graph with more than `min_cluster_size` areas gets its own
Ward tree (as in `ward_spatial/3`); if a merge distance drops below the previous one, spopt
sets it to the previous plus `0.01` (repeated until the tree is monotone, and Spatex does the
same). The tree is condensed with `min_cluster_size` (lambda is the inverse of the distance)
and the clusters are the excess-of-mass selection (`:eom`) or the leaves of the condensed
tree (`:leaf`). Areas in no cluster, and whole components with at most `min_cluster_size`
areas, are noise: label `-1`. Cluster numbers continue across components. Labels and the
linkage match spopt exactly.

## Options

  * `:min_cluster_size` - minimum number of areas of a cluster, an integer `>= 2` (default
    `15`, spopt's). spopt also accepts smaller values; see the known deviations.
  * `:extraction` - `:eom` (default) or `:leaf`.

## Examples

    iex> g = Spatex.Graph.from_arrays([0, 1, 1, 2, 3, 4, 4, 5, 2, 3], [1, 0, 2, 1, 4, 3, 5, 4, 3, 2])
    iex> r = Spatex.Region.sa3([[0.0, 0.1, 0.2, 10.0, 10.1, 10.2]], g, min_cluster_size: 3)
    iex> {r.labels, r.n_clusters, r.n_noise}
    {[1, 1, 1, 0, 0, 0], 2, 0}

# `skater`

```elixir
@spec skater(attrs(), Spatex.Graph.t(), keyword()) :: Spatex.Region.Skater.t()
```

SKATER: spatial `k`luster analysis by tree edge removal.

Builds a minimum spanning forest over the graph, weighting each link by the dissimilarity of
its two areas, then repeatedly deletes the forest edge whose removal gives the lowest
whole-map score (the sum over regions of the distance of every area to its region mean) until
`n_clusters` regions remain.

## Options

  * `:n_clusters` - required, between 1 and the number of areas.
  * `:floor` - minimum number of **areas** per region (default `0.0`: no floor). A cut leaving
    any region below the floor is not allowed; when no cut is left the result has fewer
    regions and `warnings` says so.
  * `:islands` - `:increase` (default) adds the number of connected components to
    `n_clusters`, so `n_clusters: 5` on a graph with two components yields seven regions
    (spopt's behavior); `:ignore` counts the components towards `n_clusters`.
  * `:trace` - keep the labeling after every cut in `trace` (default `false`).
  * `:dissimilarity` - `:manhattan` (default, spopt's) or `:euclidean`; used for the
    spanning forest and the score.
  * `:zero_dissimilarity` - `:keep` (default) or `:drop`. spopt silently removes links
    between areas with identical attributes, which splits the graph into false islands and
    raises `n_clusters`; Spatex keeps them. `:drop` reproduces spopt.
  * `:symmetrize` - use `A or A'` for an asymmetric graph.

The edge to cut is the first, in row-major order, with the strictly lowest score. Scores that
differ by less than about `1.0e-12` (relative) may be ranked differently from spopt because
floating-point summation order differs.

## Examples

    iex> g = Spatex.Graph.from_arrays([0, 1, 1, 2, 2, 3], [1, 0, 2, 1, 3, 2])
    iex> r = Spatex.Region.skater([[1.0, 1.1, 9.0, 9.2]], g, n_clusters: 2)
    iex> r.labels
    [0, 0, 1, 1]

# `spenc`

```elixir
@spec spenc(attrs(), Spatex.Graph.t(), keyword()) :: Spatex.Region.Spenc.t()
```

Spenc: spatially encouraged spectral clustering (Wolf 2018), spopt's `Spenc`.

The attribute affinity (`:affinity` kernel of the attributes) is multiplied elementwise by the
graph's **weights**, so only neighboring areas are similar; the affinity's normalized Laplacian
is embedded with its `n_clusters` smallest eigenvectors, divided by the square root of the
affinity degrees, and the areas are clustered in that embedding. Unlike the other methods in
this module, the graph weights matter (use a binary graph for spopt's default `W`), and the
affinity must be symmetric.

The affinity matrix, the normalized Laplacian, its eigenvalues and the embedding (up to the
sign of each eigenvector, which is normalized as spopt does) are deterministic and match
spopt. spopt finds the eigenpairs with ARPACK; Spatex uses a dense symmetric eigensolver, which
gives the same eigenpairs but needs an `n x n` matrix (n up to 5000). Label assignment is
randomized as in spopt, with ChaCha8 instead of numpy's generator, so labels match spopt's
statistically and `:hierarchical` exactly. **Clusters are not guaranteed to be contiguous.**

## Options

  * `:n_clusters` - number of clusters, `1 <= k < n` (default `5`, spopt's), or `:infinity`,
    which, as in spopt, selects `assign_labels: :hierarchical` and keeps cutting while cuts
    satisfy `:floor`.
  * `:affinity` - `:rbf` (default), `:laplacian`, `:linear`, `:polynomial` (`:poly`),
    `:sigmoid`, `:cosine`, `:nearest_neighbors` or `:precomputed`. These are the
    `sklearn.metrics.pairwise_kernels` names; `:nearest_neighbors` (a symmetrized `n_neighbors`
    connectivity graph that includes each area itself) and `:precomputed` (`attrs` is the
    `n x n` affinity) ignore the graph weights, as in spopt. Similarity kernels must give
    non-negative values; this is not checked, as in spopt.
  * `:gamma` (default `1.0`), `:degree` (`3`), `:coef0` (`1`), `:n_neighbors` (`10`) - kernel
    parameters as in scikit-learn.
  * `:assign_labels` - `:discretize` (default; Yu and Shi's rotation, random start row),
    `:kmeans` (k-means++, one run, like spopt's `KMeans(n_clusters)`; `n_init` is not used by
    spopt either) or `:hierarchical` (Shi and Malik's recursive bipartition with the Fiedler
    vector cut by grid search; deterministic). spopt 0.8.0 cannot run `:hierarchical` (it
    raises `TypeError`); Spatex implements what that code intends. Like spopt it raises when
    a cut leaves fewer than three areas to split, or when no cut is accepted.
  * `:floor`, `:floor_weights`, `:grid_resolution` - `:hierarchical` only: lower limit on the
    (weighted) size of every part (default `0`, weights all `1`) and grid points of the cut
    search (`100`).
  * `:eigen_solver`, `:eigen_tol`, `:n_init` - accepted for spopt compatibility and ignored,
    as spopt ignores them (`nil`, `:arpack` and `:lobpcg` are accepted; `:amg` raises).
  * `:seed` - non-negative integer for the random stages; `nil` (default) draws one, recorded
    in the result.
  * `:keep_embedding` (default `true`) and `:keep_affinity` (default `false`) - keep the
    matrices in the result: `true` (lists of rows), `false` or `:tensor` (`Nx`).

## Examples

    iex> g = Spatex.Graph.from_arrays([0, 1, 1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 6, 7],
    ...>   [1, 0, 2, 1, 3, 2, 4, 3, 5, 4, 6, 5, 7, 6])
    iex> x = [[0.0, 0.1, 0.2, 0.3, 3.0, 3.1, 3.2, 3.3]]
    iex> r = Spatex.Region.spenc(x, g, n_clusters: 2, gamma: 0.05, seed: 1)
    iex> Spatex.Region.relabel(r.labels)
    [0, 0, 0, 0, 1, 1, 1, 1]

# `standardize`

```elixir
@spec standardize(attrs()) :: [[float()]]
```

Z-scores every column (`(x - mean) / std`, population standard deviation). Constant columns
become zeros. Returns a list of columns, ready for the region functions.

## Examples

    iex> Spatex.Region.standardize([[1.0, 3.0]])
    [[-1.0, 1.0]]

# `ward_spatial`

```elixir
@spec ward_spatial(attrs(), Spatex.Graph.t(), keyword()) :: Spatex.Region.Ward.t()
```

Spatially constrained Ward clustering: agglomerative clustering that may only merge
neighboring clusters (scikit-learn's `AgglomerativeClustering` with `linkage="ward"` and the
graph as connectivity).

When the graph has several connected components it is completed first: for every pair of
components the two most similar areas **in attribute space** (not geography) are linked, as
scikit-learn does, and `n_connected_components` and `warnings` report it.

Cluster numbers follow scikit-learn: they come from the cut of the merge tree, or, when
`n_clusters >= max(100, 0.02 * n)` and the tree is stopped early, from the rank of each
cluster's head node. Use `relabel/1` for first-appearance numbering.

## Options

  * `:n_clusters` - required.

## Examples

    iex> g = Spatex.Graph.from_arrays([0, 1, 1, 2, 2, 3], [1, 0, 2, 1, 3, 2])
    iex> r = Spatex.Region.ward_spatial([[1.0, 1.1, 9.0, 9.2]], g, n_clusters: 2)
    iex> Spatex.Region.relabel(r.labels)
    [0, 0, 1, 1]

---

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