def ifftshift(x,axes=None): """ Inverse of fftshift. Parameters ---------- x : array_like Input array. axes : int or shape tuple, optional Axes over which to calculate. Defaults to None which is over all axes. See Also -------- fftshift """ tmp = asarray(x) ndim = len(tmp.shape) if axes is None: axes = range(ndim) y = tmp for k in axes: n = tmp.shape[k] p2 = n-(n+1)/2 mylist = concatenate((arange(p2,n),arange(p2))) y = take(y,mylist,k) return y
def fftshift(x,axes=None): """ Shift zero-frequency component to center of spectrum. This function swaps half-spaces for all axes listed (defaults to all). If len(x) is even then the Nyquist component is y[0]. Parameters ---------- x : array_like Input array. axes : int or shape tuple, optional Axes over which to shift. Default is None which shifts all axes. See Also -------- ifftshift """ tmp = asarray(x) ndim = len(tmp.shape) if axes is None: axes = range(ndim) y = tmp for k in axes: n = tmp.shape[k] p2 = (n+1)/2 mylist = concatenate((arange(p2,n),arange(p2))) y = take(y,mylist,k) return y
def fftshift(x, axes=None): """ Shift the zero-frequency component to the center of the spectrum. This function swaps half-spaces for all axes listed (defaults to all). Note that ``y[0]`` is the Nyquist component only if ``len(x)`` is even. Parameters ---------- x : array_like Input array. axes : int or shape tuple, optional Axes over which to shift. Default is None, which shifts all axes. Returns ------- y : ndarray The shifted array. See Also -------- ifftshift : The inverse of `fftshift`. Examples -------- >>> freqs = np.fft.fftfreq(10, 0.1) >>> freqs array([ 0., 1., 2., 3., 4., -5., -4., -3., -2., -1.]) >>> np.fft.fftshift(freqs) array([-5., -4., -3., -2., -1., 0., 1., 2., 3., 4.]) Shift the zero-frequency component only along the second axis: >>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3) >>> freqs array([[ 0., 1., 2.], [ 3., 4., -4.], [-3., -2., -1.]]) >>> np.fft.fftshift(freqs, axes=(1,)) array([[ 2., 0., 1.], [-4., 3., 4.], [-1., -3., -2.]]) """ tmp = asarray(x) ndim = len(tmp.shape) if axes is None: axes = list(range(ndim)) elif isinstance(axes, (int, nt.integer)): axes = (axes,) y = tmp for k in axes: n = tmp.shape[k] p2 = (n+1)//2 mylist = concatenate((arange(p2,n),arange(p2))) y = take(y,mylist,k) return y
def fftfreq(n,d=1.0): """ fftfreq(n, d=1.0) -> f DFT sample frequencies The returned float array contains the frequency bins in cycles/unit (with zero at the start) given a window length n and a sample spacing d: f = [0,1,...,n/2-1,-n/2,...,-1]/(d*n) if n is even f = [0,1,...,(n-1)/2,-(n-1)/2,...,-1]/(d*n) if n is odd """ assert isinstance(n,types.IntType) or isinstance(n, integer) return hstack((arange(0,(n-1)/2 + 1), arange(-(n/2),0))) / (n*d)
def original_fftshift(x, axes=None): """ How fftshift was implemented in v1.14""" tmp = asarray(x) ndim = tmp.ndim if axes is None: axes = list(range(ndim)) elif isinstance(axes, integer_types): axes = (axes,) y = tmp for k in axes: n = tmp.shape[k] p2 = (n + 1) // 2 mylist = concatenate((arange(p2, n), arange(p2))) y = take(y, mylist, k) return y
def ifftshift(x,axes=None): """ ifftshift(x,axes=None) - > y Inverse of fftshift. """ tmp = asarray(x) ndim = len(tmp.shape) if axes is None: axes = range(ndim) y = tmp for k in axes: n = tmp.shape[k] p2 = n-(n+1)/2 mylist = concatenate((arange(p2,n),arange(p2))) y = take(y,mylist,k) return y
def det(a): """Compute the determinant of a matrix Parameters ---------- a : array-like, shape (M, M) Returns ------- det : float or complex Determinant of a Notes ----- The determinant is computed via LU factorization, LAPACK routine z/dgetrf. """ a = asarray(a) _assertRank2(a) _assertSquareness(a) t, result_t = _commonType(a) a = _fastCopyAndTranspose(t, a) n = a.shape[0] if isComplexType(t): lapack_routine = lapack_lite.zgetrf else: lapack_routine = lapack_lite.dgetrf pivots = zeros((n,), fortran_int) results = lapack_routine(n, n, a, n, pivots, 0) info = results['info'] if (info < 0): raise TypeError, "Illegal input to Fortran routine" elif (info > 0): return 0.0 sign = add.reduce(pivots != arange(1, n+1)) % 2 return (1.-2.*sign)*multiply.reduce(diagonal(a), axis=-1)
def test_strided(self): a = arange(12) b = a[::2] low, high = utils.byte_bounds(b) # the largest pointer address is lost (even numbers only in the # stride), and compensate addresses for striding by 2 assert_equal(high - low, b.size * 2 * b.itemsize - b.itemsize)
def ifftshift(x, axes=None): """ The inverse of `fftshift`. Although identical for even-length `x`, the functions differ by one sample for odd-length `x`. Parameters ---------- x : array_like Input array. axes : int or shape tuple, optional Axes over which to calculate. Defaults to None, which shifts all axes. Returns ------- y : ndarray The shifted array. See Also -------- fftshift : Shift zero-frequency component to the center of the spectrum. Examples -------- >>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3) >>> freqs array([[ 0., 1., 2.], [ 3., 4., -4.], [-3., -2., -1.]]) >>> np.fft.ifftshift(np.fft.fftshift(freqs)) array([[ 0., 1., 2.], [ 3., 4., -4.], [-3., -2., -1.]]) """ tmp = asarray(x) ndim = len(tmp.shape) if axes is None: axes = list(range(ndim)) elif isinstance(axes, integer_types): axes = (axes,) y = tmp for k in axes: n = tmp.shape[k] p2 = n-(n+1)//2 mylist = concatenate((arange(p2, n), arange(p2))) y = take(y, mylist, k) return y
def ifftshift(x, axes=None): """ The inverse of fftshift. Parameters ---------- x : array_like Input array. axes : int or shape tuple, optional Axes over which to calculate. Defaults to None, which shifts all axes. Returns ------- y : ndarray The shifted array. See Also -------- fftshift : Shift zero-frequency component to the center of the spectrum. Examples -------- >>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3) >>> freqs array([[ 0., 1., 2.], [ 3., 4., -4.], [-3., -2., -1.]]) >>> np.fft.ifftshift(np.fft.fftshift(freqs)) array([[ 0., 1., 2.], [ 3., 4., -4.], [-3., -2., -1.]]) """ tmp = asarray(x) ndim = len(tmp.shape) if axes is None: axes = range(ndim) elif isinstance(axes, (int, nt.integer)): axes = (axes, ) y = tmp for k in axes: n = tmp.shape[k] p2 = n - (n + 1) // 2 mylist = concatenate((arange(p2, n), arange(p2))) y = take(y, mylist, k) return y
def fftfreq(n, d=1.0): """ Return the Discrete Fourier Transform sample frequencies. The returned float array `f` contains the frequency bin centers in cycles per unit of the sample spacing (with zero at the start). For instance, if the sample spacing is in seconds, then the frequency unit is cycles/second. Given a window length `n` and a sample spacing `d`:: f = [0, 1, ..., n/2-1, -n/2, ..., -1] / (d*n) if n is even f = [0, 1, ..., (n-1)/2, -(n-1)/2, ..., -1] / (d*n) if n is odd Parameters ---------- n : int Window length. d : scalar, optional Sample spacing (inverse of the sampling rate). Defaults to 1. Returns ------- f : ndarray Array of length `n` containing the sample frequencies. Examples -------- >>> signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5], dtype=float) >>> fourier = np.fft.fft(signal) >>> n = signal.size >>> timestep = 0.1 >>> freq = np.fft.fftfreq(n, d=timestep) >>> freq array([ 0. , 1.25, 2.5 , 3.75, -5. , -3.75, -2.5 , -1.25]) """ if not (isinstance(n,types.IntType) or isinstance(n, integer)): raise ValueError("n should be an integer") val = 1.0 / (n * d) results = empty(n, int) N = (n-1)//2 + 1 p1 = arange(0, N, dtype=int) results[:N] = p1 p2 = arange(-(n//2), 0, dtype=int) results[N:] = p2 return results * val
def fftfreq(n, d=1.0): """ Return the Discrete Fourier Transform sample frequencies. The returned float array `f` contains the frequency bin centers in cycles per unit of the sample spacing (with zero at the start). For instance, if the sample spacing is in seconds, then the frequency unit is cycles/second. Given a window length `n` and a sample spacing `d`:: f = [0, 1, ..., n/2-1, -n/2, ..., -1] / (d*n) if n is even f = [0, 1, ..., (n-1)/2, -(n-1)/2, ..., -1] / (d*n) if n is odd Parameters ---------- n : int Window length. d : scalar, optional Sample spacing (inverse of the sampling rate). Defaults to 1. Returns ------- f : ndarray Array of length `n` containing the sample frequencies. Examples -------- >>> signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5], dtype=float) >>> fourier = np.fft.fft(signal) >>> n = signal.size >>> timestep = 0.1 >>> freq = np.fft.fftfreq(n, d=timestep) >>> freq array([ 0. , 1.25, 2.5 , 3.75, -5. , -3.75, -2.5 , -1.25]) """ if not isinstance(n, integer_types): raise ValueError("n should be an integer") val = 1.0 / (n * d) results = empty(n, int) N = (n - 1) // 2 + 1 p1 = arange(0, N, dtype=int) results[:N] = p1 p2 = arange(-(n // 2), 0, dtype=int) results[N:] = p2 return results * val
def fftfreq(n,d=1.0): """ Discrete Fourier Transform sample frequencies. The returned float array contains the frequency bins in cycles/unit (with zero at the start) given a window length `n` and a sample spacing `d`. :: f = [0,1,...,n/2-1,-n/2,...,-1]/(d*n) if n is even f = [0,1,...,(n-1)/2,-(n-1)/2,...,-1]/(d*n) if n is odd Parameters ---------- n : int Window length. d : scalar Sample spacing. Returns ------- out : ndarray, shape(`n`,) Sample frequencies. Examples -------- >>> signal = np.array([-2., 8., -6., 4., 1., 0., 3., 5.]) >>> fourier = np.fft.fft(signal) >>> n = len(signal) >>> timestep = 0.1 >>> freq = np.fft.fftfreq(n, d=timestep) >>> freq array([ 0. , 1.25, 2.5 , 3.75, -5. , -3.75, -2.5 , -1.25]) """ assert isinstance(n,types.IntType) or isinstance(n, integer) val = 1.0/(n*d) results = empty(n, int) N = (n-1)//2 + 1 p1 = arange(0,N,dtype=int) results[:N] = p1 p2 = arange(-(n//2),0,dtype=int) results[N:] = p2 return results * val
def ifftshift(x, axes=None): """ The inverse of fftshift. Parameters ---------- x : array_like Input array. axes : int or shape tuple, optional Axes over which to calculate. Defaults to None, which shifts all axes. Returns ------- y : ndarray The shifted array. See Also -------- fftshift : Shift zero-frequency component to the center of the spectrum. Examples -------- >>> freqs = np.fft.fftfreq(9, d=1./9).reshape(3, 3) >>> freqs array([[ 0., 1., 2.], [ 3., 4., -4.], [-3., -2., -1.]]) >>> np.fft.ifftshift(np.fft.fftshift(freqs)) array([[ 0., 1., 2.], [ 3., 4., -4.], [-3., -2., -1.]]) """ tmp = asarray(x) ndim = len(tmp.shape) if axes is None: axes = range(ndim) y = tmp for k in axes: n = tmp.shape[k] p2 = n - (n + 1) / 2 mylist = concatenate((arange(p2, n), arange(p2))) y = take(y, mylist, k) return y
def main(): l = 50 # tau = 0.05 h = 0.1 u = 1 t_arr_print = [0.0, 0.1, 0.2, 0.3, 0.4, 0.5, 1.0, 5.0, 10, 20, 30] t_start = min(t_arr_print) t_end = max(t_arr_print) + 0.00001 c_start = 0.5 c_end = 0.5 c_step = 0.5 x_arr = arange(2 * h, l, h) c_arr = arange(c_start, c_end + 0.0001, c_step) for c in c_arr: tau = c / u * h t_arr = arange(t_start, t_end, tau) data = FTCS_Solver(t_start, t_end, l, tau, h, fi) data.initialize(fi) for t in t_arr: data.set_u(0, t + tau, 0) data.set_u(h, t + tau, 0) print(f"calculate for t: {round(t, 2)}") for x in x_arr: data.set_u( x, t + tau, data.u(x, t) - c * (data.u(x, t) - data.u(x - h, t))) data.set_u(l, t + tau, 0) if t in t_arr_print: print(c) print(t) plt.figure(str(round(t, 2))) plt.subplot(graph_index) plt.plot([0, h, *x_arr, l], data.get_state(t))
def animate(n): global ax global data global l global h print(data.data[n]) ax.clear() ax.plot(arange(0, l + h, h), data.data[n]) return data.data[n],
def fftfreq(n,d=1.0): """ fftfreq(n, d=1.0) -> f DFT sample frequencies The returned float array contains the frequency bins in cycles/unit (with zero at the start) given a window length n and a sample spacing d: f = [0,1,...,n/2-1,-n/2,...,-1]/(d*n) if n is even f = [0,1,...,(n-1)/2,-(n-1)/2,...,-1]/(d*n) if n is odd """ assert isinstance(n,types.IntType) or isinstance(n, integer) val = 1.0/(n*d) results = empty(n, int) N = (n-1)//2 + 1 p1 = arange(0,N,dtype=int) results[:N] = p1 p2 = arange(-(n//2),0,dtype=int) results[N:] = p2 return results * val
def fftshift(x,axes=None): """ fftshift(x, axes=None) -> y Shift zero-frequency component to center of spectrum. This function swaps half-spaces for all axes listed (defaults to all). Notes: If len(x) is even then the Nyquist component is y[0]. """ tmp = asarray(x) ndim = len(tmp.shape) if axes is None: axes = range(ndim) y = tmp for k in axes: n = tmp.shape[k] p2 = (n+1)/2 mylist = concatenate((arange(p2,n),arange(p2))) y = take(y,mylist,k) return y
def fftfreq(n, d=1.0): """ fftfreq(n, d=1.0) -> f DFT sample frequencies The returned float array contains the frequency bins in cycles/unit (with zero at the start) given a window length n and a sample spacing d: f = [0,1,...,n/2-1,-n/2,...,-1]/(d*n) if n is even f = [0,1,...,(n-1)/2,-(n-1)/2,...,-1]/(d*n) if n is odd """ assert isinstance(n, types.IntType) or isinstance(n, integer) val = 1.0 / (n * d) results = empty(n, int) N = (n - 1) // 2 + 1 p1 = arange(0, N, dtype=int) results[:N] = p1 p2 = arange(-(n // 2), 0, dtype=int) results[N:] = p2 return results * val
def animate(n): global ax global fig global data global l global h hist = data.data print(hist[n]) x_range = arange(0, l + h, h) ax.clear() ax.plot(x_range, hist[n]) return x_range,
def test_concatenate_axis_None(): a = arange(4, dtype=float64).reshape((2, 2)) b = range(3) c = ['x'] r = concatenate((a, a), axis=None) assert_equal(r.dtype, a.dtype) assert_equal(r.ndim, 1) r = concatenate((a, b), axis=None) assert_equal(r.size, a.size + len(b)) assert_equal(r.dtype, a.dtype) r = concatenate((a, b, c), axis=None) d = array(['0', '1', '2', '3', '0', '1', '2', 'x']) assert_array_equal(r, d)
def test_concatenate_axis_None(): a = arange(4, dtype=float64).reshape((2,2)) b = list(range(3)) c = ['x'] r = concatenate((a, a), axis=None) assert_equal(r.dtype, a.dtype) assert_equal(r.ndim, 1) r = concatenate((a, b), axis=None) assert_equal(r.size, a.size + len(b)) assert_equal(r.dtype, a.dtype) r = concatenate((a, b, c), axis=None) d = array(['0', '1', '2', '3', '0', '1', '2', 'x']) assert_array_equal(r,d)
def rfftfreq(n, d=1.0): """ Return the Discrete Fourier Transform sample frequencies (for usage with rfft, irfft). The returned float array `f` contains the frequency bin centers in cycles per unit of the sample spacing (with zero at the start). For instance, if the sample spacing is in seconds, then the frequency unit is cycles/second. Given a window length `n` and a sample spacing `d`:: f = [0, 1, ..., n/2-1, n/2] / (d*n) if n is even f = [0, 1, ..., (n-1)/2-1, (n-1)/2] / (d*n) if n is odd Unlike `fftfreq` (but like `scipy.fftpack.rfftfreq`) the Nyquist frequency component is considered to be positive. Parameters ---------- n : int Window length. d : scalar, optional Sample spacing (inverse of the sampling rate). Defaults to 1. Returns ------- f : ndarray Array of length ``n//2 + 1`` containing the sample frequencies. Examples -------- >>> signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5, -3, 4], dtype=float) >>> fourier = np.fft.rfft(signal) >>> n = signal.size >>> sample_rate = 100 >>> freq = np.fft.fftfreq(n, d=1./sample_rate) >>> freq array([ 0., 10., 20., 30., 40., -50., -40., -30., -20., -10.]) >>> freq = np.fft.rfftfreq(n, d=1./sample_rate) >>> freq array([ 0., 10., 20., 30., 40., 50.]) """ if not (isinstance(n, int) or isinstance(n, integer)): raise ValueError("n should be an integer") val = 1.0 / (n * d) N = n // 2 + 1 results = arange(0, N, dtype=int) return results * val
def rfftfreq(n, d=1.0): """ Return the Discrete Fourier Transform sample frequencies (for usage with rfft, irfft). The returned float array `f` contains the frequency bin centers in cycles per unit of the sample spacing (with zero at the start). For instance, if the sample spacing is in seconds, then the frequency unit is cycles/second. Given a window length `n` and a sample spacing `d`:: f = [0, 1, ..., n/2-1, n/2] / (d*n) if n is even f = [0, 1, ..., (n-1)/2-1, (n-1)/2] / (d*n) if n is odd Unlike `fftfreq` (but like `scipy.fftpack.rfftfreq`) the Nyquist frequency component is considered to be positive. Parameters ---------- n : int Window length. d : scalar, optional Sample spacing (inverse of the sampling rate). Defaults to 1. Returns ------- f : ndarray Array of length ``n//2 + 1`` containing the sample frequencies. Examples -------- >>> signal = np.array([-2, 8, 6, 4, 1, 0, 3, 5, -3, 4], dtype=float) >>> fourier = np.fft.rfft(signal) >>> n = signal.size >>> sample_rate = 100 >>> freq = np.fft.fftfreq(n, d=1./sample_rate) >>> freq array([ 0., 10., 20., 30., 40., -50., -40., -30., -20., -10.]) >>> freq = np.fft.rfftfreq(n, d=1./sample_rate) >>> freq array([ 0., 10., 20., 30., 40., 50.]) """ if not (isinstance(n,types.IntType) or isinstance(n, integer)): raise ValueError("n should be an integer") val = 1.0/(n*d) N = n//2 + 1 results = arange(0, N, dtype=int) return results * val
def beze_interpolate(x_arr, y_arr): B_x = [] B_y = [] for t in arange(0, 1.01, 0.001): res_x = 0 res_y = 0 for i in range(len(x_arr)): res_x = res_x + x_arr[i]*b(i, len(x_arr) - 1, t) res_y = res_y + y_arr[i]*b(i, len(y_arr) - 1, t) B_x.append(res_x) B_y.append(res_y) return {'x': B_x, 'y': B_y}
def det(a): """ Compute the determinant of an array. Parameters ---------- a : array_like, shape (M, M) Input array. Returns ------- det : ndarray Determinant of `a`. Notes ----- The determinant is computed via LU factorization using the LAPACK routine z/dgetrf. Examples -------- The determinant of a 2-D array [[a, b], [c, d]] is ad - bc: >>> a = np.array([[1, 2], [3, 4]]) >>> np.linalg.det(a) -2.0 """ a = asarray(a) _assertRank2(a) _assertSquareness(a) t, result_t = _commonType(a) a = _fastCopyAndTranspose(t, a) n = a.shape[0] if isComplexType(t): lapack_routine = lapack_lite.zgetrf else: lapack_routine = lapack_lite.dgetrf pivots = zeros((n, ), fortran_int) results = lapack_routine(n, n, a, n, pivots, 0) info = results['info'] if (info < 0): raise TypeError, "Illegal input to Fortran routine" elif (info > 0): return 0.0 sign = add.reduce(pivots != arange(1, n + 1)) % 2 return (1. - 2. * sign) * multiply.reduce(diagonal(a), axis=-1)
def det(a): """ Compute the determinant of an array. Parameters ---------- a : array_like, shape (M, M) Input array. Returns ------- det : ndarray Determinant of `a`. Notes ----- The determinant is computed via LU factorization using the LAPACK routine z/dgetrf. Examples -------- The determinant of a 2-D array [[a, b], [c, d]] is ad - bc: >>> a = np.array([[1, 2], [3, 4]]) >>> np.linalg.det(a) -2.0 """ a = asarray(a) _assertRank2(a) _assertSquareness(a) t, result_t = _commonType(a) a = _fastCopyAndTranspose(t, a) n = a.shape[0] if isComplexType(t): lapack_routine = lapack_lite.zgetrf else: lapack_routine = lapack_lite.dgetrf pivots = zeros((n,), fortran_int) results = lapack_routine(n, n, a, n, pivots, 0) info = results['info'] if (info < 0): raise TypeError, "Illegal input to Fortran routine" elif (info > 0): return 0.0 sign = add.reduce(pivots != arange(1, n+1)) % 2 return (1.-2.*sign)*multiply.reduce(diagonal(a), axis=-1)
def plot_u_from_book(graph_index): def a_k(k, t): res = -2*exp(pi ** 2 * k ** 2 * t) res *= (pi * k * (6 * t - 1) * sin(pi * k) + (6 * t - 3) * cos(pi * k) - 6 * t) res += pi * k * sin(pi * k) + 3 * cos(pi * k) res /= (pi ** 4 * k **4) return res def a_0(t): res = 1 / 2 res *= (t - 6 * t ** 2) res += 2 return res sum_a_k = 0 h = 0.1 l = 1 tau = 0.1 t_arr = [0, 0.1, 0.5, 1.0, 5.0, 10.0] for t in t_arr: u_arr = [] for x in arange(0, l + h, h): sum_a_k = 0 for k in range(1, 3): sum_a_k += a_k(k, t) * cos(pi * k * x) * exp(-(pi*k/l)**2 * t) u = 0.5 * a_0(t) + sum_a_k u_arr.append(u) plt.figure(str(round(t, 1))) plt.subplot(graph_index) plt.plot(u_arr) plt.show()
def test_concatenate(): # Test concatenate function # No arrays raise ValueError assert_raises(ValueError, concatenate, ()) # Scalars cannot be concatenated assert_raises(ValueError, concatenate, (0, )) assert_raises(ValueError, concatenate, (array(0), )) # One sequence returns unmodified (but as array) r4 = list(range(4)) assert_array_equal(concatenate((r4, )), r4) # Any sequence assert_array_equal(concatenate((tuple(r4), )), r4) assert_array_equal(concatenate((array(r4), )), r4) # 1D default concatenation r3 = list(range(3)) assert_array_equal(concatenate((r4, r3)), r4 + r3) # Mixed sequence types assert_array_equal(concatenate((tuple(r4), r3)), r4 + r3) assert_array_equal(concatenate((array(r4), r3)), r4 + r3) # Explicit axis specification assert_array_equal(concatenate((r4, r3), 0), r4 + r3) # Including negative assert_array_equal(concatenate((r4, r3), -1), r4 + r3) # 2D a23 = array([[10, 11, 12], [13, 14, 15]]) a13 = array([[0, 1, 2]]) res = array([[10, 11, 12], [13, 14, 15], [0, 1, 2]]) assert_array_equal(concatenate((a23, a13)), res) assert_array_equal(concatenate((a23, a13), 0), res) assert_array_equal(concatenate((a23.T, a13.T), 1), res.T) assert_array_equal(concatenate((a23.T, a13.T), -1), res.T) # Arrays much match shape assert_raises(ValueError, concatenate, (a23.T, a13.T), 0) # 3D res = arange(2 * 3 * 7).reshape((2, 3, 7)) a0 = res[..., :4] a1 = res[..., 4:6] a2 = res[..., 6:] assert_array_equal(concatenate((a0, a1, a2), 2), res) assert_array_equal(concatenate((a0, a1, a2), -1), res) assert_array_equal(concatenate((a0.T, a1.T, a2.T), 0), res.T)
def test_concatenate(): # Test concatenate function # No arrays raise ValueError assert_raises(ValueError, concatenate, ()) # Scalars cannot be concatenated assert_raises(ValueError, concatenate, (0,)) assert_raises(ValueError, concatenate, (array(0),)) # One sequence returns unmodified (but as array) r4 = list(range(4)) assert_array_equal(concatenate((r4,)), r4) # Any sequence assert_array_equal(concatenate((tuple(r4),)), r4) assert_array_equal(concatenate((array(r4),)), r4) # 1D default concatenation r3 = list(range(3)) assert_array_equal(concatenate((r4, r3)), r4 + r3) # Mixed sequence types assert_array_equal(concatenate((tuple(r4), r3)), r4 + r3) assert_array_equal(concatenate((array(r4), r3)), r4 + r3) # Explicit axis specification assert_array_equal(concatenate((r4, r3), 0), r4 + r3) # Including negative assert_array_equal(concatenate((r4, r3), -1), r4 + r3) # 2D a23 = array([[10, 11, 12], [13, 14, 15]]) a13 = array([[0, 1, 2]]) res = array([[10, 11, 12], [13, 14, 15], [0, 1, 2]]) assert_array_equal(concatenate((a23, a13)), res) assert_array_equal(concatenate((a23, a13), 0), res) assert_array_equal(concatenate((a23.T, a13.T), 1), res.T) assert_array_equal(concatenate((a23.T, a13.T), -1), res.T) # Arrays much match shape assert_raises(ValueError, concatenate, (a23.T, a13.T), 0) # 3D res = arange(2 * 3 * 7).reshape((2, 3, 7)) a0 = res[..., :4] a1 = res[..., 4:6] a2 = res[..., 6:] assert_array_equal(concatenate((a0, a1, a2), 2), res) assert_array_equal(concatenate((a0, a1, a2), -1), res) assert_array_equal(concatenate((a0.T, a1.T, a2.T), 0), res.T)
def det(a): "The determinant of the 2-d array a" a = asarray(a) _assertRank2(a) _assertSquareness(a) t, result_t = _commonType(a) a = _fastCopyAndTranspose(t, a) n = a.shape[0] if isComplexType(t): lapack_routine = lapack_lite.zgetrf else: lapack_routine = lapack_lite.dgetrf pivots = zeros((n, ), fortran_int) results = lapack_routine(n, n, a, n, pivots, 0) info = results['info'] if (info < 0): raise TypeError, "Illegal input to Fortran routine" elif (info > 0): return 0.0 sign = add.reduce(pivots != arange(1, n + 1)) % 2 return (1. - 2. * sign) * multiply.reduce(diagonal(a), axis=-1)
def det(a): "The determinant of the 2-d array a" a = asarray(a) _assertRank2(a) _assertSquareness(a) t, result_t = _commonType(a) a = _fastCopyAndTranspose(t, a) n = a.shape[0] if isComplexType(t): lapack_routine = lapack_lite.zgetrf else: lapack_routine = lapack_lite.dgetrf pivots = zeros((n,), fortran_int) results = lapack_routine(n, n, a, n, pivots, 0) info = results['info'] if (info < 0): raise TypeError, "Illegal input to Fortran routine" elif (info > 0): return 0.0 sign = add.reduce(pivots != arange(1, n+1)) % 2 return (1.-2.*sign)*multiply.reduce(diagonal(a), axis=-1)
def rfftfreq(n, d=1.0): """ Return the Discrete Fourier Transform sample frequencies (for usage with rfft, irfft). The returned float array `f` contains the frequency bin centers in cycles per unit of the sample spacing (with zero at the start). For instance, if the sample spacing is in seconds, then the frequency unit is cycles/second. Given a window length `n` and a sample spacing `d`:: f = [0, 1, ..., n/2-1, n/2] / (d*n) if n is even f = [0, 1, ..., (n-1)/2-1, (n-1)/2] / (d*n) if n is odd Unlike `fftfreq` (but like `scipy.fftpack.rfftfreq`) the Nyquist frequency component is considered to be positive. Parameters ---------- n : int Window length. d : scalar, optional Sample spacing (inverse of the sampling rate). Defaults to 1. Returns ------- f : ndarray Array of length ``n//2 + 1`` containing the sample frequencies. """ if not isinstance(n, integer_types): raise ValueError("n should be an integer") val = 1.0 / (n * d) N = n // 2 + 1 results = arange(0, N, dtype=int) return results * val
def test_byte_bounds(): a = arange(12).reshape(3, 4) low, high = utils.byte_bounds(a) assert_equal(high - low, a.size * a.itemsize)
def initialize(self, init_f): init_arr = [] for x in arange(0, self.l + self.h, self.h): init_arr.append(init_f(x, self.h)) self.data.append(init_arr)
def test_byte_bounds(self): # pointer difference matches size * itemsize # due to contiguity a = arange(12).reshape(3, 4) low, high = utils.byte_bounds(a) assert_equal(high - low, a.size * a.itemsize)
def test_unusual_order_negative_stride(self): a = arange(12).reshape(3, 4) b = a.T[::-1] low, high = utils.byte_bounds(b) assert_equal(high - low, b.size * b.itemsize)
A = 0.1 res1 = -G * M[i] + B * N[i] * M[i] res2 = P - A * N[i] - B * N[i] * M[i] return (res1, res2) t = 0 P = 5 cc = -5 dt = 0.1 i = 1 startT = 0 endT = 300 t = arange(startT, endT, dt) size = int((endT - startT) / dt) M = [0] N = [0] for i in range(1, size): if i % 100 == 0: P = P + cc cc = cc * -1 print(N) print(M) k1M, k1N = NMDer(t[i], M, N, P, i) k2M, k2N = NMDer(t[i] + dt / 2, M + dt * k1M / 2, N + dt * k1N / 2, P, i) k3M, k3N = NMDer(t[i] + dt / 2, M + dt * k2M / 2, N + dt * k2N / 2, P, i)
from matplotlib import pyplot as plt from numpy.core import arange from math import pow def f(x, a, lambd1, lambd2): print(lambd2 / lambd1) return a * (x**(lambd2 / lambd1)) if __name__ == "__main__": x_arr = arange(0, 1, 0.0001) a_arr = arange(-20, 20, 3) l1 = (-1 + (17**0.5)) / 4 l2 = (-1 - (17**0.5)) / 4 for a in a_arr: y_arr = [f(x, a, l1, l2) for x in x_arr] plt.plot(x_arr, y_arr) plt.show()
def __init__(self, scene, position, text, size=None, color=None, align=(0, 0), layer=0): if not color: color = settings.display['annotation_color'] if not size: size = settings.display['view_font_size'] self.position = fvec3(position) self.color = fvec3(color) self.size = size self.layer = layer # load font def load(scene): img, align = create_font_texture( ImageFont.truetype(ressourcedir + '/NotoMono-Regular.ttf', 2 * size)) return scene.ctx.texture(img.size, 1, img.tobytes()), align self.fonttex, self.fontalign = scene.ressource(('fonttex', size), load) # load shader def load(scene): shader = scene.ctx.program( vertex_shader=open(ressourcedir + '/shaders/font.vert').read(), fragment_shader=open(ressourcedir + '/shaders/font.frag').read(), ) shader['fonttex'].value = 0 return shader self.shader = scene.ressource('shader_font', load) # place triangles points = np.zeros((len(pointsdef) * len(text), 4), 'f4') l = 0 c = 0 for i, char in enumerate(text): if char == '\n': c = 0 l += 1 elif char == '\t': c += 4 - c % 4 # TODO: use a tab size in settings elif char == ' ': c += 1 else: n = ord(char) #placement = char_placement(2*size, *self.fontalign, n) for j, add in enumerate(pointsdef): points[len(pointsdef) * i + j] = [ add[0] + c, add[1] - l, (n % self.fontalign[0] + add[0]) / self.fontalign[0], (n // self.fontalign[0] - add[1]) / self.fontalign[1], ] c += 1 l += 1 align = (processalign(align[0], c), -processalign(align[1], l)) points -= [*align, 0, 0] self.textsize = (c, l) self.visualsize = (-align[0], -align[1], c // 2 - align[0], l - align[1]) # create the buffers on the GPU self.vb_points = scene.ctx.buffer(points) self.vb_faces = scene.ctx.buffer(np.arange(points.shape[0], dtype='u4')) self.va = scene.ctx.vertex_array( self.shader, [(self.vb_points, '2f 2f', 'v_position', 'v_uv')], )
# print() # print() # print() # print() def get_state(self, t): i = int(round(t / self.tau)) return self.data[i] if __name__ == "__main__": l = 1 tau = 0.05 h = 0.0002 t_arr_print = arange(0, 0.55, 0.05) t_start = min(t_arr_print) t_end = max(t_arr_print) + tau d_start = 0.0 d_end = 0.0 d_step = 0.1 t_arr = arange(t_start + tau, t_end, tau) d_arr = arange(0, 0.6, 0.1) #arange(d_start, d_end + 0.1, d_step) for d in d_arr: x_arr = arange(h, l, h) data = FTCS_Solver(t_start, t_end, l, tau, h, fi) data.initialize(init_f)
try: self.array.__setattr__(attr, value) except AttributeError: object.__setattr__(self, attr, value) # Only called after other approaches fail. def __getattr__(self,attr): if (attr == 'array'): return object.__getattribute__(self, attr) return self.array.__getattribute__(attr) ############################################################# # Test of class container ############################################################# if __name__ == '__main__': temp=reshape(arange(10000),(100,100)) ua=container(temp) # new object created begin test print dir(ua) print shape(ua),ua.shape # I have changed Numeric.py ua_small=ua[:3,:5] print ua_small ua_small[0,0]=10 # this did not change ua[0,0], which is not normal behavior print ua_small[0,0],ua[0,0] print sin(ua_small)/3.*6.+sqrt(ua_small**2) print less(ua_small,103),type(less(ua_small,103)) print type(ua_small*reshape(arange(15),shape(ua_small))) print reshape(ua_small,(5,3)) print transpose(ua_small)
class TestStrUnicodeSuperSubscripts: @pytest.fixture(scope="class", autouse=True) def use_unicode(self): poly.set_default_printstyle("unicode") @pytest.mark.parametrize( ("inp", "tgt"), ( ([1, 2, 3], "1.0 + 2.0·x¹ + 3.0·x²"), ([-1, 0, 3, -1], "-1.0 + 0.0·x¹ + 3.0·x² - 1.0·x³"), ( arange(12), ( "0.0 + 1.0·x¹ + 2.0·x² + 3.0·x³ + 4.0·x⁴ + 5.0·x⁵ + " "6.0·x⁶ + 7.0·x⁷ +\n8.0·x⁸ + 9.0·x⁹ + 10.0·x¹⁰ + " "11.0·x¹¹" ), ), ), ) def test_polynomial_str(self, inp, tgt): res = str(poly.Polynomial(inp)) assert_equal(res, tgt) @pytest.mark.parametrize( ("inp", "tgt"), ( ([1, 2, 3], "1.0 + 2.0·T₁(x) + 3.0·T₂(x)"), ([-1, 0, 3, -1], "-1.0 + 0.0·T₁(x) + 3.0·T₂(x) - 1.0·T₃(x)"), ( arange(12), ( "0.0 + 1.0·T₁(x) + 2.0·T₂(x) + 3.0·T₃(x) + 4.0·T₄(x) + " "5.0·T₅(x) +\n6.0·T₆(x) + 7.0·T₇(x) + 8.0·T₈(x) + " "9.0·T₉(x) + 10.0·T₁₀(x) + 11.0·T₁₁(x)" ), ), ), ) def test_chebyshev_str(self, inp, tgt): res = str(poly.Chebyshev(inp)) assert_equal(res, tgt) @pytest.mark.parametrize( ("inp", "tgt"), ( ([1, 2, 3], "1.0 + 2.0·P₁(x) + 3.0·P₂(x)"), ([-1, 0, 3, -1], "-1.0 + 0.0·P₁(x) + 3.0·P₂(x) - 1.0·P₃(x)"), ( arange(12), ( "0.0 + 1.0·P₁(x) + 2.0·P₂(x) + 3.0·P₃(x) + 4.0·P₄(x) + " "5.0·P₅(x) +\n6.0·P₆(x) + 7.0·P₇(x) + 8.0·P₈(x) + " "9.0·P₉(x) + 10.0·P₁₀(x) + 11.0·P₁₁(x)" ), ), ), ) def test_legendre_str(self, inp, tgt): res = str(poly.Legendre(inp)) assert_equal(res, tgt) @pytest.mark.parametrize( ("inp", "tgt"), ( ([1, 2, 3], "1.0 + 2.0·H₁(x) + 3.0·H₂(x)"), ([-1, 0, 3, -1], "-1.0 + 0.0·H₁(x) + 3.0·H₂(x) - 1.0·H₃(x)"), ( arange(12), ( "0.0 + 1.0·H₁(x) + 2.0·H₂(x) + 3.0·H₃(x) + 4.0·H₄(x) + " "5.0·H₅(x) +\n6.0·H₆(x) + 7.0·H₇(x) + 8.0·H₈(x) + " "9.0·H₉(x) + 10.0·H₁₀(x) + 11.0·H₁₁(x)" ), ), ), ) def test_hermite_str(self, inp, tgt): res = str(poly.Hermite(inp)) assert_equal(res, tgt) @pytest.mark.parametrize( ("inp", "tgt"), ( ([1, 2, 3], "1.0 + 2.0·He₁(x) + 3.0·He₂(x)"), ([-1, 0, 3, -1], "-1.0 + 0.0·He₁(x) + 3.0·He₂(x) - 1.0·He₃(x)"), ( arange(12), ( "0.0 + 1.0·He₁(x) + 2.0·He₂(x) + 3.0·He₃(x) + " "4.0·He₄(x) + 5.0·He₅(x) +\n6.0·He₆(x) + 7.0·He₇(x) + " "8.0·He₈(x) + 9.0·He₉(x) + 10.0·He₁₀(x) +\n" "11.0·He₁₁(x)" ), ), ), ) def test_hermiteE_str(self, inp, tgt): res = str(poly.HermiteE(inp)) assert_equal(res, tgt) @pytest.mark.parametrize( ("inp", "tgt"), ( ([1, 2, 3], "1.0 + 2.0·L₁(x) + 3.0·L₂(x)"), ([-1, 0, 3, -1], "-1.0 + 0.0·L₁(x) + 3.0·L₂(x) - 1.0·L₃(x)"), ( arange(12), ( "0.0 + 1.0·L₁(x) + 2.0·L₂(x) + 3.0·L₃(x) + 4.0·L₄(x) + " "5.0·L₅(x) +\n6.0·L₆(x) + 7.0·L₇(x) + 8.0·L₈(x) + " "9.0·L₉(x) + 10.0·L₁₀(x) + 11.0·L₁₁(x)" ), ), ), ) def test_laguerre_str(self, inp, tgt): res = str(poly.Laguerre(inp)) assert_equal(res, tgt)
class TestStrAscii: @pytest.fixture(scope="class", autouse=True) def use_ascii(self): poly.set_default_printstyle("ascii") @pytest.mark.parametrize( ("inp", "tgt"), ( ([1, 2, 3], "1.0 + 2.0 x**1 + 3.0 x**2"), ([-1, 0, 3, -1], "-1.0 + 0.0 x**1 + 3.0 x**2 - 1.0 x**3"), ( arange(12), ( "0.0 + 1.0 x**1 + 2.0 x**2 + 3.0 x**3 + 4.0 x**4 + " "5.0 x**5 + 6.0 x**6 +\n7.0 x**7 + 8.0 x**8 + " "9.0 x**9 + 10.0 x**10 + 11.0 x**11" ), ), ), ) def test_polynomial_str(self, inp, tgt): res = str(poly.Polynomial(inp)) assert_equal(res, tgt) @pytest.mark.parametrize( ("inp", "tgt"), ( ([1, 2, 3], "1.0 + 2.0 T_1(x) + 3.0 T_2(x)"), ([-1, 0, 3, -1], "-1.0 + 0.0 T_1(x) + 3.0 T_2(x) - 1.0 T_3(x)"), ( arange(12), ( "0.0 + 1.0 T_1(x) + 2.0 T_2(x) + 3.0 T_3(x) + " "4.0 T_4(x) + 5.0 T_5(x) +\n6.0 T_6(x) + 7.0 T_7(x) + " "8.0 T_8(x) + 9.0 T_9(x) + 10.0 T_10(x) +\n" "11.0 T_11(x)" ), ), ), ) def test_chebyshev_str(self, inp, tgt): res = str(poly.Chebyshev(inp)) assert_equal(res, tgt) @pytest.mark.parametrize( ("inp", "tgt"), ( ([1, 2, 3], "1.0 + 2.0 P_1(x) + 3.0 P_2(x)"), ([-1, 0, 3, -1], "-1.0 + 0.0 P_1(x) + 3.0 P_2(x) - 1.0 P_3(x)"), ( arange(12), ( "0.0 + 1.0 P_1(x) + 2.0 P_2(x) + 3.0 P_3(x) + " "4.0 P_4(x) + 5.0 P_5(x) +\n6.0 P_6(x) + 7.0 P_7(x) + " "8.0 P_8(x) + 9.0 P_9(x) + 10.0 P_10(x) +\n" "11.0 P_11(x)" ), ), ), ) def test_legendre_str(self, inp, tgt): res = str(poly.Legendre(inp)) assert_equal(res, tgt) @pytest.mark.parametrize( ("inp", "tgt"), ( ([1, 2, 3], "1.0 + 2.0 H_1(x) + 3.0 H_2(x)"), ([-1, 0, 3, -1], "-1.0 + 0.0 H_1(x) + 3.0 H_2(x) - 1.0 H_3(x)"), ( arange(12), ( "0.0 + 1.0 H_1(x) + 2.0 H_2(x) + 3.0 H_3(x) + " "4.0 H_4(x) + 5.0 H_5(x) +\n6.0 H_6(x) + 7.0 H_7(x) + " "8.0 H_8(x) + 9.0 H_9(x) + 10.0 H_10(x) +\n" "11.0 H_11(x)" ), ), ), ) def test_hermite_str(self, inp, tgt): res = str(poly.Hermite(inp)) assert_equal(res, tgt) @pytest.mark.parametrize( ("inp", "tgt"), ( ([1, 2, 3], "1.0 + 2.0 He_1(x) + 3.0 He_2(x)"), ([-1, 0, 3, -1], "-1.0 + 0.0 He_1(x) + 3.0 He_2(x) - 1.0 He_3(x)"), ( arange(12), ( "0.0 + 1.0 He_1(x) + 2.0 He_2(x) + 3.0 He_3(x) + " "4.0 He_4(x) +\n5.0 He_5(x) + 6.0 He_6(x) + " "7.0 He_7(x) + 8.0 He_8(x) + 9.0 He_9(x) +\n" "10.0 He_10(x) + 11.0 He_11(x)" ), ), ), ) def test_hermiteE_str(self, inp, tgt): res = str(poly.HermiteE(inp)) assert_equal(res, tgt) @pytest.mark.parametrize( ("inp", "tgt"), ( ([1, 2, 3], "1.0 + 2.0 L_1(x) + 3.0 L_2(x)"), ([-1, 0, 3, -1], "-1.0 + 0.0 L_1(x) + 3.0 L_2(x) - 1.0 L_3(x)"), ( arange(12), ( "0.0 + 1.0 L_1(x) + 2.0 L_2(x) + 3.0 L_3(x) + " "4.0 L_4(x) + 5.0 L_5(x) +\n6.0 L_6(x) + 7.0 L_7(x) + " "8.0 L_8(x) + 9.0 L_9(x) + 10.0 L_10(x) +\n" "11.0 L_11(x)" ), ), ), ) def test_laguerre_str(self, inp, tgt): res = str(poly.Laguerre(inp)) assert_equal(res, tgt)
import math as m from numpy.core import arange from matplotlib import pyplot as plt import pylab for tau in [0.1, 0.2, 0.25]: y = 2 z = 1 y_eiler_arr = [y] z_eiler_arr = [z] t_arr = arange(0, 100, tau) for t in t_arr: print(f"t: {t}") y = y + tau * (-y + 0.999 * z) z = z + tau * (-0.001 * z) y_eiler_arr.append(y) z_eiler_arr.append(z) plt.plot(y_eiler_arr, z_eiler_arr, label=f'tau: {round(tau, 2)}') plt.legend() plt.show()
from numpy import core as np, savetxt, loadtxt arr = np.arange(200).reshape((2, 5, 4, 5)) with open('/Users/me/Documents/code/python/own/tmp/rse.txt', "w+") as f: for each_3d in arr: for each_2d in each_3d: savetxt(f, each_2d) with open('/Users/me/Documents/code/python/own/tmp/rse.txt', "r+") as f: other_arr = loadtxt(f) reshaped_arr = other_arr.reshape((2, 5, 4, 5)) print(reshaped_arr)
self.array.__setattr__(attr, value) except AttributeError: object.__setattr__(self, attr, value) # Only called after other approaches fail. def __getattr__(self, attr): if (attr == 'array'): return object.__getattribute__(self, attr) return self.array.__getattribute__(attr) ############################################################# # Test of class container ############################################################# if __name__ == '__main__': temp = reshape(arange(10000), (100, 100)) ua = container(temp) # new object created begin test print dir(ua) print shape(ua), ua.shape # I have changed Numeric.py ua_small = ua[:3, :5] print ua_small ua_small[ 0, 0] = 10 # this did not change ua[0,0], which is not normal behavior print ua_small[0, 0], ua[0, 0] print sin(ua_small) / 3. * 6. + sqrt(ua_small**2) print less(ua_small, 103), type(less(ua_small, 103)) print type(ua_small * reshape(arange(15), shape(ua_small))) print reshape(ua_small, (5, 3))
import numpy as np from numpy.core import arange nums = np.array([1, 2, 3, 4, 5]) print(nums.shape) print(nums.dtype) nums = np.array(arange(10)) print(nums.shape[0]) print(nums) two_demension = np.array([[1, 2, 3], ["i", "m", 3], [4, 5, 6]]) print(two_demension.shape) print(two_demension) two_demension = np.array([[1, 2, 3], ["i", "m", 3, 4], [4, 5, 6]]) print(two_demension.shape) print(two_demension) two_demension = np.array([[1, 2, 3], [4, 5, 6]]) print(two_demension.shape) print(two_demension) three_demension = np.array([[[1, 2, 3], [4, 5, 6]], [[3, 4, 5], [6, 7, 8]]]) print(three_demension.shape) print(three_demension) ### 结构数组 header = np.dtype({ "names": ["name", "price", "area", "age"], "formats": ["U10", "f", "f", "i"] })