2

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?

2 Answers 2

4

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)
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for the tip on np.fromfunction and how to avoid using it, I didn't know it was slow.
3

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)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.