def lobatto_quad_multivar_poly(poly_xi_eta, N_quad, advec_var): ''' ''' shape_poly_2d = shape(poly_xi_eta) xi_LGL = lagrange.LGL_points(N_quad) eta_LGL = lagrange.LGL_points(N_quad) Xi, Eta = af_meshgrid(xi_LGL, eta_LGL) Xi = af.flat(Xi) Eta = af.flat(Eta) w_i = lagrange.lobatto_weights(N_quad) w_j = lagrange.lobatto_weights(N_quad) W_i, W_j = af_meshgrid(w_i, w_j) W_i = af.tile(af.flat(W_i), d0 = 1, d1 = shape_poly_2d[2]) W_j = af.tile(af.flat(W_j), d0 = 1, d1 = shape_poly_2d[2]) P_xi_eta_quad_val = af.transpose(polyval_2d(poly_xi_eta, Xi, Eta)) integral = af.sum(W_i * W_j * P_xi_eta_quad_val, dim = 0) return af.transpose(integral)
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 test_interpolation(): ''' ''' threshold = 8e-9 params.N_LGL = 8 gv = 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) N_LGL = 8 xi_LGL = lagrange.LGL_points(N_LGL) xi_i = af.flat(af.transpose(af.tile(xi_LGL, 1, N_LGL))) eta_j = af.tile(xi_LGL, N_LGL) f_ij = np.e**(xi_i + eta_j) interpolated_f = wave_equation_2d.lag_interpolation_2d( f_ij, gv.Li_Lj_coeffs) xi = utils.linspace(-1, 1, 8) eta = utils.linspace(-1, 1, 8) assert (af.mean( af.transpose(utils.polyval_2d(interpolated_f, xi, eta)) - np.e**(xi + eta)) < threshold)
def dct2(arr, inverse=False): if inverse: return af.transpose( idct1(af.transpose(idct1(arr, norm='ortho')), norm='ortho')) else: return af.transpose( dct1(af.transpose(dct1(arr, norm='ortho')), norm='ortho'))
def integrate(integrand_coeffs): ''' Performs integration according to the given quadrature method by taking in the coefficients of the polynomial and the number of quadrature points. The number of quadrature points and the quadrature scheme are set in params.py module. Parameters ---------- integrand_coeffs : arrayfire.Array [M N 1 1] The coefficients of M number of polynomials of order N arranged in a 2D array. Returns ------- Integral : arrayfire.Array [M 1 1 1] The value of the definite integration performed using the specified quadrature method for M polynomials. ''' integrand = integrand_coeffs if (params.scheme == 'gauss_quadrature'): #print('gauss_quad') gaussian_nodes = params.gauss_points Gauss_weights = params.gauss_weights nodes_tile = af.transpose( af.tile(gaussian_nodes, 1, integrand.shape[1])) power = af.flip(af.range(integrand.shape[1])) nodes_power = af.broadcast(utils.power, nodes_tile, power) weights_tile = af.transpose( af.tile(Gauss_weights, 1, integrand.shape[1])) nodes_weight = nodes_power * weights_tile value_at_gauss_nodes = af.matmul(integrand, nodes_weight) integral = af.sum(value_at_gauss_nodes, 1) if (params.scheme == 'lobatto_quadrature'): #print('lob_quad') lobatto_nodes = params.lobatto_quadrature_nodes Lobatto_weights = params.lobatto_weights_quadrature nodes_tile = af.transpose(af.tile(lobatto_nodes, 1, integrand.shape[1])) power = af.flip(af.range(integrand.shape[1])) nodes_power = af.broadcast(utils.power, nodes_tile, power) weights_tile = af.transpose( af.tile(Lobatto_weights, 1, integrand.shape[1])) nodes_weight = nodes_power * weights_tile value_at_lobatto_nodes = af.matmul(integrand, nodes_weight) integral = af.sum(value_at_lobatto_nodes, 1) return integral
def read_and_preprocess_mnist_data(): print('Reading and preprocessing MNIST data...') train_images = af.read_array('train_images.af', key='train_images') train_targets = af.read_array('train_targets.af', key='train_targets') test_images = af.read_array('test_images.af', key='test_images') test_targets = af.read_array('test_targets.af', key='test_targets') num_train = train_images.dims()[2] num_classes = train_targets.dims()[0] num_test = test_images.dims()[2] feature_length = int(train_images.elements() / num_train) train_feats = af.transpose( af.moddims(train_images, feature_length, num_train)) test_feats = af.transpose(af.moddims(test_images, feature_length, num_test)) train_targets = af.transpose(train_targets) test_targets = af.transpose(test_targets) X_train = train_feats.to_ndarray() y_train = train_targets.to_ndarray() X_test = test_feats.to_ndarray() y_test = test_targets.to_ndarray() y_train = onehots_to_ints(y_train) y_test = onehots_to_ints(y_test) y_train = y_train.astype('uint32') y_test = y_test.astype('uint32') print('Reading and preprocessing MNIST data DONE') return (X_train, y_train, X_test, y_test)
def forward(nn_np, data): """ Given a dictionary representing a feed forward neural net and an input data matrix compute the network's output and store it within the dictionary :param nn: neural network dictionary :param data: a numpy n by m matrix where m in the number of input units in nn :return: the output layer activations """ nn = nn_np nn['activations'] = [] afData = data.ctypes.data, data.shape, data.dtype.char for i in range(data.shape[0]): nn['activations'].append( af.Array(data[i].ctypes.data, data[i].shape, data[i].dtype.char)) nn['zs'] = [] for w, s, b in map(None, nn['weights'], nn['nonlin'], nn['biases']): #print af.transpose(nn['activations'][-1]) print nn['activations'][-1] print "" print w z = af.dot(nn['activations'][-1], w) nn['zs'].append(af.transpose(z)) nn['activations'].append(s[0](af.transpose(z))) return nn['activations'][-1]
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 volume_integral(u, advec_var): ''' Vectorize, p, q, moddims. ''' dLp_xi_ij_Lq_eta_ij = advec_var.dLp_Lq dLq_eta_ij_Lp_xi_ij = advec_var.dLq_Lp dxi_dx = 10. deta_dy = 10. jacobian = 100. c_x = params.c_x c_y = params.c_y if (params.volume_integrand_scheme_2d == 'Lobatto' and params.N_LGL == params.N_quad): w_i = af.flat( af.transpose( af.tile(advec_var.lobatto_weights_quadrature, 1, params.N_LGL))) w_j = af.tile(advec_var.lobatto_weights_quadrature, params.N_LGL) wi_wj_dLp_xi = af.broadcast(utils.multiply, w_i * w_j, advec_var.dLp_Lq) volume_integrand_ij_1_sp = c_x * dxi_dx * af.broadcast(utils.multiply,\ wi_wj_dLp_xi, u) / jacobian wi_wj_dLq_eta = af.broadcast(utils.multiply, w_i * w_j, advec_var.dLq_Lp) volume_integrand_ij_2_sp = c_y * deta_dy * af.broadcast(utils.multiply,\ wi_wj_dLq_eta, u) / jacobian volume_integral = af.reorder( af.sum(volume_integrand_ij_1_sp + volume_integrand_ij_2_sp, 0), 2, 1, 0) else: volume_integrand_ij_1 = c_x * dxi_dx * af.broadcast(utils.multiply,\ dLp_xi_ij_Lq_eta_ij,\ u) / jacobian volume_integrand_ij_2 = c_y * deta_dy * af.broadcast(utils.multiply,\ dLq_eta_ij_Lp_xi_ij,\ u) / jacobian volume_integrand_ij = af.moddims(volume_integrand_ij_1 + volume_integrand_ij_2, params.N_LGL ** 2,\ (params.N_LGL ** 2) * 100) lagrange_interpolation = af.moddims( wave_equation_2d.lag_interpolation_2d(volume_integrand_ij, advec_var.Li_Lj_coeffs), params.N_LGL, params.N_LGL, params.N_LGL**2 * 100) volume_integrand_total = utils.integrate_2d_multivar_poly(lagrange_interpolation[:, :, :],\ params.N_quad,'gauss', advec_var) volume_integral = af.transpose( af.moddims(volume_integrand_total, 100, params.N_LGL**2)) return volume_integral
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 forward(nn_np, data): """ Given a dictionary representing a feed forward neural net and an input data matrix compute the network's output and store it within the dictionary :param nn: neural network dictionary :param data: a numpy n by m matrix where m in the number of input units in nn :return: the output layer activations """ nn = af.array(nn_np.ctypes.data, nn_np.shape, nn_np.dtype.char) nn['activations'] = [data] nn['zs'] = [] for w, s, b in map(None, nn['weights'], nn['nonlin'], nn['biases']): z = af.dot(w, af.transpose(nn['activations'][-1])) + b nn['zs'].append(af.transpose(z)) nn['activations'].append(s[0](af.transpose(z))) return nn['activations'][-1]
def test_concatenated(self): a = Array([[1, 2], [1, 3], [1, 4], [1, 5], [1, 6], [1, 7], [1, 8], [1, 9], [1, 10], [1, 11]]) b = absolute_sum_of_changes(a).to_arrayfire() c = af.transpose(b) d = Array.from_arrayfire(c) e = abs_energy(d).to_numpy() self.assertAlmostEqual(e, 385, delta=self.DELTA)
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 multivariable_poly_value(poly_2d, x, y): ''' ''' polynomial_coeffs = af.transpose(af.moddims(poly_2d, poly_2d.shape[0] ** 2, poly_2d.shape[2])) power_index = af.flip(af.np_to_af_array(np.arange(poly_2d.shape[0]))) x_power_indices = af.flat(af.transpose(af.tile(power_index, 1, poly_2d.shape[0]))) y_power_indices = af.tile(power_index, poly_2d.shape[0]) x_power = af.broadcast(power, af.transpose(x), x_power_indices) y_power = af.broadcast(power, af.transpose(y), y_power_indices) polynomial_value = af.matmul(polynomial_coeffs, x_power * y_power) return polynomial_value
def lagrange_interpolation(fn_i): ''' Finds the general interpolation of a function. Parameters ---------- fn_i : af.Array [N N_LGL 1 1] Value of :math:`N` functions at the LGL points. Returns ------- lagrange_interpolation : af.Array [N N_LGL 1 1] :math:`N` interpolated polynomials for :math:`N` functions. ''' fn_i = af.transpose(af.reorder(fn_i, d0=2, d1=1, d2=0)) lagrange_interpolation = af.broadcast(utils.multiply, params.lagrange_coeffs, fn_i) lagrange_interpolation = af.reorder(af.sum(lagrange_interpolation, dim=0), d0=2, d1=1, d2=0) return lagrange_interpolation
def matmul_3D(a, b): ''' Finds the matrix multiplication of :math:`Q` pairs of matrices ``a`` and ``b``. Parameters ---------- a : af.Array [M N Q 1] First set of :math:`Q` 2D arrays :math:`N \\neq 1` and :math:`M \\neq 1`. b : af.Array [N P Q 1] Second set of :math:`Q` 2D arrays :math:`P \\neq 1`. Returns ------- matmul : af.Array [M P Q 1] Matrix multiplication of :math:`Q` sets of 2D arrays. ''' shape_a = shape(a) shape_b = shape(b) P = shape_b[1] a = af.transpose(a) a = af.reorder(a, d0=0, d1=3, d2=2, d3=1) a = af.tile(a, d0=1, d1=P) b = af.tile(b, d0=1, d1=1, d2=1, d3=a.shape[3]) matmul = af.sum(a * b, dim=0) matmul = af.reorder(matmul, d0=3, d1=1, d2=2, d3=0) return matmul
def poly1d_product(poly_a, poly_b): ''' Finds the product of two polynomials using the arrayfire convolve1 function. Parameters ---------- poly_a : af.Array[N degree_a 1 1] :math:`N` polynomials of degree :math:`degree` poly_b : af.Array[N degree_b 1 1] :math:`N` polynomials of degree :math:`degree_b` ''' return af.transpose( af.convolve1(af.transpose(poly_a), af.transpose(poly_b), conv_mode=af.CONV_MODE.EXPAND))
def polyval_2d(poly_2d, xi, eta): ''' ''' poly_2d_shape = poly_2d.shape poly_xy = af.tile(poly_2d, d0 = 1, d1 = 1, d2 = 1, d3 = xi.shape[0]) poly_xy_shape = poly_xy.shape # print(poly_xy) xi_power = af.flip(af.range(poly_xy_shape[1], dtype = af.Dtype.u32)) xi_power = af.tile(af.transpose(xi_power), d0 = poly_xy_shape[0]) xi_power = af.tile(xi_power, d0 = 1, d1 = 1, d2 = xi.shape[0]) eta_power = af.flip(af.range(poly_xy_shape[0], dtype = af.Dtype.u32)) eta_power = af.tile(eta_power, d0 = 1, d1 = poly_xy_shape[1]) eta_power = af.tile(eta_power, d0 = 1, d1 = 1, d2 = eta.shape[0]) Xi = af.reorder(xi, d0 = 2, d1 = 1, d2 = 0) Xi = af.tile(Xi, d0 = poly_xy_shape[0], d1 = poly_xy_shape[1]) Xi = af.pow(Xi, xi_power) Xi = af.reorder(Xi, d0 = 0, d1 = 1, d2 = 3, d3 = 2) # print(Xi) Eta = af.reorder(eta, d0 = 2, d1 = 1, d2 = 0) Eta = af.tile(Eta, d0 = poly_xy_shape[0], d1 = poly_xy_shape[1]) Eta = af.pow(Eta, eta_power) Eta = af.reorder(Eta, d0 = 0, d1 = 1, d2 = 3, d3 = 2) # print(Eta) Xi_Eta = Xi * Eta poly_val = af.broadcast(multiply, poly_xy, Xi_Eta) poly_val = af.sum(af.sum(poly_val, dim = 1), dim = 0) poly_val = af.reorder(poly_val, d0 = 2, d1 = 3, d2 = 0, d3 = 1) return poly_val
def polyval_1d(polynomials, xi): ''' Finds the value of the polynomials at the given :math:`\\xi` coordinates. Parameters ---------- polynomials : af.Array [number_of_polynomials N 1 1] ``number_of_polynomials`` :math:`2D` polynomials of degree :math:`N - 1` of the form .. math:: P(x) = a_0x^0 + a_1x^1 + ... \\ a_{N - 1}x^{N - 1} + a_Nx^N xi : af.Array [N 1 1 1] :math:`\\xi` coordinates at which the :math:`i^{th}` Lagrange basis polynomial is to be evaluated. Returns ------- af.Array [i.shape[0] xi.shape[0] 1 1] Evaluated polynomials at given :math:`\\xi` coordinates ''' N = int(polynomials.shape[1]) xi_ = af.tile(af.transpose(xi), d0=N) power = af.tile(af.flip(af.range(N), dim=0), d0=1, d1=xi.shape[0]) xi_power = xi_**power return af.matmul(polynomials, xi_power)
def volume_integral(u, gv): ''' Vectorize, p, q, moddims. ''' dLp_xi_ij_Lq_eta_ij = gv.dLp_Lq dLq_eta_ij_Lp_xi_ij = gv.dLq_Lp if (params.volume_integrand_scheme_2d == 'Lobatto' and params.N_LGL == params.N_quad): w_i = af.flat( af.transpose( af.tile(gv.lobatto_weights_quadrature, 1, params.N_LGL))) w_j = af.tile(gv.lobatto_weights_quadrature, params.N_LGL) wi_wj_dLp_xi = af.broadcast(utils.multiply, w_i * w_j, gv.dLp_Lq) volume_integrand_ij_1_sp = af.broadcast(utils.multiply,\ wi_wj_dLp_xi, F_xi(u, gv) * gv.sqrt_g) wi_wj_dLq_eta = af.broadcast(utils.multiply, w_i * w_j, gv.dLq_Lp) volume_integrand_ij_2_sp = af.broadcast(utils.multiply,\ wi_wj_dLq_eta, F_eta(u, gv) * gv.sqrt_g) volume_integral = af.reorder( af.sum(volume_integrand_ij_1_sp + volume_integrand_ij_2_sp, 0), 2, 1, 0) else: # NEEDS TO BE CHANGED volume_integrand_ij_1 = af.broadcast(utils.multiply,\ dLp_xi_ij_Lq_eta_ij,\ F_xi(u, gv)) volume_integrand_ij_2 = af.broadcast(utils.multiply,\ dLq_eta_ij_Lp_xi_ij,\ F_eta(u, gv)) volume_integrand_ij = af.moddims((volume_integrand_ij_1 + volume_integrand_ij_2)\ * np.mean(gv.sqrt_det_g), params.N_LGL ** 2,\ (params.N_LGL ** 2) * 100) lagrange_interpolation = af.moddims( lag_interpolation_2d(volume_integrand_ij, gv.Li_Lj_coeffs), params.N_LGL, params.N_LGL, params.N_LGL**2 * 100) volume_integrand_total = utils.integrate_2d_multivar_poly(lagrange_interpolation[:, :, :],\ params.N_quad,'gauss', gv) volume_integral = af.transpose( af.moddims(volume_integrand_total, 100, params.N_LGL**2)) return volume_integral
def simple_data(verbose=False): display_func = _util.display_func(verbose) print_func = _util.print_func(verbose) display_func(af.constant(100, 3,3, dtype=af.Dtype.f32)) display_func(af.constant(25, 3,3, dtype=af.Dtype.c32)) display_func(af.constant(2**50, 3,3, dtype=af.Dtype.s64)) display_func(af.constant(2+3j, 3,3)) display_func(af.constant(3+5j, 3,3, dtype=af.Dtype.c32)) display_func(af.range(3, 3)) display_func(af.iota(3, 3, tile_dims=(2,2))) display_func(af.identity(3, 3, 1, 2, af.Dtype.b8)) display_func(af.identity(3, 3, dtype=af.Dtype.c32)) a = af.randu(3, 4) b = af.diag(a, extract=True) c = af.diag(a, 1, extract=True) display_func(a) display_func(b) display_func(c) display_func(af.diag(b, extract = False)) display_func(af.diag(c, 1, extract = False)) display_func(af.join(0, a, a)) display_func(af.join(1, a, a, a)) display_func(af.tile(a, 2, 2)) display_func(af.reorder(a, 1, 0)) display_func(af.shift(a, -1, 1)) display_func(af.moddims(a, 6, 2)) display_func(af.flat(a)) display_func(af.flip(a, 0)) display_func(af.flip(a, 1)) display_func(af.lower(a, False)) display_func(af.lower(a, True)) display_func(af.upper(a, False)) display_func(af.upper(a, True)) a = af.randu(5,5) display_func(af.transpose(a)) af.transpose_inplace(a) display_func(a) display_func(af.select(a > 0.3, a, -0.3)) af.replace(a, a > 0.3, -0.3) display_func(a)
def simple_data(verbose=False): display_func = _util.display_func(verbose) display_func(af.constant(100, 3, 3, dtype=af.Dtype.f32)) display_func(af.constant(25, 3, 3, dtype=af.Dtype.c32)) display_func(af.constant(2**50, 3, 3, dtype=af.Dtype.s64)) display_func(af.constant(2+3j, 3, 3)) display_func(af.constant(3+5j, 3, 3, dtype=af.Dtype.c32)) display_func(af.range(3, 3)) display_func(af.iota(3, 3, tile_dims=(2, 2))) display_func(af.identity(3, 3, 1, 2, af.Dtype.b8)) display_func(af.identity(3, 3, dtype=af.Dtype.c32)) a = af.randu(3, 4) b = af.diag(a, extract=True) c = af.diag(a, 1, extract=True) display_func(a) display_func(b) display_func(c) display_func(af.diag(b, extract=False)) display_func(af.diag(c, 1, extract=False)) display_func(af.join(0, a, a)) display_func(af.join(1, a, a, a)) display_func(af.tile(a, 2, 2)) display_func(af.reorder(a, 1, 0)) display_func(af.shift(a, -1, 1)) display_func(af.moddims(a, 6, 2)) display_func(af.flat(a)) display_func(af.flip(a, 0)) display_func(af.flip(a, 1)) display_func(af.lower(a, False)) display_func(af.lower(a, True)) display_func(af.upper(a, False)) display_func(af.upper(a, True)) a = af.randu(5, 5) display_func(af.transpose(a)) af.transpose_inplace(a) display_func(a) display_func(af.select(a > 0.3, a, -0.3)) af.replace(a, a > 0.3, -0.3) display_func(a) display_func(af.pad(a, (1, 1, 0, 0), (2, 2, 0, 0)))
def polynomial_derivative(polynomial): ''' ''' derivtive_multiplier = af.tile(af.transpose(af.flip( af.range(polynomial.shape[1]))), d0 = polynomial.shape[0]) return (polynomial * derivtive_multiplier)[:, : -1]
def polynomial_product_coeffs(poly1_coeffs, poly2_coeffs): ''' ''' poly1_coeffs_tile = af.transpose(af.tile(poly1_coeffs, 1, poly1_coeffs.shape[0])) poly2_coeffs_tile = af.tile(poly2_coeffs, 1, poly2_coeffs.shape[0]) product_coeffs = poly1_coeffs_tile * poly2_coeffs_tile return product_coeffs
def T(self): """ Same as self.transpose(), except that self is returned if self.ndim < 2. """ if self.ndim < 2: return self else: return ndarray(af.transpose(self._af_array, False))
def volume_int_convergence(): ''' convergence test for volume int flux ''' N_LGL = np.arange(15).astype(float) + 3 L1_norm_option_3 = np.zeros([15]) L1_norm_option_1 = np.zeros([15]) for i in range(0, 15): test_waveEqn.change_parameters(i + 3, 16, i + 4) vol_int_analytical = np.zeros([params.N_Elements, params.N_LGL]) for j in range (params.N_Elements): for k in range (params.N_LGL): vol_int_analytical[j][k] = (analytical_volume_integral\ (af.transpose(params.element_array[j]), k)) vol_int_analytical = af.transpose(af.np_to_af_array\ (vol_int_analytical)) L1_norm_option_3[i] = af.mean(af.abs(vol_int_analytical\ - wave_equation.volume_integral_flux(params.u_init, 0))) for i in range(0, 15): test_waveEqn.change_parameters(i + 3, 16, i + 3) vol_int_analytical = np.zeros([params.N_Elements, params.N_LGL]) for j in range (params.N_Elements): for k in range (params.N_LGL): vol_int_analytical[j][k] = analytical_volume_integral(\ af.transpose(params.element_array[j]), k) vol_int_analytical = af.transpose(af.np_to_af_array(vol_int_analytical)) L1_norm_option_1[i] = af.mean(af.abs(vol_int_analytical\ - wave_equation.volume_integral_flux(params.u_init, 0))) normalization = 0.0023187 / (3 ** (-3)) print(L1_norm_option_1, L1_norm_option_3) plt.loglog(N_LGL, L1_norm_option_1, marker='o', label='L1 norm option 1') plt.loglog(N_LGL, L1_norm_option_3, marker='o', label='L1 norm option 3') plt.loglog(N_LGL, normalization * N_LGL **(-N_LGL), color='black', linestyle='--', label='$N_{LGL}^{-N_{LGL}}$') plt.title('L1 norm of volume integral term') plt.xlabel('LGL points') plt.ylabel('L1 norm') plt.legend(loc='best') plt.show()
def test_volume_integral_flux(): ''' A test function to check the volume_integral_flux function in wave_equation module by analytically calculated Gauss-Lobatto quadrature. Reference --------- The link to the sage worksheet where the calculations were caried out is given below. `https://goo.gl/5Mub8M` ''' threshold = 4e-9 params.c = 1 change_parameters(8, 10, 11, 'gaussian') referenceFluxIntegral = af.transpose(af.interop.np_to_af_array(np.array ([ [-0.002016634876668093, -0.000588597708116113, -0.0013016773719126333,\ -0.002368387579324652, -0.003620502047659841, -0.004320197094090966, -0.003445512010153811, 0.0176615086879261],\ [-0.018969769374, -0.00431252844519,-0.00882630935977,-0.0144355176966,\ -0.019612124119, -0.0209837936827, -0.0154359890788, 0.102576031756], \ [-0.108222418798, -0.0179274222595, -0.0337807018822, -0.0492589052599,\ -0.0588472807471, -0.0557970236273, -0.0374764132459, 0.361310165819],\ [-0.374448714304, -0.0399576371245, -0.0683852285846, -0.0869229749357,\ -0.0884322503841, -0.0714664112839, -0.0422339853622, 0.771847201979], \ [-0.785754362849, -0.0396035640187, -0.0579313769517, -0.0569022801117,\ -0.0392041960688, -0.0172295769141, -0.00337464521455, 1.00000000213],\ [-1.00000000213, 0.00337464521455, 0.0172295769141, 0.0392041960688,\ 0.0569022801117, 0.0579313769517, 0.0396035640187, 0.785754362849],\ [-0.771847201979, 0.0422339853622, 0.0714664112839, 0.0884322503841, \ 0.0869229749357, 0.0683852285846, 0.0399576371245, 0.374448714304],\ [-0.361310165819, 0.0374764132459, 0.0557970236273, 0.0588472807471,\ 0.0492589052599, 0.0337807018822, 0.0179274222595, 0.108222418798], \ [-0.102576031756, 0.0154359890788, 0.0209837936827, 0.019612124119, \ 0.0144355176966, 0.00882630935977, 0.00431252844519, 0.018969769374],\ [-0.0176615086879, 0.00344551201015 ,0.00432019709409, 0.00362050204766,\ 0.00236838757932, 0.00130167737191, 0.000588597708116, 0.00201663487667]\ ]))) numerical_flux = wave_equation.volume_integral_flux(params.u[:, :, 0]) assert (af.mean(af.abs(numerical_flux - referenceFluxIntegral)) < threshold)
def contour_plot(u, v, t_n): ''' ''' u_map = af.moddims(u, params.n, params.n) v_map = af.moddims(v, params.n, params.n) scale = af.np_to_af_array(np.linspace(0, 1, params.n)) x_tile = af.tile(scale, 1, params.n) y_tile = af.transpose(x_tile) speed_tile = (af.transpose(u_map)**2 + af.transpose(v_map)**2)**0.5 x_tile = np.array(x_tile) y_tile = np.array(y_tile) speed_tile = np.array(af.flip(speed_tile, 0)) pl.contourf(y_tile, x_tile, speed_tile, cmap='jet') pl.gca().set_aspect('equal') pl.title('Time = %.2f' % (t_n * params.delta_t)) pl.xlabel('x') pl.ylabel('y') pl.colorbar() pl.savefig('results/images/%04d' % (t_n) + '.png') pl.close('all')
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 forward(nn_np, data): """ Given a dictionary representing a feed forward neural net and an input data matrix compute the network's output and store it within the dictionary :param nn: neural network dictionary :param data: a numpy n by m matrix where m in the number of input units in nn :return: the output layer activations """ nn = nn_np nn['activations'] =[] afData = data.ctypes.data, data.shape, data.dtype.char for i in range(data.shape[0]): nn['activations'].append(af.Array(data[i].ctypes.data,data[i].shape,data[i].dtype.char)) nn['zs'] = [] for w, s, b in map(None, nn['weights'], nn['nonlin'], nn['biases']): #print af.transpose(nn['activations'][-1]) print nn['activations'][-1] print "" print w z = af.dot(nn['activations'][-1],w) nn['zs'].append(af.transpose(z)) nn['activations'].append(s[0](af.transpose(z))) return nn['activations'][-1]
def gauss_quad_multivar_poly(poly_xi_eta, N_quad, advec_var): ''' ''' shape_poly_2d = poly_xi_eta.shape xi_gauss = advec_var.gauss_points Xi = af.flat(af.transpose(af.tile(xi_gauss, 1, params.N_quad))) Eta = af.tile(xi_gauss, params.N_quad) w_i = advec_var.gauss_weights test_W_i = af.flat(af.transpose(af.tile(w_i, 1, params.N_quad))) test_W_j = af.tile(w_i, params.N_quad) W_i = af.tile(test_W_i, d0 = 1, d1 = shape_poly_2d[2]) W_j = af.tile(test_W_j, d0 = 1, d1 = shape_poly_2d[2]) P_xi_eta_quad_val = af.transpose(multivariable_poly_value(poly_xi_eta, Xi, Eta)) #P_xi_eta_quad_val = af.transpose(polyval_2d(poly_xi_eta, Xi, Eta)) integral = af.sum(W_i * W_j * P_xi_eta_quad_val, dim = 0) return af.transpose(integral)
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 transpose(self, *axes): if(self.ndim == 1): return self if len(axes) == 0 and self.ndim == 2: s = arrayfire.transpose(self.d_array) else: order = [0,1,2,3] if len(axes) == 0 or axes[0] is None: order[:self.ndim] = order[:self.ndim][::-1] else: if isinstance(axes[0], collections.Iterable): axes = axes[0] for i,ax in enumerate(axes): order[i] = pu.c2f(self.shape, ax) # We have to do this gymnastic due to the fact that arrayfire # uses Fortran order order[:len(axes)] = order[:len(axes)][::-1] #print order s = arrayfire.reorder(self.d_array, order[0],order[1],order[2],order[3]) return ndarray(pu.af_shape(s), dtype=self.dtype, af_array=s)
af.display(A[:,0]) A[0,0] = 11 A[1] = 100 af.display(A) af.display(B) A[1,:] = B[2,:] af.display(A) print("\n---- Bitwise operations\n") af.display(A & B) af.display(A | B) af.display(A ^ B) print("\n---- Transpose\n") af.display(A) af.display(af.transpose(A)) print("\n---- Flip Vertically / Horizontally\n") af.display(A) af.display(af.flip(A, 0)) af.display(af.flip(A, 1)) print("\n---- Sum, Min, Max along row / columns\n") af.display(A) af.display(af.sum(A, 0)) af.display(af.min(A, 0)) af.display(af.max(A, 0)) af.display(af.sum(A, 1)) af.display(af.min(A, 1)) af.display(af.max(A, 1))
a = af.array(host.array("i", [4, 5, 6])) af.display(a) print(a.elements(), a.type(), a.dims(), a.numdims()) print(a.is_empty(), a.is_scalar(), a.is_column(), a.is_row()) print(a.is_complex(), a.is_real(), a.is_double(), a.is_single()) print(a.is_real_floating(), a.is_floating(), a.is_integer(), a.is_bool()) a = af.array(host.array("l", [7, 8, 9] * 3), (3, 3)) af.display(a) print(a.elements(), a.type(), a.dims(), a.numdims()) print(a.is_empty(), a.is_scalar(), a.is_column(), a.is_row()) print(a.is_complex(), a.is_real(), a.is_double(), a.is_single()) print(a.is_real_floating(), a.is_floating(), a.is_integer(), a.is_bool()) af.display(af.transpose(a)) af.transpose_inplace(a) af.display(a) c = a.to_ctype() for n in range(a.elements()): print(c[n]) c, s = a.to_ctype(True, True) for n in range(a.elements()): print(c[n]) print(s) arr = a.to_array() lst = a.to_list(True)