# Hierarchies

> Forecast series that add up (stores into regions into a total) so the forecasts add up too.

Many series come in a hierarchy: stores sum into regions and regions into a total, products into categories, meters into
feeders. Forecast each level on its own and the forecasts rarely add up: the regions' medians will not sum to the total's.
`yhatlabs.hierarchy` builds every level from the bottom rows and adjusts the forecasts so that every parent equals the sum of
its children.

## Build, forecast, reconcile

This forecasts the population of seven countries, the two regions they form and the total, five years ahead:

```python
import pandas as pd
from yhatlabs import Client, hierarchy

pop = pd.read_csv("https://raw.githubusercontent.com/datasets/population/main/data/population.csv")
region = {"SWE": "Nordic", "NOR": "Nordic", "DNK": "Nordic", "FIN": "Nordic", "EST": "Baltic", "LVA": "Baltic", "LTU": "Baltic"}
pop = pop[pop["Country Code"].isin(region)].assign(region=lambda d: d["Country Code"].map(region))

data, tree = hierarchy.aggregate(pop, levels=[["region"], ["region", "Country Code"]], time_col="Year", target_col="Value")
print(tree["total"], tree["region=Baltic"])

yh = Client()
fc = hierarchy.reconcile(yh.forecast(data, h=5, time_col="Year", target_col="Value", freq="YS"), tree)
last = fc.df[fc.df["Year"] == fc.df["Year"].max()].set_index("unique_id")["median"] / 1e6
print(last.round(2).to_string())
print("Baltic = sum of its countries:", round(last["region=Baltic"], 3) == round(sum(last[c] for c in tree["region=Baltic"]), 3))
```

Output:

```
['region=Baltic', 'region=Nordic'] ['region=Baltic/Country Code=EST', 'region=Baltic/Country Code=LTU', 'region=Baltic/Country Code=LVA']
unique_id
region=Baltic                      6.07
region=Baltic/Country Code=EST     1.36
region=Baltic/Country Code=LTU     2.91
region=Baltic/Country Code=LVA     1.80
region=Nordic                     28.43
region=Nordic/Country Code=DNK     6.17
region=Nordic/Country Code=FIN     5.74
region=Nordic/Country Code=NOR     5.79
region=Nordic/Country Code=SWE    10.74
total                             34.50
Baltic = sum of its countries: True
```

- `hierarchy.aggregate(rows, levels=...)` takes the bottom-level rows and the columns that define each level, from the top
  down; the last level is the bottom. It returns a long table with one series per node (`region=Baltic`,
  `region=Baltic/Country Code=EST`, ..., `total`) and the tree saying which children sum into each parent.
- `yh.forecast(...)` forecasts every node, as for any set of series.
- `hierarchy.reconcile(fc, tree)` adjusts every value column (median, mean and each quantile) so that each parent equals the
  sum of its children: here the Baltic forecast equals the sum of Estonia, Latvia and Lithuania.

## How it reconciles

Each node's own forecast counts in proportion to how few bottom series it sums: a country's forecast is trusted for the
country, the total's for the total. This uses the structure alone and needs no backtest, so it works from the first forecast.

- The median and mean add up exactly.
- Interval edges are adjusted the same way, but a sum of 90% quantiles is not the 90% quantile of the sum. When the
  uncertainty of a total matters (a regional reserve, say), forecast with `samples=` and sum the paths.
- `total=None` in `aggregate` leaves out the overall total; `fc.provenance["reconciled"]` records what was done.
