def test_Li_basis_value(): ''' This test compares the output of the lagrange basis value calculated by the function ``Li_basis_value`` to the analytical value of the lagrange polynomials created using the same LGL points. The analytical values were calculated in this sage worksheet_ .. _worksheet: https://goo.gl/ADyA3U ''' threshold = 1e-11 Li_value_ref = af.np_to_af_array(utils.csv_to_numpy( 'dg_maxwell/tests/lagrange/files/Li_value.csv')) N_LGL = 8 xi_LGL = lagrange.LGL_points(N_LGL) L_basis_poly1d, L_basis_af = lagrange.lagrange_polynomials(xi_LGL) L_basis_af = af.np_to_af_array(L_basis_af) Li_indexes = af.np_to_af_array(np.arange(3, dtype = np.int32)) xi = af.np_to_af_array(np.linspace(-1., 1, 10)) Li_value = lagrange.Li_basis_value(L_basis_af, Li_indexes, xi) assert af.all_true(af.abs(Li_value - Li_value_ref) < threshold)
def grad_q(q, u, v): ''' done - Matching qx qnd qy ''' q = af.moddims(q, params.n, params.n) q_x = af.np_to_af_array(np.zeros([params.n, params.n])) q_y = af.np_to_af_array(np.zeros([params.n, params.n])) q_x[1:-1, 1:-1] = (q[:-2, 1:-1] - q[2:, 1:-1]) * (params.n - 1) / 2.0 q_y[1:-1, 1:-1] = (q[1:-1, :-2] - q[1:-1, 2:]) * (params.n - 1) / 2.0 # Horizontal boundary conditions, qx = 0 q_y[0, 1:-1] = (q[0, :-2] - q[0, 2:]) * (params.n - 1) / 2.0 q_y[-1, 1:-1] = (q[-1, :-2] - q[-1, 2:]) * (params.n - 1) / 2.0 # Vertical boundary conditions, qy = 0 q_x[1:-1, 0] = (q[:-2, 0] - q[2:, 0]) * (params.n - 1) / 2.0 q_x[1:-1, -1] = (q[:-2, -1] - q[2:, -1]) * (params.n - 1) / 2.0 #UNEXPLAINED SWITCHING in the second part of numerator in octave q_x = af.flat(q_x) q_y = af.flat(q_y) return q_x, q_y
def test_polynomial_product_coeffs(): ''' ''' threshold = 1e-12 poly1 = af.reorder( af.transpose( af.np_to_af_array(np.array([[1, 2, 3., 4], [5, -2, -4.7211, 2]]))), 0, 2, 1) poly2 = af.reorder( af.transpose( af.np_to_af_array(np.array([[-2, 4, 7., 9], [1, 0, -9.1124, 7]]))), 0, 2, 1) numerical_product_coeffs = utils.polynomial_product_coeffs(poly1, poly2) analytical_product_coeffs_1 = af.np_to_af_array( np.array([[-2, -4, -6, -8], [4, 8, 12, 16], [7, 14, 21, 28], [9, 18, 27, 36]])) analytical_product_coeffs_2 = af.np_to_af_array( np.array([[5, -2, -4.7211, 2], [0, 0, 0, 0], [-45.562, 18.2248, 43.02055164, -18.2248], [35, -14, -33.0477, 14]])) print(numerical_product_coeffs) assert af.max(af.abs(numerical_product_coeffs[:, :, 0] - analytical_product_coeffs_1 + \ numerical_product_coeffs[:, :, 1] - analytical_product_coeffs_2)) < threshold
def _soft_l_value_demapper_af(rx_symbs, M, snr, bits_map): num_bits = int(np.log2(M)) N = rx_symbs.shape[0] k = bits_map.shape[1] sig = af.np_to_af_array(rx_symbs) bit_mtx = af.moddims(af.np_to_af_array(bits_map), 1, num_bits, k, 2) tmp = af.sum(af.broadcast(lambda x,y: af.exp(-snr*af.abs(x-y)**2), bit_mtx, sig), dim=2) lvl = af.log(tmp[:,:,:,1]) - af.log(tmp[:,:,:,0]) return np.array(lvl)
def caffe_params_to_af_params(net): af_params = collections.OrderedDict() for key in net.params.viewkeys(): af_params[key] = collections.OrderedDict() af_params[key]['weights'] = af.reorder( af.np_to_af_array(net.params[key][0].data), 2, 3, 1, 0) af_params[key]['biases'] = af.np_to_af_array(net.params[key][1].data) return af_params
def _decision_af(signal, symbols, precision=16): """ Make symbol decisions on signal array onto symbols. Arrayfire function. Parameters ---------- signal : array_like input signal array symbols : array_like array of symbols to decide onto precision : int, optional bit precision either 16 for complex128 or 8 for complex 64 Returns ------- out : array_like array of decided symbols """ global NMAX if precision == 16: prec_dtype = np.complex128 elif precision == 8: prec_dtype = np.complex64 else: raise ValueError( "Precision has to be either 16 for double complex or 8 for single complex" ) Nmax = NMAX // len(symbols.flatten()) // 16 L = signal.flatten().shape[0] sig = af.np_to_af_array(signal.flatten().astype(prec_dtype)) sym = af.transpose(af.np_to_af_array(symbols.flatten().astype(prec_dtype))) tmp = af.constant(0, L, dtype=af.Dtype.c64) if L < Nmax: v, idx = af.imin(af.abs(af.broadcast(lambda x, y: x - y, sig, sym)), dim=1) tmp = af.transpose(sym)[idx] else: steps = L // Nmax rem = L % Nmax for i in range(steps): v, idx = af.imin(af.abs( af.broadcast(lambda x, y: x - y, sig[i * Nmax:(i + 1) * Nmax], sym)), dim=1) tmp[i * Nmax:(i + 1) * Nmax] = af.transpose(sym)[idx] v, idx = af.imin(af.abs( af.broadcast(lambda x, y: x - y, sig[steps * Nmax:], sym)), dim=1) tmp[steps * Nmax:] = af.transpose(sym)[idx] return np.array(tmp)
def add_boundary_conditions(u, v): u_bc = af.np_to_af_array(np.zeros([params.n, params.n])) v_bc = af.np_to_af_array(np.zeros([params.n, params.n])) u = af.moddims(u, params.n - 2, params.n - 2) v = af.moddims(v, params.n - 2, params.n - 2) u_bc[1:-1, 1:-1] = u v_bc[1:-1, 1:-1] = v u_bc[:, 0] += params.u_i_0 return u_bc, v_bc
def lagrange_polynomial_coeffs(x): ''' This function doesn't use poly1d. It calculates the coefficients of the Lagrange basis polynomials. A function to get the analytical form and the coefficients of Lagrange basis polynomials evaluated using x nodes. It calculates the Lagrange basis polynomials using the formula: .. math:: \\ L_i = \\prod_{m = 0, m \\notin i}^{N - 1}\\frac{(x - x_m)}{(x_i - x_m)} Parameters ---------- x : numpy.array [N_LGL 1 1 1] Contains the :math: `x` nodes using which the lagrange basis functions need to be evaluated. Returns ------- lagrange_basis_coeffs : numpy.ndarray A :math: `N \\times N` matrix containing the coefficients of the Lagrange basis polynomials such that :math:`i^{th}` lagrange polynomial will be the :math:`i^{th}` row of the matrix. ''' X = np.array(x) lagrange_basis_poly = [] lagrange_basis_coeffs = af.np_to_af_array( np.zeros([X.shape[0], X.shape[0]])) for j in np.arange(X.shape[0]): lagrange_basis_k = af.np_to_af_array(np.array([1.])) for m in np.arange(X.shape[0]): if m != j: lagrange_basis_k = af.convolve1(lagrange_basis_k,\ af.np_to_af_array(np.array([1, -X[m]])/ (X[j] - X[m])),\ conv_mode=af.CONV_MODE.EXPAND) lagrange_basis_coeffs[j] = af.transpose(lagrange_basis_k) return lagrange_basis_coeffs
def test_dy_dxi(): ''' This test checks the derivative :math:`\\frac{\\partial y}{\\partial \\xi}` calculated using the function :math:`dg_maxwell.wave_equation_2d.dy_dxi` for the :math:`0^{th}` element of a mesh for a circular ring. You may download the file from this :download:`link <../dg_maxwell/tests/wave_equation_2d/files/circle.msh>`. ''' threshold = 1e-7 dy_dxi_reference = af.np_to_af_array( utils.csv_to_numpy( 'dg_maxwell/tests/wave_equation_2d/files/dy_dxi_data.csv')) nodes, elements = msh_parser.read_order_2_msh( 'dg_maxwell/tests/wave_equation_2d/files/circle.msh') N_LGL = 16 xi_LGL = lagrange.LGL_points(N_LGL) eta_LGL = lagrange.LGL_points(N_LGL) Xi = af.data.tile(af.array.transpose(xi_LGL), d0=N_LGL) Eta = af.data.tile(eta_LGL, d0=1, d1=N_LGL) dy_dxi = wave_equation_2d.dy_dxi(nodes[elements[0]][:, 1], Xi, Eta) check = af.abs(dy_dxi - dy_dxi_reference) < threshold assert af.all_true(check)
def test_Li_Lj_coeffs(): ''' ''' threshold = 2e-9 N_LGL = 8 numerical_L3_xi_L4_eta_coeffs = wave_equation_2d.Li_Lj_coeffs(N_LGL)[:, :, 28] analytical_L3_xi_L4_eta_coeffs = af.np_to_af_array(np.array([\ [-129.727857225405, 27.1519390573796, 273.730966722451, - 57.2916772505673\ , - 178.518337439857, 37.3637484073274, 34.5152279428116, -7.22401021413973], \ [- 27.1519390573797, 5.68287960923199, 57.2916772505669, - 11.9911032408375,\ - 37.3637484073272, 7.82020331954072, 7.22401021413968, - 1.51197968793550 ],\ [273.730966722451, - 57.2916772505680,- 577.583286622990, 120.887730163458,\ 376.680831166362, - 78.8390033617950, - 72.8285112658236, 15.2429504489039],\ [57.2916772505673, - 11.9911032408381, - 120.887730163459, 25.3017073771593, \ 78.8390033617947, -16.5009417437969, - 15.2429504489039, 3.19033760747451],\ [- 178.518337439857, 37.3637484073272, 376.680831166362, - 78.8390033617954,\ - 245.658854496594, 51.4162061168383, 47.4963607700889, - 9.94095116237084],\ [- 37.3637484073274, 7.82020331954070, 78.8390033617948, - 16.5009417437970,\ - 51.4162061168385, 10.7613717277423, 9.94095116237085, -2.08063330348620],\ [34.5152279428116, - 7.22401021413972, - 72.8285112658235, 15.2429504489038,\ 47.4963607700889, - 9.94095116237085, - 9.18307744707700, 1.92201092760671],\ [7.22401021413973, - 1.51197968793550, -15.2429504489039, 3.19033760747451,\ 9.94095116237084, - 2.08063330348620, - 1.92201092760671, 0.402275383947182]])) af.display(numerical_L3_xi_L4_eta_coeffs - analytical_L3_xi_L4_eta_coeffs, 14) assert (af.max( af.abs(numerical_L3_xi_L4_eta_coeffs - analytical_L3_xi_L4_eta_coeffs)) <= threshold)
def test_A_matrix(): ''' Compares the tensor product calculated using the ``A_matrix`` function with an analytic value of the tensor product for :math:`N_{LGL} = 4`. The analytic value of the tensor product is calculated in this `document`_ .. _document: https://goo.gl/QNWxXp ''' threshold = 1e-12 A_matrix_ref = af.np_to_af_array( utils.csv_to_numpy( 'dg_maxwell/tests/wave_equation_2d/files/A_matrix_ref.csv')) params.N_LGL = 4 advec_var = gvar.advection_variables(params.N_LGL, params.N_quad, params.x_nodes, params.N_Elements, params.c, params.total_time, params.wave, params.c_x, params.c_y, params.courant, params.mesh_file, params.total_time_2d) A_matrix_test = wave_equation_2d.A_matrix(params.N_LGL, advec_var) assert af.max(af.abs(A_matrix_test - A_matrix_ref)) < threshold
def test_integrate(): ''' Testing the integrate() function by passing coefficients of a polynomial and comparing it to the analytical result. ''' threshold = 1e-14 params.N_LGL = 8 params.N_quad = 10 params.N_Elements = 10 wave = 'gaussian' gv = global_variables.advection_variables(params.N_LGL, params.N_quad,\ params.x_nodes, params.N_Elements,\ params.c, params.total_time, wave,\ params.c_x, params.c_y, params.courant,\ params.mesh_file, params.total_time_2d) test_coeffs = af.np_to_af_array(np.array([7., 6, 4, 2, 1, 3, 9, 2])) # The coefficients of a test polynomial # `7x^7 + 6x^6 + 4x^5 + 2x^4 + x^3 + 3x^2 + 9x + 2` # Using integrate() function. calculated_integral = lagrange.integrate(af.transpose(test_coeffs), gv) analytical_integral = 8.514285714285714 assert (calculated_integral - analytical_integral) <= threshold
def lobatto_weights(n): ''' Calculates and returns the weight function for an index n and points x. Parameters ---------- n : int Lobatto weights for n quadrature points. Returns ------- Lobatto_weights : arrayfire.Array An array of lobatto weight functions for the given x points and index. **See:** Gauss-Lobatto weights Wikipedia `link`_. .. _link: https://goo.gl/kYqTyK **Examples** lobatto_weight_function(4) returns the Gauss-Lobatto weights which are to be used with the Lobatto nodes 'LGL_points(4)' to integrate using Lobatto quadrature. ''' xi_LGL = LGL_points(n) P = sp.legendre(n - 1) Lobatto_weights = (2 / (n * (n - 1)) / (P(xi_LGL))**2) Lobatto_weights = af.np_to_af_array(Lobatto_weights) return Lobatto_weights
def gaussian_weights(N): ''' Returns the gaussian weights :math:`w_i` for :math:`N` Gaussian Nodes at index :math:`i`. They are given by .. math:: w_i = \\frac{2}{(1 - x_i^2) P'n(x_i)} Where :math:`x_i` are the Gaussian nodes and :math:`P_{n}(\\xi)` are the Legendre polynomials. Parameters ---------- N : int Number of Gaussian nodes for which the weight is to be calculated. Returns ------- gaussian_weight : arrayfire.Array [N_quad 1 1 1] The gaussian weights. ''' index = np.arange(N) # Index `i` in `w_i`, varies from 0 to N_quad - 1 gaussian_nodes = gauss_nodes(N) gaussian_weight = 2 / ((1 - (gaussian_nodes[index]) ** 2) *\ (np.polyder(sp.legendre(N))(gaussian_nodes[index])) ** 2) gaussian_weight = af.np_to_af_array(gaussian_weight) return gaussian_weight
def test_poly1d_prod(): ''' Checks the product of the polynomials of different degrees using the poly1d_product function and compares it to the analytically calculated product coefficients. ''' N = 3 N_a = 3 poly_a = af.range(N * N_a, dtype=af.Dtype.u32) poly_a = af.moddims(poly_a, d0=N, d1=N_a) N_b = 2 poly_b = af.range(N * N_b, dtype=af.Dtype.u32) poly_b = af.moddims(poly_b, d0=N, d1=N_b) ref_poly = af.np_to_af_array( np.array([[0., 0., 9., 18.], [1., 8., 23., 28.], [4., 20., 41., 40.]])) test_poly1d_prod = utils.poly1d_product(poly_a, poly_b) test_poly1d_prod_commutative = utils.poly1d_product(poly_b, poly_a) diff = af.abs(test_poly1d_prod - ref_poly) diff_commutative = af.abs(test_poly1d_prod_commutative - ref_poly) assert af.all_true(diff == 0.) and af.all_true(diff_commutative == 0.)
def LGL_points(N): ''' Calculates : math: `N` Legendre-Gauss-Lobatto (LGL) points. LGL points are the roots of the polynomial :math: `(1 - \\xi ** 2) P_{n - 1}'(\\xi) = 0` Where :math: `P_{n}(\\xi)` are the Legendre polynomials. This function finds the roots of the above polynomial. Parameters ---------- N : int Number of LGL nodes required Returns ------- lgl : arrayfire.Array [N 1 1 1] The Lagrange-Gauss-Lobatto Nodes. **See:** `document`_ .. _document: https://goo.gl/KdG2Sv ''' xi = np.poly1d([1, 0]) legendre_N_minus_1 = N * (xi * sp.legendre(N - 1) - sp.legendre(N)) lgl_points = legendre_N_minus_1.r lgl_points.sort() lgl_points = af.np_to_af_array(lgl_points) return lgl_points
def A_matrix(): ''' Calculates A matrix whose elements :math:`A_{p i}` are given by :math: `A_{p i} &= \\int^1_{-1} L_p(\\xi)L_i(\\xi) \\frac{dx}{d\\xi}` The integrals are computed using the integrate() function. Since elements are taken to be of equal size, :math: `\\frac {dx}{dxi} is same everywhere Returns ------- A_matrix : arrayfire.Array [N_LGL N_LGL 1 1] The value of integral of product of lagrange basis functions obtained by LGL points, using the integrate() function ''' # Coefficients of Lagrange basis polynomials. xi_lgl = np.asarray(params.xi_LGL) weight_arr = np.asarray(params.weight_arr) gauss_points = np.asarray(params.gauss_points) gauss_weights = np.asarray(params.gauss_weights) A_matrix = np.zeros((xi_lgl.size, xi_lgl.size)) dx_dxi = np.asarray(params.dx_dxi) for j in range(0, xi_lgl.size): for i in range(j, xi_lgl.size): function_lagrange_1 = lagrange.eval_lagrange_basis(gauss_points, j) function_lagrange_2 = function_lagrange_1 * lagrange.eval_lagrange_basis(gauss_points, i) for k in range(0, xi_lgl.size): A_matrix[j][i] += gauss_weights[k] * function_lagrange_2[k] for j in range(0, xi_lgl.size): for i in range(j, xi_lgl.size): A_matrix[i][j] = A_matrix[j][i] A_matrix *= dx_dxi A_matrix = af.np_to_af_array(A_matrix) return A_matrix
def gaussian_weights(N): ''' Returns the gaussian weights :math:`w_i` for :math:`N` Gaussian Nodes at index :math:`i`. They are given by .. math:: w_i = \\frac{2}{(1 - x_i^2) P'n(x_i)} Where :math:`x_i` are the Gaussian nodes and :math:`P_{n}(\\xi)` are the Legendre polynomials. Parameters ---------- N : int Number of Gaussian nodes for which the weight is to be calculated. Returns ------- gaussian_weight : arrayfire.Array [N_quad 1 1 1] The gaussian weights. ''' gaussian_weight = np.polynomial.legendre.leggauss(N)[1] gaussian_weight = af.np_to_af_array(gaussian_weight) return gaussian_weight
def test_polyval_2d(): ''' Tests the ``utils.polyval_2d`` function by evaluating the polynomial .. math:: P_0(\\xi) P_1(\\eta) here, .. math:: P_0(\\xi) = 3 \, \\xi^{2} + 2 \, \\xi + 1 .. math:: P_1(\\eta) = 3 \, \\eta^{2} + 2 \, \\eta + 1 at corresponding ``linspace`` points in :math:`\\xi \\in [-1, 1]` and :math:`\\eta \\in [-1, 1]`. This value is then compared with the reference value calculated analytically. The reference values are calculated in `polynomial_product_two_variables.sagews`_ .. _polynomial_product_two_variables.sagews: https://goo.gl/KwG7k9 ''' threshold = 1e-12 poly_xi_degree = 4 poly_xi = af.flip(af.np_to_af_array(np.arange(1, poly_xi_degree))) poly_eta_degree = 4 poly_eta = af.flip(af.np_to_af_array(np.arange(1, poly_eta_degree))) poly_xi_eta = utils.polynomial_product_coeffs(poly_xi, poly_eta) xi = utils.linspace(-1, 1, 8) eta = utils.linspace(-1, 1, 8) polyval_xi_eta = af.transpose(utils.polyval_2d(poly_xi_eta, xi, eta)) polyval_xi_eta_ref = af.np_to_af_array( np.array([ 4.00000000000000, 1.21449396084962, 0.481466055810080, 0.601416076634741, 1.81424406497291, 5.79925031236988, 15.6751353602663, 36.0000000000000 ])) diff = af.abs(polyval_xi_eta - polyval_xi_eta_ref) assert af.all_true(diff < threshold)
def _bps_idx_af(E, angles, symbols, N): global NMAX prec_dtype = E.dtype Ntestangles = angles.shape[1] Nmax = NMAX // Ntestangles // symbols.shape[0] // 16 L = E.shape[0] EE = E[:, np.newaxis] * np.exp(1.j * angles) syms = af.np_to_af_array(symbols.astype(prec_dtype).reshape(1, 1, -1)) idxnd = np.zeros(L, dtype=np.int32) if L <= Nmax + N: Eaf = af.np_to_af_array(EE.astype(prec_dtype)) tmp = af.min(af.abs(af.broadcast(lambda x, y: x - y, Eaf[0:L, :], syms))**2, dim=2) cs = _movavg_af(tmp, 2 * N, axis=0) val, idx = af.imin(cs, dim=1) idxnd[N:-N] = np.array(idx) else: K = L // Nmax R = L % Nmax if R < N: R = R + Nmax K -= 1 Eaf = af.np_to_af_array(EE[0:Nmax + N].astype(prec_dtype)) tmp = af.min(af.abs(af.broadcast(lambda x, y: x - y, Eaf, syms))**2, dim=2) tt = np.array(tmp) cs = _movavg_af(tmp, 2 * N, axis=0) val, idx = af.imin(cs, dim=1) idxnd[N:Nmax] = np.array(idx) for i in range(1, K): Eaf = af.np_to_af_array(EE[i * Nmax - N:(i + 1) * Nmax + N].astype( np.complex128)) tmp = af.min(af.abs(af.broadcast(lambda x, y: x - y, Eaf, syms))**2, dim=2) cs = _movavg_af(tmp, 2 * N, axis=0) val, idx = af.imin(cs, dim=1) idxnd[i * Nmax:(i + 1) * Nmax] = np.array(idx) Eaf = af.np_to_af_array(EE[K * Nmax - N:K * Nmax + R].astype( np.complex128)) tmp = af.min(af.abs(af.broadcast(lambda x, y: x - y, Eaf, syms))**2, dim=2) cs = _movavg_af(tmp, 2 * N, axis=0) val, idx = af.imin(cs, dim=1) idxnd[K * Nmax:-N] = np.array(idx) return idxnd
def test_isoparam_x(): ''' This test tests the function ``isoparam_x`` function. It uses a list of analytically calculated values at this sage worksheet `isoparam.sagews`_ for an element at :math:`5` random :math:`(\\xi, \\eta)` coordinates and finds the :math:`L_1` norm of the :math:`x` coordinates got by the ``isoparam_x`` function. .. _isoparam.sagews: https://goo.gl/3EP3Pg ''' threshold = 1e-7 x_nodes = (np.array([0., 0.2, 0., 0.5, 1., 0.8, 1., 0.5])) y_nodes = (np.array([1., 0.5, 0., 0.2, 0., 0.5, 1., 0.8])) xi = np.array( [-0.71565335, -0.6604077, -0.87006188, -0.59216134, 0.73777285]) eta = np.array( [-0.76986362, 0.62167345, -0.38380703, 0.85833585, 0.92388897]) Xi, Eta = np.meshgrid(xi, eta) Xi = af.np_to_af_array(Xi) Eta = af.np_to_af_array(Eta) x = isoparam.isoparam_x_2D(x_nodes, Xi, Eta) y = isoparam.isoparam_y_2D(y_nodes, Xi, Eta) test_x = af.np_to_af_array(np.array( \ [[ 0.20047188, 0.22359428, 0.13584604, 0.25215798, 0.80878597], [ 0.22998716, 0.2508311 , 0.1717295 , 0.27658015, 0.77835843], [ 0.26421973, 0.28242104, 0.21334805, 0.3049056 , 0.7430678 ], [ 0.17985384, 0.20456788, 0.11077948, 0.23509776, 0.83004127], [ 0.16313183, 0.18913674, 0.09044955, 0.22126127, 0.84728013]])) test_y = af.np_to_af_array( np.array([[0.19018229, 0.20188751, 0.15248238, 0.2150496, 0.18523221], [0.75018125, 0.74072916, 0.78062435, 0.73010062, 0.7541785], [0.34554379, 0.3513793, 0.32674892, 0.35794112, 0.34307598], [0.84542176, 0.83237139, 0.88745412, 0.81769672, 0.8509407], [0.87180243, 0.85775537, 0.9170449, 0.84195996, 0.87774287]])) L1norm_x_test_x = np.abs(x - test_x).sum() L1norm_y_test_y = np.abs(y - test_y).sum() assert (L1norm_x_test_x < threshold) & (L1norm_y_test_y < threshold)
def af_gauss(data,kernels): d_kernels = [] for k in kernels: d_k = af.np_to_af_array(k) d_kernels.append(af.matmul(d_k,af.transpose(d_k))) ##d_k = af.matmul(af.transpose(d_k),d_k) out = [] for d in data: d_img = af.np_to_af_array(d) for d_k in d_kernels: #res = af.convolve2_separable(d_k, af.transpose(d_k), d_img) res = af.convolve2(d_img, d_k) # create numpy array out.append(res.__array__()) return out
def time_evolution(u=None): ''' Solves the wave equation .. math:: u^{t_n + 1} = b(t_n) \\times A iterated over time.shape[0] time steps t_n Second order time stepping is used. It increases the accuracy of the wave evolution. The second order time-stepping would be `U^{n + 1/2} = U^n + dt / 2 (A^{-1} B(U^n))` `U^{n + 1} = U^n + dt (A^{-1} B(U^{n + 1/2}))` Returns ------- None ''' # Creating a folder to store hdf5 files. If it doesn't exist. results_directory = 'results/hdf5_%02d' % (int(params.N_LGL)) if not os.path.exists(results_directory): os.makedirs(results_directory) element_LGL = params.element_LGL delta_t = params.delta_t shape_u_n = utils.shape(u) time = params.time A_inverse = af.tile(af.inverse(A_matrix()), d0=1, d1=1, d2=shape_u_n[2]) element_boundaries = af.np_to_af_array(params.np_element_array) for t_n in trange(0, time.shape[0]): if (t_n % 20) == 0: h5file = h5py.File( 'results/hdf5_%02d/dump_timestep_%06d' % (int(params.N_LGL), int(t_n)) + '.hdf5', 'w') dset = h5file.create_dataset('u_i', data=u, dtype='d') dset[:, :] = u[:, :] # Code for solving 1D Maxwell's Equations # Storing u at timesteps which are multiples of 100. #if (t_n % 5) == 0: #h5file = h5py.File('results/hdf5_%02d/dump_timestep_%06d' \ #%(int(params.N_LGL), int(t_n)) + '.hdf5', 'w') #Ez_dset = h5file.create_dataset('E_z', data = u[:, :, 0], #dtype = 'd') #By_dset = h5file.create_dataset('B_y', data = u[:, :, 1], #dtype = 'd') #Ez_dset[:, :] = u[:, :, 0] #By_dset[:, :] = u[:, :, 1] u += RK4_timestepping(A_inverse, u, delta_t)
def integrate_1d(polynomials, order, scheme = 'gauss'): ''' Integrates single variables using the Gauss-Legendre or Gauss-Lobatto quadrature. Parameters ---------- polynomials : af.Array [number_of_polynomials degree 1 1] The polynomials to be integrated. order : int Order of the quadrature. scheme : str Possible options are - ``gauss`` for using Gauss-Legendre quadrature - ``lobatto`` for using Gauss-Lobatto quadrature Returns ------- integral : af.Array [number_of_polynomials 1 1 1] The integral for the respective polynomials using the given quadrature scheme. ''' integral = 0.0 if scheme == 'gauss': N_g = order xi_gauss = af.np_to_af_array(lagrange.gauss_nodes(N_g)) gauss_weights = lagrange.gaussian_weights(N_g) polyval_gauss = polyval_1d(polynomials, xi_gauss) integral = af.sum(af.transpose(af.broadcast(multiply, af.transpose(polyval_gauss), gauss_weights)), dim = 1) return integral elif scheme == 'lobatto': N_l = order xi_lobatto = lagrange.LGL_points(N_l) lobatto_weights = lagrange.lobatto_weights(N_l) polyval_lobatto = polyval_1d(polynomials, xi_lobatto) integral = af.sum(af.transpose(af.broadcast(multiply, af.transpose(polyval_lobatto), lobatto_weights)), dim = 1) return integral else: return -1.
def contour_2d(u, index): ''' ''' color_levels = np.linspace(-1.1, 1.1, 100) u_plot = af.flip(af.moddims(u, params.N_LGL, params.N_LGL, 10, 10), 0) x_plot = af.flip(af.moddims(x_e_ij, params.N_LGL, params.N_LGL, 10, 10), 0) y_plot = af.flip(af.moddims(y_e_ij, params.N_LGL, params.N_LGL, 10, 10), 0) x_contour = af.np_to_af_array( np.zeros([params.N_LGL * 10, params.N_LGL * 10])) y_contour = af.np_to_af_array( np.zeros([params.N_LGL * 10, params.N_LGL * 10])) u_contour = af.np_to_af_array( np.zeros([params.N_LGL * 10, params.N_LGL * 10])) fig = pl.figure() # for i in range(100): p = int(i / 10) q = i - p * 10 x_contour[p * params.N_LGL:params.N_LGL * (p + 1),\ q * params.N_LGL:params.N_LGL * (q + 1)] = x_plot[:, :, q, p] y_contour[p * params.N_LGL:params.N_LGL * (p + 1),\ q * params.N_LGL:params.N_LGL * (q + 1)] = y_plot[:, :, q, p] u_contour[p * params.N_LGL:params.N_LGL * (p + 1),\ q * params.N_LGL:params.N_LGL * (q + 1)] = u_plot[:, :, q, p] x_contour = np.array(x_contour) y_contour = np.array(y_contour) u_contour = np.array(u_contour) pl.contourf(x_contour, y_contour, u_contour, 200, levels=color_levels, cmap='jet') pl.gca().set_aspect('equal') pl.colorbar() pl.title('Time = %.2f' % (index * 10 * delta_t_2d)) fig.savefig('results/2D_Wave_images/%04d' % (index) + '.png') pl.close('all') return
def test_integrate_1d(): ''' Tests the ``integrate_1d`` by comparing the integral agains the analytically calculated integral. The polynomials to be integrated are all the Lagrange polynomials obtained for the LGL points. The analytical integral is calculated in this `sage worksheet`_ .. _sage worksheet: https://goo.gl/1uYyNJ ''' threshold = 1e-12 N_LGL = 8 xi_LGL = lagrange.LGL_points(N_LGL) eta_LGL = lagrange.LGL_points(N_LGL) _, Li_xi = lagrange.lagrange_polynomials(xi_LGL) _, Lj_eta = lagrange.lagrange_polynomials(eta_LGL) Li_xi = af.np_to_af_array(Li_xi) Lp_xi = Li_xi.copy() Li_Lp = utils.poly1d_product(Li_xi, Lp_xi) test_integral_gauss = utils.integrate_1d(Li_Lp, order=9, scheme='gauss') test_integral_lobatto = utils.integrate_1d(Li_Lp, order=N_LGL + 1, scheme='lobatto') ref_integral = af.np_to_af_array( np.array([ 0.0333333333333, 0.196657278667, 0.318381179651, 0.384961541681, 0.384961541681, 0.318381179651, 0.196657278667, 0.0333333333333 ])) diff_gauss = af.abs(ref_integral - test_integral_gauss) diff_lobatto = af.abs(ref_integral - test_integral_lobatto) assert af.all_true(diff_gauss < threshold) and af.all_true( diff_lobatto < threshold)
def lax_friedrichs_flux(u, gv): ''' ''' u = af.reorder(af.moddims(u, params.N_LGL**2, 10, 10), 2, 1, 0) diff_u_boundary = af.np_to_af_array(np.zeros([10, 10, params.N_LGL**2])) u_xi_minus1_boundary_right = u[:, :, :params.N_LGL] u_xi_minus1_boundary_left = af.shift(u[:, :, -params.N_LGL:], d0=0, d1=1) u[:, :, :params.N_LGL] = (u_xi_minus1_boundary_right + u_xi_minus1_boundary_left) / 2 diff_u_boundary[:, :, :params.N_LGL] = (u_xi_minus1_boundary_right - u_xi_minus1_boundary_left) u_xi_1_boundary_left = u[:, :, -params.N_LGL:] u_xi_1_boundary_right = af.shift(u[:, :, :params.N_LGL], d0=0, d1=-1) u[:, :, :params.N_LGL] = (u_xi_minus1_boundary_left + u_xi_minus1_boundary_right) / 2 diff_u_boundary[:, :, -params.N_LGL:] = (u_xi_minus1_boundary_right - u_xi_minus1_boundary_left) u_eta_minus1_boundary_down = af.shift(u[:, :, params.N_LGL - 1:params.N_LGL**2:params.N_LGL], d0=-1) u_eta_minus1_boundary_up = u[:, :, 0:-params.N_LGL + 1:params.N_LGL] u[:, :, 0:-params.N_LGL + 1:params.N_LGL] = (u_eta_minus1_boundary_down\ + u_eta_minus1_boundary_up) / 2 diff_u_boundary[:, :, 0:-params.N_LGL + 1:params.N_LGL] = (u_eta_minus1_boundary_up\ -u_eta_minus1_boundary_down) u_eta_1_boundary_down = u[:, :, params.N_LGL - 1:params.N_LGL**2:params.N_LGL] u_eta_1_boundary_up = af.shift(u[:, :, 0:-params.N_LGL + 1:params.N_LGL], d0=1) u[:, :, params.N_LGL - 1:params.N_LGL ** 2:params.N_LGL] = (u_eta_1_boundary_up\ +u_eta_1_boundary_down) / 2 diff_u_boundary[:, :, params.N_LGL - 1:params.N_LGL ** 2:params.N_LGL] = (u_eta_1_boundary_up\ -u_eta_1_boundary_down) u = af.moddims(af.reorder(u, 2, 1, 0), params.N_LGL**2, 100) diff_u_boundary = af.moddims(af.reorder(diff_u_boundary, 2, 1, 0), params.N_LGL**2, 100) F_xi_e_ij = F_xi(u, gv) - params.c_x * diff_u_boundary F_eta_e_ij = F_eta(u, gv) - params.c_y * diff_u_boundary return F_xi_e_ij, F_eta_e_ij
def time_evolution(): u = params.u_init v = params.v_init h = 1 / (params.n - 1) delta_t = params.delta_t time = params.t no_of_timesteps = time / delta_t Lambda = params.viscosity * delta_t / (params.delta_x**2) Lambda_projection = 1 / (params.delta_x**2) A_diffusion_inverse = af.np_to_af_array( np.linalg.inv(np.array(sparse_matrix(params.n - 2, -Lambda)))) A_projection_inv = af.np_to_af_array( np.linalg.inv( np.array(sparse_matrix(params.n, Lambda_projection, 'true')))) for t_n in trange(int(no_of_timesteps)): u1, v1 = diffusion_step(u, v, -Lambda, A_diffusion_inverse) # note the -lambda u2, v2 = projection_step(u1, v1, A_projection_inv) u3, v3 = advection_step(u2, v2) u, v = projection_step(u3, v3, A_projection_inv) # h5py files if (t_n % 100 == 0): with h5py.File( 'results/h5py/dump_timestep_%06d' % (int(t_n)) + '.hdf5', 'w') as hf: u_final, v_final = add_boundary_conditions(u, v) hf.create_dataset('u', data=u_final) hf.create_dataset('v', data=v_final) if (af.max(u) > 100): break return
def test_LGL_points(): ''' Comparing the LGL nodes obtained by LGL_points with the reference nodes for N = 6 ''' reference_nodes = \ af.np_to_af_array(np.array([-1., -0.7650553239294647,\ -0.28523151648064504, 0.28523151648064504,\ 0.7650553239294647, 1. \ ] \ ) \ ) calculated_nodes = (lagrange.LGL_points(6)) assert (af.max(af.abs(reference_nodes - calculated_nodes)) <= 1e-14)
def Li_Lj_coeffs(N_LGL): ''' ''' xi_LGL = lagrange.LGL_points(N_LGL) lagrange_coeffs = af.np_to_af_array( lagrange.lagrange_polynomials(xi_LGL)[1]) Li_xi = af.moddims(af.tile(af.reorder(lagrange_coeffs, 1, 2, 0), 1, N_LGL), N_LGL, 1, N_LGL**2) Lj_eta = af.tile(af.reorder(lagrange_coeffs, 1, 2, 0), 1, 1, N_LGL) Li_Lj_coeffs = utils.polynomial_product_coeffs(Li_xi, Lj_eta) return Li_Lj_coeffs