You are on page 1of 131

JCMsolve Tutorial

Electromagnetics
Version 2.10.0

This document is provided as a part of JCMwaves software products. It is provided under the terms of the End User License Agreement (EULA) for JCMwave Software Products. JCMwave and the JCMwave logo are registered trademarks of the JCMwave GmbH. Copyright c 2009 by JCMwave GmbH. All rights reserved.

Contents
Legal information 1 How to use this tutorial 2 Theoretical Background 2.1 Maxwells Equations . . . . . . . . . . . . . . . . . . . . . . . 2.2 Time Harmonic Maxwells equations: Frequency Domain . . . 3 Introduction to JCMsuite 3.1 Overview . . . . . . . . . . . . . . . . . 3.2 Main Features of JCMsolve . . . . . . 3.2.1 Problem Classes . . . . . . . . . 3.2.2 Resonance Mode and Scattering 3.2.2.1 Planar Problems . . . 3.2.2.2 Cylindrical Problems . 3.2.3 Propagating Mode Problems* . 4 Getting started 4.1 Dening Projects . . . . . . . . . . . 4.2 Starting a project . . . . . . . . . . . 4.2.1 Windows . . . . . . . . . . . . 4.2.2 Linux . . . . . . . . . . . . . 4.3 JCMsolve output and Post-Processes 4.3.1 FieldTransformation . . . . . 4.3.2 ExportFields . . . . . . . . . 4.3.3 FunctionalEvaluation . . . . . 4.4 Third Party Support . . . . . . . . . 3 2 5 7 7 8 11 11 12 13 13 14 15 16 19 19 23 23 23 23 24 25 25 25

. . . . . . . . . . . . . . . . . . Poblems* . . . . . . . . . . . . . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

. . . . . . . . .

4 5 Hello World! 6 Scattering 6.1 Scattering Problems . . . . . . . . . . . . . . . . 6.2 Scattering from Cylinder (TE polarization) . . . . 6.3 Scattering from Cylinder (arbitrary polarization) 6.4 Gaussian Beam on Micro Lens . . . . . . . . . . . 6.5 Photolithography: EUV - Mask . . . . . . . . . . 6.6 Photolithography II : EUV - Mask revisited . . . 6.7 Mie Scattering . . . . . . . . . . . . . . . . . . . . 6.8 Circular Pupil (cylindrical) . . . . . . . . . . . . . 6.9 Circular Pupil (3D) . . . . . . . . . . . . . . . . . 7 Propagating Modes 7.1 Propagating Mode Problems . . . . 7.2 Single Mode Fiber . . . . . . . . . 7.3 Leaky Waveguide . . . . . . . . . . 7.4 Rectangular Microwave Waveguide 7.5 Directional Coupler . . . . . . . . . 7.6 Plasmonic Waveguide . . . . . . . . 7.7 Photonic Crystal Fiber . . . . . . . 8 Resonance Modes 8.1 Resonance Problems . . . . 8.2 Rectangular Resonator . . . 8.3 Cylindrical Resonator . . . . 8.4 Hexagonal Photonic Crystal . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

CONTENTS 27 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 31 32 38 40 43 47 50 54 56 59 59 60 66 69 73 78 82 85 85 86 91 93 97 97 101 101 108

9 Embedded Scripting 9.1 Embedded Scripting Description . . . 9.2 Embedded Scripting: Matlab . . . . 9.2.1 Tutorial project: Refraction at 9.2.2 Photonic Crystal . . . . . . . 10 Using JCMsuite from 10.1 Initialization . . . . 10.2 Main Method Call 10.3 The Pinboard . . .

. . . . an . .

. . . . . . . . . . interface . . . . .

Python . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

113 . 113 . 114 . 114

CONTENTS

10.4 Table Access Methods . . . . . . . . . . . . . . . . . . . . . . 115 10.5 Fieldbag Access Methods . . . . . . . . . . . . . . . . . . . . . 115 11 Using JCMsuite from Matlab 11.1 Initialization . . . . . . . . . 11.2 Main Method Call . . . . . 11.3 Table Access Methods . . . 11.4 Fieldbag Access Methods . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 119 119 120 120 123 124 124 124 125 126

12 C Programming Interface 12.1 Initialization and Finalization 12.2 Main Method Call . . . . . . 12.3 The Pinboard . . . . . . . . . 12.4 Table Access Methods . . . . 12.5 Fieldbag Access Methods . . .

CONTENTS

Chapter 1 How to use this tutorial


This tutorial is structured as follows. Chapter 2 is a short summary about Maxwells equations and sets the theoretical background for the software package JCMsuite. We introduce our notations, physical units, and dene physical quantities which are used in JCMsuite. Chapter 3 is a general introduction to the software package JCMsuite and its modules. We give an overview of JCMsuites capabilities and introduce the problem classes which can be computed. In the Getting-started-chapter 4 the denition of a JCMsuite simulation project is described. We explain how to use the dierent software modules of JCMsuite under Linux and Windows. Finally we present JCMsuites possibilities of post-processing simulation results and give information about third party support. Chapter 5 is the rst tutorial project. Here we explain step by step how a project is load into the JCMcontrol the geometry triangulated with JCMgeo and nally projects solved with JCMsolve. Furthermore visualization of simulation results with the JCMview is explained. In chapter 6 (Scattering), 7 (Propagating Modes), and 8 (Resonance Modes) the tutorial projects are explained whose source les can be found in the subdirectory TutorialExamples of JCMsuites installation directory. Each chapter starts with a simple example. The following tutorial projects introduce additional features of JCMsuite and deepen important aspects. After nishing the rst project the other tutorial projects of a chapter can be worked on in any order. Each tutorial project begins with a list of learning targets and a project description explaining the physical model that is discussed. The location where the source les can be found is given. Since 7

CHAPTER 1. HOW TO USE THIS TUTORIAL

we often want to modify the tutorial projects to get a feeling for simulation parameters one should copy the corresponding tutorial directory to another destination and keep the unmodied original. The simulation results are explained followed by a discussion, where the learning targets are explained. In the Quick own modications part simulation parameters are listed which can be changed to modify the problem. The meaning of each parameter, where to nd it and suggestions for new values are given. This part is especially useful since it gives clear insight into the meaning of the parameters. Chapter 9 explains JCMsuites feature of embedded scripting. Matlab can be used to create and simulate complicated projects, geometries, parameter scans etc. An embedded scripting tutorial project about refraction at an interface is included which e.g. performs a scan about the angle of incidence of a plane wave and compares the results to the analytical Fresnel formulas. In chapter 10, 11, and 12 the usage of JCMsuite in combination with Python, Matlab, and C is explained in detail. Sections marked with a * in the table of contents (and the corresponding subsections) can be omitted during the rst reading.

Chapter 2 Theoretical Background


In this chapter we start with a short summary of the theory of light propagation. We give the general formulation of Maxwells equations in section 2.1 and introduce the involved physical quantities. In the stationary case the dynamical behaviour of the electric and magnetic eld can be separated from the spatial by an oscillatory time-harmonic ansatz with a xed angular frequency. This is explained in section 2.2. JCMsuite solves problems in this so called frequency domain.

2.1

Maxwells Equations

The mathematical model of light propagation are Maxwells equations: t E t H E H = = = = HJ E 0.

The involved physical quantities are given in Table 2.1. The material parameters are the permittivity tensor and the permeability tensor which may be anisotropic and space-dependent. In this version of JCMsuite we assume that these tensors are linear, i.e. they do not depend on the electric or magnetic eld strength. All input and output data in JCMsuite are given in SI units. 9

10

CHAPTER 2. THEORETICAL BACKGROUND Quantity Electric eld intensity E Magnetic eld intensity H Electric current density J Electric charge density Permittivity tensor Permeability tensor Unit Vm1 Am1 Am2 Cm3 Fm1 Hm1

Table 2.1: Elementary electromagnetic quantities. All units used in JCMsolve are SIunits.

2.2

Time Harmonic Maxwells equations: Frequency Domain

In experimental situations one is often interested in the stationary behaviour of the electric and magentic eld after the transient part has vanished. E.g. in a scattering setup an object is illuminated by a laser or other light source with a xed frequency the transient part of the electric eld is due to switching on the light source and vanishes on a very short timescale. JCMsuite is a simulation package for the non-transient part of the electric and magnetic eld. In the stationary case a time-harmonic ansatz can be made for the electric and magnetic eld: E(x, y, z, t) = E(x, y, z) exp(it), H(x, y, z, t) = H(x, y, z) exp(it),

where is the xed angular frequency related by = 2f to the frequency f of light. In the case that source terms J and/or are present these also have to be time-harmonic: J(x, y, z, t) = J(x, y, z) exp(it), (x, y, z, t) = (x, y, z) exp(it).

These sources could e.g. be antennas or radiating points sources with xed angular frequency. With the above ansatz Maxwells equations split into

2.2. TIME HARMONIC MAXWELLS EQUATIONS: FREQUENCY DOMAIN11 magnetic and electric eld equations: 1 E 2 E = i J, E = 0, and 1 H 2H = 1 J, H = 0. In the following we drop the wiggles. JCMsuite solves the time-harmonic Maxwells equations with the nite element method in a number of dierent settings (e.g., for the electric or the magnetic elds, for resonance mode, propagating mode, or light scattering simulations) and in 1, 2 or 3 spatial dimensions. In the time harmonic case it is very simple to determine the electric eld from the magnetic eld and vice versa. We nd from Maxwells equations: 1 H i 1 E. H = i E = (2.1) (2.2)

Finally we dene a number of important physical quantities which are derived from the electric and magnetic eld and which can be computed with JCMsolve in so called post-processes: electric energy density: wel = (E) E 4

magnetic energy density: wm = (H) H 4

Poynting vector (energy ux density): S=EH= 1 1 H H =E E i i

12

CHAPTER 2. THEORETICAL BACKGROUND

The energy densities can be integrated to get the electric/magnetic eld energy Wel/m,j in a subdomain Dj of the computational domain: Wel,j =
Dj

wel dr =
Dj

(j E) E dr 4 (j H) H , 4

Wm,j =
Dj

wm dr =
Dj

where j , j are the permittivity and permeability in subdomain Dj .

Chapter 3 Introduction to JCMsuite


In this chapter the capabilities of JCMsuite are introduced. After a short introduction to the dierent modules of the software package the focus will be on its main component which is the solver JCMsolve. Please note that the functionalities of the mesh generator JCMgeo are explained in detail in a separate tutorial enclosed with the software distribution.

3.1

Overview

JCMsuite is a software package which allows to simulate the propagation of electromagnetic waves with an exceptionally high accuracy. Figure 3.1 shows a schematic overview of the components of JCMsuite. The main part of JCMsuite is JCMsolve the nite-element method solver which allows to handle a variety of electromagnetic simulation settings. JCMsolve allows to nd guided light elds (eigenmodes) in waveguide structures or resonators and to calculate light scattering and light transition through arbitrary obstacles. JCMsolve handles 1D, 2D and 3D geometries, materials with complex refractive indices and anisotropic material constants. It calculates time-harmonic (steady-state) solutions, as explained in chapter 2. JCMsolve relies on the nite element method (FEM) and implies adaptive methods. Both ensures high accuracy of the results. Further, it uses multi-grid methods, specialized direct solvers for sparse systems, and other fast solving algorithms. This ensures high speed and moderate problem sizes. Therefore, JCMsuite handles challenging projects on standard personal computers. 13

14

CHAPTER 3. INTRODUCTION TO JCMSUITE

JCMsuite contains a exible geometry tool, JCMgeo, which automatically generates 1D, 2D and 3D nite element meshes. The module JCMview allows to visualize the meshes produced by JCMgeo and the electromagnetic eld distributions simulated by JCMsolve. The user-interface JCMcontrol allows to dene all details of a simulation project. Also, the capability of embedded scripting makes it very convenient to set up parameterized projects and complicated geometries and to perform parameter scans with nested loops over project parameters like wavelength, incident angle or geometrical quantities. Embedded scripting is supported for Matlab, Octave, and Python. Besides controlling the solver, the simulation results can be imported into the corresponding environment and can then be further processed.

JCMgeo

JCMsolve

JCMview

JCMcontrol Figure 3.1: Schematics of the modules of JCMsuite. The main tool is the FEM solver
JCMsolve. The geometry tool JCMgeo generates FEM meshes, and the tool JCMview allows to visualize the meshes and eld distributions. The functionality can be steered via the user interface JCMcontrol.

3.2

Main Features of JCMsolve

In this section we will present the main features and capabilities of JCMsuites solver JCMsolve. The organization of this section resembles the key idea of the organization of the main JCMsuite control le (project le). Keywords which also appear in the project le will be written in this font.

3.2. MAIN FEATURES OF JCMSOLVE

15

3.2.1

Problem Classes

Most of the problems of light propagation can be divided into the following three classes: Scattering: light scattering and transition through arbitrary geometries (e.g., light propagation through a micro lens or diraction o a periodic grating). Propagating mode: guided light elds in waveguide structures (e.g., guided or leaky modes in single mode bers or in photonic crystal bers). Resonance mode: eigenmodes in resonators (e.g., modes of vertical cavity surface emitting laser (VCSEL) cavities, band structures of photonic crystals, or whispering gallery modes of microsphere resonators). Each JCMsuite project belongs to one of these classes. PropagatingMode and ResonanceMode projects are eigenvalue problems. JCMsolve nds eigenvalues and corresponding eigenmodes which are the electric or magnetic eld on the given geometry. Scattering projects compute propagation of an incident electric or magnetic eld (e.g., plane waves, Gaussian beams) through a material distribution in the specied geometrical setting. If one chooses to compute the electric eld, then the magnetic eld can be determined afterwards from this solution, and vice versa as explained in section 2.2. Therefore this chapter is restricted to the computation of electric elds.

3.2.2

Resonance Mode and Scattering Poblems*

Resonance mode, propagating mode, and scattering problems can have different types of geometries. For resonance mode and scattering problems these are 1D (Slab), 2D (Planar), 3D rotational symmetric (Cylindrical), arbitrary 3D with a description of a stack of structured layers (Stack), or arbitrary 3D with a tetrahedral discretization (no keyword). The geometry of a propagation mode problem always has a 2D waveguide structure which is invariant in the third spatial dimension along the waveguide. These dierent geometries require dierent numerical treatment to minimize computation time and memory consumption. In the following we ex-

16

CHAPTER 3. INTRODUCTION TO JCMSUITE

plain the eects of dierent geometries and symmetries on Maxwells equations. 3.2.2.1 Planar Problems

The geometry of a Planar problem is invariant in one spatial dimension (zdirection). Depending on the polarization of the electric, resp. magnetic, eld further simplications of the Maxwells equations arise. Maxwells equations are still solved rigorously, no approximations are involved. It is therefore sucient to solve a Planar problem on a 2D geometry (x-y-plane). ElectricZ If the electric eld is polarized perpendicular to the x-y-plane (ElectricZ) the fully vectorial Maxwells equations reduce without further simplications to a scalar equation in two spatial dimensions: 1 Ez = 2 Ez . In the following this case is called transversal electric (TE). ElectricXY In case that the electric eld is polarized parallel to the x-yplane (TM) Maxwells equations reduce to the following vectorial equation in two spatial dimensions 1 E = 2 E for the x- and y-component of the electric eld (ElectricXY). When the electric eld is polarized parallel to the x-y-plane the magnetic eld is polarized perpendicular to the x-y-plane. Therefore the ElectricXY problem is equivalent to the MagneticZ case and vice versa. In the HelloWorld example for propagating modes this will be veried numerically. ElectricXYZ For arbitrary polarized electric eld (ElectricXYZ) in 2D the fully vectorial Maxwells equations have to be solved in two spatial dimensions 1 E = 2E E = 0 for all electric eld components. The equivalent equations for the magnetic eld are also implemented (MagneticZ, MagneticXY, MagneticXYZ).

3.2. MAIN FEATURES OF JCMSOLVE 3.2.2.2 Cylindrical Problems

17

The solution of a 3D problem is more memory and time consuming than a 2D problem. It is therefore desirable to use 2D geometries whenever possible. The computation of an electromagnetic eld in a 3D geometry with cylindrical symmetry (rotational symmetry) can be reduced to a computation on a 2D geometry (Cylindrical). The geometry is assumed to be invariant under rotation around the yaxis. For the transformation we use cylinder coordinates (r, y, ), dened by: x r cos() y = y z r sin() and the transformed electric eld Er cos() 0 sin() Ex Ey = Ey . 0 1 0 E r sin() 0 r cos() Ez r,y, r,y, 1 r,y, Er,y, = 2 r,y, Er,y, with the nabla operator r r,y, = y ,

In the rotationally symmetric case the geometry does not depend on . In the = 0 plane Maxwells equations can be written in the following form:

The permittivity tensor r,y, is transformed accordingly. The electric eld Er,y, can be decomposed in Fourier modes E(r, y) with respect to the polar angle : Er,y, =
n N

and the transformed (pseudo)-tensor xx (r, y) xy (r, y) xz (r, y)/r yy (r, y) yz (r, y)/r . r,y, (r, y, ) = r yx (r, y) zx (r, y)/r zy (r, y)/r zz (r, y)/r 2

ein En (r, y).

18

CHAPTER 3. INTRODUCTION TO JCMSUITE

The wiggled Fourier modes no longer depend on the polar angle . Using this decomposition in Maxwells equations leads to independent equations for the dierent Fourier modes, as shown in the following. The electric eld is split into a eld parallel to a cross section, E (parallel to the = 0 plane), and a eld perpendicular to the cross section, E , Er,y, = E E ,

assuming that the transformed tensors r,y, and r,y, have the form r,y, = 0 0 , r,y, = 0 0 .

After introducing P= 0 1 1 0 and = r y E E

one arrives at P 1 P n2 P1 P in P1 P 2 0 0 in P1 P P1 P E E . =

This equation does not depend on the polar angle and can therefore be solved in the = 0 plane. This reduced the 3D to a 2D problem. Computing resonance modes one species n to search for eigenmodes with the corresponding dependence on (i.e. ein ). In scattering problems r,y, the incident eld is decomposed into Fourier modes Ein . Each incoming in mode with xed n only couples to modes with the same value for n . Therefore JCMsolve solves above equations several times for increasing n . The computation is stopped automatically when the incoming modes Ein become suciently small.

3.2.3

Propagating Mode Problems*

Propagation mode problems always have a waveguide structure. This means the geometry is invariant in one spatial dimension (along the waveguide)

3.2. MAIN FEATURES OF JCMSOLVE

19

but the cross section of the waveguide is arbitrarily structured. We assume that the waveguide geometry does not depend on the spatial variable z as shown in Figure 3.2. A propagating mode is a solution to the time harmonic y x

z Figure 3.2: Waveguide structure: A waveguide is invariant in one spatial dimension (here z-direction) and arbitrarily structured in the other two dimensions. Maxwells equations. It exhibits a harmonic dependency in the z-direction, E = Epm (x, y) exp (ikz z) H = Hpm (x, y) exp (ikz z) . The parameter kz is called propagation constant. From the mathematical point of view this leads to eigenvalue problems for kz . JCMsolve returns the rescaled eigenvalue, which is the eective refractive index dened as kz 2 with k0 = . k0 0 The free space vacuum wavelength, 0 , is dened by the user and denes the time-harmonic frequency, , of the propagating light eld: ne = = 2c 0 and k0 = 2 . 0

In the following the kz eigenvalue problem is derived. We only discuss the magnetic case. All considerations map over to the electrical case when one replaces H by E and interchanges the tensors and . Let us decompose the magnetic eld Hpm (x, y) as Hpm (x, y) = and introduce 0 1 P= 1 0 H (x, y) Hz (x, y) x y

and =

20

CHAPTER 3. INTRODUCTION TO JCMSUITE

Keeping in mind that H = Hpm (x, y)eikz z the -operator acts as H = ikz P P P 0 H (x, y) Hz (x, y) eikz z .

Applying the time harmonic Maxwells equation, 1 H = 2 H and with = one gets
2 P 1 P kz P1 P zz 1 ikz P P

0 0 zz

and =

0 0 zz

ikz P1 P P1 P H Hz .

H Hz

0 0 zz

The last equation is a quadratric eigenvalue problem for the propagation constant kz . The divergence condition reads as H = ikz zz Hz .

Chapter 4 Getting started


4.1 Dening Projects

A simulation project for JCMsuite is dened in a number of input les (text les). The necessary les and the data ow are shown in Fig. 4.1. The
layout.jcm triangulator.jcm

JCMgeo

grid.jcm

<project>.jcmp materials.jcm boundary_conditions.jcm sources.jcm

fieldbag.jcm and further result files

JCMsolve

> Data analysis Postprocessing Visualization (e.g., JCMview)

JCMcontrol
Figure 4.1: Schematics of the data ow of the JCMsuite. main modules for computing a project are JCMgeo and JCMsolve. The 21

22

CHAPTER 4. GETTING STARTED

automatic mesh generator JCMgeo expects two input les (layout.jcm and triangulator.jcm). layout.jcm: The layout le. Here the geometry of the project is described. Nearly arbitrary geometries and computational domains are built from simple geometrical objects (circles, parallelograms, polygons). For an impression we give a short example: a scatterer in form of a Circle whose Center, positioned at the GlobalPosition x = 0 and y = 0 of the geometry is described as follows: Layout { Circle { Name = "Scatterer" MaterialId = 4 Priority = 1 This Port = Center GlobalPositionX = 0.0 GlobalPositionY = 0.0 Radius = 3.55 } } In the installation directory of JCMsuite a tutorial guide for creating simulation layouts is provided (GeoTutorial.pdf). So we will not go into further detail here. triangulator.jcm: The triangulator le. Here some parameters for the triangulation of the geometry are set. Also this le is explained in detail in the tutorial for JCMgeo, GeoTutorial.pdf. JCMgeo reads the layout le and the triagulator le and creates the le grid.jcm which is one of the following input les expected by JCMsolve. projectName.jcmp: The project le. The name of this le with ending jcmp can be chosen by the user. In the project le the user species the project type (as explained in section 3.2.3) and parameters for the solution process. This le can also be used to dene post-processes executed on the output data from the solution process.

4.1. DEFINING PROJECTS

23

materials.jcm: The material le. This le contains the material properties of the physical domains, i.e., the relative permittivity and permeability tensors. Each geometrical object specied in the layout le for JCMgeo has a MaterialId which refers to a material in the material le. When we look back to the circle dened in the example above we nd MaterialId = 4. Now we want that the scatterer has a certain name and permittivity: MaterialBag = { Material { Id = 4 Name = "Silica" RelPermeability = 1.0 RelPermittivity = 2.1025 } } boundary conditions.jcm: The boundary condition le. In this le the user species the type of boundary conditions on particular parts of the physical boundary. Boundaries of the computational domain are specied in the layout le via a BoundaryID. The syntax in the boundary conditions le is then: BoundaryConditionBag = { BoundaryCondition { Id = 3 Electromagnetic = TangentialMagnetic } } where Id refers to the BoundaryID. Please note that transparent or periodic boundaries of the computational domain are not boundaries in the physical sense, but rather attributes of the geometry. Therefore these types of boundaries are dened purely in the layout le and they do not appear in the boundary condition le. The JCMgeo tutorial gives an overview of possible boundary conditions. sources.jcm: The source eld le. For resonance and propagating mode projects no sources have to be specied. For scattering projects (e.g., light transition through a lithographic mask or through a lens) a source eld has

24

CHAPTER 4. GETTING STARTED

to be prescribed. This could be a plane wave, Gaussian beam, point sources, etc. E.g., for a VectorialPlaneWave we have to dene the wave vector (K) and the electric eld vector (Strength). SourceBag = { Source { MaterialId = 1 ElectricFieldStrength = { BuiltIn { VectorialPlaneWave { K = [0, -4.0536e+06, 0] Strength = [0.0, 0.0, 1.0] } } } } } Here the MaterialId is used to specify the region from where the plane wave is coupled into the geometry. Several sources can be dened within one source bag, and several source bags can be dened for one simulation run (resulting in independent eld solutions for each source bag). grid.jcm: The mesh le. This le includes the nite element mesh which contains all the geometrical information about the project. This le is automatically generated by JCMgeo. It is never modied by the user. A nite element mesh is a partition of the physical body, for example a unit cell of a photonic crystal, the cross section of a dielectric waveguide or a resonator cavity, into small elements such as triangles, tetrahedrons, etc. In general a complex body is built up from areas of dierent materials. Therefore each element carries an index-marker (integer) refering to its material domain. Since partial dierential equations need the denition of boundary conditions, each boundary element carries a further boundary index-marker. This boundary index marker allows to group the the boundary into areas with certain boundary condition types. All these material and boundary index markers are automatically assigned to the nite elements when JCMgeo translates the layout le into the grid le.

4.2. STARTING A PROJECT

25

All input les have to be located in a common directory <project_dir>. The next section explains how to start a project.

4.2

Starting a project

JCMsuite is available for Windows and Linux. It is most convenient to use JCMcontrol for the setup and computation of a project. Alternatively, an arbitrary text editor can be used for editing the input les, and the computa tions can be started over the command line (invoking Furthermore simulation projects can be set up and controlled via embedded scripting from Matlab, Octave, and Python. This is explained in section 9.

4.2.1

Windows

During installation a desktop icon for JCMcontrol is created which starts the software. The executable can also be found in the installation directory in the subdirectory bin. Opening the tab File and then Open Project in JCMcontrol a JCMsuite project can be loaded and simulated. This is also described in detail in the HelloWorld tutorial example in chapter 5.

4.2.2

Linux

The usage of JCMcontrol under Linux is the same as under Windows. Linux users sometimes to prefer to use their own specic text editor to create and edit the input les for JCMgeo and JCMsolve, and to invoke the triangulator JCMgeo and the solver JCMsolve in the command line. This is done by typing: >>> JCMgeo <project_dir> >>> JCMsolve --solve <project_dir>/project.jcmp

4.3

JCMsolve output and Post-Processes

After successful simulation a result directory project results is created. The computed elds of the nite element simulation are stored in the le fieldbag.jcm located in the result directory. The storage format (StorageFormat binary or ASCII) of this le can be choosen in the

26

CHAPTER 4. GETTING STARTED

project le. With the option StorageFormat = Pinboard, this result le is not written to disc. For eigenvalue problems the computed eigenvalues are stored in the le eigenvalues.jcm, also located in the result directory. The main simulation results for resonance and propagating mode and scattering projects can be further post-processed using built-in postprocesses like Fourier-analysis, data extraction, functional evaluation, or export functions to visualization tools. We will introduce several post-processes in the tutorial examples. The post processes are specied in the project le in PostProcess sections. They are invoked automatically after the FEM problem is solved. It is also possible to compute only the post processes when the nite element solution is already computed: over the command line JCMsolve is started with the option --post process instead of --solve. Further, postprocesses can be dened in their own separate les and invoked via command line or via JCMcontrol. In the following we introduce some post processes.

4.3.1

FieldTransformation

The FieldTransformation post-process is used to transform the computed eld into other related elds. We already explained that JCMsolve either computes the electric or magnetic eld in a project. Having computed the electric eld one gets the magnetic eld by using the post-process ElectricFieldStrengthTo (according to Eq. 2.2). The opposite case is possible using MagneticFieldStrengthToElect (see Eq. 2.1). Furthermore we can compute, e.g., the electric energy density ElectricFieldStrengthToElectricEnergyDensity the magnetic energy density MagneticFieldStrengthToMagneticEnergyDensity and the Poynting vector eld ElectricFieldStrengthToPoyntingVector MagneticFieldStrengthToPoyntingVector

4.4. THIRD PARTY SUPPORT

27

4.3.2

ExportFields

ExportFields post-processes are used to transform elds from the .jcmformat to other le formats, or to export elds at specic spatial positions, or, e.g., to Cartesian grids. Supported external formats are VTK (Visualization tool kit, an open source platform independent graphics engine) and Amira (an ecient visualization programme).

4.3.3

FunctionalEvaluation

In applications it is often necessary to determine other quantities, derived from the electric/magnetic eld in a region of space. Therefore JCMsolve oers a large number of FunctionalEvaluation post-processes. For example: how much light is scattered from an object into a specic direction in space (PropagatingFourierModes, FourierTransform) what is the eld strength far away from the scatterer (FarFieldEvaluation, ExteriorDomainEvaluation) how large is the electric/magnetic energy density inside an object (e.g. ElectricFieldEnergy) how large is the electric/magnetic ux or energy ux through a surface (e.g. ElectricFluxThroughInterfaces)

4.4

Third Party Support

JCMsuite oers third party support for Python, Matlab and Octave. In your JCMsuite installation directory you nd the subdirectory ThirdPartySupport which includes the corresponding libraries. In some tutorial examples we have included Matlab scripts to compare JCMsolve results to analytical solutions. Before starting them you have to add the corresponding path

28

CHAPTER 4. GETTING STARTED

(>> addpath your jcmroot path/ThirdPartySupport/matlab). To get further information about the support methods use, e.g.: >> help jcmwave loadamirafields >> help jcmwave loadtable In chapters 10 and 11 the usage of JCMsuite from third party programs is explained in detail.

Chapter 5 Hello World!


Learning Targets loading a project into JCMcontrol triangulation of the layout simulation of the project loading the results into JCMview In the rst tutorial project we want learn how to load and simulate a project with JCMsuite. The physical setting is propagation of TE-polarized light through vacuum. After computation of the project results we will have a closer look at the JCMsolve input les. After starting JCMcontrol (section 4.2) open the tab File->Open Project. Browse to your JCMsuite installation directory and then to TutorialExamples/ Electromagnetics/ TimeHarmonic/ Scattering/ Planar/ PlanarZ/ HelloWorld/. Open the le HelloWorls.jcmpro. Before we look at the input les let us compute the project. Choose Computation->Triangulation in JCMcontrol, or with click on the respective icon in the task bar. This starts JCMgeo and creates a triangulation of the geometry. A window with a triangulation pops 29

30

CHAPTER 5. HELLO WORLD!

up for one second. Expand the project tree in the project explorer window. The le grid.jcm is now listed in the result les list. Double clicking on grid.jcm opens JCMview for a visualization of the mesh. Now we start the nite element computation with Computation->Solve Project, or with a click on the respective icon in the task bar. Some messages from the solver are displayed in the terminal output in JCMcontrol. After few seconds the computation should be nished. The result le fieldbag.jcm is now listed in the result les list. Double clicking on fieldbag.jcm opens JCMview for a visualization of the computed electric eld distribution. In JCMview click, e.g., on Create field view->Carpet and choose to visualize the real part of the z component of the eld. In order to get informations about computation times and computational eort, double click on computational costs.jcm in the result les section of the project explorer.

Let us have a look at the input les which dene the project. They can be accessed by double-clicking on the le names in the project les section of the project explorer in JCMcontrol: The project le project.jcmp. denes the basic settings of the simulation. Here we are computing a Electromagnetic, TimeHarmonic, Scattering project on a Planar (i.e., 2D) geometry with TE-polarized elds (ElectricZ). The other parameters are explained in later tutorial projects. They dene which type of nite elements we are using and how accurately we want to compute our solution. The le layout.jcm includes the description of the geometry. It includes a Polygon dening a square shaped computational domain. In your JCMsuite installation directory you nd an extra JCMgeo tutorial where the creation of complex geometries is described step by step. The le triangulator.jcm) is a control le for JCMgeo. Looking at the le BoundaryConditions.jcm you nd no entries. This is because in the Hello World example no physical boundary conditions are applied, but the computational domain is transparent on all boundaries. For the denition of physical boundaries, see, e.g., the tutorial project 8.2 where we compute modes within a resonator with perfectly conducting walls. The le materials.jcm includes the material constants of the objects in the layout. Looking at layout.jcm again you nd MaterialId = 1 for the polygon. This identier corresponds to Id = 1 of the Material. The relative permittivity and permeability of vacuum are 1. As we will see later

31 you can dene complex scalar or tensorial permittivities and permeabilities. In the le sources.jcm you nd the description of the plane wave which is travelling through the computational domain. It is dened by the k-vector and eld strength. We are computing a TE-polarized eld with a k-vector in the x-y-plane and the eld strength directed perpendicular to the plane in which the wave propagates.

32

CHAPTER 5. HELLO WORLD!

Chapter 6 Scattering
6.1 Scattering Problems

In many physical situations one is interested in the scattering of an electromagnetic waves o certain obstacles or devices (scatterers). The scatterer is typically embedded into an innite domain. For example, the innite domain may consist of a layered media or may contain waveguides which reach innity, or it is just homogeneous space. In a post process step one may compute for example the far eld behaviour, scattering amplitudes or the coupling constant to a propagating mode of a waveguide.

33

34

CHAPTER 6. SCATTERING

6.2

Scattering from Cylinder (TE polarization)

Learning Targets basics of a scattering problem (TE polarization) transparent boundary conditions post-process: computation of electric eld energy convergence to analytical solution Project Description We compute the interaction of an incoming plane electromagnetic wave in air (wavelength = 1.55m) with an innite cylinder with material constant cyl = 2.0 and diameter dcyl = 1m. Since the problem is invariant in one spatial dimension our computational domain is two dimensional (planar), see Figure 6.1. The wavevector of the plane wave is parallel to this plane. We choose the polarization of the electric eld perpendicular to the computational domain (transversal electric, TE). In this case Maxwells equations reduce to a scalar equation for the z-component of the electric eld. The electric eld enters the computational domain, is scattered by the cylinder, and leaves the computational domain via all boundaries. Therefore transparent boundary conditions are implied on all boundaries. These boundary conditions simulate an innite exterior domain. Any reections at these articial boundaries are avoided. In a post process the electric eld energy within the cylinder is computed. A Matlab script is provided which compares this result to the analytical solution. The project les to this problem are located in directory TutorialExamples/ Electromagnetics/ TimeHarmonic/ Scattering/ Planar/ PlanarZ/ CylinderScatteringZ/ relative to JCMwaves home directory. Use JCMgeo to triangulate the layout and JCMsolve to compute the project.

6.2. SCATTERING FROM CYLINDER (TE POLARIZATION)

35

computational domain z y r

Figure 6.1: Scattering from a cylinder with radius r. The geometry is invariant in one
spatial dimension dimension, here the z-direction. The computational domain can therefore be taken as a 2D section int the x-y-plane. In this tutorial example light is propagating parallel to the computational domain with polarization in z direction (TE polarization). Also with arbitrary direction of propagation and polarization a 2D computational domain can be used (see tutorial example 6.3).

Results In the simulation run the scattering problem is rst solved on the initial mesh. This mesh is then automatically rened three times to increase the accuracy of the solution. In each renement step every triangle of the mesh is subdivided into four smaller ones. Let us have a closer look at the output that is produced during the simulation run. After the last renement step we read: *** A priori interior domain wave propagation characteristics: computational domain size: 1.9 (wavelengths). computational domain range wave propagation error: 0.0054 one wavelength wave propagation error: 0.0053

36

CHAPTER 6. SCATTERING

assembling problem ... interpolating solution from the previous grid ... interpolating solution from the previous grid: done 00:00:00.27 (cpu) assembling problem: done 00:00:00.80 (cpu) solving discrete problem ... solving discrete problem: done 00:00:00.86 (cpu) updating inner nodes ... updating inner nodes: done 00:00:00.33 (cpu) *** A Posteriori exterior domain quality check = 0.33. computational costs level unknowns cpu time cpu/unknowns total time -------------------------------------------------------0 641 00:00:00.05 7.80e-05 00:00:00 1 2129 00:00:00.16 7.52e-05 00:00:00 2 7265 00:00:00.54 7.43e-05 00:00:01 3 26561 00:00:01.99 7.49e-05 00:00:02 error estimation level rel.residuum ratio -----------------------------0 1.00000000e+00 -/1 2.90189164e-01 3.45 2 7.43388854e-02 3.90 3 1.86541003e-02 3.99

rel. error (FieldEnergy) level est.error ratio ------------------------------/-/-/1 8.47365331e-02 -/2 7.91577841e-03 10.70 3 7.61544326e-04 10.39 *** computation finished successfully

6.2. SCATTERING FROM CYLINDER (TE POLARIZATION)

37

****************** Computation completed ******************** The rst few lines give information about the size of the computational domain and a rst estimate of a so called propagation error. These measures are used by JCMsolve to set the parameters of the transparent boundary conditions in an optimal way. After that the steps of the solution process are given. Having solved the discrete problem the exterior domain quality is checked: Since we use transparent boundary conditions so called quadrilaterals are constructed at the exterior domain boundaries. They have to be adjusted correctly with respect to the incoming and scattered eld and geometry of the computational domain. This is done automatically and the correct performance checked A Posteriori. If necessary the computation is repeated with better settings for the transparent boundary. The table computational costs gives information about the number of unknowns and computation time for each renement step. Note that the cpu time per unknown (cpu/unknowns) is nearly constant with increasing number of unknowns. This is due to JCMsolves use of ecient solvers. The other two tables estimate the error of the computed eld. This error should of course decrease with increasing number of unknowns, i.e. renement steps. In the project le a Termination criterion is given: If the error of the eld energy is smaller then the user specied PrecisionFieldEnergy = 1.0e-03 the computation is successfully nished. In most of the cases not the uniform renement of the grid (each triangle is subdivided) but an adaptive renement strategy is recommended. Thereby the error of the computed eld is estimated locally after each renement step and only triangles ( half of all triangles) with a large estimated error are rened. This usually leads to faster convergence of the solution and to reduced computation time. Adaptive renement is set in project.jcmp Adaptivity = yes. After the computation the directory project results is created which contains the simulation results. The le fieldbag.jcm contains the computed electric eld on the whole computational domain. Open this le in JCMview by double-clicking on it in the project explorer. The le computational costs.jcm contains the costs for each renement step, and the le electric field energy.jcm contains the electric eld energy. You can open this le by double clicking on it in the project explorer.

38

CHAPTER 6. SCATTERING

Discussion This scattering problem can also be solved analytically. The CylinderScatteringZ directory contains a matlab script check.m which computes the electric eld of the scattering project on a rectangular domain ana and determines the electric eld energy Eeld within the cylinder. It produces a plot of the real part of the z-component of the electric eld, which can be compared to JCMsolves solution shown in Figure 6.2. For the eld energy

Figure 6.2: Scattering from a cylinder with radius r: Contour plot of real part of zcomponent of electric eld.
J ana (per unit length in z-direction) we get Eeld = 1.47095 1023 m from the J sim analytical matlab calculation and Eeld = 1.46184 1023 m from our simulation which means a relative error of 0.6%. In the paragraph Quick own modications we will reset some simulation parameters to increase the accuracy.

Quick own modications The eld strength and wave vector of the incoming plane wave are specied in sources.jcm:

101 1 0 1

6.2. SCATTERING FROM CYLINDER (TE POLARIZATION)

39

K denes the wave vector of the incoming wave and Strength the eld vector. When you modify these parameters you have to pay attention that the plane wave is transversal, i.e. the wave vector and the eld vector are orthogonal: StrengthK= 0. The geometry of the computational domain can be modied in layout.jcm: Points of the polygon Air specify the computational domain . Radius is the radius of the Circle with Name=scatterer. RefineAll denes how accurately the circle is resolved. The material parameters are given in materials.jcm and can also be modied. The le project.jcmp species the problem class and contains the main simulation parameters: The maximum number of renement steps MaxNumberSteps can be increased to get a more accurate result. This also costs more computational time. Changing Adaptivity = yes results in an adaptive renement of the grid as explained above. The post process specied in project.jcmp is used to evaluate the electric eld energy. To increase the accuracy of calculation set, e.g.: RefineAll = 5, PrecisionFieldEnergy = 1.00e-06 and Adaptivity = yes, MaxNumberSteps = 4 in project.jcmp.
J sim We get Eeld = 1.47081 1023 m . The relative error is now 0.01%.

40

CHAPTER 6. SCATTERING

6.3

Scattering from Cylinder (arbitrary polarization)

Learning Targets 2D scattering problem with arbitrary polarization comparison to analytical solution post-process: far eld evaluation Project Description This tutorial example investigates same layout as the previous tutorial example 6.2. Here the electric eld is not restricted to transversal polarization. The k-vector of the incoming plane wave does not lie in the 2D cross section described by the layout, i.e., we have conical incidence. We use the post-process FarFieldEvaluation to compute the electric eld at arbitrary points outside the computational domain. The project les to this problem are located in directory TutorialExamples/ Electromagnetics/ TimeHarmonic/ Scattering/ Planar/ PlanarXYZ/ CylinderScatteringXYZ/ relative to JCMwaves home directory. Use JCMgeo to triangulate the layout and JCMsolve to compute the project. Results In the tutorial directory we nd the matlab script check.m. This computes the analytical solution of the cylinder scattering problem and compares it to the values of the electric eld determined in the post process FarFieldEvaluation. Before you can start the check routine in Matlab you have to add the third party support path, as explained in section 4.4. Discussion We nd very good agreement between analytical and numerical results. Note that we not only get the correct intensity but also the correct phase of the scattered eld. The points where the far eld is evaluated are given in the project le in the post process section. Two FarFieldEvaluation

6.3. SCATTERING FROM CYLINDER (ARBITRARY POLARIZATION)41 post processes are dened. The evaluation points in the exterior are given in polar coordinates and as list with cartesian coordinates: PointsX, PointsY, PointsZ respectively. Quick own modications Change the evaluation points in the FarFieldEvaluation post-process in project.jcmp and check them with the matlab script. In order to increase the accuracy of the FEM computation increase RefineAll = 2 of the Circle in layout.jcm and MaxNumberSteps = 1 in project.jcmp.

42

CHAPTER 6. SCATTERING

6.4

Gaussian Beam on Micro Lens

Learning Targets dening a Gaussian beam post-process: computation of the Poynting vector Project Description In this tutorial example we consider propagation of a Gaussian beam through a micro lens. Gaussian beams are only approximative solutions of Maxwells equations. They are often used in so called Beam Propagation Models (BPM) and model a plane wave with a Gaussian envelope of the eld strength. During their propagation the width of the envelope is increasing depending on the Rayleigh range. In our example such a Gaussian beam will be focused by a micro lens. The project les to this problem are located in the directory TutorialExamples/ Electromagnetics/ TimeHarmonic/ Scattering/ Planar/ PlanarZ/ GaussianBeam/ relative to JCMwaves home directory. Use JCMgeo to triangulate the layout and JCMsolve to compute the project. Results Figure 6.3 shows the electric eld intensity of our project. The width of the Gaussian beam is increasing while propagating towards the lens. The beam is partially reected at the interface of the lens which gives rise to the interference pattern. Behind the lens we see a large intensity at the focal point. In a post process we compute the poynting vector eld of our solution. Figure 6.4 shows how the energy ux is focused by the lens. Discussion The Gaussian beam is described in sources.jcm. The MaterialId corresponds to the MaterialIds in layout.jcm which belong to the transparent boundaries. It species on which boundaries the Gaussian beam is set as a source. In addition to the eld strength and wave vector we have

6.4. GAUSSIAN BEAM ON MICRO LENS

43

Figure 6.3: Gaussian beam focussed by micro lens: Intensity of electric eld.

Figure 6.4: Gaussian beam focussed by micro lens: Poynting vector of electromagnetic
eld.

44

CHAPTER 6. SCATTERING

to specify the RayleighRange (see the parameter reference for an exact denition) of our beam. A smaller Rayleigh range leads to a smaller width but also to a faster widening of the beam. The position of minimal width of the Gaussian beam is specied by FocalPosition. Quick own modications Change the parameters of the Gaussian beam.

6.5. PHOTOLITHOGRAPHY: EUV - MASK

45

6.5

Photolithography: EUV - Mask

Learning Targets reection of light from an EUV line mask periodic boundary conditions post-process: propagating fourier coecients for periodic domains

Figure 6.5: EUV mask: multilayer with 40 MoSi (Molybdenum / Silicon) bilayers, chromium absorber, and Silicon oxide buer.

Project Description We compute the reection of light from an EUV line mask. Such a mask consists of a Bragg mirror covered with a periodic

46

CHAPTER 6. SCATTERING

arrangement of absorber lines. The Bragg mirror is a stack of alternating high-/low-refractive index material layers (usually molybdenum and silicon, MoSi). Since the mask is periodic in one space dimension it is sucient to take the periodic interval (pitch = width) as computational domain. To simulate the innite extension of the mask we apply periodic boundary conditions to the corresponding boundaries. On the other boundaries we apply transparent boundary conditions to simulate air above the EUV mask and substrate below the multilayer. When the mask is illuminated light is reected into a number of discrete diraction orders due to the periodic structure of our geometry. The post process PropagatingFourierModes determines the complex amplitudes of all diraction modes which are not evanescent. The computational domain is shown in Figure 6.5. The wave vector of the incident plane wave is parallel to this plane. The electric eld is polarized perpendicular to the plane and has wavelength of = 13.35nm. The angle of incidence is = 5 Our EUV mask has 40 MoSi-layers as a Bragg mirror. The absorber structure consists of an SiO2 buer and the covering Chromium absorber. The mask has a pitch p = 100nm. The project les to this problem are located in directory TutorialExamples/ Electromagnetics/ TimeHarmonic/ Scattering/ Planar/ PlanarZ/ EUVmask/ relative to JCMwaves home directory. Use JCMgeo to triangulate the layout and JCMsolve to compute the project. Results In the post-process all propagating diraction orders (Fourier coecients) for the incident plane wave are computed. The corresponding amplitudes are stored in the le propagating fourier coefficients.jcm. The computation reached the error criterion for the eld energy 1e 1 which was specied in the control le already after three renement steps. Therefore JCMsolve did not compute the maximum specied number of four re-

6.5. PHOTOLITHOGRAPHY: EUV - MASK

47

nement steps. If one wants to make sure that all renement steps are computed one simply has to set the error criterion to a very small value, e.g., PrecisionFieldEnergy = 1e-10. Discussion The intensity of the computed electric eld of the setup is shown in Figure 6.6. We observe that the intensity of the electric eld is

Figure 6.6: EUV mask: Intensity of electric eld. reduced below the absorber pattern. A selection of fourier coecients are shown in Figure 6.7 in dependence on the angle of reection. We notice that the computational domain can become quite large for a Bragg mirror with many layers and for large pitches. It is possible to solve the problem of light propagation in a multilayer stack analytically with the so called matrix transfer algorithm. A domain decomposition algorithm

48

CHAPTER 6. SCATTERING

1 0.1
normalized intensity

0.01 0.001 110


-4

110 0

-5

10

20

30

40

50

60

70

angle of reection [ ] Figure 6.7: Scattering from an EUV mask: Normalized intensity of dierent diraction
orders for incidence angle in = 5 . Intensity is normalized to incident eld intensity.

can be used to take advantage of the analytical solution and decrease the computation time signicantly. It combines the analytical solution and the nite element computation. The usage of the domain decomposition solver will be explained in the next tutorial example.

6.6. PHOTOLITHOGRAPHY II : EUV - MASK REVISITED

49

6.6

Photolithography II : EUV - Mask revisited

Learning Targets reection from an EUV mask domain decomposition algorithm Project Description We compute the reection of light from the EUV mask that was introduced in the previous EUV tutorial with a domain decomposition algorithm. Here we allow arbitrary incidence of the plane wave (angle between wave vector and normal vector of the multilayer surface = 5 , angle between wave vector and projection of wave vector onto the computational domain = 10.2) and arbitrary polarization. We will determine the fourier coecients of the reected plane wave with the PropagatingFourierModes post process for periodic domains. The project les to this problem are located in directory TutorialExamples/ Electromagnetics/ TimeHarmonic/ Scattering/ Planar/ PlanarXYZ/ EUVmask/ relative to JCMwaves home directory. Use JCMgeo to triangulate the layout and JCMsolve to compute the project. Results The domain decomposition algorithm works as follows. First propagation of the incident plane wave within the absorber structure is computed without the multilayer structure underneath using the nite element method. In a second step the propagation of light within the multilayer is determined analytically where the solution from the previous step on the lower boundary is taken as a source. The reected light from the multilayer and the incident plane wave on the absorber are then taken as a source for the computation of the absorber structure. These steps are iterated until a chosen accuracy is reached.

50

CHAPTER 6. SCATTERING

Discussion Although we have an arbitrarily polarized eld and therefore more unknows the project is solved very fast due to the domain decomposition algorithm. The intensity of the computed eld is shown in Figure 6.8.

Figure 6.8: EUV mask: Intensity of electric eld computed with domain decomposition
algorithm.

For periodic scatterers an incoming plane wave is scattered into dierent diraction orders which depend on the periodicity. The post process PropagatingFourierModes computes the complex amplitudes of all propagating diraction orders. Quick own Modications The multilayer structure is not described in layout.jcm but in materials.jcm. In the MaterialBag of layout.jcm we nd the entry LayeredMedia with the parameter lists LayerThickness, RelPermeabilityInLayers, and RelPermittivityInLayers which charaterize the multilayer. The rst entry of these lists species thickness and material properties of the rst layer and so on. The number of entries in all lists have to be the same of course. The substrate below the multilayer

6.6. PHOTOLITHOGRAPHY II : EUV - MASK REVISITED

51

is characterized by the material parameters RelPermeabilityLowerDomain and RelPermittivityLowerDomain. The Id value is used as MaterialId in layout.jcm to specify on which transparent boundary the multilayer is attached to the computational domain. In this example the relative error of the eld energy did not reach the specied error criterion of 1 in the control le with two adaptive renement steps. In such a case JCMsolve gives a warning at the end of the computation.

52

CHAPTER 6. SCATTERING

6.7

Mie Scattering

Learning Targets cylindrically symmetric problems post-process: evaluation of far eld coecients CoordinateRenaming symmetry axis

Figure 6.9: Mie scattering (scattering from a perfect sphere): 2D slice of the 3D geometry.

Project Description In this tutorial example we consider scattering of a plane wave with wavelength = 1.047m from a sphere with radius r = 0.7m, so called Mie scattering. The layout of this three dimensional problem is cylindrically symmetric. The project can therefore be solved on a two dimensional computational domain. The layout of the problem has to be described

6.7. MIE SCATTERING

53

on a slice of the cylinder including the symmetry axis as a boundary as shown in Figure 6.9. In scattering problems it is often desirable to determine the scattered electric eld far away from the scatterer. This computation is implemented in the FarFieldEvaluation post process. The project les to this problem are located in the directory TutorialExamples/ Electromagnetics/ TimeHarmonic/ Scattering/ Cylindrical/ MieScattering/ relative to JCMwaves home directory. Results In the tutorial directory we nd the matlab script check.m. This computes the analytical solution of the Mie scattering problem and compares the analytical far eld values to the simulated ones at the EvaluationPoints specied in the post process. We nd very good agreement. Discussion If we use the FarFieldEvaluation post process we have to take care to choose the evaluation points relatively far away from the computational domain. Note that we not only get the correct intensity but also the correct phase of the scattered eld. The points where the far eld is evaluated can be given in polar coordinates as introduced in Figure 6.10. If one is used to another labeling of the coordinate axes one can dene a CoordinateRenaming. It is dened for a FarFieldEvaluation post process: FarFieldEvaluation { MaterialFileName = "./materials.jcm" SourceFileName = "./sources.jcm" CoordinateRenaming = X:Z:-Y

CoordinateType = { ... } } }

54

CHAPTER 6. SCATTERING

The syntax of CoordinateRenaming can be understood as follows. Fig. 6.10 shows the original coordinate system. The computational domain always lies in the x-y plane. Now we want to rename the axis. The new name of the original x-axis is written before the rst colon, the new name of the original y-axis is between both colons and the name of the original z-axis after the second colon. Hence CoordinateRenaming = X:Z:-Y means the new x-axis agrees with the old x-axis, the new z-axis agrees with the old yaxis, the new (y)-axis agrees with the original z axis. This is shown in Fig. 6.11. Only right handed coordinate systems are allowed. Furthermore the points where the far eld is evaluated have to be specied in the renamed coordinate system. The results of the post process are also given in the renamed coordinate system. Quick own modications We can change the evaluation points in the FarFieldEvaluation post process in project.jcmp. Here the points are specied by the CoordinateType Polar. For a xed Radius we can choose PointLists of values for the polar angles. The number of points where the far eld is evaluated and therefore the length of the PointList is arbitrary but PointsPhi and PointsTheta must have the same length. Use the matlab script check.m to check the results.

6.7. MIE SCATTERING z

55

(Theta)

evaluation point

r (Radius) y

(Phi) x Figure 6.10: Coordinate system used for far eld evaluation. A 2D computational domain always lies in the x-y plane. For evaluation points in the x-y plane we have = 90 .

evaluation point r (Radius) (Theta) (Phi) z

x y Figure 6.11: A CoordinateRenaming is also possible. Here the coordinate system after renaming of 6.10 is shown. The x-axis is not changed, the new y-axis is the former (z)-axis, and the new z-axis is the former y-axis.

56

CHAPTER 6. SCATTERING

6.8

Circular Pupil (cylindrical)

Learning Targets cylindrically symmetric scattering project post-process: Fourier transform post-process: aerial image (far eld image after imaging) Project Description In this project we compute transmission of light through an isolated circular pupil in a gold foil. Because of the rotational symmetry this project is computed as a cylindrical problem on a 2D slice as explained in project 6.7. After the nite element computation of the near eld we are interested in the far eld image. Since we do not have a peridoic layout the far eld is not represented by a discrete set of propagating diraction modes but by a continuous Fourier transform. A discrete sampling of the Fourier transform of the image is computed in the FourierTransform post process and then used in the ExportImageToAmira post process to determine the aerial or far eld image of the pupil. A Matlab script for visualization of the far eld is included in the project directory. In project 6.9 we will compute the same problem in 3D without making use of the rotational symmetry. The project les to this problem are located in directory TutorialExamples/ Electromagnetics/ TimeHarmonic/ Scattering/ Cylindrical/ CircularPupil/ relative to JCMwaves home directory. Use JCMgeo to triangulate the layout and JCMsolve to compute the project. Results A 2D slice of the layout is triangulated. The symmetry axis corresponds to the left boundary of the computational domain. The gold foil is partially in the computational domain and extends to innity in the quadrilaterals of the transparent boundary conditions. The radius r of the circular pupil is equal to the distance between the symmetry axis and the gold foil, r = 2 m.

6.8. CIRCULAR PUPIL (CYLINDRICAL)

57

The rst post process FourierTransform computes the Fourier transform of the near eld in the half space above the layout. Above hereby means the half space y > ymax where ymax is the y-coordinate of the top boundary of the layout. For better comparison with project 6.9 and for applicability of the postprocess PassOpticalSystem (which by default assumes propagation in z-direction) a CoordinateRenaming = X:Z:-Y is introduced since for the 3D geometry the z-axis corresponds to the y-axis of this rotationally symmetrical problem. The parameter DeltaK denes the resolution of the sampling of the Fourier transform. The post process PassOpticalSystem corresponds to aerial imaging with a dened spot magnication and numerical aperture. The post process ExportImageToCartesianGrid uses the output from the aerial imaging postprocess to build up the spatial aerial image after imaging on a 3D space domain specied by GridPointsX, GridPointsY, GridPointsZ. The computation of the aerial image is simply the inverse Fourier transform. Let us denote the Fourier transform of the electric eld by E(kx , ky , kz ) = E(k). Then the inverse Fuorier transform is dened by:

E(x)

dkx

dky

dkz E(k) exp (ik x) .

(6.1)

Numerically we only have a discrete version of the continuous Fourier trans form E(k) for a number of k-values k. The discrete version of Eq. (6.1) then reads: Eh (x)
i j k

(i,j,k)Eh (k(i,j,k)) exp ik(i,j,k) x ,

(6.2)

where the superscript h denotes the discretization of the far eld and Fourier transform. The term (i,j,k) denotes the nite integration volume in the 3D k space. The post process FourierTransform computes the terms (i,j,k)Eh (k(i,j,k) ) for a number of k-values and writes these products together with the k-values into the output le. Decreasing DeltaK makes the inverse Fourier transform (6.2) more accurate. The near eld and the aerial image can be visualized using JCMview.

58

CHAPTER 6. SCATTERING

6.9

Circular Pupil (3D)

Learning Targets 3D scattering project with stacked layout post-process: fourier transform post-process: aerial image (far eld image) Project Description In this project we compute transmission of light through an isolated circular pupil in a gold foil. In contrast to project 6.8 we compute the project in 3D. The 3D layout is thereby described by a stack of layers of specic height with material distributions which change only in 2D. After the nite element computation of the near eld we are interested in the aerial image. The fourier transform of the near eld is computed with the FourierTransform post process and then used in the PassOpticalSystem and ExportImageToCartesian post processes to determine the aerial image of the pupil. The project les to this problem are located in directory TutorialExamples/ Electromagnetics/ TimeHarmonic/ Scattering/ Stack/ CircularPupil/ relative to JCMwaves home directory. Use JCMgeo to triangulate the layout and JCMsolve to compute the project. Results A discussion about the computation of the fourier transform and far eld can be found in project 6.8. The eld distributions can be visualized using JCMview. A comparison to the far eld obtained in project 6.8 shows good agreement. Dierences are due to the coarser grid in the 3D computation. Furthermore in the 3D computation the circle is approximated by a polygon and therefore not perfectly round in contrast to the rotationally symmetric computation. Let us have a look at the description of the 3D layout. It is described in layout.jcm by a stack of layers of specied heights (see also the JCMgeo

6.9. CIRCULAR PUPIL (3D)

59

tutorial for a detailed description of stacked layouts). The triangulated geometry (le grid.jcm) can be visualized using JCMview. We nd a Polygon and a Circle in the layout le. The following HeightProfile now describes of which materials the circle and the parallelogram consist in each layer. The 3D layout is a stack of 3 layers with 2D structure. Layer { Thickness = 0.02 MaterialIdMapping = [1 101 2 101] } Layer { Thickness = 0.1 MaterialIdMapping = [1 102 2 101] } Layer { Thickness = 0.02 MaterialIdMapping = [1 101 2 101] } Above and below InfiniteLayers are dened corresponding to the exterior domains. The parameter Thickness denes the extension of the respective layer in z-direction. The MaterialIdMapping maps the MaterialIds of the geometrical objects in the layout le onto the Ids of the material le. E.g., [1 102 2 101] in a specic layer means: In this layer, MaterialId 1 appearing in the 2D section of the layout le is mapped onto Id 102 in the material le and MaterialId 2 appearing in the layout le is mapped onto Id 101 in the material le for this layer.

60

CHAPTER 6. SCATTERING

Chapter 7 Propagating Modes


7.1 Propagating Mode Problems

The computation of propagating modes is a central task in the design of optical waveguides. In section 3.2.3 we already dended the propagating mode problem mathematically: We consider waveguides that are invariant in z direction and arbitrarily shaped in the x-y-plane. A propagating mode solution of time harmonic Maxwells equations then exhibits a harmonic dependency in the z-direction, E = Epm (x, y) exp (ikz z) H = Hpm (x, y) exp (ikz z) . JCMsolve searches for such propagating mode solutions and returns the effective refractive index dened as ne = kz k0 with k0 = 2 0

and the corresponding eigenmode Epm (x, y), Hpm (x, y) respectively. 0 is the vacuum wavelength of the propagating mode; the vacuum wavelength is a parameter dened by the user in the project le.

61

62

CHAPTER 7. PROPAGATING MODES

7.2

Single Mode Fiber

Learning Targets basics of a propagation mode problem tangential magnetic boundary conditions important simulation parameters comparison with approximative scalar mode solver Project Description We compute the fundamental propagation mode of a cylindrical optical ber with a doped silica core (relative permittivity core = 2.113, diameter dcore = 8.2m) and silica cladding (cladding = 2.1025, diameter dcladding = 80m), see Figure 7.1. At the outer boundary we assume that the tangential component of the magnetic eld is decayed to zero. The fundamental mode is twofold degenerate. In a sub-project projectE.jcmp the electric components are computed and in the sub-project projectH.jcmp the magnetic eld components are computed.

Silica Cladding

Doped Silica Core

Figure 7.1: Optical ber. Left: The core has a permittivity core = 2.113 and a diameter dcore = 8.2m. The cladding has a permittivity cladding = 2.1025 and a diameter dcladding = 80m. We assume that the tangential component of the magnetic eld vanishes on the outer boundary. Right: Isoline plot of the computed electric eld intensity |E|2 with nite element grid.

7.2. SINGLE MODE FIBER

63

The project les to this problem are located in the directory TutorialExamples/ Electromagnetics/ TimeHarmonic/ PropagatingMode/ SingleModeFiber/ relative to JCMwaves home directory. Use JCMgeo to triangulate the layout and JCMsolve to compute the project. Results We rst discuss the project projectE.jcmp. 1 Let us look at the output during the computation. The computation starts with an initial triangulation (refinement level 0 ...). The grid is rened twice during the computation leading to a more accurate solution. In a renement step each triangle is subdivided into four smaller ones. The output of the last renement step is shown in Figure 7.2. The table computational costs shows information about the computation time and number of unknowns. In each renement level we get an increased number of unknowns and therefore an increased computation time. Note that the computation time per unknown (cpu/unknowns) is nearly constant due to JCMsolves use of ecient solvers. The other tables show the effective refractive index ne of the rst and second mode and information about the convergence of our calculation, which we will explain in tutorial example 7.4 in more detail. The results are stored in the les eigenvalues.jcm and computational costs.jcm in directory projectE results which is created automatically. The le fieldbag.jcm contains the calculated electric eld strength of the propagating modes within the ber. Double-click on this le in the JCMcontrols project explorer in order to start JCMview to view the eld distributions of the computed eigenmodes. Discussion Since the rst and second eective refractive indices are equal we found that our eigenmode is twofold degenerate as we expected. Compute also the magnetic eld distributions of these eigenmodes using projectH.jcmp;
This tutorial example contains several project denition les: projectE.jcmp, projectH.jcmp, projectScalar.jcmp. To switch between these project les within JCMcontrol, please click with the right mouse button on the respective project le name and select Set as active project le . . . . The icons next to the project les indicate which one is active.
1

64

CHAPTER 7. PROPAGATING MODES

*** Solving "projectE.jcmp" - refinement level 2 ... computational costs level unknowns cpu time cpu/unknowns total time -------------------------------------------------------0 1857 00:00:01.55 8.35e-04 00:00:02 1 4169 00:00:03.91 9.38e-04 00:00:04 2 9657 00:00:12.14 1.26e-03 00:00:12 error estimation level est.error ratio -----------------------------0 4.66549532e+18 -/1 5.18812848e+17 8.99 2 8.97437292e+16 5.78 1. effective_refractive_index level eigenmode delta ratio -----------------------------------------------------0 1.451113e+00 + 0.000000e+00i -/-/1 1.451114e+00 + 0.000000e+00i 1.23e-07 -/2 1.451114e+00 + 0.000000e+00i 3.76e-08 3.27 2. effective_refractive_index level eigenmode delta ratio -----------------------------------------------------0 1.451113e+00 + 0.000000e+00i -/-/1 1.451114e+00 + 0.000000e+00i 1.23e-07 -/2 1.451114e+00 + 0.000000e+00i 3.76e-08 3.27 *** computation finished successfully

Figure 7.2: Single Mode Fiber: Information produced by the nite element solver for the rst and second mode. This information is also stored in the les computational costs.jcm and eigenvalues.jcm.

7.2. SINGLE MODE FIBER

65

Figure 7.3: Isoline plots of electric elds z-components Ez (imaginary part) for the twofold degenerate fundamental mode. it is found that this project converges as expected to the same fundamental eigenmodes with exactly the same eective refractive index. Figure 7.1 (right) shows the intensity iso-lines of the computed electric eld. In Figure 7.3 the z-components of the twofold degenerate fundamental modes are plotted. The eld is conned in the core of the ber and vanishes quickly (exponentially) with the distance to the core. This justies our assumption that the tangential components of the magnetic eld at the outer boundary of the cladding are zero. Boundary conditions which set the magnetic (electric) eld to zero on a boundary are so called Dirichlet boundary conditions. They are specied in the le boundary conditions.jcm. In tutorial example 7.3 and 7.7 transparent boundaries are used to take into account coupling of so-called leaky waveguide modes with the exterior domains surrounding the ber cross section. Quick own modications Now we can modify our problem. The basic simulation parameters are specied in projectE.jcmp: Lambda0 is the vacuum wavelength of light that propagates through the ber. In order to nd a propagation mode we have to make an initial guess (e.g., Guess = 1.5) for the eective refractive index. We can change

66

CHAPTER 7. PROPAGATING MODES this parameter to nd higher eigenmodes, e.g. Guess = 1.3. The parameter NumberEigenvalues species the number of eigenvalues that are determined numerically. Beside these physical model parameters we can control the accuracy of our computation. If the propagation constant is determined with an error smaller than the value PrecisionEigenvalues the calculation is stopped. MaxNumberSteps gives an upper bound for the number of renement steps of the grid that are performed during the computation. Adaptivity species if the grid is rened adaptivly or regularly. Thereby Adaptivity = yes is recommended in most cases since adaptive renement usually enhances the convergence rate of the results (i.e. decreases cpu time and leads to more accurate results). When using adaptivity the grid is rened only in regions with a large estimated error whereas without adaptivity the grid is rened uniformly. Try PrecisionEigenvalues = 1e-10 and increase MaxNumberSteps = 5 to get a more accurate result. Furthermore, compare, e.g., computations with Adaptivity = yes / no.

The geometry of the ber is described in layout.jcm: Change the Radius of the doped silica core SMFCore or of the silica cladding ComputationalDomain. The parameter RefineAll species how accurate the respective circle is resolved in its polygonal representation. The relative permeabilities and permittivities of the domains are specied in materials.jcm. Investigate how the eigenvalues change with the permittivities of the materials. Scalar Approximation The jump of the refractive index between the core and the cladding of the ber is small (ncore /ncladding 1.0024). Therefore, we want to check how close we get to the true vectorial solution by the scalar approximation where the jump of the normal eld along the material bound is neglected. This approximation yields the same scalar eigenvalue problem for the electric and magnetic eld equation. Hence the fundamental mode is not anymore twofold degenerate. The corresponding project le is named

7.2. SINGLE MODE FIBER

67

projectScalar.jcmp. In fact one nds that for the investigated simple problem, this approximation yields the exact eigenvalue up to a relative accuracy of 106 . In the post-process ExportFields we export our simulation result fieldbag.jcm to the AMIRAformat fieldbag.am. This le can be used for visualization with the JCMview, AMIRA, or Matlab(see section 4.4).

68

CHAPTER 7. PROPAGATING MODES

7.3

Leaky Waveguide

Learning Targets transparent boundary conditions leaky propagation modes convergence to analytical solution

Project Description We compute so called leaky propagation modes of a waveguide. Determination of these modes has to take into account that radiation can leak into the exterior. Therefore leaky modes are damped while propagating along the waveguide. The eective refractive index becomes complex.

dlayer rcore core layer exterior = core

Figure 7.4: Leaky waveguide structure: A silica core (permittivity core = 2.1025, radius
rcore = 1m) is surrounded by a thin layer of low refractive index material (layer and thickness dlayer = 0.2m) and an innite exterior domain consisting also silica.

7.3. LEAKY WAVEGUIDE

69

We use a very simple waveguide structure to compare our numerical result to an analytical solution of the problem. This analytical solution is implemented in the Matlabscript check.m located in the same tutorial folder. The layout is as follows: A silica core (core = 2.1025) is surrounded by a thin layer of low refractive index material (layer = 1.4). The exterior also consists of silica and extends to innity. The layout is shown in Figure 7.4. Transparent boundary conditions model that radiation can leak from the nite computational domain to the exterior without reections. The project les to this problem are located in the directory TutorialExamples/ Electromagnetics/ TimeHarmonic/ PropagatingMode/ LeakyFiber/ relative to JCMwaves home directory. Use JCMgeo to triangulate the layout and JCMsolve to compute the project. Results As expected we observe that the eective refractive index becomes complex. Now we can use the Matlabscript check.m to check if the computed eective refractive can also be found analytically. We start check.m with the computed result (we specify the rst 2 digits). >>> check(1.38) Discussion The nite element solution agrees very well with the analytical result. Since the eective refractive index is complex the leaky mode is damped while propagating along the ber. Note: If one calculates a leaky mode and is especially interested in the imaginary part of the eective refractive index and if the imaginary part is much smaller the real part it can be more ecient to use regular renement (Adaptivity = No in the project le). The adaptive renement strategy reduces the relative error of the complex eective refractive index. In such cases adaptivity may mainly reduce the error of the larger real part of the eective refractive index. Quick own modications Now we can change the material parameters of the layout in le materials.jcm. Furthermore we can change the layout itself, layout.jcm. The layout consists of two concentric circles. The radius of the core (Circle with Name = "Core") is specied by Radius = 1.0.

70

CHAPTER 7. PROPAGATING MODES

The thickness of the layer around the core is determined by Radius = 1.2 of the Circle with Name = "Layer", i.e., we have a layer with thickness 1.2 1.0 = 0.2. The Guess = 1.385 in project.jcmp can be modied to look for other propagating modes, as explained in tutorial example 7.2. The material and layout parameters can also be adjusted in the rst lines of check.m to verify other nite element results.

7.4. RECTANGULAR MICROWAVE WAVEGUIDE

71

7.4

Rectangular Microwave Waveguide

Learning Targets comparison of numerical simulation and analytical solution convergence of the numerical simulation tangential electric (perfectly conducting) boundary conditions Project Description We compute the eight rst modes of an air lled rectangular microwave waveguide with sidelengths 0.1 m and 0.05 m, propagating with a vacuum wavelength of 0.1 m. At the outer boundary we impose perfectly conducting electric boundary conditions. This means that the electric eld is normal to the boundary. The project les to this problem are located in the directory TutorialExamples/ Electromagnetics/ TimeHarmonic/ PropagatingMode/ RectangularMicrowaveWaveguide/ relative to JCMwaves home directory. Use JCMgeo to triangulate the layout and JCMsolve to compute the project. Results In the HelloWorld example 7.2 we already described that in each renement step of the calculation we get a more accurate result. Now we want to quantify this convergence of the numerical simulation. Therefore we compare the simulation results to the analytical solution of our problem. The exact eigenmodes (eective refractive indices) to the problem are given by: ne,m,n = 1 m2 n2 4

with m 0, n 0 and m + n 1. This formula yields the analytical values for the rst eight eective refractive indices shown in table 7.1. Solving project project.jcmp we get the numerical values for ne . They are also shown in table 7.1.

72 nef f 1 2 3 4 5 6 7 8

CHAPTER 7. PROPAGATING MODES analytical 0.866025404 0.0(2) 0.5i(2) 1.0i(2) 1.11803399i numerical 0.8660254 0.0000951 0.0002082i 0.5000000i 0.5000001i 1.000000i 1.000000i 1.118034i

Table 7.1: Eective refractive index nef f of rectangular waveguide. Comparison of


analytical and numerical solution for the rst 8 eigenmodes. In the analytical result (2) means that this mode is twofold degenerated.

Discussion We see that the computed nite element solution is in perfect agreement with the exact eigenvalues. Lets have a closer look at the convergences of the rst and eighth mode. The convergence information produced by the solver is given in Figure 7.5. The nite element grid is rened uniformly. One expects that the computed discrete solution converges to the exact value. Each row in the tables corresponds to one grid level. To check convergence one monitors the relative deviation of the eigenvalues corresponding to two successive grid levels. This is given in column delta. To assure convergence this relative deviation must decrease with a xed rate ratio. For this examples one expects theoretically an asymptotic ratio equal to 16.0. As can be seen in Figure 7.5 this asymptotic rate is indeed reached (column ratio). The electric elds of the computed eigenmodes are plotted in Figure 7.6. Quick own modications Now we can modify the problem. The number of renement steps, precision, and adaptivity can be modied to test the convergence towards the exact solution with higher precisions. Since we know the analytical values for the eective refractive index we can try to nd specic higher eigenmodes by setting Guess to a value close to ne,m,n with larger n, m.

7.4. RECTANGULAR MICROWAVE WAVEGUIDE

73

1. effective_refractive_index level eigenmode delta ratio -----------------------------------------------------0 8.656588e-01 + 0.000000e-01i -/-/1 8.660004e-01 + 0.000000e-01i 3.94e-04 -/2 8.660238e-01 + 0.000000e-01i 2.70e-05 14.62 3 8.660253e-01 + 0.000000e-01i 1.72e-06 15.66 4 8.660254e-01 + 0.000000e-01i 1.08e-07 15.92 5 8.660254e-01 + 0.000000e-01i 6.77e-09 15.98 8. effective_refractive_index level eigenmode delta ratio -----------------------------------------------------0 0.000000e+00 + 1.270872e+00i -/-/1 0.000000e+00 + 1.129058e+00i 1.26e-01 -/2 0.000000e+00 + 1.118887e+00i 9.09e-03 13.94 3 0.000000e+00 + 1.118090e+00i 7.13e-04 12.75 4 0.000000e+00 + 1.118038e+00i 4.67e-05 15.28 5 0.000000e+00 + 1.118034e+00i 2.95e-06 15.82 Figure 7.5: Rectangular Microwave Waveguide: Convergence information produced by the nite element solver for the rst and eight mode. The convergence rate (ratio) is in very good agreement with the theoretically expected rate for second order nite elements.

74

CHAPTER 7. PROPAGATING MODES

1)

2)

3)

4)

5)

6)

7)

8)

Figure 7.6: Rectangular Microwave Waveguide: Vector plots of the eight rst propagating modes (electric eld).

7.5. DIRECTIONAL COUPLER

75

7.5

Directional Coupler

Learning Targets guided modes in more complex structures TE/TM approximation Problem Description We compute the rst four fundamental modes of a directional coupler. The structure is as depicted in Figure 7.7. The coupler is analyzed at a vacuum wavelength of 0 = 1.55 m. The substrate consists of indium phosphite with a refractive index of nsub = 3.17. The waveguide layer is made of indium gallium arsenide phosphite, nlayer = 3.38. The two ribs of the coupler are symmetrically arranged and have a height of h = 1.0 m and a width of w = 2.4 m. The distance between the ribs is equal to d = 4.4 m. The coupler may be regarded as a structure composed of two waveguides which are close to each other. The project les to this problem are located in the directory TutorialExamples/ Electromagnetics/ TimeHarmonic/ PropagatingMode/ DirectionalCoupler/ relative to JCMwaves home directory. Use JCMgeo to triangulate the layout and JCMsolve to compute the project.

w d

w h

Air InGaAsP InP

Figure 7.7: Directional Coupler: In the example we use d = 4.4 m, h = 1.0m and
w = 2.4 m.

76

CHAPTER 7. PROPAGATING MODES

Results The computed propagation constants are: ne,1 ne,2 ne,3 ne,4 = = = = 3.194984 3.194929 3.188598 3.188552

Discussion The rst and second modes and the third and fourth modes are very close to each other respectively. They are nearby degenerate. This is due to the relatively large distance of the ribs. For larger distances of the ribs the coupling between the two waveguides vanishes and the rst and second modes are simply the two fundamental modes of the separeted waveguides. Figure 7.8 shows vector plots of the magnetic elds. The z-components of the elds are non-zero but much smaller than the components in the cross section, see Figure 7.9. TE/TM approximation Modes which are nearly completely polarized in one spatial direction (TM, TE) are typical for some optical waveguide congurations. In this example the ribs of the two waveguides may be considered as a (small) perturbation of a slab structure. For this special situation a TE/TM approximation is sometimes used, where all weak components are neglected. This yields two dierent scalar eigenvalue problems for TE and TM modes. The corresponding project les are called projectTE.jcmp and projectTM.jcmp.2 The dierence between the project le for the rigorous solution and the project les for the approximations are only few lines: Rigorous { MagneticXYZ { in project.jcmp (for the rigorous solution), Approximate { SemiVectorialMagneticX {
This tutorial example contains several project denition les: project.jcmp, projectTM.jcmp, projectTE.jcmp. To switch between these project les within JCMcontrol, please click with the right mouse button on the respective project le name and select Set as active project le . . . . The icons next to the project les indicate which one is active.
2

7.5. DIRECTIONAL COUPLER

77

1)

2)

3)

4) Figure 7.8: Directional Coupler: Magnetic eld vector plots of the rst four eigenmodes.

78

CHAPTER 7. PROPAGATING MODES

Figure 7.9: Directional Coupler: Isoline plots of the magnetic eldss z-components.

7.5. DIRECTIONAL COUPLER in projectTM.jcmp for the TM approximation, Approximate { SemiVectorialMagneticY {

79

for in projectTE.jcmp for the TE approximation. Using approximations can save some computation time. The computed propagation constants are: ne,TE,1 ne,TE,2 ne,TM,3 ne,TM,4 = = = = 3.194816 3.194766 3.188619 3.188561

Now we compare this result to the propagation constants ne,i obtained without TE/TM approximation. We see very good agreement. But the error of the TE/TM approximation (ne,i ne,TE/TM,i ) is larger than the relative distances between the rst and second mode (ne,1 ne,2 ), and between the third and fourth mode (ne,3 ne,4 ), respectively. Hence the TE/TM approximation should not be used if one is interested in small splittings of the eigenvalues. Quick own Modications We can modify the distance d between the two ribs. We expect that the magnitude of the splitting of the propagation constants ne,1 , ne,2 and ne,3 , ne,4 respectively changes. Therefore we have to modify the position of the ribs, which can be done in layout.jcm. To increase or decrease the distance please edit, e.g., the parameter GlobalPositionX for the two polygons corresponding to the ribs. The parameter GlobalPositionX denes an oset of the polygon points. For smaller distances of the ribs the eigenvalue splitting of the eigenmodes should increase.

80

CHAPTER 7. PROPAGATING MODES

7.6

Plasmonic Waveguide

Learning targets calculation of plasmon-polaritons multiscale problem adaptive renement exploitation of symmetric geometry post-process: computation of magnetic eld from electric eld Problem Description This example is taken from Berinis paper 1 . We compute a Plasmon-polariton wave guided by a thin silver lm bounded by dierent dielectrics. The geometry is sketched in Figure 7.10. The relative permittivities of the lower and upper materials are given by r,1 = 4.0 and r,3 = 3.61. The structure is analyzed for a vaccum wavelength 0 = 0.633 m. The metal lm (silver) has a relative permittivity of r,2 = 19 + 0.53i at this wavelength. In this example we compute the ss1 -mode b (c.f., Berini) which has a mirror symmetric electric eld with respect to the symmetry axis of the waveguide. Therefore it suces to discretize only one half of the waveguide and to impose a magnetic boundary condition at the symmetry axis. The metal lm has a thickness of t = 0.0245 m and a width of w = 1 m. The project les to this problem are located in the directory TutorialExamples/
P. Berini, Plasmon-polariton waves guided by thin lossy metal lms of nite width: Bound modes of symmetric structures, Physical Review B 61, 10484 (1999)
1

Upper Material t Silver w


1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0 1 0

Lower Material

Figure 7.10: Plasmon-polariton waveguide. The metal lm has a thickness of t = 0.0245 m and a width of w = 1 m.

7.6. PLASMONIC WAVEGUIDE

81

Figure 7.11: Plasmon-polariton waveguide: Field intensity around the metal lm. The electric eld is highly discontinuous across the material borders. At the corners of the metal lms characteristic singularities are clearly visible.

Figure 7.12: Plasmon-polariton waveguide: Imaginary part of electric elds zcomponent (Ez ) around the metal lm. The zcomponent of the electric eld is continuous but its derivative jumps across material interfaces.

Figure 7.13: Discretization of the computational area close to the silver lm: Electric eld strength in the vicinity of the metal lm. Especially at the metals corners the computational domain discrtetized very coarse. Electromagnetics/ TimeHarmonic/ PropagatingMode/ Plasmon/ relative to JCMwaves home directory. Use JCMgeo to triangulate the layout and JCMsolve to compute the project. Results In this example we will not look at the propagation constant but concentrate our attention on the numerical solution for the electric eld intensity on the whole computational domain, which represents a Plasmonpolariton, see Figures 7.11, 7.12.

Discussion The accurate computation of plasmon-polariton modes is a challenging problem due to the singular eld behaviour near the metals corner and due to the multi-scale structure of the geometry. We have a very slim silver lm at the interface of two thick substrates. The propagating Plasmon-polariton is mainly located at the vicinity of the silver strip. An adaptive nite element discretization is the method of choice for such prob-

1 0 0 . . 5 1 5 0 . 5 0 0 . 5

82

CHAPTER 7. PROPAGATING MODES

7.6. PLASMONIC WAVEGUIDE

83

lems. Figure 7.13 shows the mesh for the FEM computation on the last mesh renement level. Due to the adaptive renement steps the mesh is rened especially close to the strip and close to the metals corners were the electric eld shows singular behaviour and has to be resolved very accurately. In the post-process ElectricFieldStrengthToMagneticFieldStrength we compute the magnetic eld (fieldbag magnetic.jcm) from the simulated electric eld (fieldbag.jcm). Then we use the ExportFields process to export the resulting magnetic eld to the AMIRA le format (fieldbag magnetic.am). Note that the two post processes have to be in this order in the project le.

84

CHAPTER 7. PROPAGATING MODES

7.7

Photonic Crystal Fiber

Learning Targets computation of leaky modes transparent boundary conditions boundary conditions for modes in symmetric geometries post-process: computation of energy ux through interface

Figure 7.14: Geometry of a hollow core photonic crystal ber: the high-index background material (glass) is perforated by air holes in a hexagonal arrangement, and by a large central air core. Mirror boundary conditions apply to the lower and left boundaries.

1 5 0 0 0 .

0 . 5

7.7. PHOTONIC CRYSTAL FIBER

85

Project Description We compute so called leaky propagation modes in a hollow-core photonic crystal ber (HCPCF). A HCPCF guides light in a hollow core which is surrounded by a photonic crystal structure. This structure greatly reduces leakage to the exterior of the ber. The hollow core is usually lled with air or other gases. In tutorial example 7.2 we already computed propagation modes in a single mode ber. Since the electric eld at the outer boundary of the ber was very weak we used TangentialMagnetic boundary conditions, i.e., we set the tangential component of the magnetic eld equal to zero at the boundary. In this example we have to take into account that radiation can leak to the exterior of the computational domain due to the fact that the refractive index in the main waveguiding region is smaller / not larger than in the exterior. Therefore we apply transparent boundary conditions to the outer boundaries of our layout. Figure 7.14 shows a quarter of the HCPCF layout. Mirror boundary conditions are applied to the left and lower boundaries of the computational domain. To check that energy is leaking to the exterior we use the post-process ElectricFieldStrengthToEnergyFluxThroughInterfaces. It computes the energy ux through the boundaries of our computational domain. The project les to this problem are located in the directory TutorialExamples/ Electromagnetics/ TimeHarmonic/ PropagatingMode/ HollowCoreFiber/ relative to JCMwaves home directory. Use JCMgeo to triangulate the layout and JCMsolve to compute the project. Results The computed eigenmodes are written to eigenvalues.jcm in directory project results. Figure 7.15 shows the intensity of the corresponding propagation mode. Discussion The propagation constant now has an imaginary part, i.e., the computed leaky mode is damped while propagating through the ber. This is a result of the transparent boundary and leakage of radiation to the exterior. Since the problem is symmetric we choose only one quarter of the ber cross section as computational domain. At the inner boundaries we specify boundary conditions which dene the symmetry properties of the computed

86

CHAPTER 7. PROPAGATING MODES

Figure 7.15: Intensity of propagating mode within hollow-core photonic crystal ber.
Plot produced with matlab. The script Load.m for loading simulation data into matlab and producing this plot is included in the tutorial directory.

eigenmodes. Now we look at the energy ux through the boundaries of our computational domain energyFluxThroughInterfaces.jcm in the result directory. The table rows hold the values of energy ux between all pairs of adjacent materials. The physical observable of interest is the real part of the energy ux. In this tutorial example the ux from the region with material Id = 1 (material: glass inside the computational domain) to the region with material Id = 3 (material: glass in the exterior domain) corresponds to leakage to the exterior.

Chapter 8 Resonance Modes


8.1 Resonance Problems

The computation of resonances is one of the central steps in the analysis of an optical device. We consider true eigenmodes of the Maxwell operator (bounded modes) as well as radiating/leaky modes as resonances. An open device may have bounded modes as well as leaky modes radiating energy into the innitely extended exterior. The resonance mode solver also allows for the band gap computation of a photonic crystal or any other device with a periodic arrangement.

87

88

CHAPTER 8. RESONANCE MODES

8.2

Rectangular Resonator

Learning Targets basics of resonance problem convergence of numerical simulation tangential electric (perfectly conducting) boundary conditions Project Description We compute eight modes of an air lled rectangular resonator with sidelengths a = 10 m and b = 7 m. At the outer boundary we impose perfectly conducting boundary conditions. This means that the tangential component of the electric eld is zero at the boundary. The project projectFundamental.jcmp uses an algorithm that computes a specied number of fundamental eigenmodes (i.e., smallest frequencies), whereas projectNearGuess.jcmp computes eight eigenvalues close to an initial guess for the frequency .1 This can be used to search for specic modes with higher frequencies. The project les to this problem are located in the directory TutorialExamples/ Electromagnetics/ TimeHarmonic/ ResonanceMode/ RectangularResonator/ relative to JCMwaves home directory. Use JCMgeo to triangulate the layout and JCMsolve to compute the project. Results First we start the project projectFundamental.jcmp. The computation starts with an initial triangulation (refinement level 0 ...). The grid is rened four times during the computation leading to a more accurate solution. During the computation each triangle of the initial triangulation is subdivided into four smaller ones in each renement step.
This tutorial example contains several project denition les: projectFundamental.jcmp, projectNearGuess.jcmp. To switch between these project les within JCMcontrol, please click with the right mouse button on the respective project le name and select Set as active project le . . . . The icons next to the project les indicate which one is active.
1

8.2. RECTANGULAR RESONATOR [1014 s1 ] 1 2 3 4 5 6 7 8 analytical numerical 0.941825784 0.941825798 1.34546541 1.34546537 1.64234983 1.64234996 1.88365156 1.88365204 2.31482621 2.31482768 2.69093081 2.69092981 2.82547735 2.82548092 2.85099008 2.85098992

89

Table 8.1: Eigenfrequencies of rectangular resonator. Comparison of analytical and


numerical solution for the rst 8 eigenmodes.

When the simulation is nished the directory projectFundamental results is created which contains the les eigenvalues.jcm, fieldbag.jcm, and computational costs.jcm. These les contain the computed eigenvalues, the electric eld strengths of the corresponding eigenmodes, and the computational costs on the dierent levels of computation (for dierently rened meshes) respectively. Double-click on the le names in the project explorer of JCMcontrol in order to watch the contents of these les. Since this simple example can be solved analytically we can quantify the convergence of the numerical simulation. The exact eigenmodes (frequencies) to that problem are given by: e,m,n = c2 2 r r n2 m2 + 2 a2 b

with m 0, n 0 and m + n 1 and speed of light c. This formula yields the analytical values for the rst eight eigenfrequencies shown in table 8.1. The numerical values for are also shown in table 8.1. Discussion We observe that the computed nite element solution is in very good agreement with the exact fundamental eigenvalues. Let us have a closer look at the output that is produced during computation. Execution of projectFundamental.jcmp produces a convergence table for each eigenmode, e.g., for the 1. eigenmode: *** Solving "projectFundamental.jcmp"

90 - refinement level 4 ...

CHAPTER 8. RESONANCE MODES

1. eigenmode level eigenmode delta ratio ---------------------------------------------------------0 9.42665413e+13 + 0.00000000e+13i -/-/1 9.41884430e+13 + 0.00000000e+13i 8.29e-04 -/2 9.41829534e+13 + 0.00000000e+13i 5.83e-05 14.23 3 9.41826019e+13 + 0.00000000e+13i 3.73e-06 15.62 4 9.41825798e+13 + 0.00000000e+13i 2.35e-07 15.91 The nite element grid is rened uniformly. One expects that the computed discrete solution converges to the true value. Each row in the tables corresponds to one grid level. To check convergence one monitors the relative deviation of the eigenvalues corresponding to two successive grid levels. This is given in column delta. To assure convergence this relative deviation must decrease with a xed rate ratio. For this examples one expects theoretically an asymptotic ratio equal to 16.0. As can be seen this asymptotic rate is indeed reached (column ratio). Now we want to search for higher eigenmodes and execute project projectNearGuess.jcmp. The solver computes eigenmodes close to and below an initial guess (here: Guess = 6e14). This project uses a dierent renement strategy. The initial grid is rened once before the computation of eigenmodes starts. This is specied with the parameter PreRefinements = 1. Furthermore an adaptive renement strategy (Adaptivity = yes) is used. Thereby the error of the computed solution on each triangle is estimated prior to each renement step and only triangles with a large estimated error ( one half of the triangles) are rened. This usually leads to faster convergence of the solution and reduced computation time. Executing the project, output about the computational costs is also produced: *** Solving "projectNearGuess.jcmp" - refinement level 4 ... computational costs level unknowns cpu time cpu/unknowns total time -------------------------------------------------------0 32 00:00:01.01 3.16e-02 00:00:01 1 144 00:00:00.02 1.39e-04 00:00:00

8.2. RECTANGULAR RESONATOR 2 3 4 608 2496 10112 00:00:00.07 00:00:00.33 00:00:01.36 1.15e-04 1.32e-04 1.34e-04 00:00:00 00:00:00 00:00:02

91

Note that the computation time per unknown (cpu/unknowns) is nearly constant due to JCMsolves use of ecient solvers. Quick own modications Now we can modify our problem. The basic simulation parameters are specied in projectFundamental.jcmp, projectNearGuess.jcmp respectively: NumberEigenvalues = 8 species the number of eigenvalues that are computed. For projectFundamental.jcmp these are always the lowest ones. LowerBoundGuess should here be set to some reasonable value for faster convergence of the computation. In projectNearGuess.jcmp the SelectionCriterion is changed from Fundamental to NearGuess. The value set for Guess species the upper boundary where the solver starts to search for eigenvalues. If the initial guess is chosen too small (smaller than one half of the frequency of the rst fundamental eigenmode) the solver nds unwanted eigenvalues. They are many orders of magnitude smaller ( 0) then the rst fundamental mode and belong to gradient elds which are solutions of the static Maxwells equations ( = 0). Beside these physical model parameters we can control the accuracy of our computation. If the eigenvalue is determined with an error smaller than the value PrecisionEigenvalues the calculation is stopped. MaxNumberSteps gives an upper bound for the number of renement steps of the grid that are performed during the computation. Adaptivity species if the grid is rened adaptivly or regularly. Thereby Adaptivity = yes is recommended in the most cases since adaptiv renement usually decreases the cpu time and leads to more accurate results. When using adaptivity the grid is rened only in regions with a large estimated error whereas without adaptivity the grid is rened uniformly. Try PrecisionEigenvalues = 1e-10 and increase MaxNumberSteps = 5 to get a more accurate result. Furthermore you can compare computations with Adaptivity = yes / no. Since we know the analytical values for the eigenvalues you can set Guess in projectNearGuess.jcmp close to a higher eigenvalue and search for it.

92

CHAPTER 8. RESONANCE MODES

The geometry of the ber is described in layout.jcm: You can change, e.g., the Points of the Polygon dening the resonator layout and compare analytical and numerical results The relative permeability and permittivity of the rectangular domain are specied in materials.jcm. Observe how the eigenvalues change with the refractive index (square root of the permittivity) of the material by editing this input data.

8.3. CYLINDRICAL RESONATOR

93

8.3

Cylindrical Resonator

Learning Targets cylindrically symmetric resonance problem Project Description We compute four modes of an air-lled cylindrical resonator with height h = 1 m and radius r = 1 m as shown in Figure 8.1. At the outer boundary we impose perfectly electric boundary conditions. This means that the electric eld is normal to the boundary. The project.jcmp uses an initial Guess and computes a specied number of eigenvalues close to that guess. r

Figure 8.1: Cylindrical resonator with height h and radius r. The project les to this problem are located in the directory TutorialExamples/ Electromagnetics/ TimeHarmonic/ ResonanceMode/ Cylinder/ relative to JCMwaves home directory. Use JCMgeo to triangulate the layout and JCMsolve to compute the project.

94 [109 s1 ] 1 2 3 4

CHAPTER 8. RESONANCE MODES analytical 0.720948615 1.18608776 1.48549430 1.65487818 numerical 0.7209485650 1.1860871132 1.4854580175 1.6548777850

Table 8.2: Eigenfrequencies of a cylindrical resonator. Comparison of analytical and


numerical solutions for the rst four eigenmodes.

Results Since our geometry is cylindrically symmetric the electric and magnetic elds have the dependency eim (m N) on the polar angle . Our project computes the rst four eigenvalues for m = 0 according to our specication NPhi = 0 in the project le. Later we will also choose higher values. This problem can also be solved analytically. You nd a matlab script check.m which computes the rst 20 eigenmodes for m = 0, 1. We compare the numerical and analytical solutions in table 8.2. Discussion We see that the computed nite element solution is in very good agreement with the exact eigenvalues. Creating the layout for a cylindrically symmetric problem one only has to describe one slice of the geomtry, i.e., a two dimensional domain with the y-symmetry axis on a boundary. For this project the computational domain is simply a rectangle with sidelengths h = 1 m and r = 1 m. We have to take care that the symmetry axis is located at the global position x = 0 of our layout, (see also section 3.2.3). All boundaries of the geometry that lie on the symmetry axis have to be specied as Cylindrical in boundary conditions.jcm. Quick own modications Set NPhi = 1 in project.jcmp and compare with the analytical solution obtained from matlab script exact.m.

8.4. HEXAGONAL PHOTONIC CRYSTAL

95

8.4

Hexagonal Photonic Crystal

Learning Targets Bloch periodic boundary conditions photonic crystal band analysis post-process: computation of electric eld density Project Description The resonance mode solver also allows for the band gap computation of a photonic crystal or any other device with a periodic arrangement. To analyze such a device one computes so called Bloch-modes whose corresponding electromagnetic elds exhibit a certain phase jump when spatially shiftet by a lattice vector. From the numerical point of view this makes it possible to restrict the eigenmode computation onto a single unit cell of the lattice.

Figure 8.2: 2D hexagonal photonic crystal: Rows of air holes with radius r and pitch p in dielectric substrate. In this tutorial we consider a two dimensional photonic crystal with columns of air wholes in a dielectric substrate, see Figure 8.2. The radius of

96

CHAPTER 8. RESONANCE MODES

the air holes is r = 0.48 m and the pitch of the periodic lattice is p = 0.5 m. Light is propagating within this plane (x-y-plane). Only light with specic frequencies is able to propagate in the dierent directions within the photonic crystal. For a complete band diagram one has to determine eigenfrequencies for all values of the Bloch vector k within the rst Brillouin zone. As an example we will solve the eigenvalue problem at the M point of the reciprocal lattice. For the electric and magnetic eld polarized perpendicular to the computational domain we get independent eigenvalue problems, called transversal electric (TE) modes and transversal magnetic (TM) modes respectively. In the TE (TM) case the magnetic (electric) eld is polarized parallel to the computational domain. Therefore we have two possibilities to compute the eigenvalues for the TE and TM problem respectively. In the TE case we can either solve the scalar problem for the z-component of the electric eld (project TE scalar) or the vectorial problem for the x-y-components of the magnetic eld (project TE vectorial). The eigenvalues should agree. Analogously for the TM problem we have two projects project TE scalar and project TE vectorial. The project les to this problem are located in the directory TutorialExamples/ Electromagnetics/ TimeHarmonic/ ResonanceMode/ HexagonalPhC/ relative to JCMwaves home directory. Use JCMgeo to triangulate the layout and JCMsolve to compute the project. Results Fixing the Bloch vector at the M point (specied via BlochKX and BlochKY in the project le) of the Brillouin zone we get several eigenvalues for . As expected the TE (TM) eigenvalues agree when computed with the scalar and vectorial projects. Discussion It is sucient to compute the eld distributions on one unit cell of the periodic geometry when periodic boundary conditions are applied. When specifying BlochKX, BlochKY in the project le only solutions which are Bloch-periodic according to this vector are computed. Bloch-periodic

8.4. HEXAGONAL PHOTONIC CRYSTAL

97

1)

2)

3)

4)

Figure 8.3: Hexagonal photonic crystal: Electric energy density plots of the rst four
TE modes.

elds are dened as follows: E(x + p, y) = eikx p E(x, y) E(x, y + p) = eiky p E(x, y), where k = (kx , ky ) is the given Bloch vector. In the post-processes of project TE scalar we compute the electric energy density in the computational domain. Figure 8.3 shows the rst for eigenmodes for the TE case. We observe that the electric eld is mainly located in the dielectric material. Quick own modications Change the Bloch vector to compute other eigenvalues, e.g., BlochKX=0, BlochKY=0 for the point. The layout of the photonic crystal is specied in layout.jcm. Change the Radius of Circle with Name = Hole.

98

CHAPTER 8. RESONANCE MODES

Chapter 9 Embedded Scripting


9.1 Embedded Scripting Description

All of JCMwave input les support embedded scripting. With embedded scripting, the power and diversity of an entire scripting language is placed at your disposal within JCMwaves input les. Embedded scripting support is very useful for example if you want to Create large geometries in only a few lines of code Do parametrized scans e.g. with varying angle of incidence Create customly shaped surfaces on materials An embedded script section is started by a <?LanguageIdentifier tag and ended by a ?> tag. For example Matlab script sections contained within a JCMwave input le must be contained in matching <?Matlab ... ?> tags1 . As of JCMsuite 1.10 it is even possible to start a for-loop in one script section and end it in another. All JCM-code within the loop will then automatically be injected into the resulting .jcm-le for each cycle of the loop2 . Thus the use of jcmwave echo in Matlab-scripted input les to transfer output into the .jcm
For an overview on the dierent types of embedded scripts and their syntax plese refer to table 9.1 at the end of this section. 2 This feature is currently not supported in Pyhton. In Python each script block must contain a fully functional script.
1

99

100

CHAPTER 9. EMBEDDED SCRIPTING

le is obsolete, making your scripts smaller and more readable, though your old scripts will of course continue to work. To mark the input le as a template le, the letter t must be appended to its sux. The scripts as well as the unscripted parts of the JCMwave input le may contain variables that will be passed from the outside. A variable passed from the outside is marked by an identifyer name contained in brackets with a leading % sign and a tailing type identier. Valid type identiers are i for integer variables (also valid for integer arrays), f for oat variables (also valid for oat arrays), s for string variables and e for real and complex double variables (also valid for complex double arrays) As of version 1.11 the structures holding the variables in Matlab have become dynamic, thus enabling you to overwrite variables within your jcm input les. The new features make Matlab-scripting much easier and more convenient. For example to script a horizontal line of circular holes in a material now only requires the following code: ... <?Matlab for k=1:1:10 ?> Circle { MaterialId = 0 Priority = 2 AreaConstraint = 1000000000.000 Radius = 1.0 <?Matlab keys.xpos = (k*3-1); keys.elemname = [circle, num2str(k)]; ?> Name = "%(elemname)s" GlobalPositionX = %(xpos)d GlobalPositionY = 0 RefineAll = 2

9.1. EMBEDDED SCRIPTING DESCRIPTION } <?Matlab end; ?> ...

101

As you will notice, within the second Matlab code block, the values xpos and elemname in the keys-structure are replaced with the correct values for each execution of the for-loop. As another example, if you prefer to use 0 instead of the following simple snippet of Python script will do the transformation for you: ... <?Py import math omega = (2*math.pi)/%(lambda0)e JCMecho(Omega =+str(omega)) ?> ... In your nal .jcm le, e.g. if you pass 15.0 as lambda0 this will result in the line ... Omega = 0.418879020479 ... The transformation process from .jcmt template les containing script blocks into .jcm les ready for use can be seen in gure 9.1. For each supported scripting language a tool called RunEmbeddedScripts is available in the corresponding ThirdPartySupport-subdirectory of JCMwaves home directory. These scripts will then transform your template-le into a temporary standalone le for its own language. For example invoking the Python variant of RunEmbeddedScript will create a .jcm.py le and running the Matlab-version of RunEbeddedScripts will generate a jcmtmp.m le. These les will then be processed by the script language interpreter to create your nal .jcm-les. If errors should occur during the creation or execution of these temporary les, by default the Matlab implementation jcmwave runembeddedscripts will provide debugging information such as location of the erroneous code in the original .jcmt le and matlabs error

102

CHAPTER 9. EMBEDDED SCRIPTING

message3 . To disable error handling for your Matlab scripts, you can simply pass two extra string arguments to jcmwave runembeddedscripts containing the strings ebug and ff. d o To pass the variables to your scripts, in Python a dictionary containing variableIdentifier = variableValue entries is used, in Matlab a structure containing the corresponding pairs is utilized. .jcmt le JCM-code <? user script ?> JCM-code standalone script le generated code .jcm le

JCM code

RunEmbeddedScripts

invoke script interpreter

Figure 9.1: Transformation process for a JCMwave input le containing script code Matlab <?Matlab ?> jcmwave echo(string) structure RunEmbeddedScripts.py Python <?Py ?> JCMecho(string) dictionary jcmwave runembeddedscripts.m

Script start tag Script end tag File output command External variables passed in File to invoke for processing .jcmt

Table 9.1: Overview on the syntax for the currently supported types of scripting Examples using template les containing scripts in the Matlab and Python programming languages will be shown and explained in the following sections.

The error handling will only work properly on Matlab version 7.1 and higher. On older versions, you will receive a message explaining how to locate the erroneous code.

9.2. EMBEDDED SCRIPTING: MATLAB

103

9.2
9.2.1

Embedded Scripting: Matlab


Tutorial project: Refraction at an interface

Learning Targets embedded scripting with Matlab nite element parameters wave propagation error Woods anomaly Project Description In this tutorial project we investigate numerically how the electric eld behaves at a plane interface of two dielectrics. Theory tells us that an incident plane wave Ein is partially reected and transmitted. The reection coecient R and transmission coecient T quantify the amplitude of the reected Er and transmitted light E2 normalized with the amplitude of the incident plane wave. For TE-polarization they are given by Fresnels formulas: TT E = RT E = E2 2n1 cos in , = Ein n1 cos in + n2 n2 sin2 in 2 1 Er n1 cos in = Ein n1 cos in + n2 n2 sin2 in 2 1 n2 n2 sin2 in 2 1 , (9.1)

where n1 and n2 are the refractive indices of the two materials and in the incidence angle, shown in Fig. 9.2. For TM polarization the corresponding expressions are: TT M = RT M = 2n1 n2 cos in n2 cos in 2 n2 cos in 2 n2 cos in 2 + n1 n1 + n1 n2 n2 sin2 in 2 1 n2 n2 sin2 in 2 1 n2 n2 sin2 in 2 1 . (9.2)

For simplicity we assumed that the relative permeabilities of the materials are 1. We will set up this project with embedded scripting using Matlab. The script will use n1 , n2 , in , the wavelength and polarization state as input parameters and create the necessary input les for JCMsolve.

104

CHAPTER 9. EMBEDDED SCRIPTING

n2

E2

n1 Ein Er

in Figure 9.2: A plane wave Ein is incident on a interface of two dielectrics with refractive
indices n1 and n2 under the angle in . The plane wave is partially reected E1 and partially transmitted E2 .

The project les to this problem are located in directory TutorialExamples/ Electromagnetics/ TimeHarmonic/ Scattering/ Planar/ Refraction/ After computation of the project the numerical results for T and R will be determined and compared to the analytical solutions (9.1) and (9.2) respectively. We articially periodify the computational domain in one dimension to simulate an innitely extended interface. In the other dimension we use transparent boundary conditions, see Fig 9.3. In order to compute the complex amplitude of the reected and transmitted light the PropagatingFourierModes post process is used. Since the computational domain is unstructered only the zeroth diraction orders will be non-zero and give us the amplitudes of the transmitted and reected electric eld. In this example the material le depends on the refractive indices n1 , n2 and the source le on the incident angle in the wavelength and the polarization of the incident electric eld.

9.2. EMBEDDED SCRIPTING: MATLAB transparent boundary periodic boundary

105

Figure 9.3: Computational domain for refraction of a plane wave at an interface. The
domain is articially periodied in one dimension to simulate the innite exterior.

The wavelength is also used to scale the size of the computational domain. Since the computational domain is unstructered we could take an arbitrarily small section of the interface, see Fig. 9.3. For visualization and inspection of the convergence however it will extend a few wavelengths here. Furthermore we want to make numerical parameters in the JCMsolve control le project.jcm accessible from the Matlabcontrol le. The les layout.jcm, materials.jcm, layout.jcm, and project.jcmp will therefore be created with embedded scripting. Results Let us rst have a look at the Matlab control le run.m. The struct keys contains all parameters which are needed to dene the project and create the input les for JCMsolve. If this struct is not given as an input parameter to run.m default parameters are set. The struct keys is then passed via the command jcmwave runembeddedscripts to the .jcmt template les. After the four input les have been created the geometry is triangulated with the command jcmwave geo(.) and then the nite element simulation started with jcmwave solve(--solve, project.jcmp). In a post process the propagating fourier modes are computed which are load into the Matlab control le with the jcmwave loadtable command. In the rest of the run.m control le the JCMsolve results are compared to the analytical values of T and R and the eld is visualized. In order to start the project rst you have to add the third party Matlab path via

106

CHAPTER 9. EMBEDDED SCRIPTING

>> addpath YOUR JCMsuite DIR/ThirdPartySupport/Matlab/ and then execute >> jcmwave startup once. Now you can start the project with the default values with >> run The electric eld distribution which is shown corresponds to the case of total reection at the interface (Woods anomaly) which will be explained later. Now let us have a look at the template les. We start with the le layout.jcm which just uses the wavelength to scale the size of the computational domain. This is done in line 7: UnitOfLength = %(lambda)e The name lambda in brackets refers directly to the entry keys.lambda of the struct keys which was passed to the template le. The % sign indicates that a parameter passed from the outside follows and the identier e after the brackets species that the value for lambda is interpreted as a real (or complex) double. Other indentiers are i for integer values and s for string values. When the template le layout.jcmt is converted with the jcmwave runembeddedscripts command then %(lambda)e is replaced with the corresponding value for the parameter. You can check this by opening the created layout.jcm le. Next let us have a look at the materials.jcmt template le. Here we nd a Matlab block. It is opened with <?Matlab and has to be closed with ?> Within this block all Matlab commands are available. Since JCMsolve uses the relative permittivity and permeability as material parameters and not the refractive index the input parameters n1 and n2 are transformed into permittivites by taking the square (we assume that the relative permeabilities are unity). These values are assigned back to the struct keys.epsilon1 and keys.epsilon2 and then used in the material denitions, e.g. RelPermittivity = %(epsilon1)e

9.2. EMBEDDED SCRIPTING: MATLAB

107

In the template le sources.jcmt the wavelength, incidence angle, and polarization state are converted into values for the k-vector and eld strength of the incident plane wave in Cartesian coordinates. Within the rst Matlab block the absolute value of the k-vector and then its x- and y-component are computed using the incidence angle keys.thetaIn: <?Matlab kAbs=2*pi/keys.lambda; keys.kx=kAbs*sin(keys.thetaIn/180*pi); keys.ky=kAbs*cos ?> The eld strength depends on the polarization state which is specied by keys.polarization = TE or keys.polarization = TM. We nd an if ... elseif ... else statement where the polarization state is queried. The JCMsuite syntax is located between the corresponding Matlab blocks and only written into the le sources.jcm is the corresponding polarization state is specied <?Matlab if strcmp(keys.polarization,TE) #Matlab block ?> StrengthX = 0.0 #JCMsolve block StrengthY = 0.0 StrengthZ = 1 <?Matlab elseif strcmp(keys.polarization,TM) keys.Ex=-cos(keys.thetaIn/180*pi); keys.Ey=sin(keys.thetaIn/180*pi); ?> StrengthX = %(Ex)e StrengthY = %(Ey)e StrengthZ = 0.0 <?Matlab else disp([Error: Unknown polarization keys.polarization]) end ?>

108

CHAPTER 9. EMBEDDED SCRIPTING

In the case of TM polarization the eld strength vector has to be oriented perpendicular to the k-vector. For TE polarization we set the z-component of the eld strength to 1. If the polarization state is neither TE nor TM an error message is displayed. Finally we look at the template le project.jcmpt. Depending on the polarization a ElectricZ (TE) or ElectricXY (TM) project is computed. Again the JCMwave syntax blocks are located between the Matlab blocks: <?Matlab if strcmp(keys.polarization,TE) ?> ElectricZ { <?Matlab else ?> ElectricXY { <?Matlab end ?> The parameters InfoLevel, FiniteElementDegree, MaxNumberSteps, PreRefinements are integers and therefore have the identier i, e.g. FiniteElementDegree = %(femDegree)i The value for Adaptivity is either yes or no, i.e. a stringwith identier s: Adaptivity = %(adaptivity)s Now that we have set up the project with embedded scripting we can e.g. conveniently perform scans over certain parameters. Executing the Matlab le angleScan.m the transmittivity T and reectivity R are computed in dependence on the incidence angle. Furthermore the relative error to the analytical solution is given. We notice a sharp drop in the transmittivity T around 42 , which is close to the angle of total reection: 0 = arcsin n2 n1 (9.3)

We can set the values n1 = 1.5, n2 = 1.0 and in = 41.83 in the Matlab le run.m and have a look at the solution. In the lower domain (y 0) we see

9.2. EMBEDDED SCRIPTING: MATLAB

109

the superposition of the incident and reected eld. At the angle of total reection the reectivity is 1 which means that incident and reected eld have the same amplitude. Because of this we nd a very regular pattern of constructive and destructive interference. Above the line y = 0 (domain 2) the electric eld is constant in y direction. This behaviour of the electric eld is refered to as Woods anomaly and often causes problems for transparent boundary conditions. JCMsolves self adaptive transparent boundary conditions however have no problem dealing with this case: *** A Posteriori exterior domain quality check: saturation reached. informs that a close Woods anomaly was detected and properly treated. You can now conveniently set dierent values for the refractive indices, incidence angle, polarization state and numerical parameters in run.m look at the computed nite element solution and check the relative error to the analytical values for the transmission T and reectivity R.

110

CHAPTER 9. EMBEDDED SCRIPTING

9.2.2

Photonic Crystal

The following example will show how to create the geometry for a hexagonal 2D photonic crystal with an arbitary number of rows, number of columns, radius of holes and distance of holes in only a few lines of Matlab code embedded in an JCMwave layout-le. It is intended to give you an idea of the power as well as the syntax of embedded scripting. Creating the geometry of a hexagonal photonic crystal with NRows rows and Ncols columns manually would require you to input the data of all NRows/2NCols + NRows/2(NCols 1) holes in this crystal. By utilizing the loop functions in matlab, you can input only one circle and copy it to the desired positions. To do this, rst we dene a helper function Circle in a le called Circle.m which we will later use from our embedded script. Given the coordinates of the center, the radius and the row and column indices (for naming the circle), this function returns the JCMwave data for the corresponding circle as a string. This is what Circle.m looks like: function string = Circle(i, j, centerx, centery, radius) string = sprintf([ Name = "Circle num2str(i) num2str(j) "\n... MaterialId = 2\n... AreaConstraint = 1000\n... Radius = num2str(radius) \n... This Port = Center\n... GlobalPositionX = num2str(centerx) \n... GlobalPositionY = num2str(centery) \n... RefineAll = 2\n ]); If you are not familiar with the JCMwave input format for geometry layout les, please refer to the JCMwave paramer reference. Next we will write a .jcmt layout le that will call this matlab function with the proper parameters and print the string it returns into the .jcm le. This le should be called layout.jcmt and contain the two following main blocks of code. In the rst code block, the computational domain is created as a polygon: Polygon { Name = "Computational Domain" MaterialId = 1 Priority = -1

9.2. EMBEDDED SCRIPTING: MATLAB AreaConstraint = 1000 <?Matlab NCols = %(NCols)i; NRows = %(NRows)i; SpaceWidth = %(SpaceWidth)e; HoleRadius = %(HoleRadius)e; Offset = %(Offset)e; width = ((NCols-1) * SpaceWidth)... + 2 * HoleRadius+2*Offset; height = ((NRows-1) * SpaceWidth)... + 2 * HoleRadius+2*Offset; keys.points = [0 0 width 0 width height 0 height]; ?> Points = %(points)e }

111

The embedded Matlab code block is divided into two main parts: rst the variables passed are initialized into internal Matlab variables. This step is not necessary but it makes the following Matlab code more readable. The variables only have to be instanciated once. After that they will also be available in later script blocks. As can be seen in the second half of the embedded script, Matlab here is utilized to calculate the width and height of the computational domain optimally for a hexagonal photonic crystal with NCols columns and NRows rows of holes with a radius of HoleRadius and a hole spacing of SpaceWidth. All these parameters will be passed from the outside so that they can be varied easily, as will be shown later in this section. Next we will have to create the holes in the photonic crystal. Here we will use the function Circle which we dened earlier in this section. The code for creating the holes looks like this: <?Matlab for i = 1:1:NRows if mod(i, 2) == 1 for j = 1:1:NCols centery = (i-1) * SpaceWidth ... + HoleRadius + Offset; centerx = (j-1) * SpaceWidth... + HoleRadius + Offset; keys.c = Circle(i, j, centerx, centery, HoleRadius); ?>

112

CHAPTER 9. EMBEDDED SCRIPTING

Circle { %(c)s } <?Matlab end else for j = 1:1:NCols-1 centerx = (j-1) * SpaceWidth + HoleRadius... + Offset + SpaceWidth/2; centery = (i-1) * SpaceWidth + HoleRadius... + Offset; keys.c = Circle(i, j, centerx, centery, HoleRadius); ?> Circle { %(c)s } <?Matlab end end end ?> As can be seen, there are two nested for-loops in this Matlab code block. The rst loop iterates the rows. Next comes a if clause to determine if we are in an odd or in an even row. Then in the inner for loop that iterates the columns, the coordinates for the centers of the holes are calculated accordingly and passed to the Circle function. The return value of the Circle function, a string containing exactly one circle, is printed to the resulting .jcm le via the jcmwave echo command. Putting this together in a .jcmt le, all we will further require is a Matlab script that sets all the parameters and invokes the transformation to a .jcm le. All this script has to contain are the following lines for setting the parameters of the photonic crystal: keys.HoleRadius = 2; keys.SpaceWidth = 7; keys.NRows = 3; keys.NCols = 3; keys.Offset = 1;

9.2. EMBEDDED SCRIPTING: MATLAB and the following two lines for invoking the transformation process: addpath /path/to/your/jcmroot/ThirdPartySupport/matlab/ jcmwave_runembeddedscripts(layout.jcmt, keys);

113

After executing this script, invoking JCMgeo in the directory of your .jcmt les will result in a grid similar to gure 9.4

Figure 9.4: Triangulation of the hexagonal photonic crystal created with the help of embedded Matlab scripting

114

CHAPTER 9. EMBEDDED SCRIPTING

Chapter 10 Using JCMsuite from Python


The nite element solver JCMsolve comes with a Python programming interface which makes it possible to use the solver from Python. The main objective of the programming interface is to provide you with a comfortable access to the output data produced by JCMsolve. This way you need not know much about the nite element method to implement a further post process in Python based on the computed eld data or to use the computed electromagnetic elds as input data to your own simulation. For the creation of complex input les with Python we refer to the Chapter 9.1.

10.1

Initialization

You can nd the required libraries of the Python interface in the subdirectory ThirdPartySupport/Python/JCMsuite of your JCMsuite installation. Depending on the platform (Linux, Windows) we support dierent versions of Python. On Windows we currently support the version 2.4 of the Python interpreter whereas on Linux we support the version 2.3. If your installed Python version does not match these requirements you may recompile the library on your own machine. The required C le jcmwavemodule.c is placed in the directory ThirdPartySupport/Python/JCMsuite. Please do no hesitate to contact the JCMwave support team if you have any problems when creating the library. After adding the path ThirdPartySupport/Python/JCMsuite to the environment variable PYTHONPATH the Python modules are imported via: 115

116

CHAPTER 10. USING JCMSUITE FROM PYTHON

import _jcmwave_py23 as jcmwave (Linux) import _jcmwave_py24 as jcmwave (Windows) To get information about the methods implemented in the interface use the command help(jcmwave).

10.2

Main Method Call

The method jcmwave.solve("project.jcmp"); starts the FEM solver on the project specied in the le project.jcmp. It corresponds to the command line call JCMsolve --solve project.jcmp. To only compute the post-processes of project.jcmp use jcmwave.postprocess("project.jcmp"); This corresponds to JCMsolve --post process project.jcmp.

10.3

The Pinboard

A run of the solver produces output data stored in several .jcm-les on the le system. For examples the computed electromagnetic elds are stored in .jcm-les in the eldbag format. Fourier coecients and other post process values are typically stored in the Table format. To access the data the Python library provides you with a procedural interface. In a rst step the data stored in a .jcm-le is loaded to the pinboard by the method call integer handle = jcmwave.gethandle(string fileName) The pinboard can be considered as the workspace of jcm-data. The string parameter fileName is the name of the .jcm-le to be loaded. The method returns a handle to the loaded data which is used for a further reference to the data. Internally a reference counter is incremented. To release a handle (to decrement the reference counter) one calls the method void = jcmwave.releasehandle(integer handle) with the corresponding handle as input parameter.

10.4. TABLE ACCESS METHODS

117

10.4

Table Access Methods

Many JCMsolve output les are in the Table format. Once the table is loaded to the pinboard, a handle is obtained to refer to the table data one uses inteface methods to access the table data. The table title, the number of columns, the columns names and the columnss types can be retrieved by invoking the following methods: string jcmwave.table_title(integer handle); integer jcmwave.table_ncolumns(integer handle); string jcmwave.table_columnname(integer handle, integer column); string jcmwave.table_columntype(integer handle, integer column); To access an entry in row row, column col of a table one uses the method entry = jcm.table_entry(integer handle, integer row, integer col) Here, entry can be a string, integer, double or doublecomplex. To retrieve the whole column of the table one uses the method tuple jcmwave.table_column(integer handle, integer column) As an example a table column can be accessed by the following lines of code: import _jcmwave_py23 as jcmwave # load table to pinboard and get handle tableHandle = jcm.gethandle(table.jcm); # access to 5th column of table columnData = jcmwave.table_column(tableHandle, 4);

10.5

Fieldbag Access Methods

Computed electromagnetic elds are stored in .jcm-output les in the eldbag format. In such a le a collection of elds of the same type is stored. For example in an eigenmode computation a certain number of modes is computed, so that the eld output contains multiple elds. Eciently accessing a nite element eld requires some knowledge on how the elds are represented in the nite element method.

118

CHAPTER 10. USING JCMSUITE FROM PYTHON

As described in many examples of this tutorial the geometry is represented by a mesh consisting of triangles in 2D and tetrahedrons in 3D. In later versions of JCMsolve the mesh may further contains quadrilaterals in 2D and prism, bricks and pyramides in 3D. In the following we call these geometrical patches commonly cells.

Mesh Access Methods


The whole topology of the mesh can be recovered using a few methods. We refer to help(jcmwave) for more details. Here we only scetch the principles of the mesh description. A mesh does not only consist of cells but also contains sub-patches like points or edges in 2D and additionally triangles and quadrilaterals in 3D. To get the number of points one calls the method integer = jcmwave.fieldbag_npoints(integer handle) Here handle must be a valid handle to a eldbag loaded to the pinboard. Each point as a unique index. As usual in Python indexing starts from 0. The real coordinates of the point wiht index ipoint are returned after calling the method tuple = jcmwave.fieldbag_pointcoordinates( \ integer handle, integer ipoint) The edges of the mesh are characterized by the point indices of their rst and second points which can be retrieved by the method tuple = jcmwave.fieldbag_edgepointindices( \ int handle, int edgeIndex). Each cell is a mapping of a corresponding unit cell given in unit coordinates into the real physical space with real coordinates. This mapping can be evaluated by the method tuple = jcmwave.fieldbag_realcoordinatesoncell( \ integer handle, integer indexCell, tuple<real> unitCoordinates) The inverse mapping called fieldbag unitcoordinatesoncell is also available. Besides the geometry of the mesh it is also important to know which materials are present on a certain cell. In a JCMsolve project this is done by material indices. Each domain or material carries a material index so that

10.5. FIELDBAG ACCESS METHODS

119

one can speciy material properties such as permittivity tensor or permeability tensors in the le material.jcm. The material id of a cell is returned by the method fieldbag celldomainid. There exists also a fast search method fieldbag findcell which tries to nd a cell containing a given point.

Field Access Method


The restriction of the elds to a cell is polynomial function in each of the eld components. To get the maximum polynomial degree of the eld on the local patches one evokes the method integer = jcmwave.fieldbag_maxdegree(integer handle) The number of components of the eld is returned by fieldbag ncomponents. To evaluate the eld on a cell one uses the method tuple = jcmwave.fieldbag_evaluateoncell( \ integer handle, integer indexCell, \ tuple<real> unitCoordinates, integer ifield) The coordinates are given in unit coordinates and ifield is the index of the eld within the eldbag. As an example with following piece of code one gets the eld values at a the point [0.0, 0.0] for a 2D eld. import _jcmwave_py23 as jcmwave ... realCoordinates = (0.0, 0.0); fielIndex = 0; # Find a cell containing the point # fieldBagHandle is handle to loaded fieldbag. indexCell = jcmwave.fieldbag_findcell( \ fieldBagHandle, realCoordinates) # Get cell unit coordinates unitCoordinates = jcmwave.fieldbag_realcoordinatesoncell( \ fieldBagHandle, indexCell, realCoordinates) # Get Number of components nComponents = jcmwave.fieldbag_ncomponents(fieldBagHandle);

120

CHAPTER 10. USING JCMSUITE FROM PYTHON

# Now evaluate the first field contained in fieldbag fieldValues = jcmwave.fieldbag_evaluateoncell( \ fieldBagHandle, indexCell, unitCoordinates, fieldIndex); Further auxiliary methods such as eld export to cartesian grids and extraction of isolines are available.

Chapter 11 Using JCMsuite from Matlab


The nite element solver JCMsolve comes with a Matlab programming interface which make it possible to use the solver from within Matlab. The main objective of the programming interface is to provide you with a comfortable access to the output data produced by JCMsolve. This way you need not know much about the nite element method to implement a further post process based on the computed eld data or to use the computed electromagnetic elds as input data to further simulations in Matlab. For the creation of complex input les with Matlab we refer to the Chapter 9.1.

11.1

Initialization

You can nd the .m-les of the Matlab interface in the subdirectory ThirdPartySupport/matlab of your JCMsuite installation. This path has to be added via: addpath your_installation_directory/ThirdPartySupport/matlab/ To get information about a method (e.g. jcmwave loadamirafields) implemented in the interface use help jcmwave_loadamirafields

11.2

Main Method Call


121

To start JCMsolve from Matlab simply use the system call

122

CHAPTER 11. USING JCMSUITE FROM MATLAB

system(sprintf(JCMsolve --solve ./project.jcmp)) This starts the solver on the project specied in the le project.jcmp. To only compute the post-processes of project.jcmp use system(sprintf(JCMsolve --postprocess ./project.jcmp)).

11.3

Table Access Methods

Many JCMsolve output les are in the Table format. To load a table from the le fileName use table = jcmwave_loadtable(fileName); This method returns a Matlab structure. Now the table title, the number of columns, the columns names and the columnss types (e.g. of the rst column) can be retrieved: table.title size(table.columns,2) table.columns{1}.name table.columns{1}.type To access an entry in column i and line j use table.columns{i}.data(j) To retrieve the whole column i of the table one uses table.columns{i}.data

11.4

Fieldbag Access Methods

Computed electromagnetic elds are stored in .jcm-output les in the eldbag format. In such a le a collection of elds of the same type is stored. For example in an eigenmode computation a certain number of modes is computed, so that the eld output contains multiple elds. There exists no load method in Matlab for jcm eldbag les by now. The eld must be converted in a postprocess step into the AMIRA format before accessing the electromagnetic eld from Matlab. Since AMIRA does not support higher order

11.4. FIELDBAG ACCESS METHODS

123

nite elements the computed elds are linearly interpolated on a ner grid. This results in an further interpolation error. If accuracy is critical in your Matlab computation this should be kept in mind. To load a AMIRA eld the command use the command fieldbag = jcmwave_loadamirafields(fileName). The imported AMIRA elds may be dened on a cartesian or on a simplex grid. A 2D simplex grid consists of triangles whereas a 3D simplex grid consists of tetrahedrons. The return value fieldbag is a Matlab structure with the entries fieldbag.grid and fieldbag.field. In fieldbag.grid the grid is stored whereas in fieldbag.field the collection of elds living on that grid is stored.

Mesh Access Methods


The entry fieldbag.grid.type species the mesh type (cartesian or simplex). Here we only detail the case of a simplex grid in 2D. For a description of the cartesian grid format please use the Matlab help method: help jcmwave_loadamirafields The point coordinates are stored in the Np by 2 array fieldbag.grid.p. The point index to a point is the row index of that array. So with [x, y] = fieldbag.grid.p(ip, :) one retrieves the coordinates of the ipth point. The triangles of the mesh are stored in the Nt by 3 array fieldbag.grid.simplices where Nt is the number of triangles in the mesh. The indices of the three triangle points of the itth triangle are given in the itth row of the triangle array: [p1, p2, p3] = fieldbag.grid.simplices(it, :). As an example we want to get coordinates of the nodes of simplex 100: nodeIndices = fieldbag.grid.simplices(100,:) Then we can get the coordinates of these nodes via: nodeCoordinates = fieldbag.grid.p(nodeIndices(:))

124

CHAPTER 11. USING JCMSUITE FROM MATLAB

Besides the geometry of the mesh it is also important to know which materials are present on a certain simplex. In a JCMsolve project this is done by material indices. Each domain or material carries a material index so that one can speciy material properties such as permittivity tensor or permeability tensors in the le material.jcm. The material id of our simplex 100 of the grid is returned by simplexMaterialId = fieldbag.grid.materials(100)

Field Access Method


The electromagnetic elds are also stored in the Matlab structure fieldbag of the previous chapter. A single eldbag (.am-)le can contain several electromagnetic elds, e.g., several dierent eigenmodes. To access type, polarization, or number of components of the eld with index i one calls: fieldbag.field{i}.type fieldbag.field{i}.polarization fieldbag.field{i}.ncomponents E.g. a z-polarized electric eld strength tensor eld has one component. The matrix fieldbag.field{j}.data contains the eld values of eld j. It is a matrix of size (np, ncomp) where np is the number of grid points and ncomp is the number of components of the eld. To be more precies the column fieldbag.field{j}.data(:, k) holds the values of the kth component of the jth eld on the grid points. Matlab oers the method trisurf to plot a scalar eld given in simplex format. First we store the simplices t, the x and y coordinates of their nodes and the electromagnetic eld in dierent variables: t x y v = = = = fieldbag.grid.simplices; fieldbag.grid.p(:, 1); fieldbag.grid.p(:, 2); fieldbag.field{1}.data;

The following command creates a plot of the imaginary part of the z-component of the eld: trisurf(t, x, y, imag(fieldbag.field{1}.data(:,3)));

Chapter 12 C Programming Interface


The nite element solver JCMsolve comes with a C programming interface which make it possible to use the solver from your own application. The main objective of the programming interface is to provide you with a comfortable access to the output data produced by JCMsolve. This way you need not know much about the nite element method to implement a further post process based on the computed eld data or to use the computed electromagnetic elds as input data to your own simulation. Taking a look on your JCMsuite installation you will nd a dynamically loadable library called jcm fetools.dll on Windows and called jcm fetools.so on Unix/Linux in the subdirectory bin. This library must be linked to your programme. The corresponding header le jcm fetools.h is placed in the subdirectory include. All accessible methods from the jcm fetools library are listed in the header le. Apart from a few exceptions all methods are of the form int DLLIMPORT JCMMethod(TYPE* outputValue1, ..., TYPE* outputValueN, TYPE* inputValue1, ..., TYPE inputValueM). Each method returns an error code. A return value unequal zero signalizes a failure of the method. Input and output values are provided by pointers to primitive C types. TYPE is of the C type char, int, double or doublecomplex or a pointer by itself. 125

126

CHAPTER 12. C PROGRAMMING INTERFACE

12.1

Initialization and Finalization

The special initialization method void DLLIMPORT JCMInitialize(FILE* \_stdout, FILE* \_stderr) must be called before using other methods from the library. This method invokes the license manager to reserve a license. The two arguments stdout and stderr are used to redirect the standard output and the standard error output respectively. The nalization method void DLLIMPORT JCMFinalize() frees the license.

12.2

Main Method Call

The method int DLLIMPORT JCMMain(int argc, char* argv[]) behaves exactly like the command line call JCMsolve. The arguments argc and argv follow the convention of a C main programme. So argc species the number of arguments passed to the main method and argv is an array of string pointers. For example the function call char* argv[] = {"JCMsolve", "--solve", "./project.jcmp"}; JCMMain(3, argv); starts the solver on the project specied in the le project.jcmp. As for a C main method the rst string argument is always the programme name.

12.3

The Pinboard

A run of the solver typically produces output data stored in several .jcmles on the le system. For examples the computed electromagnetic elds are stored in .jcm-les in the eldbag format. Fourier coecients and other post process values are typically stored in the Table format. To access the

12.4. TABLE ACCESS METHODS

127

data the jcm fetools library provides you with a procedural interface. In a rst step the data stored in a .jcm-le is loaded to the pinboard by the method call int DLLIMPORT JCMGetHandle(int* handle, const char* fileName). The pinboard can be considered as the workspace of jcm-data. The string parameter fileName is the lename of the .jcm-le to be loaded. The method returns a handle to the loaded data which is used for a further reference to the data. Internally a reference counter is incremented. To release a handle (to decrement the reference counter) one calls the method int DLLIMPORT JCMReleaseHandle(int handle). with the corresponding handle as input parameter. The usage of a released handle will cause a segmentation fault. Further auxiliary methods refering to the pinboard are documented in the header le jcm fetools.h.

12.4

Table Access Methods

Many JCMsolve output les are in the Table format. Once the table is loaded to the pinboard and a handle is obtained to refer to the table data one uses inteface methods to access the table data. So the table title, the number of columns, the columns names and the columnss types are retrieved. We refer to the include header le jcm fetools.h for a documentation. To access an entry in a certain column the type of the column must be known. For example to get a complex value one uses the method int DLLIMPORT JCMTableGetDoubleComplexEntry( doublecomplex* entry, int handle, int row, int col). Here, entry must be a valid pointer to a variable of the doublecomplex type. So the method does not returns a pointer to the internal data. The input parameter handle must be a valid handle to the table loaded to the pinboard. The input parameters row and col specify the row and column number of the wanted entry. To retrieve the whole column of the table one uses the method

128

CHAPTER 12. C PROGRAMMING INTERFACE

int DLLIMPORT JCMTableGetDoubleComplexColumn( const doublecomplex** entry, int handle, int col). The user must supply a pointer to a doublecomplex array with a minimum length of the number of rows. As an example doublecomplex table column can be accessed by the following lines of code: #include "jcm_fetools.h" ... int tableHandle = 0; int errorCode = JCMGetHandle(&tableHandle, "table.jcm"); if (errorCode!=0) { // error handling ... } int nRows = 0; JCMTableNRows(&nRows, tableHandle); doublecomplex* columnData = new doublecomplex[nRows]; // access to 5th column of table errorCode = JCMTableGetDoubleComplexColumn(&columnData, tableHandle, 5); if (errorCode!=0) { // error handling (5th col. not existing or not // of type doublecomplex) ... }

12.5

Fieldbag Access Methods

Computed electromagnetic elds are stored in .jcm-output les in the eldbag format. In such a le a collection of elds of the same type is stored. For example in an eigenmode computation a certain number of modes is computed, so that the eld output contains multiple elds. Eciently accessing a

12.5. FIELDBAG ACCESS METHODS

129

nite element eld requires some knowledge on how the elds are represented in the nite element method. As described in many examples of this tutorial the geometry is represented by a mesh consisting of triangles in 2D and tetrahedrons in 3D. In a later version of JCMsolve the mesh may further contains quadrilaterals in 2D and prisms, bricks and pyramides in 3D. In the following we call these geometrical patches commonly cells.

Mesh Access Methods


The whole topology of the mesh can be recovered using a few methods. We refer to the header le jcm fetools.h for more details. Here we will only sketch the principles of the mesh description. A mesh does not only consists of cells but also contains sub-patches like points, edges in 2D and additionally triangles and quadrilaterals in 3D. To get the number of points one calls the method int DLLIMPORT JCMFieldBagNPoints(int* nPoints, int handle). Here handle must be a valid handle to a eldbag loaded to the pinboard. Each point has a unique index. As usual in C indexing starts from 0. The real coordinates of the pointIndex-th point are returned in *coordinates after calling the method int DLLIMPORT JCMFieldBagPointCoordinates( double** coordinates, int handle, int pointIndex). Make sure that the size of the array *coordinates is at least the space dimension. The edges of the mesh are characterized by the point indices of their rst and second points which can be retrieved by the method int DLLIMPORT JCMFieldBagEdgePointIndices( int** pointIndices, int handle, int edgeIndex). Each cell is a mapping of a corresponding unit cell given in unit coordinates into the real physical space with real coordinates. This mapping can be evaluated by the method int DLLIMPORT JCMFieldBagRealCoordinatesOnCell( double** realcoordinates, int handle, int indexCell, const double* unitcoordinates).

130

CHAPTER 12. C PROGRAMMING INTERFACE

The inverse mapping called JCMFieldBagUnitCoordinatesOnCell is also available. Besides the geometry of the mesh it is also important to know which materials are present on a certain cell. In a JCMsolve project this is done by material indices. Each domain or material carries a material index so that one can speciy material properties such as permittivity tensor or permeability tensors in the le material.jcm. The material id of a cell is returned by the method JCMFieldBagGetCellDomainId. There exists also a fast search method JCMFieldBagFindCell which tries to nd a cell containing a given point.

Field Access Method


The restriction of the elds to a cell is polynomial function in each of the eld components. To get the maximum polynomial degree of the eld on local patches one evokes the method int DLLIMPORT JCMFieldBagMaxDegree(int* maxDegree, int handle). So the eld on each cell is at most a polynomial of degree *maxDegree on each unit patch. The number of components of the eld is returned by the method JCMFieldBagNComponents. To evaluate the eld on a cell one uses the method int DLLIMPORT JCMFieldBagEvaluateOnCell( doublecomplex** values, int handle, int indexCell, const double* unitcoordinates, int iField). The coordinates are given in unit coordinates and iField is the index of the eld within the eldbag. The eld value is returned in the array *values with length equal to the number of eld components. As an example with following piece of code one gets the eld values at a the point [0, 0] for a 2D eld. #include "jcm_fetools.h" ... double realCoordinates[] = {0.0, 0.0}; double unitCoordinates[2]; int indexCell;

12.5. FIELDBAG ACCESS METHODS // Find a cell containing the point // FieldBagHandle is handle to loaded fieldbag. int errorCode = JCMFieldBagFindCell( fieldBagHandle, realcoordinates); if (errorCode!=0) { // error handling (mesh may not contains point) } // Get cell unit coordinates JCMFieldBagUnitCoordinatesOnCell( &unitCoordinates, fieldBagHandle, indexCell, realCoordinates); // Get Number of components int nComponents; JCMFieldBagNComponents( &nComponents, fieldBagHandle); // Now evaluate the first field contained in fieldbag doublecomplex* fieldValues = new doublecomplex[nComponents]; JCMFieldBagEvaluateOnCell( *values, fieldBagHandle, indexCell, unitCoordinates, 0);

131

Further auxiliary methods such as eld export to cartesian grids and extraction of isolines are available and documented in the header le jcm fetools.h.

You might also like