interplane.Get Omega
Read in your language

omega-bridge

Omega-first language interoperability: checked conversion backends and native language bindings

Brought by drakestapleton

branch main Branches Tags History

omega-bridge / tests / native / pykinds.py

46 lines · 2563 bytes Raw Blame History
1# Python caller for the f32 and ushort array kinds through the binding tools' `python` word generates
2# (ctypes, standard library only). argv: the folder holding omega_native.py and libomega_native.so.
3# Every expected value is computed here in Python (struct), independently of the Omega code.
4import ctypes, struct, sys
5sys.path.insert(0, sys.argv[1])
6import omega_native as om
7fails = 0
8def check(name, ok):
9 global fails
10 print(("PASS " if ok else "FAIL ") + name)
11 fails += not ok
12def f32(x):
13 return struct.unpack("<f", struct.pack("<f", x))[0]
14def f32bits(x):
15 return struct.unpack("<I", struct.pack("<f", x))[0]
16def f16bits(x):
17 return struct.unpack("<H", struct.pack("<e", x))[0]
18def refused(f):
19 try:
20 f()
21 except ctypes.ArgumentError:
22 return True
23 return False
24F, H, SENT = ctypes.c_float, ctypes.c_uint16, 6148914691236517205
25av = [1.5, 2.25, -3.0, 0.125]; hv = [1.0, 0.5, 2.0, -0.25]
26a = (F * 4)(*av); h = (H * 4)(*[f16bits(x) for x in hv]); o = (F * 4)()
27want = [f32(x + y) for x, y in zip(av, hv)]
28r = ctypes.c_uint64(SENT)
29check("fsum f32 view + ushort view -> f32 edit == Python",
30 om.omega_fsum(ctypes.byref(r), a, 4, h, 4, o, 4) == 0 and list(o) == want)
31check("fsum result bits == Python", r.value == f32bits(f32(want[0] + want[3])))
32g = (H * 3)(*[f16bits(x) for x in (3.0, -0.75, 1024.0)])
33check("halve ushort edit written in place == Python",
34 om.omega_halve(ctypes.byref(r), g, 3) == 0 and list(g) == [f16bits(x) for x in (1.5, -0.375, 512.0)])
35# Negative controls: what the ABI cannot carry is refused before the Omega code runs.
36r = ctypes.c_uint64(SENT); o2 = (F * 4)()
37check("fsum wrong length 3 refused (status 32), output and result untouched",
38 om.omega_fsum(ctypes.byref(r), a, 3, h, 4, o2, 4) == 32 and list(o2) == [0.0] * 4 and r.value == SENT)
39check("halve wrong length 4 refused (status 32), array untouched",
40 om.omega_halve(ctypes.byref(r), g, 4) == 32 and list(g) == [f16bits(x) for x in (1.5, -0.375, 512.0)])
41check("f64 array for an f32 view refused", refused(lambda: om.omega_fsum(ctypes.byref(r), (ctypes.c_double * 4)(), 4, h, 4, o, 4)))
42check("int32 array for an f32 view refused", refused(lambda: om.omega_fsum(ctypes.byref(r), (ctypes.c_int32 * 4)(), 4, h, 4, o, 4)))
43check("bytes for an edit ushort array refused", refused(lambda: om.omega_halve(ctypes.byref(r), bytes(6), 3)))
44check("length 2**64 refused", refused(lambda: om.omega_halve(ctypes.byref(r), g, 2**64)))
45print(("FAIL " if fails else "PASS ") + "%d failure(s)" % fails)
46sys.exit(fails != 0)