# `Geostatex.Kriging`
[🔗](https://github.com/CountlinkX-Solutions/geostatex/blob/v0.6.0/lib/geostatex/kriging.ex#L1)

Ordinary kriging, after `pykrige.OrdinaryKriging` (PyKrige).

`ordinary/3` sets up the model from observations: the variogram is either given or fitted
automatically, as PyKrige does. `execute/5` then predicts the value and the kriging variance at
new locations.

## Variogram models

PyKrige's models and parametrisation (they differ from `Geostatex.Variogram`'s):

  * `:linear` - `slope * d + nugget`;
  * `:power` - `scale * d^exponent + nugget` (`0 < exponent < 2`);
  * `:gaussian`, `:spherical`, `:exponential`, `:hole_effect` - a partial sill `psill`, a
    `range` and a `nugget` (the Gaussian uses `range * 4 / 7`, the exponential and hole-effect
    `range / 3`).

## Options of `ordinary/3`

  * `:variogram_model` - default `:linear`, as in PyKrige.
  * `:variogram_parameters` - `nil` (default: fitted), a map (`%{slope:, nugget:}`,
    `%{scale:, exponent:, nugget:}`, or `%{range:, nugget:}` with `sill:` or `psill:`) or a list
    (`[slope, nugget]`, `[scale, exponent, nugget]`, or `[sill, range, nugget]`; the partial sill
    is then `sill - nugget`, as in PyKrige).
  * `:nlags` - number of lags of the automatic variogram (default `6`); `:weight` - weight the
    short lags more in its fit (default `false`).
  * `:anisotropy_scaling`, `:anisotropy_angle` - stretch the data along an axis rotated by
    `angle` degrees about the centre of their bounding box (defaults `1.0`, `0.0`).
  * `:coordinates_type` - `:euclidean` (default) or `:geographic` (longitude / latitude in
    degrees, great-circle distances in degrees; no anisotropy).
  * `:exact_values` - at a data location return the observed value with zero variance (default
    `true`).
  * `:pseudo_inv` - solve with a pseudo-inverse (default `false`), `:pseudo_inv_type` `:pinv`
    (SVD, default) or `:pinvh` (symmetric eigendecomposition); needed when points repeat.
  * `:variogram_function` - with `variogram_model: :custom`, a function
    `fn parameters, distance -> semivariance end` called with `variogram_parameters` (a list,
    required) and each distance kriging needs (PyKrige's `"custom"` model; see below).

## Custom variograms

`variogram_model: :custom` takes any semivariance function of the distance, as PyKrige's
`variogram_function(params, distances)`. Its parameters are not fitted. The NIF first lists the
distances a call needs (between the data points and from each target to them, after the
anisotropy adjustment, in degrees for geographic coordinates), the function is evaluated at each
in Elixir, and kriging then reads those values; the lags and semivariances of the data are
still computed as for the other models. `statistics/1`, `cross_validate/4` and the 3D functions
accept custom variograms too.

    iex> stable = fn [sill, range, nugget], d -> sill * (1 - :math.exp(-d / range)) + nugget end
    iex> k = Geostatex.Kriging.ordinary([{0, 0}, {1, 0}, {2, 0}, {3, 0}], [1, 2, 4, 3],
    ...>   variogram_model: :custom, variogram_function: stable,
    ...>   variogram_parameters: [2.0, 1.5, 0.0])
    iex> {[z], _} = Geostatex.Kriging.execute(k, :points, [2.0], [0.0])
    iex> Float.round(z, 12)
    4.0

The automatic variogram follows PyKrige: `nlags` equal-width lags from the smallest to the
largest distance with the mean distance and mean semivariance of each non-empty lag, fitted with
the `soft_l1` robust loss within PyKrige's bounds. The optimiser differs from scipy's (a scan of
the range or exponent, then a bounded Levenberg-Marquardt), so the fitted parameters reach
PyKrige's objective or a lower one (see `docs/parity.md`).

## Examples

    iex> k = Geostatex.Kriging.ordinary([{0, 0}, {1, 0}, {2, 0}, {3, 0}], [1, 2, 4, 3],
    ...>   variogram_model: :linear, variogram_parameters: %{slope: 1.0, nugget: 0.0})
    iex> {[z], [s]} = Geostatex.Kriging.execute(k, :points, [1.5], [0.0])
    iex> {Float.round(z, 12), s > 0}
    {3.0, true}

# `t`

```elixir
@type t() :: %Geostatex.Kriging{
  adjust: term(),
  anisotropy: term(),
  coordinates_type: term(),
  dim: term(),
  drift_terms: term(),
  exact_values: term(),
  functional_drift: term(),
  lags: term(),
  mean: term(),
  n: term(),
  n_specified: term(),
  nlags: term(),
  ref: term(),
  semivariance: term(),
  variogram_function: term(),
  variogram_model: term(),
  variogram_model_parameters: term(),
  weight: term()
}
```

# `cross_validate`

```elixir
@spec cross_validate(atom(), term(), term(), keyword()) :: map()
```

Leave-one-out cross-validation: the variogram of the model on all the data (given or fitted),
then every point predicted by a model of the same `kind` (`:ordinary`, `:universal`,
`:ordinary_3d` or `:universal_3d`) on the other points with that variogram. `opts` are the
model's options plus `:n_closest_points` for the predictions; a `:specified_drift` loses the
left-out point's value, which becomes its drift at the target.

Returns `%{predictions:, variances:, residuals:, mse:, rmse:, mae:, variogram_model_parameters:}`
with the residuals `prediction - value` (scikit-gstat's `cross_validate` sign).

The folds run in parallel, in up to `System.schedulers_online/0` processes (a custom
`:variogram_function` is called from those processes); the results are the same as one fold
after another, and the first failing fold raises its error in the caller.

# `execute`

```elixir
@spec execute(t(), :points | :grid | :masked, [number()], [number()], keyword()) ::
  {list(), list()}
```

Predictions and kriging variances (`{z, sigmasq}`).

  * `:points` - at the points `{xs[i], ys[i]}`; two lists of the same length.
  * `:grid` - on the grid of `xs` (columns) by `ys` (rows); `ny` rows of `nx` values.
  * `:masked` - like `:grid`, with `mask:` (`ny` rows of `nx` booleans; `true` skips the cell,
    which gives `:nan`).

Option `:n_closest_points` (at least 2) uses only that many nearest observations per
prediction (PyKrige's moving window).

# `execute_3d`

```elixir
@spec execute_3d(
  t(),
  :points | :grid | :masked,
  [number()],
  [number()],
  [number()],
  keyword()
) ::
  {list(), list()}
```

Predictions and kriging variances in 3D (`{z, sigmasq}`): `:points` at `{xs[i], ys[i],
zs[i]}`, `:grid` and `:masked` on the grid of `xs`, `ys` and `zs` as `nz` planes of `ny` rows of
`nx` values (PyKrige's order); the mask has the same shape. Options as in `execute/5`.

# `ordinary`

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

Sets up ordinary kriging of `values` observed at `points`. See the module documentation.

# `ordinary_3d`

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

Ordinary kriging in 3D (`pykrige.OrdinaryKriging3D`) of `values` at `points` (`[{x, y, z}]` or
`[[x, y, z]]`). Takes the options of `ordinary/3` without `:coordinates_type` and with 3D
anisotropy instead of the 2D one: `:anisotropy_scaling_y`, `:anisotropy_scaling_z` (default
`1.0`) and `:anisotropy_angle_x`, `:anisotropy_angle_y`, `:anisotropy_angle_z` (degrees, default
`0.0`; the rotation is `Rz Ry Rx` about the centre of the data's bounding box). Predict with
`execute_3d/6`.

# `simple`

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

Simple kriging with a known mean (`gstools.krige.Simple`): the estimate is
`mean + w . (z - mean)` with weights from the covariance (`sill - gamma`) and no unbiasedness
condition, and the variance `max(sill - w . c, 0)`. Takes the options of `ordinary/3`
(Euclidean coordinates only; the default model is `:spherical`) and:

  * `:mean` - the known mean of the field (default `0.0`).

The model needs a sill: `:spherical`, `:exponential` or `:gaussian` (given or fitted as for
`ordinary/3`). The nugget is the measurement error on the kriging matrix's diagonal, as in
GSTools; `exact_values: true` (the default) is GSTools' `exact=True` and reproduces the data,
`false` smooths them. A moving window (`n_closest_points`) is not available.

GSTools models map onto these with `rescale=1`: `Exponential(len_scale: range / 3)`,
`Gaussian(len_scale: 4 / 7 * range)`, `Spherical(len_scale: range)`, `var: psill`.

# `simple_3d`

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

Simple kriging in 3D: `simple/3` with the 3D anisotropy options of `ordinary_3d/3`. Predict
with `execute_3d/6`.

# `statistics`

```elixir
@spec statistics(t()) :: map()
```

PyKrige's statistics of the model's fit (`enable_statistics`): every data point kriged, by
ordinary kriging with the model's variogram and without drift terms, from the points before
it. Returns `%{delta:, sigma:, epsilon:, q1:, q2:, cr:}`: the residuals (value minus
prediction) and kriging standard deviations of the points whose kriging variance is not about
0, the standardised residuals `delta / sigma`, `Q1 = |sum(epsilon)| / (m - 1)`,
`Q2 = sum(epsilon^2) / (m - 1)` and `cR = Q2 * exp(mean(ln(sigma^2)))`. A good model has `Q1`
near 0, `Q2` near 1 and a small `cR`.

The points enter in their order, on the anisotropy-adjusted coordinates; `pseudo_inv: true`
solves by least squares.

# `universal`

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

Sets up universal kriging (`pykrige.UniversalKriging`): ordinary kriging with drift terms in
the kriging system. Takes the options of `ordinary/3` (Euclidean coordinates only) and:

  * `:drift_terms` - any of `:regional_linear` (the x and y coordinates), `:point_log` (with
    `point_drift: [{x, y, q}]`: `-q ln(distance)` to each point), `:external_z` (with
    `external_drift:` rows of a grid over `external_drift_x` (columns) and `external_drift_y`
    (rows), interpolated bilinearly at the original coordinates), `:specified` (with
    `specified_drift:` a list of drifts, each one value per data point; `execute/5` then needs
    `specified_drift_arrays:` the same drifts at the targets) and `:functional` (with
    `functional_drift:` a list of `fn x, y -> value end`, evaluated at the anisotropy-adjusted
    coordinates).

The variogram (given or automatic) is the same as for `ordinary/3`, fitted on the data
without removing the drift, as PyKrige does.

# `universal_3d`

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

Universal kriging in 3D (`pykrige.UniversalKriging3D`): `ordinary_3d/3` with
`:drift_terms` among `:regional_linear` (the x, y and z coordinates), `:specified` and
`:functional` (`fn x, y, z -> value end` at the adjusted coordinates), as in `universal/3`.

# `variogram_objective`

```elixir
@spec variogram_objective(t(), [number()]) :: float()
```

The `soft_l1` objective of the automatic variogram fit for `params` (PyKrige's form) on the
lags of `kriging`: `sum(2 (sqrt(1 + r^2) - 1))`, `r` the (weighted) residuals.

---

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