Alex van Houten
Alex van Houten

Reputation: 410

create an x-dim array using numpy.fromfunction from a function with more than x parameters

I would like to create a 2D (x,y) array from a 5d function, say some kernel KMID:

import numpy as np
def KMID(x,y,mumid,delta,cmid):
    rsq=(x-float(len(x))/2.+0.5)**2+(y-float(len(y))/2.+0.5)**2
    return cmid*np.exp(-mumid*np.sqrt(rsq))/(rsq+delta**2)

by something like this:

shape=256,256
midscatterkernel=np.fromfunction(KMID(:,:,0.1,0.2,0.3),shape)

This gives:

SyntaxError: invalid syntax

i.e. I want to make a 2D array by iterating over just the first two indices. What is the most elegant way to do this?

Upvotes: 2

Views: 1681

Answers (2)

unutbu
unutbu

Reputation: 880079

Don't use np.fromfunction for this, since KMID can accept numpy arrays as arguments:

import numpy as np

def KMID(x, y, mumid, delta, cmid):
    rsq = (x-len(x)/2.+0.5)**2+(y-len(y)/2.+0.5)**2
    return cmid*np.exp(-mumid*np.sqrt(rsq))/(rsq+delta**2)

lenx, leny = 256, 256
midscatterkernel = KMID(
    np.arange(lenx),
    np.arange(leny)[:, np.newaxis],
    0.1, 0.2, 0.3)

(np.fromfunction is syntactic sugar for a slow Python loop. If you can do the same thing with numpy array operations, use the numpy array operations. It will be faster.)


To answer you question, however, if you did need to use np.fromfunction, but wanted to supply some of the arguments as constants, then you could use functools.partial:

import functools
def KMID(x, y, mumid, delta, cmid):
    rsq = (x-len(x)/2.+0.5)**2+(y-len(y)/2.+0.5)**2
    return cmid*np.exp(-mumid*np.sqrt(rsq))/(rsq+delta**2)

shape = 256, 256
midscatterkernel = np.fromfunction(functools.partial(KMID,mumid=0.1,delta=0.2,cmid=0.3),shape)

Upvotes: 4

Fred Foo
Fred Foo

Reputation: 363687

KMID is a function, not an array, so you can't index it with :. Do

midscatterkernel=np.fromfunction(lambda x, y: KMID(x,y,0.1,0.2,0.3), shape)

Upvotes: 3

Related Questions