Python numpy 模块,fromfunction() 实例源码
我们从Python开源项目中,提取了以下30个代码示例,用于说明如何使用numpy.fromfunction()。
def getArrayRegion(self, arr, img=None, axes=(0, 1), **kwds):
"""
Return the result of ROI.getArrayRegion() masked by the elliptical shape
of the ROI. Regions outside the ellipse are set to 0.
"""
# Note: we could use the same method as used by PolyLineROI, but this
# implementation produces a nicer mask.
arr = ROI.getArrayRegion(self, arr, img, axes, **kwds)
if arr is None or arr.shape[axes[0]] == 0 or arr.shape[axes[1]] == 0:
return arr
w = arr.shape[axes[0]]
h = arr.shape[axes[1]]
## generate an ellipsoidal mask
mask = np.fromfunction(lambda x,y: (((x+0.5)/(w/2.)-1)**2+ ((y+0.5)/(h/2.)-1)**2)**0.5 < 1, (w, h))
# reshape to match array axes
if axes[0] > axes[1]:
mask = mask.T
shape = [(n if i in axes else 1) for i,n in enumerate(arr.shape)]
mask = mask.reshape(shape)
return arr * mask
def getArrayRegion(self, arr, img=None, axes=(0, 1), **kwds):
"""
Return the result of ROI.getArrayRegion() masked by the elliptical shape
of the ROI. Regions outside the ellipse are set to 0.
"""
# Note: we could use the same method as used by PolyLineROI, but this
# implementation produces a nicer mask.
arr = ROI.getArrayRegion(self, arr, img, axes, **kwds)
if arr is None or arr.shape[axes[0]] == 0 or arr.shape[axes[1]] == 0:
return arr
w = arr.shape[axes[0]]
h = arr.shape[axes[1]]
## generate an ellipsoidal mask
mask = np.fromfunction(lambda x,y: (((x+0.5)/(w/2.)-1)**2+ ((y+0.5)/(h/2.)-1)**2)**0.5 < 1, (w, h))
# reshape to match array axes
if axes[0] > axes[1]:
mask = mask.T
shape = [(n if i in axes else 1) for i,n in enumerate(arr.shape)]
mask = mask.reshape(shape)
return arr * mask
def score(self, match):
"""
Return the one bond scoring matrix
Parameters:
-----------
match: array
match_matrix
Returns:
--------
score_matrix
"""
score_matrix = -settings.bond_weight * np.fromfunction(self.evaluate_score_matrix_vect, match.shape, match=match, dtype=int)
return score_matrix
def __call__(self, inputs,target):
applied_angle = random.uniform(-self.angle,self.angle)
diff = random.uniform(-self.diff_angle,self.diff_angle)
angle1 = applied_angle - diff/2
angle2 = applied_angle + diff/2
angle1_rad = angle1*np.pi/180
h, w, _ = target.shape
def rotate_flow(i,j,k):
return -k*(j-w/2)*(diff*np.pi/180) + (1-k)*(i-h/2)*(diff*np.pi/180)
rotate_flow_map = np.fromfunction(rotate_flow, target.shape)
target += rotate_flow_map
inputs[0] = ndimage.interpolation.rotate(inputs[0], angle1, reshape=self.reshape, order=self.order)
inputs[1] = ndimage.interpolation.rotate(inputs[1], angle2, reshape=self.reshape, order=self.order)
target = ndimage.interpolation.rotate(target, angle1, reshape=self.reshape, order=self.order)
# flow vectors must be rotated too! careful about Y flow which is upside down
target_ = np.copy(target)
target[:,:,0] = np.cos(angle1_rad)*target_[:,:,0] + np.sin(angle1_rad)*target_[:,:,1]
target[:,:,1] = -np.sin(angle1_rad)*target_[:,:,0] + np.cos(angle1_rad)*target_[:,:,1]
return inputs,target
def depthMap(self, midpointdepth=None, pose=None):
shape = self.opts['shape']
if pose is None:
pose = self.pose()
t, r = pose
n = self.planeSfN(r)
# z component from plane-equation solved for z:
zpart = np.fromfunction(lambda y, x: (-n[0] * x
- n[1] * y) / (
-n[2]), shape)
ox, oy = self.objCenter()
v = zpart[int(oy), int(ox)]
if midpointdepth is None:
# TODO: review
midpointdepth = t[2, 0]
zpart += midpointdepth - v
return zpart
def getArrayRegion(self, arr, img=None):
"""
Return the result of ROI.getArrayRegion() masked by the elliptical shape
of the ROI. Regions outside the ellipse are set to 0.
"""
# TODO: get right area for pseudosquare
arr = pg.ROI.getArrayRegion(self, arr, img)
if arr is None or arr.shape[0] == 0 or arr.shape[1] == 0:
return None
w = arr.shape[0]
h = arr.shape[1]
# generate an ellipsoidal mask
mask = np.fromfunction(lambda x,y: ((((x+0.5)/((w/2.)))-1)**2+ (
((y+0.5)/((h/2.)))-1)**2)**0.5 < self._ratioEllispeRectangle, (w, h))
return arr * mask
def _shape(self,img):
"""
??????????????
:param img:
:return: ????
"""
operator1 = np.fromfunction(self._gauss, (5, 5), sigma=self._sigma)
operator2 = np.array([[1, 1, 1],
[1,-8, 1],
[1, 1, 1]])
image_blur = signal.convolve2d(img, operator1, mode="same")
# ?????????????
image2 = signal.convolve2d(image_blur, operator2, mode="same")
if image2.max() != 0:
image2 = (image2 / float(image2.max())) * 255
else:
image2 = np.zeros(image2.shape)
# ??????????????255???????????
image2[image2>image2.mean()] = 255
# ?????????????
image2[image2 <=image2.mean()] =0
return image2
def approx_state_value_eval(env, policy,
discount=0.999, learning_rate=0.01,
n_iter=1000, print_every=None):
state_values = LinearApproximator(lambda x: x, env.observation_space.shape[0])
for episode in range(n_iter):
visited_states, rewards = MonteCarlo._run_episode(env, policy, with_actions=False)
for i, state in enumerate(visited_states):
if i + 1 >= len(rewards):
break
discounted_return_from_state = \
np.dot(np.array(rewards[i + 1:]),
np.fromfunction(lambda i: discount ** i, (len(rewards) - i - 1, )))
update = (discounted_return_from_state
- state_values.state_value(state)) * state_values.grad(state)
state_values.update_w(update, learning_rate)
if print_every is not None and episode % print_every == 0:
print('State-Value estimation:\n{}'.format(
[(s, state_values.state_value(s)) for s in visited_states[:10]]
))
return state_values
def action_value_eval(env, policy,
discount=0.999, learning_rate=0.01,
n_iter=1000, print_every=None):
action_values = [[0.0 for _ in range(env.action_space.n)] for _ in range(env.state_space.n)]
for episode in range(n_iter):
visited_state_action_pairs, rewards = MonteCarlo._run_episode(env, policy, with_actions=True)
for i, (state, action) in enumerate(visited_state_action_pairs):
if i + 1 >= len(rewards):
break
discounted_return_from_state = \
np.dot(np.array(rewards[i + 1:]),
np.fromfunction(lambda i: discount ** i, ((len(rewards) - i - 1),)))
action_values[state][action] += \
learning_rate * (discounted_return_from_state - action_values[state][action])
if print_every is not None and episode % print_every == 0:
print('Action-Value estimation:\n{}'.format(action_values))
return action_values
def __init__(self, table=None, filename=''):
"""
table: the pandas DataFrame that records rankable objects competition
record
filename: the hdf5 filename that stores the DataFrame. The DataFrame
must be indexed by 'item_pair_rate'.
"""
if table is None:
table = pd.read_hdf(filename, "item_pair_rate")
table = table[['primary','secondary','rate1','rate2','weight']]
self.table = table
# itemid to index table
idx = self._extract_list(self.table)
self.itemlist = idx
temptable = table.iloc[:,:2].values
pair = np.fromfunction(np.vectorize(lambda i, j: idx[temptable[i,j]]),
temptable.shape)
pair = np.require(pair, dtype=np.int32)
self.pair = pair
def add_gauss_noise(image,r=10):
suanzi = np.fromfunction(func, (r, r), sigma=5)
image = np.array(image)
image2 = signal.convolve2d(image, suanzi, mode="same")
image2 = (image2 / float(image2.max())) * 255
return np.array(image2)
def add_gauss_noise(image,r=10):
suanzi = np.fromfunction(func, (r, r), sigma=5)
image = np.array(image)
image2 = signal.convolve2d(image, suanzi, mode="same")
image2 = (image2 / float(image2.max())) * 255
return np.array(image2)
def initializeGL(self):
## Generate texture for rendering points
w = 64
def fn(x,y):
r = ((x-w/2.)**2 + (y-w/2.)**2) ** 0.5
return 255 * (w/2. - np.clip(r, w/2.-1.0, w/2.))
pData = np.empty((w, w, 4))
pData[:] = 255
pData[:,:,3] = np.fromfunction(fn, pData.shape[:2])
#print pData.shape, pData.min(), pData.max()
pData = pData.astype(np.ubyte)
if getattr(self, "pointTexture", None) is None:
self.pointTexture = glGenTextures(1)
glActiveTexture(GL_TEXTURE0)
glEnable(GL_TEXTURE_2D)
glBindTexture(GL_TEXTURE_2D, self.pointTexture)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, pData.shape[0], pData.shape[1], 0, GL_RGBA, GL_UNSIGNED_BYTE, pData)
self.shader = shaders.getShaderProgram('pointSprite')
#def getVBO(self, name):
#if name not in self.vbo:
#self.vbo[name] = vbo.VBO(getattr(self, name).astype('f'))
#return self.vbo[name]
#def setupGLState(self):
#"""Prepare OpenGL state for drawing. This function is called immediately before painting."""
##glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ## requires z-sorting to render properly.
#glBlendFunc(GL_SRC_ALPHA, GL_ONE)
#glEnable( GL_BLEND )
#glEnable( GL_ALPHA_TEST )
#glDisable( GL_DEPTH_TEST )
##glEnable( GL_POINT_SMOOTH )
##glHint(GL_POINT_SMOOTH_HINT, GL_NICEST)
##glPointParameterfv(GL_POINT_DISTANCE_ATTENUATION, (0, 0, -1e-3))
##glPointParameterfv(GL_POINT_SIZE_MAX, (65500,))
##glPointParameterfv(GL_POINT_SIZE_MIN, (0,))
def initializeGL(self):
## Generate texture for rendering points
w = 64
def fn(x,y):
r = ((x-w/2.)**2 + (y-w/2.)**2) ** 0.5
return 255 * (w/2. - np.clip(r, w/2.-1.0, w/2.))
pData = np.empty((w, w, 4))
pData[:] = 255
pData[:,:,3] = np.fromfunction(fn, pData.shape[:2])
#print pData.shape, pData.min(), pData.max()
pData = pData.astype(np.ubyte)
if getattr(self, "pointTexture", None) is None:
self.pointTexture = glGenTextures(1)
glActiveTexture(GL_TEXTURE0)
glEnable(GL_TEXTURE_2D)
glBindTexture(GL_TEXTURE_2D, self.pointTexture)
glTexImage2D(GL_TEXTURE_2D, 0, GL_RGBA, pData.shape[0], pData.shape[1], 0, GL_RGBA, GL_UNSIGNED_BYTE, pData)
self.shader = shaders.getShaderProgram('pointSprite')
#def getVBO(self, name):
#if name not in self.vbo:
#self.vbo[name] = vbo.VBO(getattr(self, name).astype('f'))
#return self.vbo[name]
#def setupGLState(self):
#"""Prepare OpenGL state for drawing. This function is called immediately before painting."""
##glBlendFunc(GL_SRC_ALPHA, GL_ONE_MINUS_SRC_ALPHA) ## requires z-sorting to render properly.
#glBlendFunc(GL_SRC_ALPHA, GL_ONE)
#glEnable( GL_BLEND )
#glEnable( GL_ALPHA_TEST )
#glDisable( GL_DEPTH_TEST )
##glEnable( GL_POINT_SMOOTH )
##glHint(GL_POINT_SMOOTH_HINT, GL_NICEST)
##glPointParameterfv(GL_POINT_DISTANCE_ATTENUATION, (0, 0, -1e-3))
##glPointParameterfv(GL_POINT_SIZE_MAX, (65500,))
##glPointParameterfv(GL_POINT_SIZE_MIN, (0,))
def test_save_prediction(self):
model = RandomForestClassifier()
model.id = get_model_id(model)
model.fit(self.iris.data, self.iris.target)
indexes = np.fromfunction(lambda x: x, (self.iris.data.shape[0], ), dtype=np.int32)
saving_predict_proba(model, self.iris.data, indexes)
os.remove('RandomForestClassifier_r0_N__m5_2__m4_1__m6_0p0__m1_auto__m0_N__m3_1e-07__m2_N__n0_10__b0_1__c1_gini__c0_N_190.csv')
def test_getitem_with_slice_from_2D_functional_array_2():
def test_function(i, j):
return i * i + 2 * i * j + 3
m = larray(test_function, shape=(3, 15))
assert_array_equal(m[:, 3:14:3],
numpy.fromfunction(test_function, shape=(3, 15))[:, 3:14:3])
def test_getitem_from_array_with_operations():
a1 = numpy.array([[1, 3, 5], [7, 9, 11]])
m1 = larray(a1)
f = lambda i, j: numpy.sqrt(i * i + j * j)
a2 = numpy.fromfunction(f, shape=(2, 3))
m2 = larray(f, shape=(2, 3))
a3 = 3 * a1 + a2
m3 = 3 * m1 + m2
assert_array_equal(a3[:, (0, 2)],
m3[:, (0, 2)])
def array_from_function_full(f, shape):
return np.fromfunction(f, shape)
def array_from_function_slice(f, shape):
return np.fromfunction(f, shape)[:, 0:-1:10]
def createpolygonmovie(coordfile, moviefile, background=None, xrange=(0,1), yrange=(0,1), shape=(500,500), rate=24):
# read the coordinates
polygons = np.loadtxt(os.path.expanduser(coordfile))
# open the movie file
movie = MovieFile(moviefile, shape=shape, rate=rate)
# setup the figure and its background
figure = plt.figure(1, dpi=100, figsize=(shape[0]/100.,shape[1]/100.))
x0,x1 = xrange
y0,y1 = yrange
px,py = shape
if background != None:
# transpose and scale i,j indices to x,y values
backim = np.fromfunction(lambda i,j: background((j+0.5)/px*(x1-x0)+x0,(i+0.5)/py*(y1-y0)+y0), shape[::-1])
plt.imshow(backim, origin='lower', aspect='auto', interpolation='bicubic', extent=(x0,x1,y0,y1))
plt.grid(True)
plt.xlim(xrange[0], xrange[1])
plt.ylim(yrange[0], yrange[1])
# for each line in the file, draw the polygon and add a movie frame
for p in polygons:
plt.plot(np.concatenate((p[0::2],p[0:1])), np.concatenate((p[1::2],p[1:2])), 'w-')
plt.draw() # flush the drawing
movie.add(figure.canvas.buffer_rgba(0,0)) # pass the pixel buffer on as movie frame
figure.axes[0].lines.pop() # remove the plotted line
# close things
plt.close()
movie.close()
# -----------------------------------------------------------------
def createpolygonmovie(coordfile, moviefile, background=None, xrange=(0,1), yrange=(0,1), shape=(500,500), rate=24):
# read the coordinates
polygons = np.loadtxt(os.path.expanduser(coordfile))
# open the movie file
movie = MovieFile(moviefile, shape=shape, rate=rate)
# setup the figure and its background
figure = plt.figure(1, dpi=100, figsize=(shape[0]/100.,shape[1]/100.))
x0,x1 = xrange
y0,y1 = yrange
px,py = shape
if background != None:
# transpose and scale i,j indices to x,y values
backim = np.fromfunction(lambda i,j: background((j+0.5)/px*(x1-x0)+x0,(i+0.5)/py*(y1-y0)+y0), shape[::-1])
plt.imshow(backim, origin='lower', aspect='auto', interpolation='bicubic', extent=(x0,x1,y0,y1))
plt.grid(True)
plt.xlim(xrange[0], xrange[1])
plt.ylim(yrange[0], yrange[1])
# for each line in the file, draw the polygon and add a movie frame
for p in polygons:
plt.plot(np.concatenate((p[0::2],p[0:1])), np.concatenate((p[1::2],p[1:2])), 'w-')
plt.draw() # flush the drawing
movie.add(figure.canvas.buffer_rgba(0,0)) # pass the pixel buffer on as movie frame
figure.axes[0].lines.pop() # remove the plotted line
# close things
plt.close()
movie.close()
# -----------------------------------------------------------------
def growPositions(ksize):
'''
return all positions around central point (0,0)
for a given kernel size
positions grow from smallest to biggest distances
returns [positions] and [distances] from central cell
'''
i = ksize*2+1
kk = np.ones( (i, i), dtype=bool)
x,y = np.where(kk)
pos = np.empty(shape=(i,i,2), dtype=int)
pos[:,:,0]=x.reshape(i,i)-ksize
pos[:,:,1]=y.reshape(i,i)-ksize
dist = np.fromfunction(lambda x,y: ((x-ksize)**2
+(y-ksize)**2)**0.5, (i,i))
pos = np.dstack(
np.unravel_index(
np.argsort(dist.ravel()), (i, i)))[0,1:]
pos0 = pos[:,0]
pos1 = pos[:,1]
return pos-ksize, dist[pos0, pos1]
def cam2PlaneVectorField(self, midpointdepth=None, **kwargs):
t, r = self.pose()
shape = self.opts['shape']
cam = self.opts['cameraMatrix']
# move reference point from top left quad corner to
# optical center:
# q0 = self.quad[0]
q0 = self.objCenter()
# dx,dy = cam[0,2]-q0[0], cam[1,2]-q0[1]
dx, dy = shape[1] // 2 - q0[0], shape[0] // 2 - q0[1]
# x,y component of undist plane:
rot0 = np.array([0, 0, 0], dtype=float)
worldCoord = np.fromfunction(lambda x, y:
imgPointToWorldCoord((y - dy, x - dx), rot0, t, cam
), shape).reshape(3, *shape)
# z component from plane-equation solved for z:
n = self.planeSfN(r)
x, y = worldCoord[:2]
zpart = (-n[0] * x - n[1] * y) / (-n[2])
ox, oy = self.objCenter()
v = zpart[int(oy), int(ox)]
if midpointdepth is None:
# TODO: review
midpointdepth = t[2, 0]
zpart += midpointdepth - v
worldCoord[2] = zpart
return worldCoord
# BEFORE REMOVING THINGS: MAKE EXTRA FN
def get_n_step_expected_rewards_mat(episode_rewards, estimates, discount=.99, n_step=1):
expected_reward = [0] * len(episode_rewards)
rewards_coef = np.fromfunction(lambda i,j: discount**(i-j) * (i >= j) * (i - j < n_step), (len(episode_rewards), len(episode_rewards)))
permut = np.fromfunction(lambda i,j: (i > j + n_step) * (i <= j + n_step), (len(episode_rewards), len(episode_rewards)))
return np.dot(episode_rewards, rewards_coef) + discount**(n_step) * np.dot(estimates, permut)
def bool_ops(self):
"""Allows the user to write mathmatical definitions for solids and use boolian operations on them."""
x = np.zeros((self.matrix_size, self.matrix_size, self.matrix_size))
v = np.fromfunction(self.test_solid, (self.matrix_size, self.matrix_size, self.matrix_size))
v = x + v
v = np.lib.pad(v, ((1,1),(1,1),(1,1)), 'constant') #This padds the z axis with zero's arrays so that a closed shape is produced by marching cubes.
return v
def parse_data(data):
"""
Transform ``data`` to a numpy ndarray. The parameter ``data`` may
contain data in various formats, e.g. nested lists, sympy ``Matrix``,
and so on.
Examples
========
>>> from sympy.tensor.tensor import _TensorDataLazyEvaluator
>>> _TensorDataLazyEvaluator.parse_data([1, 3, -6, 12])
[1 3 -6 12]
>>> _TensorDataLazyEvaluator.parse_data([[1, 2], [4, 7]])
[[1 2]
[4 7]]
"""
numpy = import_module('numpy')
if (numpy is not None) and (not isinstance(data, numpy.ndarray)):
if len(data) == 2 and hasattr(data[0], '__call__'):
def fromfunction_sympify(*x):
return sympify(data[0](*x))
data = numpy.fromfunction(fromfunction_sympify, data[1])
else:
vsympify = numpy.vectorize(sympify)
data = vsympify(numpy.array(data))
return data
def state_value_eval(env, policy,
discount=0.999,
learning_rate=0.01,
n_iter=1000,
print_every=None):
"""
This is EVERY-VISIT Monte-Carlo
:param env: An Environment that we can reset(), step() and get observations and
reward information.
:param policy: A strategy for behaving in an Environment. Should have a step()
method that returns an action given state information.
:param discount: Discount factor for the MDP
:param learning_rate: The amount we will shift towards an error direction.
:param n_iter: Number of episodes to run this algorithm for
:param print_every: Print the current estimate of values every X iterations
:return: The State-Value function that shows the average return we'll have starting
in each one of the states of this MDP
"""
state_values = [0.0 for _ in range(env.state_space.n)]
for episode in range(n_iter):
visited_states, rewards = MonteCarlo._run_episode(env, policy, with_actions=False)
for i, state in enumerate(visited_states):
if i + 1 >= len(rewards):
break
discounted_return_from_state = \
np.dot(np.array(rewards[i + 1:]),
np.fromfunction(lambda i: discount ** i, ((len(rewards) - i - 1),)))
state_values[state] += \
learning_rate * (discounted_return_from_state - state_values[state])
if print_every is not None and episode % print_every == 0:
print('State-Value estimation:\n{}'.format(state_values))
return state_values
def __call__(self, inputs,target):
applied_angle = random.uniform(-self.angle,self.angle)
diff = random.uniform(-self.diff_angle,self.diff_angle)
angle1 = applied_angle - diff/2
angle2 = applied_angle + diff/2
angle1_rad = angle1*np.pi/180
angle2_rad = angle2*np.pi/180
h, w, _ = inputs[0].shape
def rotate_flow(i,j,k):
return -k*(j-w/2)*(diff*np.pi/180) + (1-k)*(i-h/2)*(diff*np.pi/180)
rotate_flow_map = np.fromfunction(rotate_flow, target.shape)
target += rotate_flow_map
inputs[0] = ndimage.interpolation.rotate(inputs[0], angle1, reshape=True, order=self.order)
inputs[1] = ndimage.interpolation.rotate(inputs[1], angle2, reshape=True, order=self.order)
target = ndimage.interpolation.rotate(target, angle1, reshape=True, order=self.order)
#flow vectors must be rotated too!
target_=np.array(target, copy=True)
target[:,:,0] = np.cos(angle1_rad)*target_[:,:,0] - np.sin(angle1_rad)*target_[:,:,1]
target[:,:,1] = np.sin(angle1_rad)*target_[:,:,0] + np.cos(angle1_rad)*target_[:,:,1]
#keep angle1 and angle2 within [0,pi/2] with a reflection at pi/2: -1rad is 1rad, 2rad is pi - 2 rad
angle1_rad = np.pi/2 - np.abs(angle1_rad%np.pi - np.pi/2)
angle2_rad = np.pi/2 - np.abs(angle2_rad%np.pi - np.pi/2)
c1 = np.cos(angle1_rad)
s1 = np.sin(angle1_rad)
c2 = np.cos(angle2_rad)
s2 = np.sin(angle2_rad)
c_diag = h/np.sqrt(h*h+w*w)
s_diag = w/np.sqrt(h*h+w*w)
ratio = c_diag/max(c1*c_diag+s1*s_diag,c2*c_diag+s2*s_diag)
crop = CenterCrop((int(h*ratio),int(w*ratio)))
scale = Scale(self.size)
inputs, target = crop(inputs, target)
return scale(inputs,target)
def asanyarray(a, dtype=None, order=None):
"""Convert the input to an ndarray, but pass ndarray subclasses through.
Parameters
----------
a : array_like
Input data, in any form that can be converted to an array. This
includes scalars, lists, lists of tuples, tuples, tuples of tuples,
tuples of lists, and ndarrays.
dtype : data-type, optional
By default, the data-type is inferred from the input data.
order : {'C', 'F'}, optional
Whether to use row-major (C-style) or column-major
(Fortran-style) memory representation. Defaults to 'C'.
Returns
-------
out : ndarray or an ndarray subclass
Array interpretation of `a`. If `a` is an ndarray or a subclass
of ndarray, it is returned as-is and no copy is performed.
See Also
--------
asarray : Similar function which always returns ndarrays.
ascontiguousarray : Convert input to a contiguous array.
asfarray : Convert input to a floating point ndarray.
asfortranarray : Convert input to an ndarray with column-major
memory order.
asarray_chkfinite : Similar function which checks input for NaNs and
Infs.
fromiter : Create an array from an iterator.
fromfunction : Construct an array by executing a function on grid
positions.
Examples
--------
Convert a list into an array:
>>> a = [1, 2]
>>> np.asanyarray(a)
array([1, 2])
Instances of `ndarray` subclasses are passed through as-is:
>>> a = np.matrix([1, 2])
>>> np.asanyarray(a) is a
True
"""
return array(a, dtype, copy=False, order=order, subok=True)
def fromfunction(function, shape, **kwargs):
"""
Construct an array by executing a function over each coordinate.
The resulting array therefore has a value ``fn(x, y, z)`` at
coordinate ``(x, y, z)``.
Parameters
----------
function : callable
The function is called with N parameters, where N is the rank of
`shape`. Each parameter represents the coordinates of the array
varying along a specific axis. For example, if `shape`
were ``(2, 2)``, then the parameters in turn be (0, 0), (0, 1),
(1, 0), (1, 1).
shape : (N,) tuple of ints
Shape of the output array, which also determines the shape of
the coordinate arrays passed to `function`.
dtype : data-type, optional
Data-type of the coordinate arrays passed to `function`.
By default, `dtype` is float.
Returns
-------
fromfunction : any
The result of the call to `function` is passed back directly.
Therefore the shape of `fromfunction` is completely determined by
`function`. If `function` returns a scalar value, the shape of
`fromfunction` would match the `shape` parameter.
See Also
--------
indices, meshgrid
Notes
-----
Keywords other than `dtype` are passed to `function`.
Examples
--------
>>> np.fromfunction(lambda i, j: i == j, (3, 3), dtype=int)
array([[ True, False, False],
[False, True, False],
[False, False, True]], dtype=bool)
>>> np.fromfunction(lambda i, j: i + j, (3, 3), dtype=int)
array([[0, 1, 2],
[1, 2, 3],
[2, 3, 4]])
"""
dtype = kwargs.pop('dtype', float)
args = indices(shape, dtype=dtype)
return function(*args, **kwargs)