コード例 #1
0
    def outgoing_spherical_wave_expansion(self, layer_system):
        """The dipole field as an expansion in spherical vector wave functions.

        Args:
            layer_system (smuthi.layers.LayerSystem):   stratified medium

        Returns:
            outgoing smuthi.field_expansion.SphericalWaveExpansion object
        """
        laynum = layer_system.layer_number(self.position[2])
        k = layer_system.refractive_indices[laynum] * self.angular_frequency()
        swe_out = fldex.SphericalWaveExpansion(
            k=k,
            l_max=1,
            m_max=1,
            kind='outgoing',
            reference_point=self.position,
            lower_z=layer_system.lower_zlimit(laynum),
            upper_z=layer_system.upper_zlimit(laynum))
        l = 1
        for tau in range(2):
            for m in range(-1, 2):
                ex, ey, ez = vwf.spherical_vector_wave_function(
                    0, 0, 0, k, 1, tau, l, -m)
                b = 1j * k / np.pi * 1j * self.angular_frequency() * (
                    ex * self.current()[0] + ey * self.current()[1] +
                    ez * self.current()[2])
                swe_out.coefficients[fldex.multi_to_single_index(
                    tau, l, m, 1, 1)] = b

        return swe_out
コード例 #2
0
ファイル: particles.py プロジェクト: shepherdYoung/smuthi
 def relative_difference_Tmatrices(Tmat_s, lmax_s, mmax_s, Tmat_l,
                                   lmax_l, mmax_l):
     n_list_s = np.zeros(len(Tmat_s), dtype=int)
     n_list_l = np.zeros(len(Tmat_s), dtype=int)
     idx = 0
     for tau in range(2):
         for l in range(1, lmax_s + 1):
             for m in range(np.max([-l, -mmax_s]),
                            np.min([l, mmax_s]) + 1):
                 n_list_s[idx] = fldex.multi_to_single_index(
                     tau, l, m, lmax_s, mmax_s)
                 n_list_l[idx] = fldex.multi_to_single_index(
                     tau, l, m, lmax_l, mmax_l)
                 idx += 1
     row, column = np.meshgrid(n_list_s, n_list_s)
     row2, column2 = np.meshgrid(n_list_l, n_list_l)
     TMat_temp = np.zeros([len(Tmat_l), len(Tmat_l)], dtype=complex)
     TMat_temp[row2, column2] = Tmat_s[row, column]
     return np.linalg.norm(Tmat_l - TMat_temp) / np.linalg.norm(Tmat_l)
コード例 #3
0
def test_multi2single_stlm():
    idcs = []
    lmax = 5
    mmax = 5
    count = 0
    for tau in range(2):
        for l in range(1, lmax + 1):
            for m in range(-l, l + 1):
                idcs.append(
                    fldex.multi_to_single_index(tau=tau,
                                                l=l,
                                                m=m,
                                                l_max=lmax,
                                                m_max=mmax))
                count += 1

    assert idcs == list(range(len(idcs)))

    ind_num = fldex.blocksize(lmax, mmax)
    assert count == ind_num

    idcs = []
    lmax = 6
    mmax = 3
    count = 0
    for tau in range(2):
        for l in range(1, lmax + 1):
            mlim = min(l, mmax)
            for m in range(-mlim, mlim + 1):
                idcs.append(
                    fldex.multi_to_single_index(tau=tau,
                                                l=l,
                                                m=m,
                                                l_max=lmax,
                                                m_max=mmax))
                count += 1
    assert idcs == list(range(len(idcs)))

    ind_num = fldex.blocksize(lmax, mmax)
    assert count == ind_num
コード例 #4
0
ファイル: linear_system.py プロジェクト: shepherdYoung/smuthi
 def index(self, i, tau, l, m):
     r"""
     Args:
         i (int):    particle number
         tau (int):    spherical polarization index
         l (int):    multipole degree
         m (int):    multipole order
   
     Returns:
         Position in a system vector that corresponds to the :math:`(\tau, l, m)` coefficient of the i-th particle.
     """
     blocksizes = [
         fldex.blocksize(particle.l_max, particle.m_max)
         for particle in self.particle_list[:i]
     ]
     return sum(blocksizes) + fldex.multi_to_single_index(
         tau, l, m, self.particle_list[i].l_max,
         self.particle_list[i].m_max)
コード例 #5
0
ファイル: t_matrix.py プロジェクト: KMCzajkowski/smuthi
def t_matrix_sphere(k_medium, k_particle, radius, l_max, m_max):
    """T-matrix of a spherical scattering object.

    Args:
        k_medium (float or complex):            Wavenumber in surrounding medium (inverse length unit)
        k_particle (float or complex):          Wavenumber inside sphere (inverse length unit)
        radius (float):                         Radius of sphere (length unit)
        l_max (int):                            Maximal multipole degree
        m_max (int):                            Maximal multipole order
        blocksize (int):                        Total number of index combinations
        multi_to_single_index_map (function):   A function that maps the SVWF indices (tau, l, m) to a single index

    Returns:
         T-matrix as ndarray
    """
    t = np.zeros(
        (fldex.blocksize(l_max, m_max), fldex.blocksize(l_max, m_max)),
        dtype=complex)
    for tau in range(2):
        for m in range(-m_max, m_max + 1):
            for l in range(max(1, abs(m)), l_max + 1):
                n = fldex.multi_to_single_index(tau, l, m, l_max, m_max)
                t[n, n] = mie_coefficient(tau, l, k_medium, k_particle, radius)
    return t
コード例 #6
0
def taxsym_read_tmatrix(filename, l_max, m_max):
    """Export TAXSYM.f90 output to SMUTHI T-matrix.

    .. todo:: feedback to adapt particle m_max to nfmds m_max

    Args:
        filename (str): Name of the file containing the T-matrix output of TAXSYM.f90
        l_max (int):    Maximal multipole degree
        m_max (int):    Maximal multipole order

    Returns:
        T-matrix as numpy.ndarray
    """

    with open(smuthi.nfmds.nfmds_folder + '/TMATFILES/Info' + filename,
              'r') as info_file:
        info_file_lines = info_file.readlines()

    assert 'The scatterer is an axisymmetric particle' in ' '.join(
        info_file_lines)

    for line in info_file_lines:
        if line.split()[0:4] == ['-', 'maximum', 'expansion', 'order,']:
            n_rank = int(line.split()[-1][0:-1])

        if line.split()[0:5] == ['-', 'number', 'of', 'azimuthal', 'modes,']:
            m_rank = int(line.split()[-1][0:-1])

    with open(smuthi.nfmds.nfmds_folder + '/TMATFILES/' + filename,
              'r') as tmat_file:
        tmat_lines = tmat_file.readlines()

    t_nfmds = [[]]
    column_index = 0
    for line in tmat_lines[3:]:
        split_line = line.split()
        for i_entry in range(int(len(split_line) / 2)):
            if column_index == 2 * n_rank:
                t_nfmds.append([])
                column_index = 0
            t_nfmds[-1].append(
                complex(split_line[2 * i_entry]) +
                1j * complex(split_line[2 * i_entry + 1]))
            column_index += 1

    t_matrix = np.zeros(
        (fldex.blocksize(l_max, m_max), fldex.blocksize(l_max, m_max)),
        dtype=complex)

    for m in range(-m_max, m_max + 1):
        n_max_nfmds = n_rank - max(1, abs(m)) + 1
        for tau1 in range(2):
            for l1 in range(max(1, abs(m)), l_max + 1):
                n1 = fldex.multi_to_single_index(tau=tau1,
                                                 l=l1,
                                                 m=m,
                                                 l_max=l_max,
                                                 m_max=m_max)
                l1_nfmds = l1 - max(1, abs(m))
                n1_nfmds = 2 * n_rank * abs(m) + tau1 * n_max_nfmds + l1_nfmds
                for tau2 in range(2):
                    for l2 in range(max(1, abs(m)), l_max + 1):
                        n2 = fldex.multi_to_single_index(tau=tau2,
                                                         l=l2,
                                                         m=m,
                                                         l_max=l_max,
                                                         m_max=m_max)
                        l2_nfmds = l2 - max(1, abs(m))
                        n2_nfmds = tau2 * n_max_nfmds + l2_nfmds
                        if abs(m) <= m_rank:
                            if m >= 0:
                                t_matrix[n1, n2] = t_nfmds[n1_nfmds][n2_nfmds]
                            else:
                                t_matrix[n1,
                                         n2] = t_nfmds[n1_nfmds][n2_nfmds] * (
                                             -1)**(tau1 + tau2)

    return t_matrix
コード例 #7
0
ファイル: linear_system.py プロジェクト: shepherdYoung/smuthi
    def __init__(self,
                 vacuum_wavelength,
                 particle_list,
                 layer_system,
                 k_parallel='default',
                 resolution=None,
                 interpolator_kind='linear'):

        z_list = [particle.position[2] for particle in particle_list]
        assert z_list.count(z_list[0]) == len(z_list)

        CouplingMatrixRadialLookup.__init__(self, vacuum_wavelength,
                                            particle_list, layer_system,
                                            k_parallel, resolution)

        x_array = np.array(
            [particle.position[0] for particle in particle_list])
        y_array = np.array(
            [particle.position[1] for particle in particle_list])

        self.particle_rho_array = np.sqrt(
            (x_array[:, None] - x_array[None, :])**2 +
            (y_array[:, None] - y_array[None, :])**2)
        self.particle_phi_array = np.arctan2(
            y_array[:, None] - y_array[None, :],
            x_array[:, None] - x_array[None, :])

        # contains for each n all positions in the large system arrays that correspond to n:
        self.system_vector_index_list = [[] for i in range(self.blocksize)]

        # same size as system_vector_index_list, contains the according particle numbers:
        self.particle_number_list = [[] for i in range(self.blocksize)]
        self.m_list = [None for i in range(self.blocksize)]
        for i, particle in enumerate(particle_list):
            for m in range(-particle.m_max, particle.m_max + 1):
                for l in range(max(1, abs(m)), particle.l_max + 1):
                    for tau in range(2):
                        n_lookup = fldex.multi_to_single_index(
                            tau=tau,
                            l=l,
                            m=m,
                            l_max=self.l_max,
                            m_max=self.m_max)
                        self.system_vector_index_list[n_lookup].append(
                            self.index(i, tau, l, m))
                        self.particle_number_list[n_lookup].append(i)
                        self.m_list[n_lookup] = m
        for n in range(self.blocksize):
            self.system_vector_index_list[n] = np.array(
                self.system_vector_index_list[n])
            self.particle_number_list[n] = np.array(
                self.particle_number_list[n])

        lookup = [[None for i in range(self.blocksize)]
                  for i2 in range(self.blocksize)]
        for n1 in range(self.blocksize):
            for n2 in range(self.blocksize):
                lookup[n1][n2] = scipy.interpolate.interp1d(
                    x=self.radial_distance_array,
                    y=self.lookup_table[:, n1, n2],
                    kind=interpolator_kind,
                    axis=-1,
                    assume_sorted=True)

        def matvec(in_vec):
            out_vec = np.zeros(shape=in_vec.shape, dtype=complex)
            for n1 in range(self.blocksize):
                i1 = self.particle_number_list[n1]
                idx1 = self.system_vector_index_list[n1]
                m1 = self.m_list[n1]
                for n2 in range(self.blocksize):
                    i2 = self.particle_number_list[n2]
                    idx2 = self.system_vector_index_list[n2]
                    m2 = self.m_list[n2]
                    rho = self.particle_rho_array[i1[:, None], i2[None, :]]
                    phi = self.particle_phi_array[i1[:, None], i2[None, :]]
                    M = lookup[n1][n2](rho)
                    M = M * np.exp(1j * (m2 - m1) * phi)
                    out_vec[idx1] += M.dot(in_vec[idx2])
            return out_vec

        self.linear_operator = scipy.sparse.linalg.LinearOperator(
            shape=self.shape, matvec=matvec, dtype=complex)
コード例 #8
0
ファイル: linear_system.py プロジェクト: shepherdYoung/smuthi
    def __init__(self,
                 vacuum_wavelength,
                 particle_list,
                 layer_system,
                 k_parallel='default',
                 resolution=None,
                 cuda_blocksize=None,
                 interpolator_kind='linear'):

        if cuda_blocksize is None:
            cuda_blocksize = cu.default_blocksize

        CouplingMatrixRadialLookup.__init__(self, vacuum_wavelength,
                                            particle_list, layer_system,
                                            k_parallel, resolution)

        sys.stdout.write('Prepare CUDA kernel and device lookup data ... ')
        sys.stdout.flush()
        start_time = time.time()

        if interpolator_kind == 'linear':
            coupling_source = cu.linear_radial_lookup_source % (
                self.blocksize, self.shape[0],
                self.radial_distance_array.min(), resolution)
        elif interpolator_kind == 'cubic':
            coupling_source = cu.cubic_radial_lookup_source % (
                self.blocksize, self.shape[0],
                self.radial_distance_array.min(), resolution)

        coupling_function = SourceModule(coupling_source).get_function(
            "coupling_kernel")

        n_lookup_array = np.zeros(self.shape[0], dtype=np.uint32)
        m_particle_array = np.zeros(self.shape[0], dtype=np.float32)
        x_array = np.zeros(self.shape[0], dtype=np.float32)
        y_array = np.zeros(self.shape[0], dtype=np.float32)

        i_particle = 0
        for i, particle in enumerate(particle_list):
            for m in range(-particle.m_max, particle.m_max + 1):
                for l in range(max(1, abs(m)), particle.l_max + 1):
                    for tau in range(2):

                        #idx = self.index(i, tau, l, m)
                        i_taulm = fldex.multi_to_single_index(
                            tau, l, m, particle.l_max, particle.m_max)
                        idx = i_particle + i_taulm

                        n_lookup_array[idx] = fldex.multi_to_single_index(
                            tau, l, m, self.l_max, self.m_max)
                        m_particle_array[idx] = m

                        # scale the x and y position to the lookup resolution:
                        x_array[idx] = particle.position[0]
                        y_array[idx] = particle.position[1]

            i_particle += fldex.blocksize(particle.l_max, particle.m_max)

        # lookup as numpy array in required shape
        re_lookup = self.lookup_table.real.astype(np.float32)
        im_lookup = self.lookup_table.imag.astype(np.float32)

        # transfer data to gpu
        n_lookup_array_d = gpuarray.to_gpu(n_lookup_array)
        m_particle_array_d = gpuarray.to_gpu(m_particle_array)
        x_array_d = gpuarray.to_gpu(x_array)
        y_array_d = gpuarray.to_gpu(y_array)
        re_lookup_d = gpuarray.to_gpu(re_lookup)
        im_lookup_d = gpuarray.to_gpu(im_lookup)

        sys.stdout.write('done | elapsed: ' +
                         str(int(time.time() - start_time)) + 's\n')
        sys.stdout.flush()

        cuda_gridsize = (self.shape[0] + cuda_blocksize - 1) // cuda_blocksize

        def matvec(in_vec):
            re_in_vec_d = gpuarray.to_gpu(np.float32(in_vec.real))
            im_in_vec_d = gpuarray.to_gpu(np.float32(in_vec.imag))
            re_result_d = gpuarray.zeros(in_vec.shape, dtype=np.float32)
            im_result_d = gpuarray.zeros(in_vec.shape, dtype=np.float32)
            coupling_function(n_lookup_array_d.gpudata,
                              m_particle_array_d.gpudata,
                              x_array_d.gpudata,
                              y_array_d.gpudata,
                              re_lookup_d.gpudata,
                              im_lookup_d.gpudata,
                              re_in_vec_d.gpudata,
                              im_in_vec_d.gpudata,
                              re_result_d.gpudata,
                              im_result_d.gpudata,
                              block=(cuda_blocksize, 1, 1),
                              grid=(cuda_gridsize, 1))
            return re_result_d.get() + 1j * im_result_d.get()

        self.linear_operator = scipy.sparse.linalg.LinearOperator(
            shape=self.shape, matvec=matvec, dtype=complex)
コード例 #9
0
ファイル: linear_system.py プロジェクト: shepherdYoung/smuthi
    def __init__(self,
                 vacuum_wavelength,
                 particle_list,
                 layer_system,
                 k_parallel='default',
                 resolution=None,
                 interpolator_kind='cubic'):

        if interpolator_kind == 'cubic':
            interpolation_order = 3
        else:
            interpolation_order = 1

        CouplingMatrixVolumeLookup.__init__(self, vacuum_wavelength,
                                            particle_list, layer_system,
                                            k_parallel, resolution)

        x_array = np.array(
            [particle.position[0] for particle in particle_list])
        y_array = np.array(
            [particle.position[1] for particle in particle_list])
        z_array = np.array(
            [particle.position[2] for particle in particle_list])

        self.particle_rho_array = np.sqrt(
            (x_array[:, None] - x_array[None, :])**2 +
            (y_array[:, None] - y_array[None, :])**2)
        self.particle_phi_array = np.arctan2(
            y_array[:, None] - y_array[None, :],
            x_array[:, None] - x_array[None, :])
        self.particle_sz_array = z_array[:, None] + z_array[None, :]
        self.particle_dz_array = z_array[:, None] - z_array[None, :]

        # contains for each n all positions in the large system arrays that correspond to n:
        self.system_vector_index_list = [[] for i in range(self.blocksize)]

        # same size as system_vector_index_list, contains the according particle numbers:
        self.particle_number_list = [[] for i in range(self.blocksize)]
        self.m_list = [None for i in range(self.blocksize)]
        for i, particle in enumerate(particle_list):
            for m in range(-particle.m_max, particle.m_max + 1):
                for l in range(max(1, abs(m)), particle.l_max + 1):
                    for tau in range(2):
                        n_lookup = fldex.multi_to_single_index(
                            tau=tau,
                            l=l,
                            m=m,
                            l_max=self.l_max,
                            m_max=self.m_max)
                        self.system_vector_index_list[n_lookup].append(
                            self.index(i, tau, l, m))
                        self.particle_number_list[n_lookup].append(i)
                        self.m_list[n_lookup] = m
        for n in range(self.blocksize):
            self.system_vector_index_list[n] = np.array(
                self.system_vector_index_list[n])
            self.particle_number_list[n] = np.array(
                self.particle_number_list[n])

        self.lookup_plus_real = [[None for i in range(self.blocksize)]
                                 for i2 in range(self.blocksize)]
        self.lookup_plus_imag = [[None for i in range(self.blocksize)]
                                 for i2 in range(self.blocksize)]
        self.lookup_minus_real = [[None for i in range(self.blocksize)]
                                  for i2 in range(self.blocksize)]
        self.lookup_minus_imag = [[None for i in range(self.blocksize)]
                                  for i2 in range(self.blocksize)]
        for n1 in range(self.blocksize):
            for n2 in range(self.blocksize):
                self.lookup_plus_real[n1][
                    n2] = scipy.interpolate.RectBivariateSpline(
                        x=self.rho_array,
                        y=self.sum_z_array,
                        z=self.lookup_table_plus[:, :, n1, n2].real,
                        kx=interpolation_order,
                        ky=interpolation_order)
                self.lookup_plus_imag[n1][
                    n2] = scipy.interpolate.RectBivariateSpline(
                        x=self.rho_array,
                        y=self.sum_z_array,
                        z=self.lookup_table_plus[:, :, n1, n2].imag,
                        kx=interpolation_order,
                        ky=interpolation_order)
                self.lookup_minus_real[n1][
                    n2] = scipy.interpolate.RectBivariateSpline(
                        x=self.rho_array,
                        y=self.diff_z_array,
                        z=self.lookup_table_minus[:, :, n1, n2].real,
                        kx=interpolation_order,
                        ky=interpolation_order)
                self.lookup_minus_imag[n1][
                    n2] = scipy.interpolate.RectBivariateSpline(
                        x=self.rho_array,
                        y=self.diff_z_array,
                        z=self.lookup_table_minus[:, :, n1, n2].imag,
                        kx=interpolation_order,
                        ky=interpolation_order)

        def matvec(in_vec):
            out_vec = np.zeros(shape=in_vec.shape, dtype=complex)
            for n1 in range(self.blocksize):
                i1 = self.particle_number_list[n1]
                idx1 = self.system_vector_index_list[n1]
                m1 = self.m_list[n1]
                for n2 in range(self.blocksize):
                    i2 = self.particle_number_list[n2]
                    idx2 = self.system_vector_index_list[n2]
                    m2 = self.m_list[n2]
                    rho = self.particle_rho_array[i1[:, None], i2[None, :]]
                    phi = self.particle_phi_array[i1[:, None], i2[None, :]]
                    sz = self.particle_sz_array[i1[:, None], i2[None, :]]
                    dz = self.particle_dz_array[i1[:, None], i2[None, :]]
                    Mpl = self.lookup_plus_real[n1][n2].ev(
                        rho,
                        sz) + 1j * self.lookup_plus_imag[n1][n2].ev(rho, sz)
                    Mmn = self.lookup_minus_real[n1][n2].ev(
                        rho,
                        dz) + 1j * self.lookup_minus_imag[n1][n2].ev(rho, dz)
                    M = (Mpl + Mmn) * np.exp(1j * (m2 - m1) * phi)
                    out_vec[idx1] += M.dot(in_vec[idx2])
            return out_vec

        self.linear_operator = scipy.sparse.linalg.LinearOperator(
            shape=self.shape, matvec=matvec, dtype=complex)