Meep Reference
From AbInitio
Revision as of 08:06, 7 November 2005 (edit) Stevenj (Talk  contribs) (→Flux spectra) ← Previous diff 
Revision as of 09:09, 7 November 2005 (edit) Stevenj (Talk  contribs) (→Run and step functions) Next diff → 

Line 384:  Line 384:  
==Run and step functions==  ==Run and step functions==  
+  
+  The actual work in Meep is performed by ''run'' functions, which timestep the simulation for a given amount of time or until a given condition is satisfied.  
+  
+  The run functions, in turn, can be modified by use of ''step functions'': these are called at every time step and can perform any arbitrary computation on the fields, do outputs and I/O, or even modify the simulation. The step functions can be transformed by many ''modifier functions'', like ''atbeginning'', ''duringsources'', etcetera which cause them to only be called at certain times, etcetera, instead of at every time step.  
+  
+  ===Run functions===  
+  
+  The following run functions are available. (You can also write your own, using the lowerlevel [[#SWIG wrappersC++/SWIG functions]], but these should suffice for most needs.)  
+  
+  ;<code>(rununtil cond?/time stepfunctions...)</code>  
+  :Run the simulation until a given time or condition, calling the given step functions (if any) at each timestep. The first argument is ''either'' a number, in which case it is a time (in Meep units) to run for, ''or'' it is a function (of no arguments) which returns <code>true</code> when the simulation should stop.  
+  ;<code>(runsources stepfunctions...)</code>  
+  :Run the simulation until all sources have turned off, calling the given step functions (if any) at each timestep. Note that this does ''not'' mean that the fields will be zero at the end: in general, some fields will still be bouncing around that were excited by the sources.  
+  ;<code>(runsources+ cond?time stepfunctions...)</code>  
+  :As <code>runsources</code>, but with an additional first argument: either a number, in which case it is an ''additional'' time (in Meep units) to run for after the sources are off, ''or'' it is a function (of no arguments). In the latter case, the simulation runs until the sources are off ''and'' <code>(cond?)</code> returns <code>true</code>.  
+  
+  In particular, a useful first argument to <code>runsources+</code> or <code>rununtil</code> is often given by (as in the [[Meep tutorial]]):  
+  ;<code>(stopwhenfieldsdecayed dT c pt decayby)</code>  
+  :Return a <code>cond?</code> function, suitable for passing to <code>rununtil</code>/<code>runsources+</code>, that examines the component <code>c</code> (e.g. <code>Ex</code>, etc.) at the point <code>pt</code> (a <code>vector3</code>) and keeps running until its absolute value ''squared'' has decayed by at least <code>decayby</code> from its maximum previous value. In particular, it keeps incrementing the run time by <code>dT</code> (in Meep units) and checks the maximum value over that time period—in this way, it won't be fooled just because the field happens to go through 0 at some instant.  
+  
+  Finally, another run function, useful for computing ω('''k''') band diagrams, is:  
+  
+  ;<code>(runkpoints T kpoints)</code>  
+  :Given a list of <code>kpoints</code> (a list of <code>vector3</code>), runs a simulation for each k (specifying Blochperiodic boundary conditions) and extracts the frequencies from each one. In particular, you should have specified one or more Gaussian sources. For each k, it will run the simulation until the sources are turned off plus an additional <code>T</code> time units. It will run <code>harminv</code> (see below) at the same point/component as the first Gaussian source and look for modes in the union of the frequency ranges for all sources. The output will be a commadelimited list of frequencyies, prefixed by <code>freqs:</code>, and their imaginary parts, prefixed by <code>freqsim:</code>. (See also this [[Meep Tutorial/Band diagram, resonant modes, and transmission in a holey waveguide#Band diagramband diagram tutorial]].)  
+  
+  ===Predefined step functions===  
+  
+  Several useful step functions are predefined for you by Meep.  
+  
+  ====Output functions====  
+  
+  The most common step function is an output function, which outputs some field component to an [[w:HDF5HDF5]] file. Normally, you will want to modify this by one of the <code>at</code> functions, below, as outputting a field at ''every'' time step can get quite time and storageconsuming. The predefined output functions are:  
+  
+  ;<code>outputepsilon</code>  
+  :Output the dielectric function ε.  
+  ;<code>outputhpwr</code>  
+  :Output the magneticfield energy density <math>\mathbf{H}^2 / 2</math>  
+  ;<code>outputdpwr</code>  
+  :Output the electricfield energy density <math>\mathbf{E}^* \cdot \mathbf{D} / 2</math>  
+  ;<code>outputtotpwr</code>  
+  :Output the total electric and magnetic energy density.  
+  ;<code>output''X''fieldx</code>, <code>output''X''fieldy</code>, <code>output''X''fieldz</code>, <code>output''X''fieldr</code>, <code>output''X''fieldp</code>  
+  :Output the <math>x</math>, <math>y</math>, <math>z</math>, <math>r</math>, or <math>\phi</math> component respectively, of the field ''X'', where ''X'' is either <code>h</code>, <code>e</code>, <code>d</code>, or <code>s</code> for the magnetic, electric, displacement, or Poynting field, respectively. If the field is complex, outputs two datasets, e.g. <code>ex.r</code> and <code>ex.i</code>, within the same HDF5 file for the real and imaginary parts, respectively.  
+  ;<code>output''X''field</code>  
+  :Outputs ''all'' the components of the field ''X'', where ''X'' is either <code>h</code>, <code>e</code>, <code>d</code>, or <code>s</code> as above, to an HDF5 file. (That is, the different components are stored as different datasets within the ''same'' file.)  
+  ;<code>(outputpng component h5topngoptions)</code>  
+  :Output the given field component (e.g. <code>Ex</code>, etc.) as a [[w:PNGPNG]] image, by first outputting the HDF5 file, then converting to PNG via [[h5utilsh5topng]], then deleting the HDF5 file. The second argument is a string giving options to pass to h5topng (e.g. <code>"Zc bluered"</code>). See also the [[Meep Tutorial#Output tips and tricksMeep tutorial]].  
+  
+  ====Harminv====  
+  
+  The following step function collects field data from a given point and runs [[Harminv]] on that data to extract the frequencies, decay rates, and other information.  
+  
+  ;<code>(harminv c pt fcen df <nowiki>[maxbands]</nowiki>)</code>  
+  :Returns a step function that collects data from the field component <code>c</code> (e.g. <code>Ex</code>, etc.) at the given point <code>pt</code> (a <code>vector3</code>). Then, at the end of the run, it uses Harminv to look for modes in the given frequency range (center <code>fcen</code> and width <code>df</code>), printing the results to standard output (prefixed by <code>harminv:</code>) as commadelimited text, and also storing them to the variable <code>harminvresults</code>.  
+  
+  '''Important:''' normally, you should only use <code>harminv</code> to analyze data ''after the sources are off''. Wrapping it in <code>(aftersources (harminv ...))</code> is sufficient.  
+  
+  In particular, Harminv takes the time series <math>f(t)</math> corresponding to the given field component as a function of time and decomposes it as:  
+  
+  :<math>f(t) = \sum_n a_n e^{i\omega_n t}</math>  
+  
+  The results are stored in the list <code>harminvresults</code>, which is a list of tuples holding the frequency, amplitude, and error of the modes. Given one of these tuples, you can extract its various components with one of the accessor functions:  
+  
+  ;<code>(harminvfreq result)</code>  
+  :Return the complex frequency ω (in the usual Meep 2πc units).  
+  ;<code>(harminvfreqre result)</code>  
+  :Return the real part of the frequency ω.  
+  ;<code>(harminvfreqim result)</code>  
+  :Return the imaginary part of the frequency ω.  
+  ;<code>(harminvQ result)</code>  
+  :Return dimensionless lifetime, or "quality factor", <math>Q</math>, defined as <math>\mathrm{Re}\,\omega / 2 \mathrm{Im}\,\omega</math>.  
+  ;<code>(harminvamp result)</code>  
+  :Return the complex amplitude <math>a</math>.  
+  ;<code>(harminverr result)</code>  
+  :A crude measure of the error in the frequency (both real and imaginary)...if the error is much larger than the imaginary part, for example, then you can't trust the <math>Q</math> to be accurate. '''Note''': ''this error is only the uncertainty in the signal processing'', and tells you nothing about the errors from finite resolution, finite cell size, and so on!  
+  
+  For example, <code>(map harminvfreqre harminvresults)</code> gives you a list of the real parts of the frequencies, using the Scheme builtin <code>map</code>.  
+  
+  ===Stepfunction modifiers===  
+  
+  Rather than writing a brandnew step function every time we want to do something a bit different, the following "modifier" functions take a bunch of step functions and produce ''new'' step functions with modified behavior. (See also the [[Meep tutorial]] for examples.)  
+  
+  ====Controlling when a step function executes====  
+  
+  ;<code>(whentruefuncs cond? stepfunctions...)</code>  
+  :Given zero or more step functions and a condition function <code>cond?</code> ( a function of no arguments), evaluate the step functions whenever <code>(cond?)</code> returns <code>true</code>.  
+  ;<code>(atevery dT stepfunctions...)</code>  
+  :Given zero or more step functions, evaluates them at every time interval of <code>dT</code> units (rounded up to the next time step).  
+  ;<code>(aftertime T stepfunctions...)</code>  
+  :Given zero or more step functions, evaluates them only for times after a <code>T</code> time units have elapsed from the start of the run.  
+  ;<code>(beforetime T stepfunctions...)</code>  
+  :Given zero or more step functions, evaluates them only for times before a <code>T</code> time units have elapsed from the start of the run.  
+  ;<code>(attime T stepfunctions...)</code>  
+  :Given zero or more step functions, evaluates them only once, after a <code>T</code> time units have elapsed from the start of the run.  
+  ;<code>(aftersources stepfunctions...)</code>  
+  :Given zero or more step functions, evaluates them only for times after all of the sources have turned off.  
+  ;<code>(aftersources+ T stepfunctions...)</code>  
+  :Given zero or more step functions, evaluates them only for times after all of the sources have turned off, plus an additional <code>T</code> time units have elapsed.  
+  ;<code>(duringsources stepfunctions...)</code>  
+  :Given zero or more step functions, evaluates them only for times ''before'' all of the sources have turned off.  
+  ;<code>(atbeginning stepfunctions...)</code>  
+  :Given zero or more step functions, evaluates them only once, at the beginning of the run.  
+  ;<code>(atend stepfunctions...)</code>  
+  :Given zero or more step functions, evaluates them only once, at the end of the run.  
+  
+  ====Modifying HDF5 output====  
+  
+  ;<code>(involume v stepfunctions...)</code>  
+  :Given zero or more step functions, modifies any output functions among them to only output a subset (or a superset) of the computational cell, corresponding to the <code><nowiki>meep::geometric_volume*</nowiki></code> <code>v</code> (created by the <code>volume</code> function).  
+  ;<code>(inpoint pt stepfunctions...)</code>  
+  :Given zero or more step functions, modifies any output functions among them to only output a single ''point'' of data, at <code>pt</code> (a <code>vector3</code>).  
+  ;<code>(toappended filename stepfunctions...)</code>  
+  :Given zero or more step functions, modifies any output functions among them to ''append'' their data to datasets in a single newlycreated file named <code>filename</code> (plus an <code>.h5</code> suffix and the current filename prefix). They append by adding an ''extra dimension'' to their datasets, corresponding to time.  
+  
+  ===Writing your own step functions===  
+  
+  A step function can take two forms. The simplest is just a function of no arguments, which is called at every time step (unless modified by one of the modifier functions above). e.g.  
+  
+  (define (mystep) (print "Hello world!\n"))  
+  
+  This suffices for most purposes. However, sometimes you need a step function that opens a file, or accumulates some computation, and you need to clean up (e.g. close the file or print the results) at the end of the run. For this case, you can write a step function of one argument: that argument will either be <code><nowiki>'step</nowiki></code> when it is called during timestepping, or <code><nowiki>'finish</nowiki></code> when it is called at the end of the run.  
==Lowlevel functions==  ==Lowlevel functions==  
===SWIG wrappers===  ===SWIG wrappers=== 
Revision as of 09:09, 7 November 2005
Meep 
Download 
Release notes 
FAQ 
Meep manual 
Introduction 
Installation 
Tutorial 
Reference 
C++ Tutorial 
C++ Reference 
Acknowledgements 
License and Copyright 
Here, we document the features exposed to the user by the Meep package. We do not document the Scheme language or the functions provided by libctl (see also the libctl User Reference section of the libctl manual).
This page is simply a compact listing of the functions exposed by the interface; for a gentler introduction, see the Meep tutorial. Also, we note that this page is not, and probably never will be, a complete listing of all functions. In particular, because of the SWIG wrappers, every function in the C++ interface is accessible from Scheme, but not all of these functions are documented or intended for end users.
Contents 
Input Variables
These are global variables that you can set to control various parameters of the Meep computation. In brackets after each variable is the type of value that it should hold. (The classes, complex datatypes like geometricobject
, are described in a later subsection. The basic datatypes, like integer
, boolean
, cnumber
, and vector3
, are defined by libctl.)

geometry
[list ofgeometricobject
class]  Specifies the geometric objects making up the structure being simulated. When objects overlap, later objects in the list take precedence. Defaults to no objects (empty list).

sources
[list ofsource
class]  Specifies the current sources to be present in the simulation; defaults to none.

symmetries
[list ofsymmetry
class]  Specifies the spatial (mirror/rotation) symmetries to exploit in the simulation (defaults to none). The symmetries must be obeyed by both the structure and by the sources. See also: Exploiting symmetry in Meep.

pmllayers
[list ofpml
class]  Specifies the absorbing PML boundary layers to use; defaults to none.

defaultmaterial
[materialtype
class]  Holds the default material that is used for points not in any object of the geometry list. Defaults to
air
(ε of 1). 
geometrylattice
[lattice
class]  Specifies the the size of the unit cell (which is centered on the origin of the coordinate system). If any dimension of the lattice
size
is the special valuenosize
, then the dimension of the lattice is reduced (i.e. it becomes two or onedimensional) by default. Defaults to a cubic cell of unit size. 
dimensions
[integer
]  Explicitly specifies the dimensionality of the simulation, if the value is less than 3. If the value is 3 (the default), then the dimensions are automatically reduced if possible when any of the
geometrylattice
sizes arenosize
. Ifdimensions
is the special value ofCYLINDRICAL
, then cylindrical coordinates are used and the x and z dimensions are interpreted as r and z, respectively. 
m
[number
]  For
CYLINDRICAL
simulations, specifies that the angular φ dependence of the fields is of the form e^{imφ} (default ism=0
). If the simulation cell includes the origin r = 0, thenm
must be an integer. 
resolution
[number
orvector3
]  Specifies the computational grid resolution, in pixels per distance unit. Defaults to
10
. 
kpoint
[false
orvector3
]  If
false
(the default), then the boundaries are perfect metallic (zero electric field). If a vector, then the boundaries are Blochperiodic: the fields at one side are times the fields at the other side, separated by the lattice vector . Thekpoint
vector is specified in Cartesian coordinates, in units of 2π/distance. (This is different from MPB, equivalent to taking MPB'skpoints
through the functionreciprocal>cartesian
.) 
ensureperiodicity
[boolean
]  If
true
(the default), and if the boundary conditions are periodic (kpoint
is notfalse
), then the geometric objects are automatically repeated periodically according to the lattice vectors (the size of the computational cell). 
forcecomplexfields?
[boolean
]  By default, Meep runs its simulations with purely real fields whenever possible. It uses complex fields (which require twice the memory and computation) if the
kpoint
is nonzero or ifm
is nonzero. However, by settingforcecomplexfields?
totrue
, Meep will always use complex fields. See also: Complex fields in Meep. 
filenameprefix
[string
]  A string prepended to all output filenames. Defaults to the name of the current ctl file, with ".ctl" replaced by "" (e.g.
foo.ctl
uses a"foo"
prefix). 
Courant
[number
]  Specify the Courant factor S which relates the time step size to the spatial discretization: cΔt = SΔx. Default is
0.5
. For numerical stability, the Courant factor must be at most , and in practice should be slightly smaller. 
outputvolume
[meep::geometric_volume*
]  Specifies the default region of space that is output by the HDF5 output functions (below); see also the
(volume ...)
function to createmeep::geometric_volume*
objects. The default is'()
(null), which means that the whole computational cell is output. Normally, you should use the(involume ...)
function to modify the output volume instead of settingoutputvolume
directly. 
progressinterval
[number
]  Time interval (seconds) after which Meep prints a progress message; default is 4 seconds.
The require a bit more understanding of the inner workings of Meep to use (see also the SWIG wrappers).

structure
[meep::structure*
]  Pointer to the current structure being simulated; initialized by
(initstructure)
which is called automatically by(initfields)
which is called automatically by any of the(run)
functions. 
fields
[meep::fields*
]  Pointer to the current fields being simulated; initialized by
(initfields)
which is called automatically by any of the(run)
functions. 
numchunks
[integer
]  Minimum number of "chunks" (subarrays) to divide the structure/fields into (default 0); actual number is determined by number of processors, PML layers, etcetera. (Mainly useful for debugging.)
Predefined Variables
Variables predefined for your convenience and amusement.

air
,vacuum
[materialtype
class]  Two aliases for a predefined material type with a dielectric constant of 1.

metal
[materialtype
class]  A predefined material type corresponding to a perfectly conducting metal (in which the electric field is zero).

nothing
[materialtype
class]  A material that, effectively, punches a hole through other objects to the background (
defaultmaterial
orepsiloninputfile
). 
infinity
[number
]  A big number (1.0e20) to use for "infinite" dimensions of objects.

pi
[number
]  π (3.14159...).
Constants (enumerated types)
Several of the functions/classes in Meep ask you to specify e.g. a field component or a direction in the grid. These should be one of the following constants:

direction
constants  Specify a direction in the grid. One of
X
,Y
,Z
,R
,P
for: x, y, z, r, φ, respectively. 
boundaryside
constants  Specify particular boundary in some direction (e.g. + x or − x). One of
Low
orHigh
. 
component
constants  Specify a particular field (or other) component. One of
Ex
,Ey
,Ez
,Er
,Ep
,Hx
,Hy
,Hz
,Hy
,Hp
,Hz
,Dx
,Dy
,Dz
,Dr
,Dp
,Dielectric
, for: E_{x}, E_{y}, E_{z}, E_{r}, E_{φ}, H_{x}, H_{y}, H_{z}, H_{r}, H_{φ}, D_{x}, D_{y}, D_{z}, D_{r}, D_{φ}, , respectively. 
derivedcomponent
constants  These are additional components, which are not actually stored by Meep but are computed as needed, mainly for use in output functions. One of
Sx
,Sy
,Sz
,Sr
,Sp
,EnergyDensity
,DEnergyDensity
,HEnergyDensity
for: S_{x}, S_{y}, S_{z}, S_{r}, S_{φ} (components of the Poynting vector ), , , , respectively.
Classes
Classes are complex datatypes with various "properties" which may have default values. Classes can be "subclasses" of other classes; subclasses inherit all the properties of their superclass, and can be used any place the superclass is expected. An object of a class is constructed with:
(make class (prop1 val1) (prop2 val2) ...)
See also the libctl manual.
Meep defines several types of classes, the most numerous of which are the various geometric object classes (which are the same as those used in MPB. You can also get a list of the available classes, along with their property types and default values, at runtime with the (help)
command.
lattice
The lattice class is normally used only for the geometrylattice
variable, which sets the size of the computational cell. In MPB, you can use this to specify a variety of affine lattice structures. In Meep, only rectangular Cartesian computational cells are supported, so the only property of lattice that you should normally use is its size
.

lattice
 Properties:

size
[vector3
]  The size of the computational cell. Defaults to unit lengths.
If any dimension has the special size nosize
, then the dimensionality of the problem is (essentially) reduced by one; strictly speaking, the dielectric function is taken to be uniform along that dimension.
Because Maxwell's equations are scaleinvariant, you can use any units of distance you want to specify the cell size: nanometers, inches, parsecs, whatever. However, it is usually convenient to pick some characteristic lengthscale of your problem and set that length to 1. See also Meep Introduction#Units in Meep.
materialtype
This class is used to specify the materials that geometric objects are made of. Currently, there are three subclasses, dielectric
, perfectmetal
, and materialfunction
.

dielectric
 A uniform, isotropic, possibly nonlinear or dispersive, dielectric material; see also Dielectric materials in Meep. It has three properties:

epsilon
[number
]  The dielectric constant (must be positive). No default value. You can also use
(index n)
as a synonym for(epsilon (* n n))
. 
chi2
[number
]  The Kerr susceptibility
\chi^{(2)}
.  polarizations [list of
polarizability
class]  List of dispersive polarizabilities (see below) added to the dielectric constant, in order to model material dispersion; defaults to none.


perfectmetal
 A perfectly conducting metal; this class has no properties and you normally just use the predefined
metal
object, above. (To model imperfect conductors, use a dispersive dielectric material.) 
materialfunction
 This material type allows you to specify the material as an arbitrary function of position. It has one property:

materialfunc
[function
]  A function of one argument, the position
vector3
, that returns the material at that point. Note that the function you supply can return any material; wild and crazy users could even return anothermaterialfunction
object (which would then have its function invoked in turn).

Dispersive dielectric materials, above, are specified via a list of objects of type polarizability
, which is another class with four properties:

polarizability
 Specifies a single dispersive polarizability of damped harmonic form (see Material dispersion), with the parameters:

omega
[number
]  The resonance frequency ω_{n}.

gamma
[number
]  The resonance frequency γ_{n}.

sigma
[number
]  The scale factor σ_{n}.

energysaturation
[number
]  See Saturable gain in Meep.

geometricobject
This class, and its descendants, are used to specify the solid geometric objects that form the dielectric structure being simulated. The base class is:

geometricobject
 Properties:

material
[materialtype
class]  The material that the object is made of (usually some sort of dielectric). No default value (must be specified).

center
[vector3
]  Center point of the object. No default value.

One normally does not create objects of type geometricobject
directly, however; instead, you use one of the following subclasses. Recall that subclasses inherit the properties of their superclass, so these subclasses automatically have the material
and center
properties (which must be specified, since they have no default values).
In a twodimensional calculation, only the intersections of the objects with the xy plane are considered.

sphere
 A sphere. Properties:

radius
[number
]  Radius of the sphere. No default value.


cylinder
 A cylinder, with circular crosssection and finite height. Properties:

radius
[number
]  Radius of the cylinder's crosssection. No default value.

height
[number
]  Length of the cylinder along its axis. No default value.

axis
[vector3
]  Direction of the cylinder's axis; the length of this vector is ignored. Defaults to point parallel to the z axis.


cone
 A cone, or possibly a truncated cone. This is actually a subclass of
cylinder
, and inherits all of the same properties, with one additional property. The radius of the base of the cone is given by theradius
property inherited fromcylinder
, while the radius of the tip is given by the new property:
radius2
[number
]  Radius of the tip of the cone (i.e. the end of the cone pointed to by the
axis
vector). Defaults to zero (a "sharp" cone).


block
 A parallelepiped (i.e., a brick, possibly with nonorthogonal axes). Properties:

size
[vector3
]  The lengths of the block edges along each of its three axes. Not really a 3vector, but it has three components, each of which should be nonzero. No default value.

e1
,e2
,e3
[vector3
]  The directions of the axes of the block; the lengths of these vectors are ignored. Must be linearly independent. They default to the three lattice directions.


ellipsoid
 An ellipsoid. This is actually a subclass of
block
, and inherits all the same properties, but defines an ellipsoid inscribed inside the block.
Here are some examples of geometric objects created using the above classes, assuming mat
is some material we have defined:
; A cylinder of infinite radius and height 0.25 pointing along the x axis, ; centered at the origin: (make cylinder (center 0 0 0) (material mat) (radius infinity) (height 0.25) (axis 1 0 0))
; An ellipsoid with its long axis pointing along (1,1,1), centered on ; the origin (the other two axes are orthogonal and have equal ; semiaxis lengths): (make ellipsoid (center 0 0 0) (material mat) (size 0.8 0.2 0.2) (e1 1 1 1) (e2 0 1 1) (e3 2 1 1))
; A unit cube of material m with a spherical air hole of radius 0.2 at ; its center, the whole thing centered at (1,2,3): (set! geometry (list (make block (center 1 2 3) (material mat) (size 1 1 1)) (make sphere (center 1 2 3) (material air) (radius 0.2))))
symmetry
This class is used for the symmetries
input variable, to specify symmetries (which must preserve both the structure and the sources) for Meep to exploit. Any number of symmetries can be exploited simultaneously, but there is no point in specifying redundant symmetries: the computational cell can be reduced by at most a factor of 4 in 2d and 8 in 3d. See also Exploiting symmetry in Meep.

symmetry
 A single symmetry to exploit. This is the base class of the specific symmetries below, so normally you don't create it directly. However, it has two properties which are shared by all symmetries:

direction
[direction
constant]  The direction of the symmetry (the normal to a mirror plane or the axis for a rotational symmetry). e.g.
X
,Y
, ... (only Cartesian/grid directions are allowed). No default value. 
phase
[cnumber
]  An additional phase to multiply the fields by when operating the symmetry on them; defaults to
1.0
. e.g. a phase of1
for a mirror plane corresponds to an odd mirror. (Technically, you are essentially specifying the representation of the symmetry group that your fields and sources transform under.)

The specific symmetry subclasses are:

mirrorsym
 A mirror symmetry plane. Here, the
direction
is the direction normal to the mirror plane. 
rotate2sym
 A 180° (twofold) rotational symmetry (a.k.a. C_{2}). Here, the
direction
is the axis of the rotation. 
rotate2sym
 A 90° (fourfold) rotational symmetry (a.k.a. C_{4}). Here, the
direction
is the axis of the rotation.
pml
This class is used for specifying the PML absorbing boundary layers around the cell, if any, via the pmllayers
input variable. See also Perfectly matched layers. pmllayers
can be zero or more pml
objects, with multiple objects allowing you to specify different PML layers on different boundaries.

pml
 A single PML layer specification, which sets up one or more PML layers around the boundaries according to the following four properties.

thickness
[number
]  The spatial thickness of the PML layer (which extends from the boundary towards the inside of the computational cell). The thinner it is, the more numerical reflections become a problem. No default value.

direction
[direction
constant]  Specify the direction of the boundaries to put the PML layers next to. e.g. if
X
, then specifies PML on the boundaries (depending on the value ofside
, below). Default is the special valueALL
, which puts PML layers on the boundaries in all directions. 
side
[boundaryside
constant]  Specify which side,
Low
orHigh
of the boundary or boundaries to put PML on. e.g. if side isLow
and direction isX
, then a PML layer is added to the − x boundary. Default is the special valueALL
, which puts PML layers on both sides. 
strength
[number
]  A strength (default is
1.0
) to multiply the PML absorption coefficient by. A strength of2.0
will square the theoretical reflection coefficient of the PML (making it smaller), but will also increase numerical reflections.

source
The source
class is used to specify the current sources (via the sources
input variable). Note that all sources in Meep are separable in time and space, i.e. of the form \mathbf{J}(\mathbf{x},t) = \mathbf{A}(\mathbf{x}) \cdot f(t)
for some functions and f. (Nonseparable sources can be simulated, however, by modifying the sources after each time step.) When real fields are being used (which is the default in many cases...see the forcecomplexfields?
input variable), only the real part of the current source is used by Meep.

source
 The source class has the following properties:

src
[srctime
class]  Specify the timedependence of the source (see below). No default.

component
[component
constant]  Specify the direction and type of the current component: e.g.
Ex
,Ey
, etcetera for an electric current, andHx
,Hy
, etcetera for a magnetic current. Note that currents pointing in an arbitrary direction are specified simply as multiple current sources with the appropriate amplitudes for each component. No default. center
[vector3
] The location of the center of the current source in the computational cell; no default.
size
[vector3
] The size of the current distribution along each direction of the computational cell. The default is (0,0,0): a point source.
amplitude
[cnumber
] An overall (complex) amplitude multiplying the the current source. Default is
1.0
. ampfunc
[function
] A Scheme function of a single argument, that takes a vector3 giving a position and returns a (complex) current amplitude for that point. The position argument is relative to the
center
of the current source, so that you can move your current around without changing your function. The default is'()
(null), meaning that a constant amplitude of 1.0 is used. Note that your amplitude function (if any) is multiplied by theamplitude
property, so both properties can be used simultaneously.

The srctime
object, which specifies the time dependence of the source, can be one of the following three classes.

continuoussrc
 A continuouswave source proportional to exp( − iωt), possibly with a smooth (exponential/tanh) turnon/turnoff. It has the properties:
frequency
[number
] The frequency ω, in units of 2πc (see Units in Meep). No default value. You can instead specify
(wavelength x)
or(period x)
, which are both a synonym for(frequency (/ 1 x))
; i.e. 1/ω in these units is the vacuum wavelength or the temporal period. starttime
[number
] The starting time for the source; default is
0
(turn on at t = 0). endtime
[number
] The end time for the source; default is
infinity
(never turn off). width
[number
] Roughly, the temporal width of the smoothing (technically, the inverse of the exponential rate at which the current turns off and on). Default is
0
(no smoothing). You can instead specify(fwidth x)
, which is a synonym for(width (/ 1 x))
(i.e. the frequency width is proportional to the inverse of the temporal width). cutoff
[number
] How many
width
s the current decays for before we cut it off and set it to zero; the default is3.0
. A larger value ofcutoff
will reduce the amount of highfrequency components that are introduced by the start/stop of the source, but will of course lead to longer simulation times.

gaussiansrc
 A Gaussianpulse source roughly proportional to exp( − iωt − (t − t_{0})^{2} / 2w^{2}), It has the properties:
 The center frequency ω, in units of 2πc (see Units in Meep). No default value. You can instead specify
(wavelength x)
or(period x)
, which are both a synonym for(frequency (/ 1 x))
; i.e. 1/ω in these units is the vacuum wavelength or the temporal period. width
[number
] The width w used in the Gaussian. No default value. You can instead specify
(fwidth x)
, which is a synonym for(width (/ 1 x))
(i.e. the frequency width is proportional to the inverse of the temporal width). starttime
[number
] The starting time for the source; default is
0
(turn on at t = 0). cutoff
[number
] How many
width
s the current decays for before we cut it off and set it to zero—this applies for both turnon and turnoff of the pulse. The default is5.0
. A larger value ofcutoff
will reduce the amount of highfrequency components that are introduced by the start/stop of the source, but will of course lead to longer simulation times.
 The center frequency ω, in units of 2πc (see Units in Meep). No default value. You can instead specify

customsrc
 A userspecified source function f(t). You can also specify start/end times (at which point your current is set to zero whether or not your function is actually zero). These are optional, but you must specify an
endtime
explicitly if you want functions likerunsources
to work, since they need to know when your source turns off.
srcfunc
[function
]  The function f(t) specifying the timedependence of the source. It should take one argument (the time in Meep units) and return a complex number.
starttime
[number
] The starting time for the source; default is
( infinity)
(turn on at ). Note, however, that the simulation normally starts at t = 0 with zero fields as the initial condition, so there is implicitly a sharp turnon at t = 0 whether you specify it or not. endtime
[number
] The end time for the source; default is
infinity
(never turn off).

fluxregion
A fluxregion
object is used with addflux
below to specify a region in which Meep should accumulate the appropriate Fouriertransformed fields in order to compute a flux spectrum.
fluxregion
 A region (volume, plane, line, or point) in which to compute the integral of the Poynting vector of the Fouriertransformed fields. Its properties are:
center
[vector3
] The center of the flux region (no default).
size
[vector3
] The size of the flux region along each of the coordinate axes; default is (0,0,0) (a single point).
direction
[direction
constant] The direction in which to compute the flux (e.g.
X
,Y
, etcetera). The default isAUTOMATIC
, in which the direction is determined by taking the normal direction if the flux region is a plane (or a line, in 2d). If the normal direction is ambiguous (e.g. for a point or volume), then you must specify thedirection
explicitly (not doing so will lead to an error). weight
[cnumber
] A weight factor to multiply the flux by when it is computed; default is
1.0
.
Note that the flux is always computed in the positive coordinate direction, although this can effectively be flipped by using a weight
of 1.0
. (This is useful, for example, if you want to compute the outward flux through a box, so that the sides of the box add instead of subtract!)
Miscellaneous functions
Here, we describe a number of miscellaneous useful functions provided by Meep.
See also the reference section of the libctl manual, which describes a number of useful functions defined by libctl.
Geometry utilities
Some utility functions are provided to help you manipulate geometric objects:

(shiftgeometricobject obj shiftvector)
 Translate
obj
by the 3vectorshiftvector
. 
(geometricobjectduplicates shiftvector minmultiple maxmultiple obj)
 Return a list of duplicates of
obj
, shifted by various multiples ofshiftvector
(fromminmultiple
tomaxmultiple
, inclusive, in steps of 1). 
(geometricobjectsduplicates shiftvector minmultiple maxmultiple objlist)
 Same as
geometricobjectduplicates
, except operates on a list of objects,objlist
. If A appears before B in the input list, then all the duplicates of A appear before all the duplicates of B in the output list. 
(geometricobjectslatticeduplicates objlist [ ux uy uz ])
 Duplicates the objects in
objlist
by multiples of the Cartesian basis vectors, making all possible shifts of the "primitive cell" (see below) that fit inside the lattice cell. (This is useful for supercell calculations; see the [usertutorial.html tutorial].) The primitive cell to duplicate isux
byuy
byuz
, in units of the Cartesian basis vectors. These three parameters are optional; any that you do not specify are assumed to be1
. 
(pointinobject? point obj)
 Returns whether or not the given 3vector
point
is inside the geometric objectobj
. 
(pointinperiodicobject? point obj)
 As
pointinobject?
, but also checks translations of the given object by the lattice vectors. 
(displaygeometricobjectinfo indentby obj)
 Outputs some information about the given
obj
, indented byindentby
spaces.
Field computations
Meep supports a large number of functions to perform computations on the fields. Currently, most of them are accessed via the lowerlevel C++/SWIG interface, but we are slowly adding simpler, higherlevel versions of them here.
(getfieldpoint c pt)
 Given a
component
orderivedcomponent
constantc
and avector3
pt
, returns the value of that component at that point. (getepsilonpoint pt)
 Equivalent to
(getfieldpoint Dielectric pt)
.
(More to come...)
Reloading parameters
Once the fields have been initialized, you can change the values of various parameters by using the following functions:
(resetmeep)
 Reset all of Meep's parameters, deleting the fields, structures, etcetera, from memory as if you had not run any computations.
(restartfields)
 Restart the fields at time zero, with zero fields. (Does not reset the Fourier transforms of the flux planes, which continue to be accumulated.)
(changekpoint! k)
 Change the
kpoint
(the Bloch periodicity).
(More to come...)
Flux spectra
Given a bunch of fluxregion
objects (see above), you can tell Meep to accumulate the Fourier transforms of the fields in those regions in order to compute flux spectra. See also the transmission/reflection spectra introduction and the Meep tutorial. The most important function is:
(addflux fcen df nfreq fluxregions...)
 Add a bunch of
fluxregion
s to the current simulation (initializing the fields if they have not yet been initialized), telling Meep to accumulate the appropriate field Fourier transforms fornfreq
equally spaced frequencies covering the frequency rangefcendf/2
tofcen+df/2
. Return a flux object, which you can pass to the functions below to get the flux spectrum, etcetera.
As described in the tutorial, you normally use addflux
via statements like:
(define transmission (addflux ...))
to store the flux object in a variable. addflux
initializes the fields if necessary, just like calling run
, so you should only call it after setting up your geometry
, sources
, pmllayers
, etcetera. You can create as many flux objects as you want, e.g. to look at powers flowing in different regions or in different frequency ranges. Note, however, that Meep has to store (and update at every time step) a number of Fourier components equal to the number of grid points intersecting the flux region multiplied by the number of electric and magnetic field components required to get the Poynting vector multiplied by nfreq
, so this can get quite expensive (in both memory and time) if you want a lot of frequency points over large regions of space.
Once you have called addflux
, the Fourier transforms of the fields are accumulated automatically during timestepping by the run
functions. At any time, you can ask for Meep to print out the current flux spectrum via:
(displayfluxes fluxes...)
 Given a number of flux objects, this displays a commaseparated table of frequencies and flux spectra, prefixed by "flux1:" or similar (where the number is incremented after each run). All of the fluxes should be for the same
fcen
/df
/nfreq
. The first column are the frequencies, and subsequent columns are the flux spectra.
You might have to do something lowerlevel if you have multiple flux regions corresponding to different frequency ranges, or have other special needs. (displayfluxes f1 f2 f3)
is actually equivalent to (displaycsv "flux" (getfluxfreqs f1) (getfluxes f1) (getfluxes f2) (getfluxes f3)
, where displaycsv
takes a bunch of lists of numbers and prints them as a commaseparated table, and we are calling two lowerlevel functions:
(getfluxfreqs flux)
 Given a flux object, returns a list of the frequencies that it is computing the spectrum for.
(getfluxes flux)
 Given a flux object, returns a list of the current flux spectrum that it has accumulated.
As described in the Meep tutorial, for a reflection spectrum you often want to save the Fouriertransformed fields from a "normalization" run and then load them into another run to be subtracted. This can be done via:
(saveflux filename flux)
 Save the Fouriertransformed fields corresponding to the given flux object in an HDF5 file of the given name (without the ".h5" suffix) (the current filenameprefix is prepended automatically).
(loadflux filename flux)
 Load the Fouriertransformed fields into the given flux object (replacing any values currently there) from an HDF5 file of the given name (without the ".h5" suffix) (the current filenameprefix is prepended automatically). You must load from a file that was saved by
saveflux
in a simulation of the same dimensions (for both the computational cell and the flux regions) with the same number of processors. (loadminusflux filename flux)
 As
loadflux
, but negates the Fouriertransformed fields after they are loaded. This means that they will be subtracted from any future field Fourier transforms that are accumulated. (scalefluxfields s flux)
 Scale the Fouriertransformed fields in
flux
by the complex numbers
. e.g.loadminusflux
is equivalent toloadflux
followed byscalefluxfields
withs=1
.
Run and step functions
The actual work in Meep is performed by run functions, which timestep the simulation for a given amount of time or until a given condition is satisfied.
The run functions, in turn, can be modified by use of step functions: these are called at every time step and can perform any arbitrary computation on the fields, do outputs and I/O, or even modify the simulation. The step functions can be transformed by many modifier functions, like atbeginning, duringsources, etcetera which cause them to only be called at certain times, etcetera, instead of at every time step.
Run functions
The following run functions are available. (You can also write your own, using the lowerlevel C++/SWIG functions, but these should suffice for most needs.)
(rununtil cond?/time stepfunctions...)
 Run the simulation until a given time or condition, calling the given step functions (if any) at each timestep. The first argument is either a number, in which case it is a time (in Meep units) to run for, or it is a function (of no arguments) which returns
true
when the simulation should stop. (runsources stepfunctions...)
 Run the simulation until all sources have turned off, calling the given step functions (if any) at each timestep. Note that this does not mean that the fields will be zero at the end: in general, some fields will still be bouncing around that were excited by the sources.
(runsources+ cond?time stepfunctions...)
 As
runsources
, but with an additional first argument: either a number, in which case it is an additional time (in Meep units) to run for after the sources are off, or it is a function (of no arguments). In the latter case, the simulation runs until the sources are off and(cond?)
returnstrue
.
In particular, a useful first argument to runsources+
or rununtil
is often given by (as in the Meep tutorial):
(stopwhenfieldsdecayed dT c pt decayby)
 Return a
cond?
function, suitable for passing torununtil
/runsources+
, that examines the componentc
(e.g.Ex
, etc.) at the pointpt
(avector3
) and keeps running until its absolute value squared has decayed by at leastdecayby
from its maximum previous value. In particular, it keeps incrementing the run time bydT
(in Meep units) and checks the maximum value over that time period—in this way, it won't be fooled just because the field happens to go through 0 at some instant.
Finally, another run function, useful for computing ω(k) band diagrams, is:
(runkpoints T kpoints)
 Given a list of
kpoints
(a list ofvector3
), runs a simulation for each k (specifying Blochperiodic boundary conditions) and extracts the frequencies from each one. In particular, you should have specified one or more Gaussian sources. For each k, it will run the simulation until the sources are turned off plus an additionalT
time units. It will runharminv
(see below) at the same point/component as the first Gaussian source and look for modes in the union of the frequency ranges for all sources. The output will be a commadelimited list of frequencyies, prefixed byfreqs:
, and their imaginary parts, prefixed byfreqsim:
. (See also this band diagram tutorial.)
Predefined step functions
Several useful step functions are predefined for you by Meep.
Output functions
The most common step function is an output function, which outputs some field component to an HDF5 file. Normally, you will want to modify this by one of the at
functions, below, as outputting a field at every time step can get quite time and storageconsuming. The predefined output functions are:
outputepsilon
 Output the dielectric function ε.
outputhpwr
 Output the magneticfield energy density
outputdpwr
 Output the electricfield energy density
outputtotpwr
 Output the total electric and magnetic energy density.
outputXfieldx
,outputXfieldy
,outputXfieldz
,outputXfieldr
,outputXfieldp
 Output the x, y, z, r, or φ component respectively, of the field X, where X is either
h
,e
,d
, ors
for the magnetic, electric, displacement, or Poynting field, respectively. If the field is complex, outputs two datasets, e.g.ex.r
andex.i
, within the same HDF5 file for the real and imaginary parts, respectively. outputXfield
 Outputs all the components of the field X, where X is either
h
,e
,d
, ors
as above, to an HDF5 file. (That is, the different components are stored as different datasets within the same file.) (outputpng component h5topngoptions)
 Output the given field component (e.g.
Ex
, etc.) as a PNG image, by first outputting the HDF5 file, then converting to PNG via h5topng, then deleting the HDF5 file. The second argument is a string giving options to pass to h5topng (e.g."Zc bluered"
). See also the Meep tutorial.
Harminv
The following step function collects field data from a given point and runs Harminv on that data to extract the frequencies, decay rates, and other information.
(harminv c pt fcen df [maxbands])
 Returns a step function that collects data from the field component
c
(e.g.Ex
, etc.) at the given pointpt
(avector3
). Then, at the end of the run, it uses Harminv to look for modes in the given frequency range (centerfcen
and widthdf
), printing the results to standard output (prefixed byharminv:
) as commadelimited text, and also storing them to the variableharminvresults
.
Important: normally, you should only use harminv
to analyze data after the sources are off. Wrapping it in (aftersources (harminv ...))
is sufficient.
In particular, Harminv takes the time series f(t) corresponding to the given field component as a function of time and decomposes it as:
The results are stored in the list harminvresults
, which is a list of tuples holding the frequency, amplitude, and error of the modes. Given one of these tuples, you can extract its various components with one of the accessor functions:
(harminvfreq result)
 Return the complex frequency ω (in the usual Meep 2πc units).
(harminvfreqre result)
 Return the real part of the frequency ω.
(harminvfreqim result)
 Return the imaginary part of the frequency ω.
(harminvQ result)
 Return dimensionless lifetime, or "quality factor", Q, defined as .
(harminvamp result)
 Return the complex amplitude a.
(harminverr result)
 A crude measure of the error in the frequency (both real and imaginary)...if the error is much larger than the imaginary part, for example, then you can't trust the Q to be accurate. Note: this error is only the uncertainty in the signal processing, and tells you nothing about the errors from finite resolution, finite cell size, and so on!
For example, (map harminvfreqre harminvresults)
gives you a list of the real parts of the frequencies, using the Scheme builtin map
.
Stepfunction modifiers
Rather than writing a brandnew step function every time we want to do something a bit different, the following "modifier" functions take a bunch of step functions and produce new step functions with modified behavior. (See also the Meep tutorial for examples.)
Controlling when a step function executes
(whentruefuncs cond? stepfunctions...)
 Given zero or more step functions and a condition function
cond?
( a function of no arguments), evaluate the step functions whenever(cond?)
returnstrue
. (atevery dT stepfunctions...)
 Given zero or more step functions, evaluates them at every time interval of
dT
units (rounded up to the next time step). (aftertime T stepfunctions...)
 Given zero or more step functions, evaluates them only for times after a
T
time units have elapsed from the start of the run. (beforetime T stepfunctions...)
 Given zero or more step functions, evaluates them only for times before a
T
time units have elapsed from the start of the run. (attime T stepfunctions...)
 Given zero or more step functions, evaluates them only once, after a
T
time units have elapsed from the start of the run. (aftersources stepfunctions...)
 Given zero or more step functions, evaluates them only for times after all of the sources have turned off.
(aftersources+ T stepfunctions...)
 Given zero or more step functions, evaluates them only for times after all of the sources have turned off, plus an additional
T
time units have elapsed. (duringsources stepfunctions...)
 Given zero or more step functions, evaluates them only for times before all of the sources have turned off.
(atbeginning stepfunctions...)
 Given zero or more step functions, evaluates them only once, at the beginning of the run.
(atend stepfunctions...)
 Given zero or more step functions, evaluates them only once, at the end of the run.
Modifying HDF5 output
(involume v stepfunctions...)
 Given zero or more step functions, modifies any output functions among them to only output a subset (or a superset) of the computational cell, corresponding to the
meep::geometric_volume*
v
(created by thevolume
function). (inpoint pt stepfunctions...)
 Given zero or more step functions, modifies any output functions among them to only output a single point of data, at
pt
(avector3
). (toappended filename stepfunctions...)
 Given zero or more step functions, modifies any output functions among them to append their data to datasets in a single newlycreated file named
filename
(plus an.h5
suffix and the current filename prefix). They append by adding an extra dimension to their datasets, corresponding to time.
Writing your own step functions
A step function can take two forms. The simplest is just a function of no arguments, which is called at every time step (unless modified by one of the modifier functions above). e.g.
(define (mystep) (print "Hello world!\n"))
This suffices for most purposes. However, sometimes you need a step function that opens a file, or accumulates some computation, and you need to clean up (e.g. close the file or print the results) at the end of the run. For this case, you can write a step function of one argument: that argument will either be 'step
when it is called during timestepping, or 'finish
when it is called at the end of the run.