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).
Summary
Functions
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.
True when every region of labels induces a connected subgraph of graph.
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.
Within-region heterogeneity of a partition.
One random partition of n areas into regions, after spopt's RandomRegion.
:permutations random partitions, after spopt's RandomRegions.
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.
Renumbers labels 0..k-1 by order of first appearance, so partitions compare regardless of
numbering.
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.
SKATER: spatial kluster analysis by tree edge removal.
Spenc: spatially encouraged spectral clustering (Wolf 2018), spopt's Spenc.
Z-scores every column ((x - mean) / std, population standard deviation). Constant columns
become zeros. Returns a list of columns, ready for the region functions.
Spatially constrained Ward clustering: agglomerative clustering that may only merge
neighboring clusters (scikit-learn's AgglomerativeClustering with linkage="ward" and the
graph as connectivity).
Types
@type attrs() :: term()
@type labels() :: [non_neg_integer()]
Functions
@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'sAZP) - 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(default10) reverse moves tabu unless they improve the objective (aspiration), and stops once a partition has been visited:repetitions(default5) times;:max_iterationsdefaults to10 * nhere.:annealing(AZPSimulatedAnnealing) - basic AZP that also accepts a worse move with probabilityexp(-diff / T); a run ends after:sa_moves_term(default10) such moves.Tstarts at:init_temperature(required) and is multiplied by:cooling_factor(default0.85, in(0, 1)) each round; the search stops when a partition is visited:repetitions(default5) times or after:nonmoving_steps(default3) 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 (defaultnil: a random seed, recorded inseed).:initial- starting labels (any labels; exactlyn_clustersdistinct, each region contiguous).:metric-:euclidean(default, spopt's),:manhattanor:sqeuclidean.:max_iterations- cap on accepted moves (default1000 * n; tabu: on iterations, default10 * n).:symmetrize- useA or A'for an asymmetric graph.:methodand its options, see above. Reactive tabu is not provided.
@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}
@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 (default2; counts neighboring areas, so two neighbors in one region take two slots, as in spopt).:max_iterations_construction- construction iterations (default99).:max_iterations_sa- independent annealing runs per candidate (default10).:seed- integer seed (defaultnil: a random seed, recorded inseed).: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,:multiplelinks every area of it to its nearest area in the largest, both needing:coords;:dropremoves them (their labels arenil);:keepraises. Joins apply to every non-largest component once any component is infeasible.:coords- one{x, y}per area, used by:singleand:multiple.:symmetrize- useA 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.
Within-region heterogeneity of a partition.
Options
:kind-:pairwise(default): the sum over regions of the distance between every pair of areas (spopt'sObjectiveFunctionPairwise, 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),:euclideanor:sqeuclidean. Usekind: :center, metric: :sqeuclideanfor 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
@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:cardinalityit must equal its length. Without it, at mostn - 1(spopt loops forever for more).:cardinality- region sizes, positive integers adding up ton. The regions are built largest first; without a graph they keep the given order.:maxiter- attempts at a contiguous solution (default1000; only with a graph).:compact- grow compact regions by exhausting the current frontier before opening a new one (defaultfalse; only with a graph).:max_swaps- cap on swaps per attempt (default1_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 (defaultnil: a random seed, recorded inseed). ChaCha8 streams: a seed gives the same partition on every run and platform but not numpy's.:symmetrize- useA 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]
@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}
@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); regionistarts atseeds[i]. With the seeds spopt drew, the labels, centroids anditersare identical to its.:seed- when:seedsis absent, draw the seeds from this integer (defaultnil: a random seed, recorded inseed), one per connected component first. These are not numpy's draws.:n_clusters- required unless:seedsis given.:max_iterations- cap on the improvement loop (default10 * n * n_clusters); a warning is set when it is hit. spopt has no cap and is not proven to terminate.:symmetrize- useA 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]
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]
@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(default15, 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}
@spec skater(attrs(), Spatex.Graph.t(), keyword()) :: Spatex.Region.Skater.t()
SKATER: spatial kluster 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 (default0.0: no floor). A cut leaving any region below the floor is not allowed; when no cut is left the result has fewer regions andwarningssays so.:islands-:increase(default) adds the number of connected components ton_clusters, son_clusters: 5on a graph with two components yields seven regions (spopt's behavior);:ignorecounts the components towardsn_clusters.:trace- keep the labeling after every cut intrace(defaultfalse).: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 raisesn_clusters; Spatex keeps them.:dropreproduces spopt.:symmetrize- useA 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]
@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(default5, spopt's), or:infinity, which, as in spopt, selectsassign_labels: :hierarchicaland keeps cutting while cuts satisfy:floor.:affinity-:rbf(default),:laplacian,:linear,:polynomial(:poly),:sigmoid,:cosine,:nearest_neighborsor:precomputed. These are thesklearn.metrics.pairwise_kernelsnames;:nearest_neighbors(a symmetrizedn_neighborsconnectivity graph that includes each area itself) and:precomputed(attrsis then x naffinity) ignore the graph weights, as in spopt. Similarity kernels must give non-negative values; this is not checked, as in spopt.:gamma(default1.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'sKMeans(n_clusters);n_initis 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 raisesTypeError); 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-:hierarchicalonly: lower limit on the (weighted) size of every part (default0, weights all1) 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,:arpackand:lobpcgare accepted;:amgraises).:seed- non-negative integer for the random stages;nil(default) draws one, recorded in the result.:keep_embedding(defaulttrue) and:keep_affinity(defaultfalse) - keep the matrices in the result:true(lists of rows),falseor: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]
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]]
@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]