Created
December 21, 2019 18:13
-
-
Save michelp/55f11547d14439723fac5b446249fd35 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
src = """ | |
typedef struct BF_tuple { | |
double w; | |
uint64_t h; | |
uint64_t pi; | |
} BF_tuple; | |
typedef void (*bf_min)(BF_tuple*, BF_tuple*, BF_tuple*); | |
typedef void (*bf_plus)(BF_tuple*, BF_tuple*, BF_tuple*); | |
""" | |
from numba import cfunc, carray | |
from numba import cffi_support | |
ffi = FFI() | |
ffi.cdef(src) | |
ffi.set_source('_bf', """ | |
#include <math.h> | |
#include <stdint.h> | |
""") | |
def new_tuple(w, h, pi): | |
data = ffi.new('BF_tuple[1]') | |
ptr = ffi.cast('BF_tuple*', data) | |
ptr[0].w = w | |
ptr[0].h = h | |
ptr[0].pi = pi | |
addr = int(ffi.cast('size_t', ptr)) | |
return addr | |
cffi_support.map_type(ffi.typeof('BF_tuple'), use_record_dtype=True) | |
min_sig = cffi_support.map_type(ffi.typeof('bf_min'), use_record_dtype=True) | |
plus_sig = cffi_support.map_type(ffi.typeof('bf_plus'), use_record_dtype=True) | |
@cfunc(min_sig) | |
def bf_min(z_, x_, y_): | |
z = carray(z_, 1)[0] | |
x = carray(x_, 1)[0] | |
y = carray(y_, 1)[0] | |
z.w = x.w if x.w < y.w else y.w | |
@cfunc(plus_sig) | |
def bf_plus(z_, x_, y_): | |
z = carray(z_, 1)[0] | |
x = carray(x_, 1)[0] | |
y = carray(y_, 1)[0] | |
z.w = x.w - y.w | |
def new_udt(name): | |
t = gbffi.new('GrB_Type*') | |
lib.GrB_Type_new(t, ffi.sizeof(name)) | |
return t | |
bf = new_udt('BF_tuple') | |
def new_binop(func, typ): | |
o = gbffi.new('GrB_BinaryOp*') | |
typ = typ[0] | |
lib.GrB_BinaryOp_new(o, gbffi.cast('GxB_binary_function', func.address), typ, typ, typ) | |
return o | |
op = new_binop(bf_plus, bf) | |
op = BinaryOp('plus', 'bf', op[0]) | |
A = Matrix.from_type(bf[0], 10, 10) | |
B = Matrix.from_type(bf[0], 10, 10) | |
z = new_tuple(0.1, 1, 1) | |
x = new_tuple(0.2, 2, 2) | |
y = new_tuple(0.3, 3, 3) | |
A[0,0] = z | |
B[1,1] = x | |
with op: | |
print((A + B).nvals) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment