def __init__(self, shape, pixel_size, wavelength, na, RI_measure=1.0, **kwargs): """ Initialization of the class RI_measure: refractive index on the detection side (example: oil immersion objectives) """ super().__init__(shape, pixel_size, na, **kwargs) fxlin = genGrid(self.shape[1], 1.0 / self.pixel_size / self.shape[1], flag_shift=True) fylin = genGrid(self.shape[0], 1.0 / self.pixel_size / self.shape[0], flag_shift=True) fxlin = af.tile(fxlin.T, self.shape[0], 1) fylin = af.tile(fylin, 1, self.shape[1]) self.pupil_support = genPupil(self.shape, self.pixel_size, self.na, wavelength) self.prop_kernel_phase = 1.0j * 2.0 * np.pi * self.pupil_support * ( (RI_measure / wavelength)**2 - fxlin * af.conjg(fxlin) - fylin * af.conjg(fylin))**0.5
def C_q(q1, q2, p1, p2, p3, params): """Return the terms C_q1, C_q2.""" import arrayfire as af return (af.tile(p2**2, 1, q1.shape[1], q1.shape[2]) / af.tile(q1, p1.shape[0]), -af.tile(p1 * p2, 1, q1.shape[1], q1.shape[2]) / af.tile(q1, p1.shape[0]))
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 __init__(self): self.q1_start = np.random.randint(0, 5) self.q2_start = np.random.randint(0, 5) self.q1_end = np.random.randint(5, 10) self.q2_end = np.random.randint(5, 10) self.N_q1 = np.random.randint(16, 32) self.N_q2 = np.random.randint(16, 32) self.dq1 = (self.q1_end - self.q1_start) / self.N_q1 self.dq2 = (self.q2_end - self.q2_start) / self.N_q2 N_g = self.N_ghost = np.random.randint(1, 5) self.q1 = self.q1_start \ * (0.5 + np.arange(-self.N_ghost, self.N_q1 + self.N_ghost ) ) * self.dq1 self.q2 = self.q2_start \ * (0.5 + np.arange(-self.N_ghost, self.N_q2 + self.N_ghost ) ) * self.dq2 self.q2, self.q1 = np.meshgrid(self.q2, self.q1) self.q1, self.q2 = af.to_array(self.q1), af.to_array(self.q2) self.q1 = af.reorder(self.q1, 2, 0, 1) self.q2 = af.reorder(self.q2, 2, 0, 1) self.q1 = af.tile(self.q1, 6) self.q2 = af.tile(self.q2, 6) self._da_fields = PETSc.DMDA().create([self.N_q1, self.N_q2], dof=6, stencil_width=self.N_ghost, boundary_type=('periodic', 'periodic'), stencil_type=1, ) self._glob_fields = self._da_fields.createGlobalVec() self._local_fields = self._da_fields.createLocalVec() self._glob_fields_array = self._glob_fields.getArray() self._local_fields_array = self._local_fields.getArray() self.cell_centered_EM_fields = af.constant(0, 6, self.q1.shape[1], self.q1.shape[2], dtype=af.Dtype.f64 ) self.cell_centered_EM_fields[:, N_g:-N_g, N_g:-N_g] = \ af.sin(2 * np.pi * self.q1 + 4 * np.pi * self.q2)[:, N_g:-N_g,N_g:-N_g] self.performance_test_flag = False
def __init__(self): self.physical_system = type('obj', (object, ), {'params': type('obj', (object, ), {'charge_electron': -1}) }) self.N_q1 = 32 self.N_q2 = 64 self.single_mode_evolution = False self.N_p1 = 2 self.N_p2 = 3 self.N_p3 = 4 self.k_q1 = 2 * np.pi * fftfreq(self.N_q1, 1 / self.N_q1) self.k_q2 = 2 * np.pi * fftfreq(self.N_q2, 1 / self.N_q2) self.k_q2, self.k_q1 = np.meshgrid(self.k_q2, self.k_q1) self.k_q2, self.k_q1 = af.to_array(self.k_q2), af.to_array(self.k_q1) self.q1 = af.to_array((0.5 + np.arange(self.N_q1)) * (1 / self.N_q1)) self.q2 = af.to_array((0.5 + np.arange(self.N_q2)) * (1 / self.N_q2)) self.q1 = af.tile(self.q1, 1, self.N_q2) self.q2 = af.tile(af.reorder(self.q2), self.N_q1, 1)
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 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 _calculate_p_back(self): p1_center = self.p1_start + (0.5 + np.arange( -self.N_ghost_p, self.N_p1 + self.N_ghost_p)) * self.dp1 p2_center = self.p2_start + (0.5 + np.arange( -self.N_ghost_p, self.N_p2 + self.N_ghost_p)) * self.dp2 p3_back = self.p3_start + np.arange( -self.N_ghost_p, self.N_p3 + self.N_ghost_p) * self.dp3 p2_back, p1_back, p3_back = np.meshgrid(p2_center, p1_center, p3_center) # Flattening the arrays: p1_back = af.flat(af.to_array(p1_back)) p2_back = af.flat(af.to_array(p2_back)) p3_back = af.flat(af.to_array(p3_back)) if (self.N_species > 1): p1_back = af.tile(p1_back, 1, self.N_species) p2_back = af.tile(p2_back, 1, self.N_species) p3_back = af.tile(p3_back, 1, self.N_species) af.eval(p1_back, p2_back, p3_back) return (p1_back, p2_back, p3_back)
def _calculate_p_center(self): """ Initializes the cannonical variables p1, p2 and p3 using a centered formulation. The size, and resolution are the same as declared under domain of the physical system object. """ p1_center = self.p1_start + (0.5 + np.arange( -self.N_ghost_p, self.N_p1 + self.N_ghost_p)) * self.dp1 p2_center = self.p2_start + (0.5 + np.arange( -self.N_ghost_p, self.N_p2 + self.N_ghost_p)) * self.dp2 p3_center = self.p3_start + (0.5 + np.arange( -self.N_ghost_p, self.N_p3 + self.N_ghost_p)) * self.dp3 p2_center, p1_center, p3_center = np.meshgrid(p2_center, p1_center, p3_center) # Flattening the arrays: p1_center = af.flat(af.to_array(p1_center)) p2_center = af.flat(af.to_array(p2_center)) p3_center = af.flat(af.to_array(p3_center)) if (self.N_species > 1): p1_center = af.tile(p1_center, 1, self.N_species) p2_center = af.tile(p2_center, 1, self.N_species) p3_center = af.tile(p3_center, 1, self.N_species) af.eval(p1_center, p2_center, p3_center) return (p1_center, p2_center, p3_center)
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 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 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 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 _genFrequencyGrid(self): fxlin = genGrid(self.shape[1], 1.0 / self.pixel_size / self.shape[1], flag_shift=True) fylin = genGrid(self.shape[0], 1.0 / self.pixel_size / self.shape[0], flag_shift=True) fxlin = af.tile(fxlin.T, self.shape[0], 1) fylin = af.tile(fylin, 1, self.shape[1]) return fxlin, fylin
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 surface_term(u_n): ''' Calculates the surface term, :math:`L_p(1) f_i - L_p(-1) f_{i - 1}` using the lax_friedrichs_flux function and lagrange_basis_value from params module. Parameters ---------- u_n : arrayfire.Array [N_LGL N_Elements M 1] Amplitude of the wave at the mapped LGL nodes of each element. This code will work for multiple :math:`M` ``u_n`` Returns ------- surface_term : arrayfire.Array [N_LGL N_Elements M 1] The surface term represented in the form of an array, :math:`L_p (1) f_i - L_p (-1) f_{i - 1}`, where p varies from zero to :math:`N_{LGL}` and i from zero to :math:`N_{Elements}`. p varies along the rows and i along columns. **See:** `PDF`_ describing the algorithm to obtain the surface term. .. _PDF: https://goo.gl/Nhhgzx ''' shape_u_n = utils.shape(u_n) L_p_minus1 = af.tile(params.lagrange_basis_value[:, 0], d0=1, d1=1, d2=shape_u_n[2]) L_p_1 = af.tile(params.lagrange_basis_value[:, -1], d0=1, d1=1, d2=shape_u_n[2]) #[NOTE]: Uncomment to use lax friedrichs flux #f_i = lax_friedrichs_flux(u_n) #[NOTE]: Uncomment to use upwind flux for uncoupled advection equations f_i = upwind_flux(u_n) #[NOTE]: Uncomment to use upwind flux for Maxwell's equations #f_i = upwind_flux_maxwell_eq(u_n) f_iminus1 = af.shift(f_i, 0, 1) surface_term = utils.matmul_3D(L_p_1, f_i) \ - utils.matmul_3D(L_p_minus1, f_iminus1) return surface_term
def genPupil(shape, pixel_size, NA, wavelength): assert len(shape) == 2, "pupil should be two dimensional!" fxlin = genGrid(shape[1], 1 / pixel_size / shape[1], flag_shift=True) fylin = genGrid(shape[0], 1 / pixel_size / shape[0], flag_shift=True) fxlin = af.tile(fxlin.T, shape[0], 1) fylin = af.tile(fylin, 1, shape[1]) pupil_radius = NA / wavelength pupil = (fxlin**2 + fylin**2 <= pupil_radius** 2).as_type(af_complex_datatype) return pupil
def fft_poisson(rho, dx, dy=None): """ FFT solver which returns the value of electric field. This will only work when the system being solved for has periodic boundary conditions. Parameters: ----------- rho : The 1D/2D density array obtained from calculate_density() is passed to this function. dx : Step size in the x-grid dy : Step size in the y-grid.Set to None by default to avoid conflict with the 1D case. Output: ------- E_x, E_y : Depending on the dimensionality of the system considered, either both E_x, and E_y are returned or E_x is returned. """ k_x = af.to_array(fftfreq(rho.shape[1], dx)) k_x = af.Array.as_type(k_x, af.Dtype.c64) k_y = af.to_array(fftfreq(rho.shape[0], dy)) k_x = af.tile(af.reorder(k_x), rho.shape[0], 1) k_y = af.tile(k_y, 1, rho.shape[1]) k_y = af.Array.as_type(k_y, af.Dtype.c64) rho = np.array(rho) rho_hat = fft2(rho) rho_hat = af.to_array(rho_hat) potential_hat = af.constant(0, rho.shape[0], rho.shape[1], dtype=af.Dtype.c64) potential_hat = (1 / (4 * np.pi**2 * (k_x * k_x + k_y * k_y))) * rho_hat potential_hat[0, 0] = 0 potential_hat = np.array(potential_hat) E_x_hat = -1j * 2 * np.pi * np.array(k_x) * potential_hat E_y_hat = -1j * 2 * np.pi * np.array(k_y) * potential_hat E_x = (ifft2(E_x_hat)).real E_y = (ifft2(E_y_hat)).real E_x = af.to_array(E_x) E_y = af.to_array(E_y) af.eval(E_x, E_y) return (E_x, E_y)
def f_MB(config, f, vel_x): mass_particle = config.mass_particle boltzmann_constant = config.boltzmann_constant n = af.tile(calculate_density(f, vel_x), 1, N_velocity) T = af.tile(calculate_temperature(f, vel_x), 1, N_velocity) v_bulk = af.tile(calculate_vbulk(f, vel_x), 1, N_velocity) f_MB = n*af.sqrt(mass_particle/(2*np.pi*boltzmann_constant*T))*\ af.exp(-mass_particle*(vel_x-v_bulk)**2/(2*boltzmann_constant*T)) af.eval(f_MB) return(f_MB)
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
def tile(A, reps): try: tup = tuple(reps) except TypeError: tup = (reps,) if(len(tup) > 4): raise NotImplementedError('Only up to 4 dimensions are supported') d = len(tup) shape = list(A.shape) n = max(A.size, 1) if (d < A.ndim): tup = (1,)*(A.ndim-d) + tup # Calculate final shape while len(shape) < len(tup): shape.insert(0,1) shape = tuple(numpy.array(shape) * numpy.array(tup)) # Prepend ones to simplify calling if (d < 4): tup = (1,)*(4-d) + tup tup = pu.c2f(tup) s = arrayfire.tile(A.d_array, int(tup[0]), int(tup[1]), int(tup[2]), int(tup[3])) return afnumpy.ndarray(shape, dtype=pu.typemap(s.dtype()), af_array=s)
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_u(u, gv): ''' Calculates the coefficients of the Lagrange interpolation using the value of u at the mapped LGL points in the domain. The interpolation using the Lagrange basis polynomials is given by :math:`L_i(\\xi) u_i(\\xi)` Where L_i are the Lagrange basis polynomials and u_i is the value of u at the LGL points. Parameters ---------- u : arrayfire.Array [N_LGL N_Elements 1 1] The value of u at the mapped LGL points. Returns ------- lagrange_interpolated_coeffs : arrayfire.Array[1 N_LGL N_Elements 1] The coefficients of the polynomials obtained by Lagrange interpolation. Each polynomial is of order N_LGL - 1. ''' lagrange_coeffs_tile = af.tile(gv.lagrange_coeffs, 1, 1,\ params.N_Elements) reordered_u = af.reorder(u, 0, 2, 1) lagrange_interpolated_coeffs = af.sum(af.broadcast(utils.multiply,\ reordered_u, lagrange_coeffs_tile), 0) return lagrange_interpolated_coeffs
def calc_arrayfire(A, b, x0, maxiter=10): x = af.constant(0, b.dims()[0], dtype=af.Dtype.f32) r = b - af.matmul(A, x) p = r for i in range(maxiter): Ap = af.matmul(A, p) alpha_num = af.dot(r, r) alpha_den = af.dot(p, Ap) alpha = alpha_num / alpha_den r -= af.tile(alpha, Ap.dims()[0]) * Ap x += af.tile(alpha, Ap.dims()[0]) * p beta_num = af.dot(r, r) beta = beta_num / alpha_num p = r + af.tile(beta, p.dims()[0]) * p res = x0 - x return x, af.dot(res, res)
def calculate_x(config): """ Returns the 2D array of x which is used in the computations of the Cheng-Knorr code. Parameters: ----------- config : Object config which is obtained by set() is passed to this file Output: ------- x : Array holding the values of x tiled along axis 1 """ N_x = config.N_x N_vel_x = config.N_vel_x N_ghost_x = config.N_ghost_x left_boundary = config.left_boundary right_boundary = config.right_boundary x = np.linspace(left_boundary, right_boundary, N_x) dx = x[1] - x[0] x_ghost_left = np.linspace(-(N_ghost_x)*dx + left_boundary, left_boundary - dx, N_ghost_x) x_ghost_right = np.linspace(right_boundary + dx, right_boundary + N_ghost_x*dx , N_ghost_x) x = np.concatenate([x_ghost_left, x, x_ghost_right]) x = af.Array.as_type(af.to_array(x), af.Dtype.f64) x = af.tile(x, 1, N_vel_x) af.eval(x) return x
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 genZernikeAberration(shape, pixel_size, NA, wavelength, z_coeff=[1], z_index_list=[0]): assert len(z_coeff) == len( z_index_list ), "number of coefficients does not match with number of zernike indices!" pupil = genPupil(shape, pixel_size, NA, wavelength) fxlin = genGrid(shape[1], 1 / pixel_size / shape[1], flag_shift=True) fylin = genGrid(shape[0], 1 / pixel_size / shape[0], flag_shift=True) fxlin = af.tile(fxlin.T, shape[0], 1) fylin = af.tile(fylin, 1, shape[1]) rho, theta = cart2Pol(fxlin, fylin) rho[:, :] /= NA / wavelength def zernikePolynomial(z_index): n = int(np.ceil((-3.0 + np.sqrt(9 + 8 * z_index)) / 2.0)) m = 2 * z_index - n * (n + 2) normalization_coeff = np.sqrt(2 * (n + 1)) if abs(m) > 0 else np.sqrt(n + 1) azimuthal_function = af.sin(abs(m) * theta) if m < 0 else af.cos( abs(m) * theta) zernike_poly = af.constant(0.0, shape[0], shape[1], dtype=af_complex_datatype) for k in range((n - abs(m)) // 2 + 1): zernike_poly[:, :] += ((-1)**k * factorial(n-k))/ \ (factorial(k)*factorial(0.5*(n+m)-k)*factorial(0.5*(n-m)-k))\ * rho**(n-2*k) return normalization_coeff * zernike_poly * azimuthal_function for z_coeff_index, z_index in enumerate(z_index_list): zernike_poly = zernikePolynomial(z_index) if z_coeff_index == 0: zernike_aberration = z_coeff.ravel()[z_coeff_index] * zernike_poly else: zernike_aberration[:, :] += z_coeff.ravel( )[z_coeff_index] * zernike_poly return zernike_aberration * pupil
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 calc_arrayfire(A, b, x0, maxiter=10): x = af.constant(0, b.dims()[0], dtype=af.Dtype.f32) r = b - af.matmul(A, x) p = r for i in range(maxiter): Ap = af.matmul(A, p) alpha_num = af.dot(r, r) alpha_den = af.dot(p, Ap) alpha = alpha_num/alpha_den r -= af.tile(alpha, Ap.dims()[0]) * Ap x += af.tile(alpha, Ap.dims()[0]) * p beta_num = af.dot(r, r) beta = beta_num/alpha_num p = r + af.tile(beta, p.dims()[0]) * p af.eval(x) res = x0 - x return x, af.dot(res, res)
def templateMatchingDemo(console): root_path = os.path.dirname(os.path.abspath(__file__)) file_path = root_path if console: file_path += "/../../assets/examples/images/square.png" else: file_path += "/../../assets/examples/images/man.jpg" img_color = af.load_image(file_path, True) # Convert the image from RGB to gray-scale img = af.color_space(img_color, af.CSPACE.GRAY, af.CSPACE.RGB) iDims = img.dims() print("Input image dimensions: ", iDims) # Extract a patch from the input image patch_size = 100 tmp_img = img[100:100 + patch_size, 100:100 + patch_size] result = af.match_template(img, tmp_img) # Default disparity metric is # Sum of Absolute differences (SAD) # Currently supported metrics are # AF_SAD, AF_ZSAD, AF_LSAD, AF_SSD, # AF_ZSSD, AF_LSSD disp_img = img / 255.0 disp_tmp = tmp_img / 255.0 disp_res = normalize(result) minval, minloc = af.imin(disp_res) print("Location(linear index) of minimum disparity value = {}".format( minloc)) if not console: marked_res = af.tile(disp_img, 1, 1, 3) marked_res = draw_rectangle(marked_res, minloc%iDims[0], minloc/iDims[0],\ patch_size, patch_size) print( "Note: Based on the disparity metric option provided to matchTemplate function" ) print( "either minimum or maximum disparity location is the starting corner" ) print( "of our best matching patch to template image in the search image") wnd = af.Window(512, 512, "Template Matching Demo") while not wnd.close(): wnd.set_colormap(af.COLORMAP.DEFAULT) wnd.grid(2, 2) wnd[0, 0].image(disp_img, "Search Image") wnd[0, 1].image(disp_tmp, "Template Patch") wnd[1, 0].image(marked_res, "Best Match") wnd.set_colormap(af.COLORMAP.HEAT) wnd[1, 1].image(disp_res, "Disparity Values") wnd.show()
af.display(af.identity(3, 3, 1, 2, af.b8)) af.display(af.identity(3, 3, dtype=af.c32)) a = af.randu(3, 4) b = af.diag(a, extract=True) c = af.diag(a, 1, extract=True) af.display(a) af.display(b) af.display(c) af.display(af.diag(b, extract = False)) af.display(af.diag(c, 1, extract = False)) af.display(af.tile(a, 2, 2)) af.display(af.reorder(a, 1, 0)) af.display(af.shift(a, -1, 1)) af.display(af.moddims(a, 6, 2)) af.display(af.flat(a)) af.display(af.flip(a, 0)) af.display(af.flip(a, 1)) af.display(af.lower(a, False)) af.display(af.lower(a, True))
af.print_array(af.identity(3, 3, 1, 2, af.b8)) af.print_array(af.identity(3, 3, dtype=af.c32)) a = af.randu(3, 4) b = af.diag(a, extract=True) c = af.diag(a, 1, extract=True) af.print_array(a) af.print_array(b) af.print_array(c) af.print_array(af.diag(b, extract = False)) af.print_array(af.diag(c, 1, extract = False)) af.print_array(af.tile(a, 2, 2)) af.print_array(af.reorder(a, 1, 0)) af.print_array(af.shift(a, -1, 1)) af.print_array(af.moddims(a, 6, 2)) af.print_array(af.flat(a)) af.print_array(af.flip(a, 0)) af.print_array(af.flip(a, 1)) af.print_array(af.lower(a, False)) af.print_array(af.lower(a, True))
simple_win = af.Window(512, 512, "Conway's Game of Life - Current State") pretty_win = af.Window(512, 512, "Conway's Game of Life - Current State with visualization") simple_win.set_pos(25, 15) pretty_win.set_pos(600, 25) frame_count = 0 # Copy kernel that specifies neighborhood conditions kernel = af.Array(h_kernel, dims=(3,3)) # Generate the initial state with 0s and 1s state = (af.randu(game_h, game_w) > 0.4).as_type(af.Dtype.f32) # tile 3 times to display color display = af.tile(state, 1, 1, 3, 1) while (not simple_win.close()) and (not pretty_win.close()): delay = time() if (not simple_win.close()): simple_win.image(state) if (not pretty_win.close()): pretty_win.image(display) frame_count += 1 if (frame_count % reset == 0): state = (af.randu(game_h, game_w) > 0.4).as_type(af.Dtype.f32) neighborhood = af.convolve(state, kernel) # state == 1 && neighborhood < 2 --> state = 0 # state == 1 && neighborhood > 3 --> state = 0 # state == 0 && neighborhood == 3 --> state = 1