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

Point pattern analysis, after `pointpats` 2.6.0: centrography, Ripley's distance functions
with seeded simulation envelopes, random point processes and quadrat statistics.

Points are `[{x, y}]`, `[[x, y]]`, an `{n, 2}` `Nx.Tensor` or a pair `{xs, ys}`
(see `Spatex.Input`). Non-finite coordinates raise `ArgumentError`.

## Centrography

`mean_center/1`, `weighted_mean_center/2`, `manhattan_median/1`, `euclidean_median/1`,
`std_distance/1`, `ellipse/2`, `dtot/2`, `hull/1`, `mbr/1`, `minimum_rotated_rectangle/2`,
`minimum_bounding_circle/1` (`skyum/1`), plus the bundle `centrography/1`.

`alpha_shape/2` and `alpha_shape_auto/2` return the alpha shape of the points as WKB polygons.

The standard distance uses pointpats' raw-moment formula, which loses digits for large
coordinate offsets (UTM metres, say); center the coordinates first when that matters. The
Euclidean median is the exact Weiszfeld optimum, while pointpats stops a BFGS search at a
gradient tolerance of `1.0e-5`, so the two agree only to about four digits.

## Distance statistics

`g/2`, `f/2`, `j/2`, `k/2` and `l/2` return `{support, statistic}`; `g_test/2`, `f_test/2`,
`j_test/2`, `k_test/2` and `l_test/2` return a `Spatex.PointPats.DistanceTest` with a seeded
Monte Carlo p-value and an envelope. The estimators are **uncorrected for edge effects**,
exactly as in pointpats 2.6.0, which has no edge correction.

Quirks of pointpats that are replicated on purpose:

  * The default `support` is 20 values from 0 to the largest nearest-neighbour distance of the
    pattern, for K and L as well.
  * `g/2` and `f/2` normalize by the number of distances inside the support and start at 0.
  * `k/2` counts pairs strictly closer than each distance and always uses the bounding box of
    the points for the area, also inside the simulations of `k_test/2`.
  * The empty-space points of `f_test/2` and `j_test/2` are always drawn from the bounding box
    of the observed pattern.
  * The p-value is `min(p, 1 - p)`, so it is at most 0.5 and may be exactly 0.0.

Random draws use ChaCha8 streams derived from `(seed, simulation)`: results are reproducible
per `seed:` and independent of the number of threads, but they do not reproduce numpy's
generators. Compare simulated quantities with pointpats statistically.

### The `support` option

`nil` (20 values), an integer `m >= 2` (`m` values), `{stop}`, `{start, stop}`,
`{start, stop, count}` (the third element is a count of values) or an ascending list.

### The `hull` option

The simulation window: `:bbox` (default, bounding box of the points), `:convex` (their convex
hull) or `{xmin, ymin, xmax, ymax}`. pointpats' `"alpha"` hull is not supported.

## Random processes and quadrat statistics

`poisson/2`, `cluster_poisson/2`, `normal/2`, `cluster_normal/2`, `strauss/2` and `quadrat_test/2` (rectangle and hexagon grids).

# `curve`

```elixir
@type curve() :: {[float()], [float() | :nan | :infinity | :neg_infinity]}
```

# `point`

```elixir
@type point() :: {number(), number()}
```

# `points`

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

# `support`

```elixir
@type support() :: nil | pos_integer() | tuple() | [number()]
```

# `window`

```elixir
@type window() ::
  {number(), number(), number(), number()} | [point()] | {:convex, [point()]}
```

# `alpha_shape`

```elixir
@spec alpha_shape(points(), number()) :: [binary()]
```

Alpha shape of the points (`libpysal.cg.alpha_shape`): the polygons of the Delaunay triangles
whose circumradius is below `1 / alpha`.

Returns a list of WKB polygons (little-endian, rings closed), `[]` when no triangle qualifies.
A shape can have several polygons (separate clusters, an island inside a hole) and polygons with
holes. Each polygon has its shell clockwise and its holes counter-clockwise, as GEOS returns
them, every ring starting at its smallest vertex; polygons are ordered by their first vertex.
Larger `alpha` gives tighter shapes: `0` is the convex hull and a very large value is empty.

Fewer than four points give their convex hull whatever `alpha` is (`[]` when they are
collinear), as libpysal does. Duplicate points are ignored. Four or more points that are
collinear, or fewer than three distinct points, raise `ArgumentError`, where libpysal raises
`QhullError`; so do a negative or non-numeric `alpha` and non-finite coordinates.

## Examples

    iex> pts = [{0.0, 0.0}, {4.0, 0.3}, {4.2, 4.0}, {0.1, 3.9}, {2.1, 1.9}]
    iex> [<<1, 3, 0, 0, 0, 1, 0, 0, 0, 5, 0, 0, 0, _::binary>>] = Spatex.PointPats.alpha_shape(pts, 0.0)
    iex> Spatex.PointPats.alpha_shape(pts, 1.0e9)
    []

# `alpha_shape_auto`

```elixir
@spec alpha_shape_auto(points(), keyword()) ::
  binary() | {binary(), float()} | {binary(), float(), [{float(), float()}]}
```

Alpha shape with an automatically chosen alpha (`libpysal.cg.alpha_shape_auto`): the tightest
shape that is a single polygon containing every point.

The triangles' circumradii are ranked from the largest down; every `:step`-th radius gives a
candidate shape (the triangles with a smaller radius), and the search stops at the first
candidate that is not one hole-free polygon with all the points, returning the previous one.
Returns the WKB polygon (shell clockwise, starting at its smallest vertex).

Options:

  * `:step` - how many radii to jump per candidate, a positive integer (default `1`).
  * `:return_radius` - return `{wkb, radius}`, the circumradius whose threshold gave the
    polygon (default `false`).
  * `:return_circles` - return `{wkb, radius, centers}` where `centers` has one `{x, y}` per
    boundary edge of the shell, in ring order: the centre, on the left of the edge, of the circle
    of that radius through its ends (`construct_bounding_circles`). Implies `:return_radius`.

Needs three distinct points that are not collinear. The search compares
`radius < 1 / (1 / radius - eps)` exactly as libpysal does, so which triangle is kept at a
candidate depends on the last bit of its radius; when that makes even the first candidate
invalid, `ArgumentError` is raised (libpysal returns the first polygon of the convex hull
minus its largest triangle, or raises `UnboundLocalError` for the radius).

## Examples

    iex> pts = [{0.0, 0.0}, {4.0, 0.3}, {4.2, 4.0}, {0.1, 3.9}, {2.1, 1.9}]
    iex> {wkb, radius} = Spatex.PointPats.alpha_shape_auto(pts, return_radius: true)
    iex> is_binary(wkb) and radius > 0
    true

# `centrography`

```elixir
@spec centrography(points()) :: map()
```

Bundle of the common summaries as a map: `:mean_center`, `:manhattan_median`,
`:std_distance`, `:ellipse`, `:hull` and `:mbr`.

# `cluster_normal`

```elixir
@spec cluster_normal(window(), keyword()) :: [point()] | [[point()]]
```

Normal cluster process: `:n_seeds` cluster centres uniform in the window, each followed by
normal points around it (truncated to the window); points are ordered cluster by cluster
(sizes as numpy's `array_split`).

Takes the window and the `:size` and `:seed` options of `normal/2`, plus

  * `:n_seeds` - number of clusters (default 2).
  * `:cov` - as in `normal/2`, shared by all clusters. Default: the squared mean distance
    between the centres of the replication (pointpats computes it once, from the first
    replication, and reuses it; Spatex keeps replications independent). Required when
    `:n_seeds` is 1.

# `cluster_poisson`

```elixir
@spec cluster_poisson(window(), keyword()) :: [point()] | [[point()]]
```

Poisson cluster process: `:n_seeds` parent points, each followed by uniform children within
`:cluster_radius` of the parent and inside the window; points are ordered cluster by cluster
(sizes as numpy's `array_split`).

Takes the window and the `:size`, `:intensity` and `:seed` options of `poisson/2`, plus

  * `:n_seeds` - number of clusters (default 2).
  * `:cluster_radius` - a radius, or one per seed. Default: half the smallest distance
    between the parents (required when `n_seeds` is 1).

# `dtot`

```elixir
@spec dtot({number(), number()}, points()) :: float()
```

Sum of the Euclidean distances from the center `{x, y}` to every point.

## Examples

    iex> Spatex.PointPats.dtot({0, 0}, [{3, 4}, {0, 1}])
    6.0

# `ellipse`

```elixir
@spec ellipse(points(), keyword()) :: {float(), float(), float()}
```

Standard deviational ellipse `{major, minor, angle}`.

`angle` is the direction of the major axis in radians, counter-clockwise from the x axis,
in `(-pi/2, pi/2]`.

## Options

  * `:weights` - one weight per point (the small-sample correction still uses the number of
    points, as in pointpats).
  * `:method` - `:crimestat` (default) or `:yuill`.
  * `:crimestat_corr`, `:degfreed_corr` - the two `:yuill` corrections (default `true`).

Needs at least 3 points.

# `euclidean_median`

```elixir
@spec euclidean_median(points()) :: {float(), float()}
```

Euclidean (geometric) median by Weiszfeld iteration from the mean center.

This converges to the exact minimizer of `dtot/2`; pointpats' BFGS result is only accurate to
about `1.0e-4` relative (a documented deviation).

# `f`

```elixir
@spec f(points(), keyword()) :: curve()
```

Empty-space function `F`: `{support, statistic}`.

The distances come from `:empty_points` (a point set) or from `:n_empty` (default 1000)
seeded uniform points of the `:hull` window (default `:bbox`).

## Options

`:support`, `:empty_points`, `:n_empty`, `:hull`, `:seed` (default 0).

# `f_test`

```elixir
@spec f_test(points(), keyword()) :: Spatex.PointPats.DistanceTest.t()
```

Monte Carlo test of `F`; see `g_test/2`. Also takes `:n_empty` (default 1000).

# `g`

```elixir
@spec g(points(), keyword()) :: curve()
```

Nearest-neighbour distribution `G`: `{support, statistic}`.

## Options

  * `:support` - see the moduledoc (default 20 values up to the largest nearest-neighbour
    distance).

## Examples

    iex> {support, g} = Spatex.PointPats.g([{0, 0}, {1, 0}, {3, 0}, {5, 0}], support: [0, 1, 2])
    iex> {support, g}
    {[0.0, 1.0, 2.0], [0.0, 0.0, 1.0]}

# `g_test`

```elixir
@spec g_test(points(), keyword()) :: Spatex.PointPats.DistanceTest.t()
```

Monte Carlo test of `G` against complete spatial randomness. Returns a
`Spatex.PointPats.DistanceTest`.

## Options

  * `:support`, `:hull` - see the moduledoc.
  * `:permutations` - number of CSR simulations, default 9999; `0` disables the test
    (`:nan` p-values).
  * `:seed` - default `nil`: a random seed, recorded in the result's `seed`.
  * `:keep_simulations` - also return every simulated curve (default `false`): `true` as a
    list of `permutations` lists, `:tensor` as a `{permutations, length(support)}`
    `Nx.Tensor` of type `{:f, 64}` (optional `:nx` dependency).

# `hull`

```elixir
@spec hull(points()) :: [{float(), float()}]
```

Convex hull vertices, counter-clockwise from the lowest-x vertex; collinear points are dropped.

# `j`

```elixir
@spec j(points(), keyword()) :: curve()
```

`J = (1 - G) / (1 - F)`: `{support, statistic}`.

Takes the options of `f/2` plus `truncate: true`, which cuts the result at the first infinite
or NaN value (F reaches 1 before G, so J is normally truncated).

# `j_test`

```elixir
@spec j_test(points(), keyword()) :: Spatex.PointPats.DistanceTest.t()
```

Monte Carlo test of `J`; see `g_test/2`. Takes `:truncate` (default `true`).

DEVIATION: pointpats' `j_test` returns `None` when `truncate: true` and J has no infinite
value; Spatex returns the result in that case (it cannot occur with a support that ends at
the maximum nearest-neighbour distance, where J is `0/0` at the last distance).

# `k`

```elixir
@spec k(points(), keyword()) :: curve()
```

Ripley's K, uncorrected, with the bounding-box area of the points: `{support, statistic}`.

# `k_test`

```elixir
@spec k_test(points(), keyword()) :: Spatex.PointPats.DistanceTest.t()
```

Monte Carlo test of `K`; see `g_test/2`.

# `l`

```elixir
@spec l(points(), keyword()) :: curve()
```

`L = sqrt(K / pi)`: `{support, statistic}`. With `linearized: true` it returns `L - d`.

# `l_test`

```elixir
@spec l_test(points(), keyword()) :: Spatex.PointPats.DistanceTest.t()
```

Monte Carlo test of `L`; see `g_test/2`. Takes `:linearized` (default `false`).

# `manhattan_median`

```elixir
@spec manhattan_median(points()) :: {float(), float()}
```

Coordinate-wise median. For an even number of points it is the mean of the two middle values
(not unique; pointpats warns about this, Spatex does not).

# `mbr`

```elixir
@spec mbr(points()) :: {float(), float(), float(), float()}
```

Minimum bounding rectangle `{min_x, min_y, max_x, max_y}`.

# `mean_center`

```elixir
@spec mean_center(points()) :: {float(), float()}
```

Mean center `{x, y}`.

## Examples

    iex> Spatex.PointPats.mean_center([{0, 0}, {2, 4}])
    {1.0, 2.0}

# `minimum_bounding_circle`

```elixir
@spec minimum_bounding_circle(points()) :: {{float(), float()}, float()}
```

Smallest enclosing circle `{{cx, cy}, radius}`.

# `minimum_bounding_rectangle`

```elixir
@spec minimum_bounding_rectangle(points()) :: {float(), float(), float(), float()}
```

Alias of `mbr/1`.

# `minimum_rotated_rectangle`

```elixir
@spec minimum_rotated_rectangle(points(), keyword()) ::
  [{float(), float()}] | {[{float(), float()}], float()}
```

Minimum-area rotated rectangle: its 4 corners, counter-clockwise (pointpats' corner order
and starting corner differ, compare as a set).

With `return_angle: true` returns `{corners, angle}` where `angle` is the direction of a side
in degrees, modulo 90. Raises for collinear points.

# `normal`

```elixir
@spec normal(window(), keyword()) :: [point()] | [[point()]]
```

Bivariate normal points truncated to the window: candidates are drawn around `:center` and
redrawn until they fall inside, as pointpats' `random.normal`.

Takes the window and the `:size` and `:seed` options of `poisson/2` (no `:intensity`), plus

  * `:center` - `{x, y}`. Default: the window centre (the middle of a box, the vertex mean of
    a convex polygon).
  * `:cov` - a number `v` for the covariance `v * I` (pointpats names it a standard deviation
    but uses it as a variance, and so do we), or a symmetric positive-definite 2 x 2 matrix
    `[[xx, xy], [xy, yy]]`. Default: `(max(width, height) / 2)^2`.

A centre that almost never lands in the window raises `ArgumentError` instead of looping.

## Examples

    iex> pts = Spatex.PointPats.normal({0, 0, 10, 5}, size: 20, cov: 2, seed: 1)
    iex> length(pts)
    20

# `poisson`

```elixir
@spec poisson(window(), keyword()) :: [point()] | [[point()]]
```

Conditional Poisson (complete spatial randomness): points uniform in `window`.

`window` is `{xmin, ymin, xmax, ymax}`, a point set (its bounding box) or `{:convex, points}`
(their convex hull). Returns one pattern (a list of `{x, y}`) for a single simulation and a
list of patterns otherwise; a one-point pattern is never squeezed to a bare point.

## Options

  * `:size` - an integer number of points, or `{n_points, n_simulations}`. With `:intensity`
    an integer `size` is the number of simulations instead. Default: 100 points.
  * `:intensity` - points per unit area; the count is `trunc(area * intensity)`. Not allowed
    with a `{n, m}` size.
  * `:seed` - default 0.

## Examples

    iex> pts = Spatex.PointPats.poisson({0, 0, 10, 5}, size: 20, seed: 1)
    iex> length(pts)
    20

# `quadrat_test`

```elixir
@spec quadrat_test(points(), keyword()) :: Spatex.PointPats.Quadrat.t()
```

Quadrat test of complete spatial randomness (Pearson chi-square on the cell counts).

## Options

  * `:shape` - `:rectangle` (default) or `:hexagon`.
  * `:nx`, `:ny` - columns and rows of the rectangle grid (default 3).
  * `:rectangle_width`, `:rectangle_height` - when both are non-zero the cells have this
    size and the grid may extend past the bounding box (default 0).
  * `:lh` - side length of the flat-topped hexagons (default 10).
  * `:permutations` - number of seeded CSR realizations in the bounding box for a Monte
    Carlo p-value (default 0). Each realization is gridded on its own bounding box.
  * `:seed` - default `nil`: a random seed, recorded in the result's `seed`.
  * `:max_cells` - largest grid accepted (default 1_000_000). A larger grid raises
    `ArgumentError` before anything is allocated; a small `:lh` or cell size on projected
    coordinates can otherwise ask for billions of cells.

Returns a `Spatex.PointPats.Quadrat`.

# `skyum`

```elixir
@spec skyum(points()) :: {{float(), float()}, float()}
```

Alias of `minimum_bounding_circle/1` (pointpats implements it with Skyum's algorithm).

# `std_distance`

```elixir
@spec std_distance(points()) :: float()
```

Standard distance (see the moduledoc on its raw-moment formula).

# `strauss`

```elixir
@spec strauss(window(), keyword()) :: [point()] | [[point()]]
```

Strauss process by pointpats' birth-death Metropolis-Hastings sampler: starts from `1.5 * n`
uniform points, runs `:n_iter` births and deaths weighted by `gamma^k` (`k` the number of pairs
closer than `:r`) and keeps the first `n` points of the final pattern.

Takes the window and the `:size`, `:intensity` and `:seed` options of `poisson/2`, plus

    * `:gamma` - interaction parameter: below 1 inhibits close pairs, 1 is Poisson, above 1
      clusters. Default 0.1.
    * `:r` - interaction radius, in window units (default 0.05, as pointpats; pick it for
      your coordinates). Pairs at distance `<= r` interact.
    * `:n_iter` - steps per replication (default 5000).
    * `:max_iter` - restarts per replication when the sampler cannot reach `n` points
      (default 10).

Raises `ArgumentError` when the requested size is impossible for `:gamma` and `:r` (pointpats'
`RuntimeError`).

## Examples

    iex> pts = Spatex.PointPats.strauss({0, 0, 1, 1}, size: 10, gamma: 0.2, r: 0.1, n_iter: 200, seed: 1)
    iex> length(pts)
    10

# `weighted_mean_center`

```elixir
@spec weighted_mean_center(points(), [number()]) :: {float(), float()}
```

Center weighted by `weights / sum(weights)`.

Raises when the weights do not match the points or sum to zero.

---

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