示例#1
0
    def run(self):
        """Start the simulation."""
        self.print_simulation_header()

        # check if default contour exists, otherwise set a contour
        if coord.default_k_parallel is None:
            neff_resolution = 5e-3
            neff_max = max(
                np.array(self.layer_system.refractive_indices).real) + 1
            neff_imag = 5e-2
            coord.set_default_k_parallel(
                vacuum_wavelength=self.initial_field.vacuum_wavelength,
                neff_resolution=neff_resolution,
                neff_max=neff_max,
                neff_imag=neff_imag)

        self.initialize_linear_system()
        self.linear_system.prepare()
        self.linear_system.solve()

        # post processing
        if self.post_processing:
            self.post_processing.run(self)

        if self.save_after_run:
            self.save(self.output_dir + '/simulation.p')

        sys.stdout.write('\n')
        sys.stdout.flush()

        plt.show()
def test_w_against_wr():
    coord.set_default_k_parallel(wl, [0, 0.8, 0.8 - 0.1j, 2.1 - 0.1j, 2.1, 7],
                                 2e-3)
    laysys_air_1 = lay.LayerSystem(thicknesses=[0, 0],
                                   refractive_indices=[1, 1])
    laysys_air_2 = lay.LayerSystem(thicknesses=[0, 250, 0],
                                   refractive_indices=[1, 1, 1])

    part1 = part.Sphere(position=[100, -100, 200],
                        refractive_index=1.7,
                        radius=100,
                        l_max=2,
                        m_max=2)
    part2 = part.Sphere(position=[-100, 200, 400],
                        refractive_index=1.7,
                        radius=100,
                        l_max=2,
                        m_max=2)

    w_air_1 = coup.direct_coupling_block(wl, part1, part2, laysys_air_1)
    wr_air_2 = coup.layer_mediated_coupling_block(wl, part1, part2,
                                                  laysys_air_2)

    error = wr_air_2 - w_air_1
    np.testing.assert_almost_equal(wr_air_2, w_air_1, decimal=4)
示例#3
0
def simsmuthi(ii, lams, nkdata, fname, rad, subri):
    wl = lams[ii]
    parri = nkdata[ii]
    angles = np.linspace(0, np.pi, 181)
    z0 = -rad
    pos = LoadPosFile(fname, cc, rad, z0)
    par_list = PrepareIdenticalParticles(positions=pos,
                                         ref_ind=parri,
                                         radius=rad)

    coord.set_default_k_parallel(wl, neff_resolution=5e-3, neff_max=subri + 1)
    two_layers = smuthi.layers.LayerSystem(thicknesses=[0, 0],
                                           refractive_indices=[1, subri])
    plane_wave = smuthi.initial_field.PlaneWave(
        vacuum_wavelength=wl,
        polar_angle=0,  # from top
        azimuthal_angle=0,
        polarization=0)  # 0=TE 1=TM
    if len(par_list) == 1:
        simulation = smuthi.simulation.Simulation(layer_system=two_layers,
                                                  particle_list=par_list,
                                                  initial_field=plane_wave,
                                                  solver_type='gmres')
    else:
        simulation = smuthi.simulation.Simulation(
            layer_system=two_layers,
            particle_list=par_list,
            initial_field=plane_wave,
            solver_type='KCSolver',
            store_coupling_matrix=False,
            coupling_matrix_lookup_resolution=3)
    simulation.run()
    # evaluate differential scattering cross section
    dscs = smuthi.scattered_field.scattering_cross_section(
        initial_field=plane_wave,
        particle_list=par_list,
        layer_system=two_layers,
        polar_angles=angles)
    cext0 = smuthi.scattered_field.extinction_cross_section(
        plane_wave, par_list, two_layers)
    scat = dscs.integral()
    cext = cext0['top'] + cext0['bottom']
    return cext, scat
示例#4
0
def simsmuthi(wl, parri, par_list, subri=1, topri=1, neff_res=5e-3):
    """
    Default smuthi simulation for particles on a substrate
    Specular plane wave incidence with user-specified wavelength.
    Important note: all particles must be made of the same material!
    :param wl: wavelength
    :param parri: refractive index data of the particle
    :param subri: substrate refractive index (default: 1)
    :param topri: refractive index in which the particle is embedded (default: 1)
    :return: tuple with extinction and scattering cross-sections
    """
    for jj in range(len(par_list)):
        par_list[jj].refractive_index = parri

    coord.set_default_k_parallel(wl,
                                 neff_resolution=neff_res,
                                 neff_max=subri + 1,
                                 neff_imag=1e-2)
    two_layers = smuthi.layers.LayerSystem(thicknesses=[0, 0],
                                           refractive_indices=[topri, subri])
    plane_wave = smuthi.initial_field.PlaneWave(
        vacuum_wavelength=wl,
        polar_angle=0,  # from top
        azimuthal_angle=0,
        polarization=0)  # 0=TE 1=TM
    if len(par_list) < 3:
        simulation = smuthi.simulation.Simulation(layer_system=two_layers,
                                                  particle_list=par_list,
                                                  initial_field=plane_wave,
                                                  solver_type='gmres')
    else:
        simulation = smuthi.simulation.Simulation(
            layer_system=two_layers,
            particle_list=par_list,
            initial_field=plane_wave,
            solver_type='KCSolver',
            store_coupling_matrix=False,
            coupling_matrix_lookup_resolution=3)
    simulation.run()
    return simulation
# Parameter input ----------------------------
ld = 550
rD = [300, -200, 100]
D = [1e7, 2e7, 3e7]
thick = [0, 200, 200, 0]
n = [1, 1.5, 2 + 1e-2j, 1 + 5j]
waypoints = [0, 0.8, 0.8 - 0.1j, 2.1 - 0.1j, 2.1, 4]
neff_discr = 1e-2
rS = [100, 200, 300]
nS = 1.5
RS = 100
# --------------------------------------------

coord.set_default_k_parallel(vacuum_wavelength=ld,
                             neff_waypoints=waypoints,
                             neff_resolution=neff_discr)
dipole = init.DipoleSource(vacuum_wavelength=ld, dipole_moment=D, position=rD)
laysys = lay.LayerSystem(thicknesses=thick, refractive_indices=n)
particle = smuthi.particles.Sphere(position=rS,
                                   l_max=3,
                                   m_max=3,
                                   refractive_index=nS,
                                   radius=RS)
simulation = simul.Simulation(layer_system=laysys,
                              particle_list=[particle],
                              initial_field=dipole)

aI = dipole.spherical_wave_expansion(particle, laysys)

示例#6
0
substrate_refractive_index = 1.52
sphere_refractive_index = 2.4
distance_sphere_substrate = 50
plane_wave_polar_angle = np.pi
plane_wave_azimuthal_angle = 0
plane_wave_polarization = 0
plane_wave_amplitude = 1
lmax = 3
neff_waypoints = [0, 0.5, 0.8 - 0.1j, 2 - 0.1j, 2.5, 4]
neff_discr = 1e-3
farfield_neff_waypoints = [0, 1]
farfield_neff_discr = 1e-2

# --------------------------------------------

coord.set_default_k_parallel(vacuum_wavelength, neff_waypoints, neff_discr)

# initialize particle object
part1 = part.Sphere(position=[0, 0, distance_sphere_substrate + sphere_radius],
                    refractive_index=sphere_refractive_index,
                    radius=sphere_radius,
                    l_max=lmax,
                    m_max=lmax)
particle_list = [part1]

# initialize layer system object
lay_sys = lay.LayerSystem(
    [0, 0], [substrate_refractive_index, surrounding_medium_refractive_index])

# initialize initial field object
init_fld = init.PlaneWave(vacuum_wavelength=vacuum_wavelength,
示例#7
0
 wl = np.array([370])
 wl = np.linspace(250, 500,
                  21)  # another example declaration of wavelengths
 subri = 2  # substrate refractive index
 # nkdata = ms.LoadNkData(wl, fname) # use if you want to import Si data from Schinke
 nkdata = 0 * wl + 4  # particle refractive index
 CC = 7000
 pos = np.array([[0, 0, -rad], [CC * rad, CC * rad,
                                -rad]])  # list of particle positions
 # pos = ms.LoadPosFile(posname, CC, rad, -rad) # loads position from posname and scales it to match rad
 N_particles = pos.shape[0]
 cext_tot = []
 for ii in range(len(wl)):
     # set_default_k_parallel is extremely tricky function from Amos. Use with care.
     coord.set_default_k_parallel(wl[ii],
                                  neff_resolution=5e-3,
                                  neff_max=subri + 1)
     two_layers = layers.LayerSystem(thicknesses=[0, 0],
                                     refractive_indices=[1, subri])
     par_list = ms.PrepareIdenticalParticles(positions=pos,
                                             radius=rad,
                                             l_max=1,
                                             ref_ind=nkdata[ii])
     k0 = 2 * np.pi / wl[ii]
     c = -6 * 1j * k0**(-3) / 4
     M = conversionmatrix(N_particles, c)  # not too smart!
     Sr = layercoupling(wl[ii], par_list, two_layers, M)
     S = particlecoupling(wl[ii], pos)
     alfinv = inversepolarizabilities(par_list, wl[ii])
     Einc = initial_field(wl[ii], par_list, two_layers)
     p = solve(alfinv, S, Sr, Einc)
示例#8
0
import smuthi.scattered_field as sf
import smuthi.graphical_output as go
import smuthi.cuda_sources as cu
import numpy as np
import scipy.interpolate as interp
import matplotlib.pyplot as plt
import os

# Enable GPU usage. Uncomment if you receive GPU related errors
cu.enable_gpu()

vacuum_wavelength = 550

# Sommerfeld integral contour
coord.set_default_k_parallel(vacuum_wavelength,
                             neff_resolution=1e-2,
                             neff_max=3)

# Set the multipole truncation order
# We invite the user to play with this parameter to see how it affects
# accuracy and runtime.
lmax = 5

# particles
sphere = part.Sphere(position=[300, 300, 250],
                     refractive_index=3,
                     radius=120,
                     l_max=lmax)

cylinder = part.FiniteCylinder(position=[300, -300, 250],
                               refractive_index=3,
示例#9
0
def read_input_yaml(filename):
    """Parse input file
    
    Args:
        filename (str):    relative path and filename of input file
        
    Returns:
        smuthi.simulation.Simulation object containing the params of the input file
    """
    print('Reading ' + os.path.abspath(filename))
    with open(filename, 'r') as input_file:
        input_data = yaml.load(input_file.read())

    cu.enable_gpu(input_data.get('enable GPU', False))

    # wavelength
    wl = float(input_data['vacuum wavelength'])

    # set default coordinate arrays
    angle_unit = input_data.get('angle unit')
    if angle_unit == 'degree':
        angle_factor = np.pi / 180
    else:
        angle_factor = 1
    angle_resolution = input_data.get(
        'angular resolution', np.pi / 180 / angle_factor) * angle_factor
    coord.default_azimuthal_angles = np.arange(
        0, 2 * np.pi + angle_resolution / 2, angle_resolution)
    coord.default_polar_angles = np.arange(0, np.pi + angle_resolution / 2,
                                           angle_resolution)

    neff_resolution = float(input_data.get('n_effective resolution', 1e-2))
    neff_max = input_data.get('max n_effective')
    if neff_max is None:
        ref_ind = [
            float(n) for n in input_data['layer system']['refractive indices']
        ]
        neff_max = max(np.array(ref_ind).real) + 1
    neff_imag = float(input_data.get('n_effective imaginary deflection', 5e-2))
    coord.set_default_k_parallel(vacuum_wavelength=wl,
                                 neff_resolution=neff_resolution,
                                 neff_max=neff_max,
                                 neff_imag=neff_imag)

    # initialize simulation
    lookup_resolution = input_data.get('coupling matrix lookup resolution',
                                       None)
    if lookup_resolution is not None and lookup_resolution <= 0:
        lookup_resolution = None

    simulation = smuthi.simulation.Simulation(
        solver_type=input_data.get('solver type', 'LU'),
        solver_tolerance=float(input_data.get('solver tolerance', 1e-4)),
        store_coupling_matrix=input_data.get('store coupling matrix', True),
        coupling_matrix_lookup_resolution=lookup_resolution,
        coupling_matrix_interpolator_kind=input_data.get(
            'interpolation order', 'linear'),
        input_file=filename,
        length_unit=input_data.get('length unit'),
        output_dir=input_data.get('output folder'),
        save_after_run=input_data.get('save simulation'))

    # particle collection
    particle_list = []
    particle_input = input_data['scattering particles']
    if isinstance(particle_input, str):
        particle_type = 'sphere'
        with open(particle_input, 'r') as particle_specs_file:
            for line in particle_specs_file:
                if len(line.split()) > 0:
                    if line.split()[-1] == 'spheres':
                        particle_type = 'sphere'
                    elif line.split()[-1] == 'spheroids':
                        particle_type = 'spheroid'
                    elif line.split()[-1] == 'cylinders':
                        particle_type = 'finite cylinder'
                    if not line.split()[0] == '#':
                        numeric_line_data = [float(x) for x in line.split()]
                        pos = numeric_line_data[:3]
                        if particle_type == 'sphere':
                            r = numeric_line_data[3]
                            n = numeric_line_data[4] + 1j * numeric_line_data[5]
                            l_max = int(numeric_line_data[6])
                            m_max = int(numeric_line_data[7])
                            particle_list.append(
                                part.Sphere(position=pos,
                                            refractive_index=n,
                                            radius=r,
                                            l_max=l_max,
                                            m_max=m_max))
                        if particle_type == 'spheroid':
                            c = numeric_line_data[3]
                            a = numeric_line_data[4]
                            beta = numeric_line_data[5]
                            alpha = numeric_line_data[6]
                            n = numeric_line_data[7] + 1j * numeric_line_data[8]
                            l_max = int(numeric_line_data[9])
                            m_max = int(numeric_line_data[10])
                            particle_list.append(
                                part.Spheroid(position=pos,
                                              polar_angle=beta,
                                              azimuthal_angle=beta,
                                              refractive_index=n,
                                              semi_axis_c=c,
                                              semi_axis_a=a,
                                              l_max=l_max,
                                              m_max=m_max))
                        if particle_type == 'finite cylinder':
                            r = numeric_line_data[3]
                            h = numeric_line_data[4]
                            beta = numeric_line_data[5]
                            alpha = numeric_line_data[6]
                            n = numeric_line_data[7] + 1j * numeric_line_data[8]
                            l_max = int(numeric_line_data[9])
                            m_max = int(numeric_line_data[10])
                            particle_list.append(
                                part.FiniteCylinder(position=pos,
                                                    polar_angle=beta,
                                                    azimuthal_angle=beta,
                                                    refractive_index=n,
                                                    cylinder_radius=r,
                                                    cylinder_height=h,
                                                    l_max=l_max,
                                                    m_max=m_max))
    else:
        for prtcl in input_data['scattering particles']:
            n = (float(prtcl['refractive index']) +
                 1j * float(prtcl['extinction coefficient']))
            pos = [
                float(prtcl['position'][0]),
                float(prtcl['position'][1]),
                float(prtcl['position'][2])
            ]
            l_max = int(prtcl['l_max'])
            m_max = int(prtcl.get('m_max', l_max))
            if prtcl['shape'] == 'sphere':
                r = float(prtcl['radius'])
                particle_list.append(
                    part.Sphere(position=pos,
                                refractive_index=n,
                                radius=r,
                                l_max=l_max,
                                m_max=m_max))
            else:
                nfmds_settings = prtcl.get('NFM-DS settings', {})
                use_ds = nfmds_settings.get('use discrete sources', True)
                nint = nfmds_settings.get('nint', 200)
                nrank = nfmds_settings.get('nrank', l_max + 2)
                t_matrix_method = {
                    'use discrete sources': use_ds,
                    'nint': nint,
                    'nrank': nrank
                }
                polar_angle = prtcl.get('polar angle', 0)
                azimuthal_angle = prtcl.get('azimuthal angle', 0)

                if prtcl['shape'] == 'spheroid':
                    c = float(prtcl['semi axis c'])
                    a = float(prtcl['semi axis a'])
                    particle_list.append(
                        part.Spheroid(position=pos,
                                      polar_angle=polar_angle,
                                      azimuthal_angle=azimuthal_angle,
                                      refractive_index=n,
                                      semi_axis_a=a,
                                      semi_axis_c=c,
                                      l_max=l_max,
                                      m_max=m_max,
                                      t_matrix_method=t_matrix_method))
                elif prtcl['shape'] == 'finite cylinder':
                    h = float(prtcl['cylinder height'])
                    r = float(prtcl['cylinder radius'])
                    particle_list.append(
                        part.FiniteCylinder(position=pos,
                                            polar_angle=polar_angle,
                                            azimuthal_angle=azimuthal_angle,
                                            refractive_index=n,
                                            cylinder_radius=r,
                                            cylinder_height=h,
                                            l_max=l_max,
                                            m_max=m_max,
                                            t_matrix_method=t_matrix_method))
                else:
                    raise ValueError(
                        'Currently, only spheres, spheroids and finite cylinders are implemented'
                    )
    simulation.particle_list = particle_list

    # layer system
    thick = [float(d) for d in input_data['layer system']['thicknesses']]
    ref_ind = [
        float(n) for n in input_data['layer system']['refractive indices']
    ]
    ext_coeff = [
        float(n) for n in input_data['layer system']['extinction coefficients']
    ]
    ref_ind = np.array(ref_ind) + 1j * np.array(ext_coeff)
    ref_ind = ref_ind.tolist()
    simulation.layer_system = lay.LayerSystem(thicknesses=thick,
                                              refractive_indices=ref_ind)

    # initial field
    infld = input_data['initial field']
    if infld['type'] == 'plane wave':
        a = float(infld.get('amplitude', 1))
        pol_ang = angle_factor * float(infld['polar angle'])
        az_ang = angle_factor * float(infld['azimuthal angle'])
        if infld['polarization'] == 'TE':
            pol = 0
        elif infld['polarization'] == 'TM':
            pol = 1
        else:
            raise ValueError('polarization must be "TE" or "TM"')
        ref = [
            float(infld.get('reference point', [0, 0, 0])[0]),
            float(infld.get('reference point', [0, 0, 0])[1]),
            float(infld.get('reference point', [0, 0, 0])[2])
        ]
        initial_field = init.PlaneWave(vacuum_wavelength=wl,
                                       polar_angle=pol_ang,
                                       azimuthal_angle=az_ang,
                                       polarization=pol,
                                       amplitude=a,
                                       reference_point=ref)
    elif infld['type'] == 'Gaussian beam':
        a = float(infld['amplitude'])
        pol_ang = angle_factor * float(infld['polar angle'])
        az_ang = angle_factor * float(infld['azimuthal angle'])
        if infld['polarization'] == 'TE':
            pol = 0
        elif infld['polarization'] == 'TM':
            pol = 1
        else:
            raise ValueError('polarization must be "TE" or "TM"')
        ref = [
            float(infld['focus point'][0]),
            float(infld['focus point'][1]),
            float(infld['focus point'][2])
        ]
        ang_res = infld.get('angular resolution',
                            np.pi / 180 / ang_fac) * ang_fac
        bet_arr = np.arange(0, np.pi / 2, ang_res)
        if pol_ang <= np.pi:
            kparr = np.sin(bet_arr) * simulation.layer_system.wavenumber(
                layer_number=0, vacuum_wavelength=wl)
        else:
            kparr = np.sin(bet_arr) * simulation.layer_system.wavenumber(
                layer_number=-1, vacuum_wavelength=wl)
        wst = infld['beam waist']
        aarr = np.concatenate([np.arange(0, 2 * np.pi, ang_res), [2 * np.pi]])
        initial_field = init.GaussianBeam(vacuum_wavelength=wl,
                                          polar_angle=pol_ang,
                                          azimuthal_angle=az_ang,
                                          polarization=pol,
                                          beam_waist=wst,
                                          k_parallel_array=kparr,
                                          azimuthal_angles_array=aarr,
                                          amplitude=a,
                                          reference_point=ref)
    elif infld['type'] == 'dipole source':
        pos = [float(infld['position'][i]) for i in range(3)]
        mom = [float(infld['dipole moment'][i]) for i in range(3)]
        initial_field = init.DipoleSource(vacuum_wavelength=wl,
                                          dipole_moment=mom,
                                          position=pos)
    elif infld['type'] == 'dipole collection':
        initial_field = init.DipoleCollection(vacuum_wavelength=wl)
        dipoles = infld['dipoles']
        for dipole in dipoles:
            pos = [float(dipole['position'][i]) for i in range(3)]
            mom = [float(dipole['dipole moment'][i]) for i in range(3)]
            dip = init.DipoleSource(vacuum_wavelength=wl,
                                    dipole_moment=mom,
                                    position=pos)
            initial_field.append(dip)
    simulation.initial_field = initial_field

    # post processing
    simulation.post_processing = pp.PostProcessing()
    if input_data.get('post processing'):
        for item in input_data['post processing']:
            if item['task'] == 'evaluate far field':
                simulation.post_processing.tasks.append(item)
            elif item['task'] == 'evaluate near field':
                simulation.post_processing.tasks.append(item)

    return simulation
import smuthi.scattered_field as sf
import numpy as np
from smuthi.coordinates import default_azimuthal_angles

ld = 550
rD1 = [100, -100, 100]
D1 = [1e7, 2e7, 3e7]
rD2 = [-100, 100, -100]
D2 = [-2e7, 3e7, 1e7]

# waypoints = [0, 0.8, 0.8-0.1j, 2.1-0.1j, 2.1, 3]
neff_max = 3
neff_discr = 5e-3

coord.set_default_k_parallel(vacuum_wavelength=ld,
                             neff_resolution=neff_discr,
                             neff_max=neff_max)
#coord.default_k_parallel = np.array([0, 0.5*2*np.pi/ld])

# initialize particle object
# first two spheres in top layer
sphere1 = part.Sphere(position=[200, 200, 500],
                      refractive_index=2.4 + 0.0j,
                      radius=110,
                      l_max=3,
                      m_max=3)
sphere2 = part.Sphere(position=[200, -200, 500],
                      refractive_index=2.4 + 0.0j,
                      radius=110,
                      l_max=3,
                      m_max=3)
#idx.set_swe_specs(l_max=2)
wl = 550

part1 = part.Sphere(position=[100, -100, 200],
                    refractive_index=1.7,
                    radius=100,
                    l_max=2,
                    m_max=2)
part2 = part.Sphere(position=[-100, 200, 300],
                    refractive_index=1.7,
                    radius=100,
                    l_max=2,
                    m_max=2)

coord.set_default_k_parallel(wl, [0, 0.8, 0.8 - 0.1j, 2.1 - 0.1j, 2.1, 3],
                             2e-3)


def test_wr_against_prototype():
    laysys_substrate = lay.LayerSystem(thicknesses=[0, 0],
                                       refractive_indices=[2 + 0.1j, 1])

    wr_sub00 = coup.layer_mediated_coupling_block(wl, part1, part1,
                                                  laysys_substrate)
    wr_sub01 = coup.layer_mediated_coupling_block(wl, part1, part2,
                                                  laysys_substrate)

    wr_sub_0000 = -0.116909038698419 - 0.013001770175717j
    assert abs((wr_sub00[0, 0] - wr_sub_0000) / wr_sub_0000) < 1e-5
    wr_sub_0010 = 0.051728301055665 - 0.030410521218822j
    assert abs((wr_sub01[0, 0] - wr_sub_0010) / wr_sub_0010) < 1e-5