def test_numpy(self): assert chash(np.bool_(True)) == chash(np.bool_(True)) assert chash(np.int8(1)) == chash(np.int8(1)) assert chash(np.int16(1)) assert chash(np.int32(1)) assert chash(np.int64(1)) assert chash(np.uint8(1)) assert chash(np.uint16(1)) assert chash(np.uint32(1)) assert chash(np.uint64(1)) assert chash(np.float32(1)) == chash(np.float32(1)) assert chash(np.float64(1)) == chash(np.float64(1)) assert chash(np.float128(1)) == chash(np.float128(1)) assert chash(np.complex64(1+1j)) == chash(np.complex64(1+1j)) assert chash(np.complex128(1+1j)) == chash(np.complex128(1+1j)) assert chash(np.complex256(1+1j)) == chash(np.complex256(1+1j)) assert chash(np.datetime64('2000-01-01')) == chash(np.datetime64('2000-01-01')) assert chash(np.timedelta64(1,'W')) == chash(np.timedelta64(1,'W')) self.assertRaises(ValueError, chash, np.object()) assert chash(np.array([[1, 2], [3, 4]])) == \ chash(np.array([[1, 2], [3, 4]])) assert chash(np.array([[1, 2], [3, 4]])) != \ chash(np.array([[1, 2], [3, 4]]).T) assert chash(np.array([1, 2, 3])) == chash(np.array([1, 2, 3])) assert chash(np.array([1, 2, 3], dtype=np.int32)) != \ chash(np.array([1, 2, 3], dtype=np.int64))
def test_cublasXtZgemm(self): a = (np.random.rand(4, 4)+1j*np.random.rand(4, 4)).astype(np.complex256) b = (np.random.rand(4, 4)+1j*np.random.rand(4, 4)).astype(np.complex256) c = np.zeros((4, 4), np.complex256) cublasxt.cublasXtZgemm(self.handle, cublasxt._CUBLAS_OP['N'], cublasxt._CUBLAS_OP['N'], 4, 4, 4, np.complex256(1.0), a.ctypes.data, 4, b.ctypes.data, 4, np.complex256(0.0), c.ctypes.data, 4) np.allclose(np.dot(b.T, a.T).T, c)
def test_cublasXtZgemm(self): a = (np.random.rand(4, 4)+1j*np.random.rand(4, 4)).astype(np.complex256) b = (np.random.rand(4, 4)+1j*np.random.rand(4, 4)).astype(np.complex256) c = np.zeros((4, 4), np.complex256) cublasxt.cublasXtZgemm(self.handle, 'N', 'N', 4, 4, 4, np.complex256(1.0), a.ctypes.data, 4, b.ctypes.data, 4, np.complex256(0.0), c.ctypes.data, 4) np.allclose(np.dot(b.T, a.T).T, c)
def test_cublasXtZgemm(self): a = (np.random.rand(4, 4)+1j*np.random.rand(4, 4)).astype(np.complex256) b = (np.random.rand(4, 4)+1j*np.random.rand(4, 4)).astype(np.complex256) c = np.zeros((4, 4), np.complex256) cublasxt.cublasXtDeviceSelect(handle, 2, np.array([0, 1], np.int32).ctypes.data) cublasxt.cublasXtZgemm(self.handle, cublasxt._CUBLAS_OP['N'], cublasxt._CUBLAS_OP['N'], 4, 4, 4, np.complex256(1.0), a.ctypes.data, 4, b.ctypes.data, 4, np.complex256(0.0), c.ctypes.data, 4) np.allclose(np.dot(b.T, a.T).T, c)
def dft(td_data, exp_array = None, return_double = False, inverse = False): N = len(td_data) if exp_array is None: # Make array of exp(-2 pi i f t) to multiply. This is expensive, so only make # the code do it once. exp_array = find_exp_array(N, inverse = inverse) fd_data = np.zeros(N, dtype = np.complex256) # The first term is the DC component, which is just the sum. fd_data[0] = sum(np.complex256(td_data)) # Since this function is most often called by fft(), N is most likely a prime, so assume # there are no more trivial multiplications if N == 2: fd_data[1] += td_data[0] fd_data[1] -= td_data[1] else: for i in range(1, N): fd_data[i] += td_data[0] for j in range(1, N): fd_data[i] += td_data[j] * exp_array[i * j % N] if return_double: return np.complex128(fd_data) else: return fd_data
def test_invalid(self) -> None: prop = bcpp.Int() assert not prop.is_valid(None) assert not prop.is_valid(0.0) assert not prop.is_valid(1.0) assert not prop.is_valid(1.0 + 1.0j) assert not prop.is_valid("") assert not prop.is_valid(()) assert not prop.is_valid([]) assert not prop.is_valid({}) assert not prop.is_valid(_TestHasProps()) assert not prop.is_valid(_TestModel()) assert not prop.is_valid(np.bool8(False)) assert not prop.is_valid(np.bool8(True)) assert not prop.is_valid(np.float16(0)) assert not prop.is_valid(np.float16(1)) assert not prop.is_valid(np.float32(0)) assert not prop.is_valid(np.float32(1)) assert not prop.is_valid(np.float64(0)) assert not prop.is_valid(np.float64(1)) assert not prop.is_valid(np.complex64(1.0 + 1.0j)) assert not prop.is_valid(np.complex128(1.0 + 1.0j)) if hasattr(np, "complex256"): assert not prop.is_valid(np.complex256(1.0 + 1.0j))
def _create_base_matrix(self): # return 15x15 triangle numpy matrix under point model of scattering matrix # assign phases phi = self.mirror_phases theta = self.edge_phases # define shorthand notation for matrix readability def ei(x): return np.complex256(np.exp(1j*x)) sqt2 = np.sqrt(np.complex256(2)) # create matrix non_zero_entries = { (1,0) : 1j*ei(theta['ab']), (1,3) : 1, (2,0) : 1, (2,3) : 1j, (3,7) : ei(phi['a']+theta['ab']), (3,11) : 1j*ei(phi['a']), (4,4) : sqt2, (4,7) : 1j*ei(theta['ab']), (4,11) : 1, (6,5) : 1j*ei(theta['bc']), (6,8) : 1, (7,5) : 1, (7,8) : 1j, (8,1) : 1j*ei(phi['b']), (8,12) : ei(phi['b'] + theta['bc']), (9,1) : 1, (9,9) : sqt2, (9,12) : 1j*ei(theta['bc']), (11,10): 1j*ei(theta['ac']), (11,13): 1, (12,10): 1, (12,13): 1j, (13,2) : ei(phi['c']+theta['ac']), (13,6) : 1j*ei(phi['c']), (14,2) : 1j*ei(theta['ac']), (14,6) : 1, (14,14): sqt2 } base_matrix = np.zeros((15,15), dtype=np.complex256) for idx,non_zero_entry in non_zero_entries.iteritems(): base_matrix[idx] = non_zero_entry return np.multiply(1/sqt2, base_matrix)
def test_invalid(self): prop = bcpp.Int() assert not prop.is_valid(0.0) assert not prop.is_valid(1.0) assert not prop.is_valid(1.0+1.0j) assert not prop.is_valid("") assert not prop.is_valid(()) assert not prop.is_valid([]) assert not prop.is_valid({}) assert not prop.is_valid(_TestHasProps()) assert not prop.is_valid(_TestModel()) assert not prop.is_valid(np.bool8(False)) assert not prop.is_valid(np.bool8(True)) assert not prop.is_valid(np.float16(0)) assert not prop.is_valid(np.float16(1)) assert not prop.is_valid(np.float32(0)) assert not prop.is_valid(np.float32(1)) assert not prop.is_valid(np.float64(0)) assert not prop.is_valid(np.float64(1)) assert not prop.is_valid(np.complex64(1.0+1.0j)) assert not prop.is_valid(np.complex128(1.0+1.0j)) if hasattr(np, "complex256"): assert not prop.is_valid(np.complex256(1.0+1.0j))
def CRAM16(At, N_0): """CRAM uses a Chebishev Rational Approximation Method of order 16 to compute the solution of the matricial depletion equation. Parameters ---------- At: numpy.array Depletion matrix multiplied by the time interval over which nuclides are depleted N_0: numpy.array Initial nuclides' densities vector """ print('CRAM CALLED') t0 = time.time() lN = len(N_0) theta = np.array([ -1.0843917078696988026e1 + 1.9277446167181652284e1j, -5.2649713434426468895 + 1.6220221473167927305e1j, +5.9481522689511774808 + 3.5874573620183222829j, +3.5091036084149180974 + 8.4361989858843750826j, +6.4161776990994341923 + 1.1941223933701386874j, +1.4193758971856659786 + 1.0925363484496722585e1j, +4.9931747377179963991 + 5.9968817136039422260j, -1.4139284624888862114 + 1.3497725698892745389e1j ], dtype=np.complex256) alpha_0 = np.complex256(2.1248537104952237488e-16 + 0.0j) alpha = np.array([ -5.0901521865224915650e-7 - 2.4220017652852287970e-5j, +2.1151742182466030907e-4 + 4.3892969647380673918e-3j, +1.1339775178483930527e2 + 1.0194721704215856450e2j, +1.5059585270023467528e1 - 5.7514052776421819979j, -6.4500878025539646595e1 - 2.2459440762652096056e2j, -1.4793007113557999718 + 1.7686588323782937906j, -6.2518392463207918892e1 - 1.1190391094283228480e1j, +4.1023136835410021273e-2 - 1.5743466173455468191e-1j ], dtype=np.complex256) l = len(theta) N = N_0 * 0 _N = np.zeros((lN), dtype=np.complex128) for i in range(l): term1 = At - theta[i] * np.identity(np.shape(At)[0]) term2 = alpha[i] * N_0 _N += np.linalg.solve(term1, term2) N = 2 * _N.real N = N + alpha_0 * N_0 # For some reason here N is still complex and not only real print('CRAM took:{} s'.format(time.time() - t0)) return N.real
def test_save_longcomplex(self): val = np.complex256(1.01 + 2.3j) data = {'val': val} with pytest.warns(UserWarning) as record: save_data(data, 'bubu' + HEN_FILE_EXTENSION) assert "complex256 yet unsupported" in record[0].message.args[0] data_out = load_data('bubu' + HEN_FILE_EXTENSION) assert np.allclose(data['val'], data_out['val'])
def check_numpy_scalar_argument_return_complex(self): f = PyCFunction('foo') f += Variable('a1', numpy.complex64, 'in, out') f += Variable('a2', numpy.complex128, 'in, out') f += Variable('a3', numpy.complex256, 'in, out') foo = f.build() args = 1+2j,1+2j,1+2j results = (numpy.complex64(1+2j),numpy.complex128(1+2j),numpy.complex256(1+2j)) assert_equal(foo(*args),results) f = PyCFunction('foo') f += Variable('a1', 'npy_complex64', 'in, out') f += Variable('a2', 'npy_complex128', 'in, out') f += Variable('a3', 'npy_complex256', 'in, out') foo = f.build() args = (1+2j, 1+2j, 1+2j) results = (numpy.complex64(1+2j),numpy.complex128(1+2j),numpy.complex256(1+2j)) assert_equal(foo(*args),results)
def check_numpy_scalar_argument_return_complex(self): f = PyCFunction('foo') f += Variable('a1', numpy.complex64, 'in, out') f += Variable('a2', numpy.complex128, 'in, out') f += Variable('a3', numpy.complex256, 'in, out') foo = f.build() args = 1 + 2j, 1 + 2j, 1 + 2j results = (numpy.complex64(1 + 2j), numpy.complex128(1 + 2j), numpy.complex256(1 + 2j)) assert_equal(foo(*args), results) f = PyCFunction('foo') f += Variable('a1', 'npy_complex64', 'in, out') f += Variable('a2', 'npy_complex128', 'in, out') f += Variable('a3', 'npy_complex256', 'in, out') foo = f.build() args = (1 + 2j, 1 + 2j, 1 + 2j) results = (numpy.complex64(1 + 2j), numpy.complex128(1 + 2j), numpy.complex256(1 + 2j)) assert_equal(foo(*args), results)
def test_approx_eq_mixed_types(): assert cirq.approx_eq(np.float32(1), 1.0 + 1e-10, atol=1e-9) assert cirq.approx_eq(np.float64(1), np.complex64(1 + 1e-8j), atol=1e-4) assert cirq.approx_eq(np.uint8(1), np.complex64(1 + 1e-8j), atol=1e-4) if hasattr(np, 'complex256'): assert cirq.approx_eq(np.complex256(1), complex(1, 1e-8), atol=1e-4) assert cirq.approx_eq(np.int32(1), 1, atol=1e-9) assert cirq.approx_eq(complex(0.5, 0), Fraction(1, 2), atol=0.0) assert cirq.approx_eq(0.5 + 1e-4j, Fraction(1, 2), atol=1e-4) assert cirq.approx_eq(0, Fraction(1, 100000000), atol=1e-8) assert cirq.approx_eq(np.uint16(1), Decimal('1'), atol=0.0) assert cirq.approx_eq(np.float64(1.0), Decimal('1.00000001'), atol=1e-8) assert not cirq.approx_eq(np.complex64(1e-5j), Decimal('0.001'), atol=1e-4)
def test_Complex(self): prop = Complex() self.assertTrue(prop.is_valid(None)) # TODO: self.assertFalse(prop.is_valid(False)) # TODO: self.assertFalse(prop.is_valid(True)) self.assertTrue(prop.is_valid(0)) self.assertTrue(prop.is_valid(1)) self.assertTrue(prop.is_valid(0.0)) self.assertTrue(prop.is_valid(1.0)) self.assertTrue(prop.is_valid(1.0 + 1.0j)) self.assertFalse(prop.is_valid("")) self.assertFalse(prop.is_valid(())) self.assertFalse(prop.is_valid([])) self.assertFalse(prop.is_valid({})) self.assertFalse(prop.is_valid(Foo())) try: import numpy as np # TODO: self.assertFalse(prop.is_valid(np.bool8(False))) # TODO: self.assertFalse(prop.is_valid(np.bool8(True))) self.assertTrue(prop.is_valid(np.int8(0))) self.assertTrue(prop.is_valid(np.int8(1))) self.assertTrue(prop.is_valid(np.int16(0))) self.assertTrue(prop.is_valid(np.int16(1))) self.assertTrue(prop.is_valid(np.int32(0))) self.assertTrue(prop.is_valid(np.int32(1))) self.assertTrue(prop.is_valid(np.int64(0))) self.assertTrue(prop.is_valid(np.int64(1))) self.assertTrue(prop.is_valid(np.uint8(0))) self.assertTrue(prop.is_valid(np.uint8(1))) self.assertTrue(prop.is_valid(np.uint16(0))) self.assertTrue(prop.is_valid(np.uint16(1))) self.assertTrue(prop.is_valid(np.uint32(0))) self.assertTrue(prop.is_valid(np.uint32(1))) self.assertTrue(prop.is_valid(np.uint64(0))) self.assertTrue(prop.is_valid(np.uint64(1))) self.assertTrue(prop.is_valid(np.float16(0))) self.assertTrue(prop.is_valid(np.float16(1))) self.assertTrue(prop.is_valid(np.float32(0))) self.assertTrue(prop.is_valid(np.float32(1))) self.assertTrue(prop.is_valid(np.float64(0))) self.assertTrue(prop.is_valid(np.float64(1))) self.assertTrue(prop.is_valid(np.complex64(1.0 + 1.0j))) self.assertTrue(prop.is_valid(np.complex128(1.0 + 1.0j))) self.assertTrue(prop.is_valid(np.complex256(1.0 + 1.0j))) except ImportError: pass
def test_Complex(self): prop = Complex() self.assertTrue(prop.is_valid(None)) # TODO: self.assertFalse(prop.is_valid(False)) # TODO: self.assertFalse(prop.is_valid(True)) self.assertTrue(prop.is_valid(0)) self.assertTrue(prop.is_valid(1)) self.assertTrue(prop.is_valid(0.0)) self.assertTrue(prop.is_valid(1.0)) self.assertTrue(prop.is_valid(1.0+1.0j)) self.assertFalse(prop.is_valid("")) self.assertFalse(prop.is_valid(())) self.assertFalse(prop.is_valid([])) self.assertFalse(prop.is_valid({})) self.assertFalse(prop.is_valid(Foo())) try: import numpy as np # TODO: self.assertFalse(prop.is_valid(np.bool8(False))) # TODO: self.assertFalse(prop.is_valid(np.bool8(True))) self.assertTrue(prop.is_valid(np.int8(0))) self.assertTrue(prop.is_valid(np.int8(1))) self.assertTrue(prop.is_valid(np.int16(0))) self.assertTrue(prop.is_valid(np.int16(1))) self.assertTrue(prop.is_valid(np.int32(0))) self.assertTrue(prop.is_valid(np.int32(1))) self.assertTrue(prop.is_valid(np.int64(0))) self.assertTrue(prop.is_valid(np.int64(1))) self.assertTrue(prop.is_valid(np.uint8(0))) self.assertTrue(prop.is_valid(np.uint8(1))) self.assertTrue(prop.is_valid(np.uint16(0))) self.assertTrue(prop.is_valid(np.uint16(1))) self.assertTrue(prop.is_valid(np.uint32(0))) self.assertTrue(prop.is_valid(np.uint32(1))) self.assertTrue(prop.is_valid(np.uint64(0))) self.assertTrue(prop.is_valid(np.uint64(1))) self.assertTrue(prop.is_valid(np.float16(0))) self.assertTrue(prop.is_valid(np.float16(1))) self.assertTrue(prop.is_valid(np.float32(0))) self.assertTrue(prop.is_valid(np.float32(1))) self.assertTrue(prop.is_valid(np.float64(0))) self.assertTrue(prop.is_valid(np.float64(1))) self.assertTrue(prop.is_valid(np.complex64(1.0+1.0j))) self.assertTrue(prop.is_valid(np.complex128(1.0+1.0j))) self.assertTrue(prop.is_valid(np.complex256(1.0+1.0j))) except ImportError: pass
def test_invalid(self): prop = bcpp.Float() assert not prop.is_valid(1.0 + 1.0j) assert not prop.is_valid("") assert not prop.is_valid(()) assert not prop.is_valid([]) assert not prop.is_valid({}) assert not prop.is_valid(_TestHasProps()) assert not prop.is_valid(_TestModel()) assert not prop.is_valid(np.bool8(False)) assert not prop.is_valid(np.bool8(True)) assert not prop.is_valid(np.complex64(1.0 + 1.0j)) assert not prop.is_valid(np.complex128(1.0 + 1.0j)) if hasattr(np, "complex256"): assert not prop.is_valid(np.complex256(1.0 + 1.0j))
def __read_coefComp_previ(self): fit = open("./coef/" + self.fit + ".cnf", "r") lis = fit.readlines() fit.close() coef = [] nom = [] for i, item in enumerate(lis): aux = [] linia = item.replace("\n", "") tros = linia.split(" ") for j, jtem in enumerate(tros): if (is_real(jtem)): aux.append(np.float128(jtem)) elif (is_complex(jtem)): aux.append(np.complex256(complex(jtem))) elif (j == 0): nom.append(jtem[0]) if (len(aux) > 0): coef.append(aux) return nom, coef
def test_valid(self): prop = bcpp.Complex() assert prop.is_valid(None) assert prop.is_valid(0) assert prop.is_valid(1) assert prop.is_valid(0.0) assert prop.is_valid(1.0) assert prop.is_valid(1.0+1.0j) assert prop.is_valid(np.int8(0)) assert prop.is_valid(np.int8(1)) assert prop.is_valid(np.int16(0)) assert prop.is_valid(np.int16(1)) assert prop.is_valid(np.int32(0)) assert prop.is_valid(np.int32(1)) assert prop.is_valid(np.int64(0)) assert prop.is_valid(np.int64(1)) assert prop.is_valid(np.uint8(0)) assert prop.is_valid(np.uint8(1)) assert prop.is_valid(np.uint16(0)) assert prop.is_valid(np.uint16(1)) assert prop.is_valid(np.uint32(0)) assert prop.is_valid(np.uint32(1)) assert prop.is_valid(np.uint64(0)) assert prop.is_valid(np.uint64(1)) assert prop.is_valid(np.float16(0)) assert prop.is_valid(np.float16(1)) assert prop.is_valid(np.float32(0)) assert prop.is_valid(np.float32(1)) assert prop.is_valid(np.float64(0)) assert prop.is_valid(np.float64(1)) assert prop.is_valid(np.complex64(1.0+1.0j)) assert prop.is_valid(np.complex128(1.0+1.0j)) if hasattr(np, "complex256"): assert prop.is_valid(np.complex256(1.0+1.0j)) # TODO (bev) should fail assert prop.is_valid(False) assert prop.is_valid(True)
def test_invalid(self): prop = bcpp.Bool() assert not prop.is_valid(0) assert not prop.is_valid(1) assert not prop.is_valid(0.0) assert not prop.is_valid(1.0) assert not prop.is_valid(1.0 + 1.0j) assert not prop.is_valid("") assert not prop.is_valid(()) assert not prop.is_valid([]) assert not prop.is_valid({}) assert not prop.is_valid(_TestHasProps()) assert not prop.is_valid(_TestModel()) assert not prop.is_valid(np.int8(0)) assert not prop.is_valid(np.int8(1)) assert not prop.is_valid(np.int16(0)) assert not prop.is_valid(np.int16(1)) assert not prop.is_valid(np.int32(0)) assert not prop.is_valid(np.int32(1)) assert not prop.is_valid(np.int64(0)) assert not prop.is_valid(np.int64(1)) assert not prop.is_valid(np.uint8(0)) assert not prop.is_valid(np.uint8(1)) assert not prop.is_valid(np.uint16(0)) assert not prop.is_valid(np.uint16(1)) assert not prop.is_valid(np.uint32(0)) assert not prop.is_valid(np.uint32(1)) assert not prop.is_valid(np.uint64(0)) assert not prop.is_valid(np.uint64(1)) assert not prop.is_valid(np.float16(0)) assert not prop.is_valid(np.float16(1)) assert not prop.is_valid(np.float32(0)) assert not prop.is_valid(np.float32(1)) assert not prop.is_valid(np.float64(0)) assert not prop.is_valid(np.float64(1)) assert not prop.is_valid(np.complex64(1.0 + 1.0j)) assert not prop.is_valid(np.complex128(1.0 + 1.0j)) if hasattr(np, "complex256"): assert not prop.is_valid(np.complex256(1.0 + 1.0j))
def test_valid(self): prop = bcpp.Complex() assert prop.is_valid(None) assert prop.is_valid(0) assert prop.is_valid(1) assert prop.is_valid(0.0) assert prop.is_valid(1.0) assert prop.is_valid(1.0 + 1.0j) assert prop.is_valid(np.int8(0)) assert prop.is_valid(np.int8(1)) assert prop.is_valid(np.int16(0)) assert prop.is_valid(np.int16(1)) assert prop.is_valid(np.int32(0)) assert prop.is_valid(np.int32(1)) assert prop.is_valid(np.int64(0)) assert prop.is_valid(np.int64(1)) assert prop.is_valid(np.uint8(0)) assert prop.is_valid(np.uint8(1)) assert prop.is_valid(np.uint16(0)) assert prop.is_valid(np.uint16(1)) assert prop.is_valid(np.uint32(0)) assert prop.is_valid(np.uint32(1)) assert prop.is_valid(np.uint64(0)) assert prop.is_valid(np.uint64(1)) assert prop.is_valid(np.float16(0)) assert prop.is_valid(np.float16(1)) assert prop.is_valid(np.float32(0)) assert prop.is_valid(np.float32(1)) assert prop.is_valid(np.float64(0)) assert prop.is_valid(np.float64(1)) assert prop.is_valid(np.complex64(1.0 + 1.0j)) assert prop.is_valid(np.complex128(1.0 + 1.0j)) if hasattr(np, "complex256"): assert prop.is_valid(np.complex256(1.0 + 1.0j)) # TODO (bev) should fail assert prop.is_valid(False) assert prop.is_valid(True)
def full_source_from_model(self, m, nix, **kwargs): """Use the data from a model at a timestep nix to calculate the full source term S.""" #Get background values bgvars = m.yresult[nix, 0:3, 0] a = m.ainit*np.exp(m.tresult[nix]) if np.any(np.isnan(bgvars[0])): raise AttributeError("Background values not available for this timestep.") k = self.srceqns.k #Get potentials potentials = m.potentials(np.array([bgvars[0]]), m.pot_params) Cterms = self.calculate_Cterms(bgvars, a, potentials) results = np.complex256(self.J_terms[0](k, Cterms, **kwargs)) #Get component integrals for term in self.J_terms[1:]: results += term(k, Cterms, **kwargs) src = 1 / ((2*np.pi)**2) * results return src
def rdft(td_data, exp_array = None, return_double = False, return_full = False): N = len(td_data) N_out = N // 2 + 1 if exp_array is None: # Make array of exp(-2 pi i f t) to multiply. This is expensive, so only make # the code do it once. exp_array = find_exp_array(N) if return_full: fd_data = np.zeros(N, dtype = np.complex256) else: fd_data = np.zeros(N_out, dtype = np.complex256) # The first term is the DC component, which is just the sum. fd_data[0] = sum(np.complex256(td_data)) # Since this function is most often called by fft(), N is most likely a prime, so assume # there are no more trivial multiplications if N == 2: fd_data[1] += td_data[0] fd_data[1] -= td_data[1] else: for i in range(1, N_out): fd_data[i] += td_data[0] for j in range(1, N): fd_data[i] += td_data[j] * exp_array[i * j % N] if return_full and N > 2: # Then fill in the second half fd_data[N_out : N] = np.conj(fd_data[1 : N - N_out + 1][::-1]) if return_double: return np.complex128(fd_data) else: return fd_data
def fft(td_data, prime_factors = None, exp_array = None, return_double = False, inverse = False, M = None, M_prime_factors = None, M_exp_array2 = None, M_exp_array = None): N = len(td_data) if N < 2: if return_double: return np.complex128(td_data) else: return np.complex256(td_data) if prime_factors is None: # Find prime factors prime_factors = find_prime_factors(N) # Check if we will need to use prime_fft() for this if prime_factors[-2] >= 37: # Find the first member greater than or equal to 37 i = 0 while prime_factors[i] < 37: i += 1 M, M_prime_factors = find_M(2 * np.product(prime_factors[i:]) - 1) M_exp_array2 = find_exp_array2(np.product(prime_factors[i:]), inverse = inverse) M_exp_array = find_exp_array(M) if exp_array is None and prime_factors[0] < 37: # Make array of exp(-2 pi i f t) to multiply. This is expensive, so only make # the code do it once. exp_array = find_exp_array(N, inverse = inverse) if prime_factors[0] >= 37: # Use Bluestein's algorithm for a prime-length fft return prime_fft(td_data, return_double = return_double, inverse = inverse, exp_array2 = M_exp_array2, M = M, prime_factors = M_prime_factors, exp_array = M_exp_array) elif prime_factors[0] == N: # Do an ordinary DFT return dft(td_data, exp_array = exp_array, return_double = return_double) else: # We will break this up into smaller Fourier transforms fd_data = np.zeros(N, dtype = np.complex256) num_ffts = prime_factors[0] N_mini = N // num_ffts for i in range(num_ffts): fd_data[i * N_mini : (i + 1) * N_mini] = fft(td_data[i::num_ffts], prime_factors = prime_factors[1:], exp_array = exp_array[::num_ffts], return_double = False, M = M, M_prime_factors = M_prime_factors, M_exp_array2 = M_exp_array2, M_exp_array = M_exp_array) # Now we need to "mix" the output appropriately. First, copy all but the first fft. fd_data_copy = np.copy(fd_data[N_mini:]) # Apply phase rotations to all but the first fft for i in range(N_mini, N): exp_index = (i * (i // N_mini)) % N # Do a multiplication only if we have to if(exp_index): fd_data[i] *= exp_array[exp_index] # Add the first fft to all the others for i in range(N_mini, N, N_mini): fd_data[i : i + N_mini] += fd_data[:N_mini] # Now we have to use the copied data. Apply phase rotations and add to all other locations. for i in range(N_mini, N): copy_index = i - N_mini dst_indices = list(range(i % N_mini, N, N_mini)) # We've already taken care of the below contribution (2 for loops ago), so remove it dst_indices.remove(i) for j in dst_indices: exp_index = (j * (i // N_mini)) % N # Do a multiplication only if we have to if(exp_index): fd_data[j] += fd_data_copy[copy_index] * exp_array[exp_index] else: fd_data[j] += fd_data_copy[copy_index] # Done if return_double: return np.complex128(fd_data) else: return fd_data
def ei(x): return np.complex256(np.exp(1j*x))
def resample(data, N_out, return_double = False): N_out = int(N_out) # Number of input samples N_in = len(data) # Max and min N_max = max(N_in, N_out) N_min = min(N_in, N_out) if N_in < 2 or N_in == N_out: return data # Is the input data complex? If so, the output should be as well. is_complex = isinstance(data[0], complex) if N_out == 0: if is_complex: if return_double: return np.array([], dtype = np.complex128) else: return np.array([], dtype = np.complex256) else: if return_double: return np.array([], dtype = np.float64) else: return np.array([], dtype = np.float128) if N_out == 1: # Return the average return np.array([sum(data) / N_in]) if is_complex: resampled = np.zeros(N_out, dtype = np.complex256) else: resampled = np.zeros(N_out, dtype = np.float128) if N_in == 2: # Linear interpolation. If we've reached this point, we know that N_out >= 3. if is_complex: diff = np.complex256(data[1]) - np.complex256(data[0]) else: diff = np.float128(data[1]) - np.float128(data[0]) resampled = diff * np.array(range(N_out)) / (N_out - 1) + data[0] else: # Are we upsampling or downsampling? upordown = 'up' if N_in < N_out else 'down' # Find the least common multiple of input and output lengths to determine the # lenth of the sinc array. short_length = N_min - 1 long_length = N_max - 1 LCM = long_length while LCM % short_length: LCM += long_length # Number of sinc taps per sample at the higher sample rate sinc_taps_per_sample = LCM // long_length # Number of sinc taps per sample at the lower sample rate long_sinc_taps_per_sample = LCM // short_length sinc_length = min(N_min, 192) * long_sinc_taps_per_sample sinc_length -= (sinc_length + 1) % 2 sinc = np.zeros(sinc_length, dtype = np.float128) sinc[sinc_length // 2] = 1.0 # Frequency resolution in units of frequency bins of sinc alpha = (1 + min(192, N_min) / 24.0) # Low-pass cutoff frequency as a fraction of the sampling frequency of sinc f_cut = 0.5 / long_sinc_taps_per_sample - alpha / sinc_length if f_cut > 0: for i in range(1, sinc_length // 2 + 1): sinc[sinc_length // 2 + i] = sinc[sinc_length // 2 - i] = np.sin(two_pi * ((f_cut * i) % 1)) / (two_pi * f_cut * i) else: sinc = np.ones(sinc_length, dtype = np.float128) # Apply a Kaiser window. Note that the chosen cutoff frequency is below the # lower Nyquist rate just enough to be at the end of the main lobe. sinc *= kaiser(sinc_length, pi * alpha) # Normalize the sinc filter. Since, in general, not every tap gets used for # each output sample, the normalization has to be done this way: if upordown == 'down': taps_per_input = sinc_taps_per_sample taps_per_output = long_sinc_taps_per_sample else: taps_per_input = long_sinc_taps_per_sample taps_per_output = sinc_taps_per_sample for i in range(taps_per_input): sinc[i::taps_per_input] /= np.sum(sinc[i::taps_per_input]) # Extend the input array at the ends to prepare for filtering half_sinc_length = sinc_length // 2 N_ext = half_sinc_length // taps_per_input data = np.concatenate((-data[1:1+N_ext][::-1] + 2 * np.real(data[0]), data, -data[-N_ext-1:-1][::-1] + 2 * np.real(data[-1]))) # Filter. The center of sinc should line up with the first and last input # at the first and last output, respectively. for i in range(N_out): sinc_start = (half_sinc_length - i * taps_per_output % taps_per_input) % taps_per_input data_start = (i * taps_per_output - half_sinc_length + N_ext * taps_per_input + taps_per_input - 1) // taps_per_input sinc_subset = sinc[sinc_start::taps_per_input] resampled[i] = np.sum(sinc_subset * data[data_start:data_start+len(sinc_subset)]) if return_double: if is_complex: return np.complex128(resampled) else: return np.float64(resampled) else: return resampled
import numpy as np ''' np.int32 np.int16 np.int64 np.uint8 вещественные типы np.float32 np.float64 комплескные числа np.complex128 np.complex256 (мб его нет) булевский тип np.bool ___________________________________________ ''' # Создание массива: # из списка a = [1, 2, 3] ar = np.array(a) print(ar.shape) # измерение = 3 print(ar.size) # общее кол-во эл-тов b = [[1, 2, 3], [4, 5, 6], [7, 8, 9]] br = np.array(b, dtype=np.float64) print(br.shape)
def test_complex256_array5(self): self.run_test('def complex256_array5(x): return x', np.complex256(1 + 1j), complex256_array5=[np.complex256])
# %% arr = np.asanyarray( proxy_img.dataobj ) # array will create a copy; asarray passes through arrays; asanyarray passes subclasses like memmap through print(arr.dtype) arr # %% [markdown] # Memory maps are arrays that remain on disk, rather than in RAM. This is only possible with uncompressed images. # # We can also cast to any type we please, however unwisely. # %% print(np.uint8(proxy_img.dataobj)) # Values over 255 will be truncated print(np.complex256(proxy_img.dataobj)) # A life less ordinal # %% [markdown] slideshow={"slide_type": "subslide"} # ### Indexing and slicing array proxies # # One of the primary motivations for an array proxy is to avoid loading data unnecessarily. Accessing the array proxy with array indices or slices will return the requested values without loading other data: # %% slideshow={"slide_type": "-"} print(proxy_img.dataobj[0]) print(proxy_img.dataobj[..., 1:3]) # %% [markdown] # For example, this is useful for fetching a single volume from a BOLD series: # %% vol0 = bold.dataobj[..., 0]
def rfft(td_data, prime_factors = None, exp_array = None, return_double = False, return_full = False, M = None, M_prime_factors = None, M_exp_array2 = None, M_exp_array = None): N = len(td_data) N_out = N // 2 + 1 if N < 2: if return_double: return np.complex128(td_data) else: return np.complex256(td_data) if prime_factors is None: # Find prime factors prime_factors = find_prime_factors(N) # Check if we will need to use prime_rfft() for this if prime_factors[-2] >= 61: # Find the first member greater than or equal to 61 i = 0 while prime_factors[i] < 61: i += 1 M_in = np.product(prime_factors[i:]) M_out = M_in // 2 + 1 M, M_prime_factors = find_M(M_in + M_out - 1) M_exp_array2 = find_exp_array2(M_in) M_exp_array = find_exp_array(M) if exp_array is None and prime_factors[0] < 61: # Make array of exp(-2 pi i f t) to multiply. This is expensive, so only make # the code do it once. exp_array = find_exp_array(N) if prime_factors[0] >= 61: # Use Bluestein's algorithm for a prime-length fft return prime_rfft(td_data, return_double = return_double, return_full = return_full, exp_array2 = M_exp_array2, M = M, prime_factors = M_prime_factors, exp_array = M_exp_array) elif prime_factors[0] == N: # Do an ordinary DFT return rdft(td_data, exp_array = exp_array, return_double = return_double, return_full = return_full) else: # We will break this up into smaller Fourier transforms. Therefore, we still # need to allocate enough memory for N elements. fd_data = np.zeros(N, dtype = np.complex256) num_ffts = prime_factors[0] N_mini = N // num_ffts N_mini_out = N_mini // 2 + 1 for i in range(num_ffts): fd_data[i * N_mini : (i + 1) * N_mini] = rfft(td_data[i::num_ffts], prime_factors = prime_factors[1:], exp_array = exp_array[::num_ffts], return_double = False, return_full = True, M = M, M_prime_factors = M_prime_factors, M_exp_array2 = M_exp_array2, M_exp_array = M_exp_array) # Now we need to "mix" the output appropriately. First, copy all but the first fft. populated_indices = [x for x in range(N_mini, N) if x % N_mini < N_mini_out] fd_data_copy = fd_data[populated_indices] # Apply phase rotations to all but the first fft for i in range(N_mini, N_out): exp_index = (i * (i // N_mini)) % N # Do a multiplication only if we have to if(exp_index): fd_data[i] *= exp_array[exp_index] # Add the first fft to all the others for i in range(N_mini, N_out, N_mini): fd_data[i : i + N_mini] += fd_data[:N_mini] # Now we have to use the copied data. Apply phase rotations and add to all other locations. for i in range(len(fd_data_copy)): original_index = N_mini + i // N_mini_out * N_mini + i % N_mini_out dst_indices = list(range(original_index % N_mini, N_out, N_mini)) if original_index in dst_indices: # We've already taken care of this contribution (2 for loops ago), so remove it dst_indices.remove(original_index) for j in dst_indices: exp_index = (j * (original_index // N_mini)) % N # Do a multiplication only if we have to if(exp_index): fd_data[j] += fd_data_copy[i] * exp_array[exp_index] else: fd_data[j] += fd_data_copy[i] if original_index % N_mini and original_index % N_mini < (N_mini + 1) // 2: # Then handle the contribution from the complex conjugate original_index += N_mini - 2 * (original_index % N_mini) dst_indices = list(range(original_index % N_mini, N_out, N_mini)) if original_index in dst_indices: # We've already taken care of this contribution, so remove it dst_indices.remove(original_index) for j in dst_indices: exp_index = (j * (original_index // N_mini)) % N # Do a multiplication only if we have to if(exp_index): fd_data[j] += np.conj(fd_data_copy[i]) * exp_array[exp_index] else: fd_data[j] += np.conj(fd_data_copy[i]) if not N % 2: # The Nyquist component is real fd_data[N_out - 1] = np.real(fd_data[N_out - 1]) + 0j if return_full and N > 2: # Then fill in the second half fd_data[N_out : N] = np.conj(fd_data[1 : N - N_out + 1][::-1]) if return_double: return np.complex128(fd_data) else: return fd_data else: # Shorten the array if return_double: return np.complex128(fd_data[:N_out]) else: return fd_data[:N_out]
def ei(x): return np.complex256(np.exp(1j*x)) non_zero_entries = {
ax1 = pylab.subplot2grid((2, 2), (0, 0)) draw_pz("Unquantized Pairs", pairs) pylab.subplot2grid((2, 2), (0, 1), sharex=ax1, sharey=ax1) draw_pz("Quantized Pairs", fqpairs) print("") print( "***********************************************************************") print("Quantized pole-zero pairs") print( "***********************************************************************") for (pair, qpair) in zip(pairs, fqpairs): print "Poles:" print map(np.abs, np.complex256(qpair[0])) print "Zeros:" print map(np.abs, np.complex256(qpair[1])) if max(map(abs, qpair[0])) > 1.0: print "Warning! Quantized pole outside of unit circle!" print "Unquantized Poles:" print map(np.abs, np.float128(pair[0])) print "Unquantized Zeros:" print map(np.abs, np.float128(pair[1])) print("") print( "***********************************************************************") print("Quantized sections (Q{}.{}):".format(31 - frac_bits, frac_bits)) print( "***********************************************************************")
numpy_type_dict = { type(int()): '<i8', # type(np.float128()): '<f16', # type(np.complex256()): '<c32', type(complex()): '<c16', # type(str()): '|S1', # added below depending on version type(bool()): '|b1', type(float()): '<f8', } else: numpy_type_dict = { type(int()): '<i8', type(np.float128()): '<f16', type(np.complex256()): '<c32', type(complex()): '<c16', # type(str()): '|S1', # added below depending on version type(bool()): '|b1', type(float()): '<f8', } if sys.version_info[0] == 2: numpy_type_dict.update({ type(long()): '<i8', type(unicode()): '|U1', type(str()): '|S1' }) else: numpy_type_dict.update({ type(str()): '|U1',
# type(np.float128()): '<f16', # type(np.complex256()): '<c32', type(complex()): '<c16', # type(str()): '|S1', # added below depending on version type(bool()): '|b1', type(float()): '<f8', } else: numpy_type_dict = { type(int()): '<i8', type(np.float128()): '<f16', type(np.complex256()): '<c32', type(complex()): '<c16', # type(str()): '|S1', # added below depending on version type(bool()): '|b1', type(float()): '<f8', } if sys.version_info[0] == 2: numpy_type_dict.update({ type(long()): '<i8', type(unicode()): '|U1', type(str()): '|S1' }) else: numpy_type_dict.update({type(str()): '|U1', type(bytes()): '|S1'})
import numpy as np reveal_type(np.uint128()) reveal_type(np.uint256()) reveal_type(np.int128()) reveal_type(np.int256()) reveal_type(np.float80()) reveal_type(np.float96()) reveal_type(np.float128()) reveal_type(np.float256()) reveal_type(np.complex160()) reveal_type(np.complex192()) reveal_type(np.complex256()) reveal_type(np.complex512())
def run(self): while self.isRunning(): self.mutex.lock() devicePixelRatio = self.devicePixelRatio resultSize = self.resultSize * devicePixelRatio requestedScaleFactor = self.scaleFactor scaleFactor = requestedScaleFactor / devicePixelRatio centerX = self.centerX centerY = self.centerY self.mutex.unlock() halfWidth = resultSize.width() // 2 halfHeight = resultSize.height() // 2 image = QImage(resultSize, QImage.Format_RGB32) image.setDevicePixelRatio(devicePixelRatio) NumPasses = 8 curpass = 0 while curpass < NumPasses: Limit = int(BailoutRadius) allBlack = True for y in range(-halfHeight, halfHeight): if self.restart: break if self.abort: return ay = (centerY + (y * scaleFactor)) ayy = 1j * (centerY + (y * scaleFactor)) for x in range(-halfWidth, halfWidth): c0 = centerX + (x * scaleFactor) + ayy c = complex(Decimal(StartRe), Decimal(StartIm)) ax = centerX + (x * scaleFactor) a1 = ax b1 = ay if PrecisionVal == "Single": c = np.complex64(c) c0 = np.complex64(c0) elif PrecisionVal == "Double": c = np.complex128(c) c0 = np.complex128(c0) elif PrecisionVal == "Triple": c = np.clongdouble(c) c0 = np.clongdouble(c0) elif PrecisionVal == "Quadruple": c = np.complex256(c) c0 = np.complex256(c0) elif PrecisionVal == "Multiple": c = mp.mpc(c) c0 = mp.mpc(c0) # print(c0) numIterations = 0 while numIterations < int(MaxIterations): numIterations += 1 if fractalType == "Mandelbrot": c = pow(c, float(PowerRe)) + c0 if abs(c) > Limit: break elif fractalType == "Fast Mandelbrot": a2 = (a1 * a1) - (b1 * b1) + ax b2 = (a1 * b1 * 2) + ay if (a2 * a2) + (b2 * b2) > Limit * 2: break numIterations += 1 a1 = (a2 * a2) - (b2 * b2) + ax b1 = (a2 * b2 * 2) + ay if (a1 * a1) + (b1 * b1) > Limit * 2: break elif fractalType == "Tricorn / Mandelbar": if not IsInverse: c = np.conj(pow(c, float(PowerRe))) + c0 else: c = np.conj(pow(c, float(PowerRe))) + 1 / c0 if abs(c) >= Limit: break elif fractalType == "Burning Ship": if not IsInverse: c = pow((abs(c.real) + abs(c.imag) * 1j), float(PowerRe)) + c0 else: c = pow((abs(c.real) + abs(c.imag) * 1j), float(PowerRe)) + 1 / c0 if abs(c) >= Limit: break elif fractalType == "MandelShip": if not IsInverse: c = pow(c, float(PowerRe)) + c0 if abs(c) >= Limit: break numIterations += 1 c = pow((abs(c.real) + abs(c.imag) * 1j), float(PowerRe)) + c0 if abs(c) >= Limit: break numIterations += 1 c = pow(c, float(PowerRe)) + c0 if abs(c) >= Limit: break numIterations += 1 c = pow(c, float(PowerRe)) + c0 if abs(c) >= Limit: break else: c = pow(c, float(PowerRe)) + 1 / c0 if abs(c) >= Limit: break numIterations += 1 c = pow((abs(c.real) + abs(c.imag) * 1j), float(PowerRe)) + 1 / c0 if abs(c) >= Limit: break numIterations += 1 c = pow(c, float(PowerRe)) + 1 / c0 if abs(c) >= Limit: break numIterations += 1 c = pow(c, float(PowerRe)) + 1 / c0 if abs(c) >= Limit: break elif fractalType == "Perpendicular Mandelbrot": c = pow((abs(c.real) - c.imag * 1j), float(PowerRe)) + c0 if abs(c) >= Limit: break elif fractalType == "Perpendicular Burning Ship": c = pow((c.real + abs(c.imag) * 1j), float(PowerRe)) + c0 if abs(c) >= Limit: break elif fractalType == "Perpendicular Celtic": a2 = abs((a1 * a1) - (b1 * b1)) + ax b2 = abs(a1) * b1 * -2 + ay if (a2 * a2) + (b2 * b2) > Limit * 2: break numIterations += 1 a1 = abs((a2 * a2) - (b2 * b2)) + ax b1 = abs(a2) * b2 * -2 + ay if (a1 * a1) + (b1 * b1) > Limit * 2: break elif fractalType == "Perpendicular Buffalo": a1sqr = a1 * a1 b1sqr = b1 * b1 a2sqr = a2 * a2 b2sqr = b2 * b2 a2 = abs(a1sqr - b1sqr) + ax b2 = a1 * abs(b1) * -2 + ay if (a1 * a1) + (b1 * b1) > Limit * 2: break numIterations += 1 a1 = abs(a2sqr - b2sqr) + ax b1 = a2 * abs(b2) * -2 + ay if (a2 * a2) + (b2 * b2) > Limit * 2: break elif fractalType == "Mandelbrot Heart": c = pow((abs(c.real) + c.imag * 1j), float(PowerRe)) + c0 if abs(c) >= Limit: break elif fractalType == "Buffalo": c = pow(((abs(c.real) + abs(c.imag) * 1j) + c0 / 2), float(PowerRe)) + pow( c0 / 2 + (abs(c.real) + abs(c.imag) * 1j), float(PowerRe)) if abs(c) >= Limit: break elif fractalType == "Celtic Mandelbrot": c = pow( ((abs(c.real) + c.imag * 1j) + c0 / 2), float(PowerRe)) + pow( c0 / 2 + (abs(c.real) + c.imag * 1j), float(PowerRe)) if abs(c) >= Limit: break elif fractalType == "Celtic Mandelbar": c = pow( ((abs(c.real) - c.imag * 1j) + c0 / 2), float(PowerRe)) + pow( c0 / 2 + (abs(c.real) - c.imag * 1j), float(PowerRe)) if abs(c) >= Limit: break elif fractalType == "Celtic Heart": a2 = abs((a1 * a1) - (b1 * b1)) + ax b2 = abs(a1) * b1 * 2 + ay if (a2 * a2) + (b2 * b2) > Limit * 2: break numIterations += 1 a1 = abs((a2 * a2) - (b2 * b2)) + ax b1 = abs(a2) * b2 * 2 + ay if (a1 * a1) + (b1 * b1) > Limit * 2: break elif fractalType == "Ultra Hybrid": # Mandelbrot c = pow(c, float(PowerRe)) + c0 if abs(c) >= Limit: break numIterations += 1 # Burning Ship c = pow( abs(c.real) + 1j * abs(c.imag), float(PowerRe)) + c0 if abs(c) >= Limit: break numIterations += 1 # Tricorn / Mandelbar c = pow(np.conj(c), float(PowerRe)) + c0 if abs(c) >= Limit: break numIterations += 1 # Perpendicular Mandelbrot c = pow((abs(c.real) - c.imag * 1j), float(PowerRe)) + c0 if abs(c) >= Limit: break # Perpendicular Burning Ship numIterations += 1 c = pow((c.real + abs(c.imag) * 1j), float(PowerRe)) + c0 if abs(c) >= Limit: break numIterations += 1 elif fractalType == "Psuedo Mandelbrot": # Basically the mandelbrot except using irrational power values can result in a different mandelbrot. c = c0 - pow(c, float(PowerRe)) if abs(c) >= Limit: break # Does not work, need a suggestion from contributors. #elif fractalType == "Custom": # def custom(c, c0, Limit): # c = c+c0 # if abs(c) >= Limit: # return 0 # return c # custom(c*c, c0, Limit) if numIterations < int(MaxIterations): image.setPixel( x + halfWidth, y + halfHeight, self.colormap[numIterations % RenderThread.ColormapSize]) allBlack = False else: image.setPixel(x + halfWidth, y + halfHeight, qRgb(0, 0, 0)) if allBlack and curpass == 0: curpass = 4 else: if not self.restart: self.renderedImage.emit( image, np.float128(requestedScaleFactor)) curpass += 1 self.mutex.lock() if not self.restart: self.condition.wait(self.mutex) self.restart = False self.mutex.unlock()