Repository navigation
Expand file tree
/
Copy pathinteger_oracle.py
More file actions
52 lines (44 loc) · 2.08 KB
/
Copy pathinteger_oracle.py
File metadata and controls
52 lines (44 loc) · 2.08 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
"""Independent arbitrary-precision model for the integer filter."""
import itertools
import math
def ties_away(value):
return (1 if value >= 0 else -1) * math.floor(abs(value) + 0.5)
def map_index(index, size, mode):
if mode == "reflect":
folded = index % (size * 2)
return min(folded, size * 2 - 1 - folded)
if mode == "replicate":
return min(max(index, 0), size - 1)
return index if 0 <= index < size else None
def reference(image, coefficients, bits, fraction, accumulator, border):
"""Return 8-bit codes, coefficient codes, and per-event counts."""
h, w = len(image), len(image[0])
kh, kw = len(coefficients), len(coefficients[0])
scale = 2 ** fraction
c_limit = 2 ** (bits - 1)
a_limit = 2 ** (accumulator - 1)
def clip(value, left, right):
return sorted((left, value, right))[1]
scaled = [[ties_away(c * scale) for c in row] for row in coefficients]
weights = [[clip(c, -c_limit, c_limit - 1) for c in row] for row in scaled]
coeff_clips = sum(a != b for a, b in zip(sum(scaled, []), sum(weights, [])))
pixels = [[ties_away(clip(p, 0, 1) * 255) for p in row] for row in image]
out = [[0 for _ in range(w)] for _ in range(h)]
overflow = saturation = 0
taps = list(itertools.product(range(kh), range(kw)))
for y, x in itertools.product(range(h), range(w)):
total = 0
for j, i in taps:
ry = map_index(y + j - kh // 2, h, border)
rx = map_index(x + i - kw // 2, w, border)
if ry is None or rx is None:
continue
candidate = total + weights[j][i] * pixels[ry][rx]
total = clip(candidate, -a_limit, a_limit - 1)
overflow += total != candidate
magnitude, remainder = divmod(abs(total), scale)
rounded = (magnitude + int(2 * remainder >= scale)) * (-1 if total < 0 else 1)
out[y][x] = clip(rounded, 0, 255)
saturation += out[y][x] != rounded
return out, weights, dict(overflow=overflow, saturation=saturation,
coefficient_saturation=coeff_clips)