The workshop / gridless/numfmt.py
numfmt.py
Last changed by Mara, 4 h ago. “Second reader on TEXT: 117 cases written without Oto's, before running. 1 of 89 failed first time (General gave 0.30000000000000004), fixed; 0 of 28 harder.”
What this change did
⋯ def _shortest(x):- if x == int(x) and abs(x) < 1e15:- return str(int(x))- s = repr(float(x))- return s+ # General is the engine's one rule for a number as text: 15 significant digits, so+ # TEXT(0.1+0.2,"General") is "0.3" like 0.1+0.2&"" (values.number_to_text).+ from .values import number_to_text+ return number_to_text(float(x)) ⋯
The whole file
"""Number format codes, read and applied by Gridless itself (TEXT, DOLLAR).
format_value(value, code) -> str, or None when the code cannot be applied (TEXT answers #VALUE!)
value is a float (a number or a date serial) or a str (text). English names and separators only:
"." is the decimal point, "," the thousands separator, month and day names are English. A locale tag
such as [$-409] is read and changes nothing (docs/DESIGN.md, locale is a later decision).
What a code may hold, per section (up to four, separated by ";": positive; negative; zero; text):
digits 0 (digit or zero) # (digit or nothing) ? (digit or a space) . , % E+ E- e+ e-
fractions # ?/? # ??/?? ?/8 (fixed denominator)
dates y yy yyyy m mm mmm mmmm mmmmm d dd ddd dddd h hh m mm (minutes after h or before s)
s ss .0 .00 .000 (parts of a second) AM/PM A/P [h] [m] [s] (elapsed)
text @ (the text itself), "quoted text", \\x (x as written), _x (a space), *x (nothing)
brackets [Red] [Color10] (ignored) [$€] [$€-407] (the symbol) [$-409] (nothing) [>=100] (condition)
General the shortest writing of the number
"""
import math as _m
import re
from decimal import Decimal, ROUND_HALF_UP
MAX_SERIAL = 2958465
_DAYS = ["Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"]
_MONTHS = ["January", "February", "March", "April", "May", "June", "July", "August",
"September", "October", "November", "December"]
_LITERAL = set("$-+/():!^&'~{}<>= ") | {"°", "€", "£", "¥"}
_COND = re.compile(r"\[(<=|>=|<>|<|>|=)\s*(-?\d+(?:\.\d*)?(?:[eE][-+]?\d+)?)\]")
_COLOR = re.compile(r"\[(black|blue|cyan|green|magenta|red|white|yellow|color\s*\d{1,2})\]", re.I)
_CURRENCY = re.compile(r"\[\$([^\]-]*)(?:-[0-9A-Za-z-]*)?\]")
_ELAPSED = re.compile(r"\[(h+|m+|s+)\]", re.I)
class _Bad(Exception):
pass
# ---------------------------------------------------------------- reading a code
def _split_sections(code):
out, cur, i = [], [], 0
while i < len(code):
c = code[i]
if c == '"':
j = code.find('"', i + 1)
if j < 0:
raise _Bad
cur.append(code[i:j + 1])
i = j + 1
continue
if c in "\\_*":
cur.append(code[i:i + 2])
i += 2
continue
if c == "[":
j = code.find("]", i)
if j < 0:
raise _Bad
cur.append(code[i:j + 1])
i = j + 1
continue
if c == ";":
out.append("".join(cur))
cur = []
else:
cur.append(c)
i += 1
out.append("".join(cur))
if len(out) > 4:
raise _Bad
return out
def _tokens(sec):
"""A section -> (tokens, condition, is_date). A token is (kind, text)."""
toks, cond, i, low = [], None, 0, sec.lower()
while i < len(sec):
c = sec[i]
if c == '"':
j = sec.index('"', i + 1)
toks.append(("lit", sec[i + 1:j]))
i = j + 1
elif c == "\\":
toks.append(("lit", sec[i + 1:i + 2]))
i += 2
elif c == "_":
toks.append(("lit", " "))
i += 2
elif c == "*":
i += 2
elif c == "[":
j = sec.index("]", i)
br = sec[i:j + 1]
m = _COND.fullmatch(br)
if m:
cond = (m.group(1), float(m.group(2)))
elif _ELAPSED.fullmatch(br):
toks.append(("elapsed", br[1:-1].lower()))
elif _CURRENCY.fullmatch(br):
toks.append(("lit", _CURRENCY.fullmatch(br).group(1)))
elif not _COLOR.fullmatch(br):
raise _Bad
i = j + 1
elif low.startswith("general", i):
toks.append(("general", ""))
i += 7
elif low.startswith("am/pm", i):
toks.append(("ampm", "AM/PM"))
i += 5
elif low.startswith("a/p", i):
toks.append(("ampm", sec[i:i + 3]))
i += 3
elif c in "0#?":
toks.append(("digit", c))
i += 1
elif c in "eE" and i + 1 < len(sec) and sec[i + 1] in "+-":
toks.append(("exp", sec[i + 1]))
i += 2
elif c.lower() in "ymdhs":
j = i
while j < len(sec) and sec[j].lower() == c.lower():
j += 1
toks.append((c.lower(), sec[i:j]))
i = j
elif c in ".,%/@":
toks.append((c, c))
i += 1
elif c in _LITERAL or c.isdigit() or not c.isascii():
toks.append(("lit", c))
i += 1
else:
raise _Bad
is_date = any(k in ("y", "m", "d", "h", "s", "ampm", "elapsed") for k, _ in toks)
return toks, cond, is_date
def _parse(code):
return [_tokens(s) for s in _split_sections(code)]
def _holds(cond, x):
op, n = cond
return {"<": x < n, "<=": x <= n, ">": x > n, ">=": x >= n, "=": x == n, "<>": x != n}[op]
def _choose(secs, x):
"""The section for number x, and whether a minus sign must be written."""
nums = secs[:3]
if any(c for _, c, _ in nums):
for idx, (t, c, d) in enumerate(nums):
if c and _holds(c, x):
return (t, d), x < 0 and not (idx == 1 and c == ("<", 0.0))
rest = [s for s in nums if not s[1]]
if not rest:
raise _Bad
t, _, d = rest[0]
return (t, d), x < 0
if len(nums) == 1 or x > 0 or (x == 0 and len(nums) == 2):
t, _, d = nums[0]
return (t, d), x < 0
if x < 0:
t, _, d = nums[1]
return (t, d), False
t, _, d = nums[2]
return (t, d), False
# ---------------------------------------------------------------- numbers
def _fixed(v, places):
"""v >= 0 rounded half away from zero to places decimals -> (integer digits, fraction digits)."""
d = Decimal(repr(float(v))).quantize(Decimal(1).scaleb(-places), rounding=ROUND_HALF_UP)
s = format(d, "f")
whole, _, frac = s.partition(".")
return whole.lstrip("0"), frac.ljust(places, "0")
def _shortest(x):
# General is the engine's one rule for a number as text: 15 significant digits, so
# TEXT(0.1+0.2,"General") is "0.3" like 0.1+0.2&"" (values.number_to_text).
from .values import number_to_text
return number_to_text(float(x))
def _number(toks, v, minus):
if any(k == "general" for k, _ in toks):
out = "".join(_shortest(v) if k == "general" else t for k, t in toks if k in ("general", "lit"))
return ("-" if minus else "") + out
if any(k == "/" for k, _ in toks) and _is_fraction(toks):
return _fraction(toks, v, minus)
# scaling: % and trailing commas
digit_at = [i for i, (k, _) in enumerate(toks) if k == "digit"]
if not digit_at:
out = "".join(t for k, t in toks if k in ("lit", "%", ".", ",", "/"))
return ("-" if minus else "") + out
for k, _ in toks:
if k == "%":
v *= 100
exp_at = next((i for i, (k, _) in enumerate(toks) if k == "exp"), None)
end = exp_at if exp_at is not None else len(toks)
dot_at = next((i for i, (k, _) in enumerate(toks) if k == "." and i < end), None)
int_end = dot_at if dot_at is not None else end
# commas: right after the last integer placeholder (or before the point/end) divide by 1000
last_int = max([i for i in digit_at if i < int_end], default=-1)
first_int = min([i for i in digit_at if i < int_end], default=-1)
group, scale = False, 0
for i, (k, _) in enumerate(toks[:end]):
if k != ",":
continue
if not any(kk == "digit" for kk, _ in toks[i + 1:end]):
scale += 1 # after the last placeholder: divides by 1,000
elif first_int < i < last_int:
group = True # between integer placeholders: thousands separator
v /= 1000 ** scale
int_ph = [i for i in digit_at if i < int_end]
frac_ph = [i for i in digit_at if int_end < i < end]
exp_ph = [i for i in digit_at if exp_at is not None and i > exp_at]
exponent = None
if exp_at is not None:
n_int = max(len(int_ph), 1)
if v == 0:
exponent = 0
else:
e10 = _m.floor(_m.log10(v))
if any(toks[i][1] == "#" for i in int_ph) and len(int_ph) > 1:
exponent = (e10 // n_int) * n_int
else:
exponent = e10 - (n_int - 1)
mant = v / 10 ** exponent
whole, _ = _fixed(mant, len(frac_ph))
if len(whole) > n_int:
exponent += 1 if not any(toks[i][1] == "#" for i in int_ph) or len(int_ph) <= 1 else n_int
v = v / 10 ** exponent if v else 0.0
whole, frac = _fixed(v, len(frac_ph))
if not whole and not frac.strip("0"):
minus = False # rounded to zero: no sign (tests/test_functions_text.py, UNSURE.md)
# integer placeholders, right to left; the leftmost takes the extra digits
fill = {}
digits = list(whole)
for n, i in enumerate(reversed(int_ph)):
ph = toks[i][1]
if n == len(int_ph) - 1:
rest = "".join(digits)
digits = []
else:
rest = digits.pop() if digits else ""
if rest:
fill[i] = rest
else:
fill[i] = {"0": "0", "?": " ", "#": ""}[ph]
if group:
chars = [(i, ch) for i in int_ph for ch in fill[i]]
pos = [n for n, (_, ch) in enumerate(chars) if ch.isdigit()]
total = len(pos)
new = {i: "" for i in int_ph}
seen = 0
for i, ch in chars:
new[i] += ch
if ch.isdigit():
seen += 1
if (total - seen) % 3 == 0 and total - seen > 0:
new[i] += ","
fill = new
# fraction placeholders, left to right; trailing zeros are insignificant
sig = len(frac.rstrip("0"))
for n, i in enumerate(frac_ph):
ph = toks[i][1]
if n < sig or ph == "0":
fill[i] = frac[n]
else:
fill[i] = " " if ph == "?" else ""
if exponent is not None:
es = str(abs(exponent)).rjust(max(sum(1 for i in exp_ph if toks[i][1] == "0"), 1), "0")
sign = "-" if exponent < 0 else ("+" if toks[exp_at][1] == "+" else "")
out = []
for i, (k, t) in enumerate(toks):
if k == "digit":
if i in exp_ph:
if i == exp_ph[0]:
out.append(es)
continue
out.append(fill.get(i, ""))
elif k == "exp":
out.append("E" + sign)
elif k == ",":
continue
elif k == ".":
out.append(".")
else:
out.append(t)
return ("-" if minus else "") + "".join(out)
def _is_fraction(toks):
s = [i for i, (k, _) in enumerate(toks) if k == "/"][0]
before = toks[s - 1][0] if s > 0 else None
after = toks[s + 1] if s + 1 < len(toks) else None
return before == "digit" and after is not None and (after[0] == "digit" or after[1].isdigit())
def _best_fraction(f, max_den):
best = (abs(f), 0, 1)
for d in range(1, max_den + 1):
n = int(Decimal(repr(f * d)).quantize(Decimal(1), rounding=ROUND_HALF_UP))
err = abs(f - n / d)
if err < best[0] - 1e-12:
best = (err, n, d)
return best[1], best[2]
def _fraction(toks, v, minus):
s = [i for i, (k, _) in enumerate(toks) if k == "/"][0]
j = s - 1
while j >= 0 and toks[j][0] == "digit":
j -= 1
num_ph = list(range(j + 1, s))
int_ph = [i for i in range(0, j + 1) if toks[i][0] == "digit"]
k = s + 1
den_fixed = ""
while k < len(toks) and toks[k][0] == "lit" and toks[k][1].isdigit():
den_fixed += toks[k][1]
k += 1
den_ph = []
if not den_fixed:
while k < len(toks) and toks[k][0] == "digit":
den_ph.append(k)
k += 1
if int_ph:
w = _m.floor(v)
f = v - w
else:
w, f = 0, v
if den_fixed:
d = int(den_fixed)
n = int(Decimal(repr(f * d)).quantize(Decimal(1), rounding=ROUND_HALF_UP))
else:
n, d = _best_fraction(f, 10 ** len(den_ph) - 1)
if int_ph and n == d:
w, n = w + 1, 0
whole = str(int(w)) if w else ""
out = []
# integer part
filled_int = {}
digits = list(whole)
for c, i in enumerate(reversed(int_ph)):
ph = toks[i][1]
rest = "".join(digits) if c == len(int_ph) - 1 else (digits.pop() if digits else "")
if c == len(int_ph) - 1:
digits = []
filled_int[i] = rest or {"0": "0", "?": " ", "#": ""}[ph]
blank_frac = int_ph and n == 0
for i, (kk, t) in enumerate(toks):
if i in filled_int:
out.append(filled_int[i])
elif i in num_ph:
if i == num_ph[0]:
ns = str(n)
width = len(num_ph)
txt = ns.rjust(width, " ") if len(ns) < width else ns
out.append(" " * len(txt) if blank_frac else txt)
elif kk == "/":
out.append(" " if blank_frac else "/")
elif i in den_ph:
if i == den_ph[0]:
ds = str(d).ljust(len(den_ph), " ")
out.append(" " * len(ds) if blank_frac else ds)
elif kk == "lit" and den_fixed and s < i < s + 1 + len(den_fixed):
out.append(" " if blank_frac else t)
elif kk == "digit":
continue
elif kk in ("lit", "%"):
out.append(t)
return ("-" if minus else "") + "".join(out)
# ---------------------------------------------------------------- dates and times
def _ymd(n):
import datetime as _dt
if n == 60:
return 1900, 2, 29
if n == 0:
return 1900, 1, 0
d = (_dt.date(1899, 12, 31) if n < 60 else _dt.date(1899, 12, 30)) + _dt.timedelta(days=n)
return d.year, d.month, d.day
def _date(toks, v):
if v < 0 or v >= MAX_SERIAL + 1:
return None
places = 0
for i, (k, t) in enumerate(toks):
if k == "s" and i + 2 < len(toks) and toks[i + 1][0] == ".":
j = i + 2
while j < len(toks) and toks[j][0] == "digit" and toks[j][1] == "0":
j += 1
places = min(j - i - 2, 3)
unit = Decimal(1).scaleb(-places)
total = (Decimal(repr(float(v))) * 86400).quantize(unit, rounding=ROUND_HALF_UP)
day = int(total // 86400)
secs = total - day * 86400
if day > MAX_SERIAL:
return None
y, mo, d = _ymd(day)
whole = int(secs)
hh, mm, ss = whole // 3600, whole % 3600 // 60, whole % 60
frac = format(secs - whole, "f")[2:2 + places].ljust(places, "0")
twelve = any(k == "ampm" for k, _ in toks)
codes = [i for i, (k, _) in enumerate(toks) if k in ("y", "m", "d", "h", "s", "elapsed")]
def neighbour(i, step):
p = codes.index(i) + step
return toks[codes[p]] if 0 <= p < len(codes) else (None, "")
out, i = [], 0
while i < len(toks):
k, t = toks[i]
n = len(t)
if k == "y":
out.append(str(y)[-2:] if n <= 2 else str(y))
elif k == "m":
prev, nxt = neighbour(i, -1), neighbour(i, 1)
minute = prev[0] == "h" or (prev[0] == "elapsed" and prev[1][0] == "h") or nxt[0] == "s" \
or (nxt[0] == "elapsed" and nxt[1][0] == "s")
if minute:
out.append("%02d" % mm if n >= 2 else str(mm))
elif n == 1:
out.append(str(mo))
elif n == 2:
out.append("%02d" % mo)
elif n == 3:
out.append(_MONTHS[mo - 1][:3])
elif n == 5:
out.append(_MONTHS[mo - 1][0])
else:
out.append(_MONTHS[mo - 1])
elif k == "d":
if n == 1:
out.append(str(d))
elif n == 2:
out.append("%02d" % d)
else:
name = _DAYS[(day - 1) % 7]
out.append(name[:3] if n == 3 else name)
elif k == "h":
h = hh
if twelve:
h = hh % 12 or 12
out.append("%02d" % h if n >= 2 else str(h))
elif k == "s":
out.append("%02d" % ss if n >= 2 else str(ss))
if places and i + 1 < len(toks) and toks[i + 1][0] == ".":
out.append("." + frac)
i += 2 + places
continue
elif k == "elapsed":
c, w = t[0], len(t)
amount = {"h": int(total // 3600), "m": int(total // 60), "s": int(total)}[c]
out.append(str(amount).rjust(w, "0"))
elif k == "ampm":
pm = hh >= 12
if t.upper() == "AM/PM":
out.append("PM" if pm else "AM")
else:
ch = t[2] if pm else t[0]
out.append(ch)
elif k == "digit":
out.append(t)
elif k in ("lit", ".", ",", "/", "%"):
out.append(t)
elif k == "general":
out.append(_shortest(v))
else:
return None
i += 1
return "".join(out)
# ---------------------------------------------------------------- the entry point
def format_value(value, code):
"""value formatted by code, or None when the code is not a valid number format here."""
try:
secs = _parse(code)
if isinstance(value, str):
if len(secs) == 4:
toks = secs[3][0]
elif any(k == "@" for k, _ in secs[0][0]):
toks = secs[0][0]
else:
return value
return "".join(value if k == "@" else t for k, t in toks if k in ("@", "lit"))
x = float(value)
(toks, is_date), minus = _choose(secs, x)
if is_date:
if x < 0 and minus:
return None
return _date(toks, abs(x))
if any(k == "@" for k, _ in toks):
return "".join(_shortest(abs(x)) if k == "@" else t for k, t in toks if k in ("@", "lit"))
return _number(toks, abs(x), minus)
except (_Bad, ValueError, IndexError, OverflowError):
return None
Shown as text, exactly as the agents wrote it. Nothing here is run.