File size: 22,446 Bytes
1a48d6b
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
"""Field encoding, request validation, and estimate grids for Clairic.

Scalar types include text, numbers, dates, times, datetimes, and durations.
Lists preserve source order. Estimates use declared numeric or date ranges;
forecasts expand into bounded estimate fields for each requested step.
"""

from __future__ import annotations

import datetime
import difflib
import itertools
import math
import re
from typing import Any

READ_TYPES = ("text", "number", "date", "time", "datetime", "duration")
FIELD_TYPES = READ_TYPES + ("list", "estimate")
LIST_ITEM_TYPES = ("text", "number", "date")
DURATION_UNITS = ("seconds", "minutes", "hours", "days", "weeks", "months", "years")
MAX_LIST_ITEMS = 32
MAX_DECIMALS = 6
MAX_FORECAST_HORIZON = 64
FORECAST_INTERVALS = (
    "step",
    "minute",
    "hour",
    "day",
    "week",
    "month",
    "quarter",
    "year",
)
DEFAULT_NULL_THRESHOLD = 0.5
MAX_GRID_STEPS = 1_000_000
COMMON_KEYS = ("type", "instructions", "unit")
NUMBER_KEYS = ("integer", "decimals")
ESTIMATE_KEYS = ("min", "max", "scale", "step")
FIELD_KEYS = {
    "text": (*COMMON_KEYS, "null_threshold"),
    "number": (*COMMON_KEYS, "null_threshold", *NUMBER_KEYS),
    "date": (*COMMON_KEYS, "null_threshold"),
    "time": (*COMMON_KEYS, "null_threshold"),
    "datetime": (*COMMON_KEYS, "null_threshold"),
    "duration": (*COMMON_KEYS, "null_threshold", *NUMBER_KEYS),
    "list": (*COMMON_KEYS, "items", *NUMBER_KEYS),
    "estimate": (*COMMON_KEYS, *ESTIMATE_KEYS),
    "forecast": (*COMMON_KEYS, *ESTIMATE_KEYS, "horizon", "interval"),
}
ALL_FIELD_KEYS = tuple(
    dict.fromkeys(key for keys in FIELD_KEYS.values() for key in keys)
)

SYSTEM_PREAMBLE = (
    "Fill each field from the input with a value of its type. Text copies a span of the input. Numbers, "
    "dates, times, datetimes, and durations are read from the input or worked out from it. A list holds "
    "every matching value in input order. A field is not stated when the input does not determine it. "
    "Estimates predict a value inside the declared range."
)

FIELD_NAME = re.compile(r"^[A-Za-z_][A-Za-z0-9_.\-]{0,63}$")


def format_bound(value: float) -> str:
    if float(value).is_integer() and abs(value) < 1e15:
        return str(int(value))
    return f"{value:.6g}"


def field_line(name: str, spec: dict[str, Any]) -> str:
    kind = spec["type"]
    unit = str(spec.get("unit") or "").strip()
    if kind == "estimate" and is_date_estimate(spec):
        head = f"estimate date, {spec['min']} to {spec['max']}"
        granularity = date_granularity(spec)
        if granularity != "day":
            head += f", by {granularity}"
        elif spec.get("step") and float(spec["step"]) != 1:
            head += f", step {format_bound(float(spec['step']))} days"
    elif kind == "estimate":
        head = (
            f"estimate{(' ' + unit) if unit else ''}, {format_bound(spec['min'])} to "
            f"{format_bound(spec['max'])}, {spec.get('scale', 'linear')} scale"
        )
        if spec.get("step"):
            head += f", step {format_bound(float(spec['step']))}"
    elif kind == "list":
        head = f"list of {spec['items']}{number_options(spec)}{(' (' + unit + ')') if unit else ''}"
    elif kind == "duration":
        head = f"duration in {duration_unit(spec)}{number_options(spec)}"
    else:
        head = f"{kind}{number_options(spec) if kind == 'number' else ''}{(' (' + unit + ')') if unit else ''}"
    instructions = " ".join(str(spec.get("instructions") or "").split())
    return f"{name}: {head}." + (f" {instructions}" if instructions else "")


def number_options(spec: dict[str, Any]) -> str:
    if spec.get("integer"):
        return ", integer"
    if spec.get("decimals") is not None:
        return f", {int(spec['decimals'])} decimals"
    return ""


def duration_unit(spec: dict[str, Any]) -> str:
    return str(spec.get("unit") or "seconds")


def allowed_decimals(spec: dict[str, Any]) -> int | None:
    """Decimal places a number, duration, or number-list field allows (None: any)."""
    if spec.get("integer"):
        return 0
    return None if spec.get("decimals") is None else int(spec["decimals"])


def parse_time(value: Any) -> tuple[int, int, int]:
    """("HH:MM" or "HH:MM:SS") as (hour, minute, second); ValueError otherwise."""
    if not isinstance(value, str):
        raise ValueError(f"time must be a string, got {value!r}")  # noqa: TRY004 - callers catch ValueError
    parsed = datetime.time.fromisoformat(value)
    if parsed.microsecond or parsed.tzinfo is not None:
        raise ValueError(f"time {value!r} must be HH:MM or HH:MM:SS")
    return parsed.hour, parsed.minute, parsed.second


def format_time(hour: int, minute: int, second: int) -> str:
    return f"{hour:02d}:{minute:02d}:{second:02d}"


def parse_datetime(value: Any) -> tuple[str, tuple[int, int, int]]:
    """("YYYY-MM-DDTHH:MM[:SS]") as (ISO date, (hour, minute, second)); ValueError otherwise."""
    if not isinstance(value, str) or "T" not in value:
        raise ValueError(f"datetime must be YYYY-MM-DDTHH:MM[:SS], got {value!r}")
    day, clock = value.split("T", 1)
    return datetime.date.fromisoformat(day).isoformat(), parse_time(clock)


def forecast_instructions(instructions: str, step: int, interval: str) -> str:
    """The instructions for one step of a forecast path."""
    what = " ".join(str(instructions or "").split()).rstrip(".") or "the series"
    unit = "step" if interval == "step" else interval
    return f"Forecast {what} {step} {unit}{'s' if step > 1 else ''} after the last observation."


def check_field_keys(fields: dict[str, Any]) -> None:
    """Every field spec uses only the keys its type takes, so a misspelled option ("decimal",
    "interger") is an error instead of a constraint that is silently dropped."""
    for name, spec in fields.items():
        if not isinstance(spec, dict) or spec.get("type") not in FIELD_KEYS:
            continue
        kind = spec["type"]
        for key in spec:
            if key in FIELD_KEYS[kind]:
                continue
            if key in ALL_FIELD_KEYS:
                raise ValueError(f"field {name}: {kind} fields don't take {key!r}")
            close = difflib.get_close_matches(
                str(key), FIELD_KEYS[kind], n=1, cutoff=0.6
            )
            hint = (
                f"; did you mean {close[0]!r}?"
                if close
                else f"; {kind} fields take {', '.join(FIELD_KEYS[kind])}"
            )
            raise ValueError(f"field {name} has unknown key {key!r}{hint}")


def expand_forecasts(
    fields: dict[str, Any],
) -> tuple[dict[str, Any], dict[str, list[str]]]:
    """Request fields with every ``forecast`` replaced by ``horizon`` estimate fields named
    ``name.1`` ... ``name.H`` (same range, scale, step, and unit), plus each forecast's step names."""
    expanded: dict[str, Any] = {}
    groups: dict[str, list[str]] = {}
    for name, spec in fields.items():
        if not isinstance(spec, dict) or spec.get("type") != "forecast":
            expanded[name] = spec
            continue
        horizon = spec.get("horizon")
        if (
            isinstance(horizon, bool)
            or not isinstance(horizon, int)
            or not 1 <= horizon <= MAX_FORECAST_HORIZON
        ):
            raise ValueError(
                f"forecast {name} needs an integer horizon from 1 to {MAX_FORECAST_HORIZON}"
            )
        interval = spec.get("interval", "step")
        if interval not in FORECAST_INTERVALS:
            raise ValueError(f"forecast {name} has an unknown interval {interval!r}")
        base = {
            key: value
            for key, value in spec.items()
            if key not in ("type", "horizon", "interval", "instructions")
        }
        if is_date_estimate({"type": "estimate", **base}):
            validate_date_range(name, {"type": "estimate", **base}, kind="forecast")
        else:
            validate_number_range(name, {"type": "estimate", **base}, kind="forecast")
        groups[name] = []
        for step in range(1, horizon + 1):
            step_name = f"{name}.{step}"
            if step_name in fields or step_name in expanded:
                raise ValueError(
                    f"forecast {name} step {step_name} collides with another field"
                )
            expanded[step_name] = {
                "type": "estimate",
                **base,
                "instructions": forecast_instructions(
                    spec.get("instructions", ""), step, interval
                ),
            }
            groups[name].append(step_name)
    return expanded, groups


# ---------------------------------------------------------------- estimate transforms


def to_unit(value: float, low: float, high: float, scale: str) -> float:
    return min(1.0, max(0.0, raw_unit(value, low, high, scale)))


def raw_unit(value: float, low: float, high: float, scale: str) -> float:
    """Unit position without clamping: below 0 or above 1 when the value is outside the range (a
    non-positive value on a log scale is -1)."""
    if scale == "log":
        if value <= 0:
            return -1.0
        return (math.log(value) - math.log(low)) / (math.log(high) - math.log(low))
    return (value - low) / (high - low)


def from_unit(position: float, low: float, high: float, scale: str) -> float:
    position = min(1.0, max(0.0, position))
    if scale == "log":
        value = math.exp(math.log(low) + position * (math.log(high) - math.log(low)))
    else:
        value = low + position * (high - low)
    return min(high, max(low, value))


def resolution_in_unit(spec: dict[str, Any], resolution: float | None) -> float:
    if not resolution:
        return 0.0
    low, high, scale = estimate_range(spec)
    if scale == "log":
        return math.log1p(resolution) / (math.log(high) - math.log(low))
    return resolution / (high - low)


# ---------------------------------------------------------------- date estimates


def is_date_estimate(spec: dict[str, Any]) -> bool:
    return spec.get("type") == "estimate" and isinstance(spec.get("min"), str)


def date_granularity(spec: dict[str, Any]) -> str:
    step = spec.get("step")
    return step if step in ("month", "year") else "day"


def date_index(value: str, granularity: str = "day") -> float:
    """A date as a number on its grid: day ordinal, months since year 0, or the year."""
    date = datetime.date.fromisoformat(value)
    if granularity == "month":
        return float(date.year * 12 + date.month - 1)
    if granularity == "year":
        return float(date.year)
    return float(date.toordinal())


def index_date(index: float, granularity: str = "day") -> str:
    whole = round(index)
    if granularity == "month":
        year, month = divmod(whole, 12)
        return datetime.date(year, month + 1, 1).isoformat()
    if granularity == "year":
        return datetime.date(whole, 1, 1).isoformat()
    return datetime.date.fromordinal(whole).isoformat()


def estimate_range(spec: dict[str, Any]) -> tuple[float, float, str]:
    """Numeric bounds and scale of an estimate; date bounds become grid indexes (linear scale)."""
    if is_date_estimate(spec):
        granularity = date_granularity(spec)
        return (
            date_index(spec["min"], granularity),
            date_index(spec["max"], granularity),
            "linear",
        )
    return float(spec["min"]), float(spec["max"]), spec.get("scale", "linear")


def estimate_step(spec: dict[str, Any]) -> float:
    """The grid step in the numeric space of ``estimate_range`` (0: continuous). Date estimates always
    have a grid: ``step`` days (default 1), or one month or year."""
    if is_date_estimate(spec):
        return (
            1.0 if date_granularity(spec) != "day" else float(spec.get("step") or 1.0)
        )
    return float(spec.get("step") or 0.0)


def estimate_number(spec: dict[str, Any], value: Any) -> float:
    if is_date_estimate(spec):
        return date_index(str(value), date_granularity(spec))
    return float(value)


def estimate_value(spec: dict[str, Any], number: float) -> float | str:
    """An estimate output in the field's own terms: an ISO date for date estimates."""
    if is_date_estimate(spec):
        low, high, _ = estimate_range(spec)
        return index_date(min(max(number, low), high), date_granularity(spec))
    return number


def grid_bounds(step: float, low: float, high: float) -> tuple[float, float]:
    """The smallest and largest multiples of ``step`` inside [low, high]."""
    first = math.ceil(low / step - 1e-9) * step
    last = math.floor(high / step + 1e-9) * step
    return float(f"{first:.12g}"), float(f"{last:.12g}")


def snap(value: float, step: float, low: float, high: float) -> float:
    """Nearest grid value inside the range."""
    first, last = grid_bounds(step, low, high)
    return float(f"{min(last, max(first, round(value / step) * step)):.12g}")


def snap_quantile(value: float, step: float, low: float, high: float) -> float:
    """Quantile of the discrete distribution a continuous one implies when every grid value v owns
    [v - step/2, v + step/2): the smallest v with v + step/2 >= the continuous quantile."""
    first, last = grid_bounds(step, low, high)
    return float(
        f"{min(last, max(first, math.ceil((value - step / 2) / step - 1e-9) * step)):.12g}"
    )


def step_interval(spec: dict[str, Any], value: float) -> tuple[float, float]:
    """The value-space interval a grid value owns, clipped to the declared range (``value`` in the
    numeric space of ``estimate_range``)."""
    step = estimate_step(spec)
    low, high, _ = estimate_range(spec)
    if step <= 0:
        return value, value
    return max(low, value - step / 2), min(high, value + step / 2)


# ---------------------------------------------------------------- text spans


def _cuts_word(text: str, start: int, end: int) -> bool:
    """Whether text[start:end] splits an ASCII word or number at either edge ("dock" inside "docks",
    "12" inside "312"). Other scripts are never treated as cut, so CJK matches are unaffected."""

    def joined(left: str, right: str) -> bool:
        return left.isascii() and left.isalnum() and right.isascii() and right.isalnum()

    return (start > 0 and joined(text[start - 1], text[start])) or (
        end < len(text) and joined(text[end - 1], text[end])
    )


def _prefer_whole(
    text: str, spans: list[tuple[int, int]], limit: int
) -> list[tuple[int, int]]:
    whole = [span for span in spans if not _cuts_word(text, *span)]
    return (whole or spans)[:limit]


def find_spans(text: str, value: str, limit: int = 16) -> list[tuple[int, int]]:
    """Character spans of ``value`` in ``text``: exact matches, else case-insensitive, else with any
    whitespace between words. Within each stage, matches on word boundaries are preferred; substring
    matches inside a longer word are kept only when there is no other match."""
    value = value.strip()
    if not value:
        return []
    scan = max(limit * 8, 64)
    spans: list[tuple[int, int]] = []
    start = text.find(value)
    while start >= 0 and len(spans) < scan:
        spans.append((start, start + len(value)))
        start = text.find(value, start + 1)
    if spans:
        return _prefer_whole(text, spans, limit)
    lowered, target = text.lower(), value.lower()
    if len(lowered) == len(text):
        start = lowered.find(target)
        while start >= 0 and len(spans) < scan:
            spans.append((start, start + len(value)))
            start = lowered.find(target, start + 1)
        if spans:
            return _prefer_whole(text, spans, limit)
    pieces = value.split()
    if not pieces:
        return []
    pattern = re.compile(
        r"\s+".join(re.escape(piece) for piece in pieces), re.IGNORECASE
    )
    spans = [
        (match.start(), match.end())
        for match in itertools.islice(pattern.finditer(text), scan)
    ]
    return _prefer_whole(text, spans, limit)


# ---------------------------------------------------------------- records


def validate_fields(fields: Any) -> None:
    """A schema with any number of fields (at least one): valid names, known types, and for estimates
    a valid range, scale, and step. Requests are checked with this before prediction, so every output
    can be held to its field's type."""
    if not isinstance(fields, dict) or not fields:
        raise ValueError("fields must declare at least one field")
    for name, spec in fields.items():
        if not isinstance(name, str) or not FIELD_NAME.match(name):
            raise ValueError(f"invalid field name {name!r}")
        kind = spec.get("type") if isinstance(spec, dict) else None
        if kind not in FIELD_TYPES:
            raise ValueError(f"field {name} has unknown type {kind!r}")
        if "null_threshold" in spec:
            threshold = spec["null_threshold"]
            if kind in ("estimate", "list"):
                raise ValueError(f"{kind} {name} does not take null_threshold")
            if (
                isinstance(threshold, bool)
                or not isinstance(threshold, (int, float))
                or not 0 < threshold <= 1
            ):
                raise ValueError(f"field {name} needs null_threshold in (0, 1]")
        if kind == "list" and spec.get("items") not in LIST_ITEM_TYPES:
            raise ValueError(f"list {name} needs items in {LIST_ITEM_TYPES}")
        if kind == "duration" and duration_unit(spec) not in DURATION_UNITS:
            raise ValueError(f"duration {name} needs a unit in {DURATION_UNITS}")
        numeric = kind in ("number", "duration") or (
            kind == "list" and spec.get("items") == "number"
        )
        if not numeric and ("integer" in spec or "decimals" in spec):
            raise ValueError(
                f"field {name}: integer and decimals apply to numbers and durations only"
            )
        if "integer" in spec and not isinstance(spec["integer"], bool):
            raise ValueError(f"field {name}: integer must be true or false")
        if "decimals" in spec:
            decimals = spec["decimals"]
            if (
                isinstance(decimals, bool)
                or not isinstance(decimals, int)
                or not 0 <= decimals <= MAX_DECIMALS
            ):
                raise ValueError(
                    f"field {name}: decimals must be an integer from 0 to {MAX_DECIMALS}"
                )
            if spec.get("integer") and decimals:
                raise ValueError(f"field {name}: an integer field has 0 decimals")
        if kind == "estimate" and is_date_estimate(spec):
            validate_date_range(name, spec)
        elif kind == "estimate":
            validate_number_range(name, spec)


def null_threshold(spec: dict[str, Any]) -> float:
    """A read field answers null when p_null is at or above this (default 0.5)."""
    return float(spec.get("null_threshold", DEFAULT_NULL_THRESHOLD))


def _number(value: Any) -> float:
    if isinstance(value, bool) or not isinstance(value, (int, float)):
        raise TypeError(value)
    return float(value)


def validate_number_range(
    name: str, spec: dict[str, Any], kind: str = "estimate"
) -> None:
    try:
        low, high = _number(spec["min"]), _number(spec["max"])
    except (KeyError, TypeError) as error:
        raise ValueError(f"{kind} {name} needs numeric min and max") from error
    if not (math.isfinite(low) and math.isfinite(high)) or low >= high:
        raise ValueError(
            f"{kind} {name} needs finite min < max, got {spec['min']!r} and {spec['max']!r}"
        )
    scale = spec.get("scale", "linear")
    if scale not in ("linear", "log"):
        raise ValueError(
            f"{kind} {name} has an unknown scale {scale!r}; use 'linear' or 'log'"
        )
    if scale == "log" and low <= 0:
        raise ValueError(
            f"{kind} {name} uses scale 'log', which needs min > 0, got {spec['min']!r}"
        )
    if spec.get("step") is None:
        return
    try:
        step = _number(spec["step"])
    except TypeError as error:
        raise ValueError(
            f"{kind} {name}: step must be a positive number, got {spec['step']!r}"
        ) from error
    if not math.isfinite(step) or step <= 0:
        raise ValueError(
            f"{kind} {name}: step must be a positive number, got {spec['step']!r}"
        )
    steps = (high - low) / step
    if steps < 1:
        raise ValueError(
            f"{kind} {name}: step {spec['step']!r} is larger than the range {spec['min']!r} to {spec['max']!r}"
        )
    if steps > MAX_GRID_STEPS:
        raise ValueError(
            f"{kind} {name}: step {spec['step']!r} divides {spec['min']!r} to {spec['max']!r} into {steps:,.0f} steps; "
            f"the limit is {MAX_GRID_STEPS:,}. Use a larger step or omit it"
        )


def validate_reference_date(value: Any) -> None:
    if value is None:
        return
    try:
        datetime.date.fromisoformat(value)
    except (TypeError, ValueError) as error:
        raise ValueError(
            f"reference_date must be an ISO date, got {value!r}"
        ) from error


def validate_date_range(
    name: str, spec: dict[str, Any], kind: str = "estimate"
) -> None:
    try:
        low, high, _ = estimate_range(spec)
    except (KeyError, TypeError, ValueError) as error:
        raise ValueError(
            f"date {kind} {name} needs ISO date min and max (YYYY-MM-DD)"
        ) from error
    if not isinstance(spec.get("max"), str) or not low < high:
        raise ValueError(
            f"date {kind} {name} needs ISO date min < max, got {spec.get('min')!r} and {spec.get('max')!r}"
        )
    if spec.get("scale", "linear") != "linear":
        raise ValueError(f"date {kind} {name} only takes scale 'linear'")
    if date_granularity(spec) != "day" or spec.get("step") is None:
        return
    step = spec["step"]
    if (
        isinstance(step, bool)
        or not isinstance(step, (int, float))
        or not float(step).is_integer()
        or step < 1
    ):
        raise ValueError(
            f"date {kind} {name}: step must be a whole number of days, 'month', or 'year', got {step!r}"
        )
    if (high - low) / step < 1:
        raise ValueError(
            f"date {kind} {name}: step {step!r} days is larger than the range"
        )