Mario Arancioni
Mario Arancioni

Reputation: 49

Cythonizing a function that uses numpy

I'm trying to cythonize the following code:

def my_func(vector_b):
    vector_b = np.unpackbits(np.frombuffer(vector_b, dtype=np.uint8))
    vector_b = (vector_b * _n_vector_ranks_only)
    min_ab = np.sum(np.minimum(vector_a, vector_b))
    max_ab = np.sum(np.maximum(vector_a, vector_b))
    return min_ab / max_ab 


_n_vector_ranks_only = np.arange(1023, -1, -1, dtype=np.uint16)

# vector_a data type is same of vector_b, is not contained in db, it is passed manually
vector_a = np.frombuffer(vector_a, dtype=np.uint8)
vector_a = (vector_a * _n_vector_ranks_only)

#fetch all vectors from DB
df = dd.read_sql_table('mydb', 'postgresql://user:passwordg@localhost/table1',  npartitions=16, index_col='id', columns=['data'])
res = df.map_partitions(lambda df: df.apply( lambda x: my_func(x['data']), axis=1), meta=('result', 'double')).compute(scheduler='processes')

#data is a binary array saved with numpy packbits

At the moment I am at this point:

from ruzi_cython import ruzicka
def my_func(vector_b):
    vector_b = np.unpackbits(np.frombuffer(vector_b, dtype=np.uint8))
    vector_b = (vector_b * _n_vector_ranks_only)
    #min_ab = np.sum(np.minimum(vector_a, vector_b))
    #max_ab = np.sum(np.maximum(vector_a, vector_b))
    #return min_ab / max_ab 
    return ruzicka.run_old(vector_a, vector_b)

where ruzicka.pyx is this:

# cython: profile=True
import numpy as np
cimport numpy as np
cimport cython

ctypedef np.uint16_t data_type_t

@cython.boundscheck(False)
@cython.wraparound(False)
@cython.overflowcheck(False)
@cython.initializedcheck(False)
cdef double ruzicka_old(data_type_t[:] a, data_type_t[:] b):
    cdef int i
    cdef float max_ab = 0
    cdef float min_ab = 0
    for i in range(1024):
        if a[i] > b[i]:
            max_ab += a[i]
            min_ab += b[i]
        else:
            max_ab += b[i]
            min_ab += a[i]
    return min_ab / max_ab 

def run_old(a, b):
    return ruzicka_old(a, b)

Where I gained a lot of performances. I am still not able to cythonize with good results the first part where I do the multiply of the two arrays.

This is how I did the multiply:

cdef double ruzicka(data_type_16[:] a, data_type_8[:] b):
    cdef int i
    cdef float max_ab = 0
    cdef float min_ab = 0
    cdef data_type_16 tmp = 0
    for i in range(1024):
        tmp = b[i] * (1023-i)
        if a[i] > tmp:
            max_ab += a[i]
            min_ab += tmp
        else:
            max_ab += tmp
            min_ab += a[i]
    return min_ab / max_ab 

Upvotes: 0

Views: 233

Answers (1)

DavidW
DavidW

Reputation: 30926

It looks like you're struggling with getting the nth bit of an array (essentially doing what np.unpackbits does).

The nth bit is contained within the n//8 byte (I'm using the // divide-and-round-down operator). You can access an individual bit in a byte doing a "bitwise and" (&) with 1<<m (one bitshifted by m). That will give you the number 2**(m-1), and you really just care if it's 0 or not.

So assuming that vector_b is a np.int8_t memoryview, you can do:

byte_idx = n//8
bit_idx = n%8 # remainder operator
bitmask = 1<<bit_idx
bit_is_true = 1 if (vector_b[byte_idx]&bitmask) else 0

You need to put that in a loop and cdef the types of the variables.

Upvotes: 3

Related Questions