|
| 1 | +import numba |
| 2 | +import numpy as np |
| 3 | +from numba import float64, int64 |
| 4 | +from numba import generated_jit, njit |
| 5 | +import ast |
| 6 | + |
| 7 | +from numba.extending import overload |
| 8 | +from numba.types.containers import Tuple, UniTuple |
| 9 | + |
| 10 | + |
| 11 | +#################### |
| 12 | +# Dimension helper # |
| 13 | +#################### |
| 14 | + |
| 15 | +t_coord = numba.typeof((2.3,2.4,1)) # type of an evenly spaced dimension |
| 16 | +t_array = numba.typeof(np.array([4.0, 3.9])) # type of an unevenly spaced dimension |
| 17 | + |
| 18 | +# returns the index of a 1d point along a 1d dimension |
| 19 | +@generated_jit(nopython=True) |
| 20 | +def get_index(gc, x): |
| 21 | + if gc == t_coord: |
| 22 | + # regular coordinate |
| 23 | + def fun(gc,x): |
| 24 | + δ = (gc[1]-gc[0])/(gc[2]-1) |
| 25 | + d = x-gc[0] |
| 26 | + ii = d // δ |
| 27 | + r = d-ii*δ |
| 28 | + i = int(ii) |
| 29 | + λ = r/δ |
| 30 | + return (i, λ) |
| 31 | + return fun |
| 32 | + else: |
| 33 | + # irregular coordinate |
| 34 | + def fun(gc,x): |
| 35 | + i = int(np.searchsorted(gc, x))-1 |
| 36 | + λ = (x-gc[i])/(gc[i+1]-gc[i]) |
| 37 | + return (i, λ) |
| 38 | + return fun |
| 39 | + |
| 40 | +# returns number of dimension of a dimension |
| 41 | +@generated_jit(nopython=True) |
| 42 | +def get_size(gc): |
| 43 | + if gc == t_coord: |
| 44 | + # regular coordinate |
| 45 | + def fun(gc): |
| 46 | + return gc[2] |
| 47 | + return fun |
| 48 | + else: |
| 49 | + # irregular coordinate |
| 50 | + def fun(gc): |
| 51 | + return len(gc) |
| 52 | + return fun |
| 53 | + |
| 54 | +##################### |
| 55 | +# Generator helpers # |
| 56 | +##################### |
| 57 | + |
| 58 | +# the next functions replace the use of generators, with the difference that the |
| 59 | +# output is a tuple, which dimension is known by the jit guy. |
| 60 | + |
| 61 | +# example: |
| 62 | +# ``` |
| 63 | +# def f(x): x**2 |
| 64 | +# fmap(f, (1,2,3)) -> (1,3,9) |
| 65 | +# def g(x,y): x**2 + y |
| 66 | +# fmap(g, (1,2,3), 0.1) -> (1.1,3.1,9.1) # (g(1,0.1), g(2,0.1), g(3,0.1)) |
| 67 | +# def g(x,y): x**2 + y |
| 68 | +# fmap(g, (1,2,3), (0.1,0.2,0.3)) -> (1.1,3.0.12,9.3) |
| 69 | +# ``` |
| 70 | + |
| 71 | + |
| 72 | +def fmap(): |
| 73 | + pass |
| 74 | + |
| 75 | +@overload(fmap) |
| 76 | +def _map(*args): |
| 77 | + |
| 78 | + if len(args)==2 and isinstance(args[1], (Tuple, UniTuple)): |
| 79 | + k = len(args[1]) |
| 80 | + s = "def __map(f, t): return ({}, )".format(str.join(', ',['f(t[{}])'.format(i) for i in range(k)])) |
| 81 | + elif len(args)==3 and isinstance(args[1], (Tuple, UniTuple)): |
| 82 | + k = len(args[1]) |
| 83 | + if isinstance(args[2], (Tuple, UniTuple)): |
| 84 | + if len(args[2]) != k: |
| 85 | + # we don't know what to do in this case |
| 86 | + return None |
| 87 | + s = "def __map(f, t1, t2): return ({}, )".format(str.join(', ',['f(t1[{}], t2[{}])'.format(i,i) for i in range(k)])) |
| 88 | + else: |
| 89 | + s = "def __map(f, t1, x): return ({}, )".format(str.join(', ',['f(t1[{}], x)'.format(i,i) for i in range(k)])) |
| 90 | + else: |
| 91 | + return None |
| 92 | + d = {} |
| 93 | + eval(compile(ast.parse(s),'<string>','exec'), d) |
| 94 | + return d['__map'] |
| 95 | + |
| 96 | + |
| 97 | +# not that `fmap` does nothing in python mode... |
| 98 | +# an alternative would be |
| 99 | +# |
| 100 | +# @njit |
| 101 | +# def _fmap(): |
| 102 | +# pass |
| 103 | +# |
| 104 | +# @overload(_fmap) |
| 105 | +# ... |
| 106 | +# |
| 107 | +# @njit |
| 108 | +# def fmap(*args): |
| 109 | +# return _fmap(*args) |
| 110 | +# |
| 111 | +# but this seems to come with a performance cost. |
| 112 | +# It it is also possible to overload `map` but we would risk |
| 113 | +# a future conflict with the map api. |
| 114 | + |
| 115 | + |
| 116 | +# |
| 117 | +# @njit |
| 118 | +# def fmap(*args): |
| 119 | +# return _fmap(*args) |
| 120 | +# |
| 121 | +# funzip(((1,2), (2,3), (4,3))) -> ((1,2,4),(2,3,3)) |
| 122 | + |
| 123 | +@generated_jit(nopython=True) |
| 124 | +def funzip(t): |
| 125 | + k = t.count |
| 126 | + assert(len(set([e.count for e in t.types]))==1) |
| 127 | + l = t.types[0].count |
| 128 | + def print_tuple(t): return "({},)".format(str.join(", ", t)) |
| 129 | + tab = [ [ 't[{}][{}]'.format(i,j) for i in range(k)] for j in range(l) ] |
| 130 | + s = "def funzip(t): return {}".format(print_tuple( [print_tuple(e) for e in tab] )) |
| 131 | + d = {} |
| 132 | + eval(compile(ast.parse(s),'<string>','exec'), d) |
| 133 | + return d['funzip'] |
| 134 | + |
| 135 | + |
| 136 | +##### |
| 137 | +# array subscribing: |
| 138 | +# when X is a 2d array and I=(i,j) a 2d index, `get_coeffs(X,I)` |
| 139 | +# extracts `X[i:i+1,j:j+1]` but represents it as a tuple of tuple, so that |
| 140 | +# the number of its elements can be inferred by the compiler |
| 141 | +##### |
| 142 | + |
| 143 | + |
| 144 | +@generated_jit(nopython=True) |
| 145 | +def get_coeffs(X,I): |
| 146 | + if X.ndim>len(I): |
| 147 | + print("not implemented yet") |
| 148 | + else: |
| 149 | + from itertools import product |
| 150 | + d = len(I) |
| 151 | + mat = np.array( ["X[{}]".format(str.join(',', e)) for e in product(*[(f"I[{j}]", f"I[{j}]+1") for j in range(d)])] ).reshape((2,)*d) |
| 152 | + mattotup = lambda mat: mat if isinstance(mat,str) else "({})".format(str.join(',',[mattotup(e) for e in mat])) |
| 153 | + t = mattotup(mat) |
| 154 | + s = "def get_coeffs(X,I): return {}".format(t) |
| 155 | + dd = {} |
| 156 | + eval(compile(ast.parse(s),'<string>','exec'), dd) |
| 157 | + return dd['get_coeffs'] |
| 158 | + return fun |
| 159 | + |
| 160 | +# tensor_reduction(C,l) |
| 161 | +# (in 2d) computes the equivalent of np.einsum('ij,i,j->', C, [1-l[0],l[0]], [1-l[1],l[1]])` |
| 162 | +# but where l is a tuple and C a tuple of tuples. |
| 163 | + |
| 164 | +# this one is a temporary implementation (should be merged with old gen_splines* code) |
| 165 | +def gen_tensor_reduction(X, symbs, inds=[]): |
| 166 | + if len(symbs) == 0: |
| 167 | + return '{}[{}]'.format(X, str.join('][',[str(e) for e in inds])) |
| 168 | + else: |
| 169 | + h = symbs[0] |
| 170 | + q = symbs[1:] |
| 171 | + exprs = [ '{}*({})'.format(h if i==1 else '(1-{})'.format(h),gen_tensor_reduction(X, q,inds + [i])) for i in range(2)] |
| 172 | + return str.join( ' + ', exprs ) |
| 173 | + |
| 174 | + |
| 175 | +@generated_jit(nopython=True) |
| 176 | +def tensor_reduction(C,l): |
| 177 | + ex = gen_tensor_reduction('C', ['l[{}]'.format(i) for i in range(len(l.types))]) |
| 178 | + dd = dict() |
| 179 | + s = "def tensor_reduction(C,l): return {}".format(ex) |
| 180 | + eval(compile(ast.parse(s),'<string>','exec'), dd) |
| 181 | + return dd['tensor_reduction'] |
| 182 | + |
| 183 | +@generated_jit(nopython=True) |
| 184 | +def extract_row(a, n, tup): |
| 185 | + d = len(tup.types) |
| 186 | + dd = {} |
| 187 | + s = "def extract_row(a, n, tup): return ({},)".format(str.join(', ', [f"a[n,{i}]" for i in range(d)])) |
| 188 | + eval(compile(ast.parse(s),'<string>','exec'), dd) |
| 189 | + return dd['extract_row'] |
0 commit comments