delays.py
Cited on: LATENCY.
To run it: save delays.py, with chains.py, manystream.py, piecewise.py, poles.py, redundant.py beside it; standard library only.
"""
delays.py -- the delay of an on-line unit, read by one entry point:
pass a unit's box, as its width rate (the sup of its gradient's L1
norm over the box) and its range, or its pieces, or a chain, at a
signed digit system, and read for a box its lead, its delay L* and
its lookahead, for pieces their lead, L* and floor, and for a chain
its naive and least totals.
USE. In Python, from the folder holding delays.py, the four scripts
it imports (chains, manystream, piecewise, poles) and redundant.py,
which two of them import. At radix 4 with digits -2..2 every stream fills
[-2/3, 2/3]; the product x y has box width rate 2 * 2/3 and range
[-4/9, 4/9]:
>>> from fractions import Fraction as F
>>> from delays import unit, table
>>> M = F(2, 3)
>>> unit(4, 2, 2, 2 * M, -M * M, M * M) # (lead, L*, lookahead)
(0, 2, 2)
>>> table(4, 2, 2, 32)["1/(s+x)"][:3] # far from its pole it runs ahead
(-2, -4, -2)
WHAT IT IS FOR. An on-line unit reads its operands most significant
digit first through a signed digit set and emits its result the same
way. Its LOOKAHEAD is how many input digits it must see past each
output digit. The engines beside this file decide it exactly, each for
its own claim: manystream.py for a smooth map of any number of streams,
poles.py for the units with a pole, piecewise.py for a map built from
pieces, chains.py for units wired in series. Each is written to check
its claim over a census, not to be handed a stranger's unit. This file
is that hand: it adds no claim, and every number it returns is one of
those engines' functions called at the arguments given, save what is
composed here: the relative-gradient estimate (the law's formula) and
the adder chain's row, put together from chains.py's functions as its
laws (4) and (11) state them.
THE READER. Radix b >= 2, digits D = {-a-, ..., a+}, a+- >= 1, SLACK
rho = a- + a+ + 1 - b >= 1; a stream's values fill [-M-, M+],
M+- = a+-/(b - 1), |I| = a- + a+ the width of the digit interval
I = [-a-, a+]. The output's first digit sits o places above the
input's: the LEAD o is the least integer whose root tile
[-M- b^o, M+ b^o] holds the unit's range. With Lam the BOX WIDTH
RATE, the sup over the root box of the gradient's L1 norm, the unit is
read at the least L = c + o with b^L rho >= Lam |I| (manystream.py),
its DELAY L*, and its LOOKAHEAD is c* = L* - o, negative where it
emits before it reads. A map that is affine on the root box can read
below L* (redundant.py decides it); every other C^2 map reads at L*
exactly (the theorem manystream.py checks; this file only calls it).
unit(), certify(), piecewise() and the table's polynomial rows find L*
and the lead by a walk down that stops at -40 (manystream.Cell.least):
a rate or a range too small to end it sooner reads -40, a constant's
rate 0 and the range {0} among them. The pole rows have no such stop.
THE CALLS. Every argument that is a number is an exact rational: an
int or a fractions.Fraction. A row of table() is a named tuple Row
(lead, L, c, estimate, dead_below, dead_at), certify() returns a Cert
(lead, L, dead_below, dead_at) and piecewise() a Pieces (lead, L,
floor); unit() returns a plain tuple and chains() a dict.
unit(b, am, ap, lam, lo, hi) -> (o, L*, c*): a unit of your own,
its box width rate and its range's ends.
table(b, am, ap, h, certify=False) -> {name: row}: six units, the
product x y, the multiply-add x y + z, x^2 + y, the reciprocal
1/(s + x), the root sqrt(s + x) and the divider x/(s + y), the
pole units at POLE DISTANCE h > 0, the least value their
denominator or radicand takes (s = M- + h). A row's first four
fields are (o, L*, c*, estimate), the estimate
log_b(Gamma |I| / rho) with Gamma = Lam/K the RELATIVE GRADIENT,
K = max(hi/M+, -lo/M-) the range's scale: c* lies within one
digit of it (poles.py). Its last two fields are None unless
certify is true, and then are the output depth at which a reader
at L* - 1 dies, and the same at L*, None where the scan finds no
death or runs out of its budget; for a map not affine on the root
box the first should be a number and the second None. h <= 0 is
refused.
certify(b, am, ap, d, image, partials, lam, lo, hi) -> (o, L*, dead
below, dead at): the same certificate for a map of d streams
you describe: image(B), the exact ends (lo, hi) of the map over
a box B, a list of d intervals of Fractions; partials(B), one
interval per stream bounding that partial over B, never below
the true one.
piecewise(b, am, ap, kinks, polys) -> (o, L*, floor): a continuous
map of one stream cut at rational kinks into pieces, each a
polynomial of degree at most 3, coefficients low to high, monotone
on its piece; the floor is the least L its three clauses leave
empty (piecewise.py), at most L*, or None when the map is
still read four digits below L*, as a constant is.
chains(b, am, ap) -> {name: (naive, least) or None}: a multiplier
x y feeding a second unit, the adder (x y) + z and the product
(x y) z, and an adder feeding a product, z (x + y). Naive is the
sum of the two units' floors, least the least total that the inset
law and the threshold-miss law admit (chains.py), an upper bound
on the chain's floor. Where x y's range fits the root tile at
lead 0 the adder's least is its naive sum, the floor at every
radix (chains.py (4)), and the inset law admits nothing below
it: at such a cell the adder's floor is 2 at slack 1 alone, and
there the one pair below the sum with the producer at or above
its floor, the adder at 1, costs an escape of w - 1 or more,
above every budget. Where it does not fit the chain is led and
the product's row is None; the adder's row is the led law
(chains.py (11)) where a+- <= 2b - 1, least one below naive where
the adder's floor is 2 and a narrowed producer pays an escape
option (chains.gain_option), and None past it; z (x + y) is
None, at any cell, where the range of z times
(x + y)/b, the adder read at lead 1, does not fit. The led
adder's least is the floor at every led cell the law defines
(chains.py (11), a theorem
but at radix 3, CP's census there), the producer read at
its floor law_L(2 Mh), running ahead where U's lead sits above
it; on the
product rows the threshold-miss gain is proved and the floor may
lie below least.
Comparators cost nothing: max, min, the clamp and the rectifier are
read at lookahead 0 at every digit set (comparators.py), and so are
left out of the table.
WHAT RUNNING IT PRINTS. The file run by itself prints the table and
the chain rows at one digit system and reads the five calls against a
record, eleven checks.
THE CONTROLS. By hand, from the definitions above: the estimates of
the three tables, the integers at (5, 4, 3) and (5, 3, 4), unit()'s
rows, the led law's two edge cells and the adder at (5, 3, 4). From
this file's own earlier prints, so reading only that nothing moved:
every depth of a death, the product rows at (5, 2, 3) and (5, 3, 4),
the constants' rows. The rest are rows the engines produced before
this file existed. TABLE holds the six units at three digit systems,
each row's (lead, L*, lookahead), the square of b^estimate and the
output depth of its death at L* - 1, none dying at L*: radix 4 over
{-2..2} with h = 1/3, where x y reads (0, 2, 2) and the divider
(1, 3, 2); and radix 5 over {-4..3} and over {-3..4} with h = 1/2,
slack 3 with M- above M+ and below it, since at slack 1 an estimate
cannot tell a division by the slack from a product, at a- = a+ a
range's two ends weigh alike, and Mh is M- unless M+ is the larger.
At (4, 2, 2), h = 32, the reciprocal (-2, -4, -2). unit() on x y's
rate and range equals its table row at (4, 2, 2) and at (5, 4, 3),
and at rate 1/8 reads (-1, 0, 1), a lead off 0,
on [-1/8, 1/100] and on [-1/100, 1/8], each end of a range setting the
lead once. At (2, 1, 1) the divider at h = 2 reads (-1, 1, 2) in the
table, and described by hand to certify() the same lead and L*, dead
at depth 3 at L* - 1 and not at L* in both; with its rate understated,
3/8 for 3/4, certify() reads L = 0 and a death there, at depth 3, the
one control where a reader dies at the L it is given (a table's row
never does, so the second scan of five rows is read through
certify()'s, one ms.scan; the root's, poles.one_scan, is read dying
only at L* - 1). The
two-piece map x/2 on
x <= 0, x on x >= 0 at (5, 2, 3): lead 0, L* = 1, floor 1; the map
x/5 + x^2/20 on x <= 0, x on x >= 0 at (3, 1, 2): lead 0, L* = 1,
floor 0. A constant, 1/3 at (5, 2, 3): unit() at rate 0 reads
(0, -40, -40) and piecewise() floor None; the constant 0 reads
(-40, -40, 0). The chain rows (x y) + z,
(x y) z and z (x + y): at (4, 2, 2) (4, 4), (4, 3), (3, 3); at
(5, 2, 3) (4, 4), (4, 4), (4, 3); at (5, 3, 4), slack 3, where the
adder's floor is 1, (2, 2) three times; at (3, 2, 1), led, (4, 4) and
two rows absent. The led adder rows, from chains.py (11) and CP's
prints: (4, 1, 4) (4, 3), (2, 2, 2) (5, 4), (3, 1, 3) (4, 4), the
slack-1 (3, 2, 1) at its naive sum 4; by hand at the law's edge
a- = 2b - 1, (2, 3, 1) (5, 5) and (3, 5, 1) (3, 3), the second an
adder of floor 1 with a free escape and no gain; (2, 4, 1) and
(2, 1, 4) absent (a- = 2b, a+ = 2b). Ten refusals, each read by its
message: each of the five calls at (4, 1, 2), slack 0; unit() at radix
1, at a- = 0 and at a+ = 0; table() at h = 0 and at h = -1/3.
RUN RECORD. 11/11 checks, 0.1 s of work, 0.1 s of wall and a peak of
10.2 MB. Every certified row dies at L* - 1 and none at L*: at
(4, 2, 2), h = 1/3, at output depths 2, 1, 1, 3, 2 and 1, at
(5, 4, 3), h = 1/2, at 1, 2, 2, 2, 3 and 2, at (5, 3, 4), h = 1/2,
at 1, 2, 2, 2, 2 and 2, and the divider at (2, 1, 1), h = 2, at depth
3 by either description; its rate understated, it dies at depths 2
and 3, below the L it is given and at it. The estimate
column at (4, 2, 2) reads 1.50 for x y and 1.79 for the divider. Two
one-off sweeps, neither in the suite: the table against the tables an
earlier program printed, over every cell of radices 2 to 6 at
h = j/(b - 1), j in {1, 2, 4, 8, 32, 128}, 1,365 rows compared, none
off; and the led adder's least, below naive at 75 of the 68,756 led
cells of radices 2 to 40, the gain set chains.py CP prints (17.5 s;
the same predicate as CP's, so a read of the wiring only).
"""
import math
import time
from collections import namedtuple
from fractions import Fraction as Fr
import chains as ch
import manystream as ms
import piecewise as pwm
import poles
CHECKS = []
Row = namedtuple("Row", "lead L c estimate dead_below dead_at",
defaults=(None, None))
Cert = namedtuple("Cert", "lead L dead_below dead_at")
Pieces = namedtuple("Pieces", "lead L floor")
UNITS = ["x y", "x y + z", "x^2 + y", "1/(s+x)", "sqrt(s+x)", "x/(s+y)"]
# The record. TABLE is keyed on (b, a-, a+, h): a unit's (lead, L*,
# lookahead), the square of b^estimate (a rational at every unit; the
# root's relative gradient is a square root) and the output depth of its
# death at L* - 1.
TABLE = {
(4, 2, 2, Fr(1, 3)): {
"x y": (0, 2, 2, Fr(64), 2),
"x y + z": (1, 2, 1, Fr(784, 25), 1),
"x^2 + y": (1, 2, 1, Fr(784, 25), 1),
"1/(s+x)": (2, 3, 1, Fr(64), 3),
"sqrt(s+x)": (1, 1, 0, Fr(16, 5), 2),
"x/(s+y)": (1, 3, 2, Fr(144), 1)},
(5, 4, 3, Fr(1, 2)): {
"x y": (1, 1, 0, Fr(49, 4), 1),
"x y + z": (1, 2, 1, Fr(9), 2),
"x^2 + y": (1, 2, 1, Fr(9), 2),
"1/(s+x)": (1, 2, 1, Fr(49, 4), 2),
"sqrt(s+x)": (1, 1, 0, Fr(49, 72), 3),
"x/(s+y)": (1, 2, 1, Fr(49), 2)},
(5, 3, 4, Fr(1, 2)): {
"x y": (0, 1, 1, Fr(196, 9), 1),
"x y + z": (1, 2, 1, Fr(49, 4), 2),
"x^2 + y": (1, 2, 1, Fr(49, 4), 2),
"1/(s+x)": (1, 2, 1, Fr(196, 9), 2),
"sqrt(s+x)": (1, 1, 0, Fr(98, 81), 2),
"x/(s+y)": (1, 2, 1, Fr(49), 2)}}
CHAINS = {
(4, 2, 2): {"(x y) + z": (4, 4), "(x y) z": (4, 3), "z (x + y)": (3, 3)},
(5, 2, 3): {"(x y) + z": (4, 4), "(x y) z": (4, 4), "z (x + y)": (4, 3)},
(5, 3, 4): {"(x y) + z": (2, 2), "(x y) z": (2, 2), "z (x + y)": (2, 2)},
(3, 2, 1): {"(x y) + z": (4, 4), "(x y) z": None, "z (x + y)": None}}
LED = {(4, 1, 4): (4, 3), (2, 2, 2): (5, 4), (3, 1, 3): (4, 4),
(3, 2, 1): (4, 4), (2, 3, 1): (5, 5), (3, 5, 1): (3, 3),
(2, 4, 1): None, (2, 1, 4): None}
NEEDS_CELL = "needs b >= 2, a+- >= 1, slack a- + a+ + 1 - b >= 1"
NEEDS_H = "needs pole distance h > 0"
def check(name, ok, detail=""):
CHECKS.append(bool(ok))
tail = f" ({detail})" if detail else ""
print(f" {'PASS' if ok else 'FAIL'} {name}{tail}")
def cell_of(b, am, ap):
if b < 2 or am < 1 or ap < 1 or am + ap + 1 - b < 1:
raise ValueError(NEEDS_CELL)
return ms.Cell(b, am, ap)
def unit(b, am, ap, lam, lo, hi):
cell = cell_of(b, am, ap)
o, L = cell.lead((Fr(lo), Fr(hi))), cell.law_L(Fr(lam))
return o, L, L - o
def estimate(cell, lam, lo, hi):
G = max(float(hi) / float(cell.Mp), -float(lo) / float(cell.Mm))
return math.log(float(lam) / G * cell.I / cell.rho, cell.b)
def _named(cell):
"""The three polynomial units as manystream maps with their ranges."""
Mm, Mp, Mh = cell.Mm, cell.Mp, cell.Mh
by = {m[0]: m for m in ms.MAPS}
return {"x y": (by["x y"], (-Mm * Mp, Mh * Mh)),
"x y + z": (by["x y + z"], (-Mm * Mp - Mm, Mh * Mh + Mp)),
"x^2 + y": (by["x^2 + y"], (-Mm, Mh * Mh + Mp))}
def _dead(scan, L):
"""The output depths at which a reader dies at L - 1 and at L."""
return scan(L - 1), scan(L)
def table(b, am, ap, h, certify=False):
cell, h = cell_of(b, am, ap), Fr(h)
if h <= 0:
raise ValueError(NEEDS_H)
rows = {}
for name, (mp, rng) in _named(cell).items():
lam = mp[4](cell.Mh)
o, L = cell.lead(rng), cell.law_L(lam)
row = (o, L, L - o, estimate(cell, lam, *rng))
if certify:
row += _dead(lambda n: ms.scan(cell, mp, n, o)[0], L)
rows[name] = row
for name, u in (("1/(s+x)", poles.Recip(cell, h)),
("x/(s+y)", poles.Divider(cell, h))):
o, L = u.lead(), u.law_L()
row = (o, L, L - o, estimate(cell, u.lam, *u.rng))
if certify:
row += _dead(lambda n: ms.scan(cell, u.mapping(), n, o)[0], L)
rows[name] = row
r = poles.Root(cell, h)
o, L = r.lead(), r.law_L()
G = math.sqrt(float(h + cell.w)) / float(cell.Mp)
lam = 1 / (2 * math.sqrt(float(h)))
row = (o, L, L - o, math.log(lam / G * cell.I / cell.rho, b))
if certify:
row += _dead(lambda n: poles.one_scan(cell, r, n, o)[0], L)
rows["sqrt(s+x)"] = row
return {n: Row(*rows[n]) for n in UNITS}
def certify(b, am, ap, d, image, partials, lam, lo, hi):
cell = cell_of(b, am, ap)
o, L, _ = unit(b, am, ap, lam, lo, hi)
mp = ("map", d, image, partials, None)
return Cert(o, L, *_dead(lambda n: ms.scan(cell, mp, n, o)[0], L))
def piecewise(b, am, ap, kinks, polys):
cell = cell_of(b, am, ap)
f = pwm.PW("map", cell, kinks, polys)
L = f.law_L()
return Pieces(f.lead(), L, pwm.Clauses(f).floor(L))
def chains(b, am, ap):
cell = cell_of(b, am, ap)
rows = dict.fromkeys(["(x y) + z", "(x y) z", "z (x + y)"])
if ch.representable(cell):
naive = ch.floor_xy(cell) + ch.sum_floor(cell)
rows["(x y) + z"] = (naive, naive)
rows["(x y) z"] = ch.two_unit(cell, ch.xy_head)[:2]
elif max(am, ap) <= 2 * b - 1:
L1s, L2s = ch.floor_led(cell), ch.sum_floor(cell)
gain = L2s == 2 and ch.gain_option(cell, L1s) is not None
rows["(x y) + z"] = (L1s + L2s, L1s + L2s - gain)
if ch.sum_fed_ok(cell):
rows["z (x + y)"] = ch.two_unit(cell, ch.sum_head)[:2]
return rows
def show(b, am, ap, h, rows, chain):
print(f"the table at radix {b} over {{-{am}..{ap}}}, h = {h}: "
"(lead, L*, lookahead, estimate)")
for name, row in rows.items():
print(f" {name:10s} {row.lead:3d} {row.L:3d} {row.c:3d}"
f" {row.estimate:6.2f}")
print("the chains: (naive, least by the laws)")
for name, row in chain.items():
print(f" {name:10s} {row if row else 'absent'}")
def control_table(key, t):
"""A certified table against its record: the three integers, the
estimate through b^(2 estimate), the death at L* - 1 at its
recorded depth and none at L*."""
return list(t) == UNITS and all(
tuple(t[n][:3]) == rec[:3]
and abs(key[0] ** (2 * t[n].estimate) - rec[3]) < 1e-9 * rec[3]
and (t[n].dead_below, t[n].dead_at) == (rec[4], None)
for n, rec in TABLE[key].items())
def control_refused(why, call, *args):
try:
call(*args)
except ValueError as e:
return str(e) == why
except Exception:
return False
return False
def main():
t0 = time.time()
keys = ((4, 2, 2, Fr(1, 3)), (5, 4, 3, Fr(1, 2)), (5, 3, 4, Fr(1, 2)))
tabs = [table(*k, certify=True) for k in keys]
t, t2, c1 = tabs[0], tabs[1], chains(4, 2, 2)
show(*keys[0], t, c1)
print("CONTROLS")
for k, tk in zip(keys, tabs):
check(f"the table at {k[:3]}, h = {k[3]}, is its record: "
f"{[tuple(r[:3]) for r in tk.values()]}, estimates "
f"{[f'{r.estimate:.2f}' for r in tk.values()]}, dead at "
f"{[(r.dead_below, r.dead_at) for r in tk.values()]}",
control_table(k, tk))
r = table(4, 2, 2, 32)["1/(s+x)"]
check(f"the reciprocal at h = 32 runs ahead: {r[:3]}",
r[:3] == (-2, -4, -2))
M = Fr(2, 3)
off = (unit(4, 2, 2, Fr(1, 8), Fr(-1, 8), Fr(1, 100)),
unit(4, 2, 2, Fr(1, 8), Fr(-1, 100), Fr(1, 8)))
check(f"unit() on x y's rate and range is its row at (4, 2, 2) and "
f"at (5, 4, 3), and at rate 1/8 on [-1/8, 1/100] and on "
f"[-1/100, 1/8] reads {off}",
unit(4, 2, 2, 2 * M, -M * M, M * M) == t["x y"][:3] == (0, 2, 2)
and unit(5, 4, 3, 2, Fr(-3, 4), 1) == t2["x y"][:3] == (1, 1, 0)
and off == ((-1, 0, 1), (-1, 0, 1)))
s = Fr(1) + 2 # s = M- + h at (2, 1, 1), h = 2
def img(B):
v = [x / (s + y) for x in B[0] for y in B[1]]
return min(v), max(v)
def parts(B):
X = max(abs(B[0][0]), abs(B[0][1]))
return [(1 / (s + B[1][1]), 1 / (s + B[1][0])),
(-X / (s + B[1][0]) ** 2, X / (s + B[1][0]) ** 2)]
got = certify(2, 1, 1, 2, img, parts, Fr(3, 4), Fr(-1, 2), Fr(1, 2))
low = certify(2, 1, 1, 2, img, parts, Fr(3, 8), Fr(-1, 2), Fr(1, 2))
d = table(2, 1, 1, 2, certify=True)["x/(s+y)"]
check(f"the divider at (2, 1, 1), h = 2, in the table and described "
f"by hand: {tuple(d[:3])}, {got}; its rate understated: {low}",
got == Cert(-1, 1, 3, None) and tuple(d[:3]) == (-1, 1, 2)
and abs(2 ** d.estimate - 3) < 1e-9
and (d.dead_below, d.dead_at) == (3, None)
and low == Cert(-1, 0, 2, 3))
p1 = piecewise(5, 2, 3, [0], [(0, Fr(1, 2)), (0, 1)])
p2 = piecewise(3, 1, 2, [0], [(0, Fr(1, 5), Fr(1, 20)), (0, 1)])
check(f"the two piecewise specimens: {p1}, {p2}",
p1 == (0, 1, 1) and p2 == (0, 1, 0))
third = Fr(1, 3)
k1 = unit(5, 2, 3, 0, third, third)
k2 = piecewise(5, 2, 3, [0], [(third,), (third,)])
k0 = unit(5, 2, 3, 0, 0, 0)
check(f"a constant, 1/3 at (5, 2, 3), has no least L, and 0 no "
f"least lead: {k1}, {k2}, {k0}",
k1 == (0, -40, -40) and k2 == (0, -40, None)
and k0 == (-40, -40, 0))
cs = {c: chains(*c) for c in CHAINS}
check(f"the chain rows: {cs}", cs == CHAINS and c1 == CHAINS[4, 2, 2])
led = {c: chains(*c)["(x y) + z"] for c in LED}
check(f"the led adder rows: {led}", led == LED)
bad = [(unit, 4, 1, 2, 1, -1, 1), (table, 4, 1, 2, 1),
(certify, 4, 1, 2, 2, img, parts, 1, -1, 1),
(piecewise, 4, 1, 2, [0], [(0, 1), (0, 1)]), (chains, 4, 1, 2),
(unit, 1, 1, 1, 1, -1, 1), (unit, 4, 0, 4, 1, -1, 1),
(unit, 4, 4, 0, 1, -1, 1)]
bad = [(NEEDS_CELL,) + c for c in bad] + [
(NEEDS_H, table, 4, 2, 2, 0), (NEEDS_H, table, 4, 2, 2, Fr(-1, 3))]
no = 0 # stopped at the first call let through: one may never return
while no < len(bad) and control_refused(*bad[no]):
no += 1
check(f"refused, slack 0 at each call, radix 1, a- = 0, a+ = 0, "
f"h = 0 and h < 0: {no} of {len(bad)}", no == len(bad) == 10)
print(f"{sum(CHECKS)}/{len(CHECKS)} checks passed, "
f"{time.time() - t0:.1f} s")
raise SystemExit(0 if all(CHECKS) else 1)
if __name__ == "__main__":
main()