cedarkit-query 0.2.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,967 @@
1
+ """Pure canonicalization and bounded selection algebra; no source or resource I/O."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import hashlib
6
+ import itertools
7
+ import math
8
+ import re
9
+ from datetime import datetime, timedelta, timezone
10
+ from decimal import Decimal, localcontext
11
+ from fractions import Fraction
12
+
13
+ from ._json import canonical, plain
14
+ from .errors import QueryError
15
+
16
+ DEFAULT_MAX_EXPANSION = 10000
17
+ _EPOCH = datetime(1970, 1, 1, tzinfo=timezone.utc)
18
+ _TIME = re.compile(
19
+ r"^(\d{4}-\d{2}-\d{2}T\d{2}:\d{2}:\d{2})(\.\d+)?(Z|[+-]\d{2}:\d{2})$"
20
+ )
21
+ _DURATION = re.compile(
22
+ r"^P(?:(\d+(?:\.\d+)?)D)?(?:T(?:(\d+(?:\.\d+)?)H)?(?:(\d+(?:\.\d+)?)M)?(?:(\d+(?:\.\d+)?)S)?)?$"
23
+ )
24
+ _VERTICAL_UNITS = {
25
+ "pressure": ("hPa", {"Pa": Decimal("0.01"), "hPa": Decimal(1)}),
26
+ "height_above_ground": (
27
+ "m",
28
+ {"m": Decimal(1), "cm": Decimal("0.01"), "km": Decimal(1000)},
29
+ ),
30
+ "height_above_sea": (
31
+ "m",
32
+ {"m": Decimal(1), "cm": Decimal("0.01"), "km": Decimal(1000)},
33
+ ),
34
+ "depth_below_land": (
35
+ "m",
36
+ {"m": Decimal(1), "cm": Decimal("0.01"), "km": Decimal(1000)},
37
+ ),
38
+ }
39
+ NAMED_LEVELS = frozenset(
40
+ {"surface", "atmosphere_top", "entire_atmosphere", "mean_sea_level"}
41
+ )
42
+ _UNIT_ALIASES = {
43
+ "pascal": "Pa",
44
+ "hectopascal": "hPa",
45
+ "meter": "m",
46
+ "metre": "m",
47
+ "centimeter": "cm",
48
+ "centimetre": "cm",
49
+ "kilometer": "km",
50
+ "kilometre": "km",
51
+ }
52
+
53
+
54
+ def _fail(path, message, code="invalid_query", **context):
55
+ raise QueryError(code, path, message, context or None)
56
+
57
+
58
+ def json_number(value):
59
+ value = Decimal(str(value))
60
+ if not value.is_finite():
61
+ _fail("", "finite number required")
62
+ if value == value.to_integral_value():
63
+ return int(value)
64
+ result = float(value)
65
+ if not math.isfinite(result) or Decimal(str(result)) != value:
66
+ _fail("", "value cannot be represented losslessly as a JSON number")
67
+ return result
68
+
69
+
70
+ def duration_seconds(value, path=""):
71
+ match = _DURATION.fullmatch(value)
72
+ if (
73
+ not match
74
+ or not any(match.groups())
75
+ or ("T" in value and not any(match.groups()[1:]))
76
+ ):
77
+ _fail(path, "expected a nonnegative fixed ISO 8601 duration")
78
+ with localcontext() as ctx:
79
+ ctx.prec = max(28, len(value) + 12)
80
+ result = sum(
81
+ (
82
+ Decimal(v or 0) * scale
83
+ for v, scale in zip(match.groups(), (86400, 3600, 60, 1))
84
+ ),
85
+ Decimal(0),
86
+ )
87
+ if result != result.quantize(Decimal("0.000000001")):
88
+ _fail(path, "duration precision finer than nanoseconds is unsupported")
89
+ return result
90
+
91
+
92
+ def duration_text(seconds):
93
+ text = format(Decimal(seconds), "f")
94
+ return "PT" + (text.rstrip("0").rstrip(".") if "." in text else text) + "S"
95
+
96
+
97
+ def time_seconds(value, path=""):
98
+ match = _TIME.fullmatch(value)
99
+ if not match:
100
+ _fail(path, "expected an explicit-timezone ISO 8601 timestamp")
101
+ if len((match[2] or "").rstrip("0")) > 10:
102
+ _fail(path, "timestamp precision finer than nanoseconds is unsupported")
103
+ try:
104
+ dt = datetime.fromisoformat(match[1] + match[3].replace("Z", "+00:00"))
105
+ delta = dt.astimezone(timezone.utc) - _EPOCH
106
+ return Decimal(delta.days * 86400 + delta.seconds) + Decimal(match[2] or 0)
107
+ except (ValueError, OverflowError) as exc:
108
+ raise QueryError(
109
+ "invalid_query", path, "invalid calendar date or offset"
110
+ ) from exc
111
+
112
+
113
+ def time_text(seconds):
114
+ seconds = Decimal(seconds)
115
+ whole = math.floor(seconds)
116
+ try:
117
+ dt = _EPOCH + timedelta(seconds=whole)
118
+ except OverflowError as exc:
119
+ raise QueryError(
120
+ "invalid_query", "", "timestamp outside supported calendar"
121
+ ) from exc
122
+ fraction = seconds - whole
123
+ return (
124
+ f"{dt.year:04d}-{dt.month:02d}-{dt.day:02d}T{dt.hour:02d}:{dt.minute:02d}:{dt.second:02d}"
125
+ + (format(fraction, "f")[1:].rstrip("0") if fraction else "")
126
+ + "Z"
127
+ )
128
+
129
+
130
+ def unit_name(unit):
131
+ return _UNIT_ALIASES.get(unit, unit)
132
+
133
+
134
+ def _numeric(value, kind, path=""):
135
+ if kind == "time":
136
+ return time_seconds(value, path)
137
+ if kind == "duration":
138
+ return duration_seconds(value, path)
139
+ if type(value) not in (int, float):
140
+ _fail(path, "numeric range value required")
141
+ return Decimal(str(value))
142
+
143
+
144
+ def _encode(value, kind):
145
+ return (
146
+ time_text(value)
147
+ if kind == "time"
148
+ else duration_text(value)
149
+ if kind == "duration"
150
+ else json_number(value)
151
+ )
152
+
153
+
154
+ def selector_kind(field):
155
+ return (
156
+ "time"
157
+ if field in {"time", "valid_time"}
158
+ else "duration"
159
+ if field == "step"
160
+ else "number"
161
+ )
162
+
163
+
164
+ def _normal_selector(value, kind, path, factor=Decimal(1)):
165
+ def scalar(item):
166
+ if kind in {"time", "duration", "number"}:
167
+ return _encode(_numeric(item, kind, path) * factor, kind)
168
+ return item
169
+
170
+ if isinstance(value, dict) and "range" in value:
171
+ r = value["range"]
172
+ start, end = scalar(r["start"]), scalar(r["end"])
173
+ if _numeric(start, kind, path) > _numeric(end, kind, path):
174
+ _fail(path + "/range/end", "range end precedes start")
175
+ result = {"start": start, "end": end}
176
+ if "every" in r:
177
+ stride_kind = "duration" if kind == "time" else kind
178
+ stride = _numeric(r["every"], stride_kind, path + "/range/every") * factor
179
+ if stride <= 0:
180
+ _fail(path + "/range/every", "range interval must be positive")
181
+ result["every"] = _encode(stride, stride_kind)
182
+ return start if start == end else {"range": result}
183
+ values = value if isinstance(value, list) else [value]
184
+ unique = {canonical(scalar(v)): scalar(v) for v in values}
185
+ values = sorted(
186
+ unique.values(),
187
+ key=lambda v: (
188
+ _numeric(v, kind)
189
+ if kind in {"number", "time", "duration"}
190
+ else canonical(v)
191
+ ),
192
+ )
193
+ return values[0] if len(values) == 1 else values
194
+
195
+
196
+ def _vertical_factor(kind, unit, path):
197
+ if kind in NAMED_LEVELS or kind == "model_level":
198
+ if unit is not None:
199
+ _fail(path, "named levels and model indices have no physical unit")
200
+ return None, Decimal(1)
201
+ if kind not in _VERTICAL_UNITS:
202
+ _fail(
203
+ path,
204
+ "vertical type requires explicit definition",
205
+ "invalid_config",
206
+ reason="missing_context",
207
+ )
208
+ default, factors = _VERTICAL_UNITS[kind]
209
+ unit = default if unit is None else unit_name(unit)
210
+ if unit not in factors:
211
+ _fail(path, "unit is not valid for this vertical type")
212
+ return default, factors[unit]
213
+
214
+
215
+ def _endpoint(endpoint, outer_type, outer_unit, path, allow_unbound):
216
+ item = {"value": endpoint} if type(endpoint) in (int, float) else dict(endpoint)
217
+ kind = item.get("type", outer_type)
218
+ if outer_type is not None and kind != outer_type:
219
+ _fail(path + "/type", "endpoint conflicts with the shared vertical type")
220
+ if (
221
+ outer_unit is not None
222
+ and "unit" in item
223
+ and unit_name(item["unit"]) != unit_name(outer_unit)
224
+ ):
225
+ _fail(path + "/unit", "endpoint conflicts with the shared unit")
226
+ if kind is None:
227
+ if allow_unbound:
228
+ return item
229
+ _fail(
230
+ path,
231
+ "endpoint needs a vertical type",
232
+ "invalid_config",
233
+ reason="missing_context",
234
+ )
235
+ if kind in NAMED_LEVELS:
236
+ if "value" in item or "unit" in item or outer_unit is not None:
237
+ _fail(path, "named boundary must not have a value or unit")
238
+ return {"type": kind}
239
+ if "value" not in item:
240
+ _fail(path + "/value", "numeric boundary requires a value")
241
+ unit, factor = _vertical_factor(kind, item.get("unit", outer_unit), path + "/unit")
242
+ value = json_number(Decimal(str(item["value"])) * factor)
243
+ if kind == "model_level" and (type(value) is not int or value < 0):
244
+ _fail(path + "/value", "model level must be a nonnegative integer")
245
+ return {"type": kind, "value": value, **({"unit": unit} if unit else {})}
246
+
247
+
248
+ def _normalize(query, path="", allow_unbound=False):
249
+ result = dict(query)
250
+ kind, unit = result.get("level_type"), result.get("level_unit")
251
+ if "layer" in result:
252
+ layers = (
253
+ result["layer"] if isinstance(result["layer"], list) else [result["layer"]]
254
+ )
255
+ normalized = []
256
+ for i, layer in enumerate(layers):
257
+ item = {
258
+ end: _endpoint(
259
+ layer[end], kind, unit, f"{path}/layer/{i}/{end}", allow_unbound
260
+ )
261
+ for end in ("bottom", "top")
262
+ }
263
+ bottom, top = item["bottom"], item["top"]
264
+ if (
265
+ bottom.get("type")
266
+ in {
267
+ "pressure",
268
+ "depth_below_land",
269
+ "height_above_ground",
270
+ "height_above_sea",
271
+ }
272
+ and bottom.get("type") == top.get("type")
273
+ and "value" in bottom
274
+ and "value" in top
275
+ ):
276
+ reverse = bottom.get("type") in {"pressure", "depth_below_land"}
277
+ if bottom["value"] == top["value"] or (
278
+ bottom["value"] < top["value"]
279
+ if reverse
280
+ else bottom["value"] > top["value"]
281
+ ):
282
+ _fail(
283
+ path + "/layer",
284
+ "layer boundaries have invalid physical direction or zero width",
285
+ )
286
+ normalized.append(item)
287
+ normalized = list({canonical(v): v for v in normalized}.values())
288
+ normalized.sort(key=canonical)
289
+ result["layer"] = normalized[0] if len(normalized) == 1 else normalized
290
+ result.pop("level_type", None)
291
+ result.pop("level_unit", None)
292
+ elif kind is not None:
293
+ canonical_unit, factor = _vertical_factor(kind, unit, path + "/level_unit")
294
+ if kind in NAMED_LEVELS and "level" in result:
295
+ _fail(path + "/level", "named level must not have a value")
296
+ if "level" in result:
297
+ result["level"] = _normal_selector(
298
+ result["level"], "number", path + "/level", factor
299
+ )
300
+ if kind == "model_level":
301
+ values = result["level"]
302
+ check = (
303
+ list(values["range"].values())
304
+ if isinstance(values, dict)
305
+ else values
306
+ if isinstance(values, list)
307
+ else [values]
308
+ )
309
+ if any(type(v) is not int or v < 0 for v in check):
310
+ _fail(path + "/level", "model levels must be nonnegative integers")
311
+ if canonical_unit:
312
+ result["level_unit"] = canonical_unit
313
+ else:
314
+ result.pop("level_unit", None)
315
+ elif "level" in result:
316
+ result["level"] = _normal_selector(result["level"], "number", path + "/level")
317
+ if unit is not None:
318
+ result["level_unit"] = unit_name(unit)
319
+ for field in ("time", "step", "valid_time", "member", "parameter", "member_role"):
320
+ if field in result:
321
+ category = (
322
+ selector_kind(field)
323
+ if field in {"time", "step", "valid_time", "member"}
324
+ else "literal"
325
+ )
326
+ result[field] = _normal_selector(
327
+ result[field], category, path + "/" + field
328
+ )
329
+ if "native" in result:
330
+ result["native"] = {
331
+ "grib": {
332
+ k: _normal_selector(
333
+ v,
334
+ "number" if isinstance(v, dict) else "literal",
335
+ path + "/native/grib/" + k,
336
+ )
337
+ for k, v in result["native"]["grib"].items()
338
+ }
339
+ }
340
+ times = [result.get(k) for k in ("time", "step", "valid_time")]
341
+ if all(isinstance(v, str) for v in times):
342
+ if time_seconds(times[0]) + duration_seconds(times[1]) != time_seconds(
343
+ times[2]
344
+ ):
345
+ _fail(path + "/valid_time", "time + step differs from valid_time")
346
+ supplied = {k: result[k] for k in ("time", "step", "valid_time") if k in result}
347
+ if len(supplied) == 2 and all(isinstance(v, str) for v in supplied.values()):
348
+ numbers = {k: _numeric(v, selector_kind(k)) for k, v in supplied.items()}
349
+ missing = next(k for k in ("time", "step", "valid_time") if k not in supplied)
350
+ value = (
351
+ numbers["time"] + numbers["step"]
352
+ if missing == "valid_time"
353
+ else numbers["valid_time"] - numbers["step"]
354
+ if missing == "time"
355
+ else numbers["valid_time"] - numbers["time"]
356
+ )
357
+ if missing == "step" and value < 0:
358
+ _fail(path + "/step", "valid_time precedes time")
359
+ result[missing] = _encode(value, selector_kind(missing))
360
+ return result
361
+
362
+
363
+ def normalize_query(query):
364
+ from .model import Query
365
+
366
+ query = Query(query).to_dict()
367
+ return Query(_normalize(query))
368
+
369
+
370
+ def _count(selector, kind):
371
+ if isinstance(selector, list):
372
+ return len(selector)
373
+ if isinstance(selector, dict) and "range" in selector:
374
+ r = selector["range"]
375
+ if "every" not in r:
376
+ return None
377
+ step_kind = "duration" if kind == "time" else kind
378
+ return (
379
+ int(
380
+ (_numeric(r["end"], kind) - _numeric(r["start"], kind))
381
+ // _numeric(r["every"], step_kind)
382
+ )
383
+ + 1
384
+ )
385
+ return 1
386
+
387
+
388
+ def _values(selector, kind):
389
+ if isinstance(selector, list):
390
+ yield from selector
391
+ elif (
392
+ isinstance(selector, dict)
393
+ and "range" in selector
394
+ and "every" in selector["range"]
395
+ ):
396
+ r = selector["range"]
397
+ first = _numeric(r["start"], kind)
398
+ stride = _numeric(r["every"], "duration" if kind == "time" else kind)
399
+ for index in range(_count(selector, kind)):
400
+ yield _encode(first + index * stride, kind)
401
+ else:
402
+ yield selector
403
+
404
+
405
+ def _contains(selector, value, kind):
406
+ if isinstance(selector, list):
407
+ return any(canonical(v) == canonical(value) for v in selector)
408
+ if isinstance(selector, dict) and "range" in selector:
409
+ r = selector["range"]
410
+ first, last, actual = (_numeric(v, kind) for v in (r["start"], r["end"], value))
411
+ return first <= actual <= last and (
412
+ "every" not in r
413
+ or (actual - first)
414
+ % _numeric(r["every"], "duration" if kind == "time" else kind)
415
+ == 0
416
+ )
417
+ return canonical(selector) == canonical(value)
418
+
419
+
420
+ def _range_intersection(a, b, kind):
421
+ left, right = a["range"], b["range"]
422
+ lo = max(_numeric(left["start"], kind), _numeric(right["start"], kind))
423
+ hi = min(_numeric(left["end"], kind), _numeric(right["end"], kind))
424
+ if lo > hi:
425
+ return None
426
+ discrete = [r for r in (left, right) if "every" in r]
427
+ if not discrete:
428
+ return (
429
+ _encode(lo, kind)
430
+ if lo == hi
431
+ else {"range": {"start": _encode(lo, kind), "end": _encode(hi, kind)}}
432
+ )
433
+ step_kind = "duration" if kind == "time" else kind
434
+ fractions = [
435
+ Fraction(_numeric(r[key], step_kind if key == "every" else kind))
436
+ for r in discrete
437
+ for key in ("start", "every")
438
+ ]
439
+ scale = math.lcm(*(f.denominator for f in fractions))
440
+ lattice = [
441
+ (int(fractions[i] * scale), int(fractions[i + 1] * scale))
442
+ for i in range(0, len(fractions), 2)
443
+ ]
444
+ origin, stride = lattice[0]
445
+ if len(lattice) == 2:
446
+ other, step = lattice[1]
447
+ gcd = math.gcd(stride, step)
448
+ if (other - origin) % gcd:
449
+ return None
450
+ modulus = step // gcd
451
+ k = (
452
+ ((other - origin) // gcd * pow(stride // gcd, -1, modulus)) % modulus
453
+ if modulus > 1
454
+ else 0
455
+ )
456
+ origin += stride * k
457
+ stride = math.lcm(stride, step)
458
+ first = Decimal(origin) / scale
459
+ delta = Decimal(stride) / scale
460
+ first += max(0, math.ceil((lo - first) / delta)) * delta
461
+ if first > hi:
462
+ return None
463
+ last = first + int((hi - first) // delta) * delta
464
+ if first == last:
465
+ return _encode(first, kind)
466
+ return {
467
+ "range": {
468
+ "start": _encode(first, kind),
469
+ "end": _encode(last, kind),
470
+ "every": _encode(delta, step_kind),
471
+ }
472
+ }
473
+
474
+
475
+ def _intersection(a, b, kind):
476
+ if isinstance(a, dict) and "range" in a and isinstance(b, dict) and "range" in b:
477
+ return _range_intersection(a, b, kind)
478
+ if isinstance(a, dict) and "range" in a:
479
+ a, b = b, a
480
+ candidates = a if isinstance(a, list) else [a]
481
+ values = [v for v in candidates if _contains(b, v, kind)]
482
+ return None if not values else values[0] if len(values) == 1 else values
483
+
484
+
485
+ def _intersect(a, b, *, native=False):
486
+ shared_type = a.get("level_type", b.get("level_type")) if not native else None
487
+ if shared_type is not None:
488
+ try:
489
+ a = _normalize({"level_type": shared_type, **a}, allow_unbound=True)
490
+ b = _normalize({"level_type": shared_type, **b}, allow_unbound=True)
491
+ except QueryError:
492
+ return None
493
+ result = dict(a)
494
+ # Layer normalization removes the shared type. A single-level restriction
495
+ # cannot be represented as a layer, so such a conjunction is empty.
496
+ if ("level" in a and "layer" in b) or ("layer" in a and "level" in b):
497
+ return None
498
+ for field, value in b.items():
499
+ if field == "native":
500
+ merged = _intersect(
501
+ a.get("native", {}).get("grib", {}), value["grib"], native=True
502
+ )
503
+ if merged is None:
504
+ return None
505
+ result[field] = {"grib": merged}
506
+ elif field in result:
507
+ selected = _intersection(result[field], value, selector_kind(field))
508
+ if selected is None:
509
+ return None
510
+ result[field] = selected
511
+ else:
512
+ result[field] = value
513
+ if not native and "layer" in result and "level_type" in result:
514
+ try:
515
+ result = _normalize(result, allow_unbound=True)
516
+ except QueryError:
517
+ return None
518
+ return result
519
+
520
+
521
+ def intersect_scopes(left, right):
522
+ """Conjoin configuration bounds without enumerating a product domain.
523
+
524
+ Scopes constrain later selections; they are not executable requests. Time
525
+ tuple legality and max_expansion still apply when effective queries are
526
+ prepared/expanded. A partial vertical bound can gain its type from the other
527
+ scope, using the same intersection semantics as Query selection.
528
+ """
529
+ from .model import Query
530
+
531
+ a = _normalize(Query(left).to_dict(), allow_unbound=True)
532
+ b = _normalize(Query(right).to_dict(), allow_unbound=True)
533
+ result = _intersect(a, b)
534
+ return None if result is None else Query(result)
535
+
536
+
537
+ def intersect_queries(left, right, *, max_expansion=DEFAULT_MAX_EXPANSION):
538
+ """Return a conjunction, or None for two legal disjoint selections."""
539
+ a, b = normalize_query(left).to_dict(), normalize_query(right).to_dict()
540
+ for q in (a, b):
541
+ if all(k in q for k in ("time", "step", "valid_time")):
542
+ for _ in _time_rows(q, None):
543
+ pass
544
+ result = _intersect(a, b)
545
+ if result is None:
546
+ return None
547
+ # Individually legal time conditions may become empty after conjunction.
548
+ try:
549
+ normalized = _normalize(result)
550
+ rows = expand_queries([normalized], max_expansion=max_expansion)
551
+ except QueryError as exc:
552
+ if exc.code == "invalid_query":
553
+ return None
554
+ raise
555
+ return normalize_query(result) if rows else None
556
+
557
+
558
+ def _subset(value, bound, kind):
559
+ if not (isinstance(value, dict) and "range" in value):
560
+ return all(
561
+ _contains(bound, v, kind)
562
+ for v in (value if isinstance(value, list) else [value])
563
+ )
564
+ count = _count(value, kind)
565
+ if isinstance(bound, dict) and "range" in bound:
566
+ a, b = value["range"], bound["range"]
567
+ sk = "duration" if kind == "time" else kind
568
+ first = _numeric(a["start"], kind)
569
+ stride = _numeric(a["every"], sk)
570
+ last = first + (count - 1) * stride
571
+ if first < _numeric(b["start"], kind) or last > _numeric(b["end"], kind):
572
+ return False
573
+ return "every" not in b or (
574
+ _contains(bound, a["start"], kind)
575
+ and (count == 1 or stride % _numeric(b["every"], sk) == 0)
576
+ )
577
+ if count > (len(bound) if isinstance(bound, list) else 1):
578
+ return False
579
+ return all(_contains(bound, v, kind) for v in _values(value, kind))
580
+
581
+
582
+ def _affine_selector(selector, kind, target_kind, factor, offset):
583
+ def number(value):
584
+ return factor * _numeric(value, kind) + offset
585
+
586
+ def legal(value):
587
+ return (
588
+ value >= 0
589
+ if target_kind == "duration"
590
+ else Decimal("-62135596800") <= value <= Decimal("253402300799.999999999")
591
+ if target_kind == "time"
592
+ else True
593
+ )
594
+
595
+ if isinstance(selector, dict) and "range" in selector:
596
+ r = selector["range"]
597
+ start = _numeric(r["start"], kind)
598
+ end = _numeric(r["end"], kind)
599
+ stride = None
600
+ if "every" in r:
601
+ stride = _numeric(r["every"], "duration" if kind == "time" else kind)
602
+ end = start + (_count(selector, kind) - 1) * stride
603
+ lo, hi = sorted((factor * start + offset, factor * end + offset))
604
+ if target_kind == "duration":
605
+ lower, upper = Decimal(0), hi
606
+ elif target_kind == "time":
607
+ lower, upper = Decimal("-62135596800"), Decimal("253402300799.999999999")
608
+ else:
609
+ lower, upper = lo, hi
610
+ clipped = max(lo, lower)
611
+ if stride is not None:
612
+ stride = abs(factor) * stride
613
+ clipped = lo + math.ceil((clipped - lo) / stride) * stride
614
+ hi = min(hi, upper)
615
+ if clipped > hi:
616
+ return None
617
+ result = {
618
+ "start": _encode(clipped, target_kind),
619
+ "end": _encode(hi, target_kind),
620
+ }
621
+ if stride is not None:
622
+ result["every"] = _encode(
623
+ stride, "duration" if target_kind == "time" else target_kind
624
+ )
625
+ return {"range": result}
626
+ values = (
627
+ [number(v) for v in selector]
628
+ if isinstance(selector, list)
629
+ else [number(selector)]
630
+ )
631
+ values = [_encode(v, target_kind) for v in values if legal(v)]
632
+ return None if not values else values[0] if len(values) == 1 else values
633
+
634
+
635
+ def constrain_query(query, constraints):
636
+ """Apply fixed/scope constraints without silently dropping explicit choices."""
637
+ from .model import Query
638
+
639
+ # Product-supplied vertical type may resolve a partial Query.
640
+ raw, fixed = plain(query), plain(constraints)
641
+ if "level_type" not in raw and "level_type" in fixed:
642
+ raw = {"level_type": fixed["level_type"], **raw}
643
+ q, c = _normalize(Query(raw).to_dict()), _normalize(Query(fixed).to_dict())
644
+
645
+ def compatible(value, bound, kind):
646
+ if (
647
+ isinstance(value, dict)
648
+ and "range" in value
649
+ and "every" not in value["range"]
650
+ ):
651
+ return _intersection(value, bound, kind) is not None
652
+ return _subset(value, bound, kind)
653
+
654
+ for key, value in q.items():
655
+ if key not in c:
656
+ continue
657
+ if key == "native":
658
+ for name, selector in value["grib"].items():
659
+ bound = c[key]["grib"].get(name)
660
+ if bound is not None and not compatible(selector, bound, "number"):
661
+ _fail(
662
+ "/native/grib/" + name,
663
+ "explicit native choice conflicts with bound constraints",
664
+ "constraint_conflict",
665
+ reason="fixed_condition_conflict",
666
+ )
667
+ elif not compatible(value, c[key], selector_kind(key)):
668
+ _fail(
669
+ "/" + key,
670
+ "explicit choice conflicts with bound constraints",
671
+ "constraint_conflict",
672
+ reason="fixed_condition_conflict",
673
+ )
674
+ result = _intersect(q, c)
675
+ if result is None:
676
+ _fail(
677
+ "",
678
+ "selection conflicts with bound constraints",
679
+ "constraint_conflict",
680
+ reason="fixed_condition_conflict",
681
+ )
682
+ return Query(result)
683
+
684
+
685
+ def _time_rows(query, limit):
686
+ keys = [k for k in ("time", "step", "valid_time") if k in query]
687
+ finite = [k for k in keys if _count(query[k], selector_kind(k)) is not None]
688
+ if len(finite) < 2:
689
+
690
+ def expand(index, row):
691
+ if index == len(keys):
692
+ yield row
693
+ else:
694
+ key = keys[index]
695
+ for v in _values(query[key], selector_kind(key)):
696
+ yield from expand(index + 1, {**row, key: v})
697
+
698
+ yield from expand(0, {})
699
+ return
700
+ pair = min(
701
+ itertools.combinations(finite, 2),
702
+ key=lambda pair: math.prod(_count(query[k], selector_kind(k)) for k in pair),
703
+ )
704
+ seen = {k: set() for k in finite}
705
+ emitted = 0
706
+ coefficients = {"time": 1, "step": 1, "valid_time": -1}
707
+ outer, inner = pair
708
+ third = next(k for k in coefficients if k not in pair)
709
+ for av in _values(query[outer], selector_kind(outer)):
710
+ inner_domain = query[inner]
711
+ outer_number = _numeric(av, selector_kind(outer))
712
+ if third in query:
713
+ transformed = _affine_selector(
714
+ query[third],
715
+ selector_kind(third),
716
+ selector_kind(inner),
717
+ -coefficients[third] // coefficients[inner],
718
+ -coefficients[outer] * outer_number / coefficients[inner],
719
+ )
720
+ inner_domain = (
721
+ None
722
+ if transformed is None
723
+ else _intersection(inner_domain, transformed, selector_kind(inner))
724
+ )
725
+ elif third == "step":
726
+ # Both timestamps are explicit; negative forecast durations are not
727
+ # legal, and need not be enumerated to prove that fact.
728
+ if inner == "time":
729
+ lower = (
730
+ query[inner]["range"]["start"]
731
+ if isinstance(query[inner], dict)
732
+ else query[inner][0]
733
+ if isinstance(query[inner], list)
734
+ else query[inner]
735
+ )
736
+ if time_seconds(lower) > outer_number:
737
+ inner_domain = None
738
+ else:
739
+ inner_domain = _intersection(
740
+ inner_domain, {"range": {"start": lower, "end": av}}, "time"
741
+ )
742
+ else:
743
+ upper = (
744
+ query[inner]["range"]["end"]
745
+ if isinstance(query[inner], dict)
746
+ else query[inner][-1]
747
+ if isinstance(query[inner], list)
748
+ else query[inner]
749
+ )
750
+ if time_seconds(upper) < outer_number:
751
+ inner_domain = None
752
+ else:
753
+ inner_domain = _intersection(
754
+ inner_domain, {"range": {"start": av, "end": upper}}, "time"
755
+ )
756
+ if inner_domain is None:
757
+ _fail(
758
+ "/" + outer,
759
+ "explicit time choice participates in no legal time combination",
760
+ )
761
+ for bv in _values(inner_domain, selector_kind(inner)):
762
+ row = dict(zip(pair, (av, bv)))
763
+ numbers = {k: _numeric(v, selector_kind(k)) for k, v in row.items()}
764
+ value = (
765
+ -(
766
+ coefficients[outer] * numbers[outer]
767
+ + coefficients[inner] * numbers[inner]
768
+ )
769
+ / coefficients[third]
770
+ )
771
+ if third == "step" and value < 0:
772
+ continue
773
+ row[third] = _encode(value, selector_kind(third))
774
+ if any(not _contains(query[k], row[k], selector_kind(k)) for k in keys):
775
+ continue
776
+ for k in finite:
777
+ seen[k].add(canonical(row[k]))
778
+ emitted += 1
779
+ if limit is not None and emitted > limit:
780
+ _limit(limit)
781
+ yield row
782
+ for key in finite:
783
+ if len(seen[key]) != _count(query[key], selector_kind(key)):
784
+ _fail(
785
+ "/" + key,
786
+ "explicit time choice participates in no legal time combination",
787
+ )
788
+
789
+
790
+ def _limit(limit):
791
+ _fail(
792
+ "/queries",
793
+ "effective discrete expansion exceeds the configured limit",
794
+ "expansion_limit_exceeded",
795
+ limit=limit,
796
+ count_lower_bound=limit + 1,
797
+ )
798
+
799
+
800
+ def _validate_limit(limit):
801
+ if type(limit) is not int or limit <= 0:
802
+ _fail(
803
+ "/execution/max_expansion",
804
+ "max_expansion must be a positive integer",
805
+ "invalid_config",
806
+ )
807
+
808
+
809
+ def _expand_one(query, limit, member_roles, cemc):
810
+ fields = [
811
+ k
812
+ for k in query
813
+ if k not in {"time", "step", "valid_time", "native", "member_role"}
814
+ ]
815
+ # Native predicates remain one paired object until their individual selectors
816
+ # are expanded in the same bounded recursion.
817
+ if "member" not in query and "member_role" in query:
818
+ fields.append("member_role")
819
+ if "native" in query:
820
+ for key in query["native"]["grib"]:
821
+ fields.append("native.grib." + key)
822
+
823
+ def get(field):
824
+ return (
825
+ query["native"]["grib"][field[12:]]
826
+ if field.startswith("native.grib.")
827
+ else query[field]
828
+ )
829
+
830
+ def build(index, row):
831
+ if index == len(fields):
832
+ yield row
833
+ return
834
+ key = fields[index]
835
+ value = get(key)
836
+ for item in _values(value, selector_kind(key)):
837
+ if key.startswith("native.grib."):
838
+ next_row = {
839
+ **row,
840
+ "native": {
841
+ "grib": {
842
+ **row.get("native", {}).get("grib", {}),
843
+ key[12:]: item,
844
+ }
845
+ },
846
+ }
847
+ else:
848
+ next_row = {**row, key: item}
849
+ yield from build(index + 1, next_row)
850
+
851
+ for time_row in _time_rows(query, limit):
852
+ for row in build(0, time_row):
853
+ if "member_role" in query and "member_role" not in row:
854
+ role = None
855
+ if "member" in row and type(row["member"]) is int:
856
+ role = (member_roles or {}).get(str(row["member"]))
857
+ if role is None and cemc:
858
+ role = "control" if row["member"] == 0 else "perturbation"
859
+ if role is not None and not _contains(
860
+ query["member_role"], role, "literal"
861
+ ):
862
+ _fail(
863
+ "/member_role",
864
+ "member number conflicts with the effective role mapping",
865
+ "constraint_conflict",
866
+ reason="fixed_condition_conflict",
867
+ )
868
+ row["member_role"] = role if role is not None else query["member_role"]
869
+ yield row
870
+
871
+
872
+ def expand_queries(
873
+ queries, *, max_expansion=DEFAULT_MAX_EXPANSION, member_roles=None, cemc=False
874
+ ):
875
+ """Expand effective discrete combinations, preserving Query/time/layer pairings."""
876
+ _validate_limit(max_expansion)
877
+ if not isinstance(queries, (list, tuple)):
878
+ _fail("/queries", "queries must be a sequence")
879
+ output = {}
880
+ for qi, query in enumerate(queries):
881
+ normalized = normalize_query(query).to_dict()
882
+ try:
883
+ for row in _expand_one(normalized, max_expansion, member_roles, cemc):
884
+ output.setdefault(canonical(row), row)
885
+ if len(output) > max_expansion:
886
+ _limit(max_expansion)
887
+ except QueryError as exc:
888
+ if exc.code == "expansion_limit_exceeded":
889
+ raise QueryError(
890
+ exc.code,
891
+ exc.path,
892
+ exc.message,
893
+ {
894
+ **dict(exc.context),
895
+ "origins": [{"step_index": 0, "query_index": qi}],
896
+ },
897
+ ) from exc
898
+ raise
899
+ from .model import Query
900
+
901
+ return tuple(Query(output[k]) for k in sorted(output))
902
+
903
+
904
+ def query_identity(query, *, context=None):
905
+ """Identity includes supplied semantic scope/versions, never resolves aliases implicitly."""
906
+ normalized = [q.to_dict() for q in expand_queries([query])]
907
+ return (
908
+ "sha256:"
909
+ + hashlib.sha256(
910
+ canonical(
911
+ {
912
+ "queries": normalized,
913
+ "context": {} if context is None else plain(context),
914
+ }
915
+ ).encode()
916
+ ).hexdigest()
917
+ )
918
+
919
+
920
+ def combine_queries(steps, *, scope=None, max_expansion=DEFAULT_MAX_EXPANSION):
921
+ """Pure AND-of-OR combination, with branch origins, checked after each step.
922
+
923
+ Backend resource-dependent parameter constraints should be applied to every
924
+ input with prepare_queries first, even after an earlier step became empty.
925
+ """
926
+ _validate_limit(max_expansion)
927
+ branches = [({}, [])]
928
+ for si, inputs in enumerate(steps):
929
+ if not isinstance(inputs, (list, tuple)) or not inputs:
930
+ _fail("/queries", "each selection step requires a nonempty Query list")
931
+ normalized = []
932
+ for qi, q in enumerate(inputs):
933
+ q = (
934
+ constrain_query(q, scope).to_dict()
935
+ if scope is not None
936
+ else normalize_query(q).to_dict()
937
+ )
938
+ if all(k in q for k in ("time", "step", "valid_time")):
939
+ for _ in _time_rows(q, max_expansion if si == 0 else None):
940
+ pass
941
+ normalized.append((q, {"step_index": si, "query_index": qi}))
942
+ merged = {}
943
+ for previous, origins in branches:
944
+ for query, origin in normalized:
945
+ conjunction = intersect_queries(
946
+ previous, query, max_expansion=max_expansion
947
+ )
948
+ if conjunction is None:
949
+ continue
950
+ data = conjunction.to_dict()
951
+ key = canonical(data)
952
+ entry = merged.setdefault(key, [data, []])
953
+ for item in origins + [origin]:
954
+ if item not in entry[1]:
955
+ entry[1].append(item)
956
+ branches = [merged[k] for k in sorted(merged)]
957
+ expand_queries([q for q, _ in branches], max_expansion=max_expansion)
958
+ return tuple(
959
+ {
960
+ "index": i,
961
+ "query": q,
962
+ "origins": sorted(
963
+ origins, key=lambda o: (o["step_index"], o["query_index"])
964
+ ),
965
+ }
966
+ for i, (q, origins) in enumerate(branches)
967
+ )