Skip to content

Instantly share code, notes, and snippets.

@epifanio
Created September 24, 2018 03:16
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save epifanio/47340242f5be2de2c50577bf82c37143 to your computer and use it in GitHub Desktop.
Save epifanio/47340242f5be2de2c50577bf82c37143 to your computer and use it in GitHub Desktop.
Display the source blob
Display the rendered blob
Raw
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
@epifanio
Copy link
Author

epifanio commented Sep 24, 2018

by adding a new module with the following function, which operates on a single point instead of an array:

%%file numba_parallel.py
import numba
from numba import jit
import numpy as np

@cc.export('ray_tracing1',  'b1(f8, f8, f8[:,:])')
@jit(nopython=True, nogil=True)
def ray_tracing1(x,y,poly):
    n = len(poly)
    inside = False
    p2x = 0.0
    p2y = 0.0
    xints = 0.0
    p1x,p1y = poly[0]
    for i in range(n+1):
        p2x,p2y = poly[i % n]
        if y > min(p1y,p2y):
            if y <= max(p1y,p2y):
                if x <= max(p1x,p2x):
                    if p1y != p2y:
                        xints = (y-p1y)*(p2x-p1x)/(p2y-p1y)+p1x
                    if p1x == p2x or x <= xints:
                        inside = not inside
        p1x,p1y = p2x,p2y

    return inside

I can define then a new function that make use of numba.prange to loop over all the points in parallel:

import numba

@numba.njit(parallel=True)
def parallel_tracing(pp, poly):
    D = np.empty(len(pp), dtype=numba.boolean)
    for i in numba.prange(1, len(D) - 1):
        D[i] = nbspatial.ray_tracing1(pp[i][0], pp[i][1], polygon)
    return D

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment