For example, a toy math function:
def F(x,*args):
val=0
for x_ in x:
val += x_**2
if val<=args[0]:
val= -100
elif val>args[1]:
val= 100
return val
I want to call it inside another function using map to evaluate a list of values:
import numpy as np
if __name__ == "__main__":
def passf(F, x, *args):
#do some operations......
return map(F, x, *args)
x = np.array([[0,1,2],[10,2,0],[0,0,0]])
print(list(passf(F, x, 1,100)))
It gave an error TypeError: 'int' object is not iterable
. It works if return map(F, x, *args)
is changed to list operation return [F(x_, *args) for x_ in x]
. But i would like to use map()
, since later i am planning to use multiprocessing pool map
to evaluate the values in parallel. So is it possible to use map with *args
as input parameter?
Edit: So this is the working main part, by using list operation instead of map()
:
import numpy as np
if __name__ == "__main__":
def passf(F, x, *args):
#do some operations......
return [F(x_, *args) for x_ in x]
x = np.array([[0,1,2],[10,2,0],[0,0,0]])
print(list(passf(F, x, 1,100)))
This outputs:
[5, 100, -100]
Basically F
accepts 2D numpy array and positional arguments (*args), each element of the array (which is 1D array) will be evaluated by F
and outputs a scalar. So in this case [0,1,2]
as input will return 5
, [10,2,0]
returns 100
, and [0,0,0]
returns -100
. So i want this to be done by using map()
as stated above instead of list operation.
For passf
, it accepts a function F
, so i have many different F
s which will be passed to passf
, where each F
accepts different *args
.
Edit 2: added F
as input parameter for passf
and passf
explanation.
Since function F has two two (or more) inputs, you will have to use lambda to be able to use multiple inputs, then call map on that.
def passf_2(x, *args):
return list(map(lambda x_: F(x_, *args), [x_ for x_ in x]))
You will still have to use list comprehension to break down your array into 1D arrays, but this function should work with your main aim of multiprocessing.