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

Map classification, mirroring `mapclassify` 2.11.0.

Every classifier returns a `%Spatex.Classify{}` with the class upper bounds (`bins`), the
class of each observation (`yb`, zero based), the observations per class (`counts`) and
fit summaries `tss`, `adcm` and `gadf`.

Class `i` holds the values in `(bins[i-1], bins[i]]`; the first class is closed at the
lower edge (`lowest`, the minimum of `y` unless given). This is mapclassify's right-closed
`bin1d`. A value above the last bin matches no interval and stays in class 0 (this can only
happen with `percentiles/2` bins that stop below 100, exactly as in mapclassify).

## Classifiers

| Function | mapclassify |
|---|---|
| `equal_interval/2` | `EqualInterval` |
| `quantiles/2` | `Quantiles` |
| `box_plot/2` | `BoxPlot` |
| `std_mean/2` | `StdMean` |
| `percentiles/2` | `Percentiles` |
| `maximum_breaks/2` | `MaximumBreaks` |
| `head_tail_breaks/1` | `HeadTailBreaks` |
| `user_defined/3` | `UserDefined` |
| `fisher_jenks/2` | `FisherJenks` |
| `fisher_jenks_sampled/2` | `FisherJenksSampled` |
| `jenks_caspall/2` | `JenksCaspall` |
| `jenks_caspall_sampled/2` | `JenksCaspallSampled` |
| `jenks_caspall_forced/2` | `JenksCaspallForced` |
| `natural_breaks/2` | `NaturalBreaks` |
| `pretty_breaks/2` | `PrettyBreaks` |
| `max_p/2` | `MaxP` |
| `gadf/2` | `gadf` |
| `k_classifiers/2` | `KClassifiers` |

`classify/3` dispatches on mapclassify's scheme names.

## Optimal classifiers

`fisher_jenks/2` is the exact optimum for within-class variance and matches mapclassify bit
for bit (it replicates mapclassify's `float32` dynamic program). It costs `O(n^2 k)`; for
large `n` use `fisher_jenks_sampled/2`. `natural_breaks/2` is one-dimensional k-means with
seeded k-means++ restarts. mapclassify draws its start points from an unseeded random
generator, so only statistical agreement is possible: on well separated data the results are
identical, in general Spatex reaches the same or a lower within-class variance. The sampled
classifiers draw their subsample from a ChaCha stream seeded by `:seed` (default `nil`: a random
seed, recorded in `info.seed`), so they
are reproducible but not equal to mapclassify's `numpy` draws.

## The `k` field

`k` follows mapclassify's `k` attribute: the requested number of classes for
`equal_interval/2` and `maximum_breaks/2`, and the number of bins for the others. This
deviates from mapclassify for `quantiles/2` on tied data, where mapclassify keeps the
requested `k` although fewer bins remain; here `k` is the real number of bins.

## Warnings

Conditions that mapclassify reports with `warnings.warn` are collected in `warnings` and
logged with `Logger.warning/1`: a `quantiles/2` that collapsed to fewer than `k` unique bins,
and a `maximum_breaks/2` with fewer unique gaps than `k - 1` (ties then break by position;
`numpy.argsort`, which mapclassify uses, leaves that order unspecified).

## Input

`y` accepts anything `Spatex.Input.to_f64_binary/2` does and must be finite. Invalid
input and invalid options raise `ArgumentError`.

## Examples

    iex> c = Spatex.Classify.equal_interval([1, 7, 4, 12, 4, 31], k: 5)
    iex> c.bins
    [7.0, 13.0, 19.0, 25.0, 31.0]
    iex> c.yb
    [0, 0, 0, 1, 0, 4]
    iex> c.counts
    [4, 1, 0, 0, 1]
    iex> Spatex.Classify.legend(c)
    ["[ 1.00,  7.00]", "( 7.00, 13.00]", "(13.00, 19.00]", "(19.00, 25.00]", "(25.00, 31.00]"]
    iex> Spatex.Classify.find_bin(c, [0, 8, 100])
    [0, 1, 4]

# `method`

```elixir
@type method() ::
  :equal_interval
  | :quantiles
  | :box_plot
  | :std_mean
  | :percentiles
  | :maximum_breaks
  | :head_tail_breaks
  | :user_defined
  | :fisher_jenks
  | :fisher_jenks_sampled
  | :jenks_caspall
  | :jenks_caspall_sampled
  | :jenks_caspall_forced
  | :natural_breaks
  | :pretty_breaks
  | :max_p
```

# `t`

```elixir
@type t() :: %Spatex.Classify{
  adcm: float(),
  bins: [float()],
  counts: [non_neg_integer()],
  gadf: float(),
  info: map(),
  k: pos_integer(),
  lowest: float(),
  method: method(),
  tss: float(),
  warnings: [String.t()],
  yb: [non_neg_integer()]
}
```

# `box_plot`

```elixir
@spec box_plot(term(), keyword()) :: t()
```

Box-plot classes (`mapclassify.BoxPlot`): lower fence, Q1, median, Q3, upper fence, maximum.

With a maximum below the upper fence the fence is dropped from the bins, leaving five
classes. `info` holds `:hinge`, `:iqr`, `:low_outlier_ids` (class 0, values below the lower
fence) and `:high_outlier_ids` (class 5). Ids are zero-based positions in `y`. Options:
`:hinge` (default `1.5`).

# `classify`

```elixir
@spec classify(term(), method() | String.t(), keyword()) :: t()
```

Classifies `y` with the named scheme, like `mapclassify.classify`.

`scheme` is a method atom (`:fisher_jenks`, `:quantiles`, ...) or a mapclassify scheme name
such as `"FisherJenks"` or `"natural_breaks"` (case and underscores are ignored). `opts` are
those of the matching function; `:user_defined` takes its bins as `bins:`.

    iex> Spatex.Classify.classify([1, 2, 3, 10, 11, 12, 30, 31], :fisher_jenks, k: 3).bins
    [3.0, 12.0, 31.0]

# `equal_interval`

```elixir
@spec equal_interval(term(), keyword()) :: t()
```

Equal-width classes between the minimum and maximum (`mapclassify.EqualInterval`).

Raises when all values are equal. Options: `:k` (default `5`).

# `find_bin`

```elixir
@spec find_bin(t(), number() | term()) :: non_neg_integer() | [non_neg_integer()]
```

Class index of each value against the classification's bins (`MapClassifier.find_bin`).

Like `numpy.digitize(x, bins, right: true)`, but values above the last bin fall in the last
class and values below the first in class 0. A number returns an integer, anything else a list.

# `fisher_jenks`

```elixir
@spec fisher_jenks(term(), keyword()) :: t()
```

Exact optimal classes minimising the within-class sum of squares (`mapclassify.FisherJenks`).

Raises when `y` has fewer than `k` unique values. Cost is `O(n^2 k)` time and `O(n k)`
memory. Options: `:k` (default `5`).

    iex> Spatex.Classify.fisher_jenks([1, 2, 3, 10, 11, 12, 30, 31], k: 3).bins
    [3.0, 12.0, 31.0]

# `fisher_jenks_sampled`

```elixir
@spec fisher_jenks_sampled(term(), keyword()) :: t()
```

Fisher-Jenks bins fitted on a random subsample, then applied to all of `y`
(`mapclassify.FisherJenksSampled`).

The subsample has `trunc(n * pct)` draws with replacement, always including `min(y)` and
`max(y)`; with `truncate: true` it is capped at about 1000 draws. Options: `:k` (default
`5`), `:pct` (default `0.1`, in `(0, 1]`), `:truncate` (default `true`) and `:seed`
(default `nil`: a random seed, recorded in `info.seed`).

# `gadf`

```elixir
@spec gadf(term(), keyword()) :: {pos_integer(), t(), float()}
```

The smallest `k` whose classification reaches a goodness of absolute deviation fit above
`:pct` (`mapclassify.gadf`).

Tries `k = 2..maxk` with `:method` (a method atom or scheme name, default `:quantiles`) and
stops at the first classification with `gadf > pct`; when none does, the `maxk` one is
returned. Options: `:method`, `:maxk` (default `15`, at least `2`), `:pct` (default `0.8`,
in `(0, 1)`) and the method's own options. Returns `{k, classification, gadf}`.

    iex> {k, _c, _gadf} = Spatex.Classify.gadf([1, 2, 3, 10, 11, 12, 30, 31], method: :fisher_jenks)
    iex> k
    3

# `head_tail_breaks`

```elixir
@spec head_tail_breaks(term()) :: t()
```

Head/tail breaks for heavy-tailed data (`mapclassify.HeadTailBreaks`): the mean, then the
mean of the values above it, until the head is constant.

# `intervals`

```elixir
@spec intervals(t()) :: [{float() | :neg_infinity, float()}]
```

The class intervals as `{low, high}` pairs. The first `low` is `lowest`, or `:neg_infinity`
when `lowest` is above the first bin. All intervals are closed on the right; the others are
open on the left, and so is the first when its `low` is `:neg_infinity`.

# `jenks_caspall`

```elixir
@spec jenks_caspall(term(), keyword()) :: t()
```

Jenks-Caspall classes: alternate between assigning every value to the nearest class median and
recomputing the medians, starting from quantiles (`mapclassify.JenksCaspall`).

`info.iterations` holds the number of rounds. If a class becomes empty mapclassify produces
undefined results; here the iteration stops and the non-empty classes are returned. Options:
`:k` (default `5`).

# `jenks_caspall_forced`

```elixir
@spec jenks_caspall_forced(term(), keyword()) :: t()
```

Jenks-Caspall with forced single-observation moves between neighbouring quantile classes
while the within-class sum of squares decreases (`mapclassify.JenksCaspallForced`).

Raises when all values are equal. Options: `:k` (default `5`).

Moves are by position in `y`, so classes need not be contiguous in value and `mapclassify`
can return unordered class maxima. Spatex deviates there and always returns ascending `bins`.

# `jenks_caspall_sampled`

```elixir
@spec jenks_caspall_sampled(term(), keyword()) :: t()
```

Jenks-Caspall bins fitted on a random subsample (`mapclassify.JenksCaspallSampled`); the
subsample always includes `max(y)`. Options: `:k` (default `5`), `:pct` (default `0.1`) and
`:seed` (default `nil`: drawn and recorded in `info.seed`). The subsample is capped at about
1000 draws.

# `k_classifiers`

```elixir
@spec k_classifiers(term(), keyword()) :: %{
  results: %{required(method()) =&gt; {pos_integer(), t(), float()}},
  best: {method(), pos_integer(), t(), float()}
}
```

Runs `gadf/2` for Quantiles, FisherJenks, NaturalBreaks and MaximumBreaks
(`mapclassify.KClassifiers`) with `maxk = n - 1`.

Returns `%{results: %{method => {k, classification, gadf}}, best: {method, k,
classification, gadf}}`, where the best has the smallest `k`, ties broken by the largest
`gadf` (FisherJenks first). mapclassify swaps `k` and `gadf` in that comparison, so its `best`
can differ (see `docs/parity.md`); NaturalBreaks uses Spatex's seeded k-means. Options:
`:pct` (default `0.8`).

# `legend`

```elixir
@spec legend(t(), keyword()) :: [String.t()]
```

Legend labels identical to `mapclassify`'s `get_legend_classes/1`, such as `"[ 1.00,  7.00]"`.

Edges are formatted with `:decimals` digits (default `2`, mapclassify's `"{:.2f}"`) and
right-aligned to a common width; the first label starts with `[` unless the lower edge is
open (`-inf`), then with `(`.

# `max_p`

```elixir
@spec max_p(term(), keyword()) :: t()
```

Max-p classes (`mapclassify.MaxP`): `k` contiguous classes of the sorted values grown from
quantile seeds, then one round of border swaps that do not raise the sum of squares.

Options: `:k` (default `5`), `:initial` (default `1000`), `:seed1` (default `0`) and
`:seed2` (default `1`). The growth and swap orders replay numpy's legacy generator seeded with
`:seed1` / `:seed2`, as mapclassify does, so results match it. mapclassify mixes sorted
positions with unsorted values, so it only agrees with this function on sorted input (see
`docs/parity.md`). Raises when fewer than `k` distinct quantiles exist.

# `maximum_breaks`

```elixir
@spec maximum_breaks(term(), keyword()) :: t()
```

Breaks at the `k - 1` largest gaps between sorted values (`mapclassify.MaximumBreaks`).

Raises when all values are equal or there are fewer than `k` values. Options: `:k`
(default `5`) and `:mindiff` (default `0`; stored in `info`, unused, as in mapclassify).

# `natural_breaks`

```elixir
@spec natural_breaks(term(), keyword()) :: t()
```

Natural breaks: one-dimensional k-means (`mapclassify.NaturalBreaks`).

Runs `:initial` k-means++ restarts from a ChaCha stream seeded by `:seed` and keeps the
lowest within-class variance; the bins are the class maxima. With fewer than `k` unique values
every unique value becomes a class (logged as a warning). Options: `:k` (default `5`),
`:initial` (default `10`) and `:seed` (default `nil`: a random seed, recorded in `info.seed`).
Unlike mapclassify, whose start points are unseeded, an explicit seed makes the result a pure
function of the arguments.

# `percentiles`

```elixir
@spec percentiles(term(), keyword()) :: t()
```

Classes cut at percentiles (`mapclassify.Percentiles`). Options: `:pct` (default
`[1, 10, 50, 90, 99, 100]`, each in `0..100`).

# `pretty_breaks`

```elixir
@spec pretty_breaks(term(), keyword()) :: t()
```

Pretty breaks: equally spaced round bounds (`mapclassify.PrettyBreaks`).

The step is 1, 2 or 5 times a power of ten, chosen from the range and `k`; the bounds are
the multiples of the step from below `min(y)` up to at least `max(y)`, so the number of
classes can differ from `k`. As in mapclassify, `k` stays the requested value and the fit
statistics (`tss`, `adcm`, `gadf`) cover classes `0..k-1`. Options: `:k` (default `5`, at
least `2`).

    iex> Spatex.Classify.pretty_breaks([1, 7, 4, 12, 4, 31], k: 6).bins
    [10.0, 20.0, 30.0, 40.0]

# `quantiles`

```elixir
@spec quantiles(term(), keyword()) :: t()
```

Classes holding (approximately) the same number of observations (`mapclassify.Quantiles`).

Percentiles use linear interpolation like `scipy.stats.scoreatpercentile`; repeated cut
points are dropped, which leaves fewer than `k` bins and logs a warning. The top bin is
always `max(y)`: mapclassify's last percentile can drift just below 100 (for example
`k = 23` on `1..46`) and then assigns the maximum to class 0; Spatex does not. Options:
`:k` (default `5`).

# `std_mean`

```elixir
@spec std_mean(term(), keyword()) :: t()
```

Classes at multiples of the sample standard deviation around the mean
(`mapclassify.StdMean`, standard deviation with `ddof = 1`).

The maximum is appended as a last bin when the last cut is below it. Options: `:multiples`
(default `[-2, -1, 1, 2]`) and `:anchor` (default `false`); with `anchor: true` the multiples
become every integer from `trunc((min - mean) / std)` to `trunc((max - mean) / std)`
(the given `:multiples` are then ignored).

# `user_defined`

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

Classes with the given upper bounds (`mapclassify.UserDefined`).

When the last bin is below `max(y)` the maximum is appended as an extra bin. Option
`:lowest` only changes the lower edge shown by `legend/2` and `intervals/1`.

---

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