-
Notifications
You must be signed in to change notification settings - Fork 27
/
Copy pathmy_accumarray.py
40 lines (37 loc) · 1.42 KB
/
my_accumarray.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import numpy as np
def map_functionnames():
function_name_dict = {'plus' : (np.add, 0.),
'minus' : (np.subtract, 0.),
'times' : (np.multiply, 1.),
'max' : (np.maximum, -np.inf),
'min' : (np.minimum, np.inf),
'and' : (np.logical_and, True),
'or' : (np.logical_or, False)
}
return function_name_dict
def my_accumarray(indices, vals, size, func='plus', fill_value=0):
# get dictionary
function_name_dict = map_functionnames()
if not func in function_name_dict:
raise KeyError('Function name not defined for accumarray')
if np.isscalar(vals):
if isinstance(indices, tuple):
shape = indices[0].shape
else:
shape = indices.shape
vals = np.tile(vals, shape)
#get the function and the default value
(function, value) = function_name_dict[func]
#create an array to hold things
output = np.ndarray(size)
output[:] = value
function.at(output, indices, vals)
# also check whether indices have been used or not
isthere = np.ndarray(size, 'bool')
istherevals = np.ones(vals.shape, 'bool')
(function, value) = function_name_dict['or']
isthere[:] = value
function.at(isthere, indices, istherevals)
#fill things that were not used with fill value
output[np.invert(isthere)] = fill_value
return output