def gradient(nn, delta): nabla_b = [] nabla_w = [] # output dact = nn['nonlin'][-1][1] t = nn['zs'][-1] asdf = dact(2) #This is d_relu. It is a binary output dW = average_gradient(delta * af.sign(1e-5 - nn['zs'][-1]), nn['activations'][-2]) nabla_b.append(af.mean(delta)) nabla_w.append(dW) for i in range(len(nn['weights']) - 2, -1, -1): dact = delta * af.max(nn['zs'][i + 1]) trans = nn['weights'][i + 1].T delta = af.matmul(trans, dact) dW = average_gradient(delta, nn['activations'][i]) nabla_b.append(af.mean(delta * af.max(nn['zs'][i]))) nabla_w.append(dW) return nabla_w, nabla_b
def get_cartesian_coords(q1, q2, q1_start_local_left=None, q2_start_local_bottom=None, return_jacobian = False ): q1_midpoint = 0.5*(af.max(q1) + af.min(q1)) q2_midpoint = 0.5*(af.max(q2) + af.min(q2)) # Default initializsation to rectangular grid x = q1 y = q2 jacobian = None if (q1_start_local_left != None and q2_start_local_bottom != None): if (return_jacobian): return (x, y, jacobian) else: return(x, y) else: print("Error in get_cartesian_coords(): q1_start_local_left or q2_start_local_bottom not provided") return(x, y)
def get_cartesian_coords(q1, q2, q1_start_local_left=None, q2_start_local_bottom=None, return_jacobian=False): q1_midpoint = 0.5 * (af.max(q1) + af.min(q1)) q2_midpoint = 0.5 * (af.max(q2) + af.min(q2)) d_q1 = (q1[0, 0, 1, 0] - q1[0, 0, 0, 0]).scalar() d_q2 = (q2[0, 0, 0, 1] - q2[0, 0, 0, 0]).scalar() # Default initializsation to rectangular grid x = q1 y = q2 #x = q1*(2+q2) #y = q2 jacobian = None #[[1. + 0.*q1, 0.*q1], #[ 0.*q1, 1. + 0.*q1] #] if (q1_start_local_left != None and q2_start_local_bottom != None): if (return_jacobian): return (x, y, jacobian) else: return (x, y) else: print( "Error in get_cartesian_coords(): q1_start_local_left or q2_start_local_bottom not provided" )
def gradient(nn, delta): nabla_b = [] nabla_w = [] # output dact = nn['nonlin'][-1][1] t = nn['zs'][-1] asdf = dact(2) #This is d_relu. It is a binary output dW = average_gradient(delta*af.sign(1e-5 - nn['zs'][-1]), nn['activations'][-2]) nabla_b.append(af.mean(delta)) nabla_w.append(dW) for i in range(len(nn['weights']) - 2, -1, -1): dact = delta * af.max(nn['zs'][i+1]) trans = nn['weights'][i+1].T delta = af.matmul(trans, dact) dW = average_gradient(delta,nn['activations'][i]) nabla_b.append(af.mean(delta*af.max(nn['zs'][i]))) nabla_w.append(dW) return nabla_w, nabla_b
def test_dirichlet(): obj = test('dirichlet', 'dirichlet') obj._A_q1, obj._A_q2 = af.Array([100]), af.Array([100]) obj._A_q1 = af.tile(obj._A_q1, 1, 1, obj.q1_center.shape[2]) obj._A_q2 = af.tile(obj._A_q2, 1, 1, obj.q1_center.shape[2]) obj.dt = 0.001 obj.f = af.constant(0, obj.q1_center.shape[0], obj.q1_center.shape[1], obj.q1_center.shape[2], dtype=af.Dtype.f64) apply_bcs_f(obj) expected = af.constant(0, obj.q1_center.shape[0], obj.q1_center.shape[1], obj.q1_center.shape[2], dtype=af.Dtype.f64) N_g = obj.N_ghost # Only ingoing characteristics should be affected: expected[:N_g] = af.select(obj.q1_center < obj.q1_start, 1, expected)[:N_g] expected[:, :N_g] = af.select(obj.q2_center < obj.q2_start, 2, expected)[:, :N_g] assert (af.max(af.abs(obj.f[:, N_g:-N_g] - expected[:, N_g:-N_g])) < 5e-14) assert (af.max(af.abs(obj.f[N_g:-N_g, :] - expected[N_g:-N_g, :])) < 5e-14)
def get_cartesian_coords(q1, q2, q1_start_local_left=None, q2_start_local_bottom=None, return_jacobian = False ): q1_midpoint = 0.5*(af.max(q1) + af.min(q1)) q2_midpoint = 0.5*(af.max(q2) + af.min(q2)) d_q1 = (q1[0, 0, 1, 0] - q1[0, 0, 0, 0]).scalar() d_q2 = (q2[0, 0, 0, 1] - q2[0, 0, 0, 0]).scalar() N_g = domain.N_ghost N_q1 = q1.dims()[2] - 2*N_g # Manually apply quadratic transformation for each zone along q1 N_q2 = q2.dims()[3] - 2*N_g # Manually apply quadratic transformation for each zone along q1 # Default initializsation to rectangular grid x = q1 y = q2 jacobian = [[1. + 0.*q1, 0.*q1], [ 0.*q1, 1. + 0.*q1] ] if (q1_start_local_left != None and q2_start_local_bottom != None): if (return_jacobian): return (x, y, jacobian) else: return(x, y) else: print("Error in get_cartesian_coords(): q1_start_local_left or q2_start_local_bottom not provided")
def get_cartesian_coords(q1, q2, q1_start_local_left=None, q2_start_local_bottom=None, return_jacobian = False ): q1_midpoint = 0.5*(af.max(q1) + af.min(q1)) q2_midpoint = 0.5*(af.max(q2) + af.min(q2)) x = q1 y = q2 jacobian = [[1. + 0.*q1, 0.*q1], [ 0.*q1, 1. + 0.*q1] ] print("coords.py : ", q1_midpoint, q2_midpoint) if (q1_start_local_left != None and q2_start_local_bottom != None): if (return_jacobian): return(x, y, jacobian) else: return(x, y) else: print("Error in get_cartesian_coords(): q1_start_local_left or q2_start_local_bottom not provided") return(x, y)
def get_cartesian_coords(q1, q2): q1_midpoint = 0.5*(af.max(q1) + af.min(q1)) q2_midpoint = 0.5*(af.max(q2) + af.min(q2)) x = q1 y = q2 return(x, y)
def tau_defect(q1, q2, p1, p2, p3): q1_midpoint = 0.5 * (af.max(q1) + af.min(q1)) q2_midpoint = 0.5 * (af.max(q2) + af.min(q2)) if (q2_midpoint < 0.75): tau_mr = np.inf else: tau_mr = 0.01 return (tau_mr * q1**0 * p1**0)
def get_cartesian_coords(q1, q2): q1_midpoint = 0.5 * (af.max(q1) + af.min(q1)) q2_midpoint = 0.5 * (af.max(q2) + af.min(q2)) x = q1 y = q2 # if (q1_midpoint > 4.25): # y = 3*q2-1 return (x, y)
def get_cartesian_coords(q1, q2): q1_midpoint = 0.5 * (af.max(q1) + af.min(q1)) q2_midpoint = 0.5 * (af.max(q2) + af.min(q2)) x = q1 y = q2 # if (q1_midpoint > 1.) and (q1_midpoint < 4.): # y = 0.5*q2+0.125 return (x, y)
def get_cartesian_coords(q1, q2, q1_start_local_left=None, q2_start_local_bottom=None, return_jacobian=False): q1_midpoint = 0.5 * (af.max(q1) + af.min(q1)) q2_midpoint = 0.5 * (af.max(q2) + af.min(q2)) x = q1 y = q2 jacobian = None if (q1_start_local_left != None and q2_start_local_bottom != None): if (q1_midpoint < -4.62): # Domain 1 and 7 y = 0.816 * q2 elif ((q1_midpoint > -4.62) and (q1_midpoint < 0)): # Domain 2 and 8 y = (q2 * (1 + 0.04 * (q1))) elif ((q1_midpoint > 29.46) and (q1_midpoint < 32.98) and (q2_midpoint < 12)): # Domain 5 y = ((q2 - 12) * (1 - 0.1193 * (q1 - 29.46))) + 12 elif ((q1_midpoint > 32.98) and (q2_midpoint < 12)): # Domain 6 y = 0.58 * (q2 - 12) + 12 elif ((q1_midpoint > 26.3) and (q1_midpoint < 29.46) and (q2_midpoint > 12)): # Domain 10 y = ((q2 - 12) * (1 - 2 * 0.0451 * (q1 - 26.3))) + 12 elif ((q1_midpoint > 29.46) and (q1_midpoint < 32.98) and (q2_midpoint > 12)): # Domain 11 y = ((q2 - 12) * (1 - 2 * 0.0451 * (q1 - 26.3))) + 12 elif ((q1_midpoint > 32.98) and (q2_midpoint > 12)): # Domain 12 y = 0.40 * (q2 - 12) + 12 # Numerically calculate Jacobian jacobian = None if (return_jacobian): return (x, y, jacobian) else: return (x, y) else: print( "Error in get_cartesian_coords(): q1_start_local_left or q2_start_local_bottom not provided" )
def get_cartesian_coords(q1, q2, q1_start_local_left=None, q2_start_local_bottom=None, return_jacobian=False): q1_midpoint = 0.5 * (af.max(q1) + af.min(q1)) q2_midpoint = 0.5 * (af.max(q2) + af.min(q2)) d_q1 = (q1[0, 0, 1, 0] - q1[0, 0, 0, 0]).scalar() d_q2 = (q2[0, 0, 0, 1] - q2[0, 0, 0, 0]).scalar() # Default initializsation to rectangular grid x = q1 y = q2 #x = q1*(2+q2) #y = q2 jacobian = None #[[1. + 0.*q1, 0.*q1], #[ 0.*q1, 1. + 0.*q1] #] if (q1_start_local_left != None and q2_start_local_bottom != None): # X_Y_top_right = [1, 1] # X_Y_top_left = [-1, 1] # X_Y_bottom_left = [-1, -1] # X_Y_bottom_right = [1, -1] # # x_y_top_right = [1, 1] # x_y_top_left = [-1, 1] # x_y_bottom_left = [-1, -0.5] # x_y_bottom_right = [1, -1] # # x, y = affine(q1, q2, # x_y_bottom_left, x_y_bottom_right, # x_y_top_right, x_y_top_left, # X_Y_bottom_left, X_Y_bottom_right, # X_Y_top_right, X_Y_top_left, # ) # # Numerically calculate Jacobian # jacobian = None if (return_jacobian): return (x, y, jacobian) else: return (x, y) else: print( "Error in get_cartesian_coords(): q1_start_local_left or q2_start_local_bottom not provided" )
def lowpass_filter(f): f_hat = af.fft(f) dp1 = (domain.p1_end[0] - domain.p1_start[0]) / domain.N_p1 k_v = af.tile(af.to_array(np.fft.fftfreq(domain.N_p1, dp1)), 1, 1, f.shape[2], f.shape[3]) # Applying the filter: f_hat_filtered = 0.5 * (f_hat * (af.tanh( (k_v + 0.9 * af.max(k_v)) / 0.5) - af.tanh( (k_v + 0.9 * af.min(k_v)) / 0.5))) f_hat = af.select(af.abs(k_v) < 0.8 * af.max(k_v), f_hat, f_hat_filtered) f = af.real(af.ifft(f_hat)) return (f)
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_surface_term(): ''' A test function to test the surface_term function in the wave_equation module using analytical Lax-Friedrichs flux. ''' threshold = 1e-13 params.c = 1 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) analytical_f_i = (gv.u_init[-1, :]) analytical_f_i_minus1 = (af.shift(gv.u_init[-1, :], 0, 1)) L_p_1 = af.constant(0, params.N_LGL, dtype=af.Dtype.f64) L_p_1[params.N_LGL - 1] = 1 L_p_minus1 = af.constant(0, params.N_LGL, dtype=af.Dtype.f64) L_p_minus1[0] = 1 analytical_surface_term = af.blas.matmul(L_p_1, analytical_f_i)\ - af.blas.matmul(L_p_minus1, analytical_f_i_minus1) numerical_surface_term = (wave_equation.surface_term(gv.u_init[:, :], gv)) assert af.max(af.abs(analytical_surface_term - numerical_surface_term)) \ < threshold return analytical_surface_term
def _train(self, X: af.Array, Y: af.Array, alpha: float, lambda_param: float, penalty: str, maxerr: float, maxiter: int) -> af.Array: # Add bias feature bias = af.constant(1, X.dims()[0], 1) X_biased = af.join(1, bias, X) # Initialize parameters to 0 Weights = af.constant(0, X_biased.dims()[1], Y.dims()[1]) for i in range(maxiter): # Get the cost and gradient J, dJ = self._cost(Weights, X_biased, Y, lambda_param, penalty) err = af.max(af.abs(J)) if err < maxerr: Weights = Weights[1:] # Remove bias weights return Weights # Update the weights via gradient descent Weights = Weights - alpha * dJ # Remove bias weights Weights = Weights[1:] return Weights
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_surface_term(): ''' A test function to test the surface_term function in the wave_equation module using analytical Lax-Friedrichs flux. ''' threshold = 1e-13 params.c = 1 change_parameters(8, 10, 8, 'gaussian') analytical_f_i = (params.u[-1, :, 0]) analytical_f_i_minus1 = (af.shift(params.u[-1, :, 0], 0, 1)) L_p_1 = af.constant(0, params.N_LGL, dtype=af.Dtype.f64) L_p_1[params.N_LGL - 1] = 1 L_p_minus1 = af.constant(0, params.N_LGL, dtype=af.Dtype.f64) L_p_minus1[0] = 1 analytical_surface_term = af.blas.matmul(L_p_1, analytical_f_i)\ - af.blas.matmul(L_p_minus1, analytical_f_i_minus1) numerical_surface_term = (wave_equation.surface_term(params.u[:, :, 0])) assert af.max(af.abs(analytical_surface_term - numerical_surface_term)) \ < threshold return analytical_surface_term
def train(X, Y, alpha=0.1, lambda_param=1.0, maxerr=0.01, maxiter=1000, verbose=False): # Initialize parameters to 0 Weights = af.constant(0, X.dims()[1], Y.dims()[1]) for i in range(maxiter): # Get the cost and gradient J, dJ = cost(Weights, X, Y, lambda_param) err = af.max(af.abs(J)) if err < maxerr: print('Iteration {0:4d} Err: {1:4f}'.format(i + 1, err)) print('Training converged') return Weights if verbose and ((i + 1) % 10 == 0): print('Iteration {0:4d} Err: {1:4f}'.format(i + 1, err)) # Update the parameters via gradient descent Weights = Weights - alpha * dJ if verbose: print('Training stopped after {0:d} iterations'.format(maxiter)) return Weights
def get_cartesian_coords(q1, q2): q1_midpoint = 0.5 * (af.max(q1) + af.min(q1)) q2_midpoint = 0.5 * (af.max(q2) + af.min(q2)) y = q2 if (q2_midpoint < 0): x = q1 else: x = q1 * (1 + q2) #x = q1 #indices = q2>0 #x[indices] = (q1*(1 + q2))[indices] return (x, y)
def train(self, X, Y, num_classes=None): # "fit" data self._data = X self._labels = Y if num_classes == None: self._num_classes = int(af.max(Y) + 1) else: self._num_classes = int(num_classes)
def time_evolution(): for time_index, t0 in enumerate(time_array): print('Computing For Time =', t0) n_nls = nls.compute_moments('density') p1_bulk_nls = nls.compute_moments('mom_p1_bulk') / n_nls p2_bulk_nls = nls.compute_moments('mom_p2_bulk') / n_nls p3_bulk_nls = nls.compute_moments('mom_p3_bulk') / n_nls E_nls = nls.compute_moments('energy') T_nls = (nls.compute_moments('energy') - n_nls * p1_bulk_nls**2 - n_nls * p2_bulk_nls**2 - n_nls * p3_bulk_nls**2) / n_nls rho_data_nls[time_index] = af.max(n_nls) p1b_data_nls[time_index] = af.max(p1_bulk_nls) p2b_data_nls[time_index] = af.max(p2_bulk_nls) p3b_data_nls[time_index] = af.max(p3_bulk_nls) temp_data_nls[time_index] = af.max(T_nls) n_ls = ls.compute_moments('density') p1_bulk_ls = ls.compute_moments('mom_p1_bulk') / n_ls p2_bulk_ls = ls.compute_moments('mom_p2_bulk') / n_ls p3_bulk_ls = ls.compute_moments('mom_p3_bulk') / n_ls T_ls = (ls.compute_moments('energy') - n_ls * p1_bulk_ls**2 - n_ls * p2_bulk_ls**2 - n_ls * p3_bulk_ls**2) / n_ls rho_data_ls[time_index] = af.max(n_ls) p1b_data_ls[time_index] = af.max(p1_bulk_ls) p2b_data_ls[time_index] = af.max(p2_bulk_ls) p3b_data_ls[time_index] = af.max(p3_bulk_ls) temp_data_ls[time_index] = af.max(T_ls) nls.strang_timestep(dt) ls.RK2_timestep(dt)
def max(self, axis: tp.Optional[int] = None): """ Return the maximum along a given axis. """ new_array = af.max(self._af_array, dim=axis) if isinstance(new_array, af.Array): return ndarray(new_array) else: return new_array
def pool(image, w, s): #TODO: Remove assumption of image.dims()[3] == 1 d0, d1, d2 = image.dims() #TODO: remove reorder and moddims call image = af.moddims(af.reorder(image, 2, 0, 1), 1, d2, d0, d1) d0, d1, d2, d3 = image.dims() h_o = (d2 - w)/s + 1 w_o = (d3 - w)/s + 1 tiles = af.unwrap(af.reorder(image, 2, 3, 1, 0), w, w, s, s) return af.reorder(af.reorder(af.moddims(af.max(tiles, 0), d0, h_o, w_o, d1), 0, 3, 1, 2), 2, 3, 1, 0)
def test_lax_friedrichs_flux(): ''' A test function to test the lax_friedrichs_flux function in wave_equation module. ''' threshold = 1e-14 params.c = 1 f_i = wave_equation.lax_friedrichs_flux(params.u[:, :, 0]) analytical_lax_friedrichs_flux = params.u[-1, :, 0] assert af.max(af.abs(analytical_lax_friedrichs_flux - f_i)) < threshold
def test_gauss_weights(): ''' Test to check the gaussian weights calculated. ''' threshold = 2e-8 analytical_gauss_weights = af.Array([0.23692688505618908, 0.47862867049936647,\ 0.5688888888888889, 0.47862867049936647, \ 0.23692688505618908 ] ) calculated_gauss_weights = lagrange.gaussian_weights(5) assert af.max(af.abs(analytical_gauss_weights - calculated_gauss_weights))\ <= threshold
def time_evolution(): for time_index, t0 in enumerate(time_array): print('For Time =', t0) print('MIN(f) =', af.min(nls.f[3:-3, 3:-3])) print('MAX(f) =', af.max(nls.f[3:-3, 3:-3])) print('SUM(f) =', af.sum(nls.f[3:-3, 3:-3])) print() nls.strang_timestep(dt) n_nls = nls.compute_moments('density') h5f = h5py.File('dump/%04d' % (time_index + 1) + '.h5', 'w') h5f.create_dataset('n', data=n_nls) h5f.close()
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 test_periodic(): obj = test('periodic', 'periodic') obj.f[obj.N_ghost:-obj.N_ghost,obj.N_ghost:-obj.N_ghost] = \ af.sin(2 * np.pi * obj.q1_center + 4 * np.pi * obj.q2_center)[obj.N_ghost: -obj.N_ghost, obj.N_ghost: -obj.N_ghost ] apply_bcs_f(obj) expected = af.sin(2 * np.pi * obj.q1_center + 4 * np.pi * obj.q2_center) assert (af.max( af.abs(obj.f - expected)[obj.N_ghost:-obj.N_ghost, obj.N_ghost:-obj.N_ghost]) < 5e-14)
def af_assert(left, right, eps=1E-6): if (af.max(af.abs(left -right)) > eps): raise ValueError("Arrays not within dictated precision") return
def simple_algorithm(verbose = False): display_func = _util.display_func(verbose) print_func = _util.print_func(verbose) a = af.randu(3, 3) print_func(af.sum(a), af.product(a), af.min(a), af.max(a), af.count(a), af.any_true(a), af.all_true(a)) display_func(af.sum(a, 0)) display_func(af.sum(a, 1)) display_func(af.product(a, 0)) display_func(af.product(a, 1)) display_func(af.min(a, 0)) display_func(af.min(a, 1)) display_func(af.max(a, 0)) display_func(af.max(a, 1)) display_func(af.count(a, 0)) display_func(af.count(a, 1)) display_func(af.any_true(a, 0)) display_func(af.any_true(a, 1)) display_func(af.all_true(a, 0)) display_func(af.all_true(a, 1)) display_func(af.accum(a, 0)) display_func(af.accum(a, 1)) display_func(af.sort(a, is_ascending=True)) display_func(af.sort(a, is_ascending=False)) b = (a > 0.1) * a c = (a > 0.4) * a d = b / c print_func(af.sum(d)); print_func(af.sum(d, nan_val=0.0)); display_func(af.sum(d, dim=0, nan_val=0.0)); val,idx = af.sort_index(a, is_ascending=True) display_func(val) display_func(idx) val,idx = af.sort_index(a, is_ascending=False) display_func(val) display_func(idx) b = af.randu(3,3) keys,vals = af.sort_by_key(a, b, is_ascending=True) display_func(keys) display_func(vals) keys,vals = af.sort_by_key(a, b, is_ascending=False) display_func(keys) display_func(vals) c = af.randu(5,1) d = af.randu(5,1) cc = af.set_unique(c, is_sorted=False) dd = af.set_unique(af.sort(d), is_sorted=True) display_func(cc) display_func(dd) display_func(af.set_union(cc, dd, is_unique=True)) display_func(af.set_union(cc, dd, is_unique=False)) display_func(af.set_intersect(cc, cc, is_unique=True)) display_func(af.set_intersect(cc, cc, is_unique=False))
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)) print("\n---- Get minimum with index\n") (min_val, min_idx) = af.imin(A, 0) af.display(min_val) af.display(min_idx)
def max(self, s, axis): return arrayfire.max(s, axis)
def _relu(x, eps=1e-5): return af.max(x)
def normalize(a): mx = af.max(a) mn = af.min(a) return (a - mn)/(mx - mn)
#!/usr/bin/python import arrayfire as af a = af.randu(3, 3) print(af.sum(a), af.product(a), af.min(a), af.max(a), af.count(a), af.any_true(a), af.all_true(a)) af.print_array(af.sum(a, 0)) af.print_array(af.sum(a, 1)) af.print_array(af.product(a, 0)) af.print_array(af.product(a, 1)) af.print_array(af.min(a, 0)) af.print_array(af.min(a, 1)) af.print_array(af.max(a, 0)) af.print_array(af.max(a, 1)) af.print_array(af.count(a, 0)) af.print_array(af.count(a, 1)) af.print_array(af.any_true(a, 0)) af.print_array(af.any_true(a, 1)) af.print_array(af.all_true(a, 0)) af.print_array(af.all_true(a, 1)) af.print_array(af.accum(a, 0)) af.print_array(af.accum(a, 1))