use std::borrow::Cow;
use std::collections::{BTreeMap, BTreeSet, HashMap};
use std::io::ErrorKind;
use std::path::{Path, PathBuf};
use std::time::Instant;
use crate::error::{
DatasetError, IoOp, IoResultExt as _, IoStepExt as _, JsonResultExt as _, NumberResultExt as _,
Result, WithinExt as _,
};
use serde::{Deserialize, Serialize};
use crate::areas::{Area, read_areas_geojson};
use crate::cli::{NormalsArgs, ValuesArgs};
use crate::config::{Comparison, DatasetConfig, PeriodKind, Reader};
use crate::coverage::Grid;
use crate::numbers::{CoverageTable, area_values};
use crate::rasters::{Period, RasterFile, discover, match_template};
use crate::source::Raster;
const HEADER: &str = "area_id,slot,normal,years,baseline,attribution";
const COLUMNS: usize = 6;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
pub struct Normal {
pub area_id: String,
pub slot: String,
pub normal: f64,
pub years: u32,
pub baseline: String,
}
#[derive(Debug, Serialize)]
struct NormalsStats {
files: usize,
ms_total: f64,
ms_per_file: f64,
slots: Vec<String>,
baseline: String,
attribution: String,
#[serde(skip_serializing_if = "Option::is_none")]
empty: Option<Vec<String>>,
}
pub fn write_normals_csv(path: &Path, normals: &[Normal], attribution: &str) -> Result<()> {
let mut rows: Vec<&Normal> = normals.iter().collect();
rows.sort_by(|a, b| (&a.area_id, &a.slot).cmp(&(&b.area_id, &b.slot)));
let attribution = csv_field(attribution);
let mut text = String::with_capacity((rows.len() + 1) * (64 + attribution.len()));
text.push_str(HEADER);
text.push('\n');
for n in rows {
text.push_str(&format!(
"{},{},{},{},{},{attribution}\n",
csv_field(&n.area_id),
csv_field(&n.slot),
n.normal,
n.years,
csv_field(&n.baseline),
));
}
std::fs::write(path, text).io_at(IoOp::Write, path)
}
pub(crate) fn csv_field(field: &str) -> Cow<'_, str> {
if field.contains([',', '"', '\n', '\r']) {
Cow::Owned(format!("\"{}\"", field.replace('"', "\"\"")))
} else {
Cow::Borrowed(field)
}
}
pub fn read_normals_csv(path: &Path) -> Result<Vec<Normal>> {
let text = std::fs::read_to_string(path).io_at(IoOp::Read, path)?;
let records = parse_csv(&text).within(format!("parsing {}", path.display()))?;
let mut records = records.into_iter();
let header = records.next().unwrap_or_default();
if header.join(",") != HEADER {
return Err(DatasetError::data(format!(
"{}: header is {:?}, expected {HEADER:?}",
path.display(),
header.join(",")
)));
}
let mut normals = Vec::with_capacity(records.len());
for (index, record) in records.enumerate() {
let row = index + 2;
let [area_id, slot, normal, years, baseline, _attribution]: [String; COLUMNS] =
record.try_into().map_err(|r: Vec<String>| {
DatasetError::data(format!(
"{} row {row}: {} fields, expected {COLUMNS}",
path.display(),
r.len()
))
})?;
normals.push(Normal {
normal: normal
.parse()
.number_of(format!("{} row {row}: normal {normal:?}", path.display()))?,
years: years
.parse()
.number_of(format!("{} row {row}: years {years:?}", path.display()))?,
area_id,
slot,
baseline,
});
}
Ok(normals)
}
pub(crate) fn parse_csv(text: &str) -> Result<Vec<Vec<String>>> {
let mut records = Vec::new();
let mut record = Vec::new();
let mut field = String::new();
let mut in_quotes = false;
let mut chars = text.chars().peekable();
while let Some(c) = chars.next() {
if in_quotes {
match c {
'"' if chars.peek() == Some(&'"') => {
chars.next();
field.push('"');
}
'"' => in_quotes = false,
_ => field.push(c),
}
continue;
}
match c {
'"' if field.is_empty() => in_quotes = true,
',' => record.push(std::mem::take(&mut field)),
'\r' if chars.peek() == Some(&'\n') => {}
'\n' => {
record.push(std::mem::take(&mut field));
records.push(std::mem::take(&mut record));
}
_ => field.push(c),
}
}
if in_quotes {
return Err(DatasetError::data("unterminated quoted field"));
}
if !field.is_empty() || !record.is_empty() {
record.push(field);
records.push(record);
}
Ok(records)
}
fn parse_baseline(text: &str) -> Result<(i32, i32)> {
let year = |s: &str| {
(s.len() == 4 && s.bytes().all(|b| b.is_ascii_digit()))
.then(|| s.parse::<i32>().ok())
.flatten()
};
let parsed = text
.split_once('-')
.and_then(|(a, b)| Some((year(a)?, year(b)?)));
match parsed {
Some((first, last)) if first <= last => Ok((first, last)),
_ => Err(DatasetError::usage(format!(
"--baseline {text:?} is not YYYY-YYYY with the first year first"
))),
}
}
fn parse_slots(text: &str, kind: PeriodKind) -> Result<BTreeSet<String>> {
let mut slots = BTreeSet::new();
let last = b'0'.saturating_add(kind.periods_per_month());
for slot in text.split(',').map(str::trim) {
let b = slot.as_bytes();
let valid = b.len() == 4
&& b[2] == b'-'
&& matches!(slot[..2].parse::<u8>(), Ok(1..=12))
&& b[..2].iter().all(u8::is_ascii_digit)
&& (b'1'..=last).contains(&b[3]);
if !valid {
match kind {
PeriodKind::Pentad => {
return Err(DatasetError::usage(format!(
"--slots: {slot:?} is not a slot MM-P (month 01-12, pentad 1-6)"
)));
}
PeriodKind::Dekad => {
return Err(DatasetError::usage(format!(
"--slots: {slot:?} is not a slot MM-D (month 01-12, dekad 1-3)"
)));
}
}
}
slots.insert(slot.to_owned());
}
Ok(slots)
}
const CACHE_SUFFIX: &str = ".values.csv";
const CACHE_HEADER: &str = "area_id,value";
const FNV_OFFSET: u64 = 0xcbf2_9ce4_8422_2325;
fn fnv1a_extend(mut hash: u64, bytes: &[u8]) -> u64 {
for &b in bytes {
hash ^= u64::from(b);
hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
}
hash
}
#[must_use]
pub(crate) fn fnv1a_64(bytes: &[u8]) -> u64 {
fnv1a_extend(FNV_OFFSET, bytes)
}
fn geometry_hash(areas: &[Area]) -> u64 {
let mut order: Vec<&Area> = areas.iter().collect();
order.sort_by(|a, b| a.id.cmp(&b.id));
let count = |n: usize| (n as u64).to_le_bytes();
let mut hash = FNV_OFFSET;
for area in order {
hash = fnv1a_extend(hash, area.id.as_bytes());
hash = fnv1a_extend(hash, &[0]);
hash = fnv1a_extend(hash, &count(area.shape.0.len()));
for polygon in &area.shape.0 {
hash = fnv1a_extend(hash, &count(1 + polygon.interiors().len()));
for ring in std::iter::once(polygon.exterior()).chain(polygon.interiors()) {
hash = fnv1a_extend(hash, &count(ring.0.len()));
for c in &ring.0 {
hash = fnv1a_extend(hash, &c.x.to_bits().to_le_bytes());
hash = fnv1a_extend(hash, &c.y.to_bits().to_le_bytes());
}
}
}
}
hash
}
#[derive(Debug, Clone, PartialEq, Eq)]
struct CacheKey {
count: usize,
ids: u64,
release: String,
config: u64,
grid: u64,
geometry: u64,
}
impl CacheKey {
fn new(areas: &[Area], release: &str, config: &DatasetConfig, grid: u64) -> Self {
let mut ids: Vec<&str> = areas.iter().map(|a| a.id.as_str()).collect();
ids.sort_unstable();
CacheKey {
count: ids.len(),
ids: fnv1a_64(ids.join("\n").as_bytes()),
release: release.to_owned(),
config: config_hash(config),
grid,
geometry: geometry_hash(areas),
}
}
fn with_grid(&self, grid: u64) -> Self {
CacheKey {
grid,
..self.clone()
}
}
fn line(&self) -> String {
format!(
"# areas {} {:016x} release={} config={:016x} grid={:016x} geometry={:016x}",
self.count, self.ids, self.release, self.config, self.grid, self.geometry
)
}
fn parse(line: &str) -> Option<Self> {
let rest = line.strip_prefix("# areas ")?;
let (count, rest) = rest.split_once(' ')?;
let (ids, rest) = rest.split_once(' ')?;
let (rest, geometry) = rest.rsplit_once(" geometry=")?;
let (rest, grid) = rest.rsplit_once(" grid=")?;
let (release, config) = rest.rsplit_once(" config=")?;
let hex = |s: &str| (s.len() == 16).then(|| u64::from_str_radix(s, 16).ok())?;
Some(CacheKey {
count: count.parse().ok()?,
ids: hex(ids)?,
release: release.strip_prefix("release=")?.to_owned(),
config: hex(config)?,
grid: hex(grid)?,
geometry: hex(geometry)?,
})
}
}
fn config_hash(config: &DatasetConfig) -> u64 {
let mut bytes = Vec::with_capacity(config.id.len() + 64 + config.flags.len() * 8);
bytes.extend(config.id.as_bytes());
bytes.push(0);
for v in [
config.scale,
config.offset,
config.valid_min,
config.valid_max,
] {
bytes.extend(v.to_bits().to_le_bytes());
}
match config.nodata {
Some(v) => {
bytes.push(1);
bytes.extend(v.to_bits().to_le_bytes());
}
None => bytes.push(0),
}
bytes.extend((config.flags.len() as u64).to_le_bytes());
for v in &config.flags {
bytes.extend(v.to_bits().to_le_bytes());
}
bytes.push(match config.reader {
Reader::Whole => 0,
Reader::Windowed => 1,
});
fnv1a_64(&bytes)
}
fn grid_hash(grid: &Grid) -> u64 {
let t = &grid.transform;
let mut bytes = Vec::with_capacity(40);
bytes.extend(grid.width.to_le_bytes());
bytes.extend(grid.height.to_le_bytes());
for v in [t.origin_x, t.origin_y, t.pixel_width, t.pixel_height] {
bytes.extend(v.to_bits().to_le_bytes());
}
fnv1a_64(&bytes)
}
fn check_cache_grids(read: &[(&Path, u64)], grid: Option<u64>) -> Result<()> {
let (expected, of) = match (grid, read.first()) {
(Some(g), _) => (g, "the rasters give"),
(None, Some((_, g))) => (*g, "the other cache files give"),
(None, None) => return Ok(()),
};
if let Some((path, found)) = read.iter().find(|(_, g)| *g != expected) {
return Err(DatasetError::data(format!(
"{}: values cache of another grid ({found:016x}, {of} {expected:016x}); delete it \
to recompute",
path.display()
)));
}
Ok(())
}
fn cache_path(dir: &Path, raster: &Path) -> Result<PathBuf> {
let stem = raster
.file_stem()
.and_then(|s| s.to_str())
.ok_or_else(|| DatasetError::data(format!("{} has no file name", raster.display())))?;
Ok(dir.join(format!("{stem}{CACHE_SUFFIX}")))
}
fn write_cache(path: &Path, key: &CacheKey, areas: &[Area], values: &[Option<f64>]) -> Result<()> {
let mut rows: Vec<(&str, Option<f64>)> = areas
.iter()
.map(|a| a.id.as_str())
.zip(values.iter().copied())
.collect();
rows.sort_by(|a, b| a.0.cmp(b.0));
let header = key.line();
let mut text = String::with_capacity(header.len() + 16 + rows.len() * 48);
text.push_str(&header);
text.push('\n');
text.push_str(CACHE_HEADER);
text.push('\n');
for (id, value) in rows {
let value = value.map(|v| v.to_string()).unwrap_or_default();
text.push_str(&format!("{},{value}\n", csv_field(id)));
}
if let Some(parent) = path.parent() {
std::fs::create_dir_all(parent).io_at(IoOp::Create, parent)?;
}
let mut partial = path.as_os_str().to_owned();
partial.push(".partial");
let partial = PathBuf::from(partial);
std::fs::write(&partial, text).io_at(IoOp::Write, &partial)?;
std::fs::rename(&partial, path).io_step(format!(
"renaming {} to {}",
partial.display(),
path.display()
))
}
fn key_mismatch(found: &CacheKey, expected: &CacheKey, check_grid: bool) -> Option<String> {
if (found.count, found.ids) != (expected.count, expected.ids) {
return Some(format!(
"values cache of other areas ({} areas {:016x}, the areas give {} {:016x})",
found.count, found.ids, expected.count, expected.ids
));
}
if found.geometry != expected.geometry {
return Some(format!(
"values cache of other area shapes (geometry {:016x}, the areas give {:016x})",
found.geometry, expected.geometry
));
}
if found.release != expected.release {
return Some(format!(
"values cache of another boundary release ({:?}, the areas are {:?})",
found.release, expected.release
));
}
if found.config != expected.config {
return Some(format!(
"values cache of another config ({:016x}, the config gives {:016x})",
found.config, expected.config
));
}
if check_grid && found.grid != expected.grid {
return Some(format!(
"values cache of another grid ({:016x}, the rasters give {:016x})",
found.grid, expected.grid
));
}
None
}
fn read_cache(
path: &Path,
expected: &CacheKey,
check_grid: bool,
areas: &[Area],
) -> Result<(Vec<Option<f64>>, CacheKey)> {
let text = std::fs::read_to_string(path).io_at(IoOp::Read, path)?;
let (first, rest) = text.split_once('\n').unwrap_or((text.as_str(), ""));
let Some(found) = CacheKey::parse(first) else {
if first.starts_with("# areas ") && !first.contains(" geometry=") {
return Err(DatasetError::data(format!(
"{}: values cache without an area geometry hash (made before it was added); \
delete it to recompute",
path.display()
)));
}
return Err(DatasetError::data(format!(
"{}: first line {first:?} is not a values cache header; delete it to recompute",
path.display()
)));
};
if let Some(why) = key_mismatch(&found, expected, check_grid) {
return Err(DatasetError::data(format!(
"{}: {why}; delete it to recompute",
path.display()
)));
}
let records = parse_csv(rest).within(format!("parsing {}", path.display()))?;
let mut records = records.into_iter();
if records.next().unwrap_or_default().join(",") != CACHE_HEADER {
return Err(DatasetError::data(format!(
"{}: second line is not {CACHE_HEADER:?}",
path.display()
)));
}
let mut by_id: HashMap<String, Option<f64>> = HashMap::with_capacity(areas.len());
for (index, record) in records.enumerate() {
let row = index + 3;
let [id, value]: [String; 2] = record.try_into().map_err(|r: Vec<String>| {
DatasetError::data(format!(
"{} row {row}: {} fields, expected 2",
path.display(),
r.len()
))
})?;
let value = if value.is_empty() {
None
} else {
Some(
value
.parse::<f64>()
.number_of(format!("{} row {row}: value {value:?}", path.display()))?,
)
};
if by_id.insert(id.clone(), value).is_some() {
return Err(DatasetError::data(format!(
"{} row {row}: area {id:?} appears twice",
path.display()
)));
}
}
if by_id.len() != areas.len() {
return Err(DatasetError::data(format!(
"{}: {} rows for {} areas",
path.display(),
by_id.len(),
areas.len()
)));
}
let values = areas
.iter()
.map(|a| {
by_id.get(&a.id).copied().ok_or_else(|| {
DatasetError::data(format!("{}: no row for area {:?}", path.display(), a.id))
})
})
.collect::<Result<_>>()?;
Ok((values, found))
}
fn raster_values(
path: &Path,
areas: &[Area],
config: &DatasetConfig,
table: &mut Option<CoverageTable>,
) -> Result<Vec<Option<f64>>> {
let source = Raster::open(path, config)?;
let current = match table.take() {
Some(t) => t,
None => {
let grid = source.grid().within(path.display().to_string())?;
CoverageTable::build(areas, grid)
}
};
let values = area_values(¤t, &source, config, path);
*table = Some(current);
Ok(values?.into_iter().map(|v| v.value).collect())
}
fn discover_cache(dir: &Path, config: &DatasetConfig) -> Result<BTreeMap<Period, PathBuf>> {
let entries = match std::fs::read_dir(dir) {
Ok(entries) => entries,
Err(e) if e.kind() == ErrorKind::NotFound => return Ok(BTreeMap::new()),
Err(e) => return Err(e).io_at(IoOp::List, dir),
};
let mut paths = entries
.map(|entry| entry.map(|e| e.path()))
.collect::<Result<Vec<_>, _>>()
.io_at(IoOp::List, dir)?;
paths.sort();
let stems: BTreeSet<&str> = [config.file_template.as_str(), config.prelim_template()]
.into_iter()
.filter_map(|t| Path::new(t).file_stem().and_then(|s| s.to_str()))
.collect();
let mut found: BTreeMap<Period, PathBuf> = BTreeMap::new();
for path in paths {
let period = path
.file_name()
.and_then(|n| n.to_str())
.and_then(|n| n.strip_suffix(CACHE_SUFFIX))
.and_then(|stem| stems.iter().find_map(|t| match_template(t, stem)));
let Some(period) = period else { continue };
if let Some(first) = found.insert(period, path.clone()) {
return Err(DatasetError::data(format!(
"{} and {} both hold period {}",
first.display(),
path.display(),
period.start_iso()
)));
}
}
Ok(found)
}
fn slot_period(year: i32, slot: &str, kind: PeriodKind) -> Option<Period> {
let (month, index) = slot.split_once('-')?;
Some(Period {
year,
month: month.parse().ok()?,
index: index.parse().ok()?,
kind,
})
}
struct BaselineSource<'a> {
raster: Option<&'a RasterFile>,
cache: Option<PathBuf>,
}
pub fn run(args: &NormalsArgs) -> Result<()> {
let config = DatasetConfig::load(&args.config)?;
let (first, last) = parse_baseline(&args.baseline)?;
let baseline = format!("{first}-{last}");
let attribution = config.attribution_for((first, last));
let slots = parse_slots(&args.slots, config.period)?;
let found = discover(
&args.rasters,
&config.file_template,
config.prelim_template(),
)?;
let cached = match &args.cache {
Some(dir) => discover_cache(dir, &config)?,
None => BTreeMap::new(),
};
if found.is_empty() && cached.is_empty() {
return Err(DatasetError::data(format!(
"no raster in {} matches the template {} (final/) or {} (prelim/)",
args.rasters.display(),
config.file_template,
config.prelim_template()
)));
}
let wanted = |p: &Period| (first..=last).contains(&p.year) && slots.contains(&p.slot());
let mut selected: BTreeMap<Period, BaselineSource<'_>> = BTreeMap::new();
for raster in found.iter().filter(|r| wanted(&r.period)) {
let cache = match &args.cache {
Some(dir) => Some(cache_path(dir, &raster.path)?),
None => None,
};
selected.insert(
raster.period,
BaselineSource {
raster: Some(raster),
cache,
},
);
}
for (period, path) in cached.into_iter().filter(|(p, _)| wanted(p)) {
selected
.entry(period)
.and_modify(|s| s.cache = Some(path.clone()))
.or_insert(BaselineSource {
raster: None,
cache: Some(path),
});
}
let before_record = |year: i32, slot: &str| {
let start = slot_period(year, slot, config.period).map(|p| p.start_iso());
matches!((start, config.record_start.as_deref()), (Some(s), Some(r)) if s.as_str() < r)
};
let present: BTreeSet<(i32, String)> = selected.keys().map(|p| (p.year, p.slot())).collect();
let missing: Vec<String> = (first..=last)
.flat_map(|year| slots.iter().map(move |slot| (year, slot)))
.filter(|(year, slot)| !present.contains(&(*year, (*slot).clone())))
.filter(|(year, slot)| !before_record(*year, slot))
.map(|(year, slot)| format!("{year} {slot}"))
.collect();
if !missing.is_empty() {
return Err(DatasetError::data(format!(
"baseline {baseline} is missing rasters in {}: {}",
args.rasters.display(),
missing.join(", ")
)));
}
let areas_file = read_areas_geojson(&args.areas)?;
let areas = &areas_file.areas;
let base = CacheKey::new(areas, &areas_file.boundary_release, &config, 0);
let key_on = |grid: u64| base.with_grid(grid);
let started = Instant::now();
let mut table: Option<CoverageTable> = None;
let mut sums: BTreeMap<String, Vec<(f64, u32)>> = BTreeMap::new();
let mut cache_grids: Vec<(&Path, u64)> = Vec::new();
for (period, source) in &selected {
let values = match (&source.cache, source.raster) {
(Some(cache), _) if cache.is_file() => {
let (values, found) = read_cache(cache, &key_on(0), false, areas)?;
cache_grids.push((cache.as_path(), found.grid));
values
}
(cache, Some(raster)) => {
let values = raster_values(&raster.path, areas, &config, &mut table)?;
if let (Some(cache), Some(t)) = (cache, &table) {
write_cache(cache, &key_on(grid_hash(&t.grid)), areas, &values)?;
}
values
}
(_, None) => {
return Err(DatasetError::data(format!(
"period {} has neither a raster nor a cache file",
period.start_iso()
)));
}
};
let acc = sums
.entry(period.slot())
.or_insert_with(|| vec![(0.0, 0); areas.len()]);
for (slot_sum, value) in acc.iter_mut().zip(&values) {
if let Some(v) = value {
slot_sum.0 += v;
slot_sum.1 += 1;
}
}
}
let ms_total = started.elapsed().as_secs_f64() * 1000.0;
let from_cache = cache_grids.len();
check_cache_grids(&cache_grids, table.as_ref().map(|t| grid_hash(&t.grid)))?;
let mut normals = Vec::with_capacity(areas.len() * sums.len());
let mut empty = Vec::new();
for (slot, acc) in &sums {
for (area, &(sum, years)) in areas.iter().zip(acc) {
if years == 0 {
empty.push(format!("{} {slot}", area.id));
continue;
}
normals.push(Normal {
area_id: area.id.clone(),
slot: slot.clone(),
normal: sum / f64::from(years),
years,
baseline: baseline.clone(),
});
}
}
let tolerated = matches!(config.comparison, Comparison::Average) || args.allow_empty;
let empty = if tolerated {
if !empty.is_empty() {
tracing::warn!(
count = empty.len(),
first = empty.first().map_or("", String::as_str),
"no baseline year gives a value: no normal for these areas and slots"
);
}
Some(empty)
} else if empty.is_empty() {
None
} else {
return Err(DatasetError::data(format!(
"no baseline year gives a value for area and slot: {}",
empty.join(", ")
)));
};
if let Some(parent) = args.out.parent().filter(|p| !p.as_os_str().is_empty()) {
std::fs::create_dir_all(parent).io_at(IoOp::Create, parent)?;
}
write_normals_csv(&args.out, &normals, &attribution)?;
let files = selected.len();
let stats = NormalsStats {
files,
ms_total,
ms_per_file: if files == 0 {
0.0
} else {
ms_total / files as f64
},
slots: slots.into_iter().collect(),
baseline,
attribution,
empty,
};
let stats_path = args.out.with_file_name("normals-stats.json");
let json = serde_json::to_string_pretty(&stats).json_of("encoding normals stats")?;
std::fs::write(&stats_path, json).io_at(IoOp::Write, &stats_path)?;
tracing::info!(
files = stats.files,
from_cache,
normals = normals.len(),
out = %args.out.display(),
"dataset normals written"
);
Ok(())
}
pub fn run_values(args: &ValuesArgs) -> Result<()> {
let config = DatasetConfig::load(&args.config)?;
let name = args
.raster
.file_name()
.and_then(|n| n.to_str())
.unwrap_or_default();
if match_template(&config.file_template, name).is_none()
&& match_template(config.prelim_template(), name).is_none()
{
return Err(DatasetError::data(format!(
"{}: the name matches neither {} nor {}",
args.raster.display(),
config.file_template,
config.prelim_template()
)));
}
let areas_file = read_areas_geojson(&args.areas)?;
let areas = &areas_file.areas;
let base = CacheKey::new(areas, &areas_file.boundary_release, &config, 0);
let key_on = |grid: &Grid| base.with_grid(grid_hash(grid));
let path = cache_path(&args.cache, &args.raster)?;
if path.is_file() {
let grid = Raster::open(&args.raster, &config)?
.grid()
.within(args.raster.display().to_string())?;
read_cache(&path, &key_on(&grid), true, areas)?;
tracing::info!(cache = %path.display(), "dataset values cached already");
} else {
let mut table = None;
let values = raster_values(&args.raster, areas, &config, &mut table)?;
let grid = table
.map(|t| t.grid)
.ok_or_else(|| DatasetError::data("the raster gave no grid"))?;
write_cache(&path, &key_on(&grid), areas, &values)?;
tracing::info!(cache = %path.display(), "dataset values written");
}
println!("{}", path.display());
Ok(())
}
#[cfg(test)]
mod tests {
use super::*;
use std::collections::BTreeSet;
const CHIRPS: &str = "Rainfall: CHIRPS v3.0, Climate Hazards Center, UC Santa Barbara. \
CC BY 4.0. DOI 10.15780/G2JQ0P";
fn normal(area_id: &str, slot: &str, normal: f64, years: u32) -> Normal {
Normal {
area_id: area_id.to_owned(),
slot: slot.to_owned(),
normal,
years,
baseline: "1991-2020".to_owned(),
}
}
fn sample() -> Vec<Normal> {
vec![
normal("div-b", "07-2", 0.1 + 0.2, 30),
normal("div-a", "07-2", 12.345_678_901_234_567, 29),
normal("div-a", "06-1", 0.0, 30),
normal("div \"q\", x", "06-1", 1e-12, 1),
]
}
#[test]
fn the_csv_round_trips() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("normals.csv");
write_normals_csv(&path, &sample(), CHIRPS).unwrap();
let read = read_normals_csv(&path).unwrap();
let key = |n: &Normal| (n.area_id.clone(), n.slot.clone(), n.years);
let written: BTreeSet<_> = sample().iter().map(key).collect();
let back: BTreeSet<_> = read.iter().map(key).collect();
assert_eq!(back, written);
let a = read
.iter()
.find(|n| n.area_id == "div-a" && n.slot == "07-2")
.unwrap();
assert_eq!(a.normal.to_bits(), 12.345_678_901_234_567_f64.to_bits());
let b = read.iter().find(|n| n.area_id == "div-b").unwrap();
assert_eq!(b.normal.to_bits(), (0.1_f64 + 0.2).to_bits());
assert_eq!(b.baseline, "1991-2020");
}
#[test]
fn the_csv_header_is_fixed() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("normals.csv");
write_normals_csv(&path, &sample(), CHIRPS).unwrap();
let text = std::fs::read_to_string(&path).unwrap();
let mut lines = text.lines();
assert_eq!(
lines.next(),
Some("area_id,slot,normal,years,baseline,attribution")
);
let row = text
.lines()
.find(|l| l.starts_with("div-b,"))
.expect("a row for div-b");
assert!(row.ends_with(&format!(",\"{CHIRPS}\"")), "{row}");
}
#[test]
fn rows_are_sorted_by_area_then_slot() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("normals.csv");
write_normals_csv(&path, &sample(), CHIRPS).unwrap();
let text = std::fs::read_to_string(&path).unwrap();
let keys: Vec<(String, String)> = text
.lines()
.skip(1)
.filter(|l| l.starts_with("div-"))
.map(|l| {
let mut f = l.split(',');
(f.next().unwrap().to_owned(), f.next().unwrap().to_owned())
})
.collect();
assert_eq!(keys.len(), 3);
assert!(keys.windows(2).all(|w| w[0] < w[1]), "{keys:?}");
}
#[test]
fn a_bad_baseline_is_an_error() {
for text in [
"1991",
"1991-20",
"2020-1991",
"abcd-efgh",
"1991-2020-2030",
] {
assert!(parse_baseline(text).is_err(), "{text}");
}
assert_eq!(parse_baseline("1991-2020").unwrap(), (1991, 2020));
}
#[test]
fn dekad_slots_parse() {
let slots = parse_slots("01-1,12-3", PeriodKind::Dekad).expect("dekad slots");
assert_eq!(
slots,
BTreeSet::from(["01-1".to_owned(), "12-3".to_owned()])
);
let err = parse_slots("01-4", PeriodKind::Dekad).expect_err("no dekad 4");
assert!(
geolith::error::report(&err).contains("dekad 1-3"),
"{err:#}"
);
let pentads = parse_slots("01-4, 12-6", PeriodKind::Pentad).expect("pentad slots");
assert!(
pentads.contains("01-4") && pentads.contains("12-6"),
"{pentads:?}"
);
let err = parse_slots("01-7", PeriodKind::Pentad).expect_err("no pentad 7");
assert_eq!(
geolith::error::report(&err),
"--slots: \"01-7\" is not a slot MM-P (month 01-12, pentad 1-6)"
);
}
#[test]
fn fnv1a_matches_the_reference_vectors() {
assert_eq!(fnv1a_64(b""), 0xcbf2_9ce4_8422_2325);
assert_eq!(fnv1a_64(b"a"), 0xaf63_dc4c_8601_ec8c);
assert_eq!(fnv1a_64(b"foobar"), 0x8594_4171_f739_67e8);
}
fn area(id: &str) -> Area {
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: geo::MultiPolygon::new(vec![]),
}
}
#[test]
fn the_cache_header_hashes_the_sorted_ids() {
let config = rainfall();
let key = |list: &[Area]| CacheKey::new(list, "r1", &config, 0xabc).line();
let one = key(&[area("a")]);
assert!(
one.starts_with("# areas 1 af63dc4c8601ec8c release=r1 config="),
"{one}"
);
assert!(one.contains(" grid=0000000000000abc geometry="), "{one}");
assert_eq!(
key(&[area("foobar"), area("a")]),
key(&[area("a"), area("foobar")])
);
assert_ne!(key(&[area("a"), area("b")]), key(&[area("a"), area("c")]));
let spaced = CacheKey::new(&[area("a")], "r 2 config=x", &config, 7);
assert_eq!(CacheKey::parse(&spaced.line()), Some(spaced));
}
fn square_area(id: &str, x0: f64, y0: f64, size: f64) -> Area {
let ring = vec![
(x0, y0),
(x0 + size, y0),
(x0 + size, y0 + size),
(x0, y0 + size),
(x0, y0),
];
Area {
shape: geo::MultiPolygon::new(vec![geo::Polygon::new(ring.into(), vec![])]),
..area(id)
}
}
#[test]
fn the_geometry_hash_follows_the_shapes_not_the_order() {
let a = square_area("a", 0.0, 0.0, 1.0);
let b = square_area("b", 2.0, 0.0, 1.0);
let base = geometry_hash(&[a.clone(), b.clone()]);
assert_eq!(geometry_hash(&[b.clone(), a.clone()]), base, "area order");
let moved = square_area("b", 2.0, 0.0, 1.000_000_1);
assert_ne!(geometry_hash(&[a.clone(), moved]), base, "a moved vertex");
let swapped = [
square_area("a", 2.0, 0.0, 1.0),
square_area("b", 0.0, 0.0, 1.0),
];
assert_ne!(geometry_hash(&swapped), base, "shapes swapped between ids");
let mut holed = a.clone();
holed.shape.0[0].interiors_push(vec![(0.2, 0.2), (0.4, 0.2), (0.4, 0.4), (0.2, 0.2)]);
assert_ne!(geometry_hash(&[holed, b.clone()]), base, "a hole");
let mut split = a.clone();
let first = split.shape.0[0].clone();
split.shape.0 = vec![
geo::Polygon::new(
geo::LineString::from(first.exterior().0[..3].to_vec()),
vec![],
),
geo::Polygon::new(
geo::LineString::from(first.exterior().0[3..].to_vec()),
vec![],
),
];
assert_ne!(geometry_hash(&[split, b]), base, "ring boundaries count");
}
#[test]
fn the_config_hash_follows_the_value_fields_only() {
let config = rainfall();
let base = config_hash(&config);
let mut other = config.clone();
other.name = "another name".to_owned();
other.max_zoom = 3;
assert_eq!(config_hash(&other), base, "display fields do not count");
let changed: [fn(&mut DatasetConfig); 8] = [
|c| c.id.push('x'),
|c| c.scale = 2.0,
|c| c.offset = 0.5,
|c| c.valid_min = -1.0,
|c| c.valid_max = 10.0,
|c| c.nodata = None,
|c| c.flags.push(1.0),
|c| c.reader = Reader::Windowed,
];
for (i, change) in changed.iter().enumerate() {
let mut c = config.clone();
change(&mut c);
assert_ne!(config_hash(&c), base, "field change {i}");
}
}
#[test]
fn a_cache_on_another_grid_is_refused() {
let a = Path::new("/c/a.values.csv");
let b = Path::new("/c/b.values.csv");
check_cache_grids(&[(a, 1), (b, 1)], Some(1)).unwrap();
check_cache_grids(&[(a, 1), (b, 1)], None).unwrap();
let err = check_cache_grids(&[(a, 1), (b, 2)], Some(1)).expect_err("b on grid 2");
assert_eq!(
geolith::error::report(&err),
"/c/b.values.csv: values cache of another grid (0000000000000002, the rasters \
give 0000000000000001); delete it to recompute"
);
let err = check_cache_grids(&[(a, 3), (b, 2)], None).expect_err("b differs from a");
assert_eq!(
geolith::error::report(&err),
"/c/b.values.csv: values cache of another grid (0000000000000002, the other cache \
files give 0000000000000003); delete it to recompute"
);
let grid = |x: f64| Grid {
width: 4,
height: 4,
transform: geolith::terrain::dem::GeoTransform {
origin_x: x,
origin_y: 1.0,
pixel_width: 0.5,
pixel_height: 0.5,
},
};
assert_ne!(grid_hash(&grid(0.0)), grid_hash(&grid(1e-12)));
}
fn rainfall() -> DatasetConfig {
DatasetConfig::load(
&Path::new(env!("CARGO_MANIFEST_DIR")).join("data/datasets/rainfall.json"),
)
.unwrap()
}
#[test]
fn a_cache_round_trips_and_rejects_a_short_file() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("sub").join("r.values.csv");
let areas = [area("z"), area("a, b"), area("m")];
let values = [Some(0.1 + 0.2), None, Some(-0.0015)];
let key = CacheKey::new(&areas, "r1", &rainfall(), 9);
write_cache(&path, &key, &areas, &values).unwrap();
let text = std::fs::read_to_string(&path).unwrap();
let rows: Vec<&str> = text.lines().skip(2).collect();
assert_eq!(rows, ["\"a, b\",", "m,-0.0015", "z,0.30000000000000004"]);
let (back, found) = read_cache(&path, &key, true, &areas).unwrap();
assert_eq!(back, values);
assert_eq!(found, key);
let short: String = text.lines().take(3).map(|l| format!("{l}\n")).collect();
std::fs::write(&path, short).unwrap();
let err = read_cache(&path, &key, true, &areas).expect_err("one row for three areas");
assert!(
geolith::error::report(&err).contains("1 rows for 3 areas"),
"{err:#}"
);
}
#[test]
fn a_csv_with_another_header_is_rejected() {
let dir = tempfile::tempdir().unwrap();
let path = dir.path().join("normals.csv");
std::fs::write(
&path,
"area_id,slot,normal,years,baseline\na,06-1,1,1,1991-2020\n",
)
.unwrap();
let err = read_normals_csv(&path).expect_err("old header");
assert!(geolith::error::report(&err).contains("header"), "{err:#}");
}
}