Exemple #1
0
    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)
Exemple #2
0
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)
Exemple #3
0
def calculate_p_center(p1_start, p2_start, p3_start,
                       N_p1, N_p2, N_p3,
                       dp1, dp2, dp3, 
                      ):
    """
    Initializes the cannonical variables p1, p2 and p3 using a centered
    formulation.
    """
    p1_center = af.constant(0, N_p1 * N_p2 * N_p3, len(p1_start), dtype = af.Dtype.f64)
    p2_center = af.constant(0, N_p1 * N_p2 * N_p3, len(p2_start), dtype = af.Dtype.f64)
    p3_center = af.constant(0, N_p1 * N_p2 * N_p3, len(p3_start), dtype = af.Dtype.f64)

    # Assigning for each species:
    for i in range(len(p1_start)):

        p1 = p1_start[i] + (0.5 + np.arange(N_p1)) * dp1[i]
        p2 = p2_start[i] + (0.5 + np.arange(N_p2)) * dp2[i]
        p3 = p3_start[i] + (0.5 + np.arange(N_p3)) * dp3[i]
        
        p2_center[:, i] = af.flat(af.to_array(np.meshgrid(p2, p1, p3)[0]))
        p1_center[:, i] = af.flat(af.to_array(np.meshgrid(p2, p1, p3)[1]))
        p3_center[:, i] = af.flat(af.to_array(np.meshgrid(p2, p1, p3)[2]))

    af.eval(p1_center, p2_center, p3_center)
    return (p1_center, p2_center, p3_center)
def grad_q(q, u, v):
    '''
    done - Matching qx qnd qy
    '''
    q = af.moddims(q, params.n, params.n)

    q_x = af.np_to_af_array(np.zeros([params.n, params.n]))
    q_y = af.np_to_af_array(np.zeros([params.n, params.n]))

    q_x[1:-1, 1:-1] = (q[:-2, 1:-1] - q[2:, 1:-1]) * (params.n - 1) / 2.0
    q_y[1:-1, 1:-1] = (q[1:-1, :-2] - q[1:-1, 2:]) * (params.n - 1) / 2.0

    # Horizontal boundary conditions, qx = 0
    q_y[0, 1:-1] = (q[0, :-2] - q[0, 2:]) * (params.n - 1) / 2.0
    q_y[-1, 1:-1] = (q[-1, :-2] - q[-1, 2:]) * (params.n - 1) / 2.0

    # Vertical boundary conditions, qy = 0
    q_x[1:-1, 0] = (q[:-2, 0] - q[2:, 0]) * (params.n - 1) / 2.0
    q_x[1:-1, -1] = (q[:-2, -1] - q[2:, -1]) * (params.n - 1) / 2.0
    #UNEXPLAINED SWITCHING in the second part of numerator in octave

    q_x = af.flat(q_x)
    q_y = af.flat(q_y)

    return q_x, q_y
def calculate_dfdp_background(self):
    """
    Calculates the derivative of the background distribution 
    with respect to the variables p1, p2, p3. This is used to
    solve for the contribution from the fields
    """
    f_b = af.moddims(self.f_background, self.N_p1, self.N_p2, self.N_p3)

    # Using a 4th order central difference stencil:
    dfdp1_background = (-af.shift(f_b, -2) + 8 * af.shift(f_b, -1) + af.shift(
        f_b, 2) - 8 * af.shift(f_b, 1)) / (12 * self.dp1)

    dfdp2_background = (-af.shift(f_b, 0, -2) + 8 * af.shift(f_b, 0, -1) +
                        af.shift(f_b, 0, 2) -
                        8 * af.shift(f_b, 0, 1)) / (12 * self.dp2)

    dfdp3_background = (-af.shift(f_b, 0, 0, -2) +
                        8 * af.shift(f_b, 0, 0, -1) + af.shift(f_b, 0, 0, 2) -
                        8 * af.shift(f_b, 0, 0, 1)) / (12 * self.dp3)

    # Reordering such that the variations in velocity are along axis 2
    self.dfdp1_background = af.reorder(af.flat(dfdp1_background), 2, 3, 0, 1)
    self.dfdp2_background = af.reorder(af.flat(dfdp2_background), 2, 3, 0, 1)
    self.dfdp3_background = af.reorder(af.flat(dfdp3_background), 2, 3, 0, 1)

    af.eval(self.dfdp1_background, self.dfdp2_background,
            self.dfdp3_background)

    return
Exemple #6
0
def test_calculate_p():
    obj = test()

    p1, p2, p3 = calculate_p(obj)

    p1_expected = obj.p1_start + (0.5 + np.arange(obj.N_p1)) * obj.dp1
    p2_expected = obj.p2_start + (0.5 + np.arange(obj.N_p2)) * obj.dp2
    p3_expected = obj.p3_start + (0.5 + np.arange(obj.N_p3)) * obj.dp3

    p2_expected, p1_expected, p3_expected = np.meshgrid(p2_expected,
                                                        p1_expected,
                                                        p3_expected
                                                       )
    
    p1_expected = af.reorder(af.flat(af.to_array(p1_expected)),
                             2, 3, 0, 1
                            )
                          
    p2_expected = af.reorder(af.flat(af.to_array(p2_expected)),
                             2, 3, 0, 1
                            )
                         
    p3_expected = af.reorder(af.flat(af.to_array(p3_expected)),
                             2, 3, 0, 1
                            )

    assert(af.sum(af.abs(p1_expected - p1)) == 0)
    assert(af.sum(af.abs(p2_expected - p2)) == 0)
    assert(af.sum(af.abs(p3_expected - p3)) == 0)
Exemple #7
0
def dump_coordinate_info(self, arrays, name, file_name):

    self._da_coord_arrays = PETSc.DMDA().create(
        [self.N_q1, self.N_q2],
        dof=len(arrays),
        proc_sizes=(self._nproc_in_q1, self._nproc_in_q2),
        ownership_ranges=self._ownership_ranges,
        comm=self._comm)
    self._glob_coord = self._da_coord_arrays.createGlobalVec()
    self._glob_coord_array = self._glob_coord.getArray()

    N_g = self.N_ghost

    for i in range(len(arrays)):
        if (i == 0):
            array_to_dump = arrays[0][:, :, N_g:-N_g, N_g:-N_g]
        else:
            array_to_dump = af.join(0, array_to_dump, arrays[i][:, :, N_g:-N_g,
                                                                N_g:-N_g])
    af.flat(array_to_dump).to_ndarray(self._glob_coord_array)
    PETSc.Object.setName(self._glob_coord, name)
    viewer = PETSc.Viewer().createBinary(file_name + '.bin',
                                         'w',
                                         comm=self._comm)
    viewer(self._glob_coord)
Exemple #8
0
    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(0, self.N_p1, 1)) * self.dp1
        
        p2_center = \
            self.p2_start + (0.5 + np.arange(0, self.N_p2, 1)) * self.dp2
        
        p3_center = \
            self.p3_start + (0.5 + np.arange(0, self.N_p3, 1)) * self.dp3

        p2_center, p1_center, p3_center = np.meshgrid(p2_center,
                                                      p1_center,
                                                      p3_center
                                                     )

        # Flattening the obtained 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))

        # Reordering such that variation in velocity is along axis 2:
        # This is done to be consistent with the positionsExpanded form:
        p1_center = af.reorder(p1_center, 2, 3, 0, 1)
        p2_center = af.reorder(p2_center, 2, 3, 0, 1)
        p3_center = af.reorder(p3_center, 2, 3, 0, 1)

        af.eval(p1_center, p2_center, p3_center)
        return(p1_center, p2_center, p3_center)
Exemple #9
0
    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)
Exemple #10
0
def communicate_fields(self, on_fdtd_grid=False):
    """
    Used in communicating the values at the boundary zones for each of
    the local vectors among all procs.This routine is called to take care
    of communication(and periodic B.C's) procedures for the EM field
    arrays. The function is used for communicating the EM field values 
    on the cell centered grid  which is used by default. Additionally,it can
    also be used to communicate the values on the Yee-grid which is used by the FDTD solver.
    """
    if (self.performance_test_flag == True):
        tic = af.time()

    # Obtaining start coordinates for the local zone
    # Additionally, we also obtain the size of the local zone
    ((i_q1_start, i_q2_start), (N_q1_local,
                                N_q2_local)) = self._da_fields.getCorners()

    N_g = self.N_g

    # Assigning the values of the af.Array
    # fields quantities to the PETSc.Vec:

    if (on_fdtd_grid is True):
        flattened_global_EM_fields_array = \
            af.flat(self.yee_grid_EM_fields[:, :, N_g:-N_g, N_g:-N_g])
        flattened_global_EM_fields_array.to_ndarray(self._glob_fields_array)

    else:
        flattened_global_EM_fields_array = \
            af.flat(self.cell_centered_EM_fields[:, :, N_g:-N_g, N_g:-N_g])
        flattened_global_EM_fields_array.to_ndarray(self._glob_fields_array)

    # Takes care of boundary conditions and interzonal communications:
    self._da_fields.globalToLocal(self._glob_fields, self._local_fields)

    # Converting back to af.Array
    if (on_fdtd_grid is True):

        self.yee_grid_EM_fields = af.moddims(
            af.to_array(self._local_fields_array), 6, 1, N_q1_local + 2 * N_g,
            N_q2_local + 2 * N_g)

        af.eval(self.yee_grid_EM_fields)

    else:

        self.cell_centered_EM_fields = af.moddims(
            af.to_array(self._local_fields_array), 6, 1, N_q1_local + 2 * N_g,
            N_q2_local + 2 * N_g)

        af.eval(self.cell_centered_EM_fields)

    if (self.performance_test_flag == True):
        af.sync()
        toc = af.time()
        self.time_communicate_fields += toc - tic

    return
Exemple #11
0
def dump_moments(self, file_name):
    """
    This function is used to dump variables to a file for later usage.

    Parameters
    ----------

    file_name : str
                The variables will be dumped to this provided file name.

    Returns
    -------

    This function returns None. However it creates a file 'file_name.h5',
    containing all the moments that were defined under moments_defs in
    physical_system.

    Examples
    --------

    >> solver.dump_variables('boltzmann_moments_dump')

    The above set of statements will create a HDF5 file which contains the
    all the moments which have been defined in the physical_system object.
    The data is always stored with the key 'moments' inside the HDF5 file.
    Suppose 'density' and 'energy' are two these moments, and are declared
    the first and second in the moment_exponents object:

    These variables can then be accessed from the file using
    
    >> import h5py
    
    >> h5f = h5py.File('boltzmann_moments_dump.h5', 'r')
    
    >> rho = h5f['moments'][:][:, :, 0]
    
    >> E   = h5f['moments'][:][:, :, 1]
    
    >> h5f.close()
    """
    N_g = self.N_ghost

    i = 0
    for key in self.physical_system.moment_exponents:
        if (i == 0):
            array_to_dump = self.compute_moments(key)[:, N_g:-N_g, N_g:-N_g]
        else:
            array_to_dump = af.join(
                0, array_to_dump,
                self.compute_moments(key)[:, N_g:-N_g, N_g:-N_g])
        i += 1

    af.flat(array_to_dump).to_ndarray(self._glob_moments_array)
    PETSc.Object.setName(self._glob_moments, 'moments')
    viewer = PETSc.Viewer().createHDF5(file_name + '.h5', 'w', comm=self._comm)
    viewer(self._glob_moments)
Exemple #12
0
def communicate_f(self):
    """
    Used in communicating the values at the boundary zones
    for each of the local vectors among all procs.
    This routine is called to take care of communication
    (and periodic B.C's) procedures for the distribution
    function array.
    """
    if (self.performance_test_flag == True):
        tic = af.time()

    # Obtaining start coordinates for the local zone
    # Additionally, we also obtain the size of the local zone
    ((i_q1_start, i_q2_start), (N_q1_local,
                                N_q2_local)) = self._da_f.getCorners()

    N_g_q = self.N_ghost_q
    N_g_p = self.N_ghost_p

    # Assigning the local array only when Dirichlet
    # boundary conditions are applied. This is needed since
    # only inflowing characteristics are to be changed by
    # the apply boundary conditions function.

    if (self.boundary_conditions.in_q1_left == 'dirichlet'
            or self.boundary_conditions.in_q1_right == 'dirichlet'
            or self.boundary_conditions.in_q2_bottom == 'dirichlet'
            or self.boundary_conditions.in_q2_top == 'dirichlet'):
        af.flat(self.f).to_ndarray(self._local_f_array)

    # Global value is non-inclusive of the ghost-zones:
    af.flat(self.f[:, :, N_g_q:-N_g_q,
                   N_g_q:-N_g_q]).to_ndarray(self._glob_f_array)

    # The following function takes care of interzonal communications
    # Additionally, it also automatically applies periodic BCs when necessary
    self._da_f.globalToLocal(self._glob_f, self._local_f)

    # Converting back from PETSc.Vec to af.Array:
    f_flattened = af.to_array(self._local_f_array)
    self.f = af.moddims(f_flattened, (self.N_p1 + 2 * N_g_p) *
                        (self.N_p2 + 2 * N_g_p) * (self.N_p3 + 2 * N_g_p),
                        self.N_species, N_q1_local + 2 * N_g_q,
                        N_q2_local + 2 * N_g_q)

    af.eval(self.f)

    if (self.performance_test_flag == True):
        af.sync()
        toc = af.time()
        self.time_communicate_f += toc - tic

    return
Exemple #13
0
    def __init__(self):
        self.physical_system = type('obj', (object, ), {
            'moment_exponents': moment_exponents,
            'moment_coeffs': moment_coeffs
        })
        self.p1_start = -10
        self.p2_start = -10
        self.p3_start = -10

        self.N_p1 = 32
        self.N_p2 = 32
        self.N_p3 = 32

        self.dp1 = (-2 * self.p1_start) / self.N_p1
        self.dp2 = (-2 * self.p2_start) / self.N_p2
        self.dp3 = (-2 * self.p3_start) / self.N_p3

        self.N_q1 = 16
        self.N_q2 = 16

        self.N_ghost = 3

        self.p1 = self.p1_start + (0.5 + np.arange(self.N_p1)) * self.dp1
        self.p2 = self.p2_start + (0.5 + np.arange(self.N_p2)) * self.dp2
        self.p3 = self.p3_start + (0.5 + np.arange(self.N_p3)) * self.dp3

        self.p2, self.p1, self.p3 = np.meshgrid(self.p2, self.p1, self.p3)

        self.p1 = af.flat(af.to_array(self.p1))
        self.p2 = af.flat(af.to_array(self.p2))
        self.p3 = af.flat(af.to_array(self.p3))

        self.q1 = (-self.N_ghost + 0.5 +
                   np.arange(self.N_q1 + 2 * self.N_ghost)) / self.N_q1

        self.q2 = (-self.N_ghost + 0.5 +
                   np.arange(self.N_q2 + 2 * self.N_ghost)) / self.N_q2

        self.q2, self.q1 = np.meshgrid(self.q2, self.q1)

        self.q1 = af.reorder(af.to_array(self.q1), 2, 0, 1)
        self.q2 = af.reorder(af.to_array(self.q2), 2, 0, 1)

        rho = (1 + 0.01 * af.sin(2 * np.pi * self.q1 + 4 * np.pi * self.q2))
        T = (1 + 0.01 * af.cos(2 * np.pi * self.q1 + 4 * np.pi * self.q2))

        p1_b = 0.01 * af.exp(-10 * self.q1**2 - 10 * self.q2**2)
        p2_b = 0.01 * af.exp(-10 * self.q1**2 - 10 * self.q2**2)
        p3_b = 0.01 * af.exp(-10 * self.q1**2 - 10 * self.q2**2)

        self.f = maxwell_boltzmann(rho, T, p1_b, p2_b, p3_b, self.p1, self.p2,
                                   self.p3)
def log_loss(y_true, y_prob):
    """Compute Logistic loss for classification.
    Parameters
    ----------
    y_true : array-like or label indicator matrix
        Ground truth (correct) labels.
    y_prob : array-like of float, shape = (n_samples, n_classes)
        Predicted probabilities, as returned by a classifier's
        predict_proba method.
    Returns
    -------
    loss : float
        The degree to which the samples are correctly predicted.
    """
#    eps = np.finfo(y_prob.dtype).eps
#    y_prob = np.clip(y_prob, eps, 1 - eps)
#    if y_prob.shape[1] == 1:
#        y_prob = np.append(1 - y_prob, y_prob, axis=1)
#
#    if y_true.shape[1] == 1:
#        y_true = np.append(1 - y_true, y_true, axis=1)
#
#    return - xlogy(y_true, y_prob).sum() / y_prob.shape[0]

    eps = numpy.finfo(typemap(y_prob.dtype())).eps
    y_prob[y_prob < eps] = eps
    y_prob[y_prob > (1.0 - eps)] = 1.0 - eps

    if y_prob.numdims() == 1:
        y_prob = af.join(1, (1.0 - y_prob).as_type(y_prob.dtype()), y_prob)

    if y_true.numdims() == 1:
        y_true = af.join(1, (1.0 - y_true).as_type(y_true.dtype()), y_true)

    return - af.sum(af.flat(xlogy(y_true, y_prob))) / y_prob.shape[0]
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)
Exemple #16
0
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)
Exemple #17
0
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)))
Exemple #18
0
def dump_distribution_function(self, file_name):
    """
    This function is used to dump distribution function to a file for
    later usage.This dumps the complete 5D distribution function which
    can be used for post-processing

    Parameters
    ----------

    file_name : The distribution_function array will be dumped to this
                provided file name.

    Returns
    -------

    This function returns None. However it creates a file 'file_name.h5',
    containing the data of the distribution function

    Examples
    --------
    
    >> solver.dump_distribution_function('distribution_function')

    The above statement will create a HDF5 file which contains the
    distribution function. The data is always stored with the key 
    'distribution_function'

    This can later be accessed using

    >> import h5py
    
    >> h5f = h5py.File('distribution_function', 'r')
    
    >> f   = h5f['distribution_function'][:]
    
    >> h5f.close()
    """
    N_g = self.N_ghost

    af.flat(self.f[:, N_g:-N_g, N_g:-N_g]).to_ndarray(self._glob_f_array)
    PETSc.Object.setName(self._glob_f, 'distribution_function')
    viewer = PETSc.Viewer().createHDF5(file_name + '.h5', 'w', comm=self._comm)
    viewer(self._glob_f)

    return
def projection_step(u, v, A_projection):

    N_squared = params.n**2
    u_boundary_condition, v_boundary_condition = add_boundary_conditions(u, v)
    q = projection_step_poisson(u_boundary_condition, v_boundary_condition,
                                A_projection)
    gradient_q = grad_q(q, u, v)

    u_boundary_condition = af.flat(u_boundary_condition)
    v_boundary_condition = af.flat(v_boundary_condition)

    u4 = u_boundary_condition - gradient_q[0]
    v4 = v_boundary_condition - gradient_q[1]

    u4 = af.flat(af.moddims(u4, params.n, params.n)[1:-1, 1:-1])
    v4 = af.flat(af.moddims(v4, params.n, params.n)[1:-1, 1:-1])

    return u4, v4
Exemple #20
0
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
Exemple #21
0
def Get_Linear_Equation_Gpu(x,
                            weight,
                            bin_data_num,
                            bin_data_y,
                            r,
                            dtype='f4'):
    n, p = x.shape
    d = p - 1
    if dtype is 'f4':
        dtype = af.Dtype.f32
    elif dtype is 'f8':
        dtype = af.Dtype.f64
    xw = af.constant(0, n, p, dtype=dtype)
    for ii in af.ParallelRange(p):
        xw[:, ii] = x[:, ii] * weight
    s = af.constant(0, p, p, np.prod(bin_data_num.shape), dtype=dtype)
    t = af.constant(0, p, np.prod(bin_data_num.shape), dtype=dtype)
    ker_d = np.ones(4, dtype='int')
    ker_d[:d] = 2 * r + 1
    if d is 4:
        for i in range(p):
            for j in range(i, p):
                if i is 0:
                    kernel = af.moddims(xw[:, j], ker_d[0], ker_d[1], ker_d[2],
                                        ker_d[3])
                    t[j] = af.flat(
                        af.reorder(Convolve4(bin_data_y, kernel), 3, 2, 1, 0))
                else:
                    kernel = af.moddims(xw[:, i] * x[:, j], ker_d[0], ker_d[1],
                                        ker_d[2], ker_d[3])
                s[i, j] = af.flat(
                    af.reorder(Convolve4(bin_data_num, kernel), 3, 2, 1, 0))
                s[j, i] = s[i, j]
    elif d < 4:
        for i in range(p):
            for j in range(i, p):
                if i is 0:
                    kernel = af.moddims(xw[:, j], ker_d[0], ker_d[1], ker_d[2],
                                        ker_d[3])
                    if kernel.elements() is 1:
                        t[j] = af.flat((bin_data_y * kernel.to_list()[0]).T)
                    else:
                        t[j] = af.flat(af.fft_convolve(bin_data_y, kernel).T)
                else:
                    kernel = af.moddims(xw[:, i] * x[:, j], ker_d[0], ker_d[1],
                                        ker_d[2], ker_d[3])
                if kernel.elements() is 1:
                    s[i, j] = af.flat((bin_data_num * kernel.to_list()[0]).T)
                else:
                    s[i, j] = af.flat(af.fft_convolve(bin_data_num, kernel).T)
                s[j, i] = s[i, j]
    for i in range(1, p):
        s[i, i] += 1e-12
    return ([
        np.array(s).reshape(p**2, -1).T.reshape(-1, p, p),
        np.array(af.flat(t))
    ])
def squared_loss(y_true, y_pred):
    """Compute the squared loss for regression.
    Parameters
    ----------
    y_true : array-like or label indicator matrix
        Ground truth (correct) values.
    y_pred : array-like or label indicator matrix
        Predicted values, as returned by a regression estimator.
    Returns
    -------
    loss : float
        The degree to which the samples are correctly predicted.
    """
    return af.mean(af.flat((y_true - y_pred) ** 2)) / 2
Exemple #23
0
 def predict(self, X):
     near_locs, near_dists = af.vision.nearest_neighbour(X, self._data, self._dim, \
                                                         self._num_nearest, self._match_type)
     weights = self._get_neighbor_weights(near_dists)
     top_labels = af.moddims(self._labels[near_locs], \
                             get_dims(near_locs)[0], get_dims(near_locs)[1])
     accum_weights = af.scan_by_key(
         top_labels, weights)  # reduce by key would be more ideal
     _, max_weight_locs = af.imax(accum_weights, dim=0)
     pred_idxs = af.range(get_dims(accum_weights)[1]) * get_dims(
         accum_weights)[0] + max_weight_locs.T
     top_labels_flat = af.flat(top_labels)
     pred_classes = top_labels_flat[pred_idxs]
     return pred_classes
Exemple #24
0
    def __init__(self, N):
        self.p_dim = 3

        self.p1_start = -10
        self.p2_start = -10
        self.p3_start = -10

        self.p1_end = 10
        self.p2_end = 10
        self.p3_end = 10

        self.N_p1 = N
        self.N_p2 = N
        self.N_p3 = N

        self.dp1 = (self.p1_end - self.p1_start) / self.N_p1
        self.dp2 = (self.p2_end - self.p2_start) / self.N_p2
        self.dp3 = (self.p3_end - self.p3_start) / self.N_p3

        self.p1 = self.p1_start + (0.5 + np.arange(self.N_p1)) * self.dp1
        self.p2 = self.p2_start + (0.5 + np.arange(self.N_p2)) * self.dp2
        self.p3 = self.p3_start + (0.5 + np.arange(self.N_p3)) * self.dp3

        self.p2, self.p1, self.p3 = np.meshgrid(self.p2, self.p1, self.p3)

        self.p1, self.p2, self.p3 = af.to_array(self.p1),\
                                    af.to_array(self.p2),\
                                    af.to_array(self.p3)

        self.p1 = af.reorder(af.flat(self.p1), 2, 3, 0, 1)
        self.p2 = af.reorder(af.flat(self.p2), 2, 3, 0, 1)
        self.p3 = af.reorder(af.flat(self.p3), 2, 3, 0, 1)


        self.f_background =   af.exp(-self.p1**2) \
                            * af.exp(-self.p2**2) \
                            * af.exp(-self.p3**2)
Exemple #25
0
def af_to_petsc_glob_array(domain_metadata, af_array, glob_array):

    # domaint_metadata obj should contain the following
    i_q1_start = domain_metadata.i_q1_start  # start index of bulk domain
    i_q1_end = domain_metadata.i_q1_end  # end index, before ghost zones

    i_q2_start = domain_metadata.i_q2_start
    i_q2_end = domain_metadata.i_q2_end

    tmp_array = af.flat(af_array[:, :, i_q1_start:i_q1_end,
                                 i_q2_start:i_q2_end])

    tmp_array.to_ndarray(glob_array)

    return
Exemple #26
0
 def _predict(self, query, train_feats, train_labels, k, dist_type,
              weight_by_dist):
     near_locs, near_dists = af.vision.nearest_neighbour(query, train_feats, 1, \
                                                         k, dist_type)
     weights = self._get_neighbor_weights(near_dists, weight_by_dist, k)
     top_labels = af.moddims(train_labels[near_locs], \
                             near_locs.dims()[0], near_locs.dims()[1])
     accum_weights = af.scan_by_key(
         top_labels, weights)  # reduce by key would be more ideal
     _, max_weight_locs = af.imax(accum_weights, dim=0)
     pred_idxs = af.range(accum_weights.dims()
                          [1]) * accum_weights.dims()[0] + max_weight_locs.T
     top_labels_flat = af.flat(top_labels)
     pred_classes = top_labels_flat[pred_idxs]
     return pred_classes
Exemple #27
0
def calculate_p_corner(p1_start, p2_start, p3_start,
                       N_p1, N_p2, N_p3,
                       dp1, dp2, dp3, 
                      ):
    """
    Initializes the cannonical variables p1, p2 and p3 at the corners of the
    momentum space grid zone
    """
    p1_corner = af.constant(0, N_p1 * N_p2 * N_p3, len(p1_start), dtype = af.Dtype.f64)
    p2_corner = af.constant(0, N_p1 * N_p2 * N_p3, len(p2_start), dtype = af.Dtype.f64)
    p3_corner = af.constant(0, N_p1 * N_p2 * N_p3, len(p3_start), dtype = af.Dtype.f64)

    # Assigning for each species:
    for i in range(len(p1_start)):

        p1 = p1_start[i] + (np.arange(N_p1)) * dp1[i]
        p2 = p2_start[i] + (np.arange(N_p2)) * dp2[i]
        p3 = p3_start[i] + (np.arange(N_p3)) * dp3[i]
        
        p2_corner[:, i] = af.flat(af.to_array(np.meshgrid(p2, p1, p3)[0]))
        p1_corner[:, i] = af.flat(af.to_array(np.meshgrid(p2, p1, p3)[1]))
        p3_corner[:, i] = af.flat(af.to_array(np.meshgrid(p2, p1, p3)[2]))

    return (p1_corner, p2_corner, p3_corner)
Exemple #28
0
def gauss_quad_multivar_poly(poly_xi_eta, N_quad, advec_var):
    '''
    '''
    shape_poly_2d = poly_xi_eta.shape
    xi_gauss      = advec_var.gauss_points

    Xi  = af.flat(af.transpose(af.tile(xi_gauss, 1, params.N_quad)))
    Eta = af.tile(xi_gauss, params.N_quad)

    w_i = advec_var.gauss_weights

    test_W_i = af.flat(af.transpose(af.tile(w_i, 1, params.N_quad)))
    test_W_j = af.tile(w_i, params.N_quad)

    W_i = af.tile(test_W_i, d0 = 1, d1 = shape_poly_2d[2])
    W_j = af.tile(test_W_j, d0 = 1, d1 = shape_poly_2d[2])

    P_xi_eta_quad_val = af.transpose(multivariable_poly_value(poly_xi_eta,
                                                              Xi, Eta))
    #P_xi_eta_quad_val = af.transpose(polyval_2d(poly_xi_eta, Xi, Eta))

    integral = af.sum(W_i * W_j * P_xi_eta_quad_val, dim = 0)

    return af.transpose(integral)
Exemple #29
0
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
Exemple #30
0
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 test_1V():

    obj = test()

    obj.single_mode_evolution = False

    f_generalized = MB_dist(obj.q1_center, obj.q2_center, obj.p1, obj.p2,
                            obj.p3, 1)

    C_f_hat_generalized = 2 * af.fft2(
        collision_operator.BGK(
            f_generalized, obj.q1_center, obj.q2_center, obj.p1, obj.p2,
            obj.p3, obj.compute_moments,
            obj.physical_system.params)) / (obj.N_q2 * obj.N_q1)

    # Background
    C_f_hat_generalized[0, 0, :] = 0

    # Finding the indices of the mode excited:
    i_q1_max = np.unravel_index(
        af.imax(af.abs(C_f_hat_generalized))[1],
        (obj.N_q1, obj.N_q2, obj.N_p1 * obj.N_p2 * obj.N_p3),
        order='F')[0]

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

    obj.p1 = np.array(af.reorder(obj.p1, 1, 2, 3, 0))
    obj.p2 = np.array(af.reorder(obj.p2, 1, 2, 3, 0))
    obj.p3 = np.array(af.reorder(obj.p3, 1, 2, 3, 0))

    delta_f_hat = 0.01 * (1 / (2 * np.pi))**(1 / 2) \
                       * np.exp(-0.5 * obj.p1**2)

    obj.single_mode_evolution = True

    C_f_hat_single_mode = collision_operator.linearized_BGK(
        delta_f_hat, obj.p1, obj.p2, obj.p3, obj.compute_moments,
        obj.physical_system.params)

    assert (af.mean(
        af.abs(
            af.flat(C_f_hat_generalized[i_q1_max, i_q2_max]) -
            af.to_array(C_f_hat_single_mode.flatten()))) < 1e-14)
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.display(af.upper(a, False))
af.display(af.upper(a, True))
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))

af.print_array(af.upper(a, False))
af.print_array(af.upper(a, True))
Exemple #34
0
 def flat(self):        
     ret = ndarray(self.size, dtype=self.dtype, af_array=arrayfire.flat(self.d_array))
     ret._base = self
     return ret