forked from longtao.wu/droboticflow
79 lines
2.5 KiB
Python
79 lines
2.5 KiB
Python
from __future__ import annotations
|
|
|
|
import math
|
|
import re
|
|
from collections.abc import Iterable
|
|
|
|
MAX_SAFE_INTEGER = 9_007_199_254_740_991
|
|
EXACT_POSITIVE_INT_RE = re.compile(r"^[1-9][0-9]*$")
|
|
INTEGERISH_RE = re.compile(r"^[+-]?[0-9]+$")
|
|
|
|
|
|
def _parse_finite_float(label: str, value: str) -> tuple[float | None, str | None]:
|
|
if not value:
|
|
return None, f"{label} is required"
|
|
try:
|
|
parsed_value = float(value)
|
|
except ValueError:
|
|
return None, f"{label} must be numeric"
|
|
if not math.isfinite(parsed_value):
|
|
return None, f"{label} must be finite"
|
|
return parsed_value, None
|
|
|
|
|
|
def unit_interval_threshold_issues(thresholds: Iterable[tuple[str, str]]) -> list[str]:
|
|
issues: list[str] = []
|
|
for label, value in thresholds:
|
|
parsed_value, issue = _parse_finite_float(label, value)
|
|
if issue:
|
|
issues.append(issue)
|
|
continue
|
|
if parsed_value is None:
|
|
continue
|
|
if parsed_value < 0 or parsed_value > 1:
|
|
issues.append(f"{label} must be in the range [0, 1]")
|
|
return issues
|
|
|
|
|
|
def positive_float_issues(values: Iterable[tuple[str, str]]) -> list[str]:
|
|
issues: list[str] = []
|
|
for label, value in values:
|
|
parsed_value, issue = _parse_finite_float(label, value)
|
|
if issue:
|
|
issues.append(issue)
|
|
continue
|
|
if parsed_value is None:
|
|
continue
|
|
if parsed_value <= 0:
|
|
issues.append(f"{label} must be greater than 0")
|
|
return issues
|
|
|
|
|
|
def parse_positive_int(label: str, value: object) -> tuple[int | None, str | None]:
|
|
raw = "" if value is None else str(value).strip()
|
|
if not raw:
|
|
return None, f"{label} is required"
|
|
if not EXACT_POSITIVE_INT_RE.fullmatch(raw):
|
|
if INTEGERISH_RE.fullmatch(raw):
|
|
try:
|
|
parsed_value = int(raw)
|
|
except ValueError:
|
|
parsed_value = 0
|
|
if parsed_value <= 0:
|
|
return None, f"{label} must be greater than 0"
|
|
return None, f"{label} must be an exact positive integer"
|
|
return None, f"{label} must be an integer"
|
|
parsed_value = int(raw)
|
|
if parsed_value > MAX_SAFE_INTEGER:
|
|
return None, f"{label} must be a safe integer"
|
|
return parsed_value, None
|
|
|
|
|
|
def positive_int_issues(values: Iterable[tuple[str, object]]) -> list[str]:
|
|
issues: list[str] = []
|
|
for label, value in values:
|
|
_, issue = parse_positive_int(label, value)
|
|
if issue:
|
|
issues.append(issue)
|
|
return issues
|