2 Provides functionality for multidimensional usage of scalar-functions.
4 Read the vectorize docstring for more details.
7 def apply_on_element(f
, args
, kwargs
, n
):
9 Returns a structure with the same dimension as the specified argument,
10 where each basic element is replaced by the function f applied on it. All
11 other arguments stay the same.
13 # Get the specified argument.
14 if isinstance(n
, int):
17 elif isinstance(n
, str):
21 # Define reduced function that is only dependend of the specified argument.
23 if hasattr(x
, "__iter__"):
24 return map(f_reduced
, x
)
30 return f(*args
, **kwargs
)
32 # f_reduced will call itself recursively so that in the end f is applied to
34 return map(f_reduced
, structure
)
36 def iter_copy(structure
):
38 Returns a copy of an iterable object (also copying all embedded iterables).
42 if hasattr(i
, "__iter__"):
43 l
.append(iter_copy(i
))
48 def structure_copy(structure
):
50 Returns a copy of the given structure (numpy-array, list, iterable, ..).
52 if hasattr(structure
, "copy"):
53 return structure
.copy()
54 return iter_copy(structure
)
59 Generalizes a function taking scalars to accept multidimensional arguments.
68 [sin(1), sin(x), sin(y)]
75 >>diff([f(x,y,z),g(x,y,z),h(x,y,z)], [x,y,z])
76 [[d/dx f, d/dy f, d/dz f],
77 [d/dx g, d/dy g, d/dz g],
78 [d/dx h, d/dy h, d/dz h]]
80 def __init__(self
, *mdargs
):
82 The given numbers and strings characterize the arguments that will be
83 treated as data structures, where the decorated function will be applied
84 to every single element.
85 If no argument is given, everything is treated multidimensional.
88 assert isinstance(a
, (int,str))
91 def __call__(self
, f
):
93 Returns a wrapper for the one-dimensional function that can handle
94 multidimensional arguments.
96 def wrapper(*args
, **kwargs
):
97 # Get arguments that should be treated multidimensional
101 mdargs
= range(len(args
)) + kwargs
.keys()
103 arglength
= len(args
)
106 if isinstance(n
, int):
111 elif isinstance(n
, str):
117 if hasattr(entry
, "__iter__"):
118 # Create now a copy of the given array and manipulate then
119 # the entries directly.
122 args
[n
] = structure_copy(entry
)
124 kwargs
[n
] = structure_copy(entry
)
125 result
= apply_on_element(wrapper
, args
, kwargs
, n
)
127 return f(*args
, **kwargs
)
128 wrapper
.__doc
__ = f
.__doc
__
129 wrapper
.__name
__ = f
.__name
__