# Use case: drawing the map and the regions. Mexican states, 1940-2000

Run this notebook from a git checkout of Spatex: it installs Spatex from the checkout (`path:`).

## Setup

> **Not run in CI.** GeoFrame is not on Hex yet, so CI does not fetch it.
> Run this notebook locally with a GeoFrame checkout:
>
> ```
> SPATEX_GEOFRAME_PATH=/path/to/geoframe livebook server notebooks/mexico_case.livemd
> ```
>
> or headlessly, to check that every cell works:
>
> ```
> SPATEX_GEOFRAME_PATH=/path/to/geoframe elixir scripts/run_livemd.exs notebooks/mexico_case.livemd
> ```
>
> Spanish version: `notebooks/es/caso_regiones_mexico.livemd`.

```elixir
geoframe_path =
  System.get_env("SPATEX_GEOFRAME_PATH") ||
    raise "set SPATEX_GEOFRAME_PATH to a GeoFrame checkout before starting this notebook"

Mix.install([
  {:spatex, path: Path.join(__DIR__, "..")},
  {:rustler, "~> 0.38", runtime: false},
  {:geoframe, path: geoframe_path},
  {:explorer, "~> 0.13"},
  {:kino, "~> 0.19"}
])
```

## The question

A planning ministry is preparing a report on regional development. It needs two things that look
technical but change the message of the report:

1. A **map** of income by state. How the values are cut into colors decides what readers see.
2. A set of **regions** to organize policy. Do the official regions group states that really
   share an economic situation, or would other regions describe the country better?

The data are real: per-capita GDP of the 32 Mexican states every ten years from 1940 to 2000,
with several regional schemes used in the literature, among them the regions of INEGI, the
national statistics office (Rey and Sastre Gutiérrez, 2010, as distributed with PySAL).

## 1. Load the states

```elixir
require Explorer.DataFrame, as: DF
alias Explorer.Series, as: S
alias GeoFrame.GeoDataFrame, as: GDF

states =
  [__DIR__, "data", "mexico", "mexicojoin.shp"]
  |> Path.join()
  |> GeoFrame.read_file!()

data = GDF.data(states)
years = ~w(1940 1950 1960 1970 1980 1990 2000)
income = Enum.map(years, &S.to_list(data["PCGDP" <> &1]))

{GDF.n_rows(states), S.min(data["PCGDP2000"]), S.max(data["PCGDP2000"])}
```

In 2000 the richest state had more than six times the per-capita GDP of the poorest.

## 2. Same data, three maps

`Spatex.Classify` implements the classification schemes of mapclassify. With the same 2000 values
and five classes, three common choices:

```elixir
y = data["PCGDP2000"]

schemes =
  for scheme <- [:quantiles, :equal_interval, :fisher_jenks] do
    c = Spatex.Classify.classify(y, scheme, k: 5)
    %{scheme: Atom.to_string(scheme), upper_bounds: Enum.map(c.bins, &round/1), states_per_class: c.counts, gadf: c.gadf}
  end

DF.new(schemes)
```

* **Quantiles** put the same number of states in every class. The map looks balanced, but states
  with very different incomes end up in the same color and close ones are split.
* **Equal intervals** cut the range in equal steps. With one very rich state, 17 of the 32 states
  fall in the lowest class: the map says "almost everyone is poor".
* **Fisher-Jenks** chooses the cuts that make classes as homogeneous as possible.

The **goodness of absolute deviation fit** (GADF, 1 is a perfect fit) measures how well each
classification keeps states with similar values together. Fisher-Jenks is the best of the three.
`k_classifiers/2` asks the reverse question: how many classes each method needs to reach a GADF of
0.8.

```elixir
k_classifiers = Spatex.Classify.k_classifiers(y)

k_classifiers.results
|> Enum.map(fn {method, {k, _classification, gadf}} -> %{method: Atom.to_string(method), classes_needed: k, gadf: gadf} end)
|> DF.new()
|> DF.sort_by(asc: classes_needed)
```

Fisher-Jenks reaches the target with five classes; quantiles need nine. For the report, five
Fisher-Jenks classes give a readable legend that does not distort the data:

```elixir
states = Spatex.GeoFrame.put_results(states, Spatex.Classify.fisher_jenks(y, k: 5), prefix: "income_class_")

GeoFrame.Kino.deck(states,
  color: {"income_class_yb", :viridis},
  opacity: 0.85,
  tooltip: ["NAME", "PCGDP2000", "income_class_yb"]
)
```

## 3. How good are the official regions?

A region scheme is useful for economic policy if states in the same region are alike and regions
differ from each other. Theil's index measures that directly: the **between-region share** is the
part of inequality between states that the regions explain. `Spatex.Inequality.theil_d/3` gives it
for every decade at once.

```elixir
rows = Enum.zip_with(income, & &1)

between_share = fn labels ->
  t = Spatex.Inequality.theil_d(rows, labels)
  Enum.zip_with(t.bg, t.t, &(&1 / &2))
end

official = ~w(INEGI INEGI2 HANSON98 HANSON03 ESQUIVEL99)

official
|> Enum.map(fn scheme ->
  labels = S.to_list(data[scheme])
  shares = between_share.(labels)
  %{scheme: scheme, regions: length(Enum.uniq(labels)), share_1970: Enum.at(shares, 3), share_2000: List.last(shares)}
end)
|> DF.new()
```

INEGI's five regions, and its variant `INEGI2`, explain less than a fifth of the inequality
between states in 2000. They were
drawn for statistical and administrative purposes, not to group states by income, and it shows.
Other schemes from the literature, with five to seven regions, explain a third to a half.

## 4. Regions drawn from the data

`Spatex.Region` builds contiguous regions from attributes. The attributes here are the log incomes
of all seven decades, standardized, so a region groups neighboring states with a similar
**trajectory** since 1940. We ask for five regions, as many as INEGI's:

```elixir
graph = Spatex.GeoFrame.graph(states, :queen)

attrs = income |> Enum.map(fn decade -> Enum.map(decade, &:math.log/1) end) |> Spatex.Region.standardize()

regions = %{
  "AZP" => Spatex.Region.azp(attrs, graph, n_clusters: 5, seed: 1).labels,
  "SKATER (min. 3 states)" => Spatex.Region.skater(attrs, graph, n_clusters: 5, floor: 3).labels,
  "Ward (spatial)" => Spatex.Region.ward_spatial(attrs, graph, n_clusters: 5).labels,
  "INEGI" => S.to_list(data["INEGI"])
}

regions
|> Enum.map(fn {name, labels} ->
  sizes = labels |> Enum.frequencies() |> Map.values() |> Enum.sort()

  %{
    scheme: name,
    states_per_region: sizes,
    between_share_2000: List.last(between_share.(labels)),
    within_region_dissimilarity: Spatex.Region.objective(attrs, labels, kind: :center, metric: :sqeuclidean)
  }
end)
|> DF.new()
|> DF.sort_by(desc: between_share_2000)
```

With the same number of regions, the data-driven schemes explain between two and a half and four
times as much of the inequality as INEGI's, and their states are much more alike (lower
dissimilarity). The algorithms differ in a way that matters for policy:

* **Ward** gives the highest share but isolates Mexico City (Distrito Federal) as a region of its
  own: correct statistically, awkward administratively.
* **SKATER** with `floor: 3` forbids regions of fewer than three states, but leaves one large
  region of 16 states.
* **AZP** produces the most balanced regions, five to eight states each, at a lower but still much
  higher share than INEGI's.

```elixir
states =
  states
  |> GDF.put("region_azp", S.from_list(Enum.map(regions["AZP"], &"region #{&1}")))
  |> GDF.put("region_inegi", S.from_list(Enum.map(regions["INEGI"], &"INEGI #{round(&1)}")))

GeoFrame.Kino.deck(states,
  color: {"region_azp", :categorical},
  opacity: 0.85,
  tooltip: ["NAME", "PCGDP2000", "region_azp", "region_inegi"]
)
```

```elixir
regions["AZP"]
|> Enum.zip(S.to_list(data["NAME"]))
|> Enum.group_by(&elem(&1, 0), &elem(&1, 1))
|> Enum.map(fn {region, names} -> %{region: region, states: Enum.join(names, ", ")} end)
|> DF.new()
```

The AZP regions read like a map of Mexico's economy: the northern border states, the center-west,
the capital and its neighbors, the poorer south, and the Gulf and Yucatán peninsula.

A caution: these regions were fitted to these same incomes, so they are expected to explain them
better than a scheme drawn for other purposes. They are a strong starting point for an economic
regionalization, to be checked on other indicators before adopting them.

## 5. Deliverables

```elixir
out_dir = Path.join(System.tmp_dir!(), "mexico_case")
File.mkdir_p!(out_dir)

:ok = GeoFrame.write_file(states, Path.join(out_dir, "states_classes_regions.gpkg"))

out_dir |> File.ls!() |> Enum.sort()
```

## What this showed

* The **classification scheme** of a choropleth map changes its message; GADF and
  `k_classifiers/2` choose it on evidence instead of habit.
* **Theil's between-region share** scores any regional scheme against the data.
* **AZP, SKATER and spatial Ward** draw contiguous regions from data, with options (`floor`, the
  number of regions) that encode practical constraints.

The same tools serve to design sales territories, school or health districts, electoral wards
(with a population threshold, see Max-p in the North Carolina notebook), or any map that has to be
both accurate and readable.
