# Python numpy.vectorize() Examples

The following are 30 code examples for showing how to use numpy.vectorize(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module , or try the search function .

Example 1
```def test_static_nonlinearity(self):
# Linear dynamical system
linsys = self.siso_linsys
ioslin = ios.LinearIOSystem(linsys)

# Nonlinear saturation
sat = lambda u: u if abs(u) < 1 else np.sign(u)
sat_output = lambda t, x, u, params: sat(u)
nlsat =  ios.NonlinearIOSystem(None, sat_output, inputs=1, outputs=1)

# Set up parameters for simulation
T, U, X0 = self.T, 2 * self.U, self.X0
Usat = np.vectorize(sat)(U)

# Make sure saturation works properly by comparing linear system with
# saturated input to nonlinear system with saturation composition
lti_t, lti_y, lti_x = ct.forced_response(linsys, T, Usat, X0)
ios_t, ios_y, ios_x = ios.input_output_response(
ioslin * nlsat, T, U, X0, return_x=True)
np.testing.assert_array_almost_equal(lti_t, ios_t)
np.testing.assert_array_almost_equal(lti_y, ios_y, decimal=2) ```
Example 2
```def test_keywords2_ticket_2100(self):
# Test kwarg support: enhancement ticket 2100

def foo(a, b=1):
return a + b

f = vectorize(foo)
args = np.array([1, 2, 3])
r1 = f(a=args)
r2 = np.array([2, 3, 4])
assert_array_equal(r1, r2)
r1 = f(b=1, a=args)
assert_array_equal(r1, r2)
r1 = f(args, b=2)
r2 = np.array([3, 4, 5])
assert_array_equal(r1, r2) ```
Example 3
```def dict_lookup(dict_, keys, default=None):
"""Looks up :attr:`keys` in the dict, returns the corresponding values.

The :attr:`default` is used for keys not present in the dict.

Args:
dict_ (dict): A dictionary for lookup.
keys: A numpy array or a (possibly nested) list of keys.
default (optional): Value to be returned when a key is not in
:attr:`dict_`. Error is raised if :attr:`default` is not given and
key is not in the dict.

Returns:
A numpy array of values with the same structure as :attr:`keys`.

Raises:
TypeError: If key is not in :attr:`dict_` and :attr:`default` is `None`.
"""
return np.vectorize(lambda x: dict_.get(x, default))(keys) ```
Example 4
```def xindex(array, row_num, col_num=None, area_num=1):
is_reference = isinstance(array, Ranges)
if is_reference:
arrays = [Ranges((rng,), array.values).value for rng in array.ranges]
else:
arrays = [array]

row_num, col_num, area_num = parse_ranges(row_num, col_num, area_num)[0]

res = np.vectorize(_index, excluded={0}, otypes=[object])(
arrays, row_num, col_num, area_num, is_reference,
isinstance(row_num, np.ndarray)
)
if not res.shape:
res = res.reshape(1, 1)
return res.view(Array) ```
Example 5
```def testRelativePositionalEmbeddingLayer(self):
with self.session(use_gpu=False):
p = layers.RelativePositionalEmbeddingLayer.Params().Set(
layer = p.Instantiate()
indices = np.array([-5, -2, 0, 1, 4], dtype=np.int32)
pos_emb = layer.FPropDefaultTheta(tf.convert_to_tensor(indices))

self.evaluate(tf.global_variables_initializer())
actual_pos_emb, full_emb = self.evaluate([pos_emb, layer.vars.w])

expected_output = np.take_along_axis(full_emb,
np.expand_dims(clipped_indices, -1),
0)
print('expected_position_embs:', expected_output)
print('actual_position_embs:', actual_pos_emb)
self.assertAllClose(actual_pos_emb, expected_output) ```
Example 6
```def plot3d(self, scale=0.32):
r"""Plot 3d scatter plot of benchmark function.

Args:
scale (float): Scale factor for points.
"""
fig = plt.figure()
ax = Axes3D(fig)
func = self.function()
Xr, Yr = arange(self.Lower, self.Upper, scale), arange(self.Lower, self.Upper, scale)
X, Y = meshgrid(Xr, Yr)
Z = vectorize(self.__2dfun)(X, Y, func)
ax.plot_surface(X, Y, Z, rstride=8, cstride=8, alpha=0.3)
ax.contourf(X, Y, Z, zdir='z', offset=-10, cmap=cm.coolwarm)
ax.set_xlabel('X')
ax.set_ylabel('Y')
ax.set_zlabel('Z')
plt.show()

# vim: tabstop=3 noexpandtab shiftwidth=3 softtabstop=3 ```
Example 7
```def _munp(self, n, beta, m):
"""
Returns the n-th non-central moment of the crystalball function.
"""
N = 1.0 / (m/beta / (m-1) * np.exp(-beta**2 / 2.0) + _norm_pdf_C * _norm_cdf(beta))

def n_th_moment(n, beta, m):
"""
Returns n-th moment. Defined only if n+1 < m
Function cannot broadcast due to the loop over n
"""
A = (m/beta)**m * np.exp(-beta**2 / 2.0)
B = m/beta - beta
rhs = 2**((n-1)/2.0) * sc.gamma((n+1)/2) * (1.0 + (-1)**n * sc.gammainc((n+1)/2, beta**2 / 2))
lhs = np.zeros(rhs.shape)
for k in range(n + 1):
lhs += sc.binom(n, k) * B**(n-k) * (-1)**k / (m - k - 1) * (m/beta)**(-m + k + 1)
return A * lhs + rhs

return N * _lazywhere(np.atleast_1d(n + 1 < m),
(n, beta, m),
np.vectorize(n_th_moment, otypes=[np.float]),
np.inf) ```
Example 8
```def get_forces(self):
# Return the force vector for the problem
topx_to_id = np.vectorize(
lambda x: xy_to_id(x, 0, self.nelx, self.nely))
topx = 2 * topx_to_id(np.arange((self.nelx + 1) // 2)) + 1
f = np.zeros((2 * (self.nelx + 1) * (self.nely + 1), 1))
f[topx, 0] = -100
return f ```
Example 9
```def get_forces(self):
# Return the force vector for the problem
topx_to_id = np.vectorize(
lambda x: xy_to_id(x, 0, self.nelx, self.nely))
topx = 2 * topx_to_id(np.arange((self.nelx + 1) // 2)) + 1
f = np.zeros((2 * (self.nelx + 1) * (self.nely + 1), 1))
f[topx, 0] = -100
return f ```
Example 10
```def get_fixed_nodes(self):
""" Return a list of fixed nodes for the problem. """
x = np.arange(self.passive_min_x)
topx_to_id = np.vectorize(
lambda x: xy_to_id(x, 0, self.nelx, self.nely))
ids = topx_to_id(x)
fixed = np.union1d(2 * ids, 2 * ids + 1)
return fixed ```
Example 11
```def get_passive_elements(self):
X, Y = np.mgrid[self.passive_min_x:self.passive_max_x + 1,
self.passive_min_y:self.passive_max_y]
pairs = np.vstack([X.ravel(), Y.ravel()]).T
passive_to_ids = np.vectorize(lambda pair: xy_to_id(*pair,
nelx=self.nelx - 1, nely=self.nely - 1), signature="(m)->()")
return passive_to_ids(pairs) ```
Example 12
```def __getitem__(self, index):
raw_data = np.fromfile(self.im_idx[index], dtype=np.float32).reshape((-1, 4))
if self.imageset == 'test':
annotated_data = np.expand_dims(np.zeros_like(raw_data[:,0],dtype=int),axis=1)
else:
annotated_data = np.fromfile(self.im_idx[index].replace('velodyne','labels')[:-3]+'label', dtype=np.int32).reshape((-1,1))
annotated_data = annotated_data & 0xFFFF #delete high 16 digits binary
annotated_data = np.vectorize(self.learning_map.__getitem__)(annotated_data)
data_tuple = (raw_data[:,:3], annotated_data.astype(np.uint8))
if self.return_ref:
data_tuple += (raw_data[:,3],)
return data_tuple ```
Example 13
```def getTransform(img, pc, s, m_p, mean_m):
z = np.copy(img)
p, m = getLandmarks(img, pc, m_p)

#using img, p, m, s, mean_m get the normalized image
p_1, p_2 = p[0], p[1]
s_1, s_2 = s[0], s[1]

#histogram values at locations (pc + landmarks)
m = [p_1] + list(m) + [p_2]
#map scale corresponding to these values
mean_m = [s_1] + list(mean_m) + [s_2]
new_img = np.zeros_like(img, dtype=np.int64)
hist_indices = np.zeros_like(img, dtype=np.int64)

hist_indices = np.copy(new_img)

for m_ in m:
hist_indices += (img > m_).astype(int)

hist_indices = np.clip(hist_indices, 1, len(m) - 1, out=hist_indices)

indexer_m = lambda v: m[v]
indexer_mm = lambda v: mean_m[v]
f_m = np.vectorize(indexer_m)
f_mm = np.vectorize(indexer_mm)

new_p_1 = f_m(hist_indices - 1)
new_p_2 = f_m(hist_indices)
new_s_1 = f_mm(hist_indices - 1)
new_s_2 = f_mm(hist_indices)

new_img = mapLandmarksVec([new_p_1, new_p_2], [new_s_1, new_s_2], img)

new_img = np.clip(new_img, s_1-1, s_2+1, out=new_img)

return new_img

################################################################## ```
Example 14
```def calc_EVPOC(self):
Comp = self.Completeness

bins = 1000
# xedges is array of separation values for interpolant
xedges = np.linspace(0., Comp.PlanetPopulation.rrange[1].value, bins)*\
Comp.PlanetPopulation.arange.unit
xedges = xedges.to('AU').value

# yedges is array of delta magnitude values for interpolant
ymin = np.round(-2.5*np.log10(float(Comp.PlanetPopulation.prange[1]*\
Comp.PlanetPopulation.Rprange[1]/Comp.PlanetPopulation.rrange[0])**2))
ymax = np.round(-2.5*np.log10(float(Comp.PlanetPopulation.prange[0]*\
Comp.PlanetPopulation.Rprange[0]/Comp.PlanetPopulation.rrange[1])**2*1e-11))
yedges = np.linspace(ymin, ymax, bins)

# number of planets for each Monte Carlo simulation
nplan = int(np.min([1e6,Comp.Nplanets]))
# number of simulations to perform (must be integer)
steps = int(Comp.Nplanets/nplan)

Cpath = os.path.join(Comp.classpath, Comp.filename+'.comp')
H, xedges, yedges = self.genC(Cpath, nplan, xedges, yedges, steps)
EVPOCpdf = interpolate.RectBivariateSpline(xedges, yedges, H.T)
EVPOC = np.vectorize(EVPOCpdf.integral)

self.EVPOC = EVPOC ```
Example 15
```def predict_proba(self, X):
f = np.vectorize(self._platt_func)
raw_predictions = self.decision_function(X)
platt_predictions = f(raw_predictions).reshape(-1, 1)
prob_positive = platt_predictions / platt_predictions.sum(axis=1)[:, None]
prob_negative = 1.0 - prob_positive
probabilities = np.hstack([prob_negative, prob_positive])
return probabilities ```
Example 16
```def dcg(true_order_relevance, validate_order, top_values=10):
# retrieve relevance score for each value in validation order
relevance = np.vectorize(lambda x: true_order_relevance.get(x, 0))(
validate_order[:top_values]
)
gain = 2 ** relevance - 1
discount = np.log2(np.arange(1, len(gain) + 1) + 1)
sum_dcg = np.sum(gain / discount)
return sum_dcg

# TODO: remove this and replace with current contrib method once azureml-contrib-explain-model moved to release ```
Example 17
```def testExpandCoefficients(self):
for _ in range(10):
num_variables = np.random.randint(1, 4)
degrees = np.random.randint(0, 4, [num_variables])
coefficients = np.random.randint(-3, 3, degrees + 1)
entropy = np.random.uniform(0, 10)
expanded = polynomials.expand_coefficients(coefficients, entropy)
collapsed = np.vectorize(sum)(expanded)
self.assertAllEqual(coefficients, collapsed) ```
Example 18
```def generate_csv_data(func, output_csv_filename, x_range=(0, 1), N=500):
x_vec = np.linspace(x_range[0], x_range[1], N)
y_vec = np.vectorize(func)(x_vec)
with open(output_csv_filename, "w") as f:
writer = csv.writer(f)
field_names = ["x1", "y"]
writer.writerow(field_names)
for (x, y) in zip(x_vec, y_vec):
field_values = [x, y]
writer.writerow(field_values) ```
Example 19
```def test_simple(self):
if a > b:
return a - b
else:
return a + b

r = f([0, 3, 6, 9], [1, 3, 5, 7])
assert_array_equal(r, [1, 6, 1, 2]) ```
Example 20
```def test_scalar(self):
if a > b:
return a - b
else:
return a + b

r = f([0, 3, 6, 9], 5)
assert_array_equal(r, [5, 8, 1, 4]) ```
Example 21
```def test_large(self):
x = np.linspace(-3, 2, 10000)
f = vectorize(lambda x: x)
y = f(x)
assert_array_equal(y, x) ```
Example 22
```def test_ufunc(self):
import math
f = vectorize(math.cos)
args = np.array([0, 0.5 * np.pi, np.pi, 1.5 * np.pi, 2 * np.pi])
r1 = f(args)
r2 = np.cos(args)
assert_array_almost_equal(r1, r2) ```
Example 23
```def test_keywords(self):

def foo(a, b=1):
return a + b

f = vectorize(foo)
args = np.array([1, 2, 3])
r1 = f(args)
r2 = np.array([2, 3, 4])
assert_array_equal(r1, r2)
r1 = f(args, 2)
r2 = np.array([3, 4, 5])
assert_array_equal(r1, r2) ```
Example 24
```def test_keywords3_ticket_2100(self):
# Test excluded with mixed positional and kwargs: ticket 2100
def mypolyval(x, p):
_p = list(p)
res = _p.pop(0)
while _p:
res = res * x + _p.pop(0)
return res

vpolyval = np.vectorize(mypolyval, excluded=['p', 1])
ans = [3, 6]
assert_array_equal(ans, vpolyval(x=[0, 1], p=[1, 2, 3]))
assert_array_equal(ans, vpolyval([0, 1], p=[1, 2, 3]))
assert_array_equal(ans, vpolyval([0, 1], [1, 2, 3])) ```
Example 25
```def test_keywords4_ticket_2100(self):
# Test vectorizing function with no positional args.
@vectorize
def f(**kw):
res = 1.0
for _k in kw:
res *= kw[_k]
return res

assert_array_equal(f(a=[1, 2], b=[3, 4]), [3, 8]) ```
Example 26
```def test_keywords5_ticket_2100(self):
# Test vectorizing function with no kwargs args.
@vectorize
def f(*v):
return np.prod(v)

assert_array_equal(f([1, 2], [3, 4]), [3, 8]) ```
Example 27
```def test_coverage1_ticket_2100(self):
def foo():
return 1

f = vectorize(foo)
assert_array_equal(f(), 1) ```
Example 28
```def test_UnboundMethod_ticket_1156(self):
# Regression test for issue 1156
class Foo:
b = 2

def bar(self, a):
return a ** self.b

assert_array_equal(vectorize(Foo().bar)(np.arange(9)),
np.arange(9) ** 2)
assert_array_equal(vectorize(Foo.bar)(Foo(), np.arange(9)),
np.arange(9) ** 2) ```
Example 29
```def test_execution_order_ticket_1487(self):
# Regression test for dependence on execution order: issue 1487
f1 = vectorize(lambda x: x)
res1a = f1(np.arange(3))
res1b = f1(np.arange(0.1, 3))
f2 = vectorize(lambda x: x)
res2b = f2(np.arange(0.1, 3))
res2a = f2(np.arange(3))
assert_equal(res1a, res2a)
assert_equal(res1b, res2b) ```
Example 30
```def test_string_ticket_1892(self):