Python numpy.vectorize() Examples
The following are 30
code examples of numpy.vectorize().
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 also want to check out all available functions/classes of the module
numpy
, or try the search function
.
Example #1
Source File: iosys_test.py From python-control with BSD 3-Clause "New" or "Revised" License | 9 votes |
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
Source File: test_function_base.py From recruit with Apache License 2.0 | 7 votes |
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
Source File: utils.py From Counterfactual-StoryRW with MIT License | 7 votes |
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
Source File: layers_test.py From lingvo with Apache License 2.0 | 6 votes |
def testRelativePositionalEmbeddingLayer(self): with self.session(use_gpu=False): radius = 3 p = layers.RelativePositionalEmbeddingLayer.Params().Set( name='rel_position_emb', radius=radius, dim=4) 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]) clipped_indices = np.vectorize(lambda x: max(-radius, min(radius, x)))( indices) + radius 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 #5
Source File: benchmark.py From NiaPy with MIT License | 6 votes |
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 #6
Source File: look.py From formulas with European Union Public License 1.1 | 6 votes |
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 #7
Source File: _continuous_distns.py From lambda-packs with MIT License | 6 votes |
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
Source File: _discrete_distns.py From lambda-packs with MIT License | 5 votes |
def _rvs(self, low, high): """An array of *size* random integers >= ``low`` and < ``high``.""" if self._size is not None: # Numpy's RandomState.randint() doesn't broadcast its arguments. # Use `broadcast_to()` to extend the shapes of low and high # up to self._size. Then we can use the numpy.vectorize'd # randint without needing to pass it a `size` argument. low = broadcast_to(low, self._size) high = broadcast_to(high, self._size) randint = np.vectorize(self._random_state.randint, otypes=[np.int_]) return randint(low, high)
Example #9
Source File: autotune_advanced_notebook.py From scVI with MIT License | 5 votes |
def get_param_df(self): ddd = {} for i, trial in enumerate(self.trials): dd = {} dd["marginal_ll"] = trial["result"]["loss"] for item in trial["result"]["space"].values(): for key, value in item.items(): dd[key] = value ddd[i] = dd df_space = pd.DataFrame(ddd) df_space = df_space.T n_params_dataset = np.vectorize( partial(n_params, self.trainer.gene_dataset.nb_genes) ) df_space["n_params"] = n_params_dataset( df_space["n_layers"], df_space["n_hidden"], df_space["n_latent"] ) df_space = df_space[ [ "marginal_ll", "n_layers", "n_hidden", "n_latent", "reconstruction_loss", "dropout_rate", "lr", "n_epochs", "n_params", ] ] df_space = df_space.sort_values(by="marginal_ll") df_space["run index"] = df_space.index df_space.index = np.arange(1, df_space.shape[0] + 1) return df_space
Example #10
Source File: posterior_utils.py From scVI with MIT License | 5 votes |
def knn_purity(latent, label, n_neighbors=30): nbrs = NearestNeighbors(n_neighbors=n_neighbors + 1).fit(latent) indices = nbrs.kneighbors(latent, return_distance=False)[:, 1:] neighbors_labels = np.vectorize(lambda i: label[i])(indices) # pre cell purity scores scores = ((neighbors_labels - label.reshape(-1, 1)) == 0).mean(axis=1) res = [ np.mean(scores[label == i]) for i in np.unique(label) ] # per cell-type purity return np.mean(res)
Example #11
Source File: test_function_base.py From lambda-packs with MIT License | 5 votes |
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 #12
Source File: test_function_base.py From lambda-packs with MIT License | 5 votes |
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 #13
Source File: test_function_base.py From lambda-packs with MIT License | 5 votes |
def test_scalar(self): def addsubtract(a, b): if a > b: return a - b else: return a + b f = vectorize(addsubtract) r = f([0, 3, 6, 9], 5) assert_array_equal(r, [5, 8, 1, 4])
Example #14
Source File: test_function_base.py From lambda-packs with MIT License | 5 votes |
def test_large(self): x = np.linspace(-3, 2, 10000) f = vectorize(lambda x: x) y = f(x) assert_array_equal(y, x)
Example #15
Source File: test_function_base.py From lambda-packs with MIT License | 5 votes |
def test_keywords_no_func_code(self): # This needs to test a function that has keywords but # no func_code attribute, since otherwise vectorize will # inspect the func_code. import random try: vectorize(random.randrange) # Should succeed except: raise AssertionError()
Example #16
Source File: test_function_base.py From lambda-packs with MIT License | 5 votes |
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 #17
Source File: function_base.py From lambda-packs with MIT License | 5 votes |
def _create_arrays(broadcast_shape, dim_sizes, list_of_core_dims, dtypes): """Helper for creating output arrays in vectorize.""" shapes = _calculate_shapes(broadcast_shape, dim_sizes, list_of_core_dims) arrays = tuple(np.empty(shape, dtype=dtype) for shape, dtype in zip(shapes, dtypes)) return arrays
Example #18
Source File: math.py From formulas with European Union Public License 1.1 | 5 votes |
def xsumproduct(*args): # Check all arrays are the same length # Excel returns #VAlUE! error if they don't match raise_errors(args) assert len(set(arg.size for arg in args)) == 1 inputs = [] for a in args: a = a.ravel() x = np.zeros_like(a, float) b = np.vectorize(is_number)(a) x[b] = a[b] inputs.append(x) return np.sum(np.prod(inputs, axis=0))
Example #19
Source File: test_footprint_tile_occurrence.py From buzzard with Apache License 2.0 | 5 votes |
def assert_property_unique(src, tiles, size, occx, occy, boundary_effect_locus): tls = np.vectorize(operator.attrgetter('tl'), signature='()->(2)')(tiles.flatten()) assert np.unique(tls, axis=0).shape[0] == tiles.size
Example #20
Source File: test_footprint_tile_occurrence.py From buzzard with Apache License 2.0 | 5 votes |
def assert_property_tile_size(src, tiles, size, occx, occy, boundary_effect_locus): w = np.vectorize(operator.attrgetter('w'))(tiles.flatten()) assert np.unique(w).size == 1 h = np.vectorize(operator.attrgetter('h'))(tiles.flatten()) assert np.unique(h).size == 1
Example #21
Source File: test_footprint_tile_count.py From buzzard with Apache License 2.0 | 5 votes |
def assert_property_unique(fps, tiles, tx, ty, ox, oy, param2): tls = np.vectorize(operator.attrgetter('tl'), signature='()->(2)')(tiles.flatten()) assert np.unique(tls, axis=0).shape[0] == tiles.size
Example #22
Source File: test_footprint_tile_count.py From buzzard with Apache License 2.0 | 5 votes |
def assert_property_overlap(fps, tiles, tx, ty, ox, oy, param2): if param2 == 'br': stride = tiles[0, 0].rsize - (ox, oy) refptx, refpty = 'lx', 'ty' elif param2 == 'tl': stride = tiles[-1, -1].rsize - (ox, oy) refptx, refpty = 'rx', 'by' elif param2 == 'tr': stride = tiles[-1, 0].rsize - (ox, oy) refptx, refpty = 'lx', 'by' elif param2 == 'bl': stride = tiles[0, -1].rsize - (ox, oy) refptx, refpty = 'rx', 'ty' else: assert False refptx = operator.attrgetter(refptx) refpty = operator.attrgetter(refpty) if tiles.shape[0] > 1: diffs_vert = np.vectorize( lambda a, b: abs(refpty(a) - refpty(b)))( tiles[0:-1], tiles[1:]) assert (diffs_vert == stride[1]).all() if tiles.shape[1] > 1: diffs_horiz = np.vectorize( lambda a, b: abs(refptx(a) - refptx(b)))( tiles[:, 0:-1], tiles[:, 1:]) assert (diffs_horiz == stride[0]).all()
Example #23
Source File: test_footprint_tile_count.py From buzzard with Apache License 2.0 | 5 votes |
def assert_property_tile_size(fps, tiles, tx, ty, ox, oy, param2): w = np.vectorize(operator.attrgetter('w'))(tiles.flatten()) assert np.unique(w).size == 1 h = np.vectorize(operator.attrgetter('h'))(tiles.flatten()) assert np.unique(h).size == 1
Example #24
Source File: make_submission.py From kaggle-rcic-1st with MIT License | 5 votes |
def _assign_unique_in_plate(self, plate): preds = np.array(list(map(itemgetter(1), plate))) preds = np.vectorize(lambda x: x if x != -np.inf else -1e10)(preds) _, indices = linear_sum_assignment(-preds) return [(k, v.item()) for (k, _), v in zip(plate, indices)]
Example #25
Source File: test_conversion.py From recruit with Apache License 2.0 | 5 votes |
def _compare_utc_to_local(tz_didx): def f(x): return conversion.tz_convert_single(x, UTC, tz_didx.tz) result = conversion.tz_convert(tz_didx.asi8, UTC, tz_didx.tz) expected = np.vectorize(f)(tz_didx.asi8) tm.assert_numpy_array_equal(result, expected)
Example #26
Source File: function_base.py From recruit with Apache License 2.0 | 5 votes |
def _create_arrays(broadcast_shape, dim_sizes, list_of_core_dims, dtypes): """Helper for creating output arrays in vectorize.""" shapes = _calculate_shapes(broadcast_shape, dim_sizes, list_of_core_dims) arrays = tuple(np.empty(shape, dtype=dtype) for shape, dtype in zip(shapes, dtypes)) return arrays
Example #27
Source File: function_base.py From recruit with Apache License 2.0 | 5 votes |
def _parse_input_dimensions(args, input_core_dims): """ Parse broadcast and core dimensions for vectorize with a signature. Arguments --------- args : Tuple[ndarray, ...] Tuple of input arguments to examine. input_core_dims : List[Tuple[str, ...]] List of core dimensions corresponding to each input. Returns ------- broadcast_shape : Tuple[int, ...] Common shape to broadcast all non-core dimensions to. dim_sizes : Dict[str, int] Common sizes for named core dimensions. """ broadcast_args = [] dim_sizes = {} for arg, core_dims in zip(args, input_core_dims): _update_dim_sizes(dim_sizes, arg, core_dims) ndim = arg.ndim - len(core_dims) dummy_array = np.lib.stride_tricks.as_strided(0, arg.shape[:ndim]) broadcast_args.append(dummy_array) broadcast_shape = np.lib.stride_tricks._broadcast_shape(*broadcast_args) return broadcast_shape, dim_sizes
Example #28
Source File: tower.py From fenics-topopt with MIT License | 5 votes |
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 #29
Source File: test_arraysetops.py From recruit with Apache License 2.0 | 5 votes |
def test_isin(self): # the tests for in1d cover most of isin's behavior # if in1d is removed, would need to change those tests to test # isin instead. def _isin_slow(a, b): b = np.asarray(b).flatten().tolist() return a in b isin_slow = np.vectorize(_isin_slow, otypes=[bool], excluded={1}) def assert_isin_equal(a, b): x = isin(a, b) y = isin_slow(a, b) assert_array_equal(x, y) #multidimensional arrays in both arguments a = np.arange(24).reshape([2, 3, 4]) b = np.array([[10, 20, 30], [0, 1, 3], [11, 22, 33]]) assert_isin_equal(a, b) #array-likes as both arguments c = [(9, 8), (7, 6)] d = (9, 7) assert_isin_equal(c, d) #zero-d array: f = np.array(3) assert_isin_equal(f, b) assert_isin_equal(a, f) assert_isin_equal(f, f) #scalar: assert_isin_equal(5, b) assert_isin_equal(a, 6) assert_isin_equal(5, 6) #empty array-like: x = [] assert_isin_equal(x, b) assert_isin_equal(a, x) assert_isin_equal(x, x)
Example #30
Source File: test_function_base.py From recruit with Apache License 2.0 | 5 votes |
def test_size_zero_output(self): # see issue 5868 f = np.vectorize(lambda x: x) x = np.zeros([0, 5], dtype=int) with assert_raises_regex(ValueError, 'otypes'): f(x) f.otypes = 'i' assert_array_equal(f(x), x) f = np.vectorize(lambda x: x, signature='()->()') with assert_raises_regex(ValueError, 'otypes'): f(x) f = np.vectorize(lambda x: x, signature='()->()', otypes='i') assert_array_equal(f(x), x) f = np.vectorize(lambda x: x, signature='(n)->(n)', otypes='i') assert_array_equal(f(x), x) f = np.vectorize(lambda x: x, signature='(n)->(n)') assert_array_equal(f(x.T), x.T) f = np.vectorize(lambda x: [x], signature='()->(n)', otypes='i') with assert_raises_regex(ValueError, 'new output dimensions'): f(x)