-
Notifications
You must be signed in to change notification settings - Fork 0
/
generate.py
96 lines (67 loc) · 2.95 KB
/
generate.py
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
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
# Vector generator for src/vectors/**/*.zig using numpy/scipy
import os
import os.path
import random
import numpy
import scipy
# Floating point precision to round and serialize to
PRECISION = 8
################################################################################
# Helper functions for generating random types
################################################################################
def random_complex64(n):
return numpy.around(numpy.array([complex(2 * random.random() - 1.0, 2 * random.random() - 1.0) for _ in range(n)]).astype(numpy.complex64), PRECISION)
def random_float32(n):
return numpy.around(numpy.array([2 * random.random() - 1.0 for _ in range(n)]).astype(numpy.float32), PRECISION)
################################################################################
# Vector Serialization
################################################################################
def serialize(vector):
"""Serialize a vector into a Zig array."""
if isinstance(vector, numpy.ndarray):
if vector.dtype == "float32":
return f"[{len(vector)}]f32{{ " + ", ".join([f"{e:.{PRECISION}f}" for e in vector]) + " }"
elif vector.dtype == "complex64":
return f"[{len(vector)}]std.math.Complex(f32){{ " + ", ".join([f".{{ .re = {e.real:.{PRECISION}f}, .im = {e.imag:.{PRECISION}f} }}" for e in vector]) + " }"
else:
raise NotImplementedError(f"Unsupported ndarray data type: {vector.dtype}")
else:
raise NotImplementedError(f"Unsupported vector type: {type(vector)}")
################################################################################
# Generate
################################################################################
def generate(filename):
"""Generate test vectors in `filename`."""
# Initialize random seed for determinism
random.seed(1)
python_buffer = ""
with open(filename, "r+") as f:
# Extract python code from python tag and stop at autogenerated tag
in_python_tag = False
for line in iter(f.readline, None):
if not line or "@autogenerated" in line:
break
elif "@python" in line:
in_python_tag = not in_python_tag
elif in_python_tag:
python_buffer += line[3:]
# Initialize vectors
vectors = {}
def vector(name, v):
print(f"Generating vector {filename}:{name}")
vectors[name] = v
# Run code
exec(python_buffer)
# Truncate rest of file
f.truncate(f.tell())
f.seek(f.tell())
# Serialize vectors
f.write("\n")
for name in vectors:
f.write(f"pub const {name} = {serialize(vectors[name])};\n")
if __name__ == "__main__":
# Walk vectors directory
for root, _, files in os.walk("src/vectors"):
for file in files:
if file.endswith(".zig"):
generate(os.path.join(root, file))