Tutorial

131
JCMsolve – Tutorial Electromagnetics Version 2.10.0

description

Electromagnetic Field Theory

Transcript of Tutorial

Page 1: Tutorial

JCMsolve – Tutorial

ElectromagneticsVersion 2.10.0

Page 2: Tutorial

2

This document is provided as a part of JCMwave’s software products. It is pro-vided under the terms of the End User License Agreement (EULA) for JCMwaveSoftware Products.JCMwave and the JCMwave logo are registered trademarks of the JCMwaveGmbH.Copyright c©2009 by JCMwave GmbH. All rights reserved.

Page 3: Tutorial

Contents

Legal information 2

1 How to use this tutorial 5

2 Theoretical Background 7

2.1 Maxwell’s Equations . . . . . . . . . . . . . . . . . . . . . . . 7

2.2 Time Harmonic Maxwell’s equations: Frequency Domain . . . 8

3 Introduction to JCMsuite 11

3.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

3.2 Main Features of JCMsolve . . . . . . . . . . . . . . . . . . . 12

3.2.1 Problem Classes . . . . . . . . . . . . . . . . . . . . . . 13

3.2.2 Resonance Mode and Scattering Poblems* . . . . . . . 13

3.2.2.1 Planar Problems . . . . . . . . . . . . . . . . 14

3.2.2.2 Cylindrical Problems . . . . . . . . . . . . . . 15

3.2.3 Propagating Mode Problems* . . . . . . . . . . . . . . 16

4 Getting started 19

4.1 Defining Projects . . . . . . . . . . . . . . . . . . . . . . . . . 19

4.2 Starting a project . . . . . . . . . . . . . . . . . . . . . . . . . 23

4.2.1 Windows . . . . . . . . . . . . . . . . . . . . . . . . . . 23

4.2.2 Linux . . . . . . . . . . . . . . . . . . . . . . . . . . . 23

4.3 JCMsolve output and Post-Processes . . . . . . . . . . . . . . 23

4.3.1 FieldTransformation . . . . . . . . . . . . . . . . . . . 24

4.3.2 ExportFields . . . . . . . . . . . . . . . . . . . . . . . 25

4.3.3 FunctionalEvaluation . . . . . . . . . . . . . . . . . . . 25

4.4 Third Party Support . . . . . . . . . . . . . . . . . . . . . . . 25

3

Page 4: Tutorial

4 CONTENTS

5 Hello World! 27

6 Scattering 316.1 Scattering Problems . . . . . . . . . . . . . . . . . . . . . . . 316.2 Scattering from Cylinder (TE polarization) . . . . . . . . . . . 326.3 Scattering from Cylinder (arbitrary polarization) . . . . . . . 386.4 Gaussian Beam on Micro Lens . . . . . . . . . . . . . . . . . . 406.5 Photolithography: EUV - Mask . . . . . . . . . . . . . . . . . 436.6 Photolithography II : EUV - Mask revisited . . . . . . . . . . 476.7 Mie Scattering . . . . . . . . . . . . . . . . . . . . . . . . . . . 506.8 Circular Pupil (cylindrical) . . . . . . . . . . . . . . . . . . . . 546.9 Circular Pupil (3D) . . . . . . . . . . . . . . . . . . . . . . . . 56

7 Propagating Modes 597.1 Propagating Mode Problems . . . . . . . . . . . . . . . . . . . 597.2 Single Mode Fiber . . . . . . . . . . . . . . . . . . . . . . . . 607.3 Leaky Waveguide . . . . . . . . . . . . . . . . . . . . . . . . . 667.4 Rectangular Microwave Waveguide . . . . . . . . . . . . . . . 697.5 Directional Coupler . . . . . . . . . . . . . . . . . . . . . . . . 737.6 Plasmonic Waveguide . . . . . . . . . . . . . . . . . . . . . . . 787.7 Photonic Crystal Fiber . . . . . . . . . . . . . . . . . . . . . . 82

8 Resonance Modes 858.1 Resonance Problems . . . . . . . . . . . . . . . . . . . . . . . 858.2 Rectangular Resonator . . . . . . . . . . . . . . . . . . . . . . 868.3 Cylindrical Resonator . . . . . . . . . . . . . . . . . . . . . . . 918.4 Hexagonal Photonic Crystal . . . . . . . . . . . . . . . . . . . 93

9 Embedded Scripting 979.1 Embedded Scripting Description . . . . . . . . . . . . . . . . . 979.2 Embedded Scripting: Matlab . . . . . . . . . . . . . . . . . . 101

9.2.1 Tutorial project: Refraction at an interface . . . . . . . 1019.2.2 Photonic Crystal . . . . . . . . . . . . . . . . . . . . . 108

10 Using JCMsuite from Python 11310.1 Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11310.2 Main Method Call . . . . . . . . . . . . . . . . . . . . . . . . 11410.3 The Pinboard . . . . . . . . . . . . . . . . . . . . . . . . . . . 114

Page 5: Tutorial

CONTENTS 5

10.4 Table Access Methods . . . . . . . . . . . . . . . . . . . . . . 11510.5 Fieldbag Access Methods . . . . . . . . . . . . . . . . . . . . . 115

11 Using JCMsuite from Matlab 11911.1 Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11911.2 Main Method Call . . . . . . . . . . . . . . . . . . . . . . . . 11911.3 Table Access Methods . . . . . . . . . . . . . . . . . . . . . . 12011.4 Fieldbag Access Methods . . . . . . . . . . . . . . . . . . . . . 120

12 C Programming Interface 12312.1 Initialization and Finalization . . . . . . . . . . . . . . . . . . 12412.2 Main Method Call . . . . . . . . . . . . . . . . . . . . . . . . 12412.3 The Pinboard . . . . . . . . . . . . . . . . . . . . . . . . . . . 12412.4 Table Access Methods . . . . . . . . . . . . . . . . . . . . . . 12512.5 Fieldbag Access Methods . . . . . . . . . . . . . . . . . . . . . 126

Page 6: Tutorial

6 CONTENTS

Page 7: Tutorial

Chapter 1

How to use this tutorial

This tutorial is structured as follows. Chapter 2 is a short summary aboutMaxwell’s equations and sets the theoretical background for the softwarepackage JCMsuite. We introduce our notations, physical units, and definephysical quantities which are used in JCMsuite.

Chapter 3 is a general introduction to the software package JCMsuite andits modules. We give an overview of JCMsuite’s capabilities and introducethe problem classes which can be computed.

In the Getting-started-chapter 4 the definition of a JCMsuite simulationproject is described. We explain how to use the different software modules ofJCMsuite under Linux and Windows. Finally we present JCMsuite’s possi-bilities of post-processing simulation results and give information about thirdparty support.

Chapter 5 is the first tutorial project. Here we explain step by step howa project is load into the JCMcontrol the geometry triangulated with JCM-geo and finally projects solved with JCMsolve. Furthermore visualization ofsimulation results with the JCMview is explained.

In chapter 6 (Scattering), 7 (Propagating Modes), and 8 (ResonanceModes) the tutorial projects are explained whose source files can be foundin the subdirectory TutorialExamples of JCMsuite’s installation directory.Each chapter starts with a simple example. The following tutorial projectsintroduce additional features of JCMsuite and deepen important aspects. Af-ter finishing the first project the other tutorial projects of a chapter can beworked on in any order. Each tutorial project begins with a list of learningtargets and a project description explaining the physical model that isdiscussed. The location where the source files can be found is given. Since

7

Page 8: Tutorial

8 CHAPTER 1. HOW TO USE THIS TUTORIAL

we often want to modify the tutorial projects to get a feeling for simulationparameters one should copy the corresponding tutorial directory to anotherdestination and keep the unmodified original. The simulation results are ex-plained followed by a discussion, where the learning targets are explained.In the Quick own modifications part simulation parameters are listedwhich can be changed to modify the problem. The meaning of each pa-rameter, where to find it and suggestions for new values are given. Thispart is especially useful since it gives clear insight into the meaning of theparameters.

Chapter 9 explains JCMsuite’s feature of embedded scripting. Matlab canbe used to create and simulate complicated projects, geometries, parameterscans etc. An embedded scripting tutorial project about refraction at aninterface is included which e.g. performs a scan about the angle of incidenceof a plane wave and compares the results to the analytical Fresnel formulas.

In chapter 10, 11, and 12 the usage of JCMsuite in combination withPython, Matlab, and C is explained in detail.

Sections marked with a * in the table of contents (and the correspondingsubsections) can be omitted during the first reading.

Page 9: Tutorial

Chapter 2

Theoretical Background

In this chapter we start with a short summary of the theory of light prop-agation. We give the general formulation of Maxwell’s equations in section2.1 and introduce the involved physical quantities. In the stationary casethe dynamical behaviour of the electric and magnetic field can be separatedfrom the spatial by an oscillatory time-harmonic ansatz with a fixed angularfrequency. This is explained in section 2.2. JCMsuite solves problems in thisso called frequency domain.

2.1 Maxwell’s Equations

The mathematical model of light propagation are Maxwell’s equations:

∂tǫE = ∇× H − J

∂tµH = −∇× E

∇ · ǫE = ρ

∇ · µH = 0.

The involved physical quantities are given in Table 2.1. The material pa-rameters are the permittivity tensor ǫ and the permeability tensor µ whichmay be anisotropic and space-dependent. In this version of JCMsuite weassume that these tensors are linear, i.e. they do not depend on the electricor magnetic field strength. All input and output data in JCMsuite are givenin SI units.

9

Page 10: Tutorial

10 CHAPTER 2. THEORETICAL BACKGROUND

Quantity Unit

Electric field intensity E Vm−1

Magnetic field intensity H Am−1

Electric current density J Am−2

Electric charge density ρ Cm−3

Permittivity tensor ǫ Fm−1

Permeability tensor µ Hm−1

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

2.2 Time Harmonic Maxwell’s equations: Fre-

quency Domain

In experimental situations one is often interested in the stationary behaviourof the electric and magentic field after the transient part has vanished. E.g. ina scattering setup an object is illuminated by a laser or other light source witha fixed frequency the transient part of the electric field is due to switchingon the light source and vanishes on a very short timescale. JCMsuite is asimulation package for the non-transient part of the electric and magneticfield. In the stationary case a time-harmonic ansatz can be made for theelectric and magnetic field:

E(x, y, z, t) = E(x, y, z) exp(−iωt),

H(x, y, z, t) = H(x, y, z) exp(−iωt),

where ω is the fixed angular frequency related by ω = 2πf to the frequencyf of light. In the case that source terms J and/or ρ are present these alsohave to be time-harmonic:

J(x, y, z, t) = J(x, y, z) exp(−iωt),

ρ(x, y, z, t) = ρ(x, y, z) exp(−iωt).

These sources could e.g. be antennas or radiating points sources with fixedangular frequency. With the above ansatz Maxwell’s equations split into

Page 11: Tutorial

2.2. TIME HARMONIC MAXWELL’S EQUATIONS: FREQUENCY DOMAIN11

magnetic and electric field equations:

∇× µ−1∇× E− ω2ǫE = −iωJ,

∇ · ǫE = 0,

and

∇× ǫ−1∇× H − ω2µH = ∇× ǫ−1J,

∇ · µH = 0.

In the following we drop the wiggles. JCMsuite solves the time-harmonicMaxwell’s equations with the finite element method in a number of differentsettings (e.g., for the electric or the magnetic fields, for resonance mode,propagating mode, or light scattering simulations) and in 1, 2 or 3 spatialdimensions.

In the time harmonic case it is very simple to determine the electric fieldfrom the magnetic field and vice versa. We find from Maxwell’s equations:

E =1

iωǫ∇×H (2.1)

H = −1

iωǫ∇× E. (2.2)

Finally we define a number of important physical quantities which are de-rived from the electric and magnetic field and which can be computed withJCMsolve in so called post-processes:

• electric energy density:

wel =(ǫE)∗ · E

4

• magnetic energy density:

wm =(µH)∗ · H

4

• Poynting vector (energy flux density):

S = E × H =

(

1

iωǫ∇× H

)

×H = E ×

(

−1

iωǫ∇× E

)

Page 12: Tutorial

12 CHAPTER 2. THEORETICAL BACKGROUND

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

Wel,j =

Dj

weld~r =

Dj

(ǫjE)∗ ·E

4dr

Wm,j =

Dj

wmd~r =

Dj

(µjH)∗ ·H

4,

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

Page 13: Tutorial

Chapter 3

Introduction to JCMsuite

In this chapter the capabilities of JCMsuite are introduced. After a shortintroduction to the different modules of the software package the focus willbe on its main component which is the solver JCMsolve. Please note thatthe functionalities of the mesh generator JCMgeo are explained in detail ina separate tutorial enclosed with the software distribution.

3.1 Overview

JCMsuite is a software package which allows to simulate the propagation ofelectromagnetic waves with an exceptionally high accuracy. Figure 3.1 showsa schematic overview of the components of JCMsuite. The main part of JCM-suite is JCMsolve – the finite-element method solver which allows to handlea variety of electromagnetic simulation settings. JCMsolve allows to findguided light fields (eigenmodes) in waveguide structures or resonators andto calculate light scattering and light transition through arbitrary obstacles.JCMsolve handles 1D, 2D and 3D geometries, materials with complex refrac-tive indices and anisotropic material constants. It calculates time-harmonic(steady-state) solutions, as explained in chapter 2.

JCMsolve relies on the finite element method (FEM) and implies adap-tive methods. Both ensures high accuracy of the results. Further, it usesmulti-grid methods, specialized direct solvers for sparse systems, and otherfast solving algorithms. This ensures high speed and moderate problem sizes.Therefore, JCMsuite handles challenging projects on standard personal com-puters.

13

Page 14: Tutorial

14 CHAPTER 3. INTRODUCTION TO JCMSUITE

JCMsuite contains a flexible geometry tool, JCMgeo, which automaticallygenerates 1D, 2D and 3D finite element meshes. The module JCMview allowsto visualize the meshes produced by JCMgeo and the electromagnetic fielddistributions simulated by JCMsolve.

The user-interface JCMcontrol allows to define all details of a simulationproject. Also, the capability of embedded scripting makes it very convenientto set up parameterized projects and complicated geometries and to performparameter scans with nested loops over project parameters like wavelength,incident angle or geometrical quantities. Embedded scripting is supported forMatlab, Octave, and Python. Besides controlling the solver, the simulationresults can be imported into the corresponding environment and can then befurther processed.

JCMgeo JCMsolve JCMview

JCMcontrol

Figure 3.1: Schematics of the modules of JCMsuite. The main tool is the FEM solverJCMsolve. The geometry tool JCMgeo generates FEM meshes, and the tool JCMviewallows to visualize the meshes and field distributions. The functionality can be steered viathe user interface JCMcontrol.

3.2 Main Features of JCMsolve

In this section we will present the main features and capabilities of JCM-suite’s solver JCMsolve. The organization of this section resembles the keyidea of the organization of the main JCMsuite control file (project file).Keywords which also appear in the project file will be written in this font.

Page 15: Tutorial

3.2. MAIN FEATURES OF JCMSOLVE 15

3.2.1 Problem Classes

Most of the problems of light propagation can be divided into the followingthree classes:

• Scattering: light scattering and transition through arbitrary geometries(e.g., light propagation through a micro lens or diffraction off a periodicgrating).

• Propagating mode: guided light fields in waveguide structures (e.g.,guided or leaky modes in single mode fibers or in photonic crystalfibers).

• Resonance mode: eigenmodes in resonators (e.g., modes of vertical cav-ity surface emitting laser (VCSEL) cavities, band structures of photoniccrystals, or whispering gallery modes of microsphere resonators).

Each JCMsuite project belongs to one of these classes. PropagatingMode

and ResonanceMode projects are eigenvalue problems. JCMsolve finds eigen-values and corresponding eigenmodes which are the electric or magnetic fieldon the given geometry. Scattering projects compute propagation of an in-cident electric or magnetic field (e.g., plane waves, Gaussian beams) througha material distribution in the specified geometrical setting.

If one chooses to compute the electric field, then the magnetic field canbe determined afterwards from this solution, and vice versa as explained insection 2.2. Therefore this chapter is restricted to the computation of electricfields.

3.2.2 Resonance Mode and Scattering Poblems*

Resonance mode, propagating mode, and scattering problems can have dif-ferent types of geometries. For resonance mode and scattering problemsthese are 1D (Slab), 2D (Planar), 3D rotational symmetric (Cylindrical),arbitrary 3D with a description of a stack of structured layers (Stack), orarbitrary 3D with a tetrahedral discretization (no keyword). The geometryof a propagation mode problem always has a 2D waveguide structure whichis invariant in the third spatial dimension along the waveguide.

These different geometries require different numerical treatment to min-imize computation time and memory consumption. In the following we ex-

Page 16: Tutorial

16 CHAPTER 3. INTRODUCTION TO JCMSUITE

plain the effects of different geometries and symmetries on Maxwell’s equa-tions.

3.2.2.1 Planar Problems

The geometry of a Planar problem is invariant in one spatial dimension (z-direction). Depending on the polarization of the electric, resp. magnetic, fieldfurther simplifications of the Maxwell’s equations arise. Maxwell’s equationsare still solved rigorously, no approximations are involved. It is thereforesufficient to solve a Planar problem on a 2D geometry (x-y-plane).

ElectricZ If the electric field is polarized perpendicular to the x-y-plane(ElectricZ) the fully vectorial Maxwell’s equations reduce without furthersimplifications 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 field is polarized parallel to the x-y-plane (TM) Maxwell’s equations reduce to the following vectorial equationin two spatial dimensions

∇× µ−1∇×E = ω2ǫE

for the x- and y-component of the electric field (ElectricXY). When theelectric field is polarized parallel to the x-y-plane the magnetic field is polar-ized perpendicular to the x-y-plane. Therefore the ElectricXY problem isequivalent to the MagneticZ case and vice versa. In the HelloWorld examplefor propagating modes this will be verified numerically.

ElectricXYZ For arbitrary polarized electric field (ElectricXYZ) in 2Dthe fully vectorial Maxwell’s equations have to be solved in two spatial di-mensions

∇× µ−1∇×E = ω2ǫE

∇ · ǫE = 0

for all electric field components.The equivalent equations for the magnetic field are also implemented

(MagneticZ, MagneticXY, MagneticXYZ).

Page 17: Tutorial

3.2. MAIN FEATURES OF JCMSOLVE 17

3.2.2.2 Cylindrical Problems

The solution of a 3D problem is more memory and time consuming than a2D problem. It is therefore desirable to use 2D geometries whenever possible.The computation of an electromagnetic field in a 3D geometry with cylindri-cal symmetry (rotational symmetry) can be reduced to a computation on a2D geometry (Cylindrical).

The geometry is assumed to be invariant under rotation around the y-axis. For the transformation we use cylinder coordinates (r, y, ϕ), definedby:

xyz

=

r cos(ϕ)y

r sin(ϕ)

and the transformed electric field

Er

Ey

=

cos(ϕ) 0 sin(ϕ)0 1 0

−r sin(ϕ) 0 r cos(ϕ)

Ex

Ey

Ez

.

In the rotationally symmetric case the geometry does not depend on ϕ. Inthe ϕ = 0 plane Maxwell’s equations can be written in the following form:

∇r,y,ϕ × µr,y,ϕ−1∇r,y,ϕ × Er,y,ϕ = ω2ǫr,y,ϕEr,y,ϕ

with the nabla operator

∇r,y,ϕ =

∂r

∂y

∂ϕ

,

and the transformed (pseudo)-tensor

µr,y,ϕ(r, y, ϕ) = r

µxx(r, y) µxy(r, y) µxz(r, y)/rµyx(r, y) µyy(r, y) µyz(r, y)/r

µzx(r, y)/r µzy(r, y)/r µzz(r, y)/r2

.

The permittivity tensor ǫr,y,ϕ is transformed accordingly. The electric field

Er,y,ϕ can be decomposed in Fourier modes E(r, y) with respect to the polarangle ϕ:

Er,y,ϕ =∑

nϕ∈N

einϕϕEnϕ(r, y).

Page 18: Tutorial

18 CHAPTER 3. INTRODUCTION TO JCMSUITE

The wiggled Fourier modes no longer depend on the polar angle ϕ. Usingthis decomposition in Maxwell’s equations leads to independent equations forthe different Fourier modes, as shown in the following. The electric field issplit into a field parallel to a cross section, E⊥ (parallel to the ϕ = 0 plane),and a field perpendicular to the cross section, Eϕ,

Er,y,ϕ =

[

E⊥

]

,

assuming that the transformed tensors µr,y,ϕ and ǫr,y,ϕ have the form

µr,y,ϕ =

[

µ⊥⊥ 00 µϕϕ

]

, ǫr,y,ϕ =

[

ǫ⊥⊥ 00 ǫϕϕ

]

.

After introducing

P =

[

0 −11 0

]

and ∇⊥ =

[

∂r

∂y

]

one arrives at[

P∇⊥µ−1ϕϕ∇⊥ · P − n2

ϕPµ−1⊥⊥

P −inϕPµ−1⊥⊥

P∇⊥

−inϕ∇⊥ · Pµ−1⊥⊥

P ∇⊥ · Pµ−1⊥⊥

P∇⊥

] [

E⊥

]

=

ω2

[

ǫ⊥⊥ 00 ǫϕϕ

] [

E⊥

]

.

This equation does not depend on the polar angle ϕ and can therefore besolved in the ϕ = 0 plane. This reduced the 3D to a 2D problem.

Computing resonance modes one specifies nϕ to search for eigenmodeswith the corresponding dependence on ϕ (i.e. einϕϕ). In scattering problemsthe incident field is decomposed into Fourier modes Ein

r,y,ϕ. Each incomingmode with fixed nin

ϕ 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 sufficiently small.

3.2.3 Propagating Mode Problems*

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

Page 19: Tutorial

3.2. MAIN FEATURES OF JCMSOLVE 19

but the cross section of the waveguide is arbitrarily structured. We assumethat the waveguide geometry does not depend on the spatial variable z asshown in Figure 3.2. A propagating mode is a solution to the time harmonic

x

y

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.

Maxwell’s equations. It exhibits a harmonic dependency in the z-direction,

E = Epm(x, y) exp (ikzz)

H = Hpm(x, y) exp (ikzz) .

The parameter kz is called propagation constant. From the mathematicalpoint of view this leads to eigenvalue problems for kz. JCMsolve returns therescaled eigenvalue, which is the effective refractive index defined as

neff =kz

k0with k0 =

λ0.

The free space vacuum wavelength, λ0, is defined by the user and defines thetime-harmonic frequency, ω, of the propagating light field:

ω =2πc

λ0and k0 =

λ0.

In the following the kz eigenvalue problem is derived. We only discuss themagnetic case. All considerations map over to the electrical case when onereplaces H by E and interchanges the tensors ǫ and µ.

Let us decompose the magnetic field Hpm(x, y) as

Hpm(x, y) =

[

H⊥(x, y)Hz(x, y)

]

and introduce

P =

[

0 −11 0

]

and ∇⊥ =

[

∂x

∂y

]

.

Page 20: Tutorial

20 CHAPTER 3. INTRODUCTION TO JCMSUITE

Keeping in mind that H = Hpm(x, y)eikzz the ∇×-operator acts as

∇×H =

[

ikzP −P∇⊥

−∇⊥ · P 0

] [

H⊥(x, y)Hz(x, y)

]

eikzz.

Applying the time harmonic Maxwell’s equation,

∇× ǫ−1∇×H = ω2H

and with

ǫ =

[

ǫ⊥⊥ 00 ǫzz

]

and µ =

[

µ⊥⊥ 00 µzz

]

one gets

[

P∇⊥ǫ−1zz ∇⊥ · P − k2

zPǫ−1⊥⊥

P −ikzPǫ−1⊥⊥

P∇⊥

−ikz∇⊥ · Pǫ−1⊥⊥

P ∇⊥ · Pǫ−1⊥⊥

P∇⊥

] [

H⊥

Hz

]

=

ω2

[

µ⊥⊥ 00 µzz

] [

H⊥

Hz

]

.

The last equation is a quadratric eigenvalue problem for the propagationconstant kz. The divergence condition reads as ∇⊥ · µ⊥⊥H⊥ = −ikzµzzHz.

Page 21: Tutorial

Chapter 4

Getting started

4.1 Defining Projects

A simulation project for JCMsuite is defined in a number of input files (textfiles). The necessary files and the data flow are shown in Fig. 4.1. The

layout.jcm

triangulator.jcm

materials.jcm

boundary_conditions.jcm

sources.jcm

JCMgeogrid.jcm

JCMsolve >Data analysisPostprocessingVisualization

JCMcontrol

(e.g., JCMview)

fieldbag.jcm and<project>.jcmp further result files

Figure 4.1: Schematics of the data flow of the JCMsuite.

main modules for computing a project are JCMgeo and JCMsolve. The

21

Page 22: Tutorial

22 CHAPTER 4. GETTING STARTED

automatic mesh generator JCMgeo expects two input files (layout.jcm andtriangulator.jcm).

layout.jcm: The layout file. Here the geometry of the project is described.Nearly arbitrary geometries and computational domains are built from simplegeometrical objects (circles, parallelograms, polygons). For an impressionwe 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 isdescribed 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 simu-lation layouts is provided (GeoTutorial.pdf). So we will not go into furtherdetail here.

triangulator.jcm: The triangulator file. Here some parameters for thetriangulation of the geometry are set. Also this file is explained in detail inthe tutorial for JCMgeo, GeoTutorial.pdf. JCMgeo reads the layout fileand the triagulator file and creates the file grid.jcm which is one of thefollowing input files expected by JCMsolve.

projectName.jcmp: The project file. The name of this file with endingjcmp can be chosen by the user. In the project file the user specifies theproject type (as explained in section 3.2.3) and parameters for the solutionprocess. This file can also be used to define post-processes executed on theoutput data from the solution process.

Page 23: Tutorial

4.1. DEFINING PROJECTS 23

materials.jcm: The material file. This file contains the material proper-ties of the physical domains, i.e., the relative permittivity and permeabilitytensors. Each geometrical object specified in the layout file for JCMgeo hasa MaterialId which refers to a material in the material file. When we lookback to the circle defined in the example above we find 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 file. In this file theuser specifies the type of boundary conditions on particular parts of thephysical boundary. Boundaries of the computational domain are specified inthe layout file via a BoundaryID. The syntax in the boundary conditions fileis then:

BoundaryConditionBag = {

BoundaryCondition {

Id = 3

Electromagnetic = TangentialMagnetic

}

}

where Id refers to the BoundaryID. Please note that transparent or periodicboundaries of the computational domain are not boundaries in the physi-cal sense, but rather attributes of the geometry. Therefore these types ofboundaries are defined purely in the layout file and they do not appear inthe boundary condition file.

The JCMgeo tutorial gives an overview of possible boundary conditions.

sources.jcm: The source field file. For resonance and propagating modeprojects no sources have to be specified. For scattering projects (e.g., lighttransition through a lithographic mask or through a lens) a source field has

Page 24: Tutorial

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 define the wave vector (K)and the electric field 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 waveis coupled into the geometry.

Several sources can be defined within one source bag, and several sourcebags can be defined for one simulation run (resulting in independent fieldsolutions for each source bag).

grid.jcm: The mesh file. This file includes the finite element mesh whichcontains all the geometrical information about the project. This file is auto-matically generated by JCMgeo. It is never modified by the user. A finiteelement mesh is a partition of the physical body, for example a unit cellof a photonic crystal, the cross section of a dielectric waveguide or a res-onator cavity, into small elements such as triangles, tetrahedrons, etc. Ingeneral a complex body is built up from areas of different materials. There-fore each element carries an index-marker (integer) refering to its materialdomain. Since partial differential equations need the definition of boundaryconditions, each boundary element carries a further boundary index-marker.This boundary index marker allows to group the the boundary into areaswith certain boundary condition types. All these material and boundary in-dex markers are automatically assigned to the finite elements when JCMgeotranslates the layout file into the grid file.

Page 25: Tutorial

4.2. STARTING A PROJECT 25

All input files 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 useJCMcontrol for the setup and computation of a project. Alternatively, anarbitrary text editor can be used for editing the input files, and the computa-tions can be started over the command line (invoking Furthermore simulationprojects 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 startsthe software. The executable can also be found in the installation directoryin the subdirectory bin. Opening the tab File and then Open Project inJCMcontrol a JCMsuite project can be loaded and simulated. This is alsodescribed 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. Linuxusers sometimes to prefer to use their own specific text editor to create andedit the input files for JCMgeo and JCMsolve, and to invoke the triangulatorJCMgeo and the solver JCMsolve in the command line. This is done bytyping:

>>> 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 cre-ated. The computed fields of the finite element simulation are stored inthe file fieldbag.jcm located in the result directory. The storage for-mat (StorageFormat binary or ASCII) of this file can be choosen in the

Page 26: Tutorial

26 CHAPTER 4. GETTING STARTED

project file. With the option StorageFormat = Pinboard, this result file isnot written to disc. For eigenvalue problems the computed eigenvalues arestored in the file eigenvalues.jcm, also located in the result directory. Themain simulation results for resonance and propagating mode and scatter-ing projects can be further post-processed using built-in postprocesses likeFourier-analysis, data extraction, functional evaluation, or export functionsto visualization tools. We will introduce several post-processes in the tutorialexamples. The post processes are specified in the project file 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 finite elementsolution is already computed: over the command line JCMsolve is startedwith the option --post process instead of --solve. Further, postprocessescan be defined in their own separate files and invoked via command line orvia JCMcontrol.

In the following we introduce some post processes.

4.3.1 FieldTransformation

The FieldTransformation post-process is used to transform the computedfield into other related fields. We already explained that JCMsolve eithercomputes the electric or magnetic field in a project. Having computed theelectric field one gets the magnetic field by using the post-process ElectricFieldStrengthToMag(according to Eq. 2.2). The opposite case is possible using MagneticFieldStrengthToElectr

(see Eq. 2.1).

Furthermore we can compute, e.g.,

• the electric energy density

ElectricFieldStrengthToElectricEnergyDensity

• the magnetic energy density

MagneticFieldStrengthToMagneticEnergyDensity

• and the Poynting vector field

ElectricFieldStrengthToPoyntingVector

MagneticFieldStrengthToPoyntingVector

Page 27: Tutorial

4.4. THIRD PARTY SUPPORT 27

4.3.2 ExportFields

ExportFields post-processes are used to transform fields from the .jcm-format to other file formats, or to export fields at specific spatial positions, or,e.g., to Cartesian grids. Supported external formats are VTK (Visualizationtool kit, an open source platform independent graphics engine) and Amira(an efficient visualization programme).

4.3.3 FunctionalEvaluation

In applications it is often necessary to determine other quantities, derivedfrom the electric/magnetic field in a region of space. Therefore JCMsolveoffers a large number of FunctionalEvaluation post-processes.

For example:

• how much light is scattered from an object into a specific direction inspace (PropagatingFourierModes, FourierTransform)

• what is the field 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 flux or energy flux through a surface(e.g. ElectricFluxThroughInterfaces)

4.4 Third Party Support

JCMsuite offers third party support for Python, Matlab and Octave. In yourJCMsuite installation directory you find the subdirectory ThirdPartySupport

which includes the corresponding libraries.

In some tutorial examples we have included Matlab scripts to compareJCMsolve results to analytical solutions. Before starting them you have toadd the corresponding path

Page 28: Tutorial

28 CHAPTER 4. GETTING STARTED

(>> addpath your jcmroot path/ThirdPartySupport/matlab). To get fur-ther information about the support methods use, e.g.:>> help jcmwave loadamirafields

>> help jcmwave loadtable In chapters 10 and 11 the usage of JCMsuitefrom third party programs is explained in detail.

Page 29: Tutorial

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 first tutorial project we want learn how to load and simulate a projectwith JCMsuite. The physical setting is propagation of TE-polarized lightthrough vacuum. After computation of the project results we will have acloser look at the JCMsolve input files.

After starting JCMcontrol (section 4.2) open the tab File->Open Project.Browse to your JCMsuite installation directory and then toTutorialExamples/

Electromagnetics/

TimeHarmonic/

Scattering/

Planar/

PlanarZ/

HelloWorld/.Open the file HelloWorls.jcmpro. Before we look at the input files let us com-pute the project. Choose Computation->Triangulation in JCMcontrol, orwith click on the respective icon in the task bar. This starts JCMgeo andcreates a triangulation of the geometry. A window with a triangulation pops

29

Page 30: Tutorial

30 CHAPTER 5. HELLO WORLD!

up for one second. Expand the project tree in the project explorer window.The file grid.jcm is now listed in the result files list. Double clicking ongrid.jcm opens JCMview for a visualization of the mesh.

Now we start the finite element computation with Computation->Solve

Project, or with a click on the respective icon in the task bar. Some messagesfrom the solver are displayed in the terminal output in JCMcontrol. After fewseconds the computation should be finished. The result file fieldbag.jcm

is now listed in the result files list. Double clicking on fieldbag.jcm opensJCMview for a visualization of the computed electric field distribution. InJCMview click, e.g., on Create field view->Carpet and choose to visu-alize the real part of the z component of the field. In order to get infor-mations about computation times and computational effort, double click oncomputational costs.jcm in the result files section of the project explorer.

Let us have a look at the input files which define the project. They canbe accessed by double-clicking on the file names in the project files sectionof the project explorer in JCMcontrol:

The project file project.jcmp. defines the basic settings of the simula-tion. Here we are computing a Electromagnetic, TimeHarmonic, Scatteringproject on a Planar (i.e., 2D) geometry with TE-polarized fields (ElectricZ).The other parameters are explained in later tutorial projects. They definewhich type of finite elements we are using and how accurately we want tocompute our solution.

The file layout.jcm includes the description of the geometry. It includesa Polygon defining a square shaped computational domain. In your JCM-suite installation directory you find an extra JCMgeo tutorial where thecreation of complex geometries is described step by step.

The file triangulator.jcm) is a control file for JCMgeo.Looking at the file BoundaryConditions.jcm you find no entries. This

is because in the Hello World example no physical boundary conditions areapplied, but the computational domain is transparent on all boundaries. Forthe definition of physical boundaries, see, e.g., the tutorial project 8.2 wherewe compute modes within a resonator with perfectly conducting walls.

The file materials.jcm includes the material constants of the objectsin the layout. Looking at layout.jcm again you find MaterialId = 1 forthe polygon. This identifier corresponds to Id = 1 of the Material. Therelative permittivity and permeability of vacuum are 1. As we will see later

Page 31: Tutorial

31

you can define complex scalar or tensorial permittivities and permeabilities.In the file sources.jcm you find the description of the plane wave which

is travelling through the computational domain. It is defined by the k-vectorand field strength. We are computing a TE-polarized field with a k-vectorin the x-y-plane and the field strength directed perpendicular to the planein which the wave propagates.

Page 32: Tutorial

32 CHAPTER 5. HELLO WORLD!

Page 33: Tutorial

Chapter 6

Scattering

6.1 Scattering Problems

In many physical situations one is interested in the scattering of an electro-magnetic waves off certain obstacles or devices (scatterers). The scattereris typically embedded into an infinite domain. For example, the infinite do-main may consist of a layered media or may contain waveguides which reachinfinity, or it is just homogeneous space. In a post process step one maycompute for example the far field behaviour, scattering amplitudes or thecoupling constant to a propagating mode of a waveguide.

33

Page 34: Tutorial

34 CHAPTER 6. SCATTERING

6.2 Scattering from Cylinder (TE polariza-

tion)

Learning Targets

• basics of a scattering problem (TE polarization)

• transparent boundary conditions

• post-process: computation of electric field energy

• convergence to analytical solution

Project Description We compute the interaction of an incoming planeelectromagnetic wave in air (wavelength λ = 1.55µm) with an infinite cylin-der with material constant ǫcyl = 2.0 and diameter dcyl = 1µm. Since theproblem is invariant in one spatial dimension our computational domain istwo dimensional (planar), see Figure 6.1. The wavevector of the plane waveis parallel to this plane. We choose the polarization of the electric field per-pendicular to the computational domain (transversal electric, TE). In thiscase Maxwell’s equations reduce to a scalar equation for the z-component ofthe electric field.

The electric field enters the computational domain, is scattered by thecylinder, and leaves the computational domain via all boundaries. There-fore transparent boundary conditions are implied on all boundaries. Theseboundary conditions simulate an infinite exterior domain. Any reflections atthese artificial boundaries are avoided.

In a post process the electric field energy within the cylinder is computed.A Matlab script is provided which compares this result to the analyticalsolution. The project files to this problem are located in directoryTutorialExamples/

Electromagnetics/

TimeHarmonic/

Scattering/

Planar/

PlanarZ/

CylinderScatteringZ/

relative to JCMwave’s home directory. Use JCMgeo to triangulate the layoutand JCMsolve to compute the project.

Page 35: Tutorial

6.2. SCATTERING FROM CYLINDER (TE POLARIZATION) 35

r

computational domain

x

y

z

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

Results In the simulation run the scattering problem is first solved on theinitial mesh. This mesh is then automatically refined three times to increasethe accuracy of the solution. In each refinement step every triangle of themesh is subdivided into four smaller ones. Let us have a closer look at theoutput that is produced during the simulation run. After the last refinementstep 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

Page 36: Tutorial

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

Page 37: Tutorial

6.2. SCATTERING FROM CYLINDER (TE POLARIZATION) 37

****************** ’Computation’ completed ********************

The first few lines give information about the size of the computational do-main and a first estimate of a so called propagation error. These measuresare used by JCMsolve to set the parameters of the transparent boundaryconditions in an optimal way.

After that the steps of the solution process are given. Having solved thediscrete problem the exterior domain quality is checked: Since we usetransparent boundary conditions so called quadrilaterals are constructed atthe exterior domain boundaries. They have to be adjusted correctly with re-spect to the incoming and scattered field and geometry of the computationaldomain. This is done automatically and the correct performance checked A

Posteriori. If necessary the computation is repeated with better settingsfor the transparent boundary.

The table computational costs gives information about the number ofunknowns and computation time for each refinement step. Note that thecpu time per unknown (cpu/unknowns) is nearly constant with increasingnumber of unknowns. This is due to JCMsolve’s use of efficient solvers. Theother two tables estimate the error of the computed field. This error shouldof course decrease with increasing number of unknowns, i.e. refinement steps.In the project file a Termination criterion is given: If the error of the fieldenergy is smaller then the user specified PrecisionFieldEnergy = 1.0e-03

the computation is successfully finished.In most of the cases not the uniform refinement of the grid (each triangle is

subdivided) but an adaptive refinement strategy is recommended. Therebythe error of the computed field is estimated locally after each refinementstep and only triangles (≈ half of all triangles) with a large estimated errorare refined. This usually leads to faster convergence of the solution and toreduced computation time. Adaptive refinement is set in project.jcmp –Adaptivity = yes.

After the computation the directory project results is created whichcontains the simulation results. The file fieldbag.jcm contains the com-puted electric field on the whole computational domain. Open this file inJCMview by double-clicking on it in the project explorer. The file

computational costs.jcm contains the costs for each refinement step,and the file electric field energy.jcm contains the electric field energy.You can open this file by double clicking on it in the project explorer.

Page 38: Tutorial

38 CHAPTER 6. SCATTERING

Discussion This scattering problem can also be solved analytically. TheCylinderScatteringZ directory contains a matlab script check.m whichcomputes the electric field of the scattering project on a rectangular domainand determines the electric field energy Eana

field within the cylinder. It producesa plot of the real part of the z-component of the electric field, which can becompared to JCMsolve’s solution shown in Figure 6.2. For the field energy

�1 0 1�101

Figure 6.2: Scattering from a cylinder with radius r: Contour plot of real part of z-component of electric field.

(per unit length in z-direction) we get Eanafield = 1.47095 · 10−23 J

mfrom the

analytical matlab calculation and Esimfield = 1.46184 · 10−23 J

mfrom our simu-

lation which means a relative error of ∆ ≈ 0.6%. In the paragraph Quickown modifications we will reset some simulation parameters to increasethe accuracy.

Quick own modifications The field strength and wave vector of the in-coming plane wave are specified in sources.jcm:

Page 39: Tutorial

6.2. SCATTERING FROM CYLINDER (TE POLARIZATION) 39

• K defines the wave vector of the incoming wave and Strength the fieldvector. When you modify these parameters you have to pay attentionthat the plane wave is transversal, i.e. the wave vector and the fieldvector are orthogonal:Strength·K= 0.

The geometry of the computational domain can be modified in layout.jcm:

• Points of the polygon ”Air” specify the computational domain .

• Radius is the radius of the Circle with Name=’’scatterer’’. RefineAlldefines how accurately the circle is resolved.

The material parameters are given in materials.jcm and can also be mod-ified.

The file project.jcmp specifies the problem class and contains the mainsimulation parameters:

• The maximum number of refinement steps MaxNumberSteps can beincreased to get a more accurate result. This also costs more compu-tational time.

• Changing Adaptivity = yes results in an adaptive refinement of thegrid as explained above.

The post process specified in project.jcmp is used to evaluate the electricfield energy.To increase the accuracy of calculation set, e.g.:RefineAll = 5,PrecisionFieldEnergy = 1.00e-06 and Adaptivity = yes, MaxNumberSteps= 4 in project.jcmp.

We get Esimfield = 1.47081 · 10−23 J

m. The relative error is now ∆ ≈ 0.01%.

Page 40: Tutorial

40 CHAPTER 6. SCATTERING

6.3 Scattering from Cylinder (arbitrary po-

larization)

Learning Targets

• 2D scattering problem with arbitrary polarization

• comparison to analytical solution

• post-process: far field evaluation

Project Description This tutorial example investigates same layout asthe previous tutorial example 6.2. Here the electric field is not restrictedto transversal polarization. The k-vector of the incoming plane wave doesnot lie in the 2D cross section described by the layout, i.e., we have conicalincidence. We use the post-process FarFieldEvaluation to compute theelectric field at arbitrary points outside the computational domain. Theproject files to this problem are located in directoryTutorialExamples/

Electromagnetics/

TimeHarmonic/

Scattering/

Planar/

PlanarXYZ/

CylinderScatteringXYZ/

relative to JCMwave’s home directory. Use JCMgeo to triangulate the layoutand JCMsolve to compute the project.

Results In the tutorial directory we find the matlab script check.m. Thiscomputes the analytical solution of the cylinder scattering problem and com-pares it to the values of the electric field determined in the post processFarFieldEvaluation. Before you can start the check routine in Matlab youhave to add the third party support path, as explained in section 4.4.

Discussion We find very good agreement between analytical and numeri-cal results. Note that we not only get the correct intensity but also the correctphase of the scattered field. The points where the far field is evaluated aregiven in the project file in the post process section. Two FarFieldEvaluation

Page 41: Tutorial

6.3. SCATTERING FROM CYLINDER (ARBITRARY POLARIZATION)41

post processes are defined. The evaluation points in the exterior are given inpolar coordinates and as list with cartesian coordinates: PointsX, PointsY,PointsZ respectively.

Quick own modifications Change the evaluation points in theFarFieldEvaluation post-process in project.jcmp and check them withthe matlab script. In order to increase the accuracy of the FEM computationincrease RefineAll = 2 of the Circle in layout.jcm and MaxNumberSteps

= 1 in project.jcmp.

Page 42: Tutorial

42 CHAPTER 6. SCATTERING

6.4 Gaussian Beam on Micro Lens

Learning Targets

• defining a Gaussian beam

• post-process: computation of the Poynting vector

Project Description In this tutorial example we consider propagation ofa Gaussian beam through a micro lens. Gaussian beams are only approx-imative solutions of Maxwell’s equations. They are often used in so called“Beam Propagation Models” (BPM) and model a plane wave with a Gaus-sian envelope of the field strength. During their propagation the width ofthe envelope is increasing depending on the Rayleigh range. In our examplesuch a Gaussian beam will be focused by a micro lens. The project files tothis problem are located in the directoryTutorialExamples/

Electromagnetics/

TimeHarmonic/

Scattering/

Planar/

PlanarZ/

GaussianBeam/

relative to JCMwave’s home directory. Use JCMgeo to triangulate the layoutand JCMsolve to compute the project.

Results Figure 6.3 shows the electric field intensity of our project. Thewidth of the Gaussian beam is increasing while propagating towards the lens.The beam is partially reflected at the interface of the lens which gives riseto the interference pattern. Behind the lens we see a large intensity at thefocal point.

In a post process we compute the poynting vector field of our solution.Figure 6.4 shows how the energy flux is focused by the lens.

Discussion The Gaussian beam is described in sources.jcm. The MaterialIdcorresponds to the MaterialIds in layout.jcm which belong to the trans-parent boundaries. It specifies on which boundaries the Gaussian beam isset as a source. In addition to the field strength and wave vector we have

Page 43: Tutorial

6.4. GAUSSIAN BEAM ON MICRO LENS 43

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

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

Page 44: Tutorial

44 CHAPTER 6. SCATTERING

to specify the RayleighRange (see the parameter reference for an exact defi-nition) of our beam. A smaller Rayleigh range leads to a smaller width butalso to a faster widening of the beam. The position of minimal width of theGaussian beam is specified by FocalPosition.

Quick own modifications Change the parameters of the Gaussian beam.

Page 45: Tutorial

6.5. PHOTOLITHOGRAPHY: EUV - MASK 45

6.5 Photolithography: EUV - Mask

Learning Targets

• reflection of light from an EUV line mask

• periodic boundary conditions

• post-process: propagating fourier coefficients for periodic domains

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

Project Description We compute the reflection of light from an EUVline mask. Such a mask consists of a Bragg mirror covered with a periodic

Page 46: Tutorial

46 CHAPTER 6. SCATTERING

arrangement of absorber lines. The Bragg mirror is a stack of alternatinghigh-/low-refractive index material layers (usually molybdenum and silicon,MoSi).

Since the mask is periodic in one space dimension it is sufficient to take theperiodic interval (pitch = width) as computational domain. To simulate theinfinite extension of the mask we apply periodic boundary conditions to thecorresponding boundaries. On the other boundaries we apply transparentboundary conditions to simulate air above the EUV mask and substratebelow the multilayer.

When the mask is illuminated light is reflected into a number of discretediffraction orders due to the periodic structure of our geometry. The postprocess PropagatingFourierModes determines the complex amplitudes ofall diffraction modes which are not evanescent.

The computational domain is shown in Figure 6.5. The wave vector ofthe incident plane wave is parallel to this plane. The electric field is polarizedperpendicular to the plane and has wavelength of λ = 13.35nm. The angleof incidence is θ = 5◦

Our EUV mask has 40 MoSi-layers as a Bragg mirror. The absorberstructure consists of an SiO2 buffer and the covering Chromium absorber.The mask has a pitch p = 100nm.

The project files to this problem are located in directoryTutorialExamples/

Electromagnetics/

TimeHarmonic/

Scattering/

Planar/

PlanarZ/

EUVmask/

relative to JCMwave’s home directory. Use JCMgeo to triangulate the layoutand JCMsolve to compute the project.

Results In the post-process all propagating diffraction orders (Fourier co-efficients) for the incident plane wave are computed. The correspondingamplitudes are stored in the file propagating fourier coefficients.jcm.The computation reached the error criterion for the field energy 1e−1 whichwas specified in the control file already after three refinement steps. There-fore JCMsolve did not compute the maximum specified number of four re-

Page 47: Tutorial

6.5. PHOTOLITHOGRAPHY: EUV - MASK 47

finement steps. If one wants to make sure that all refinement steps arecomputed 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 field of the setup isshown in Figure 6.6. We observe that the intensity of the electric field is

Figure 6.6: EUV mask: Intensity of electric field.

reduced below the absorber pattern. A selection of fourier coefficients areshown in Figure 6.7 in dependence on the angle of reflection.

We notice that the computational domain can become quite large fora Bragg mirror with many layers and for large pitches. It is possible tosolve the problem of light propagation in a multilayer stack analytically withthe so called matrix transfer algorithm. A domain decomposition algorithm

Page 48: Tutorial

48 CHAPTER 6. SCATTERING

0 10 20 30 40 50 60 701×10-5

1×10-4

0.001

0.01

0.1

1

angle of reflection θ [◦]

nor

mal

ized

inte

nsi

ty

Figure 6.7: Scattering from an EUV mask: Normalized intensity of different diffractionorders for incidence angle θin = 5◦. Intensity is normalized to incident field intensity.

can be used to take advantage of the analytical solution and decrease thecomputation time significantly. It combines the analytical solution and thefinite element computation. The usage of the domain decomposition solverwill be explained in the next tutorial example.

Page 49: Tutorial

6.6. PHOTOLITHOGRAPHY II : EUV - MASK REVISITED 49

6.6 Photolithography II : EUV - Mask revis-

ited

Learning Targets

• reflection from an EUV mask

• domain decomposition algorithm

Project Description We compute the reflection of light from the EUVmask that was introduced in the previous EUV tutorial with a domain decom-position algorithm. Here we allow arbitrary incidence of the plane wave (an-gle between wave vector and normal vector of the multilayer surface θ = 5◦,angle between wave vector and projection of wave vector onto the compu-tational domain φ = 10.2◦) and arbitrary polarization. We will determine thefourier coefficients of the reflected plane wave with the PropagatingFourierModespost process for periodic domains.

The project files to this problem are located in directoryTutorialExamples/

Electromagnetics/

TimeHarmonic/

Scattering/

Planar/

PlanarXYZ/

EUVmask/

relative to JCMwave’s home directory. Use JCMgeo to triangulate the layoutand JCMsolve to compute the project.

Results The domain decomposition algorithm works as follows. First prop-agation of the incident plane wave within the absorber structure is computedwithout the multilayer structure underneath using the finite element method.In a second step the propagation of light within the multilayer is determinedanalytically where the solution from the previous step on the lower boundaryis taken as a source. The reflected light from the multilayer and the incidentplane wave on the absorber are then taken as a source for the computationof the absorber structure. These steps are iterated until a chosen accuracyis reached.

Page 50: Tutorial

50 CHAPTER 6. SCATTERING

Discussion Although we have an arbitrarily polarized field and thereforemore unknows the project is solved very fast due to the domain decomposi-tion algorithm. The intensity of the computed field is shown in Figure 6.8.

Figure 6.8: EUV mask: Intensity of electric field computed with domain decompositionalgorithm.

For periodic scatterers an incoming plane wave is scattered into differ-ent diffraction orders which depend on the periodicity. The post processPropagatingFourierModes computes the complex amplitudes of all propa-gating diffraction orders.

Quick own Modifications The multilayer structure is not described inlayout.jcm but in materials.jcm. In the MaterialBag of layout.jcm

we find the entry LayeredMedia with the parameter lists LayerThickness,RelPermeabilityInLayers, and RelPermittivityInLayers which chara-terize the multilayer. The first entry of these lists specifies thickness andmaterial properties of the first layer and so on. The number of entries inall lists have to be the same of course. The substrate below the multilayer

Page 51: Tutorial

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 isattached to the computational domain.

In this example the relative error of the field energy did not reach thespecified error criterion of 1 in the control file with two adaptive refinementsteps. In such a case JCMsolve gives a warning at the end of the computation.

Page 52: Tutorial

52 CHAPTER 6. SCATTERING

6.7 Mie Scattering

Learning Targets

• cylindrically symmetric problems

• post-process: evaluation of far field coefficients

• CoordinateRenaming

r

symmetry axis

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

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

Page 53: Tutorial

6.7. MIE SCATTERING 53

on a slice of the cylinder including the symmetry axis as a boundary as shownin Figure 6.9. In scattering problems it is often desirable to determine thescattered electric field far away from the scatterer. This computation is im-plemented in the FarFieldEvaluation post process. The project files to thisproblem are located in the directoryTutorialExamples/

Electromagnetics/

TimeHarmonic/

Scattering/

Cylindrical/

MieScattering/

relative to JCMwave’s home directory.

Results In the tutorial directory we find the matlab script check.m. Thiscomputes the analytical solution of the Mie scattering problem and comparesthe analytical far field values to the simulated ones at the EvaluationPointsspecified in the post process. We find very good agreement.

Discussion If we use the FarFieldEvaluation post process we have totake care to choose the evaluation points relatively far away from the com-putational domain. Note that we not only get the correct intensity but alsothe correct phase of the scattered field. The points where the far field isevaluated 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 define aCoordinateRenaming. It is defined for a FarFieldEvaluation post process:

FarFieldEvaluation {

MaterialFileName = "./materials.jcm"

SourceFileName = "./sources.jcm"

CoordinateRenaming = X:Z:-Y

CoordinateType = {

...

}

}

}

Page 54: Tutorial

54 CHAPTER 6. SCATTERING

The syntax of CoordinateRenaming can be understood as follows. Fig. 6.10shows the original coordinate system. The computational domain alwayslies in the x-y plane. Now we want to rename the axis. The new ”name”of the original x-axis is written before the first colon, the new name of theoriginal y-axis is between both colons and the name of the original z-axisafter the second colon. Hence CoordinateRenaming = X:Z:-Y means thenew x-axis agrees with the old x-axis, the new z-axis agrees with the old y-axis, 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 thepoints where the far field is evaluated have to be specified in the renamedcoordinate system. The results of the post process are also given in therenamed coordinate system.

Quick own modifications We can change the evaluation points in theFarFieldEvaluation post process in project.jcmp. Here the points arespecified by the CoordinateType Polar. For a fixed Radius we can choosePointLists of values for the polar angles. The number of points where thefar field is evaluated and therefore the length of the PointList is arbitrarybut PointsPhi and PointsTheta must have the same length. Use the matlabscript check.m to check the results.

Page 55: Tutorial

6.7. MIE SCATTERING 55

x

y

z

evaluation point

r (Radius)

ϕ (Phi)

θ (Theta)

Figure 6.10: Coordinate system used for far field evaluation. A 2D computa-tional domain always lies in the x-y plane. For evaluation points in the x-yplane we have θ = 90◦.

x

y

z

evaluation point

r (Radius)

ϕ (Phi)

θ (Theta)

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

Page 56: Tutorial

56 CHAPTER 6. SCATTERING

6.8 Circular Pupil (cylindrical)

Learning Targets

• cylindrically symmetric scattering project

• post-process: Fourier transform

• post-process: aerial image (far field image after imaging)

Project Description In this project we compute transmission of lightthrough an isolated circular pupil in a gold foil. Because of the rotationalsymmetry this project is computed as a cylindrical problem on a 2D slice asexplained in project 6.7. After the finite element computation of the near fieldwe are interested in the far field image. Since we do not have a peridoic layoutthe far field is not represented by a discrete set of propagating diffractionmodes but by a continuous Fourier transform. A discrete sampling of theFourier transform of the image is computed in the FourierTransform postprocess and then used in the ExportImageToAmira post process to determinethe aerial or far field image of the pupil. A Matlab script for visualization ofthe far field is included in the project directory. In project 6.9 we will computethe same problem in 3D without making use of the rotational symmetry. Theproject files to this problem are located in directoryTutorialExamples/

Electromagnetics/

TimeHarmonic/

Scattering/

Cylindrical/

CircularPupil/

relative to JCMwave’s home directory. Use JCMgeo to triangulate the layoutand JCMsolve to compute the project.

Results A 2D slice of the layout is triangulated. The symmetry axis cor-responds to the left boundary of the computational domain. The gold foil ispartially in the computational domain and extends to infinity in the quadri-laterals of the transparent boundary conditions. The radius r of the circularpupil is equal to the distance between the symmetry axis and the gold foil,r = 2 µm.

Page 57: Tutorial

6.8. CIRCULAR PUPIL (CYLINDRICAL) 57

The first post process FourierTransform computes the Fourier transformof the near field in the half space above the layout. ’Above’ hereby means thehalf space y > ymax where ymax is the y-coordinate of the top boundary of thelayout. For better comparison with project 6.9 and for applicability of thepostprocess PassOpticalSystem (which by default assumes propagation inz-direction) a CoordinateRenaming = X:Z:-Y is introduced since for the 3Dgeometry the z-axis corresponds to the y-axis of this rotationally symmetricalproblem. The parameter DeltaK defines the resolution of the sampling ofthe Fourier transform. The post process PassOpticalSystem corresponds toaerial imaging with a defined spot magnification and numerical aperture. Thepost process ExportImageToCartesianGrid uses the output from the aerialimaging postprocess to build up the spatial aerial image after imaging on a 3Dspace domain specified by GridPointsX, GridPointsY, GridPointsZ. Thecomputation of the aerial image is simply the inverse Fourier transform. Letus denote the Fourier transform of the electric field by E(kx, ky, kz) = E(k).Then the inverse Fuorier transform is defined 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) thenreads:

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 field and Fouriertransform. The term ∆(i,j,k) denotes the finite 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-valuesinto the output file. Decreasing DeltaK makes the inverse Fourier transform(6.2) more accurate. The near field and the aerial image can be visualizedusing JCMview.

Page 58: Tutorial

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 field image)

Project Description In this project we compute transmission of lightthrough an isolated circular pupil in a gold foil. In contrast to project 6.8 wecompute the project in 3D. The 3D layout is thereby described by a stack oflayers of specific height with material distributions which change only in 2D.After the finite element computation of the near field we are interested in theaerial image. The fourier transform of the near field is computed with theFourierTransform post process and then used in the PassOpticalSystem

and ExportImageToCartesian post processes to determine the aerial imageof the pupil.The project files to this problem are located in directoryTutorialExamples/

Electromagnetics/

TimeHarmonic/

Scattering/

Stack/

CircularPupil/

relative to JCMwave’s home directory. Use JCMgeo to triangulate the layoutand JCMsolve to compute the project.

Results A discussion about the computation of the fourier transform andfar field can be found in project 6.8. The field distributions can be visualizedusing JCMview. A comparison to the far field obtained in project 6.8 showsgood agreement. Differences are due to the coarser grid in the 3D compu-tation. Furthermore in the 3D computation the circle is approximated bya polygon and therefore not perfectly round in contrast to the rotationallysymmetric computation.

Let us have a look at the description of the 3D layout. It is describedin layout.jcm by a stack of layers of specified heights (see also the JCMgeo

Page 59: Tutorial

6.9. CIRCULAR PUPIL (3D) 59

tutorial for a detailed description of stacked layouts). The triangulated ge-ometry (file grid.jcm) can be visualized using JCMview. We find a Polygon

and a Circle in the layout file. The following HeightProfile now describesof which materials the circle and the parallelogram consist in each layer. The3D 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 defined corresponding to the exteriordomains. The parameter Thickness defines the extension of the respectivelayer in z-direction. The MaterialIdMapping maps the MaterialIds of thegeometrical objects in the layout file onto the Ids of the material file. E.g., [1102 2 101] in a specific layer means: In this layer, MaterialId 1 appearingin the 2D section of the layout file is mapped onto Id 102 in the material fileand MaterialId 2 appearing in the layout file is mapped onto Id 101 in thematerial file for this layer.

Page 60: Tutorial

60 CHAPTER 6. SCATTERING

Page 61: Tutorial

Chapter 7

Propagating Modes

7.1 Propagating Mode Problems

The computation of propagating modes is a central task in the design of op-tical waveguides. In section 3.2.3 we already definded the propagating modeproblem mathematically: We consider waveguides that are invariant in z di-rection and arbitrarily shaped in the x-y-plane. A propagating mode solutionof time harmonic Maxwell’s equations then exhibits a harmonic dependencyin the z-direction,

E = Epm(x, y) exp (ikzz)

H = Hpm(x, y) exp (ikzz) .

JCMsolve searches for such propagating mode solutions and returns the ef-fective refractive index defined as

neff =kz

k0with k0 =

λ0

and the corresponding eigenmode Epm(x, y), Hpm(x, y) respectively. λ0 isthe vacuum wavelength of the propagating mode; the vacuum wavelength isa parameter defined by the user in the project file.

61

Page 62: Tutorial

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 modeof a cylindrical optical fiber with a doped silica core (relative permittivityǫcore = 2.113, diameter dcore = 8.2µm) and silica cladding (ǫcladding = 2.1025,diameter dcladding = 80µm), see Figure 7.1. At the outer boundary we assumethat the tangential component of the magnetic field is decayed to zero. Thefundamental mode is twofold degenerate. In a sub-project projectE.jcmp

the electric components are computed and in the sub-project projectH.jcmpthe magnetic field components are computed.

Doped SilicaCore

Silica Cladding

Figure 7.1: Optical fiber. Left: The core has a permittivity ǫcore = 2.113 and a diam-eter dcore = 8.2µm. The cladding has a permittivity ǫcladding = 2.1025 and a diameterdcladding = 80µm. We assume that the tangential component of the magnetic field vanisheson the outer boundary. Right: Isoline plot of the computed electric field intensity |E|2

with finite element grid.

Page 63: Tutorial

7.2. SINGLE MODE FIBER 63

The project files to this problem are located in the directoryTutorialExamples/

Electromagnetics/

TimeHarmonic/

PropagatingMode/

SingleModeFiber/

relative to JCMwave’s home directory. Use JCMgeo to triangulate the layoutand JCMsolve to compute the project.

Results We first discuss the project projectE.jcmp. 1 Let us look at theoutput during the computation. The computation starts with an initial tri-angulation (refinement level 0 ...). The grid is refined twice during thecomputation leading to a more accurate solution. In a refinement step eachtriangle is subdivided into four smaller ones. The output of the last refine-ment step is shown in Figure 7.2. The table computational costs showsinformation about the computation time and number of unknowns. In eachrefinement level we get an increased number of unknowns and therefore anincreased computation time. Note that the computation time per unknown(cpu/unknowns) is nearly constant due to JCMsolve’s use of efficient solvers.The other tables show the effective refractive index neff of the firstand 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 files eigenvalues.jcm andcomputational costs.jcm in directory projectE results which is createdautomatically. The file fieldbag.jcm contains the calculated electric fieldstrength of the propagating modes within the fiber. Double-click on this filein the JCMcontrol’s project explorer in order to start JCMview to view thefield distributions of the computed eigenmodes.

Discussion Since the first and second effective refractive indices are equalwe found that our eigenmode is twofold degenerate as we expected. Computealso the magnetic field distributions of these eigenmodes using projectH.jcmp;

1This tutorial example contains several project definition files: projectE.jcmp,projectH.jcmp, projectScalar.jcmp. To switch between these project files within JCM-control, please click with the right mouse button on the respective project file name andselect Set as active project file . . . . The icons next to the project files indicate which oneis active.

Page 64: Tutorial

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 finite elementsolver for the first and second mode. This information is also stored in the filescomputational costs.jcm and eigenvalues.jcm.

Page 65: Tutorial

7.2. SINGLE MODE FIBER 65

Figure 7.3: Isoline plots of electric field’s z-components Ez (imaginary part) for thetwofold degenerate fundamental mode.

it is found that this project converges – as expected – to the same funda-mental eigenmodes with exactly the same effective refractive index.

Figure 7.1 (right) shows the intensity iso-lines of the computed electricfield. In Figure 7.3 the z-components of the twofold degenerate fundamentalmodes are plotted. The field is confined in the core of the fiber and van-ishes quickly (exponentially) with the distance to the core. This justifiesour assumption that the tangential components of the magnetic field at theouter boundary of the cladding are zero. Boundary conditions which set themagnetic (electric) field to zero on a boundary are so called Dirichlet bound-ary conditions. They are specified in the file boundary conditions.jcm. Intutorial example 7.3 and 7.7 transparent boundaries are used to take into ac-count coupling of so-called leaky waveguide modes with the exterior domainssurrounding the fiber cross section.

Quick own modifications Now we can modify our problem. The basicsimulation parameters are specified in projectE.jcmp:

• Lambda0 is the vacuum wavelength of light that propagates throughthe fiber.

• In order to find a propagation mode we have to make an initial guess(e.g., Guess = 1.5) for the effective refractive index. We can change

Page 66: Tutorial

66 CHAPTER 7. PROPAGATING MODES

this parameter to find higher eigenmodes, e.g. Guess = 1.3. Theparameter NumberEigenvalues specifies the number of eigenvalues thatare determined numerically.

• Beside these physical model parameters we can control the accuracy ofour computation. If the propagation constant is determined with anerror smaller than the value PrecisionEigenvalues the calculationis stopped. MaxNumberSteps gives an upper bound for the number ofrefinement steps of the grid that are performed during the computa-tion. Adaptivity specifies if the grid is refined adaptivly or regularly.Thereby Adaptivity = yes is recommended in most cases since adap-tive refinement usually enhances the convergence rate of the results (i.e.decreases cpu time and leads to more accurate results). When usingadaptivity the grid is refined only in regions with a large estimatederror whereas without adaptivity the grid is refined uniformly.

Try PrecisionEigenvalues = 1e-10 and increase MaxNumberSteps =

5 to get a more accurate result. Furthermore, compare, e.g., computa-tions with Adaptivity = yes / no.

The geometry of the fiber is described in layout.jcm:

• Change the Radius of the doped silica core SMFCore or of the silicacladding ComputationalDomain.

• The parameter RefineAll specifies how accurate the respective circleis resolved in its polygonal representation.

The relative permeabilities and permittivities of the domains are specified inmaterials.jcm. Investigate how the eigenvalues change with the permittiv-ities of the materials.

Scalar Approximation The jump of the refractive index between the coreand the cladding of the fiber is small (ncore/ncladding ∼ 1.0024). Therefore,we want to check how close we get to the true vectorial solution by the scalarapproximation where the jump of the normal field along the material boundis neglected. This approximation yields the same scalar eigenvalue problemfor the electric and magnetic field equation. Hence the fundamental modeis not anymore twofold degenerate. The corresponding project file is named

Page 67: Tutorial

7.2. SINGLE MODE FIBER 67

projectScalar.jcmp. In fact one finds that for the investigated simple prob-lem, this approximation yields the exact eigenvalue up to a relative accuracyof 10−6. In the post-process ExportFields we export our simulation resultfieldbag.jcm to the AMIRAformat fieldbag.am. This file can be used forvisualization with the JCMview, AMIRA, or Matlab(see section 4.4).

Page 68: Tutorial

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 ofa waveguide. Determination of these modes has to take into account thatradiation can leak into the exterior. Therefore leaky modes are damped whilepropagating along the waveguide. The effective refractive index becomescomplex.

ǫcore

ǫlayer

rcore

dlayer

ǫexterior = ǫcore

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

Page 69: Tutorial

7.3. LEAKY WAVEGUIDE 69

We use a very simple waveguide structure to compare our numerical resultto an analytical solution of the problem. This analytical solution is imple-mented in the Matlabscript check.m located in the same tutorial folder. Thelayout is as follows: A silica core (ǫcore = 2.1025) is surrounded by a thinlayer of low refractive index material (ǫlayer = 1.4). The exterior also consistsof silica and extends to infinity. The layout is shown in Figure 7.4. Trans-parent boundary conditions model that radiation can leak from the finitecomputational domain to the exterior without reflections.The project files to this problem are located in the directoryTutorialExamples/

Electromagnetics/

TimeHarmonic/

PropagatingMode/

LeakyFiber/

relative to JCMwave’s home directory. Use JCMgeo to triangulate the layoutand JCMsolve to compute the project.

Results As expected we observe that the effective refractive index becomescomplex. Now we can use the Matlabscript check.m to check if the computedeffective refractive can also be found analytically. We start check.m with thecomputed result (we specify the first 2 digits).

>>> check(1.38)

Discussion The finite element solution agrees very well with the analyti-cal result. Since the effective refractive index is complex the leaky mode isdamped while propagating along the fiber. Note: If one calculates a leakymode and is especially interested in the imaginary part of the effective re-fractive index and if the imaginary part is much smaller the real part it canbe more efficient to use regular refinement (Adaptivity = No in the projectfile). The adaptive refinement strategy reduces the relative error of the com-plex effective refractive index. In such cases adaptivity may mainly reducethe error of the larger real part of the effective refractive index.

Quick own modifications Now we can change the material parametersof the layout in file materials.jcm. Furthermore we can change the layoutitself, layout.jcm. The layout consists of two concentric circles. The radiusof the core (Circle with Name = "Core") is specified by Radius = 1.0.

Page 70: Tutorial

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 thickness1.2 − 1.0 = 0.2. The Guess = 1.385 in project.jcmp can be modifiedto look for other propagating modes, as explained in tutorial example 7.2.The material and layout parameters can also be adjusted in the first lines ofcheck.m to verify other finite element results.

Page 71: Tutorial

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 first modes of an air filledrectangular microwave waveguide with sidelengths 0.1 m and 0.05 m, propa-gating with a vacuum wavelength of 0.1m. At the outer boundary we imposeperfectly conducting electric boundary conditions. This means that the elec-tric field is normal to the boundary.

The project files to this problem are located in the directoryTutorialExamples/

Electromagnetics/

TimeHarmonic/

PropagatingMode/

RectangularMicrowaveWaveguide/

relative to JCMwave’s home directory. Use JCMgeo to triangulate the layoutand JCMsolve to compute the project.

Results In the HelloWorld example 7.2 we already described that in eachrefinement step of the calculation we get a more accurate result. Now wewant to quantify this convergence of the numerical simulation. Thereforewe compare the simulation results to the analytical solution of our problem.The exact eigenmodes (effective refractive indices) to the problem are givenby:

neff,m,n =

1 −m2

4− n2

with m ≥ 0, n ≥ 0 and m + n ≥ 1. This formula yields the analytical valuesfor the first eight effective refractive indices shown in table 7.1. Solvingproject project.jcmp we get the numerical values for neff . They are alsoshown in table 7.1.

Page 72: Tutorial

72 CHAPTER 7. PROPAGATING MODES

neff analytical numerical

1 0.866025404 0.8660254

23

0.0(2)0.00009510.0002082i

45

0.5i(2)0.5000000i0.5000001i

67

1.0i(2)1.000000i1.000000i

8 1.11803399i 1.118034i

Table 7.1: Effective refractive index neff of rectangular waveguide. Comparison ofanalytical and numerical solution for the first 8 eigenmodes. In the analytical result ”(2)”means that this mode is twofold degenerated.

Discussion We see that the computed finite element solution is in per-fect agreement with the exact eigenvalues. Let’s have a closer look at theconvergences of the first and eighth mode. The convergence information pro-duced by the solver is given in Figure 7.5. The finite element grid is refineduniformly. One expects that the computed discrete solution converges tothe exact value. Each row in the tables corresponds to one grid level. Tocheck convergence one monitors the relative deviation of the eigenvalues cor-responding to two successive grid levels. This is given in column delta. Toassure convergence this relative deviation must decrease with a fixed rateratio. 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 indeedreached (column ”ratio”).

The electric fields of the computed eigenmodes are plotted in Figure 7.6.

Quick own modifications Now we can modify the problem. The numberof refinement steps, precision, and adaptivity can be modified to test theconvergence towards the exact solution with higher precisions. Since weknow the analytical values for the effective refractive index we can try tofind specific higher eigenmodes by setting Guess to a value close to neff,m,n

with larger n, m.

Page 73: Tutorial

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 bythe finite element solver for the first and eight mode. The convergence rate (ratio) is invery good agreement with the theoretically expected rate for second order finite elements.

Page 74: Tutorial

74 CHAPTER 7. PROPAGATING MODES

1) 2)

3) 4)

5) 6)

7) 8)

Figure 7.6: Rectangular Microwave Waveguide: Vector plots of the eight first propagat-ing modes (electric field).

Page 75: Tutorial

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 first four fundamental modes of adirectional coupler. The structure is as depicted in Figure 7.7. The coupler isanalyzed at a vacuum wavelength of λ0 = 1.55 µm. The substrate consists ofindium phosphite with a refractive index of nsub = 3.17. The waveguide layeris made of indium gallium arsenide phosphite, nlayer = 3.38. The two ribs ofthe coupler are symmetrically arranged and have a height of h = 1.0 µm and awidth 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 waveguideswhich are close to each other.The project files to this problem are located in the directoryTutorialExamples/

Electromagnetics/

TimeHarmonic/

PropagatingMode/

DirectionalCoupler/

relative to JCMwave’s home directory. Use JCMgeo to triangulate the layoutand JCMsolve to compute the project.

hAir

InGaAsP

InP

w w

d

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

Page 76: Tutorial

76 CHAPTER 7. PROPAGATING MODES

Results The computed propagation constants are:

neff,1 = 3.194984

neff,2 = 3.194929

neff,3 = 3.188598

neff,4 = 3.188552

Discussion The first and second modes and the third and fourth modes arevery close to each other respectively. They are ”nearby” degenerate. This isdue to the relatively large distance of the ribs. For larger distances of the ribsthe coupling between the two waveguides vanishes and the first and secondmodes are simply the two fundamental modes of the separeted waveguides.Figure 7.8 shows vector plots of the magnetic fields. The z-components ofthe fields are non-zero but much smaller than the components in the crosssection, see Figure 7.9.

TE/TM approximation Modes which are nearly completely polarized inone spatial direction (TM, TE) are typical for some optical waveguide config-urations. In this example the ribs of the two waveguides may be consideredas a (small) perturbation of a slab structure. For this special situation aTE/TM approximation is sometimes used, where all weak components areneglected. This yields two different scalar eigenvalue problems for TE andTM modes. The corresponding project files are called projectTE.jcmp andprojectTM.jcmp.2 The difference between the project file for the rigoroussolution and the project files for the approximations are only few lines:

Rigorous {

MagneticXYZ {

in project.jcmp (for the rigorous solution),

Approximate {

SemiVectorialMagneticX {

2This tutorial example contains several project definition files: project.jcmp,projectTM.jcmp, projectTE.jcmp. To switch between these project files within JCM-control, please click with the right mouse button on the respective project file name andselect Set as active project file . . . . The icons next to the project files indicate which oneis active.

Page 77: Tutorial

7.5. DIRECTIONAL COUPLER 77

1)

2)

3)

4)

Figure 7.8: Directional Coupler: Magnetic field vector plots of the first four eigenmodes.

Page 78: Tutorial

78 CHAPTER 7. PROPAGATING MODES

Figure 7.9: Directional Coupler: Isoline plots of the magnetic fields’s z-components.

Page 79: Tutorial

7.5. DIRECTIONAL COUPLER 79

in projectTM.jcmp for the TM approximation,

Approximate {

SemiVectorialMagneticY {

for in projectTE.jcmp for the TE approximation. Using approximations cansave some computation time. The computed propagation constants are:

neff,TE,1 = 3.194816

neff,TE,2 = 3.194766

neff,TM,3 = 3.188619

neff,TM,4 = 3.188561

Now we compare this result to the propagation constants neff,i obtained with-out TE/TM approximation. We see very good agreement. But the error ofthe TE/TM approximation (neff,i − neff,TE/TM,i) is larger than the relativedistances between the first and second mode (neff,1 − neff,2), and betweenthe third and fourth mode (neff,3 − neff,4), respectively. Hence the TE/TMapproximation should not be used if one is interested in small splittings ofthe eigenvalues.

Quick own Modifications We can modify the distance d between thetwo ribs. We expect that the magnitude of the splitting of the propa-gation constants neff,1, neff,2 and neff,3, neff,4 respectively changes. There-fore we have to modify the position of the ribs, which can be done inlayout.jcm. To increase or decrease the distance please edit, e.g., the pa-rameter GlobalPositionX for the two polygons corresponding to the ribs.The parameter GlobalPositionX defines an offset of the polygon points. Forsmaller distances of the ribs the eigenvalue splitting of the eigenmodes shouldincrease.

Page 80: Tutorial

80 CHAPTER 7. PROPAGATING MODES

7.6 Plasmonic Waveguide

Learning targets

• calculation of plasmon-polaritons

• multiscale problem

• adaptive refinement

• exploitation of symmetric geometry

• post-process: computation of magnetic field from electric field

Problem Description This example is taken from Berini’s paper 1. Wecompute a Plasmon-polariton wave guided by a thin silver film boundedby different dielectrics. The geometry is sketched in Figure 7.10. The rel-ative 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 film (silver) has a relative permittivity of ǫr,2 =−19 + 0.53i at this wavelength. In this example we compute the ss1

b -mode(c.f., Berini) which has a mirror symmetric electric field with respect to thesymmetry axis of the waveguide. Therefore it suffices to discretize only onehalf of the waveguide and to impose a magnetic boundary condition at thesymmetry axis. The metal film has a thickness of t = 0.0245 µm and a widthof w = 1 µm.The project files to this problem are located in the directoryTutorialExamples/

1P. Berini, Plasmon-polariton waves guided by thin lossy metal films of finite width:

Bound modes of symmetric structures, Physical Review B 61, 10484 (1999)

� � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �� � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � � �Silvert

w

Upper Material

Lower Material

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

Page 81: Tutorial

7.6. PLASMONIC WAVEGUIDE 81

Figure 7.11: Plasmon-polariton waveguide: Field intensity around the metal film. Theelectric field is highly discontinuous across the material borders. At the corners of themetal films characteristic singularities are clearly visible.

Figure 7.12: Plasmon-polariton waveguide: Imaginary part of electric field’s z-component ℑ(Ez) around the metal film. The z–component of the electric field is contin-uous but it’s derivative jumps across material interfaces.

Page 82: Tutorial

82 CHAPTER 7. PROPAGATING MODES

0 0.5 1 1.5�0.500.5

Figure 7.13: Discretization of the computational area close to the silver film: Electricfield strength in the vicinity of the metal film. Especially at the metal’s corners thecomputational domain discrtetized very coarse.

Electromagnetics/

TimeHarmonic/

PropagatingMode/

Plasmon/

relative to JCMwave’s home directory. Use JCMgeo to triangulate the layoutand JCMsolve to compute the project.

Results In this example we will not look at the propagation constant butconcentrate our attention on the numerical solution for the electric field in-tensity on the whole computational domain, which represents a Plasmon-polariton, see Figures 7.11, 7.12.

Discussion The accurate computation of plasmon-polariton modes is achallenging problem due to the singular field behaviour near the metal’s cor-ner and due to the multi-scale structure of the geometry. We have a veryslim silver film at the interface of two thick substrates. The propagatingPlasmon-polariton is mainly located at the vicinity of the silver strip. Anadaptive finite element discretization is the method of choice for such prob-

Page 83: Tutorial

7.6. PLASMONIC WAVEGUIDE 83

lems. Figure 7.13 shows the mesh for the FEM computation on the last meshrefinement level. Due to the adaptive refinement steps the mesh is refinedespecially close to the strip and close to the metal’s corners were the electricfield shows singular behaviour and has to be resolved very accurately.

In the post-process ElectricFieldStrengthToMagneticFieldStrengthwe compute the magnetic field (fieldbag magnetic.jcm) from the simulatedelectric field (fieldbag.jcm). Then we use the ExportFields process to ex-port the resulting magnetic field to the AMIRA file format (fieldbag magnetic.am).Note that the two post processes have to be in this order in the project file.

Page 84: Tutorial

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 flux through interface

0 0.5 100.5

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

Page 85: Tutorial

7.7. PHOTONIC CRYSTAL FIBER 85

Project Description We compute so called leaky propagation modes ina hollow-core photonic crystal fiber (HCPCF). A HCPCF guides light ina hollow core which is surrounded by a photonic crystal structure. Thisstructure greatly reduces leakage to the exterior of the fiber. The hollowcore is usually filled with air or other gases.

In tutorial example 7.2 we already computed propagation modes in a sin-gle mode fiber. Since the electric field at the outer boundary of the fiber wasvery weak we used TangentialMagnetic boundary conditions, i.e., we set thetangential component of the magnetic field equal to zero at the boundary. Inthis example we have to take into account that radiation can leak to the ex-terior of the computational domain due to the fact that the refractive indexin the main waveguiding region is smaller / not larger than in the exterior.Therefore we apply transparent boundary conditions to the outer boundariesof our layout. Figure 7.14 shows a quarter of the HCPCF layout. Mirrorboundary conditions are applied to the left and lower boundaries of the com-putational domain. To check that energy is leaking to the exterior we use thepost-process ElectricFieldStrengthToEnergyFluxThroughInterfaces. Itcomputes the energy flux through the boundaries of our computational do-main. The project files to this problem are located in the directoryTutorialExamples/

Electromagnetics/

TimeHarmonic/

PropagatingMode/

HollowCoreFiber/

relative to JCMwave’s home directory. Use JCMgeo to triangulate the layoutand JCMsolve to compute the project.

Results The computed eigenmodes are written to eigenvalues.jcm indirectory project results. Figure 7.15 shows the intensity of the corre-sponding propagation mode.

Discussion The propagation constant now has an imaginary part, i.e., thecomputed leaky mode is damped while propagating through the fiber. This isa result of the transparent boundary and leakage of radiation to the exterior.

Since the problem is symmetric we choose only one quarter of the fibercross section as computational domain. At the inner boundaries we specifyboundary conditions which define the symmetry properties of the computed

Page 86: Tutorial

86 CHAPTER 7. PROPAGATING MODES

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

eigenmodes.Now we look at the energy flux through the boundaries of our computa-

tional domain energyFluxThroughInterfaces.jcm in the result directory.The table rows hold the values of energy flux between all pairs of adjacentmaterials. The physical observable of interest is the real part of the energyflux. In this tutorial example the flux from the region with material Id = 1(material: glass inside the computational domain) to the region with mate-rial Id = 3 (material: glass in the exterior domain) corresponds to leakageto the exterior.

Page 87: Tutorial

Chapter 8

Resonance Modes

8.1 Resonance Problems

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

87

Page 88: Tutorial

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 filled rectangularresonator with sidelengths a = 10 µm and b = 7 µm. At the outer boundarywe impose perfectly conducting boundary conditions. This means that thetangential component of the electric field is zero at the boundary.

The project projectFundamental.jcmp uses an algorithm that computesa specified number of fundamental eigenmodes (i.e., smallest frequencies),whereas projectNearGuess.jcmp computes eight eigenvalues close to an ini-tial guess for the frequency ω.1

This can be used to search for specific modes with higher frequencies.The project files to this problem are located in the directoryTutorialExamples/

Electromagnetics/

TimeHarmonic/

ResonanceMode/

RectangularResonator/

relative to JCMwave’s home directory. Use JCMgeo to triangulate the layoutand JCMsolve to compute the project.

Results First we start the project projectFundamental.jcmp. The com-putation starts with an initial triangulation (refinement level 0 ...).The grid is refined four times during the computation leading to a moreaccurate solution. During the computation each triangle of the initial trian-gulation is subdivided into four smaller ones in each refinement step.

1This tutorial example contains several project definition files:projectFundamental.jcmp, projectNearGuess.jcmp. To switch between these projectfiles within JCMcontrol, please click with the right mouse button on the respectiveproject file name and select Set as active project file . . . . The icons next to the projectfiles indicate which one is active.

Page 89: Tutorial

8.2. RECTANGULAR RESONATOR 89

ω [1014s−1] analytical numerical

1 0.941825784 0.9418257982 1.34546541 1.345465373 1.64234983 1.642349964 1.88365156 1.883652045 2.31482621 2.314827686 2.69093081 2.690929817 2.82547735 2.825480928 2.85099008 2.85098992

Table 8.1: Eigenfrequencies ω of rectangular resonator. Comparison of analytical andnumerical solution for the first 8 eigenmodes.

When the simulation is finished the directory projectFundamental results

is created which contains the files eigenvalues.jcm, fieldbag.jcm, andcomputational costs.jcm. These files contain the computed eigenvalues,the electric field strengths of the corresponding eigenmodes, and the compu-tational costs on the different levels of computation (for differently refinedmeshes) respectively. Double-click on the file names in the project explorerof JCMcontrol in order to watch the contents of these files.

Since this simple example can be solved analytically we can quantify theconvergence of the numerical simulation. The exact eigenmodes (frequencies)to that problem are given by:

ωeff,m,n =

c2

ǫrµr

π2

(

n2

a2+

m2

b2

)

with m ≥ 0, n ≥ 0 and m + n ≥ 1 and speed of light c. This formula yieldsthe analytical values for the first eight eigenfrequencies shown in table 8.1.

The numerical values for ω are also shown in table 8.1.

Discussion We observe that the computed finite element solution is invery good agreement with the exact fundamental eigenvalues. Let us havea closer look at the output that is produced during computation. Execu-tion of projectFundamental.jcmp produces a convergence table for eacheigenmode, e.g., for the 1. eigenmode:

*** Solving "projectFundamental.jcmp"

Page 90: Tutorial

90 CHAPTER 8. RESONANCE MODES

- refinement level 4 ...

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 finite element grid is refined uniformly. One expects that the computeddiscrete solution converges to the true value. Each row in the tables cor-responds to one grid level. To check convergence one monitors the relativedeviation of the eigenvalues corresponding to two successive grid levels. Thisis given in column delta. To assure convergence this relative deviation mustdecrease with a fixed rate ratio. For this examples one expects theoreticallyan asymptotic ratio equal to 16.0. As can be seen this asymptotic rate isindeed reached (column ”ratio”).

Now we want to search for higher eigenmodes and execute projectprojectNearGuess.jcmp. The solver computes eigenmodes close to and be-low an initial guess (here: Guess = 6e14). This project uses a differentrefinement strategy. The initial grid is refined once before the computationof eigenmodes starts. This is specified with the parameter PreRefinements= 1. Furthermore an adaptive refinement strategy (Adaptivity = yes) isused. Thereby the error of the computed solution on each triangle is esti-mated prior to each refinement step and only triangles with a large estimatederror (≈ one half of the triangles) are refined. This usually leads to fasterconvergence of the solution and reduced computation time. Executing theproject, 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

Page 91: Tutorial

8.2. RECTANGULAR RESONATOR 91

2 608 00:00:00.07 1.15e-04 00:00:00

3 2496 00:00:00.33 1.32e-04 00:00:00

4 10112 00:00:01.36 1.34e-04 00:00:02

Note that the computation time per unknown (cpu/unknowns) is nearly con-stant due to JCMsolve’s use of efficient solvers.

Quick own modifications Now we can modify our problem. The basicsimulation parameters are specified in projectFundamental.jcmp,projectNearGuess.jcmp respectively:

• NumberEigenvalues = 8 specifies the number of eigenvalues that arecomputed. For projectFundamental.jcmp these are always the lowestones. LowerBoundGuess should here be set to some reasonable valuefor faster convergence of the computation. In projectNearGuess.jcmp

the SelectionCriterion is changed from Fundamental to NearGuess.The value set for Guess specifies the upper boundary where the solverstarts to search for eigenvalues. If the initial guess is chosen too small(smaller than one half of the frequency of the first fundamental eigen-mode) the solver finds unwanted eigenvalues. They are many orders ofmagnitude smaller (ω ≈ 0) then the first fundamental mode and belongto gradient fields which are solutions of the static Maxwell’s equations(ω = 0).

• Beside these physical model parameters we can control the accuracy ofour computation. If the eigenvalue is determined with an error smallerthan the value PrecisionEigenvalues the calculation is stopped.MaxNumberSteps gives an upper bound for the number of refinementsteps of the grid that are performed during the computation. Adaptivityspecifies if the grid is refined adaptivly or regularly. Thereby Adaptivity

= yes is recommended in the most cases since adaptiv refinement usu-ally decreases the cpu time and leads to more accurate results. Whenusing adaptivity the grid is refined only in regions with a large esti-mated error whereas without adaptivity the grid is refined uniformly.

Try PrecisionEigenvalues = 1e-10 and increase MaxNumberSteps =

5 to get a more accurate result. Furthermore you can compare com-putations with Adaptivity = yes / no. Since we know the analyticalvalues for the eigenvalues you can set Guess in projectNearGuess.jcmp

close to a higher eigenvalue and search for it.

Page 92: Tutorial

92 CHAPTER 8. RESONANCE MODES

The geometry of the fiber is described in layout.jcm:

• You can change, e.g., the Points of the Polygon defining the resonatorlayout and compare analytical and numerical results

The relative permeability and permittivity of the rectangular domain arespecified in materials.jcm. Observe how the eigenvalues change with therefractive index (square root of the permittivity) of the material by editingthis input data.

Page 93: Tutorial

8.3. CYLINDRICAL RESONATOR 93

8.3 Cylindrical Resonator

Learning Targets

• cylindrically symmetric resonance problem

Project Description We compute four modes of an air-filled cylindricalresonator with height h = 1 m and radius r = 1 m as shown in Figure 8.1. Atthe outer boundary we impose perfectly electric boundary conditions. Thismeans that the electric field is normal to the boundary. The project.jcmp

uses an initial Guess and computes a specified number of eigenvalues closeto that guess.

h

r

Figure 8.1: Cylindrical resonator with height h and radius r.

The project files to this problem are located in the directoryTutorialExamples/

Electromagnetics/

TimeHarmonic/

ResonanceMode/

Cylinder/

relative to JCMwave’s home directory. Use JCMgeo to triangulate the layoutand JCMsolve to compute the project.

Page 94: Tutorial

94 CHAPTER 8. RESONANCE MODES

ω [109s−1] analytical numerical

1 0.720948615 0.72094856502 1.18608776 1.18608711323 1.48549430 1.48545801754 1.65487818 1.6548777850

Table 8.2: Eigenfrequencies ω of a cylindrical resonator. Comparison of analytical andnumerical solutions for the first four eigenmodes.

Results Since our geometry is cylindrically symmetric the electric andmagnetic fields have the dependency eimϕ (m ∈ N) on the polar angle ϕ.Our project computes the first four eigenvalues for m = 0 according to ourspecification NPhi = 0 in the project file. Later we will also choose highervalues. This problem can also be solved analytically. You find a matlabscript check.m which computes the first 20 eigenmodes for m = 0, 1.

We compare the numerical and analytical solutions in table 8.2.

Discussion We see that the computed finite element solution is in verygood agreement with the exact eigenvalues.

Creating the layout for a cylindrically symmetric problem one only hasto describe one slice of the geomtry, i.e., a two dimensional domain withthe y-symmetry axis on a boundary. For this project the computationaldomain is simply a rectangle with sidelengths h = 1 m and r = 1 m. Wehave to take care that the symmetry axis is located at the global positionx = 0 of our layout, (see also section 3.2.3). All boundaries of the geom-etry that lie on the symmetry axis have to be specified as Cylindrical inboundary conditions.jcm.

Quick own modifications Set NPhi = 1 in project.jcmp and comparewith the analytical solution obtained from matlab script exact.m.

Page 95: Tutorial

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 field density

Project Description The resonance mode solver also allows for the bandgap computation of a photonic crystal or any other device with a periodicarrangement. To analyze such a device one computes so called Bloch-modeswhose corresponding electromagnetic fields exhibit a certain phase jumpwhen spatially shiftet by a lattice vector. From the numerical point of viewthis makes it possible to restrict the eigenmode computation onto a singleunit cell of the lattice.

rp

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 withcolumns of air wholes in a dielectric substrate, see Figure 8.2. The radius of

Page 96: Tutorial

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 specificfrequencies is able to propagate in the different directions within the photoniccrystal. For a complete band diagram one has to determine eigenfrequenciesfor all values of the Bloch vector k within the first Brillouin zone. As an ex-ample we will solve the eigenvalue problem at the M point of the reciprocallattice.

For the electric and magnetic field polarized perpendicular to the compu-tational domain we get independent eigenvalue problems, called transversalelectric (TE) modes and transversal magnetic (TM) modes respectively. Inthe TE (TM) case the magnetic (electric) field is polarized parallel to thecomputational domain.

Therefore we have two possibilities to compute the eigenvalues for the TEand TM problem respectively. In the TE case we can either solve the scalarproblem for the z-component of the electric field (project TE scalar) orthe vectorial problem for the x-y-components of the magnetic field(project TE vectorial). The eigenvalues should agree. Analogously forthe TM problem we have two projects project TE scalar andproject TE vectorial. The project files to this problem are located in thedirectoryTutorialExamples/

Electromagnetics/

TimeHarmonic/

ResonanceMode/

HexagonalPhC/

relative to JCMwave’s home directory. Use JCMgeo to triangulate the layoutand JCMsolve to compute the project.

Results Fixing the Bloch vector at the M point (specified via BlochKX andBlochKY in the project file) of the Brillouin zone we get several eigenvaluesfor ω. As expected the TE (TM) eigenvalues agree when computed with thescalar and vectorial projects.

Discussion It is sufficient to compute the field distributions on one unitcell of the periodic geometry when periodic boundary conditions are applied.When specifying BlochKX, BlochKY in the project file only solutions whichare Bloch-periodic according to this vector are computed. Bloch-periodic

Page 97: Tutorial

8.4. HEXAGONAL PHOTONIC CRYSTAL 97

1) 2)

3) 4)

Figure 8.3: Hexagonal photonic crystal: Electric energy density plots of the first fourTE modes.

fields are defined as follows:

E(x + p, y) = eikxpE(x, y)E(x, y + p) = eikypE(x, y),

where k = (kx, ky) is the given Bloch vector.In the post-processes of project TE scalar we compute the electric en-

ergy density in the computational domain. Figure 8.3 shows the first foreigenmodes for the TE case. We observe that the electric field is mainlylocated in the dielectric material.

Quick own modifications Change the Bloch vector to compute othereigenvalues, e.g., BlochKX=0, BlochKY=0 for the Γ point. The layout of thephotonic crystal is specified in layout.jcm. Change the Radius of Circlewith Name = ‘‘Hole’’.

Page 98: Tutorial

98 CHAPTER 8. RESONANCE MODES

Page 99: Tutorial

Chapter 9

Embedded Scripting

9.1 Embedded Scripting Description

All of JCMwave input files support embedded scripting. With embeddedscripting, the power and diversity of an entire scripting language is placed atyour disposal within JCMwave’s input files. Embedded scripting support isvery 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 tagand ended by a ?> tag.

For example Matlab script sections contained within a JCMwave inputfile must be contained in matching <?Matlab ... ?> tags1. As of JCMsuite1.10 it is even possible to start a for-loop in one script section and end itin another. All JCM-code within the loop will then automatically be injectedinto the resulting .jcm-file for each cycle of the loop2. Thus the use ofjcmwave echo in Matlab-scripted input files to transfer output into the .jcm

1For an overview on the different types of embedded scripts and their syntax plese referto table 9.1 at the end of this section.

2This feature is currently not supported in Pyhton. In Python each script block mustcontain a fully functional script.

99

Page 100: Tutorial

100 CHAPTER 9. EMBEDDED SCRIPTING

file is obsolete, making your scripts smaller and more readable, though yourold scripts will of course continue to work.

To mark the input file as a template file, the letter “t” must be appendedto its suffix.

The scripts as well as the unscripted parts of the JCMwave input file maycontain variables that will be passed from the outside. A variable passedfrom the outside is marked by an identifyer name contained in brackets witha leading % sign and a tailing type identifier. Valid type identifiers are

• i for integer variables (also valid for integer arrays),

• f for float variables (also valid for float arrays),

• s for string variables and

• e for real and complex double variables (also valid for complex doublearrays)

As of version 1.11 the structures holding the variables in Matlab havebecome dynamic, thus enabling you to overwrite variables within your jcm

input files.The new features make Matlab-scripting much easier and more conve-

nient. For example to script a horizontal line of circular holes in a materialnow 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

Page 101: Tutorial

9.1. EMBEDDED SCRIPTING DESCRIPTION 101

}

<?Matlab end; ?>

...

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 foreach execution of the for-loop.

As another example, if you prefer to use λ0 instead of ω the followingsimple 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 final .jcm file, e.g. if you pass 15.0 as lambda0 this will result in theline

...

Omega = 0.418879020479

...

The transformation process from .jcmt template files containing scriptblocks into .jcm files ready for use can be seen in figure 9.1. For eachsupported scripting language a tool called RunEmbeddedScripts is avail-able in the corresponding ThirdPartySupport-subdirectory of JCMwave’shome directory. These scripts will then transform your template-file into atemporary standalone file for its own language. For example invoking thePython variant of RunEmbeddedScript will create a .jcm.py file and run-ning the Matlab-version of RunEbeddedScripts will generate a jcmtmp.m

file. These files will then be processed by the script language interpreterto create your final .jcm-files. If errors should occur during the creation orexecution of these temporary files, by default the Matlab implementationjcmwave runembeddedscripts will provide debugging information such aslocation of the erroneous code in the original .jcmt file and matlabs error

Page 102: Tutorial

102 CHAPTER 9. EMBEDDED SCRIPTING

message3. To disable error handling for your Matlab scripts, you can simplypass two extra string arguments to jcmwave runembeddedscripts contain-ing the strings debug´ and off´.

To pass the variables to your scripts, in Python a dictionary containingvariableIdentifier = variableValue entries is used, in Matlab a struc-ture containing the corresponding pairs is utilized.

.jcmt file standalone script file .jcm file

RunEmbeddedScripts

JCM-code

JCM-code

<?userscript?>

generatedcode JCM code

invoke script interpreter

Figure 9.1: Transformation process for a JCMwave input file containing scriptcode

Matlab Python

Script start tag <?Matlab <?Py

Script end tag ?> ?>

File output command jcmwave echo(string) JCMecho(string)

External variables structure dictionarypassed inFile to invoke RunEmbeddedScripts.py jcmwave runembeddedscripts.m

for processing .jcmt

Table 9.1: Overview on the syntax for the currently supported types of script-ing

Examples using template files containing scripts in the Matlab and Python

programming languages will be shown and explained in the following sections.

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

Page 103: Tutorial

9.2. EMBEDDED SCRIPTING: MATLAB 103

9.2 Embedded Scripting: Matlab

9.2.1 Tutorial project: Refraction at an interface

Learning Targets

• embedded scripting with Matlab

• finite element parameters

• wave propagation error

• Wood’s anomaly

Project Description In this tutorial project we investigate numericallyhow the electric field behaves at a plane interface of two dielectrics. Theorytells us that an incident plane wave Ein is partially reflected and transmit-ted. The reflection coefficient R and transmission coefficient T quantify theamplitude of the reflected Er and transmitted light E2 normalized with theamplitude of the incident plane wave. For TE-polarization they are given byFresnel’s formulas:

TTE =E2

Ein=

2n1 cos θin

n1 cos θin +√

n22 − n2

1 sin2 θin

,

RTE =Er

Ein=

n1 cos θin −√

n22 − n2

1 sin2 θin

n1 cos θin +√

n22 − n2

1 sin2 θin

, (9.1)

where n1 and n2 are the refractive indices of the two materials and θin theincidence angle, shown in Fig. 9.2. For TM polarization the correspondingexpressions are:

TTM =2n1n2 cos θin

n22 cos θin + n1

n22 − n2

1 sin2 θin

RTM =n2

2 cos θin − n1

n22 − n2

1 sin2 θin

n22 cos θin + n1

n22 − n2

1 sin2 θin

. (9.2)

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

Page 104: Tutorial

104 CHAPTER 9. EMBEDDED SCRIPTING

θin

Ein

E2

Er

n1

n2

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

The project files to this problem are located in directoryTutorialExamples/

Electromagnetics/

TimeHarmonic/

Scattering/

Planar/

Refraction/

After computation of the project the numerical results for T and R will bedetermined and compared to the analytical solutions (9.1) and (9.2) respec-tively. We artificially periodify the computational domain in one dimensionto simulate an infinitely extended interface. In the other dimension we usetransparent boundary conditions, see Fig 9.3. In order to compute the com-plex amplitude of the reflected and transmitted light the PropagatingFourierModespost process is used. Since the computational domain is unstructered onlythe zeroth diffraction orders will be non-zero and give us the amplitudes ofthe transmitted and reflected electric field. In this example the material filedepends on the refractive indices n1, n2 and the source file on the incidentangle θin the wavelength λ and the polarization of the incident electric field.

Page 105: Tutorial

9.2. EMBEDDED SCRIPTING: MATLAB 105

transparent boundary

per

iodic

bou

ndar

y

Figure 9.3: Computational domain for refraction of a plane wave at an interface. Thedomain is artificially periodified in one dimension to simulate the infinite exterior.

The wavelength λ is also used to scale the size of the computational domain.Since the computational domain is unstructered we could take an arbitrarilysmall section of the interface, see Fig. 9.3. For visualization and inspectionof the convergence however it will extend a few wavelengths here. Further-more we want to make numerical parameters in the JCMsolve control fileproject.jcm accessible from the Matlabcontrol file. The files layout.jcm,materials.jcm, layout.jcm, and project.jcmp will therefore be createdwith embedded scripting.

Results Let us first have a look at the Matlab control file run.m. Thestruct keys contains all parameters which are needed to define the projectand create the input files for JCMsolve. If this struct is not given as aninput parameter to run.m default parameters are set. The struct keys isthen passed via the command jcmwave runembeddedscripts to the .jcmt

template files. After the four input files have been created the geometry is tri-angulated with the command jcmwave geo(’.’) and then the finite elementsimulation started with jcmwave solve(’--solve’, ’project.jcmp’). Ina post process the propagating fourier modes are computed which are loadinto the Matlab control file with the jcmwave loadtable command. In therest of the run.m control file the JCMsolve results are compared to the ana-lytical values of T and R and the field is visualized.

In order to start the project first you have to add the third party Matlabpath via

Page 106: Tutorial

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 field distribution which is shown corresponds to the case of totalreflection at the interface (Wood’s anomaly) which will be explained later.

Now let us have a look at the template files. We start with the filelayout.jcm which just uses the wavelength λ to scale the size of the com-putational domain. This is done in line 7:

UnitOfLength = %(lambda)e

The name lambda in brackets refers directly to the entry keys.lambda ofthe struct keys which was passed to the template file. The % sign indicatesthat a parameter passed from the outside follows and the identifier e af-ter the brackets specifies that the value for lambda is interpreted as a real(or complex) double. Other indentifiers are i for integer values and s forstring values. When the template file layout.jcmt is converted with thejcmwave runembeddedscripts command then %(lambda)e is replaced withthe corresponding value for the parameter. You can check this by openingthe created layout.jcm file.

Next let us have a look at the materials.jcmt template file. Here wefind a Matlab block. It is opened with

<?Matlab

and has to be closed with

?>

Within this block all Matlab commands are available. Since JCMsolve usesthe relative permittivity and permeability as material parameters and notthe refractive index the input parameters n1 and n2 are transformed intopermittivites by taking the square (we assume that the relative permeabilitiesare unity). These values are assigned back to the struct keys.epsilon1 andkeys.epsilon2 and then used in the material definitions, e.g.

RelPermittivity = %(epsilon1)e

Page 107: Tutorial

9.2. EMBEDDED SCRIPTING: MATLAB 107

In the template file sources.jcmt the wavelength, incidence angle, andpolarization state are converted into values for the k-vector and field strengthof the incident plane wave in Cartesian coordinates. Within the first Matlabblock the absolute value of the k-vector and then its x- and y-component arecomputed 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 field strength depends on the polarization state which is specified bykeys.polarization = ’TE’ or keys.polarization = ’TM’. We find an if

... elseif ... else statement where the polarization state is queried. TheJCMsuite syntax is located between the corresponding Matlab blocks andonly written into the file sources.jcm is the corresponding polarization stateis specified

<?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

?>

Page 108: Tutorial

108 CHAPTER 9. EMBEDDED SCRIPTING

In the case of TM polarization the field strength vector has to be orientedperpendicular to the k-vector. For TE polarization we set the z-componentof the field strength to 1. If the polarization state is neither ’TE’ nor ’TM’

an error message is displayed.Finally we look at the template file 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 identifier i, e.g.

FiniteElementDegree = %(femDegree)i

The value for Adaptivity is either yes or no, i.e. a stringwith identifier 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 Matlabfile angleScan.m the transmittivity T and reflectivity R are computed independence on the incidence angle. Furthermore the relative error to theanalytical solution is given. We notice a sharp drop in the transmittivity Taround 42◦, which is close to the angle of total reflection:

θ0 = arcsinn2

n1

(9.3)

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

Page 109: Tutorial

9.2. EMBEDDED SCRIPTING: MATLAB 109

the superposition of the incident and reflected field. At the angle of totalreflection the reflectivity is 1 which means that incident and reflected fieldhave the same amplitude. Because of this we find a very regular pattern ofconstructive and destructive interference. Above the line y = 0 (domain 2)the electric field is constant in y direction. This behaviour of the electricfield is refered to as Wood’s anomaly and often causes problems for trans-parent boundary conditions. JCMsolve’s self adaptive transparent boundaryconditions however have no problem dealing with this case:

*** A Posteriori exterior domain quality check: saturation reached.

informs that a close Wood’s anomaly was detected and properly treated. Youcan now conveniently set different values for the refractive indices, incidenceangle, polarization state and numerical parameters in run.m look at the com-puted finite element solution and check the relative error to the analyticalvalues for the transmission T and reflectivity R.

Page 110: Tutorial

110 CHAPTER 9. EMBEDDED SCRIPTING

9.2.2 Photonic Crystal

The following example will show how to create the geometry for a hexagonal2D 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 codeembedded in an JCMwave layout-file. It is intended to give you an idea ofthe power as well as the syntax of embedded scripting.

Creating the geometry of a hexagonal photonic crystal with NRows rowsand Ncols columns manually would require you to input the data of all⌈NRows/2⌉NCols + ⌊NRows/2⌋(NCols − 1) holes in this crystal.

By utilizing the loop functions in matlab, you can input only one circleand copy it to the desired positions. To do this, first we define a helperfunction Circle in a file called Circle.m which we will later use from ourembedded script. Given the coordinates of the center, the radius and therow and column indices (for naming the circle), this function returns theJCMwave data for the corresponding circle as a string. This is what Circle.mlooks 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 layoutfiles, please refer to the JCMwave paramer reference. Next we will write a.jcmt layout file that will call this matlab function with the proper param-eters and print the string it returns into the .jcm file. This file should becalled layout.jcmt and contain the two following main blocks of code.

In the first code block, the computational domain is created as a polygon:

Polygon {

Name = "Computational Domain"

MaterialId = 1

Priority = -1

Page 111: Tutorial

9.2. EMBEDDED SCRIPTING: MATLAB 111

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

}

The embedded Matlab code block is divided into two main parts: first thevariables passed are initialized into internal Matlab variables. This step isnot necessary but it makes the following Matlab code more readable. Thevariables only have to be instanciated once. After that they will also beavailable in later script blocks. As can be seen in the second half of theembedded script, Matlab here is utilized to calculate the width and height ofthe computational domain optimally for a hexagonal photonic crystal withNCols columns and NRows rows of holes with a radius of HoleRadius and ahole spacing of SpaceWidth. All these parameters will be passed from theoutside 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 wewill use the function Circle which we defined earlier in this section. Thecode 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); ?>

Page 112: Tutorial

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 first loop iterates the rows. Next comes a if clause to determine if weare in an odd or in an even row. Then in the inner for loop that iterates thecolumns, the coordinates for the centers of the holes are calculated accord-ingly 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 file via the jcmwave echo command.

Putting this together in a .jcmt file, all we will further require is a Matlab

script that sets all the parameters and invokes the transformation to a .jcm

file. All this script has to contain are the following lines for setting theparameters of the photonic crystal:

keys.HoleRadius = 2;

keys.SpaceWidth = 7;

keys.NRows = 3;

keys.NCols = 3;

keys.Offset = 1;

Page 113: Tutorial

9.2. EMBEDDED SCRIPTING: MATLAB 113

and the following two lines for invoking the transformation process:

addpath ’/path/to/your/jcmroot/ThirdPartySupport/matlab/’

jcmwave_runembeddedscripts(’layout.jcmt’, keys);

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

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

Page 114: Tutorial

114 CHAPTER 9. EMBEDDED SCRIPTING

Page 115: Tutorial

Chapter 10

Using JCMsuite from Python

The finite element solver JCMsolve comes with a Python programming in-terface which makes it possible to use the solver from Python. The mainobjective of the programming interface is to provide you with a comfortableaccess to the output data produced by JCMsolve. This way you need notknow much about the finite element method to implement a further postprocess in Python based on the computed field data or to use the computedelectromagnetic fields as input data to your own simulation. For the creationof complex input files with Python we refer to the Chapter 9.1.

10.1 Initialization

You can find the required libraries of the Python interface in the subdirectoryThirdPartySupport/Python/JCMsuite of your JCMsuite installation. De-pending on the platform (Linux, Windows) we support different versions ofPython. On Windows we currently support the version 2.4 of the Pythoninterpreter whereas on Linux we support the version 2.3. If your installedPython version does not match these requirements you may recompile thelibrary on your own machine. The required C file jcmwavemodule.c is placedin the directory ThirdPartySupport/Python/JCMsuite. Please do no hesi-tate to contact the JCMwave support team if you have any problems whencreating the library.

After adding the path ThirdPartySupport/Python/JCMsuite to the en-vironment variable PYTHONPATH the Python modules are imported via:

115

Page 116: Tutorial

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 thecommand

help(jcmwave).

10.2 Main Method Call

The method

jcmwave.solve("project.jcmp");

starts the FEM solver on the project specified in the file project.jcmp. Itcorresponds to the command line call JCMsolve --solve project.jcmp. Toonly 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-files on thefile system. For examples the computed electromagnetic fields are storedin .jcm-files in the “fieldbag” format. Fourier coefficients and other postprocess values are typically stored in the “Table” format. To access the datathe Python library provides you with a procedural interface. In a first stepthe data stored in a .jcm-file 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 stringparameter fileName is the name of the .jcm-file to be loaded. The methodreturns a handle to the loaded data which is used for a further reference tothe 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.

Page 117: Tutorial

10.4. TABLE ACCESS METHODS 117

10.4 Table Access Methods

Many JCMsolve output files are in the “Table” format. Once the table isloaded to the pinboard, a handle is obtained to refer to the table data oneuses inteface methods to access the table data. The table title, the numberof columns, the column’s names and the columns’s types can be retrieved byinvoking 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 retrievethe 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 fields are stored in .jcm-output files in the field-bag format. In such a file a collection of fields of the same type is stored. Forexample in an eigenmode computation a certain number of modes is com-puted, so that the field output contains multiple fields. Efficiently accessing afinite element field requires some knowledge on how the fields are representedin the finite element method.

Page 118: Tutorial

118 CHAPTER 10. USING JCMSUITE FROM PYTHON

As described in many examples of this tutorial the geometry is representedby a mesh consisting of triangles in 2D and tetrahedrons in 3D. In laterversions of JCMsolve the mesh may further contains quadrilaterals in 2D andprism, bricks and pyramides in 3D. In the following we call these geometricalpatches commonly “cells”.

Mesh Access Methods

The whole topology of the mesh can be recovered using a few methods. Werefer to help(jcmwave) for more details. Here we only scetch the principlesof the mesh description. A mesh does not only consist of cells but alsocontains sub-patches like points or edges in 2D and additionally trianglesand 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 fieldbag 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 callingthe method

tuple = jcmwave.fieldbag_pointcoordinates( \

integer handle, integer ipoint)

The edges of the mesh are characterized by the point indices of their firstand 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 coordinatesinto the real physical space with “real” coordinates. This mapping can beevaluated by the method

tuple = jcmwave.fieldbag_realcoordinatesoncell( \

integer handle, integer indexCell, tuple<real> unitCoordinates)

The inverse mapping called fieldbag unitcoordinatesoncell is also avail-able. Besides the geometry of the mesh it is also important to know whichmaterials are present on a certain cell. In a JCMsolve project this is done bymaterial indices. Each domain or material carries a material index so that

Page 119: Tutorial

10.5. FIELDBAG ACCESS METHODS 119

one can specifiy material properties such as permittivity tensor or permeabil-ity tensors in the file material.jcm. The material id of a cell is returned bythe method fieldbag celldomainid. There exists also a fast search methodfieldbag findcell which tries to find a cell containing a given point.

Field Access Method

The restriction of the fields to a cell is polynomial function in each of thefield components. To get the maximum polynomial degree of the field on thelocal patches one evokes the method

integer = jcmwave.fieldbag_maxdegree(integer handle)

The number of components of the field is returned by fieldbag ncomponents.To evaluate the field 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 thefield within the fieldbag. As an example with following piece of code one getsthe field values at a the point [0.0, 0.0] for a 2D field.

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);

Page 120: Tutorial

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 field export to cartesian grids and extrac-tion of isolines are available.

Page 121: Tutorial

Chapter 11

Using JCMsuite from Matlab

The finite element solver JCMsolve comes with a Matlab programming in-terface which make it possible to use the solver from within Matlab. Themain objective of the programming interface is to provide you with a com-fortable access to the output data produced by JCMsolve. This way youneed not know much about the finite element method to implement a fur-ther post process based on the computed field data or to use the computedelectromagnetic fields as input data to further simulations in Matlab. Forthe creation of complex input files with Matlab we refer to the Chapter 9.1.

11.1 Initialization

You can find the .m-files of the Matlab interface in the subdirectoryThirdPartySupport/matlab of your JCMsuite installation. This path hasto be added via:

addpath your_installation_directory/ThirdPartySupport/matlab/

To get information about a method (e.g. jcmwave loadamirafields) imple-mented in the interface use

help jcmwave_loadamirafields

11.2 Main Method Call

To start JCMsolve from Matlab simply use the system call

121

Page 122: Tutorial

122 CHAPTER 11. USING JCMSUITE FROM MATLAB

system(sprintf(’JCMsolve --solve ./project.jcmp’))

This starts the solver on the project specified in the file project.jcmp. Toonly compute the post-processes of project.jcmp use

system(sprintf(’JCMsolve --postprocess ./project.jcmp’)).

11.3 Table Access Methods

Many JCMsolve output files are in the “Table” format. To load a table fromthe file fileName use

table = jcmwave_loadtable(fileName);

This method returns a Matlab structure. Now the table title, the numberof columns, the column’s names and the columns’s types (e.g. of the firstcolumn) 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 fields are stored in .jcm-output files in the field-bag format. In such a file a collection of fields of the same type is stored. Forexample in an eigenmode computation a certain number of modes is com-puted, so that the field output contains multiple fields. There exists no loadmethod in Matlab for jcm fieldbag files by now. The field must be convertedin a postprocess step into the AMIRA format before accessing the electro-magnetic field from Matlab. Since AMIRA does not support higher order

Page 123: Tutorial

11.4. FIELDBAG ACCESS METHODS 123

finite elements the computed fields are linearly interpolated on a finer grid.This results in an further interpolation error. If accuracy is critical in yourMatlab computation this should be kept in mind.

To load a AMIRA field the command use the command

fieldbag = jcmwave_loadamirafields(fileName).

The imported AMIRA fields may be defined on a cartesian or on a simplexgrid. A 2D simplex grid consists of triangles whereas a 3D simplex gridconsists of tetrahedrons. The return value fieldbag is a Matlab structurewith the entries fieldbag.grid and fieldbag.field. In fieldbag.grid

the grid is stored whereas in fieldbag.field the collection of fields “living”on that grid is stored.

Mesh Access Methods

The entry fieldbag.grid.type specifies the mesh type (cartesian or sim-plex). Here we only detail the case of a simplex grid in 2D. For a descriptionof 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 meshare stored in the Nt by 3 array fieldbag.grid.simplices where Nt is thenumber of triangles in the mesh. The indices of the three triangle points ofthe 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(:))

Page 124: Tutorial

124 CHAPTER 11. USING JCMSUITE FROM MATLAB

Besides the geometry of the mesh it is also important to know which materialsare present on a certain simplex. In a JCMsolve project this is done bymaterial indices. Each domain or material carries a material index so that onecan specifiy material properties such as permittivity tensor or permeabilitytensors in the file material.jcm. The material id of our simplex 100 of thegrid is returned by

simplexMaterialId = fieldbag.grid.materials(100)

Field Access Method

The electromagnetic fields are also stored in the Matlab structure fieldbag

of the previous chapter. A single fieldbag (.am-)file can contain several elec-tromagnetic fields, e.g., several different eigenmodes. To access type, polar-ization, or number of components of the field with index i one calls:

fieldbag.field{i}.type

fieldbag.field{i}.polarization

fieldbag.field{i}.ncomponents

E.g. a z-polarized electric field strength tensor field has one component. Thematrix fieldbag.field{j}.data contains the field values of field j. It is amatrix of size (np, ncomp) where np is the number of grid points and ncompis the number of components of the field. To be more precies the columnfieldbag.field{j}.data(:, k) holds the values of the k’th component ofthe j’th field on the grid points.Matlab offers the method trisurf to plot a scalar field given in simplexformat. First we store the simplices t, the x and y coordinates of their nodesand the electromagnetic field in different variables:

t = fieldbag.grid.simplices;

x = fieldbag.grid.p(:, 1);

y = fieldbag.grid.p(:, 2);

v = fieldbag.field{1}.data;

The following command creates a plot of the imaginary part of the z-componentof the field:

trisurf(t, x, y, imag(fieldbag.field{1}.data(:,3)));

Page 125: Tutorial

Chapter 12

C Programming Interface

The finite element solver JCMsolve comes with a C programming interfacewhich make it possible to use the solver from your own application. Themain objective of the programming interface is to provide you with a com-fortable access to the output data produced by JCMsolve. This way youneed not know much about the finite element method to implement a fur-ther post process based on the computed field data or to use the computedelectromagnetic fields as input data to your own simulation.

Taking a look on your JCMsuite installation you will find a dynamicallyloadable 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 yourprogramme. The corresponding header file jcm fetools.h is placed in thesubdirectory include. All accessible methods from the jcm fetools libraryare listed in the header file. Apart from a few exceptions all methods are ofthe form

int DLLIMPORT JCMMethod(TYPE* outputValue1, ...,

TYPE* outputValueN,

TYPE* inputValue1, ...,

TYPE inputValueM).

Each method returns an error code. A return value unequal zero signalizes afailure of the method. Input and output values are provided by pointers toprimitive C types. TYPE is of the C type char, int, double or doublecomplexor a pointer by itself.

125

Page 126: Tutorial

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 methodinvokes the license manager to reserve a license. The two arguments stdout

and stderr are used to redirect the standard output and the standard erroroutput respectively. The finalization 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 specifiesthe number of arguments passed to the main method and argv is an arrayof string pointers. For example the function call

char* argv[] = {"JCMsolve",

"--solve",

"./project.jcmp"};

JCMMain(3, argv);

starts the solver on the project specified in the file project.jcmp. As for aC main method the first string argument is always the programme name.

12.3 The Pinboard

A run of the solver typically produces output data stored in several .jcm-files on the file system. For examples the computed electromagnetic fields arestored in .jcm-files in the “fieldbag” format. Fourier coefficients and otherpost process values are typically stored in the “Table” format. To access the

Page 127: Tutorial

12.4. TABLE ACCESS METHODS 127

data the jcm fetools library provides you with a procedural interface. Ina first step the data stored in a .jcm-file is loaded to the pinboard by themethod call

int DLLIMPORT JCMGetHandle(int* handle, const char* fileName).

The pinboard can be considered as the workspace of jcm-data. The stringparameter fileName is the filename of the .jcm-file to be loaded. The methodreturns a handle to the loaded data which is used for a further reference tothe 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 releasedhandle will cause a segmentation fault. Further auxiliary methods referingto the pinboard are documented in the header file jcm fetools.h.

12.4 Table Access Methods

Many JCMsolve output files are in the “Table” format. Once the table isloaded to the pinboard and a handle is obtained to refer to the table data oneuses inteface methods to access the table data. So the table title, the numberof columns, the column’s names and the columns’s types are retrieved. Werefer to the include header file jcm fetools.h for a documentation. To accessan entry in a certain column the type of the column must be known. Forexample 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 inputparameter 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 ofthe wanted entry. To retrieve the whole column of the table one uses themethod

Page 128: Tutorial

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 minimumlength of the number of rows. As an example doublecomplex table columncan 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 fields are stored in .jcm-output files in the field-bag format. In such a file a collection of fields of the same type is stored. Forexample in an eigenmode computation a certain number of modes is com-puted, so that the field output contains multiple fields. Efficiently accessing a

Page 129: Tutorial

12.5. FIELDBAG ACCESS METHODS 129

finite element field requires some knowledge on how the fields are representedin the finite element method.

As described in many examples of this tutorial the geometry is representedby a mesh consisting of triangles in 2D and tetrahedrons in 3D. In a laterversion of JCMsolve the mesh may further contains quadrilaterals in 2D andprisms, bricks and pyramides in 3D. In the following we call these geometricalpatches commonly “cells”.

Mesh Access Methods

The whole topology of the mesh can be recovered using a few methods. Werefer to the header file jcm fetools.h for more details. Here we will onlysketch the principles of the mesh description. A mesh does not only consistsof cells but also contains sub-patches like points, edges in 2D and additionallytriangles and quadrilaterals in 3D. To get the number of points one calls themethod

int DLLIMPORT JCMFieldBagNPoints(int* nPoints, int handle).

Here handle must be a valid handle to a fieldbag loaded to the pinboard.Each point has a unique index. As usual in C indexing starts from ”0”. Thereal 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 spacedimension. The edges of the mesh are characterized by the point indices oftheir first 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 coordi-nates into the real physical space with “real” coordinates. This mapping canbe evaluated by the method

int DLLIMPORT JCMFieldBagRealCoordinatesOnCell(

double** realcoordinates, int handle,

int indexCell,

const double* unitcoordinates).

Page 130: Tutorial

130 CHAPTER 12. C PROGRAMMING INTERFACE

The inverse mapping called JCMFieldBagUnitCoordinatesOnCell is alsoavailable. Besides the geometry of the mesh it is also important to knowwhich materials are present on a certain cell. In a JCMsolve project this isdone by material indices. Each domain or material carries a material indexso that one can specifiy material properties such as permittivity tensor orpermeability tensors in the file material.jcm. The material id of a cell isreturned by the method JCMFieldBagGetCellDomainId. There exists also afast search method JCMFieldBagFindCell which tries to find a cell contain-ing a given point.

Field Access Method

The restriction of the fields to a cell is polynomial function in each of thefield components. To get the maximum polynomial degree of the field onlocal patches one evokes the method

int DLLIMPORT JCMFieldBagMaxDegree(int* maxDegree, int handle).

So the field on each cell is at most a polynomial of degree *maxDegree oneach unit patch. The number of components of the field is returned by themethod JCMFieldBagNComponents. To evaluate the field on a cell one usesthe 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 thefield within the fieldbag. The field value is returned in the array *values

with length equal to the number of field components. As an example withfollowing piece of code one gets the field values at a the point [0, 0] for a 2Dfield.

#include "jcm_fetools.h"

...

double realCoordinates[] = {0.0, 0.0};

double unitCoordinates[2];

int indexCell;

Page 131: Tutorial

12.5. FIELDBAG ACCESS METHODS 131

// 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);

Further auxiliary methods such as field export to cartesian grids and extrac-tion of isolines are available and documented in the header file jcm fetools.h.