Python numpy.extract() Examples
The following are 30
code examples of numpy.extract().
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: tools_fri_doa_plane.py From pyroomacoustics with MIT License | 6 votes |
def build_mtx_amp(phi_k, p_mic_x, p_mic_y): """ the matrix that maps Diracs' amplitudes to the visibility Parameters ---------- phi_k: Diracs' location (azimuth) p_mic_x: a vector that contains microphones' x-coordinates p_mic_y: a vector that contains microphones' y-coordinates """ xk, yk = polar2cart(1, phi_k[np.newaxis, :]) num_mic = p_mic_x.size p_mic_x_outer = p_mic_x[:, np.newaxis] p_mic_y_outer = p_mic_y[:, np.newaxis] p_mic_x_inner = p_mic_x[np.newaxis, :] p_mic_y_inner = p_mic_y[np.newaxis, :] extract_cond = np.reshape((1 - np.eye(num_mic)).astype(bool), (-1, 1), order='C') baseline_x = np.extract(extract_cond, p_mic_x_outer - p_mic_x_inner)[:, np.newaxis] baseline_y = np.extract(extract_cond, p_mic_y_outer - p_mic_y_inner)[:, np.newaxis] return np.exp(-1j * (xk * baseline_x + yk * baseline_y))
Example #2
Source File: tools_fri_doa_plane.py From pyroomacoustics with MIT License | 6 votes |
def mtx_freq2visi(M, p_mic_x, p_mic_y): """ build the matrix that maps the Fourier series to the visibility Parameters ---------- M: the Fourier series expansion is limited from -M to M p_mic_x: a vector that constains microphones x coordinates p_mic_y: a vector that constains microphones y coordinates """ num_mic = p_mic_x.size ms = np.reshape(np.arange(-M, M + 1, step=1), (1, -1), order='F') p_mic_x_outer = p_mic_x[:, np.newaxis] p_mic_y_outer = p_mic_y[:, np.newaxis] p_mic_x_inner = p_mic_x[np.newaxis, :] p_mic_y_inner = p_mic_y[np.newaxis, :] extract_cond = np.reshape((1 - np.eye(num_mic)).astype(bool), (-1, 1), order='C') baseline_x = np.extract(extract_cond, p_mic_x_outer - p_mic_x_inner)[:, np.newaxis] baseline_y = np.extract(extract_cond, p_mic_y_outer - p_mic_y_inner)[:, np.newaxis] baseline_norm = np.sqrt(baseline_x * baseline_x + baseline_y * baseline_y) return (-1j) ** ms * sp.special.jv(ms, baseline_norm) * \ np.exp(1j * ms * np.arctan2(baseline_y, baseline_x))
Example #3
Source File: tools_fri_doa_plane.py From pyroomacoustics with MIT License | 6 votes |
def multiband_extract_off_diag(mtx): """ extract off-diagonal entries in mtx The output vector is order in a column major manner Parameters ---------- mtx: input matrix to extract the off-diagonal entries """ # we transpose the matrix because the function np.extract will first flatten the matrix # withe ordering convention 'C' instead of 'F'!! Q = mtx.shape[0] num_bands = mtx.shape[2] extract_cond = np.reshape((1 - np.eye(Q)).T.astype(bool), (-1, 1), order='F') return np.column_stack([np.reshape(np.extract(extract_cond, mtx[:, :, band].T), (-1, 1), order='F') for band in range(num_bands)])
Example #4
Source File: downie.py From IkaLog with Apache License 2.0 | 6 votes |
def _detect_gear_level(self, gear_level_image): img_level = matcher.MM_COLOR_BY_HUE( hue=(30 - 5, 30 + 5), visibility=(200, 255))(gear_level_image) cv2.imshow('level', img_level) img_level_hist = np.sum(img_level / 255, axis=0) img_level_x = np.extract(img_level_hist > 3, np.arange(1024)) level_width = np.amax(img_level_x) - np.amin(img_level_x) if level_width < 10: return 1 elif level_width < 40: return 2 return 3 # Sub abilities
Example #5
Source File: _continuous_distns.py From GraphicDesignPatternByPython with MIT License | 6 votes |
def _cdf(self, x, c): output = np.zeros(x.shape, dtype=x.dtype) val = (1.0+c)/(1.0-c) c1 = x < np.pi c2 = 1-c1 xp = np.extract(c1, x) xn = np.extract(c2, x) if np.any(xn): valn = np.extract(c2, np.ones_like(x)*val) xn = 2*np.pi - xn yn = np.tan(xn/2.0) on = 1.0-1.0/np.pi*np.arctan(valn*yn) np.place(output, c2, on) if np.any(xp): valp = np.extract(c1, np.ones_like(x)*val) yp = np.tan(xp/2.0) op = 1.0/np.pi*np.arctan(valp*yp) np.place(output, c1, op) return output
Example #6
Source File: fits_image.py From Aegean with Academic Free License v3.0 | 6 votes |
def get_background_rms(self): """ Calculate the rms of the image. The rms is calculated from the interqurtile range (IQR), to reduce bias from source pixels. Returns ------- rms : float The image rms. Notes ----- The rms value is cached after first calculation. """ # TODO: return a proper background RMS ignoring the sources # This is an approximate method suggested by PaulH. # I have no idea where this magic 1.34896 number comes from... if self._rms is None: # Get the pixels values without the NaNs data = numpy.extract(self.hdu.data > -9999999, self.hdu.data) p25 = scipy.stats.scoreatpercentile(data, 25) p75 = scipy.stats.scoreatpercentile(data, 75) iqr = p75 - p25 self._rms = iqr / 1.34896 return self._rms
Example #7
Source File: _continuous_distns.py From lambda-packs with MIT License | 6 votes |
def _cdf(self, x, c): output = np.zeros(x.shape, dtype=x.dtype) val = (1.0+c)/(1.0-c) c1 = x < np.pi c2 = 1-c1 xp = np.extract(c1, x) xn = np.extract(c2, x) if np.any(xn): valn = np.extract(c2, np.ones_like(x)*val) xn = 2*np.pi - xn yn = np.tan(xn/2.0) on = 1.0-1.0/np.pi*np.arctan(valn*yn) np.place(output, c2, on) if np.any(xp): valp = np.extract(c1, np.ones_like(x)*val) yp = np.tan(xp/2.0) op = 1.0/np.pi*np.arctan(valp*yp) np.place(output, c1, op) return output
Example #8
Source File: mstats_basic.py From Computable with MIT License | 6 votes |
def skew(a, axis=0, bias=True): a, axis = _chk_asarray(a,axis) n = a.count(axis) m2 = moment(a, 2, axis) m3 = moment(a, 3, axis) olderr = np.seterr(all='ignore') try: vals = ma.where(m2 == 0, 0, m3 / m2**1.5) finally: np.seterr(**olderr) if not bias: can_correct = (n > 2) & (m2 > 0) if can_correct.any(): m2 = np.extract(can_correct, m2) m3 = np.extract(can_correct, m3) nval = ma.sqrt((n-1.0)*n)/(n-2.0)*m3/m2**1.5 np.place(vals, can_correct, nval) return vals
Example #9
Source File: common.py From tIGAr with GNU Lesser General Public License v3.0 | 5 votes |
def getComm(self): """ Returns the extraction generator's MPI communicator. """ return self.comm # what type of element (CG or DG) to extract to # (override in subclass for non-default behavior)
Example #10
Source File: data_sampler.py From PES-Learn with BSD 3-Clause "New" or "Revised" License | 5 votes |
def include_first_n(self, train_indices, test_indices): """ Force first n lowest energy points to be in training set Useful for global-minimum-biased fits for applications such as vibrational computations. """ # force first n indices to be in training set a = np.arange(self.first_n) tmp = np.concatenate((train_indices, a) ,axis=0) train_indices = np.unique(tmp) # avoids double counting # adjust test set accordingly condition = test_indices > self.first_n test_indices = np.extract(condition, test_indices) return train_indices, test_indices
Example #11
Source File: tools_fri_doa_plane.py From FRIDA with MIT License | 5 votes |
def extract_off_diag(mtx): """ extract off diagonal entries in mtx. The output vector is order in a column major manner. :param mtx: input matrix to extract the off diagonal entries :return: """ # we transpose the matrix because the function np.extract will first flatten the matrix # withe ordering convention 'C' instead of 'F'!! extract_cond = np.reshape((1 - np.eye(*mtx.shape)).T.astype(bool), (-1, 1), order='F') return np.reshape(np.extract(extract_cond, mtx.T), (-1, 1), order='F')
Example #12
Source File: function_base.py From Splunking-Crime with GNU Affero General Public License v3.0 | 5 votes |
def place(arr, mask, vals): """ Change elements of an array based on conditional and input values. Similar to ``np.copyto(arr, vals, where=mask)``, the difference is that `place` uses the first N elements of `vals`, where N is the number of True values in `mask`, while `copyto` uses the elements where `mask` is True. Note that `extract` does the exact opposite of `place`. Parameters ---------- arr : ndarray Array to put data into. mask : array_like Boolean mask array. Must have the same size as `a`. vals : 1-D sequence Values to put into `a`. Only the first N elements are used, where N is the number of True values in `mask`. If `vals` is smaller than N, it will be repeated, and if elements of `a` are to be masked, this sequence must be non-empty. See Also -------- copyto, put, take, extract Examples -------- >>> arr = np.arange(6).reshape(2, 3) >>> np.place(arr, arr>2, [44, 55]) >>> arr array([[ 0, 1, 2], [44, 55, 44]]) """ if not isinstance(arr, np.ndarray): raise TypeError("argument 1 must be numpy.ndarray, " "not {name}".format(name=type(arr).__name__)) return _insert(arr, mask, vals)
Example #13
Source File: tools_fri_doa_plane.py From pyroomacoustics with MIT License | 5 votes |
def extract_off_diag(mtx): """ extract off diagonal entries in mtx. The output vector is order in a column major manner. Parameters ---------- mtx: input matrix to extract the off diagonal entries """ # we transpose the matrix because the function np.extract will first flatten the matrix # withe ordering convention 'C' instead of 'F'!! extract_cond = np.reshape((1 - np.eye(*mtx.shape)).T.astype(bool), (-1, 1), order='F') return np.reshape(np.extract(extract_cond, mtx.T), (-1, 1), order='F')
Example #14
Source File: common.py From tIGAr with GNU Lesser General Public License v3.0 | 5 votes |
def getDegree(self,field): """ Returns the polynomial degree needed to extract the ``field``-th unknown scalar field. """ return self.getScalarSpline(field).getDegree()
Example #15
Source File: function_base.py From pySINDy with MIT License | 5 votes |
def place(arr, mask, vals): """ Change elements of an array based on conditional and input values. Similar to ``np.copyto(arr, vals, where=mask)``, the difference is that `place` uses the first N elements of `vals`, where N is the number of True values in `mask`, while `copyto` uses the elements where `mask` is True. Note that `extract` does the exact opposite of `place`. Parameters ---------- arr : ndarray Array to put data into. mask : array_like Boolean mask array. Must have the same size as `a`. vals : 1-D sequence Values to put into `a`. Only the first N elements are used, where N is the number of True values in `mask`. If `vals` is smaller than N, it will be repeated, and if elements of `a` are to be masked, this sequence must be non-empty. See Also -------- copyto, put, take, extract Examples -------- >>> arr = np.arange(6).reshape(2, 3) >>> np.place(arr, arr>2, [44, 55]) >>> arr array([[ 0, 1, 2], [44, 55, 44]]) """ if not isinstance(arr, np.ndarray): raise TypeError("argument 1 must be numpy.ndarray, " "not {name}".format(name=type(arr).__name__)) return _insert(arr, mask, vals)
Example #16
Source File: function_base.py From ImageFusion with MIT License | 5 votes |
def place(arr, mask, vals): """ Change elements of an array based on conditional and input values. Similar to ``np.copyto(arr, vals, where=mask)``, the difference is that `place` uses the first N elements of `vals`, where N is the number of True values in `mask`, while `copyto` uses the elements where `mask` is True. Note that `extract` does the exact opposite of `place`. Parameters ---------- arr : array_like Array to put data into. mask : array_like Boolean mask array. Must have the same size as `a`. vals : 1-D sequence Values to put into `a`. Only the first N elements are used, where N is the number of True values in `mask`. If `vals` is smaller than N it will be repeated. See Also -------- copyto, put, take, extract Examples -------- >>> arr = np.arange(6).reshape(2, 3) >>> np.place(arr, arr>2, [44, 55]) >>> arr array([[ 0, 1, 2], [44, 55, 44]]) """ return _insert(arr, mask, vals)
Example #17
Source File: _util.py From Splunking-Crime with GNU Affero General Public License v3.0 | 5 votes |
def _lazywhere(cond, arrays, f, fillvalue=None, f2=None): """ np.where(cond, x, fillvalue) always evaluates x even where cond is False. This one only evaluates f(arr1[cond], arr2[cond], ...). For example, >>> a, b = np.array([1, 2, 3, 4]), np.array([5, 6, 7, 8]) >>> def f(a, b): return a*b >>> _lazywhere(a > 2, (a, b), f, np.nan) array([ nan, nan, 21., 32.]) Notice it assumes that all `arrays` are of the same shape, or can be broadcasted together. """ if fillvalue is None: if f2 is None: raise ValueError("One of (fillvalue, f2) must be given.") else: fillvalue = np.nan else: if f2 is not None: raise ValueError("Only one of (fillvalue, f2) can be given.") arrays = np.broadcast_arrays(*arrays) temp = tuple(np.extract(cond, arr) for arr in arrays) tcode = np.mintypecode([a.dtype.char for a in arrays]) out = _valarray(np.shape(arrays[0]), value=fillvalue, typecode=tcode) np.place(out, cond, f(*temp)) if f2 is not None: temp = tuple(np.extract(~cond, arr) for arr in arrays) np.place(out, ~cond, f2(*temp)) return out
Example #18
Source File: indexing.py From cupy with MIT License | 5 votes |
def extract(condition, a): """Return the elements of an array that satisfy some condition. This is equivalent to ``np.compress(ravel(condition), ravel(arr))``. If ``condition`` is boolean, ``np.extract`` is equivalent to ``arr[condition]``. Args: condition (int or array_like): An array whose nonzero or True entries indicate the elements of array to extract. a (cupy.ndarray): Input array of the same size as condition. Returns: cupy.ndarray: Rank 1 array of values from arr where condition is True. .. warning:: This function may synchronize the device. .. seealso:: :func:`numpy.extract` """ if not isinstance(a, cupy.ndarray): raise TypeError('extract requires input array to be cupy.ndarray') if not isinstance(condition, cupy.ndarray): condition = cupy.array(condition) a = a.ravel() condition = condition.ravel() return a.take(condition.nonzero()[0])
Example #19
Source File: indexing.py From cupy with MIT License | 5 votes |
def compress(condition, a, axis=None, out=None): """Returns selected slices of an array along given axis. Args: condition (1-D array of bools): Array that selects which entries to return. If len(condition) is less than the size of a along the given axis, then output is truncated to the length of the condition array. a (cupy.ndarray): Array from which to extract a part. axis (int): Axis along which to take slices. If None (default), work on the flattened array. out (cupy.ndarray): Output array. If provided, it should be of appropriate shape and dtype. Returns: cupy.ndarray: A copy of a without the slices along axis for which condition is false. .. warning:: This function may synchronize the device. .. seealso:: :func:`numpy.compress` """ return a.compress(condition, axis, out)
Example #20
Source File: pauli_trotter_evolution.py From qiskit-aqua with Apache License 2.0 | 5 votes |
def evolution_for_pauli(self, pauli_op: PauliOp) -> PrimitiveOp: r""" Compute evolution Operator for a single Pauli using a ``PauliBasisChange``. Args: pauli_op: The ``PauliOp`` to evolve. Returns: A ``PrimitiveOp``, either the evolution ``CircuitOp`` or a ``PauliOp`` equal to the identity if pauli_op is the identity. """ def replacement_fn(cob_instr_op, dest_pauli_op): z_evolution = dest_pauli_op.exp_i() # Remember, circuit composition order is mirrored operator composition order. return cob_instr_op.adjoint().compose(z_evolution).compose(cob_instr_op) # Note: PauliBasisChange will pad destination with identities # to produce correct CoB circuit sig_bits = np.logical_or(pauli_op.primitive.z, pauli_op.primitive.x) # type: ignore a_sig_bit = int(max(np.extract(sig_bits, np.arange(pauli_op.num_qubits)[::-1]))) destination = (I.tensorpower(a_sig_bit)) ^ (Z * pauli_op.coeff) cob = PauliBasisChange(destination_basis=destination, replacement_fn=replacement_fn) return cast(PrimitiveOp, cob.convert(pauli_op)) # TODO implement Abelian grouped evolution.
Example #21
Source File: function_base.py From Fluid-Designer with GNU General Public License v3.0 | 5 votes |
def place(arr, mask, vals): """ Change elements of an array based on conditional and input values. Similar to ``np.copyto(arr, vals, where=mask)``, the difference is that `place` uses the first N elements of `vals`, where N is the number of True values in `mask`, while `copyto` uses the elements where `mask` is True. Note that `extract` does the exact opposite of `place`. Parameters ---------- arr : array_like Array to put data into. mask : array_like Boolean mask array. Must have the same size as `a`. vals : 1-D sequence Values to put into `a`. Only the first N elements are used, where N is the number of True values in `mask`. If `vals` is smaller than N it will be repeated. See Also -------- copyto, put, take, extract Examples -------- >>> arr = np.arange(6).reshape(2, 3) >>> np.place(arr, arr>2, [44, 55]) >>> arr array([[ 0, 1, 2], [44, 55, 44]]) """ return _insert(arr, mask, vals)
Example #22
Source File: function_base.py From predictive-maintenance-using-machine-learning with Apache License 2.0 | 5 votes |
def place(arr, mask, vals): """ Change elements of an array based on conditional and input values. Similar to ``np.copyto(arr, vals, where=mask)``, the difference is that `place` uses the first N elements of `vals`, where N is the number of True values in `mask`, while `copyto` uses the elements where `mask` is True. Note that `extract` does the exact opposite of `place`. Parameters ---------- arr : ndarray Array to put data into. mask : array_like Boolean mask array. Must have the same size as `a`. vals : 1-D sequence Values to put into `a`. Only the first N elements are used, where N is the number of True values in `mask`. If `vals` is smaller than N, it will be repeated, and if elements of `a` are to be masked, this sequence must be non-empty. See Also -------- copyto, put, take, extract Examples -------- >>> arr = np.arange(6).reshape(2, 3) >>> np.place(arr, arr>2, [44, 55]) >>> arr array([[ 0, 1, 2], [44, 55, 44]]) """ if not isinstance(arr, np.ndarray): raise TypeError("argument 1 must be numpy.ndarray, " "not {name}".format(name=type(arr).__name__)) return _insert(arr, mask, vals)
Example #23
Source File: result_detail.py From IkaLog with Apache License 2.0 | 5 votes |
def is_entries_still_sliding(self, img_entries): white_filter = matcher.MM_WHITE() array0to14 = np.array(range(15), dtype=np.int32) x_pos_list = [] for img_entry in img_entries: img_XX = img_entry[:, 1173 - 610: 1173 + 13 - 610] # -> 2D img_XX_hist = np.sum(white_filter(img_XX), axis=0) # -> 1D img_XX_hist_x = np.extract(img_XX_hist > 0, array0to14[ 0:img_XX_hist.shape[0]]) if img_XX_hist_x.shape[0] == 0: continue img_XX_hist_x_avg = np.average(img_XX_hist_x) x_pos_list.append(img_XX_hist_x_avg) x_avg_min = np.amin(x_pos_list) x_avg_max = np.amax(x_pos_list) x_diff = int(x_avg_max - x_avg_min) if 0: # debug print('is_entries_still_sliding: x_pos_list %s min %f max %f diff %d' % (x_pos_list, x_avg_min, x_avg_max, x_diff)) return x_diff
Example #24
Source File: inklings_tracker.py From IkaLog with Apache License 2.0 | 5 votes |
def _get_vs_xpos(self, context): img = self._crop_frame(context, self.meter_x1, 24 + 38, self.meter_x2, 24 + 40) img_w = matcher.MM_WHITE( sat=(0, 8), visibility=(248, 256))(img) img_vs_hist = np.sum(img_w, axis=0) img_vs_x = np.extract(img_vs_hist > 128, np.arange(1024)) if len(img_vs_x) == 0: return None vs_x_min = np.amin(img_vs_x) vs_x_max = np.amax(img_vs_x) vs_x = int((vs_x_min + vs_x_max) / 2) return vs_x ## # _find_active_inklings # # Find active inklings on the frame. # @param self The object. # @param context The context. # @param x1 Absolute x value to start discovery. # @param x2 Absolute x value to finish discovery. # # This function looks for eye of the inklings (with white pixels). # # To reduce false-positive detection, it also checks the pixel # of the squid. Since it's body should be colored (not white or black), # it ignores eye pixels without colored body pixels. #
Example #25
Source File: objective_tracker.py From IkaLog with Apache License 2.0 | 5 votes |
def tower_pos(self, context): img = context['engine']['frame'][self.tower_line_top:self.tower_line_top + self.tower_line_height, self.tower_left:self.tower_left + self.tower_width] img2 = cv2.resize(img, (self.tower_width, 100)) img_hsv = cv2.cvtColor(img, cv2.COLOR_BGR2HSV) for i in range(2): img2[20:40, :, i] = cv2.resize( img_hsv[:, :, 0], (self.tower_width, 20)) img2[40:60, :, i] = cv2.resize( img_hsv[:, :, 1], (self.tower_width, 20)) img2[60:80, :, i] = cv2.resize( img_hsv[:, :, 2], (self.tower_width, 20)) # ゲージのうち信頼できる部分だけでマスクする img3 = img & self.ui_tower_mask # 白い部分にいまヤグラ/ホコがある img3_hsv = cv2.cvtColor(img3, cv2.COLOR_BGR2HSV) white_mask_v = cv2.inRange(img3_hsv[:, :, 2], 248, 256) x_list = np.arange(self.tower_width) tower_x = np.extract(white_mask_v[3, :] > 128, x_list) if tower_x.shape[0] == 0: return None tower_xPos = np.average(tower_x) # FixMe: マスクした関係が位置がずれている可能性があるので、適宜補正すべき xPos_pct = (tower_xPos - self.tower_width / 2) / \ (self.tower_width * 0.86 / 2) * 100 # あきらかにおかしい値が出たらとりあえず排除 if xPos_pct < -120 or 120 < xPos_pct: xPos_pct = None return xPos_pct
Example #26
Source File: _distn_infrastructure.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def argsreduce(cond, *args): """Return the sequence of ravel(args[i]) where ravel(condition) is True in 1D. Examples -------- >>> import numpy as np >>> rand = np.random.random_sample >>> A = rand((4, 5)) >>> B = 2 >>> C = rand((1, 5)) >>> cond = np.ones(A.shape) >>> [A1, B1, C1] = argsreduce(cond, A, B, C) >>> B1.shape (20,) >>> cond[2,:] = 0 >>> [A2, B2, C2] = argsreduce(cond, A, B, C) >>> B2.shape (15,) """ newargs = np.atleast_1d(*args) if not isinstance(newargs, list): newargs = [newargs, ] expand_arr = (cond == cond) return [np.extract(cond, arr1 * expand_arr) for arr1 in newargs]
Example #27
Source File: _continuous_distns.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def _stats(self, b, moments='mv'): mu, mu2, g1, g2 = None, None, None, None if 'm' in moments: mask = b > 1 bt = np.extract(mask, b) mu = valarray(np.shape(b), value=np.inf) np.place(mu, mask, bt / (bt-1.0)) if 'v' in moments: mask = b > 2 bt = np.extract(mask, b) mu2 = valarray(np.shape(b), value=np.inf) np.place(mu2, mask, bt / (bt-2.0) / (bt-1.0)**2) if 's' in moments: mask = b > 3 bt = np.extract(mask, b) g1 = valarray(np.shape(b), value=np.nan) vals = 2 * (bt + 1.0) * np.sqrt(bt - 2.0) / ((bt - 3.0) * np.sqrt(bt)) np.place(g1, mask, vals) if 'k' in moments: mask = b > 4 bt = np.extract(mask, b) g2 = valarray(np.shape(b), value=np.nan) vals = (6.0*np.polyval([1.0, 1.0, -6, -2], bt) / np.polyval([1.0, -7.0, 12.0, 0.0], bt)) np.place(g2, mask, vals) return mu, mu2, g1, g2
Example #28
Source File: _util.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def _lazyselect(condlist, choicelist, arrays, default=0): """ Mimic `np.select(condlist, choicelist)`. Notice it assumes that all `arrays` are of the same shape, or can be broadcasted together. All functions in `choicelist` must accept array arguments in the order given in `arrays` and must return an array of the same shape as broadcasted `arrays`. Examples -------- >>> x = np.arange(6) >>> np.select([x <3, x > 3], [x**2, x**3], default=0) array([ 0, 1, 4, 0, 64, 125]) >>> _lazyselect([x < 3, x > 3], [lambda x: x**2, lambda x: x**3], (x,)) array([ 0., 1., 4., 0., 64., 125.]) >>> a = -np.ones_like(x) >>> _lazyselect([x < 3, x > 3], ... [lambda x, a: x**2, lambda x, a: a * x**3], ... (x, a), default=np.nan) array([ 0., 1., 4., nan, -64., -125.]) """ arrays = np.broadcast_arrays(*arrays) tcode = np.mintypecode([a.dtype.char for a in arrays]) out = _valarray(np.shape(arrays[0]), value=default, typecode=tcode) for index in range(len(condlist)): func, cond = choicelist[index], condlist[index] if np.all(cond is False): continue cond, _ = np.broadcast_arrays(cond, arrays[0]) temp = tuple(np.extract(cond, arr) for arr in arrays) np.place(out, cond, func(*temp)) return out
Example #29
Source File: _util.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def _lazywhere(cond, arrays, f, fillvalue=None, f2=None): """ np.where(cond, x, fillvalue) always evaluates x even where cond is False. This one only evaluates f(arr1[cond], arr2[cond], ...). For example, >>> a, b = np.array([1, 2, 3, 4]), np.array([5, 6, 7, 8]) >>> def f(a, b): return a*b >>> _lazywhere(a > 2, (a, b), f, np.nan) array([ nan, nan, 21., 32.]) Notice it assumes that all `arrays` are of the same shape, or can be broadcasted together. """ if fillvalue is None: if f2 is None: raise ValueError("One of (fillvalue, f2) must be given.") else: fillvalue = np.nan else: if f2 is not None: raise ValueError("Only one of (fillvalue, f2) can be given.") arrays = np.broadcast_arrays(*arrays) temp = tuple(np.extract(cond, arr) for arr in arrays) tcode = np.mintypecode([a.dtype.char for a in arrays]) out = _valarray(np.shape(arrays[0]), value=fillvalue, typecode=tcode) np.place(out, cond, f(*temp)) if f2 is not None: temp = tuple(np.extract(~cond, arr) for arr in arrays) np.place(out, ~cond, f2(*temp)) return out
Example #30
Source File: function_base.py From GraphicDesignPatternByPython with MIT License | 5 votes |
def place(arr, mask, vals): """ Change elements of an array based on conditional and input values. Similar to ``np.copyto(arr, vals, where=mask)``, the difference is that `place` uses the first N elements of `vals`, where N is the number of True values in `mask`, while `copyto` uses the elements where `mask` is True. Note that `extract` does the exact opposite of `place`. Parameters ---------- arr : ndarray Array to put data into. mask : array_like Boolean mask array. Must have the same size as `a`. vals : 1-D sequence Values to put into `a`. Only the first N elements are used, where N is the number of True values in `mask`. If `vals` is smaller than N, it will be repeated, and if elements of `a` are to be masked, this sequence must be non-empty. See Also -------- copyto, put, take, extract Examples -------- >>> arr = np.arange(6).reshape(2, 3) >>> np.place(arr, arr>2, [44, 55]) >>> arr array([[ 0, 1, 2], [44, 55, 44]]) """ if not isinstance(arr, np.ndarray): raise TypeError("argument 1 must be numpy.ndarray, " "not {name}".format(name=type(arr).__name__)) return _insert(arr, mask, vals)