use std::collections::BTreeMap;
use std::fs;
use std::path::{Path, PathBuf};
use crate::error::{DatasetError, IoOp, IoResultExt as _, JsonResultExt as _, Result};
use serde::Serialize;
use serde_json::Value;
use crate::cli::SlotsArgs;
use crate::layout::settings;
pub const DECIMALS: &[(&str, usize)] = &[("rainfall", 3), ("ndvi", 4)];
#[derive(Debug, Clone, PartialEq)]
pub struct SlotHistory {
pub years: u32,
pub mean_min: f64,
pub mean_median: f64,
pub mean_max: f64,
pub median_min: f64,
pub median_max: f64,
pub min_share_under_1mm: Option<f64>,
pub max_share_under_1mm: Option<f64>,
pub max_area_mm: Option<f64>,
pub yearly_means: Vec<f64>,
}
#[derive(Debug, Clone, PartialEq)]
pub struct SlotTable {
pub dataset: String,
pub unit: String,
pub slots: BTreeMap<String, SlotHistory>,
pub source: String,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Sample {
pub year: u32,
pub slot: String,
pub values: Vec<f64>,
}
#[must_use]
pub fn parse_name(name: &str) -> Option<(u32, String)> {
let stem = name.strip_suffix(".values.csv")?;
let mut parts = stem.rsplit('.');
let index: u32 = parts.next()?.parse().ok()?;
let month = parts.next()?;
let year: u32 = parts.next()?.parse().ok()?;
if year < 1000 || month.len() != 2 || index > 9 {
return None;
}
Some((year, format!("{month}-{index}")))
}
#[must_use]
pub fn parse_values(text: &str) -> Vec<f64> {
let mut values = Vec::new();
for line in text.lines() {
if line.is_empty() || line.starts_with('#') || line.starts_with("area_id,") {
continue;
}
let cell = line.rsplit_once(',').map_or(line, |(_, cell)| cell).trim();
if cell.is_empty() {
continue;
}
if let Ok(value) = cell.parse::<f64>()
&& value.is_finite()
{
values.push(value);
}
}
values
}
#[must_use]
pub fn median(values: &[f64]) -> f64 {
let mut sorted = values.to_vec();
sorted.sort_by(f64::total_cmp);
let middle = sorted.len() / 2;
if sorted.len() % 2 == 1 {
sorted[middle]
} else {
(sorted[middle - 1] + sorted[middle]) / 2.0
}
}
fn round(value: f64, digits: usize) -> f64 {
format!("{value:.digits$}").parse::<f64>().unwrap_or(value)
}
#[must_use]
pub fn decimals(dataset: &str) -> usize {
DECIMALS
.iter()
.find(|(id, _)| *id == dataset)
.map_or(4, |(_, digits)| *digits)
}
pub fn slot_table(
dataset: &str,
samples: &[Sample],
source: &str,
baseline: (u32, u32),
) -> Result<SlotTable> {
let digits = decimals(dataset);
let mut by_slot: BTreeMap<String, BTreeMap<u32, Vec<f64>>> = BTreeMap::new();
for sample in samples {
if sample.values.is_empty() || sample.year < baseline.0 || sample.year > baseline.1 {
continue;
}
let years = by_slot.entry(sample.slot.clone()).or_default();
if years.insert(sample.year, sample.values.clone()).is_some() {
return Err(DatasetError::data(format!(
"slot {} has two samples of one year",
sample.slot
)));
}
}
let mut slots = BTreeMap::new();
for (slot, years) in by_slot {
let mut means = Vec::with_capacity(years.len());
let mut medians = Vec::with_capacity(years.len());
let mut shares = Vec::with_capacity(years.len());
let mut max_area: f64 = 0.0;
for values in years.values() {
means.push(values.iter().sum::<f64>() / values.len() as f64);
medians.push(median(values));
let dry = values.iter().filter(|value| **value < 1.0).count();
shares.push(dry as f64 / values.len() as f64);
for value in values {
max_area = max_area.max(*value);
}
}
let history = SlotHistory {
years: u32::try_from(means.len()).unwrap_or(u32::MAX),
mean_min: round(min_of(&means), digits),
mean_median: round(median(&means), digits),
mean_max: round(max_of(&means), digits),
median_min: round(min_of(&medians), digits),
median_max: round(max_of(&medians), digits),
min_share_under_1mm: (dataset == "rainfall").then(|| round(min_of(&shares), 3)),
max_share_under_1mm: (dataset == "rainfall").then(|| round(max_of(&shares), 3)),
max_area_mm: (dataset == "rainfall").then(|| round(max_area, 1)),
yearly_means: means.iter().map(|mean| round(*mean, digits)).collect(),
};
slots.insert(slot, history);
}
Ok(SlotTable {
dataset: dataset.to_owned(),
unit: if dataset == "ndvi" { "ndvi" } else { "mm" }.to_owned(),
slots,
source: source.to_owned(),
})
}
fn min_of(values: &[f64]) -> f64 {
values.iter().copied().fold(f64::INFINITY, f64::min)
}
fn max_of(values: &[f64]) -> f64 {
values.iter().copied().fold(f64::NEG_INFINITY, f64::max)
}
pub fn read_cache(dir: &Path) -> Result<Vec<Sample>> {
let entries = fs::read_dir(dir).io_at(IoOp::Read, dir)?;
let mut names: Vec<PathBuf> = entries
.filter_map(|entry| entry.ok().map(|entry| entry.path()))
.collect();
names.sort();
let mut samples = Vec::new();
for path in names {
let name = path
.file_name()
.and_then(|name| name.to_str())
.unwrap_or_default();
let Some((year, slot)) = parse_name(name) else {
continue;
};
let text = fs::read_to_string(&path).io_at(IoOp::Read, &path)?;
samples.push(Sample {
year,
slot,
values: parse_values(&text),
});
}
Ok(samples)
}
#[must_use]
pub fn source_line(dataset: &str, areas: usize, baseline: &str) -> String {
let years = baseline
.split_once('-')
.and_then(|(from, to)| Some((from.parse::<i64>().ok()?, to.parse::<i64>().ok()?)))
.map_or(0, |(from, to)| to - from + 1);
let product = if dataset == "ndvi" {
"CLMS NDVI 300 m dekads"
} else {
"CHIRPS v3.0 pentads"
};
format!(
"{product} {baseline} ({years} years): the area values of every baseline raster \
(`geolith dataset values`, the reading of the build), the national mean over the \
{areas} areas that carry a value; min_share_under_1mm is the smallest share of areas \
under 1 mm over the years (the wettest year)."
)
}
#[must_use]
pub fn slot_table_path(repo: &Path, dataset: &str, cc: &str) -> PathBuf {
let name = if cc == "in" {
format!("{dataset}-slots.json")
} else {
format!("{dataset}-slots-{cc}.json")
};
repo.join("packages/dataset-builder/data/datasets")
.join(name)
}
pub fn read_slots(path: &Path) -> Result<SlotTable> {
let text = fs::read_to_string(path).io_at(IoOp::Read, path)?;
let value: Value =
serde_json::from_str(&text).json_of(format!("{} is not JSON", path.display()))?;
let dataset = value
.get("dataset")
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned();
let unit = value
.get("unit")
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned();
let source = value
.get("source")
.and_then(Value::as_str)
.unwrap_or_default()
.to_owned();
let mut slots = BTreeMap::new();
let entries = value.get("slots").and_then(Value::as_object);
for (slot, history) in entries.into_iter().flatten() {
let number = |key: &str| history.get(key).and_then(Value::as_f64);
let (Some(mean_min), Some(mean_max)) = (number("mean_min"), number("mean_max")) else {
return Err(DatasetError::data(format!(
"{}: slot {slot} needs numeric mean_min and mean_max",
path.display()
)));
};
if !mean_min.is_finite() || !mean_max.is_finite() {
return Err(DatasetError::data(format!(
"{}: slot {slot} needs numeric mean_min and mean_max",
path.display()
)));
}
slots.insert(
slot.clone(),
SlotHistory {
years: history
.get("years")
.and_then(Value::as_u64)
.and_then(|years| u32::try_from(years).ok())
.unwrap_or_default(),
mean_min,
mean_median: number("mean_median").unwrap_or(mean_min),
mean_max,
median_min: number("median_min").unwrap_or_default(),
median_max: number("median_max").unwrap_or_default(),
min_share_under_1mm: number("min_share_under_1mm"),
max_share_under_1mm: number("max_share_under_1mm"),
max_area_mm: number("max_area_mm"),
yearly_means: history
.get("yearly_means")
.and_then(Value::as_array)
.map(|values| values.iter().filter_map(Value::as_f64).collect())
.unwrap_or_default(),
},
);
}
Ok(SlotTable {
dataset,
unit,
slots,
source,
})
}
pub fn slot_key(end: &str, dataset: &str) -> Result<String> {
let bytes = end.as_bytes();
let date = bytes.len() == 10
&& bytes[4] == b'-'
&& bytes[7] == b'-'
&& [0, 1, 2, 3, 5, 6, 8, 9]
.iter()
.all(|index| bytes[*index].is_ascii_digit());
let day: u32 = end
.get(8..10)
.and_then(|day| day.parse().ok())
.filter(|_| date)
.ok_or_else(|| DatasetError::data(format!("not a date YYYY-MM-DD: {end}")))?;
let month = &end[5..7];
let index = if dataset == "ndvi" {
match day {
10 => 1,
20 => 2,
_ => 3,
}
} else if day.is_multiple_of(5) && day <= 25 {
day / 5
} else {
6
};
Ok(format!("{month}-{index}"))
}
fn js_number(value: f64, digits: usize) -> Value {
let mut text = format!("{value:.digits$}");
if let Some(dot) = text.find('.') {
while text.ends_with('0') {
text.pop();
}
if text.len() == dot + 1 {
text.pop();
}
}
if text
.chars()
.all(|char| char == '0' || char == '.' || char == '-')
{
return Value::from(0);
}
serde_json::from_str(&text).unwrap_or_else(|_| Value::from(0))
}
#[derive(Serialize)]
struct TableJson<'a> {
dataset: &'a str,
unit: &'a str,
slots: BTreeMap<&'a str, HistoryJson>,
source: &'a str,
}
#[derive(Serialize)]
struct HistoryJson {
years: u32,
mean_min: Value,
mean_median: Value,
mean_max: Value,
median_min: Value,
median_max: Value,
yearly_means: Vec<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
min_share_under_1mm: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
max_share_under_1mm: Option<Value>,
#[serde(skip_serializing_if = "Option::is_none")]
max_area_mm: Option<Value>,
}
pub fn render(table: &SlotTable) -> Result<String> {
let digits = decimals(&table.dataset);
let slots = table
.slots
.iter()
.map(|(slot, history)| {
(
slot.as_str(),
HistoryJson {
years: history.years,
mean_min: js_number(history.mean_min, digits),
mean_median: js_number(history.mean_median, digits),
mean_max: js_number(history.mean_max, digits),
median_min: js_number(history.median_min, digits),
median_max: js_number(history.median_max, digits),
yearly_means: history
.yearly_means
.iter()
.map(|mean| js_number(*mean, digits))
.collect(),
min_share_under_1mm: history
.min_share_under_1mm
.map(|value| js_number(value, 3)),
max_share_under_1mm: history
.max_share_under_1mm
.map(|value| js_number(value, 3)),
max_area_mm: history.max_area_mm.map(|value| js_number(value, 1)),
},
)
})
.collect();
let text = serde_json::to_string_pretty(&TableJson {
dataset: &table.dataset,
unit: &table.unit,
slots,
source: &table.source,
})
.json_of("serializing the slot table")?;
Ok(format!("{text}\n"))
}
pub fn write_slots(dataset: &str, cc: &str, cache: &Path, out: &Path) -> Result<usize> {
if !cache.is_dir() {
return Err(DatasetError::data(format!(
"no values cache in {}",
cache.display()
)));
}
let samples = read_cache(cache)?;
if samples.is_empty() {
return Err(DatasetError::data(format!(
"{} holds no <product>.<year>.<MM>.<n>.values.csv",
cache.display()
)));
}
let s = settings(Some(dataset), Some(cc))?;
let areas = s
.country_config()
.and_then(|config| config.boundaries.invariants.areas)
.unwrap_or(0);
let (from, to) = baseline_years(&s.baseline);
let table = slot_table(
dataset,
&samples,
&source_line(dataset, areas, &s.baseline),
(from, to),
)?;
let text = render(&table)?;
if let Some(parent) = out.parent() {
fs::create_dir_all(parent).io_at(IoOp::Create, parent)?;
}
fs::write(out, text).io_at(IoOp::Write, out)?;
println!(
"slots: {} slots from {} rasters -> {}",
table.slots.len(),
samples.len(),
out.display()
);
Ok(table.slots.len())
}
#[must_use]
pub fn baseline_years(baseline: &str) -> (u32, u32) {
match baseline.split_once('-') {
Some((from, to)) => match (from.parse::<u32>(), to.parse::<u32>()) {
(Ok(from), Ok(to)) => (from, to),
_ => (0, u32::MAX),
},
None => (0, u32::MAX),
}
}
pub fn run(args: &SlotsArgs) -> Result<()> {
let dataset = args.dataset.as_deref().unwrap_or("rainfall");
let cc = args.country.as_deref().unwrap_or("in");
let out = match &args.out {
Some(out) => out.clone(),
None => {
let s = settings(Some(dataset), Some(cc))?;
slot_table_path(&s.repo, dataset, cc)
}
};
let cache = &args.cache;
write_slots(dataset, cc, cache, &out)?;
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn a_cache_name_gives_its_year_and_slot() {
assert_eq!(
parse_name("chirps-v3.0.1991.01.1.values.csv"),
Some((1991, "01-1".to_owned()))
);
assert_eq!(
parse_name("ndvi300-v3.2014.12.3.values.csv"),
Some((2014, "12-3".to_owned()))
);
assert_eq!(parse_name("notes.csv"), None);
assert_eq!(parse_name("v.2026.01.10.values.csv"), None);
}
#[test]
fn values_skip_an_empty_cell_and_a_comment() {
let text = "area_id,value\n# a comment\na,1.5\nb,\nc,2\n";
assert_eq!(parse_values(text), vec![1.5, 2.0]);
}
#[test]
fn the_median_of_an_even_list_is_the_mean_of_its_middles() {
assert_eq!(median(&[3.0, 1.0, 2.0]), 2.0);
assert_eq!(median(&[4.0, 1.0, 3.0, 2.0]), 2.5);
assert_eq!(median(&[7.0]), 7.0);
}
fn sample(year: u32, slot: &str, values: &[f64]) -> Sample {
Sample {
year,
slot: slot.to_owned(),
values: values.to_vec(),
}
}
#[test]
fn a_slot_carries_one_mean_per_year_and_its_extremes() {
let samples = [
sample(1991, "01-1", &[1.0, 3.0]),
sample(1992, "01-1", &[2.0, 2.0]),
sample(1993, "01-1", &[0.0, 0.0]),
];
let table = slot_table("rainfall", &samples, "source", (1991, 2020)).expect("table");
let history = &table.slots["01-1"];
assert_eq!(history.years, 3);
assert_eq!(history.yearly_means, vec![2.0, 2.0, 0.0]);
assert_eq!(history.mean_min, 0.0);
assert_eq!(history.mean_max, 2.0);
assert_eq!(history.mean_median, 2.0);
assert_eq!(history.min_share_under_1mm, Some(0.0));
assert_eq!(history.max_share_under_1mm, Some(1.0));
assert_eq!(history.max_area_mm, Some(3.0));
assert_eq!(table.unit, "mm");
}
#[test]
fn a_year_outside_the_baseline_never_enters_the_table() {
let samples = [
sample(1990, "01-1", &[5.0]),
sample(1991, "01-1", &[1.0]),
sample(2021, "01-1", &[9.0]),
];
let table = slot_table("rainfall", &samples, "source", (1991, 2020)).expect("table");
assert_eq!(table.slots["01-1"].years, 1);
assert_eq!(table.slots["01-1"].mean_min, 1.0);
assert_eq!(table.slots["01-1"].yearly_means, vec![1.0]);
}
#[test]
fn ndvi_keeps_four_decimals_and_no_dry_share() {
let samples = [sample(2019, "01-1", &[0.1234, 0.5678])];
let table = slot_table("ndvi", &samples, "source", (2019, 2025)).expect("table");
let history = &table.slots["01-1"];
assert_eq!(table.unit, "ndvi");
assert_eq!(history.mean_min, 0.3456);
assert_eq!(history.min_share_under_1mm, None);
assert_eq!(history.max_area_mm, None);
}
#[test]
fn the_rendered_file_is_the_script_layout() {
let table = SlotTable {
dataset: "rainfall".to_owned(),
unit: "mm".to_owned(),
slots: BTreeMap::from([(
"01-1".to_owned(),
SlotHistory {
years: 2,
mean_min: 1.5,
mean_median: 2.0,
mean_max: 2.5,
median_min: 1.0,
median_max: 3.0,
min_share_under_1mm: Some(0.5),
max_share_under_1mm: Some(0.25),
max_area_mm: Some(12.3),
yearly_means: vec![1.5, 2.5],
},
)]),
source: "CHIRPS".to_owned(),
};
let text = render(&table).expect("render");
let expected = r#"{
"dataset": "rainfall",
"unit": "mm",
"slots": {
"01-1": {
"years": 2,
"mean_min": 1.5,
"mean_median": 2,
"mean_max": 2.5,
"median_min": 1,
"median_max": 3,
"yearly_means": [
1.5,
2.5
],
"min_share_under_1mm": 0.5,
"max_share_under_1mm": 0.25,
"max_area_mm": 12.3
}
},
"source": "CHIRPS"
}
"#;
assert_eq!(text, expected);
}
#[test]
fn a_slot_key_is_the_pentad_or_the_dekad_of_its_end() {
assert_eq!(slot_key("2026-11-15", "rainfall").expect("date"), "11-3");
assert_eq!(slot_key("2026-11-30", "rainfall").expect("date"), "11-6");
assert_eq!(slot_key("2026-11-10", "ndvi").expect("date"), "11-1");
assert_eq!(slot_key("2026-11-25", "ndvi").expect("date"), "11-3");
assert!(slot_key("2026-11", "rainfall").is_err());
}
#[test]
fn india_keeps_the_short_table_name_and_a_country_does_not() {
let repo = Path::new("/r");
assert_eq!(
slot_table_path(repo, "rainfall", "in"),
PathBuf::from("/r/packages/dataset-builder/data/datasets/rainfall-slots.json")
);
assert_eq!(
slot_table_path(repo, "rainfall", "us"),
PathBuf::from("/r/packages/dataset-builder/data/datasets/rainfall-slots-us.json")
);
}
#[test]
fn the_source_line_names_the_product_the_years_and_the_areas() {
assert_eq!(
source_line("rainfall", 787, "1991-2020"),
"CHIRPS v3.0 pentads 1991-2020 (30 years): the area values of every baseline raster \
(`geolith dataset values`, the reading of the build), the national mean over the 787 \
areas that carry a value; min_share_under_1mm is the smallest share of areas under \
1 mm over the years (the wettest year)."
);
}
#[test]
fn a_table_without_a_numeric_mean_is_refused_naming_the_slot() {
let dir = tempfile::tempdir().expect("a temp dir");
let path = dir.path().join("rainfall-slots.json");
fs::write(&path, r#"{"slots":{"01-1":{"years":1}}}"#).expect("write");
let err = read_slots(&path).expect_err("no mean_min");
assert!(
err.to_string()
.contains("slot 01-1 needs numeric mean_min and mean_max"),
"{err}"
);
}
}