use std::collections::{BTreeMap, BTreeSet, HashMap, HashSet};
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
use std::time::{Instant, SystemTime, UNIX_EPOCH};
use crate::error::{
DatasetError, IoOp, IoResultExt as _, IoStepExt as _, JsonResultExt as _, NumberResultExt as _,
Result, WithinExt as _,
};
use geo::coordinate_position::CoordPos;
use geo::dimensions::Dimensions;
use geo::{BoundingRect as _, Centroid as _, MultiPolygon, Rect, Relate as _};
use serde::{Deserialize, Serialize};
use crate::areas::{Area, read_areas_geojson};
use crate::cli::BuildArgs;
use crate::config::{Comparison, DatasetConfig, MAX_LAYER_PERIODS};
use crate::country::CountryConfig;
use crate::crosswalk::{Crosswalk, LGD_ATTRIBUTION};
use crate::layer::{ClipMask, LayerStats, write_layer_pmtiles};
use crate::normals::{Normal, csv_field, parse_csv, read_normals_csv};
use crate::numbers::{AreaValue, CoverageTable, area_values_read};
use crate::rasters::{Period, RasterFile, Status, date_plus_days, discover, utc_compact, utc_iso};
use crate::series;
use crate::source::{Raster, ReadStats};
use geolith::admin::india::IndiaOutline;
const SERIES_LEN: usize = 12;
const MAX_NEIGHBOURS: usize = 8;
const NUMBERS_HEADER: &str = "area_id,name,state,country,period_start,period_end,status,value,\
normal,anomaly_pct,anomaly_abs,coverage_pct,cells,sparse,attribution";
const INDIA_NEEDS_OUTLINE: &str =
"dataset build covers India: pass --india-outline <Survey of India GeoJSON>";
fn area_slug(area: &Area) -> String {
match &area.parent_name {
Some(state) => format!("{}/{}", slugify(state), slugify(&area.name)),
None => slugify(&area.name),
}
}
fn area_slugs(areas: &[Area]) -> BTreeMap<String, String> {
let mut counts: BTreeMap<String, usize> = BTreeMap::new();
for area in areas {
*counts.entry(area_slug(area)).or_default() += 1;
}
areas
.iter()
.map(|area| {
let slug = area_slug(area);
let disambiguated = match (&area.code, counts.get(&slug)) {
(Some(code), Some(2..)) => format!("{slug}-{}", slugify(code)),
_ => slug,
};
(area.id.clone(), disambiguated)
})
.collect()
}
const PUBLISHED_HEADER: &str = "region_code,district,capital";
const PUBLISHED_CODE_HEADER: &str = "code";
#[must_use]
pub fn build_id(latest_period_end: &str, built_at_unix: i64) -> String {
format!("{latest_period_end}.{}", utc_compact(built_at_unix))
}
#[must_use]
pub fn anomaly(
value: f64,
normal: Option<f64>,
min_normal: Option<f64>,
) -> (Option<f64>, Option<f64>) {
let Some(normal) = normal else {
return (None, None);
};
let pct = min_normal
.is_some_and(|min| normal >= min)
.then(|| (value - normal) / normal * 100.0);
(pct, Some(value - normal))
}
const FOLD: &[(&str, &str)] = &[
("àáâãäåāăąạả", "a"),
("æ", "ae"),
("çćĉċč", "c"),
("ďđḍð", "d"),
("èéêëēĕėęěẹ", "e"),
("ĝğġģ", "g"),
("ĥħḥ", "h"),
("ìíîïĩīĭįıị", "i"),
("ij", "ij"),
("ĵ", "j"),
("ķ", "k"),
("ĺļľŀłḷḹ", "l"),
("ṃṁ", "m"),
("ñńņňʼnŋṅṇ", "n"),
("òóôõöøōŏőọ", "o"),
("œ", "oe"),
("ŕŗřṛṝ", "r"),
("śŝşšṣ", "s"),
("ß", "ss"),
("ţťŧṭ", "t"),
("þ", "th"),
("ùúûüũūŭůűųụ", "u"),
("ŵ", "w"),
("ýÿŷ", "y"),
("źżž", "z"),
];
#[must_use]
pub fn slugify(name: &str) -> String {
let mut slug = String::with_capacity(name.len());
let mut pending_dash = false;
let mut push = |c: char, slug: &mut String| {
if c.is_ascii_alphanumeric() {
if pending_dash && !slug.is_empty() {
slug.push('-');
}
pending_dash = false;
slug.push(c);
} else {
pending_dash = true;
}
};
for c in name.chars().flat_map(char::to_lowercase) {
if c.is_ascii() {
push(c, &mut slug);
} else if let Some((_, ascii)) = FOLD.iter().find(|(from, _)| from.contains(c)) {
for a in ascii.chars() {
push(a, &mut slug);
}
}
}
slug
}
fn rects_meet(a: Rect<f64>, b: Rect<f64>) -> bool {
a.min().x <= b.max().x
&& b.min().x <= a.max().x
&& a.min().y <= b.max().y
&& b.min().y <= a.max().y
}
fn share_a_border(a: &MultiPolygon<f64>, b: &MultiPolygon<f64>) -> bool {
let matrix = a.relate(b);
matrix.get(CoordPos::OnBoundary, CoordPos::OnBoundary) == Dimensions::OneDimensional
|| matrix.get(CoordPos::Inside, CoordPos::Inside) == Dimensions::TwoDimensional
}
#[must_use]
pub fn neighbours(areas: &[Area], max: usize) -> HashMap<String, Vec<String>> {
let info: Vec<_> = areas
.iter()
.map(|a| (a.shape.bounding_rect(), a.shape.centroid()))
.collect();
let mut near: Vec<Vec<(f64, &str)>> = vec![Vec::new(); areas.len()];
for (i, (area, (rect, centre))) in areas.iter().zip(&info).enumerate() {
let Some(rect) = rect else { continue };
for (j, (other, (other_rect, other_centre))) in
areas.iter().zip(&info).enumerate().skip(i + 1)
{
let bordering = other_rect.is_some_and(|r| rects_meet(*rect, r))
&& share_a_border(&area.shape, &other.shape);
if !bordering {
continue;
}
let distance = match (centre, other_centre) {
(Some(a), Some(b)) => (a.x() - b.x()).hypot(a.y() - b.y()),
_ => f64::INFINITY,
};
near[i].push((distance, other.id.as_str()));
near[j].push((distance, area.id.as_str()));
}
}
let mut found = HashMap::with_capacity(areas.len());
for (area, mut list) in areas.iter().zip(near) {
list.sort_by(|a, b| a.0.total_cmp(&b.0).then_with(|| a.1.cmp(b.1)));
list.truncate(max);
found.insert(
area.id.clone(),
list.into_iter().map(|(_, id)| id.to_owned()).collect(),
);
}
found
}
const fn next_period(p: Period) -> Period {
let last = p.kind.periods_per_month();
match (p.index >= last, p.month >= 12) {
(true, true) => Period {
year: p.year + 1,
month: 1,
index: 1,
..p
},
(true, false) => Period {
month: p.month + 1,
index: 1,
..p
},
(false, _) => Period {
index: p.index + 1,
..p
},
}
}
fn season_span(season_start: &str, latest: Period) -> Option<(String, Vec<Period>)> {
let (month, day) = season_start.split_once('-')?;
let (month, day): (u8, u8) = (month.parse().ok()?, day.parse().ok()?);
let (end_year, end_month, end_day) = latest.end();
let year = if (month, day) <= (end_month, end_day) {
end_year
} else {
end_year - 1
};
let starts = latest.kind.starts();
let index = starts.iter().filter(|&&start| start <= day).count().max(1);
let mut period = Period {
year,
month,
index: u8::try_from(index).ok()?,
kind: latest.kind,
};
let mut span = Vec::new();
while period <= latest {
span.push(period);
period = next_period(period);
}
Some((format!("{year:04}-{month:02}-{day:02}"), span))
}
fn season_totals(
span: &[Period],
value_of: impl Fn(Period) -> Option<f64>,
normal_of: impl Fn(Period) -> Option<f64>,
min_normal: Option<f64>,
) -> (Option<f64>, Option<f64>, Option<f64>) {
let value: Option<f64> = span.iter().map(|p| value_of(*p)).sum();
let normal: Option<f64> = span.iter().map(|p| normal_of(*p)).sum();
let pct = value.and_then(|v| anomaly(v, normal, min_normal).0);
(value, normal, pct)
}
#[derive(Debug, Clone, PartialEq, Eq, Hash, Serialize, Deserialize)]
pub struct ComparisonRecord {
pub kind: Comparison,
pub baseline: String,
pub label: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sensor: Option<String>,
}
fn comparison_of(
config: &DatasetConfig,
path: Option<&Path>,
normals: &[Normal],
) -> Result<Option<ComparisonRecord>> {
let (Comparison::Average, Some(path)) = (config.comparison, path) else {
return Ok(None);
};
let baselines: BTreeSet<&str> = normals.iter().map(|n| n.baseline.as_str()).collect();
let baseline = match baselines.iter().collect::<Vec<_>>().as_slice() {
[one] => (**one).to_owned(),
[] => {
return Err(DatasetError::data(format!(
"{}: no normals row gives a baseline",
path.display()
)));
}
several => {
return Err(DatasetError::data(format!(
"{}: normals rows hold {} baselines ({}): one build compares with one",
path.display(),
several.len(),
baselines.iter().copied().collect::<Vec<_>>().join(", ")
)));
}
};
if let Some(wanted) = &config.baseline
&& *wanted != baseline
{
return Err(DatasetError::data(format!(
"{}: normals of baseline {baseline}, but the config asks for {wanted}",
path.display()
)));
}
let label = config
.comparison_label(&baseline)
.ok_or_else(|| DatasetError::data("an average dataset has a comparison label"))?;
Ok(Some(ComparisonRecord {
kind: config.comparison,
baseline,
label,
sensor: config.sensor.clone(),
}))
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct SeriesPoint {
pub period_start: String,
pub period_end: String,
pub days: u8,
pub value: Option<f64>,
pub normal: Option<f64>,
pub status: Status,
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct AreaRecord {
pub id: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub code: Option<String>,
pub lgd_code: Option<String>,
pub approximate: bool,
pub sparse: bool,
pub name: String,
pub state: Option<String>,
pub country: String,
pub slug: String,
pub dataset: String,
pub unit: String,
pub period_start: String,
pub period_end: String,
pub days: u8,
pub status: Status,
pub stale_after: String,
pub value: Option<f64>,
pub normal: Option<f64>,
pub anomaly_pct: Option<f64>,
pub anomaly_abs: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub comparison: Option<ComparisonRecord>,
pub season_start: Option<String>,
pub season_value: Option<f64>,
pub season_normal: Option<f64>,
pub season_anomaly_pct: Option<f64>,
pub series: Vec<SeriesPoint>,
pub neighbours: Vec<String>,
pub source: String,
pub attribution: String,
pub licence: String,
pub codes_attribution: Option<String>,
pub built_at: String,
pub engine_version: String,
pub boundary_release: String,
pub coverage_pct: f64,
pub cells: u32,
pub fallback: bool,
}
#[derive(Debug, Serialize, PartialEq)]
pub struct ExcludedRow {
pub id: String,
pub coverage_pct: f64,
}
#[derive(Debug, Serialize)]
struct IndexRow<'a> {
id: &'a str,
slug: &'a str,
name: &'a str,
state: Option<&'a str>,
value: Option<f64>,
anomaly_pct: Option<f64>,
normal: Option<f64>,
anomaly_abs: Option<f64>,
approximate: bool,
#[serde(skip_serializing_if = "Option::is_none")]
value_class: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
comparison_class: Option<String>,
}
#[derive(Debug, Serialize)]
struct HistoryLayer {
period_end: String,
path: String,
max_zoom: u8,
tiles_written: u64,
bytes: u64,
ms: f64,
}
#[derive(Debug, Serialize)]
struct Index<'a> {
dataset: &'a str,
country: String,
build_id: &'a str,
status: Status,
period_start: String,
period_end: &'a str,
days: u8,
stale_after: &'a str,
#[serde(skip_serializing_if = "Option::is_none")]
comparison: Option<&'a ComparisonRecord>,
attribution: &'a str,
licence: &'a str,
codes_attribution: Option<&'a str>,
published: Vec<String>,
#[serde(skip_serializing_if = "<[ExcludedRow]>::is_empty")]
excluded: Vec<ExcludedRow>,
areas: Vec<IndexRow<'a>>,
}
#[derive(Debug, Serialize)]
struct ManifestFile {
path: String,
bytes: u64,
}
#[derive(Debug, Serialize)]
struct Manifest<'a> {
build_id: &'a str,
attribution: &'a str,
files: Vec<ManifestFile>,
}
#[derive(Debug, Serialize)]
struct BuildMs {
coverage: f64,
neighbours: f64,
numbers: f64,
layer: f64,
history_layers: f64,
write: f64,
}
#[derive(Debug, Serialize)]
struct StepReads {
numbers: u64,
layer: u64,
}
#[derive(Debug, Serialize)]
struct BuildStats<'a> {
rasters: usize,
areas: usize,
attribution: &'a str,
ms: BuildMs,
windows_read: StepReads,
pixels_read: StepReads,
fallback_cells: BTreeMap<&'a str, [f64; 2]>,
}
#[derive(Debug, Serialize)]
struct LayerStatsFile<'a> {
#[serde(flatten)]
stats: &'a LayerStats,
attribution: &'a str,
#[serde(skip_serializing_if = "<[HistoryLayer]>::is_empty")]
history: &'a [HistoryLayer],
}
fn ms_since(started: Instant) -> f64 {
started.elapsed().as_secs_f64() * 1000.0
}
fn csv_number(value: Option<f64>) -> String {
value.map(|v| v.to_string()).unwrap_or_default()
}
fn write_json(path: &Path, value: &impl Serialize) -> Result<()> {
let text =
serde_json::to_string_pretty(value).json_of(format!("encoding {}", path.display()))?;
std::fs::write(path, text).io_at(IoOp::Write, path)
}
fn list_files(dir: &Path) -> Result<Vec<ManifestFile>> {
let mut files = Vec::new();
let mut pending = vec![dir.to_path_buf()];
while let Some(current) = pending.pop() {
for entry in std::fs::read_dir(¤t).io_at(IoOp::List, ¤t)? {
let entry = entry.io_at(IoOp::List, ¤t)?;
let path = entry.path();
let meta = entry.metadata().io_at(IoOp::Read, &path)?;
if meta.is_dir() {
pending.push(path);
continue;
}
let relative = path.strip_prefix(dir).within(format!(
"{} is outside {}",
path.display(),
dir.display()
))?;
let parts: Vec<String> = relative
.components()
.map(|c| c.as_os_str().to_string_lossy().into_owned())
.collect();
files.push(ManifestFile {
path: parts.join("/"),
bytes: meta.len(),
});
}
}
files.sort_by(|a, b| a.path.cmp(&b.path));
Ok(files)
}
struct Numbers {
values: BTreeMap<Period, Vec<AreaValue>>,
latest: Raster,
reads: ReadStats,
coverage_ms: f64,
numbers_ms: f64,
}
fn read_numbers(
needed: &BTreeMap<Period, &RasterFile>,
latest: Period,
areas: &[Area],
config: &DatasetConfig,
) -> Result<Numbers> {
let started = Instant::now();
let mut coverage_ms = 0.0;
let mut table: Option<CoverageTable> = None;
let mut values = BTreeMap::new();
let mut reads = ReadStats::default();
let mut latest_raster = None;
for (period, raster) in needed {
let source = Raster::open(&raster.path, config)?;
let current = match table.take() {
Some(t) => t,
None => {
let built = Instant::now();
let grid = source.grid().within(raster.path.display().to_string())?;
let t = CoverageTable::build(areas, grid);
coverage_ms = ms_since(built);
t
}
};
let (period_values, period_reads) =
area_values_read(¤t, &source, config, &raster.path)?;
reads.windows += period_reads.windows;
reads.pixels += period_reads.pixels;
values.insert(*period, period_values);
table = Some(current);
if *period == latest {
latest_raster = Some(source);
}
}
Ok(Numbers {
values,
latest: latest_raster
.ok_or_else(|| DatasetError::data("the latest raster was not read"))?,
reads,
coverage_ms,
numbers_ms: ms_since(started) - coverage_ms,
})
}
pub fn resolve_published(csv: &Path, areas: &[Area]) -> Result<Vec<String>> {
let text = std::fs::read_to_string(csv).io_at(IoOp::Read, csv)?;
let body: String = text
.lines()
.filter(|line| !line.trim_start().starts_with('#'))
.collect::<Vec<_>>()
.join("\n");
let records = parse_csv(&body).within(format!("parsing {}", csv.display()))?;
let mut records = records.into_iter();
let header = records.next().unwrap_or_default().join(",");
if header == PUBLISHED_CODE_HEADER {
return resolve_published_codes(csv, records.collect(), areas);
}
if header != PUBLISHED_HEADER {
return Err(DatasetError::data(format!(
"{}: header is {header:?}, expected {PUBLISHED_HEADER:?} or {PUBLISHED_CODE_HEADER:?}",
csv.display()
)));
}
let mut ids = Vec::with_capacity(records.len());
let mut first_row: HashMap<String, usize> = HashMap::with_capacity(records.len());
for (index, record) in records.enumerate() {
let row = index + 2;
let [region_code, district, _capital]: [String; 3] =
record.try_into().map_err(|r: Vec<String>| {
DatasetError::data(format!(
"{} row {row}: {} fields, expected 3",
csv.display(),
r.len()
))
})?;
let matches: Vec<&Area> = areas
.iter()
.filter(|a| {
a.region_code.as_deref() == Some(region_code.as_str()) && a.name == district
})
.collect();
match matches.as_slice() {
[area] => {
if let Some(earlier) = first_row.insert(area.id.clone(), row) {
return Err(DatasetError::data(format!(
"{} rows {earlier} and {row} both name area {:?} ({region_code}, \
{district})",
csv.display(),
area.id
)));
}
ids.push(area.id.clone());
}
[] => {
return Err(DatasetError::data(format!(
"{} row {row} ({region_code}, {district}) matches no area",
csv.display()
)));
}
several => {
return Err(DatasetError::data(format!(
"{} row {row} ({region_code}, {district}) matches {} areas",
csv.display(),
several.len()
)));
}
}
}
ids.sort();
Ok(ids)
}
fn resolve_published_codes(
csv: &Path,
records: Vec<Vec<String>>,
areas: &[Area],
) -> Result<Vec<String>> {
let by_code: HashMap<&str, &Area> = areas
.iter()
.filter_map(|area| area.code.as_deref().map(|code| (code, area)))
.collect();
let mut ids = Vec::with_capacity(records.len());
let mut first_row: HashMap<String, usize> = HashMap::with_capacity(records.len());
for (index, record) in records.into_iter().enumerate() {
let row = index + 2;
let [code]: [String; 1] = record.try_into().map_err(|r: Vec<String>| {
DatasetError::data(format!(
"{} row {row}: {} fields, expected 1",
csv.display(),
r.len()
))
})?;
let Some(area) = by_code.get(code.as_str()) else {
return Err(DatasetError::data(format!(
"{} row {row} ({code}) matches no area: no area carries that code",
csv.display()
)));
};
if let Some(earlier) = first_row.insert(area.id.clone(), row) {
return Err(DatasetError::data(format!(
"{} rows {earlier} and {row} both name area {:?} ({code})",
csv.display(),
area.id
)));
}
ids.push(area.id.clone());
}
ids.sort();
Ok(ids)
}
fn is_shipped(path: &str) -> bool {
matches!(
path,
"tiles.pmtiles" | "index.json" | "numbers.csv" | "series.json"
) || path
.strip_prefix("areas/")
.is_some_and(|name| !name.contains('/') && name.ends_with(".json"))
|| path
.strip_prefix("tiles/")
.and_then(|name| name.strip_suffix(".pmtiles"))
.is_some_and(is_iso_day)
}
fn is_iso_day(text: &str) -> bool {
let b = text.as_bytes();
b.len() == 10
&& b.iter().enumerate().all(|(i, c)| match i {
4 | 7 => *c == b'-',
_ => c.is_ascii_digit(),
})
}
fn history_layer_path(period_end: &str) -> String {
format!("tiles/{period_end}.pmtiles")
}
pub fn run(args: &BuildArgs) -> Result<()> {
let now = SystemTime::now()
.duration_since(UNIX_EPOCH)
.map_err(DatasetError::Clock)?;
let built_at = i64::try_from(now.as_secs()).number_of("system clock out of range")?;
let dir = run_at(args, built_at)?;
println!("{}", dir.display());
Ok(())
}
#[derive(Debug, Default, PartialEq)]
struct BuildLimits {
bounds: Option<[f64; 4]>,
min_coverage_pct: Option<f64>,
codes_attribution: Option<String>,
max_zoom: Option<u8>,
history_max_zoom: Option<u8>,
}
fn parse_bounds(text: &str) -> Result<[f64; 4]> {
let parts: Vec<&str> = text.split(',').map(str::trim).collect();
let numbers: Vec<f64> = parts
.iter()
.map(|part| {
part.parse::<f64>()
.number_of(format!("--bounds {text:?}: {part:?} is not a number"))
})
.collect::<Result<_>>()?;
let [min_lon, min_lat, max_lon, max_lat]: [f64; 4] = numbers
.try_into()
.map_err(|_| DatasetError::usage(format!("--bounds needs four numbers, got {text:?}")))?;
let rises = |a: f64, b: f64| a.partial_cmp(&b) == Some(std::cmp::Ordering::Less);
if !rises(min_lon, max_lon) || !rises(min_lat, max_lat) {
return Err(DatasetError::usage(format!(
"--bounds {text:?} is out of order: needs min_lon < max_lon and min_lat < max_lat"
)));
}
Ok([min_lon, min_lat, max_lon, max_lat])
}
fn build_limits(
args: &BuildArgs,
country: Option<&CountryConfig>,
dataset: &str,
) -> Result<BuildLimits> {
let limits = country.and_then(|c| c.limits(dataset));
Ok(BuildLimits {
bounds: args.bounds.as_deref().map(parse_bounds).transpose()?,
min_coverage_pct: args
.min_coverage
.or_else(|| limits.and_then(|l| l.min_coverage_pct)),
codes_attribution: args
.codes_attribution
.clone()
.or_else(|| country.and_then(|c| c.boundaries.codes_attribution.clone())),
max_zoom: limits.and_then(|l| l.max_zoom),
history_max_zoom: limits.and_then(|l| l.history_max_zoom),
})
}
pub fn run_at(args: &BuildArgs, built_at_unix: i64) -> Result<PathBuf> {
let mut config = DatasetConfig::load(&args.config)?;
let country_config = args
.country_config
.as_deref()
.map(CountryConfig::load)
.transpose()?;
let limits = build_limits(args, country_config.as_ref(), &config.id)?;
if let Some(zoom) = limits.max_zoom {
config.max_zoom = zoom;
}
if let Some(zoom) = limits.history_max_zoom {
config.history_max_zoom = Some(zoom);
}
let areas_file = read_areas_geojson(&args.areas)?;
let areas = &areas_file.areas;
let covers_india = areas.iter().any(|a| a.country == "IN");
if covers_india && args.india_outline.is_none() {
return Err(DatasetError::data(INDIA_NEEDS_OUTLINE));
}
let countries: BTreeSet<&str> = areas.iter().map(|a| a.country.as_str()).collect();
if countries.len() > 1 {
return Err(DatasetError::data(format!(
"the areas hold {} countries ({}): one build is one country",
countries.len(),
countries.iter().copied().collect::<Vec<_>>().join(", ")
)));
}
let country = countries.first().copied().unwrap_or_default().to_owned();
let mut ids = HashSet::with_capacity(areas.len());
if let Some(repeated) = areas.iter().find(|a| !ids.insert(a.id.as_str())) {
return Err(DatasetError::data(format!(
"area id {:?} appears more than once",
repeated.id
)));
}
if let Some(bad) = areas
.iter()
.find(|a| a.id.is_empty() || a.id.contains(['/', '\\']) || a.id.starts_with('.'))
{
return Err(DatasetError::data(format!(
"area id {:?} cannot name a file",
bad.id
)));
}
let published = match &args.published {
Some(csv) => resolve_published(csv, areas)?,
None => Vec::new(),
};
let crosswalk = match &args.crosswalk {
Some(csv) => Crosswalk::read(csv, areas)?,
None => Crosswalk::default(),
};
let codes_attribution = limits
.codes_attribution
.clone()
.or_else(|| crosswalk.has_codes().then(|| LGD_ATTRIBUTION.to_string()));
let clip = match &args.india_outline {
Some(path) if covers_india => {
Some(ClipMask::new(IndiaOutline::load(path)?.polygons().clone()))
}
_ => None,
};
let layer_bounds = limits.bounds.or_else(|| {
clip.is_none()
.then(|| country_config.as_ref().map(|c| c.bounds))
.flatten()
});
let found = discover(
&args.rasters,
&config.file_template,
config.prelim_template(),
)?;
let Some(latest) = found.last() else {
return Err(DatasetError::data(format!(
"no raster in {} matches the template {} (final/) or {} (prelim/)",
args.rasters.display(),
config.file_template,
config.prelim_template()
)));
};
config.attribution = config.attribution_for((latest.period.year, latest.period.year));
let layer_periods = args.layer_periods.or(config.layer_periods).unwrap_or(1);
if !(1..=MAX_LAYER_PERIODS).contains(&layer_periods) {
return Err(DatasetError::usage(format!(
"--layer-periods {layer_periods} is not 1 to {MAX_LAYER_PERIODS}"
)));
}
let latest_end = latest.period.end_iso();
let stale_after = date_plus_days(latest.period.end(), config.stale_after_days);
let id = build_id(&latest_end, built_at_unix);
let final_dir = args.out.join(&id);
if final_dir.exists() {
return Err(DatasetError::data(format!(
"build dir {} exists: dated outputs are never overwritten",
final_dir.display()
)));
}
let normal_rows = match &args.normals {
Some(path) => read_normals_csv(path)?,
None => Vec::new(),
};
let comparison = comparison_of(&config, args.normals.as_deref(), &normal_rows)?;
let normal_baselines: BTreeSet<String> =
normal_rows.iter().map(|n| n.baseline.clone()).collect();
let normal_baseline = match normal_baselines.len() {
1 => normal_baselines.into_iter().next(),
_ => None,
};
let normals: HashMap<(String, String), f64> = normal_rows
.into_iter()
.map(|n| ((n.area_id, n.slot), n.normal))
.collect();
let normal_of =
|area_id: &str, period: Period| normals.get(&(area_id.to_owned(), period.slot())).copied();
let series = &found[found.len().saturating_sub(SERIES_LEN)..];
let season = config
.season_start
.as_deref()
.and_then(|s| season_span(s, latest.period));
let mut needed: BTreeMap<Period, &RasterFile> = series.iter().map(|r| (r.period, r)).collect();
let mut season_complete = false;
if let Some((_, span)) = &season {
let on_disk: BTreeMap<Period, &RasterFile> = found.iter().map(|r| (r.period, r)).collect();
let complete: Option<Vec<&RasterFile>> =
span.iter().map(|p| on_disk.get(p).copied()).collect();
season_complete = complete.is_some();
needed.extend(
complete
.unwrap_or_default()
.into_iter()
.map(|r| (r.period, r)),
);
}
let numbers = read_numbers(&needed, latest.period, areas, &config)?;
let value_at =
|period: Period, index: usize| numbers.values.get(&period).and_then(|v| v.get(index));
let started = Instant::now();
let near = neighbours(areas, MAX_NEIGHBOURS);
let neighbours_ms = ms_since(started);
let built_at = utc_iso(built_at_unix);
let latest_values = numbers
.values
.get(&latest.period)
.ok_or_else(|| DatasetError::data("no values for the latest period"))?;
let keep: Vec<bool> = (0..areas.len())
.map(|index| {
limits
.min_coverage_pct
.is_none_or(|floor| latest_values[index].coverage_pct >= floor)
})
.collect();
let mut excluded: Vec<ExcludedRow> = areas
.iter()
.enumerate()
.filter(|(index, _)| !keep[*index])
.map(|(index, area)| ExcludedRow {
id: area.id.clone(),
coverage_pct: latest_values[index].coverage_pct,
})
.collect();
excluded.sort_by(|a, b| a.id.cmp(&b.id));
if let Some(id) = published.iter().find(|id| {
areas
.iter()
.position(|a| a.id == **id)
.is_none_or(|index| !keep[index])
}) {
let coverage = excluded
.iter()
.find(|row| row.id == *id)
.map_or(0.0, |row| row.coverage_pct);
return Err(DatasetError::usage(format!(
"--published names area {id}, which this build excludes: its coverage is \
{coverage:.1}%, under the {}% floor",
limits.min_coverage_pct.unwrap_or(0.0)
)));
}
let mut records = Vec::with_capacity(areas.len());
let mut slugs: HashMap<String, String> = HashMap::with_capacity(areas.len());
let by_id = area_slugs(areas);
for (index, area) in areas.iter().enumerate() {
if !keep[index] {
continue;
}
let current = value_at(latest.period, index)
.ok_or_else(|| DatasetError::data(format!("no value for area {}", area.id)))?;
let normal = normal_of(&area.id, latest.period);
let (anomaly_pct, anomaly_abs) = current.value.map_or((None, None), |v| {
anomaly(v, normal, config.anomaly_pct_min_normal)
});
let (season_value, season_normal, season_anomaly_pct) = match &season {
Some((_, span)) if season_complete => season_totals(
span,
|p| value_at(p, index).and_then(|v| v.value),
|p| normal_of(&area.id, p),
config.anomaly_pct_min_normal,
),
_ => (None, None, None),
};
let series_points = series
.iter()
.map(|r| SeriesPoint {
period_start: r.period.start_iso(),
period_end: r.period.end_iso(),
days: r.period.days(),
value: value_at(r.period, index).and_then(|v| v.value),
normal: normal_of(&area.id, r.period),
status: r.status,
})
.collect();
let slug = by_id
.get(&area.id)
.cloned()
.unwrap_or_else(|| area_slug(area));
let label = crosswalk.label(&area.id);
if let Some(other) = slugs.insert(slug.clone(), area.id.clone()) {
return Err(DatasetError::data(format!(
"two areas share the slug {:?}: {other} and {}",
slug, area.id
)));
}
records.push(AreaRecord {
id: area.id.clone(),
code: area.code.clone(),
lgd_code: label.lgd_code,
approximate: area.code.is_none() && label.approximate,
sparse: current.sparse,
name: area.name.clone(),
state: area.parent_name.clone(),
country: area.country.clone(),
slug,
dataset: config.id.clone(),
unit: config.unit.clone(),
period_start: latest.period.start_iso(),
period_end: latest_end.clone(),
days: latest.period.days(),
status: latest.status,
stale_after: stale_after.clone(),
value: current.value,
normal,
anomaly_pct,
anomaly_abs,
comparison: comparison.clone(),
season_start: season.as_ref().map(|(start, _)| start.clone()),
season_value,
season_normal,
season_anomaly_pct,
series: series_points,
neighbours: near.get(&area.id).cloned().unwrap_or_default(),
source: config.source_url.clone(),
attribution: config.attribution.clone(),
licence: config.licence.clone(),
codes_attribution: codes_attribution.clone(),
built_at: built_at.clone(),
engine_version: env!("CARGO_PKG_VERSION").to_owned(),
boundary_release: areas_file.boundary_release.clone(),
coverage_pct: current.coverage_pct,
cells: current.cells,
fallback: current.fallback,
});
}
records.sort_by(|a, b| a.id.cmp(&b.id));
std::fs::create_dir_all(&args.out).io_at(IoOp::Create, &args.out)?;
let dir = args.out.join(format!(".{id}.partial"));
match std::fs::remove_dir_all(&dir) {
Err(e) if e.kind() == ErrorKind::NotFound => {}
other => other.io_at(IoOp::Remove, &dir)?,
}
std::fs::create_dir(&dir).io_at(IoOp::Create, &dir)?;
let areas_dir = dir.join("areas");
std::fs::create_dir(&areas_dir).io_at(IoOp::Create, &areas_dir)?;
let started = Instant::now();
let (layer, reads) = write_layer_pmtiles(
&numbers.latest,
&config,
clip.as_ref(),
&dir.join("tiles.pmtiles"),
&latest_end,
layer_bounds,
)?;
let layer_ms = ms_since(started);
tracing::info!(
windows = reads.windows,
pixels = reads.pixels,
"dataset layer windows read"
);
let started = Instant::now();
let history_zoom = config.history_max_zoom.unwrap_or(config.max_zoom);
let before_latest = &series[..series.len().saturating_sub(1)];
let history_files = &before_latest[before_latest
.len()
.saturating_sub(usize::from(layer_periods) - 1)..];
let mut history = Vec::with_capacity(history_files.len());
if !history_files.is_empty() {
std::fs::create_dir(dir.join("tiles")).io_at(IoOp::Create, dir.join("tiles"))?;
}
for file in history_files {
let period_end = file.period.end_iso();
let path = history_layer_path(&period_end);
let mut period_config = config.clone();
period_config.max_zoom = history_zoom;
let raster = Raster::open(&file.path, &period_config)?;
let one = Instant::now();
let (stats, _) = write_layer_pmtiles(
&raster,
&period_config,
clip.as_ref(),
&dir.join(&path),
&period_end,
layer_bounds,
)?;
history.push(HistoryLayer {
period_end,
path,
max_zoom: history_zoom,
tiles_written: stats.tiles_written,
bytes: stats.bytes,
ms: ms_since(one),
});
}
let history_ms = ms_since(started);
let started = Instant::now();
for record in &records {
write_json(&areas_dir.join(format!("{}.json", record.id)), record)?;
}
let index = Index {
dataset: &config.id,
country,
build_id: &id,
status: latest.status,
period_start: latest.period.start_iso(),
period_end: &latest_end,
days: latest.period.days(),
stale_after: &stale_after,
comparison: comparison.as_ref(),
attribution: &config.attribution,
licence: &config.licence,
codes_attribution: codes_attribution.as_deref(),
published,
excluded,
areas: records
.iter()
.map(|r| IndexRow {
id: &r.id,
slug: &r.slug,
name: &r.name,
state: r.state.as_deref(),
value: r.value,
anomaly_pct: r.anomaly_pct,
normal: r.normal,
anomaly_abs: r.anomaly_abs,
approximate: r.approximate,
value_class: config
.classes
.as_ref()
.map(|c| series::value_code(r.value, c).to_string()),
comparison_class: config.classes.as_ref().map(|c| {
series::comparison_code(r.value, r.normal, c, config.anomaly_pct_min_normal)
.to_string()
}),
})
.collect(),
};
write_json(&dir.join("index.json"), &index)?;
if config.classes.is_some() {
let header = series::SeriesHeader {
country: &index.country,
build_id: &id,
codes_attribution: codes_attribution.as_deref(),
comparison: comparison.as_ref(),
normal_baseline: normal_baseline.as_deref(),
};
let file = series::series_file(&config, &records, &header, |end| {
if end == latest_end {
Some(series::PeriodLayer {
path: "tiles.pmtiles".to_owned(),
max_zoom: config.max_zoom,
})
} else {
history
.iter()
.find(|h| h.period_end == end)
.map(|h| series::PeriodLayer {
path: h.path.clone(),
max_zoom: h.max_zoom,
})
}
})?;
write_json(&dir.join("series.json"), &file)?;
}
write_numbers_csv(
&dir.join("numbers.csv"),
areas,
series,
&numbers,
&normal_of,
&config,
)?;
write_json(
&dir.join("layer-stats.json"),
&LayerStatsFile {
stats: &layer,
attribution: &config.attribution,
history: &history,
},
)?;
let write_ms = ms_since(started);
let latest_values = numbers
.values
.get(&latest.period)
.ok_or_else(|| DatasetError::data("no values for the latest period"))?;
let stats = BuildStats {
rasters: needed.len(),
areas: areas.len(),
attribution: &config.attribution,
ms: BuildMs {
coverage: numbers.coverage_ms,
neighbours: neighbours_ms,
numbers: numbers.numbers_ms,
layer: layer_ms,
history_layers: history_ms,
write: write_ms,
},
windows_read: StepReads {
numbers: numbers.reads.windows,
layer: reads.windows,
},
pixels_read: StepReads {
numbers: numbers.reads.pixels,
layer: reads.pixels,
},
fallback_cells: latest_values
.iter()
.filter_map(|v| v.fallback_cell.map(|cell| (v.area_id.as_str(), cell)))
.collect(),
};
write_json(&dir.join("build-stats.json"), &stats)?;
let manifest = Manifest {
build_id: &id,
attribution: &config.attribution,
files: list_files(&dir)?
.into_iter()
.filter(|f| is_shipped(&f.path))
.collect(),
};
write_json(&dir.join("manifest.json"), &manifest)?;
if final_dir.exists() {
std::fs::remove_dir_all(&dir).io_at(IoOp::Remove, &dir)?;
return Err(DatasetError::data(format!(
"build dir {} exists: dated outputs are never overwritten",
final_dir.display()
)));
}
std::fs::rename(&dir, &final_dir).io_step(format!(
"renaming {} to {}",
dir.display(),
final_dir.display()
))?;
Ok(final_dir)
}
fn write_numbers_csv(
path: &Path,
areas: &[Area],
series: &[RasterFile],
numbers: &Numbers,
normal_of: &impl Fn(&str, Period) -> Option<f64>,
config: &DatasetConfig,
) -> Result<()> {
let attribution = csv_field(&config.attribution);
let mut rows: Vec<(&str, String, String)> = Vec::with_capacity(areas.len() * series.len());
for (index, area) in areas.iter().enumerate() {
for raster in series {
let Some(v) = numbers
.values
.get(&raster.period)
.and_then(|values| values.get(index))
else {
continue;
};
let normal = normal_of(&area.id, raster.period);
let (pct, abs) = v.value.map_or((None, None), |value| {
anomaly(value, normal, config.anomaly_pct_min_normal)
});
let status = match raster.status {
Status::Final => "final",
Status::Prelim => "prelim",
};
let line = format!(
"{},{},{},{},{},{},{status},{},{},{},{},{},{},{},{attribution}\n",
csv_field(&area.id),
csv_field(&area.name),
csv_field(area.parent_name.as_deref().unwrap_or_default()),
csv_field(&area.country),
raster.period.start_iso(),
raster.period.end_iso(),
csv_number(v.value),
csv_number(normal),
csv_number(pct),
csv_number(abs),
v.coverage_pct,
v.cells,
v.sparse,
);
rows.push((&area.id, raster.period.end_iso(), line));
}
}
rows.sort_by(|a, b| (a.0, &a.1).cmp(&(b.0, &b.1)));
let mut text = String::with_capacity(
NUMBERS_HEADER.len() + 1 + rows.iter().map(|r| r.2.len()).sum::<usize>(),
);
text.push_str(NUMBERS_HEADER);
text.push('\n');
for (_, _, line) in &rows {
text.push_str(line);
}
std::fs::write(path, text).io_at(IoOp::Write, path)
}
#[cfg(test)]
mod tests {
use geo::{MultiPolygon, Polygon};
use super::*;
use crate::areas::Area;
use crate::config::PeriodKind;
use crate::rasters::Period;
#[test]
fn bounds_are_four_numbers_in_order() {
assert_eq!(
parse_bounds("-170,18,-66,72").expect("parses"),
[-170.0, 18.0, -66.0, 72.0]
);
let err = parse_bounds("1,2,3").expect_err("three numbers");
assert!(
geolith::error::report(&err).contains("four numbers"),
"{err:#}"
);
let err = parse_bounds("10,0,-10,20").expect_err("reversed");
assert!(
geolith::error::report(&err).contains("out of order"),
"{err:#}"
);
let err = parse_bounds("a,0,1,2").expect_err("not a number");
assert!(
geolith::error::report(&err).contains("not a number"),
"{err:#}"
);
}
#[test]
fn build_id_has_the_spec_shape() {
assert_eq!(
build_id("2026-11-10", 1_794_859_463),
"2026-11-10.20261116T2004Z"
);
}
#[test]
fn anomaly_is_relative_and_absolute() {
let (pct, abs) = anomaly(42.1, Some(60.3), Some(1.0));
let pct = pct.expect("normal above 1 mm");
assert!((pct - -30.182_421_227_197_35).abs() < 1e-6, "{pct}");
let abs = abs.expect("abs with a normal");
assert!((abs - -18.2).abs() < 1e-9, "{abs}");
assert_eq!(anomaly(42.1, None, Some(1.0)), (None, None));
}
#[test]
fn a_normal_below_1_mm_gives_no_percentage() {
assert_eq!(anomaly(0.0, Some(0.4), Some(1.0)), (None, Some(-0.4)));
}
#[test]
fn the_percentage_threshold_comes_from_the_config() {
let (pct, abs) = anomaly(0.5, Some(0.4), Some(0.1));
let pct = pct.expect("normal above the threshold");
assert!((pct - 25.0).abs() < 1e-9, "{pct}");
assert!(abs.is_some_and(|a| (a - 0.1).abs() < 1e-12), "{abs:?}");
let (pct, abs) = anomaly(0.5, Some(0.4), None);
assert_eq!(pct, None);
assert!(abs.is_some_and(|a| (a - 0.1).abs() < 1e-12), "{abs:?}");
assert_eq!(anomaly(80.0, Some(60.0), None).0, None);
}
#[test]
fn a_dekad_series_steps_by_dekads() {
let d = |year: i32, month: u8, index: u8| Period {
year,
month,
index,
kind: PeriodKind::Dekad,
};
assert_eq!(next_period(d(2026, 10, 2)), d(2026, 10, 3));
assert_eq!(next_period(d(2026, 10, 3)), d(2026, 11, 1));
assert_eq!(next_period(d(2026, 12, 3)), d(2027, 1, 1));
let (start, span) = season_span("06-11", d(2026, 7, 1)).expect("season");
assert_eq!(start, "2026-06-11");
let slots: Vec<String> = span.iter().map(Period::slot).collect();
assert_eq!(slots, ["06-2", "06-3", "07-1"]);
assert!(span.iter().all(|p| p.kind == PeriodKind::Dekad), "{span:?}");
}
#[test]
fn slugs_are_ascii() {
assert_eq!(slugify("Nashik"), "nashik");
assert_eq!(slugify("Jammu & Kashmir"), "jammu-kashmir");
assert_eq!(slugify("Thoothukudi (Tuticorin)"), "thoothukudi-tuticorin");
assert_eq!(slugify("Bhandāra"), "bhandara");
assert_eq!(slugify(" Ñuñoa, São Paulo "), "nunoa-sao-paulo");
}
fn square_area(id: &str, x0: f64, y0: f64, side: f64) -> Area {
let ring = vec![
(x0, y0),
(x0 + side, y0),
(x0 + side, y0 + side),
(x0, y0 + side),
(x0, y0),
];
Area {
code: None,
id: id.to_owned(),
name: id.to_owned(),
country: "ZZ".to_owned(),
level: "county".to_owned(),
parent_id: None,
parent_name: None,
region_code: None,
shape: MultiPolygon::new(vec![Polygon::new(ring.into(), vec![])]),
}
}
#[test]
fn neighbours_share_an_edge_and_are_capped() {
let mut grid = Vec::with_capacity(9);
for x in 0..3 {
for y in 0..3 {
grid.push(square_area(
&format!("{x},{y}"),
f64::from(x),
f64::from(y),
1.0,
));
}
}
grid.push(square_area("far", 10.0, 10.0, 1.0));
let found = neighbours(&grid, 8);
let mut centre = found["1,1"].clone();
centre.sort();
assert_eq!(centre, ["0,1", "1,0", "1,2", "2,1"]);
let mut corner = found["0,0"].clone();
corner.sort();
assert_eq!(corner, ["0,1", "1,0"]);
assert!(found["far"].is_empty());
let mut ring = vec![square_area("big", 0.0, 0.0, 3.0)];
for i in -1..=3 {
for j in -1..=3 {
if (0..3).contains(&i) && (0..3).contains(&j) {
continue;
}
ring.push(square_area(
&format!("r{i},{j}"),
f64::from(i),
f64::from(j),
1.0,
));
}
}
let found = neighbours(&ring, 8);
let big = &found["big"];
assert_eq!(big.len(), 8, "{big:?}");
for middle in ["r-1,1", "r3,1", "r1,-1", "r1,3"] {
assert!(
big.iter().any(|id| id == middle),
"{middle} missing: {big:?}"
);
}
for corner in ["r-1,-1", "r3,3", "r-1,3", "r3,-1"] {
assert!(!big.iter().any(|id| id == corner), "{corner} kept: {big:?}");
}
}
#[test]
fn the_season_runs_from_its_first_pentad_to_the_latest() {
let latest = Period {
year: 2026,
month: 7,
index: 2,
kind: PeriodKind::Pentad,
};
let (start, span) = season_span("06-01", latest).expect("season");
assert_eq!(start, "2026-06-01");
let slots: Vec<String> = span.iter().map(Period::slot).collect();
assert_eq!(
slots,
[
"06-1", "06-2", "06-3", "06-4", "06-5", "06-6", "07-1", "07-2"
]
);
let may = Period {
year: 2026,
month: 5,
index: 6,
kind: PeriodKind::Pentad,
};
let (start, span) = season_span("06-01", may).expect("season");
assert_eq!(start, "2025-06-01");
assert_eq!(
span.len(),
72,
"June 2025 .. May 2026 is 12 months of 6 pentads"
);
}
#[test]
fn season_totals_need_every_pentad_and_every_normal() {
let p = |month: u8, index: u8| Period {
year: 2026,
month,
index,
kind: PeriodKind::Pentad,
};
let span = [p(6, 1), p(6, 2)];
let all = season_totals(&span, |_| Some(10.0), |_| Some(8.0), Some(1.0));
assert_eq!(all.0, Some(20.0));
assert_eq!(all.1, Some(16.0));
let pct = all.2.expect("both totals");
assert!((pct - 25.0).abs() < 1e-12, "{pct}");
let gap = season_totals(
&span,
|q| (q != p(6, 2)).then_some(10.0),
|_| Some(8.0),
Some(1.0),
);
assert_eq!(gap, (None, Some(16.0), None));
let no_normal = season_totals(
&span,
|_| Some(10.0),
|q| (q == p(6, 1)).then_some(8.0),
Some(1.0),
);
assert_eq!(no_normal, (Some(20.0), None, None));
}
}