def mandelbrot(data, it, maxval):
    C = data
    Z = data
    mag = af.constant(0, *C.dims())

    for ii in range(1, 1 + it):
        # Doing the calculation
        Z = Z * Z + C

        # Get indices where abs(Z) crosses maxval
        cond = ((af.abs(Z) > maxval)).as_type(af.Dtype.f32)
        mag = af.maxof(mag, cond * ii)

        C = C * (1 - cond)
        Z = Z * (1 - cond)

        af.eval(C)
        af.eval(Z)

    return mag / maxval
def time_evolution(gv):
    '''
    '''
    # Creating a folder to store hdf5 files. If it doesn't exist.
    results_directory = 'results/2d_hdf5_%02d' % (int(params.N_LGL))
    if not os.path.exists(results_directory):
        os.makedirs(results_directory)

    u = gv.u_e_ij
    delta_t = gv.delta_t_2d
    time = gv.time_2d
    u_init = gv.u_e_ij

    A_inverse = af.np_to_af_array(np.linalg.inv(np.array(A_matrix(gv))))

    for i in trange(time.shape[0]):
        L1_norm = af.mean(af.abs(u_init - u))

        if (L1_norm >= 100):
            break
        if (i % 10) == 0:
            h5file = h5py.File(
                'results/2d_hdf5_%02d/dump_timestep_%06d' %
                (int(params.N_LGL), int(i)) + '.hdf5', 'w')
            dset = h5file.create_dataset('u_i', data=u, dtype='d')

            dset[:, :] = u[:, :]

        u += +RK4_timestepping(A_inverse, u, delta_t, gv)

        #Implementing second order time-stepping.
        #u_n_plus_half =  u + af.matmul(A_inverse, b_vector(u))\
        #                      * delta_t / 2

        #u            +=  af.matmul(A_inverse, b_vector(u_n_plus_half))\
        #                  * delta_t

    return L1_norm
Exemple #3
0
def time_evolution(gv):
    '''
    '''
    # Creating a folder to store hdf5 files. If it doesn't exist.
    results_directory = 'results/xi_eta_2d_hdf5_%02d' % (int(params.N_LGL))
    if not os.path.exists(results_directory):
        os.makedirs(results_directory)

    A_inverse = af.np_to_af_array(
        np.linalg.inv(np.array(A_matrix_xi_eta(params.N_LGL, gv))))
    xi_LGL = lagrange.LGL_points(params.N_LGL)
    xi_i = af.flat(af.transpose(af.tile(xi_LGL, 1, params.N_LGL)))
    eta_j = af.tile(xi_LGL, params.N_LGL)

    u_init_2d = gv.u_e_ij
    delta_t = gv.delta_t_2d
    time = gv.time
    u = u_init_2d
    time = gv.time_2d

    for i in trange(0, time.shape[0]):
        L1_norm = af.mean(af.abs(u_init_2d - u))

        if (L1_norm >= 100):
            print(L1_norm)
            break
        if (i % 10) == 0:
            h5file = h5py.File(
                'results/xi_eta_2d_hdf5_%02d/dump_timestep_%06d' %
                (int(params.N_LGL), int(i)) + '.hdf5', 'w')
            dset = h5file.create_dataset('u_i', data=u, dtype='d')

            dset[:, :] = u[:, :]

        u += RK4_timestepping(A_inverse, u, delta_t, gv)

    return L1_norm
Exemple #4
0
def test():
    print("\nTesting benchmark functions...")
    A, b, x0 = setup_input(50)  # dense A
    Asp = to_sparse(A)
    x1, _ = calc_arrayfire(A, b, x0)
    x2, _ = calc_arrayfire(Asp, b, x0)
    if af.sum(af.abs(x1 - x2) / x2 > 1e-6):
        raise ValueError("arrayfire test failed")
    if np:
        An = to_numpy(A)
        bn = to_numpy(b)
        x0n = to_numpy(x0)
        x3, _ = calc_numpy(An, bn, x0n)
        if not np.allclose(x3, x1.to_list()):
            raise ValueError("numpy test failed")
    if sp:
        Asc = to_scipy_sparse(Asp)
        x4, _ = calc_scipy_sparse(Asc, bn, x0n)
        if not np.allclose(x4, x1.to_list()):
            raise ValueError("scipy.sparse test failed")
        x5, _ = calc_scipy_sparse_linalg_cg(Asc, bn, x0n)
        if not np.allclose(x5, x1.to_list()):
            raise ValueError("scipy.sparse.linalg.cg test failed")
    print("    all tests passed...")
Exemple #5
0
def check_error(params):
    error = np.zeros(N.size)

    for i in range(N.size):
        domain.N_p1 = int(N[i])
        # Defining the physical system to be solved:
        system = physical_system(domain, boundary_conditions, params,
                                 initialize, advection_terms,
                                 collision_operator.BGK, moments)

        # Declaring a linear system object which will evolve the defined physical system:
        nls = nonlinear_solver(system)

        # Time parameters:
        dt = 0.01 * 32 / nls.N_p1
        t_final = 0.2

        time_array = np.arange(dt, t_final + dt, dt)

        (A_p1, A_p2,
         A_p3) = af.broadcast(nls._A_p, nls.f, 0, nls.q1_center, nls.q2_center,
                              nls.p1_center, nls.p2_center, nls.p3_center,
                              nls.fields_solver, nls.physical_system.params)

        f_analytic = af.broadcast(initialize.initialize_f, nls.q1_center,
                                  nls.q2_center,
                                  add(nls.p1_center, -A_p1 * t_final),
                                  add(nls.p2_center, -A_p2 * t_final),
                                  nls.p3_center, nls.physical_system.params)

        for time_index, t0 in enumerate(time_array):
            nls.strang_timestep(dt)

        error[i] = af.mean(af.abs(nls.f - f_analytic))

    return (error)
def test():
    print("\nTesting benchmark functions...")
    A, b, x0 = setup_input(n=50, sparsity=7)  # dense A
    Asp = to_sparse(A)
    x1, _ = calc_arrayfire(A, b, x0)
    x2, _ = calc_arrayfire(Asp, b, x0)
    if af.sum(af.abs(x1 - x2)/x2 > 1e-5):
        raise ValueError("arrayfire test failed")
    if np:
        An = to_numpy(A)
        bn = to_numpy(b)
        x0n = to_numpy(x0)
        x3, _ = calc_numpy(An, bn, x0n)
        if not np.allclose(x3, x1.to_list()):
            raise ValueError("numpy test failed")
    if sp:
        Asc = to_scipy_sparse(Asp)
        x4, _ = calc_scipy_sparse(Asc, bn, x0n)
        if not np.allclose(x4, x1.to_list()):
            raise ValueError("scipy.sparse test failed")
        x5, _ = calc_scipy_sparse_linalg_cg(Asc, bn, x0n)
        if not np.allclose(x5, x1.to_list()):
            raise ValueError("scipy.sparse.linalg.cg test failed")
    print("    all tests passed...")
af.display(c)

af.display(-a)
af.display(+a)
af.display(~a)
af.display(a)

af.display(af.cast(a, af.c32))
af.display(af.maxof(a,b))
af.display(af.minof(a,b))
af.display(af.rem(a,b))

a = af.randu(3,3) - 0.5
b = af.randu(3,3) - 0.5

af.display(af.abs(a))
af.display(af.arg(a))
af.display(af.sign(a))
af.display(af.round(a))
af.display(af.trunc(a))
af.display(af.floor(a))
af.display(af.ceil(a))
af.display(af.hypot(a, b))
af.display(af.sin(a))
af.display(af.cos(a))
af.display(af.tan(a))
af.display(af.asin(a))
af.display(af.acos(a))
af.display(af.atan(a))
af.display(af.atan2(a, b))
Exemple #8
0
def simple_arith(verbose = False):
    display_func = _util.display_func(verbose)
    print_func   = _util.print_func(verbose)

    a = af.randu(3,3,dtype=af.Dtype.u32)
    b = af.constant(4, 3, 3, dtype=af.Dtype.u32)
    display_func(a)
    display_func(b)

    c = a + b
    d = a
    d += b

    display_func(c)
    display_func(d)
    display_func(a + 2)
    display_func(3 + a)


    c = a - b
    d = a
    d -= b

    display_func(c)
    display_func(d)
    display_func(a - 2)
    display_func(3 - a)

    c = a * b
    d = a
    d *= b

    display_func(c * 2)
    display_func(3 * d)
    display_func(a * 2)
    display_func(3 * a)

    c = a / b
    d = a
    d /= b

    display_func(c / 2.0)
    display_func(3.0 / d)
    display_func(a / 2)
    display_func(3 / a)

    c = a % b
    d = a
    d %= b

    display_func(c % 2.0)
    display_func(3.0 % d)
    display_func(a % 2)
    display_func(3 % a)

    c = a ** b
    d = a
    d **= b

    display_func(c ** 2.0)
    display_func(3.0 ** d)
    display_func(a ** 2)
    display_func(3 ** a)

    display_func(a < b)
    display_func(a < 0.5)
    display_func(0.5 < a)

    display_func(a <= b)
    display_func(a <= 0.5)
    display_func(0.5 <= a)

    display_func(a > b)
    display_func(a > 0.5)
    display_func(0.5 > a)

    display_func(a >= b)
    display_func(a >= 0.5)
    display_func(0.5 >= a)

    display_func(a != b)
    display_func(a != 0.5)
    display_func(0.5 != a)

    display_func(a == b)
    display_func(a == 0.5)
    display_func(0.5 == a)

    display_func(a & b)
    display_func(a & 2)
    c = a
    c &= 2
    display_func(c)

    display_func(a | b)
    display_func(a | 2)
    c = a
    c |= 2
    display_func(c)

    display_func(a >> b)
    display_func(a >> 2)
    c = a
    c >>= 2
    display_func(c)

    display_func(a << b)
    display_func(a << 2)
    c = a
    c <<= 2
    display_func(c)

    display_func(-a)
    display_func(+a)
    display_func(~a)
    display_func(a)

    display_func(af.cast(a, af.Dtype.c32))
    display_func(af.maxof(a,b))
    display_func(af.minof(a,b))
    display_func(af.rem(a,b))

    a = af.randu(3,3) - 0.5
    b = af.randu(3,3) - 0.5

    display_func(af.abs(a))
    display_func(af.arg(a))
    display_func(af.sign(a))
    display_func(af.round(a))
    display_func(af.trunc(a))
    display_func(af.floor(a))
    display_func(af.ceil(a))
    display_func(af.hypot(a, b))
    display_func(af.sin(a))
    display_func(af.cos(a))
    display_func(af.tan(a))
    display_func(af.asin(a))
    display_func(af.acos(a))
    display_func(af.atan(a))
    display_func(af.atan2(a, b))

    c = af.cplx(a)
    d = af.cplx(a,b)
    display_func(c)
    display_func(d)
    display_func(af.real(d))
    display_func(af.imag(d))
    display_func(af.conjg(d))

    display_func(af.sinh(a))
    display_func(af.cosh(a))
    display_func(af.tanh(a))
    display_func(af.asinh(a))
    display_func(af.acosh(a))
    display_func(af.atanh(a))

    a = af.abs(a)
    b = af.abs(b)

    display_func(af.root(a, b))
    display_func(af.pow(a, b))
    display_func(af.pow2(a))
    display_func(af.exp(a))
    display_func(af.expm1(a))
    display_func(af.erf(a))
    display_func(af.erfc(a))
    display_func(af.log(a))
    display_func(af.log1p(a))
    display_func(af.log10(a))
    display_func(af.log2(a))
    display_func(af.sqrt(a))
    display_func(af.cbrt(a))

    a = af.round(5 * af.randu(3,3) - 1)
    b = af.round(5 * af.randu(3,3) - 1)

    display_func(af.factorial(a))
    display_func(af.tgamma(a))
    display_func(af.lgamma(a))
    display_func(af.iszero(a))
    display_func(af.isinf(a/b))
    display_func(af.isnan(a/a))

    a = af.randu(5, 1)
    b = af.randu(1, 5)
    c = af.broadcast(lambda x,y: x+y, a, b)
    display_func(a)
    display_func(b)
    display_func(c)

    @af.broadcast
    def test_add(aa, bb):
        return aa + bb

    display_func(test_add(a, b))
Exemple #9
0
def test_communicate_f():
    obj = test_distribution_function()
    communicate_f(obj)

    expected = af.sin(2 * np.pi * obj.q1 + 4 * np.pi * obj.q2)
    assert (af.mean(af.abs(obj.f - expected)) < 5e-14)
Exemple #10
0
    def _initialize(self, params):
        """
        Called when the solver object is declared. This function is
        used to initialize the distribution function, and the field
        quantities using the options as provided by the user. The
        quantities are then mapped to the fourier basis by taking FFTs.
        The independant modes are then evolved by using the linear
        solver.
        """
        # af.broadcast(function, *args) performs batched operations on
        # function(*args):
        f     = af.broadcast(self.physical_system.initial_conditions.\
                             initialize_f, self.q1_center, self.q2_center,
                             self.p1, self.p2, self.p3, params
                             )
        # Taking FFT:
        f_hat = af.fft2(f)

        # Since (k_q1, k_q2) = (0, 0) will give the background distribution:
        # The division by (self.N_q1 * self.N_q2) is performed since the FFT
        # at (0, 0) returns (amplitude * (self.N_q1 * self.N_q2))
        self.f_background = af.abs(f_hat[0, 0, :])/ (self.N_q1 * self.N_q2)

        # Calculating derivatives of the background distribution function:
        self._calculate_dfdp_background()
   
        # Scaling Appropriately:
        # Except the case of (0, 0) the FFT returns
        # (0.5 * amplitude * (self.N_q1 * self.N_q2)):
        f_hat = 2 * f_hat / (self.N_q1 * self.N_q2)

        if(self.single_mode_evolution == True):
            # Background
            f_hat[0, 0, :] = 0

            # Finding the indices of the perturbation introduced:
            i_q1_max = np.unravel_index(af.imax(af.abs(f_hat))[1], 
                                        (self.N_q1, self.N_q2, 
                                         self.N_p1 * self.N_p2 * self.N_p3
                                        ),order = 'F'
                                       )[0]

            i_q2_max = np.unravel_index(af.imax(af.abs(f_hat))[1], 
                                        (self.N_q1, self.N_q2, 
                                         self.N_p1 * self.N_p2 * self.N_p3
                                        ),order = 'F'
                                       )[1]

            # Taking sum to get a scalar value:
            params.k_q1 = af.sum(self.k_q1[i_q1_max, i_q2_max])
            params.k_q2 = af.sum(self.k_q2[i_q1_max, i_q2_max])

            self.f_background = np.array(self.f_background).\
                                reshape(self.N_p1, self.N_p2, self.N_p3)

            self.p1 = np.array(self.p1).\
                      reshape(self.N_p1, self.N_p2, self.N_p3)
            self.p2 = np.array(self.p2).\
                      reshape(self.N_p1, self.N_p2, self.N_p3)
            self.p3 = np.array(self.p3).\
                      reshape(self.N_p1, self.N_p2, self.N_p3)

            self._A_q1 = np.array(self._A_q1).\
                         reshape(self.N_p1, self.N_p2, self.N_p3)
            self._A_q2 = np.array(self._A_q2).\
                         reshape(self.N_p1, self.N_p2, self.N_p3)

            params.rho_background = self.compute_moments('density',
                                                         self.f_background
                                                        )
            
            params.p1_bulk_background = self.compute_moments('mom_p1_bulk',
                                                             self.f_background
                                                            ) / params.rho_background
            params.p2_bulk_background = self.compute_moments('mom_p2_bulk',
                                                             self.f_background
                                                            ) / params.rho_background
            params.p3_bulk_background = self.compute_moments('mom_p3_bulk',
                                                             self.f_background
                                                            ) / params.rho_background
            
            params.T_background = ((1 / params.p_dim) * \
                                   self.compute_moments('energy',
                                                        self.f_background
                                                       )
                                   - params.rho_background * 
                                     params.p1_bulk_background**2
                                   - params.rho_background * 
                                     params.p2_bulk_background**2
                                   - params.rho_background * 
                                     params.p3_bulk_background**2
                                  ) / params.rho_background

            self.dfdp1_background = np.array(self.dfdp1_background).\
                                    reshape(self.N_p1, self.N_p2, self.N_p3)
            self.dfdp2_background = np.array(self.dfdp2_background).\
                                    reshape(self.N_p1, self.N_p2, self.N_p3)
            self.dfdp3_background = np.array(self.dfdp3_background).\
                                    reshape(self.N_p1, self.N_p2, self.N_p3)

            # Unable to recover pert_real and pert_imag accurately from the input.
            # There seems to be some error in recovering these quantities which
            # is dependant upon the resolution. Using user-defined quantities instead
            delta_f_hat =   params.pert_real * self.f_background \
                          + params.pert_imag * self.f_background * 1j 

            self.Y = np.array([delta_f_hat])
            compute_electrostatic_fields(self)
            self.Y = np.array([delta_f_hat, 
                               self.delta_E1_hat, self.delta_E2_hat, self.delta_E3_hat,
                               self.delta_B1_hat, self.delta_B2_hat, self.delta_B3_hat
                              ]
                             )

        else:
            # Using a vector Y to evolve the system:
            self.Y = af.constant(0, self.N_q1, self.N_q2,
                                 self.N_p1 * self.N_p2 * self.N_p3,
                                 7, dtype = af.Dtype.c64
                                )

            # Assigning the 0th indice along axis 3 to the f_hat:
            self.Y[:, :, :, 0] = f_hat

            # Initializing the EM field quantities:
            self.E3_hat = af.constant(0, self.N_q1, self.N_q2,
                                      self.N_p1 * self.N_p2 * self.N_p3, 
                                      dtype = af.Dtype.c64
                                     )

            self.B1_hat = af.constant(0, self.N_q1, self.N_q2,
                                      self.N_p1 * self.N_p2 * self.N_p3,
                                      dtype = af.Dtype.c64
                                     )
            
            self.B2_hat = af.constant(0, self.N_q1, self.N_q2,
                                      self.N_p1 * self.N_p2 * self.N_p3,
                                      dtype = af.Dtype.c64
                                     ) 
            
            self.B3_hat = af.constant(0, self.N_q1, self.N_q2,
                                      self.N_p1 * self.N_p2 * self.N_p3,
                                      dtype = af.Dtype.c64
                                     )
            
            # Initializing EM fields using Poisson Equation:
            if(self.physical_system.params.fields_initialize == 'electrostatic' or
               self.physical_system.params.fields_initialize == 'fft'
              ):
                compute_electrostatic_fields(self)

            # If option is given as user-defined:
            elif(self.physical_system.params.fields_initialize == 'user-defined'):
                E1, E2, E3 = \
                    self.physical_system.initial_conditions.initialize_E(self.q1_center, self.q2_center, self.physical_system.params)
                
                B1, B2, B3 = \
                    self.physical_system.initial_conditions.initialize_B(self.q1_center, self.q2_center, self.physical_system.params)

                # Scaling Appropriately
                self.E1_hat = af.tile(2 * af.fft2(E1) / (self.N_q1 * self.N_q2), 1, 1, self.N_p1 * self.N_p2 * self.N_p3)
                self.E2_hat = af.tile(2 * af.fft2(E2) / (self.N_q1 * self.N_q2), 1, 1, self.N_p1 * self.N_p2 * self.N_p3)
                self.E3_hat = af.tile(2 * af.fft2(E3) / (self.N_q1 * self.N_q2), 1, 1, self.N_p1 * self.N_p2 * self.N_p3)
                self.B1_hat = af.tile(2 * af.fft2(B1) / (self.N_q1 * self.N_q2), 1, 1, self.N_p1 * self.N_p2 * self.N_p3)
                self.B2_hat = af.tile(2 * af.fft2(B2) / (self.N_q1 * self.N_q2), 1, 1, self.N_p1 * self.N_p2 * self.N_p3)
                self.B3_hat = af.tile(2 * af.fft2(B3) / (self.N_q1 * self.N_q2), 1, 1, self.N_p1 * self.N_p2 * self.N_p3)
                
            else:
                raise NotImplementedError('Method invalid/not-implemented')

            # Assigning other indices along axis 3 to be
            # the EM field quantities:
            self.Y[:, :, :, 1] = self.E1_hat
            self.Y[:, :, :, 2] = self.E2_hat
            self.Y[:, :, :, 3] = self.E3_hat
            self.Y[:, :, :, 4] = self.B1_hat
            self.Y[:, :, :, 5] = self.B2_hat
            self.Y[:, :, :, 6] = self.B3_hat

            af.eval(self.Y)

        return
def Umeda_b1_deposition( charge_electron, positions_x, positions_y, velocity_x, velocity_y,\
                            x_grid, y_grid, ghost_cells, length_domain_x, length_domain_y, dt  ):
    '''
    A modified Umeda's scheme was implemented to handle a pure one dimensional case.

    function Umeda_b1_deposition( charge, x, velocity_x,\
                                  x_grid, ghost_cells, length_domain_x, dt\
                                )
    -----------------------------------------------------------------------
    Input variables: charge, x, velocity_required_x, x_grid, ghost_cells, length_domain_x, dt

        charge: This is an array containing the charges deposited at the density grid nodes.

        positions_x: An one dimensional array of size equal to number of particles taken in the PIC code.
        It contains the positions of particles in x direction.
        
        positions_y:  An one dimensional array of size equal to number of particles taken in the PIC code.
        It contains the positions of particles in y direction.

        velocity_x: An one dimensional array of size equal to number of particles taken in the PIC code.
        It contains the velocities of particles in y direction.
        
        velocity_y: An one dimensional array of size equal to number of particles taken in the PIC code.
        It contains the velocities of particles in x direction.

        x_grid: This is an array denoting the position grid in x direction chosen in the PIC simulation
        
        y_grid: This is an array denoting the position grid in y direction chosen in the PIC simulation

        ghost_cells: This is the number of ghost cells used in the simulation domain.

        length_domain_x: This is the length of the domain in x direction

        dt: this is the dt/time step chosen in the simulation
    -----------------------------------------------------------------------
    returns: Jx_x_indices, Jx_y_indices, Jx_values_at_these_indices,\
           Jy_x_indices, Jy_y_indices, Jy_values_at_these_indices

        Jx_x_indices: This returns the x indices (columns) of the array where the respective currents stored in
        Jx_values_at_these_indices have to be deposited
      
        Jx_y_indices: This returns the y indices (rows) of the array where the respective currents stored in
        Jx_values_at_these_indices have to be deposited      

        Jx_values_at_these_indices: This is an array containing the currents to be deposited.
        
        Jy_x_indices, Jy_y_indices and Jy_values_at_these_indices are similar to Jx_x_indices, 
        Jx_y_indices and Jx_values_at_these_indices for Jy

    For further details on the scheme refer to Umeda's paper provided in the sagemath folder as the
    naming conventions used in the function use the papers naming convention.(x_1, x_2, x_r, F_x, )

    '''

    nx = (x_grid.elements() - 1 - 2 * ghost_cells)  # number of zones
    ny = (y_grid.elements() - 1 - 2 * ghost_cells)  # number of zones

    dx = length_domain_x / nx
    dy = length_domain_y / ny

    # Start location x_1, y_1 at t = n * dt
    # Start location x_2, y_2 at t = (n+1) * dt

    x_1 = (positions_x).as_type(af.Dtype.f64)
    x_2 = (positions_x + (velocity_x * dt)).as_type(af.Dtype.f64)

    y_1 = (positions_y).as_type(af.Dtype.f64)
    y_2 = (positions_y + (velocity_y * dt)).as_type(af.Dtype.f64)

    # Calculation i_1 and i_2, indices of left corners of cells containing the particles
    # at x_1 and x_2 respectively and j_1 and j_2: indices of bottoms of cells containing the particles
    # at y_1 and y_2 respectively

    i_1 = af.arith.floor(((af.abs(x_1 - af.sum(x_grid[0]))) / dx) -
                         ghost_cells)
    j_1 = af.arith.floor(((af.abs(y_1 - af.sum(y_grid[0]))) / dy) -
                         ghost_cells)

    i_2 = af.arith.floor(((af.abs(x_2 - af.sum(x_grid[0]))) / dx) -
                         ghost_cells)
    j_2 = af.arith.floor(((af.abs(y_2 - af.sum(y_grid[0]))) / dy) -
                         ghost_cells)

    i_dx = dx * af.join(1, i_1, i_2)
    j_dy = dy * af.join(1, j_1, j_2)

    i_dx_x_avg = af.join(1, af.max(i_dx, 1), ((x_1 + x_2) / 2))
    j_dy_y_avg = af.join(1, af.max(j_dy, 1), ((y_1 + y_2) / 2))

    x_r_term_1 = dx + af.min(i_dx, 1)
    x_r_term_2 = af.max(i_dx_x_avg, 1)

    y_r_term_1 = dy + af.min(j_dy, 1)
    y_r_term_2 = af.max(j_dy_y_avg, 1)

    x_r_combined_term = af.join(1, x_r_term_1, x_r_term_2)
    y_r_combined_term = af.join(1, y_r_term_1, y_r_term_2)

    # Computing the relay point (x_r, y_r)

    x_r = af.min(x_r_combined_term, 1)
    y_r = af.min(y_r_combined_term, 1)

    # Calculating the fluxes and the weights

    F_x_1 = charge_electron * (x_r - x_1) / dt
    F_x_2 = charge_electron * (x_2 - x_r) / dt

    F_y_1 = charge_electron * (y_r - y_1) / dt
    F_y_2 = charge_electron * (y_2 - y_r) / dt

    W_x_1 = (x_1 + x_r) / (2 * dx) - i_1
    W_x_2 = (x_2 + x_r) / (2 * dx) - i_2

    W_y_1 = (y_1 + y_r) / (2 * dy) - j_1
    W_y_2 = (y_2 + y_r) / (2 * dy) - j_2

    # computing the charge densities at the grid nodes using the
    # fluxes and the weights

    J_x_1_1 = (1 / (dx * dy)) * (F_x_1 * (1 - W_y_1))
    J_x_1_2 = (1 / (dx * dy)) * (F_x_1 * (W_y_1))

    J_x_2_1 = (1 / (dx * dy)) * (F_x_2 * (1 - W_y_2))
    J_x_2_2 = (1 / (dx * dy)) * (F_x_2 * (W_y_2))

    J_y_1_1 = (1 / (dx * dy)) * (F_y_1 * (1 - W_x_1))
    J_y_1_2 = (1 / (dx * dy)) * (F_y_1 * (W_x_1))

    J_y_2_1 = (1 / (dx * dy)) * (F_y_2 * (1 - W_x_2))
    J_y_2_2 = (1 / (dx * dy)) * (F_y_2 * (W_x_2))

    # concatenating the x, y indices for Jx

    Jx_x_indices = af.join(0,\
                           i_1 + ghost_cells,\
                           i_1 + ghost_cells,\
                           i_2 + ghost_cells,\
                           i_2 + ghost_cells\
                          )

    Jx_y_indices = af.join(0,\
                           j_1 + ghost_cells,\
                           (j_1 + 1 + ghost_cells),\
                            j_2 + ghost_cells,\
                           (j_2 + 1 + ghost_cells)\
                          )

    # concatenating the currents at x, y indices for Jx

    Jx_values_at_these_indices = af.join(0,\
                                         J_x_1_1,\
                                         J_x_1_2,\
                                         J_x_2_1,\
                                         J_x_2_2\
                                        )

    # concatenating the x, y indices for Jy

    Jy_x_indices = af.join(0,\
                           i_1 + ghost_cells,\
                           (i_1 + 1 + ghost_cells),\
                            i_2 + ghost_cells,\
                           (i_2 + 1 + ghost_cells)\
                          )

    Jy_y_indices = af.join(0,\
                           j_1 + ghost_cells,\
                           j_1 + ghost_cells,\
                           j_2 + ghost_cells,\
                           j_2 + ghost_cells\
                          )

    # concatenating the currents at x, y indices for Jx

    Jy_values_at_these_indices = af.join(0,\
                                         J_y_1_1,\
                                         J_y_1_2,\
                                         J_y_2_1,\
                                         J_y_2_2\
                                        )

    af.eval(Jx_x_indices, Jx_y_indices, Jy_x_indices, Jy_y_indices)

    af.eval(Jx_values_at_these_indices, Jy_values_at_these_indices)

    return Jx_x_indices, Jx_y_indices, Jx_values_at_these_indices,\
           Jy_x_indices, Jy_y_indices, Jy_values_at_these_indices
    pl.plot(np.array(numerical_first_moment_p3_term[:, 0, :, 0]).ravel(),
            label='N = ' + str(N[i]))
    pl.plot(np.array(analytic_first_moment_p3_term_e[:, 0, :, 0]).ravel(),
            '--',
            color='black')
    pl.show()

    pl.plot(np.array(numerical_first_moment_p3_term[:, 1, :, 0]).ravel(),
            label='N = ' + str(N[i]))
    pl.plot(np.array(analytic_first_moment_p3_term_i[:, 0, :, 0]).ravel(),
            '--',
            color='black')
    pl.show()

    error_p2_e[i] = af.mean(
        af.abs(numerical_first_moment_p2_term[:, 0] -
               analytic_first_moment_p2_term_e))
    error_p2_i[i] = af.mean(
        af.abs(numerical_first_moment_p2_term[:, 1] -
               analytic_first_moment_p2_term_i))
    error_p3_e[i] = af.mean(
        af.abs(numerical_first_moment_p3_term[:, 0] -
               analytic_first_moment_p3_term_e))
    error_p3_i[i] = af.mean(
        af.abs(numerical_first_moment_p3_term[:, 1] -
               analytic_first_moment_p3_term_i))

pl.loglog(N, error_p2_e, '-o', label=r'$p_{2e}$')
pl.loglog(N, error_p2_i, '-o', label=r'$p_{2i}$')
pl.loglog(N, error_p3_e, '-o', label=r'$p_{3e}$')
pl.loglog(N, error_p3_i, '-o', label=r'$p_{3i}$')
pl.loglog(N,
Exemple #13
0
def test_shear_y():

    t = np.random.rand(1)[0]
    N = 2**np.arange(5, 10)
    error = np.zeros(N.size)

    for i in range(N.size):
        domain.N_q1 = int(N[i])
        domain.N_q2 = int(N[i])

        # Defining the physical system to be solved:
        system = physical_system(domain, boundary_conditions_y, params,
                                 initialize_y, advection_terms,
                                 collision_operator.BGK, moment_defs)

        L_q1 = domain.q1_end - domain.q1_start
        L_q2 = domain.q2_end - domain.q2_start

        nls = nonlinear_solver(system)
        N_g = nls.N_ghost_q

        # For left:
        f_reference_bot = af.broadcast(
            initialize_y.initialize_f,
            af.select(
                nls.q1_center - t < domain.q1_start,  # Periodic domain
                nls.q1_center - t + L_q1,
                nls.q1_center - t),
            nls.q2_center,
            nls.p1_center,
            nls.p2_center,
            nls.p3_center,
            params)[:, N_g:-N_g, -2 * N_g:-N_g]

        # For right:
        f_reference_top = af.broadcast(
            initialize_y.initialize_f,
            af.select(nls.q1_center + t > domain.q1_end,
                      nls.q1_center + t - L_q1, nls.q1_center + t),
            nls.q2_center, nls.p1_center, nls.p2_center, nls.p3_center,
            params)[:, N_g:-N_g, N_g:2 * N_g]

        nls.time_elapsed = t
        nls._communicate_f()
        nls._apply_bcs_f()

        error[i] =   af.mean(af.abs(nls.f[:, N_g:-N_g, :N_g] - f_reference_bot)) \
                   + af.mean(af.abs(nls.f[:, N_g:-N_g, -N_g:] - f_reference_top))

    pl.loglog(N, error, '-o', label='Numerical')
    pl.loglog(N,
              error[0] * 32**3 / N**3,
              '--',
              color='black',
              label=r'$O(N^{-3})$')
    pl.xlabel(r'$N$')
    pl.ylabel('Error')
    pl.legend()
    pl.savefig('plot2.png')

    poly = np.polyfit(np.log10(N), np.log10(error), 1)
    assert (abs(poly[0] + 3) < 0.3)
Exemple #14
0
af.display(c)

af.display(-a)
af.display(+a)
af.display(~a)
af.display(a)

af.display(af.cast(a, af.c32))
af.display(af.maxof(a, b))
af.display(af.minof(a, b))
af.display(af.rem(a, b))

a = af.randu(3, 3) - 0.5
b = af.randu(3, 3) - 0.5

af.display(af.abs(a))
af.display(af.arg(a))
af.display(af.sign(a))
af.display(af.round(a))
af.display(af.trunc(a))
af.display(af.floor(a))
af.display(af.ceil(a))
af.display(af.hypot(a, b))
af.display(af.sin(a))
af.display(af.cos(a))
af.display(af.tan(a))
af.display(af.asin(a))
af.display(af.acos(a))
af.display(af.atan(a))
af.display(af.atan2(a, b))
Exemple #15
0
def check_error(params):
    error = np.zeros(N.size)

    for i in range(N.size):
        domain.N_p1 = int(N[i])
        domain.N_p2 = int(N[i])
        domain.N_p3 = int(N[i])

        # Defining the physical system to be solved:
        system = physical_system(domain,
                                 boundary_conditions,
                                 params,
                                 initialize,
                                 advection_terms,
                                 collision_operator.BGK,
                                 moment_defs
                                )

        # Declaring a linear system object which will evolve the defined physical system:
        nls = nonlinear_solver(system)
        N_g = nls.N_ghost_q

        # Time parameters:
        dt      = 0.001 * 32/nls.N_p1
        t_final = 0.1

        time_array  = np.arange(dt, t_final + dt, dt)

        if(time_array[-1]>t_final):
            time_array = np.delete(time_array, -1)

        # Finding final resting point of the blob:
        E1 = nls.cell_centered_EM_fields[0]
        E2 = nls.cell_centered_EM_fields[1]
        E3 = nls.cell_centered_EM_fields[2]
        
        B1 = nls.cell_centered_EM_fields[3]
        B2 = nls.cell_centered_EM_fields[4]
        B3 = nls.cell_centered_EM_fields[5]

        sol = odeint(dp_dt, np.array([0, 0, 0]), time_array,
                     args = (af.mean(E1), af.mean(E2), af.mean(E3), 
                             af.mean(B1), af.mean(B2), af.mean(B3), 
                             params.charge_electron,
                             params.mass_particle
                            ),
                     atol = 1e-12, rtol = 1e-12
                    ) 

        f_reference = af.broadcast(initialize.initialize_f, 
                                   nls.q1_center, nls.q2_center,
                                   nls.p1_center - sol[-1, 0], 
                                   nls.p2_center - sol[-1, 1],
                                   nls.p3_center - sol[-1, 2], 
                                   params
                                  )

        for time_index, t0 in enumerate(time_array):
            nls.strang_timestep(dt)

        error[i] = af.mean(af.abs(  nls.f
                                  - f_reference
                                 )
                          )

    return(error)
Exemple #16
0
# Declaring a linear system object which will evolve the defined physical system:
nls = nonlinear_solver(system)
N_g = nls.N_ghost

# Time parameters:
dt_fvm = params.N_cfl * min(nls.dq1, nls.dq2) \
                      / max(domain.p1_end + domain.p2_end + domain.p3_end) # joining elements of the list

dt_fdtd = params.N_cfl * min(nls.dq1, nls.dq2) \
                       / params.c # lightspeed

dt = dt_fvm  # min(dt_fvm, dt_fdtd)

print('Minimum Value of f:', af.min(nls.f))
print('Error in density:', af.mean(af.abs(nls.compute_moments('density') - 1)))

v2_bulk = nls.compute_moments('mom_v2_bulk') / nls.compute_moments('density')
v3_bulk = nls.compute_moments('mom_v3_bulk') / nls.compute_moments('density')

v2_bulk_ana =   params.amplitude * -1.7450858652952794e-15 * af.cos(params.k_q1 * nls.q1_center) \
              - params.amplitude * 0.5123323181646575      * af.sin(params.k_q1 * nls.q1_center)

v3_bulk_ana =   params.amplitude * 0.5123323181646597 * af.cos(params.k_q1 * nls.q1_center) \
              - params.amplitude * 0                  * af.sin(params.k_q1 * nls.q1_center)

print('Error in v2_bulk:',
      af.mean(af.abs((v2_bulk - v2_bulk_ana) / v2_bulk_ana)))
print('Error in v3_bulk:',
      af.mean(af.abs((v3_bulk - v3_bulk_ana) / v3_bulk_ana)))
#!/usr/bin/python

#######################################################
# Copyright (c) 2015, ArrayFire
# All rights reserved.
#
# This file is distributed under 3-clause BSD license.
# The complete license agreement can be obtained at:
# http://arrayfire.com/licenses/BSD-3-Clause
########################################################

import arrayfire as af

af.info()

POINTS = 30
N = 2 * POINTS

x = (af.iota(d0 = N, d1 = 1, tile_dims = (1, N)) - POINTS) / POINTS
y = (af.iota(d0 = 1, d1 = N, tile_dims = (N, 1)) - POINTS) / POINTS

win = af.Window(800, 800, "3D Surface example using ArrayFire")

t = 0
while not win.close():
    t = t + 0.07
    z = 10*x*-af.abs(y) * af.cos(x*x*(y+t))+af.sin(y*(x+t))-1.5;
    win.surface(x, y, z)
def af_assert(left, right, eps=1E-6):
    if (af.max(af.abs(left - right)) > eps):
        raise ValueError("Arrays not within dictated precision")
    return
Exemple #19
0
    # Defining the physical system to be solved:
    system = physical_system(domain, boundary_conditions, params, initialize,
                             advection_terms, collision_operator.BGK,
                             moment_defs)

    # Declaring a linear system object which will evolve the defined physical system:
    nls = nonlinear_solver(system)
    N_g = nls.N_ghost_q

    # Time parameters:
    dt = 0.01 * 32 / nls.N_q1
    t_final = 0.1

    time_array = np.arange(dt, t_final + dt, dt)
    from initialize import initialize_f
    f_initial = 0.01 * af.exp(-500 * (nls.q1_center - 0.6)**2 - 500 *
                              (nls.q2_center - 0.6)**2)
    add = lambda a, b: a + b
    #f_initial  = af.broadcast(intialize_f, af.broadcast(nls.q1_center, nls.q2_center,

    for time_index, t0 in enumerate(time_array):
        nls.strang_timestep(dt)

    error[i] = af.mean(
        af.abs(nls.f[10, N_g:-N_g, N_g:-N_g] -
               f_initial[:, N_g:-N_g, N_g:-N_g]))

print(error)
print(np.polyfit(np.log10(N), np.log10(error), 1))
Exemple #20
0
def simple_arith(verbose=False):
    display_func = _util.display_func(verbose)
    print_func = _util.print_func(verbose)

    a = af.randu(3, 3)
    b = af.constant(4, 3, 3)
    display_func(a)
    display_func(b)

    c = a + b
    d = a
    d += b

    display_func(c)
    display_func(d)
    display_func(a + 2)
    display_func(3 + a)

    c = a - b
    d = a
    d -= b

    display_func(c)
    display_func(d)
    display_func(a - 2)
    display_func(3 - a)

    c = a * b
    d = a
    d *= b

    display_func(c * 2)
    display_func(3 * d)
    display_func(a * 2)
    display_func(3 * a)

    c = a / b
    d = a
    d /= b

    display_func(c / 2.0)
    display_func(3.0 / d)
    display_func(a / 2)
    display_func(3 / a)

    c = a % b
    d = a
    d %= b

    display_func(c % 2.0)
    display_func(3.0 % d)
    display_func(a % 2)
    display_func(3 % a)

    c = a**b
    d = a
    d **= b

    display_func(c**2.0)
    display_func(3.0**d)
    display_func(a**2)
    display_func(3**a)

    display_func(a < b)
    display_func(a < 0.5)
    display_func(0.5 < a)

    display_func(a <= b)
    display_func(a <= 0.5)
    display_func(0.5 <= a)

    display_func(a > b)
    display_func(a > 0.5)
    display_func(0.5 > a)

    display_func(a >= b)
    display_func(a >= 0.5)
    display_func(0.5 >= a)

    display_func(a != b)
    display_func(a != 0.5)
    display_func(0.5 != a)

    display_func(a == b)
    display_func(a == 0.5)
    display_func(0.5 == a)

    a = af.randu(3, 3, dtype=af.Dtype.u32)
    b = af.constant(4, 3, 3, dtype=af.Dtype.u32)

    display_func(a & b)
    display_func(a & 2)
    c = a
    c &= 2
    display_func(c)

    display_func(a | b)
    display_func(a | 2)
    c = a
    c |= 2
    display_func(c)

    display_func(a >> b)
    display_func(a >> 2)
    c = a
    c >>= 2
    display_func(c)

    display_func(a << b)
    display_func(a << 2)
    c = a
    c <<= 2
    display_func(c)

    display_func(-a)
    display_func(+a)
    display_func(~a)
    display_func(a)

    display_func(af.cast(a, af.Dtype.c32))
    display_func(af.maxof(a, b))
    display_func(af.minof(a, b))
    display_func(af.rem(a, b))

    a = af.randu(3, 3) - 0.5
    b = af.randu(3, 3) - 0.5

    display_func(af.abs(a))
    display_func(af.arg(a))
    display_func(af.sign(a))
    display_func(af.round(a))
    display_func(af.trunc(a))
    display_func(af.floor(a))
    display_func(af.ceil(a))
    display_func(af.hypot(a, b))
    display_func(af.sin(a))
    display_func(af.cos(a))
    display_func(af.tan(a))
    display_func(af.asin(a))
    display_func(af.acos(a))
    display_func(af.atan(a))
    display_func(af.atan2(a, b))

    c = af.cplx(a)
    d = af.cplx(a, b)
    display_func(c)
    display_func(d)
    display_func(af.real(d))
    display_func(af.imag(d))
    display_func(af.conjg(d))

    display_func(af.sinh(a))
    display_func(af.cosh(a))
    display_func(af.tanh(a))
    display_func(af.asinh(a))
    display_func(af.acosh(a))
    display_func(af.atanh(a))

    a = af.abs(a)
    b = af.abs(b)

    display_func(af.root(a, b))
    display_func(af.pow(a, b))
    display_func(af.pow2(a))
    display_func(af.sigmoid(a))
    display_func(af.exp(a))
    display_func(af.expm1(a))
    display_func(af.erf(a))
    display_func(af.erfc(a))
    display_func(af.log(a))
    display_func(af.log1p(a))
    display_func(af.log10(a))
    display_func(af.log2(a))
    display_func(af.sqrt(a))
    display_func(af.cbrt(a))

    a = af.round(5 * af.randu(3, 3) - 1)
    b = af.round(5 * af.randu(3, 3) - 1)

    display_func(af.factorial(a))
    display_func(af.tgamma(a))
    display_func(af.lgamma(a))
    display_func(af.iszero(a))
    display_func(af.isinf(a / b))
    display_func(af.isnan(a / a))

    a = af.randu(5, 1)
    b = af.randu(1, 5)
    c = af.broadcast(lambda x, y: x + y, a, b)
    display_func(a)
    display_func(b)
    display_func(c)

    @af.broadcast
    def test_add(aa, bb):
        return aa + bb

    display_func(test_add(a, b))
Exemple #21
0
def abserr(predicted, target):
    return 100 * af.sum(af.abs(predicted - target)) / predicted.elements()
def indices_and_currents_TSC_2D( charge_electron, positions_x, positions_y, velocity_x, velocity_y,\
                            x_grid, y_grid, ghost_cells, length_domain_x, length_domain_y, dt  ):
    """
    
    function indices_and_currents_TSC_2D( charge_electron, positions_x,\
                                          positions_y, velocity_x, velocity_y,\
                                          x_grid, y_grid, ghost_cells,\
                                          length_domain_x, length_domain_y, dt\
                                        )
    return the x and y indices for Jx and Jy and respective currents associated with these indices 
    
    """

    positions_x_new = positions_x + velocity_x * dt
    positions_y_new = positions_y + velocity_y * dt

    base_indices_x = af.data.constant(0,
                                      positions_x.elements(),
                                      dtype=af.Dtype.u32)
    base_indices_y = af.data.constant(0,
                                      positions_x.elements(),
                                      dtype=af.Dtype.u32)

    dx = af.sum(x_grid[1] - x_grid[0])
    dy = af.sum(y_grid[1] - y_grid[0])

    # Computing S0_x and S0_y
    ###########################################################################################

    # Determining the grid cells containing the respective particles

    x_zone = (((af.abs(positions_x - af.sum(x_grid[0]))) / dx).as_type(
        af.Dtype.u32))
    y_zone = (((af.abs(positions_y - af.sum(y_grid[0]))) / dy).as_type(
        af.Dtype.u32))

    # Determing the indices of the closest grid node in x direction

    temp = af.where(af.abs(positions_x-x_grid[x_zone]) < \
                    af.abs(positions_x-x_grid[x_zone + 1])\
                   )

    if (temp.elements() > 0):
        base_indices_x[temp] = x_zone[temp]

    temp = af.where(af.abs(positions_x - x_grid[x_zone]) >= \
                    af.abs(positions_x-x_grid[x_zone + 1])\
                   )

    if (temp.elements() > 0):
        base_indices_x[temp] = (x_zone[temp] + 1).as_type(af.Dtype.u32)

    # Determing the indices of the closest grid node in y direction

    temp = af.where(af.abs(positions_y-y_grid[y_zone]) < \
                    af.abs(positions_y-y_grid[y_zone + 1])\
                   )

    if (temp.elements() > 0):
        base_indices_y[temp] = y_zone[temp]

    temp = af.where(
        af.abs(positions_y - y_grid[y_zone]) >= af.abs(positions_y -
                                                       x_grid[y_zone + 1]))

    if (temp.elements() > 0):
        base_indices_y[temp] = (y_zone[temp] + 1).as_type(af.Dtype.u32)

    # Concatenating the index list for near by grid nodes in x direction
    # TSC affect 5 nearest grid nodes around in 1 Dimensions

    base_indices_minus_two = (base_indices_x - 2).as_type(af.Dtype.u32)
    base_indices_minus = (base_indices_x - 1).as_type(af.Dtype.u32)
    base_indices_plus = (base_indices_x + 1).as_type(af.Dtype.u32)
    base_indices_plus_two = (base_indices_x + 2).as_type(af.Dtype.u32)



    index_list_x = af.join( 1,\
                             af.join(1, base_indices_minus_two, base_indices_minus, base_indices_x),\
                             af.join(1, base_indices_plus, base_indices_plus_two),\
                          )

    # Concatenating the index list for near by grid nodes in y direction
    # TSC affect 5 nearest grid nodes around in 1 Dimensions

    base_indices_minus_two = (base_indices_y - 2).as_type(af.Dtype.u32)
    base_indices_minus = (base_indices_y - 1).as_type(af.Dtype.u32)
    base_indices_plus = (base_indices_y + 1).as_type(af.Dtype.u32)
    base_indices_plus_two = (base_indices_y + 2).as_type(af.Dtype.u32)


    index_list_y = af.join( 1,\
                             af.join(1, base_indices_minus_two, base_indices_minus, base_indices_y),\
                             af.join(1, base_indices_plus, base_indices_plus_two),\
                          )

    # Concatenating the positions_x for determining weights for near by grid nodes in y direction
    # TSC affect 5 nearest grid nodes around in 1 Dimensions

    positions_x_5x        = af.join( 0,\
                                     af.join(0, positions_x, positions_x, positions_x),\
                                     af.join(0, positions_x, positions_x),\
                                   )

    positions_y_5x        = af.join( 0,\
                                     af.join(0, positions_y, positions_y, positions_y),\
                                     af.join(0, positions_y, positions_y),\
                                   )

    # Determining S0 for positions at t = n * dt

    distance_nodes_x = x_grid[af.flat(index_list_x)]

    distance_nodes_y = y_grid[af.flat(index_list_y)]

    W_x = 0 * distance_nodes_x.copy()
    W_y = 0 * distance_nodes_y.copy()

    # Determining weights in x direction

    temp = af.where(af.abs(distance_nodes_x - positions_x_5x) < (0.5 * dx))

    if (temp.elements() > 0):
        W_x[temp] = 0.75 - (
            af.abs(distance_nodes_x[temp] - positions_x_5x[temp]) / dx)**2

    temp = af.where((af.abs(distance_nodes_x - positions_x_5x) >= (0.5*dx) )\
                     * (af.abs(distance_nodes_x - positions_x_5x) < (1.5 * dx) )\
                   )

    if (temp.elements() > 0):
        W_x[temp] = 0.5 * (
            1.5 -
            (af.abs(distance_nodes_x[temp] - positions_x_5x[temp]) / dx))**2

    # Determining weights in y direction

    temp = af.where(af.abs(distance_nodes_y - positions_y_5x) < (0.5 * dy))

    if (temp.elements() > 0):
        W_y[temp] = 0.75 - (
            af.abs(distance_nodes_y[temp] - positions_y_5x[temp]) / dy)**2

    temp = af.where((af.abs(distance_nodes_y - positions_y_5x) >= (0.5*dy) )\
                     * (af.abs(distance_nodes_y - positions_y_5x) < (1.5 * dy) )\
                   )

    if (temp.elements() > 0):
        W_y[temp] = 0.5 * (
            1.5 -
            (af.abs(distance_nodes_y[temp] - positions_y_5x[temp]) / dy))**2

    # Restructering W_x and W_y for visualization and ease of understanding

    W_x = af.data.moddims(W_x, positions_x.elements(), 5)
    W_y = af.data.moddims(W_y, positions_y.elements(), 5)

    # Tiling the S0_x and S0_y for the 25 indices around the particle

    S0_x = af.tile(W_x, 1, 1, 5)
    S0_y = af.tile(W_y, 1, 1, 5)

    S0_y = af.reorder(S0_y, 0, 2, 1)

    #Computing S1_x and S1_y
    ###########################################################################################

    positions_x_5x_new    = af.join( 0,\
                                     af.join(0, positions_x_new, positions_x_new, positions_x_new),\
                                     af.join(0, positions_x_new, positions_x_new),\
                                   )

    positions_y_5x_new    = af.join( 0,\
                                     af.join(0, positions_y_new, positions_y_new, positions_y_new),\
                                     af.join(0, positions_y_new, positions_y_new),\
                                   )

    # Determining S0 for positions at t = n * dt

    W_x = 0 * distance_nodes_x.copy()
    W_y = 0 * distance_nodes_y.copy()

    # Determining weights in x direction

    temp = af.where(af.abs(distance_nodes_x - positions_x_5x_new) < (0.5 * dx))

    if (temp.elements() > 0):
        W_x[temp] = 0.75 - (
            af.abs(distance_nodes_x[temp] - positions_x_5x_new[temp]) / dx)**2

    temp = af.where((af.abs(distance_nodes_x - positions_x_5x_new) >= (0.5*dx) )\
                     * (af.abs(distance_nodes_x - positions_x_5x_new) < (1.5 * dx) )\
                   )

    if (temp.elements() > 0):
        W_x[temp] = 0.5 * (1.5 - (af.abs(distance_nodes_x[temp] \
                                  - positions_x_5x_new[temp])/dx\
                                 )\
                          )**2

    # Determining weights in y direction

    temp = af.where(af.abs(distance_nodes_y - positions_y_5x_new) < (0.5 * dy))

    if (temp.elements() > 0):
        W_y[temp] = 0.75 - (af.abs(distance_nodes_y[temp] \
                                   - positions_y_5x_new[temp]\
                                  )/dy\
                           )**2

    temp = af.where((af.abs(distance_nodes_y - positions_y_5x_new) >= (0.5*dy) )\
                     * (af.abs(distance_nodes_y - positions_y_5x_new) < (1.5 * dy) )\
                   )

    if (temp.elements() > 0):
        W_y[temp] = 0.5 * (1.5 - (af.abs(distance_nodes_y[temp] \
                                         - positions_y_5x_new[temp])/dy\
                                 )\
                          )**2

    # Restructering W_x and W_y for visualization and ease of understanding

    W_x = af.data.moddims(W_x, positions_x.elements(), 5)
    W_y = af.data.moddims(W_y, positions_x.elements(), 5)

    # Tiling the S0_x and S0_y for the 25 indices around the particle

    S1_x = af.tile(W_x, 1, 1, 5)
    S1_y = af.tile(W_y, 1, 1, 5)

    S1_y = af.reorder(S1_y, 0, 2, 1)

    ###########################################################################################

    # Determining the final weight matrix for currents in 3D matrix form factor

    W_x = (S1_x - S0_x) * (S0_y + (0.5 * (S1_y - S0_y)))

    W_y = (S1_y - S0_y) * (S0_x + (0.5 * (S1_x - S0_x)))

    ###########################################################################################

    # Assigning Jx and Jy according to Esirkepov's scheme

    Jx = af.data.constant(0, positions_x.elements(), 5, 5, dtype=af.Dtype.f64)
    Jy = af.data.constant(0, positions_x.elements(), 5, 5, dtype=af.Dtype.f64)

    Jx[:, 0, :] = -1 * charge_electron * (dx / dt) * W_x[:, 0, :].copy()
    Jx[:,
       1, :] = Jx[:, 0, :] + -1 * charge_electron * (dx /
                                                     dt) * W_x[:, 1, :].copy()
    Jx[:,
       2, :] = Jx[:, 1, :] + -1 * charge_electron * (dx /
                                                     dt) * W_x[:, 2, :].copy()
    Jx[:,
       3, :] = Jx[:, 2, :] + -1 * charge_electron * (dx /
                                                     dt) * W_x[:, 3, :].copy()
    Jx[:,
       4, :] = Jx[:, 3, :] + -1 * charge_electron * (dx /
                                                     dt) * W_x[:, 4, :].copy()

    # Computing current density using currents

    Jx = (1 / (dx * dy)) * Jx

    Jy[:, :, 0] = -1 * charge_electron * (dy / dt) * W_y[:, :, 0].copy()
    Jy[:, :,
       1] = Jy[:, :,
               0] + -1 * charge_electron * (dy / dt) * W_y[:, :, 1].copy()
    Jy[:, :,
       2] = Jy[:, :,
               1] + -1 * charge_electron * (dy / dt) * W_y[:, :, 2].copy()
    Jy[:, :,
       3] = Jy[:, :,
               2] + -1 * charge_electron * (dy / dt) * W_y[:, :, 3].copy()
    Jy[:, :,
       4] = Jy[:, :,
               3] + -1 * charge_electron * (dy / dt) * W_y[:, :, 4].copy()

    # Computing current density using currents

    Jy = (1 / (dx * dy)) * Jy

    # Preparing the final index and current vectors
    ###########################################################################################

    # Determining the x indices for charge deposition
    index_list_x_Jx = af.flat(af.tile(index_list_x, 1, 1, 5))

    # Determining the y indices for charge deposition
    y_current_zone = af.tile(index_list_y, 1, 1, 5)
    index_list_y_Jx = af.flat(af.reorder(y_current_zone, 0, 2, 1))

    currents_Jx = af.flat(Jx)

    # Determining the x indices for charge deposition
    index_list_x_Jy = af.flat(af.tile(index_list_x, 1, 1, 5))

    # Determining the y indices for charge deposition
    y_current_zone = af.tile(index_list_y, 1, 1, 5)
    index_list_y_Jy = af.flat(af.reorder(y_current_zone, 0, 2, 1))

    # Flattenning the Currents array
    currents_Jy = af.flat(Jy)

    af.eval(index_list_x_Jx, index_list_y_Jx)
    af.eval(index_list_x_Jy, index_list_y_Jy)
    af.eval(currents_Jx, currents_Jy)


    return index_list_x_Jx, index_list_y_Jx, currents_Jx,\
           index_list_x_Jy, index_list_y_Jy, currents_Jy
def f0_ee_constant_T(f, p_x, p_y, p_z, params):
    """
    Return the local equilibrium distribution corresponding to the tau_ee
    relaxation time when lattice temperature, T, is set to constant.
    Parameters:
    -----------
    f : Distribution function array
        shape:(N_v, N_s, N_q1, N_q2)
    
    p_x : The array that holds data for the v1 dimension in v-space
         shape:(N_v, N_s, 1, 1)

    p_y : The array that holds data for the v2 dimension in v-space
         shape:(N_v, N_s, 1, 1)

    p_z : The array that holds data for the v3 dimension in v-space
         shape:(N_v, N_s, 1, 1)
    
    params: The parameters file/object that is originally declared by the user.
            This can be used to inject other functions/attributes into the function

    """

    # Initial guess
    mu_ee       = params.mu_ee
    T_ee        = params.T_ee
    vel_drift_x = params.vel_drift_x 
    vel_drift_y = params.vel_drift_y
    
    for n in range(params.collision_nonlinear_iters):

        E_upper = params.E_band
        k       = params.boltzmann_constant
        
        tmp1        = (E_upper - mu_ee - p_x*vel_drift_x - p_y*vel_drift_y)
        tmp         = (tmp1/(k*T_ee))
        denominator = (k*T_ee**2.*(af.exp(tmp) + 2. + af.exp(-tmp)) )
        
        a_0 = T_ee      / denominator
        a_1 = tmp1      / denominator
        a_2 = T_ee * p_x / denominator
        a_3 = T_ee * p_y / denominator

        af.eval(a_0, a_1, a_2, a_3)


        # TODO: Multiply with the integral measure dp_x * dp_y
        a_00 = integral_over_p(a_0, params.integral_measure)
        ##a_01 = af.sum(a_1, 0)
        a_02 = integral_over_p(a_2, params.integral_measure)
        a_03 = integral_over_p(a_3, params.integral_measure)

        #a_10 = af.sum(E_upper * a_0, 0)
        #a_11 = af.sum(E_upper * a_1, 0)
        #a_12 = af.sum(E_upper * a_2, 0)
        #a_13 = af.sum(E_upper * a_3, 0)

        a_20 = integral_over_p(p_x * a_0, params.integral_measure)
        ##a_21 = af.sum(p_x * a_1, 0)
        a_22 = integral_over_p(p_x * a_2, params.integral_measure)
        a_23 = integral_over_p(p_x * a_3, params.integral_measure)

        a_30 = integral_over_p(p_y * a_0, params.integral_measure)
        ##a_31 = af.sum(p_y * a_1, 0)
        a_32 = integral_over_p(p_y * a_2, params.integral_measure)
        a_33 = integral_over_p(p_y * a_3, params.integral_measure)

        A = [ [a_00, a_02, a_03], \
              [a_20, a_22, a_23], \
              [a_30, a_32, a_33]  \
            ]
        
        
        fermi_dirac = 1./(af.exp( (  E_upper - mu_ee
                                   - vel_drift_x*p_x - vel_drift_y*p_y 
                                  )/(k*T_ee) 
                                ) + 1.
                         )
        af.eval(fermi_dirac)

        zeroth_moment  =         (f - fermi_dirac)
        #second_moment  = E_upper*(f - fermi_dirac)
        first_moment_x =      p_x*(f - fermi_dirac)
        first_moment_y =      p_y*(f - fermi_dirac)

        eqn_mass_conservation   = integral_over_p(zeroth_moment,  params.integral_measure)
        #eqn_energy_conservation = af.sum(second_moment,  0)
        eqn_mom_x_conservation  = integral_over_p(first_moment_x, params.integral_measure)
        eqn_mom_y_conservation  = integral_over_p(first_moment_y, params.integral_measure)

        residual = [eqn_mass_conservation, \
                    eqn_mom_x_conservation, \
                    eqn_mom_y_conservation]

        error_norm = np.max([af.max(af.abs(residual[0])),
                             af.max(af.abs(residual[1])),
                             af.max(af.abs(residual[2]))
                            ]
                           )
        print("    rank = ", params.rank,
	      "||residual_ee|| = ", error_norm
	     )

#        if (error_norm < 1e-13):
#            params.mu_ee       = mu_ee      
#            params.T_ee        = T_ee       
#            params.vel_drift_x = vel_drift_x
#            params.vel_drift_y = vel_drift_y
#            return(fermi_dirac)

        b_0 = eqn_mass_conservation  
        #b_1 = eqn_energy_conservation
        b_2 = eqn_mom_x_conservation 
        b_3 = eqn_mom_y_conservation 
        b   = [b_0, b_2, b_3]

        # Solve Ax = b
        # where A == Jacobian,
        #       x == delta guess (correction to guess), 
        #       b = -residual

        A_inv = inverse_3x3_matrix(A)
        
        x_0 = A_inv[0][0]*b[0] + A_inv[0][1]*b[1] + A_inv[0][2]*b[2]
        #x_1 = A_inv[1][0]*b[0] + A_inv[1][1]*b[1] + A_inv[1][2]*b[2] + A_inv[1][3]*b[3]
        x_2 = A_inv[1][0]*b[0] + A_inv[1][1]*b[1] + A_inv[1][2]*b[2]
        x_3 = A_inv[2][0]*b[0] + A_inv[2][1]*b[1] + A_inv[2][2]*b[2]

        delta_mu = x_0
        #delta_T  = x_1
        delta_vx = x_2
        delta_vy = x_3
        
        mu_ee       = mu_ee       + delta_mu
        #T_ee        = T_ee        + delta_T
        vel_drift_x = vel_drift_x + delta_vx
        vel_drift_y = vel_drift_y + delta_vy

        af.eval(mu_ee, vel_drift_x, vel_drift_y)

    # Solved for (mu_ee, T_ee, vel_drift_x, vel_drift_y). Now store in params
    params.mu_ee       = mu_ee      
    #params.T_ee        = T_ee       
    params.vel_drift_x = vel_drift_x
    params.vel_drift_y = vel_drift_y

    fermi_dirac = 1./(af.exp( (  E_upper - mu_ee
                               - vel_drift_x*p_x - vel_drift_y*p_y 
                              )/(k*T_ee) 
                            ) + 1.
                     )
    af.eval(fermi_dirac)

    zeroth_moment  =          f - fermi_dirac
    #second_moment  = E_upper*(f - fermi_dirac)
    first_moment_x =      p_x*(f - fermi_dirac)
    first_moment_y =      p_y*(f - fermi_dirac)
    
    eqn_mass_conservation   = integral_over_p(zeroth_moment,  params.integral_measure)
    #eqn_energy_conservation = af.sum(second_moment,  0)
    eqn_mom_x_conservation  = integral_over_p(first_moment_x, params.integral_measure)
    eqn_mom_y_conservation  = integral_over_p(first_moment_y, params.integral_measure)

    residual = [eqn_mass_conservation, \
                eqn_mom_x_conservation, \
                eqn_mom_y_conservation
               ]

    error_norm = np.max([af.max(af.abs(residual[0])),
                         af.max(af.abs(residual[1])),
                         af.max(af.abs(residual[2]))
                        ]
                       )
    print("    rank = ", params.rank,
	  "||residual_ee|| = ", error_norm
	 )
    N_g = domain.N_ghost
    print("    rank = ", params.rank,
          "mu_ee = ", af.mean(params.mu_ee[0, 0, N_g:-N_g, N_g:-N_g]),
          "T_ee = ", af.mean(params.T_ee[0, 0, N_g:-N_g, N_g:-N_g]),
          "<v_x> = ", af.mean(params.vel_drift_x[0, 0, N_g:-N_g, N_g:-N_g]),
          "<v_y> = ", af.mean(params.vel_drift_y[0, 0, N_g:-N_g, N_g:-N_g])
         )
    PETSc.Sys.Print("    ------------------")

    return(fermi_dirac)
Exemple #24
0
    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


for i in trange(201):
    h5py_data = h5py.File(
        'results/xi_eta_2d_hdf5_%02d/dump_timestep_%06d' %
        (int(params.N_LGL), int(10 * i)) + '.hdf5', 'r')
    u_LGL = af.np_to_af_array(h5py_data['u_i'][:])
    contour_2d(u_LGL, i)
    if i > 199:
        print(af.mean(af.abs(u_LGL - params.u_e_ij)))

# Creating a folder to store hdf5 files. If it doesn't exist.
results_directory = 'results/1D_Wave_images'

if not os.path.exists(results_directory):
    os.makedirs(results_directory)

# The directory where h5py files are stored.
#h5py_directory = 'results/hdf5_%02d' %int(params.N_LGL)
#
#path, dirs, files = os.walk(h5py_directory).__next__()
#file_count = len(files)
#print(file_count)
#
#
Exemple #25
0
def check_error(params):
    error = np.zeros(N.size)

    for i in range(N.size):
        domain.N_p1 = int(N[i])
        domain.N_p2 = int(N[i])
        # Defining the physical system to be solved:
        system = physical_system(domain,
                                 boundary_conditions,
                                 params,
                                 initialize,
                                 advection_terms,
                                 collision_operator.BGK,
                                 moments
                                )

        nls = nonlinear_solver(system)

        # Time parameters:
        dt = 0.001 * 32/nls.N_p1
        
        # First, we check when the blob returns to (0, 0)
        E1 = nls.fields_solver.cell_centered_EM_fields[0]
        E2 = nls.fields_solver.cell_centered_EM_fields[1]
        B3 = nls.fields_solver.cell_centered_EM_fields[5]

        sol = odeint(dp_dt, np.array([0, 0]), time_array_odeint,
                     args = (af.mean(E1), af.mean(E2), af.mean(B3), 
                             af.sum(params.charge[0]),
                             af.sum(params.mass[0])
                            ),
                     atol = 1e-12, rtol = 1e-12
                    ) 

        dist_from_origin = abs(sol[:, 0]) + abs(sol[:, 1])
        
        # The time when the distance is minimum apart from the start is the time
        # when the blob returns back to the center:
        # However, this is an approximate solution. To get a more accurate solution, 
        # we provide this guess to our root finder scipy.optimize.root
        t_final_approx = time_array_odeint[np.argmin(dist_from_origin[1:])]
        t_final        = root(residual, t_final_approx, 
                              args = (af.mean(E1), af.mean(E2), af.mean(B3), 
                                      params.charge[0],
                                      params.mass[0]
                                     ),
                              method = 'lm', tol = 1e-12
                             ).x

        time_array  = np.arange(dt, float("{0:.3f}".format(t_final[0])) + dt, dt)

        if(time_array[-1]>t_final):
            time_array = np.delete(time_array, -1)
    
        f_reference = nls.f

        for time_index, t0 in enumerate(time_array):
            nls.strang_timestep(dt)

        error[i] = af.mean(af.abs(  nls.f
                                  - f_reference
                                 )
                          )

    return(error)
Exemple #26
0
#!/usr/bin/python

#######################################################
# Copyright (c) 2015, ArrayFire
# All rights reserved.
#
# This file is distributed under 3-clause BSD license.
# The complete license agreement can be obtained at:
# http://arrayfire.com/licenses/BSD-3-Clause
########################################################

import arrayfire as af

af.info()

POINTS = 30
N = 2 * POINTS

x = (af.iota(d0=N, d1=1, tile_dims=(1, N)) - POINTS) / POINTS
y = (af.iota(d0=1, d1=N, tile_dims=(N, 1)) - POINTS) / POINTS

win = af.Window(800, 800, "3D Surface example using ArrayFire")

t = 0
while not win.close():
    t = t + 0.07
    z = 10 * x * -af.abs(y) * af.cos(x * x * (y + t)) + af.sin(y *
                                                               (x + t)) - 1.5
    win.surface(x, y, z)
Exemple #27
0
def test_fdtd_mode1_periodic():

    N = np.array([128])  #2**np.arange(5, 8)

    error_B1 = np.zeros(N.size)
    error_B2 = np.zeros(N.size)
    error_E3 = np.zeros(N.size)

    for i in range(N.size):

        af.device_gc()
        dt = (1 / int(N[i])) * 1 / 2
        time = np.arange(dt, 10 * 1 + dt, dt)

        params.dt = dt

        obj = test_periodic(int(N[i]), initialize_fdtd_mode1, params)
        N_g = obj.fields_solver.N_g

        E1_initial = obj.fields_solver.yee_grid_EM_fields[0].copy()
        E2_initial = obj.fields_solver.yee_grid_EM_fields[1].copy()
        E3_initial = obj.fields_solver.yee_grid_EM_fields[2].copy()

        B1_initial = obj.fields_solver.yee_grid_EM_fields[3].copy()
        B2_initial = obj.fields_solver.yee_grid_EM_fields[4].copy()
        B3_initial = obj.fields_solver.yee_grid_EM_fields[5].copy()

        # electric_energy = 1/4 * (  E3_initial**2                       # Ez(i+1/2, j+1/2)
        #                          + af.shift(E3_initial, 0, 0, 1, 0)**2 # Ez(i-1/2, j+1/2)
        #                          + af.shift(E3_initial, 0, 0, 0, 1)**2 # Ez(i+1/2, j-1/2)
        #                          + af.shift(E3_initial, 0, 0, 1, 1)**2 # Ez(i-1/2, j-1/2)
        #                         )

        # magnetic_energy_x = 0.5 * (  B1_n_plus_half * B1_n_minus_half                        # (i+1/2, j)
        #                            + af.shift(B1_n_plus_half * B1_n_minus_half, 0, 0, 1, 0)  # (i-1/2, j)
        #                           )

        # magnetic_energy_y = 0.5 * (  B2_n_plus_half * B2_n_minus_half                       # (i, j+1/2)
        #                            + af.shift(B2_n_plus_half * B2_n_minus_half, 0, 0, 0, 1) # (i, j-1/2)
        #                           )

        energy = np.zeros([time.size])

        B1_at_n_minus_half_i = obj.fields_solver.yee_grid_EM_fields[3].copy()
        B1_at_n_minus_half_i_plus_1 = af.shift(B1_at_n_minus_half_i, 0, 0, 0,
                                               -1)

        for time_index, t0 in enumerate(time):

            B1_at_n_plus_half_i = obj.fields_solver.yee_grid_EM_fields[3].copy(
            )
            B1_at_n_plus_half_i_plus_1 = af.shift(B1_at_n_plus_half_i, 0, 0, 0,
                                                  -1)

            E3_n = obj.fields_solver.yee_grid_EM_fields[2].copy()

            J1 = J2 = J3 = 0 * obj.fields_solver.q1_center**0
            obj.fields_solver.evolve_electrodynamic_fields(J1, J2, J3, dt)

            E3_n_plus_1 = obj.fields_solver.yee_grid_EM_fields[2].copy()

            energy[time_index] = af.sum(
                (E3_n_plus_1 * B1_at_n_minus_half_i_plus_1
                 )[:, :, N_g:-N_g,
                   N_g:-N_g]) * obj.fields_solver.dq1 * obj.fields_solver.dq2

            B1_at_n_minus_half_i = B1_at_n_plus_half_i.copy()
            B1_at_n_minus_half_i_plus_1 = af.shift(B1_at_n_minus_half_i, 0, 0,
                                                   0, -1)

            # electric_energy   = E3_at_n**2
            # magnetic_energy_x = B1_n_plus_half * B1_n_minus_half
            # magnetic_energy_y = B2_n_plus_half * B2_n_minus_half
            # pl.plot(np.array(obj.fields_solver.q1_center).reshape(134, 9)[3:-3, 0],
            #         np.array(obj.fields_solver.yee_grid_EM_fields[1]).reshape(134, 9)[3:-3, 0],
            #         label = r'$Ey_{i+1/2}^n$')
            # pl.plot(np.array(obj.fields_solver.q1_center).reshape(134, 9)[3:-3, 0],
            #         np.array(obj.fields_solver.yee_grid_EM_fields[5]).reshape(134, 9)[3:-3, 0], '--',
            #         label = r'${Bz}_{i}^{n+1/2}$')
            # pl.legend(fontsize = 20)
            # pl.ylim([-2, 2])
            # pl.title('Time = %.2f'%t0)
            # pl.savefig('images/%04d'%time_index + '.png')
            # pl.clf()

            # pl.contourf(np.array(obj.fields_solver.yee_grid_EM_fields[2]).reshape(134, 134), 40)
            # pl.savefig('images/%04d'%time_index + '.png')
            # pl.clf()

            # energy = af.sum((electric_energy + magnetic_energy_x + magnetic_energy_y)[:, :, N_g:-N_g, N_g:-N_g])
            # if(time_index == 0):
            #     error[time_index] = energy * obj.fields_solver.dq1 * obj.fields_solver.dq2
            # else:
            #     error[time_index] = abs((energy) * obj.fields_solver.dq1 * obj.fields_solver.dq2 -  error[0])

        import h5py
        h5f = h5py.File('data/Bi+n-_Ei+n+.h5', 'w')
        h5f.create_dataset('data', data=energy[1:])
        h5f.create_dataset('time', data=time[1:])
        h5f.close()

        # pl.plot(time[1:], energy[1:])
        # pl.show()
        # # pl.ylabel(r'$B_z^{n+1/2}(i) \times (E_y^{n+1}(i+1/2) + E_y^{n}(i+1/2))$')
        # pl.xlabel('Time')
        # # pl.ylim([1e-15, 1e-9])
        # pl.savefig('plot.png', bbox_inches = 'tight')

        error_B1[i] = af.sum(
            af.abs(obj.fields_solver.yee_grid_EM_fields[3, :, N_g:-N_g,
                                                        N_g:-N_g] -
                   B1_initial[:, :, N_g:-N_g, N_g:-N_g])) / (
                       B1_initial.elements())

        error_B2[i] = af.sum(
            af.abs(obj.fields_solver.yee_grid_EM_fields[4, :, N_g:-N_g,
                                                        N_g:-N_g] -
                   B2_initial[:, :, N_g:-N_g, N_g:-N_g])) / (
                       B2_initial.elements())

        error_E3[i] = af.sum(
            af.abs(obj.fields_solver.yee_grid_EM_fields[2, :, N_g:-N_g,
                                                        N_g:-N_g] -
                   E3_initial[:, :, N_g:-N_g, N_g:-N_g])) / (
                       E3_initial.elements())

    poly_B1 = np.polyfit(np.log10(N), np.log10(error_B1), 1)
    poly_B2 = np.polyfit(np.log10(N), np.log10(error_B2), 1)
    poly_E3 = np.polyfit(np.log10(N), np.log10(error_E3), 1)

    print(error_B1)
    print(error_B2)
    print(error_E3)

    print(poly_B1)
    print(poly_B2)
    print(poly_E3)

    pl.loglog(N, error_B1, '-o', label=r'$B_x$')
    pl.loglog(N, error_B2, '-o', label=r'$B_y$')
    pl.loglog(N, error_E3, '-o', label=r'$E_z$')
    pl.loglog(N,
              error_B2[0] * 32**2 / N**2,
              '--',
              color='black',
              label=r'$O(N^{-2})$')
    pl.xlabel(r'$N$')
    pl.ylabel('Error')
    pl.legend()
    pl.savefig('convergenceplot.png')

    assert (abs(poly_B1[0] + 2) < 0.2)
    assert (abs(poly_B2[0] + 2) < 0.2)
    assert (abs(poly_E3[0] + 2) < 0.2)
def af_assert(left, right, eps=1E-6):
    if (af.max(af.abs(left -right)) > eps):
        raise ValueError("Arrays not within dictated precision")
    return
Exemple #29
0
def test_fdtd_mode2_periodic():

    N = np.array([64])  #2**np.arange(5, 8)

    error_E1 = np.zeros(N.size)
    error_E2 = np.zeros(N.size)
    error_B3 = np.zeros(N.size)

    for i in range(N.size):

        dt = (1 / int(N[i])) * np.sqrt(9 / 5) / 2
        time = np.arange(dt, 10 * np.sqrt(9 / 5) + dt, dt)

        params.dt = dt

        obj = test_periodic(N[i], initialize_fdtd_mode2, params)
        N_g = obj.fields_solver.N_g

        B3_initial = obj.fields_solver.yee_grid_EM_fields[5].copy()
        E1_initial = obj.fields_solver.yee_grid_EM_fields[0].copy()
        E2_initial = obj.fields_solver.yee_grid_EM_fields[1].copy()

        error = np.zeros([time.size])
        for time_index, t0 in enumerate(time):

            B3_n_minus_half = obj.fields_solver.yee_grid_EM_fields[5].copy()
            J1 = J2 = J3 = 0 * obj.fields_solver.q1_center**0
            obj.fields_solver.evolve_electrodynamic_fields(J1, J2, J3, dt)
            B3_n_plus_half = obj.fields_solver.yee_grid_EM_fields[5].copy()

            E1_at_n = obj.fields_solver.yee_grid_EM_fields[0].copy()
            E2_at_n = obj.fields_solver.yee_grid_EM_fields[1].copy()

            electric_energy_x = E1_at_n**2
            electric_energy_y = E2_at_n**2
            magnetic_energy = B3_n_plus_half * B3_n_minus_half

            energy = af.sum((magnetic_energy + electric_energy_x +
                             electric_energy_y)[:, :, N_g:-N_g, N_g:-N_g])
            if (time_index == 0):
                error[
                    time_index] = energy * obj.fields_solver.dq1 * obj.fields_solver.dq2
            else:
                error[time_index] = abs((energy) * obj.fields_solver.dq1 *
                                        obj.fields_solver.dq2 - error[0])

        pl.semilogy(time[1:], error[1:])
        pl.ylabel('Error')
        pl.xlabel('Time')
        pl.ylim([1e-15, 1e-9])
        pl.savefig('plot.png', bbox_inches='tight')

        error_E1[i] = af.sum(
            af.abs(obj.fields_solver.yee_grid_EM_fields[0, :, N_g:-N_g,
                                                        N_g:-N_g] -
                   E1_initial[:, :, N_g:-N_g, N_g:-N_g])) / (
                       E1_initial.elements())

        error_E2[i] = af.sum(
            af.abs(obj.fields_solver.yee_grid_EM_fields[1, :, N_g:-N_g,
                                                        N_g:-N_g] -
                   E2_initial[:, :, N_g:-N_g, N_g:-N_g])) / (
                       E2_initial.elements())

        error_B3[i] = af.sum(
            af.abs(obj.fields_solver.yee_grid_EM_fields[5, :, N_g:-N_g,
                                                        N_g:-N_g] -
                   B3_initial[:, :, N_g:-N_g, N_g:-N_g])) / (
                       B3_initial.elements())

    print(error_E1)
    print(error_E2)
    print(error_B3)

    poly_E1 = np.polyfit(np.log10(N), np.log10(error_E1), 1)
    poly_E2 = np.polyfit(np.log10(N), np.log10(error_E2), 1)
    poly_B3 = np.polyfit(np.log10(N), np.log10(error_B3), 1)

    pl.loglog(N, error_E1, '-o', label=r'$E_x$')
    pl.loglog(N, error_E2, '-o', label=r'$E_y$')
    pl.loglog(N, error_B3, '-o', label=r'$B_z$')
    pl.loglog(N,
              error_E1[0] * 32**2 / N**2,
              '--',
              color='black',
              label=r'$O(N^{-2})$')
    pl.xlabel(r'$N$')
    pl.ylabel('Error')
    pl.legend()
    pl.savefig('convergenceplot.png')

    print(poly_E1)
    print(poly_E2)
    print(poly_B3)

    assert (abs(poly_E1[0] + 2) < 0.3)
    assert (abs(poly_E2[0] + 2) < 0.3)
    assert (abs(poly_B3[0] + 2) < 0.3)
def f0_defect_constant_T(f, p_x, p_y, p_z, params):
    """
    Return the local equilibrium distribution corresponding to the tau_D
    relaxation time when lattice temperature, T, is set to constant.
    Parameters:
    -----------
    f : Distribution function array
        shape:(N_v, N_s, N_q1, N_q2)
    
    p_x : The array that holds data for the v1 dimension in v-space
         shape:(N_v, N_s, 1, 1)

    p_y : The array that holds data for the v2 dimension in v-space
         shape:(N_v, N_s, 1, 1)

    p_z : The array that holds data for the v3 dimension in v-space
         shape:(N_v, N_s, 1, 1)
    
    params: The parameters file/object that is originally declared by the user.
            This can be used to inject other functions/attributes into the function

    """

    mu = params.mu
    T  = params.T

    for n in range(params.collision_nonlinear_iters):

        E_upper = params.E_band
        k       = params.boltzmann_constant

        tmp         = ((E_upper - mu)/(k*T))
        denominator = (k*T**2.*(af.exp(tmp) + 2. + af.exp(-tmp)) )

        # TODO: Multiply with the integral measure dp_x * dp_y
        a00 = integral_over_p(T/denominator, params.integral_measure)

        fermi_dirac = 1./(af.exp( (E_upper - mu)/(k*T) ) + 1.)
        af.eval(fermi_dirac)

        zeroth_moment = f - fermi_dirac

        eqn_mass_conservation = integral_over_p(zeroth_moment,
                                                params.integral_measure
                                               )

        N_g = domain.N_ghost
        error_mass_conservation = af.max(af.abs(eqn_mass_conservation)[0, 0, N_g:-N_g, N_g:-N_g])

        print("    rank = ", params.rank,
	      "||residual_defect|| = ", error_mass_conservation
	     )

        res      = eqn_mass_conservation
        dres_dmu = -a00

        delta_mu = -res/dres_dmu

        mu = mu + delta_mu

        af.eval(mu)

    # Solved for mu. Now store in params
    params.mu = mu

    # Print final residual
    fermi_dirac = 1./(af.exp( (E_upper - mu)/(k*T) ) + 1.)
    af.eval(fermi_dirac)

    zeroth_moment = f - fermi_dirac

    eqn_mass_conservation   = integral_over_p(zeroth_moment,
                                              params.integral_measure
                                             )

    N_g = domain.N_ghost
    error_mass_conservation = af.max(af.abs(eqn_mass_conservation)[0, 0, N_g:-N_g, N_g:-N_g])

    print("    rank = ", params.rank,
	  "||residual_defect|| = ", error_mass_conservation
	 )
    print("    rank = ", params.rank,
          "mu = ", af.mean(params.mu[0, 0, N_g:-N_g, N_g:-N_g]),
          "T = ", af.mean(params.T[0, 0, N_g:-N_g, N_g:-N_g])
         )
    PETSc.Sys.Print("    ------------------")

    return(fermi_dirac)
Exemple #31
0
def test_fdtd_mode1_mirror():

    N = 2**np.arange(5, 8)

    error_B1 = np.zeros(N.size)
    error_B2 = np.zeros(N.size)
    error_E3 = np.zeros(N.size)

    for i in range(N.size):

        dt = (1 / int(N[i])) * np.sqrt(9 / 5) / 2
        time = np.arange(dt, 4 * np.sqrt(9 / 5) + dt, dt)

        params.dt = dt

        obj = test_mirror(N[i], initialize_fdtd_mode2, params)
        N_g = obj.fields_solver.N_g

        B1_initial = obj.fields_solver.yee_grid_EM_fields[3].copy()
        B2_initial = obj.fields_solver.yee_grid_EM_fields[4].copy()
        E3_initial = obj.fields_solver.yee_grid_EM_fields[2].copy()

        for time_index, t0 in enumerate(time):
            J1 = J2 = J3 = 0 * obj.fields_solver.q1_center**0
            obj.fields_solver.evolve_electrodynamic_fields(J1, J2, J3, dt)

        error_B1[i] = af.sum(
            af.abs(obj.fields_solver.yee_grid_EM_fields[3, :, N_g:-N_g,
                                                        N_g:-N_g] -
                   B1_initial[:, :, N_g:-N_g, N_g:-N_g])) / (
                       B1_initial.elements())

        error_B2[i] = af.sum(
            af.abs(obj.fields_solver.yee_grid_EM_fields[4, :, N_g:-N_g,
                                                        N_g:-N_g] -
                   B2_initial[:, :, N_g:-N_g, N_g:-N_g])) / (
                       B2_initial.elements())

        error_E3[i] = af.sum(
            af.abs(obj.fields_solver.yee_grid_EM_fields[2, :, N_g:-N_g,
                                                        N_g:-N_g] -
                   E3_initial[:, :, N_g:-N_g, N_g:-N_g])) / (
                       E3_initial.elements())

    print(error_B1)
    print(error_B2)
    print(error_E3)

    poly_B1 = np.polyfit(np.log10(N), np.log10(error_B1), 1)
    poly_B2 = np.polyfit(np.log10(N), np.log10(error_B2), 1)
    poly_E3 = np.polyfit(np.log10(N), np.log10(error_E3), 1)

    pl.loglog(N, error_B1, '-o', label=r'$B_x$')
    pl.loglog(N, error_B2, '-o', label=r'$B_y$')
    pl.loglog(N, error_E3, '-o', label=r'$E_z$')
    pl.loglog(N,
              error_B1[0] * 32**2 / N**2,
              '--',
              color='black',
              label=r'$O(N^{-2})$')
    pl.xlabel(r'$N$')
    pl.ylabel('Error')
    pl.legend()
    pl.savefig('convergenceplot.png')

    assert (abs(poly_B1[0] + 1) < 0.2)
    assert (abs(poly_B2[0] + 1) < 0.2)
    assert (abs(poly_E3[0] + 1) < 0.2)
Exemple #32
0
def initialize_f(q1, q2, p1, p2, p3, params):
    f = af.select(af.abs(p1)<2.5, q1**0 * p1**0, 0)
    af.eval(f)
    return (f)
Exemple #33
0
def test_fdtd_mode2_mirror():

    N = 2**np.arange(5, 11)

    error_E1 = np.zeros(N.size)
    error_E2 = np.zeros(N.size)
    error_B3 = np.zeros(N.size)

    for i in range(N.size):

        dt = (1 / int(N[i])) * 1 / 2
        time = np.arange(dt, 4 * 1 + dt, dt)

        params.dt = dt

        obj = test_mirror(N[i], initialize_fdtd_mode2, params)
        N_g = obj.fields_solver.N_g

        E1_initial = obj.fields_solver.yee_grid_EM_fields[0].copy()
        E2_initial = obj.fields_solver.yee_grid_EM_fields[1].copy()
        B3_initial = obj.fields_solver.yee_grid_EM_fields[5].copy()

        for time_index, t0 in enumerate(time):

            # pl.subplot(3, 1, 1)
            # pl.gca().axes.xaxis.set_ticklabels([])
            # pl.gca().axes.yaxis.set_ticklabels([])
            # pl.title(r'$E_x$')
            # pl.contourf(np.array(obj.fields_solver.q1_center).reshape(38, 38),
            #             np.array(obj.fields_solver.q2_center).reshape(38, 38),
            #             np.array(obj.fields_solver.yee_grid_EM_fields[0, :, :, :]).reshape(38, 38),
            #             100
            #            )

            # pl.subplot(3, 1, 2)
            # pl.gca().axes.xaxis.set_ticklabels([])
            # pl.gca().axes.yaxis.set_ticklabels([])
            # pl.title(r'$E_y$')
            # pl.contourf(np.array(obj.fields_solver.q1_center).reshape(38, 38),
            #             np.array(obj.fields_solver.q2_center).reshape(38, 38),
            #             np.array(obj.fields_solver.yee_grid_EM_fields[1, :, :, :]).reshape(38, 38),
            #             100
            #            )

            # pl.subplot(3, 1, 3)
            # pl.title(r'$B_z$')
            # pl.contourf(np.array(obj.fields_solver.q1_center).reshape(38, 38),
            #             np.array(obj.fields_solver.q2_center).reshape(38, 38),
            #             np.array(obj.fields_solver.yee_grid_EM_fields[5, :, :, :]).reshape(38, 38),
            #             100
            #            )
            # pl.xlabel(r'$x$')
            # pl.ylabel(r'$y$')
            # pl.savefig('images/%04d'%time_index + '.png')
            # pl.clf()

            J1 = J2 = J3 = 0 * obj.fields_solver.q1_center**0
            obj.fields_solver.evolve_electrodynamic_fields(J1, J2, J3, dt)

        error_E1[i] = af.sum(
            af.abs(obj.fields_solver.yee_grid_EM_fields[0, :, N_g:-N_g,
                                                        N_g:-N_g] -
                   E1_initial[:, :, N_g:-N_g, N_g:-N_g])) / (
                       E1_initial.elements())

        error_E2[i] = af.sum(
            af.abs(obj.fields_solver.yee_grid_EM_fields[1, :, N_g:-N_g,
                                                        N_g:-N_g] -
                   E2_initial[:, :, N_g:-N_g, N_g:-N_g])) / (
                       E2_initial.elements())

        error_B3[i] = af.sum(
            af.abs(obj.fields_solver.yee_grid_EM_fields[5, :, N_g:-N_g,
                                                        N_g:-N_g] -
                   B3_initial[:, :, N_g:-N_g, N_g:-N_g])) / (
                       B3_initial.elements())

    poly_E1 = np.polyfit(np.log10(N), np.log10(error_E1), 1)
    poly_E2 = np.polyfit(np.log10(N), np.log10(error_E2), 1)
    poly_B3 = np.polyfit(np.log10(N), np.log10(error_B3), 1)

    print(error_E1)
    print(error_E2)
    print(error_B3)

    print(poly_E1)
    print(poly_E2)
    print(poly_B3)

    pl.loglog(N, error_E1, '-o', label=r'$E_x$')
    pl.loglog(N, error_E2, '-o', label=r'$E_y$')
    pl.loglog(N, error_B3, '-o', label=r'$B_z$')
    pl.loglog(N,
              error_B3[0] * N[0]**2 / N**2,
              '--',
              color='black',
              label=r'$\mathcal{O}(N^{-2})$')
    pl.xlabel(r'$N$')
    pl.ylabel('Error')
    pl.legend(framealpha=0)
    pl.savefig('convergenceplot.png', bbox_inches='tight')

    assert (abs(poly_E1[0] + 2) < 0.4)
    assert (abs(poly_E2[0] + 2) < 0.4)
    assert (abs(poly_B3[0] + 2) < 0.4)
Exemple #34
0
 def __abs__(self):
     s = arrayfire.abs(self.d_array)
     # dtype is wrong for complex types
     return ndarray(self.shape, dtype=pu.typemap(s.dtype()), af_array=s)
Exemple #35
0
def reconstruct_weno5(input_array, axis):
    """
    Reconstructs the input array using a WENO5 reconstruction.

    Parameters
    ----------
    
    input_array: af.Array
                 Array holding the cells data.
    
    axis: int
          Axis along which the reconstruction method is to be applied.
    """

    eps = 1e-17

    if (axis == 0):

        x0_shift = 2
        y0_shift = 0
        z0_shift = 0
        w0_shift = 0
        x1_shift = 1
        y1_shift = 0
        z1_shift = 0
        w1_shift = 0
        x3_shift = -1
        y3_shift = 0
        z3_shift = 0
        w3_shift = 0
        x4_shift = -2
        y4_shift = 0
        z4_shift = 0
        w4_shift = 0

    elif (axis == 1):

        x0_shift = 0
        y0_shift = 2
        z0_shift = 0
        w0_shift = 0
        x1_shift = 0
        y1_shift = 1
        z1_shift = 0
        w1_shift = 0
        x3_shift = 0
        y3_shift = -1
        z3_shift = 0
        w3_shift = 0
        x4_shift = 0
        y4_shift = -2
        z4_shift = 0
        w4_shift = 0

    elif (axis == 2):

        x0_shift = 0
        y0_shift = 0
        z0_shift = 2
        w0_shift = 0
        x1_shift = 0
        y1_shift = 0
        z1_shift = 1
        w1_shift = 0
        x3_shift = 0
        y3_shift = 0
        z3_shift = -1
        w3_shift = 0
        x4_shift = 0
        y4_shift = 0
        z4_shift = -2
        w4_shift = 0

    elif (axis == 3):

        x0_shift = 0
        y0_shift = 0
        z0_shift = 0
        w0_shift = 2
        x1_shift = 0
        y1_shift = 0
        z1_shift = 0
        w1_shift = 1
        x3_shift = 0
        y3_shift = 0
        z3_shift = 0
        w3_shift = -1
        x4_shift = 0
        y4_shift = 0
        z4_shift = 0
        w4_shift = -2

    else:
        raise Exception('Invalid choice for axis')

    y0 = af.shift(input_array, x0_shift, y0_shift, z0_shift, w0_shift)
    y1 = af.shift(input_array, x1_shift, y1_shift, z1_shift, w1_shift)
    y2 = input_array
    y3 = af.shift(input_array, x3_shift, y3_shift, z3_shift, w3_shift)
    y4 = af.shift(input_array, x4_shift, y4_shift, z4_shift, w4_shift)

    # Compute smoothness operators
    beta1 = ((4 / 3) * y0 * y0 - (19 / 3) * y0 * y1 + (25 / 3) * y1 * y1 +
             (11 / 3) * y0 * y2 - (31 / 3) * y1 * y2 + (10 / 3) * y2 *
             y2) + eps * (1.0 + af.abs(y0) + af.abs(y1) + af.abs(y2))

    beta2 = ((4 / 3) * y1 * y1 - (19 / 3) * y1 * y2 + (25 / 3) * y2 * y2 +
             (11 / 3) * y1 * y3 - (31 / 3) * y2 * y3 + (10 / 3) * y3 *
             y3) + eps * (1.0 + af.abs(y1) + af.abs(y2) + af.abs(y3))

    beta3 = ((4 / 3) * y2 * y2 - (19 / 3) * y2 * y3 + (25 / 3) * y3 * y3 +
             (11 / 3) * y2 * y4 - (31 / 3) * y3 * y4 + (10 / 3) * y4 *
             y4) + eps * (1.0 + af.abs(y2) + af.abs(y3) + af.abs(y4))

    # Compute weights
    w1r = 1 / (16 * beta1 * beta1)
    w2r = 5 / (8 * beta2 * beta2)
    w3r = 5 / (16 * beta3 * beta3)

    w1l = 5 / (16 * beta1 * beta1)
    w2l = 5 / (8 * beta2 * beta2)
    w3l = 1 / (16 * beta3 * beta3)

    denl = w1l + w2l + w3l
    denr = w1r + w2r + w3r

    # Substencil Interpolations
    u1r = 0.375 * y0 - 1.25 * y1 + 1.875 * y2
    u2r = -0.125 * y1 + 0.75 * y2 + 0.375 * y3
    u3r = 0.375 * y2 + 0.75 * y3 - 0.125 * y4

    u1l = -0.125 * y0 + 0.75 * y1 + 0.375 * y2
    u2l = 0.375 * y1 + 0.75 * y2 - 0.125 * y3
    u3l = 1.875 * y2 - 1.25 * y3 + 0.375 * y4

    # Reconstruction:
    left_value = (w1l * u1l + w2l * u2l + w3l * u3l) / denl
    right_value = (w1r * u1r + w2r * u2r + w3r * u3r) / denr

    return (left_value, right_value)
Exemple #36
0
dt = min(dt_fvm, dt_fdtd)
params.dt = dt

# Defining the physical system to be solved:
system = physical_system(domain, boundary_conditions, params, initialize,
                         advection_terms, collision_operator.BGK, moments)

# Declaring a linear system object which will evolve the defined physical system:
nls = nonlinear_solver(system)
N_g = nls.N_ghost

print('Minimum Value of f_e:', af.min(nls.f[:, 0]))
print('Minimum Value of f_i:', af.min(nls.f[:, 1]))

print('Error in density_e:',
      af.mean(af.abs(nls.compute_moments('density')[:, 0] - 1)))
print('Error in density_i:',
      af.mean(af.abs(nls.compute_moments('density')[:, 1] - 1)))

v2_bulk = nls.compute_moments('mom_v2_bulk') / nls.compute_moments('density')
v3_bulk = nls.compute_moments('mom_v3_bulk') / nls.compute_moments('density')

v2_bulk_i =   params.amplitude * -4.801714581503802e-15 * af.cos(params.k_q1 * nls.q1_center) \
            - params.amplitude * -0.3692429960259134 * af.sin(params.k_q1 * nls.q1_center)

v2_bulk_e =   params.amplitude * -4.85722573273506e-15 * af.cos(params.k_q1 * nls.q1_center) \
            - params.amplitude * - 0.333061857862197* af.sin(params.k_q1 * nls.q1_center)

v3_bulk_i =   params.amplitude * -0.3692429960259359 * af.cos(params.k_q1 * nls.q1_center) \
            - params.amplitude * 1.8041124150158794e-16  * af.sin(params.k_q1 * nls.q1_center)
 def __abs__(self):
     s = arrayfire.abs(self.d_array)
     # dtype is wrong for complex types
     return ndarray(self.shape, dtype=pu.typemap(s.dtype()), af_array=s)