use std::path::Path;
use crate::error::{DatasetError, IoStepExt as _, JsonResultExt as _, Result, WithinExt as _};
use serde::{Deserialize, Deserializer, Serialize, Serializer};
use geolith::terrain::Crs;
const MAX_ZOOM_LIMIT: u8 = 22;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct DatasetConfig {
pub id: String,
pub name: String,
pub unit: String,
pub period: PeriodKind,
pub scale: f64,
pub offset: f64,
pub valid_min: f64,
pub valid_max: f64,
pub nodata: Option<f64>,
#[serde(default, skip_serializing_if = "Vec::is_empty")]
pub flags: Vec<f64>,
pub crs_epsg: Option<u32>,
pub file_template: String,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub prelim_file_template: Option<String>,
pub ramp: Vec<RampStop>,
pub max_zoom: u8,
pub tile_size: u32,
pub season_start: Option<String>,
pub stale_after_days: u16,
pub attribution: String,
pub source_url: String,
pub licence: String,
#[serde(default)]
pub comparison: Comparison,
#[serde(default = "default_anomaly_pct_min_normal")]
pub anomaly_pct_min_normal: Option<f64>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub record_start: Option<String>,
#[serde(default)]
pub reader: Reader,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub baseline: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub sensor: Option<String>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub classes: Option<Classes>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub layer_periods: Option<u8>,
#[serde(default, skip_serializing_if = "Option::is_none")]
pub history_max_zoom: Option<u8>,
}
pub const MAX_LAYER_PERIODS: u8 = 12;
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct Classes {
pub value: Vec<f64>,
pub comparison: Vec<f64>,
pub comparison_kind: ClassComparison,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum ClassComparison {
PctOfNormal,
AnomalyAbs,
}
const fn default_anomaly_pct_min_normal() -> Option<f64> {
Some(1.0)
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Comparison {
#[default]
Normal,
Average,
}
#[non_exhaustive]
#[derive(Debug, Clone, Copy, Default, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "lowercase")]
pub enum Reader {
#[default]
Whole,
Windowed,
}
#[non_exhaustive]
#[derive(
Debug, Clone, Copy, Default, PartialEq, Eq, Hash, PartialOrd, Ord, Serialize, Deserialize,
)]
#[serde(rename_all = "lowercase", try_from = "String")]
pub enum PeriodKind {
#[default]
Pentad,
Dekad,
}
impl PeriodKind {
pub(crate) const fn name(self) -> &'static str {
match self {
Self::Pentad => "pentad",
Self::Dekad => "dekad",
}
}
const fn token(self) -> &'static str {
match self {
Self::Pentad => "{pentad}",
Self::Dekad => "{dekad}",
}
}
#[must_use]
pub const fn periods_per_month(self) -> u8 {
match self {
Self::Pentad => 6,
Self::Dekad => 3,
}
}
#[must_use]
pub const fn starts(self) -> &'static [u8] {
match self {
Self::Pentad => &[1, 6, 11, 16, 21, 26],
Self::Dekad => &[1, 11, 21],
}
}
}
impl TryFrom<String> for PeriodKind {
type Error = String;
fn try_from(value: String) -> Result<Self, Self::Error> {
match value.as_str() {
"pentad" => Ok(Self::Pentad),
"dekad" => Ok(Self::Dekad),
other => Err(format!(
"unknown period {other:?}: expected \"pentad\" or \"dekad\""
)),
}
}
}
#[derive(Debug, Clone, PartialEq, Serialize, Deserialize)]
#[serde(deny_unknown_fields)]
pub struct RampStop {
pub value: f64,
#[serde(
serialize_with = "serialize_color",
deserialize_with = "deserialize_color"
)]
pub color: [u8; 4],
}
fn parse_color(text: &str) -> Option<[u8; 4]> {
let hex = text.strip_prefix('#')?;
if !(hex.len() == 6 || hex.len() == 8) || !hex.bytes().all(|b| b.is_ascii_hexdigit()) {
return None;
}
let channel = |i: usize| u8::from_str_radix(hex.get(i..i + 2)?, 16).ok();
let alpha = if hex.len() == 8 { channel(6)? } else { 255 };
Some([channel(0)?, channel(2)?, channel(4)?, alpha])
}
fn deserialize_color<'de, D: Deserializer<'de>>(deserializer: D) -> Result<[u8; 4], D::Error> {
let text = String::deserialize(deserializer)?;
parse_color(&text).ok_or_else(|| {
serde::de::Error::custom(format!("colour {text:?} is not #rrggbb or #rrggbbaa"))
})
}
fn serialize_color<S: Serializer>(color: &[u8; 4], serializer: S) -> Result<S::Ok, S::Error> {
let [r, g, b, a] = *color;
let text = if a == 255 {
format!("#{r:02x}{g:02x}{b:02x}")
} else {
format!("#{r:02x}{g:02x}{b:02x}{a:02x}")
};
serializer.serialize_str(&text)
}
fn is_month_day(text: &str) -> bool {
let bytes = text.as_bytes();
if bytes.len() != 5 || bytes[2] != b'-' {
return false;
}
let (Ok(month), Ok(day)) = (text[..2].parse::<u8>(), text[3..].parse::<u8>()) else {
return false;
};
let days = match month {
1 | 3 | 5 | 7 | 8 | 10 | 12 => 31,
4 | 6 | 9 | 11 => 30,
2 => 29,
_ => return false,
};
bytes
.iter()
.enumerate()
.all(|(i, b)| i == 2 || b.is_ascii_digit())
&& (1..=days).contains(&day)
}
fn is_iso_date(text: &str) -> bool {
let Some((year, month_day)) = text.split_at_checked(4) else {
return false;
};
let Some(month_day) = month_day.strip_prefix('-') else {
return false;
};
let Ok(year) = year.parse::<i32>() else {
return false;
};
let leap = (year % 4 == 0 && year % 100 != 0) || year % 400 == 0;
text.as_bytes()[..4].iter().all(u8::is_ascii_digit)
&& is_month_day(month_day)
&& (leap || month_day != "02-29")
}
impl DatasetConfig {
pub fn load(path: &Path) -> Result<Self> {
let text = std::fs::read_to_string(path)
.io_step(format!("reading dataset config {}", path.display()))?;
Self::from_json_str(&text).within(format!("invalid dataset config {}", path.display()))
}
pub fn from_json_str(s: &str) -> Result<Self> {
let config: Self = serde_json::from_str(s).json_of("parsing dataset config JSON")?;
config.validate()?;
Ok(config)
}
fn validate(&self) -> Result<()> {
if self.ramp.len() < 2 {
return Err(DatasetError::config(format!(
"ramp needs at least 2 stops, found {}",
self.ramp.len()
)));
}
if self.ramp.windows(2).any(|w| w[0].value >= w[1].value) {
return Err(DatasetError::config(
"ramp values must be strictly increasing",
));
}
if self.valid_min >= self.valid_max {
return Err(DatasetError::config(format!(
"valid_min {} must be below valid_max {}",
self.valid_min, self.valid_max
)));
}
if self.max_zoom > MAX_ZOOM_LIMIT {
return Err(DatasetError::config(format!(
"max_zoom {} is above {MAX_ZOOM_LIMIT}",
self.max_zoom
)));
}
if !matches!(self.tile_size, 256 | 512) {
return Err(DatasetError::config(format!(
"tile_size {} must be 256 or 512",
self.tile_size
)));
}
if let Some(day) = &self.season_start {
if !is_month_day(day) {
return Err(DatasetError::config(format!(
"season_start {day:?} is not MM-DD"
)));
}
let starts: Vec<String> = self
.period
.starts()
.iter()
.map(|d| format!("{d:02}"))
.collect();
if !starts.iter().any(|start| day.ends_with(start.as_str())) {
return Err(DatasetError::config(format!(
"season_start {day:?} is not the first day of a {} (days {})",
self.period.name(),
starts.join(", ")
)));
}
}
let templates = [
("file_template", Some(&self.file_template)),
("prelim_file_template", self.prelim_file_template.as_ref()),
];
for (key, template) in templates {
let Some(template) = template else { continue };
let own = template.matches(self.period.token()).count();
let other = [PeriodKind::Pentad, PeriodKind::Dekad]
.into_iter()
.filter(|kind| *kind != self.period)
.map(|kind| template.matches(kind.token()).count())
.sum::<usize>();
if own != 1 || other != 0 {
return Err(DatasetError::config(format!(
"{key} {template:?} must hold {} exactly once and no other period \
placeholder ({} period)",
self.period.token(),
self.period.name()
)));
}
}
if let Some(day) = &self.record_start
&& !is_iso_date(day)
{
return Err(DatasetError::config(format!(
"record_start {day:?} is not a date YYYY-MM-DD"
)));
}
if let Some(years) = &self.baseline {
let year = |s: &str| s.len() == 4 && s.bytes().all(|b| b.is_ascii_digit());
match years.split_once('-') {
Some((first, last)) if year(first) && year(last) && first <= last => {}
_ => {
return Err(DatasetError::config(format!(
"baseline {years:?} is not YYYY-YYYY with the first year first"
)));
}
}
}
if self.sensor.as_deref().is_some_and(|s| s.trim().is_empty()) {
return Err(DatasetError::config("sensor is empty"));
}
if let Some(classes) = &self.classes {
for (name, breaks) in [
("classes.value", &classes.value),
("classes.comparison", &classes.comparison),
] {
if breaks.is_empty() || breaks.len() > crate::series::MAX_BREAKS {
return Err(DatasetError::config(format!(
"{name} needs 1 to {} breaks, not {}",
crate::series::MAX_BREAKS,
breaks.len()
)));
}
if breaks.iter().any(|b| !b.is_finite()) || breaks.windows(2).any(|w| w[0] >= w[1])
{
return Err(DatasetError::config(format!(
"{name} breaks must be finite and increasing: {breaks:?}"
)));
}
}
}
if let Some(n) = self.layer_periods
&& !(1..=MAX_LAYER_PERIODS).contains(&n)
{
return Err(DatasetError::config(format!(
"layer_periods {n} is not 1 to {MAX_LAYER_PERIODS}"
)));
}
if let Some(z) = self.history_max_zoom
&& z > self.max_zoom
{
return Err(DatasetError::config(format!(
"history_max_zoom {z} is above max_zoom {}",
self.max_zoom
)));
}
if let Some(code) = self.crs_epsg {
Crs::from_epsg(code).within(format!("crs_epsg {code}"))?;
}
Ok(())
}
#[must_use]
pub fn decode(&self, raw: f32) -> Option<f64> {
let raw = f64::from(raw);
if raw.is_nan() || self.nodata == Some(raw) || self.flags.contains(&raw) {
return None;
}
let value = raw * self.scale + self.offset;
(self.valid_min..=self.valid_max)
.contains(&value)
.then_some(value)
}
#[must_use]
pub fn comparison_label(&self, baseline: &str) -> Option<String> {
match self.comparison {
Comparison::Normal => None,
Comparison::Average => {
let range = match baseline.split_once('-') {
Some((first, last)) => format!("{first}\u{2013}{last}"),
None => baseline.to_owned(),
};
Some(match &self.sensor {
Some(sensor) => format!("vs {range} average ({sensor})"),
None => format!("vs {range} average"),
})
}
}
}
#[must_use]
pub fn attribution_for(&self, years: (i32, i32)) -> String {
let (first, last) = years;
let text = if first == last {
first.to_string()
} else {
format!("{first}\u{2013}{last}")
};
self.attribution.replace("{year}", &text)
}
#[must_use]
pub fn prelim_template(&self) -> &str {
self.prelim_file_template
.as_deref()
.unwrap_or(&self.file_template)
}
#[must_use]
pub fn crs(&self) -> Option<Crs> {
self.crs_epsg.and_then(|code| Crs::from_epsg(code).ok())
}
}
#[cfg(test)]
mod tests {
use super::*;
fn config_json(overrides: &[(&str, &str)]) -> String {
let mut fields: Vec<(String, String)> = vec![
("id".into(), "\"t\"".into()),
("name".into(), "\"T\"".into()),
("unit".into(), "\"mm\"".into()),
("period".into(), "\"pentad\"".into()),
("scale".into(), "1.0".into()),
("offset".into(), "0.0".into()),
("valid_min".into(), "0.0".into()),
("valid_max".into(), "5000.0".into()),
("nodata".into(), "-9999.0".into()),
("crs_epsg".into(), "4326".into()),
(
"file_template".into(),
"\"t.{year}.{month}.{pentad}.tif\"".into(),
),
("max_zoom".into(), "6".into()),
("tile_size".into(), "256".into()),
("season_start".into(), "\"06-01\"".into()),
("stale_after_days".into(), "18".into()),
("attribution".into(), "\"a\"".into()),
("source_url".into(), "\"https://example.org\"".into()),
("licence".into(), "\"CC BY 4.0\"".into()),
(
"ramp".into(),
r##"[{"value": 0.0, "color": "#ffffd9"}, {"value": 5.0, "color": "#0c2c84"}]"##
.into(),
),
];
for (key, value) in overrides {
match fields.iter_mut().find(|(k, _)| k == key) {
Some(field) => field.1 = (*value).to_owned(),
None => fields.push(((*key).to_owned(), (*value).to_owned())),
}
}
let body: Vec<String> = fields
.iter()
.map(|(k, v)| format!("\"{k}\": {v}"))
.collect();
format!("{{{}}}", body.join(", "))
}
#[test]
fn rainfall_config_loads() {
let path =
std::path::Path::new(env!("CARGO_MANIFEST_DIR")).join("data/datasets/rainfall.json");
let config = DatasetConfig::load(&path).expect("rainfall.json loads");
assert_eq!(config.max_zoom, 6);
assert_eq!(config.tile_size, 256);
assert_eq!(
config.attribution,
"Rainfall: CHIRPS v3.0, Climate Hazards Center, UC Santa Barbara. CC BY 4.0. \
DOI 10.15780/G2JQ0P"
);
assert_eq!(config.licence, "CC BY 4.0");
assert_eq!(config.season_start.as_deref(), Some("06-01"));
assert_eq!(config.period, PeriodKind::Pentad);
assert_eq!(config.crs(), Some(geolith::terrain::Crs::Wgs84));
use crate::rasters::match_template;
assert!(match_template(&config.file_template, "chirps-v3.0.2026.10.6.cog").is_some());
assert!(match_template(&config.file_template, "chirps-v3.0.1991.01.1.cog").is_some());
assert!(match_template(config.prelim_template(), "chirps-v3.0.2026.11.2.tif").is_some());
assert!(match_template(config.prelim_template(), "chirps-v3.0.2026.11.2.cog").is_none());
assert_eq!(config.nodata, Some(-9999.0));
assert_eq!(config.stale_after_days, 18);
}
#[test]
fn stale_after_days_is_required() {
let json = config_json(&[]).replace("\"stale_after_days\": 18, ", "");
assert!(!json.contains("stale_after_days"), "{json}");
let err = DatasetConfig::from_json_str(&json).expect_err("no stale_after_days");
assert!(
geolith::error::report(&err).contains("stale_after_days"),
"{err:#}"
);
let set = DatasetConfig::from_json_str(&config_json(&[("stale_after_days", "24")]))
.expect("valid config");
assert_eq!(set.stale_after_days, 24);
}
#[test]
fn prelim_template_defaults_to_file_template() {
let plain = DatasetConfig::from_json_str(&config_json(&[])).expect("valid config");
assert_eq!(plain.prelim_template(), "t.{year}.{month}.{pentad}.tif");
let split = DatasetConfig::from_json_str(&config_json(&[(
"prelim_file_template",
"\"p.{year}.{month}.{pentad}.tif\"",
)]))
.expect("valid config");
assert_eq!(split.prelim_template(), "p.{year}.{month}.{pentad}.tif");
assert_eq!(split.file_template, "t.{year}.{month}.{pentad}.tif");
}
#[test]
fn load_names_the_missing_path() {
let err = DatasetConfig::load(std::path::Path::new("/nonexistent/rain.json"))
.expect_err("no such file");
assert!(
geolith::error::report(&err).contains("/nonexistent/rain.json"),
"{err:#}"
);
}
#[test]
fn decode_masks_nodata_and_range() {
let config = DatasetConfig::from_json_str(&config_json(&[])).expect("valid config");
assert_eq!(config.decode(-9999.0), None);
assert_eq!(config.decode(f32::NAN), None);
assert_eq!(config.decode(-1.0), None);
assert_eq!(config.decode(5000.5), None);
assert_eq!(config.decode(0.0), Some(0.0));
assert_eq!(config.decode(42.5), Some(42.5));
}
#[test]
fn decode_applies_scale_then_offset() {
let config = DatasetConfig::from_json_str(&config_json(&[
("scale", "0.004"),
("offset", "-0.08"),
("valid_min", "-1.0"),
("valid_max", "1.0"),
("nodata", "255.0"),
]))
.expect("valid config");
let decoded = config.decode(250.0).expect("250 is in range");
assert!((decoded - 0.92).abs() < 1e-12, "{decoded}");
assert_eq!(config.decode(255.0), None);
}
#[test]
fn ramp_colours_parse() {
let config = DatasetConfig::from_json_str(&config_json(&[(
"ramp",
r##"[{"value": 0.0, "color": "#0c2c84"}, {"value": 1.0, "color": "#0c2c8480"}]"##,
)]))
.expect("valid config");
let opaque = config
.ramp
.iter()
.find(|stop| stop.value == 0.0)
.expect("stop at 0");
assert_eq!(opaque.color, [12, 44, 132, 255]);
let translucent = config
.ramp
.iter()
.find(|stop| stop.value == 1.0)
.expect("stop at 1");
assert_eq!(translucent.color, [12, 44, 132, 128]);
}
#[test]
fn a_season_start_off_a_period_start_is_rejected() {
let err = DatasetConfig::from_json_str(&config_json(&[("season_start", "\"06-03\"")]))
.expect_err("06-03 is inside pentad 06-1");
assert!(geolith::error::report(&err).contains("06-03"), "{err:#}");
for day in ["06-01", "06-06", "02-26", "12-21"] {
let json = config_json(&[("season_start", &format!("\"{day}\""))]);
let config = DatasetConfig::from_json_str(&json)
.unwrap_or_else(|e| panic!("{day} starts a pentad: {e:#}"));
assert_eq!(config.season_start.as_deref(), Some(day));
}
}
#[test]
fn bad_configs_are_rejected() {
let cases: [(&str, &str); 9] = [
("ramp", r##"[{"value": 0.0, "color": "#ffffd9"}]"##),
(
"ramp",
r##"[{"value": 5.0, "color": "#ffffd9"}, {"value": 5.0, "color": "#0c2c84"}]"##,
),
("valid_min", "10.0"),
("max_zoom", "23"),
("tile_size", "300"),
("season_start", "\"June 1\""),
("unknwon_key", "1"),
(
"ramp",
r##"[{"value": 0.0, "color": "ffffd9"}, {"value": 5.0, "color": "#0c2c84"}]"##,
),
("crs_epsg", "27700"),
];
for (key, value) in cases {
let json = if key == "valid_min" {
config_json(&[("valid_min", value), ("valid_max", "0.0")])
} else {
config_json(&[(key, value)])
};
assert!(
DatasetConfig::from_json_str(&json).is_err(),
"{key} = {value} must be rejected"
);
}
let err = DatasetConfig::from_json_str(&config_json(&[("period", "\"week\"")]))
.expect_err("week is no period");
assert!(geolith::error::report(&err).contains("week"), "{err:#}");
}
fn repo_config(name: &str) -> DatasetConfig {
let path = std::path::Path::new(env!("CARGO_MANIFEST_DIR"))
.join("data/datasets")
.join(name);
DatasetConfig::load(&path).unwrap_or_else(|e| panic!("{name} loads: {e:#}"))
}
fn dekad_json(overrides: &[(&str, &str)]) -> String {
let mut all = vec![
("period", "\"dekad\""),
("file_template", "\"ndvi300-v3.{year}.{month}.{dekad}.tif\""),
("season_start", "null"),
];
all.extend_from_slice(overrides);
config_json(&all)
}
#[test]
fn rainfall_json_parses_with_p1_defaults() {
let config = repo_config("rainfall.json");
assert_eq!(config.comparison, Comparison::Normal);
assert_eq!(config.reader, Reader::Whole);
assert_eq!(config.anomaly_pct_min_normal, Some(1.0));
assert!(config.flags.is_empty(), "{:?}", config.flags);
assert_eq!(config.record_start, None);
let again = serde_json::to_string(&config).expect("serialises");
let reparsed = DatasetConfig::from_json_str(&again).expect("re-parses");
assert_eq!(reparsed, config);
}
#[test]
fn ndvi_json_parses() {
let config = repo_config("ndvi.json");
assert_eq!(config.period, PeriodKind::Dekad);
assert_eq!(config.scale, 0.004);
assert_eq!(config.offset, -0.08);
assert_eq!(config.nodata, Some(255.0));
assert_eq!(config.flags, [252.0, 253.0, 254.0]);
assert_eq!(config.reader, Reader::Windowed);
assert_eq!(config.comparison, Comparison::Average);
assert_eq!(config.anomaly_pct_min_normal, None);
assert_eq!(config.record_start.as_deref(), Some("2014-01-01"));
assert_eq!(config.baseline.as_deref(), Some("2019-2025"));
assert_eq!(config.sensor.as_deref(), Some("Sentinel-3 OLCI"));
assert_eq!(config.max_zoom, 9);
assert_eq!(config.season_start, None);
assert_eq!(config.stale_after_days, 24);
let again = serde_json::to_string(&config).expect("serialises");
assert_eq!(
DatasetConfig::from_json_str(&again).expect("re-parses"),
config
);
}
#[test]
fn ndvi_raw_flags_and_nodata_are_masked() {
let config = repo_config("ndvi.json");
let low = config.decode(0.0).expect("raw 0 is valid");
assert!((low - -0.08).abs() < 1e-12, "{low}");
let high = config.decode(250.0).expect("raw 250 is valid");
assert!((high - 0.92).abs() < 1e-12, "{high}");
for raw in 251..=255u8 {
assert_eq!(config.decode(f32::from(raw)), None, "raw {raw}");
}
assert_eq!(config.decode(f32::NAN), None);
}
#[test]
fn dekad_templates_match() {
use crate::rasters::{Period, match_template};
assert_eq!(
match_template(
"ndvi300-v3.{year}.{month}.{dekad}.tif",
"ndvi300-v3.2026.10.2.tif"
),
Some(Period {
year: 2026,
month: 10,
index: 2,
kind: PeriodKind::Dekad,
})
);
assert_eq!(
match_template(
"ndvi300-v3.{year}.{month}.{dekad}.tif",
"ndvi300-v3.2026.10.4.tif"
),
None
);
DatasetConfig::from_json_str(&dekad_json(&[])).expect("a dekad template is valid");
for template in [
"\"n.{year}.{month}.{pentad}.{dekad}.tif\"",
"\"n.{year}.{month}.tif\"",
"\"n.{year}.{month}.{pentad}.tif\"",
"\"n.{year}.{month}.{dekad}.{dekad}.tif\"",
] {
let err = DatasetConfig::from_json_str(&dekad_json(&[("file_template", template)]))
.expect_err(template);
assert!(
geolith::error::report(&err).contains("file_template"),
"{err:#}"
);
}
let err = DatasetConfig::from_json_str(&dekad_json(&[(
"prelim_file_template",
"\"p.{year}.{month}.{pentad}.tif\"",
)]))
.expect_err("a pentad prelim template in a dekad config");
assert!(
geolith::error::report(&err).contains("prelim_file_template"),
"{err:#}"
);
let err = DatasetConfig::from_json_str(&config_json(&[(
"file_template",
"\"t.{year}.{month}.{dekad}.tif\"",
)]))
.expect_err("a dekad template in a pentad config");
assert!(geolith::error::report(&err).contains("{pentad}"), "{err:#}");
}
#[test]
fn season_start_must_start_a_dekad() {
for day in ["06-01", "06-11", "02-21"] {
let json = dekad_json(&[("season_start", &format!("\"{day}\""))]);
let config = DatasetConfig::from_json_str(&json)
.unwrap_or_else(|e| panic!("{day} starts a dekad: {e:#}"));
assert_eq!(config.season_start.as_deref(), Some(day));
}
for day in ["06-06", "06-26", "06-02"] {
let json = dekad_json(&[("season_start", &format!("\"{day}\""))]);
let err = DatasetConfig::from_json_str(&json).expect_err(day);
let text = geolith::error::report(&err);
assert!(text.contains(day) && text.contains("dekad"), "{text}");
}
}
#[test]
fn record_start_must_be_a_date() {
let set = DatasetConfig::from_json_str(&dekad_json(&[("record_start", "\"2014-01-21\"")]))
.expect("valid record_start");
assert_eq!(set.record_start.as_deref(), Some("2014-01-21"));
for bad in [
"\"2014-1-21\"",
"\"21-01-2014\"",
"\"2014-02-30\"",
"\"2015-02-29\"",
] {
let err =
DatasetConfig::from_json_str(&dekad_json(&[("record_start", bad)])).expect_err(bad);
assert!(
geolith::error::report(&err).contains("record_start"),
"{err:#}"
);
}
DatasetConfig::from_json_str(&dekad_json(&[("record_start", "\"2016-02-29\"")]))
.expect("a leap day is a date");
}
#[test]
fn repo_configs_carry_the_series_classes() {
let rainfall = repo_config("rainfall.json");
let classes = rainfall.classes.expect("rainfall classes");
assert_eq!(classes.value, [1.0, 5.0, 10.0, 25.0, 50.0, 100.0, 200.0]);
assert_eq!(classes.comparison, [25.0, 50.0, 80.0, 120.0, 150.0, 200.0]);
assert_eq!(classes.comparison_kind, ClassComparison::PctOfNormal);
assert_eq!(rainfall.layer_periods, Some(12));
assert_eq!(rainfall.history_max_zoom, None);
let ndvi = repo_config("ndvi.json");
let classes = ndvi.classes.expect("ndvi classes");
assert_eq!(classes.value, [0.2, 0.3, 0.4, 0.5, 0.6, 0.7, 0.8]);
assert_eq!(classes.comparison, [-0.1, -0.05, -0.02, 0.02, 0.05, 0.1]);
assert_eq!(classes.comparison_kind, ClassComparison::AnomalyAbs);
let mirrored: Vec<f64> = classes.comparison.iter().rev().map(|b| -b).collect();
assert_eq!(mirrored, classes.comparison);
assert_eq!(ndvi.layer_periods, Some(12));
assert_eq!(ndvi.history_max_zoom, Some(7));
}
#[test]
fn bad_classes_and_layer_settings_are_refused() {
let classes = |value: &str, comparison: &str| {
format!(
r#"{{"value":{value},"comparison":{comparison},"comparison_kind":"anomaly_abs"}}"#
)
};
let ok = classes("[0.2,0.5]", "[-0.1,0.1]");
DatasetConfig::from_json_str(&dekad_json(&[("classes", &ok)])).expect("valid classes");
let too_many = format!(
"[{}]",
(0..36).map(|i| i.to_string()).collect::<Vec<_>>().join(",")
);
for bad in [
classes("[]", "[1]"),
classes("[0.5,0.2]", "[1]"),
classes("[0.2,0.2]", "[1]"),
classes("[1]", &too_many),
r#"{"value":[1],"comparison":[1],"comparison_kind":"ratio"}"#.to_owned(),
r#"{"value":[1],"comparison":[1],"comparison_kind":"anomaly_abs","x":1}"#.to_owned(),
] {
assert!(
DatasetConfig::from_json_str(&dekad_json(&[("classes", &bad)])).is_err(),
"accepted {bad}"
);
}
for (key, value, good) in [
("layer_periods", "1", true),
("layer_periods", "12", true),
("layer_periods", "0", false),
("layer_periods", "13", false),
("history_max_zoom", "0", true),
] {
let parsed = DatasetConfig::from_json_str(&dekad_json(&[(key, value)]));
assert_eq!(parsed.is_ok(), good, "{key} {value}: {parsed:?}");
}
let above = DatasetConfig::from_json_str(&dekad_json(&[("history_max_zoom", "23")]));
assert!(above.is_err());
}
#[test]
fn a_baseline_is_two_years_first_first() {
let rainfall = repo_config("rainfall.json");
assert_eq!(rainfall.baseline, None);
assert_eq!(rainfall.sensor, None);
for good in ["2019-2025", "2020-2020"] {
DatasetConfig::from_json_str(&dekad_json(&[("baseline", &format!("\"{good}\""))]))
.unwrap_or_else(|e| panic!("{good}: {e:#}"));
}
for bad in ["2025-2019", "2019", "19-25", "2019-2025-1", ""] {
assert!(
DatasetConfig::from_json_str(&dekad_json(&[("baseline", &format!("\"{bad}\""))]))
.is_err(),
"{bad:?} accepted"
);
}
assert!(DatasetConfig::from_json_str(&dekad_json(&[("sensor", "\" \"")])).is_err());
}
#[test]
fn the_comparison_label_never_says_normal() {
let ndvi = repo_config("ndvi.json");
let label = ndvi.comparison_label("2019-2025").expect("average label");
assert_eq!(label, "vs 2019\u{2013}2025 average (Sentinel-3 OLCI)");
assert!(!label.to_lowercase().contains("normal"), "{label}");
let no_sensor = DatasetConfig {
sensor: None,
..ndvi
};
assert_eq!(
no_sensor.comparison_label("2014-2025").as_deref(),
Some("vs 2014\u{2013}2025 average")
);
assert_eq!(
repo_config("rainfall.json").comparison_label("1991-2020"),
None
);
}
#[test]
fn the_copernicus_year_is_filled() {
let ndvi = repo_config("ndvi.json");
assert_eq!(
ndvi.attribution_for((2026, 2026)),
"Contains modified Copernicus Land Monitoring Service information 2026"
);
assert_eq!(
ndvi.attribution_for((2014, 2025)),
"Contains modified Copernicus Land Monitoring Service information 2014\u{2013}2025"
);
let rainfall = repo_config("rainfall.json");
assert_eq!(rainfall.attribution_for((2014, 2025)), rainfall.attribution);
assert!(!rainfall.attribution.contains("{year}"));
}
#[test]
fn period_kinds_know_their_starts() {
assert_eq!(PeriodKind::default(), PeriodKind::Pentad);
assert_eq!(PeriodKind::Pentad.periods_per_month(), 6);
assert_eq!(PeriodKind::Dekad.periods_per_month(), 3);
assert_eq!(PeriodKind::Pentad.starts(), [1, 6, 11, 16, 21, 26]);
assert_eq!(PeriodKind::Dekad.starts(), [1, 11, 21]);
}
}