"""Python wrapper of nttconv.so with an exact oracle test.""" import ctypes, numpy as np, os from pathlib import Path _lib = ctypes.CDLL(str(Path(__file__).resolve().parent / 'nttconv.so')) _A = np.ctypeslib.ndpointer(dtype=np.int64, ndim=1, flags='C_CONTIGUOUS') _lib.conv_div.argtypes = [_A, _A, ctypes.c_int, ctypes.c_int64, ctypes.c_int, _A] _lib.conv_div.restype = ctypes.c_int LOG2P = 115.5 def conv_div(a, b, D, ceil): """out[k] = floor/ceil( sum_{i+j=k} a_i b_j / D ), k < len(a); a,b >= 0 int64, same length.""" a = np.ascontiguousarray(a, dtype=np.int64); b = np.ascontiguousarray(b, dtype=np.int64) n = len(a); assert len(b) == n ma = int(a.max()) if n else 0; mb = int(b.max()) if n else 0 assert int(a.min()) >= 0 and int(b.min()) >= 0 # exactness: every s_k <= n*ma*mb < 2^115 < P assert n * ma * mb < 2 ** 115, ('NTT range', n, ma, mb) out = np.zeros(n, dtype=np.int64) if ma == 0 or mb == 0: return out rc = _lib.conv_div(a, b, n, int(D), int(ceil), out) if rc: raise ArithmeticError('conv_div rc %d' % rc) return out def oracle_test(seed=11): rng = np.random.default_rng(seed) for n, top in [(9, 2**20), (7, 2**40), (64, 2**47), (300, 2**45), (1000, 2**42), (513, 2**46)]: a = rng.integers(0, top, n, dtype=np.int64); b = rng.integers(0, top, n, dtype=np.int64) a[: n // 7] = 0; b[-n // 5:] = 0 a[-1] = top - 1; b[0] = top - 1 for D in ((1, 3) if top <= 2**20 else ()) + (2**28 * 800000 + 7, 2**61 + 3, 2**52 - 1): for up in (0, 1): out = conv_div(a, b, D, up) A = [int(x) for x in a]; B = [int(x) for x in b] for k in range(n): s = sum(A[i] * B[k - i] for i in range(k + 1)) q = -((-s) // D) if up else s // D if q >= 2**63: continue assert out[k] == q, (n, D, up, k) print('NTT oracle test passed (exact big-int comparison)') if __name__ == '__main__': import time oracle_test() for n in (100001, 400001, 800001): a = np.random.default_rng(1).integers(0, 2**42, n, dtype=np.int64); b = a[::-1].copy() t = time.time(); conv_div(a, b, 2**28 * 800000, 0); print('n', n, 'sec', time.time() - t)