1 """   2 lib: general stuff; nothing here knows about tables or AI.   3 (c) 2026, Tim Menzies <timm@ieee.org>, MIT license   4 """   5 import os, re, sys, random   6 from glob import glob   7 from types import SimpleNamespace as o   8 from collections.abc import Iterator   9   10 isa  = isinstance  11 TINY = 1e-32  12 MOOT = os.environ.get("MOOT") or os.path.expanduser("~/gits/moot")  13   14 def thing(s: str) -> int|float|bool|str:  15   "Coerce a string to int/float/bool, else leave as str"  16   for f in (int, float):  17     try: return f(s)  18     except ValueError: pass  19   return s=="True" or (s!="False" and s)  20   21 def settings(doc: str) -> o:  22   "Parse '--key ... = val' lines of doc into an o()"  23   pat = r"--(\w+)\s+[^=\n]*=\s*(\S+)"  24   return o(**{k: thing(v) for k,v in re.findall(pat, doc)})  25   26 def cli(the: o) -> None:  27   "Update `the` from the command line's --key=val flags"  28   for arg in sys.argv[1:]:  29     if arg[:2]=="--" and "=" in arg:  30       k,v = arg[2:].split("=",1)  31       if hasattr(the, k): setattr(the, k, thing(v))  32   33 def conf(the: o, prog="", **extra) -> str:  34   "Copy-pastable one-liner of the current settings: prog :key val :key val"  35   d = {**vars(the), **extra}  36   return prog + "".join(" :%s %s" % kv for kv in d.items())  37   38 def name(file: str) -> str:  39   "a/b/auto93.csv -> auto93"  40   return file.split("/")[-1].removesuffix(".csv")  41   42 def path(file: str) -> str:  43   "Expand a leading $MOOT (the moot repo) and ~"  44   return os.path.expanduser(file.replace("$MOOT", MOOT, 1))  45   46 def csvs(dir: str, rows=range(10**9), n=20, seed=1) -> list:  47   "n random (seeded) csvs under dir whose row count is in rows"  48   fs = sorted(f for f in glob(f"{path(dir)}/**/*.csv", recursive=True)  49               if sum(1 for _ in open(f)) - 1 in rows)  50   return random.Random(seed).sample(fs, min(n, len(fs)))  51   52 def csv(file: str) -> Iterator[list]:  53   "Yield typed rows; a leading $MOOT expands to the moot repo"  54   file = path(file)  55   with open(file, encoding="utf-8") as f:  56     for line in f:  57       row = [x.strip() for x in line.split(",")]  58       if any(row): yield [thing(x) for x in row]  59   60 def table(names: list, labels: list, cols: list) -> None:  61   "Print one column per name, one row per label; widths fit"  62   rows = [[""] + names] + [[label] + [round(col[j]) for col in cols]  63                            for j, label in enumerate(labels)]  64   wide = [max(len(str(x)) for x in col) for col in zip(*rows)]  65   for row in rows:  66     print("%-*s" % (wide[0], row[0]) + "".join(  67           "  %*s" % wx for wx in zip(wide[1:], row[1:])))  68