Python numpy.iscomplexobj() Examples
The following are 30 code examples for showing how to use numpy.iscomplexobj(). 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
numpy
, or try the search function
.
Example 1
Project: pyscf Author: pyscf File: gw_slow.py License: Apache License 2.0 | 6 votes |
def construct_tdm(self): td_xy = 2 * numpy.asarray(self.td_xy) tdm_oo = einsum('vxia,ipaq->vxpq', td_xy, self["oovo"]) tdm_ov = einsum('vxia,ipaq->vxpq', td_xy, self["oovv"]) tdm_vv = einsum('vxia,ipaq->vxpq', td_xy, self["ovvv"]) if numpy.iscomplexobj(self["oovv"]): tdm_vo = einsum('vxia,ipaq->vxpq', td_xy, self["ovvo"]) else: tdm_vo = tdm_ov.swapaxes(2, 3).conj() tdm = numpy.concatenate( ( numpy.concatenate((tdm_oo, tdm_ov), axis=3), numpy.concatenate((tdm_vo, tdm_vv), axis=3) ), axis=2, ) return tdm
Example 2
Project: pyscf Author: pyscf File: __init__.py License: Apache License 2.0 | 6 votes |
def RCCSD(mf, frozen=None, mo_coeff=None, mo_occ=None): import numpy from pyscf import lib from pyscf.soscf import newton_ah from pyscf.cc import dfccsd if isinstance(mf, scf.uhf.UHF): raise RuntimeError('RCCSD cannot be used with UHF method.') elif isinstance(mf, scf.rohf.ROHF): lib.logger.warn(mf, 'RCCSD method does not support ROHF method. ROHF object ' 'is converted to UHF object and UCCSD method is called.') mf = scf.addons.convert_to_uhf(mf) return UCCSD(mf, frozen, mo_coeff, mo_occ) if isinstance(mf, newton_ah._CIAH_SOSCF) or not isinstance(mf, scf.hf.RHF): mf = scf.addons.convert_to_rhf(mf) if getattr(mf, 'with_df', None): return dfccsd.RCCSD(mf, frozen, mo_coeff, mo_occ) elif numpy.iscomplexobj(mo_coeff) or numpy.iscomplexobj(mf.mo_coeff): return rccsd.RCCSD(mf, frozen, mo_coeff, mo_occ) else: return ccsd.CCSD(mf, frozen, mo_coeff, mo_occ)
Example 3
Project: pyscf Author: pyscf File: common_slow.py License: Apache License 2.0 | 6 votes |
def mkk2ab(mk, k): """ Transforms MK and M TD matrices into A and B matrices. Args: mk (numpy.ndarray): TD MK-matrix; k (numpy.ndarray): TD K-matrix; Returns: A and B submatrices. """ if numpy.iscomplexobj(mk) or numpy.iscomplexobj(k): raise ValueError("MK- and/or K-matrixes are complex-valued: no transform is possible") m = solve(k.T, mk.T).T a = 0.5 * (m + k) b = 0.5 * (m - k) return a, b
Example 4
Project: pyqmc Author: WagnerGroup File: multislater.py License: MIT License | 6 votes |
def __init__(self, mol, mf, mc, tol=None, freeze_orb=None): self.tol = -1 if tol is None else tol self.parameters = {} self._mol = mol self._nelec = (mc.nelecas[0] + mc.ncore, mc.nelecas[1] + mc.ncore) self._copy_ci(mc) if len(mc.mo_coeff.shape) == 3: self.parameters["mo_coeff_alpha"] = mc.mo_coeff[0][:, : mc.ncas + mc.ncore] self.parameters["mo_coeff_beta"] = mc.mo_coeff[1][:, : mc.ncas + mc.ncore] else: self.parameters["mo_coeff_alpha"] = mc.mo_coeff[:, : mc.ncas + mc.ncore] self.parameters["mo_coeff_beta"] = mc.mo_coeff[:, : mc.ncas + mc.ncore] self._coefflookup = ("mo_coeff_alpha", "mo_coeff_beta") self.pbc_str = "PBC" if hasattr(mol, "a") else "" self.iscomplex = bool(sum(map(np.iscomplexobj, self.parameters.values()))) self.get_phase = (lambda x: x / np.abs(x)) if self.iscomplex else np.sign self.freeze_orb = [[], []] if freeze_orb is None else freeze_orb
Example 5
Project: pyqmc Author: WagnerGroup File: slater.py License: MIT License | 6 votes |
def _init_mol(self, mol, mf): from pyscf import scf for s, lookup in enumerate(self._coefflookup): if len(mf.mo_occ.shape) == 2: self.parameters[lookup] = mf.mo_coeff[s][ :, np.asarray(mf.mo_occ[s] > 0.9) ] else: minocc = (0.9, 1.1)[s] self.parameters[lookup] = mf.mo_coeff[:, np.asarray(mf.mo_occ > minocc)] self._nelec = tuple(mol.nelec) self._mol = mol self.iscomplex = bool(sum(map(np.iscomplexobj, self.parameters.values()))) self.evaluate_orbitals = self._evaluate_orbitals_mol self.evaluate_mos = self._evaluate_mos_mol
Example 6
Project: pyGSTi Author: pyGSTio File: __init__.py License: Apache License 2.0 | 6 votes |
def safe_bulk_eval_compact_polys(vtape, ctape, paramvec, dest_shape): """Typechecking wrapper for :function:`bulk_eval_compact_polys`. The underlying method has two implementations: one for real-valued `ctape`, and one for complex-valued. This wrapper will dynamically dispatch to the appropriate implementation method based on the type of `ctape`. If the type of `ctape` is known prior to calling, it's slightly faster to call the appropriate implementation method directly; if not. """ if _np.iscomplexobj(ctape): ret = bulk_eval_compact_polys_complex(vtape, ctape, paramvec, dest_shape) im_norm = _np.linalg.norm(_np.imag(ret)) if im_norm > 1e-6: print("WARNING: norm(Im part) = {:g}".format(im_norm)) else: ret = bulk_eval_compact_polys(vtape, ctape, paramvec, dest_shape) return _np.real(ret)
Example 7
Project: pyGSTi Author: pyGSTio File: spamvec.py License: Apache License 2.0 | 6 votes |
def __init__(self, vec, evotype="auto", typ="prep"): """ Initialize a FullSPAMVec object. Parameters ---------- vec : array_like or SPAMVec a 1D numpy array representing the SPAM operation. The shape of this array sets the dimension of the SPAM op. evotype : {"densitymx", "statevec"} the evolution type being used. typ : {"prep", "effect"} whether this is a state preparation or an effect (measurement) SPAM vector. """ vec = SPAMVec.convert_to_vector(vec) if evotype == "auto": evotype = "statevec" if _np.iscomplexobj(vec) else "densitymx" assert(evotype in ("statevec", "densitymx")), \ "Invalid evolution type '%s' for %s" % (evotype, self.__class__.__name__) DenseSPAMVec.__init__(self, vec, evotype, typ)
Example 8
Project: recruit Author: Frank-qlu File: test_polynomial.py License: Apache License 2.0 | 6 votes |
def test_poly(self): assert_array_almost_equal(np.poly([3, -np.sqrt(2), np.sqrt(2)]), [1, -3, -2, 6]) # From matlab docs A = [[1, 2, 3], [4, 5, 6], [7, 8, 0]] assert_array_almost_equal(np.poly(A), [1, -6, -72, -27]) # Should produce real output for perfect conjugates assert_(np.isrealobj(np.poly([+1.082j, +2.613j, -2.613j, -1.082j]))) assert_(np.isrealobj(np.poly([0+1j, -0+-1j, 1+2j, 1-2j, 1.+3.5j, 1-3.5j]))) assert_(np.isrealobj(np.poly([1j, -1j, 1+2j, 1-2j, 1+3j, 1-3.j]))) assert_(np.isrealobj(np.poly([1j, -1j, 1+2j, 1-2j]))) assert_(np.isrealobj(np.poly([1j, -1j, 2j, -2j]))) assert_(np.isrealobj(np.poly([1j, -1j]))) assert_(np.isrealobj(np.poly([1, -1]))) assert_(np.iscomplexobj(np.poly([1j, -1.0000001j]))) np.random.seed(42) a = np.random.randn(100) + 1j*np.random.randn(100) assert_(np.isrealobj(np.poly(np.concatenate((a, np.conjugate(a))))))
Example 9
Project: recruit Author: Frank-qlu File: nanops.py License: Apache License 2.0 | 6 votes |
def _maybe_null_out(result, axis, mask, min_count=1): if axis is not None and getattr(result, 'ndim', False): null_mask = (mask.shape[axis] - mask.sum(axis) - min_count) < 0 if np.any(null_mask): if is_numeric_dtype(result): if np.iscomplexobj(result): result = result.astype('c16') else: result = result.astype('f8') result[null_mask] = np.nan else: # GH12941, use None to auto cast null result[null_mask] = None elif result is not tslibs.NaT: null_mask = mask.size - mask.sum() if null_mask < min_count: result = np.nan return result
Example 10
Project: pylops Author: equinor File: Diagonal.py License: GNU Lesser General Public License v3.0 | 6 votes |
def __init__(self, diag, dims=None, dir=0, dtype='float64'): self.diag = diag.flatten() self.complex = True if np.iscomplexobj(self.diag) else False if dims is None: self.shape = (len(self.diag), len(self.diag)) self.dims = None self.reshape = False else: diagdims = [1] * len(dims) diagdims[dir] = dims[dir] self.diag = self.diag.reshape(diagdims) self.shape = (np.prod(dims), np.prod(dims)) self.dims = dims self.reshape = True self.dtype = np.dtype(dtype) self.explicit = False
Example 11
Project: pylops Author: equinor File: MatrixMult.py License: GNU Lesser General Public License v3.0 | 6 votes |
def __init__(self, A, dims=None, dtype='float64'): self.A = A if isinstance(A, np.ndarray): self.complex = np.iscomplexobj(A) else: self.complex = np.iscomplexobj(A.data) if dims is None: self.reshape = False self.shape = A.shape self.explicit = True else: if isinstance(dims, int): dims = (dims, ) self.reshape = True self.dims = np.array(dims, dtype=np.int) self.shape = (A.shape[0]*np.prod(self.dims), A.shape[1]*np.prod(self.dims)) self.explicit = False self.dtype = np.dtype(dtype)
Example 12
Project: lambda-packs Author: ryfeus File: arpack.py License: MIT License | 6 votes |
def _augmented_orthonormal_cols(x, k): # extract the shape of the x array n, m = x.shape # create the expanded array and copy x into it y = np.empty((n, m+k), dtype=x.dtype) y[:, :m] = x # do some modified gram schmidt to add k random orthonormal vectors for i in range(k): # sample a random initial vector v = np.random.randn(n) if np.iscomplexobj(x): v = v + 1j*np.random.randn(n) # subtract projections onto the existing unit length vectors for j in range(m+i): u = y[:, j] v -= (np.dot(v, u.conj()) / np.dot(u, u.conj())) * u # normalize v v /= np.sqrt(np.dot(v, v.conj())) # add v into the output array y[:, m+i] = v # return the expanded array return y
Example 13
Project: lambda-packs Author: ryfeus File: filters.py License: MIT License | 6 votes |
def _correlate_or_convolve(input, weights, output, mode, cval, origin, convolution): input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') origins = _ni_support._normalize_sequence(origin, input.ndim) weights = numpy.asarray(weights, dtype=numpy.float64) wshape = [ii for ii in weights.shape if ii > 0] if len(wshape) != input.ndim: raise RuntimeError('filter weights array has incorrect shape.') if convolution: weights = weights[tuple([slice(None, None, -1)] * weights.ndim)] for ii in range(len(origins)): origins[ii] = -origins[ii] if not weights.shape[ii] & 1: origins[ii] -= 1 for origin, lenw in zip(origins, wshape): if (lenw // 2 + origin < 0) or (lenw // 2 + origin > lenw): raise ValueError('invalid origin') if not weights.flags.contiguous: weights = weights.copy() output, return_value = _ni_support._get_output(output, input) mode = _ni_support._extend_mode_to_code(mode) _nd_image.correlate(input, weights, output, mode, cval, origins) return return_value
Example 14
Project: lambda-packs Author: ryfeus File: test_polynomial.py License: MIT License | 6 votes |
def test_poly(self): assert_array_almost_equal(np.poly([3, -np.sqrt(2), np.sqrt(2)]), [1, -3, -2, 6]) # From matlab docs A = [[1, 2, 3], [4, 5, 6], [7, 8, 0]] assert_array_almost_equal(np.poly(A), [1, -6, -72, -27]) # Should produce real output for perfect conjugates assert_(np.isrealobj(np.poly([+1.082j, +2.613j, -2.613j, -1.082j]))) assert_(np.isrealobj(np.poly([0+1j, -0+-1j, 1+2j, 1-2j, 1.+3.5j, 1-3.5j]))) assert_(np.isrealobj(np.poly([1j, -1j, 1+2j, 1-2j, 1+3j, 1-3.j]))) assert_(np.isrealobj(np.poly([1j, -1j, 1+2j, 1-2j]))) assert_(np.isrealobj(np.poly([1j, -1j, 2j, -2j]))) assert_(np.isrealobj(np.poly([1j, -1j]))) assert_(np.isrealobj(np.poly([1, -1]))) assert_(np.iscomplexobj(np.poly([1j, -1.0000001j]))) np.random.seed(42) a = np.random.randn(100) + 1j*np.random.randn(100) assert_(np.isrealobj(np.poly(np.concatenate((a, np.conjugate(a))))))
Example 15
Project: vnpy_crypto Author: birforce File: test_polynomial.py License: MIT License | 6 votes |
def test_poly(self): assert_array_almost_equal(np.poly([3, -np.sqrt(2), np.sqrt(2)]), [1, -3, -2, 6]) # From matlab docs A = [[1, 2, 3], [4, 5, 6], [7, 8, 0]] assert_array_almost_equal(np.poly(A), [1, -6, -72, -27]) # Should produce real output for perfect conjugates assert_(np.isrealobj(np.poly([+1.082j, +2.613j, -2.613j, -1.082j]))) assert_(np.isrealobj(np.poly([0+1j, -0+-1j, 1+2j, 1-2j, 1.+3.5j, 1-3.5j]))) assert_(np.isrealobj(np.poly([1j, -1j, 1+2j, 1-2j, 1+3j, 1-3.j]))) assert_(np.isrealobj(np.poly([1j, -1j, 1+2j, 1-2j]))) assert_(np.isrealobj(np.poly([1j, -1j, 2j, -2j]))) assert_(np.isrealobj(np.poly([1j, -1j]))) assert_(np.isrealobj(np.poly([1, -1]))) assert_(np.iscomplexobj(np.poly([1j, -1.0000001j]))) np.random.seed(42) a = np.random.randn(100) + 1j*np.random.randn(100) assert_(np.isrealobj(np.poly(np.concatenate((a, np.conjugate(a))))))
Example 16
Project: vnpy_crypto Author: birforce File: nanops.py License: MIT License | 6 votes |
def _maybe_null_out(result, axis, mask, min_count=1): if axis is not None and getattr(result, 'ndim', False): null_mask = (mask.shape[axis] - mask.sum(axis) - min_count) < 0 if np.any(null_mask): if is_numeric_dtype(result): if np.iscomplexobj(result): result = result.astype('c16') else: result = result.astype('f8') result[null_mask] = np.nan else: # GH12941, use None to auto cast null result[null_mask] = None elif result is not tslib.NaT: null_mask = mask.size - mask.sum() if null_mask < min_count: result = np.nan return result
Example 17
Project: nussl Author: nussl File: audio_signal.py License: MIT License | 6 votes |
def stft_data(self, value): if value is None: self._stft_data = None return elif not isinstance(value, np.ndarray): raise AudioSignalException('Type of self.stft_data must be of type np.ndarray!') if value.ndim == 1: raise AudioSignalException('Cannot support arrays with less than 2 dimensions!') if value.ndim == 2: value = np.expand_dims(value, axis=constants.STFT_CHAN_INDEX) if value.ndim > 3: raise AudioSignalException('Cannot support arrays with more than 3 dimensions!') if not np.iscomplexobj(value): warnings.warn('Initializing STFT with data that is non-complex. ' 'This might lead to weird results!') self._stft_data = value
Example 18
Project: Computable Author: ktraunmueller File: filters.py License: MIT License | 6 votes |
def _correlate_or_convolve(input, weights, output, mode, cval, origin, convolution): input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') origins = _ni_support._normalize_sequence(origin, input.ndim) weights = numpy.asarray(weights, dtype=numpy.float64) wshape = [ii for ii in weights.shape if ii > 0] if len(wshape) != input.ndim: raise RuntimeError('filter weights array has incorrect shape.') if convolution: weights = weights[tuple([slice(None, None, -1)] * weights.ndim)] for ii in range(len(origins)): origins[ii] = -origins[ii] if not weights.shape[ii] & 1: origins[ii] -= 1 for origin, lenw in zip(origins, wshape): if (lenw // 2 + origin < 0) or (lenw // 2 + origin > lenw): raise ValueError('invalid origin') if not weights.flags.contiguous: weights = weights.copy() output, return_value = _ni_support._get_output(output, input) mode = _ni_support._extend_mode_to_code(mode) _nd_image.correlate(input, weights, output, mode, cval, origins) return return_value
Example 19
Project: pyscf Author: pyscf File: common_slow.py License: Apache License 2.0 | 5 votes |
def __init__(self, mf, frozen=None): """ Performs TD calculation. Roots and eigenvectors are stored in `self.e`, `self.xy`. Args: mf: the mean-field model; frozen (int, Iterable): the number of frozen valence orbitals or the list of frozen orbitals; """ self._scf = mf self.driver = None self.nroots = None self.eri = None self.xy = None self.e = None self.frozen = frozen self.fast = not numpy.iscomplexobj(numpy.asanyarray(mf.mo_coeff))
Example 20
Project: pyGSTi Author: pyGSTio File: spamvec.py License: Apache License 2.0 | 5 votes |
def __init__(self, vec, evotype="auto", typ="prep"): """ Initialize a StaticSPAMVec object. Parameters ---------- vec : array_like or SPAMVec a 1D numpy array representing the SPAM operation. The shape of this array sets the dimension of the SPAM op. evotype : {"densitymx", "statevec"} the evolution type being used. typ : {"prep", "effect"} whether this is a state preparation or an effect (measurement) SPAM vector. """ vec = SPAMVec.convert_to_vector(vec) if evotype == "auto": evotype = "statevec" if _np.iscomplexobj(vec) else "densitymx" elif evotype == "statevec": vec = _np.asarray(vec, complex) # ensure all statevec vecs are complex (densitymx could be either?) assert(evotype in ("statevec", "densitymx")), \ "Invalid evolution type '%s' for %s" % (evotype, self.__class__.__name__) DenseSPAMVec.__init__(self, vec, evotype, typ)
Example 21
Project: recruit Author: Frank-qlu File: test_overrides.py License: Apache License 2.0 | 5 votes |
def test_interface(self): class MyArray(object): def __array_function__(self, func, types, args, kwargs): return (self, func, types, args, kwargs) original = MyArray() (obj, func, types, args, kwargs) = dispatched_one_arg(original) assert_(obj is original) assert_(func is dispatched_one_arg) assert_equal(set(types), {MyArray}) # assert_equal uses the overloaded np.iscomplexobj() internally assert_(args == (original,)) assert_equal(kwargs, {})
Example 22
Project: pylops Author: equinor File: sparsity.py License: GNU Lesser General Public License v3.0 | 5 votes |
def _softthreshold(x, thresh): r"""Soft thresholding. Applies soft thresholding to vector ``x`` (equal to the proximity operator for :math:`||\mathbf{x}||_1`) as shown in [1]_. .. [1] Chen, Y., Chen, K., Shi, P., Wang, Y., “Irregular seismic data reconstruction using a percentile-half-thresholding algorithm”, Journal of Geophysics and Engineering, vol. 11. 2014. Parameters ---------- x : :obj:`numpy.ndarray` Vector thresh : :obj:`float` Threshold Returns ------- x1 : :obj:`numpy.ndarray` Tresholded vector """ #if np.iscomplexobj(x): # # https://stats.stackexchange.com/questions/357339/soft-thresholding- # # for-the-lasso-with-complex-valued-data # x1 = np.maximum(np.abs(x) - thresh, 0.) * np.exp(1j * np.angle(x)) #else: # x1 = np.maximum(np.abs(x)-thresh, 0.) * np.sign(x) x1 = x - thresh * x / np.abs(x) x1[np.abs(x) <= thresh] = 0 return x1
Example 23
Project: lambda-packs Author: ryfeus File: realtransforms.py License: MIT License | 5 votes |
def _dct(x, type, n=None, axis=-1, overwrite_x=False, normalize=None): """ Return Discrete Cosine Transform of arbitrary type sequence x. Parameters ---------- x : array_like input array. n : int, optional Length of the transform. If ``n < x.shape[axis]``, `x` is truncated. If ``n > x.shape[axis]``, `x` is zero-padded. The default results in ``n = x.shape[axis]``. axis : int, optional Axis along which the dct is computed; the default is over the last axis (i.e., ``axis=-1``). overwrite_x : bool, optional If True, the contents of `x` can be destroyed; the default is False. Returns ------- z : ndarray """ x0, n, copy_made = __fix_shape(x, n, axis, 'DCT') if type == 1 and n < 2: raise ValueError("DCT-I is not defined for size < 2") overwrite_x = overwrite_x or copy_made nm = _get_norm_mode(normalize) if np.iscomplexobj(x0): return (_raw_dct(x0.real, type, n, axis, nm, overwrite_x) + 1j * _raw_dct(x0.imag, type, n, axis, nm, overwrite_x)) else: return _raw_dct(x0, type, n, axis, nm, overwrite_x)
Example 24
Project: lambda-packs Author: ryfeus File: realtransforms.py License: MIT License | 5 votes |
def _dst(x, type, n=None, axis=-1, overwrite_x=False, normalize=None): """ Return Discrete Sine Transform of arbitrary type sequence x. Parameters ---------- x : array_like input array. n : int, optional Length of the transform. axis : int, optional Axis along which the dst is computed. (default=-1) overwrite_x : bool, optional If True the contents of x can be destroyed. (default=False) Returns ------- z : real ndarray """ x0, n, copy_made = __fix_shape(x, n, axis, 'DST') if type == 1 and n < 2: raise ValueError("DST-I is not defined for size < 2") overwrite_x = overwrite_x or copy_made nm = _get_norm_mode(normalize) if np.iscomplexobj(x0): return (_raw_dst(x0.real, type, n, axis, nm, overwrite_x) + 1j * _raw_dst(x0.imag, type, n, axis, nm, overwrite_x)) else: return _raw_dst(x0, type, n, axis, nm, overwrite_x)
Example 25
Project: lambda-packs Author: ryfeus File: _testutils.py License: MIT License | 5 votes |
def __repr__(self): """Pretty-printing, esp. for Nose output""" if np.any(list(map(np.iscomplexobj, self.param_columns))): is_complex = " (complex)" else: is_complex = "" if self.dataname: return "<Data for %s%s: %s>" % (self.func.__name__, is_complex, os.path.basename(self.dataname)) else: return "<Data for %s%s>" % (self.func.__name__, is_complex)
Example 26
Project: lambda-packs Author: ryfeus File: filters.py License: MIT License | 5 votes |
def correlate1d(input, weights, axis=-1, output=None, mode="reflect", cval=0.0, origin=0): """Calculate a one-dimensional correlation along the given axis. The lines of the array along the given axis are correlated with the given weights. Parameters ---------- %(input)s weights : array One-dimensional sequence of numbers. %(axis)s %(output)s %(mode)s %(cval)s %(origin)s Examples -------- >>> from scipy.ndimage import correlate1d >>> correlate1d([2, 8, 0, 4, 1, 9, 9, 0], weights=[1, 3]) array([ 8, 26, 8, 12, 7, 28, 36, 9]) """ input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') output, return_value = _ni_support._get_output(output, input) weights = numpy.asarray(weights, dtype=numpy.float64) if weights.ndim != 1 or weights.shape[0] < 1: raise RuntimeError('no filter weights given') if not weights.flags.contiguous: weights = weights.copy() axis = _ni_support._check_axis(axis, input.ndim) if (len(weights) // 2 + origin < 0) or (len(weights) // 2 + origin > len(weights)): raise ValueError('invalid origin') mode = _ni_support._extend_mode_to_code(mode) _nd_image.correlate1d(input, weights, axis, output, mode, cval, origin) return return_value
Example 27
Project: lambda-packs Author: ryfeus File: filters.py License: MIT License | 5 votes |
def uniform_filter1d(input, size, axis=-1, output=None, mode="reflect", cval=0.0, origin=0): """Calculate a one-dimensional uniform filter along the given axis. The lines of the array along the given axis are filtered with a uniform filter of given size. Parameters ---------- %(input)s size : int length of uniform filter %(axis)s %(output)s %(mode)s %(cval)s %(origin)s Examples -------- >>> from scipy.ndimage import uniform_filter1d >>> uniform_filter1d([2, 8, 0, 4, 1, 9, 9, 0], size=3) array([4, 3, 4, 1, 4, 6, 6, 3]) """ input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') axis = _ni_support._check_axis(axis, input.ndim) if size < 1: raise RuntimeError('incorrect filter size') output, return_value = _ni_support._get_output(output, input) if (size // 2 + origin < 0) or (size // 2 + origin >= size): raise ValueError('invalid origin') mode = _ni_support._extend_mode_to_code(mode) _nd_image.uniform_filter1d(input, size, axis, output, mode, cval, origin) return return_value
Example 28
Project: lambda-packs Author: ryfeus File: interpolation.py License: MIT License | 5 votes |
def spline_filter1d(input, order=3, axis=-1, output=numpy.float64): """ Calculates a one-dimensional spline filter along the given axis. The lines of the array along the given axis are filtered by a spline filter. The order of the spline must be >= 2 and <= 5. Parameters ---------- input : array_like The input array. order : int, optional The order of the spline, default is 3. axis : int, optional The axis along which the spline filter is applied. Default is the last axis. output : ndarray or dtype, optional The array in which to place the output, or the dtype of the returned array. Default is `numpy.float64`. Returns ------- spline_filter1d : ndarray or None The filtered input. If `output` is given as a parameter, None is returned. """ if order < 0 or order > 5: raise RuntimeError('spline order not supported') input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') output, return_value = _ni_support._get_output(output, input) if order in [0, 1]: output[...] = numpy.array(input) else: axis = _ni_support._check_axis(axis, input.ndim) _nd_image.spline_filter1d(input, order, axis, output) return return_value
Example 29
Project: lambda-packs Author: ryfeus File: interpolation.py License: MIT License | 5 votes |
def spline_filter(input, order=3, output=numpy.float64): """ Multi-dimensional spline filter. For more details, see `spline_filter1d`. See Also -------- spline_filter1d Notes ----- The multi-dimensional filter is implemented as a sequence of one-dimensional spline filters. The intermediate arrays are stored in the same data type as the output. Therefore, for output types with a limited precision, the results may be imprecise because intermediate results may be stored with insufficient precision. """ if order < 2 or order > 5: raise RuntimeError('spline order not supported') input = numpy.asarray(input) if numpy.iscomplexobj(input): raise TypeError('Complex type not supported') output, return_value = _ni_support._get_output(output, input) if order not in [0, 1] and input.ndim > 0: for axis in range(input.ndim): spline_filter1d(input, order, axis, output=output) input = output else: output[...] = input[...] return return_value
Example 30
Project: lambda-packs Author: ryfeus File: matfuncs.py License: MIT License | 5 votes |
def _maybe_real(A, B, tol=None): """ Return either B or the real part of B, depending on properties of A and B. The motivation is that B has been computed as a complicated function of A, and B may be perturbed by negligible imaginary components. If A is real and B is complex with small imaginary components, then return a real copy of B. The assumption in that case would be that the imaginary components of B are numerical artifacts. Parameters ---------- A : ndarray Input array whose type is to be checked as real vs. complex. B : ndarray Array to be returned, possibly without its imaginary part. tol : float Absolute tolerance. Returns ------- out : real or complex array Either the input array B or only the real part of the input array B. """ # Note that booleans and integers compare as real. if np.isrealobj(A) and np.iscomplexobj(B): if tol is None: tol = {0:feps*1e3, 1:eps*1e6}[_array_precision[B.dtype.char]] if np.allclose(B.imag, 0.0, atol=tol): B = B.real return B ############################################################################### # Matrix functions.