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

Exploratory spatial data analysis, mirroring `esda` 2.10.0.

## Global Moran's I

  * `moran/3` - univariate Moran's I (`esda.Moran`)
  * `moran_bv/4` - bivariate Moran's I (`esda.Moran_BV`)
  * `moran_rate/4` - Moran's I of rates with empirical-Bayes adjustment (`esda.Moran_Rate`)
  * `assuncao_rate/2` - the empirical-Bayes standardized rates on their own

## Geary, Getis-Ord G and join counts

  * `geary/3` - Geary's C (`esda.Geary`), one-tailed analytic inference
  * `getis_ord_g/3` - general G (`esda.G`); weights are always binarized, so there is no
    `:transform` option, and `y` must be non-negative
  * `join_counts/3` - binary join counts (`esda.Join_Counts`); takes `drop_islands: true`
    (default) and no `:transform` (binary weights are forced)

They take the options below (except where noted) and reuse the same seeded permutation
engine as Moran.

## Local Moran's I

  * `moran_local/3` - local Moran's I / LISA (`esda.Moran_Local`)
  * `moran_local_bv/4` - bivariate local Moran's I (`esda.Moran_Local_BV`)

Both use conditional randomization and return a `Spatex.ESDA.MoranLocal` whose per-site
fields are lists aligned with the graph's ids. See their documentation for the extra options.

## Local Geary, local join counts and LOSH

  * `geary_local/3` - local Geary (`esda.Geary_Local`); the graph is row-standardized
  * `geary_local_mv/3` - multivariate local Geary (`esda.Geary_Local_MV`)
  * `join_counts_local/3` - univariate local join counts (`esda.Join_Counts_Local`) of a
    binary variable; weights are used as binary, self weights are ignored
  * `join_counts_local_bv/4`, `join_counts_local_mv/3` - bivariate (`CLC`, `BJC`) and
    multivariate local join counts (`esda.Join_Counts_Local_BV`, `Join_Counts_Local_MV`)
  * `losh/3` - local spatial heteroscedasticity (`esda.LOSH`); weights are used as given

The first two take `:permutations`, `:seed`, `:keep_simulations` and `:alternative` as
`moran_local/3` does (no `:transform`); `losh/3` takes `:a` and `:inference`.

## Local Getis-Ord G and multiple testing

  * `g_local/3` - local `G_i` and `G*_i` (`esda.G_Local`), returning a `Spatex.ESDA.GLocal`;
    takes `:star`, `:alternative` and `:island_weight` besides the common options, and only
    the `:r` and `:b` transforms
  * `fdr/2` - the false-discovery-rate p-value cut-off (`esda.fdr`)

## Options

The global statistics accept:

  * `:permutations` - number of random permutations, default `999`; `0` skips the
    permutation test and leaves the simulation fields `nil`.
  * `:seed` - non-negative integer below 2^64. Default `nil`: a random seed is drawn and
    stored in the result's `seed` field, so any run can be reproduced. The same seed gives
    bit-for-bit identical simulations regardless of how many threads run them. The stream
    is ChaCha8-based, so the simulated values differ from numpy's; they agree with PySAL
    statistically, not draw by draw.
  * `:transform` - weights transformation applied to the graph first (`:r`, `:b`, `:d`,
    `:v`, `:o`), default `:r` as in PySAL. A graph already carrying that transform is used
    as is.
  * `:keep_simulations` - keep the simulations (`sim`) in the result: `true` (nested lists),
    `false` or `:tensor`. Default `true` for the global statistics and `false` for the local
    ones, whose `n x permutations` matrix can be large (`n = 50_000` with 999 permutations is
    about 2 GB of boxed floats). `:tensor` returns the same draws as an `Nx.Tensor` of type
    `{:f, 64}` built straight from the native binary, with no list decoding: shape
    `{permutations}` for a global statistic and `{n, permutations}` for a local one (join
    counts give one such tensor per `sim_*` vector). It needs the optional `:nx` dependency;
    with `permutations: 0` the simulations are `nil` whatever the value.

`moran/3` and `moran_rate/4` also take `:two_tailed` (default `true`), which doubles the
analytic `p_norm` and `p_rand`. The permutation p-value `p_sim` is the folded
pseudo p-value `(larger + 1) / (P + 1)`, and `p_z_sim` is always one-tailed, as in esda.

## Input

`y`, `x`, `events` and `base` are anything `Spatex.Input.to_f64_binary/2` accepts, aligned
with the graph's node order, and must be finite. Invalid input raises `ArgumentError`.
Constant variables raise (PySAL returns NaN), as does a graph without weights.

# `assuncao_rate`

```elixir
@spec assuncao_rate(term(), term()) :: [float()]
```

Empirical-Bayes standardized rates of Assuncao and Reis (1999), `esda.smoothing.assuncao_rate`.

## Examples

    iex> [a, b] = Spatex.ESDA.assuncao_rate([1, 4], [10, 20])
    iex> {Float.round(a, 4), Float.round(b, 4)}
    {-0.7559, 0.3651}

# `fdr`

```elixir
@spec fdr(term(), number()) :: float()
```

The false discovery rate cut-off of `p_values` (`esda.fdr`).

A Benjamini-Hochberg style threshold, not a vector of adjusted p-values: reject the sites
whose p-value is below the returned number. The p-values are sorted in descending order and
compared with `index * alpha / n`, `index = n, ..., 1`; the first threshold strictly greater
than its p-value is returned. If none qualifies, the conservative Bonferroni bound
`alpha / n` is returned. `alpha` is in `(0, 1]` (default `0.05`).

Raises `ArgumentError` for an empty list, non-numeric or NaN p-values and negative p-values.
(esda would sort NaN first; `p_sim` with `alternative: :two_sided` may exceed 1, which is
accepted.)

## Examples

    iex> Spatex.ESDA.fdr([0.001, 0.01, 0.02, 0.04, 0.3, 0.5])
    0.025000000000000005
    iex> Spatex.ESDA.fdr([0.5, 0.6])
    0.025
    iex> Spatex.ESDA.fdr([0.5, 0.6, 0.7, 0.8], 0.1)
    0.025

# `g_local`

```elixir
@spec g_local(term(), Spatex.Graph.t(), keyword()) :: Spatex.ESDA.GLocal.t()
```

Local Getis-Ord `G_i` / `G*_i` of `y` over `graph` (`esda.G_Local`).

`y` must be finite and non-negative with a positive sum (esda does not check). Returns a
`Spatex.ESDA.GLocal`. Takes `:permutations`, `:seed` and `:keep_simulations` as described in
the module documentation, plus:

  * `:transform` - `:r` (default, esda's `"R"`) or `:b`. Unlike the other statistics the
    graph is transformed only after the diagonal has been decided, so pass the graph as
    built, not pre-transformed (a graph already labelled `:b` is treated as binary input).
  * `:star` - the self weight rule of esda: `false` (default) computes `G_i`, removing any
    diagonal; `true` computes `G*_i`, keeping a nonzero diagonal or else assigning self weight
    `1` (binary graph or `transform: :b`) or the largest weight of the node's row (`:r`);
    `nil` infers it from the diagonal of the graph; a number assigns that self weight to every
    node (so `star: 1` is a unit self weight, not `true`).
  * `:alternative` - `:directed` (default), `:two_sided`, `:greater`, `:lesser` or `:folded`,
    as for `moran_local/3`.
  * `:island_weight` - weight of the single pseudo-neighbor an island is given in the
    simulations, default `0.0` (esda's `island_weight`).

Inference is by conditional randomization of the raw `y` values (see `moran_local/3`); islands
get the smallest possible `p_sim`, an esda quirk kept for parity.

## Examples

    iex> g = Spatex.Graph.from_arrays([0, 1, 1, 2, 2, 3], [1, 0, 2, 1, 3, 2])
    iex> m = Spatex.ESDA.g_local([1, 2, 3, 4], g, permutations: 0)
    iex> Enum.map(m.gs, &Float.round(&1, 4))
    [0.2222, 0.25, 0.4286, 0.5]
    iex> m = Spatex.ESDA.g_local([1, 2, 3, 4], g, permutations: 0, star: true)
    iex> {m.star, Enum.map(m.gs, &Float.round(&1, 4))}
    {true, [0.15, 0.2, 0.3, 0.35]}

# `geary`

```elixir
@spec geary(term(), Spatex.Graph.t(), keyword()) :: Spatex.ESDA.Geary.t()
```

Global Geary's C of `y` over `graph` (`esda.Geary`).

Takes the options of the module documentation (`:transform` defaults to `:r`, as in PySAL).
The analytic p-values are one-tailed (the tail follows the sign of `C - 1`), there is no
`:two_tailed` option, and `p_z_sim` is the survival function of `|z_sim|`. Returns a
`Spatex.ESDA.Geary`.

## Examples

    iex> g = Spatex.Graph.from_arrays([0, 1, 1, 2, 2, 3], [1, 0, 2, 1, 3, 2])
    iex> m = Spatex.ESDA.geary([1, 2, 4, 3], g, permutations: 0)
    iex> {Float.round(m.c, 4), m.ec}
    {0.525, 1.0}

# `geary_local`

```elixir
@spec geary_local(term(), Spatex.Graph.t(), keyword()) :: Spatex.ESDA.GearyLocal.t()
```

Local Geary (`esda.Geary_Local`) of `x` over `graph`, which is always row-standardized.

Returns a `Spatex.ESDA.GearyLocal`. Takes `:permutations` (default `999`), `:seed`,
`:keep_simulations` and `:alternative` as in `moran_local/3`, plus:

  * `:labels` - also return esda's cluster/outlier labels in `labs` (`1` outlier, `2`
    cluster, `3` other, `4` not significant), default `false`; needs `permutations > 0`.
  * `:sig` - significance level of the labels, in `(0, 1]`, default `0.05`.
  * `:island_weight` - weight of the single pseudo-neighbor an island is given in the
    simulations, default `0.0` (esda's `island_weight`).

Inference is by conditional randomization (see `moran_local/3`). Islands get `local_g` 0 and
the smallest possible `p_sim`. Constant `x` raises (PySAL returns NaN).

## Examples

    iex> g = Spatex.Graph.from_arrays([0, 1, 1, 2], [1, 0, 2, 1])
    iex> m = Spatex.ESDA.geary_local([1, 2, 3], g, permutations: 0)
    iex> Enum.map(m.local_g, &Float.round(&1, 4))
    [1.5, 1.5, 1.5]

# `geary_local_mv`

```elixir
@spec geary_local_mv([term()], Spatex.Graph.t(), keyword()) ::
  Spatex.ESDA.GearyLocalMV.t()
```

Multivariate local Geary (`esda.Geary_Local_MV`) of `variables`, a list of at least two
vectors aligned with `graph`.

Returns a `Spatex.ESDA.GearyLocalMV`. The graph is row-standardised, every variable is
standardised (ddof 0) and `local_g` averages the per-variable local Geary statistics. Options:
`:permutations` (default `999`), `:seed` and `:keep_simulations` as in `moran_local/3`. The
pseudo p-value is esda's folded one (there is no `:alternative`); one conditional draw
relabels the neighbors for every variable at once. esda's draws are unseeded, Spatex's are
seeded. Islands get `local_g` 0 and the smallest possible `p_sim`; a constant variable raises.

## Examples

    iex> g = Spatex.Graph.from_arrays([0, 1, 1, 2], [1, 0, 2, 1])
    iex> m = Spatex.ESDA.geary_local_mv([[1, 2, 3], [3, 1, 2]], g, permutations: 0)
    iex> Enum.map(m.local_g, &Float.round(&1, 4))
    [3.75, 2.625, 1.5]

# `getis_ord_g`

```elixir
@spec getis_ord_g(term(), Spatex.Graph.t(), keyword()) :: Spatex.ESDA.G.t()
```

Global Getis-Ord general G of `y` over `graph` (`esda.G`).

Weights are binarized whatever transformation the graph carries (PySAL does the same and
offers no choice), so `:transform` is not accepted. `y` must be non-negative and have at
least two non-zero values. `z_norm` and `p_norm` are `:nan` when the variance is not
positive; `p_norm` and `p_z_sim` are `1 - Phi(|z|)` as in esda. Returns a `Spatex.ESDA.G`.

## Examples

    iex> g = Spatex.Graph.from_arrays([0, 1, 1, 2, 2, 3], [1, 0, 2, 1, 3, 2])
    iex> m = Spatex.ESDA.getis_ord_g([1, 2, 4, 3], g, permutations: 0)
    iex> {Float.round(m.g, 4), Float.round(m.eg, 4)}
    {0.6286, 0.5}

# `join_counts`

```elixir
@spec join_counts(term(), Spatex.Graph.t(), keyword()) :: Spatex.ESDA.JoinCounts.t()
```

Binary join counts of `y` (0 or 1) over `graph` (`esda.Join_Counts`).

The graph is binarized and every directed edge counts, tallied by halves, so a symmetric
graph yields `j` undirected joins. With `drop_islands: true` (default) island nodes are
ignored; with `false` an island's zero-weight self-loop counts as a same-colour join, as in
esda. `y` must be strictly 0/1 with both values present. Returns a
`Spatex.ESDA.JoinCounts`; see it for the field list and the `sim_autocorr_chi2` deviation.

## Examples

    iex> g = Spatex.Graph.from_arrays([0, 1, 1, 2, 2, 3], [1, 0, 2, 1, 3, 2])
    iex> m = Spatex.ESDA.join_counts([1, 1, 0, 0], g, permutations: 0)
    iex> {m.j, m.bb, m.ww, m.bw}
    {3.0, 1.0, 1.0, 1.0}

# `join_counts_local`

```elixir
@spec join_counts_local(term(), Spatex.Graph.t(), keyword()) ::
  Spatex.ESDA.JoinCountsLocal.t()
```

Univariate local join counts (`esda.Join_Counts_Local`) of the binary variable `y`.

Returns a `Spatex.ESDA.JoinCountsLocal`. Takes `:permutations` (default `999`), `:seed`,
`:keep_simulations` and `:alternative` as in `moran_local/3`, and `:island_weight` as in
`geary_local/3`. Self weights are ignored and
every non-zero weight is one join, so the graph needs no `:transform`. `y` must contain
only 0 and 1 (`ArgumentError` otherwise); islands count 0, and `p_sim` is `:nan` wherever the
count is 0, as in esda.

## Examples

    iex> g = Spatex.Graph.from_arrays([0, 1, 1, 2], [1, 0, 2, 1])
    iex> Spatex.ESDA.join_counts_local([1, 1, 0], g, permutations: 0).ljc
    [1.0, 1.0, 0.0]

# `join_counts_local_bv`

```elixir
@spec join_counts_local_bv(term(), term(), Spatex.Graph.t(), keyword()) ::
  Spatex.ESDA.JoinCountsLocal.t()
```

Bivariate local join counts (`esda.Join_Counts_Local_BV`) of the binary variables `x` and `z`.

`:case` selects the statistic:

  * `:clc` (default) - co-location: at a site with `x = z = 1`, the neighbors with
    `x = z = 1`. This is `join_counts_local/3` of `x * z` (esda simulates `z_i` times the drawn
    products, which differs only where the count, and so `p_sim`, is 0 / `:nan`).
  * `:bjc` - bivariate joins: at a site with `x = 1, z = 0`, the neighbors with `x = 0, z = 1`.
    As in esda the simulation draws `z` only (`x_i` times the drawn `z` joins), so it ignores
    the `1 - z_i` and `1 - x_j` factors of the observation.

Other options and the returned `Spatex.ESDA.JoinCountsLocal` are those of
`join_counts_local/3`.

# `join_counts_local_mv`

```elixir
@spec join_counts_local_mv([term()], Spatex.Graph.t(), keyword()) ::
  Spatex.ESDA.JoinCountsLocal.t()
```

Multivariate local join counts (`esda.Join_Counts_Local_MV`): at a site where every binary
variable is 1, the neighbors where every variable is 1.

`variables` is a list of at least two binary vectors. The statistic and its simulation are
those of `join_counts_local/3` on the product of the variables, as in esda. Options and the
returned `Spatex.ESDA.JoinCountsLocal` are those of `join_counts_local/3`.

# `losh`

```elixir
@spec losh(term(), Spatex.Graph.t(), keyword()) :: Spatex.ESDA.Losh.t()
```

Local spatial heteroscedasticity (`esda.LOSH`, Ord and Getis 2012) of `y` over `graph`.

Returns a `Spatex.ESDA.Losh`. The graph is used as given (the statistic does not depend on
row scaling). Options:

  * `:a` - residual exponent, default `2` (a variance measure); `1` gives absolute
    deviations.
  * `:inference` - `nil` (default) or `:chi2` (`:chi_square` is accepted too): chi-square
    p-values `pval`, valid for `a == 2` only (with another `a` a warning is logged and
    `pval` stays `nil`, as in esda). esda has no permutation inference, so there is none.

Islands: esda returns all-`NaN` values as soon as one site has no neighbors; Spatex computes
the statistic over the sites that have neighbors and reports `:nan` for the islands.

## Examples

    iex> g = Spatex.Graph.from_arrays([0, 1, 1, 2], [1, 0, 2, 1])
    iex> m = Spatex.ESDA.losh([1, 2, 4], g)
    iex> Enum.map(m.hi, &Float.round(&1, 4))
    [0.1429, 1.4286, 0.1429]

# `moran`

```elixir
@spec moran(term(), Spatex.Graph.t(), keyword()) :: Spatex.ESDA.Moran.t()
```

Global Moran's I of `y` over `graph`.

See the module documentation for the options. Returns a `Spatex.ESDA.Moran`.

## Examples

    iex> g = Spatex.Graph.from_arrays([0, 1, 1, 2], [1, 0, 2, 1])
    iex> m = Spatex.ESDA.moran([1, 2, 4], g, permutations: 0)
    iex> Float.round(m.i, 6)
    -0.035714
    iex> m.ei
    -0.5
    iex> m.sim
    nil

# `moran_bv`

```elixir
@spec moran_bv(term(), term(), Spatex.Graph.t(), keyword()) :: Spatex.ESDA.MoranBV.t()
```

Bivariate Moran's I between `x` and the spatial lag of `y` (`esda.Moran_BV`).

Both variables are standardized with the sample standard deviation and the statistic is
`sum(zx * W zy) / (n - 1)`; permutations shuffle `y`. Takes the options of the module
documentation except `:two_tailed`. Returns a `Spatex.ESDA.MoranBV`.

# `moran_local`

```elixir
@spec moran_local(term(), Spatex.Graph.t(), keyword()) :: Spatex.ESDA.MoranLocal.t()
```

Local Moran's I (LISA) of `y` over `graph` (`esda.Moran_Local`).

Returns a `Spatex.ESDA.MoranLocal`; use `Spatex.ESDA.MoranLocal.cluster_labels/2` for the
High-High / Low-Low / ... map classes. Takes `:permutations`, `:seed`, `:transform` and
`:keep_simulations` as described in the module documentation, plus:

  * `:geoda_quads` - number the quadrants as GeoDa does (Low-High 3, Low-Low 2), default
    `false`.
  * `:alternative` - `:directed` (default, esda's `None`), `:two_sided`, `:greater`,
    `:lesser` or `:folded`: the tail(s) of the pseudo p-value, replicating
    `esda.significance.calculate_significance` (`:two_sided` can exceed 1, as in esda).

Inference is by conditional randomization: the site's value stays fixed and its neighbors'
values are drawn without replacement from the other sites. As in esda, one set of
permutation draws is shared by all sites, which makes simulations correlated across sites.
Islands get the smallest possible `p_sim`, `1 / (permutations + 1)` (an esda quirk kept for
parity). Constant `y` raises (PySAL returns NaN).

## Examples

    iex> g = Spatex.Graph.from_arrays([0, 1, 1, 2, 2, 3], [1, 0, 2, 1, 3, 2])
    iex> m = Spatex.ESDA.moran_local([1, 5, 2, 8], g, permutations: 0)
    iex> m.q
    [2, 4, 2, 4]
    iex> Enum.map(m.is, &Float.round(&1, 4))
    [-0.3, -0.25, -0.5, -0.8]

# `moran_local_bv`

```elixir
@spec moran_local_bv(term(), term(), Spatex.Graph.t(), keyword()) ::
  Spatex.ESDA.MoranLocal.t()
```

Bivariate local Moran's I (`esda.Moran_Local_BV`): the standardized `x` at each site against
the spatial lag of the standardized `y`.

Takes the options of `moran_local/3`; permutations draw the neighbors' `y` values. esda has
no analytic moments for this statistic, so `ei`, `vi`, `se_i`, `ei_c` and `vi_c` are `nil`
and `lag` is the lag of `z_y`. Returns a `Spatex.ESDA.MoranLocal`.

# `moran_rate`

```elixir
@spec moran_rate(term(), term(), Spatex.Graph.t(), keyword()) ::
  Spatex.ESDA.MoranRate.t()
```

Moran's I of rates `events / base` (`esda.Moran_Rate`).

With `adjusted: true` (default) the rates are the empirical-Bayes standardized rates of
`assuncao_rate/2`; with `adjusted: false` they are plain ratios. Takes the options of
`moran/3` plus `:adjusted`. `base` must be positive and `events` non-negative. Returns a
`Spatex.ESDA.MoranRate` whose `y` holds the rates used.

---

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